This file is a merged representation of a subset of the codebase, containing files not matching ignore patterns, combined into a single document by Repomix.
The content has been processed where comments have been removed, empty lines have been removed, content has been compressed (code blocks are separated by ⋮---- delimiter).

<file_summary>
This section contains a summary of this file.

<purpose>
This file contains a packed representation of a subset of the repository's contents that is considered the most important context.
It is designed to be easily consumable by AI systems for analysis, code review,
or other automated processes.
</purpose>

<file_format>
The content is organized as follows:
1. This summary section
2. Repository information
3. Directory structure
4. Repository files (if enabled)
5. Multiple file entries, each consisting of:
  - File path as an attribute
  - Full contents of the file
</file_format>

<usage_guidelines>
- This file should be treated as read-only. Any changes should be made to the
  original repository files, not this packed version.
- When processing this file, use the file path to distinguish
  between different files in the repository.
- Be aware that this file may contain sensitive information. Handle it with
  the same level of security as you would the original repository.
</usage_guidelines>

<notes>
- Some files may have been excluded based on .gitignore rules and Repomix's configuration
- Binary files are not included in this packed representation. Please refer to the Repository Structure section for a complete list of file paths, including binary files
- Files matching these patterns are excluded: **/.git/**, **/.github/**, **/node_modules/**, **/vendor/**, **/third_party/**, **/external/**, **/libs/**, **/lib/**, **/bin/**, **/obj/**, **/build/**, **/dist/**, **/target/**, **/out/**, **/release/**, **/debug/**, **/wwwroot/**, **/public/**, **/assets/**, **/static/**, **/[tT]est/**, **/[tT]ests/**, **/__tests__/**, **/[lL]ogs/**, **/[mM]igrations/**, **/.vs/**, **/.vscode/**, **/.idea/**, **/.pnpm-store/**, **/.yarn/**, **/.npm/**, **/__pycache__/**, **/.pytest_cache/**, **/.mypy_cache/**, **/.gradle/**, **/.mvn/**, **/coverage/**, **/.coverage/**, **/reports/**, **/report/**, **/TestResults/**, **/tmp/**, **/temp/**, **/.tmp/**, **/.cache/**, **/.history/**, **/.DS_Store, **/Thumbs.db, **/*.log, **/*.out, **/*.err, **/*.trace, **/*.trc, **/*.tmp, **/*.cache, **/*.dmp, **/*.dump, **/*.core, **/*.binlog, **/*.ndjson, **/*.jsonl, **/*.csv, **/*.evtx, **/*.etl, **/*.access, **/*.error, **/*.exe, **/*.dll, **/*.so, **/*.dylib, **/*.bin, **/*.app, **/*.msi, **/*.apk, **/*.ipa, **/*.lib, **/*.a, **/*.o, **/*.obj, **/*.lo, **/*.lai, **/*.class, **/*.jar, **/*.war, **/*.ear, **/*.pdb, **/*.idb, **/*.ilk, **/*.nupkg, **/*.snupkg, **/*.gem, **/*.whl, **/*.egg, **/*.deb, **/*.rpm, **/*.zip, **/*.tar, **/*.gz, **/*.tgz, **/*.rar, **/*.bz2, **/*.xz, **/*.7z, **/*.lz, **/*.lzma, **/*.min.js, **/*.min.css, **/*.map, **/*.css, **/*.scss, **/*.sass, **/*.less, **/*.jpg, **/*.jpeg, **/*.png, **/*.gif, **/*.bmp, **/*.tif, **/*.tiff, **/*.webp, **/*.heif, **/*.heic, **/*.svg, **/*.eps, **/*.ai, **/*.raw, **/*.cr2, **/*.cr3, **/*.nef, **/*.arw, **/*.dng, **/*.orf, **/*.rw2, **/*.avif, **/*.apng, **/*.ico, **/*.psd, **/*.psb, **/*.xcf, **/*.hdr, **/*.exr, **/*.dcm, **/*.dicom, **/*.fits, **/*.ppm, **/*.pgm, **/*.pbm, **/*.j2k, **/*.jp2, **/*.pcx, **/*.tga, **/*.iff, **/*.sgi, **/*.ras, **/*.coverage, **/*.lcov, **/*.gcov, **/*.gcda, **/*.gcno, **/*.generated, **/*.g.cs, **/*.designer.cs, **/*.lock, **/*.lock.json, **/*.eot, **/*.ttf, **/*.woff, **/*.woff2, **/*.pfx, **/*.p12, **/*.cer, **/*.crt, **/*.key, **/*.editorconfig, **/*.tool-versions, **/*.onnx, **/*.pt, **/*.pth, **/*.h5, **/*.ckpt, **/*.sln, **/*.csproj, **/*.config, **/*.user, **/*.vsidx, **/*.v2, **/*.db*, **/.*ignore, **/.git*, **/*.config.*, **/.env, **/.gitignore, **/.browserslistrc, **/*.lock, **/*.mod, **/*.sum, **/*.resource, **/*.robot, **/*.sh, core/imageroot/**, core/rclone/**, core/rsync/**, core/support/**
- Files matching patterns in .gitignore are excluded
- Files matching default ignore patterns are excluded
- Code comments have been removed from supported file types
- Empty lines have been removed from all files
- Content has been compressed - code blocks are separated by ⋮---- delimiter
- Files are sorted by Git change count (files with more changes are at the bottom)
</notes>

</file_summary>

<directory_structure>
.apidoc/
  id-rename.js
.devcontainer/
  devcontainer.json
core/
  agent/
    models/
      event.go
      processor.go
      task.go
    validation/
      validation.go
    agent.go
    AGENTS.md
    envstate.go
    hbuiltin.go
    hevent.go
    htask.go
    README.md
    worklimit.go
  api-moduled/
    example/
      handlers/
        create/
          post
          validate-input.json
        list/
          post
          validate-output.json
        login/
          post
    validation/
      validation.go
    AGENTS.md
    api-moduled.go
    README.md
  api-server/
    audit/
      audit.go
    configuration/
      configuration.go
    methods/
      audit.go
      auth_test.go
      auth.go
      tasks.go
    middleware/
      middleware_test.go
      middleware.go
      token_error_test.go
    models/
      audit.go
      event.go
      socket.go
      task.go
      user_authorizations.go
    redis/
      redis.go
    response/
      response.go
    socket/
      action.go
      socket.go
    utils/
      muclock.go
      utils.go
    AGENTS.md
    api-server-logs.go
    api-server.go
    README.md
  ui/
    src/
      components/
        applications-center/
          AddNoteModal.vue
        backup/
          AddRepositoryModal.vue
          BackupDetailsModal.vue
          BackupInstanceSelector.vue
          BackupPasswordModal.vue
          CreateOrEditBackupModal.vue
          EditRepositoryModal.vue
          ImportBackupDestinationModal.vue
          InstanceToRestoreInfo.vue
          RestoreMultipleInstancesSelector.vue
          RestoreSingleInstanceModal.vue
          RestoreSingleInstanceSelector.vue
          RestoreSingleInstanceSnapshotSelector.vue
        domains/
          AddExternalProviderModal.vue
          AddInternalProviderModal.vue
          ChangeUserPasswordModal.vue
          CreateDomainModal.vue
          CreateOrEditGroupModal.vue
          CreateOrEditUserModal.vue
          DeleteSambaProviderModal.vue
          DomainGroups.vue
          DomainUsers.vue
          DomainUsersAndGroups.vue
          EditExternalDomainModal.vue
          EditPasswordPolicy.vue
          EditPasswordWarningModal.vue
          ImportUsersModal.vue
        error/
          TaskErrorInfo.vue
          TaskErrorInfoHierarchy.vue
          TaskErrorModal.vue
          TaskTreeHierarchy.vue
        initialize-cluster/
          SetFqdn.vue
          SkipRestoreAppsModal.vue
          WelcomeLogo.vue
        nodes/
          NewLeaderModal.vue
          NodeCard.vue
          NodeSelector.vue
          PromoteNodeModal.vue
          RemoveNodeModal.vue
          SetFqdnModal.vue
        settings/
          2FaQrCodeModal.vue
          AcmeSettingsPanel.vue
          ChangeAdminPasswordModal.vue
          CloudLogManagerConfigureModal.vue
          ConfigureFrontendProxyModal.vue
          ConfirmRevoke2FaModal.vue
          CreateAdminModal.vue
          CreateOrEditHttpRouteModal.vue
          DeleteObsoleteCertificatesModal.vue
          EditAcmeServerModal.vue
          EditAdminDisplayNameModal.vue
          Enable2FaModal.vue
          HttpFrontendProxiesPanel.vue
          HttpRouteDetailModal.vue
          HttpRoutesPanel.vue
          LokiCard.vue
          RequestTlsCertificateModal.vue
          SyslogConfigureModal.vue
          TlsCertificatesPanel.vue
          UploadTlsCertificateModal.vue
        shell/
          AppDrawer.vue
          GlobalSearch.vue
          HeaderGlobalMenu.vue
          MobileSideMenu.vue
          NotificationDrawer.vue
          ShellHeader.vue
          SideMenu.vue
          SideMenuContent.vue
        software-center/
          AdditionalVolumesSelector.vue
          AppInfoModal.vue
          AppList.vue
          AutomaticUpdatesModal.vue
          CertificationLevelBadge.vue
          CloneOrMoveAppModal.vue
          ImageGallery.vue
          InstallAppModal.vue
          RestartModuleModal.vue
          SetInstanceLabelModal.vue
          UpdateAppModal.vue
        system-logs/
          LogHighlightMark.vue
          LogOutput.vue
          LogSearch.vue
      i18n/
        index.js
      mixins/
        2fa.js
        audit.js
        ipAddress.js
        login.js
        node.js
        notification.js
        websocket.js
      router/
        index.js
      store/
        index.js
      views/
        settings/
          ClusterAdmins.vue
          Settings.vue
          SettingsAccount.vue
          SettingsCluster.vue
          SettingsFirewall.vue
          SettingsHttpRoutes.vue
          SettingsMetrics.vue
          SettingsSmartHost.vue
          SettingsSoftwareRepositories.vue
          SettingsSubscription.vue
          SettingsSystemLogs.vue
          SettingsTlsCertificates.vue
        About.vue
        Applications.vue
        ApplicationsCenter.vue
        AuditTrail.vue
        Backup.vue
        ClusterStatus.vue
        DomainConfiguration.vue
        Domains.vue
        InitializeCluster.vue
        Login.vue
        NodeDetail.vue
        NodeFirewall.vue
        Nodes.vue
        SoftwareCenter.vue
        SoftwareCenterAppInstances.vue
        SoftwareCenterCoreApps.vue
        SystemLogs.vue
      App.vue
      main.js
    .eslintrc.js
    .yarnrc.yml
    babel.config.js
    Containerfile
    package.json
    README.md
    vue.config.js
docs/
  core/
    agents.md
    api_server.md
    backup_restore.md
    clone_module.md
    container_metrics.md
    database.md
    events.md
    filesystem.md
    firewall.md
    index.md
    logs.md
    metrics.md
    phone_home.md
    port_allocation.md
    proxy_certificates.md
    smarthost.md
    software_repositories.md
    subscription.md
    testing.md
    tun.md
    updates.md
    user_domains.md
    validation.md
    volume_metrics.md
    vpn.md
  modules/
    agent.md
    backup_restore.md
    certificates.md
    certification.md
    code_snippets.md
    database.md
    images.md
    index.md
    metadata.md
    metrics.md
    network.md
    new_module.md
    port_allocation.md
    rootless_rootfull.md
    service_providers.md
    systemd_units.md
    testing.md
    updates.md
    volumes.md
  ui/
    core.md
    index.md
    library.md
    modules.md
    translation.md
  _config.yml
  api.md
  build_system.md
  design.md
  development_process.md
  Gemfile
  index.md
  license.md
  quickstart.md
  README.md
AGENTS.md
CONTRIBUTING
LICENSE
README.md
renovate.json
</directory_structure>

<files>
This section contains the contents of the repository's files.

<file path=".apidoc/id-rename.js">
// Create the module directory
</file>

<file path=".devcontainer/devcontainer.json">
// For format details, see https://aka.ms/devcontainer.json. For config options, see the README at:
// https://github.com/microsoft/vscode-dev-containers/tree/v0.245.2/containers/javascript-node
{
  "name": "ns8-core",
  "image": "mcr.microsoft.com/devcontainers/javascript-node:22-bookworm",
  // Configure tool-specific properties.
  "customizations": {
    // Configure properties specific to VS Code.
    "vscode": {
      // Add the IDs of extensions you want installed when the container is created.
      "extensions": [
        "dbaeumer.vscode-eslint",
        "esbenp.prettier-vscode",
        "octref.vetur",
        "shenjiaolong.vue-helper",
        "streetsidesoftware.code-spell-checker"
      ]
    }
  },
  // If you're using docker to develop with vscode, comment all options below and rebuild without cache the container.
  "workspaceMount": "source=${localWorkspaceFolder},target=/workspace,type=bind,Z",
  "workspaceFolder": "/workspace",
  // --userns=keep-id is used to correctly mount podman volume
  // --network=host is required for hot-reload
  "runArgs": ["--userns=keep-id", "--network=host"],
  "containerUser": "node",
  "remoteUser": "node"
}
</file>

<file path="core/agent/models/event.go">
package models
⋮----
import (
	"os"
	"sort"
)
⋮----
"os"
"sort"
⋮----
type Event struct {
	Source  string
	Name    string
	Payload string
}
⋮----
func CreateEventHandler(eventName string, basePaths []string) Processor
</file>

<file path="core/agent/models/processor.go">
package models
⋮----
import (
	"encoding/json"
	"errors"
	"fmt"
	"os"
)
⋮----
"encoding/json"
"errors"
"fmt"
"os"
⋮----
type Step struct {
	Name   string
	Path   string
	Weight int
}
⋮----
type Processor struct {
	Status   string `json:"status"`
	Progress int    `json:"progress"`
	Steps    []Step `json:"-"`
}
⋮----
func CreateOneStepProcessor(stepName string) Processor
⋮----
/*
 * An abstract "Processor" actually processes a Task or an Event. Given a
 * list of base paths, each subdirectory defines a task action or an event
 * handler. If two base paths contain the same subdir name, the processor
 * counts as one.
 */
func ListProcessors(paths []string) []string
⋮----
func (d Processor) ToJSON() []byte
⋮----
func (d *Processor) SetProgressAtStep(stepIndex int, stepProgress int) error
⋮----
func (d *Processor) getStepIndex(stepName string) (int, error)
⋮----
func (d *Processor) SetStepWeight(stepName string, weight int) error
</file>

<file path="core/agent/models/task.go">
package models
⋮----
import (
	"os"
	"sort"
	"time"
)
⋮----
"os"
"sort"
"time"
⋮----
type Task struct {
	ID        string    `json:"id" structs:"id"`
	Action    string    `json:"action" structs:"action"`
	Data      any       `json:"data" structs:"data"`
	Extra     any       `json:"extra" structs:"extra"`
	Queue     string    `json:"queue" structs:"queue"`
	User      string    `json:"user" structs:"user"`
	Timestamp time.Time `json:"timestamp" structs:"timestamp"`
	Parent    string    `json:"parent" structs:"parent"`
}
⋮----
const (
	STEP_VALIDATE_INPUT  = "validate-input.json"
	STEP_VALIDATE_OUTPUT = "validate-output.json"
)
⋮----
func CreateTaskProcessor(actionName string, actionPaths []string) Processor
⋮----
var inputSchema = ""
var outputSchema = ""
⋮----
// Squash the action dirs in a single list
⋮----
// Executable steps under the actionPaths are launched sequentially
// in alphabetical order:
</file>

<file path="core/agent/validation/validation.go">
package validation
⋮----
import (
	"encoding/json"
	"fmt"
	"github.com/xeipuuv/gojsonschema"
	"os"
	"strings"
)
⋮----
"encoding/json"
"fmt"
"github.com/xeipuuv/gojsonschema"
"os"
"strings"
⋮----
type ValidationError struct {
	Parameter string `json:"parameter"`
	Error     string `json:"error"`
	Value     any    `json:"value"`
	Field     string `json:"field"`
}
⋮----
func ToJSON(errorList []gojsonschema.ResultError) ([]byte, error)
⋮----
func ValidateGoStruct(schemaPath string, data any) ([]gojsonschema.ResultError, error)
⋮----
func ValidateJsonString(schemaPath string, data []byte) ([]gojsonschema.ResultError, error)
⋮----
var ddata any
</file>

<file path="core/agent/agent.go">
package main
⋮----
import (
	"context"
	"flag"
	"log"
	"os"
	"os/signal"
	"strconv"
	"syscall"
	"time"
	"github.com/redis/go-redis/v9"
)
⋮----
"context"
"flag"
"log"
"os"
"os/signal"
"strconv"
"syscall"
"time"
⋮----
"github.com/redis/go-redis/v9"
⋮----
const (
	SD_EMERG   = "<0>"
	SD_ALERT   = "<1>"
	SD_CRIT    = "<2>"
	SD_ERR     = "<3>"
	SD_WARNING = "<4>"
	SD_NOTICE  = "<5>"
	SD_INFO    = "<6>"
	SD_DEBUG   = "<7>"
)
⋮----
var ctx = context.Background()
var agentPrefix string
var actionPaths flagStringSlice
var eventPaths flagStringSlice
⋮----
var pollingDuration = 5000 * time.Millisecond
var taskExpireDuration = 8 * time.Hour
⋮----
var maxConcurrency = 32
var overloadSleep = 500 * time.Millisecond
⋮----
type flagStringSlice []string
⋮----
func (v *flagStringSlice) String() string
⋮----
return "" // doesn't matter
⋮----
func (v *flagStringSlice) Set(raw string) error
⋮----
func setClientNameCallback(ctx context.Context, cn *redis.Conn) error
⋮----
func main()
⋮----
// Parse command-line arguments
⋮----
// Override max number of concurrent tasks and event handlers
⋮----
// Overrid the wait time before rejecting tasks and events
⋮----
var signalChannel = make(chan os.Signal, 1)
⋮----
var actionsCtx, cancelActions = context.WithCancel(ctx)
var eventsCtx, cancelEvents = context.WithCancel(ctx)
</file>

<file path="core/agent/AGENTS.md">
# Agent

The agent daemon executes **actions** and **events** on cluster nodes. It reads
tasks from Redis queues and runs step scripts found in the filesystem.

## Build & test

```bash
go build .                   # build the agent binary
bash test-agent.sh           # run Robot Framework tests (requires buildah and podman)
```

`test-agent.sh` spins up a Redis container and runs the test suite in
`test/suite/`. Mock actions live in `test/actions/` and `test/events/`.

## Module layout

| File | Purpose |
|------|---------|
| `agent.go` | Main entry, CLI flags, signal handling (SIGUSR1), goroutine orchestration |
| `htask.go` | Task handler — `BRPOP` from `<agent-id>/tasks`, runs action steps, publishes progress, obscures secrets |
| `hevent.go` | Event handler — subscribes to `*/event/*` patterns |
| `hbuiltin.go` | Built-in actions: `list-actions`, `cancel-task`, `rejectAction` (overload handling) |
| `envstate.go` | Reads the `./environment` state file (KEY=VALUE) |
| `worklimit.go` | Atomic concurrency limiter for goroutines |
| `models/` | Data types and factory functions: `Task`, `Processor`, `Step`, `Event`, `CreateTaskProcessor()`, `CreateEventHandler()`, `ListProcessors()` |
| `validation/` | JSON Schema validation via `gojsonschema` |

## How actions execute

1. Agent pops a task from Redis (`BRPOP <agent-id>/tasks`).
2. Locates the action directory and discovers step executables (sorted
   alphabetically).
3. Input is validated against `validate-input.json` if present (inserted as
   first step). Output is validated against `validate-output.json` if present
   (inserted as last step).
4. Each step runs as a subprocess receiving:
   - **stdin (fd 0)**: task data JSON
   - **stdout (fd 1)**: captured as output
   - **stderr (fd 2)**: logged
   - **fd 3 (`AGENT_COMFD`)**: IPC channel for `set-progress`,
     `set-status` (only `validation-failed` is accepted), `set-weight` commands
5. Writes results to Redis: `task/<agent-id>/<task-id>/{context,output,error,exit_code}`.
   Task results expire after 8 hours.

## Task lifecycle

`pending → running → completed | aborted | validation-failed`

## Exit codes

- `0` - success
- `1` - **available to use** for generic errors
- `2-7` - **available to use** for action-specific error numbers
- `8` - the invoked action is not defined or has 0 steps (the directory is empty)
- `9` - OS `exec()` error, like "file is not executable" and similar
- `10` - default exit code once `validation-failed` status is set. It
  can be overridden by terminating the step with a non-zero exit code.
- `11` - error "Agent is busy" is returned if the number of running
  actions or events has reached `MAX_CONCURRENCY` (32) and after waiting
  `OVERLOAD_SLEEP` (500ms) that number did not decrease.
- `12-31` - reserved to the agent implementation
- `32-255` - **available to use** for action-specific error numbers

## Environment variables

**Action steps** inherit the agent `./environment` contents plus:

- `AGENT_COMFD=3` — IPC file descriptor for action commands
- `AGENT_TASK_ID`, `AGENT_TASK_ACTION`, `AGENT_TASK_USER` — task context

**Event handler steps** inherit the agent `./environment` contents plus:

- `AGENT_COMFD=2` — commands are redirected to stderr (ignored)
- `AGENT_EVENT_NAME`, `AGENT_EVENT_SOURCE` — event context

**Agent-level tuning** (consumed by the agent process, not passed to steps):

- `AGENT_POLLING_INTERVAL` — BRPOP timeout in ms (default 5000)
- `MAX_CONCURRENCY` — max concurrent tasks (default 32)
- `OVERLOAD_SLEEP` — grace period before rejecting (default varies)

## Conventions

- Action steps are standalone executables (Python 3 or Bash), numbered for
  ordering (`00validate`, `50update`, `60post`).
- Secrets in task context are obscured with `"XXX"` in Redis.
- Logging uses systemd severity prefixes (`SD_ERR`, `SD_DEBUG`, etc.).
- Concurrency is bounded by `MAX_CONCURRENCY` (default 32); excess tasks get
  exit code 11.
</file>

<file path="core/agent/envstate.go">
package main
⋮----
import (
	"log"
	"os"
	"strings"
)
⋮----
"log"
"os"
"strings"
⋮----
func readStateFile() []string
</file>

<file path="core/agent/hbuiltin.go">
package main
⋮----
import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"sync"
	"github.com/NethServer/ns8-core/core/agent/models"
	"github.com/redis/go-redis/v9"
)
⋮----
"context"
"encoding/json"
"fmt"
"log"
"sync"
⋮----
"github.com/NethServer/ns8-core/core/agent/models"
"github.com/redis/go-redis/v9"
⋮----
func runListActions(rdb *redis.Client, task *models.Task)
⋮----
func runCancelTask(rdb *redis.Client, task *models.Task, cancelFuncMap map[string]context.CancelFunc, tcMu *sync.Mutex)
⋮----
type CancelRequest struct {
		Task    string
		Timeout int
	}
⋮----
var request CancelRequest
var exitCode int
⋮----
// STEP 1. builtin-validation.json
⋮----
func rejectAction(rdb *redis.Client, actionCtx context.Context, task *models.Task)
</file>

<file path="core/agent/hevent.go">
package main
⋮----
import (
	"context"
	"log"
	"os"
	"os/exec"
	"strings"
	"time"
	"github.com/NethServer/ns8-core/core/agent/models"
	"github.com/redis/go-redis/v9"
)
⋮----
"context"
"log"
"os"
"os/exec"
"strings"
"time"
⋮----
"github.com/NethServer/ns8-core/core/agent/models"
"github.com/redis/go-redis/v9"
⋮----
func listenEventsAsync(ctx context.Context, complete chan int)
⋮----
// Fallback to leader address
⋮----
// Fallback to local default
⋮----
func runEvent(wg *workersLimiter, event *models.Event)
⋮----
var exitCode int = 0
var lastStep string = ""
⋮----
handler := models.CreateEventHandler(event.Name, eventPaths) // global variable
⋮----
return // if event handler is not defined, skip silently this run
⋮----
// Get additional environment variables from the filesystem
</file>

<file path="core/agent/htask.go">
package main
⋮----
import (
	"context"
	"encoding/csv"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"log"
	"os"
	"os/exec"
	"strconv"
	"strings"
	"sync"
	"syscall"
	"time"
	"github.com/NethServer/ns8-core/core/agent/models"
	"github.com/NethServer/ns8-core/core/agent/validation"
	"github.com/redis/go-redis/v9"
)
⋮----
"context"
"encoding/csv"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"os"
"os/exec"
"strconv"
"strings"
"sync"
"syscall"
"time"
⋮----
"github.com/NethServer/ns8-core/core/agent/models"
"github.com/NethServer/ns8-core/core/agent/validation"
"github.com/redis/go-redis/v9"
⋮----
func runAction(rdb *redis.Client, actionCtx context.Context, task *models.Task)
⋮----
var actionOutput string = ""
var actionError string = ""
var exitCode int = 0
⋮----
publishStatus(rdb, progressChannel, actionDescriptor) // publish pending status
⋮----
// If the action is not defined our exit code is returned
// More info in man systemd.exec and from `systemd-analyze exit-status` output
⋮----
var weight int
var err error
⋮----
var progress int
⋮----
func listenActionsAsync(actionsCtx context.Context, complete chan int)
⋮----
var tcMu sync.Mutex
⋮----
func readTasks(queueRdb *redis.Client, rdb *redis.Client, brpopCtx context.Context, taskCh chan models.Task)
⋮----
var lastPopErr error = errors.New("WRONGPASS invalid username-password pair or user is disabled.")
⋮----
var task models.Task
⋮----
func exportToRedis(env []string) []any
⋮----
func publishStatus(client redis.Cmdable, progressChannel string, actionDescriptor models.Processor)
⋮----
func obscureTaskInput(jsonStr string) string
⋮----
var jsonData map[string]any
⋮----
func isSensitive(target string) bool
⋮----
func recursiveObscureSensitiveKeys(data any)
</file>

<file path="core/agent/README.md">
# Agent

* Go version 1.18+
* Run `go build .` in this directory

## Startup

Start the agent passing the following arguments

1. The agent prefix identifier (e.g. "cluster", "node/1", "module/mail1"...)
2. One or more root action/event directories

For instance:

    ./agent --agentid module/mail1 . --actionsdir ~/.config/actions --eventsdir ~/.config/events

The agent accepts also some environment variables, so a complete invocation from Bash could be:

    REDIS_ADDRESS=127.0.0.1:6379 REDIS_PASSWORD= ./agent module/mail1 . ~/.config/actions

## Agent behavior test suite

During development it is useful to test code changes quickly. The
`test-agent.sh` build the Golang `agent` binary and starts a
Robotframework test suite:

    bash test-agent.sh

The test suite aims to describe the commands sent to Redis by the agent
and the expected results in the agent log and environment file.

- The `test-agent.sh` script starts a detached Podman container that runs
  a Redis DB instance: `test-agent-redis`. Run the following command on a
  separate terminal to receive a detailed Redis command trace:

      podman exec -ti test-agent-redis nc 127.0.0.1 6379 <<<$'MONITOR\r\n'

- The test suite runs in a foreground container, `test-agent-suite`. On
  each run, the test suite starts and stops the `agent` process and deals
  with Redis DB setup/cleanup. Additional script arguments are forwarded
  to the Robotframework command. For example to invoke `robot` help:

      bash test-agent.sh --help

- Test results are written to the persistent `tstate` volume. To export
  its contents run:

      mkdir tstate
      podman volume export tstate | tar -C tstate -v -x -f -

When testing is finished, stop and destroy the Redis container with:

    podman stop test-agent-redis


## Task processing

After startup, the agent process blocks and waits for incoming tasks on a
Redis list (BRPOP). The list key is given by `<agent_prefix>/tasks`, e.g.
`module/mail1/tasks`.

Each list item represents a **task** to be processed by an **action**. It
must be a string representing a valid JSON-encoded object with the
following structure:

```json
{
    "id": "UUID-STRING",
    "action": "action-name",
    "data": {},
    "extra": {}
}
```

When a task is popped the agent

1. write the task payload to Redis key
   `task/<agent-id>/<task-id>/context`. Any attribute of the task `data`
   that ends with `password`, `secret`, or `token` has value replaced with
   the string `XXX`.

2. starts the action in background (more details about Action in the next
   section)

3. immediately returns to wait for more tasks on the Redis list while the
   action is running

## Actions execution model

An **action** is defined by one or more directories with the same name under the root directories
(those passed as arguments to the agent executable). Each executable file under the action
directories is an **action step**.

    dir1
     +--first-action
         +--step1
         +--step2
         +--step3

    dir2
     +--first-action
         +--step3
         +--step4

If two action steps have the same file name the last root action directory argument wins,
and previous executables with the same name are ignored.

Action steps are invoked in alphabetical order, no matter the directory where the file is placed.

For instance if agent is started with `agent id dir1 dir2` and the directories of the figure above
when `first-action` is invoked the excuted steps are:

- `dir1/first-action/step1`
- `dir1/first-action/step2`
- `dir2/first-action/step3`
- `dir2/first-action/step4`

## Action status and outcomes

The possible action status are:

- `pending`
- `running`
- `completed`
- `aborted`
- `validation-failed`

An action status is initially set to `pending` then switches to `running` during normal steps execution.

If the execution of a step cannot be started successfully by the OS `exec()` system call the whole action
is `aborted` and the exit code 9 is set.

If an action step completes with a non-zero exit code, the whole action is considered `aborted` and no more steps are
invoked.

When all steps are executed successfully the action is considered `completed`. Then the following keys are set in Redis DB

- `task/<agent-id>/<task-id>/output`, collects data sent to FD 1 by all steps
- `task/<agent-id>/<task-id>/error`, collects data sent to FD 2 by all steps
- `task/<agent-id>/<task-id>/exit_code`, 0 if all steps were successful, otherwise the exit code of the failing step
- `<agent-id>/environment`, copy of additional environment variables passed
  to the action steps. The values are stored in the local module
  filesystem and copied to Redis if the action has completed successfully.

The `validation-failed` status must be set manually with the `set-status` command, described below. When the `validation-failed`
status is set, no more steps are invoked and the action exit code is set to 10 unless another non-zero exit code is returned by
the last step.

Exit codes and their meaning:

- `0` - success
- `1` - **available to use** for generic errors
- `2-7` - **available to use** for action-specific error numbers
- `8` - the invoked action is not defined or has 0 steps (the directory is empty)
- `9` - OS `exec()` error, like "file is not executable" and similar
- `10` - default exit code once `validation-failed` status is set. It
  can be overridden by terminating the step with a non-zero exit code.
- `11` - error "Agent is busy" is returned if the number of running
  actions or events has reached `MAX_CONCURRENCY` (32) and after waiting
  `OVERLOAD_SLEEP` (500ms) that number did not decrease.
- `12-31` - reserved to the agent implementation
- `32-255` - **available to use** for action-specific error numbers

## File descriptors

Each action step receives the `task.data` contents in JSON representation
from FD 0 (INPUT). Any data sent to FD 1 (OUTPUT) constitutes the action
output data, and any data sent to FD 2 (ERROR) is immediately copied to
the agent error stream and appended to the action error data.

An action step receives an additional file descriptor where it can write special command strings. The file descriptor number can be obtained from the `AGENT_COMFD` environment variable.

## Validation

Validation of input and output can be enforced using [JSON
Schema](https://json-schema.org/).

To validate the input just drop a `validate-input.json` file inside the
action directory, to validate the output just create a
`validate-output.json` file.

As general rule, schema files are loaded from special paths:
- `${AGENT_INSTALL_DIR}/validator-definitions.json`: this is always picked
  up by the agent from all actions. It can contain the common data format
  definitions
- `${AGENT_INSTALL_DIR}/actions/<action-name>/validate-input.json`: schema
  applied to validate the input data
- `${AGENT_INSTALL_DIR}/actions/<action-name>/validate-output.json`:
  schema applied to validate the output data

Additional validation logic can be implemented in an early step script
like `01validation`. If the validation fails, the step must execute the
[set-status](#set-status) command and return a non-zero exit code.


## Environment and working directory

A running action step receives the **current working directory** value and its operating system process environment from the agent. This environment consists of

- variables inherited from the agent environment (e.g. PATH, PYTHONPATH...)
- variables loaded from the local filesystem (state file `./environment`) and
  copied to the Redis DB, under the hash key `<AGENT_ID>/environment`
  (e.g. MODULE_ID, IMAGE_URL...)
- runtime agent vars:

    * `AGENT_COMFD` (integer) The file descriptor number where **action commands** (see below) can be writte to
    * `AGENT_TASK_ID` (string) The unique identifier of the Task that started the Action
    * `AGENT_TASK_ACTION` (string) The Action name
    * `AGENT_TASK_USER` (string) The user invoking the action, if available

## Action commands

A command sent to the `AGENT_COMFD` file descriptor is an UTF-8 encoded string with a trailing new-line character.
The string represents an array of space delimited fields. It must be composed at least by one field that identifies the
*command name*. Further fields are *arguments*:

    CommandName [ SPACE Argument ]... NEWLINE

Fields are separated by the space character. If a field value contains
a space it can be wrapped by double quotes.

Available commands are:

- `set-status`
- `set-progress`
- `set-weight`

For example, to send a `set-progress` command in a Bash script:

    echo 'set-progress 73' >&${AGENT_COMFD}

The same command in Python 3

    import os
    fd = int(os.environ['AGENT_COMFD'])
    os.write(fd, 'set-progress 73\n'.encode('utf-8'))

### set-status

The `set-status` command manually changes the status of the running action. The command requires the new status name
as argument. Accepted status names are:

- `validation-failed` - see the **Action status** section for more information

For example

    set-status validation-failed

### set-progress

A step *progress* is a number from 0 to 100. It helps the UI to show the user a smooth progress bar.

When a step execution completes successfully its progress value is automatically set to 100.

For instance the following command is sent during the 3rd step of a running action. The action has
5 steps. The command sets the current (3rd) step progress to 73 (out of 100).

    set-progress 73

The overall action progress value is given by the sum of all completed steps plus
the current step progress value. From the previous example the sum is

    100 + 100 + 73 = 273

As the action has 5 steps (100 units each) the overall action progress is

    273 * 100 / 500 = 54%

The UI can show the user that the running task progress is at 54%.

### set-weight

Each action step is assigned 1 as default *weight*. The step weight multiplies its progress value to obtain the overall action progress value. For example

    set-weight 50update 8

The above command sets the `50update` step weight to 8. A step that downloads data from the network, or performs a long filesystem
operation can be assigned a bigger weight to balance the progress increments of the action.

## Builtin actions

The `agent` binary implements some builtin actions. They are not read from
the directories passed as command arguments and cannot be overridden.

### list-actions

The `list-actions` action scans the action directories on the filesystems
and returns an array of action names. Builtin actions are included, too.

Action input is ignored.

Action output (JSON format):

    ["action1", "action2", "list-actions", "cancel-task"]

### cancel-task

The `cancel-task` action cancels a running task, by sending a TERM signal
to the currently running step process and any other process forked from
it.  Depending on how the TERM signal is handled by the step process and
its exit code, the action can be subsequently aborted or continue
execution.

If the given task ID does not match any running task, the action aborts
with code `2`.

Action input (JSON format):

    {"task":"fbee04e5-f251-4cda-a835-d7598449bf16"}

Action output is undefined.

## Events

Actions are started when a task object is received: it is designed to be a
one-to-one communication channel.  On the opposite, Events are a form of
one-to-many communication.  When the agent starts it listens for events
with a Redis `PSUBSCRIBE */event/*` command.

If the TCP connection is closed, the underlying `go-redis` library handles
the server reconnection.

When an event matching the PSUBSCRIBE pattern is received, the agent
starts to process it.

The Redis channel matches the pattern `<Source>/event/<Name>`. The prefix
is the event **source**. The suffix is the event **name**.

The event processing model resembles the actions one: a matching event
name is searched in the directory list defined by ``--eventsdir`` command
arguments. Then a list of executable event handler steps is built with the
same rules of action steps. The steps are executed in alphabetical order
and if one of them has non-zero exit code, the event processing is
aborted.

Action execution similarities are:

- The event payload can be read from the step stdin
- The step stdout and stderr file descriptors are redirected to the agent stderr

Differences with the action execution are:

- The final event exit code is written to the agent log only
- Commands sent to AGENT_COMFD are ignored (and redirected to the agent stderr)
</file>

<file path="core/agent/worklimit.go">
package main
⋮----
import (
	"sync"
	"sync/atomic"
	"time"
)
⋮----
"sync"
"sync/atomic"
"time"
⋮----
type workersLimiter struct {
	wg      sync.WaitGroup
	counter int64
	limit   int64
	delay   time.Duration
}
⋮----
func NewWorkersLimiter(limit int, delay time.Duration) *workersLimiter
⋮----
func (w *workersLimiter) Add(delta int)
⋮----
func (w *workersLimiter) Done()
⋮----
func (w *workersLimiter) Wait()
⋮----
func (w *workersLimiter) ObserveOverload() bool
</file>

<file path="core/api-moduled/example/handlers/create/post">
#!/bin/bash

env 1>&2

printf '{
    "id": 123456,
    "user": "%s"
}\n' $JWT_USER
</file>

<file path="core/api-moduled/example/handlers/create/validate-input.json">
{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "title": "create input",
    "$id": "http://schema.nethserver.org/example/create-input.json",
    "type": "object",
    "required": ["id"],
    "properties": {
        "id": {
            "type": "integer",
            "minimum": 1
        }
    }
}
</file>

<file path="core/api-moduled/example/handlers/list/post">
#!/bin/bash

env 1>&2

printf '{
  "objects": [{"id":123456}]
}\n'
</file>

<file path="core/api-moduled/example/handlers/list/validate-output.json">
{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "title": "list output",
    "$id": "http://schema.nethserver.org/example/list-output.json",
    "type": "object",
    "required": ["objects"],
    "properties": {
        "objects": {
            "type": "array",
            "minItems": 1
        }
    }
}
</file>

<file path="core/api-moduled/example/handlers/login/post">
#!/bin/bash


env 1>&2

exec jq '{"uid":.username,"scopes":["s1","s2"],"groups":["domain admins"]}'
</file>

<file path="core/api-moduled/validation/validation.go">
package validation
⋮----
import (
	"encoding/json"
	"fmt"
	"github.com/xeipuuv/gojsonschema"
	"os"
	"strings"
)
⋮----
"encoding/json"
"fmt"
"github.com/xeipuuv/gojsonschema"
"os"
"strings"
⋮----
type ValidationError struct {
	Parameter string `json:"parameter"`
	Error     string `json:"error"`
	Value     any    `json:"value"`
	Field     string `json:"field"`
}
⋮----
func toValidationErrorArray(errorList []gojsonschema.ResultError) []ValidationError
⋮----
func validateGoStruct(schemaPath string, data any) ([]gojsonschema.ResultError, error)
⋮----
func ValidatePayload(schemaPath string, data []byte) ([]ValidationError, error)
⋮----
var ddata any
</file>

<file path="core/api-moduled/AGENTS.md">
# API Moduled

Lightweight, filesystem-driven HTTP API server for individual NS8 modules.
It wraps external executables (shell scripts, Python) with JWT auth and
JSON Schema validation. Each module instance runs its own `api-moduled`
process.

Known applications using `api-moduled` are ns8-samba and ns8-openldap.
They use it to implement a user self-service portal (create/edit/delete
users and groups of the LDAP DB).

## Build

```bash
go build .                   # build with CGO_ENABLED=0 (no C deps)
```

## Module layout

The entire server is two files:

| File | Purpose |
|------|---------|
| `api-moduled.go` | Main entry — routing, JWT setup, handler dispatch (~370 LOC) |
| `validation/validation.go` | JSON Schema validation with external definitions support |

## How it works

Handlers are **directories on disk**, not Go code. The URL path maps directly
to a handler directory:

```
POST /api/myhandler  →  executes  handlers/myhandler/post
```

Each handler directory can contain:
- `post` — executable to run (receives JSON on stdin, returns JSON on stdout)
- `validate-input.json` — optional input schema
- `validate-output.json` — optional output schema

### Request flow

```
POST /api/:handler
  → validate input against validate-input.json
  → execute handlers/:handler/post with JSON stdin
  → validate output against validate-output.json
  → return JSON response
```

### Environment injected into handlers

- `PATH` — inherited from the server process
- `JWT_ID` — authenticated user identity
- `JWT_CLAIMS` — full JWT claims as JSON
- Values of environment variables whose names are listed in `AMLD_EXPORT_ENV`

## Authentication

- **Login**: `POST /api/login` calls `handlers/login/post` which must return
  JSON claims (including a `uid` field). Exit code 2–7 = bad credentials;
  exit code 1 or 8+ = internal error.
- **Logout**: `POST /api/logout` invalidates the current token.
- **JWT**: Configurable timeout (default 4h). Scope claim is an optional array
  of allowed handler names. If the scope claim is absent, the token is unrestricted;
  if it is present but empty, no handlers are allowed.
- **Basic auth**: `GET /api/auth` validates credentials without issuing a token.

## Configuration

All via `AMLD_` prefixed environment variables (uses Viper):

| Variable | Default | Purpose |
|----------|---------|---------|
| `AMLD_HANDLER_DIR` | `./handlers/` | Handler directory root |
| `AMLD_PUBLIC_DIR` | `./public/` | Static files directory |
| `AMLD_BIND_ADDRESS` | `:9313` | Listen address |
| `AMLD_JWT_SECRET` | (empty) | JWT signing key — **must be set** |
| `AMLD_JWT_TIMEOUT` | `4h` | Token expiry |
| `AMLD_JWT_TOKEN_LOOKUP` | `header: Authorization` | Where to find the JWT token |
| `AMLD_JWT_REALM` | `api-moduled` | JWT realm name |
| `AMLD_ID_KEY` | `uid` | JWT identity claim key |
| `AMLD_EXPORT_ENV` | — | Extra env vars for handlers |
| `AMLD_RATE_LIMIT_AVERAGE` | `25` | Per-IP requests/sec across all routes; `0` disables |
| `AMLD_RATE_LIMIT_BURST` | `300` | Burst allowance above the average |

The sustained average is what bounds a flood; the burst only sets how many
requests may arrive at once, and is sized for a legitimate UI page load. A burst
below `1` is clamped to `1` by `RateLimiter`; use `AMLD_RATE_LIMIT_AVERAGE=0` to
disable the limiter.

## Key differences from api-server

- **No Redis dependency** — auth is delegated to handler scripts
- **No SQLite** — no audit log
- **No WebSocket** — request/response only
- **Generic** — knows nothing about NethServer; any executable can be a handler
- **Stateless** — single static binary, trivial to deploy
</file>

<file path="core/api-moduled/api-moduled.go">
package main
⋮----
import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"io"
	"log"
	"net/http"
	"os"
	"os/exec"
	"path"
	"strings"
	"sync"
	"time"
	"github.com/NethServer/ns8-core/core/api-moduled/validation"
	jwt "github.com/appleboy/gin-jwt/v3"
	"github.com/appleboy/gin-jwt/v3/core"
	"github.com/gin-contrib/cors"
	"github.com/gin-contrib/gzip"
	"github.com/gin-contrib/static"
	"github.com/gin-gonic/gin"
	gojwt "github.com/golang-jwt/jwt/v5"
	"github.com/spf13/viper"
	"golang.org/x/time/rate"
)
⋮----
"bytes"
"context"
"encoding/json"
"errors"
"io"
"log"
"net/http"
"os"
"os/exec"
"path"
"strings"
"sync"
"time"
⋮----
"github.com/NethServer/ns8-core/core/api-moduled/validation"
jwt "github.com/appleboy/gin-jwt/v3"
"github.com/appleboy/gin-jwt/v3/core"
"github.com/gin-contrib/cors"
"github.com/gin-contrib/gzip"
"github.com/gin-contrib/static"
"github.com/gin-gonic/gin"
gojwt "github.com/golang-jwt/jwt/v5"
"github.com/spf13/viper"
"golang.org/x/time/rate"
⋮----
var logger *log.Logger
⋮----
func BodyLimit(limitBytes int64) gin.HandlerFunc
⋮----
const rateLimiterStaleAfter = 3 * time.Minute
const rateLimiterCleanupInterval = time.Minute
⋮----
type rateLimiterVisitor struct {
	limiter  *rate.Limiter
	lastSeen time.Time
}
⋮----
func RateLimiter(rps rate.Limit, burst int) gin.HandlerFunc
⋮----
var mu sync.Mutex
⋮----
const (
	SD_EMERG   = "<0>"
	SD_ALERT   = "<1>"
	SD_CRIT    = "<2>"
	SD_ERR     = "<3>"
	SD_WARNING = "<4>"
	SD_NOTICE  = "<5>"
	SD_INFO    = "<6>"
	SD_DEBUG   = "<7>"
)
⋮----
func main()
⋮----
func prepareEnvironment(ginCtx *gin.Context) []string
⋮----
func apiPostHandler(ginCtx *gin.Context)
⋮----
var responsePayload gin.H
⋮----
type noRefreshTokenStore struct{}
⋮----
func (noRefreshTokenStore) Set(ctx context.Context, token string, userData any, expiry time.Time) error
⋮----
func (noRefreshTokenStore) Get(ctx context.Context, token string) (any, error)
⋮----
func (noRefreshTokenStore) Delete(ctx context.Context, token string) error
⋮----
func (noRefreshTokenStore) Cleanup(ctx context.Context) (int, error)
⋮----
func (noRefreshTokenStore) Count(ctx context.Context) (int, error)
⋮----
func tokenErrorMessage(err error) string
⋮----
func createJwtInstance(baseHandlerDir string) *jwt.GinJWTMiddleware
⋮----
func runLogin(baseHandlerDir string, requestBytes []byte, ginCtx *gin.Context) ([]byte, error, int, string)
⋮----
func basicAuth(ginCtx *gin.Context)
</file>

<file path="core/api-moduled/README.md">
# api-moduled

Generic HTTP API server with JSON schema validation and JWT authentication

## Configuration

Configuration parameters can be passed as environment variables.

- `AMLD_PUBLIC_DIR`, the directory from which static files are served --
  default `./public/`

- `AMLD_HANDLER_DIR`, the root directory where the handler commands are --
  default `./handlers/`

- `AMLD_BIND_ADDRESS`, the IP address and port number where the HTTP
  server listens for connections -- default `:9313`

- `AMLD_ID_KEY`, the name of the key in the JWT claims payload which holds
  the authenticated identity value -- default `uid`

- `AMLD_JWT_SECRET`, a secret random string used for JWT signature --
  default `` (empty)

- `AMLD_JWT_TIMEOUT`, duration in seconds of a JWT token -- default
  `14400` (4 hours)

- `AMLD_JWT_TOKEN_LOOKUP`, configure GIN-JWT token lookup. Refer to its
  README for details -- default `header: Authorization`

- `AMLD_JWT_REALM`, set the Realm for GIN-JWT cookie-based authorization
  -- default `api-moduled`

- `AMLD_EXPORT_ENV`, space-separated list of environment variable names that
  are exported to handler commands -- default `` (empty)

- `AMLD_RATE_LIMIT_AVERAGE`, max sustained requests per second per client IP
  across all API routes -- default `25`; set to `0` to disable rate limiting

- `AMLD_RATE_LIMIT_BURST`, burst allowance above the average before requests
  are rejected with HTTP 429 -- default `300`

The sustained average is what bounds a flood; the burst only sets how many
requests may arrive at once, and is therefore sized for a legitimate UI page
load.

A burst below `1` is raised to `1`, because a zero-capacity token bucket would
reject every request; use `AMLD_RATE_LIMIT_AVERAGE=0` to disable the limiter.

## How to implement the API

Each directory under `AMLD_HANDLER_DIR` is considered an API HTTP route.

For instance, if a `list/` directory exists under `AMLD_HANDLER_DIR` the
corresponding `/api/list` URL path is bound to it. Under the `list/`
directory the following files can exist:

- `post` executable command, which implements the POST HTTP verb.
- `validate-input.json` file, with the JSON schema of a valid input
- `validate-output.json` file, with the JSON schema of a valid output

Note that the `login/` directory has a special meaning.

## Command execution

When a API command is executed, the following environment variables are
passed:

- `PATH`, a copy of the existing `PATH` variable from the server
  environment
- `JWT_ID`, the value of the identity key in the JWT claims payload
- `JWT_CLAIMS`, the JWT claims payload, in JSON-encoded form
- other variables listed in `AMLD_EXPORT_ENV`

The command stderr is sent to the server log.

Furthermore, in a POST request handler:

- The command process can read from standard input the request payload, if
  it passes the JSON schema input validation step
- The command output is returned as response to the API caller, if it
  passes the JSON schema output validation step

Note that the output of the `login/post` command is not returned to the
client: it has a special meaning decribed in the *Authentication* section.

## Authentication

### JWT token
The `login` handler, bound to `/api/login` URL path is the only one that
can be accessed without a valid JWT token. It must provide a `post`
command, implementing the following protocol:

- The command stdin receives the request payload as usual
- If the login is successful the command prints to stdout the JWT claims
  in JSON format.
  * Print out as little data as possible!
  * Ensure the claims include the JWT identifier attribute, matching
    `JWT_ID` configuration.
  * The command exit code must be 0.
- If the login fails, exit code must be between 2 and 7 for bad
  credentials. A value of 1 or 8 and above is considered a generic error.
  Different log lines are printed to stderr accordingly. For example:

      Bad login attempt! Exit code 2; remote address: 1.2.3.4

  In case of internal error

      Error from /home/openldap1/.config/api-moduled/handlers/login/post: exit code 1

Note that for the `login` handler, the `validate-output.json` file is
ignored. This is an example of `/api/login` response payload:

### Basic auth
You can check whether a user's credentials are valid via the `GET /api/auth` API which
does not return an authentication token but responds:
- `200 OK` if credentials are valid
- `401 Unauthorized` if credentials are invalid

```json
{
  "claims": {
    "groups": [],
    "scope" : ["change-password"],
    "uid": "first.user"
  },
  "expire": "2023-10-13T14:11:27Z",
  "message": "login succeeded",
  "code": 200,
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2OTcyMDYyODcsImdyb3VwcyI6W10sIm9yaWdfaWF0IjoxNjk3MTkxODg3LCJ1aWQiOiJmaXJzdC51c2VyIn0.ItWqHn94-vLWB3sIS5ontvKqJhcIrnxoYn-yG4hY9xw"
}
```

Format description:

- The `claims` attribute is a copy of JWT claims. The `claims.scope`
  attribute is used for authorization checks, as explained in the next
  section.
- JWT itself is returned as a string in the `token` attribute
- `expire` timestamp corresponds to the JWT `exp` date

In case of login failure, HTTP status 401 is returned, with a similar payload:

```json
{
  "code": 401,
  "message": "incorrect Username or Password"
}
```

## Authorization

The `login` script can optionally return a `scope` claim, so the token can
be used only for a restricted list of handlers.

- If the `scope` claim is not set, the token is valid for any handler.
- Otherwise, if the `scope` claim is set and its value is an array of
  strings, on each request the handler name is seeked in the array. If a
  match is found, the request is authorized, otherwise a `403` status is
  returned to the client.
</file>

<file path="core/api-server/audit/audit.go">
package audit
⋮----
import (
	"fmt"
	"strings"
	"time"
	"github.com/pkg/errors"
	"github.com/NethServer/ns8-core/core/api-server/configuration"
	"github.com/NethServer/ns8-core/core/api-server/models"
	"github.com/NethServer/ns8-core/core/api-server/utils"
	"database/sql"
	_ "github.com/mattn/go-sqlite3"
)
⋮----
"fmt"
"strings"
"time"
⋮----
"github.com/pkg/errors"
⋮----
"github.com/NethServer/ns8-core/core/api-server/configuration"
"github.com/NethServer/ns8-core/core/api-server/models"
"github.com/NethServer/ns8-core/core/api-server/utils"
⋮----
"database/sql"
⋮----
_ "github.com/mattn/go-sqlite3"
⋮----
faults struct {
		faultySchema  bool
		faultyOpen    bool
		faultyConfig  bool
		faultyWALMode bool
	}
⋮----
dbUtils struct {
		conn         *sql.DB
		openFail     error
		faultyStatus faults
		tableExist   func(err error) bool
		isFaulty     func(f faults) (bool, string)
	}
⋮----
var db *dbUtils
⋮----
func Init()
⋮----
func createDB()
⋮----
func enableWALBasedJournal()
⋮----
func Store(audit models.Audit)
⋮----
func QueryArgs(query string, args ...any) []models.Audit
⋮----
var results []models.Audit
⋮----
var auditRow models.Audit
var timestamp string
⋮----
func Query(query string) []string
⋮----
var results []string
⋮----
var field string
</file>

<file path="core/api-server/configuration/configuration.go">
package configuration
⋮----
import (
	"os"
	"strconv"
	"strings"
)
⋮----
"os"
"strconv"
"strings"
⋮----
type Configuration struct {
	ListenAddress string   `json:"listen_address"`
	RedisAddress  string   `json:"redis_address"`
	RedisUser     string   `json:"redis_user"`
	RedisPassword string   `json:"redis_password"`
	Secret        string   `json:"secret"`
	StaticPath    string   `json:"static_path"`
	AuditFile     string   `json:"audit_file"`
	Issuer        string   `json:"issuer"`
	SensitiveList []string `json:"sensitive_list"`
	GlobalRateLimitAverage int `json:"global_rate_limit_average"`
	GlobalRateLimitBurst   int `json:"global_rate_limit_burst"`
}
⋮----
var Config = Configuration{}
⋮----
func Init()
</file>

<file path="core/api-server/methods/audit.go">
package methods
⋮----
import (
	"net/http"
	"strconv"
	"strings"
	"github.com/fatih/structs"
	"github.com/gin-gonic/gin"
	"github.com/NethServer/ns8-core/core/api-server/audit"
	"github.com/NethServer/ns8-core/core/api-server/configuration"
	"github.com/NethServer/ns8-core/core/api-server/response"
)
⋮----
"net/http"
"strconv"
"strings"
⋮----
"github.com/fatih/structs"
"github.com/gin-gonic/gin"
⋮----
"github.com/NethServer/ns8-core/core/api-server/audit"
"github.com/NethServer/ns8-core/core/api-server/configuration"
"github.com/NethServer/ns8-core/core/api-server/response"
⋮----
func GetAudits(c *gin.Context)
⋮----
func GetAuditsUsers(c *gin.Context)
⋮----
func GetAuditsActions(c *gin.Context)
</file>

<file path="core/api-server/methods/auth_test.go">
package methods
⋮----
import "testing"
⋮----
func TestCheckIPAllowed(t *testing.T)
</file>

<file path="core/api-server/methods/auth.go">
package methods
⋮----
import (
	"context"
	"crypto/rand"
	"encoding/base32"
	"fmt"
	"net"
	"net/http"
	"net/url"
	"path/filepath"
	"strings"
	jwt "github.com/appleboy/gin-jwt/v3"
	"github.com/dgryski/dgoogauth"
	"github.com/fatih/structs"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/pkg/errors"
	"github.com/NethServer/ns8-core/core/api-server/configuration"
	"github.com/NethServer/ns8-core/core/api-server/models"
	"github.com/NethServer/ns8-core/core/api-server/redis"
	"github.com/NethServer/ns8-core/core/api-server/response"
	"github.com/NethServer/ns8-core/core/api-server/utils"
)
⋮----
"context"
"crypto/rand"
"encoding/base32"
"fmt"
"net"
"net/http"
"net/url"
"path/filepath"
"strings"
⋮----
jwt "github.com/appleboy/gin-jwt/v3"
"github.com/dgryski/dgoogauth"
"github.com/fatih/structs"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"github.com/pkg/errors"
⋮----
"github.com/NethServer/ns8-core/core/api-server/configuration"
"github.com/NethServer/ns8-core/core/api-server/models"
"github.com/NethServer/ns8-core/core/api-server/redis"
"github.com/NethServer/ns8-core/core/api-server/response"
"github.com/NethServer/ns8-core/core/api-server/utils"
⋮----
var ctx = context.Background()
⋮----
func RedisLive() bool
⋮----
func RedisAuthentication(username string, password string) error
⋮----
func RedisAuthorization(username string, c *gin.Context) (models.UserAuthorizations, error)
⋮----
var userAuthorizationsRedis models.UserAuthorizations
⋮----
var pathGet string
var pathScan string
⋮----
var actions []string
⋮----
// duplicated values are allowed, since Authorizator checks only existence
⋮----
// compose user authorizations
⋮----
userAuthorizationsRedis.Role = roles // keep original string of raw role list
⋮----
// close redis connection
⋮----
// return auths
⋮----
// CheckOTP godoc
// @Summary Check if OTP validates for the given username
func CheckOTP(username string, otp string) bool
⋮----
func checkOtpBySecret(secret string, otp string) bool
⋮----
// set OTP configuration
⋮----
// verify OTP
⋮----
// Set2FAStatus godoc
// @Summary Set the 2FA Redis flag, if OTP is verified
// @Produce  json
// @Success 200 {object} response.StatusOK{code=int,message=string,data=object}
// @Failure 400 {object} response.StatusBadRequest{code=int,message=string,data=object}
// @Router /2FA [post]
// @Tags /2FA auth
func Set2FAStatus(c *gin.Context)
⋮----
// get payload
var jsonOTP models.OTPJson
⋮----
// Check if OTP is valid
⋮----
// set the user 2FA secret: the next login request requires OTP.
⋮----
// response
⋮----
func QRCode(c *gin.Context)
⋮----
func Get2FAStatus(c *gin.Context)
⋮----
func Del2FAStatus(c *gin.Context)
⋮----
// BasicAuthModule godoc
// @Summary Use Basic HTTP auth for module
// @Description for a specific action, check basic auth for module
⋮----
// @Header 200 {string} Authorization "Basic base64(username:password)"
⋮----
// @Failure 401 {object} response.StatusUnauthorized{code=int,message=string,data=object}
// @Failure 403 {object} response.StatusForbidden{code=int,message=string,data=object}
// @Router /module/{module_id}/http-basic/{action} [get]
// @Tags /module basic_auth
func BasicAuthModule(c *gin.Context)
⋮----
// get http basic credentials
⋮----
// init redis connection
⋮----
// check authentication
⋮----
// check source IP against per-user allowed networks
⋮----
// check authorizations
⋮----
// get action for current role and entity: SMEMBERS <entity>/<reference>/roles/<role>
⋮----
// handle redis error
⋮----
// verify wildcard actions
⋮----
func setUserSecret(username string, secret string) error
⋮----
func getUserSecret(username string) string
⋮----
func Needs2faCheck(username string) bool
⋮----
// getClusterNetworks returns the loopback addresses and the cluster VPN
// network (stored in the Redis key "cluster/network") as a comma-separated
⋮----
func getClusterNetworks() string
⋮----
func GetUserNetworks(username string) string
⋮----
func CheckIPAllowed(clientIP string, allowedNetworks string) bool
⋮----
// Treat bare IPs (no prefix length) as single-host networks:
// use /32 for IPv4 and /128 for IPv6.
⋮----
// Invalid IP entry, skip it
</file>

<file path="core/api-server/methods/tasks.go">
package methods
⋮----
import (
	"encoding/json"
	"net/http"
	"sort"
	"strconv"
	"strings"
	"time"
	"github.com/fatih/structs"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	guuid "github.com/google/uuid"
	"github.com/mpvl/unique"
	"github.com/nqd/flat"
	jwt "github.com/appleboy/gin-jwt/v3"
	"github.com/NethServer/ns8-core/core/api-server/audit"
	"github.com/NethServer/ns8-core/core/api-server/configuration"
	"github.com/NethServer/ns8-core/core/api-server/models"
	"github.com/NethServer/ns8-core/core/api-server/redis"
	"github.com/NethServer/ns8-core/core/api-server/response"
)
⋮----
"encoding/json"
"net/http"
"sort"
"strconv"
"strings"
"time"
⋮----
"github.com/fatih/structs"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
guuid "github.com/google/uuid"
"github.com/mpvl/unique"
"github.com/nqd/flat"
⋮----
jwt "github.com/appleboy/gin-jwt/v3"
⋮----
"github.com/NethServer/ns8-core/core/api-server/audit"
"github.com/NethServer/ns8-core/core/api-server/configuration"
"github.com/NethServer/ns8-core/core/api-server/models"
"github.com/NethServer/ns8-core/core/api-server/redis"
"github.com/NethServer/ns8-core/core/api-server/response"
⋮----
func getList(c *gin.Context, queueName string)
⋮----
var list []string
⋮----
func getTasks(c *gin.Context, queueName string)
⋮----
var taskMap map[string]map[string]any
⋮----
var taskContentData any
⋮----
func getTaskFile(c *gin.Context, filePath string)
⋮----
var outputData any
⋮----
func getTaskContext(c *gin.Context, filePath string)
⋮----
var contextData any
⋮----
func createTask(c *gin.Context, queueName string)
⋮----
var jsonTask models.TaskJSON
⋮----
var task models.Task
⋮----
var jsonDyn map[string]any
⋮----
func GetClusterTasks(c *gin.Context)
⋮----
func GetClusterTaskFiles(c *gin.Context)
⋮----
func GetClusterTaskContext(c *gin.Context)
⋮----
func GetNodes(c *gin.Context)
⋮----
func GetNodeTasks(c *gin.Context)
⋮----
func GetNodeTaskFiles(c *gin.Context)
⋮----
func GetNodeTaskContext(c *gin.Context)
⋮----
func GetModules(c *gin.Context)
⋮----
func GetModuleTasks(c *gin.Context)
⋮----
func GetModuleTaskFiles(c *gin.Context)
⋮----
func GetModuleTaskContext(c *gin.Context)
⋮----
func CreateClusterTask(c *gin.Context)
⋮----
func CreateNodeTask(c *gin.Context)
⋮----
func CreateModuleTask(c *gin.Context)
</file>

<file path="core/api-server/middleware/middleware_test.go">
package middleware
⋮----
import (
	"io"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
	"github.com/gin-gonic/gin"
)
⋮----
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
⋮----
"github.com/gin-gonic/gin"
⋮----
func TestRateLimiter(t *testing.T)
⋮----
func TestRateLimiterZeroBurst(t *testing.T)
⋮----
func TestBodyLimit(t *testing.T)
</file>

<file path="core/api-server/middleware/middleware.go">
package middleware
⋮----
import (
	"context"
	"fmt"
	"net/http"
	"path/filepath"
	"strings"
	"sync"
	"time"
	"github.com/pkg/errors"
	"github.com/fatih/structs"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"golang.org/x/time/rate"
	jwt "github.com/appleboy/gin-jwt/v3"
	"github.com/appleboy/gin-jwt/v3/core"
	gojwt "github.com/golang-jwt/jwt/v5"
	"github.com/NethServer/ns8-core/core/api-server/audit"
	"github.com/NethServer/ns8-core/core/api-server/configuration"
	"github.com/NethServer/ns8-core/core/api-server/methods"
	"github.com/NethServer/ns8-core/core/api-server/models"
	"github.com/NethServer/ns8-core/core/api-server/response"
	"github.com/NethServer/ns8-core/core/api-server/utils"
)
⋮----
"context"
"fmt"
"net/http"
"path/filepath"
"strings"
"sync"
"time"
⋮----
"github.com/pkg/errors"
⋮----
"github.com/fatih/structs"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"golang.org/x/time/rate"
⋮----
jwt "github.com/appleboy/gin-jwt/v3"
"github.com/appleboy/gin-jwt/v3/core"
gojwt "github.com/golang-jwt/jwt/v5"
⋮----
"github.com/NethServer/ns8-core/core/api-server/audit"
"github.com/NethServer/ns8-core/core/api-server/configuration"
"github.com/NethServer/ns8-core/core/api-server/methods"
"github.com/NethServer/ns8-core/core/api-server/models"
"github.com/NethServer/ns8-core/core/api-server/response"
"github.com/NethServer/ns8-core/core/api-server/utils"
⋮----
func BodyLimit(limitBytes int64) gin.HandlerFunc
⋮----
const rateLimiterStaleAfter = 3 * time.Minute
const rateLimiterCleanupInterval = time.Minute
⋮----
type rateLimiterVisitor struct {
	limiter  *rate.Limiter
	lastSeen time.Time
}
⋮----
func RateLimiter(rps rate.Limit, burst int) gin.HandlerFunc
⋮----
var mu sync.Mutex
⋮----
type login struct {
	Username string `form:"username" json:"username" binding:"required"`
	Password string `form:"password" json:"password" binding:"required"`
	Otp      string `form:"otp" json:"otp,omitempty"`
}
⋮----
var jwtMiddleware *jwt.GinJWTMiddleware
var identityKey = "id"
⋮----
const jwtRealm = "nethserver"
⋮----
type noRefreshTokenStore struct{}
⋮----
func (noRefreshTokenStore) Set(ctx context.Context, token string, userData any, expiry time.Time) error
⋮----
func (noRefreshTokenStore) Get(ctx context.Context, token string) (any, error)
⋮----
func (noRefreshTokenStore) Delete(ctx context.Context, token string) error
⋮----
func (noRefreshTokenStore) Cleanup(ctx context.Context) (int, error)
⋮----
func (noRefreshTokenStore) Count(ctx context.Context) (int, error)
⋮----
func TokenErrorMessage(err error) string
⋮----
func InstanceJWT() *jwt.GinJWTMiddleware
⋮----
func InitJWT() *jwt.GinJWTMiddleware
⋮----
var loginVals login
⋮----
// set login credentials
⋮----
// check if redis is running
⋮----
// return user auth model
⋮----
OtpPass:  otpPassClaim, // true if OTP passed, false if OTP is not needed
⋮----
// read current user
⋮----
// create claims map
⋮----
var jsonTask models.Task
⋮----
// not authorized
⋮----
func generateLogMessage(c *gin.Context, username string, otpNeed bool) string
</file>

<file path="core/api-server/middleware/token_error_test.go">
package middleware
⋮----
import (
	"errors"
	"testing"
	"time"
	gojwt "github.com/golang-jwt/jwt/v5"
	"github.com/NethServer/ns8-core/core/api-server/configuration"
)
⋮----
"errors"
"testing"
"time"
⋮----
gojwt "github.com/golang-jwt/jwt/v5"
⋮----
"github.com/NethServer/ns8-core/core/api-server/configuration"
⋮----
const testSecret = "test-secret"
⋮----
func signToken(t *testing.T, method gojwt.SigningMethod, key any, claims gojwt.MapClaims) string
⋮----
func TestTokenErrorMessage(t *testing.T)
⋮----
func TestTokenErrorMessageOther(t *testing.T)
</file>

<file path="core/api-server/models/audit.go">
package models
⋮----
import (
	"time"
)
⋮----
"time"
⋮----
type Audit struct {
	ID        int       `json:"id" structs:"id"`
	User      string    `json:"user" structs:"user"`
	Action    string    `json:"action" structs:"action"`
	Data      string    `json:"data" structs:"data"`
	Timestamp time.Time `json:"timestamp" structs:"timestamp"`
}
</file>

<file path="core/api-server/models/event.go">
package models
⋮----
import (
	"time"
)
⋮----
"time"
⋮----
type Event struct {
	Name      string    `json:"name" structs:"name"`
	Payload   any       `json:"payload" structs:"payload"`
	Timestamp time.Time `json:"timestamp" structs:"timestamp"`
	Type      string    `json:"type" structs:"type"`
}
</file>

<file path="core/api-server/models/socket.go">
package models
⋮----
type SocketAction struct {
	Action  string `json:"action" structs:"action"`
	Payload any    `json:"payload" structs:"payload"`
}
⋮----
type LogsStartAction struct {
	Id         string `json:"id" structs:"id"`
	Mode       string `json:"mode" structs:"mode"`
	Lines      string `json:"lines" structs:"lines"`
	Filter     string `json:"filter" structs:"filter"`
	From       string `json:"from" structs:"from"`
	To         string `json:"to" structs:"to"`
	Entity     string `json:"entity" structs:"entity"`
	EntityName string `json:"entity_name" structs:"entity_name"`
	TimeZone   string `json:"timezone" structs:"timezone"`
	Instance   string `json:"instance" structs:"instance"`
	Regexp     bool   `json:"regexp" structs:"regexp"`
}
⋮----
type LogsStopAction struct {
	Id  string `json:"id" structs:"id"`
	Pid string `json:"pid" structs:"pid"`
}
</file>

<file path="core/api-server/models/task.go">
package models
⋮----
import (
	"time"
)
⋮----
"time"
⋮----
type Task struct {
	ID        string    `json:"id" structs:"id"`
	Action    string    `json:"action" structs:"action"`
	Data      any       `json:"data" structs:"data"`
	Extra     any       `json:"extra" structs:"extra"`
	Queue     string    `json:"queue" structs:"queue"`
	User      string    `json:"user" structs:"user"`
	Timestamp time.Time `json:"timestamp" structs:"timestamp"`
	Parent    string    `json:"parent" structs:"parent"`
}
⋮----
type TaskJSON struct {
	ID     string `json:"id" structs:"id" example:"null"`
	Action string `json:"action" structs:"action" example:"list-modules"`
	Data   any    `json:"data" structs:"data"`
	Extra  any    `json:"extra" structs:"extra"`
	Parent string `json:"parent" structs:"parent"`
}
</file>

<file path="core/api-server/models/user_authorizations.go">
package models
⋮----
type UserAuthorizations struct {
	Username        string   `json:"username" structs:"username"`
	Role            string   `json:"role" structs:"role"`
	Actions         []string `json:"actions" structs:"actions"`
	OtpPass         bool     `json:"otppass" structs:"otppass"`
	AllowedNetworks string   `json:"allowed_networks" structs:"allowed_networks"`
}
⋮----
type OTPJson struct {
	OTP    string `json:"otp" structs:"otp"`
	Secret string `json:"secret" structs:"secret"`
}
⋮----
type Status2FA struct {
	Status bool `json:"status" structs:"status"`
}
</file>

<file path="core/api-server/redis/redis.go">
package redis
⋮----
import (
	"context"
	"fmt"
	"github.com/NethServer/ns8-core/core/api-server/configuration"
	"strconv"
	"strings"
	"github.com/redis/go-redis/v9"
)
⋮----
"context"
"fmt"
"github.com/NethServer/ns8-core/core/api-server/configuration"
"strconv"
"strings"
⋮----
"github.com/redis/go-redis/v9"
⋮----
func Instance() *redis.Client
⋮----
func GetLeaderHostAddress(ctx context.Context, rdb *redis.Client) string
⋮----
var err error
var leaderNodeId string
var leaderHostAddress string
⋮----
/*
 * Check the client with name "searchName" has an idle time less than "limit"
 */
func CheckClientIdle(ctx context.Context, rdb *redis.Client, searchName string, limit int) error
⋮----
var clientName string
var clientIdle int
var convError error
⋮----
func setClientNameCallback(ctx context.Context, cn *redis.Conn) error
</file>

<file path="core/api-server/response/response.go">
package response
⋮----
type LoginRequestJWT struct {
	Username string `json:"username" example:"edoardo" structs:"username"`
	Password string `json:"password" example:"Nethesis,1234" structs:"password"`
}
⋮----
type LoginResponseJWT struct {
	Code   int    `json:"code" example:"200" structs:"code"`
	Token  string `json:"token" example:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY3Rpb25zIjpbXSwiZXhwIjoxNjE5NTM0OTQ4LCJpZCI6ImVkb2FyZG8iLCJvcmlnX2lhdCI6MTYxODkzMDE0OCwicm9sZSI6IiJ9.bNRFa7MCQK-rTczOjLveXEWBqhjK-FWhnUPD3_ixcCI"  structs:"token"`
	Expire string `json:"expire" example:"2021-04-27T16:49:08+02:00" structs:"expire"`
}
⋮----
type StatusOK struct {
	Code    int    `json:"code" example:"200" structs:"code"`
	Message string `json:"message" example:"Success" structs:"message"`
	Data    any    `json:"data" structs:"data"`
}
⋮----
type StatusCreated struct {
	Code    int    `json:"code" example:"201" structs:"code"`
	Message string `json:"message" example:"Created" structs:"message"`
	Data    any    `json:"data" structs:"data"`
}
⋮----
type StatusBadRequest struct {
	Code    int    `json:"code" example:"400" structs:"code"`
	Message string `json:"message" example:"Bad request" structs:"message"`
	Data    any    `json:"data" structs:"data"`
}
⋮----
type StatusUnauthorized struct {
	Code    int    `json:"code" example:"401" structs:"code"`
	Message string `json:"message" example:"Unauthorized" structs:"message"`
	Data    any    `json:"data" structs:"data"`
}
⋮----
type StatusForbidden struct {
	Code    int    `json:"code" example:"403" structs:"code"`
	Message string `json:"message" example:"Forbidden" structs:"message"`
	Data    any    `json:"data" structs:"data"`
}
⋮----
type StatusNotFound struct {
	Code    int    `json:"code" example:"404" structs:"code"`
	Message string `json:"message" example:"Not found" structs:"message"`
	Data    any    `json:"data" structs:"data"`
}
⋮----
type StatusInternalServerError struct {
	Code    int    `json:"code" example:"500" structs:"code"`
	Message string `json:"message" example:"Internal server error" structs:"message"`
	Data    any    `json:"data" structs:"data"`
}
⋮----
type StatusServiceUnavailable struct {
	Code    int    `json:"code" example:"503" structs:"code"`
	Message string `json:"message" example:"Service unavailable" structs:"message"`
	Data    any    `json:"data" structs:"data"`
}
</file>

<file path="core/api-server/socket/action.go">
package socket
⋮----
import (
	"bufio"
	"encoding/json"
	"fmt"
	"os"
	"os/exec"
	"strconv"
	"strings"
	"sync"
	"syscall"
	jwt "github.com/appleboy/gin-jwt/v3"
	"github.com/gin-gonic/gin"
	"github.com/olahol/melody"
	"github.com/pkg/errors"
	"github.com/NethServer/ns8-core/core/api-server/middleware"
	"github.com/NethServer/ns8-core/core/api-server/models"
	"github.com/NethServer/ns8-core/core/api-server/utils"
)
⋮----
"bufio"
"encoding/json"
"fmt"
"os"
"os/exec"
"strconv"
"strings"
"sync"
"syscall"
⋮----
jwt "github.com/appleboy/gin-jwt/v3"
"github.com/gin-gonic/gin"
"github.com/olahol/melody"
"github.com/pkg/errors"
⋮----
"github.com/NethServer/ns8-core/core/api-server/middleware"
"github.com/NethServer/ns8-core/core/api-server/models"
"github.com/NethServer/ns8-core/core/api-server/utils"
⋮----
func Action(socketAction models.SocketAction, s *melody.Session, wg *sync.WaitGroup)
⋮----
var logsAction models.LogsStopAction
⋮----
var logsAction models.LogsStartAction
⋮----
var mode = ""
var from = ""
var to = ""
var timezone = "UTC"
⋮----
// read to EOF before Wait: the command output reaches the
// frontend whole, whether the stream ends well or badly
⋮----
// the pid matters only in the first logs-start
// message, where the frontend picks it up to stop
// the follow later on
⋮----
func writeLogsError(s *melody.Session, id string, message string)
⋮----
func refuseLogsStart(s *melody.Session, logsAction models.LogsStartAction, message string)
⋮----
const maxDumpLines = 2000
⋮----
func dumpLines(lines string) (int, error)
⋮----
func escapeLogqlString(s string) string
⋮----
func buildLogqlQuery(logsAction models.LogsStartAction) string
⋮----
var streamSelector string
⋮----
// a bad pattern is rejected by Loki, which compiles it anyway
⋮----
func reverse(ss []string) []string
</file>

<file path="core/api-server/socket/socket.go">
package socket
⋮----
import (
	"context"
	"encoding/json"
	"sync"
	"syscall"
	"time"
	"github.com/olahol/melody"
	"github.com/pkg/errors"
	"github.com/NethServer/ns8-core/core/api-server/models"
	"github.com/NethServer/ns8-core/core/api-server/redis"
	"github.com/NethServer/ns8-core/core/api-server/utils"
)
⋮----
"context"
"encoding/json"
"sync"
"syscall"
"time"
⋮----
"github.com/olahol/melody"
"github.com/pkg/errors"
⋮----
"github.com/NethServer/ns8-core/core/api-server/models"
"github.com/NethServer/ns8-core/core/api-server/redis"
"github.com/NethServer/ns8-core/core/api-server/utils"
⋮----
var socketConnection *melody.Melody
var muClock *utils.MuClock
⋮----
const maxSessionLogcli = 4
⋮----
var childsLock sync.Mutex
⋮----
func Instance() *melody.Melody
⋮----
func onPong(s *melody.Session)
⋮----
func onDisconnect(s *melody.Session)
⋮----
func acquireLogcli(s *melody.Session) bool
⋮----
func releaseLogcli(s *melody.Session)
⋮----
func addChild(s *melody.Session, pid int)
⋮----
func removeChild(s *melody.Session, pid int) bool
⋮----
func takeChilds(s *melody.Session) []int
⋮----
func onMessage(s *melody.Session, msg []byte)
⋮----
var socketAction models.SocketAction
⋮----
func validSessionFilter(s *melody.Session) bool
⋮----
func getSessionExpireTimestamp(s *melody.Session) int64
⋮----
func relayRedisProgressEvents(socketConnection *melody.Melody)
⋮----
func writeSocketResponse(s *melody.Session, name string, msg any)
</file>

<file path="core/api-server/utils/muclock.go">
package utils
⋮----
import (
	"sync"
	"time"
)
⋮----
"sync"
"time"
⋮----
type MuClock struct {
	mux     sync.Mutex
	curTime int64
}
⋮----
func (clk *MuClock) Sync()
⋮----
func (clk *MuClock) Now() int64
</file>

<file path="core/api-server/utils/utils.go">
package utils
⋮----
import (
	"os"
	"slices"
	"strconv"
	"time"
)
⋮----
"os"
"slices"
"strconv"
"time"
⋮----
func LogError(err error)
⋮----
func Contains(a string, values []string) bool
⋮----
func EpochToHumanDate(epochTime int) string
</file>

<file path="core/api-server/AGENTS.md">
# API Server

Gin-based REST API serving the admin UI. Provides JWT authentication, WebSocket
real-time updates, task management, and SQLite audit logging.

## Build

```bash
go build api-server.go       # build api-server binary
go build api-server-logs.go  # logs CLI tool
```

Built with `CGO_ENABLED=1` (required by `go-sqlite3`). The `build-image.sh`
script uses `-ldflags='-extldflags=-static'` for static linking and adds
`-tags sqlite_omit_load_extension`.

## Test

```bash
bash test-api-server.sh          # black-box Robot Framework suite (podman)
go test -tags sqlite_omit_load_extension \
  $(go list -f '{{if ne .Name "main"}}{{.ImportPath}}{{end}}' ./...)  # unit tests
```

`test-api-server.sh` builds the binary, starts a Redis server of the same
version shipped by core, and runs `test/suite/` in a Python container: the
suite prepares Redis like a leader node (ACL users from
`install-finalize.sh`, roles, 2FA and allowed networks), starts
`api-server` and checks it with HTTP and WebSocket clients, a fake agent
that pops tasks from the queues, and the Redis `MONITOR` command
(`test/suite/ApiServerLibrary.py`). Expected texts and status codes are
the API contract: clients like the UI match them. Change a test only when
the behavior change is intended. Arguments are passed to `robot`, e.g.
`bash test-api-server.sh --test 'Expired token'`.

## Module layout

| Path | Purpose |
|------|---------|
| `api-server.go` | Main entry — route definitions, middleware wiring |
| `api-server-logs.go` | Cobra CLI tool for sending WebSocket log actions |
| `methods/tasks.go` | Task CRUD: create, list, get output/status/context |
| `methods/auth.go` | Redis ACL auth, 2FA/OTP setup and validation |
| `methods/audit.go` | Audit log queries (filter by user, action, date range) |
| `middleware/` | JWT lifecycle: authenticator, authorizer, payload builder |
| `models/` | Data structs: Audit, Event, Task, UserAuthorizations, SocketAction |
| `utils/` | Error logging, string helpers, mutex-guarded clock for session expiry |
| `redis/` | Redis client factory (new client per call), leader host lookup, health checks |
| `audit/` | SQLite audit store (WAL mode, transactions) |
| `socket/` | Melody WebSocket — session management, Redis event relay |
| `response/` | Standardized HTTP response envelopes (StatusOK, StatusBadRequest, etc.) |
| `configuration/` | All config from environment variables (no config files) |

## Routing structure

```
POST /api/login                                        # no auth
POST /api/logout                                       # no auth
GET  /api/module/:module_id/http-basic/:action         # basic auth, for app integration
─── JWT middleware applied to /api routes below ───
GET  /api/cluster/tasks                                # list cluster tasks
GET  /api/cluster/task/:task_id/status                 # task status
GET  /api/cluster/task/:task_id/context                # task context
POST /api/cluster/tasks                                # create cluster task
GET  /api/nodes                                        # list nodes
GET  /api/node/:node_id/tasks                          # list node tasks
GET  /api/node/:node_id/task/:task_id/status           # node task status
GET  /api/node/:node_id/task/:task_id/context          # node task context
POST /api/node/:node_id/tasks                          # create node task
GET  /api/modules                                      # list modules
GET  /api/module/:module_id/tasks                      # list module tasks
GET  /api/module/:module_id/task/:task_id/status       # module task status
GET  /api/module/:module_id/task/:task_id/context      # module task context
POST /api/module/:module_id/tasks                      # create module task
GET  /api/audit                                        # audit log queries
GET  /api/audit/users                                  # audit log users
GET  /api/audit/actions                                # audit log actions
POST /api/2FA                                          # enable 2FA
GET  /api/2FA                                          # get 2FA status
DELETE /api/2FA                                        # disable 2FA
GET  /api/2FA/qr-code                                  # generate QR code

/ws                                                    # WebSocket (Melody); auth via "authorize" action with JWT payload
```

## Authentication

- **Primary**: Redis ACL credentials validated on login
- **JWT**: 14-day expiry; claims contain username, 2FA flag, and placeholder
  `role`/`actions` fields (always empty). Actual role and actions are fetched
  fresh from Redis on every request via `IdentityHandler`.
- **Authorization**: Action-based (not role-based) using `filepath.Match`
  wildcard patterns against the user's authorized actions list (from Redis).
  All GET requests bypass authorization checks.
- **2FA**: Optional TOTP via `github.com/dgryski/dgoogauth`; enforced at
  login. `/api/2FA` POST/DELETE endpoints are explicitly exempted in the
  authorizer.

## Configuration

All via environment variables: `LISTEN_ADDRESS`, `REDIS_ADDRESS`, `REDIS_USER`,
`REDIS_PASSWORD`, `SECRET` (JWT key), `STATIC_PATH`, `AUDIT_FILE`,
`SENSITIVE_LIST`, `ISSUER` (TOTP issuer name, default `NethServer`),
`GLOBAL_RATE_LIMIT_AVERAGE` (per-IP requests/sec across all routes, default
`25`; `0` disables), and `GLOBAL_RATE_LIMIT_BURST` (burst allowance, default
`300`).

The sustained average is what bounds a flood; the burst only sets how many
requests may arrive at once, and is sized for a legitimate UI page load. A burst
below `1` is clamped to `1` by `RateLimiter`; use `GLOBAL_RATE_LIMIT_AVERAGE=0`
to disable the limiter.

## Conventions

- Response envelopes use `structs.Map()` for struct-to-JSON conversion.
- Redis keys follow `task/<entity>/<id>/<task-id>/{context,output,error,exit_code}` (e.g. `task/node/<node-id>/<task-id>/output`).
- Audit events: `login-ok`, `auth-fail`, `create-task` stored in SQLite.
- WebSocket sessions are validated on each ping-pong (JWT expiry check).
- Tests: see the Test section above; end-to-end tests on a real cluster
  are in `core/tests/`.
</file>

<file path="core/api-server/api-server-logs.go">
package main
⋮----
import (
	"github.com/NethServer/ns8-core/core/api-server/models"
	"github.com/NethServer/ns8-core/core/api-server/socket"
	"fmt"
	"os"
	"sync"
	"github.com/google/uuid"
	"github.com/spf13/cobra"
)
⋮----
"github.com/NethServer/ns8-core/core/api-server/models"
"github.com/NethServer/ns8-core/core/api-server/socket"
⋮----
"fmt"
"os"
"sync"
⋮----
"github.com/google/uuid"
"github.com/spf13/cobra"
⋮----
var (
	modeFlag       = "tail"
	linesFlag      = "25"
	fromFlag       = ""
	toFlag         = ""
	entityFlag     = "cluster"
	entityNameFlag = ""
	searchFlag     = ""
	timezone       = ""
	instance       = ""
	regexpFlag     = false
)
⋮----
var RootCmd = &cobra.Command{
	Use:   "api-server-logs",
	Short: "api-server-logs is a wrapper of api-server websocket logs",
}
⋮----
var VersionCmd = &cobra.Command{
	Use:   "version",
	Short: "show api-server-logs version",
	Run: func(cmd *cobra.Command, args []string) {
		fmt.Println(RootCmd.Use + " " + "0.0.1")
	},
}
⋮----
var LogsCmd = &cobra.Command{
	Use:   "logs",
	Short: "get logs of a specific entity. default: cluster",
	Run: func(cmd *cobra.Command, args []string) {
		Logs()
	},
}
⋮----
func Execute()
⋮----
func Logs()
⋮----
var wg sync.WaitGroup
⋮----
func main()
</file>

<file path="core/api-server/api-server.go">
package main
⋮----
import (
	"io/ioutil"
	"net/http"
	"github.com/fatih/structs"
	"github.com/gin-contrib/cors"
	"github.com/gin-contrib/gzip"
	"github.com/gin-contrib/static"
	"github.com/gin-gonic/gin"
	"golang.org/x/time/rate"
	"github.com/NethServer/ns8-core/core/api-server/audit"
	"github.com/NethServer/ns8-core/core/api-server/configuration"
	"github.com/NethServer/ns8-core/core/api-server/methods"
	"github.com/NethServer/ns8-core/core/api-server/middleware"
	"github.com/NethServer/ns8-core/core/api-server/response"
	"github.com/NethServer/ns8-core/core/api-server/socket"
)
⋮----
"io/ioutil"
"net/http"
⋮----
"github.com/fatih/structs"
"github.com/gin-contrib/cors"
"github.com/gin-contrib/gzip"
"github.com/gin-contrib/static"
"github.com/gin-gonic/gin"
"golang.org/x/time/rate"
⋮----
"github.com/NethServer/ns8-core/core/api-server/audit"
"github.com/NethServer/ns8-core/core/api-server/configuration"
"github.com/NethServer/ns8-core/core/api-server/methods"
"github.com/NethServer/ns8-core/core/api-server/middleware"
"github.com/NethServer/ns8-core/core/api-server/response"
"github.com/NethServer/ns8-core/core/api-server/socket"
⋮----
func main()
⋮----
// handle missing endpoint
</file>

<file path="core/api-server/README.md">
# api-server

This component is used to send command from UI to Redis, using HTTP Rest API and Redis Pub/Sub protocol.

## Building

To build the binary just execute

```bash
# get dependencies
go get

# build binary
go build

# build docs
swag init
```

## Configuration

The configuration is read from ENV

```bash
LISTEN_ADDRESS=0.0.0.0:8080
REDIS_ADDRESS=127.0.0.1:6379
REDIS_USER=default
REDIS_PASSWORD=""
SECRET=MY_SECRET,11
GLOBAL_RATE_LIMIT_AVERAGE=25
GLOBAL_RATE_LIMIT_BURST=300
```

- `GLOBAL_RATE_LIMIT_AVERAGE`: max sustained requests per second per client
  IP across all API routes, default is `25`; set to `0` to disable rate
  limiting
- `GLOBAL_RATE_LIMIT_BURST`: burst allowance above the average before
  requests are rejected with HTTP 429, default is `300`

The sustained average is what bounds a flood; the burst only sets how many
requests may arrive at once, and is therefore sized for a legitimate
cluster-admin page load (~150 requests: static assets plus task round-trips).

A burst below `1` is raised to `1`, because a zero-capacity token bucket would
reject every request; use `GLOBAL_RATE_LIMIT_AVERAGE=0` to disable the limiter.

## Running

To execute the binary run

```bash
./api-server
```

You can also specify configurations using env vars

```bash
LISTEN_ADDRESS=0.0.0.0:8080 REDIS_ADDRESS=127.0.0.1:6379 REDIS_USER=my-user REDIS_PASSWORD=MyPass SECRET=MY_SECRET,11./api-server
```

## APIs

Each API is authenticated and authorized through a `JWT (JSON Web Token)`. In order to get access to the APIs you have to login before and get a JWT `token`. `SECRET` is used to set the JWT signature.

### Network access restrictions

The API server enforces source-IP restrictions at login and on every
authenticated request:

- **Agent credentials** (`cluster`, `node/*`, `module/*`): always
  restricted to `127.0.0.1`, `::1`, and the cluster VPN network (Redis
  key `cluster/network`). Login from any other IP returns HTTP 401;
  requests with an agent-issued JWT from outside those networks return
  HTTP 403. This is unconditional and cannot be overridden.

- **User accounts** (e.g. `admin`): an optional `allowed_networks` field
  can be set via `cluster/add-user` or `cluster/alter-user`. When
  non-empty, logins and JWT requests from non-matching IPs are rejected
  (401/403 respectively). An empty list means no IP restriction.

#### Login API list

-   `POST /login`

```bash
curl -s -H "Content-Type: application/json" -X POST http://localhost:8080/api/login --data '{"username": "<username>", "password": "<password>"}' | jq
```

```json
{
  "code": 200,
  "expire": "2021-04-21T14:05:35+02:00",
  "token":  "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY3Rpb25zIjpbImNyZWF0ZS11c2VycyIsImRlbGV0ZS11c2VycyJdLCJleHAiOjE2MTkwMDY3MzUsImlkIjoiZWRvYXJkbyIsIm9yaWdfaWF0IjoxNjE4NDAxOTM1LCJyb2xlIjoiYWRtaW4ifQ.ru8CbqduPTBI4G9R3zINC_-L38Thggg_9ExFV3Grf18"
}
```

Once you have the `token`, each request must include this `token` in the header.

```bash
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY3Rpb25zIjpbImNyZWF0ZS11c2VycyIsImRlbGV0ZS11c2VycyJdLCJleHAiOjE2MTg5MDc2NTIsImlkIjoiZWRvYXJkbyIsIm9yaWdfaWF0IjoxNjE4MzAyODUyLCJyb2xlIjoiYWRtaW4ifQ.dyqSFWi7L0aKAe7mujBJ9eN2nFnC9PcnFPhSQOZc2Nc"
```

The finally API request should be:

```bash
curl -s -H "Authorization: Bearer <your_token>" -X <VERB> http://localhost:8080/api/<api_name> --data '{<your_json_data}' | jq
```

### Basic authentication

There are some cases where it is necessary to validate requests coming from other servers (Caddy, Nginx, ...) using the HTTP Basic authentication method. To achieve this functionality some routes verify authentication using basic auth.

The api-server could check that the action passed from route is among the user (obtained from Basic-Auth credentials) role authorized actions.

#### Basic authentication API list

-   `GET /module/:module_id/http-basic/:action` Use Basic HTTP auth for module

    Where:
    - `:module_id`: is the name of the module to check for action
    - `:action`: is the action to validate in the authorized actions

### 2FA (Two-Factor authentication)

If you feel comfortable and more secure to use 2FA, you can enable it inside the user setting page o via API. To enable these are the steps:

-   Login and get a valid JWT token
-   Enable 2FA for a specific user
-   Scan auto-generated QR code and add the secret inside your Google Authenticator (or similar protocol app)
-   Copy the generated OTP from the app and call the API to verifiy the OTP
-   After the OTP verification the JWT token can be used to call APIs

#### 2FA API list

-   `GET /api/2FA` Read current 2FA status
    ```json
    RESPONSE
    {
      "code": 200,
      "data": true,
      "message": "2FA set for this user"
    }

    {
      "code": 200,
      "data": false,
      "message": "2FA not set for this user"
    }
    ```

-   `DELETE /api/2FA` Revoke 2FA secret
    ```json
    BODY
    {
      "code": 200,
      "data": "",
      "message": "2FA revocate successfully"
    }
    ```

-   `GET /api/2FA/qr-code` Get URL with Authenticator setup (can be used to generate a QR Code)
    ```json
    RESPONSE
    {
      "code": 200,
      "data": {
        "key": "OQPZYGNFP4E37NJUCBR7ELEONC7WSXZW",
        "url": "otpauth://totp/NethServer:admin2fa?algorithm=SHA1\u0026digits=6\u0026issuer=NethServer\u0026period=30\u0026secret=OQPZYGNFP4E37NJUCBR7ELEONC7WSXZW"
      },
      "message": "QR code string"
    }
    ```

- `POST /api/2FA` Used to validate the OTP
   ```json
   BODY
   {
     "otp": "157720",
     "secret": "4W5XXQDHH3ROJBUOHEKUEL6M44IYUOMO"
   }

   RESPONSE
   {
    "code": 200,
    "data": null,
    "message": "2FA set successfully"
  }
   ```

### API list

The API doc is generated using swagger. The `swagger.json` file is built
automatically and published at:

<https://raw.githubusercontent.com/NethServer/ns8-core/swagdoc/swagger.json>

## Redis

  Each API is mapped to a specific command on Redis:

-   `GET /api/<cluster|node|module>/tasks` ⟶ `LRANGE <cluster|node|module>/tasks 0 -1`

-   `POST /api/<cluster|node|module>/tasks` ⟶ `LPUSH <cluster|node|module>/tasks <payload>`

    `PAYLOAD` contains the task information:

    -   `id` ⟶ task id is an uuid string generated from server
    -   `action` ⟶ action to execute
    -   `data` ⟶ data used from action to execute the task

## Audit

Every request made to the server, using its APIs or WebSocket, is logged inside an audit db. The audit db is store in a file using a SQLite database schema. Each record is composed by:

-   `ID`: the unique id of the record, autoincrement
-   `User`: the name of the user that made the specific action
-   `Action`: the name of the action made by the user
-   `Data`: the payload of the action (if present). To avoid storing
    passwords in clear-text, any attribute in `Data` matching any of the
    substrings "password", "secret", "token" is forced to value "XXX".
-   `Timestamp`: the time when the specific action is executed

## Websockets

The API server provides a WebSocket connection under the `/ws` path. Through websocket it is possible to send commands and receive data asynchronously via the socket channel.

### Commands

At the moment the supported commands are:

-   `logs-start`: used to get the logs for a specific entity (cluster, node or module). Use loki cli (`logcli`) to search and retrieve logs
-   `logs-stop`: used to stop the logs you are following (normally used in tail mode)

To execute commands via websocket, you need to send a payload to the websocket and listen to the results.

#### logs-start

```json
INPUT
{
   "action": "logs-start",
   "payload": {
      "id": "2fd5b630-3d27-4b88-ac11-ad2d09f4bbd7",
      "mode": "dump",
      "lines": "25",
      "filter": "",
      "from": "2021-01-19T10:00:00Z",
      "to": "2021-01-19T20:00:00Z",
      "entity" :"module",
      "entity_name": "traefik1",
      "timezone": "Europe/Rome",
      "instance": "loki1",
      "regexp": false
   }
}
```

-   `action`: fixed to `logs-start`
-   `payload`: payload of the action
    -   `id`: used to track multiple stream output (used in UI to get different logs stream in different panes)
    -   `mode`: must be `tail` or `dump` - `string` (choose how to retrieve logs)
    -   `lines`: could be empty or a number - `string` (could be empty in `tail` mode)
    -   `filter`: could be empty or string - `string` (used to search specific words inside logs)
    -   `from`: could be empty or iso8601 date string - `string` (used to search specific logs in a date range)
    -   `to`: could be empty or iso8601 date string - `string` (used to search specific logs in a date range)
    -   `entity`: must be `cluster` or `node` or `module` - `string`
    -   `entity_name`: could be empty (`cluster` case) or name of the entity - `string` (ex. hostname of the node or module id like `traefik1`)
    -   `timezone`: could be empty (default UTC) or a specific valid timezone (eg. Europe/Rome)
    -   `instance`: could be empty (default loki instance) or the id of a specific loki instance - `string` (ex. `loki1`)
    -   `regexp`: could be empty (default `false`) - `bool` (when `true` the `filter` is a RE2 regular expression instead of a substring)

```json
OUTPUT
{
   "name": "logs-start",
   "payload": {
      "message": "2022-02-17T20:47:24+01:00 fedora33.n2.edoardo --\u003e [GIN-debug] Listening and serving HTTP on 127.0.0.1:8080",
      "pid": "14431"
   },
   "timestamp":"2022-03-01T09:01:41.698943069Z",
   "type":"action"
}
```

-   `name`: is the name of the action
-   `payload`: contains the response logs
    -   `message`: contains the log message
    -   `pid`: is the pid of the process that actually reads log
    -   a failed query has no attribute of its own: the `logcli` error text is sent as `message`, and in `tail` mode a `logs-stop` follows it
-   `timestamp`: timestamp of the action
-   `type`: used to identify the websocket outputs

#### logs-stop

```json
INPUT
{
   "action": "logs-stop",
   "payload": {
      "id": "2fd5b630-3d27-4b88-ac11-ad2d09f4bbd7",
      "pid": "14088"
   }
}
```

-   `action`: fixed to `logs-start`
-   `payload`: payload of the action
-   `pid`: contains the pid of the process that reads log

```json
OUTPUT
{
   "name": "logs-stop",
   "payload": {
      "id": "2fd5b630-3d27-4b88-ac11-ad2d09f4bbd7",
      "pid": "14431",
      "message": "logs follow stopped"
   },
   "timestamp":"2022-03-01T09:01:41.698943069Z",
   "type":"action"
}
```

-   `name`: is the name of the action
-   `payload`: contains the response logs
    -   `id`: id of the trackes log stream
    -   `pid`: is the pid of the process that actually reads log
-   `timestamp`: timestamp of the action
-   `type`: used to identify the websocket outputs

### Task events

The websocket also listens for every event of every task launched within the cluster and reports the payload through the socket channel.

# api-server-logs

This component is a wrapper of api-server websocket logs

## Usage

```bash
# ./api-server-logs

api-server-logs is a wrapper of api-server websocket logs

Usage:
  api-server-logs [command]

Available Commands:
  completion  Generate the autocompletion script for the specified shell
  help        Help about any command
  logs        get logs of a specific entity. default: cluster
  version     show api-server-logs version

Flags:
  -h, --help   help for api-server-logs

Use "api-server-logs [command] --help" for more information about a command.
```

### Commands

-   `completion`:

    ```bash
    Generate the autocompletion script for api-server-logs for the specified shell.
    See each sub-command's help for details on how to use the generated script.

    Usage:
      api-server-logs completion [command]

    Available Commands:
      bash        Generate the autocompletion script for bash
      fish        Generate the autocompletion script for fish
      powershell  Generate the autocompletion script for powershell
      zsh         Generate the autocompletion script for zsh

    Flags:
      -h, --help   help for completion
    ```

-   `help`: prints the Usage output
-   `logs`: the command to retrieve logs in dump or follow mode

    ```bash
    get logs of a specific entity. default: cluster

    Usage:
      api-server-logs logs [flags]

    Flags:
      -e, --entity string     get logs for a specific entity: cluster, node, module (default "cluster")
      -f, --from string       get logs from a specific date. ISO8601 format
      -h, --help              help for logs
      -i, --instance string   search for logs in a specific instance. (Example: loki1, loki2, ...)
      -l, --lines string      get logs for a specific lines in dump mode (default "25")
      -m, --mode string       get logs in a specific mode: tail or dump (default "tail")
      -n, --name string       get logs for a specific entity name. used in node or module
      -r, --regexp            treat the search string as a regular expression instead of a substring
      -s, --search string     get logs for a specific search string
      -z, --timezone string   get logs in a specific timezone
      -t, --to string         get logs to a specific date. ISO8601 format
    ```

-   `version`: prints the command version
    ```bash
    api-server-logs 0.0.1
    ```
</file>

<file path="core/ui/src/components/applications-center/AddNoteModal.vue">
<template>
  <NsModal
    :visible="visible"
    :isLoading="loading.saveNote"
    @primary-click="saveNote"
    @modal-hidden="onModalHidden"
    size="default"
  >
    <template slot="title">{{
      isEdit ? $t("applications.edit_note") : $t("applications.add_note")
    }}</template>
    <template slot="content">
      <div class="mg-bottom-md">{{ $t("applications.note_description") }}</div>
      <div class="flex flex-col">
        <div class="flex items-center justify-between">
          <div class="bx--label no-mg-bottom">
            {{ $t("applications.note") }}
          </div>
          <div class="bx--label no-mg-bottom text-right">
            {{ note.length }}/100
          </div>
        </div>
        <cv-text-area
          v-model="note"
          :placeholder="$t('applications.enter_note')"
          :maxLength="100"
          :rows="4"
          :disabled="loading.saveNote"
          :invalid-message="invalidNoteLength"
          :helper-text="$t('applications.note_helper_text')"
          data-modal-primary-focus
        />
        <cv-inline-notification
          v-if="error.saveNote"
          kind="error"
          :title="$t('action.set-note')"
          :description="error"
          :showCloseButton="false"
        />
      </div>
    </template>
    <template slot="secondary-button">{{ $t("common.cancel") }}</template>
    <template slot="primary-button">{{
      isEdit ? $t("common.save") : $t("applications.add_note")
    }}</template>
  </NsModal>
</template>
⋮----
<template slot="title">{{
      isEdit ? $t("applications.edit_note") : $t("applications.add_note")
    }}</template>
<template slot="content">
      <div class="mg-bottom-md">{{ $t("applications.note_description") }}</div>
      <div class="flex flex-col">
        <div class="flex items-center justify-between">
          <div class="bx--label no-mg-bottom">
            {{ $t("applications.note") }}
          </div>
          <div class="bx--label no-mg-bottom text-right">
            {{ note.length }}/100
          </div>
        </div>
        <cv-text-area
          v-model="note"
          :placeholder="$t('applications.enter_note')"
          :maxLength="100"
          :rows="4"
          :disabled="loading.saveNote"
          :invalid-message="invalidNoteLength"
          :helper-text="$t('applications.note_helper_text')"
          data-modal-primary-focus
        />
        <cv-inline-notification
          v-if="error.saveNote"
          kind="error"
          :title="$t('action.set-note')"
          :description="error"
          :showCloseButton="false"
        />
      </div>
    </template>
⋮----
<div class="mg-bottom-md">{{ $t("applications.note_description") }}</div>
⋮----
{{ $t("applications.note") }}
⋮----
{{ note.length }}/100
⋮----
<template slot="secondary-button">{{ $t("common.cancel") }}</template>
<template slot="primary-button">{{
      isEdit ? $t("common.save") : $t("applications.add_note")
    }}</template>
⋮----
<script>
import { UtilService, TaskService, IconService } from "@nethserver/ns8-ui-lib";
import to from "await-to-js";
export default {
  name: "saveNoteModal",
  mixins: [UtilService, TaskService, IconService],
  props: {
    visible: {
      type: Boolean,
      required: true,
    },
    isEdit: {
      type: Boolean,
      default: false,
    },
    currentNote: {
      type: String,
      default: "",
    },
    noteInstance: Object,
  },
  data() {
    return {
      note: this.currentNote,
      error: { saveNote: "" },
      loading: { saveNote: false },
    };
  },
  watch: {
    currentNote(newVal) {
      this.note = newVal;
    },
    visible(newVal) {
      if (newVal) {
        this.note = this.currentNote;
      }
    },
  },
  computed: {
    invalidNoteLength() {
      if (this.note.length == 100) {
        return this.$t("applications.note_too_long");
      }
      return "";
    },
  },
  methods: {
    onModalHidden() {
      this.clearErrors();
      this.$emit("hide");
    },
    async saveNote() {
      this.error.saveNote = "";
      this.loading.saveNote = true;
      const taskAction = "set-note";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.saveNoteCompleted
      );
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.saveNoteAborted
      );
      const res = await to(
        this.createModuleTaskForApp(this.noteInstance.id, {
          action: taskAction,
          data: {
            note: this.note,
          },
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.saveNote = this.getErrorMessage(err);
        this.loading.saveNote = false;
        return;
      }
      this.$emit("hide");
    },
    saveNoteAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.saveNote = this.$t("error.generic_error");
      this.loading.saveNote = false;
    },
    saveNoteCompleted() {
      this.loading.saveNote = false;
      this.$emit("hide");
      this.$emit("saveNoteCompleted");
    },
  },
};
</script>
<style scoped lang="scss">
@import "../../styles/carbon-utils";
</style>
</file>

<file path="core/ui/src/components/backup/AddRepositoryModal.vue">
<template>
  <NsWizard
    size="default"
    :visible="isShown"
    :cancelLabel="$t('common.cancel')"
    :previousLabel="$t('common.previous')"
    :nextLabel="isLastStep ? $t('backup.add_repository') : $t('common.next')"
    :isPreviousDisabled="isFirstStep || loading.addBackupRepository"
    :isNextDisabled="isNextButtonDisabled"
    :isNextLoading="loading.addBackupRepository"
    @modal-hidden="$emit('hide')"
    @cancel="$emit('hide')"
    @previousStep="previousStep"
    @nextStep="nextStep"
    :isLastStep="isLastStep"
  >
    <template slot="title">{{ $t("backup.add_repository") }}</template>
    <template slot="content">
      <cv-form>
        <NsInlineNotification
          v-if="error.getClusterStatus"
          kind="error"
          :title="$t('action.get-cluster-status')"
          :description="error.getClusterStatus"
          :showCloseButton="false"
        />
        <NsInlineNotification
          v-if="error.listBackupEndpoints"
          kind="error"
          :title="$t('action.list-cluster-backup-endpoints')"
          :description="error.listBackupEndpoints"
          :showCloseButton="false"
        />
        <template v-if="step == 'provider'">
          <div class="mg-bottom-md">
            {{ $t("backup.select_backup_provider") }}
          </div>
          <cv-grid>
            <cv-row>
              <cv-column :md="4">
                <NsTile
                  :light="true"
                  kind="selectable"
                  v-model="isClusterSelected"
                  value="providerValue"
                  @click="selectCluster()"
                  class="provider-card"
                >
                  <div class="provider-card-content">
                    <div class="provider-icon">
                      <img
                        :src="require('@/assets/node_storage.png')"
                        alt="cluster logo"
                      />
                    </div>
                    <h6>
                      {{ $t("backup.cluster") }}
                    </h6>
                  </div>
                </NsTile>
              </cv-column>
              <cv-column :md="4">
                <NsTile
                  :light="true"
                  kind="selectable"
                  v-model="isSambaSelected"
                  value="providerValue"
                  @click="selectSamba()"
                  class="provider-card"
                >
                  <div class="provider-card-content">
                    <div class="provider-icon">
                      <img
                        :src="require('@/assets/samba.png')"
                        alt="samba logo"
                      />
                    </div>
                    <h6>
                      {{ $t("backup.samba") }}
                    </h6>
                  </div>
                </NsTile>
              </cv-column>
              <cv-column :md="4">
                <NsTile
                  :light="true"
                  kind="selectable"
                  v-model="isAmazonS3Selected"
                  value="providerValue"
                  @click="selectAmazonS3()"
                  class="provider-card"
                >
                  <div class="provider-card-content">
                    <div class="provider-icon">
                      <img
                        :src="require('@/assets/aws.png')"
                        alt="amazon s3 logo"
                      />
                    </div>
                    <h6>
                      {{ $t("backup.aws") }}
                    </h6>
                  </div>
                </NsTile>
              </cv-column>
              <cv-column :md="4">
                <NsTile
                  :light="true"
                  kind="selectable"
                  v-model="isBackblazeSelected"
                  value="providerValue"
                  @click="selectBackblaze()"
                  class="provider-card"
                >
                  <div class="provider-card-content">
                    <div class="provider-icon">
                      <img
                        :src="require('@/assets/backblaze.png')"
                        alt="backblaze logo"
                      />
                    </div>
                    <h6>
                      {{ $t("backup.backblaze") }}
                    </h6>
                  </div>
                </NsTile>
              </cv-column>
              <cv-column :md="4">
                <NsTile
                  :light="true"
                  kind="selectable"
                  v-model="isGenericS3Selected"
                  value="providerValue"
                  @click="selectGenericS3()"
                  class="provider-card"
                >
                  <div class="provider-card-content">
                    <div class="provider-icon">
                      <img
                        :src="require('@/assets/s3-generic.png')"
                        alt="generic s3 logo"
                      />
                    </div>
                    <h6>
                      {{ $t("backup.generic-s3") }}
                    </h6>
                  </div>
                </NsTile>
              </cv-column>
              <cv-column :md="4">
                <NsTile
                  :light="true"
                  kind="selectable"
                  v-model="isRcloneSelected"
                  value="providerValue"
                  @click="selectRclone()"
                  class="provider-card"
                >
                  <div class="provider-card-content">
                    <div class="provider-icon">
                      <img
                        :src="require('@/assets/rclone.png')"
                        alt="rclone logo"
                      />
                    </div>
                    <h6>
                      {{ $t("backup.rclone") }}
                    </h6>
                  </div>
                </NsTile>
              </cv-column>
            </cv-row>
          </cv-grid>
        </template>
        <template v-if="step == 'nodes'">
          <div class="mg-bottom-sm">{{ $t("backup.select_cluster_node") }}</div>
          <NodeSelector
            class="mg-top-xlg"
            @selectNode="onSelectNode"
            :disabledNodes="disabledNodes"
            :loading="loading.getClusterStatus"
          >
            <template v-for="(nodeMessages, nodeId) in nodesInfo">
              <template :slot="`node-${nodeId}`">
                <div
                  v-for="(nodeMessage, index) in nodeMessages"
                  :key="index"
                  class="node-message"
                >
                  {{ nodeMessage }}
                </div>
              </template>
            </template>
          </NodeSelector>
        </template>
        <template v-if="step == 'settings'">
          <NsInlineNotification
            v-if="error.repoConnection"
            kind="error"
            :title="$t('backup.backup_repository_connection_error')"
            :description="$t('backup.' + error.repoConnection)"
            :showCloseButton="false"
          />
          <template v-if="isBackblazeSelected">
            <cv-text-input
              :label="$t('backup.backblaze_url_label')"
              v-model.trim="url"
              :invalid-message="error.url"
              :disabled="loading.addBackupRepository"
              ref="url"
            >
            </cv-text-input>
            <cv-text-input
              :label="$t('backup.b2_account_id')"
              v-model.trim="backblaze.b2_account_id"
              :invalid-message="error.backblaze.b2_account_id"
              :disabled="loading.addBackupRepository"
              autocomplete="off"
              ref="b2_account_id"
            >
            </cv-text-input>
            <cv-text-input
              :label="$t('backup.b2_account_key')"
              type="password"
              v-model.trim="backblaze.b2_account_key"
              :disabled="loading.addBackupRepository"
              :invalid-message="error.backblaze.b2_account_key"
              :password-hide-label="$t('password.hide_password')"
              :password-show-label="$t('password.show_password')"
              autocomplete="new-password"
              ref="b2_account_key"
            ></cv-text-input>
          </template>
          <template v-if="isAmazonS3Selected">
            <cv-text-input
              :label="$t('backup.aws_url_label')"
              v-model.trim="url"
              :invalid-message="error.url"
              :disabled="loading.addBackupRepository"
              ref="url"
            >
            </cv-text-input>
            <cv-text-input
              :label="$t('backup.aws_default_region')"
              v-model.trim="aws.aws_default_region"
              :invalid-message="error.aws.aws_default_region"
              :disabled="loading.addBackupRepository"
              ref="aws_default_region"
            >
            </cv-text-input>
            <cv-text-input
              :label="$t('backup.aws_access_key_id')"
              v-model.trim="aws.aws_access_key_id"
              :invalid-message="error.aws.aws_access_key_id"
              :disabled="loading.addBackupRepository"
              autocomplete="off"
              ref="aws_access_key_id"
            >
            </cv-text-input>
            <cv-text-input
              :label="$t('backup.aws_secret_access_key')"
              type="password"
              v-model.trim="aws.aws_secret_access_key"
              :disabled="loading.addBackupRepository"
              :invalid-message="error.aws.aws_secret_access_key"
              :password-hide-label="$t('password.hide_password')"
              :password-show-label="$t('password.show_password')"
              autocomplete="new-password"
              ref="aws_secret_access_key"
            ></cv-text-input>
          </template>
          <template v-if="isRcloneSelected">
            <div>
              <label class="bx--label">{{
                $t("backup.rclone_configuration_source")
              }}</label>
              <cv-radio-group
                :vertical="true"
                :disabled="loading.addBackupRepository"
              >
                <cv-radio-button
                  ref="paste_configuration"
                  :label="
                    $t('backup.rclone_configuration_source_paste_configuration')
                  "
                  value="paste"
                  v-model="rclone.configuration_source"
                />
                <cv-radio-button
                  ref="upload_configuration"
                  :label="
                    $t(
                      'backup.rclone_configuration_source_upload_configuration'
                    )
                  "
                  value="upload"
                  v-model="rclone.configuration_source"
                />
              </cv-radio-group>
            </div>
            <template v-if="rclone.configuration_source == 'paste'">
              <cv-text-area
                class="mg-top-md"
                :label="$t('backup.rclone_configuration_content')"
                v-model.trim="rclone.rclone_conf_secret"
                :invalid-message="error.rclone.rclone_conf_secret"
                :helper-text="
                  $t(
                    'backup.rclone_configuration_content_single_destination_helper_text'
                  )
                "
                :value="rclone.rclone_conf_secret"
                rows="5"
                ref="rclone_conf_secret"
                :disabled="loading.addBackupRepository"
              >
              </cv-text-area>
            </template>
            <template v-else>
              <div
                :class="{
                  'file-uploader-error': error.rclone.configuration_file,
                }"
              >
                <cv-file-uploader
                  :key="componentKey"
                  :label="$t('backup.rclone_configuration_file')"
                  :helper-text="$t('backup.rclone_configuration_file_helper')"
                  :multiple="false"
                  :removable="true"
                  :clear-on-reselect="true"
                  :drop-target-label="
                    $t('common.drag_and_drop_or_click_to_upload')
                  "
                  v-model="rclone.configuration_uploaded_file"
                  accept=".conf,.txt"
                  ref="backup_file"
                ></cv-file-uploader>
                <div
                  v-if="error.rclone.configuration_file"
                  class="validation-failed-invalid-message"
                >
                  {{ error.rclone.configuration_file }}
                </div>
              </div>
            </template>
            <cv-text-input
              :label="
                $t('backup.rclone_base_path') +
                ' (' +
                $t('common.optional') +
                ')'
              "
              v-model.trim="rclone.base_path"
              :invalid-message="error.rclone.base_path"
              :disabled="loading.addBackupRepository"
              ref="rclone_base_path"
            >
            </cv-text-input>
          </template>
          <template v-if="isGenericS3Selected">
            <NsTextInput
              :label="$t('backup.genericS3_url_label')"
              v-model.trim="url"
              :invalid-message="error.url"
              :placeholder="$t('backup.genericS3_placeholder')"
              :disabled="loading.addBackupRepository"
              ref="url"
            >
              <template slot="tooltip">
                <span>{{ $t("backup.genericS3_url_tooltip") }}</span>
              </template>
            </NsTextInput>
            <cv-text-input
              :label="$t('backup.genericS3_access_key_id')"
              v-model.trim="genericS3.aws_access_key_id"
              :invalid-message="error.genericS3.aws_access_key_id"
              :disabled="loading.addBackupRepository"
              autocomplete="off"
              ref="genericS3_access_key_id"
            >
            </cv-text-input>
            <cv-text-input
              :label="$t('backup.genericS3_secret_access_key')"
              type="password"
              v-model.trim="genericS3.aws_secret_access_key"
              :disabled="loading.addBackupRepository"
              :invalid-message="error.genericS3.aws_secret_access_key"
              :password-hide-label="$t('password.hide_password')"
              :password-show-label="$t('password.show_password')"
              autocomplete="new-password"
              ref="genericS3_secret_access_key"
            ></cv-text-input>
          </template>
          <template v-if="isSambaSelected">
            <NsInlineNotification
              kind="info"
              :title="$t('backup.smb_protocol_warning_title')"
              :description="$t('backup.smb_protocol_warning_description')"
              :showCloseButton="false"
            />
            <cv-text-input
              :label="$t('backup.smb_host')"
              v-model.trim="smb.smb_host"
              :invalid-message="error.smb.smb_host"
              :disabled="loading.addBackupRepository"
              ref="smb_host"
            >
            </cv-text-input>
            <NsTextInput
              :label="$t('backup.smb_url_label')"
              v-model.trim="url"
              :invalid-message="error.url"
              :disabled="loading.addBackupRepository"
              :placeholder="$t('backup.smb_url_placeholder')"
              ref="url"
            >
              <template slot="tooltip">
                <span>{{ $t("backup.smb_url_tooltip") }}</span>
              </template>
            </NsTextInput>
            <cv-text-input
              :label="$t('backup.smb_domain')"
              v-model.trim="smb.smb_domain"
              :invalid-message="error.smb.smb_domain"
              :disabled="loading.addBackupRepository"
              ref="smb_domain"
            >
            </cv-text-input>
            <cv-text-input
              :label="$t('backup.smb_user')"
              v-model.trim="smb.smb_user"
              :invalid-message="error.smb.smb_user"
              :disabled="loading.addBackupRepository"
              autocomplete="off"
              ref="smb_user"
            >
            </cv-text-input>
            <cv-text-input
              :label="$t('backup.smb_pass')"
              type="password"
              v-model.trim="smb.smb_pass"
              :disabled="loading.addBackupRepository"
              :invalid-message="error.smb.smb_pass"
              :password-hide-label="$t('password.hide_password')"
              :password-show-label="$t('password.show_password')"
              autocomplete="new-password"
              ref="smb_pass"
            ></cv-text-input>
          </template>
          <cv-text-input
            :label="$t('backup.repository_name')"
            v-model.trim="name"
            :helper-text="$t('backup.repository_name_helper')"
            :invalid-message="error.name"
            :disabled="loading.addBackupRepository"
            ref="name"
          >
          </cv-text-input>
          <cv-accordion ref="accordion">
            <cv-accordion-item :open="toggleAccordion[0]">
              <template slot="title">{{ $t("common.advanced") }}</template>
              <template slot="content">
                <NsTextInput
                  :label="
                    $t('backup.data_encryption_key') +
                    ' (' +
                    $t('common.optional') +
                    ')'
                  "
                  v-model="password"
                  :helper-text="$t('backup.repository_password_helper')"
                  :placeholder="
                    $t('common.eg_value', { value: 'a76917c4522...' })
                  "
                  :invalid-message="error.password"
                  :disabled="loading.addBackupRepository"
                  autocomplete="new-password"
                  ref="password"
                >
                  <template slot="tooltip">
                    {{ $t("backup.data_encryption_key_tooltip") }}
                  </template>
                </NsTextInput>
              </template>
            </cv-accordion-item>
          </cv-accordion>
          <NsInlineNotification
            v-if="error.addBackupRepository"
            kind="error"
            :title="$t('action.add-backup-repository')"
            :description="error.addBackupRepository"
            :showCloseButton="false"
          />
        </template>
      </cv-form>
    </template>
  </NsWizard>
</template>
⋮----
<template slot="title">{{ $t("backup.add_repository") }}</template>
<template slot="content">
      <cv-form>
        <NsInlineNotification
          v-if="error.getClusterStatus"
          kind="error"
          :title="$t('action.get-cluster-status')"
          :description="error.getClusterStatus"
          :showCloseButton="false"
        />
        <NsInlineNotification
          v-if="error.listBackupEndpoints"
          kind="error"
          :title="$t('action.list-cluster-backup-endpoints')"
          :description="error.listBackupEndpoints"
          :showCloseButton="false"
        />
        <template v-if="step == 'provider'">
          <div class="mg-bottom-md">
            {{ $t("backup.select_backup_provider") }}
          </div>
          <cv-grid>
            <cv-row>
              <cv-column :md="4">
                <NsTile
                  :light="true"
                  kind="selectable"
                  v-model="isClusterSelected"
                  value="providerValue"
                  @click="selectCluster()"
                  class="provider-card"
                >
                  <div class="provider-card-content">
                    <div class="provider-icon">
                      <img
                        :src="require('@/assets/node_storage.png')"
                        alt="cluster logo"
                      />
                    </div>
                    <h6>
                      {{ $t("backup.cluster") }}
                    </h6>
                  </div>
                </NsTile>
              </cv-column>
              <cv-column :md="4">
                <NsTile
                  :light="true"
                  kind="selectable"
                  v-model="isSambaSelected"
                  value="providerValue"
                  @click="selectSamba()"
                  class="provider-card"
                >
                  <div class="provider-card-content">
                    <div class="provider-icon">
                      <img
                        :src="require('@/assets/samba.png')"
                        alt="samba logo"
                      />
                    </div>
                    <h6>
                      {{ $t("backup.samba") }}
                    </h6>
                  </div>
                </NsTile>
              </cv-column>
              <cv-column :md="4">
                <NsTile
                  :light="true"
                  kind="selectable"
                  v-model="isAmazonS3Selected"
                  value="providerValue"
                  @click="selectAmazonS3()"
                  class="provider-card"
                >
                  <div class="provider-card-content">
                    <div class="provider-icon">
                      <img
                        :src="require('@/assets/aws.png')"
                        alt="amazon s3 logo"
                      />
                    </div>
                    <h6>
                      {{ $t("backup.aws") }}
                    </h6>
                  </div>
                </NsTile>
              </cv-column>
              <cv-column :md="4">
                <NsTile
                  :light="true"
                  kind="selectable"
                  v-model="isBackblazeSelected"
                  value="providerValue"
                  @click="selectBackblaze()"
                  class="provider-card"
                >
                  <div class="provider-card-content">
                    <div class="provider-icon">
                      <img
                        :src="require('@/assets/backblaze.png')"
                        alt="backblaze logo"
                      />
                    </div>
                    <h6>
                      {{ $t("backup.backblaze") }}
                    </h6>
                  </div>
                </NsTile>
              </cv-column>
              <cv-column :md="4">
                <NsTile
                  :light="true"
                  kind="selectable"
                  v-model="isGenericS3Selected"
                  value="providerValue"
                  @click="selectGenericS3()"
                  class="provider-card"
                >
                  <div class="provider-card-content">
                    <div class="provider-icon">
                      <img
                        :src="require('@/assets/s3-generic.png')"
                        alt="generic s3 logo"
                      />
                    </div>
                    <h6>
                      {{ $t("backup.generic-s3") }}
                    </h6>
                  </div>
                </NsTile>
              </cv-column>
              <cv-column :md="4">
                <NsTile
                  :light="true"
                  kind="selectable"
                  v-model="isRcloneSelected"
                  value="providerValue"
                  @click="selectRclone()"
                  class="provider-card"
                >
                  <div class="provider-card-content">
                    <div class="provider-icon">
                      <img
                        :src="require('@/assets/rclone.png')"
                        alt="rclone logo"
                      />
                    </div>
                    <h6>
                      {{ $t("backup.rclone") }}
                    </h6>
                  </div>
                </NsTile>
              </cv-column>
            </cv-row>
          </cv-grid>
        </template>
        <template v-if="step == 'nodes'">
          <div class="mg-bottom-sm">{{ $t("backup.select_cluster_node") }}</div>
          <NodeSelector
            class="mg-top-xlg"
            @selectNode="onSelectNode"
            :disabledNodes="disabledNodes"
            :loading="loading.getClusterStatus"
          >
            <template v-for="(nodeMessages, nodeId) in nodesInfo">
              <template :slot="`node-${nodeId}`">
                <div
                  v-for="(nodeMessage, index) in nodeMessages"
                  :key="index"
                  class="node-message"
                >
                  {{ nodeMessage }}
                </div>
              </template>
            </template>
          </NodeSelector>
        </template>
        <template v-if="step == 'settings'">
          <NsInlineNotification
            v-if="error.repoConnection"
            kind="error"
            :title="$t('backup.backup_repository_connection_error')"
            :description="$t('backup.' + error.repoConnection)"
            :showCloseButton="false"
          />
          <template v-if="isBackblazeSelected">
            <cv-text-input
              :label="$t('backup.backblaze_url_label')"
              v-model.trim="url"
              :invalid-message="error.url"
              :disabled="loading.addBackupRepository"
              ref="url"
            >
            </cv-text-input>
            <cv-text-input
              :label="$t('backup.b2_account_id')"
              v-model.trim="backblaze.b2_account_id"
              :invalid-message="error.backblaze.b2_account_id"
              :disabled="loading.addBackupRepository"
              autocomplete="off"
              ref="b2_account_id"
            >
            </cv-text-input>
            <cv-text-input
              :label="$t('backup.b2_account_key')"
              type="password"
              v-model.trim="backblaze.b2_account_key"
              :disabled="loading.addBackupRepository"
              :invalid-message="error.backblaze.b2_account_key"
              :password-hide-label="$t('password.hide_password')"
              :password-show-label="$t('password.show_password')"
              autocomplete="new-password"
              ref="b2_account_key"
            ></cv-text-input>
          </template>
          <template v-if="isAmazonS3Selected">
            <cv-text-input
              :label="$t('backup.aws_url_label')"
              v-model.trim="url"
              :invalid-message="error.url"
              :disabled="loading.addBackupRepository"
              ref="url"
            >
            </cv-text-input>
            <cv-text-input
              :label="$t('backup.aws_default_region')"
              v-model.trim="aws.aws_default_region"
              :invalid-message="error.aws.aws_default_region"
              :disabled="loading.addBackupRepository"
              ref="aws_default_region"
            >
            </cv-text-input>
            <cv-text-input
              :label="$t('backup.aws_access_key_id')"
              v-model.trim="aws.aws_access_key_id"
              :invalid-message="error.aws.aws_access_key_id"
              :disabled="loading.addBackupRepository"
              autocomplete="off"
              ref="aws_access_key_id"
            >
            </cv-text-input>
            <cv-text-input
              :label="$t('backup.aws_secret_access_key')"
              type="password"
              v-model.trim="aws.aws_secret_access_key"
              :disabled="loading.addBackupRepository"
              :invalid-message="error.aws.aws_secret_access_key"
              :password-hide-label="$t('password.hide_password')"
              :password-show-label="$t('password.show_password')"
              autocomplete="new-password"
              ref="aws_secret_access_key"
            ></cv-text-input>
          </template>
          <template v-if="isRcloneSelected">
            <div>
              <label class="bx--label">{{
                $t("backup.rclone_configuration_source")
              }}</label>
              <cv-radio-group
                :vertical="true"
                :disabled="loading.addBackupRepository"
              >
                <cv-radio-button
                  ref="paste_configuration"
                  :label="
                    $t('backup.rclone_configuration_source_paste_configuration')
                  "
                  value="paste"
                  v-model="rclone.configuration_source"
                />
                <cv-radio-button
                  ref="upload_configuration"
                  :label="
                    $t(
                      'backup.rclone_configuration_source_upload_configuration'
                    )
                  "
                  value="upload"
                  v-model="rclone.configuration_source"
                />
              </cv-radio-group>
            </div>
            <template v-if="rclone.configuration_source == 'paste'">
              <cv-text-area
                class="mg-top-md"
                :label="$t('backup.rclone_configuration_content')"
                v-model.trim="rclone.rclone_conf_secret"
                :invalid-message="error.rclone.rclone_conf_secret"
                :helper-text="
                  $t(
                    'backup.rclone_configuration_content_single_destination_helper_text'
                  )
                "
                :value="rclone.rclone_conf_secret"
                rows="5"
                ref="rclone_conf_secret"
                :disabled="loading.addBackupRepository"
              >
              </cv-text-area>
            </template>
            <template v-else>
              <div
                :class="{
                  'file-uploader-error': error.rclone.configuration_file,
                }"
              >
                <cv-file-uploader
                  :key="componentKey"
                  :label="$t('backup.rclone_configuration_file')"
                  :helper-text="$t('backup.rclone_configuration_file_helper')"
                  :multiple="false"
                  :removable="true"
                  :clear-on-reselect="true"
                  :drop-target-label="
                    $t('common.drag_and_drop_or_click_to_upload')
                  "
                  v-model="rclone.configuration_uploaded_file"
                  accept=".conf,.txt"
                  ref="backup_file"
                ></cv-file-uploader>
                <div
                  v-if="error.rclone.configuration_file"
                  class="validation-failed-invalid-message"
                >
                  {{ error.rclone.configuration_file }}
                </div>
              </div>
            </template>
            <cv-text-input
              :label="
                $t('backup.rclone_base_path') +
                ' (' +
                $t('common.optional') +
                ')'
              "
              v-model.trim="rclone.base_path"
              :invalid-message="error.rclone.base_path"
              :disabled="loading.addBackupRepository"
              ref="rclone_base_path"
            >
            </cv-text-input>
          </template>
          <template v-if="isGenericS3Selected">
            <NsTextInput
              :label="$t('backup.genericS3_url_label')"
              v-model.trim="url"
              :invalid-message="error.url"
              :placeholder="$t('backup.genericS3_placeholder')"
              :disabled="loading.addBackupRepository"
              ref="url"
            >
              <template slot="tooltip">
                <span>{{ $t("backup.genericS3_url_tooltip") }}</span>
              </template>
            </NsTextInput>
            <cv-text-input
              :label="$t('backup.genericS3_access_key_id')"
              v-model.trim="genericS3.aws_access_key_id"
              :invalid-message="error.genericS3.aws_access_key_id"
              :disabled="loading.addBackupRepository"
              autocomplete="off"
              ref="genericS3_access_key_id"
            >
            </cv-text-input>
            <cv-text-input
              :label="$t('backup.genericS3_secret_access_key')"
              type="password"
              v-model.trim="genericS3.aws_secret_access_key"
              :disabled="loading.addBackupRepository"
              :invalid-message="error.genericS3.aws_secret_access_key"
              :password-hide-label="$t('password.hide_password')"
              :password-show-label="$t('password.show_password')"
              autocomplete="new-password"
              ref="genericS3_secret_access_key"
            ></cv-text-input>
          </template>
          <template v-if="isSambaSelected">
            <NsInlineNotification
              kind="info"
              :title="$t('backup.smb_protocol_warning_title')"
              :description="$t('backup.smb_protocol_warning_description')"
              :showCloseButton="false"
            />
            <cv-text-input
              :label="$t('backup.smb_host')"
              v-model.trim="smb.smb_host"
              :invalid-message="error.smb.smb_host"
              :disabled="loading.addBackupRepository"
              ref="smb_host"
            >
            </cv-text-input>
            <NsTextInput
              :label="$t('backup.smb_url_label')"
              v-model.trim="url"
              :invalid-message="error.url"
              :disabled="loading.addBackupRepository"
              :placeholder="$t('backup.smb_url_placeholder')"
              ref="url"
            >
              <template slot="tooltip">
                <span>{{ $t("backup.smb_url_tooltip") }}</span>
              </template>
            </NsTextInput>
            <cv-text-input
              :label="$t('backup.smb_domain')"
              v-model.trim="smb.smb_domain"
              :invalid-message="error.smb.smb_domain"
              :disabled="loading.addBackupRepository"
              ref="smb_domain"
            >
            </cv-text-input>
            <cv-text-input
              :label="$t('backup.smb_user')"
              v-model.trim="smb.smb_user"
              :invalid-message="error.smb.smb_user"
              :disabled="loading.addBackupRepository"
              autocomplete="off"
              ref="smb_user"
            >
            </cv-text-input>
            <cv-text-input
              :label="$t('backup.smb_pass')"
              type="password"
              v-model.trim="smb.smb_pass"
              :disabled="loading.addBackupRepository"
              :invalid-message="error.smb.smb_pass"
              :password-hide-label="$t('password.hide_password')"
              :password-show-label="$t('password.show_password')"
              autocomplete="new-password"
              ref="smb_pass"
            ></cv-text-input>
          </template>
          <cv-text-input
            :label="$t('backup.repository_name')"
            v-model.trim="name"
            :helper-text="$t('backup.repository_name_helper')"
            :invalid-message="error.name"
            :disabled="loading.addBackupRepository"
            ref="name"
          >
          </cv-text-input>
          <cv-accordion ref="accordion">
            <cv-accordion-item :open="toggleAccordion[0]">
              <template slot="title">{{ $t("common.advanced") }}</template>
              <template slot="content">
                <NsTextInput
                  :label="
                    $t('backup.data_encryption_key') +
                    ' (' +
                    $t('common.optional') +
                    ')'
                  "
                  v-model="password"
                  :helper-text="$t('backup.repository_password_helper')"
                  :placeholder="
                    $t('common.eg_value', { value: 'a76917c4522...' })
                  "
                  :invalid-message="error.password"
                  :disabled="loading.addBackupRepository"
                  autocomplete="new-password"
                  ref="password"
                >
                  <template slot="tooltip">
                    {{ $t("backup.data_encryption_key_tooltip") }}
                  </template>
                </NsTextInput>
              </template>
            </cv-accordion-item>
          </cv-accordion>
          <NsInlineNotification
            v-if="error.addBackupRepository"
            kind="error"
            :title="$t('action.add-backup-repository')"
            :description="error.addBackupRepository"
            :showCloseButton="false"
          />
        </template>
      </cv-form>
    </template>
⋮----
<template v-if="step == 'provider'">
          <div class="mg-bottom-md">
            {{ $t("backup.select_backup_provider") }}
          </div>
          <cv-grid>
            <cv-row>
              <cv-column :md="4">
                <NsTile
                  :light="true"
                  kind="selectable"
                  v-model="isClusterSelected"
                  value="providerValue"
                  @click="selectCluster()"
                  class="provider-card"
                >
                  <div class="provider-card-content">
                    <div class="provider-icon">
                      <img
                        :src="require('@/assets/node_storage.png')"
                        alt="cluster logo"
                      />
                    </div>
                    <h6>
                      {{ $t("backup.cluster") }}
                    </h6>
                  </div>
                </NsTile>
              </cv-column>
              <cv-column :md="4">
                <NsTile
                  :light="true"
                  kind="selectable"
                  v-model="isSambaSelected"
                  value="providerValue"
                  @click="selectSamba()"
                  class="provider-card"
                >
                  <div class="provider-card-content">
                    <div class="provider-icon">
                      <img
                        :src="require('@/assets/samba.png')"
                        alt="samba logo"
                      />
                    </div>
                    <h6>
                      {{ $t("backup.samba") }}
                    </h6>
                  </div>
                </NsTile>
              </cv-column>
              <cv-column :md="4">
                <NsTile
                  :light="true"
                  kind="selectable"
                  v-model="isAmazonS3Selected"
                  value="providerValue"
                  @click="selectAmazonS3()"
                  class="provider-card"
                >
                  <div class="provider-card-content">
                    <div class="provider-icon">
                      <img
                        :src="require('@/assets/aws.png')"
                        alt="amazon s3 logo"
                      />
                    </div>
                    <h6>
                      {{ $t("backup.aws") }}
                    </h6>
                  </div>
                </NsTile>
              </cv-column>
              <cv-column :md="4">
                <NsTile
                  :light="true"
                  kind="selectable"
                  v-model="isBackblazeSelected"
                  value="providerValue"
                  @click="selectBackblaze()"
                  class="provider-card"
                >
                  <div class="provider-card-content">
                    <div class="provider-icon">
                      <img
                        :src="require('@/assets/backblaze.png')"
                        alt="backblaze logo"
                      />
                    </div>
                    <h6>
                      {{ $t("backup.backblaze") }}
                    </h6>
                  </div>
                </NsTile>
              </cv-column>
              <cv-column :md="4">
                <NsTile
                  :light="true"
                  kind="selectable"
                  v-model="isGenericS3Selected"
                  value="providerValue"
                  @click="selectGenericS3()"
                  class="provider-card"
                >
                  <div class="provider-card-content">
                    <div class="provider-icon">
                      <img
                        :src="require('@/assets/s3-generic.png')"
                        alt="generic s3 logo"
                      />
                    </div>
                    <h6>
                      {{ $t("backup.generic-s3") }}
                    </h6>
                  </div>
                </NsTile>
              </cv-column>
              <cv-column :md="4">
                <NsTile
                  :light="true"
                  kind="selectable"
                  v-model="isRcloneSelected"
                  value="providerValue"
                  @click="selectRclone()"
                  class="provider-card"
                >
                  <div class="provider-card-content">
                    <div class="provider-icon">
                      <img
                        :src="require('@/assets/rclone.png')"
                        alt="rclone logo"
                      />
                    </div>
                    <h6>
                      {{ $t("backup.rclone") }}
                    </h6>
                  </div>
                </NsTile>
              </cv-column>
            </cv-row>
          </cv-grid>
        </template>
⋮----
{{ $t("backup.select_backup_provider") }}
⋮----
{{ $t("backup.cluster") }}
⋮----
{{ $t("backup.samba") }}
⋮----
{{ $t("backup.aws") }}
⋮----
{{ $t("backup.backblaze") }}
⋮----
{{ $t("backup.generic-s3") }}
⋮----
{{ $t("backup.rclone") }}
⋮----
<template v-if="step == 'nodes'">
          <div class="mg-bottom-sm">{{ $t("backup.select_cluster_node") }}</div>
          <NodeSelector
            class="mg-top-xlg"
            @selectNode="onSelectNode"
            :disabledNodes="disabledNodes"
            :loading="loading.getClusterStatus"
          >
            <template v-for="(nodeMessages, nodeId) in nodesInfo">
              <template :slot="`node-${nodeId}`">
                <div
                  v-for="(nodeMessage, index) in nodeMessages"
                  :key="index"
                  class="node-message"
                >
                  {{ nodeMessage }}
                </div>
              </template>
            </template>
          </NodeSelector>
        </template>
⋮----
<div class="mg-bottom-sm">{{ $t("backup.select_cluster_node") }}</div>
⋮----
<template v-for="(nodeMessages, nodeId) in nodesInfo">
              <template :slot="`node-${nodeId}`">
                <div
                  v-for="(nodeMessage, index) in nodeMessages"
                  :key="index"
                  class="node-message"
                >
                  {{ nodeMessage }}
                </div>
              </template>
            </template>
⋮----
<template :slot="`node-${nodeId}`">
                <div
                  v-for="(nodeMessage, index) in nodeMessages"
                  :key="index"
                  class="node-message"
                >
                  {{ nodeMessage }}
                </div>
              </template>
⋮----
{{ nodeMessage }}
⋮----
<template v-if="step == 'settings'">
          <NsInlineNotification
            v-if="error.repoConnection"
            kind="error"
            :title="$t('backup.backup_repository_connection_error')"
            :description="$t('backup.' + error.repoConnection)"
            :showCloseButton="false"
          />
          <template v-if="isBackblazeSelected">
            <cv-text-input
              :label="$t('backup.backblaze_url_label')"
              v-model.trim="url"
              :invalid-message="error.url"
              :disabled="loading.addBackupRepository"
              ref="url"
            >
            </cv-text-input>
            <cv-text-input
              :label="$t('backup.b2_account_id')"
              v-model.trim="backblaze.b2_account_id"
              :invalid-message="error.backblaze.b2_account_id"
              :disabled="loading.addBackupRepository"
              autocomplete="off"
              ref="b2_account_id"
            >
            </cv-text-input>
            <cv-text-input
              :label="$t('backup.b2_account_key')"
              type="password"
              v-model.trim="backblaze.b2_account_key"
              :disabled="loading.addBackupRepository"
              :invalid-message="error.backblaze.b2_account_key"
              :password-hide-label="$t('password.hide_password')"
              :password-show-label="$t('password.show_password')"
              autocomplete="new-password"
              ref="b2_account_key"
            ></cv-text-input>
          </template>
          <template v-if="isAmazonS3Selected">
            <cv-text-input
              :label="$t('backup.aws_url_label')"
              v-model.trim="url"
              :invalid-message="error.url"
              :disabled="loading.addBackupRepository"
              ref="url"
            >
            </cv-text-input>
            <cv-text-input
              :label="$t('backup.aws_default_region')"
              v-model.trim="aws.aws_default_region"
              :invalid-message="error.aws.aws_default_region"
              :disabled="loading.addBackupRepository"
              ref="aws_default_region"
            >
            </cv-text-input>
            <cv-text-input
              :label="$t('backup.aws_access_key_id')"
              v-model.trim="aws.aws_access_key_id"
              :invalid-message="error.aws.aws_access_key_id"
              :disabled="loading.addBackupRepository"
              autocomplete="off"
              ref="aws_access_key_id"
            >
            </cv-text-input>
            <cv-text-input
              :label="$t('backup.aws_secret_access_key')"
              type="password"
              v-model.trim="aws.aws_secret_access_key"
              :disabled="loading.addBackupRepository"
              :invalid-message="error.aws.aws_secret_access_key"
              :password-hide-label="$t('password.hide_password')"
              :password-show-label="$t('password.show_password')"
              autocomplete="new-password"
              ref="aws_secret_access_key"
            ></cv-text-input>
          </template>
          <template v-if="isRcloneSelected">
            <div>
              <label class="bx--label">{{
                $t("backup.rclone_configuration_source")
              }}</label>
              <cv-radio-group
                :vertical="true"
                :disabled="loading.addBackupRepository"
              >
                <cv-radio-button
                  ref="paste_configuration"
                  :label="
                    $t('backup.rclone_configuration_source_paste_configuration')
                  "
                  value="paste"
                  v-model="rclone.configuration_source"
                />
                <cv-radio-button
                  ref="upload_configuration"
                  :label="
                    $t(
                      'backup.rclone_configuration_source_upload_configuration'
                    )
                  "
                  value="upload"
                  v-model="rclone.configuration_source"
                />
              </cv-radio-group>
            </div>
            <template v-if="rclone.configuration_source == 'paste'">
              <cv-text-area
                class="mg-top-md"
                :label="$t('backup.rclone_configuration_content')"
                v-model.trim="rclone.rclone_conf_secret"
                :invalid-message="error.rclone.rclone_conf_secret"
                :helper-text="
                  $t(
                    'backup.rclone_configuration_content_single_destination_helper_text'
                  )
                "
                :value="rclone.rclone_conf_secret"
                rows="5"
                ref="rclone_conf_secret"
                :disabled="loading.addBackupRepository"
              >
              </cv-text-area>
            </template>
            <template v-else>
              <div
                :class="{
                  'file-uploader-error': error.rclone.configuration_file,
                }"
              >
                <cv-file-uploader
                  :key="componentKey"
                  :label="$t('backup.rclone_configuration_file')"
                  :helper-text="$t('backup.rclone_configuration_file_helper')"
                  :multiple="false"
                  :removable="true"
                  :clear-on-reselect="true"
                  :drop-target-label="
                    $t('common.drag_and_drop_or_click_to_upload')
                  "
                  v-model="rclone.configuration_uploaded_file"
                  accept=".conf,.txt"
                  ref="backup_file"
                ></cv-file-uploader>
                <div
                  v-if="error.rclone.configuration_file"
                  class="validation-failed-invalid-message"
                >
                  {{ error.rclone.configuration_file }}
                </div>
              </div>
            </template>
            <cv-text-input
              :label="
                $t('backup.rclone_base_path') +
                ' (' +
                $t('common.optional') +
                ')'
              "
              v-model.trim="rclone.base_path"
              :invalid-message="error.rclone.base_path"
              :disabled="loading.addBackupRepository"
              ref="rclone_base_path"
            >
            </cv-text-input>
          </template>
          <template v-if="isGenericS3Selected">
            <NsTextInput
              :label="$t('backup.genericS3_url_label')"
              v-model.trim="url"
              :invalid-message="error.url"
              :placeholder="$t('backup.genericS3_placeholder')"
              :disabled="loading.addBackupRepository"
              ref="url"
            >
              <template slot="tooltip">
                <span>{{ $t("backup.genericS3_url_tooltip") }}</span>
              </template>
            </NsTextInput>
            <cv-text-input
              :label="$t('backup.genericS3_access_key_id')"
              v-model.trim="genericS3.aws_access_key_id"
              :invalid-message="error.genericS3.aws_access_key_id"
              :disabled="loading.addBackupRepository"
              autocomplete="off"
              ref="genericS3_access_key_id"
            >
            </cv-text-input>
            <cv-text-input
              :label="$t('backup.genericS3_secret_access_key')"
              type="password"
              v-model.trim="genericS3.aws_secret_access_key"
              :disabled="loading.addBackupRepository"
              :invalid-message="error.genericS3.aws_secret_access_key"
              :password-hide-label="$t('password.hide_password')"
              :password-show-label="$t('password.show_password')"
              autocomplete="new-password"
              ref="genericS3_secret_access_key"
            ></cv-text-input>
          </template>
          <template v-if="isSambaSelected">
            <NsInlineNotification
              kind="info"
              :title="$t('backup.smb_protocol_warning_title')"
              :description="$t('backup.smb_protocol_warning_description')"
              :showCloseButton="false"
            />
            <cv-text-input
              :label="$t('backup.smb_host')"
              v-model.trim="smb.smb_host"
              :invalid-message="error.smb.smb_host"
              :disabled="loading.addBackupRepository"
              ref="smb_host"
            >
            </cv-text-input>
            <NsTextInput
              :label="$t('backup.smb_url_label')"
              v-model.trim="url"
              :invalid-message="error.url"
              :disabled="loading.addBackupRepository"
              :placeholder="$t('backup.smb_url_placeholder')"
              ref="url"
            >
              <template slot="tooltip">
                <span>{{ $t("backup.smb_url_tooltip") }}</span>
              </template>
            </NsTextInput>
            <cv-text-input
              :label="$t('backup.smb_domain')"
              v-model.trim="smb.smb_domain"
              :invalid-message="error.smb.smb_domain"
              :disabled="loading.addBackupRepository"
              ref="smb_domain"
            >
            </cv-text-input>
            <cv-text-input
              :label="$t('backup.smb_user')"
              v-model.trim="smb.smb_user"
              :invalid-message="error.smb.smb_user"
              :disabled="loading.addBackupRepository"
              autocomplete="off"
              ref="smb_user"
            >
            </cv-text-input>
            <cv-text-input
              :label="$t('backup.smb_pass')"
              type="password"
              v-model.trim="smb.smb_pass"
              :disabled="loading.addBackupRepository"
              :invalid-message="error.smb.smb_pass"
              :password-hide-label="$t('password.hide_password')"
              :password-show-label="$t('password.show_password')"
              autocomplete="new-password"
              ref="smb_pass"
            ></cv-text-input>
          </template>
          <cv-text-input
            :label="$t('backup.repository_name')"
            v-model.trim="name"
            :helper-text="$t('backup.repository_name_helper')"
            :invalid-message="error.name"
            :disabled="loading.addBackupRepository"
            ref="name"
          >
          </cv-text-input>
          <cv-accordion ref="accordion">
            <cv-accordion-item :open="toggleAccordion[0]">
              <template slot="title">{{ $t("common.advanced") }}</template>
              <template slot="content">
                <NsTextInput
                  :label="
                    $t('backup.data_encryption_key') +
                    ' (' +
                    $t('common.optional') +
                    ')'
                  "
                  v-model="password"
                  :helper-text="$t('backup.repository_password_helper')"
                  :placeholder="
                    $t('common.eg_value', { value: 'a76917c4522...' })
                  "
                  :invalid-message="error.password"
                  :disabled="loading.addBackupRepository"
                  autocomplete="new-password"
                  ref="password"
                >
                  <template slot="tooltip">
                    {{ $t("backup.data_encryption_key_tooltip") }}
                  </template>
                </NsTextInput>
              </template>
            </cv-accordion-item>
          </cv-accordion>
          <NsInlineNotification
            v-if="error.addBackupRepository"
            kind="error"
            :title="$t('action.add-backup-repository')"
            :description="error.addBackupRepository"
            :showCloseButton="false"
          />
        </template>
⋮----
<template v-if="isBackblazeSelected">
            <cv-text-input
              :label="$t('backup.backblaze_url_label')"
              v-model.trim="url"
              :invalid-message="error.url"
              :disabled="loading.addBackupRepository"
              ref="url"
            >
            </cv-text-input>
            <cv-text-input
              :label="$t('backup.b2_account_id')"
              v-model.trim="backblaze.b2_account_id"
              :invalid-message="error.backblaze.b2_account_id"
              :disabled="loading.addBackupRepository"
              autocomplete="off"
              ref="b2_account_id"
            >
            </cv-text-input>
            <cv-text-input
              :label="$t('backup.b2_account_key')"
              type="password"
              v-model.trim="backblaze.b2_account_key"
              :disabled="loading.addBackupRepository"
              :invalid-message="error.backblaze.b2_account_key"
              :password-hide-label="$t('password.hide_password')"
              :password-show-label="$t('password.show_password')"
              autocomplete="new-password"
              ref="b2_account_key"
            ></cv-text-input>
          </template>
⋮----
<template v-if="isAmazonS3Selected">
            <cv-text-input
              :label="$t('backup.aws_url_label')"
              v-model.trim="url"
              :invalid-message="error.url"
              :disabled="loading.addBackupRepository"
              ref="url"
            >
            </cv-text-input>
            <cv-text-input
              :label="$t('backup.aws_default_region')"
              v-model.trim="aws.aws_default_region"
              :invalid-message="error.aws.aws_default_region"
              :disabled="loading.addBackupRepository"
              ref="aws_default_region"
            >
            </cv-text-input>
            <cv-text-input
              :label="$t('backup.aws_access_key_id')"
              v-model.trim="aws.aws_access_key_id"
              :invalid-message="error.aws.aws_access_key_id"
              :disabled="loading.addBackupRepository"
              autocomplete="off"
              ref="aws_access_key_id"
            >
            </cv-text-input>
            <cv-text-input
              :label="$t('backup.aws_secret_access_key')"
              type="password"
              v-model.trim="aws.aws_secret_access_key"
              :disabled="loading.addBackupRepository"
              :invalid-message="error.aws.aws_secret_access_key"
              :password-hide-label="$t('password.hide_password')"
              :password-show-label="$t('password.show_password')"
              autocomplete="new-password"
              ref="aws_secret_access_key"
            ></cv-text-input>
          </template>
⋮----
<template v-if="isRcloneSelected">
            <div>
              <label class="bx--label">{{
                $t("backup.rclone_configuration_source")
              }}</label>
              <cv-radio-group
                :vertical="true"
                :disabled="loading.addBackupRepository"
              >
                <cv-radio-button
                  ref="paste_configuration"
                  :label="
                    $t('backup.rclone_configuration_source_paste_configuration')
                  "
                  value="paste"
                  v-model="rclone.configuration_source"
                />
                <cv-radio-button
                  ref="upload_configuration"
                  :label="
                    $t(
                      'backup.rclone_configuration_source_upload_configuration'
                    )
                  "
                  value="upload"
                  v-model="rclone.configuration_source"
                />
              </cv-radio-group>
            </div>
            <template v-if="rclone.configuration_source == 'paste'">
              <cv-text-area
                class="mg-top-md"
                :label="$t('backup.rclone_configuration_content')"
                v-model.trim="rclone.rclone_conf_secret"
                :invalid-message="error.rclone.rclone_conf_secret"
                :helper-text="
                  $t(
                    'backup.rclone_configuration_content_single_destination_helper_text'
                  )
                "
                :value="rclone.rclone_conf_secret"
                rows="5"
                ref="rclone_conf_secret"
                :disabled="loading.addBackupRepository"
              >
              </cv-text-area>
            </template>
            <template v-else>
              <div
                :class="{
                  'file-uploader-error': error.rclone.configuration_file,
                }"
              >
                <cv-file-uploader
                  :key="componentKey"
                  :label="$t('backup.rclone_configuration_file')"
                  :helper-text="$t('backup.rclone_configuration_file_helper')"
                  :multiple="false"
                  :removable="true"
                  :clear-on-reselect="true"
                  :drop-target-label="
                    $t('common.drag_and_drop_or_click_to_upload')
                  "
                  v-model="rclone.configuration_uploaded_file"
                  accept=".conf,.txt"
                  ref="backup_file"
                ></cv-file-uploader>
                <div
                  v-if="error.rclone.configuration_file"
                  class="validation-failed-invalid-message"
                >
                  {{ error.rclone.configuration_file }}
                </div>
              </div>
            </template>
            <cv-text-input
              :label="
                $t('backup.rclone_base_path') +
                ' (' +
                $t('common.optional') +
                ')'
              "
              v-model.trim="rclone.base_path"
              :invalid-message="error.rclone.base_path"
              :disabled="loading.addBackupRepository"
              ref="rclone_base_path"
            >
            </cv-text-input>
          </template>
⋮----
<label class="bx--label">{{
                $t("backup.rclone_configuration_source")
              }}</label>
⋮----
<template v-if="rclone.configuration_source == 'paste'">
              <cv-text-area
                class="mg-top-md"
                :label="$t('backup.rclone_configuration_content')"
                v-model.trim="rclone.rclone_conf_secret"
                :invalid-message="error.rclone.rclone_conf_secret"
                :helper-text="
                  $t(
                    'backup.rclone_configuration_content_single_destination_helper_text'
                  )
                "
                :value="rclone.rclone_conf_secret"
                rows="5"
                ref="rclone_conf_secret"
                :disabled="loading.addBackupRepository"
              >
              </cv-text-area>
            </template>
<template v-else>
              <div
                :class="{
                  'file-uploader-error': error.rclone.configuration_file,
                }"
              >
                <cv-file-uploader
                  :key="componentKey"
                  :label="$t('backup.rclone_configuration_file')"
                  :helper-text="$t('backup.rclone_configuration_file_helper')"
                  :multiple="false"
                  :removable="true"
                  :clear-on-reselect="true"
                  :drop-target-label="
                    $t('common.drag_and_drop_or_click_to_upload')
                  "
                  v-model="rclone.configuration_uploaded_file"
                  accept=".conf,.txt"
                  ref="backup_file"
                ></cv-file-uploader>
                <div
                  v-if="error.rclone.configuration_file"
                  class="validation-failed-invalid-message"
                >
                  {{ error.rclone.configuration_file }}
                </div>
              </div>
            </template>
⋮----
{{ error.rclone.configuration_file }}
⋮----
<template v-if="isGenericS3Selected">
            <NsTextInput
              :label="$t('backup.genericS3_url_label')"
              v-model.trim="url"
              :invalid-message="error.url"
              :placeholder="$t('backup.genericS3_placeholder')"
              :disabled="loading.addBackupRepository"
              ref="url"
            >
              <template slot="tooltip">
                <span>{{ $t("backup.genericS3_url_tooltip") }}</span>
              </template>
            </NsTextInput>
            <cv-text-input
              :label="$t('backup.genericS3_access_key_id')"
              v-model.trim="genericS3.aws_access_key_id"
              :invalid-message="error.genericS3.aws_access_key_id"
              :disabled="loading.addBackupRepository"
              autocomplete="off"
              ref="genericS3_access_key_id"
            >
            </cv-text-input>
            <cv-text-input
              :label="$t('backup.genericS3_secret_access_key')"
              type="password"
              v-model.trim="genericS3.aws_secret_access_key"
              :disabled="loading.addBackupRepository"
              :invalid-message="error.genericS3.aws_secret_access_key"
              :password-hide-label="$t('password.hide_password')"
              :password-show-label="$t('password.show_password')"
              autocomplete="new-password"
              ref="genericS3_secret_access_key"
            ></cv-text-input>
          </template>
⋮----
<template slot="tooltip">
                <span>{{ $t("backup.genericS3_url_tooltip") }}</span>
              </template>
⋮----
<span>{{ $t("backup.genericS3_url_tooltip") }}</span>
⋮----
<template v-if="isSambaSelected">
            <NsInlineNotification
              kind="info"
              :title="$t('backup.smb_protocol_warning_title')"
              :description="$t('backup.smb_protocol_warning_description')"
              :showCloseButton="false"
            />
            <cv-text-input
              :label="$t('backup.smb_host')"
              v-model.trim="smb.smb_host"
              :invalid-message="error.smb.smb_host"
              :disabled="loading.addBackupRepository"
              ref="smb_host"
            >
            </cv-text-input>
            <NsTextInput
              :label="$t('backup.smb_url_label')"
              v-model.trim="url"
              :invalid-message="error.url"
              :disabled="loading.addBackupRepository"
              :placeholder="$t('backup.smb_url_placeholder')"
              ref="url"
            >
              <template slot="tooltip">
                <span>{{ $t("backup.smb_url_tooltip") }}</span>
              </template>
            </NsTextInput>
            <cv-text-input
              :label="$t('backup.smb_domain')"
              v-model.trim="smb.smb_domain"
              :invalid-message="error.smb.smb_domain"
              :disabled="loading.addBackupRepository"
              ref="smb_domain"
            >
            </cv-text-input>
            <cv-text-input
              :label="$t('backup.smb_user')"
              v-model.trim="smb.smb_user"
              :invalid-message="error.smb.smb_user"
              :disabled="loading.addBackupRepository"
              autocomplete="off"
              ref="smb_user"
            >
            </cv-text-input>
            <cv-text-input
              :label="$t('backup.smb_pass')"
              type="password"
              v-model.trim="smb.smb_pass"
              :disabled="loading.addBackupRepository"
              :invalid-message="error.smb.smb_pass"
              :password-hide-label="$t('password.hide_password')"
              :password-show-label="$t('password.show_password')"
              autocomplete="new-password"
              ref="smb_pass"
            ></cv-text-input>
          </template>
⋮----
<template slot="tooltip">
                <span>{{ $t("backup.smb_url_tooltip") }}</span>
              </template>
⋮----
<span>{{ $t("backup.smb_url_tooltip") }}</span>
⋮----
<template slot="title">{{ $t("common.advanced") }}</template>
<template slot="content">
                <NsTextInput
                  :label="
                    $t('backup.data_encryption_key') +
                    ' (' +
                    $t('common.optional') +
                    ')'
                  "
                  v-model="password"
                  :helper-text="$t('backup.repository_password_helper')"
                  :placeholder="
                    $t('common.eg_value', { value: 'a76917c4522...' })
                  "
                  :invalid-message="error.password"
                  :disabled="loading.addBackupRepository"
                  autocomplete="new-password"
                  ref="password"
                >
                  <template slot="tooltip">
                    {{ $t("backup.data_encryption_key_tooltip") }}
                  </template>
                </NsTextInput>
              </template>
⋮----
<template slot="tooltip">
                    {{ $t("backup.data_encryption_key_tooltip") }}
                  </template>
⋮----
{{ $t("backup.data_encryption_key_tooltip") }}
⋮----
<script>
import { UtilService, TaskService, IconService } from "@nethserver/ns8-ui-lib";
import to from "await-to-js";
import last from "lodash/last";
import NodeSelector from "@/components/nodes/NodeSelector";
export default {
  name: "AddRepositoryModal",
  components: { NodeSelector },
  mixins: [UtilService, TaskService, IconService],
  props: {
    isShown: {
      type: Boolean,
      default: true,
    },
    repositories: {
      type: Array,
      required: true,
    },
  },
  data() {
    return {
      step: "",
      steps: ["provider", "nodes", "settings"],
      isBackblazeSelected: false,
      isRcloneSelected: false,
      isAmazonS3Selected: false,
      isGenericS3Selected: false,
      isSambaSelected: false,
      isClusterSelected: false,
      endpoints: [],
      selectedNode: null,
      name: "",
      url: "",
      password: "",
      componentKey: Date.now(), // used to reset file uploader
      backblaze: {
        b2_account_id: "",
        b2_account_key: "",
        repoPrefix: "b2:",
      },
      aws: {
        aws_access_key_id: "",
        aws_default_region: "",
        aws_secret_access_key: "",
        repoPrefix: "s3:s3.amazonaws.com/",
      },
      smb: {
        smb_host: "",
        smb_user: "",
        smb_pass: "",
        smb_domain: "",
        repoPrefix: "smb:",
      },
      genericS3: {
        aws_access_key_id: "",
        aws_secret_access_key: "",
        repoPrefix: "s3:",
      },
      rclone: {
        configuration_source: "paste",
        rclone_conf_secret: "",
        base_path: "",
        configuration_uploaded_file: null,
        repoPrefix: "",
      },
      cluster: {
        repoPrefix: "",
      },
      clusterStatus: [],
      loading: {
        addBackupRepository: false,
        listBackupEndpoints: false,
        getClusterStatus: false,
        fileReading: false,
      },
      error: {
        getClusterStatus: "",
        name: "",
        url: "",
        addBackupRepository: "",
        repoConnection: "",
        listBackupEndpoints: "",
        backblaze: {
          b2_account_id: "",
          b2_account_key: "",
        },
        aws: {
          aws_access_key_id: "",
          aws_default_region: "",
          aws_secret_access_key: "",
        },
        smb: {
          smb_host: "",
          smb_user: "",
          smb_pass: "",
          smb_domain: "",
        },
        genericS3: {
          aws_access_key_id: "",
          aws_default_region: "",
          aws_secret_access_key: "",
        },
        rclone: {
          rclone_conf_secret: "",
          base_path: "",
          configuration_source: "",
          configuration_file: "",
        },
      },
    };
  },
  computed: {
    stepIndex() {
      return this.steps.indexOf(this.step);
    },
    isFirstStep() {
      return this.stepIndex == 0;
    },
    isLastStep() {
      return this.stepIndex == this.steps.length - 1;
    },
    isNextButtonDisabled() {
      const isLoading =
        this.loading.addBackupRepository || this.loading.fileReading;
      const isNoProvider = !this.selectedProvider;
      // Only check for node selection on the nodes step when cluster is selected
      const isClusterWithoutNode =
        this.step === "nodes" && this.isClusterSelected && !this.selectedNode;
      return isLoading || isNoProvider || isClusterWithoutNode;
    },
    selectedProvider() {
      if (this.isBackblazeSelected) {
        return "backblaze";
      } else if (this.isAmazonS3Selected) {
        return "aws";
      } else if (this.isGenericS3Selected) {
        return "genericS3";
      } else if (this.isRcloneSelected) {
        return "rclone";
      } else if (this.isSambaSelected) {
        return "smb";
      } else if (this.isClusterSelected) {
        return "cluster";
      } else {
        return null;
      }
    },
    selectedProviderPrefix() {
      return this[this.selectedProvider].repoPrefix;
    },
    disabledNodes() {
      const disabledNodeIds = [];
      for (const node of this.clusterStatus) {
        if (!node.online) {
          disabledNodeIds.push(node.id);
          continue;
        }
        const endpointLabel = this.getEndpointLabelForNode(node);
        const endpoint = this.endpoints.find(
          (item) => item.label === endpointLabel || item.name === endpointLabel
        );
        if (endpoint) {
          const isEndpointUsed = this.repositories.some(
            (repo) => repo.url === endpoint.value
          );
          if (isEndpointUsed) {
            disabledNodeIds.push(node.id);
          }
        }
      }
      return disabledNodeIds;
    },
    nodesInfo() {
      const nodesInfo = {};
      for (const node of this.clusterStatus) {
        const nodeMessages = [];
        if (!node.online) {
          nodeMessages.push(this.$t("software_center.node_offline"));
        } else {
          const endpointLabel = this.getEndpointLabelForNode(node);
          const endpoint = this.endpoints.find(
            (item) =>
              item.label === endpointLabel || item.name === endpointLabel
          );
          if (endpoint) {
            const isEndpointUsed = this.repositories.some(
              (repo) => repo.url === endpoint.value
            );
            if (isEndpointUsed) {
              nodeMessages.push(this.$t("backup.repository_already_used"));
            }
          }
        }
        if (nodeMessages.length > 0) {
          nodesInfo[node.id] = nodeMessages;
        }
      }
      return nodesInfo;
    },
  },
  watch: {
    isShown: function () {
      if (this.isShown) {
        this.step = this.steps[0];
        this.componentKey = Date.now();
        this.clearFields();
        this.clearErrors();
        this.listBackupEndpoints();
      }
    },
    step: function () {
      if (this.step == "nodes") {
        if (this.isClusterSelected) {
          this.getClusterStatus();
        }
      } else if (this.step == "settings") {
        this.name = "";
        if (this.selectedProvider == "smb") {
          this.focusElement("smb_host");
        } else if (
          this.selectedProvider != "cluster" &&
          this.selectedProvider != "rclone"
        ) {
          this.focusElement("url");
        }
      }
    },
    selectedProvider: function (newProvider, oldProvider) {
      if (oldProvider && newProvider !== oldProvider) {
        this.url = "";
        this.password = "";
        this.selectedNode = null;
        this.backblaze.b2_account_id = "";
        this.backblaze.b2_account_key = "";
        this.aws.aws_access_key_id = "";
        this.aws.aws_default_region = "";
        this.aws.aws_secret_access_key = "";
        this.genericS3.aws_access_key_id = "";
        this.genericS3.aws_secret_access_key = "";
        this.smb.smb_host = "";
        this.smb.smb_user = "";
        this.smb.smb_pass = "";
        this.smb.smb_domain = "";
        this.rclone.configuration_source = "paste";
        this.rclone.rclone_conf_secret = "";
        this.rclone.base_path = "";
        this.rclone.configuration_uploaded_file = null;
      }
    },
    "rclone.configuration_uploaded_file": function (newFiles) {
      if (newFiles && newFiles.length > 0 && newFiles[0].file) {
        const reader = new FileReader();
        this.loading.fileReading = true;
        reader.onload = (e) => {
          this.rclone.rclone_conf_secret = e.target.result.trim();
          this.loading.fileReading = false;
        };
        reader.onerror = () => {
          this.loading.fileReading = false;
          this.error.rclone.configuration_file = this.$t(
            "backup.rclone_conf_error"
          );
        };
        reader.readAsText(newFiles[0].file);
      } else {
        this.rclone.rclone_conf_secret = "";
        this.loading.fileReading = false;
      }
    },
  },
  methods: {
    async getClusterStatus() {
      this.loading.getClusterStatus = true;
      this.error.getClusterStatus = "";
      const taskAction = "get-cluster-status";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.getClusterStatusAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.getClusterStatusCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.getClusterStatus = this.getErrorMessage(err);
        this.loading.getClusterStatus = false;
        return;
      }
    },
    getClusterStatusAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.getClusterStatus = this.$t("error.generic_error");
      this.loading.getClusterStatus = false;
    },
    getClusterStatusCompleted(taskContext, taskResult) {
      this.clusterStatus = taskResult.output.nodes;
      this.loading.getClusterStatus = false;
    },
    clearFields() {
      this.isBackblazeSelected = false;
      this.isAmazonS3Selected = false;
      this.isGenericS3Selected = false;
      this.isRcloneSelected = false;
      this.isSambaSelected = false;
      this.isClusterSelected = false;
      this.name = "";
      this.url = "";
      this.selectedNode = null;
      this.backblaze.b2_account_id = "";
      this.backblaze.b2_account_key = "";
      this.aws.aws_access_key_id = "";
      this.aws.aws_default_region = "";
      this.aws.aws_secret_access_key = "";
      this.genericS3.aws_access_key_id = "";
      this.genericS3.aws_secret_access_key = "";
      this.smb.smb_host = "";
      this.smb.smb_user = "";
      this.smb.smb_pass = "";
      this.smb.smb_domain = "";
      this.rclone.configuration_source = "paste";
      this.rclone.rclone_conf_secret = "";
      this.rclone.base_path = "";
      this.rclone.configuration_uploaded_file = null;
    },
    nextStep() {
      if (this.isNextButtonDisabled) {
        return;
      }
      if (this.isLastStep) {
        this.addBackupRepository();
      } else {
        // Skip nodes step if cluster is not selected
        if (this.step === "provider" && !this.isClusterSelected) {
          this.step = "settings";
        } else {
          this.step = this.steps[this.stepIndex + 1];
        }
      }
    },
    previousStep() {
      if (!this.isFirstStep) {
        if (this.step === "settings" && !this.isClusterSelected) {
          this.step = "provider";
        } else {
          this.step = this.steps[this.stepIndex - 1];
        }
      }
    },
    selectBackblaze() {
      this.isRcloneSelected = false;
      this.isAmazonS3Selected = false;
      this.isGenericS3Selected = false;
      this.isSambaSelected = false;
      this.isClusterSelected = false;
    },
    selectAmazonS3() {
      this.isBackblazeSelected = false;
      this.isRcloneSelected = false;
      this.isGenericS3Selected = false;
      this.isSambaSelected = false;
      this.isClusterSelected = false;
    },
    selectSamba() {
      this.isBackblazeSelected = false;
      this.isRcloneSelected = false;
      this.isGenericS3Selected = false;
      this.isAmazonS3Selected = false;
      this.isClusterSelected = false;
    },
    selectGenericS3() {
      this.isBackblazeSelected = false;
      this.isRcloneSelected = false;
      this.isAmazonS3Selected = false;
      this.isSambaSelected = false;
      this.isClusterSelected = false;
    },
    selectRclone() {
      this.isBackblazeSelected = false;
      this.isAmazonS3Selected = false;
      this.isGenericS3Selected = false;
      this.isSambaSelected = false;
      this.isClusterSelected = false;
    },
    selectCluster() {
      this.isBackblazeSelected = false;
      this.isAmazonS3Selected = false;
      this.isGenericS3Selected = false;
      this.isSambaSelected = false;
      this.isRcloneSelected = false;
    },
    buildRepositoryParameters() {
      switch (this.selectedProvider) {
        case "backblaze":
          return {
            b2_account_id: this.backblaze.b2_account_id,
            b2_account_key: this.backblaze.b2_account_key,
          };
        case "aws":
          return {
            aws_default_region: this.aws.aws_default_region,
            aws_access_key_id: this.aws.aws_access_key_id,
            aws_secret_access_key: this.aws.aws_secret_access_key,
          };
        case "genericS3":
          return {
            aws_access_key_id: this.genericS3.aws_access_key_id,
            aws_secret_access_key: this.genericS3.aws_secret_access_key,
          };
        case "rclone":
          return {
            rclone_conf_secret: this.rclone.rclone_conf_secret,
            basepath: this.rclone.base_path,
          };
        case "smb":
          return {
            smb_host: this.smb.smb_host,
            smb_user: this.smb.smb_user,
            smb_pass: this.smb.smb_pass,
            smb_domain: this.smb.smb_domain,
          };
        case "cluster":
          return {};
      }
    },
    validateAddBackblazeRepository() {
      this.error.name = "";
      this.error.url = "";
      this.error.repoConnection = "";
      this.error.backblaze.b2_account_id = "";
      this.error.backblaze.b2_account_key = "";
      let isValidationOk = true;
      if (!this.url) {
        this.error.url = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("url");
          isValidationOk = false;
        }
      } else if (this.url.includes(" ")) {
        this.error.url = this.$t("backup.invalid_url");
        if (isValidationOk) {
          this.focusElement("url");
          isValidationOk = false;
        }
      }
      if (!this.backblaze.b2_account_id) {
        this.error.backblaze.b2_account_id = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("b2_account_id");
          isValidationOk = false;
        }
      }
      if (!this.backblaze.b2_account_key) {
        this.error.backblaze.b2_account_key = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("b2_account_key");
          isValidationOk = false;
        }
      }
      if (!this.name) {
        this.error.name = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("name");
          isValidationOk = false;
        }
      }
      return isValidationOk;
    },
    validateAmazonS3Repository() {
      this.error.name = "";
      this.error.url = "";
      this.error.repoConnection = "";
      this.error.aws.aws_access_key_id = "";
      this.error.aws.aws_default_region = "";
      this.error.aws.aws_secret_access_key = "";
      let isValidationOk = true;
      if (!this.url) {
        this.error.url = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("url");
          isValidationOk = false;
        }
      } else if (this.url.includes(" ")) {
        this.error.url = this.$t("backup.invalid_url");
        if (isValidationOk) {
          this.focusElement("url");
          isValidationOk = false;
        }
      }
      if (!this.aws.aws_access_key_id) {
        this.error.aws.aws_access_key_id = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("aws_access_key_id");
          isValidationOk = false;
        }
      }
      if (!this.aws.aws_default_region) {
        this.error.aws.aws_default_region = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("aws_default_region");
          isValidationOk = false;
        }
      }
      if (!this.aws.aws_secret_access_key) {
        this.error.aws.aws_secret_access_key = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("aws_secret_access_key");
          isValidationOk = false;
        }
      }
      if (!this.name) {
        this.error.name = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("name");
          isValidationOk = false;
        }
      }
      return isValidationOk;
    },
    validateAddGenericS3Repository() {
      this.error.name = "";
      this.error.url = "";
      this.error.repoConnection = "";
      this.error.genericS3.aws_access_key_id = "";
      this.error.genericS3.aws_default_region = "";
      this.error.genericS3.aws_secret_access_key = "";
      let isValidationOk = true;
      if (!this.url) {
        this.error.url = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("url");
          isValidationOk = false;
        }
      } else if (this.url.includes(" ")) {
        this.error.url = this.$t("backup.invalid_url");
        if (isValidationOk) {
          this.focusElement("url");
          isValidationOk = false;
        }
      }
      if (!this.genericS3.aws_access_key_id) {
        this.error.genericS3.aws_access_key_id = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("genericS3_access_key_id");
          isValidationOk = false;
        }
      }
      if (!this.genericS3.aws_secret_access_key) {
        this.error.genericS3.aws_secret_access_key = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("genericS3_secret_access_key");
          isValidationOk = false;
        }
      }
      if (!this.name) {
        this.error.name = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("name");
          isValidationOk = false;
        }
      }
      return isValidationOk;
    },
    validateAddRcloneRepository() {
      this.error.name = "";
      this.error.repoConnection = "";
      this.error.rclone.rclone_conf_secret = "";
      this.error.rclone.base_path = "";
      this.error.rclone.configuration_file = "";
      let isValidationOk = true;
      if (this.rclone.configuration_source === "paste") {
        if (!this.rclone.rclone_conf_secret) {
          this.error.rclone.rclone_conf_secret = this.$t("common.required");
          if (isValidationOk) {
            this.focusElement("rclone_conf_secret");
            isValidationOk = false;
          }
        }
      } else {
        if (
          !this.rclone.configuration_uploaded_file ||
          this.rclone.configuration_uploaded_file.length === 0
        ) {
          this.error.rclone.configuration_file = this.$t("common.required");
          isValidationOk = false;
        }
      }
      if (!this.name) {
        this.error.name = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("name");
          isValidationOk = false;
        }
      }
      return isValidationOk;
    },
    validateAddSambaRepository() {
      this.error.name = "";
      this.error.url = "";
      this.error.repoConnection = "";
      this.error.smb.smb_host = "";
      this.error.smb.smb_user = "";
      this.error.smb.smb_pass = "";
      this.error.smb.smb_domain = "";
      let isValidationOk = true;
      if (!this.url) {
        this.error.url = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("url");
          isValidationOk = false;
        }
      } else if (this.url.includes(" ")) {
        this.error.url = this.$t("backup.invalid_url");
        if (isValidationOk) {
          this.focusElement("url");
          isValidationOk = false;
        }
      }
      if (!this.smb.smb_host) {
        this.error.smb.smb_host = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("smb_host");
          isValidationOk = false;
        }
      }
      if (!this.smb.smb_user) {
        this.error.smb.smb_user = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("smb_user");
          isValidationOk = false;
        }
      }
      if (!this.smb.smb_domain) {
        this.error.smb.smb_domain = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("smb_domain");
          isValidationOk = false;
        }
      }
      if (!this.smb.smb_pass) {
        this.error.smb.smb_pass = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("smb_pass");
          isValidationOk = false;
        }
      }
      if (!this.name) {
        this.error.name = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("name");
          isValidationOk = false;
        }
      }
      return isValidationOk;
    },
    validateAddClusterRepository() {
      this.error.name = "";
      this.error.url = "";
      this.error.repoConnection = "";
      let isValidationOk = true;
      if (!this.url) {
        this.error.url = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("url");
          isValidationOk = false;
        }
      } else if (this.url.includes(" ")) {
        this.error.url = this.$t("backup.invalid_url");
        if (isValidationOk) {
          this.focusElement("url");
          isValidationOk = false;
        }
      }
      if (!this.name) {
        this.error.name = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("name");
          isValidationOk = false;
        }
      }
      return isValidationOk;
    },
    validateAddBackupRepository() {
      switch (this.selectedProvider) {
        case "backblaze":
          return this.validateAddBackblazeRepository();
        case "rclone":
          return this.validateAddRcloneRepository();
        case "aws":
          return this.validateAmazonS3Repository();
        case "genericS3":
          return this.validateAddGenericS3Repository();
        case "smb":
          return this.validateAddSambaRepository();
        case "cluster":
          return this.validateAddClusterRepository();
      }
    },
    async addBackupRepository() {
      if (!this.validateAddBackupRepository()) {
        return;
      }
      this.error.addBackupRepository = "";
      this.loading.addBackupRepository = true;
      const taskAction = "add-backup-repository";
      this.$root.$off(taskAction + "-validation-failed");
      this.$root.$once(
        taskAction + "-validation-failed",
        this.addBackupRepositoryValidationFailed
      );
      this.$root.$once(
        taskAction + "-completed",
        this.addBackupRepositoryCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {
            name: this.name,
            provider:
              this.selectedProvider == "genericS3"
                ? "generic-s3"
                : this.selectedProvider,
            url: this.selectedProviderPrefix + this.url,
            parameters: this.buildRepositoryParameters(),
            password: this.password,
          },
          extra: {
            title: this.$t("action." + taskAction),
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.addBackupRepository = this.getErrorMessage(err);
        return;
      }
    },
    getValidationErrorField(validationError) {
      const fieldTokens = validationError.field.split(".");
      return last(fieldTokens);
    },
    addBackupRepositoryValidationFailed(validationErrors) {
      this.loading.addBackupRepository = false;
      let focusAlreadySet = false;
      for (const validationError of validationErrors) {
        let field = this.getValidationErrorField(validationError);
        const connectionErrors = [
          "backup_repository_not_accessible",
          "no_read_permission",
          "no_write_permission",
          "no_delete_permission",
        ];
        if (connectionErrors.includes(validationError.error)) {
          this.error.repoConnection = validationError.error;
        } else if (field !== "(root)" && field !== "provider") {
          const errorField =
            this.selectedProvider === "rclone" && field === "basepath"
              ? "base_path"
              : this.selectedProvider === "rclone" && field === "parameters"
              ? "rclone_conf_secret"
              : field;
          const refField =
            this.selectedProvider === "rclone" && field === "basepath"
              ? "rclone_base_path"
              : this.selectedProvider === "rclone" && field === "parameters"
              ? "rclone_conf_secret"
              : field;
          const translationKey =
            this.selectedProvider === "rclone" &&
            errorField === "rclone_conf_secret"
              ? "rclone_conf_error"
              : validationError.error;
          const displayField =
            this.selectedProvider === "rclone" &&
            errorField === "rclone_conf_secret" &&
            this.rclone.configuration_source === "upload"
              ? "configuration_file"
              : errorField;
          if (
            displayField === "name" ||
            displayField === "url" ||
            displayField === "repoConnection"
          ) {
            this.error[displayField] = this.$t("backup." + translationKey);
          } else {
            this.error[this.selectedProvider][displayField] = this.$t(
              "backup." + translationKey
            );
          }
          if (!focusAlreadySet) {
            this.$nextTick(() => {
              const el = this.$refs[refField];
              if (el) {
                if (typeof el.focus === "function") {
                  el.focus();
                } else if (el.$el) {
                  const focusable = el.$el.querySelector("input, textarea");
                  if (focusable) focusable.focus();
                }
              }
            });
            focusAlreadySet = true;
          }
        }
      }
    },
    addBackupRepositoryCompleted() {
      this.loading.addBackupRepository = false;
      this.$emit("repoCreated");
      this.$emit("hide");
    },
    async listBackupEndpoints() {
      this.loading.listBackupEndpoints = true;
      this.error.listBackupEndpoints = "";
      const taskAction = "list-cluster-backup-endpoints";
      this.$root.$once(
        taskAction + "-completed",
        this.listBackupEndpointsCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.listBackupEndpoints = this.getErrorMessage(err);
        return;
      }
    },
    listBackupEndpointsCompleted(taskContext, taskResult) {
      let endpoints = taskResult.output.endpoints.sort(
        this.sortByProperty("ui_label")
      );
      function convertToObject(endpoints) {
        return {
          name: endpoints.ui_label,
          label: endpoints.ui_label,
          value: endpoints.url,
        };
      }
      this.endpoints = endpoints.map(convertToObject);
      this.setUrlFromSelectedNode();
      this.loading.listBackupEndpoints = false;
    },
    onSelectNode(node) {
      this.selectedNode = node;
      this.setUrlFromSelectedNode();
    },
    getEndpointLabelForNode(node) {
      return node.ui_name ? node.ui_name : `Node ${node.id}`;
    },
    setUrlFromSelectedNode() {
      if (!this.selectedNode) {
        this.url = "";
        return;
      }
      const endpointLabel = this.getEndpointLabelForNode(this.selectedNode);
      const endpoint = this.endpoints.find(
        (item) => item.label === endpointLabel || item.name === endpointLabel
      );
      this.url = endpoint ? endpoint.value : "";
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
::v-deep .bx--file {
  width: 100%;
  max-width: 38rem;
}
::v-deep .bx--file__drop-container {
  width: 100%;
  max-width: 38rem;
}
.file-uploader-error ::v-deep .bx--file__drop-container {
  outline: 2px solid $danger-01;
  outline-offset: -2px;
}
.file-uploader-error .validation-failed-invalid-message {
  margin-top: -0.75rem;
  margin-bottom: 0.75rem;
  color: $danger-01;
  font-size: 0.75rem;
}
::v-deep .bx--file-container {
  width: 100%;
  max-width: 38rem;
}
::v-deep .bx--file__selected-file {
  background-color: #ffffff;
  max-width: 38rem;
}
.provider-card {
  min-height: 9rem;
  padding-right: $spacing-05;
}
.provider-card-content {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.provider-icon {
  width: 3rem;
  height: 3rem;
  margin-bottom: $spacing-06;
}
.provider-icon img {
  width: 100%;
  height: 100%;
}
</style>
</file>

<file path="core/ui/src/components/backup/BackupDetailsModal.vue">
<template>
  <NsModal size="default" :visible="isShown" @modal-hidden="$emit('hide')">
    <template slot="title">{{ $t("backup.backup_details") }}</template>
    <template slot="content">
      <div class="key-value-setting">
        <span class="label">{{ $t("backup.name") }}</span>
        <span class="value">{{ backup.name }}</span>
      </div>
      <div class="key-value-setting">
        <span class="label">{{ $t("backup.repository") }}</span>
        <span class="value">{{ backup.repoName }}</span>
      </div>
      <div class="key-value-setting">
        <span class="label">{{ $t("backup.schedule") }}</span>
        <span class="value">
          {{ getBackupScheduleDescription(backup.schedule) }}
        </span>
      </div>
      <div class="key-value-setting">
        <span class="label">{{ $t("backup.retention") }}</span>
        <span class="value">{{
          $tc("backup.num_backup_snapshots", backup.retention, {
            num: backup.retention,
          })
        }}</span>
      </div>
      <div class="setting instances key-value-setting">
        <span class="label">{{
          $tc("backup.applications", instances.length)
        }}</span>
        <div class="instance-list">
          <div v-if="instances.length === 0">-</div>
          <div v-else v-for="instance in instances" :key="instance.module_id">
            <cv-interactive-tooltip
              alignment="center"
              direction="top"
              class="tooltip-with-text-trigger"
            >
              <template slot="trigger">
                <NsSvg
                  v-if="instance.status && instance.status.success == true"
                  :svg="CheckmarkFilled16"
                  class="ns-success backup-status-icon"
                />
                <NsSvg
                  v-else-if="
                    instance.status && instance.status.success == false
                  "
                  :svg="ErrorFilled16"
                  class="ns-error backup-status-icon"
                />
                <NsSvg
                  v-else
                  :svg="Warning16"
                  class="ns-warning backup-status-icon"
                />
                <span>
                  {{
                    instance.ui_name
                      ? instance.ui_name + " (" + instance.module_id + ")"
                      : instance.module_id
                  }}
                </span>
              </template>
              <template slot="content">
                <h5 class="last-backup">{{ $t("backup.last_backup") }}</h5>
                <div class="key-value-setting narrow">
                  <span class="label">
                    {{ $t("backup.status") }}
                  </span>
                  <span class="value status">
                    <span
                      v-if="instance.status && instance.status.success == true"
                      class="ns-success-dark-bg"
                    >
                      {{ $t("common.success") }}
                    </span>
                    <span
                      v-else-if="
                        instance.status && instance.status.success == false
                      "
                      class="ns-error-dark-bg"
                    >
                      {{ $t("error.error") }}
                    </span>
                    <span v-else class="ns-warning-dark-bg">
                      {{ $t("backup.backup_has_not_run_yet") }}
                    </span>
                  </span>
                </div>
                <div class="key-value-setting narrow">
                  <span class="label">
                    {{ $t("backup.completed") }}
                  </span>
                  <span class="value">
                    <span v-if="instance.status && instance.status.end">
                      {{
                        (instance.status.end * 1000)
                          | date("yyyy-MM-dd HH:mm:ss")
                      }}
                    </span>
                    <span v-else>-</span>
                  </span>
                </div>
                <div class="key-value-setting narrow">
                  <span class="label">
                    {{ $t("backup.duration") }}
                  </span>
                  <span class="value">
                    <span
                      v-if="
                        instance.status &&
                        instance.status.end &&
                        instance.status.start
                      "
                    >
                      {{
                        (instance.status.end - instance.status.start)
                          | secondsFormat
                      }}
                    </span>
                    <span v-else>-</span>
                  </span>
                </div>
                <div class="key-value-setting narrow">
                  <span class="label">
                    {{ $t("backup.total_size") }}
                  </span>
                  <span class="value">
                    <span v-if="instance.status && instance.status.total_size">
                      {{ instance.status.total_size | byteFormat }}
                    </span>
                    <span v-else>-</span>
                  </span>
                </div>
                <div class="key-value-setting narrow">
                  <span class="label">
                    {{ $t("backup.total_file_count") }}
                  </span>
                  <span class="value">
                    <span
                      v-if="instance.status && instance.status.total_file_count"
                    >
                      {{ instance.status.total_file_count }}
                    </span>
                    <span v-else>-</span>
                  </span>
                </div>
              </template>
            </cv-interactive-tooltip>
          </div>
        </div>
      </div>
    </template>
    <template slot="primary-button">{{ $t("common.close") }}</template>
  </NsModal>
</template>
⋮----
<template slot="title">{{ $t("backup.backup_details") }}</template>
<template slot="content">
      <div class="key-value-setting">
        <span class="label">{{ $t("backup.name") }}</span>
        <span class="value">{{ backup.name }}</span>
      </div>
      <div class="key-value-setting">
        <span class="label">{{ $t("backup.repository") }}</span>
        <span class="value">{{ backup.repoName }}</span>
      </div>
      <div class="key-value-setting">
        <span class="label">{{ $t("backup.schedule") }}</span>
        <span class="value">
          {{ getBackupScheduleDescription(backup.schedule) }}
        </span>
      </div>
      <div class="key-value-setting">
        <span class="label">{{ $t("backup.retention") }}</span>
        <span class="value">{{
          $tc("backup.num_backup_snapshots", backup.retention, {
            num: backup.retention,
          })
        }}</span>
      </div>
      <div class="setting instances key-value-setting">
        <span class="label">{{
          $tc("backup.applications", instances.length)
        }}</span>
        <div class="instance-list">
          <div v-if="instances.length === 0">-</div>
          <div v-else v-for="instance in instances" :key="instance.module_id">
            <cv-interactive-tooltip
              alignment="center"
              direction="top"
              class="tooltip-with-text-trigger"
            >
              <template slot="trigger">
                <NsSvg
                  v-if="instance.status && instance.status.success == true"
                  :svg="CheckmarkFilled16"
                  class="ns-success backup-status-icon"
                />
                <NsSvg
                  v-else-if="
                    instance.status && instance.status.success == false
                  "
                  :svg="ErrorFilled16"
                  class="ns-error backup-status-icon"
                />
                <NsSvg
                  v-else
                  :svg="Warning16"
                  class="ns-warning backup-status-icon"
                />
                <span>
                  {{
                    instance.ui_name
                      ? instance.ui_name + " (" + instance.module_id + ")"
                      : instance.module_id
                  }}
                </span>
              </template>
              <template slot="content">
                <h5 class="last-backup">{{ $t("backup.last_backup") }}</h5>
                <div class="key-value-setting narrow">
                  <span class="label">
                    {{ $t("backup.status") }}
                  </span>
                  <span class="value status">
                    <span
                      v-if="instance.status && instance.status.success == true"
                      class="ns-success-dark-bg"
                    >
                      {{ $t("common.success") }}
                    </span>
                    <span
                      v-else-if="
                        instance.status && instance.status.success == false
                      "
                      class="ns-error-dark-bg"
                    >
                      {{ $t("error.error") }}
                    </span>
                    <span v-else class="ns-warning-dark-bg">
                      {{ $t("backup.backup_has_not_run_yet") }}
                    </span>
                  </span>
                </div>
                <div class="key-value-setting narrow">
                  <span class="label">
                    {{ $t("backup.completed") }}
                  </span>
                  <span class="value">
                    <span v-if="instance.status && instance.status.end">
                      {{
                        (instance.status.end * 1000)
                          | date("yyyy-MM-dd HH:mm:ss")
                      }}
                    </span>
                    <span v-else>-</span>
                  </span>
                </div>
                <div class="key-value-setting narrow">
                  <span class="label">
                    {{ $t("backup.duration") }}
                  </span>
                  <span class="value">
                    <span
                      v-if="
                        instance.status &&
                        instance.status.end &&
                        instance.status.start
                      "
                    >
                      {{
                        (instance.status.end - instance.status.start)
                          | secondsFormat
                      }}
                    </span>
                    <span v-else>-</span>
                  </span>
                </div>
                <div class="key-value-setting narrow">
                  <span class="label">
                    {{ $t("backup.total_size") }}
                  </span>
                  <span class="value">
                    <span v-if="instance.status && instance.status.total_size">
                      {{ instance.status.total_size | byteFormat }}
                    </span>
                    <span v-else>-</span>
                  </span>
                </div>
                <div class="key-value-setting narrow">
                  <span class="label">
                    {{ $t("backup.total_file_count") }}
                  </span>
                  <span class="value">
                    <span
                      v-if="instance.status && instance.status.total_file_count"
                    >
                      {{ instance.status.total_file_count }}
                    </span>
                    <span v-else>-</span>
                  </span>
                </div>
              </template>
            </cv-interactive-tooltip>
          </div>
        </div>
      </div>
    </template>
⋮----
<span class="label">{{ $t("backup.name") }}</span>
<span class="value">{{ backup.name }}</span>
⋮----
<span class="label">{{ $t("backup.repository") }}</span>
<span class="value">{{ backup.repoName }}</span>
⋮----
<span class="label">{{ $t("backup.schedule") }}</span>
⋮----
{{ getBackupScheduleDescription(backup.schedule) }}
⋮----
<span class="label">{{ $t("backup.retention") }}</span>
<span class="value">{{
          $tc("backup.num_backup_snapshots", backup.retention, {
            num: backup.retention,
          })
        }}</span>
⋮----
<span class="label">{{
          $tc("backup.applications", instances.length)
        }}</span>
⋮----
<template slot="trigger">
                <NsSvg
                  v-if="instance.status && instance.status.success == true"
                  :svg="CheckmarkFilled16"
                  class="ns-success backup-status-icon"
                />
                <NsSvg
                  v-else-if="
                    instance.status && instance.status.success == false
                  "
                  :svg="ErrorFilled16"
                  class="ns-error backup-status-icon"
                />
                <NsSvg
                  v-else
                  :svg="Warning16"
                  class="ns-warning backup-status-icon"
                />
                <span>
                  {{
                    instance.ui_name
                      ? instance.ui_name + " (" + instance.module_id + ")"
                      : instance.module_id
                  }}
                </span>
              </template>
⋮----
{{
                    instance.ui_name
                      ? instance.ui_name + " (" + instance.module_id + ")"
                      : instance.module_id
                  }}
⋮----
<template slot="content">
                <h5 class="last-backup">{{ $t("backup.last_backup") }}</h5>
                <div class="key-value-setting narrow">
                  <span class="label">
                    {{ $t("backup.status") }}
                  </span>
                  <span class="value status">
                    <span
                      v-if="instance.status && instance.status.success == true"
                      class="ns-success-dark-bg"
                    >
                      {{ $t("common.success") }}
                    </span>
                    <span
                      v-else-if="
                        instance.status && instance.status.success == false
                      "
                      class="ns-error-dark-bg"
                    >
                      {{ $t("error.error") }}
                    </span>
                    <span v-else class="ns-warning-dark-bg">
                      {{ $t("backup.backup_has_not_run_yet") }}
                    </span>
                  </span>
                </div>
                <div class="key-value-setting narrow">
                  <span class="label">
                    {{ $t("backup.completed") }}
                  </span>
                  <span class="value">
                    <span v-if="instance.status && instance.status.end">
                      {{
                        (instance.status.end * 1000)
                          | date("yyyy-MM-dd HH:mm:ss")
                      }}
                    </span>
                    <span v-else>-</span>
                  </span>
                </div>
                <div class="key-value-setting narrow">
                  <span class="label">
                    {{ $t("backup.duration") }}
                  </span>
                  <span class="value">
                    <span
                      v-if="
                        instance.status &&
                        instance.status.end &&
                        instance.status.start
                      "
                    >
                      {{
                        (instance.status.end - instance.status.start)
                          | secondsFormat
                      }}
                    </span>
                    <span v-else>-</span>
                  </span>
                </div>
                <div class="key-value-setting narrow">
                  <span class="label">
                    {{ $t("backup.total_size") }}
                  </span>
                  <span class="value">
                    <span v-if="instance.status && instance.status.total_size">
                      {{ instance.status.total_size | byteFormat }}
                    </span>
                    <span v-else>-</span>
                  </span>
                </div>
                <div class="key-value-setting narrow">
                  <span class="label">
                    {{ $t("backup.total_file_count") }}
                  </span>
                  <span class="value">
                    <span
                      v-if="instance.status && instance.status.total_file_count"
                    >
                      {{ instance.status.total_file_count }}
                    </span>
                    <span v-else>-</span>
                  </span>
                </div>
              </template>
⋮----
<h5 class="last-backup">{{ $t("backup.last_backup") }}</h5>
⋮----
{{ $t("backup.status") }}
⋮----
{{ $t("common.success") }}
⋮----
{{ $t("error.error") }}
⋮----
{{ $t("backup.backup_has_not_run_yet") }}
⋮----
{{ $t("backup.completed") }}
⋮----
{{
                        (instance.status.end * 1000)
                          | date("yyyy-MM-dd HH:mm:ss")
                      }}
⋮----
{{ $t("backup.duration") }}
⋮----
{{
                        (instance.status.end - instance.status.start)
                          | secondsFormat
                      }}
⋮----
{{ $t("backup.total_size") }}
⋮----
{{ instance.status.total_size | byteFormat }}
⋮----
{{ $t("backup.total_file_count") }}
⋮----
{{ instance.status.total_file_count }}
⋮----
<template slot="primary-button">{{ $t("common.close") }}</template>
⋮----
<script>
import { UtilService, IconService } from "@nethserver/ns8-ui-lib";
export default {
  name: "BackupDetailsModal",
  mixins: [UtilService, IconService],
  props: {
    isShown: {
      type: Boolean,
      default: true,
    },
    backup: {
      type: Object,
      required: true,
    },
  },
  computed: {
    instances() {
      const backupInstances = [...this.backup.instances];
      return backupInstances.sort(this.sortByProperty("module_id"));
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
.instances {
  display: flex;
}
.instance-list {
  display: flex;
  flex-direction: column;
  row-gap: $spacing-04;
}
.instance-list div {
  display: flex;
  align-items: center;
}
.backup-status-icon {
  margin-right: $spacing-02;
  flex-shrink: 0;
}
.last-backup {
  margin-bottom: $spacing-05;
}
.status {
  font-weight: bold;
}
</style>
</file>

<file path="core/ui/src/components/backup/BackupInstanceSelector.vue">
<template>
  <div class="instance-selector">
    <NsInlineNotification
      v-if="isShownNotBackedUpNotification && selection == 'notBackedUp'"
      kind="info"
      :title="$t('backup.not_backed_up_instances_selected')"
      :showCloseButton="false"
    />
    <div class="toolbar">
      <NsDropdownAction kind="secondary" disabled>
        <template v-slot:trigger>{{
          $t("backup.select_by_category")
        }}</template>
        <cv-overflow-menu-item @click="selectAll">
          {{ $t("common.all") }}
        </cv-overflow-menu-item>
        <cv-overflow-menu-item @click="selectNone">
          {{ $t("common.none") }}
        </cv-overflow-menu-item>
        <cv-overflow-menu-item
          @click="selectNotBackedUp"
          :disabled="!instancesNotBackedUp.length"
        >
          {{ $t("backup.not_backed_up") }}
        </cv-overflow-menu-item>
        <cv-overflow-menu-item @click="selectCoreModules">
          {{ $tc("common.core_module_c", 2) }}
        </cv-overflow-menu-item>
      </NsDropdownAction>
      <span class="selection-info">{{
        $t("common.x_of_y_selected", {
          selected: numSelected,
          total: internalInstances.length,
        })
      }}</span>
    </div>
    <div class="search">
      <cv-search
        :label="$t('backup.search_instances')"
        :placeholder="$t('backup.search_instances')"
        :clear-aria-label="$t('common.clear_search')"
        v-model.trim="searchQuery"
        v-debounce="searchInstance"
        @input="onSearchInput"
        class="search-input"
        :disabled="loading"
        ref="search"
      >
      </cv-search>
    </div>
    <div class="instance-list">
      <cv-tile v-if="loading" light>
        <cv-skeleton-text :paragraph="true" :line-count="8"></cv-skeleton-text>
      </cv-tile>
      <NsEmptyState
        v-else-if="!instancesToDisplay.length"
        :title="$t('common.no_search_results')"
        :animationData="GhostLottie"
        animationTitle="ghost"
        :loop="1"
      >
        <template #description>
          <div>{{ $t("common.no_search_results_description") }}</div>
        </template>
      </NsEmptyState>
      <cv-tile
        v-else
        light
        v-for="instance of instancesToDisplay"
        :key="'tile-' + instance.id"
        class="instance-tile"
      >
        <label class="instance-label">
          <cv-checkbox
            v-model="selectedList"
            :value="instance.id"
            hide-label
            class="checkbox-instance"
            :id="instance.id"
          />
          <div class="app-icon">
            <img
              :src="
                instance.logo
                  ? instance.logo
                  : require('@/assets/module_default_logo.png')
              "
              :alt="instance.id + ' logo'"
            />
          </div>
          <div>
            <span>{{ getInstanceLabel(instance) }} </span>
          </div>
          <NsTag
            v-if="instance.flags.includes('core_module')"
            kind="gray"
            size="sm"
            :label="$t('common.core_app')"
            class="core-module-tag"
          />
        </label>
      </cv-tile>
    </div>
  </div>
</template>
⋮----
<template v-slot:trigger>{{
          $t("backup.select_by_category")
        }}</template>
⋮----
{{ $t("common.all") }}
⋮----
{{ $t("common.none") }}
⋮----
{{ $t("backup.not_backed_up") }}
⋮----
{{ $tc("common.core_module_c", 2) }}
⋮----
<span class="selection-info">{{
        $t("common.x_of_y_selected", {
          selected: numSelected,
          total: internalInstances.length,
        })
      }}</span>
⋮----
<template #description>
          <div>{{ $t("common.no_search_results_description") }}</div>
        </template>
⋮----
<div>{{ $t("common.no_search_results_description") }}</div>
⋮----
<span>{{ getInstanceLabel(instance) }} </span>
⋮----
<script>
import { UtilService, LottieService } from "@nethserver/ns8-ui-lib";
import _isEqual from "lodash/isEqual";
import _cloneDeep from "lodash/cloneDeep";
export default {
  name: "BackupInstanceSelector",
  components: {},
  mixins: [UtilService, LottieService],
  props: {
    instances: {
      type: Array,
      required: true,
    },
    selection: {
      type: [String, Array],
      default: "",
    },
    instancesNotBackedUp: {
      type: Array,
      default: () => [],
    },
    loading: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      internalInstances: [],
      selectedList: [],
      searchQuery: "",
      searchResults: [],
      searchFields: ["id", "module", "ui_name"],
      isSearchActive: false,
    };
  },
  computed: {
    numSelected() {
      return this.selectedList.length;
    },
    isShownNotBackedUpNotification() {
      return _isEqual(this.selectedList, this.idsNotBackedUp);
    },
    idsNotBackedUp() {
      return this.instancesNotBackedUp.map((i) => i.id);
    },
    instancesToDisplay() {
      if (this.isSearchActive) {
        return this.searchResults;
      } else {
        return this.internalInstances;
      }
    },
  },
  watch: {
    instances: function () {
      const instances = _cloneDeep(this.instances);
      this.internalInstances = instances.filter((i) => {
        return !i.flags.includes("no_data_backup");
      });
      this.selectedList = [];
      this.updateSelection();
    },
    selection: function () {
      this.updateSelection();
    },
    instancesNotBackedUp: function () {
      this.updateSelection();
    },
    selectedList: function () {
      this.$emit("select", this.selectedList);
    },
  },
  methods: {
    selectAll() {
      this.selectedList = [];
      for (const instance of this.internalInstances) {
        this.selectedList.push(instance.id);
      }
    },
    selectNone() {
      this.selectedList = [];
    },
    selectNotBackedUp() {
      this.selectedList = [];
      for (const id of this.idsNotBackedUp) {
        this.selectedList.push(id);
      }
    },
    selectCoreModules() {
      this.selectedList = [];
      for (const instance of this.internalInstances) {
        if (instance.flags.includes("core_module")) {
          this.selectedList.push(instance.id);
        }
      }
    },
    selectInstances() {
      this.selectedList = [];
      for (const instance of this.selection) {
        const instanceId = instance.module_id
          ? instance.module_id
          : instance.id;
        this.selectedList.push(instanceId);
      }
    },
    getInstanceLabel(instance) {
      return instance.ui_name
        ? instance.ui_name + " (" + instance.id + ")"
        : instance.id;
    },
    updateSelection() {
      if (typeof this.selection == "string") {
        switch (this.selection) {
          case "all":
            this.selectAll();
            break;
          case "none":
          case "":
            this.selectNone();
            break;
          case "notBackedUp":
            this.selectNotBackedUp();
            break;
          case "core":
            this.selectCoreModules();
            break;
        }
      } else {
        this.selectInstances();
      }
    },
    searchInstance() {
      const cleanRegex = /[^a-zA-Z0-9]/g;
      const queryText = this.searchQuery.replace(cleanRegex, "");
      // empty search
      if (queryText.length == 0) {
        this.isSearchActive = false;
        return;
      }
      // show search results
      this.isSearchActive = true;
      // search
      this.searchResults = this.internalInstances.filter((instance) => {
        // compare query text with all search fields of option
        return this.searchFields.some((searchField) => {
          const searchValue = instance[searchField];
          if (searchValue) {
            return new RegExp(queryText, "i").test(
              searchValue.replace(cleanRegex, "")
            );
          }
        });
      }, this);
    },
    onSearchInput() {
      // needed to manage clear search button
      if (!this.searchQuery.length) {
        this.searchInstance();
      }
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
.instance-selector {
  display: flex;
  flex-direction: column;
}
.toolbar {
  display: flex;
  flex-direction: row;
  margin-bottom: $spacing-05;
}
.search-input {
  margin-bottom: $spacing-05;
}
.selection-info {
  margin-left: $spacing-07;
}
.instance-list {
  overflow-y: auto;
  height: 18rem;
}
.instance-tile {
  margin-bottom: 0;
  border-bottom: 2px solid $ui-01;
}
.instance-label {
  display: flex;
  align-items: center;
}
.checkbox-instance {
  display: inline-block;
  margin-top: 0 !important;
  margin-bottom: 0;
  margin-right: $spacing-05;
  flex-grow: 0;
}
.app-icon {
  display: inline-block;
  width: 2rem;
  height: 2rem;
  flex-shrink: 0;
  margin-right: $spacing-03;
}
.app-icon img {
  width: 100%;
  height: 100%;
}
.core-module-tag {
  margin-left: auto;
}
</style>
⋮----
<style lang="scss">
@import "../../styles/carbon-utils";
.search-input .bx--text-input__field-wrapper,
.search-input .bx--text-input {
  max-width: 100% !important;
}
</style>
</file>

<file path="core/ui/src/components/backup/BackupPasswordModal.vue">
<template>
  <NsModal
    size="default"
    :visible="isShown"
    @modal-hidden="$emit('hide')"
    @primary-click="setBackupPassword"
    :primary-button-disabled="!clusterPassword || !confirmRead"
  >
    <template slot="title">{{
      $t("backup.set_cluster_backup_password")
    }}</template>
    <template slot="content">
      <cv-form @submit.prevent="!clusterPassword || !confirmRead">
        <NsInlineNotification
          kind="info"
          :description="$t('backup.cluster_backup_password_info_description')"
          :showCloseButton="false"
        />
        <NsTextInput
          v-model="clusterPassword"
          type="password"
          :label="$t('backup.password')"
          :passwordHideLabel="$t('password.hide_password')"
          :passwordShowLabel="$t('password.show_password')"
          data-modal-primary-focus
          class="confirm-password"
          ref="confirmPassword"
        />
        <NsCheckbox
          :label="$t('backup.i_have_stored_encryption_password')"
          v-model="confirmRead"
          value="confirmRead"
          class="mg-top-lg"
        />
      </cv-form>
    </template>
    <template slot="secondary-button">{{ $t("common.cancel") }}</template>
    <template slot="primary-button">{{
      $t("backup.set_cluster_backup_password")
    }}</template>
  </NsModal>
</template>
⋮----
<template slot="title">{{
      $t("backup.set_cluster_backup_password")
    }}</template>
<template slot="content">
      <cv-form @submit.prevent="!clusterPassword || !confirmRead">
        <NsInlineNotification
          kind="info"
          :description="$t('backup.cluster_backup_password_info_description')"
          :showCloseButton="false"
        />
        <NsTextInput
          v-model="clusterPassword"
          type="password"
          :label="$t('backup.password')"
          :passwordHideLabel="$t('password.hide_password')"
          :passwordShowLabel="$t('password.show_password')"
          data-modal-primary-focus
          class="confirm-password"
          ref="confirmPassword"
        />
        <NsCheckbox
          :label="$t('backup.i_have_stored_encryption_password')"
          v-model="confirmRead"
          value="confirmRead"
          class="mg-top-lg"
        />
      </cv-form>
    </template>
<template slot="secondary-button">{{ $t("common.cancel") }}</template>
<template slot="primary-button">{{
      $t("backup.set_cluster_backup_password")
    }}</template>
⋮----
<script>
import {
  UtilService,
  TaskService,
  IconService,
  DateTimeService,
} from "@nethserver/ns8-ui-lib";
import to from "await-to-js";
export default {
  name: "PasswordBackupModal",
  mixins: [UtilService, TaskService, IconService, DateTimeService],
  props: {
    isShown: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      name: "",
      confirmRead: false,
      loading: {
        setBackupPassword: false,
      },
      clusterPassword: "",
      error: {
        setBackupPassword: "",
      },
    };
  },
  watch: {
    isShown: function () {
      if (this.isShown) {
        this.confirmRead = false;
        this.clusterPassword = "";
      }
    },
  },
  methods: {
    async setBackupPassword() {
      this.loading.downloadClusterBackup = true;
      const taskAction = "download-cluster-backup";
      this.$root.$off(taskAction + "-aborted");
      this.$root.$once(taskAction + "-aborted", this.setBackupPasswordAborted);
      this.$root.$off(taskAction + "-completed");
      this.$root.$once(
        taskAction + "-completed",
        this.setBackupPasswordCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: { password: this.clusterPassword },
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
          },
        })
      );
      const err = res[0];
      this.$emit("hide");
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.setBackupPassword = this.getErrorMessage(err);
        return;
      }
    },
    setBackupPasswordAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.loading.setBackupPassword = false;
    },
    setBackupPasswordCompleted() {
      this.loading.setBackupPassword = false;
      this.$emit("password-set");
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
</style>
</file>

<file path="core/ui/src/components/backup/CreateOrEditBackupModal.vue">
<template>
  <div class="create-backup-modal">
    <NsWizard
      size="default"
      :visible="isShown"
      :cancelLabel="$t('common.cancel')"
      :previousLabel="$t('common.previous')"
      :nextLabel="nextButtonLabel"
      :isPreviousDisabled="isFirstStep || loading.addBackup"
      :isNextDisabled="isNextButtonDisabled"
      :isNextLoading="loading.addBackup"
      @modal-hidden="$emit('hide')"
      @cancel="$emit('hide')"
      @previousStep="previousStep"
      @nextStep="nextStep"
      :isLastStep="isLastStep"
    >
      <template slot="title">{{
        isEditing ? $t("backup.edit_backup") : $t("backup.schedule_backup")
      }}</template>
      <template slot="content">
        <cv-form>
          <div v-show="step == 'instances'">
            <BackupInstanceSelector
              :instances="installedModules"
              :selection="isEditing ? backup.instances : instanceSelection"
              :instancesNotBackedUp="instancesNotBackedUp"
              :loading="loading.listInstalledModules"
              @select="onSelectInstances"
            />
          </div>
          <div v-show="step == 'repository'">
            <div class="mg-bottom-md">
              {{ $t("backup.choose_destination_repository") }}
            </div>
            <cv-grid class="no-padding">
              <cv-row>
                <cv-column
                  v-for="repo in internalRepositories"
                  :key="'col-' + repo.id"
                  :md="4"
                >
                  <NsTile
                    :light="true"
                    kind="selectable"
                    :value="repo.id"
                    :footerIcon="DataBase20"
                    v-model="repo.selected"
                    @click="deselectOtherRepos(repo)"
                    class="min-height-card"
                  >
                    <h6>
                      {{ repo.name }}
                    </h6>
                    <div class="mg-top-md">
                      {{ $t("backup." + repo.provider) }}
                    </div>
                    <div class="mg-top-sm ellipsis">
                      {{ repo.url }}
                    </div>
                  </NsTile>
                </cv-column>
              </cv-row>
            </cv-grid>
          </div>
          <div v-show="step == 'settings'">
            <cv-grid class="schedule-container no-padding">
              <cv-row>
                <cv-column :md="2" :max="4">
                  <cv-select
                    v-model="schedule.interval"
                    :label="$t('backup.schedule')"
                    :disabled="loading.addBackup || loading.alterBackup"
                    :invalid-message="$t(error.schedule)"
                    class="schedule-interval"
                  >
                    <cv-select-option value="hourly">
                      {{ $t("backup.hourly") }}
                    </cv-select-option>
                    <cv-select-option value="daily">
                      {{ $t("backup.daily") }}
                    </cv-select-option>
                    <cv-select-option value="weekly">
                      {{ $t("backup.weekly") }}
                    </cv-select-option>
                    <cv-select-option value="monthly">
                      {{ $t("backup.monthly") }}
                    </cv-select-option>
                  </cv-select>
                </cv-column>
                <cv-column
                  v-if="schedule.interval == 'hourly'"
                  :md="2"
                  :max="4"
                >
                  <cv-text-input
                    :label="$t('backup.minute')"
                    v-model.trim="schedule.minute"
                    type="number"
                    min="0"
                    max="59"
                    :disabled="loading.addBackup || loading.alterBackup"
                    ref="schedule-minute"
                  >
                  </cv-text-input>
                </cv-column>
                <cv-column v-if="schedule.interval == 'daily'" :md="2" :max="4">
                  <NsTimePicker
                    hideClearButton
                    v-model="schedule.time"
                    :label="$t('backup.at')"
                  ></NsTimePicker>
                </cv-column>
                <template v-if="schedule.interval == 'weekly'">
                  <cv-column :md="2" :max="4">
                    <cv-select
                      v-model="schedule.weekDay"
                      :label="$t('backup.on')"
                      :disabled="loading.addBackup || loading.alterBackup"
                    >
                      <cv-select-option value="monday">
                        {{ $t("calendar.monday") }}
                      </cv-select-option>
                      <cv-select-option value="tuesday">
                        {{ $t("calendar.tuesday") }}
                      </cv-select-option>
                      <cv-select-option value="wednesday">
                        {{ $t("calendar.wednesday") }}
                      </cv-select-option>
                      <cv-select-option value="thursday">
                        {{ $t("calendar.thursday") }}
                      </cv-select-option>
                      <cv-select-option value="friday">
                        {{ $t("calendar.friday") }}
                      </cv-select-option>
                      <cv-select-option value="saturday">
                        {{ $t("calendar.saturday") }}
                      </cv-select-option>
                      <cv-select-option value="sunday">
                        {{ $t("calendar.sunday") }}
                      </cv-select-option>
                    </cv-select>
                  </cv-column>
                  <cv-column :md="2" :max="4">
                    <NsTimePicker
                      hideClearButton
                      v-model="schedule.time"
                      :label="$t('backup.at')"
                    ></NsTimePicker>
                  </cv-column>
                </template>
                <template v-if="schedule.interval == 'monthly'">
                  <cv-column :md="2" :max="4">
                    <cv-text-input
                      :label="$t('backup.on_day')"
                      v-model.trim="schedule.monthDay"
                      type="number"
                      min="1"
                      max="31"
                      :disabled="loading.addBackup || loading.alterBackup"
                    >
                    </cv-text-input>
                  </cv-column>
                  <cv-column :md="2" :max="4">
                    <NsTimePicker
                      hideClearButton
                      v-model="schedule.time"
                      :label="$t('backup.at')"
                    ></NsTimePicker>
                  </cv-column>
                </template>
                <cv-column
                  v-if="schedule.interval == 'custom'"
                  :md="6"
                  :max="12"
                >
                  <NsTextInput
                    v-model.trim="schedule.custom"
                    :label="$t('backup.calendar_event_expression')"
                    :invalid-message="$t(error.schedule)"
                    :disabled="loading.addBackup || loading.alterBackup"
                    tooltipAlignment="center"
                    tooltipDirection="bottom"
                    ref="schedule-custom"
                  >
                    <template #tooltip>
                      <div class="mg-bottom-sm">
                        {{ $t("backup.custom_schedule_tooltip_description") }}
                      </div>
                      <div class="mg-bottom-sm">
                        {{ $t("backup.custom_schedule_tooltip_more_info") }}
                        <cv-link
                          href="https://www.freedesktop.org/software/systemd/man/systemd.time.html#Calendar%20Events"
                          target="_blank"
                        >
                          {{
                            $t(
                              "backup.custom_schedule_tooltip_systemd_time_documentation"
                            )
                          }}
                        </cv-link>
                      </div>
                    </template>
                  </NsTextInput>
                </cv-column>
              </cv-row>
              <cv-row
                v-if="schedule.interval !== 'custom'"
                class="mg-bottom-xlg"
              >
                <cv-column class="schedule-description">
                  {{ getBackupScheduleDescription(schedule) }}
                </cv-column>
              </cv-row>
              <cv-row>
                <cv-column :md="2" :max="4">
                  <NsTextInput
                    :label="$t('backup.retention')"
                    v-model.trim="retention"
                    type="number"
                    min="1"
                    :helper-text="$t('backup.backup_snapshots')"
                    :invalid-message="$t(error.retention)"
                    :disabled="loading.addBackup || loading.alterBackup"
                    tooltipAlignment="end"
                    tooltipDirection="right"
                    ref="retention"
                    class="retention"
                  >
                    <template #tooltip>{{
                      $t("backup.retention_tooltip")
                    }}</template>
                  </NsTextInput>
                </cv-column>
              </cv-row>
            </cv-grid>
          </div>
          <div v-show="step == 'name'">
            <cv-text-input
              :label="$t('backup.backup_name')"
              v-model.trim="name"
              :helper-text="$t('backup.backup_name_helper')"
              :invalid-message="$t(error.name)"
              :disabled="loading.addBackup || loading.alterBackup"
              class="mg-bottom-xlg"
              ref="name"
            >
            </cv-text-input>
            <cv-checkbox
              :label="$t('backup.run_backup_now')"
              v-model="runBackupOnFinish"
              :disabled="loading.addBackup || loading.alterBackup"
              value="checkRunBackupOnFinish"
            />
            <NsInlineNotification
              v-if="error.addBackup"
              kind="error"
              :title="$t('action.add-backup')"
              :description="error.addBackup"
              :showCloseButton="false"
            />
            <NsInlineNotification
              v-if="error.alterBackup"
              kind="error"
              :title="$t('action.alter-backup')"
              :description="error.alterBackup"
              :showCloseButton="false"
            />
          </div>
        </cv-form>
      </template>
    </NsWizard>
  </div>
</template>
⋮----
<template slot="title">{{
        isEditing ? $t("backup.edit_backup") : $t("backup.schedule_backup")
      }}</template>
<template slot="content">
        <cv-form>
          <div v-show="step == 'instances'">
            <BackupInstanceSelector
              :instances="installedModules"
              :selection="isEditing ? backup.instances : instanceSelection"
              :instancesNotBackedUp="instancesNotBackedUp"
              :loading="loading.listInstalledModules"
              @select="onSelectInstances"
            />
          </div>
          <div v-show="step == 'repository'">
            <div class="mg-bottom-md">
              {{ $t("backup.choose_destination_repository") }}
            </div>
            <cv-grid class="no-padding">
              <cv-row>
                <cv-column
                  v-for="repo in internalRepositories"
                  :key="'col-' + repo.id"
                  :md="4"
                >
                  <NsTile
                    :light="true"
                    kind="selectable"
                    :value="repo.id"
                    :footerIcon="DataBase20"
                    v-model="repo.selected"
                    @click="deselectOtherRepos(repo)"
                    class="min-height-card"
                  >
                    <h6>
                      {{ repo.name }}
                    </h6>
                    <div class="mg-top-md">
                      {{ $t("backup." + repo.provider) }}
                    </div>
                    <div class="mg-top-sm ellipsis">
                      {{ repo.url }}
                    </div>
                  </NsTile>
                </cv-column>
              </cv-row>
            </cv-grid>
          </div>
          <div v-show="step == 'settings'">
            <cv-grid class="schedule-container no-padding">
              <cv-row>
                <cv-column :md="2" :max="4">
                  <cv-select
                    v-model="schedule.interval"
                    :label="$t('backup.schedule')"
                    :disabled="loading.addBackup || loading.alterBackup"
                    :invalid-message="$t(error.schedule)"
                    class="schedule-interval"
                  >
                    <cv-select-option value="hourly">
                      {{ $t("backup.hourly") }}
                    </cv-select-option>
                    <cv-select-option value="daily">
                      {{ $t("backup.daily") }}
                    </cv-select-option>
                    <cv-select-option value="weekly">
                      {{ $t("backup.weekly") }}
                    </cv-select-option>
                    <cv-select-option value="monthly">
                      {{ $t("backup.monthly") }}
                    </cv-select-option>
                  </cv-select>
                </cv-column>
                <cv-column
                  v-if="schedule.interval == 'hourly'"
                  :md="2"
                  :max="4"
                >
                  <cv-text-input
                    :label="$t('backup.minute')"
                    v-model.trim="schedule.minute"
                    type="number"
                    min="0"
                    max="59"
                    :disabled="loading.addBackup || loading.alterBackup"
                    ref="schedule-minute"
                  >
                  </cv-text-input>
                </cv-column>
                <cv-column v-if="schedule.interval == 'daily'" :md="2" :max="4">
                  <NsTimePicker
                    hideClearButton
                    v-model="schedule.time"
                    :label="$t('backup.at')"
                  ></NsTimePicker>
                </cv-column>
                <template v-if="schedule.interval == 'weekly'">
                  <cv-column :md="2" :max="4">
                    <cv-select
                      v-model="schedule.weekDay"
                      :label="$t('backup.on')"
                      :disabled="loading.addBackup || loading.alterBackup"
                    >
                      <cv-select-option value="monday">
                        {{ $t("calendar.monday") }}
                      </cv-select-option>
                      <cv-select-option value="tuesday">
                        {{ $t("calendar.tuesday") }}
                      </cv-select-option>
                      <cv-select-option value="wednesday">
                        {{ $t("calendar.wednesday") }}
                      </cv-select-option>
                      <cv-select-option value="thursday">
                        {{ $t("calendar.thursday") }}
                      </cv-select-option>
                      <cv-select-option value="friday">
                        {{ $t("calendar.friday") }}
                      </cv-select-option>
                      <cv-select-option value="saturday">
                        {{ $t("calendar.saturday") }}
                      </cv-select-option>
                      <cv-select-option value="sunday">
                        {{ $t("calendar.sunday") }}
                      </cv-select-option>
                    </cv-select>
                  </cv-column>
                  <cv-column :md="2" :max="4">
                    <NsTimePicker
                      hideClearButton
                      v-model="schedule.time"
                      :label="$t('backup.at')"
                    ></NsTimePicker>
                  </cv-column>
                </template>
                <template v-if="schedule.interval == 'monthly'">
                  <cv-column :md="2" :max="4">
                    <cv-text-input
                      :label="$t('backup.on_day')"
                      v-model.trim="schedule.monthDay"
                      type="number"
                      min="1"
                      max="31"
                      :disabled="loading.addBackup || loading.alterBackup"
                    >
                    </cv-text-input>
                  </cv-column>
                  <cv-column :md="2" :max="4">
                    <NsTimePicker
                      hideClearButton
                      v-model="schedule.time"
                      :label="$t('backup.at')"
                    ></NsTimePicker>
                  </cv-column>
                </template>
                <cv-column
                  v-if="schedule.interval == 'custom'"
                  :md="6"
                  :max="12"
                >
                  <NsTextInput
                    v-model.trim="schedule.custom"
                    :label="$t('backup.calendar_event_expression')"
                    :invalid-message="$t(error.schedule)"
                    :disabled="loading.addBackup || loading.alterBackup"
                    tooltipAlignment="center"
                    tooltipDirection="bottom"
                    ref="schedule-custom"
                  >
                    <template #tooltip>
                      <div class="mg-bottom-sm">
                        {{ $t("backup.custom_schedule_tooltip_description") }}
                      </div>
                      <div class="mg-bottom-sm">
                        {{ $t("backup.custom_schedule_tooltip_more_info") }}
                        <cv-link
                          href="https://www.freedesktop.org/software/systemd/man/systemd.time.html#Calendar%20Events"
                          target="_blank"
                        >
                          {{
                            $t(
                              "backup.custom_schedule_tooltip_systemd_time_documentation"
                            )
                          }}
                        </cv-link>
                      </div>
                    </template>
                  </NsTextInput>
                </cv-column>
              </cv-row>
              <cv-row
                v-if="schedule.interval !== 'custom'"
                class="mg-bottom-xlg"
              >
                <cv-column class="schedule-description">
                  {{ getBackupScheduleDescription(schedule) }}
                </cv-column>
              </cv-row>
              <cv-row>
                <cv-column :md="2" :max="4">
                  <NsTextInput
                    :label="$t('backup.retention')"
                    v-model.trim="retention"
                    type="number"
                    min="1"
                    :helper-text="$t('backup.backup_snapshots')"
                    :invalid-message="$t(error.retention)"
                    :disabled="loading.addBackup || loading.alterBackup"
                    tooltipAlignment="end"
                    tooltipDirection="right"
                    ref="retention"
                    class="retention"
                  >
                    <template #tooltip>{{
                      $t("backup.retention_tooltip")
                    }}</template>
                  </NsTextInput>
                </cv-column>
              </cv-row>
            </cv-grid>
          </div>
          <div v-show="step == 'name'">
            <cv-text-input
              :label="$t('backup.backup_name')"
              v-model.trim="name"
              :helper-text="$t('backup.backup_name_helper')"
              :invalid-message="$t(error.name)"
              :disabled="loading.addBackup || loading.alterBackup"
              class="mg-bottom-xlg"
              ref="name"
            >
            </cv-text-input>
            <cv-checkbox
              :label="$t('backup.run_backup_now')"
              v-model="runBackupOnFinish"
              :disabled="loading.addBackup || loading.alterBackup"
              value="checkRunBackupOnFinish"
            />
            <NsInlineNotification
              v-if="error.addBackup"
              kind="error"
              :title="$t('action.add-backup')"
              :description="error.addBackup"
              :showCloseButton="false"
            />
            <NsInlineNotification
              v-if="error.alterBackup"
              kind="error"
              :title="$t('action.alter-backup')"
              :description="error.alterBackup"
              :showCloseButton="false"
            />
          </div>
        </cv-form>
      </template>
⋮----
{{ $t("backup.choose_destination_repository") }}
⋮----
{{ repo.name }}
⋮----
{{ $t("backup." + repo.provider) }}
⋮----
{{ repo.url }}
⋮----
{{ $t("backup.hourly") }}
⋮----
{{ $t("backup.daily") }}
⋮----
{{ $t("backup.weekly") }}
⋮----
{{ $t("backup.monthly") }}
⋮----
<template v-if="schedule.interval == 'weekly'">
                  <cv-column :md="2" :max="4">
                    <cv-select
                      v-model="schedule.weekDay"
                      :label="$t('backup.on')"
                      :disabled="loading.addBackup || loading.alterBackup"
                    >
                      <cv-select-option value="monday">
                        {{ $t("calendar.monday") }}
                      </cv-select-option>
                      <cv-select-option value="tuesday">
                        {{ $t("calendar.tuesday") }}
                      </cv-select-option>
                      <cv-select-option value="wednesday">
                        {{ $t("calendar.wednesday") }}
                      </cv-select-option>
                      <cv-select-option value="thursday">
                        {{ $t("calendar.thursday") }}
                      </cv-select-option>
                      <cv-select-option value="friday">
                        {{ $t("calendar.friday") }}
                      </cv-select-option>
                      <cv-select-option value="saturday">
                        {{ $t("calendar.saturday") }}
                      </cv-select-option>
                      <cv-select-option value="sunday">
                        {{ $t("calendar.sunday") }}
                      </cv-select-option>
                    </cv-select>
                  </cv-column>
                  <cv-column :md="2" :max="4">
                    <NsTimePicker
                      hideClearButton
                      v-model="schedule.time"
                      :label="$t('backup.at')"
                    ></NsTimePicker>
                  </cv-column>
                </template>
⋮----
{{ $t("calendar.monday") }}
⋮----
{{ $t("calendar.tuesday") }}
⋮----
{{ $t("calendar.wednesday") }}
⋮----
{{ $t("calendar.thursday") }}
⋮----
{{ $t("calendar.friday") }}
⋮----
{{ $t("calendar.saturday") }}
⋮----
{{ $t("calendar.sunday") }}
⋮----
<template v-if="schedule.interval == 'monthly'">
                  <cv-column :md="2" :max="4">
                    <cv-text-input
                      :label="$t('backup.on_day')"
                      v-model.trim="schedule.monthDay"
                      type="number"
                      min="1"
                      max="31"
                      :disabled="loading.addBackup || loading.alterBackup"
                    >
                    </cv-text-input>
                  </cv-column>
                  <cv-column :md="2" :max="4">
                    <NsTimePicker
                      hideClearButton
                      v-model="schedule.time"
                      :label="$t('backup.at')"
                    ></NsTimePicker>
                  </cv-column>
                </template>
⋮----
<template #tooltip>
                      <div class="mg-bottom-sm">
                        {{ $t("backup.custom_schedule_tooltip_description") }}
                      </div>
                      <div class="mg-bottom-sm">
                        {{ $t("backup.custom_schedule_tooltip_more_info") }}
                        <cv-link
                          href="https://www.freedesktop.org/software/systemd/man/systemd.time.html#Calendar%20Events"
                          target="_blank"
                        >
                          {{
                            $t(
                              "backup.custom_schedule_tooltip_systemd_time_documentation"
                            )
                          }}
                        </cv-link>
                      </div>
                    </template>
⋮----
{{ $t("backup.custom_schedule_tooltip_description") }}
⋮----
{{ $t("backup.custom_schedule_tooltip_more_info") }}
⋮----
{{
                            $t(
                              "backup.custom_schedule_tooltip_systemd_time_documentation"
                            )
                          }}
⋮----
{{ getBackupScheduleDescription(schedule) }}
⋮----
<template #tooltip>{{
                      $t("backup.retention_tooltip")
                    }}</template>
⋮----
<script>
import { UtilService, TaskService, IconService } from "@nethserver/ns8-ui-lib";
import to from "await-to-js";
import BackupInstanceSelector from "@/components/backup/BackupInstanceSelector";
import _cloneDeep from "lodash/cloneDeep";
import _capitalize from "lodash/capitalize";
const DEFAULT_SCHEDULE_INTERVAL = "daily";
const DEFAULT_SCHEDULE_MINUTE = "0";
const DEFAULT_SCHEDULE_TIME = "00:00";
const DEFAULT_SCHEDULE_WEEK_DAY = "sunday";
const DEFAULT_SCHEDULE_MONTH_DAY = "1";
const DEFAULT_SCHEDULE_CUSTOM = "";
const DEFAULT_RETENTION = "5";
export default {
  name: "CreateOrEditBackupModal",
  components: { BackupInstanceSelector },
  mixins: [UtilService, TaskService, IconService],
  props: {
    isShown: {
      type: Boolean,
      default: true,
    },
    isEditing: {
      type: Boolean,
      default: false,
    },
    repositories: {
      type: Array,
      required: true,
    },
    instanceSelection: {
      type: String,
      default: "",
    },
    instancesNotBackedUp: {
      type: Array,
      default: () => [],
    },
    backup: {
      type: Object,
      required: true,
    },
    backups: {
      type: Array,
      required: true,
    },
  },
  data() {
    return {
      step: "",
      instances: [],
      name: "",
      schedule: {
        interval: DEFAULT_SCHEDULE_INTERVAL,
        minute: DEFAULT_SCHEDULE_MINUTE,
        time: DEFAULT_SCHEDULE_TIME,
        weekDay: DEFAULT_SCHEDULE_WEEK_DAY,
        monthDay: DEFAULT_SCHEDULE_MONTH_DAY,
        custom: DEFAULT_SCHEDULE_CUSTOM,
      },
      retention: DEFAULT_RETENTION,
      installedModules: [],
      internalRepositories: [],
      runBackupOnFinish: false,
      loading: {
        addBackup: false,
        alterBackup: false,
        listInstalledModules: true,
      },
      error: {
        name: "",
        repository: "",
        schedule: "",
        retention: "",
        addBackup: "",
        alterBackup: "",
        listInstalledModules: "",
      },
    };
  },
  computed: {
    stepIndex() {
      return this.steps.indexOf(this.step);
    },
    isFirstStep() {
      return this.stepIndex == 0;
    },
    isLastStep() {
      return this.stepIndex == this.steps.length - 1;
    },
    isNextButtonDisabled() {
      return (
        this.loading.addBackup ||
        this.loading.alterBackup ||
        !this.installedModules.length ||
        (this.step == "instances" && !this.instances.length) ||
        (this.step == "repository" && !this.selectedRepo)
      );
    },
    nextButtonLabel() {
      if (this.isLastStep) {
        if (this.isEditing) {
          return this.$t("common.save");
        } else {
          return this.$t("backup.create_backup");
        }
      } else {
        return this.$t("common.next");
      }
    },
    steps() {
      if (this.isEditing) {
        return ["instances", "settings", "name"];
      } else {
        return ["instances", "repository", "settings", "name"];
      }
    },
    selectedRepo() {
      return this.internalRepositories.find((r) => r.selected);
    },
    isScheduleValid() {
      switch (this.schedule.interval) {
        case "hourly":
          return this.schedule.minute >= 0 && this.schedule.minute <= 59;
        case "daily":
          return this.time24HourPattern.test(this.schedule.time);
        case "weekly":
          return (
            this.schedule.weekDay &&
            this.time24HourPattern.test(this.schedule.time)
          );
        case "monthly":
          return (
            this.schedule.monthDay >= 1 &&
            this.schedule.monthDay <= 31 &&
            this.time24HourPattern.test(this.schedule.time)
          );
      }
      return false;
    },
    scheduleExpression() {
      switch (this.schedule.interval) {
        case "hourly": {
          const minutes = this.schedule.minute.padStart(2, "0");
          return `*-*-* *:${minutes}:00`;
        }
        case "daily":
          return `*-*-* ${this.schedule.time}:00`;
        case "weekly": {
          const shortDay = _capitalize(this.schedule.weekDay.substring(0, 3));
          return `${shortDay} *-*-* ${this.schedule.time}:00`;
        }
        case "monthly": {
          const monthDay = this.schedule.monthDay.padStart(2, "0");
          return `*-*-${monthDay} ${this.schedule.time}:00`;
        }
        case "custom":
          return this.schedule.custom;
      }
      return null;
    },
  },
  watch: {
    isShown: function () {
      if (this.isShown) {
        this.step = this.steps[0];
        this.$nextTick(() => {
          if (this.isEditing) {
            this.name = this.backup.name;
            this.schedule = _cloneDeep(this.backup.schedule);
            this.retention = this.backup.retention.toString();
            this.runBackupOnFinish = false;
            this.updateInternalRepositories();
          } else {
            this.clearFields();
          }
        });
        this.listInstalledModules();
      }
    },
    repositories: function () {
      this.updateInternalRepositories();
    },
    step: function () {
      if (this.step == "settings" && !this.isEditing) {
        let backupName = this.$t("backup.default_backup_name", {
          repository: this.selectedRepo.name,
        });
        let isBackupNameDuplicated = this.backups.find(
          (b) => b.name == backupName
        );
        let backupNameSuffix = 2;
        while (isBackupNameDuplicated) {
          backupName =
            this.$t("backup.default_backup_name", {
              repository: `${this.selectedRepo.name}`,
            }) + ` (${backupNameSuffix})`;
          isBackupNameDuplicated = this.backups.find(
            (b) => b.name == backupName
          );
          backupNameSuffix++;
        }
        this.name = backupName;
      }
    },
  },
  created() {
    this.updateInternalRepositories();
  },
  methods: {
    clearFields() {
      this.instances = [];
      this.name = "";
      this.schedule.interval = DEFAULT_SCHEDULE_INTERVAL;
      this.schedule.minute = DEFAULT_SCHEDULE_MINUTE;
      this.schedule.time = DEFAULT_SCHEDULE_TIME;
      this.schedule.weekDay = DEFAULT_SCHEDULE_WEEK_DAY;
      this.schedule.monthDay = DEFAULT_SCHEDULE_MONTH_DAY;
      this.schedule.custom = DEFAULT_SCHEDULE_CUSTOM;
      this.retention = DEFAULT_RETENTION;
      this.runBackupOnFinish = false;
      for (let repo of this.internalRepositories) {
        repo.selected = false;
      }
      // preselect if there is only one repo
      if (this.internalRepositories.length == 1) {
        this.internalRepositories[0].selected = true;
      }
    },
    nextStep() {
      if (this.isNextButtonDisabled) {
        return;
      }
      if (!this.validateStep()) {
        return;
      }
      if (this.isLastStep) {
        if (this.isEditing) {
          this.alterBackup();
        } else {
          this.addBackup();
        }
      } else {
        this.step = this.steps[this.stepIndex + 1];
      }
    },
    previousStep() {
      if (!this.isFirstStep) {
        this.step = this.steps[this.stepIndex - 1];
      }
    },
    updateInternalRepositories() {
      // deep copy (needed to avoid reactivity issues)
      let internalRepositories = _cloneDeep(this.repositories);
      if (this.isEditing) {
        // edit backup
        for (const repo of internalRepositories) {
          if (this.backup.repository == repo.id) {
            repo.selected = true;
          } else {
            repo.selected = false;
          }
        }
      } else {
        // create backup
        for (const repo of internalRepositories) {
          repo.selected = false;
        }
        // preselect if there is only one repo
        if (internalRepositories.length == 1) {
          internalRepositories[0].selected = true;
        }
      }
      this.internalRepositories = internalRepositories;
    },
    validateSettingsStep() {
      let isValidationOk = true;
      this.error.retention = "";
      if (!this.retention || this.retention < 1) {
        this.error.retention = "error.invalid_value";
        if (isValidationOk) {
          this.focusElement("retention");
          isValidationOk = false;
        }
      }
      return isValidationOk;
    },
    validateNameStep() {
      let isValidationOk = true;
      this.error.name = "";
      if (!this.name) {
        this.error.name = "common.required";
        if (isValidationOk) {
          this.focusElement("name");
          isValidationOk = false;
        }
      }
      return isValidationOk;
    },
    validateStep() {
      switch (this.step) {
        case "settings":
          return this.validateSettingsStep();
        case "name":
          return this.validateNameStep();
        default:
          return true;
      }
    },
    async addBackup() {
      this.error.addBackup = "";
      this.loading.addBackup = true;
      const taskAction = "add-backup";
      this.$root.$off(taskAction + "-aborted");
      this.$root.$once(taskAction + "-aborted", this.addBackupAborted);
      this.$root.$off(taskAction + "-validation-failed");
      this.$root.$once(
        taskAction + "-validation-failed",
        this.addBackupValidationFailed
      );
      this.$root.$off(taskAction + "-completed");
      this.$root.$once(taskAction + "-completed", this.addBackupCompleted);
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {
            name: this.name,
            repository: this.selectedRepo.id,
            schedule: this.scheduleExpression,
            schedule_hint: this.schedule,
            retention: parseInt(this.retention),
            instances: this.instances,
            enabled: true,
          },
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            runBackupOnFinish: this.runBackupOnFinish,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.addBackup = this.getErrorMessage(err);
        return;
      }
    },
    addBackupAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.loading.addBackup = false;
      this.$emit("hide");
    },
    addBackupValidationFailed(validationErrors) {
      this.loading.addBackup = false;
      let focusAlreadySet = false;
      for (const validationError of validationErrors) {
        const param = validationError.parameter;
        this.error[param] = "backup." + validationError.error;
        if (!focusAlreadySet) {
          this.focusElement(param);
          focusAlreadySet = true;
        }
      }
    },
    addBackupCompleted(taskContext, taskResult) {
      this.loading.addBackup = false;
      this.$emit("hide");
      const runBackupOnFinish = taskContext.extra.runBackupOnFinish;
      const backupId = taskResult.output;
      const createdBackup = {
        id: backupId,
        name: taskContext.data.name,
      };
      this.$emit("backupCreated", runBackupOnFinish, createdBackup);
    },
    async alterBackup() {
      this.error.alterBackup = "";
      this.loading.alterBackup = true;
      const taskAction = "alter-backup";
      this.$root.$off(taskAction + "-validation-failed");
      this.$root.$once(
        taskAction + "-validation-failed",
        this.alterBackupValidationFailed
      );
      this.$root.$off(taskAction + "-completed");
      this.$root.$once(taskAction + "-completed", this.alterBackupCompleted);
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {
            id: this.backup.id,
            name: this.name,
            repository: this.backup.repository,
            schedule: this.scheduleExpression,
            schedule_hint: this.schedule,
            retention: parseInt(this.retention),
            instances: this.instances,
            enabled: this.backup.enabled,
          },
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            runBackupOnFinish: this.runBackupOnFinish,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.alterBackup = this.getErrorMessage(err);
        return;
      }
    },
    alterBackupValidationFailed(validationErrors) {
      this.loading.alterBackup = false;
      let focusAlreadySet = false;
      for (const validationError of validationErrors) {
        const param = validationError.parameter;
        this.error[param] = "backup." + validationError.error;
        if (!focusAlreadySet) {
          this.focusElement(param);
          focusAlreadySet = true;
        }
      }
    },
    alterBackupCompleted(taskContext) {
      this.loading.alterBackup = false;
      this.$emit("hide");
      const runBackupOnFinish = taskContext.extra.runBackupOnFinish;
      const alteredBackup = {
        id: taskContext.data.id,
        name: taskContext.data.name,
      };
      this.$emit("backupAltered", runBackupOnFinish, alteredBackup);
    },
    async listInstalledModules() {
      this.loading.listInstalledModules = true;
      const taskAction = "list-installed-modules";
      this.$root.$once(
        taskAction + "-completed",
        this.listInstalledModulesCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
          },
        })
      );
      const err = res[0];
      if (err) {
        this.error.listInstalledModules = this.getErrorMessage(err);
        this.createErrorNotification(
          err,
          this.$t("task.cannot_create_task", { action: taskAction })
        );
        return;
      }
    },
    listInstalledModulesCompleted(taskContext, taskResult) {
      this.loading.listInstalledModules = false;
      let apps = [];
      for (let instanceList of Object.values(taskResult.output)) {
        for (let instance of instanceList) {
          apps.push(instance);
        }
      }
      apps.sort(this.sortModuleInstances());
      this.installedModules = apps;
    },
    onSelectInstances(instances) {
      this.instances = instances;
    },
    deselectOtherRepos(repo) {
      for (let r of this.internalRepositories) {
        if (r.id !== repo.id) {
          r.selected = false;
        }
      }
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
.schedule-description {
  font-weight: bold;
}
.calendar-event-expression-tooltip {
  display: inline-block;
}
.calendar-event-expression-tooltip-title {
  margin-bottom: $spacing-03;
}
</style>
⋮----
<style lang="scss">
@import "../../styles/carbon-utils";
.calendar-event-expression-tooltip .bx--tooltip__trigger {
  margin-left: 0 !important;
}
</style>
</file>

<file path="core/ui/src/components/backup/EditRepositoryModal.vue">
<template>
  <NsModal
    size="default"
    :visible="isShown"
    @modal-hidden="$emit('hide')"
    @primary-click="alterBackupRepository"
    :primary-button-disabled="
      loading.alterBackupRepository || loading.fileReading
    "
  >
    <template slot="title">{{ $t("backup.edit_destination") }}</template>
    <template slot="content">
      <cv-form @submit.prevent="alterBackupRepository">
        <NsInlineNotification
          v-if="error.repoConnection"
          kind="error"
          :title="$t('backup.backup_repository_connection_error')"
          :description="$t('backup.' + error.repoConnection)"
          :showCloseButton="false"
        />
        <template v-if="repository.provider == 'backblaze'">
          <cv-text-input
            :label="$t('backup.b2_account_id')"
            v-model.trim="backblaze.b2_account_id"
            :invalid-message="$t(error.backblaze.b2_account_id)"
            :disabled="loading.alterBackupRepository"
            ref="b2_account_id"
          >
          </cv-text-input>
          <cv-text-input
            :placeholder="$t('common.unchanged_password')"
            :label="$t('backup.b2_account_key')"
            v-model.trim="backblaze.b2_account_key"
            :invalid-message="$t(error.backblaze.b2_account_key)"
            :disabled="loading.alterBackupRepository"
            ref="b2_account_key"
            type="password"
            :password-hide-label="$t('password.hide_password')"
            :password-show-label="$t('password.show_password')"
          >
          </cv-text-input>
        </template>
        <template v-if="repository.provider == 'aws'">
          <cv-text-input
            :label="$t('backup.aws_access_key_id')"
            v-model.trim="aws.aws_access_key_id"
            :invalid-message="$t(error.aws.aws_access_key_id)"
            :disabled="loading.alterBackupRepository"
            ref="aws_access_key_id"
          >
          </cv-text-input>
          <cv-text-input
            :label="$t('backup.aws_default_region')"
            v-model.trim="aws.aws_default_region"
            :invalid-message="$t(error.aws.aws_default_region)"
            :disabled="loading.alterBackupRepository"
            ref="aws_default_region"
          >
          </cv-text-input>
          <cv-text-input
            :placeholder="$t('common.unchanged_password')"
            :label="$t('backup.aws_secret_access_key')"
            v-model.trim="aws.aws_secret_access_key"
            :invalid-message="$t(error.aws.aws_secret_access_key)"
            :disabled="loading.alterBackupRepository"
            type="password"
            :password-hide-label="$t('password.hide_password')"
            :password-show-label="$t('password.show_password')"
            ref="aws_secret_access_key"
          >
          </cv-text-input>
        </template>
        <template v-if="repository.provider == 'smb'">
          <NsInlineNotification
            kind="info"
            :title="$t('backup.smb_protocol_warning_title')"
            :description="$t('backup.smb_protocol_warning_description')"
            :showCloseButton="false"
          />
          <cv-text-input
            :label="$t('backup.smb_host')"
            v-model.trim="smb.smb_host"
            :invalid-message="error.smb.smb_host"
            :disabled="loading.alterBackupRepository"
            ref="smb_host"
          >
          </cv-text-input>
          <cv-text-input
            :label="$t('backup.smb_domain')"
            v-model.trim="smb.smb_domain"
            :invalid-message="error.smb.smb_domain"
            :disabled="loading.alterBackupRepository"
            ref="smb_domain"
          >
          </cv-text-input>
          <cv-text-input
            :label="$t('backup.smb_user')"
            v-model.trim="smb.smb_user"
            :invalid-message="error.smb.smb_user"
            :disabled="loading.alterBackupRepository"
            ref="smb_user"
          >
          </cv-text-input>
          <cv-text-input
            :placeholder="$t('common.unchanged_password')"
            :label="$t('backup.smb_pass')"
            type="password"
            v-model.trim="smb.smb_pass"
            :disabled="loading.alterBackupRepository"
            :invalid-message="error.smb.smb_pass"
            :password-hide-label="$t('password.hide_password')"
            :password-show-label="$t('password.show_password')"
            ref="smb_pass"
          ></cv-text-input>
        </template>
        <template v-if="repository.provider == 'generic-s3'">
          <cv-text-input
            :label="$t('backup.genericS3_access_key_id')"
            v-model.trim="genericS3.aws_access_key_id"
            :invalid-message="$t(error.genericS3.aws_access_key_id)"
            :disabled="loading.alterBackupRepository"
            ref="genericS3_access_key_id"
          >
          </cv-text-input>
          <cv-text-input
            :placeholder="$t('common.unchanged_password')"
            :label="$t('backup.genericS3_secret_access_key')"
            v-model.trim="genericS3.aws_secret_access_key"
            :invalid-message="$t(error.genericS3.aws_secret_access_key)"
            :disabled="loading.alterBackupRepository"
            type="password"
            :password-hide-label="$t('password.hide_password')"
            :password-show-label="$t('password.show_password')"
            ref="genericS3_secret_access_key"
          >
          </cv-text-input>
        </template>
        <template v-if="repository.provider == 'rclone'">
          <div>
            <label class="bx--label">{{
              $t("backup.rclone_configuration_source")
            }}</label>
            <cv-radio-group
              :vertical="true"
              :disabled="loading.alterBackupRepository"
            >
              <cv-radio-button
                :label="
                  $t('backup.rclone_configuration_source_keep_configuration')
                "
                value="keep"
                v-model="rclone.configuration_source"
              />
              <cv-radio-button
                :label="
                  $t('backup.rclone_configuration_source_paste_configuration')
                "
                value="paste"
                v-model="rclone.configuration_source"
              />
              <cv-radio-button
                :label="
                  $t('backup.rclone_configuration_source_upload_configuration')
                "
                value="upload"
                v-model="rclone.configuration_source"
              />
            </cv-radio-group>
          </div>
          <template v-if="rclone.configuration_source == 'paste'">
            <cv-text-area
              class="mg-top-md"
              :label="$t('backup.rclone_configuration_content')"
              v-model.trim="rclone.rclone_conf_secret"
              :invalid-message="error.rclone.rclone_conf_secret"
              :helper-text="
                $t(
                  'backup.rclone_configuration_content_single_destination_helper_text'
                )
              "
              :value="rclone.rclone_conf_secret"
              rows="5"
              ref="rclone_conf_secret"
              :disabled="loading.alterBackupRepository"
            ></cv-text-area>
          </template>
          <template v-else-if="rclone.configuration_source == 'upload'">
            <div
              :class="{
                'file-uploader-error': error.rclone.configuration_file,
              }"
            >
              <cv-file-uploader
                :key="componentKey"
                :label="$t('backup.rclone_configuration_file')"
                :helper-text="$t('backup.rclone_configuration_file_helper')"
                :multiple="false"
                :removable="true"
                :clear-on-reselect="true"
                :drop-target-label="
                  $t('common.drag_and_drop_or_click_to_upload')
                "
                v-model="rclone.configuration_uploaded_file"
                accept=".conf,.txt"
                ref="backup_file"
              ></cv-file-uploader>
              <div
                v-if="error.rclone.configuration_file"
                class="validation-failed-invalid-message"
              >
                {{ error.rclone.configuration_file }}
              </div>
            </div>
          </template>
          <cv-text-input
            :label="
              $t('backup.rclone_base_path') + ' (' + $t('common.optional') + ')'
            "
            v-model.trim="rclone.base_path"
            :invalid-message="error.rclone.base_path"
            :disabled="loading.alterBackupRepository"
            ref="rclone_base_path"
          ></cv-text-input>
        </template>
        <cv-text-input
          :label="$t('backup.repository_name')"
          v-model.trim="name"
          :helper-text="$t('backup.repository_name_helper')"
          :invalid-message="error.name"
          :disabled="loading.alterBackupRepository"
          ref="name"
        >
        </cv-text-input>
        <cv-accordion>
          <cv-accordion-item :open="false">
            <template slot="title">{{ $t("common.advanced") }}</template>
            <template slot="content">
              <div>
                <label class="bx--label">
                  <span>
                    {{ $t("backup.data_encryption_key") }}
                  </span>
                  <cv-interactive-tooltip
                    alignment="center"
                    direction="right"
                    class="info"
                  >
                    <template slot="content">
                      <div>
                        {{ $t("backup.data_encryption_key_tooltip") }}
                      </div>
                    </template>
                  </cv-interactive-tooltip>
                </label>
                <NsCodeSnippet
                  light
                  copyTipPosition="left"
                  copyTipAlignment="center"
                  :copyTooltip="$t('common.copy_to_clipboard')"
                  :copy-feedback="$t('common.copied_to_clipboard')"
                  :feedback-aria-label="$t('common.copied_to_clipboard')"
                  :wrap-text="true"
                  :moreText="$t('common.show_more')"
                  :lessText="$t('common.show_less')"
                  hideExpandButton
                  class="mg-top-sm"
                  >{{ repository.password }}</NsCodeSnippet
                >
              </div>
            </template>
          </cv-accordion-item>
        </cv-accordion>
        <NsInlineNotification
          v-if="error.alterBackupRepository"
          kind="error"
          :title="$t('action.add-backup-repository')"
          :description="error.alterBackupRepository"
          :showCloseButton="false"
        />
      </cv-form>
    </template>
    <template slot="secondary-button">{{ $t("common.cancel") }}</template>
    <template slot="primary-button">{{ $t("common.save") }}</template>
  </NsModal>
</template>
⋮----
<template slot="title">{{ $t("backup.edit_destination") }}</template>
<template slot="content">
      <cv-form @submit.prevent="alterBackupRepository">
        <NsInlineNotification
          v-if="error.repoConnection"
          kind="error"
          :title="$t('backup.backup_repository_connection_error')"
          :description="$t('backup.' + error.repoConnection)"
          :showCloseButton="false"
        />
        <template v-if="repository.provider == 'backblaze'">
          <cv-text-input
            :label="$t('backup.b2_account_id')"
            v-model.trim="backblaze.b2_account_id"
            :invalid-message="$t(error.backblaze.b2_account_id)"
            :disabled="loading.alterBackupRepository"
            ref="b2_account_id"
          >
          </cv-text-input>
          <cv-text-input
            :placeholder="$t('common.unchanged_password')"
            :label="$t('backup.b2_account_key')"
            v-model.trim="backblaze.b2_account_key"
            :invalid-message="$t(error.backblaze.b2_account_key)"
            :disabled="loading.alterBackupRepository"
            ref="b2_account_key"
            type="password"
            :password-hide-label="$t('password.hide_password')"
            :password-show-label="$t('password.show_password')"
          >
          </cv-text-input>
        </template>
        <template v-if="repository.provider == 'aws'">
          <cv-text-input
            :label="$t('backup.aws_access_key_id')"
            v-model.trim="aws.aws_access_key_id"
            :invalid-message="$t(error.aws.aws_access_key_id)"
            :disabled="loading.alterBackupRepository"
            ref="aws_access_key_id"
          >
          </cv-text-input>
          <cv-text-input
            :label="$t('backup.aws_default_region')"
            v-model.trim="aws.aws_default_region"
            :invalid-message="$t(error.aws.aws_default_region)"
            :disabled="loading.alterBackupRepository"
            ref="aws_default_region"
          >
          </cv-text-input>
          <cv-text-input
            :placeholder="$t('common.unchanged_password')"
            :label="$t('backup.aws_secret_access_key')"
            v-model.trim="aws.aws_secret_access_key"
            :invalid-message="$t(error.aws.aws_secret_access_key)"
            :disabled="loading.alterBackupRepository"
            type="password"
            :password-hide-label="$t('password.hide_password')"
            :password-show-label="$t('password.show_password')"
            ref="aws_secret_access_key"
          >
          </cv-text-input>
        </template>
        <template v-if="repository.provider == 'smb'">
          <NsInlineNotification
            kind="info"
            :title="$t('backup.smb_protocol_warning_title')"
            :description="$t('backup.smb_protocol_warning_description')"
            :showCloseButton="false"
          />
          <cv-text-input
            :label="$t('backup.smb_host')"
            v-model.trim="smb.smb_host"
            :invalid-message="error.smb.smb_host"
            :disabled="loading.alterBackupRepository"
            ref="smb_host"
          >
          </cv-text-input>
          <cv-text-input
            :label="$t('backup.smb_domain')"
            v-model.trim="smb.smb_domain"
            :invalid-message="error.smb.smb_domain"
            :disabled="loading.alterBackupRepository"
            ref="smb_domain"
          >
          </cv-text-input>
          <cv-text-input
            :label="$t('backup.smb_user')"
            v-model.trim="smb.smb_user"
            :invalid-message="error.smb.smb_user"
            :disabled="loading.alterBackupRepository"
            ref="smb_user"
          >
          </cv-text-input>
          <cv-text-input
            :placeholder="$t('common.unchanged_password')"
            :label="$t('backup.smb_pass')"
            type="password"
            v-model.trim="smb.smb_pass"
            :disabled="loading.alterBackupRepository"
            :invalid-message="error.smb.smb_pass"
            :password-hide-label="$t('password.hide_password')"
            :password-show-label="$t('password.show_password')"
            ref="smb_pass"
          ></cv-text-input>
        </template>
        <template v-if="repository.provider == 'generic-s3'">
          <cv-text-input
            :label="$t('backup.genericS3_access_key_id')"
            v-model.trim="genericS3.aws_access_key_id"
            :invalid-message="$t(error.genericS3.aws_access_key_id)"
            :disabled="loading.alterBackupRepository"
            ref="genericS3_access_key_id"
          >
          </cv-text-input>
          <cv-text-input
            :placeholder="$t('common.unchanged_password')"
            :label="$t('backup.genericS3_secret_access_key')"
            v-model.trim="genericS3.aws_secret_access_key"
            :invalid-message="$t(error.genericS3.aws_secret_access_key)"
            :disabled="loading.alterBackupRepository"
            type="password"
            :password-hide-label="$t('password.hide_password')"
            :password-show-label="$t('password.show_password')"
            ref="genericS3_secret_access_key"
          >
          </cv-text-input>
        </template>
        <template v-if="repository.provider == 'rclone'">
          <div>
            <label class="bx--label">{{
              $t("backup.rclone_configuration_source")
            }}</label>
            <cv-radio-group
              :vertical="true"
              :disabled="loading.alterBackupRepository"
            >
              <cv-radio-button
                :label="
                  $t('backup.rclone_configuration_source_keep_configuration')
                "
                value="keep"
                v-model="rclone.configuration_source"
              />
              <cv-radio-button
                :label="
                  $t('backup.rclone_configuration_source_paste_configuration')
                "
                value="paste"
                v-model="rclone.configuration_source"
              />
              <cv-radio-button
                :label="
                  $t('backup.rclone_configuration_source_upload_configuration')
                "
                value="upload"
                v-model="rclone.configuration_source"
              />
            </cv-radio-group>
          </div>
          <template v-if="rclone.configuration_source == 'paste'">
            <cv-text-area
              class="mg-top-md"
              :label="$t('backup.rclone_configuration_content')"
              v-model.trim="rclone.rclone_conf_secret"
              :invalid-message="error.rclone.rclone_conf_secret"
              :helper-text="
                $t(
                  'backup.rclone_configuration_content_single_destination_helper_text'
                )
              "
              :value="rclone.rclone_conf_secret"
              rows="5"
              ref="rclone_conf_secret"
              :disabled="loading.alterBackupRepository"
            ></cv-text-area>
          </template>
          <template v-else-if="rclone.configuration_source == 'upload'">
            <div
              :class="{
                'file-uploader-error': error.rclone.configuration_file,
              }"
            >
              <cv-file-uploader
                :key="componentKey"
                :label="$t('backup.rclone_configuration_file')"
                :helper-text="$t('backup.rclone_configuration_file_helper')"
                :multiple="false"
                :removable="true"
                :clear-on-reselect="true"
                :drop-target-label="
                  $t('common.drag_and_drop_or_click_to_upload')
                "
                v-model="rclone.configuration_uploaded_file"
                accept=".conf,.txt"
                ref="backup_file"
              ></cv-file-uploader>
              <div
                v-if="error.rclone.configuration_file"
                class="validation-failed-invalid-message"
              >
                {{ error.rclone.configuration_file }}
              </div>
            </div>
          </template>
          <cv-text-input
            :label="
              $t('backup.rclone_base_path') + ' (' + $t('common.optional') + ')'
            "
            v-model.trim="rclone.base_path"
            :invalid-message="error.rclone.base_path"
            :disabled="loading.alterBackupRepository"
            ref="rclone_base_path"
          ></cv-text-input>
        </template>
        <cv-text-input
          :label="$t('backup.repository_name')"
          v-model.trim="name"
          :helper-text="$t('backup.repository_name_helper')"
          :invalid-message="error.name"
          :disabled="loading.alterBackupRepository"
          ref="name"
        >
        </cv-text-input>
        <cv-accordion>
          <cv-accordion-item :open="false">
            <template slot="title">{{ $t("common.advanced") }}</template>
            <template slot="content">
              <div>
                <label class="bx--label">
                  <span>
                    {{ $t("backup.data_encryption_key") }}
                  </span>
                  <cv-interactive-tooltip
                    alignment="center"
                    direction="right"
                    class="info"
                  >
                    <template slot="content">
                      <div>
                        {{ $t("backup.data_encryption_key_tooltip") }}
                      </div>
                    </template>
                  </cv-interactive-tooltip>
                </label>
                <NsCodeSnippet
                  light
                  copyTipPosition="left"
                  copyTipAlignment="center"
                  :copyTooltip="$t('common.copy_to_clipboard')"
                  :copy-feedback="$t('common.copied_to_clipboard')"
                  :feedback-aria-label="$t('common.copied_to_clipboard')"
                  :wrap-text="true"
                  :moreText="$t('common.show_more')"
                  :lessText="$t('common.show_less')"
                  hideExpandButton
                  class="mg-top-sm"
                  >{{ repository.password }}</NsCodeSnippet
                >
              </div>
            </template>
          </cv-accordion-item>
        </cv-accordion>
        <NsInlineNotification
          v-if="error.alterBackupRepository"
          kind="error"
          :title="$t('action.add-backup-repository')"
          :description="error.alterBackupRepository"
          :showCloseButton="false"
        />
      </cv-form>
    </template>
⋮----
<template v-if="repository.provider == 'backblaze'">
          <cv-text-input
            :label="$t('backup.b2_account_id')"
            v-model.trim="backblaze.b2_account_id"
            :invalid-message="$t(error.backblaze.b2_account_id)"
            :disabled="loading.alterBackupRepository"
            ref="b2_account_id"
          >
          </cv-text-input>
          <cv-text-input
            :placeholder="$t('common.unchanged_password')"
            :label="$t('backup.b2_account_key')"
            v-model.trim="backblaze.b2_account_key"
            :invalid-message="$t(error.backblaze.b2_account_key)"
            :disabled="loading.alterBackupRepository"
            ref="b2_account_key"
            type="password"
            :password-hide-label="$t('password.hide_password')"
            :password-show-label="$t('password.show_password')"
          >
          </cv-text-input>
        </template>
⋮----
<template v-if="repository.provider == 'aws'">
          <cv-text-input
            :label="$t('backup.aws_access_key_id')"
            v-model.trim="aws.aws_access_key_id"
            :invalid-message="$t(error.aws.aws_access_key_id)"
            :disabled="loading.alterBackupRepository"
            ref="aws_access_key_id"
          >
          </cv-text-input>
          <cv-text-input
            :label="$t('backup.aws_default_region')"
            v-model.trim="aws.aws_default_region"
            :invalid-message="$t(error.aws.aws_default_region)"
            :disabled="loading.alterBackupRepository"
            ref="aws_default_region"
          >
          </cv-text-input>
          <cv-text-input
            :placeholder="$t('common.unchanged_password')"
            :label="$t('backup.aws_secret_access_key')"
            v-model.trim="aws.aws_secret_access_key"
            :invalid-message="$t(error.aws.aws_secret_access_key)"
            :disabled="loading.alterBackupRepository"
            type="password"
            :password-hide-label="$t('password.hide_password')"
            :password-show-label="$t('password.show_password')"
            ref="aws_secret_access_key"
          >
          </cv-text-input>
        </template>
⋮----
<template v-if="repository.provider == 'smb'">
          <NsInlineNotification
            kind="info"
            :title="$t('backup.smb_protocol_warning_title')"
            :description="$t('backup.smb_protocol_warning_description')"
            :showCloseButton="false"
          />
          <cv-text-input
            :label="$t('backup.smb_host')"
            v-model.trim="smb.smb_host"
            :invalid-message="error.smb.smb_host"
            :disabled="loading.alterBackupRepository"
            ref="smb_host"
          >
          </cv-text-input>
          <cv-text-input
            :label="$t('backup.smb_domain')"
            v-model.trim="smb.smb_domain"
            :invalid-message="error.smb.smb_domain"
            :disabled="loading.alterBackupRepository"
            ref="smb_domain"
          >
          </cv-text-input>
          <cv-text-input
            :label="$t('backup.smb_user')"
            v-model.trim="smb.smb_user"
            :invalid-message="error.smb.smb_user"
            :disabled="loading.alterBackupRepository"
            ref="smb_user"
          >
          </cv-text-input>
          <cv-text-input
            :placeholder="$t('common.unchanged_password')"
            :label="$t('backup.smb_pass')"
            type="password"
            v-model.trim="smb.smb_pass"
            :disabled="loading.alterBackupRepository"
            :invalid-message="error.smb.smb_pass"
            :password-hide-label="$t('password.hide_password')"
            :password-show-label="$t('password.show_password')"
            ref="smb_pass"
          ></cv-text-input>
        </template>
⋮----
<template v-if="repository.provider == 'generic-s3'">
          <cv-text-input
            :label="$t('backup.genericS3_access_key_id')"
            v-model.trim="genericS3.aws_access_key_id"
            :invalid-message="$t(error.genericS3.aws_access_key_id)"
            :disabled="loading.alterBackupRepository"
            ref="genericS3_access_key_id"
          >
          </cv-text-input>
          <cv-text-input
            :placeholder="$t('common.unchanged_password')"
            :label="$t('backup.genericS3_secret_access_key')"
            v-model.trim="genericS3.aws_secret_access_key"
            :invalid-message="$t(error.genericS3.aws_secret_access_key)"
            :disabled="loading.alterBackupRepository"
            type="password"
            :password-hide-label="$t('password.hide_password')"
            :password-show-label="$t('password.show_password')"
            ref="genericS3_secret_access_key"
          >
          </cv-text-input>
        </template>
⋮----
<template v-if="repository.provider == 'rclone'">
          <div>
            <label class="bx--label">{{
              $t("backup.rclone_configuration_source")
            }}</label>
            <cv-radio-group
              :vertical="true"
              :disabled="loading.alterBackupRepository"
            >
              <cv-radio-button
                :label="
                  $t('backup.rclone_configuration_source_keep_configuration')
                "
                value="keep"
                v-model="rclone.configuration_source"
              />
              <cv-radio-button
                :label="
                  $t('backup.rclone_configuration_source_paste_configuration')
                "
                value="paste"
                v-model="rclone.configuration_source"
              />
              <cv-radio-button
                :label="
                  $t('backup.rclone_configuration_source_upload_configuration')
                "
                value="upload"
                v-model="rclone.configuration_source"
              />
            </cv-radio-group>
          </div>
          <template v-if="rclone.configuration_source == 'paste'">
            <cv-text-area
              class="mg-top-md"
              :label="$t('backup.rclone_configuration_content')"
              v-model.trim="rclone.rclone_conf_secret"
              :invalid-message="error.rclone.rclone_conf_secret"
              :helper-text="
                $t(
                  'backup.rclone_configuration_content_single_destination_helper_text'
                )
              "
              :value="rclone.rclone_conf_secret"
              rows="5"
              ref="rclone_conf_secret"
              :disabled="loading.alterBackupRepository"
            ></cv-text-area>
          </template>
          <template v-else-if="rclone.configuration_source == 'upload'">
            <div
              :class="{
                'file-uploader-error': error.rclone.configuration_file,
              }"
            >
              <cv-file-uploader
                :key="componentKey"
                :label="$t('backup.rclone_configuration_file')"
                :helper-text="$t('backup.rclone_configuration_file_helper')"
                :multiple="false"
                :removable="true"
                :clear-on-reselect="true"
                :drop-target-label="
                  $t('common.drag_and_drop_or_click_to_upload')
                "
                v-model="rclone.configuration_uploaded_file"
                accept=".conf,.txt"
                ref="backup_file"
              ></cv-file-uploader>
              <div
                v-if="error.rclone.configuration_file"
                class="validation-failed-invalid-message"
              >
                {{ error.rclone.configuration_file }}
              </div>
            </div>
          </template>
          <cv-text-input
            :label="
              $t('backup.rclone_base_path') + ' (' + $t('common.optional') + ')'
            "
            v-model.trim="rclone.base_path"
            :invalid-message="error.rclone.base_path"
            :disabled="loading.alterBackupRepository"
            ref="rclone_base_path"
          ></cv-text-input>
        </template>
⋮----
<label class="bx--label">{{
              $t("backup.rclone_configuration_source")
            }}</label>
⋮----
<template v-if="rclone.configuration_source == 'paste'">
            <cv-text-area
              class="mg-top-md"
              :label="$t('backup.rclone_configuration_content')"
              v-model.trim="rclone.rclone_conf_secret"
              :invalid-message="error.rclone.rclone_conf_secret"
              :helper-text="
                $t(
                  'backup.rclone_configuration_content_single_destination_helper_text'
                )
              "
              :value="rclone.rclone_conf_secret"
              rows="5"
              ref="rclone_conf_secret"
              :disabled="loading.alterBackupRepository"
            ></cv-text-area>
          </template>
<template v-else-if="rclone.configuration_source == 'upload'">
            <div
              :class="{
                'file-uploader-error': error.rclone.configuration_file,
              }"
            >
              <cv-file-uploader
                :key="componentKey"
                :label="$t('backup.rclone_configuration_file')"
                :helper-text="$t('backup.rclone_configuration_file_helper')"
                :multiple="false"
                :removable="true"
                :clear-on-reselect="true"
                :drop-target-label="
                  $t('common.drag_and_drop_or_click_to_upload')
                "
                v-model="rclone.configuration_uploaded_file"
                accept=".conf,.txt"
                ref="backup_file"
              ></cv-file-uploader>
              <div
                v-if="error.rclone.configuration_file"
                class="validation-failed-invalid-message"
              >
                {{ error.rclone.configuration_file }}
              </div>
            </div>
          </template>
⋮----
{{ error.rclone.configuration_file }}
⋮----
<template slot="title">{{ $t("common.advanced") }}</template>
<template slot="content">
              <div>
                <label class="bx--label">
                  <span>
                    {{ $t("backup.data_encryption_key") }}
                  </span>
                  <cv-interactive-tooltip
                    alignment="center"
                    direction="right"
                    class="info"
                  >
                    <template slot="content">
                      <div>
                        {{ $t("backup.data_encryption_key_tooltip") }}
                      </div>
                    </template>
                  </cv-interactive-tooltip>
                </label>
                <NsCodeSnippet
                  light
                  copyTipPosition="left"
                  copyTipAlignment="center"
                  :copyTooltip="$t('common.copy_to_clipboard')"
                  :copy-feedback="$t('common.copied_to_clipboard')"
                  :feedback-aria-label="$t('common.copied_to_clipboard')"
                  :wrap-text="true"
                  :moreText="$t('common.show_more')"
                  :lessText="$t('common.show_less')"
                  hideExpandButton
                  class="mg-top-sm"
                  >{{ repository.password }}</NsCodeSnippet
                >
              </div>
            </template>
⋮----
{{ $t("backup.data_encryption_key") }}
⋮----
<template slot="content">
                      <div>
                        {{ $t("backup.data_encryption_key_tooltip") }}
                      </div>
                    </template>
⋮----
{{ $t("backup.data_encryption_key_tooltip") }}
⋮----
>{{ repository.password }}</NsCodeSnippet
⋮----
<template slot="secondary-button">{{ $t("common.cancel") }}</template>
<template slot="primary-button">{{ $t("common.save") }}</template>
⋮----
<script>
import { UtilService, TaskService, IconService } from "@nethserver/ns8-ui-lib";
import to from "await-to-js";
export default {
  name: "EditRepositoryModal",
  mixins: [UtilService, TaskService, IconService],
  props: {
    isShown: {
      type: Boolean,
      default: true,
    },
    repository: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      name: "",
      backblaze: {
        b2_account_id: "",
        b2_account_key: "",
      },
      aws: {
        aws_access_key_id: "",
        aws_default_region: "",
        aws_secret_access_key: "",
      },
      genericS3: {
        aws_access_key_id: "",
        aws_secret_access_key: "",
      },
      cluster: {},
      smb: {
        smb_host: "",
        smb_user: "",
        smb_pass: "",
        smb_domain: "",
      },
      rclone: {
        configuration_source: "keep",
        rclone_conf_secret: "",
        base_path: "",
        configuration_uploaded_file: null,
      },
      componentKey: Date.now(),
      loading: {
        alterBackupRepository: false,
        fileReading: false,
      },
      error: {
        name: "",
        repoConnection: "",
        backblaze: {
          b2_account_id: "",
          b2_account_key: "",
        },
        aws: {
          aws_access_key_id: "",
          aws_default_region: "",
          aws_secret_access_key: "",
        },
        genericS3: {
          aws_access_key_id: "",
          aws_secret_access_key: "",
        },
        cluster: {},
        smb: {
          smb_host: "",
          smb_user: "",
          smb_pass: "",
          smb_domain: "",
        },
        rclone: {
          rclone_conf_secret: "",
          base_path: "",
          configuration_file: "",
        },
      },
    };
  },
  watch: {
    isShown: function () {
      if (this.isShown) {
        // ensure repository prop is updated as well
        this.$nextTick(() => {
          this.clearErrors();
          this.name = this.repository.name;
          switch (this.repository.provider) {
            case "backblaze":
              this.backblaze.b2_account_id =
                this.repository.parameters.b2_account_id;
              this.backblaze.b2_account_key = "";
              break;
            case "aws":
              this.aws.aws_access_key_id =
                this.repository.parameters.aws_access_key_id;
              this.aws.aws_default_region =
                this.repository.parameters.aws_default_region;
              this.aws.aws_secret_access_key = "";
              break;
            case "generic-s3":
              this.genericS3.aws_access_key_id =
                this.repository.parameters.aws_access_key_id;
              this.genericS3.aws_secret_access_key = "";
              break;
            case "smb":
              this.smb.smb_host = this.repository.parameters.smb_host;
              this.smb.smb_domain = this.repository.parameters.smb_domain;
              this.smb.smb_user = this.repository.parameters.smb_user;
              this.smb.smb_pass = "";
              break;
            case "rclone":
              this.rclone.configuration_source = "keep";
              this.rclone.rclone_conf_secret = "";
              this.rclone.base_path = this.repository.basepath || "";
              this.rclone.configuration_uploaded_file = null;
              this.componentKey = Date.now();
              break;
          }
        });
      }
    },
    "rclone.configuration_uploaded_file": function (newFiles) {
      if (newFiles && newFiles.length > 0 && newFiles[0].file) {
        const reader = new FileReader();
        this.loading.fileReading = true;
        reader.onload = (e) => {
          this.rclone.rclone_conf_secret = e.target.result.trim();
          this.loading.fileReading = false;
        };
        reader.onerror = () => {
          this.loading.fileReading = false;
          this.error.rclone.configuration_file = this.$t(
            "backup.rclone_conf_error"
          );
        };
        reader.readAsText(newFiles[0].file);
      } else {
        this.rclone.rclone_conf_secret = "";
        this.loading.fileReading = false;
      }
    },
  },
  methods: {
    buildRepositoryParameters() {
      switch (this.repository.provider) {
        case "backblaze":
          return {
            b2_account_id: this.backblaze.b2_account_id,
            b2_account_key: this.backblaze.b2_account_key,
          };
        case "aws":
          return {
            aws_default_region: this.aws.aws_default_region,
            aws_access_key_id: this.aws.aws_access_key_id,
            aws_secret_access_key: this.aws.aws_secret_access_key,
          };
        case "generic-s3":
          return {
            aws_access_key_id: this.genericS3.aws_access_key_id,
            aws_secret_access_key: this.genericS3.aws_secret_access_key,
          };
        case "rclone": {
          const secret = this.rclone.rclone_conf_secret;
          return {
            rclone_conf_secret:
              secret && !secret.endsWith("\n") ? secret + "\n" : secret,
            basepath: this.rclone.base_path,
          };
        }
        case "cluster":
          return {};
        case "smb":
          return {
            smb_host: this.smb.smb_host,
            smb_user: this.smb.smb_user,
            smb_pass: this.smb.smb_pass,
            smb_domain: this.smb.smb_domain,
          };
      }
    },
    validateAlterBackblazeRepository() {
      this.error.name = "";
      this.error.repoConnection = "";
      this.error.backblaze.b2_account_id = "";
      this.error.backblaze.b2_account_key = "";
      let isValidationOk = true;
      if (!this.backblaze.b2_account_id) {
        this.error.backblaze.b2_account_id = "common.required";
        if (isValidationOk) {
          this.focusElement("b2_account_id");
          isValidationOk = false;
        }
      }
      if (!this.name) {
        this.error.name = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("name");
          isValidationOk = false;
        }
      }
      return isValidationOk;
    },
    validateAmazonS3Repository() {
      this.error.name = "";
      this.error.repoConnection = "";
      this.error.aws.aws_access_key_id = "";
      this.error.aws.aws_default_region = "";
      this.error.aws.aws_secret_access_key = "";
      let isValidationOk = true;
      if (!this.aws.aws_access_key_id) {
        this.error.aws.aws_access_key_id = "common.required";
        if (isValidationOk) {
          this.focusElement("aws_access_key_id");
          isValidationOk = false;
        }
      }
      if (!this.aws.aws_default_region) {
        this.error.aws.aws_default_region = "common.required";
        if (isValidationOk) {
          this.focusElement("aws_default_region");
          isValidationOk = false;
        }
      }
      if (!this.name) {
        this.error.name = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("name");
          isValidationOk = false;
        }
      }
      return isValidationOk;
    },
    validateAlterSambaRepository() {
      this.error.name = "";
      this.error.repoConnection = "";
      this.error.smb.smb_host = "";
      this.error.smb.smb_user = "";
      this.error.smb.smb_pass = "";
      this.error.smb.smb_domain = "";
      let isValidationOk = true;
      if (!this.smb.smb_host) {
        this.error.smb.smb_host = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("smb_host");
          isValidationOk = false;
        }
      }
      if (!this.smb.smb_user) {
        this.error.smb.smb_user = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("smb_user");
          isValidationOk = false;
        }
      }
      if (!this.smb.smb_domain) {
        this.error.smb.smb_domain = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("smb_domain");
          isValidationOk = false;
        }
      }
      if (!this.name) {
        this.error.name = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("name");
          isValidationOk = false;
        }
      }
      return isValidationOk;
    },
    validateAlterGenericS3Repository() {
      this.error.name = "";
      this.error.repoConnection = "";
      this.error.genericS3.aws_access_key_id = "";
      this.error.genericS3.aws_secret_access_key = "";
      let isValidationOk = true;
      if (!this.genericS3.aws_access_key_id) {
        this.error.genericS3.aws_access_key_id = "common.required";
        if (isValidationOk) {
          this.focusElement("genericS3_access_key_id");
          isValidationOk = false;
        }
      }
      if (!this.name) {
        this.error.name = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("name");
          isValidationOk = false;
        }
      }
      return isValidationOk;
    },
    validateAlterClusterRepository() {
      this.error.name = "";
      this.error.repoConnection = "";
      let isValidationOk = true;
      if (!this.name) {
        this.error.name = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("name");
          isValidationOk = false;
        }
      }
      return isValidationOk;
    },
    validateAlterRcloneRepository() {
      this.error.name = "";
      this.error.repoConnection = "";
      this.error.rclone.rclone_conf_secret = "";
      this.error.rclone.base_path = "";
      this.error.rclone.configuration_file = "";
      let isValidationOk = true;
      if (this.rclone.configuration_source === "paste") {
        if (!this.rclone.rclone_conf_secret) {
          this.error.rclone.rclone_conf_secret = this.$t("common.required");
          if (isValidationOk) {
            this.focusElement("rclone_conf_secret");
            isValidationOk = false;
          }
        }
      } else if (this.rclone.configuration_source === "upload") {
        if (
          !this.rclone.configuration_uploaded_file ||
          this.rclone.configuration_uploaded_file.length === 0
        ) {
          this.error.rclone.configuration_file = this.$t("common.required");
          isValidationOk = false;
        }
      }
      if (!this.name) {
        this.error.name = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("name");
          isValidationOk = false;
        }
      }
      return isValidationOk;
    },
    validateAlterBackupRepository() {
      switch (this.repository.provider) {
        case "backblaze":
          return this.validateAlterBackblazeRepository();
        case "aws":
          return this.validateAmazonS3Repository();
        case "generic-s3":
          return this.validateAlterGenericS3Repository();
        case "smb":
          return this.validateAlterSambaRepository();
        case "cluster":
          return this.validateAlterClusterRepository();
        case "rclone":
          return this.validateAlterRcloneRepository();
      }
    },
    async alterBackupRepository() {
      if (!this.validateAlterBackupRepository()) {
        return;
      }
      this.loading.alterBackupRepository = true;
      this.error.alterBackupRepository = "";
      const taskAction = "alter-backup-repository";
      this.$root.$off(taskAction + "-validation-failed");
      this.$root.$once(
        taskAction + "-validation-failed",
        this.alterBackupRepositoryValidationFailed
      );
      this.$root.$once(
        taskAction + "-completed",
        this.alterBackupRepositoryCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {
            id: this.repository.id,
            name: this.name,
            provider: this.repository.provider,
            parameters: this.buildRepositoryParameters(),
          },
          extra: {
            title: this.$t("action." + taskAction),
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.alterBackupRepository = this.getErrorMessage(err);
        return;
      }
    },
    alterBackupRepositoryValidationFailed(validationErrors) {
      this.loading.alterBackupRepository = false;
      let focusAlreadySet = false;
      for (const validationError of validationErrors) {
        const param = validationError.parameter;
        const connectionErrors = [
          "backup_repository_not_accessible",
          "no_read_permission",
          "no_write_permission",
          "no_delete_permission",
        ];
        if (connectionErrors.includes(validationError.error)) {
          this.error.repoConnection = validationError.error;
        } else {
          if (
            this.repository.provider === "rclone" &&
            (param === "rclone_conf_secret" ||
              param === "basepath" ||
              param === "parameters")
          ) {
            const key =
              param === "basepath"
                ? "base_path"
                : param === "parameters"
                ? "rclone_conf_secret"
                : param;
            const translationKey =
              key === "rclone_conf_secret"
                ? "rclone_conf_error"
                : validationError.error;
            const errorKey =
              key === "rclone_conf_secret" &&
              this.rclone.configuration_source === "upload"
                ? "configuration_file"
                : key;
            this.error.rclone[errorKey] = this.$t("backup." + translationKey);
          } else if (param !== "provider" && param !== "(root)") {
            this.error[param] = this.$t("backup." + validationError.error);
          }
          if (!focusAlreadySet) {
            const refKey =
              this.repository.provider === "rclone" && param === "basepath"
                ? "rclone_base_path"
                : param;
            this.$nextTick(() => {
              const el = this.$refs[refKey];
              if (el) {
                if (typeof el.focus === "function") {
                  el.focus();
                } else if (el.$el) {
                  const focusable = el.$el.querySelector("input, textarea");
                  if (focusable) focusable.focus();
                }
              }
            });
            focusAlreadySet = true;
          }
        }
      }
    },
    alterBackupRepositoryCompleted() {
      this.loading.alterBackupRepository = false;
      this.$emit("repoAltered");
      this.$emit("hide");
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
::v-deep .bx--file {
  width: 100%;
  max-width: 38rem;
}
::v-deep .bx--file__drop-container {
  width: 100%;
  max-width: 38rem;
}
::v-deep .bx--file-container {
  width: 100%;
  max-width: 38rem;
}
::v-deep .bx--file__selected-file {
  background-color: #ffffff;
  max-width: 38rem;
}
.file-uploader-error ::v-deep .bx--file__drop-container {
  outline: 2px solid $danger-01;
  outline-offset: -2px;
}
.file-uploader-error .validation-failed-invalid-message {
  margin-top: -0.75rem;
  margin-bottom: 0.75rem;
  color: $danger-01;
  font-size: 0.75rem;
}
</style>
</file>

<file path="core/ui/src/components/backup/ImportBackupDestinationModal.vue">
<template>
  <NsModal
    :visible="visible"
    :primaryButtonDisabled="loading"
    :isLoading="loading"
    @primary-click="importBackupFile()"
    @secondary-click="cancelModal()"
    v-on:modal-hide-request="cancelModal()"
    autoHideOff
    hasFormContent
  >
    <template slot="title">
      {{ $t("backup.import_destinations") }}
    </template>
    <template slot="content">
      <cv-form @submit.prevent="">
        <p class="mb-6">
          {{ $t("backup.import_destinations_description") }}
        </p>
        <div class="mb-4" :class="{ 'file-uploader-error': errors.file }">
          <cv-file-uploader
            :key="componentKey"
            :label="$t('backup.cluster_backup_file')"
            :multiple="false"
            :removable="true"
            :clear-on-reselect="true"
            :drop-target-label="$t('common.drag_and_drop_or_click_to_upload')"
            v-model="backupFile"
            accept=".json.gz.gpg,.bin,.gpg"
            ref="backup_file"
          ></cv-file-uploader>
          <div v-if="errors.file" class="validation-failed-invalid-message">
            {{ errors.file }}
          </div>
        </div>
        <div class="mb-4">
          <cv-text-input
            v-model="password"
            :label="$t('backup.backup_password')"
            :helperText="$t('backup.enter_backup_password')"
            type="password"
            ref="backup_password"
            :invalid-message="errors.password"
          ></cv-text-input>
        </div>
      </cv-form>
    </template>
    <template slot="primary-button">
      {{ $t("backup.import") }}
    </template>
    <template slot="secondary-button">
      {{ $t("common.cancel") }}
    </template>
  </NsModal>
</template>
⋮----
<template slot="title">
      {{ $t("backup.import_destinations") }}
    </template>
⋮----
{{ $t("backup.import_destinations") }}
⋮----
<template slot="content">
      <cv-form @submit.prevent="">
        <p class="mb-6">
          {{ $t("backup.import_destinations_description") }}
        </p>
        <div class="mb-4" :class="{ 'file-uploader-error': errors.file }">
          <cv-file-uploader
            :key="componentKey"
            :label="$t('backup.cluster_backup_file')"
            :multiple="false"
            :removable="true"
            :clear-on-reselect="true"
            :drop-target-label="$t('common.drag_and_drop_or_click_to_upload')"
            v-model="backupFile"
            accept=".json.gz.gpg,.bin,.gpg"
            ref="backup_file"
          ></cv-file-uploader>
          <div v-if="errors.file" class="validation-failed-invalid-message">
            {{ errors.file }}
          </div>
        </div>
        <div class="mb-4">
          <cv-text-input
            v-model="password"
            :label="$t('backup.backup_password')"
            :helperText="$t('backup.enter_backup_password')"
            type="password"
            ref="backup_password"
            :invalid-message="errors.password"
          ></cv-text-input>
        </div>
      </cv-form>
    </template>
⋮----
{{ $t("backup.import_destinations_description") }}
⋮----
{{ errors.file }}
⋮----
<template slot="primary-button">
      {{ $t("backup.import") }}
    </template>
⋮----
{{ $t("backup.import") }}
⋮----
<template slot="secondary-button">
      {{ $t("common.cancel") }}
    </template>
⋮----
{{ $t("common.cancel") }}
⋮----
<script>
import { NsModal } from "@nethserver/ns8-ui-lib";
import _isEmpty from "lodash/isEmpty";
function initialData() {
  return {
    backupFile: null,
    password: "",
    componentKey: Date.now(),
    errors: {
      file: null,
      password: null,
    },
  };
}
export default {
  name: "ImportBackupDestinationModal",
  components: { NsModal },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    loading: {
      type: Boolean,
      default: false,
    },
    backupFileError: {
      type: String,
      default: null,
    },
  },
  data() {
    return initialData();
  },
  methods: {
    isFormValid() {
      return this.isFileSelected && this.password;
    },
    validateForm() {
      this.errors.file = null;
      this.errors.password = null;
      if (!this.isFileSelected) {
        this.errors.file = this.$t("common.required");
      }
      if (!this.password) {
        this.errors.password = this.$t("common.required");
      }
      return this.isFormValid();
    },
    importBackupFile() {
      if (!this.validateForm()) {
        return;
      }
      this.$emit("import-backup-submit", {
        backupFile: this.backupFile?.[0]?.file ?? null,
        backupPassword: this.password,
      });
    },
    cancelModal() {
      this.clearForm();
      this.$emit("hide");
    },
    clearForm() {
      this.backupFile = null;
      this.password = "";
      this.errors = { file: null, password: null };
    },
  },
  computed: {
    isFileSelected: function () {
      return !_isEmpty(this.backupFile);
    },
  },
  watch: {
    visible: function (newVal) {
      if (newVal) {
        const newData = initialData();
        this.backupFile = newData.backupFile;
        this.password = newData.password;
        this.componentKey = newData.componentKey;
        this.errors = newData.errors;
      }
    },
    backupFileError: function (val) {
      if (this.backupFile && this.backupFile[0]) {
        this.backupFile[0].invalidMessage = val;
      }
    },
  },
};
</script>
<style scoped>
.file-uploader-error ::v-deep .bx--file__drop-container {
  outline: 2px solid #da1e28;
  outline-offset: -2px;
}
.file-uploader-error .validation-failed-invalid-message {
  margin-top: -2rem;
}
</style>
</file>

<file path="core/ui/src/components/backup/InstanceToRestoreInfo.vue">
<template>
  <div>
    <div v-if="instance.module_ui_name">
      {{ `${instance.module_ui_name} (${instance.module_id})` }}
    </div>
    <div v-else-if="instance.module_id">
      {{ instance.module_id }}
    </div>
    <div v-else>
      {{ instance.path }}
    </div>
    <div class="secondary-row">
      {{ formattedTimestamp }}
    </div>
    <div class="secondary-row">
      {{ `${instance.repository_name} (${instance.repository_url})` }}
    </div>
    <div
      v-if="instance.node_fqdn || instance.is_generated_locally !== null"
      class="secondary-row"
    >
      <template
        v-if="instance.node_fqdn && instance.is_generated_locally !== null"
      >
        <template v-if="instance.is_generated_locally">
          {{
            $t("backup.from_node_name_of_this_cluster", {
              name: instance.node_fqdn,
            })
          }}
        </template>
        <template v-else>
          {{
            $t("backup.from_node_name_of_different_cluster", {
              name: instance.node_fqdn,
            })
          }}
        </template>
      </template>
      <template v-else-if="instance.node_fqdn">
        {{
          $t("backup.from_node_name", {
            name: instance.node_fqdn,
          })
        }}
      </template>
      <template v-else>
        <template v-if="instance.is_generated_locally">
          {{ $t("backup.from_this_cluster") }}
        </template>
        <template v-else>
          {{ $t("backup.from_different_cluster") }}
        </template>
      </template>
    </div>
  </div>
</template>
⋮----
{{ `${instance.module_ui_name} (${instance.module_id})` }}
⋮----
{{ instance.module_id }}
⋮----
{{ instance.path }}
⋮----
{{ formattedTimestamp }}
⋮----
{{ `${instance.repository_name} (${instance.repository_url})` }}
⋮----
<template
        v-if="instance.node_fqdn && instance.is_generated_locally !== null"
      >
        <template v-if="instance.is_generated_locally">
          {{
            $t("backup.from_node_name_of_this_cluster", {
              name: instance.node_fqdn,
            })
          }}
        </template>
        <template v-else>
          {{
            $t("backup.from_node_name_of_different_cluster", {
              name: instance.node_fqdn,
            })
          }}
        </template>
      </template>
⋮----
<template v-if="instance.is_generated_locally">
          {{
            $t("backup.from_node_name_of_this_cluster", {
              name: instance.node_fqdn,
            })
          }}
        </template>
⋮----
{{
            $t("backup.from_node_name_of_this_cluster", {
              name: instance.node_fqdn,
            })
          }}
⋮----
<template v-else>
          {{
            $t("backup.from_node_name_of_different_cluster", {
              name: instance.node_fqdn,
            })
          }}
        </template>
⋮----
{{
            $t("backup.from_node_name_of_different_cluster", {
              name: instance.node_fqdn,
            })
          }}
⋮----
<template v-else-if="instance.node_fqdn">
        {{
          $t("backup.from_node_name", {
            name: instance.node_fqdn,
          })
        }}
      </template>
⋮----
{{
          $t("backup.from_node_name", {
            name: instance.node_fqdn,
          })
        }}
⋮----
<template v-else>
        <template v-if="instance.is_generated_locally">
          {{ $t("backup.from_this_cluster") }}
        </template>
        <template v-else>
          {{ $t("backup.from_different_cluster") }}
        </template>
      </template>
⋮----
<template v-if="instance.is_generated_locally">
          {{ $t("backup.from_this_cluster") }}
        </template>
⋮----
{{ $t("backup.from_this_cluster") }}
⋮----
<template v-else>
          {{ $t("backup.from_different_cluster") }}
        </template>
⋮----
{{ $t("backup.from_different_cluster") }}
⋮----
<script>
import { DateTimeService } from "@nethserver/ns8-ui-lib";
export default {
  name: "InstanceToRestoreInfo",
  mixins: [DateTimeService],
  props: {
    instance: {
      type: Object,
      required: true,
    },
  },
  computed: {
    formattedTimestamp() {
      return new Intl.DateTimeFormat(navigator.language, {
        dateStyle: "long",
        timeStyle: "short",
      }).format(new Date(this.instance.timestamp * 1000));
    },
  },
  data() {
    return {};
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
.secondary-row {
  margin-top: $spacing-02;
  color: $ui-04;
}
</style>
</file>

<file path="core/ui/src/components/backup/RestoreMultipleInstancesSelector.vue">
<template>
  <div class="instance-selector">
    <div class="toolbar">
      <NsDropdownAction kind="secondary" disabled>
        <template v-slot:trigger>{{ $t("common.select") }}</template>
        <cv-overflow-menu-item @click="selectAll">
          {{ $t("common.all") }}
        </cv-overflow-menu-item>
        <cv-overflow-menu-item @click="selectNone">
          {{ $t("common.none") }}
        </cv-overflow-menu-item>
      </NsDropdownAction>
      <span class="selection-info">{{
        $t("common.x_of_y_selected", {
          selected: numSelected,
          total: instancesToDisplay.length,
        })
      }}</span>
    </div>
    <div class="search">
      <cv-search
        :label="$t('backup.search_instances')"
        :placeholder="$t('backup.search_instances')"
        :clear-aria-label="$t('common.clear_search')"
        v-model.trim="searchQuery"
        v-debounce="searchInstance"
        @input="onSearchInput"
        class="search-input"
        :disabled="loading"
        :light="light"
        ref="search"
      >
      </cv-search>
    </div>
    <div class="instance-list">
      <cv-tile v-if="loading" :light="light">
        <cv-skeleton-text :paragraph="true" :line-count="8"></cv-skeleton-text>
      </cv-tile>
      <NsEmptyState
        v-else-if="!instancesFiltered.length"
        :title="$t('common.no_search_results')"
        :animationData="GhostLottie"
        animationTitle="ghost"
        :loop="1"
      >
        <template #description>
          <div>{{ $t("common.no_search_results_description") }}</div>
        </template>
      </NsEmptyState>
      <cv-tile
        v-else
        :light="light"
        v-for="(instance, index) of instancesFilteredLoaded"
        :key="index"
        :class="['instance-tile', { 'instance-tile-light': light }]"
      >
        <label class="instance-label">
          <cv-checkbox
            v-model="selectedList"
            :value="instance.repository_id + '@' + instance.path"
            hide-label
            class="checkbox-instance"
            :id="instance.repository_id + '/' + instance.path"
          />
          <InstanceToRestoreInfo :instance="instance" />
        </label>
      </cv-tile>
      <infinite-loading
        :identifier="infiniteId"
        @infinite="infiniteScrollHandler"
      ></infinite-loading>
    </div>
  </div>
</template>
⋮----
<template v-slot:trigger>{{ $t("common.select") }}</template>
⋮----
{{ $t("common.all") }}
⋮----
{{ $t("common.none") }}
⋮----
<span class="selection-info">{{
        $t("common.x_of_y_selected", {
          selected: numSelected,
          total: instancesToDisplay.length,
        })
      }}</span>
⋮----
<template #description>
          <div>{{ $t("common.no_search_results_description") }}</div>
        </template>
⋮----
<div>{{ $t("common.no_search_results_description") }}</div>
⋮----
<script>
import { UtilService, LottieService } from "@nethserver/ns8-ui-lib";
import InstanceToRestoreInfo from "./InstanceToRestoreInfo.vue";
export default {
  name: "RestoreMultipleInstancesSelector",
  components: { InstanceToRestoreInfo },
  mixins: [UtilService, LottieService],
  props: {
    instances: {
      type: Array,
      required: true,
    },
    selection: {
      type: [String, Array],
      default: "",
    },
    loading: {
      type: Boolean,
      default: false,
    },
    light: Boolean,
    additionalVolumes: {
      type: Boolean,
      default: false,
    },
    coreApps: {
      type: Array,
      required: true,
    },
  },
  data() {
    return {
      selectedList: [],
      searchQuery: "",
      searchResults: [],
      searchFields: [
        "module_id",
        "module_ui_name",
        "name",
        "repository_name",
        "repository_provider",
        "node_fqdn",
        "repository_url",
      ],
      isSearchActive: false,
      instancesFilteredLoaded: [],
      pageNum: 0,
      pageSize: 20,
      infiniteId: +new Date(),
    };
  },
  computed: {
    numSelected() {
      return this.selectedList.length;
    },
    instancesToDisplay() {
      if (this.additionalVolumes) {
        const coreAppIds = this.coreApps.flatMap((app) =>
          app.instances.map((instance) => instance.id)
        );
        return this.instances.filter((instance) =>
          coreAppIds.includes(instance.module_id)
        );
      } else {
        return this.instances;
      }
    },
    instancesFiltered() {
      if (this.isSearchActive) {
        return this.searchResults;
      } else {
        return this.instancesToDisplay;
      }
    },
  },
  watch: {
    instances: function () {
      this.selectedList = [];
      this.updateSelection();
    },
    selection: function () {
      this.updateSelection();
    },
    selectedList: function () {
      const selectedInstances = [];
      for (const selectedValue of this.selectedList) {
        const [repoId, path] = selectedValue.split(/@(.+)/, 2);
        const instanceFound = this.instances.find(
          (i) => i.path == path && i.repository_id == repoId
        );
        if (instanceFound) {
          selectedInstances.push(instanceFound);
        }
      }
      this.$emit("select", selectedInstances);
    },
    instancesFiltered: function () {
      this.instancesFilteredLoaded = [];
      this.pageNum = 0;
      this.infiniteId += 1;
      this.infiniteScrollHandler();
    },
  },
  methods: {
    selectAll() {
      this.selectedList = [];
      for (const instance of this.instancesToDisplay) {
        this.selectedList.push(instance.repository_id + "@" + instance.path);
      }
    },
    selectNone() {
      this.selectedList = [];
    },
    updateSelection() {
      switch (this.selection) {
        case "all":
          this.selectAll();
          break;
        case "none":
        case "":
          this.selectNone();
          break;
      }
    },
    infiniteScrollHandler($state) {
      const pageInstances = this.instancesFiltered.slice(
        this.pageNum * this.pageSize,
        (this.pageNum + 1) * this.pageSize
      );
      if (pageInstances.length) {
        this.pageNum++;
        this.instancesFilteredLoaded.push(...pageInstances);
        if ($state) {
          $state.loaded();
        }
      } else {
        if ($state) {
          $state.complete();
        }
      }
    },
    searchInstance() {
      // clean query
      const cleanRegex = /[^a-zA-Z0-9]/g;
      const queryText = this.searchQuery.replace(cleanRegex, "");
      // empty search
      if (queryText.length == 0) {
        this.isSearchActive = false;
        return;
      }
      // show search results
      this.isSearchActive = true;
      // search only in instances of core apps if additional volumes are shown, otherwise in all instances
      this.searchResults = this.instancesToDisplay.filter((instance) => {
        // compare query text with all search fields of option
        return this.searchFields.some((searchField) => {
          const searchValue = instance[searchField];
          if (searchValue) {
            return new RegExp(queryText, "i").test(
              searchValue.replace(cleanRegex, "")
            );
          }
        });
      }, this);
    },
    onSearchInput() {
      // needed to manage clear search button
      if (!this.searchQuery.length) {
        this.searchInstance();
      }
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
.instance-selector {
  display: flex;
  flex-direction: column;
}
.toolbar {
  display: flex;
  flex-direction: row;
  margin-bottom: $spacing-05;
}
.search-input {
  margin-bottom: $spacing-05;
}
.selection-info {
  margin-left: $spacing-07;
}
.instance-list {
  overflow-y: auto;
  max-height: 23rem;
}
.instance-tile {
  margin-bottom: 0;
  border-bottom: 2px solid $ui-02;
}
.instance-tile-light {
  border-bottom: 2px solid $ui-01;
}
.instance-label {
  display: flex;
  align-items: center;
}
.checkbox-instance {
  display: inline-block;
  margin-top: 0 !important;
  margin-bottom: 0;
  margin-right: $spacing-05;
  flex-grow: 0;
}
</style>
⋮----
<style lang="scss">
@import "../../styles/carbon-utils";
.search-input .bx--text-input__field-wrapper,
.search-input .bx--text-input {
  max-width: 100% !important;
}
</style>
</file>

<file path="core/ui/src/components/backup/RestoreSingleInstanceModal.vue">
<template>
  <NsWizard
    size="default"
    :visible="isShown"
    :cancelLabel="$t('common.cancel')"
    :previousLabel="$t('common.previous')"
    :nextLabel="
      isLastStep || shouldShowRestoreLabel
        ? $t('backup.restore')
        : $t('common.next')
    "
    :isPreviousDisabled="isFirstStep || loading.restoreModule"
    :isNextDisabled="isNextButtonDisabled"
    @modal-hidden="$emit('hide')"
    @modal-shown="onModalShown"
    @cancel="$emit('hide')"
    @previousStep="previousStep"
    @nextStep="nextStep"
    :isLastStep="isLastStep"
  >
    <template slot="title">{{ $t("backup.restore_app") }}</template>
    <template slot="content">
      <cv-form @submit.prevent="nextStep">
        <template v-if="step == 'instance'">
          <div class="mg-bottom-md">
            {{ $t("backup.select_instance_to_restore") }}
          </div>
          <NsInlineNotification
            v-if="error.readBackupRepositories"
            kind="error"
            :title="$t('action.read-backup-repositories')"
            :description="error.readBackupRepositories"
            :showCloseButton="false"
          />
          <cv-grid class="mg-top-xlg mg-bottom-md no-padding">
            <cv-row>
              <cv-column>
                <RestoreSingleInstanceSelector
                  :instances="instances"
                  :loading="loading.readBackupRepositories"
                  :light="true"
                  @select="onSelectInstance"
                />
              </cv-column>
            </cv-row>
            <cv-row>
              <cv-column>
                <NsCheckbox
                  :label="
                    $t('backup.replace_existing_app', {
                      app: instanceToReplace,
                    })
                  "
                  v-model="replaceExistingApp"
                  :disabled="!instanceToReplace || replaceExistingDisabled"
                  value="checkReplaceExistingApp"
                  class="mg-top-xlg"
                  tooltipAlignment="start"
                  tooltipDirection="right"
                >
                  <template slot="tooltip">
                    <div
                      v-if="
                        selectedInstance &&
                        instanceToReplace &&
                        replaceExistingDisabled
                      "
                    >
                      {{
                        $t(
                          "backup.replace_existing_app_is_not_available_tooltip"
                        )
                      }}
                    </div>
                    <div v-else-if="!selectedInstance">
                      {{
                        $t("backup.replace_existing_app_select_an_app_tooltip")
                      }}
                    </div>
                    <div v-else>
                      {{ $t("backup.replace_existing_app_tooltip") }}
                    </div>
                  </template>
                </NsCheckbox>
              </cv-column>
            </cv-row>
          </cv-grid>
        </template>
        <template v-if="step == 'snapshot'">
          <div>
            {{ $t("backup.select_backup_snapshot") }}
          </div>
          <NsInlineNotification
            v-if="error.readBackupSnapshots"
            kind="error"
            :title="$t('action.read-backup-snapshots')"
            :description="error.readBackupSnapshots"
            :showCloseButton="false"
          />
          <cv-grid class="mg-top-xlg mg-bottom-md no-padding">
            <cv-row>
              <cv-column>
                <RestoreSingleInstanceSnapshotSelector
                  :snapshots="backupSnapshots"
                  :loading="loading.readBackupSnapshots"
                  :light="true"
                  @select="onSelectSnapshot"
                />
              </cv-column>
            </cv-row>
          </cv-grid>
        </template>
        <template v-if="step == 'node'">
          <div>
            {{ $t("backup.select_restore_node") }}
          </div>
          <NsInlineNotification
            v-if="error.determineRestoreEligibility"
            kind="error"
            :title="$t('action.determine-restore-eligibility')"
            :description="error.determineRestoreEligibility"
            :showCloseButton="false"
          />
          <NsInlineNotification
            v-if="error.getClusterStatus"
            kind="error"
            :title="$t('action.get-cluster-status')"
            :description="error.getClusterStatus"
            :showCloseButton="false"
          />
          <NsInlineNotification
            v-if="error.listModules"
            kind="error"
            :title="$t('action.list-modules')"
            :description="error.listModules"
            :showCloseButton="false"
          />
          <NsInlineNotification
            v-if="error.nodesList"
            kind="error"
            :title="$t('action.list-nodes')"
            :description="error.nodesList"
            :showCloseButton="false"
          />
          <NsInlineNotification
            v-if="error.listMountPoints"
            kind="error"
            :title="$t('action.list-mountpoints')"
            :description="error.listMountPoints"
            :showCloseButton="false"
          />
          <NsInlineNotification
            v-if="
              clusterNodesCount == disabledNodes.length && !isLoadingNodeData
            "
            kind="info"
            :title="$t('backup.no_node_eligible_for_instance_restoration')"
            :showCloseButton="false"
          />
          <NodeSelector
            :nodesWithAdditionalStorage="nodesWithAdditionalStorage"
            :nodesDefaultDiskInfo="nodesDefaultDiskInfo"
            @selectNode="onSelectNode"
            :disabledNodes="disabledNodes"
            :loading="isLoadingNodeData"
            class="mg-top-xlg"
          >
            <template v-for="(nodeInfoMessage, nodeId) in nodesInfo">
              <template :slot="`node-${nodeId}`">
                <template v-if="Array.isArray(nodeInfoMessage)">
                  {{ nodeInfoMessage.join(", ") }}
                </template>
                <template v-else>
                  {{ nodeInfoMessage }}
                </template>
              </template>
            </template>
          </NodeSelector>
        </template>
        <template v-else-if="step == 'volumes' && selectedNode">
          <div>
            {{
              $t("software_center.select_node_volume_for_installation", {
                node: this.getNodeLabel(selectedNode) || "",
              })
            }}. {{ $t("software_center.other_files_remain_on_default_volume") }}
          </div>
          <AdditionalVolumesSelector
            @selectVolume="onSelectVolume"
            :volumes="additionalVolumes"
            :light="true"
            class="mg-top-lg"
          />
        </template>
        <NsInlineNotification
          v-if="error.restoreModule"
          kind="error"
          :title="$t('action.restore-module')"
          :description="error.restoreModule"
          :showCloseButton="false"
        />
      </cv-form>
    </template>
  </NsWizard>
</template>
⋮----
<template slot="title">{{ $t("backup.restore_app") }}</template>
<template slot="content">
      <cv-form @submit.prevent="nextStep">
        <template v-if="step == 'instance'">
          <div class="mg-bottom-md">
            {{ $t("backup.select_instance_to_restore") }}
          </div>
          <NsInlineNotification
            v-if="error.readBackupRepositories"
            kind="error"
            :title="$t('action.read-backup-repositories')"
            :description="error.readBackupRepositories"
            :showCloseButton="false"
          />
          <cv-grid class="mg-top-xlg mg-bottom-md no-padding">
            <cv-row>
              <cv-column>
                <RestoreSingleInstanceSelector
                  :instances="instances"
                  :loading="loading.readBackupRepositories"
                  :light="true"
                  @select="onSelectInstance"
                />
              </cv-column>
            </cv-row>
            <cv-row>
              <cv-column>
                <NsCheckbox
                  :label="
                    $t('backup.replace_existing_app', {
                      app: instanceToReplace,
                    })
                  "
                  v-model="replaceExistingApp"
                  :disabled="!instanceToReplace || replaceExistingDisabled"
                  value="checkReplaceExistingApp"
                  class="mg-top-xlg"
                  tooltipAlignment="start"
                  tooltipDirection="right"
                >
                  <template slot="tooltip">
                    <div
                      v-if="
                        selectedInstance &&
                        instanceToReplace &&
                        replaceExistingDisabled
                      "
                    >
                      {{
                        $t(
                          "backup.replace_existing_app_is_not_available_tooltip"
                        )
                      }}
                    </div>
                    <div v-else-if="!selectedInstance">
                      {{
                        $t("backup.replace_existing_app_select_an_app_tooltip")
                      }}
                    </div>
                    <div v-else>
                      {{ $t("backup.replace_existing_app_tooltip") }}
                    </div>
                  </template>
                </NsCheckbox>
              </cv-column>
            </cv-row>
          </cv-grid>
        </template>
        <template v-if="step == 'snapshot'">
          <div>
            {{ $t("backup.select_backup_snapshot") }}
          </div>
          <NsInlineNotification
            v-if="error.readBackupSnapshots"
            kind="error"
            :title="$t('action.read-backup-snapshots')"
            :description="error.readBackupSnapshots"
            :showCloseButton="false"
          />
          <cv-grid class="mg-top-xlg mg-bottom-md no-padding">
            <cv-row>
              <cv-column>
                <RestoreSingleInstanceSnapshotSelector
                  :snapshots="backupSnapshots"
                  :loading="loading.readBackupSnapshots"
                  :light="true"
                  @select="onSelectSnapshot"
                />
              </cv-column>
            </cv-row>
          </cv-grid>
        </template>
        <template v-if="step == 'node'">
          <div>
            {{ $t("backup.select_restore_node") }}
          </div>
          <NsInlineNotification
            v-if="error.determineRestoreEligibility"
            kind="error"
            :title="$t('action.determine-restore-eligibility')"
            :description="error.determineRestoreEligibility"
            :showCloseButton="false"
          />
          <NsInlineNotification
            v-if="error.getClusterStatus"
            kind="error"
            :title="$t('action.get-cluster-status')"
            :description="error.getClusterStatus"
            :showCloseButton="false"
          />
          <NsInlineNotification
            v-if="error.listModules"
            kind="error"
            :title="$t('action.list-modules')"
            :description="error.listModules"
            :showCloseButton="false"
          />
          <NsInlineNotification
            v-if="error.nodesList"
            kind="error"
            :title="$t('action.list-nodes')"
            :description="error.nodesList"
            :showCloseButton="false"
          />
          <NsInlineNotification
            v-if="error.listMountPoints"
            kind="error"
            :title="$t('action.list-mountpoints')"
            :description="error.listMountPoints"
            :showCloseButton="false"
          />
          <NsInlineNotification
            v-if="
              clusterNodesCount == disabledNodes.length && !isLoadingNodeData
            "
            kind="info"
            :title="$t('backup.no_node_eligible_for_instance_restoration')"
            :showCloseButton="false"
          />
          <NodeSelector
            :nodesWithAdditionalStorage="nodesWithAdditionalStorage"
            :nodesDefaultDiskInfo="nodesDefaultDiskInfo"
            @selectNode="onSelectNode"
            :disabledNodes="disabledNodes"
            :loading="isLoadingNodeData"
            class="mg-top-xlg"
          >
            <template v-for="(nodeInfoMessage, nodeId) in nodesInfo">
              <template :slot="`node-${nodeId}`">
                <template v-if="Array.isArray(nodeInfoMessage)">
                  {{ nodeInfoMessage.join(", ") }}
                </template>
                <template v-else>
                  {{ nodeInfoMessage }}
                </template>
              </template>
            </template>
          </NodeSelector>
        </template>
        <template v-else-if="step == 'volumes' && selectedNode">
          <div>
            {{
              $t("software_center.select_node_volume_for_installation", {
                node: this.getNodeLabel(selectedNode) || "",
              })
            }}. {{ $t("software_center.other_files_remain_on_default_volume") }}
          </div>
          <AdditionalVolumesSelector
            @selectVolume="onSelectVolume"
            :volumes="additionalVolumes"
            :light="true"
            class="mg-top-lg"
          />
        </template>
        <NsInlineNotification
          v-if="error.restoreModule"
          kind="error"
          :title="$t('action.restore-module')"
          :description="error.restoreModule"
          :showCloseButton="false"
        />
      </cv-form>
    </template>
⋮----
<template v-if="step == 'instance'">
          <div class="mg-bottom-md">
            {{ $t("backup.select_instance_to_restore") }}
          </div>
          <NsInlineNotification
            v-if="error.readBackupRepositories"
            kind="error"
            :title="$t('action.read-backup-repositories')"
            :description="error.readBackupRepositories"
            :showCloseButton="false"
          />
          <cv-grid class="mg-top-xlg mg-bottom-md no-padding">
            <cv-row>
              <cv-column>
                <RestoreSingleInstanceSelector
                  :instances="instances"
                  :loading="loading.readBackupRepositories"
                  :light="true"
                  @select="onSelectInstance"
                />
              </cv-column>
            </cv-row>
            <cv-row>
              <cv-column>
                <NsCheckbox
                  :label="
                    $t('backup.replace_existing_app', {
                      app: instanceToReplace,
                    })
                  "
                  v-model="replaceExistingApp"
                  :disabled="!instanceToReplace || replaceExistingDisabled"
                  value="checkReplaceExistingApp"
                  class="mg-top-xlg"
                  tooltipAlignment="start"
                  tooltipDirection="right"
                >
                  <template slot="tooltip">
                    <div
                      v-if="
                        selectedInstance &&
                        instanceToReplace &&
                        replaceExistingDisabled
                      "
                    >
                      {{
                        $t(
                          "backup.replace_existing_app_is_not_available_tooltip"
                        )
                      }}
                    </div>
                    <div v-else-if="!selectedInstance">
                      {{
                        $t("backup.replace_existing_app_select_an_app_tooltip")
                      }}
                    </div>
                    <div v-else>
                      {{ $t("backup.replace_existing_app_tooltip") }}
                    </div>
                  </template>
                </NsCheckbox>
              </cv-column>
            </cv-row>
          </cv-grid>
        </template>
⋮----
{{ $t("backup.select_instance_to_restore") }}
⋮----
<template slot="tooltip">
                    <div
                      v-if="
                        selectedInstance &&
                        instanceToReplace &&
                        replaceExistingDisabled
                      "
                    >
                      {{
                        $t(
                          "backup.replace_existing_app_is_not_available_tooltip"
                        )
                      }}
                    </div>
                    <div v-else-if="!selectedInstance">
                      {{
                        $t("backup.replace_existing_app_select_an_app_tooltip")
                      }}
                    </div>
                    <div v-else>
                      {{ $t("backup.replace_existing_app_tooltip") }}
                    </div>
                  </template>
⋮----
{{
                        $t(
                          "backup.replace_existing_app_is_not_available_tooltip"
                        )
                      }}
⋮----
{{
                        $t("backup.replace_existing_app_select_an_app_tooltip")
                      }}
⋮----
{{ $t("backup.replace_existing_app_tooltip") }}
⋮----
<template v-if="step == 'snapshot'">
          <div>
            {{ $t("backup.select_backup_snapshot") }}
          </div>
          <NsInlineNotification
            v-if="error.readBackupSnapshots"
            kind="error"
            :title="$t('action.read-backup-snapshots')"
            :description="error.readBackupSnapshots"
            :showCloseButton="false"
          />
          <cv-grid class="mg-top-xlg mg-bottom-md no-padding">
            <cv-row>
              <cv-column>
                <RestoreSingleInstanceSnapshotSelector
                  :snapshots="backupSnapshots"
                  :loading="loading.readBackupSnapshots"
                  :light="true"
                  @select="onSelectSnapshot"
                />
              </cv-column>
            </cv-row>
          </cv-grid>
        </template>
⋮----
{{ $t("backup.select_backup_snapshot") }}
⋮----
<template v-if="step == 'node'">
          <div>
            {{ $t("backup.select_restore_node") }}
          </div>
          <NsInlineNotification
            v-if="error.determineRestoreEligibility"
            kind="error"
            :title="$t('action.determine-restore-eligibility')"
            :description="error.determineRestoreEligibility"
            :showCloseButton="false"
          />
          <NsInlineNotification
            v-if="error.getClusterStatus"
            kind="error"
            :title="$t('action.get-cluster-status')"
            :description="error.getClusterStatus"
            :showCloseButton="false"
          />
          <NsInlineNotification
            v-if="error.listModules"
            kind="error"
            :title="$t('action.list-modules')"
            :description="error.listModules"
            :showCloseButton="false"
          />
          <NsInlineNotification
            v-if="error.nodesList"
            kind="error"
            :title="$t('action.list-nodes')"
            :description="error.nodesList"
            :showCloseButton="false"
          />
          <NsInlineNotification
            v-if="error.listMountPoints"
            kind="error"
            :title="$t('action.list-mountpoints')"
            :description="error.listMountPoints"
            :showCloseButton="false"
          />
          <NsInlineNotification
            v-if="
              clusterNodesCount == disabledNodes.length && !isLoadingNodeData
            "
            kind="info"
            :title="$t('backup.no_node_eligible_for_instance_restoration')"
            :showCloseButton="false"
          />
          <NodeSelector
            :nodesWithAdditionalStorage="nodesWithAdditionalStorage"
            :nodesDefaultDiskInfo="nodesDefaultDiskInfo"
            @selectNode="onSelectNode"
            :disabledNodes="disabledNodes"
            :loading="isLoadingNodeData"
            class="mg-top-xlg"
          >
            <template v-for="(nodeInfoMessage, nodeId) in nodesInfo">
              <template :slot="`node-${nodeId}`">
                <template v-if="Array.isArray(nodeInfoMessage)">
                  {{ nodeInfoMessage.join(", ") }}
                </template>
                <template v-else>
                  {{ nodeInfoMessage }}
                </template>
              </template>
            </template>
          </NodeSelector>
        </template>
⋮----
{{ $t("backup.select_restore_node") }}
⋮----
<template v-for="(nodeInfoMessage, nodeId) in nodesInfo">
              <template :slot="`node-${nodeId}`">
                <template v-if="Array.isArray(nodeInfoMessage)">
                  {{ nodeInfoMessage.join(", ") }}
                </template>
                <template v-else>
                  {{ nodeInfoMessage }}
                </template>
              </template>
            </template>
⋮----
<template :slot="`node-${nodeId}`">
                <template v-if="Array.isArray(nodeInfoMessage)">
                  {{ nodeInfoMessage.join(", ") }}
                </template>
                <template v-else>
                  {{ nodeInfoMessage }}
                </template>
              </template>
⋮----
<template v-if="Array.isArray(nodeInfoMessage)">
                  {{ nodeInfoMessage.join(", ") }}
                </template>
⋮----
{{ nodeInfoMessage.join(", ") }}
⋮----
<template v-else>
                  {{ nodeInfoMessage }}
                </template>
⋮----
{{ nodeInfoMessage }}
⋮----
<template v-else-if="step == 'volumes' && selectedNode">
          <div>
            {{
              $t("software_center.select_node_volume_for_installation", {
                node: this.getNodeLabel(selectedNode) || "",
              })
            }}. {{ $t("software_center.other_files_remain_on_default_volume") }}
          </div>
          <AdditionalVolumesSelector
            @selectVolume="onSelectVolume"
            :volumes="additionalVolumes"
            :light="true"
            class="mg-top-lg"
          />
        </template>
⋮----
{{
              $t("software_center.select_node_volume_for_installation", {
                node: this.getNodeLabel(selectedNode) || "",
              })
            }}. {{ $t("software_center.other_files_remain_on_default_volume") }}
⋮----
}}. {{ $t("software_center.other_files_remain_on_default_volume") }}
⋮----
<script>
import { UtilService, TaskService, IconService } from "@nethserver/ns8-ui-lib";
import to from "await-to-js";
import NodeSelector from "@/components/nodes/NodeSelector";
import RestoreSingleInstanceSelector from "@/components/backup/RestoreSingleInstanceSelector";
import { mapState } from "vuex";
import RestoreSingleInstanceSnapshotSelector from "./RestoreSingleInstanceSnapshotSelector.vue";
import AdditionalVolumesSelector from "@/components/software-center/AdditionalVolumesSelector.vue";
export default {
  name: "RestoreSingleInstanceModal",
  components: {
    NodeSelector,
    RestoreSingleInstanceSelector,
    RestoreSingleInstanceSnapshotSelector,
    AdditionalVolumesSelector,
  },
  mixins: [UtilService, TaskService, IconService],
  props: {
    isShown: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      step: "",
      steps: ["instance", "snapshot", "node", "volumes"],
      instances: [],
      backupSnapshots: [],
      selectedNode: null,
      selectedInstance: null,
      selectedSnapshot: null,
      replaceExistingApp: false,
      installDestinations: [],
      clusterStatus: [],
      nodesList: [],
      selectedVolume: {},
      modules: [],
      nodesDefaultDiskInfo: {},
      nodesAdditionalDiskInfo: {},
      loading: {
        readBackupRepositories: true,
        restoreModule: false,
        readBackupSnapshots: false,
        determineRestoreEligibility: false,
        getClusterStatus: true,
        listModules: true,
        nodesList: true,
      },
      error: {
        readBackupRepositories: "",
        restoreModule: "",
        readBackupSnapshots: "",
        determineRestoreEligibility: "",
        getClusterStatus: "",
        listMountPoints: "",
        listModules: "",
      },
    };
  },
  computed: {
    ...mapState(["clusterNodes"]),
    isLoadingNodeData() {
      return (
        this.loading.determineRestoreEligibility ||
        this.loading.nodesList ||
        this.loading.listModules ||
        this.loading.getClusterStatus
      );
    },
    clusterNodesCount() {
      return this.clusterNodes.length;
    },
    stepIndex() {
      return this.steps.indexOf(this.step);
    },
    isFirstStep() {
      return this.stepIndex == 0;
    },
    isLastStep() {
      if (this.step == "node" && this.selectedNode) {
        if (
          !this.nodesWithAdditionalStorage.includes(this.selectedNode.id) ||
          this.appVolumes.length === 0
        ) {
          return true;
        }
      }
      return this.stepIndex == this.steps.length - 1;
    },
    isNextButtonDisabled() {
      return (
        this.loading.restoreModule ||
        (this.step == "instance" && !this.selectedInstance) ||
        (this.step == "snapshot" && !this.selectedSnapshot) ||
        (this.step == "node" &&
          (this.isLoadingNodeData ||
            !this.selectedNode ||
            (this.clusterNodesCount == this.disabledNodes.length &&
              !this.shouldShowRestoreLabel))) ||
        (this.step == "volumes" &&
          (!this.selectedNode ||
            !this.selectedVolume ||
            Object.keys(this.selectedVolume).length === 0))
      );
    },
    selectedModule() {
      if (
        !this.selectedInstance ||
        !this.modules ||
        this.modules.length === 0
      ) {
        return null;
      }
      return this.modules.find(
        (module) => module.id === this.selectedInstance.name
      );
    },
    additionalVolumes() {
      const output = this.nodesAdditionalDiskInfo[this.selectedNode?.id];
      if (!output) return [];
      const volumes = [...output.mountpoints];
      if (output.default_disk) {
        volumes.push({ ...output.default_disk, default: true });
      }
      return volumes;
    },
    appVolumes() {
      if (
        this.selectedModule &&
        this.selectedModule.versions &&
        this.selectedModule.versions.length &&
        this.selectedModule.versions[0].labels &&
        this.selectedModule.versions[0].labels["org.nethserver.volumes"]
      ) {
        const volumesString =
          this.selectedModule.versions[0].labels["org.nethserver.volumes"];
        return volumesString.split(" ").map((v) => v.trim());
      }
      return [];
    },
    instanceToReplace() {
      if (
        !(this.selectedInstance && this.selectedInstance.installed_instance)
      ) {
        return "";
      }
      if (this.selectedInstance.installed_instance_ui_name) {
        return (
          this.selectedInstance.installed_instance_ui_name +
          " (" +
          this.selectedInstance.installed_instance +
          ")"
        );
      } else {
        return this.selectedInstance.installed_instance;
      }
    },
    replaceExistingDisabled() {
      // FIXME: remove hardcoded values due to the static port, the API should give us this info
      //check if the selected instance is not in an array ['loki']
      const notAllowed = [
        "samba",
        "loki",
        "mail",
        "ejabberd",
        "nethvoice-proxy",
      ];
      return notAllowed.includes(this.selectedInstance.name) ? true : false;
    },
    nodesInfo() {
      const nodesInfo = {};
      for (const nodeInfo of this.installDestinations) {
        if (!nodeInfo.eligible) {
          const rejectReason = nodeInfo.reject_reason;
          if (rejectReason.message === "max_per_node_limit") {
            const numMaxInstances = rejectReason.parameter;
            nodesInfo[nodeInfo.node_id] = this.$tc(
              `software_center.reason_${rejectReason.message}`,
              numMaxInstances,
              { param: numMaxInstances }
            );
          } else {
            nodesInfo[nodeInfo.node_id] = this.$t(
              `software_center.reason_${rejectReason.message}`,
              { param: rejectReason.parameter }
            );
          }
        } else if (nodeInfo.instances) {
          nodesInfo[nodeInfo.node_id] = this.$tc(
            "software_center.num_instances_installed",
            nodeInfo.instances,
            { num: nodeInfo.instances }
          );
        }
      }
      for (const node of this.clusterStatus) {
        if (!node.online) {
          nodesInfo[node.id] = this.$t("software_center.node_offline");
        }
      }
      return nodesInfo;
    },
    disabledNodes() {
      const nonEligibleNodeIds = this.installDestinations
        .filter((nodeInfo) => !nodeInfo.eligible)
        .map((nodeInfo) => nodeInfo.node_id);
      const offlineNodeIds = this.clusterStatus
        .filter((node) => !node.online)
        .map((node) => node.id);
      return [...new Set([...nonEligibleNodeIds, ...offlineNodeIds])];
    },
    nodesWithAdditionalStorage() {
      const nodeIds = [];
      if (this.appVolumes.length === 0) {
        return nodeIds;
      }
      if (this.nodesList && Array.isArray(this.nodesList)) {
        for (const node of this.nodesList) {
          if (node.additional_disk_count > 0) {
            nodeIds.push(node.node_id);
          }
        }
      }
      return nodeIds;
    },
    shouldShowRestoreLabel() {
      return (
        this.step == "node" &&
        this.selectedNode &&
        (!this.nodesWithAdditionalStorage.includes(this.selectedNode.id) ||
          this.appVolumes.length === 0)
      );
    },
  },
  watch: {
    isShown: function () {
      if (this.isShown) {
        this.step = this.steps[0];
        this.selectedInstance = null;
        this.replaceExistingApp = false;
        this.readBackupRepositories();
      }
    },
    step: function () {
      if (this.step == "instance") {
        this.selectedInstance = null;
        this.replaceExistingApp = false;
      } else if (this.step == "snapshot") {
        this.selectedSnapshot = null;
        this.readBackupSnapshots();
      } else if (this.step == "node") {
        this.nodesDefaultDiskInfo = {};
        this.nodesAdditionalDiskInfo = {};
        this.determineRestoreEligibility();
        this.listNodes();
        this.listModules();
        this.getClusterStatus();
      }
    },
  },
  methods: {
    nextStep() {
      if (this.isNextButtonDisabled) {
        return;
      }
      if (this.isLastStep) {
        this.restoreModule(this.selectedVolume);
      } else {
        if (
          this.step == "node" &&
          (!this.nodesWithAdditionalStorage.includes(this.selectedNode.id) ||
            this.appVolumes.length === 0)
        ) {
          this.restoreModule();
        } else {
          this.step = this.steps[this.stepIndex + 1];
        }
      }
    },
    previousStep() {
      if (!this.isFirstStep) {
        this.selectedVolume = {};
        this.step = this.steps[this.stepIndex - 1];
      }
    },
    onModalShown() {
      this.clearErrors();
      this.clusterStatus = [];
      this.nodesList = [];
      this.selectedVolume = {};
      this.instances = [];
      this.backupSnapshots = [];
      this.selectedInstance = null;
      this.selectedSnapshot = null;
      this.replaceExistingApp = false;
      this.installDestinations = [];
      this.nodesAdditionalDiskInfo = {};
      if (this.clusterNodesCount == 1) {
        const firstNode = this.clusterNodes[0];
        this.selectedNode = { ...firstNode, selected: true };
      } else {
        this.selectedNode = null;
      }
    },
    async listModules() {
      this.loading.listModules = true;
      this.error.listModules = "";
      this.modules = [];
      const taskAction = "list-modules";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.listModulesAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.listModulesCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.listModules = this.getErrorMessage(err);
        this.loading.listModules = false;
        return;
      }
    },
    listModulesAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.listModules = this.$t("error.generic_error");
      this.loading.listModules = false;
    },
    listModulesCompleted(taskContext, taskResult) {
      this.loading.listModules = false;
      let modules = taskResult.output;
      this.modules = modules;
      this.loading.listModules = false;
    },
    async listNodes() {
      this.error.nodesList = "";
      this.loading.nodesList = true;
      const taskAction = "list-nodes";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.listNodesAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.listNodesCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.nodesList = this.getErrorMessage(err);
        return;
      }
    },
    listNodesAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.nodesList = this.$t("error.generic_error");
      this.loading.nodesList = false;
    },
    listNodesCompleted(taskContext, taskResult) {
      this.nodesList = taskResult.output.nodes;
      this.loading.nodesList = false;
    },
    async listMountPoints(nodeId) {
      const taskAction = "list-mountpoints";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.listMountPointsAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        (taskContext, taskResult) =>
          this.listMountPointsCompleted(taskContext, taskResult, nodeId)
      );
      const res = await to(
        this.createNodeTask(nodeId, {
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(
          `error creating task ${taskAction} for node ${nodeId}`,
          err
        );
        this.error.listMountPoints = this.getErrorMessage(err);
        return;
      }
    },
    listMountPointsAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.listMountPoints = this.$t("error.generic_error");
    },
    listMountPointsCompleted(taskContext, taskResult, nodeId) {
      const output = taskResult.output;
      this.$set(this.nodesAdditionalDiskInfo, nodeId, output);
      if (output.default_disk) {
        this.$set(this.nodesDefaultDiskInfo, nodeId, output.default_disk);
      }
    },
    async readBackupRepositories() {
      this.error.readBackupRepositories = "";
      this.loading.readBackupRepositories = true;
      const taskAction = "read-backup-repositories";
      this.$root.$off(taskAction + "-aborted");
      this.$root.$once(
        taskAction + "-aborted",
        this.readBackupRepositoriesAborted
      );
      this.$root.$off(taskAction + "-completed");
      this.$root.$once(
        taskAction + "-completed",
        this.readBackupRepositoriesCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.readBackupRepositories = this.getErrorMessage(err);
        return;
      }
    },
    readBackupRepositoriesAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.readBackupRepositories = this.$t("error.generic_error");
      this.loading.readBackupRepositories = false;
    },
    readBackupRepositoriesCompleted(taskContext, taskResult) {
      let instances = taskResult.output;
      instances.sort(this.sortByProperty("timestamp")).reverse();
      this.instances = instances;
      this.loading.readBackupRepositories = false;
    },
    async readBackupSnapshots() {
      this.error.readBackupSnapshots = "";
      this.loading.readBackupSnapshots = true;
      const taskAction = "read-backup-snapshots";
      this.$root.$off(taskAction + "-aborted");
      this.$root.$once(
        taskAction + "-aborted",
        this.readBackupSnapshotsAborted
      );
      this.$root.$off(taskAction + "-completed");
      this.$root.$once(
        taskAction + "-completed",
        this.readBackupSnapshotsCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {
            repository: this.selectedInstance.repository_id,
            path: this.selectedInstance.path,
          },
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.readBackupSnapshots = this.getErrorMessage(err);
        return;
      }
    },
    readBackupSnapshotsAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      if (taskResult.error.includes("wrong password or no key found")) {
        this.error.readBackupSnapshots = this.$t(
          "backup.wrong_password_or_no_key_found"
        );
      } else {
        this.error.readBackupSnapshots = this.$t("error.generic_error");
      }
      this.loading.readBackupSnapshots = false;
    },
    readBackupSnapshotsCompleted(taskContext, taskResult) {
      let snapshots = taskResult.output;
      snapshots.sort(this.sortByProperty("timestamp")).reverse();
      this.backupSnapshots = snapshots;
      this.loading.readBackupSnapshots = false;
    },
    async restoreModule(volumes) {
      this.loading.restoreModule = true;
      this.error.restoreModule = "";
      const taskAction = "restore-module";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.restoreModuleAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.restoreModuleCompleted
      );
      const app = this.selectedInstance.path.split("/")[0];
      const nodeName =
        this.selectedNode.ui_name ||
        this.$t("common.node") + ` ${this.selectedNode.id}`;
      const data = {
        repository: this.selectedInstance.repository_id,
        path: this.selectedInstance.path,
        snapshot: this.selectedSnapshot.id,
        node: this.selectedNode.id,
        replace: this.replaceExistingApp,
      };
      if (volumes?.path && this.appVolumes.length) {
        data.volumes = {};
        this.appVolumes.forEach((volume) => {
          data.volumes[volume] = volumes.path;
        });
      }
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data,
          extra: {
            eventId,
            title: this.$t("action." + taskAction),
            description: this.$t("backup.restoring_app_to_node", {
              app: app,
              node: nodeName,
            }),
            node: nodeName,
            completion: {
              i18nString: "backup.instance_restored_to_node",
              extraTextParams: ["node"],
              outputTextParams: ["module_id"],
            },
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.restoreModule = this.getErrorMessage(err);
        this.loading.restoreModule = false;
        return;
      }
      this.loading.restoreModule = false;
      this.$emit("hide");
    },
    restoreModuleAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.restoreModule = this.$t("error.generic_error");
      this.loading.restoreModule = false;
      this.$emit("hide");
    },
    restoreModuleCompleted() {
      this.loading.restoreModule = false;
      this.$root.$emit("reloadAppDrawer");
    },
    onSelectNode(selectedNode) {
      this.selectedNode = selectedNode;
    },
    onSelectInstance(selectedInstance) {
      this.selectedInstance = selectedInstance;
      this.replaceExistingApp = false;
    },
    onSelectSnapshot(selectedSnapshot) {
      this.selectedSnapshot = selectedSnapshot;
    },
    onSelectVolume(selectedVolume) {
      this.selectedVolume = selectedVolume;
    },
    async determineRestoreEligibility() {
      this.loading.determineRestoreEligibility = true;
      this.error.determineRestoreEligibility = "";
      this.selectedNode = null;
      const taskAction = "determine-restore-eligibility";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.determineRestoreEligibilityAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.determineRestoreEligibilityCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {
            repository: this.selectedInstance.repository_id,
            path: this.selectedInstance.path,
            snapshot: this.selectedSnapshot.id,
          },
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.determineRestoreEligibility = this.getErrorMessage(err);
        return;
      }
    },
    determineRestoreEligibilityAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.determineRestoreEligibility = this.$t("error.generic_error");
      this.loading.determineRestoreEligibility = false;
    },
    determineRestoreEligibilityCompleted(taskContext, taskResult) {
      this.installDestinations = taskResult.output.install_destinations;
      this.loading.determineRestoreEligibility = false;
    },
    async getClusterStatus() {
      this.loading.getClusterStatus = true;
      this.error.getClusterStatus = "";
      const taskAction = "get-cluster-status";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.getClusterStatusAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.getClusterStatusCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.getClusterStatus = this.getErrorMessage(err);
        return;
      }
    },
    getClusterStatusAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.getClusterStatus = this.$t("error.generic_error");
      this.loading.getClusterStatus = false;
    },
    getClusterStatusCompleted(taskContext, taskResult) {
      this.clusterStatus = taskResult.output.nodes;
      for (const node of this.clusterStatus.filter((n) => n.online)) {
        this.listMountPoints(node.id);
      }
      this.loading.getClusterStatus = false;
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
.instances {
  margin-top: $spacing-07;
}
</style>
</file>

<file path="core/ui/src/components/backup/RestoreSingleInstanceSelector.vue">
<template>
  <div class="instance-selector">
    <div class="search">
      <cv-search
        :label="$t('backup.search_instances')"
        :placeholder="$t('backup.search_instances')"
        :clear-aria-label="$t('common.clear_search')"
        v-model.trim="searchQuery"
        v-debounce="searchInstance"
        @input="onSearchInput"
        class="search-input"
        :disabled="loading"
        :light="light"
        ref="search"
      >
      </cv-search>
    </div>
    <div class="instance-list">
      <div v-if="loading">
        <cv-tile
          v-for="index in 3"
          :key="index"
          :light="light"
          class="instance-tile"
        >
          <cv-skeleton-text
            :paragraph="true"
            :line-count="3"
          ></cv-skeleton-text>
        </cv-tile>
      </div>
      <NsEmptyState
        v-else-if="!internalInstances.length"
        :title="$t('backup.no_instance_to_restore')"
      >
        <template #description>{{
          $t("backup.no_instance_to_restore_description")
        }}</template>
      </NsEmptyState>
      <NsEmptyState
        v-else-if="!instancesFiltered.length"
        :title="$t('common.no_search_results')"
        :animationData="GhostLottie"
        animationTitle="ghost"
        :loop="1"
      >
        <template #description>
          <div>{{ $t("common.no_search_results_description") }}</div>
        </template>
      </NsEmptyState>
      <NsTile
        v-else
        v-for="(instance, index) of instancesFilteredLoaded"
        :key="index"
        :light="light"
        kind="selectable"
        v-model="instance.selected"
        value="instanceValue"
        @click="deselectOtherInstances(instance)"
        class="instance-tile"
      >
        <InstanceToRestoreInfo :instance="instance" />
      </NsTile>
      <infinite-loading
        :identifier="infiniteId"
        @infinite="infiniteScrollHandler"
      ></infinite-loading>
    </div>
  </div>
</template>
⋮----
<template #description>{{
          $t("backup.no_instance_to_restore_description")
        }}</template>
⋮----
<template #description>
          <div>{{ $t("common.no_search_results_description") }}</div>
        </template>
⋮----
<div>{{ $t("common.no_search_results_description") }}</div>
⋮----
<script>
import { UtilService, LottieService } from "@nethserver/ns8-ui-lib";
import _cloneDeep from "lodash/cloneDeep";
import InstanceToRestoreInfo from "./InstanceToRestoreInfo.vue";
export default {
  name: "RestoreSingleInstanceSelector",
  components: { InstanceToRestoreInfo },
  mixins: [UtilService, LottieService],
  props: {
    instances: {
      type: Array,
      required: true,
    },
    loading: {
      type: Boolean,
      default: false,
    },
    light: Boolean,
  },
  data() {
    return {
      internalInstances: [],
      searchQuery: "",
      searchResults: [],
      searchFields: [
        "module_id",
        "module_ui_name",
        "name",
        "repository_name",
        "repository_provider",
        "node_fqdn",
        "repository_url",
      ],
      isSearchActive: false,
      instancesFilteredLoaded: [],
      pageNum: 0,
      pageSize: 20,
      infiniteId: +new Date(),
    };
  },
  computed: {
    instancesFiltered() {
      if (this.isSearchActive) {
        return this.searchResults;
      } else {
        return this.internalInstances;
      }
    },
    selectedInstance() {
      return this.internalInstances.find((i) => i.selected);
    },
  },
  watch: {
    selectedInstance: function () {
      this.$emit("select", this.selectedInstance);
    },
    instances: function () {
      this.updateInternalInstances();
    },
    loading: function () {
      this.searchQuery = "";
      this.searchResults = [];
      this.isSearchActive = false;
    },
    instancesFiltered: function () {
      this.instancesFilteredLoaded = [];
      this.pageNum = 0;
      this.infiniteId += 1;
      this.infiniteScrollHandler();
    },
  },
  created() {
    this.updateInternalInstances();
  },
  methods: {
    updateInternalInstances() {
      // deep copy (needed to avoid reactivity issues)
      let internalInstances = _cloneDeep(this.instances);
      for (const instance of internalInstances) {
        instance.selected = false;
      }
      this.internalInstances = internalInstances;
    },
    searchInstance() {
      // clean query
      const cleanRegex = /[^a-zA-Z0-9]/g;
      const queryText = this.searchQuery.replace(cleanRegex, "");
      // empty search
      if (queryText.length == 0) {
        this.isSearchActive = false;
        return;
      }
      // show search results
      this.isSearchActive = true;
      // search
      this.searchResults = this.internalInstances.filter((instance) => {
        // compare query text with all search fields of option
        return this.searchFields.some((searchField) => {
          const searchValue = instance[searchField];
          if (searchValue) {
            return new RegExp(queryText, "i").test(
              searchValue.replace(cleanRegex, "")
            );
          }
        });
      }, this);
    },
    onSearchInput() {
      // needed to manage clear search button
      if (!this.searchQuery.length) {
        this.searchInstance();
      }
    },
    deselectOtherInstances(instance) {
      for (let i of this.internalInstances) {
        if (i.path !== instance.path) {
          i.selected = false;
        }
      }
    },
    infiniteScrollHandler($state) {
      const pageItems = this.instancesFiltered.slice(
        this.pageNum * this.pageSize,
        (this.pageNum + 1) * this.pageSize
      );
      if (pageItems.length) {
        this.pageNum++;
        this.instancesFilteredLoaded.push(...pageItems);
        if ($state) {
          $state.loaded();
        }
      } else {
        if ($state) {
          $state.complete();
        }
      }
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
.instance-selector {
  display: flex;
  flex-direction: column;
}
.search-input {
  margin-bottom: $spacing-05;
}
.instance-list {
  overflow-y: auto;
  max-height: 23rem;
}
.ns-tile.instance-tile,
.cv-tile.instance-tile {
  margin-bottom: $spacing-03;
}
.secondary-row {
  margin-top: $spacing-02;
  color: $ui-04;
}
</style>
⋮----
<style lang="scss">
@import "../../styles/carbon-utils";
.search-input .bx--text-input__field-wrapper,
.search-input .bx--text-input {
  max-width: 100% !important;
}
</style>
</file>

<file path="core/ui/src/components/backup/RestoreSingleInstanceSnapshotSelector.vue">
<template>
  <div class="snapshot-selector">
    <div class="snapshot-list">
      <div v-if="loading">
        <cv-tile
          v-for="index in 3"
          :key="index"
          :light="light"
          class="snapshot-tile"
        >
          <cv-skeleton-text
            :paragraph="true"
            :line-count="2"
          ></cv-skeleton-text>
        </cv-tile>
      </div>
      <NsEmptyState
        v-else-if="!internalSnapshots.length"
        :title="$t('backup.no_snapshot_to_restore')"
      />
      <NsTile
        v-else
        v-for="(snapshot, index) of internalSnapshotsLoaded"
        :key="index"
        :light="light"
        kind="selectable"
        v-model="snapshot.selected"
        value="snapshotValue"
        @click="deselectOtherSnapshots(snapshot)"
        class="snapshot-tile"
      >
        <div class="flex items-center gap-2">
          <span>{{ formatSnapshotTimestamp(snapshot.timestamp) }}</span>
          <cv-tag
            v-if="index == 0"
            kind="blue"
            :label="$t('backup.most_recent')"
            size="sm"
            class="no-margin"
          ></cv-tag>
        </div>
        <div class="secondary-row">
          {{
            snapshot.total_bytes >= 0
              ? $options.filters.byteFormat(snapshot.total_bytes)
              : "-"
          }}
        </div>
      </NsTile>
      <infinite-loading
        :identifier="infiniteId"
        @infinite="infiniteScrollHandler"
      ></infinite-loading>
    </div>
  </div>
</template>
⋮----
<span>{{ formatSnapshotTimestamp(snapshot.timestamp) }}</span>
⋮----
{{
            snapshot.total_bytes >= 0
              ? $options.filters.byteFormat(snapshot.total_bytes)
              : "-"
          }}
⋮----
<script>
import { UtilService, DateTimeService } from "@nethserver/ns8-ui-lib";
import _cloneDeep from "lodash/cloneDeep";
export default {
  name: "RestoreSingleInstanceSnapshotSelector",
  components: {},
  mixins: [UtilService, DateTimeService],
  props: {
    snapshots: {
      type: Array,
      required: true,
    },
    loading: {
      type: Boolean,
      default: false,
    },
    light: Boolean,
  },
  data() {
    return {
      internalSnapshots: [],
      internalSnapshotsLoaded: [],
      pageNum: 0,
      pageSize: 20,
      infiniteId: +new Date(),
    };
  },
  computed: {
    selectedSnapshot() {
      return this.internalSnapshots.find((i) => i.selected);
    },
  },
  watch: {
    selectedSnapshot: function () {
      this.$emit("select", this.selectedSnapshot);
    },
    snapshots: function () {
      this.updateInternalSnapshots();
    },
    internalSnapshots: function () {
      this.internalSnapshotsLoaded = [];
      this.pageNum = 0;
      this.infiniteId += 1;
      this.infiniteScrollHandler();
    },
  },
  created() {
    this.updateInternalSnapshots();
  },
  methods: {
    formatSnapshotTimestamp(timestamp) {
      return new Intl.DateTimeFormat(navigator.language, {
        dateStyle: "long",
        timeStyle: "short",
      }).format(new Date(timestamp * 1000));
    },
    updateInternalSnapshots() {
      let internalSnapshots = _cloneDeep(this.snapshots);
      for (const snapshot of internalSnapshots) {
        snapshot.selected = false;
      }
      this.internalSnapshots = internalSnapshots;
    },
    deselectOtherSnapshots(snapshot) {
      for (let s of this.internalSnapshots) {
        if (s.id !== snapshot.id) {
          s.selected = false;
        }
      }
    },
    infiniteScrollHandler($state) {
      const pageItems = this.internalSnapshots.slice(
        this.pageNum * this.pageSize,
        (this.pageNum + 1) * this.pageSize
      );
      if (pageItems.length) {
        this.pageNum++;
        this.internalSnapshotsLoaded.push(...pageItems);
        if ($state) {
          $state.loaded();
        }
      } else {
        if ($state) {
          $state.complete();
        }
      }
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
.snapshot-selector {
  display: flex;
  flex-direction: column;
}
.snapshot-list {
  overflow-y: auto;
  max-height: 21rem;
}
.ns-tile.snapshot-tile,
.cv-tile.snapshot-tile {
  margin-bottom: $spacing-03;
}
.secondary-row {
  margin-top: $spacing-02;
  color: $ui-04;
}
</style>
</file>

<file path="core/ui/src/components/domains/AddExternalProviderModal.vue">
<template>
  <NsModal
    v-if="domain"
    size="default"
    :visible="isShown"
    @modal-hidden="$emit('hide')"
    @primary-click="addExternalProvider"
    :primary-button-disabled="loading.addExternalProvider"
  >
    <template slot="title">{{
      $t("domain_configuration.add_provider")
    }}</template>
    <template slot="content">
      <cv-form @submit.prevent="addExternalProvider">
        <cv-text-input
          :label="$t('domains.host')"
          v-model.trim="host"
          :invalid-message="$t(error.host)"
          :disabled="loading.addExternalProvider"
          ref="host"
        >
        </cv-text-input>
        <cv-text-input
          :label="$t('domains.port')"
          v-model.trim="port"
          :invalid-message="$t(error.port)"
          type="number"
          :disabled="loading.addExternalProvider"
          ref="port"
        >
        </cv-text-input>
      </cv-form>
      <NsInlineNotification
        v-if="error.addExternalProvider"
        kind="error"
        :title="$t('action.add-external-provider')"
        :description="error.addExternalProvider"
        :showCloseButton="false"
      />
    </template>
    <template slot="secondary-button">{{ $t("common.cancel") }}</template>
    <template slot="primary-button">{{
      $t("domain_configuration.add_provider")
    }}</template>
  </NsModal>
</template>
⋮----
<template slot="title">{{
      $t("domain_configuration.add_provider")
    }}</template>
<template slot="content">
      <cv-form @submit.prevent="addExternalProvider">
        <cv-text-input
          :label="$t('domains.host')"
          v-model.trim="host"
          :invalid-message="$t(error.host)"
          :disabled="loading.addExternalProvider"
          ref="host"
        >
        </cv-text-input>
        <cv-text-input
          :label="$t('domains.port')"
          v-model.trim="port"
          :invalid-message="$t(error.port)"
          type="number"
          :disabled="loading.addExternalProvider"
          ref="port"
        >
        </cv-text-input>
      </cv-form>
      <NsInlineNotification
        v-if="error.addExternalProvider"
        kind="error"
        :title="$t('action.add-external-provider')"
        :description="error.addExternalProvider"
        :showCloseButton="false"
      />
    </template>
<template slot="secondary-button">{{ $t("common.cancel") }}</template>
<template slot="primary-button">{{
      $t("domain_configuration.add_provider")
    }}</template>
⋮----
<script>
import { UtilService, TaskService, IconService } from "@nethserver/ns8-ui-lib";
import to from "await-to-js";
export default {
  name: "AddExternalProviderModal",
  mixins: [UtilService, TaskService, IconService],
  props: {
    isShown: {
      type: Boolean,
      default: true,
    },
    domain: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      host: "",
      port: "",
      loading: {
        addExternalProvider: false,
      },
      error: {
        host: "",
        port: "",
        addExternalProvider: "",
      },
    };
  },
  watch: {
    isShown: function () {
      if (this.isShown) {
        this.clearErrors(this);
        // reset form
        this.host = "";
        this.port = "";
        setTimeout(() => {
          this.focusElement("host");
        }, 300);
      }
    },
  },
  methods: {
    validateAddExternalProvider() {
      this.clearErrors(this);
      let isValidationOk = true;
      if (!this.host) {
        this.error.host = "common.required";
        if (isValidationOk) {
          this.focusElement("host");
          isValidationOk = false;
        }
      }
      if (!this.port) {
        this.error.port = "common.required";
        if (isValidationOk) {
          this.focusElement("port");
          isValidationOk = false;
        }
      }
      return isValidationOk;
    },
    async addExternalProvider() {
      if (!this.validateAddExternalProvider()) {
        return;
      }
      this.loading.addExternalProvider = true;
      const taskAction = "add-external-provider";
      this.$root.$off(taskAction + "-validation-failed");
      this.$root.$once(
        taskAction + "-validation-failed",
        this.addExternalProviderValidationFailed
      );
      this.$root.$once(
        taskAction + "-completed",
        this.addExternalProviderCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {
            domain: this.domain.name,
            protocol: "ldap",
            host: this.host,
            port: parseInt(this.port),
          },
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.addExternalProvider = this.getErrorMessage(err);
        return;
      }
    },
    addExternalProviderValidationFailed(validationErrors) {
      this.loading.addExternalProvider = false;
      let focusAlreadySet = false;
      for (const validationError of validationErrors) {
        const param = validationError.parameter;
        this.error[param] = "domains." + validationError.error;
        if (!focusAlreadySet) {
          this.focusElement(param);
          focusAlreadySet = true;
        }
      }
    },
    addExternalProviderCompleted() {
      this.loading.addExternalProvider = false;
      this.$emit("hide");
      this.$emit("reloadDomains");
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
</style>
</file>

<file path="core/ui/src/components/domains/AddInternalProviderModal.vue">
<template>
  <NsWizard
    size="default"
    :visible="isShown"
    :cancelLabel="$t('common.cancel')"
    :previousLabel="$t('common.previous')"
    :nextLabel="nextButtonLabel"
    :isPreviousDisabled="true"
    :isNextDisabled="isNextButtonDisabled"
    :isCancelDisabled="isCancelButtonDisabled"
    :isNextLoading="false"
    @modal-hidden="$emit('hide')"
    @cancel="$emit('hide')"
    @nextStep="nextStep"
    :isLastStep="hideButtonIcon"
  >
    <template slot="title">{{
      $t("domain_configuration.add_provider")
    }}</template>
    <template slot="content">
      <template v-if="step == 'node'">
        <div>
          {{ $t("domains.choose_node_for_account_provider_installation") }}
        </div>
        <NsInlineNotification
          v-if="clusterNodes.length == disabledNodes.length"
          kind="info"
          :title="$t('domains.no_node_eligible_for_provider_installation')"
          :showCloseButton="false"
        />
        <NsInlineNotification
          v-if="error.getClusterStatus"
          kind="error"
          :title="$t('action.get-cluster-status')"
          :description="error.getClusterStatus"
          :showCloseButton="false"
        />
        <NsInlineNotification
          v-if="error.nodesList"
          kind="error"
          :title="$t('action.list-nodes')"
          :description="error.nodesList"
          :showCloseButton="false"
        />
        <NsInlineNotification
          v-if="error.listModules"
          kind="error"
          :title="$t('action.list-modules')"
          :description="error.listModules"
          :showCloseButton="false"
        />
        <NsInlineNotification
          v-if="error.listMountPoints"
          kind="error"
          :title="$t('action.list-mountpoints')"
          :description="error.listMountPoints"
          :showCloseButton="false"
        />
        <NodeSelector
          v-else
          :disabledNodes="disabledNodes"
          :nodesWithAdditionalStorage="nodesWithAdditionalStorage"
          :nodesDefaultDiskInfo="nodesDefaultDiskInfo"
          @selectNode="onSelectNode"
          :loading="
            loading.listModules || loading.nodesList || loading.getClusterStatus
          "
          class="mg-top-xlg"
        >
          <template v-for="node in clusterNodes">
            <template :slot="`node-${node.id}`">
              <span v-if="nodesInfo[node.id]" :key="node.id">
                {{ $t(nodesInfo[node.id].message) }}
              </span>
            </template>
          </template>
        </NodeSelector>
      </template>
      <template v-if="step == 'installingProvider'">
        <NsInlineNotification
          v-if="error.addInternalProvider"
          kind="error"
          :title="$t('action.add-internal-provider')"
          :description="error.addInternalProvider"
          :showCloseButton="false"
        />
        <NsEmptyState
          :title="$t('domains.installing_account_provider')"
          :animationData="GearsLottie"
          animationTitle="gears"
          :loop="true"
        />
        <NsProgressBar
          :value="installProviderProgress"
          :indeterminate="!installProviderProgress"
          class="mg-bottom-md"
        />
      </template>
      <template v-if="step == 'volumes' && selectedNode">
        <NsInlineNotification
          v-if="error.listMountPoints"
          kind="error"
          :title="$t('action.list-mountpoints')"
          :description="error.listMountPoints"
          :showCloseButton="false"
        />
        <div>
          <NsInlineNotification
            kind="info"
            :title="$t('domains.nodes_with_additional_storage_info')"
            :description="
              $t('domains.nodes_with_additional_storage_info_description')
            "
            :showCloseButton="false"
          />
          <div>
            {{
              $t("domains.select_node_volume_for_installation", {
                node: this.getNodeLabel(selectedNode) || "",
              })
            }}. {{ $t("software_center.other_files_remain_on_default_volume") }}
          </div>
          <AdditionalVolumesSelector
            @selectVolume="onSelectVolume"
            :volumes="additionalVolumes"
            :light="true"
            class="mg-top-lg"
          />
        </div>
      </template>
      <template v-if="step == 'internalConfig'">
        <template v-if="isOpenLdap">
          <NsInlineNotification
            v-if="error.openldap.getDefaults"
            kind="error"
            :title="$t('action.get-defaults')"
            :description="error.openldap.getDefaults"
            :showCloseButton="false"
          />
          <cv-form>
            <NsTextInput
              :label="$t('openldap.admuser')"
              v-model.trim="openldap.admuser"
              :helper-text="$t('openldap.enter_openldap_admin_username')"
              :invalid-message="$t(error.openldap.admuser)"
              :disabled="
                loading.openldap.configureModule || loading.openldap.getDefaults
              "
              ref="admuser"
            >
            </NsTextInput>
            <NsTextInput
              :label="$t('openldap.admpass')"
              type="password"
              v-model="openldap.admpass"
              :helper-text="$t('openldap.enter_openldap_admin_password')"
              :invalid-message="$t(error.openldap.admpass)"
              :disabled="
                loading.openldap.configureModule || loading.openldap.getDefaults
              "
              :password-hide-label="$t('password.hide_password')"
              :password-show-label="$t('password.show_password')"
              ref="admpass"
              name="admpass"
            ></NsTextInput>
          </cv-form>
          <NsInlineNotification
            v-if="error.openldap.configureModule"
            kind="error"
            :title="$t('action.configure-module')"
            :description="error.openldap.configureModule"
            :showCloseButton="false"
          />
        </template>
        <template v-if="isSamba">
          <NsInlineNotification
            v-if="error.samba.getDefaults"
            kind="error"
            :title="$t('action.get-defaults')"
            :description="error.samba.getDefaults"
            :showCloseButton="false"
          />
          <cv-form>
            <NsTextInput
              :label="$t('samba.adminuser')"
              v-model.trim="samba.adminuser"
              :helper-text="$t('samba.enter_samba_admin_username')"
              :invalid-message="$t(error.samba.adminuser)"
              :disabled="
                loading.samba.configureModule || loading.samba.getDefaults
              "
              ref="adminuser"
            >
            </NsTextInput>
            <NsTextInput
              :label="$t('samba.adminpass')"
              type="password"
              v-model="samba.adminpass"
              :helper-text="$t('samba.enter_samba_admin_password')"
              :invalid-message="$t(error.samba.adminpass)"
              :disabled="
                loading.samba.configureModule || loading.samba.getDefaults
              "
              :password-hide-label="$t('password.hide_password')"
              :password-show-label="$t('password.show_password')"
              ref="adminpass"
              name="adminpass"
            ></NsTextInput>
            <NsTextInput
              :label="$t('samba.hostname')"
              v-model.trim="samba.hostname"
              :invalid-message="$t(error.samba.hostname)"
              :disabled="
                loading.samba.configureModule || loading.samba.getDefaults
              "
              ref="hostname"
            >
            </NsTextInput>
            <NsInlineNotification
              v-if="!samba.canInstallFileServer"
              kind="info"
              :description="$t('samba.enable_file_server_disabled_info')"
              :showCloseButton="false"
            />
            <NsToggle
              :label="$t('samba.enable_file_server_label')"
              value="enableFileServer"
              :form-item="true"
              v-model="samba.enableFileServer"
              :disabled="
                !samba.canInstallFileServer ||
                loading.samba.configureModule ||
                loading.samba.getDefaults
              "
              tooltipAlignment="start"
              tooltipDirection="bottom"
              ref="enableFileServer"
            >
              <template slot="tooltip">{{
                $t("samba.enable_file_server_tooltip")
              }}</template>
              <template slot="text-left">{{ $t("common.disabled") }}</template>
              <template slot="text-right">{{ $t("common.enabled") }}</template>
            </NsToggle>
            <NsInlineNotification
              v-if="samba.enableFileServer"
              kind="warning"
              :title="$t('common.warning')"
              :description="$t('samba.choose_ip_address_warning')"
              :showCloseButton="false"
            />
            <NsComboBox
              v-if="samba.enableFileServer"
              v-model="samba.ipaddress"
              :label="$t('common.choose')"
              :options="filteredIpAddressOptions"
              auto-highlight
              :title="$t('samba.provider_ipaddress')"
              :invalid-message="$t(error.samba.ipaddress)"
              :disabled="
                loading.samba.configureModule || loading.samba.getDefaults
              "
              light
              class="mg-bottom-5"
              ref="ipaddress"
            >
            </NsComboBox>
            <NsInlineNotification
              v-if="!samba.enableFileServer && vpnInterface"
              kind="info"
              :description="
                $t('samba.provider_on_vpn_address_message', {
                  vpnIpAddress: vpnInterface.value,
                })
              "
              :showCloseButton="false"
            />
          </cv-form>
          <NsInlineNotification
            v-if="error.samba.configureModule"
            kind="error"
            :title="$t('action.configure-module')"
            :description="error.samba.configureModule"
            :showCloseButton="false"
          />
          <NsInlineNotification
            v-if="error.samba.cannotReachDc"
            kind="error"
            :title="$t('domains.cannot_connect_to_domain_controller')"
            :description="
              $t('domains.cannot_connect_to_domain_controller_description')
            "
            :showCloseButton="false"
          />
        </template>
      </template>
      <template v-if="step == 'configuringProvider'">
        <NsEmptyState
          :title="$t('domains.configuring_account_provider')"
          :animationData="GearsLottie"
          animationTitle="gears"
          :loop="true"
        />
        <NsProgressBar
          :value="configureProviderProgress"
          :indeterminate="!configureProviderProgress"
          class="mg-bottom-md"
        />
      </template>
    </template>
  </NsWizard>
</template>
⋮----
<template slot="title">{{
      $t("domain_configuration.add_provider")
    }}</template>
<template slot="content">
      <template v-if="step == 'node'">
        <div>
          {{ $t("domains.choose_node_for_account_provider_installation") }}
        </div>
        <NsInlineNotification
          v-if="clusterNodes.length == disabledNodes.length"
          kind="info"
          :title="$t('domains.no_node_eligible_for_provider_installation')"
          :showCloseButton="false"
        />
        <NsInlineNotification
          v-if="error.getClusterStatus"
          kind="error"
          :title="$t('action.get-cluster-status')"
          :description="error.getClusterStatus"
          :showCloseButton="false"
        />
        <NsInlineNotification
          v-if="error.nodesList"
          kind="error"
          :title="$t('action.list-nodes')"
          :description="error.nodesList"
          :showCloseButton="false"
        />
        <NsInlineNotification
          v-if="error.listModules"
          kind="error"
          :title="$t('action.list-modules')"
          :description="error.listModules"
          :showCloseButton="false"
        />
        <NsInlineNotification
          v-if="error.listMountPoints"
          kind="error"
          :title="$t('action.list-mountpoints')"
          :description="error.listMountPoints"
          :showCloseButton="false"
        />
        <NodeSelector
          v-else
          :disabledNodes="disabledNodes"
          :nodesWithAdditionalStorage="nodesWithAdditionalStorage"
          :nodesDefaultDiskInfo="nodesDefaultDiskInfo"
          @selectNode="onSelectNode"
          :loading="
            loading.listModules || loading.nodesList || loading.getClusterStatus
          "
          class="mg-top-xlg"
        >
          <template v-for="node in clusterNodes">
            <template :slot="`node-${node.id}`">
              <span v-if="nodesInfo[node.id]" :key="node.id">
                {{ $t(nodesInfo[node.id].message) }}
              </span>
            </template>
          </template>
        </NodeSelector>
      </template>
      <template v-if="step == 'installingProvider'">
        <NsInlineNotification
          v-if="error.addInternalProvider"
          kind="error"
          :title="$t('action.add-internal-provider')"
          :description="error.addInternalProvider"
          :showCloseButton="false"
        />
        <NsEmptyState
          :title="$t('domains.installing_account_provider')"
          :animationData="GearsLottie"
          animationTitle="gears"
          :loop="true"
        />
        <NsProgressBar
          :value="installProviderProgress"
          :indeterminate="!installProviderProgress"
          class="mg-bottom-md"
        />
      </template>
      <template v-if="step == 'volumes' && selectedNode">
        <NsInlineNotification
          v-if="error.listMountPoints"
          kind="error"
          :title="$t('action.list-mountpoints')"
          :description="error.listMountPoints"
          :showCloseButton="false"
        />
        <div>
          <NsInlineNotification
            kind="info"
            :title="$t('domains.nodes_with_additional_storage_info')"
            :description="
              $t('domains.nodes_with_additional_storage_info_description')
            "
            :showCloseButton="false"
          />
          <div>
            {{
              $t("domains.select_node_volume_for_installation", {
                node: this.getNodeLabel(selectedNode) || "",
              })
            }}. {{ $t("software_center.other_files_remain_on_default_volume") }}
          </div>
          <AdditionalVolumesSelector
            @selectVolume="onSelectVolume"
            :volumes="additionalVolumes"
            :light="true"
            class="mg-top-lg"
          />
        </div>
      </template>
      <template v-if="step == 'internalConfig'">
        <template v-if="isOpenLdap">
          <NsInlineNotification
            v-if="error.openldap.getDefaults"
            kind="error"
            :title="$t('action.get-defaults')"
            :description="error.openldap.getDefaults"
            :showCloseButton="false"
          />
          <cv-form>
            <NsTextInput
              :label="$t('openldap.admuser')"
              v-model.trim="openldap.admuser"
              :helper-text="$t('openldap.enter_openldap_admin_username')"
              :invalid-message="$t(error.openldap.admuser)"
              :disabled="
                loading.openldap.configureModule || loading.openldap.getDefaults
              "
              ref="admuser"
            >
            </NsTextInput>
            <NsTextInput
              :label="$t('openldap.admpass')"
              type="password"
              v-model="openldap.admpass"
              :helper-text="$t('openldap.enter_openldap_admin_password')"
              :invalid-message="$t(error.openldap.admpass)"
              :disabled="
                loading.openldap.configureModule || loading.openldap.getDefaults
              "
              :password-hide-label="$t('password.hide_password')"
              :password-show-label="$t('password.show_password')"
              ref="admpass"
              name="admpass"
            ></NsTextInput>
          </cv-form>
          <NsInlineNotification
            v-if="error.openldap.configureModule"
            kind="error"
            :title="$t('action.configure-module')"
            :description="error.openldap.configureModule"
            :showCloseButton="false"
          />
        </template>
        <template v-if="isSamba">
          <NsInlineNotification
            v-if="error.samba.getDefaults"
            kind="error"
            :title="$t('action.get-defaults')"
            :description="error.samba.getDefaults"
            :showCloseButton="false"
          />
          <cv-form>
            <NsTextInput
              :label="$t('samba.adminuser')"
              v-model.trim="samba.adminuser"
              :helper-text="$t('samba.enter_samba_admin_username')"
              :invalid-message="$t(error.samba.adminuser)"
              :disabled="
                loading.samba.configureModule || loading.samba.getDefaults
              "
              ref="adminuser"
            >
            </NsTextInput>
            <NsTextInput
              :label="$t('samba.adminpass')"
              type="password"
              v-model="samba.adminpass"
              :helper-text="$t('samba.enter_samba_admin_password')"
              :invalid-message="$t(error.samba.adminpass)"
              :disabled="
                loading.samba.configureModule || loading.samba.getDefaults
              "
              :password-hide-label="$t('password.hide_password')"
              :password-show-label="$t('password.show_password')"
              ref="adminpass"
              name="adminpass"
            ></NsTextInput>
            <NsTextInput
              :label="$t('samba.hostname')"
              v-model.trim="samba.hostname"
              :invalid-message="$t(error.samba.hostname)"
              :disabled="
                loading.samba.configureModule || loading.samba.getDefaults
              "
              ref="hostname"
            >
            </NsTextInput>
            <NsInlineNotification
              v-if="!samba.canInstallFileServer"
              kind="info"
              :description="$t('samba.enable_file_server_disabled_info')"
              :showCloseButton="false"
            />
            <NsToggle
              :label="$t('samba.enable_file_server_label')"
              value="enableFileServer"
              :form-item="true"
              v-model="samba.enableFileServer"
              :disabled="
                !samba.canInstallFileServer ||
                loading.samba.configureModule ||
                loading.samba.getDefaults
              "
              tooltipAlignment="start"
              tooltipDirection="bottom"
              ref="enableFileServer"
            >
              <template slot="tooltip">{{
                $t("samba.enable_file_server_tooltip")
              }}</template>
              <template slot="text-left">{{ $t("common.disabled") }}</template>
              <template slot="text-right">{{ $t("common.enabled") }}</template>
            </NsToggle>
            <NsInlineNotification
              v-if="samba.enableFileServer"
              kind="warning"
              :title="$t('common.warning')"
              :description="$t('samba.choose_ip_address_warning')"
              :showCloseButton="false"
            />
            <NsComboBox
              v-if="samba.enableFileServer"
              v-model="samba.ipaddress"
              :label="$t('common.choose')"
              :options="filteredIpAddressOptions"
              auto-highlight
              :title="$t('samba.provider_ipaddress')"
              :invalid-message="$t(error.samba.ipaddress)"
              :disabled="
                loading.samba.configureModule || loading.samba.getDefaults
              "
              light
              class="mg-bottom-5"
              ref="ipaddress"
            >
            </NsComboBox>
            <NsInlineNotification
              v-if="!samba.enableFileServer && vpnInterface"
              kind="info"
              :description="
                $t('samba.provider_on_vpn_address_message', {
                  vpnIpAddress: vpnInterface.value,
                })
              "
              :showCloseButton="false"
            />
          </cv-form>
          <NsInlineNotification
            v-if="error.samba.configureModule"
            kind="error"
            :title="$t('action.configure-module')"
            :description="error.samba.configureModule"
            :showCloseButton="false"
          />
          <NsInlineNotification
            v-if="error.samba.cannotReachDc"
            kind="error"
            :title="$t('domains.cannot_connect_to_domain_controller')"
            :description="
              $t('domains.cannot_connect_to_domain_controller_description')
            "
            :showCloseButton="false"
          />
        </template>
      </template>
      <template v-if="step == 'configuringProvider'">
        <NsEmptyState
          :title="$t('domains.configuring_account_provider')"
          :animationData="GearsLottie"
          animationTitle="gears"
          :loop="true"
        />
        <NsProgressBar
          :value="configureProviderProgress"
          :indeterminate="!configureProviderProgress"
          class="mg-bottom-md"
        />
      </template>
    </template>
⋮----
<template v-if="step == 'node'">
        <div>
          {{ $t("domains.choose_node_for_account_provider_installation") }}
        </div>
        <NsInlineNotification
          v-if="clusterNodes.length == disabledNodes.length"
          kind="info"
          :title="$t('domains.no_node_eligible_for_provider_installation')"
          :showCloseButton="false"
        />
        <NsInlineNotification
          v-if="error.getClusterStatus"
          kind="error"
          :title="$t('action.get-cluster-status')"
          :description="error.getClusterStatus"
          :showCloseButton="false"
        />
        <NsInlineNotification
          v-if="error.nodesList"
          kind="error"
          :title="$t('action.list-nodes')"
          :description="error.nodesList"
          :showCloseButton="false"
        />
        <NsInlineNotification
          v-if="error.listModules"
          kind="error"
          :title="$t('action.list-modules')"
          :description="error.listModules"
          :showCloseButton="false"
        />
        <NsInlineNotification
          v-if="error.listMountPoints"
          kind="error"
          :title="$t('action.list-mountpoints')"
          :description="error.listMountPoints"
          :showCloseButton="false"
        />
        <NodeSelector
          v-else
          :disabledNodes="disabledNodes"
          :nodesWithAdditionalStorage="nodesWithAdditionalStorage"
          :nodesDefaultDiskInfo="nodesDefaultDiskInfo"
          @selectNode="onSelectNode"
          :loading="
            loading.listModules || loading.nodesList || loading.getClusterStatus
          "
          class="mg-top-xlg"
        >
          <template v-for="node in clusterNodes">
            <template :slot="`node-${node.id}`">
              <span v-if="nodesInfo[node.id]" :key="node.id">
                {{ $t(nodesInfo[node.id].message) }}
              </span>
            </template>
          </template>
        </NodeSelector>
      </template>
⋮----
{{ $t("domains.choose_node_for_account_provider_installation") }}
⋮----
<template v-for="node in clusterNodes">
            <template :slot="`node-${node.id}`">
              <span v-if="nodesInfo[node.id]" :key="node.id">
                {{ $t(nodesInfo[node.id].message) }}
              </span>
            </template>
          </template>
⋮----
<template :slot="`node-${node.id}`">
              <span v-if="nodesInfo[node.id]" :key="node.id">
                {{ $t(nodesInfo[node.id].message) }}
              </span>
            </template>
⋮----
{{ $t(nodesInfo[node.id].message) }}
⋮----
<template v-if="step == 'installingProvider'">
        <NsInlineNotification
          v-if="error.addInternalProvider"
          kind="error"
          :title="$t('action.add-internal-provider')"
          :description="error.addInternalProvider"
          :showCloseButton="false"
        />
        <NsEmptyState
          :title="$t('domains.installing_account_provider')"
          :animationData="GearsLottie"
          animationTitle="gears"
          :loop="true"
        />
        <NsProgressBar
          :value="installProviderProgress"
          :indeterminate="!installProviderProgress"
          class="mg-bottom-md"
        />
      </template>
<template v-if="step == 'volumes' && selectedNode">
        <NsInlineNotification
          v-if="error.listMountPoints"
          kind="error"
          :title="$t('action.list-mountpoints')"
          :description="error.listMountPoints"
          :showCloseButton="false"
        />
        <div>
          <NsInlineNotification
            kind="info"
            :title="$t('domains.nodes_with_additional_storage_info')"
            :description="
              $t('domains.nodes_with_additional_storage_info_description')
            "
            :showCloseButton="false"
          />
          <div>
            {{
              $t("domains.select_node_volume_for_installation", {
                node: this.getNodeLabel(selectedNode) || "",
              })
            }}. {{ $t("software_center.other_files_remain_on_default_volume") }}
          </div>
          <AdditionalVolumesSelector
            @selectVolume="onSelectVolume"
            :volumes="additionalVolumes"
            :light="true"
            class="mg-top-lg"
          />
        </div>
      </template>
⋮----
{{
              $t("domains.select_node_volume_for_installation", {
                node: this.getNodeLabel(selectedNode) || "",
              })
            }}. {{ $t("software_center.other_files_remain_on_default_volume") }}
⋮----
}}. {{ $t("software_center.other_files_remain_on_default_volume") }}
⋮----
<template v-if="step == 'internalConfig'">
        <template v-if="isOpenLdap">
          <NsInlineNotification
            v-if="error.openldap.getDefaults"
            kind="error"
            :title="$t('action.get-defaults')"
            :description="error.openldap.getDefaults"
            :showCloseButton="false"
          />
          <cv-form>
            <NsTextInput
              :label="$t('openldap.admuser')"
              v-model.trim="openldap.admuser"
              :helper-text="$t('openldap.enter_openldap_admin_username')"
              :invalid-message="$t(error.openldap.admuser)"
              :disabled="
                loading.openldap.configureModule || loading.openldap.getDefaults
              "
              ref="admuser"
            >
            </NsTextInput>
            <NsTextInput
              :label="$t('openldap.admpass')"
              type="password"
              v-model="openldap.admpass"
              :helper-text="$t('openldap.enter_openldap_admin_password')"
              :invalid-message="$t(error.openldap.admpass)"
              :disabled="
                loading.openldap.configureModule || loading.openldap.getDefaults
              "
              :password-hide-label="$t('password.hide_password')"
              :password-show-label="$t('password.show_password')"
              ref="admpass"
              name="admpass"
            ></NsTextInput>
          </cv-form>
          <NsInlineNotification
            v-if="error.openldap.configureModule"
            kind="error"
            :title="$t('action.configure-module')"
            :description="error.openldap.configureModule"
            :showCloseButton="false"
          />
        </template>
        <template v-if="isSamba">
          <NsInlineNotification
            v-if="error.samba.getDefaults"
            kind="error"
            :title="$t('action.get-defaults')"
            :description="error.samba.getDefaults"
            :showCloseButton="false"
          />
          <cv-form>
            <NsTextInput
              :label="$t('samba.adminuser')"
              v-model.trim="samba.adminuser"
              :helper-text="$t('samba.enter_samba_admin_username')"
              :invalid-message="$t(error.samba.adminuser)"
              :disabled="
                loading.samba.configureModule || loading.samba.getDefaults
              "
              ref="adminuser"
            >
            </NsTextInput>
            <NsTextInput
              :label="$t('samba.adminpass')"
              type="password"
              v-model="samba.adminpass"
              :helper-text="$t('samba.enter_samba_admin_password')"
              :invalid-message="$t(error.samba.adminpass)"
              :disabled="
                loading.samba.configureModule || loading.samba.getDefaults
              "
              :password-hide-label="$t('password.hide_password')"
              :password-show-label="$t('password.show_password')"
              ref="adminpass"
              name="adminpass"
            ></NsTextInput>
            <NsTextInput
              :label="$t('samba.hostname')"
              v-model.trim="samba.hostname"
              :invalid-message="$t(error.samba.hostname)"
              :disabled="
                loading.samba.configureModule || loading.samba.getDefaults
              "
              ref="hostname"
            >
            </NsTextInput>
            <NsInlineNotification
              v-if="!samba.canInstallFileServer"
              kind="info"
              :description="$t('samba.enable_file_server_disabled_info')"
              :showCloseButton="false"
            />
            <NsToggle
              :label="$t('samba.enable_file_server_label')"
              value="enableFileServer"
              :form-item="true"
              v-model="samba.enableFileServer"
              :disabled="
                !samba.canInstallFileServer ||
                loading.samba.configureModule ||
                loading.samba.getDefaults
              "
              tooltipAlignment="start"
              tooltipDirection="bottom"
              ref="enableFileServer"
            >
              <template slot="tooltip">{{
                $t("samba.enable_file_server_tooltip")
              }}</template>
              <template slot="text-left">{{ $t("common.disabled") }}</template>
              <template slot="text-right">{{ $t("common.enabled") }}</template>
            </NsToggle>
            <NsInlineNotification
              v-if="samba.enableFileServer"
              kind="warning"
              :title="$t('common.warning')"
              :description="$t('samba.choose_ip_address_warning')"
              :showCloseButton="false"
            />
            <NsComboBox
              v-if="samba.enableFileServer"
              v-model="samba.ipaddress"
              :label="$t('common.choose')"
              :options="filteredIpAddressOptions"
              auto-highlight
              :title="$t('samba.provider_ipaddress')"
              :invalid-message="$t(error.samba.ipaddress)"
              :disabled="
                loading.samba.configureModule || loading.samba.getDefaults
              "
              light
              class="mg-bottom-5"
              ref="ipaddress"
            >
            </NsComboBox>
            <NsInlineNotification
              v-if="!samba.enableFileServer && vpnInterface"
              kind="info"
              :description="
                $t('samba.provider_on_vpn_address_message', {
                  vpnIpAddress: vpnInterface.value,
                })
              "
              :showCloseButton="false"
            />
          </cv-form>
          <NsInlineNotification
            v-if="error.samba.configureModule"
            kind="error"
            :title="$t('action.configure-module')"
            :description="error.samba.configureModule"
            :showCloseButton="false"
          />
          <NsInlineNotification
            v-if="error.samba.cannotReachDc"
            kind="error"
            :title="$t('domains.cannot_connect_to_domain_controller')"
            :description="
              $t('domains.cannot_connect_to_domain_controller_description')
            "
            :showCloseButton="false"
          />
        </template>
      </template>
⋮----
<template v-if="isOpenLdap">
          <NsInlineNotification
            v-if="error.openldap.getDefaults"
            kind="error"
            :title="$t('action.get-defaults')"
            :description="error.openldap.getDefaults"
            :showCloseButton="false"
          />
          <cv-form>
            <NsTextInput
              :label="$t('openldap.admuser')"
              v-model.trim="openldap.admuser"
              :helper-text="$t('openldap.enter_openldap_admin_username')"
              :invalid-message="$t(error.openldap.admuser)"
              :disabled="
                loading.openldap.configureModule || loading.openldap.getDefaults
              "
              ref="admuser"
            >
            </NsTextInput>
            <NsTextInput
              :label="$t('openldap.admpass')"
              type="password"
              v-model="openldap.admpass"
              :helper-text="$t('openldap.enter_openldap_admin_password')"
              :invalid-message="$t(error.openldap.admpass)"
              :disabled="
                loading.openldap.configureModule || loading.openldap.getDefaults
              "
              :password-hide-label="$t('password.hide_password')"
              :password-show-label="$t('password.show_password')"
              ref="admpass"
              name="admpass"
            ></NsTextInput>
          </cv-form>
          <NsInlineNotification
            v-if="error.openldap.configureModule"
            kind="error"
            :title="$t('action.configure-module')"
            :description="error.openldap.configureModule"
            :showCloseButton="false"
          />
        </template>
⋮----
<template v-if="isSamba">
          <NsInlineNotification
            v-if="error.samba.getDefaults"
            kind="error"
            :title="$t('action.get-defaults')"
            :description="error.samba.getDefaults"
            :showCloseButton="false"
          />
          <cv-form>
            <NsTextInput
              :label="$t('samba.adminuser')"
              v-model.trim="samba.adminuser"
              :helper-text="$t('samba.enter_samba_admin_username')"
              :invalid-message="$t(error.samba.adminuser)"
              :disabled="
                loading.samba.configureModule || loading.samba.getDefaults
              "
              ref="adminuser"
            >
            </NsTextInput>
            <NsTextInput
              :label="$t('samba.adminpass')"
              type="password"
              v-model="samba.adminpass"
              :helper-text="$t('samba.enter_samba_admin_password')"
              :invalid-message="$t(error.samba.adminpass)"
              :disabled="
                loading.samba.configureModule || loading.samba.getDefaults
              "
              :password-hide-label="$t('password.hide_password')"
              :password-show-label="$t('password.show_password')"
              ref="adminpass"
              name="adminpass"
            ></NsTextInput>
            <NsTextInput
              :label="$t('samba.hostname')"
              v-model.trim="samba.hostname"
              :invalid-message="$t(error.samba.hostname)"
              :disabled="
                loading.samba.configureModule || loading.samba.getDefaults
              "
              ref="hostname"
            >
            </NsTextInput>
            <NsInlineNotification
              v-if="!samba.canInstallFileServer"
              kind="info"
              :description="$t('samba.enable_file_server_disabled_info')"
              :showCloseButton="false"
            />
            <NsToggle
              :label="$t('samba.enable_file_server_label')"
              value="enableFileServer"
              :form-item="true"
              v-model="samba.enableFileServer"
              :disabled="
                !samba.canInstallFileServer ||
                loading.samba.configureModule ||
                loading.samba.getDefaults
              "
              tooltipAlignment="start"
              tooltipDirection="bottom"
              ref="enableFileServer"
            >
              <template slot="tooltip">{{
                $t("samba.enable_file_server_tooltip")
              }}</template>
              <template slot="text-left">{{ $t("common.disabled") }}</template>
              <template slot="text-right">{{ $t("common.enabled") }}</template>
            </NsToggle>
            <NsInlineNotification
              v-if="samba.enableFileServer"
              kind="warning"
              :title="$t('common.warning')"
              :description="$t('samba.choose_ip_address_warning')"
              :showCloseButton="false"
            />
            <NsComboBox
              v-if="samba.enableFileServer"
              v-model="samba.ipaddress"
              :label="$t('common.choose')"
              :options="filteredIpAddressOptions"
              auto-highlight
              :title="$t('samba.provider_ipaddress')"
              :invalid-message="$t(error.samba.ipaddress)"
              :disabled="
                loading.samba.configureModule || loading.samba.getDefaults
              "
              light
              class="mg-bottom-5"
              ref="ipaddress"
            >
            </NsComboBox>
            <NsInlineNotification
              v-if="!samba.enableFileServer && vpnInterface"
              kind="info"
              :description="
                $t('samba.provider_on_vpn_address_message', {
                  vpnIpAddress: vpnInterface.value,
                })
              "
              :showCloseButton="false"
            />
          </cv-form>
          <NsInlineNotification
            v-if="error.samba.configureModule"
            kind="error"
            :title="$t('action.configure-module')"
            :description="error.samba.configureModule"
            :showCloseButton="false"
          />
          <NsInlineNotification
            v-if="error.samba.cannotReachDc"
            kind="error"
            :title="$t('domains.cannot_connect_to_domain_controller')"
            :description="
              $t('domains.cannot_connect_to_domain_controller_description')
            "
            :showCloseButton="false"
          />
        </template>
⋮----
<template slot="tooltip">{{
                $t("samba.enable_file_server_tooltip")
              }}</template>
<template slot="text-left">{{ $t("common.disabled") }}</template>
<template slot="text-right">{{ $t("common.enabled") }}</template>
⋮----
<template v-if="step == 'configuringProvider'">
        <NsEmptyState
          :title="$t('domains.configuring_account_provider')"
          :animationData="GearsLottie"
          animationTitle="gears"
          :loop="true"
        />
        <NsProgressBar
          :value="configureProviderProgress"
          :indeterminate="!configureProviderProgress"
          class="mg-bottom-md"
        />
      </template>
⋮----
<script>
import {
  UtilService,
  TaskService,
  IconService,
  LottieService,
} from "@nethserver/ns8-ui-lib";
import to from "await-to-js";
import NodeSelector from "@/components/nodes/NodeSelector";
import AdditionalVolumesSelector from "@/components/software-center/AdditionalVolumesSelector.vue";
import { mapState } from "vuex";
export default {
  name: "AddInternalProviderModal",
  components: { NodeSelector, AdditionalVolumesSelector },
  mixins: [UtilService, TaskService, IconService, LottieService],
  props: {
    isShown: {
      type: Boolean,
      default: true,
    },
    domain: {
      type: Object,
      required: true,
    },
    isResumeConfiguration: {
      type: Boolean,
      default: false,
    },
    providerId: {
      type: String,
      default: "",
    },
    domains: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      step: "node",
      installProviderProgress: 0,
      configureProviderProgress: 0,
      selectedNode: null,
      modules: [],
      nodesList: [],
      clusterStatus: [],
      nodesAdditionalDiskInfo: {},
      nodesDefaultDiskInfo: {},
      selectedVolume: {},
      openldap: {
        admuser: "",
        admpass: "",
      },
      samba: {
        adminuser: "",
        adminpass: "",
        ipaddress: "",
        ipAddressOptions: [],
        hostname: "",
        canInstallFileServer: false,
        enableFileServer: false,
      },
      loading: {
        listModules: false,
        nodesList: false,
        getClusterStatus: false,
        openldap: {
          getDefaults: false,
          configureModule: false,
        },
        samba: {
          getDefaults: false,
          configureModule: false,
        },
      },
      error: {
        addInternalProvider: "",
        listModules: "",
        nodesList: "",
        getClusterStatus: "",
        listMountPoints: "",
        openldap: {
          admuser: "",
          admpass: "",
          configureModule: "",
          getDefaults: "",
        },
        samba: {
          adminuser: "",
          adminpass: "",
          ipaddress: "",
          hostname: "",
          configureModule: "",
          getDefaults: "",
          cannotReachDc: false,
        },
      },
    };
  },
  computed: {
    ...mapState(["clusterNodes"]),
    hideButtonIcon() {
      return (
        this.step === "volumes" ||
        (this.step === "node" &&
          this.selectedNode &&
          !this.nodesWithAdditionalStorage.includes(this.selectedNode.id)) ||
        this.step === "internalConfig"
      );
    },
    isOpenLdap() {
      return this.domain.schema == "rfc2307";
    },
    isSamba() {
      return this.domain.schema == "ad";
    },
    nodesWithAdditionalStorage() {
      const nodeIds = [];
      if (!this.isSamba) {
        return nodeIds;
      }
      if (this.hasFileServerProvider) {
        return nodeIds;
      }
      if (!this.sambaModule || this.sambaVolumes.length === 0) {
        return nodeIds;
      }
      if (this.nodesList && Array.isArray(this.nodesList)) {
        for (const node of this.nodesList) {
          if (node.additional_disk_count > 0) {
            nodeIds.push(node.node_id);
          }
        }
      }
      return nodeIds;
    },
    sambaVolumes() {
      if (
        this.sambaModule &&
        this.sambaModule.versions &&
        this.sambaModule.versions.length &&
        this.sambaModule.versions[0].labels &&
        this.sambaModule.versions[0].labels["org.nethserver.volumes"]
      ) {
        const volumesString =
          this.sambaModule.versions[0].labels["org.nethserver.volumes"];
        return volumesString.split(" ").map((v) => v.trim());
      }
      return [];
    },
    nextButtonLabel() {
      if (this.step == "volumes") {
        return this.$t("domains.install_provider");
      } else if (this.step == "node") {
        if (
          this.selectedNode &&
          this.nodesWithAdditionalStorage.includes(this.selectedNode.id)
        ) {
          return this.$t("common.next");
        } else {
          return this.$t("domains.install_provider");
        }
      } else if (this.step == "internalConfig") {
        return this.$t("domains.configure_provider");
      } else {
        return this.$t("common.next");
      }
    },
    isNextButtonDisabled() {
      return (
        this.step == "installingProvider" ||
        this.step == "configuringProvider" ||
        (this.step == "node" && !this.selectedNode) ||
        (this.step == "volumes" && !this.selectedVolume?.path) ||
        this.loading.samba.configureModule ||
        this.loading.openldap.configureModule
      );
    },
    isCancelButtonDisabled() {
      return (
        this.step == "installingProvider" || this.step == "configuringProvider"
      );
    },
    vpnInterface() {
      return this.samba.ipAddressOptions.find((option) => {
        return option.iface === "wg0";
      });
    },
    filteredIpAddressOptions() {
      if (this.samba.enableFileServer) {
        return this.samba.ipAddressOptions.filter((option) => {
          return option != this.vpnInterface;
        });
      } else {
        return this.samba.ipAddressOptions;
      }
    },
    disabledNodes() {
      const offlineNodeIds = this.clusterStatus
        .filter((node) => !node.online)
        .map((node) => node.id);
      if (this.isOpenLdap) {
        return offlineNodeIds;
      } else {
        if (!this.sambaModule) {
          return offlineNodeIds;
        }
        const ineligibleNodeIds = this.sambaModule.install_destinations
          .filter((nodeInfo) => !nodeInfo.eligible)
          .map((nodeInfo) => nodeInfo.node_id);
        return [...new Set([...offlineNodeIds, ...ineligibleNodeIds])];
      }
    },
    nodesInfo() {
      const info = {};
      const offlineNodeIds = this.clusterStatus
        .filter((node) => !node.online)
        .map((node) => node.id);
      offlineNodeIds.forEach((nodeId) => {
        info[nodeId] = {
          message: "software_center.node_offline",
        };
      });
      if (this.isSamba && this.sambaModule) {
        const ineligibleNodeIds = this.sambaModule.install_destinations
          .filter((nodeInfo) => !nodeInfo.eligible)
          .map((nodeInfo) => nodeInfo.node_id);
        ineligibleNodeIds.forEach((nodeId) => {
          if (!info[nodeId]) {
            info[nodeId] = {
              message: "domains.provider_already_installed",
            };
          }
        });
      }
      return info;
    },
    additionalVolumes() {
      const output = this.nodesAdditionalDiskInfo[this.selectedNode?.id];
      if (!output) return [];
      const volumes = [...output.mountpoints];
      if (output.default_disk) {
        volumes.push({ ...output.default_disk, default: true });
      }
      return volumes;
    },
    sambaModule() {
      return this.modules.find((module) => module.id === "samba");
    },
    hasFileServerProvider() {
      return (
        this.domain.providers &&
        Array.isArray(this.domain.providers) &&
        this.domain.providers.some((provider) => provider.file_server === true)
      );
    },
  },
  watch: {
    isShown: function () {
      if (this.isShown) {
        this.clearErrors();
        if (!this.isResumeConfiguration) {
          this.step = "node";
          this.getClusterStatus();
          if (!this.isOpenLdap) {
            this.listModules();
            this.listNodes();
          }
        } else {
          this.step = "internalConfig";
          if (this.isOpenLdap) {
            this.getOpenLdapDefaults();
          } else if (this.isSamba) {
            this.getSambaDefaults();
          }
        }
      }
    },
    providerId: function () {
      this.newProviderId = this.providerId;
    },
    step: function () {
      if (this.step == "node") {
        this.getClusterStatus();
      }
    },
  },
  created() {
    this.newProviderId = this.providerId;
  },
  methods: {
    nextStep() {
      switch (this.step) {
        case "node":
          if (
            this.isSamba &&
            this.selectedNode &&
            this.nodesWithAdditionalStorage.includes(this.selectedNode.id)
          ) {
            this.step = "volumes";
          } else {
            this.step = "installingProvider";
            this.installProvider();
          }
          break;
        case "volumes":
          this.step = "installingProvider";
          this.installProvider(this.selectedVolume);
          break;
        case "internalConfig":
          if (this.isSamba) {
            this.configureSambaModule();
          } else if (this.isOpenLdap) {
            this.configureOpenLdapModule();
          }
          break;
      }
    },
    onSelectVolume(selectedVolume) {
      this.selectedVolume = selectedVolume;
    },
    onSelectNode(selectedNode) {
      this.selectedNode = selectedNode;
    },
    async getClusterStatus() {
      this.loading.getClusterStatus = true;
      this.error.getClusterStatus = "";
      const taskAction = "get-cluster-status";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.getClusterStatusAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.getClusterStatusCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.getClusterStatus = this.getErrorMessage(err);
        this.loading.getClusterStatus = false;
        return;
      }
    },
    getClusterStatusAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.getClusterStatus = this.$t("error.generic_error");
      this.loading.getClusterStatus = false;
    },
    getClusterStatusCompleted(taskContext, taskResult) {
      this.clusterStatus = taskResult.output.nodes;
      for (const node of this.clusterStatus.filter((n) => n.online)) {
        this.listMountPoints(node.id);
      }
      this.loading.getClusterStatus = false;
    },
    async listNodes() {
      this.error.nodesList = "";
      this.loading.nodesList = true;
      const taskAction = "list-nodes";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.listNodesAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.listNodesCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.nodesList = this.getErrorMessage(err);
        this.loading.nodesList = false;
        return;
      }
    },
    listNodesAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.nodesList = this.$t("error.generic_error");
      this.loading.nodesList = false;
    },
    listNodesCompleted(taskContext, taskResult) {
      this.nodesList = taskResult.output.nodes;
      this.loading.nodesList = false;
    },
    async listMountPoints(nodeId) {
      const taskAction = "list-mountpoints";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.listMountPointsAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        (taskContext, taskResult) =>
          this.listMountPointsCompleted(taskContext, taskResult, nodeId)
      );
      const res = await to(
        this.createNodeTask(nodeId, {
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(
          `error creating task ${taskAction} for node ${nodeId}`,
          err
        );
        this.error.listMountPoints = this.getErrorMessage(err);
        return;
      }
    },
    listMountPointsAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.listMountPoints = this.$t("error.generic_error");
    },
    listMountPointsCompleted(taskContext, taskResult, nodeId) {
      const output = taskResult.output;
      this.$set(this.nodesAdditionalDiskInfo, nodeId, output);
      if (output.default_disk) {
        this.$set(this.nodesDefaultDiskInfo, nodeId, output.default_disk);
      }
    },
    async installProvider(volumes) {
      this.error.addInternalProvider = "";
      const taskAction = "add-internal-provider";
      const eventId = this.getUuid();
      this.installProviderProgress = 0;
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.addInternalProviderCompleted
      );
      this.$root.$on(
        `${taskAction}-progress-${eventId}`,
        this.addInternalProviderProgress
      );
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.addInternalProviderAborted
      );
      const providerImage = this.isOpenLdap ? "openldap" : "samba";
      const data = {
        image: providerImage,
        node: parseInt(this.selectedNode.id),
        domain: this.domain.name,
      };
      if (volumes?.path && this.sambaVolumes.length) {
        data.volumes = {};
        this.sambaVolumes.forEach((volume) => {
          data.volumes[volume] = volumes.path;
        });
      }
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data,
          extra: {
            title: this.$t("action." + taskAction),
            node: this.selectedNode.id,
            isNotificationHidden: true,
            isProgressNotified: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.addInternalProvider = this.getErrorMessage(err);
        return;
      }
    },
    addInternalProviderAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.$root.$off(
        `${taskContext.action}-progress-${taskContext.extra.eventId}`
      );
      this.$emit("hide");
    },
    addInternalProviderCompleted(taskContext, taskResult) {
      this.$root.$off(
        `${taskContext.action}-progress-${taskContext.extra.eventId}`
      );
      this.step = "internalConfig";
      this.newProviderId = taskResult.output.module_id;
      if (this.isSamba) {
        this.getSambaDefaults();
      } else {
        this.getOpenLdapDefaults();
      }
      this.$emit("reloadDomains");
      this.$root.$emit("reloadAppDrawer");
    },
    addInternalProviderProgress(progress) {
      this.installProviderProgress = progress;
    },
    async getOpenLdapDefaults() {
      this.loading.openldap.getDefaults = true;
      this.error.openldap.getDefaults = "";
      const taskAction = "get-defaults";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.getOpenLdapDefaultsAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.getOpenLdapDefaultsCompleted
      );
      const res = await to(
        this.createModuleTaskForApp(this.newProviderId, {
          action: taskAction,
          data: {
            provision: "join-domain",
            domain: this.domain.name,
          },
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.openldap.getDefaults = this.getErrorMessage(err);
        return;
      }
    },
    getOpenLdapDefaultsAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.loading.openldap.getDefaults = false;
      this.$emit("hide");
    },
    getOpenLdapDefaultsCompleted(taskContext, taskResult) {
      this.loading.openldap.getDefaults = false;
      const defaults = taskResult.output;
      this.openldap.admuser = defaults.admuser;
      this.openldap.admpass = "";
      // focus on first field
      this.$nextTick(() => {
        this.focusElement("admuser");
      });
    },
    async getSambaDefaults() {
      this.loading.samba.getDefaults = true;
      this.error.samba.getDefaults = "";
      const taskAction = "get-defaults";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.getSambaDefaultsAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.getSambaDefaultsCompleted
      );
      const res = await to(
        this.createModuleTaskForApp(this.newProviderId, {
          action: taskAction,
          data: {
            provision: "join-domain",
            realm: this.domain.name,
          },
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.samba.getDefaults = this.getErrorMessage(err);
        return;
      }
    },
    getSambaDefaultsAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.loading.samba.getDefaults = false;
      this.$emit("hide");
    },
    getSambaDefaultsCompleted(taskContext, taskResult) {
      this.loading.samba.getDefaults = false;
      const defaults = taskResult.output;
      this.samba.adminuser = defaults.adminuser;
      this.samba.adminpass = "";
      this.samba.hostname = defaults.hostname;
      this.samba.canInstallFileServer = defaults.can_install_file_server;
      // ip address combo box
      let index = 0;
      for (const ipObject of defaults.ipaddress_list) {
        const option = {
          name: ipObject.ipaddress.replace(/\W/g, "_"),
          label: ipObject.ipaddress + " - " + ipObject.label,
          value: ipObject.ipaddress,
          iface: ipObject.label,
        };
        this.$set(this.samba.ipAddressOptions, index, option);
        index++;
      }
      this.$nextTick(() => {
        this.focusElement("adminuser");
      });
    },
    clearOpenLdapErrors() {
      for (const key of Object.keys(this.error.openldap)) {
        this.error.openldap[key] = "";
      }
    },
    clearSambaErrors() {
      for (const key of Object.keys(this.error.samba)) {
        this.error.samba[key] = "";
      }
    },
    validateConfigureOpenLdapModule() {
      this.clearOpenLdapErrors();
      let isValidationOk = true;
      // openldap admin user
      if (!this.openldap.admuser) {
        this.error.openldap.admuser = "common.required";
        if (isValidationOk) {
          this.focusElement("admuser");
          isValidationOk = false;
        }
      }
      if (!this.openldap.admpass) {
        this.error.openldap.admpass = "common.required";
        if (isValidationOk) {
          this.focusElement("admpass");
          isValidationOk = false;
        }
      }
      return isValidationOk;
    },
    validateConfigureSambaModule() {
      this.clearSambaErrors();
      let isValidationOk = true;
      if (!this.samba.adminuser) {
        this.error.samba.adminuser = "common.required";
        if (isValidationOk) {
          this.focusElement("adminuser");
          isValidationOk = false;
        }
      }
      if (!this.samba.adminpass) {
        this.error.samba.adminpass = "common.required";
        if (isValidationOk) {
          this.focusElement("adminpass");
          isValidationOk = false;
        }
      }
      if (!this.samba.hostname) {
        this.error.samba.hostname = "common.required";
        if (isValidationOk) {
          this.focusElement("hostname");
          isValidationOk = false;
        }
      }
      if (this.samba.enableFileServer && !this.samba.ipaddress) {
        this.error.samba.ipaddress = "common.required";
        if (isValidationOk) {
          isValidationOk = false;
        }
      }
      return isValidationOk;
    },
    async configureSambaModule() {
      const isValidationOk = this.validateConfigureSambaModule();
      if (!isValidationOk) {
        return;
      }
      this.loading.samba.configureModule = true;
      const taskAction = "configure-module";
      const eventId = this.getUuid();
      this.configureProviderProgress = 0;
      if (!this.samba.enableFileServer) {
        this.samba.ipaddress = this.vpnInterface.value;
      }
      this.$root.$once(
        `${taskAction}-validation-failed-${eventId}`,
        this.configureSambaModuleValidationFailed
      );
      this.$root.$once(
        `${taskAction}-validation-ok-${eventId}`,
        this.configureSambaModuleValidationOk
      );
      this.$root.$on(
        `${taskAction}-progress-${eventId}`,
        this.configureSambaModuleProgress
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.configureSambaModuleCompleted
      );
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.configureSambaModuleAborted
      );
      const res = await to(
        this.createModuleTaskForApp(this.newProviderId, {
          action: taskAction,
          data: {
            adminuser: this.samba.adminuser,
            adminpass: this.samba.adminpass,
            realm: this.domain.name,
            ipaddress: this.samba.ipaddress,
            hostname: this.samba.hostname,
            provision: "join-domain",
          },
          extra: {
            title: this.$t("samba.samba_configuration"),
            isNotificationHidden: true,
            isProgressNotified: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.samba.configureModule = this.getErrorMessage(err);
        this.loading.samba.configureModule = false;
        return;
      }
    },
    configureSambaModuleValidationOk() {
      this.step = "configuringProvider";
    },
    configureSambaModuleValidationFailed(validationErrors, taskContext) {
      this.loading.samba.configureModule = false;
      this.$root.$off(
        `${taskContext.action}-progress-${taskContext.extra.eventId}`
      );
      let focusAlreadySet = false;
      for (const validationError of validationErrors) {
        if (
          [
            "realm_dc_reachable_check_failed",
            "realm_dc_avail_check_failed",
          ].includes(validationError.error)
        ) {
          this.error.samba.cannotReachDc = true;
        } else {
          const param = validationError.parameter;
          this.error.samba[param] = "domains." + validationError.error;
          if (!focusAlreadySet && param != "ipaddress") {
            this.focusElement(param);
            focusAlreadySet = true;
          }
        }
      }
    },
    configureSambaModuleProgress(progress) {
      this.configureProviderProgress = progress;
    },
    configureSambaModuleCompleted(taskContext) {
      this.loading.samba.configureModule = false;
      this.$root.$off(
        `${taskContext.action}-progress-${taskContext.extra.eventId}`
      );
      this.$emit("hide");
      this.$emit("reloadDomains");
      this.$root.$emit("reloadAppDrawer");
    },
    configureSambaModuleAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.loading.samba.configureModule = false;
      this.$root.$off(
        `${taskContext.action}-progress-${taskContext.extra.eventId}`
      );
      this.$emit("hide");
    },
    async configureOpenLdapModule() {
      const isValidationOk = this.validateConfigureOpenLdapModule();
      if (!isValidationOk) {
        return;
      }
      this.loading.openldap.configureModule = true;
      const taskAction = "configure-module";
      const eventId = this.getUuid();
      this.configureProviderProgress = 0;
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.configureOpenLdapModuleAborted
      );
      this.$root.$once(
        `${taskAction}-validation-failed-${eventId}`,
        this.configureOpenLdapModuleValidationFailed
      );
      this.$root.$once(
        `${taskAction}-validation-ok-${eventId}`,
        this.configureOpenLdapModuleValidationOk
      );
      this.$root.$on(
        `${taskAction}-progress-${eventId}`,
        this.configureOpenLdapModuleProgress
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.configureOpenLdapModuleCompleted
      );
      const res = await to(
        this.createModuleTaskForApp(this.newProviderId, {
          action: taskAction,
          data: {
            admuser: this.openldap.admuser,
            admpass: this.openldap.admpass,
            domain: this.domain.name,
            provision: "join-domain",
          },
          extra: {
            title: this.$t("openldap.openldap_configuration"),
            isNotificationHidden: true,
            isProgressNotified: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.openldap.configureModule = this.getErrorMessage(err);
        this.loading.openldap.configureModule = false;
        return;
      }
    },
    configureOpenLdapModuleAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.loading.openldap.configureModule = false;
      this.$root.$off(
        `${taskContext.action}-progress-${taskContext.extra.eventId}`
      );
      this.$emit("hide");
    },
    configureOpenLdapModuleValidationOk() {
      this.step = "configuringProvider";
    },
    configureOpenLdapModuleValidationFailed(validationErrors, taskContext) {
      this.loading.openldap.configureModule = false;
      this.$root.$off(
        `${taskContext.action}-progress-${taskContext.extra.eventId}`
      );
      let focusAlreadySet = false;
      for (const validationError of validationErrors) {
        const param = validationError.parameter;
        this.error.openldap[param] = "domains." + validationError.error;
        if (!focusAlreadySet) {
          this.focusElement(param);
          focusAlreadySet = true;
        }
      }
    },
    configureOpenLdapModuleProgress(progress) {
      this.configureProviderProgress = progress;
    },
    configureOpenLdapModuleCompleted(taskContext) {
      this.loading.openldap.configureModule = false;
      this.$root.$off(
        `${taskContext.action}-progress-${taskContext.extra.eventId}`
      );
      this.$emit("hide");
      this.$emit("reloadDomains");
    },
    async listModules() {
      this.loading.listModules = true;
      this.error.listModules = "";
      this.modules = [];
      this.selectedNode = null;
      const taskAction = "list-modules";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.listModulesAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.listModulesCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.listModules = this.getErrorMessage(err);
        this.loading.listModules = false;
        return;
      }
    },
    listModulesAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.listModules = this.$t("error.generic_error");
      this.loading.listModules = false;
    },
    listModulesCompleted(taskContext, taskResult) {
      this.loading.listModules = false;
      let modules = taskResult.output;
      this.modules = modules;
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
.mg-top {
  margin-top: $spacing-05;
}
.row {
  margin-bottom: $spacing-03;
}
.label {
  padding-right: 0.5rem;
  font-weight: bold;
}
.bx--form {
  .bx--form-item,
  .cv-combo-box {
    margin-bottom: $spacing-06;
  }
}
.mg-bottom-5 {
  margin-bottom: 5rem !important;
}
</style>
</file>

<file path="core/ui/src/components/domains/ChangeUserPasswordModal.vue">
<template>
  <NsModal
    size="default"
    :visible="isShown"
    @modal-hidden="onModalHidden"
    @primary-click="changeUserPassword"
    :primary-button-disabled="loading.alterUser || loading.listPasswordPolicy"
    class="no-pad-modal"
  >
    <template v-if="user" slot="title">{{
      $t("domain_users.change_password_for_user", { user: user.user })
    }}</template>
    <template slot="content">
      <cv-form @submit.prevent="changeUserPassword">
        <NsPasswordInput
          :newPasswordLabel="$t('password.new_password')"
          :confirmPasswordLabel="$t('password.re_enter_new_password')"
          v-model="newPassword"
          @passwordValidation="onPasswordValidation"
          :newPasswordInvalidMessage="$t(error.newPassword)"
          :confirmPasswordInvalidMessage="$t(error.confirmPassword)"
          :passwordHideLabel="$t('password.hide_password')"
          :passwordShowLabel="$t('password.show_password')"
          :lengthLabel="$t('password.long_enough')"
          :lowercaseLabel="$t('password.lowercase_letter')"
          :uppercaseLabel="$t('password.uppercase_letter')"
          :numberLabel="$t('password.number')"
          :symbolLabel="$t('password.symbol')"
          :equalLabel="$t('password.equal')"
          :focus="focusPasswordField"
          :clearConfirmPasswordCommand="clearConfirmPasswordCommand"
          :minLength="
            policy.strength.enforced
              ? parseInt(policy.strength.password_min_length, 10)
              : 0
          "
          :checkComplexity="
            policy.strength.enforced ? policy.strength.complexity_check : false
          "
        />
        <NsToggle
          v-if="isActiveDirectory"
          :label="$t('domain_users.change_password_at_next_login')"
          value="mustChangePassword"
          :form-item="true"
          v-model="mustChangePassword"
          :disabled="
            loading.addUser || loading.alterUser || passwordMustBeChanged
          "
          tooltipAlignment="start"
          tooltipDirection="bottom"
          ref="mustChangePassword"
        >
          <template slot="tooltip">{{
            $t("domain_users.must_change_password_tooltip")
          }}</template>
          <template slot="text-left">{{ $t("common.disabled") }}</template>
          <template slot="text-right">{{ $t("common.enabled") }}</template>
        </NsToggle>
        <div v-if="passwordMustBeChanged">
          <NsInlineNotification
            kind="info"
            :title="$t('domain_users.must_change_password_information_title')"
            :description="
              $t('domain_users.must_change_password_information_description')
            "
            :showCloseButton="false"
          />
        </div>
        <div v-if="error.alterUser">
          <NsInlineNotification
            kind="error"
            :title="$t('action.alter-user')"
            :description="error.alterUser"
            :showCloseButton="false"
          />
        </div>
        <NsInlineNotification
          v-if="error.listPasswordPolicy"
          kind="error"
          :title="$t('action.get-password-policy')"
          :description="error.listPasswordPolicy"
          :showCloseButton="false"
        />
      </cv-form>
    </template>
    <template slot="secondary-button">{{ $t("common.cancel") }}</template>
    <template slot="primary-button">{{
      $t("domain_users.change_password")
    }}</template>
  </NsModal>
</template>
⋮----
<template v-if="user" slot="title">{{
      $t("domain_users.change_password_for_user", { user: user.user })
    }}</template>
<template slot="content">
      <cv-form @submit.prevent="changeUserPassword">
        <NsPasswordInput
          :newPasswordLabel="$t('password.new_password')"
          :confirmPasswordLabel="$t('password.re_enter_new_password')"
          v-model="newPassword"
          @passwordValidation="onPasswordValidation"
          :newPasswordInvalidMessage="$t(error.newPassword)"
          :confirmPasswordInvalidMessage="$t(error.confirmPassword)"
          :passwordHideLabel="$t('password.hide_password')"
          :passwordShowLabel="$t('password.show_password')"
          :lengthLabel="$t('password.long_enough')"
          :lowercaseLabel="$t('password.lowercase_letter')"
          :uppercaseLabel="$t('password.uppercase_letter')"
          :numberLabel="$t('password.number')"
          :symbolLabel="$t('password.symbol')"
          :equalLabel="$t('password.equal')"
          :focus="focusPasswordField"
          :clearConfirmPasswordCommand="clearConfirmPasswordCommand"
          :minLength="
            policy.strength.enforced
              ? parseInt(policy.strength.password_min_length, 10)
              : 0
          "
          :checkComplexity="
            policy.strength.enforced ? policy.strength.complexity_check : false
          "
        />
        <NsToggle
          v-if="isActiveDirectory"
          :label="$t('domain_users.change_password_at_next_login')"
          value="mustChangePassword"
          :form-item="true"
          v-model="mustChangePassword"
          :disabled="
            loading.addUser || loading.alterUser || passwordMustBeChanged
          "
          tooltipAlignment="start"
          tooltipDirection="bottom"
          ref="mustChangePassword"
        >
          <template slot="tooltip">{{
            $t("domain_users.must_change_password_tooltip")
          }}</template>
          <template slot="text-left">{{ $t("common.disabled") }}</template>
          <template slot="text-right">{{ $t("common.enabled") }}</template>
        </NsToggle>
        <div v-if="passwordMustBeChanged">
          <NsInlineNotification
            kind="info"
            :title="$t('domain_users.must_change_password_information_title')"
            :description="
              $t('domain_users.must_change_password_information_description')
            "
            :showCloseButton="false"
          />
        </div>
        <div v-if="error.alterUser">
          <NsInlineNotification
            kind="error"
            :title="$t('action.alter-user')"
            :description="error.alterUser"
            :showCloseButton="false"
          />
        </div>
        <NsInlineNotification
          v-if="error.listPasswordPolicy"
          kind="error"
          :title="$t('action.get-password-policy')"
          :description="error.listPasswordPolicy"
          :showCloseButton="false"
        />
      </cv-form>
    </template>
⋮----
<template slot="tooltip">{{
            $t("domain_users.must_change_password_tooltip")
          }}</template>
<template slot="text-left">{{ $t("common.disabled") }}</template>
<template slot="text-right">{{ $t("common.enabled") }}</template>
⋮----
<template slot="secondary-button">{{ $t("common.cancel") }}</template>
<template slot="primary-button">{{
      $t("domain_users.change_password")
    }}</template>
⋮----
<script>
import { UtilService, TaskService, IconService } from "@nethserver/ns8-ui-lib";
import to from "await-to-js";
export default {
  name: "ChangeUserPasswordModal",
  mixins: [UtilService, TaskService, IconService],
  props: {
    isShown: Boolean,
    domain: { type: Object },
    user: { type: [Object, null] },
  },
  data() {
    return {
      newPassword: "",
      passwordValidation: null,
      focusPasswordField: { element: "" },
      clearConfirmPasswordCommand: 0,
      mustChangePassword: false,
      policy: {
        strength: {
          complexity_check: false,
          enforced: false,
          password_min_length: 8,
        },
      },
      loading: {
        alterUser: false,
        listPasswordPolicy: false,
      },
      error: {
        alterUser: "",
        newPassword: "",
        confirmPassword: "",
        listPasswordPolicy: "",
        mustChangePassword: "",
      },
    };
  },
  computed: {
    mainProvider() {
      return this.domain.providers[0].id;
    },
    isActiveDirectory() {
      return this.domain && this.domain.schema === "ad";
    },
    passwordMustBeChanged() {
      return this.user && this.user.must_change ? true : false;
    },
  },
  watch: {
    isShown: function () {
      if (this.isShown) {
        this.newPassword = "";
        this.clearConfirmPasswordCommand++;
        this.listPasswordPolicy();
        setTimeout(() => {
          this.focusPasswordField = { element: "newPassword" };
        }, 400);
        this.mustChangePassword =
          this.user && this.user.must_change ? true : false;
      }
    },
  },
  methods: {
    async listPasswordPolicy() {
      this.loading.listPasswordPolicy = true;
      this.error.listPasswordPolicy = "";
      const taskAction = "get-password-policy";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.listPasswordPolicyCompleted
      );
      const res = await to(
        this.createModuleTaskForApp(this.mainProvider, {
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.listPasswordPolicy = this.getErrorMessage(err);
        return;
      }
    },
    listPasswordPolicyCompleted(taskContext, taskResult) {
      const config = taskResult.output;
      this.policy.strength.enforced = config.strength.enforced;
      this.policy.strength.complexity_check = config.strength.complexity_check;
      this.policy.strength.password_min_length =
        config.strength.password_min_length.toString();
      this.loading.listPasswordPolicy = false;
    },
    validateChangeUserPassword() {
      this.clearErrors();
      let isValidationOk = true;
      if (!this.newPassword) {
        this.error.newPassword = this.$t("common.required");
        if (isValidationOk) {
          this.focusPasswordField = { element: "newPassword" };
          isValidationOk = false;
        }
      } else {
        if (this.currentPassword === this.newPassword) {
          if (!this.error.newPassword) {
            this.error.newPassword = this.$t(
              "password.old_new_passwords_must_be_different"
            );
          }
          if (isValidationOk) {
            this.focusPasswordField = { element: "newPassword" };
            isValidationOk = false;
          }
        }
        if (
          !this.passwordValidation.isLengthOk ||
          !this.passwordValidation.isLowercaseOk ||
          !this.passwordValidation.isUppercaseOk ||
          !this.passwordValidation.isNumberOk ||
          !this.passwordValidation.isSymbolOk
        ) {
          if (!this.error.newPassword) {
            this.error.newPassword = this.$t("password.password_not_secure");
          }
          if (isValidationOk) {
            this.focusPasswordField = { element: "newPassword" };
            isValidationOk = false;
          }
        }
        if (!this.passwordValidation.isEqualOk) {
          if (!this.error.newPassword) {
            this.error.newPassword = this.$t("password.passwords_do_not_match");
          }
          if (!this.error.confirmPassword) {
            this.error.confirmPassword = this.$t(
              "password.passwords_do_not_match"
            );
          }
          if (isValidationOk) {
            this.focusPasswordField = { element: "confirmPassword" };
            isValidationOk = false;
          }
        }
      }
      return isValidationOk;
    },
    async changeUserPassword() {
      if (!this.validateChangeUserPassword()) {
        return;
      }
      this.loading.alterUser = true;
      this.error.alterUser = "";
      const taskAction = "alter-user";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.alterUserAborted
      );
      this.$root.$once(
        `${taskAction}-validation-ok-${eventId}`,
        this.alterUserValidationOk
      );
      this.$root.$once(
        `${taskAction}-validation-failed-${eventId}`,
        this.alterUserValidationFailed
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.alterUserCompleted
      );
      const res = await to(
        this.createModuleTaskForApp(this.mainProvider, {
          action: taskAction,
          data: {
            user: this.user.user,
            password: this.newPassword,
            must_change_password: this.mustChangePassword,
          },
          extra: {
            title: this.$t("domain_users.change_password_for_user", {
              user: this.user.user,
            }),
            description: this.$t("common.processing"),
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.alterUser = this.getErrorMessage(err);
        this.loading.alterUser = false;
        return;
      }
    },
    alterUserAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.loading.alterUser = false;
      this.$emit("hide");
    },
    alterUserValidationOk() {
      this.loading.alterUser = false;
      this.$emit("hide");
    },
    alterUserValidationFailed(validationErrors) {
      this.loading.alterUser = false;
      let focusAlreadySet = false;
      for (const validationError of validationErrors) {
        const param = validationError.parameter;
        this.error[param] = this.$t("domain_users." + validationError.error);
        if (!focusAlreadySet) {
          this.focusElement(param);
          focusAlreadySet = true;
        }
      }
    },
    alterUserCompleted() {
      this.loading.alterUser = false;
      this.$emit("reloadUsers");
    },
    onModalHidden() {
      this.clearErrors();
      this.$emit("hide");
    },
    onPasswordValidation(passwordValidation) {
      this.passwordValidation = passwordValidation;
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
</style>
</file>

<file path="core/ui/src/components/domains/CreateDomainModal.vue">
<template>
  <NsWizard
    size="default"
    :visible="isShown"
    :cancelLabel="$t('common.cancel')"
    :previousLabel="$t('common.previous')"
    :nextLabel="nextButtonLabel"
    :isPreviousDisabled="isPreviousButtonDisabled"
    :isNextDisabled="isNextButtonDisabled"
    :isCancelDisabled="isCancelButtonDisabled"
    :isNextLoading="loading.external.addExternalDomain"
    @modal-hidden="$emit('hide')"
    @cancel="$emit('hide')"
    @previousStep="previousStep"
    @nextStep="nextStep"
    :isLastStep="hideButtonIcon"
  >
    <template slot="title">{{ $t("domains.create_domain") }}</template>
    <template slot="content">
      <template v-if="step == 'location'">
        <div class="mg-bottom-md">
          {{ $t("domains.select_domain_location") }}
        </div>
        <div class="bx--grid no-padding">
          <div class="bx--row">
            <div class="bx--col-md-4">
              <NsTile
                :light="true"
                kind="selectable"
                v-model="isInternalSelected"
                value="locationValue"
                @click="isExternalSelected = false"
                class="min-height-card"
              >
                <h6 class="mg-bottom-md">
                  {{ $t("domains.internal") }}
                </h6>
                <div>
                  {{ $t("domains.internal_description") }}
                </div>
              </NsTile>
            </div>
            <div class="bx--col-md-4">
              <NsTile
                :light="true"
                kind="selectable"
                v-model="isExternalSelected"
                value="locationValue"
                @click="isInternalSelected = false"
                class="min-height-card"
              >
                <h6 class="mg-bottom-md">
                  {{ $t("domains.external") }}
                </h6>
                <div>
                  {{ $t("domains.external_description") }}
                </div>
              </NsTile>
            </div>
          </div>
        </div>
      </template>
      <template v-if="step == 'instance'">
        <div class="mg-bottom-md">
          {{ $t("domains.select_prodiver_module") }}
        </div>
        <div class="bx--grid no-padding">
          <div class="bx--row">
            <div class="bx--col-md-4">
              <NsTile
                :light="true"
                kind="selectable"
                v-model="isOpenLdapSelected"
                value="instanceValue"
                @click="isSambaSelected = false"
                class="min-height-card"
              >
                <h6 class="mg-bottom-md">
                  {{ $t("domains.openldap") }}
                </h6>
              </NsTile>
            </div>
            <div class="bx--col-md-4">
              <NsTile
                :light="true"
                kind="selectable"
                v-model="isSambaSelected"
                value="instanceValue"
                @click="isOpenLdapSelected = false"
                class="min-height-card"
              >
                <h6 class="mg-bottom-md">
                  {{ $t("domains.samba") }}
                </h6>
              </NsTile>
            </div>
          </div>
        </div>
      </template>
      <template v-if="step == 'externalConfig'">
        <cv-form>
          <cv-text-input
            :label="$t('domains.domain')"
            v-model.trim="external.domain"
            :helper-text="$t('domains.enter_external_domain_name')"
            :invalid-message="$t(error.external.domain)"
            :disabled="loading.external.addExternalDomain"
            ref="domain"
          >
          </cv-text-input>
          <cv-text-input
            :label="$t('domains.host')"
            v-model.trim="external.host"
            :invalid-message="$t(error.external.host)"
            :disabled="loading.external.addExternalDomain"
            ref="host"
          >
          </cv-text-input>
          <cv-text-input
            :label="$t('domains.port')"
            v-model.trim="external.port"
            :invalid-message="$t(error.external.port)"
            :disabled="loading.external.addExternalDomain"
            type="number"
            ref="port"
          >
          </cv-text-input>
          <cv-text-input
            :label="$t('domains.bind_dn')"
            v-model.trim="external.bind_dn"
            :invalid-message="$t(error.external.bind_dn)"
            :disabled="loading.external.addExternalDomain"
            ref="bind_dn"
          >
          </cv-text-input>
          <cv-text-input
            :label="$t('domains.bind_password')"
            type="password"
            v-model="external.bind_password"
            :invalid-message="$t(error.external.bind_password)"
            :disabled="loading.external.addExternalDomain"
            :password-hide-label="$t('password.hide_password')"
            :password-show-label="$t('password.show_password')"
            ref="bind_password"
          >
          </cv-text-input>
          <cv-text-input
            :label="$t('domains.base_dn') + ' (' + $t('common.optional') + ')'"
            v-model.trim="external.base_dn"
            :invalid-message="$t(error.external.base_dn)"
            :disabled="loading.external.addExternalDomain"
            ref="base_dn"
          >
          </cv-text-input>
          <cv-toggle
            :label="$t('domains.tls')"
            value="tlsValue"
            :form-item="true"
            v-model="external.tls"
            :disabled="loading.external.addExternalDomain"
            ref="tls"
          >
            <template slot="text-left">{{ $t("common.disabled") }}</template>
            <template slot="text-right">{{ $t("common.enabled") }}</template>
          </cv-toggle>
          <NsInlineNotification
            v-if="error.external.tls"
            kind="error"
            :title="$t(error.external.tls)"
            :showCloseButton="false"
          />
          <cv-toggle
            :label="$t('domains.tls_verify')"
            value="tls_verifyValue"
            :form-item="true"
            v-model="external.tls_verify"
            :disabled="loading.external.addExternalDomain"
            ref="tls_verify"
          >
            <template slot="text-left">{{ $t("common.disabled") }}</template>
            <template slot="text-right">{{ $t("common.enabled") }}</template>
          </cv-toggle>
          <NsInlineNotification
            v-if="error.external.tls_verify"
            kind="error"
            :title="$t(error.external.tls_verify)"
            :showCloseButton="false"
          />
        </cv-form>
      </template>
      <template v-if="step == 'node'">
        <div>
          {{ $t("domains.choose_node_for_account_provider_installation") }}
        </div>
        <NsInlineNotification
          v-if="clusterNodes.length == disabledNodes.length"
          kind="info"
          :title="$t('domains.no_node_eligible_for_provider_installation')"
          :showCloseButton="false"
        />
        <NsInlineNotification
          v-if="error.listModules"
          kind="error"
          :title="$t('action.list-modules')"
          :description="error.listModules"
          :showCloseButton="false"
        />
        <NsInlineNotification
          v-if="error.getClusterStatus"
          kind="error"
          :title="$t('action.get-cluster-status')"
          :description="error.getClusterStatus"
          :showCloseButton="false"
        />
        <NsInlineNotification
          v-if="error.nodesList"
          kind="error"
          :title="$t('action.list-nodes')"
          :description="error.nodesList"
          :showCloseButton="false"
        />
        <NsInlineNotification
          v-if="error.listMountPoints"
          kind="error"
          :title="$t('action.list-mountpoints')"
          :description="error.listMountPoints"
          :showCloseButton="false"
        />
        <NodeSelector
          v-else
          :disabledNodes="disabledNodes"
          :nodesWithAdditionalStorage="nodesWithAdditionalStorage"
          :nodesDefaultDiskInfo="nodesDefaultDiskInfo"
          @selectNode="onSelectNode"
          :loading="isLoadingNodesData"
          class="mg-top-xlg"
        >
          <template v-for="node in clusterNodes">
            <template :slot="`node-${node.id}`">
              <span v-if="nodesInfo[node.id]" :key="node.id">
                {{ $t(nodesInfo[node.id].message) }}
              </span>
            </template>
          </template>
        </NodeSelector>
      </template>
      <template v-if="step == 'installingProvider'">
        <NsInlineNotification
          v-if="error.addInternalProvider"
          kind="error"
          :title="$t('action.add-internal-provider')"
          :description="error.addInternalProvider"
          :showCloseButton="false"
        />
        <NsEmptyState
          :title="$t('domains.installing_account_provider')"
          :animationData="GearsLottie"
          animationTitle="gears"
          :loop="true"
        />
        <NsProgressBar
          :value="installProviderProgress"
          :indeterminate="!installProviderProgress"
          class="mg-bottom-md"
        />
      </template>
      <template v-if="step == 'volumes' && selectedNode">
        <NsInlineNotification
          v-if="error.listMountPoints"
          kind="error"
          :title="$t('action.list-mountpoints')"
          :description="error.listMountPoints"
          :showCloseButton="false"
        />
        <div>
          <NsInlineNotification
            kind="info"
            :title="$t('domains.nodes_with_additional_storage_info')"
            :description="
              $t('domains.nodes_with_additional_storage_info_description')
            "
            :showCloseButton="false"
          />
          <div>
            {{
              $t("domains.select_node_volume_for_installation", {
                node: this.getNodeLabel(selectedNode) || "",
              })
            }}. {{ $t("software_center.other_files_remain_on_default_volume") }}
          </div>
          <AdditionalVolumesSelector
            @selectVolume="onSelectVolume"
            :volumes="additionalVolumes"
            :light="true"
            class="mg-top-lg"
          />
        </div>
      </template>
      <template v-if="step == 'internalConfig'">
        <template v-if="isOpenLdapSelected">
          <NsInlineNotification
            v-if="error.openldap.getDefaults"
            kind="error"
            :title="$t('action.get-defaults')"
            :description="error.openldap.getDefaults"
            :showCloseButton="false"
          />
          <cv-form>
            <cv-text-input
              :label="$t('openldap.domain')"
              v-model.trim="openldap.domain"
              :invalid-message="$t(error.openldap.domain)"
              :disabled="
                loading.openldap.configureModule || loading.openldap.getDefaults
              "
              ref="domain"
            >
            </cv-text-input>
            <cv-text-input
              :label="$t('openldap.admuser')"
              v-model.trim="openldap.admuser"
              :invalid-message="$t(error.openldap.admuser)"
              :disabled="
                loading.openldap.configureModule || loading.openldap.getDefaults
              "
              ref="admuser"
            >
            </cv-text-input>
            <NsPasswordInput
              :newPasswordLabel="$t('openldap.admpass')"
              :confirmPasswordLabel="$t('openldap.admpass_confirm')"
              v-model="openldap.admpass"
              @passwordValidation="onNewOpenLdapPasswordValidation"
              :newPasswordHelperText="
                $t('openldap.choose_openldap_admin_password')
              "
              :newPasswordInvalidMessage="$t(error.openldap.admpass)"
              :confirmPasswordInvalidMessage="
                $t(error.openldap.confirmPassword)
              "
              :passwordHideLabel="$t('password.hide_password')"
              :passwordShowLabel="$t('password.show_password')"
              :lengthLabel="$t('password.long_enough')"
              :lowercaseLabel="$t('password.lowercase_letter')"
              :uppercaseLabel="$t('password.uppercase_letter')"
              :numberLabel="$t('password.number')"
              :symbolLabel="$t('password.symbol')"
              :equalLabel="$t('password.equal')"
              :focus="openldap.focusPasswordField"
              :disabled="
                loading.openldap.configureModule || loading.openldap.getDefaults
              "
              light
              class="new-provider-password"
            />
          </cv-form>
          <NsInlineNotification
            v-if="error.openldap.configureModule"
            kind="error"
            :title="$t('action.configure-module')"
            :description="error.openldap.configureModule"
            :showCloseButton="false"
          />
        </template>
        <template v-if="isSambaSelected">
          <NsInlineNotification
            v-if="error.samba.getDefaults"
            kind="error"
            :title="$t('action.get-defaults')"
            :description="error.samba.getDefaults"
            :showCloseButton="false"
          />
          <cv-form>
            <cv-text-input
              :label="$t('samba.realm')"
              v-model.trim="samba.realm"
              :invalid-message="$t(error.samba.realm)"
              :disabled="
                loading.samba.configureModule || loading.samba.getDefaults
              "
              ref="realm"
            >
            </cv-text-input>
            <cv-text-input
              :label="$t('samba.nbdomain')"
              v-model.trim="samba.nbdomain"
              :invalid-message="$t(error.samba.nbdomain)"
              :disabled="
                loading.samba.configureModule || loading.samba.getDefaults
              "
              ref="nbdomain"
            >
            </cv-text-input>
            <NsTextInput
              :label="$t('samba.choose_samba_admin_username')"
              v-model.trim="samba.adminuser"
              :invalid-message="$t(error.samba.adminuser)"
              :disabled="
                loading.samba.configureModule || loading.samba.getDefaults
              "
              tooltipAlignment="start"
              tooltipDirection="bottom"
              ref="adminuser"
            >
              <template slot="tooltip">
                <div class="mg-bottom-sm">
                  {{ $t("samba.samba_admin_username_tooltip_1") }}
                </div>
                <ul class="unordered-list">
                  <li class="mg-bottom-sm">
                    {{ $t("samba.samba_admin_username_tooltip_2") }}
                  </li>
                  <li>{{ $t("samba.samba_admin_username_tooltip_3") }}</li>
                </ul>
              </template>
            </NsTextInput>
            <NsPasswordInput
              :newPasswordLabel="$t('samba.choose_samba_admin_password')"
              :confirmPasswordLabel="$t('samba.adminpass_confirm')"
              v-model="samba.adminpass"
              @passwordValidation="onNewSambaPasswordValidation"
              :newPasswordInvalidMessage="$t(error.samba.adminpass)"
              :confirmPasswordInvalidMessage="$t(error.samba.confirmPassword)"
              :passwordHideLabel="$t('password.hide_password')"
              :passwordShowLabel="$t('password.show_password')"
              :lengthLabel="$t('password.long_enough')"
              :lowercaseLabel="$t('password.lowercase_letter')"
              :uppercaseLabel="$t('password.uppercase_letter')"
              :numberLabel="$t('password.number')"
              :symbolLabel="$t('password.symbol')"
              :equalLabel="$t('password.equal')"
              :focus="samba.focusPasswordField"
              :disabled="
                loading.samba.configureModule || loading.samba.getDefaults
              "
              light
              class="new-provider-password"
            />
            <NsTextInput
              :label="$t('samba.hostname')"
              v-model.trim="samba.hostname"
              :invalid-message="$t(error.samba.hostname)"
              :disabled="
                loading.samba.configureModule || loading.samba.getDefaults
              "
              ref="hostname"
            >
            </NsTextInput>
            <NsToggle
              :label="$t('samba.enable_file_server_label')"
              value="enableFileServer"
              :form-item="true"
              v-model="samba.enableFileServer"
              :disabled="
                loading.samba.configureModule || loading.samba.getDefaults
              "
              tooltipAlignment="start"
              tooltipDirection="bottom"
              ref="enableFileServer"
            >
              <template slot="tooltip">{{
                $t("samba.enable_file_server_tooltip")
              }}</template>
              <template slot="text-left">{{ $t("common.disabled") }}</template>
              <template slot="text-right">{{ $t("common.enabled") }}</template>
            </NsToggle>
            <NsInlineNotification
              v-if="samba.enableFileServer"
              kind="warning"
              :title="$t('common.warning')"
              :description="$t('samba.choose_ip_address_warning')"
              :showCloseButton="false"
            />
            <NsComboBox
              v-if="samba.enableFileServer"
              v-model="samba.ipaddress"
              :label="$t('common.choose')"
              :options="filteredIpAddressOptions"
              auto-highlight
              :title="$t('samba.provider_ipaddress')"
              :invalid-message="$t(error.samba.ipaddress)"
              :disabled="
                loading.samba.configureModule || loading.samba.getDefaults
              "
              light
              class="mg-bottom-5"
              ref="ipaddress"
            >
            </NsComboBox>
            <NsInlineNotification
              v-if="!samba.enableFileServer && vpnInterface"
              kind="info"
              :description="
                $t('samba.provider_on_vpn_address_message', {
                  vpnIpAddress: vpnInterface.value,
                })
              "
              :showCloseButton="false"
            />
          </cv-form>
          <NsInlineNotification
            v-if="error.samba.configureModule"
            kind="error"
            :title="$t('action.configure-module')"
            :description="error.samba.configureModule"
            :showCloseButton="false"
          />
          <NsInlineNotification
            v-if="error.samba.cannotReachDc"
            kind="error"
            :title="$t('domains.cannot_connect_to_domain_controller')"
            :description="
              $t('domains.cannot_connect_to_domain_controller_description')
            "
            :showCloseButton="false"
          />
        </template>
      </template>
      <template v-if="step == 'configuringProvider'">
        <NsEmptyState
          :title="$t('domains.configuring_account_provider')"
          :animationData="GearsLottie"
          animationTitle="gears"
          :loop="true"
        />
        <NsProgressBar
          :value="configureProviderProgress"
          :indeterminate="!configureProviderProgress"
          class="mg-bottom-md"
        />
      </template>
    </template>
  </NsWizard>
</template>
⋮----
<template slot="title">{{ $t("domains.create_domain") }}</template>
<template slot="content">
      <template v-if="step == 'location'">
        <div class="mg-bottom-md">
          {{ $t("domains.select_domain_location") }}
        </div>
        <div class="bx--grid no-padding">
          <div class="bx--row">
            <div class="bx--col-md-4">
              <NsTile
                :light="true"
                kind="selectable"
                v-model="isInternalSelected"
                value="locationValue"
                @click="isExternalSelected = false"
                class="min-height-card"
              >
                <h6 class="mg-bottom-md">
                  {{ $t("domains.internal") }}
                </h6>
                <div>
                  {{ $t("domains.internal_description") }}
                </div>
              </NsTile>
            </div>
            <div class="bx--col-md-4">
              <NsTile
                :light="true"
                kind="selectable"
                v-model="isExternalSelected"
                value="locationValue"
                @click="isInternalSelected = false"
                class="min-height-card"
              >
                <h6 class="mg-bottom-md">
                  {{ $t("domains.external") }}
                </h6>
                <div>
                  {{ $t("domains.external_description") }}
                </div>
              </NsTile>
            </div>
          </div>
        </div>
      </template>
      <template v-if="step == 'instance'">
        <div class="mg-bottom-md">
          {{ $t("domains.select_prodiver_module") }}
        </div>
        <div class="bx--grid no-padding">
          <div class="bx--row">
            <div class="bx--col-md-4">
              <NsTile
                :light="true"
                kind="selectable"
                v-model="isOpenLdapSelected"
                value="instanceValue"
                @click="isSambaSelected = false"
                class="min-height-card"
              >
                <h6 class="mg-bottom-md">
                  {{ $t("domains.openldap") }}
                </h6>
              </NsTile>
            </div>
            <div class="bx--col-md-4">
              <NsTile
                :light="true"
                kind="selectable"
                v-model="isSambaSelected"
                value="instanceValue"
                @click="isOpenLdapSelected = false"
                class="min-height-card"
              >
                <h6 class="mg-bottom-md">
                  {{ $t("domains.samba") }}
                </h6>
              </NsTile>
            </div>
          </div>
        </div>
      </template>
      <template v-if="step == 'externalConfig'">
        <cv-form>
          <cv-text-input
            :label="$t('domains.domain')"
            v-model.trim="external.domain"
            :helper-text="$t('domains.enter_external_domain_name')"
            :invalid-message="$t(error.external.domain)"
            :disabled="loading.external.addExternalDomain"
            ref="domain"
          >
          </cv-text-input>
          <cv-text-input
            :label="$t('domains.host')"
            v-model.trim="external.host"
            :invalid-message="$t(error.external.host)"
            :disabled="loading.external.addExternalDomain"
            ref="host"
          >
          </cv-text-input>
          <cv-text-input
            :label="$t('domains.port')"
            v-model.trim="external.port"
            :invalid-message="$t(error.external.port)"
            :disabled="loading.external.addExternalDomain"
            type="number"
            ref="port"
          >
          </cv-text-input>
          <cv-text-input
            :label="$t('domains.bind_dn')"
            v-model.trim="external.bind_dn"
            :invalid-message="$t(error.external.bind_dn)"
            :disabled="loading.external.addExternalDomain"
            ref="bind_dn"
          >
          </cv-text-input>
          <cv-text-input
            :label="$t('domains.bind_password')"
            type="password"
            v-model="external.bind_password"
            :invalid-message="$t(error.external.bind_password)"
            :disabled="loading.external.addExternalDomain"
            :password-hide-label="$t('password.hide_password')"
            :password-show-label="$t('password.show_password')"
            ref="bind_password"
          >
          </cv-text-input>
          <cv-text-input
            :label="$t('domains.base_dn') + ' (' + $t('common.optional') + ')'"
            v-model.trim="external.base_dn"
            :invalid-message="$t(error.external.base_dn)"
            :disabled="loading.external.addExternalDomain"
            ref="base_dn"
          >
          </cv-text-input>
          <cv-toggle
            :label="$t('domains.tls')"
            value="tlsValue"
            :form-item="true"
            v-model="external.tls"
            :disabled="loading.external.addExternalDomain"
            ref="tls"
          >
            <template slot="text-left">{{ $t("common.disabled") }}</template>
            <template slot="text-right">{{ $t("common.enabled") }}</template>
          </cv-toggle>
          <NsInlineNotification
            v-if="error.external.tls"
            kind="error"
            :title="$t(error.external.tls)"
            :showCloseButton="false"
          />
          <cv-toggle
            :label="$t('domains.tls_verify')"
            value="tls_verifyValue"
            :form-item="true"
            v-model="external.tls_verify"
            :disabled="loading.external.addExternalDomain"
            ref="tls_verify"
          >
            <template slot="text-left">{{ $t("common.disabled") }}</template>
            <template slot="text-right">{{ $t("common.enabled") }}</template>
          </cv-toggle>
          <NsInlineNotification
            v-if="error.external.tls_verify"
            kind="error"
            :title="$t(error.external.tls_verify)"
            :showCloseButton="false"
          />
        </cv-form>
      </template>
      <template v-if="step == 'node'">
        <div>
          {{ $t("domains.choose_node_for_account_provider_installation") }}
        </div>
        <NsInlineNotification
          v-if="clusterNodes.length == disabledNodes.length"
          kind="info"
          :title="$t('domains.no_node_eligible_for_provider_installation')"
          :showCloseButton="false"
        />
        <NsInlineNotification
          v-if="error.listModules"
          kind="error"
          :title="$t('action.list-modules')"
          :description="error.listModules"
          :showCloseButton="false"
        />
        <NsInlineNotification
          v-if="error.getClusterStatus"
          kind="error"
          :title="$t('action.get-cluster-status')"
          :description="error.getClusterStatus"
          :showCloseButton="false"
        />
        <NsInlineNotification
          v-if="error.nodesList"
          kind="error"
          :title="$t('action.list-nodes')"
          :description="error.nodesList"
          :showCloseButton="false"
        />
        <NsInlineNotification
          v-if="error.listMountPoints"
          kind="error"
          :title="$t('action.list-mountpoints')"
          :description="error.listMountPoints"
          :showCloseButton="false"
        />
        <NodeSelector
          v-else
          :disabledNodes="disabledNodes"
          :nodesWithAdditionalStorage="nodesWithAdditionalStorage"
          :nodesDefaultDiskInfo="nodesDefaultDiskInfo"
          @selectNode="onSelectNode"
          :loading="isLoadingNodesData"
          class="mg-top-xlg"
        >
          <template v-for="node in clusterNodes">
            <template :slot="`node-${node.id}`">
              <span v-if="nodesInfo[node.id]" :key="node.id">
                {{ $t(nodesInfo[node.id].message) }}
              </span>
            </template>
          </template>
        </NodeSelector>
      </template>
      <template v-if="step == 'installingProvider'">
        <NsInlineNotification
          v-if="error.addInternalProvider"
          kind="error"
          :title="$t('action.add-internal-provider')"
          :description="error.addInternalProvider"
          :showCloseButton="false"
        />
        <NsEmptyState
          :title="$t('domains.installing_account_provider')"
          :animationData="GearsLottie"
          animationTitle="gears"
          :loop="true"
        />
        <NsProgressBar
          :value="installProviderProgress"
          :indeterminate="!installProviderProgress"
          class="mg-bottom-md"
        />
      </template>
      <template v-if="step == 'volumes' && selectedNode">
        <NsInlineNotification
          v-if="error.listMountPoints"
          kind="error"
          :title="$t('action.list-mountpoints')"
          :description="error.listMountPoints"
          :showCloseButton="false"
        />
        <div>
          <NsInlineNotification
            kind="info"
            :title="$t('domains.nodes_with_additional_storage_info')"
            :description="
              $t('domains.nodes_with_additional_storage_info_description')
            "
            :showCloseButton="false"
          />
          <div>
            {{
              $t("domains.select_node_volume_for_installation", {
                node: this.getNodeLabel(selectedNode) || "",
              })
            }}. {{ $t("software_center.other_files_remain_on_default_volume") }}
          </div>
          <AdditionalVolumesSelector
            @selectVolume="onSelectVolume"
            :volumes="additionalVolumes"
            :light="true"
            class="mg-top-lg"
          />
        </div>
      </template>
      <template v-if="step == 'internalConfig'">
        <template v-if="isOpenLdapSelected">
          <NsInlineNotification
            v-if="error.openldap.getDefaults"
            kind="error"
            :title="$t('action.get-defaults')"
            :description="error.openldap.getDefaults"
            :showCloseButton="false"
          />
          <cv-form>
            <cv-text-input
              :label="$t('openldap.domain')"
              v-model.trim="openldap.domain"
              :invalid-message="$t(error.openldap.domain)"
              :disabled="
                loading.openldap.configureModule || loading.openldap.getDefaults
              "
              ref="domain"
            >
            </cv-text-input>
            <cv-text-input
              :label="$t('openldap.admuser')"
              v-model.trim="openldap.admuser"
              :invalid-message="$t(error.openldap.admuser)"
              :disabled="
                loading.openldap.configureModule || loading.openldap.getDefaults
              "
              ref="admuser"
            >
            </cv-text-input>
            <NsPasswordInput
              :newPasswordLabel="$t('openldap.admpass')"
              :confirmPasswordLabel="$t('openldap.admpass_confirm')"
              v-model="openldap.admpass"
              @passwordValidation="onNewOpenLdapPasswordValidation"
              :newPasswordHelperText="
                $t('openldap.choose_openldap_admin_password')
              "
              :newPasswordInvalidMessage="$t(error.openldap.admpass)"
              :confirmPasswordInvalidMessage="
                $t(error.openldap.confirmPassword)
              "
              :passwordHideLabel="$t('password.hide_password')"
              :passwordShowLabel="$t('password.show_password')"
              :lengthLabel="$t('password.long_enough')"
              :lowercaseLabel="$t('password.lowercase_letter')"
              :uppercaseLabel="$t('password.uppercase_letter')"
              :numberLabel="$t('password.number')"
              :symbolLabel="$t('password.symbol')"
              :equalLabel="$t('password.equal')"
              :focus="openldap.focusPasswordField"
              :disabled="
                loading.openldap.configureModule || loading.openldap.getDefaults
              "
              light
              class="new-provider-password"
            />
          </cv-form>
          <NsInlineNotification
            v-if="error.openldap.configureModule"
            kind="error"
            :title="$t('action.configure-module')"
            :description="error.openldap.configureModule"
            :showCloseButton="false"
          />
        </template>
        <template v-if="isSambaSelected">
          <NsInlineNotification
            v-if="error.samba.getDefaults"
            kind="error"
            :title="$t('action.get-defaults')"
            :description="error.samba.getDefaults"
            :showCloseButton="false"
          />
          <cv-form>
            <cv-text-input
              :label="$t('samba.realm')"
              v-model.trim="samba.realm"
              :invalid-message="$t(error.samba.realm)"
              :disabled="
                loading.samba.configureModule || loading.samba.getDefaults
              "
              ref="realm"
            >
            </cv-text-input>
            <cv-text-input
              :label="$t('samba.nbdomain')"
              v-model.trim="samba.nbdomain"
              :invalid-message="$t(error.samba.nbdomain)"
              :disabled="
                loading.samba.configureModule || loading.samba.getDefaults
              "
              ref="nbdomain"
            >
            </cv-text-input>
            <NsTextInput
              :label="$t('samba.choose_samba_admin_username')"
              v-model.trim="samba.adminuser"
              :invalid-message="$t(error.samba.adminuser)"
              :disabled="
                loading.samba.configureModule || loading.samba.getDefaults
              "
              tooltipAlignment="start"
              tooltipDirection="bottom"
              ref="adminuser"
            >
              <template slot="tooltip">
                <div class="mg-bottom-sm">
                  {{ $t("samba.samba_admin_username_tooltip_1") }}
                </div>
                <ul class="unordered-list">
                  <li class="mg-bottom-sm">
                    {{ $t("samba.samba_admin_username_tooltip_2") }}
                  </li>
                  <li>{{ $t("samba.samba_admin_username_tooltip_3") }}</li>
                </ul>
              </template>
            </NsTextInput>
            <NsPasswordInput
              :newPasswordLabel="$t('samba.choose_samba_admin_password')"
              :confirmPasswordLabel="$t('samba.adminpass_confirm')"
              v-model="samba.adminpass"
              @passwordValidation="onNewSambaPasswordValidation"
              :newPasswordInvalidMessage="$t(error.samba.adminpass)"
              :confirmPasswordInvalidMessage="$t(error.samba.confirmPassword)"
              :passwordHideLabel="$t('password.hide_password')"
              :passwordShowLabel="$t('password.show_password')"
              :lengthLabel="$t('password.long_enough')"
              :lowercaseLabel="$t('password.lowercase_letter')"
              :uppercaseLabel="$t('password.uppercase_letter')"
              :numberLabel="$t('password.number')"
              :symbolLabel="$t('password.symbol')"
              :equalLabel="$t('password.equal')"
              :focus="samba.focusPasswordField"
              :disabled="
                loading.samba.configureModule || loading.samba.getDefaults
              "
              light
              class="new-provider-password"
            />
            <NsTextInput
              :label="$t('samba.hostname')"
              v-model.trim="samba.hostname"
              :invalid-message="$t(error.samba.hostname)"
              :disabled="
                loading.samba.configureModule || loading.samba.getDefaults
              "
              ref="hostname"
            >
            </NsTextInput>
            <NsToggle
              :label="$t('samba.enable_file_server_label')"
              value="enableFileServer"
              :form-item="true"
              v-model="samba.enableFileServer"
              :disabled="
                loading.samba.configureModule || loading.samba.getDefaults
              "
              tooltipAlignment="start"
              tooltipDirection="bottom"
              ref="enableFileServer"
            >
              <template slot="tooltip">{{
                $t("samba.enable_file_server_tooltip")
              }}</template>
              <template slot="text-left">{{ $t("common.disabled") }}</template>
              <template slot="text-right">{{ $t("common.enabled") }}</template>
            </NsToggle>
            <NsInlineNotification
              v-if="samba.enableFileServer"
              kind="warning"
              :title="$t('common.warning')"
              :description="$t('samba.choose_ip_address_warning')"
              :showCloseButton="false"
            />
            <NsComboBox
              v-if="samba.enableFileServer"
              v-model="samba.ipaddress"
              :label="$t('common.choose')"
              :options="filteredIpAddressOptions"
              auto-highlight
              :title="$t('samba.provider_ipaddress')"
              :invalid-message="$t(error.samba.ipaddress)"
              :disabled="
                loading.samba.configureModule || loading.samba.getDefaults
              "
              light
              class="mg-bottom-5"
              ref="ipaddress"
            >
            </NsComboBox>
            <NsInlineNotification
              v-if="!samba.enableFileServer && vpnInterface"
              kind="info"
              :description="
                $t('samba.provider_on_vpn_address_message', {
                  vpnIpAddress: vpnInterface.value,
                })
              "
              :showCloseButton="false"
            />
          </cv-form>
          <NsInlineNotification
            v-if="error.samba.configureModule"
            kind="error"
            :title="$t('action.configure-module')"
            :description="error.samba.configureModule"
            :showCloseButton="false"
          />
          <NsInlineNotification
            v-if="error.samba.cannotReachDc"
            kind="error"
            :title="$t('domains.cannot_connect_to_domain_controller')"
            :description="
              $t('domains.cannot_connect_to_domain_controller_description')
            "
            :showCloseButton="false"
          />
        </template>
      </template>
      <template v-if="step == 'configuringProvider'">
        <NsEmptyState
          :title="$t('domains.configuring_account_provider')"
          :animationData="GearsLottie"
          animationTitle="gears"
          :loop="true"
        />
        <NsProgressBar
          :value="configureProviderProgress"
          :indeterminate="!configureProviderProgress"
          class="mg-bottom-md"
        />
      </template>
    </template>
⋮----
<template v-if="step == 'location'">
        <div class="mg-bottom-md">
          {{ $t("domains.select_domain_location") }}
        </div>
        <div class="bx--grid no-padding">
          <div class="bx--row">
            <div class="bx--col-md-4">
              <NsTile
                :light="true"
                kind="selectable"
                v-model="isInternalSelected"
                value="locationValue"
                @click="isExternalSelected = false"
                class="min-height-card"
              >
                <h6 class="mg-bottom-md">
                  {{ $t("domains.internal") }}
                </h6>
                <div>
                  {{ $t("domains.internal_description") }}
                </div>
              </NsTile>
            </div>
            <div class="bx--col-md-4">
              <NsTile
                :light="true"
                kind="selectable"
                v-model="isExternalSelected"
                value="locationValue"
                @click="isInternalSelected = false"
                class="min-height-card"
              >
                <h6 class="mg-bottom-md">
                  {{ $t("domains.external") }}
                </h6>
                <div>
                  {{ $t("domains.external_description") }}
                </div>
              </NsTile>
            </div>
          </div>
        </div>
      </template>
⋮----
{{ $t("domains.select_domain_location") }}
⋮----
{{ $t("domains.internal") }}
⋮----
{{ $t("domains.internal_description") }}
⋮----
{{ $t("domains.external") }}
⋮----
{{ $t("domains.external_description") }}
⋮----
<template v-if="step == 'instance'">
        <div class="mg-bottom-md">
          {{ $t("domains.select_prodiver_module") }}
        </div>
        <div class="bx--grid no-padding">
          <div class="bx--row">
            <div class="bx--col-md-4">
              <NsTile
                :light="true"
                kind="selectable"
                v-model="isOpenLdapSelected"
                value="instanceValue"
                @click="isSambaSelected = false"
                class="min-height-card"
              >
                <h6 class="mg-bottom-md">
                  {{ $t("domains.openldap") }}
                </h6>
              </NsTile>
            </div>
            <div class="bx--col-md-4">
              <NsTile
                :light="true"
                kind="selectable"
                v-model="isSambaSelected"
                value="instanceValue"
                @click="isOpenLdapSelected = false"
                class="min-height-card"
              >
                <h6 class="mg-bottom-md">
                  {{ $t("domains.samba") }}
                </h6>
              </NsTile>
            </div>
          </div>
        </div>
      </template>
⋮----
{{ $t("domains.select_prodiver_module") }}
⋮----
{{ $t("domains.openldap") }}
⋮----
{{ $t("domains.samba") }}
⋮----
<template v-if="step == 'externalConfig'">
        <cv-form>
          <cv-text-input
            :label="$t('domains.domain')"
            v-model.trim="external.domain"
            :helper-text="$t('domains.enter_external_domain_name')"
            :invalid-message="$t(error.external.domain)"
            :disabled="loading.external.addExternalDomain"
            ref="domain"
          >
          </cv-text-input>
          <cv-text-input
            :label="$t('domains.host')"
            v-model.trim="external.host"
            :invalid-message="$t(error.external.host)"
            :disabled="loading.external.addExternalDomain"
            ref="host"
          >
          </cv-text-input>
          <cv-text-input
            :label="$t('domains.port')"
            v-model.trim="external.port"
            :invalid-message="$t(error.external.port)"
            :disabled="loading.external.addExternalDomain"
            type="number"
            ref="port"
          >
          </cv-text-input>
          <cv-text-input
            :label="$t('domains.bind_dn')"
            v-model.trim="external.bind_dn"
            :invalid-message="$t(error.external.bind_dn)"
            :disabled="loading.external.addExternalDomain"
            ref="bind_dn"
          >
          </cv-text-input>
          <cv-text-input
            :label="$t('domains.bind_password')"
            type="password"
            v-model="external.bind_password"
            :invalid-message="$t(error.external.bind_password)"
            :disabled="loading.external.addExternalDomain"
            :password-hide-label="$t('password.hide_password')"
            :password-show-label="$t('password.show_password')"
            ref="bind_password"
          >
          </cv-text-input>
          <cv-text-input
            :label="$t('domains.base_dn') + ' (' + $t('common.optional') + ')'"
            v-model.trim="external.base_dn"
            :invalid-message="$t(error.external.base_dn)"
            :disabled="loading.external.addExternalDomain"
            ref="base_dn"
          >
          </cv-text-input>
          <cv-toggle
            :label="$t('domains.tls')"
            value="tlsValue"
            :form-item="true"
            v-model="external.tls"
            :disabled="loading.external.addExternalDomain"
            ref="tls"
          >
            <template slot="text-left">{{ $t("common.disabled") }}</template>
            <template slot="text-right">{{ $t("common.enabled") }}</template>
          </cv-toggle>
          <NsInlineNotification
            v-if="error.external.tls"
            kind="error"
            :title="$t(error.external.tls)"
            :showCloseButton="false"
          />
          <cv-toggle
            :label="$t('domains.tls_verify')"
            value="tls_verifyValue"
            :form-item="true"
            v-model="external.tls_verify"
            :disabled="loading.external.addExternalDomain"
            ref="tls_verify"
          >
            <template slot="text-left">{{ $t("common.disabled") }}</template>
            <template slot="text-right">{{ $t("common.enabled") }}</template>
          </cv-toggle>
          <NsInlineNotification
            v-if="error.external.tls_verify"
            kind="error"
            :title="$t(error.external.tls_verify)"
            :showCloseButton="false"
          />
        </cv-form>
      </template>
⋮----
<template slot="text-left">{{ $t("common.disabled") }}</template>
<template slot="text-right">{{ $t("common.enabled") }}</template>
⋮----
<template slot="text-left">{{ $t("common.disabled") }}</template>
<template slot="text-right">{{ $t("common.enabled") }}</template>
⋮----
<template v-if="step == 'node'">
        <div>
          {{ $t("domains.choose_node_for_account_provider_installation") }}
        </div>
        <NsInlineNotification
          v-if="clusterNodes.length == disabledNodes.length"
          kind="info"
          :title="$t('domains.no_node_eligible_for_provider_installation')"
          :showCloseButton="false"
        />
        <NsInlineNotification
          v-if="error.listModules"
          kind="error"
          :title="$t('action.list-modules')"
          :description="error.listModules"
          :showCloseButton="false"
        />
        <NsInlineNotification
          v-if="error.getClusterStatus"
          kind="error"
          :title="$t('action.get-cluster-status')"
          :description="error.getClusterStatus"
          :showCloseButton="false"
        />
        <NsInlineNotification
          v-if="error.nodesList"
          kind="error"
          :title="$t('action.list-nodes')"
          :description="error.nodesList"
          :showCloseButton="false"
        />
        <NsInlineNotification
          v-if="error.listMountPoints"
          kind="error"
          :title="$t('action.list-mountpoints')"
          :description="error.listMountPoints"
          :showCloseButton="false"
        />
        <NodeSelector
          v-else
          :disabledNodes="disabledNodes"
          :nodesWithAdditionalStorage="nodesWithAdditionalStorage"
          :nodesDefaultDiskInfo="nodesDefaultDiskInfo"
          @selectNode="onSelectNode"
          :loading="isLoadingNodesData"
          class="mg-top-xlg"
        >
          <template v-for="node in clusterNodes">
            <template :slot="`node-${node.id}`">
              <span v-if="nodesInfo[node.id]" :key="node.id">
                {{ $t(nodesInfo[node.id].message) }}
              </span>
            </template>
          </template>
        </NodeSelector>
      </template>
⋮----
{{ $t("domains.choose_node_for_account_provider_installation") }}
⋮----
<template v-for="node in clusterNodes">
            <template :slot="`node-${node.id}`">
              <span v-if="nodesInfo[node.id]" :key="node.id">
                {{ $t(nodesInfo[node.id].message) }}
              </span>
            </template>
          </template>
⋮----
<template :slot="`node-${node.id}`">
              <span v-if="nodesInfo[node.id]" :key="node.id">
                {{ $t(nodesInfo[node.id].message) }}
              </span>
            </template>
⋮----
{{ $t(nodesInfo[node.id].message) }}
⋮----
<template v-if="step == 'installingProvider'">
        <NsInlineNotification
          v-if="error.addInternalProvider"
          kind="error"
          :title="$t('action.add-internal-provider')"
          :description="error.addInternalProvider"
          :showCloseButton="false"
        />
        <NsEmptyState
          :title="$t('domains.installing_account_provider')"
          :animationData="GearsLottie"
          animationTitle="gears"
          :loop="true"
        />
        <NsProgressBar
          :value="installProviderProgress"
          :indeterminate="!installProviderProgress"
          class="mg-bottom-md"
        />
      </template>
<template v-if="step == 'volumes' && selectedNode">
        <NsInlineNotification
          v-if="error.listMountPoints"
          kind="error"
          :title="$t('action.list-mountpoints')"
          :description="error.listMountPoints"
          :showCloseButton="false"
        />
        <div>
          <NsInlineNotification
            kind="info"
            :title="$t('domains.nodes_with_additional_storage_info')"
            :description="
              $t('domains.nodes_with_additional_storage_info_description')
            "
            :showCloseButton="false"
          />
          <div>
            {{
              $t("domains.select_node_volume_for_installation", {
                node: this.getNodeLabel(selectedNode) || "",
              })
            }}. {{ $t("software_center.other_files_remain_on_default_volume") }}
          </div>
          <AdditionalVolumesSelector
            @selectVolume="onSelectVolume"
            :volumes="additionalVolumes"
            :light="true"
            class="mg-top-lg"
          />
        </div>
      </template>
⋮----
{{
              $t("domains.select_node_volume_for_installation", {
                node: this.getNodeLabel(selectedNode) || "",
              })
            }}. {{ $t("software_center.other_files_remain_on_default_volume") }}
⋮----
}}. {{ $t("software_center.other_files_remain_on_default_volume") }}
⋮----
<template v-if="step == 'internalConfig'">
        <template v-if="isOpenLdapSelected">
          <NsInlineNotification
            v-if="error.openldap.getDefaults"
            kind="error"
            :title="$t('action.get-defaults')"
            :description="error.openldap.getDefaults"
            :showCloseButton="false"
          />
          <cv-form>
            <cv-text-input
              :label="$t('openldap.domain')"
              v-model.trim="openldap.domain"
              :invalid-message="$t(error.openldap.domain)"
              :disabled="
                loading.openldap.configureModule || loading.openldap.getDefaults
              "
              ref="domain"
            >
            </cv-text-input>
            <cv-text-input
              :label="$t('openldap.admuser')"
              v-model.trim="openldap.admuser"
              :invalid-message="$t(error.openldap.admuser)"
              :disabled="
                loading.openldap.configureModule || loading.openldap.getDefaults
              "
              ref="admuser"
            >
            </cv-text-input>
            <NsPasswordInput
              :newPasswordLabel="$t('openldap.admpass')"
              :confirmPasswordLabel="$t('openldap.admpass_confirm')"
              v-model="openldap.admpass"
              @passwordValidation="onNewOpenLdapPasswordValidation"
              :newPasswordHelperText="
                $t('openldap.choose_openldap_admin_password')
              "
              :newPasswordInvalidMessage="$t(error.openldap.admpass)"
              :confirmPasswordInvalidMessage="
                $t(error.openldap.confirmPassword)
              "
              :passwordHideLabel="$t('password.hide_password')"
              :passwordShowLabel="$t('password.show_password')"
              :lengthLabel="$t('password.long_enough')"
              :lowercaseLabel="$t('password.lowercase_letter')"
              :uppercaseLabel="$t('password.uppercase_letter')"
              :numberLabel="$t('password.number')"
              :symbolLabel="$t('password.symbol')"
              :equalLabel="$t('password.equal')"
              :focus="openldap.focusPasswordField"
              :disabled="
                loading.openldap.configureModule || loading.openldap.getDefaults
              "
              light
              class="new-provider-password"
            />
          </cv-form>
          <NsInlineNotification
            v-if="error.openldap.configureModule"
            kind="error"
            :title="$t('action.configure-module')"
            :description="error.openldap.configureModule"
            :showCloseButton="false"
          />
        </template>
        <template v-if="isSambaSelected">
          <NsInlineNotification
            v-if="error.samba.getDefaults"
            kind="error"
            :title="$t('action.get-defaults')"
            :description="error.samba.getDefaults"
            :showCloseButton="false"
          />
          <cv-form>
            <cv-text-input
              :label="$t('samba.realm')"
              v-model.trim="samba.realm"
              :invalid-message="$t(error.samba.realm)"
              :disabled="
                loading.samba.configureModule || loading.samba.getDefaults
              "
              ref="realm"
            >
            </cv-text-input>
            <cv-text-input
              :label="$t('samba.nbdomain')"
              v-model.trim="samba.nbdomain"
              :invalid-message="$t(error.samba.nbdomain)"
              :disabled="
                loading.samba.configureModule || loading.samba.getDefaults
              "
              ref="nbdomain"
            >
            </cv-text-input>
            <NsTextInput
              :label="$t('samba.choose_samba_admin_username')"
              v-model.trim="samba.adminuser"
              :invalid-message="$t(error.samba.adminuser)"
              :disabled="
                loading.samba.configureModule || loading.samba.getDefaults
              "
              tooltipAlignment="start"
              tooltipDirection="bottom"
              ref="adminuser"
            >
              <template slot="tooltip">
                <div class="mg-bottom-sm">
                  {{ $t("samba.samba_admin_username_tooltip_1") }}
                </div>
                <ul class="unordered-list">
                  <li class="mg-bottom-sm">
                    {{ $t("samba.samba_admin_username_tooltip_2") }}
                  </li>
                  <li>{{ $t("samba.samba_admin_username_tooltip_3") }}</li>
                </ul>
              </template>
            </NsTextInput>
            <NsPasswordInput
              :newPasswordLabel="$t('samba.choose_samba_admin_password')"
              :confirmPasswordLabel="$t('samba.adminpass_confirm')"
              v-model="samba.adminpass"
              @passwordValidation="onNewSambaPasswordValidation"
              :newPasswordInvalidMessage="$t(error.samba.adminpass)"
              :confirmPasswordInvalidMessage="$t(error.samba.confirmPassword)"
              :passwordHideLabel="$t('password.hide_password')"
              :passwordShowLabel="$t('password.show_password')"
              :lengthLabel="$t('password.long_enough')"
              :lowercaseLabel="$t('password.lowercase_letter')"
              :uppercaseLabel="$t('password.uppercase_letter')"
              :numberLabel="$t('password.number')"
              :symbolLabel="$t('password.symbol')"
              :equalLabel="$t('password.equal')"
              :focus="samba.focusPasswordField"
              :disabled="
                loading.samba.configureModule || loading.samba.getDefaults
              "
              light
              class="new-provider-password"
            />
            <NsTextInput
              :label="$t('samba.hostname')"
              v-model.trim="samba.hostname"
              :invalid-message="$t(error.samba.hostname)"
              :disabled="
                loading.samba.configureModule || loading.samba.getDefaults
              "
              ref="hostname"
            >
            </NsTextInput>
            <NsToggle
              :label="$t('samba.enable_file_server_label')"
              value="enableFileServer"
              :form-item="true"
              v-model="samba.enableFileServer"
              :disabled="
                loading.samba.configureModule || loading.samba.getDefaults
              "
              tooltipAlignment="start"
              tooltipDirection="bottom"
              ref="enableFileServer"
            >
              <template slot="tooltip">{{
                $t("samba.enable_file_server_tooltip")
              }}</template>
              <template slot="text-left">{{ $t("common.disabled") }}</template>
              <template slot="text-right">{{ $t("common.enabled") }}</template>
            </NsToggle>
            <NsInlineNotification
              v-if="samba.enableFileServer"
              kind="warning"
              :title="$t('common.warning')"
              :description="$t('samba.choose_ip_address_warning')"
              :showCloseButton="false"
            />
            <NsComboBox
              v-if="samba.enableFileServer"
              v-model="samba.ipaddress"
              :label="$t('common.choose')"
              :options="filteredIpAddressOptions"
              auto-highlight
              :title="$t('samba.provider_ipaddress')"
              :invalid-message="$t(error.samba.ipaddress)"
              :disabled="
                loading.samba.configureModule || loading.samba.getDefaults
              "
              light
              class="mg-bottom-5"
              ref="ipaddress"
            >
            </NsComboBox>
            <NsInlineNotification
              v-if="!samba.enableFileServer && vpnInterface"
              kind="info"
              :description="
                $t('samba.provider_on_vpn_address_message', {
                  vpnIpAddress: vpnInterface.value,
                })
              "
              :showCloseButton="false"
            />
          </cv-form>
          <NsInlineNotification
            v-if="error.samba.configureModule"
            kind="error"
            :title="$t('action.configure-module')"
            :description="error.samba.configureModule"
            :showCloseButton="false"
          />
          <NsInlineNotification
            v-if="error.samba.cannotReachDc"
            kind="error"
            :title="$t('domains.cannot_connect_to_domain_controller')"
            :description="
              $t('domains.cannot_connect_to_domain_controller_description')
            "
            :showCloseButton="false"
          />
        </template>
      </template>
⋮----
<template v-if="isOpenLdapSelected">
          <NsInlineNotification
            v-if="error.openldap.getDefaults"
            kind="error"
            :title="$t('action.get-defaults')"
            :description="error.openldap.getDefaults"
            :showCloseButton="false"
          />
          <cv-form>
            <cv-text-input
              :label="$t('openldap.domain')"
              v-model.trim="openldap.domain"
              :invalid-message="$t(error.openldap.domain)"
              :disabled="
                loading.openldap.configureModule || loading.openldap.getDefaults
              "
              ref="domain"
            >
            </cv-text-input>
            <cv-text-input
              :label="$t('openldap.admuser')"
              v-model.trim="openldap.admuser"
              :invalid-message="$t(error.openldap.admuser)"
              :disabled="
                loading.openldap.configureModule || loading.openldap.getDefaults
              "
              ref="admuser"
            >
            </cv-text-input>
            <NsPasswordInput
              :newPasswordLabel="$t('openldap.admpass')"
              :confirmPasswordLabel="$t('openldap.admpass_confirm')"
              v-model="openldap.admpass"
              @passwordValidation="onNewOpenLdapPasswordValidation"
              :newPasswordHelperText="
                $t('openldap.choose_openldap_admin_password')
              "
              :newPasswordInvalidMessage="$t(error.openldap.admpass)"
              :confirmPasswordInvalidMessage="
                $t(error.openldap.confirmPassword)
              "
              :passwordHideLabel="$t('password.hide_password')"
              :passwordShowLabel="$t('password.show_password')"
              :lengthLabel="$t('password.long_enough')"
              :lowercaseLabel="$t('password.lowercase_letter')"
              :uppercaseLabel="$t('password.uppercase_letter')"
              :numberLabel="$t('password.number')"
              :symbolLabel="$t('password.symbol')"
              :equalLabel="$t('password.equal')"
              :focus="openldap.focusPasswordField"
              :disabled="
                loading.openldap.configureModule || loading.openldap.getDefaults
              "
              light
              class="new-provider-password"
            />
          </cv-form>
          <NsInlineNotification
            v-if="error.openldap.configureModule"
            kind="error"
            :title="$t('action.configure-module')"
            :description="error.openldap.configureModule"
            :showCloseButton="false"
          />
        </template>
⋮----
<template v-if="isSambaSelected">
          <NsInlineNotification
            v-if="error.samba.getDefaults"
            kind="error"
            :title="$t('action.get-defaults')"
            :description="error.samba.getDefaults"
            :showCloseButton="false"
          />
          <cv-form>
            <cv-text-input
              :label="$t('samba.realm')"
              v-model.trim="samba.realm"
              :invalid-message="$t(error.samba.realm)"
              :disabled="
                loading.samba.configureModule || loading.samba.getDefaults
              "
              ref="realm"
            >
            </cv-text-input>
            <cv-text-input
              :label="$t('samba.nbdomain')"
              v-model.trim="samba.nbdomain"
              :invalid-message="$t(error.samba.nbdomain)"
              :disabled="
                loading.samba.configureModule || loading.samba.getDefaults
              "
              ref="nbdomain"
            >
            </cv-text-input>
            <NsTextInput
              :label="$t('samba.choose_samba_admin_username')"
              v-model.trim="samba.adminuser"
              :invalid-message="$t(error.samba.adminuser)"
              :disabled="
                loading.samba.configureModule || loading.samba.getDefaults
              "
              tooltipAlignment="start"
              tooltipDirection="bottom"
              ref="adminuser"
            >
              <template slot="tooltip">
                <div class="mg-bottom-sm">
                  {{ $t("samba.samba_admin_username_tooltip_1") }}
                </div>
                <ul class="unordered-list">
                  <li class="mg-bottom-sm">
                    {{ $t("samba.samba_admin_username_tooltip_2") }}
                  </li>
                  <li>{{ $t("samba.samba_admin_username_tooltip_3") }}</li>
                </ul>
              </template>
            </NsTextInput>
            <NsPasswordInput
              :newPasswordLabel="$t('samba.choose_samba_admin_password')"
              :confirmPasswordLabel="$t('samba.adminpass_confirm')"
              v-model="samba.adminpass"
              @passwordValidation="onNewSambaPasswordValidation"
              :newPasswordInvalidMessage="$t(error.samba.adminpass)"
              :confirmPasswordInvalidMessage="$t(error.samba.confirmPassword)"
              :passwordHideLabel="$t('password.hide_password')"
              :passwordShowLabel="$t('password.show_password')"
              :lengthLabel="$t('password.long_enough')"
              :lowercaseLabel="$t('password.lowercase_letter')"
              :uppercaseLabel="$t('password.uppercase_letter')"
              :numberLabel="$t('password.number')"
              :symbolLabel="$t('password.symbol')"
              :equalLabel="$t('password.equal')"
              :focus="samba.focusPasswordField"
              :disabled="
                loading.samba.configureModule || loading.samba.getDefaults
              "
              light
              class="new-provider-password"
            />
            <NsTextInput
              :label="$t('samba.hostname')"
              v-model.trim="samba.hostname"
              :invalid-message="$t(error.samba.hostname)"
              :disabled="
                loading.samba.configureModule || loading.samba.getDefaults
              "
              ref="hostname"
            >
            </NsTextInput>
            <NsToggle
              :label="$t('samba.enable_file_server_label')"
              value="enableFileServer"
              :form-item="true"
              v-model="samba.enableFileServer"
              :disabled="
                loading.samba.configureModule || loading.samba.getDefaults
              "
              tooltipAlignment="start"
              tooltipDirection="bottom"
              ref="enableFileServer"
            >
              <template slot="tooltip">{{
                $t("samba.enable_file_server_tooltip")
              }}</template>
              <template slot="text-left">{{ $t("common.disabled") }}</template>
              <template slot="text-right">{{ $t("common.enabled") }}</template>
            </NsToggle>
            <NsInlineNotification
              v-if="samba.enableFileServer"
              kind="warning"
              :title="$t('common.warning')"
              :description="$t('samba.choose_ip_address_warning')"
              :showCloseButton="false"
            />
            <NsComboBox
              v-if="samba.enableFileServer"
              v-model="samba.ipaddress"
              :label="$t('common.choose')"
              :options="filteredIpAddressOptions"
              auto-highlight
              :title="$t('samba.provider_ipaddress')"
              :invalid-message="$t(error.samba.ipaddress)"
              :disabled="
                loading.samba.configureModule || loading.samba.getDefaults
              "
              light
              class="mg-bottom-5"
              ref="ipaddress"
            >
            </NsComboBox>
            <NsInlineNotification
              v-if="!samba.enableFileServer && vpnInterface"
              kind="info"
              :description="
                $t('samba.provider_on_vpn_address_message', {
                  vpnIpAddress: vpnInterface.value,
                })
              "
              :showCloseButton="false"
            />
          </cv-form>
          <NsInlineNotification
            v-if="error.samba.configureModule"
            kind="error"
            :title="$t('action.configure-module')"
            :description="error.samba.configureModule"
            :showCloseButton="false"
          />
          <NsInlineNotification
            v-if="error.samba.cannotReachDc"
            kind="error"
            :title="$t('domains.cannot_connect_to_domain_controller')"
            :description="
              $t('domains.cannot_connect_to_domain_controller_description')
            "
            :showCloseButton="false"
          />
        </template>
⋮----
<template slot="tooltip">
                <div class="mg-bottom-sm">
                  {{ $t("samba.samba_admin_username_tooltip_1") }}
                </div>
                <ul class="unordered-list">
                  <li class="mg-bottom-sm">
                    {{ $t("samba.samba_admin_username_tooltip_2") }}
                  </li>
                  <li>{{ $t("samba.samba_admin_username_tooltip_3") }}</li>
                </ul>
              </template>
⋮----
{{ $t("samba.samba_admin_username_tooltip_1") }}
⋮----
{{ $t("samba.samba_admin_username_tooltip_2") }}
⋮----
<li>{{ $t("samba.samba_admin_username_tooltip_3") }}</li>
⋮----
<template slot="tooltip">{{
                $t("samba.enable_file_server_tooltip")
              }}</template>
<template slot="text-left">{{ $t("common.disabled") }}</template>
<template slot="text-right">{{ $t("common.enabled") }}</template>
⋮----
<template v-if="step == 'configuringProvider'">
        <NsEmptyState
          :title="$t('domains.configuring_account_provider')"
          :animationData="GearsLottie"
          animationTitle="gears"
          :loop="true"
        />
        <NsProgressBar
          :value="configureProviderProgress"
          :indeterminate="!configureProviderProgress"
          class="mg-bottom-md"
        />
      </template>
⋮----
<script>
import {
  UtilService,
  TaskService,
  IconService,
  LottieService,
} from "@nethserver/ns8-ui-lib";
import to from "await-to-js";
import NodeSelector from "@/components/nodes/NodeSelector";
import AdditionalVolumesSelector from "@/components/software-center/AdditionalVolumesSelector.vue";
import { mapState } from "vuex";
export default {
  name: "CreateDomainModal",
  components: { NodeSelector, AdditionalVolumesSelector },
  mixins: [UtilService, TaskService, IconService, LottieService],
  props: {
    isShown: {
      type: Boolean,
      default: true,
    },
    isResumeConfiguration: {
      type: Boolean,
      default: false,
    },
    providerId: {
      type: String,
      default: "",
    },
    isOpenLdap: {
      type: Boolean,
      default: false,
    },
    isSamba: {
      type: Boolean,
      default: false,
    },
    domains: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      step: "",
      isInternalSelected: false,
      isExternalSelected: false,
      newProviderId: "",
      isOpenLdapSelected: false,
      isSambaSelected: false,
      installProviderProgress: 0,
      configureProviderProgress: 0,
      selectedNode: null,
      modules: [],
      nodesList: [],
      clusterStatus: [],
      nodesAdditionalDiskInfo: {},
      nodesDefaultDiskInfo: {},
      selectedVolume: {},
      samba: {
        adminuser: "",
        adminpass: "",
        realm: "",
        ipaddress: "",
        ipAddressOptions: [],
        hostname: "",
        nbdomain: "",
        passwordValidation: null,
        focusPasswordField: { element: "" },
        enableFileServer: false,
      },
      openldap: {
        domain: "",
        admuser: "",
        admpass: "",
        passwordValidation: null,
        focusPasswordField: { element: "" },
      },
      external: {
        domain: "",
        host: "",
        port: "",
        bind_dn: "",
        bind_password: "",
        base_dn: "",
        tls: true,
        tls_verify: true,
      },
      loading: {
        listModules: false,
        nodesList: false,
        getClusterStatus: false,
        samba: {
          getDefaults: false,
          configureModule: false,
        },
        openldap: {
          getDefaults: false,
          configureModule: false,
        },
        external: {
          addExternalDomain: false,
        },
      },
      error: {
        addInternalProvider: "",
        listModules: "",
        nodesList: "",
        getClusterStatus: "",
        listMountPoints: "",
        samba: {
          adminuser: "",
          adminpass: "",
          confirmPassword: "",
          realm: "",
          ipaddress: "",
          hostname: "",
          nbdomain: "",
          configureModule: "",
          getDefaults: "",
          addExternalDomain: "",
          cannotReachDc: false,
        },
        openldap: {
          getDefaults: "",
          domain: "",
          admuser: "",
          admpass: "",
          confirmPassword: "",
        },
        external: {
          domain: "",
          host: "",
          port: "",
          bind_dn: "",
          bind_password: "",
          base_dn: "",
          tls: "",
          tls_verify: "",
        },
      },
    };
  },
  computed: {
    ...mapState(["clusterNodes"]),
    nodesWithAdditionalStorage() {
      const nodeIds = [];
      if (!this.isSambaSelected) {
        return nodeIds;
      }
      if (!this.sambaModule || this.sambaVolumes.length === 0) {
        return nodeIds;
      }
      if (this.nodesList && Array.isArray(this.nodesList)) {
        for (const node of this.nodesList) {
          if (node.additional_disk_count > 0) {
            nodeIds.push(node.node_id);
          }
        }
      }
      return nodeIds;
    },
    additionalVolumes() {
      const output = this.nodesAdditionalDiskInfo[this.selectedNode?.id];
      if (!output) return [];
      const volumes = [...output.mountpoints];
      if (output.default_disk) {
        volumes.push({ ...output.default_disk, default: true });
      }
      return volumes;
    },
    isLoadingNodesData() {
      return (
        this.loading.nodesList ||
        this.loading.getClusterStatus ||
        this.loading.listModules
      );
    },
    sambaVolumes() {
      if (
        this.sambaModule &&
        this.sambaModule.versions &&
        this.sambaModule.versions.length &&
        this.sambaModule.versions[0].labels &&
        this.sambaModule.versions[0].labels["org.nethserver.volumes"]
      ) {
        const volumesString =
          this.sambaModule.versions[0].labels["org.nethserver.volumes"];
        return volumesString.split(" ").map((v) => v.trim());
      }
      return [];
    },
    nextButtonLabel() {
      if (this.step == "volumes") {
        return this.$t("domains.install_provider");
      } else if (this.step == "node") {
        if (
          this.selectedNode &&
          this.nodesWithAdditionalStorage.includes(this.selectedNode.id)
        ) {
          return this.$t("common.next");
        } else {
          return this.$t("domains.install_provider");
        }
      } else if (
        this.step == "internalConfig" ||
        this.step == "externalConfig"
      ) {
        return this.$t("domains.configure_domain");
      } else {
        return this.$t("common.next");
      }
    },
    isNextButtonDisabled() {
      return (
        this.loading.openldap.configureModule ||
        this.loading.samba.configureModule ||
        this.loading.external.addExternalDomain ||
        this.step == "installingProvider" ||
        this.step == "configuringProvider" ||
        (this.step == "location" &&
          !this.isInternalSelected &&
          !this.isExternalSelected) ||
        (this.step == "instance" &&
          !this.isOpenLdapSelected &&
          !this.isSambaSelected) ||
        (this.step == "node" && !this.selectedNode) ||
        (this.step == "volumes" && !this.selectedVolume?.path)
      );
    },
    isCancelButtonDisabled() {
      return (
        this.step == "installingProvider" || this.step == "configuringProvider"
      );
    },
    isPreviousButtonDisabled() {
      return (
        this.isResumeConfiguration ||
        this.loading.samba.configureModule ||
        this.loading.openldap.configureModule ||
        this.loading.external.addExternalDomain ||
        [
          "location",
          "installingProvider",
          "internalConfig",
          "configureProviderProgress",
        ].includes(this.step)
      );
    },
    vpnInterface() {
      return this.samba.ipAddressOptions.find((option) => {
        return option.iface === "wg0";
      });
    },
    filteredIpAddressOptions() {
      if (this.samba.enableFileServer) {
        return this.samba.ipAddressOptions.filter((option) => {
          return option != this.vpnInterface;
        });
      } else {
        return this.samba.ipAddressOptions;
      }
    },
    sambaModule() {
      return this.modules.find((module) => module.id === "samba");
    },
    disabledNodes() {
      const offlineNodeIds = this.clusterStatus
        .filter((node) => !node.online)
        .map((node) => node.id);
      if (this.isOpenLdapSelected) {
        return offlineNodeIds;
      } else {
        if (!this.sambaModule) {
          return offlineNodeIds;
        }
        const ineligibleNodeIds = this.sambaModule.install_destinations
          .filter((nodeInfo) => !nodeInfo.eligible)
          .map((nodeInfo) => nodeInfo.node_id);
        return [...new Set([...offlineNodeIds, ...ineligibleNodeIds])];
      }
    },
    nodesInfo() {
      const info = {};
      const offlineNodeIds = this.clusterStatus
        .filter((node) => !node.online)
        .map((node) => node.id);
      offlineNodeIds.forEach((nodeId) => {
        info[nodeId] = {
          message: "software_center.node_offline",
        };
      });
      if (this.isSambaSelected && this.sambaModule) {
        const ineligibleNodeIds = this.sambaModule.install_destinations
          .filter((nodeInfo) => !nodeInfo.eligible)
          .map((nodeInfo) => nodeInfo.node_id);
        ineligibleNodeIds.forEach((nodeId) => {
          if (!info[nodeId]) {
            info[nodeId] = {
              message: "domains.provider_already_installed",
            };
          }
        });
      }
      return info;
    },
    hideButtonIcon() {
      return (
        this.step === "volumes" ||
        (this.step === "node" &&
          this.selectedNode &&
          !this.nodesWithAdditionalStorage.includes(this.selectedNode.id)) ||
        this.step === "internalConfig"
      );
    },
  },
  watch: {
    isShown: function () {
      if (this.isShown) {
        this.clearErrors();
        if (!this.isResumeConfiguration) {
          this.step = "location";
        } else {
          this.step = "internalConfig";
          if (this.isOpenLdap) {
            this.getOpenLdapDefaults();
          } else if (this.isSamba) {
            this.getSambaDefaults();
          }
        }
      }
    },
    providerId: function () {
      this.newProviderId = this.providerId;
    },
    isOpenLdap: function () {
      this.isOpenLdapSelected = this.isOpenLdap;
    },
    isSamba: function () {
      this.isSambaSelected = this.isSamba;
    },
    step: function () {
      if (this.step == "node") {
        this.getClusterStatus();
        if (!this.isOpenLdapSelected) {
          this.listModules();
          this.listNodes();
        }
      }
    },
  },
  created() {
    this.newProviderId = this.providerId;
    this.isOpenLdapSelected = this.isOpenLdap;
    this.isSambaSelected = this.isSamba;
  },
  methods: {
    onSelectVolume(selectedVolume) {
      this.selectedVolume = selectedVolume;
    },
    async getClusterStatus() {
      this.loading.getClusterStatus = true;
      this.error.getClusterStatus = "";
      const taskAction = "get-cluster-status";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.getClusterStatusAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.getClusterStatusCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.getClusterStatus = this.getErrorMessage(err);
        this.loading.getClusterStatus = false;
        return;
      }
    },
    getClusterStatusAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.getClusterStatus = this.$t("error.generic_error");
      this.loading.getClusterStatus = false;
    },
    getClusterStatusCompleted(taskContext, taskResult) {
      this.clusterStatus = taskResult.output.nodes;
      for (const node of this.clusterStatus.filter((n) => n.online)) {
        this.listMountPoints(node.id);
      }
      this.loading.getClusterStatus = false;
    },
    async listNodes() {
      this.error.nodesList = "";
      this.loading.nodesList = true;
      const taskAction = "list-nodes";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.listNodesAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.listNodesCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.nodesList = this.getErrorMessage(err);
        this.loading.nodesList = false;
        return;
      }
    },
    listNodesAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.nodesList = this.$t("error.generic_error");
      this.loading.nodesList = false;
    },
    listNodesCompleted(taskContext, taskResult) {
      this.nodesList = taskResult.output.nodes;
      this.loading.nodesList = false;
    },
    async listMountPoints(nodeId) {
      const taskAction = "list-mountpoints";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.listMountPointsAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        (taskContext, taskResult) =>
          this.listMountPointsCompleted(taskContext, taskResult, nodeId)
      );
      const res = await to(
        this.createNodeTask(nodeId, {
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(
          `error creating task ${taskAction} for node ${nodeId}`,
          err
        );
        this.error.listMountPoints = this.getErrorMessage(err);
        return;
      }
    },
    listMountPointsAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.listMountPoints = this.$t("error.generic_error");
    },
    listMountPointsCompleted(taskContext, taskResult, nodeId) {
      const output = taskResult.output;
      this.$set(this.nodesAdditionalDiskInfo, nodeId, output);
      if (output.default_disk) {
        this.$set(this.nodesDefaultDiskInfo, nodeId, output.default_disk);
      }
    },
    nextStep() {
      switch (this.step) {
        case "location":
          if (this.isInternalSelected) {
            this.step = "instance";
          } else {
            this.step = "externalConfig";
          }
          break;
        case "instance":
          this.step = "node";
          break;
        case "externalConfig":
          this.addExternalDomain();
          break;
        case "node":
          if (
            this.isSambaSelected &&
            this.selectedNode &&
            this.nodesWithAdditionalStorage.includes(this.selectedNode.id)
          ) {
            this.step = "volumes";
          } else {
            this.step = "installingProvider";
            this.installProvider();
          }
          break;
        case "volumes":
          this.step = "installingProvider";
          this.installProvider(this.selectedVolume);
          break;
        case "internalConfig":
          if (this.isSambaSelected) {
            this.configureSambaModule();
          } else if (this.isOpenLdapSelected) {
            this.configureOpenLdapModule();
          }
          break;
      }
    },
    previousStep() {
      switch (this.step) {
        case "instance":
        case "externalConfig":
          this.step = "location";
          break;
        case "node":
          this.step = "instance";
          break;
        case "volumes":
          this.selectedVolume = {};
          this.step = "node";
          break;
      }
    },
    async installProvider(volumes) {
      this.error.addInternalProvider = "";
      const taskAction = "add-internal-provider";
      const eventId = this.getUuid();
      this.installProviderProgress = 0;
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.addInternalProviderAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.addInternalProviderCompleted
      );
      this.$root.$on(
        `${taskAction}-progress-${eventId}`,
        this.addInternalProviderProgress
      );
      const selectedNodeId = this.selectedNode
        ? parseInt(this.selectedNode.id)
        : 1;
      const providerImage = this.isOpenLdapSelected ? "openldap" : "samba";
      const data = {
        image: providerImage,
        node: selectedNodeId,
      };
      if (volumes?.path && this.sambaVolumes.length) {
        data.volumes = {};
        this.sambaVolumes.forEach((volume) => {
          data.volumes[volume] = volumes.path;
        });
      }
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data,
          extra: {
            title: this.$t("action." + taskAction),
            node: selectedNodeId,
            isNotificationHidden: true,
            isProgressNotified: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.addInternalProvider = this.getErrorMessage(err);
        return;
      }
    },
    addInternalProviderAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.$root.$off(
        `${taskContext.action}-progress-${taskContext.extra.eventId}`
      );
      this.$emit("hide");
    },
    addInternalProviderCompleted(taskContext, taskResult) {
      this.$root.$off(
        `${taskContext.action}-progress-${taskContext.extra.eventId}`
      );
      this.step = "internalConfig";
      this.newProviderId = taskResult.output.module_id;
      if (this.isSambaSelected) {
        this.getSambaDefaults();
      } else {
        this.getOpenLdapDefaults();
      }
      this.$emit("reloadDomains");
      this.$root.$emit("reloadAppDrawer");
    },
    addInternalProviderProgress(progress) {
      this.installProviderProgress = progress;
    },
    async getOpenLdapDefaults() {
      this.loading.openldap.getDefaults = true;
      this.error.openldap.getDefaults = "";
      const taskAction = "get-defaults";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.getOpenLdapDefaultsAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.getOpenLdapDefaultsCompleted
      );
      const res = await to(
        this.createModuleTaskForApp(this.newProviderId, {
          action: taskAction,
          data: {
            provision: "new-domain",
          },
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.openldap.getDefaults = this.getErrorMessage(err);
        return;
      }
    },
    getOpenLdapDefaultsAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.loading.openldap.getDefaults = false;
      this.$emit("hide");
    },
    getOpenLdapDefaultsCompleted(taskContext, taskResult) {
      this.loading.openldap.getDefaults = false;
      const defaults = taskResult.output;
      this.openldap.domain = defaults.domain;
      this.openldap.admuser = defaults.admuser;
      this.openldap.admpass = "";
      // focus on first field
      this.$nextTick(() => {
        this.focusElement("domain");
      });
    },
    async getSambaDefaults() {
      this.loading.samba.getDefaults = true;
      this.error.samba.getDefaults = "";
      const taskAction = "get-defaults";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.getSambaDefaultsAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.getSambaDefaultsCompleted
      );
      const res = await to(
        this.createModuleTaskForApp(this.newProviderId, {
          action: taskAction,
          data: {
            provision: "new-domain",
          },
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.samba.getDefaults = this.getErrorMessage(err);
        return;
      }
    },
    getSambaDefaultsAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.loading.samba.getDefaults = false;
      this.$emit("hide");
    },
    getSambaDefaultsCompleted(taskContext, taskResult) {
      this.loading.samba.getDefaults = false;
      const defaults = taskResult.output;
      this.samba.adminuser = defaults.adminuser;
      this.samba.hostname = defaults.hostname;
      this.samba.nbdomain = defaults.nbdomain;
      this.samba.realm = defaults.realm;
      this.samba.adminpass = "";
      this.samba.ipaddress = "";
      this.samba.enableFileServer = false;
      // ip address combo box
      let index = 0;
      for (const ipObject of defaults.ipaddress_list) {
        const option = {
          name: ipObject.ipaddress.replace(/\W/g, "_"),
          label: ipObject.ipaddress + " - " + ipObject.label,
          value: ipObject.ipaddress,
          iface: ipObject.label,
        };
        this.$set(this.samba.ipAddressOptions, index, option);
        index++;
      }
      this.$nextTick(() => {
        this.focusElement("realm");
      });
    },
    clearSambaErrors() {
      for (const key of Object.keys(this.error.samba)) {
        this.error.samba[key] = "";
      }
    },
    validateConfigureSambaModule() {
      this.clearSambaErrors();
      let isValidationOk = true;
      // samba realm
      if (!this.samba.realm) {
        this.error.samba.realm = "common.required";
        if (isValidationOk) {
          this.focusElement("realm");
          isValidationOk = false;
        }
      }
      if (!this.samba.nbdomain) {
        this.error.samba.nbdomain = "common.required";
        if (isValidationOk) {
          this.focusElement("nbdomain");
          isValidationOk = false;
        }
      }
      if (!this.samba.adminuser) {
        this.error.samba.adminuser = "common.required";
        if (isValidationOk) {
          this.focusElement("adminuser");
          isValidationOk = false;
        }
      }
      if (!this.samba.adminpass) {
        this.error.samba.adminpass = "common.required";
        if (isValidationOk) {
          this.samba.focusPasswordField = { element: "newPassword" };
          isValidationOk = false;
        }
      } else {
        if (
          !this.samba.passwordValidation.isLengthOk ||
          !this.samba.passwordValidation.isLowercaseOk ||
          !this.samba.passwordValidation.isUppercaseOk ||
          !this.samba.passwordValidation.isNumberOk ||
          !this.samba.passwordValidation.isSymbolOk
        ) {
          if (!this.error.samba.adminpass) {
            this.error.samba.adminpass = "password.password_not_secure";
          }
          if (isValidationOk) {
            this.samba.focusPasswordField = { element: "newPassword" };
            isValidationOk = false;
          }
        }
        if (!this.samba.passwordValidation.isEqualOk) {
          if (!this.error.samba.adminpass) {
            this.error.samba.adminpass = "password.passwords_do_not_match";
          }
          if (!this.error.samba.confirmPassword) {
            this.error.samba.confirmPassword =
              "password.passwords_do_not_match";
          }
          if (isValidationOk) {
            this.samba.focusPasswordField = { element: "confirmPassword" };
            isValidationOk = false;
          }
        }
      }
      if (!this.samba.hostname) {
        this.error.samba.hostname = "common.required";
        if (isValidationOk) {
          this.focusElement("hostname");
          isValidationOk = false;
        }
      }
      if (this.samba.enableFileServer && !this.samba.ipaddress) {
        this.error.samba.ipaddress = "common.required";
        if (isValidationOk) {
          isValidationOk = false;
        }
      }
      return isValidationOk;
    },
    async configureSambaModule() {
      const isValidationOk = this.validateConfigureSambaModule();
      if (!isValidationOk) {
        return;
      }
      this.loading.samba.configureModule = true;
      const taskAction = "configure-module";
      const eventId = this.getUuid();
      this.configureProviderProgress = 0;
      if (!this.samba.enableFileServer) {
        this.samba.ipaddress = this.vpnInterface.value;
      }
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.configureSambaModuleAborted
      );
      this.$root.$once(
        `${taskAction}-validation-failed-${eventId}`,
        this.configureSambaModuleValidationFailed
      );
      this.$root.$once(
        `${taskAction}-validation-ok-${eventId}`,
        this.configureSambaModuleValidationOk
      );
      this.$root.$on(
        `${taskAction}-progress-${eventId}`,
        this.configureSambaModuleProgress
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.configureSambaModuleCompleted
      );
      const res = await to(
        this.createModuleTaskForApp(this.newProviderId, {
          action: taskAction,
          data: {
            adminuser: this.samba.adminuser,
            adminpass: this.samba.adminpass,
            realm: this.samba.realm,
            ipaddress: this.samba.ipaddress,
            hostname: this.samba.hostname,
            nbdomain: this.samba.nbdomain,
            provision: "new-domain",
          },
          extra: {
            title: this.$t("samba.samba_configuration"),
            isNotificationHidden: true,
            isProgressNotified: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.samba.configureModule = this.getErrorMessage(err);
        this.loading.samba.configureModule = false;
        return;
      }
    },
    configureSambaModuleValidationOk() {
      this.step = "configuringProvider";
    },
    configureSambaModuleValidationFailed(validationErrors, taskContext) {
      this.loading.samba.configureModule = false;
      this.$root.$off(
        `${taskContext.action}-progress-${taskContext.extra.eventId}`
      );
      let focusAlreadySet = false;
      for (const validationError of validationErrors) {
        if (
          [
            "realm_dc_reachable_check_failed",
            "realm_dc_avail_check_failed",
          ].includes(validationError.error)
        ) {
          this.error.samba.cannotReachDc = true;
        } else {
          const param = validationError.parameter;
          this.error.samba[param] = "domains." + validationError.error;
          if (!focusAlreadySet) {
            this.focusElement(param);
            focusAlreadySet = true;
          }
        }
      }
    },
    configureSambaModuleProgress(progress) {
      this.configureProviderProgress = progress;
    },
    configureSambaModuleCompleted(taskContext) {
      this.loading.samba.configureModule = false;
      this.$root.$off(
        `${taskContext.action}-progress-${taskContext.extra.eventId}`
      );
      this.$emit("hide");
      this.$emit("reloadDomains");
      this.$root.$emit("reloadAppDrawer");
    },
    configureSambaModuleAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.loading.samba.configureModule = false;
      this.$root.$off(
        `${taskContext.action}-progress-${taskContext.extra.eventId}`
      );
      this.$emit("hide");
    },
    clearOpenLdapErrors() {
      for (const key of Object.keys(this.error.openldap)) {
        this.error.openldap[key] = "";
      }
    },
    validateConfigureOpenLdapModule() {
      this.clearOpenLdapErrors();
      let isValidationOk = true;
      // openldap domain
      if (!this.openldap.domain) {
        this.error.openldap.domain = "common.required";
        if (isValidationOk) {
          this.focusElement("domain");
          isValidationOk = false;
        }
      }
      if (!this.openldap.admuser) {
        this.error.openldap.admuser = "common.required";
        if (isValidationOk) {
          this.focusElement("admuser");
          isValidationOk = false;
        }
      }
      if (!this.openldap.admpass) {
        this.error.openldap.admpass = "common.required";
        if (isValidationOk) {
          this.openldap.focusPasswordField = { element: "newPassword" };
          isValidationOk = false;
        }
      } else {
        if (
          !this.openldap.passwordValidation.isLengthOk ||
          !this.openldap.passwordValidation.isLowercaseOk ||
          !this.openldap.passwordValidation.isUppercaseOk ||
          !this.openldap.passwordValidation.isNumberOk ||
          !this.openldap.passwordValidation.isSymbolOk
        ) {
          if (!this.error.openldap.admpass) {
            this.error.openldap.admpass = "password.password_not_secure";
          }
          if (isValidationOk) {
            this.openldap.focusPasswordField = { element: "newPassword" };
            isValidationOk = false;
          }
        }
        if (!this.openldap.passwordValidation.isEqualOk) {
          if (!this.error.openldap.admpass) {
            this.error.openldap.admpass = "password.passwords_do_not_match";
          }
          if (!this.error.openldap.confirmPassword) {
            this.error.openldap.confirmPassword =
              "password.passwords_do_not_match";
          }
          if (isValidationOk) {
            this.openldap.focusPasswordField = { element: "confirmPassword" };
            isValidationOk = false;
          }
        }
      }
      return isValidationOk;
    },
    async configureOpenLdapModule() {
      const isValidationOk = this.validateConfigureOpenLdapModule();
      if (!isValidationOk) {
        return;
      }
      this.loading.openldap.configureModule = true;
      const taskAction = "configure-module";
      const eventId = this.getUuid();
      this.configureProviderProgress = 0;
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.configureOpenLdapModuleAborted
      );
      this.$root.$once(
        `${taskAction}-validation-failed-${eventId}`,
        this.configureOpenLdapModuleValidationFailed
      );
      this.$root.$once(
        `${taskAction}-validation-ok-${eventId}`,
        this.configureOpenLdapModuleValidationOk
      );
      this.$root.$on(
        `${taskAction}-progress-${eventId}`,
        this.configureOpenLdapModuleProgress
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.configureOpenLdapModuleCompleted
      );
      const res = await to(
        this.createModuleTaskForApp(this.newProviderId, {
          action: taskAction,
          data: {
            domain: this.openldap.domain,
            admuser: this.openldap.admuser,
            admpass: this.openldap.admpass,
            provision: "new-domain",
          },
          extra: {
            title: this.$t("openldap.openldap_configuration"),
            isNotificationHidden: true,
            isProgressNotified: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.openldap.configureModule = this.getErrorMessage(err);
        this.loading.openldap.configureModule = false;
        return;
      }
    },
    configureOpenLdapModuleValidationOk() {
      this.step = "configuringProvider";
    },
    configureOpenLdapModuleValidationFailed(validationErrors, taskContext) {
      this.loading.openldap.configureModule = false;
      this.$root.$off(
        `${taskContext.action}-progress-${taskContext.extra.eventId}`
      );
      let focusAlreadySet = false;
      for (const validationError of validationErrors) {
        const param = validationError.parameter;
        this.error.openldap[param] = "domains." + validationError.error;
        if (!focusAlreadySet) {
          this.focusElement(param);
          focusAlreadySet = true;
        }
      }
    },
    configureOpenLdapModuleProgress(progress) {
      this.configureProviderProgress = progress;
    },
    configureOpenLdapModuleCompleted(taskContext) {
      this.loading.openldap.configureModule = false;
      this.$root.$off(
        `${taskContext.action}-progress-${taskContext.extra.eventId}`
      );
      this.$emit("hide");
      this.$emit("reloadDomains");
    },
    configureOpenLdapModuleAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.loading.openldap.configureModule = false;
      this.$root.$off(
        `${taskContext.action}-progress-${taskContext.extra.eventId}`
      );
      this.$emit("hide");
    },
    onNewSambaPasswordValidation(passwordValidation) {
      this.samba.passwordValidation = passwordValidation;
    },
    onNewOpenLdapPasswordValidation(passwordValidation) {
      this.openldap.passwordValidation = passwordValidation;
    },
    validateAddExternalDomain() {
      this.clearExternalDomainErrors();
      let isValidationOk = true;
      if (!this.external.domain) {
        this.error.external.domain = "common.required";
        if (isValidationOk) {
          this.focusElement("domain");
          isValidationOk = false;
        }
      }
      if (!this.external.host) {
        this.error.external.host = "common.required";
        if (isValidationOk) {
          this.focusElement("host");
          isValidationOk = false;
        }
      }
      if (!this.external.port) {
        this.error.external.port = "common.required";
        if (isValidationOk) {
          this.focusElement("port");
          isValidationOk = false;
        }
      }
      if (!this.external.bind_dn) {
        this.error.external.bind_dn = "common.required";
        if (isValidationOk) {
          this.focusElement("bind_dn");
          isValidationOk = false;
        }
      }
      if (!this.external.bind_password) {
        this.error.external.bind_password = "common.required";
        if (isValidationOk) {
          this.focusElement("bind_password");
          isValidationOk = false;
        }
      }
      return isValidationOk;
    },
    async addExternalDomain() {
      const isValidationOk = this.validateAddExternalDomain();
      if (!isValidationOk) {
        return;
      }
      this.loading.external.addExternalDomain = true;
      const taskAction = "add-external-domain";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.addExternalDomainAborted
      );
      this.$root.$once(
        `${taskAction}-validation-failed-${eventId}`,
        this.addExternalDomainValidationFailed
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.addExternalDomainCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {
            domain: this.external.domain,
            protocol: "ldap",
            host: this.external.host,
            port: parseInt(this.external.port),
            bind_dn: this.external.bind_dn,
            bind_password: this.external.bind_password,
            base_dn: this.external.base_dn,
            tls: this.external.tls,
            tls_verify: this.external.tls_verify,
          },
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.addExternalDomain = this.getErrorMessage(err);
        return;
      }
    },
    addExternalDomainValidationFailed(validationErrors) {
      this.loading.external.addExternalDomain = false;
      let focusAlreadySet = false;
      for (const validationError of validationErrors) {
        const param = validationError.parameter;
        this.error.external[param] = "domains." + validationError.error;
        if (!focusAlreadySet) {
          this.focusElement(param);
          focusAlreadySet = true;
        }
      }
    },
    addExternalDomainAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.loading.external.addExternalDomain = false;
      this.$emit("hide");
    },
    addExternalDomainCompleted() {
      this.loading.external.addExternalDomain = false;
      this.$emit("hide");
      this.$emit("reloadDomains");
    },
    clearExternalDomainErrors() {
      for (const key of Object.keys(this.error.external)) {
        this.error.external[key] = "";
      }
    },
    onSelectNode(selectedNode) {
      this.selectedNode = selectedNode;
    },
    async listModules() {
      this.loading.listModules = true;
      this.error.listModules = "";
      this.modules = [];
      this.selectedNode = null;
      const taskAction = "list-modules";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.listModulesAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.listModulesCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.listModules = this.getErrorMessage(err);
        this.loading.listModules = false;
        return;
      }
    },
    listModulesAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.listModules = this.$t("error.generic_error");
      this.loading.listModules = false;
    },
    listModulesCompleted(taskContext, taskResult) {
      this.loading.listModules = false;
      let modules = taskResult.output;
      this.modules = modules;
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
.row {
  margin-bottom: $spacing-03;
}
.label {
  padding-right: 0.5rem;
  font-weight: bold;
}
.bx--form {
  .bx--form-item,
  .cv-combo-box {
    margin-bottom: $spacing-06;
  }
}
.mg-bottom-5 {
  margin-bottom: 5rem !important;
}
</style>
⋮----
<style lang="scss">
@import "../../styles/carbon-utils";
.new-provider-password .new-password-container {
  margin-bottom: $spacing-06 !important;
}
</style>
</file>

<file path="core/ui/src/components/domains/CreateOrEditGroupModal.vue">
<template>
  <NsModal
    size="default"
    :visible="isShown"
    :primary-button-disabled="isPrimaryButtonDisabled"
    :isLoading="loading.addGroup || loading.alterGroup"
    @modal-hidden="onModalHidden"
    @primary-click="createOrEditGroup"
    class="no-pad-modal"
  >
    <template slot="title">{{
      isEditing
        ? $t("domain_users.edit_group")
        : $t("domain_users.create_group")
    }}</template>
    <template slot="content">
      <cv-form @submit.prevent="createOrEditGroup">
        <NsInlineNotification
          v-if="error.getDomainGroup"
          kind="error"
          :title="$t('action.get-domain-group')"
          :description="error.getDomainGroup"
          :showCloseButton="false"
        />
        <NsTextInput
          v-model.trim="name"
          :label="$t('domain_users.name')"
          :invalid-message="error.group"
          :disabled="isEditing || loading.addGroup || loading.alterGroup"
          data-modal-primary-focus
          ref="group"
        />
        <NsTextInput
          v-model.trim="description"
          :label="$t('domain_users.description')"
          :invalid-message="error.description"
          :disabled="loading.addGroup || loading.alterGroup"
          ref="description"
        />
        <NsMultiSelect
          v-model="selectedUsers"
          :options="allUsersForSelect"
          :title="$t('domain_users.users') + ' (' + $t('common.optional') + ')'"
          :label="selectUsersLabel"
          :filterable="!!allUsers.length"
          :auto-filter="true"
          :auto-highlight="true"
          :invalid-message="error.users"
          :disabled="
            !allUsers.length ||
            loading.getDomainGroup ||
            loading.addGroup ||
            loading.alterGroup
          "
          showSelectedItems
          :unselectAriaLabel="$t('common.unselect')"
          :clearSelectionAriaLabel="$t('common.clear_selection')"
          :clearFilterLabel="$t('common.clear_filter')"
          :selectedLabel="$t('common.selected_l')"
          :userInputLabel="$t('common.user_input_l')"
          class="mg-bottom-14"
          ref="users"
        />
        <NsInlineNotification
          v-if="error.addGroup"
          kind="error"
          :title="$t('action.add-group')"
          :description="error.addGroup"
          :showCloseButton="false"
        />
        <NsInlineNotification
          v-if="error.alterGroup"
          kind="error"
          :title="$t('action.alter-group')"
          :description="error.alterGroup"
          :showCloseButton="false"
        />
      </cv-form>
    </template>
    <template slot="secondary-button">{{ $t("common.cancel") }}</template>
    <template slot="primary-button">{{
      isEditing
        ? $t("domain_users.edit_group")
        : $t("domain_users.create_group")
    }}</template>
  </NsModal>
</template>
⋮----
<template slot="title">{{
      isEditing
        ? $t("domain_users.edit_group")
        : $t("domain_users.create_group")
    }}</template>
<template slot="content">
      <cv-form @submit.prevent="createOrEditGroup">
        <NsInlineNotification
          v-if="error.getDomainGroup"
          kind="error"
          :title="$t('action.get-domain-group')"
          :description="error.getDomainGroup"
          :showCloseButton="false"
        />
        <NsTextInput
          v-model.trim="name"
          :label="$t('domain_users.name')"
          :invalid-message="error.group"
          :disabled="isEditing || loading.addGroup || loading.alterGroup"
          data-modal-primary-focus
          ref="group"
        />
        <NsTextInput
          v-model.trim="description"
          :label="$t('domain_users.description')"
          :invalid-message="error.description"
          :disabled="loading.addGroup || loading.alterGroup"
          ref="description"
        />
        <NsMultiSelect
          v-model="selectedUsers"
          :options="allUsersForSelect"
          :title="$t('domain_users.users') + ' (' + $t('common.optional') + ')'"
          :label="selectUsersLabel"
          :filterable="!!allUsers.length"
          :auto-filter="true"
          :auto-highlight="true"
          :invalid-message="error.users"
          :disabled="
            !allUsers.length ||
            loading.getDomainGroup ||
            loading.addGroup ||
            loading.alterGroup
          "
          showSelectedItems
          :unselectAriaLabel="$t('common.unselect')"
          :clearSelectionAriaLabel="$t('common.clear_selection')"
          :clearFilterLabel="$t('common.clear_filter')"
          :selectedLabel="$t('common.selected_l')"
          :userInputLabel="$t('common.user_input_l')"
          class="mg-bottom-14"
          ref="users"
        />
        <NsInlineNotification
          v-if="error.addGroup"
          kind="error"
          :title="$t('action.add-group')"
          :description="error.addGroup"
          :showCloseButton="false"
        />
        <NsInlineNotification
          v-if="error.alterGroup"
          kind="error"
          :title="$t('action.alter-group')"
          :description="error.alterGroup"
          :showCloseButton="false"
        />
      </cv-form>
    </template>
<template slot="secondary-button">{{ $t("common.cancel") }}</template>
<template slot="primary-button">{{
      isEditing
        ? $t("domain_users.edit_group")
        : $t("domain_users.create_group")
    }}</template>
⋮----
<script>
import { UtilService, TaskService, IconService } from "@nethserver/ns8-ui-lib";
import to from "await-to-js";
export default {
  name: "CreateOrEditGroupModal",
  mixins: [UtilService, TaskService, IconService],
  props: {
    isShown: Boolean,
    isEditing: {
      type: Boolean,
      default: false,
    },
    domain: { type: Object },
    group: { type: [Object, null] },
    allUsers: { type: Array, required: true },
  },
  data() {
    return {
      name: "",
      description: "",
      selectedUsers: [],
      loading: {
        addGroup: false,
        alterGroup: false,
        getDomainGroup: false,
      },
      error: {
        addGroup: "",
        alterGroup: "",
        getDomainGroup: "",
        group: "",
        description: "",
        users: "",
      },
    };
  },
  computed: {
    allUsersForSelect() {
      return this.allUsers.map((user) => {
        const userLabel = user.display_name
          ? `${user.user} (${user.display_name})`
          : user.user;
        return {
          value: user.user,
          label: userLabel,
          name: user.user,
        };
      });
    },
    isPrimaryButtonDisabled() {
      return (
        this.loading.addGroup ||
        this.loading.alterGroup ||
        this.loading.getDomainGroup ||
        !!this.error.getDomainGroup
      );
    },
    mainProvider() {
      return this.domain.providers[0].id;
    },
    selectUsersLabel() {
      if (this.loading.getDomainGroup) {
        return this.$t("common.loading");
      } else if (this.allUsers.length) {
        return this.$t("domain_users.select_users");
      } else {
        return this.$t("domain_users.no_user");
      }
    },
  },
  watch: {
    isShown: function () {
      if (this.isShown) {
        this.clearErrors();
        if (this.isEditing) {
          this.name = this.group.group;
          this.description = this.group.description;
          this.selectedUsers = [];
          this.getDomainGroup();
        }
      } else {
        if (this.isEditing) {
          this.clearFields();
        }
      }
    },
  },
  methods: {
    createOrEditGroup() {
      if (this.isEditing) {
        this.alterGroup();
      } else {
        this.addGroup();
      }
    },
    validateAddGroup() {
      this.clearErrors();
      let isValidationOk = true;
      if (!this.name) {
        this.error.group = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("group");
          isValidationOk = false;
        }
      }
      return isValidationOk;
    },
    async addGroup() {
      if (!this.validateAddGroup()) {
        return;
      }
      this.loading.addGroup = true;
      this.error.addGroup = "";
      const taskAction = "add-group";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.addGroupAborted
      );
      this.$root.$once(
        `${taskAction}-validation-ok-${eventId}`,
        this.addGroupValidationOk
      );
      this.$root.$once(
        `${taskAction}-validation-failed-${eventId}`,
        this.addGroupValidationFailed
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.addGroupCompleted
      );
      const res = await to(
        this.createModuleTaskForApp(this.mainProvider, {
          action: taskAction,
          data: {
            group: this.name,
            description: this.description,
            users: this.selectedUsers,
          },
          extra: {
            title: this.$t("domain_users.create_group_group", {
              group: this.name,
            }),
            description: this.$t("common.processing"),
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.addGroup = this.getErrorMessage(err);
        this.loading.addGroup = false;
        return;
      }
    },
    addGroupAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.loading.addGroup = false;
      this.$emit("hide");
    },
    addGroupValidationOk() {
      this.loading.addGroup = false;
      this.$emit("hide");
    },
    addGroupValidationFailed(validationErrors) {
      this.loading.addGroup = false;
      let focusAlreadySet = false;
      for (const validationError of validationErrors) {
        const param = validationError.parameter;
        this.error[param] = this.$t("domain_users." + validationError.error);
        if (!focusAlreadySet) {
          this.focusElement(param);
          focusAlreadySet = true;
        }
      }
    },
    addGroupCompleted() {
      this.clearFields();
      this.loading.addGroup = false;
      this.$emit("reloadGroups");
    },
    async alterGroup() {
      this.loading.alterGroup = true;
      this.error.alterGroup = "";
      const taskAction = "alter-group";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.alterGroupAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.alterGroupCompleted
      );
      const res = await to(
        this.createModuleTaskForApp(this.mainProvider, {
          action: taskAction,
          data: {
            group: this.group.group,
            description: this.description,
            users: this.selectedUsers,
          },
          extra: {
            title: this.$t("domain_users.edit_group_group", {
              group: this.group.group,
            }),
            description: this.$t("common.processing"),
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.alterGroup = this.getErrorMessage(err);
        this.loading.alterGroup = false;
        return;
      }
      this.$emit("hide");
    },
    alterGroupAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.loading.alterGroup = false;
    },
    alterGroupCompleted() {
      this.loading.alterGroup = false;
      this.$emit("reloadGroups");
    },
    onModalHidden() {
      this.clearErrors();
      this.$emit("hide");
    },
    async getDomainGroup() {
      this.loading.getDomainGroup = true;
      this.error.getDomainGroup = "";
      const taskAction = "get-domain-group";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.getDomainGroupAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.getDomainGroupCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {
            domain: this.domain.name,
            group: this.group.group,
          },
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.getDomainGroup = this.getErrorMessage(err);
        return;
      }
    },
    getDomainGroupAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.loading.getDomainGroup = false;
      this.error.getDomainGroup = this.$t("error.generic_error");
    },
    getDomainGroupCompleted(taskContext, taskResult) {
      const users = taskResult.output.group.users;
      this.selectedUsers = users.map((u) => u.user);
      this.loading.getDomainGroup = false;
    },
    clearFields() {
      this.name = "";
      this.description = "";
      this.selectedUsers = [];
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
.mg-bottom-14 {
  margin-bottom: 14rem;
}
</style>
</file>

<file path="core/ui/src/components/domains/CreateOrEditUserModal.vue">
<template>
  <NsModal
    size="default"
    :visible="isShown"
    :primary-button-disabled="isPrimaryButtonDisabled"
    :isLoading="loading.addUser || loading.alterUser"
    @modal-hidden="onModalHidden"
    @primary-click="createOrEditUser"
    class="no-pad-modal"
  >
    <template slot="title">{{
      isEditing ? $t("domain_users.edit_user") : $t("domain_users.create_user")
    }}</template>
    <template slot="content">
      <cv-form @submit.prevent="createOrEditUser" autocomplete="off">
        <NsInlineNotification
          v-if="error.getDomainUser"
          kind="error"
          :title="$t('action.get-domain-user')"
          :description="error.getDomainUser"
          :showCloseButton="false"
        />
        <NsTextInput
          v-model.trim="username"
          :label="$t('domain_users.username')"
          :invalid-message="error.user"
          :disabled="isEditing || loading.addUser || loading.alterUser"
          :helper-text="$t('domain_users.username_helper_text')"
          :placeholder="$t('common.eg_value', { value: 'jane.doe' })"
          data-modal-primary-focus
          autocomplete="off"
          ref="user"
        />
        <NsTextInput
          v-model.trim="displayName"
          :label="$t('domain_users.display_name')"
          :invalid-message="error.display_name"
          :helper-text="$t('domain_users.display_name_helper_text')"
          :disabled="loading.addUser || loading.alterUser"
          :placeholder="$t('common.eg_value', { value: 'Jane Doe' })"
          autocomplete="off"
          ref="display_name"
        />
        <NsTextInput
          v-model.trim="mail"
          :label="
            $t('domain_users.mail') + ' (' + $t('common.optional') + ')'
          "
          :invalid-message="error.mail"
          :disabled="loading.addUser || loading.alterUser"
          autocomplete="off"
          :placeholder="
            $t('common.eg_value', { value: 'jane.doe@example.com' })
          "
          tooltipAlignment="start"
          tooltipDirection="bottom"
          ref="mail"
          type="email"
        >
          <template slot="tooltip">{{
            $t("domain_users.mail_tooltip")
          }}</template>
        </NsTextInput>
        <NsTextInput
          v-model.trim="phoneExtension"
          :label="
            $t('domain_users.phone_extension') + ' (' + $t('common.optional') + ')'
          "
          :invalid-message="error.phone_extension"
          :disabled="loading.addUser || loading.alterUser"
          autocomplete="off"
          :placeholder="$t('common.eg_value', { value: '123' })"
          tooltipAlignment="start"
          tooltipDirection="bottom"
          ref="phone_extension"
        >
          <template slot="tooltip">{{
            $t("domain_users.phone_extension_tooltip")
          }}</template>
        </NsTextInput>
        <NsMultiSelect
          v-model="selectedGroups"
          :options="allGroupsForSelect"
          :title="
            $t('domain_users.groups') + ' (' + $t('common.optional') + ')'
          "
          :label="selectGroupsLabel"
          :filterable="!!allGroups.length"
          :auto-filter="true"
          :auto-highlight="true"
          :invalid-message="error.groups"
          :disabled="
            !allGroups.length ||
            loading.getDomainUser ||
            loading.addUser ||
            loading.alterUser
          "
          showSelectedItems
          :unselectAriaLabel="$t('common.unselect')"
          :clearSelectionAriaLabel="$t('common.clear_selection')"
          :clearFilterLabel="$t('common.clear_filter')"
          :selectedLabel="$t('common.selected_l')"
          :userInputLabel="$t('common.user_input_l')"
          ref="groups"
        />
        <NsPasswordInput
          v-if="!isEditing"
          :newPasswordLabel="$t('password.password')"
          :confirmPasswordLabel="$t('domain_users.confirm_password')"
          v-model="newPassword"
          @passwordValidation="onPasswordValidation"
          :newPasswordInvalidMessage="$t(error.newPassword)"
          :confirmPasswordInvalidMessage="$t(error.confirmPassword)"
          :passwordHideLabel="$t('password.hide_password')"
          :passwordShowLabel="$t('password.show_password')"
          :lengthLabel="$t('password.long_enough')"
          :lowercaseLabel="$t('password.lowercase_letter')"
          :uppercaseLabel="$t('password.uppercase_letter')"
          :numberLabel="$t('password.number')"
          :symbolLabel="$t('password.symbol')"
          :equalLabel="$t('password.equal')"
          :focus="focusPasswordField"
          :clearConfirmPasswordCommand="clearConfirmPasswordCommand"
          :minLength="
            policy.strength.enforced
              ? parseInt(policy.strength.password_min_length, 10)
              : 0
          "
          :checkComplexity="
            policy.strength.enforced ? policy.strength.complexity_check : false
          "
          autocomplete="new-password"
        />
        <NsToggle
          v-if="!isEditing && isActiveDirectory"
          :label="$t('domain_users.change_password_at_next_login')"
          value="mustChangePassword"
          :form-item="true"
          v-model="mustChangePassword"
          :disabled="loading.addUser || loading.alterUser"
          tooltipAlignment="start"
          tooltipDirection="bottom"
          ref="mustChangePassword"
        >
          <template slot="tooltip">{{
            $t("domain_users.must_change_password_tooltip")
          }}</template>
          <template slot="text-left">{{ $t("common.disabled") }}</template>
          <template slot="text-right">{{ $t("common.enabled") }}</template>
        </NsToggle>
        <NsToggle
          v-if="policy.expiration.enforced"
          :label="$t('domain_users.no_password_expiration_policy')"
          value="noPasswordExpirationPolicy"
          :form-item="true"
          v-model="noPasswordExpirationPolicy"
          :disabled="loading.addUser || loading.alterUser"
          tooltipAlignment="start"
          tooltipDirection="bottom"
          ref="noPasswordExpirationPolicy"
        >
          <template slot="tooltip">{{
            $t("domain_users.no_password_expiration_policy_tooltip")
          }}</template>
          <template slot="text-left">{{ $t("common.disabled") }}</template>
          <template slot="text-right">{{ $t("common.enabled") }}</template>
        </NsToggle>
        <NsInlineNotification
          v-if="error.addUser"
          kind="error"
          :title="$t('action.add-user')"
          :description="error.addUser"
          :showCloseButton="false"
        />
        <NsInlineNotification
          v-if="error.alterUser"
          kind="error"
          :title="$t('action.alter-user')"
          :description="error.alterUser"
          :showCloseButton="false"
        />
        <NsInlineNotification
          v-if="error.listPasswordPolicy"
          kind="error"
          :title="$t('action.get-password-policy')"
          :description="error.listPasswordPolicy"
          :showCloseButton="false"
        />
      </cv-form>
    </template>
    <template slot="secondary-button">{{ $t("common.cancel") }}</template>
    <template slot="primary-button">{{
      isEditing ? $t("domain_users.edit_user") : $t("domain_users.create_user")
    }}</template>
  </NsModal>
</template>
⋮----
<template slot="title">{{
      isEditing ? $t("domain_users.edit_user") : $t("domain_users.create_user")
    }}</template>
<template slot="content">
      <cv-form @submit.prevent="createOrEditUser" autocomplete="off">
        <NsInlineNotification
          v-if="error.getDomainUser"
          kind="error"
          :title="$t('action.get-domain-user')"
          :description="error.getDomainUser"
          :showCloseButton="false"
        />
        <NsTextInput
          v-model.trim="username"
          :label="$t('domain_users.username')"
          :invalid-message="error.user"
          :disabled="isEditing || loading.addUser || loading.alterUser"
          :helper-text="$t('domain_users.username_helper_text')"
          :placeholder="$t('common.eg_value', { value: 'jane.doe' })"
          data-modal-primary-focus
          autocomplete="off"
          ref="user"
        />
        <NsTextInput
          v-model.trim="displayName"
          :label="$t('domain_users.display_name')"
          :invalid-message="error.display_name"
          :helper-text="$t('domain_users.display_name_helper_text')"
          :disabled="loading.addUser || loading.alterUser"
          :placeholder="$t('common.eg_value', { value: 'Jane Doe' })"
          autocomplete="off"
          ref="display_name"
        />
        <NsTextInput
          v-model.trim="mail"
          :label="
            $t('domain_users.mail') + ' (' + $t('common.optional') + ')'
          "
          :invalid-message="error.mail"
          :disabled="loading.addUser || loading.alterUser"
          autocomplete="off"
          :placeholder="
            $t('common.eg_value', { value: 'jane.doe@example.com' })
          "
          tooltipAlignment="start"
          tooltipDirection="bottom"
          ref="mail"
          type="email"
        >
          <template slot="tooltip">{{
            $t("domain_users.mail_tooltip")
          }}</template>
        </NsTextInput>
        <NsTextInput
          v-model.trim="phoneExtension"
          :label="
            $t('domain_users.phone_extension') + ' (' + $t('common.optional') + ')'
          "
          :invalid-message="error.phone_extension"
          :disabled="loading.addUser || loading.alterUser"
          autocomplete="off"
          :placeholder="$t('common.eg_value', { value: '123' })"
          tooltipAlignment="start"
          tooltipDirection="bottom"
          ref="phone_extension"
        >
          <template slot="tooltip">{{
            $t("domain_users.phone_extension_tooltip")
          }}</template>
        </NsTextInput>
        <NsMultiSelect
          v-model="selectedGroups"
          :options="allGroupsForSelect"
          :title="
            $t('domain_users.groups') + ' (' + $t('common.optional') + ')'
          "
          :label="selectGroupsLabel"
          :filterable="!!allGroups.length"
          :auto-filter="true"
          :auto-highlight="true"
          :invalid-message="error.groups"
          :disabled="
            !allGroups.length ||
            loading.getDomainUser ||
            loading.addUser ||
            loading.alterUser
          "
          showSelectedItems
          :unselectAriaLabel="$t('common.unselect')"
          :clearSelectionAriaLabel="$t('common.clear_selection')"
          :clearFilterLabel="$t('common.clear_filter')"
          :selectedLabel="$t('common.selected_l')"
          :userInputLabel="$t('common.user_input_l')"
          ref="groups"
        />
        <NsPasswordInput
          v-if="!isEditing"
          :newPasswordLabel="$t('password.password')"
          :confirmPasswordLabel="$t('domain_users.confirm_password')"
          v-model="newPassword"
          @passwordValidation="onPasswordValidation"
          :newPasswordInvalidMessage="$t(error.newPassword)"
          :confirmPasswordInvalidMessage="$t(error.confirmPassword)"
          :passwordHideLabel="$t('password.hide_password')"
          :passwordShowLabel="$t('password.show_password')"
          :lengthLabel="$t('password.long_enough')"
          :lowercaseLabel="$t('password.lowercase_letter')"
          :uppercaseLabel="$t('password.uppercase_letter')"
          :numberLabel="$t('password.number')"
          :symbolLabel="$t('password.symbol')"
          :equalLabel="$t('password.equal')"
          :focus="focusPasswordField"
          :clearConfirmPasswordCommand="clearConfirmPasswordCommand"
          :minLength="
            policy.strength.enforced
              ? parseInt(policy.strength.password_min_length, 10)
              : 0
          "
          :checkComplexity="
            policy.strength.enforced ? policy.strength.complexity_check : false
          "
          autocomplete="new-password"
        />
        <NsToggle
          v-if="!isEditing && isActiveDirectory"
          :label="$t('domain_users.change_password_at_next_login')"
          value="mustChangePassword"
          :form-item="true"
          v-model="mustChangePassword"
          :disabled="loading.addUser || loading.alterUser"
          tooltipAlignment="start"
          tooltipDirection="bottom"
          ref="mustChangePassword"
        >
          <template slot="tooltip">{{
            $t("domain_users.must_change_password_tooltip")
          }}</template>
          <template slot="text-left">{{ $t("common.disabled") }}</template>
          <template slot="text-right">{{ $t("common.enabled") }}</template>
        </NsToggle>
        <NsToggle
          v-if="policy.expiration.enforced"
          :label="$t('domain_users.no_password_expiration_policy')"
          value="noPasswordExpirationPolicy"
          :form-item="true"
          v-model="noPasswordExpirationPolicy"
          :disabled="loading.addUser || loading.alterUser"
          tooltipAlignment="start"
          tooltipDirection="bottom"
          ref="noPasswordExpirationPolicy"
        >
          <template slot="tooltip">{{
            $t("domain_users.no_password_expiration_policy_tooltip")
          }}</template>
          <template slot="text-left">{{ $t("common.disabled") }}</template>
          <template slot="text-right">{{ $t("common.enabled") }}</template>
        </NsToggle>
        <NsInlineNotification
          v-if="error.addUser"
          kind="error"
          :title="$t('action.add-user')"
          :description="error.addUser"
          :showCloseButton="false"
        />
        <NsInlineNotification
          v-if="error.alterUser"
          kind="error"
          :title="$t('action.alter-user')"
          :description="error.alterUser"
          :showCloseButton="false"
        />
        <NsInlineNotification
          v-if="error.listPasswordPolicy"
          kind="error"
          :title="$t('action.get-password-policy')"
          :description="error.listPasswordPolicy"
          :showCloseButton="false"
        />
      </cv-form>
    </template>
⋮----
<template slot="tooltip">{{
            $t("domain_users.mail_tooltip")
          }}</template>
⋮----
<template slot="tooltip">{{
            $t("domain_users.phone_extension_tooltip")
          }}</template>
⋮----
<template slot="tooltip">{{
            $t("domain_users.must_change_password_tooltip")
          }}</template>
<template slot="text-left">{{ $t("common.disabled") }}</template>
<template slot="text-right">{{ $t("common.enabled") }}</template>
⋮----
<template slot="tooltip">{{
            $t("domain_users.no_password_expiration_policy_tooltip")
          }}</template>
<template slot="text-left">{{ $t("common.disabled") }}</template>
<template slot="text-right">{{ $t("common.enabled") }}</template>
⋮----
<template slot="secondary-button">{{ $t("common.cancel") }}</template>
<template slot="primary-button">{{
      isEditing ? $t("domain_users.edit_user") : $t("domain_users.create_user")
    }}</template>
⋮----
<script>
import { UtilService, TaskService, IconService } from "@nethserver/ns8-ui-lib";
import to from "await-to-js";
export default {
  name: "CreateOrEditUserModal",
  mixins: [UtilService, TaskService, IconService],
  props: {
    isShown: Boolean,
    isEditing: {
      type: Boolean,
      default: false,
    },
    domain: { type: Object },
    user: { type: [Object, null] },
    allGroups: { type: Array, required: true },
  },
  data() {
    return {
      username: "",
      displayName: "",
      selectedGroups: [],
      newPassword: "",
      passwordValidation: null,
      focusPasswordField: { element: "" },
      clearConfirmPasswordCommand: 0,
      mail: "",
      phoneExtension: "",
      mustChangePassword: false,
      noPasswordExpirationPolicy: false,
      policy: {
        strength: {
          complexity_check: false,
          enforced: false,
          password_min_length: 8,
        },
        expiration: {
          enforced: false,
        },
      },
      loading: {
        addUser: false,
        alterUser: false,
        getDomainUser: false,
        listPasswordPolicy: false,
      },
      error: {
        addUser: "",
        alterUser: "",
        getDomainUser: "",
        user: "",
        display_name: "",
        newPassword: "",
        confirmPassword: "",
        groups: "",
        listPasswordPolicy: "",
        mail: "",
        phone_extension: "",
        mustChangePassword: "",
        noPasswordExpirationPolicy: "",
      },
    };
  },
  computed: {
    allGroupsForSelect() {
      return this.allGroups.map((group) => {
        return {
          value: group.group,
          label: group.group,
          name: group.group,
        };
      });
    },
    isPrimaryButtonDisabled() {
      return (
        this.loading.addUser ||
        this.loading.alterUser ||
        this.loading.getDomainUser ||
        this.loading.listPasswordPolicy ||
        !!this.error.getDomainUser
      );
    },
    mainProvider() {
      return this.domain.providers[0].id;
    },
    isActiveDirectory() {
      return this.domain && this.domain.schema === "ad";
    },
    selectGroupsLabel() {
      if (this.loading.getDomainUser) {
        return this.$t("common.loading");
      } else if (this.allGroups.length) {
        return this.$t("domain_users.select_groups");
      } else {
        return this.$t("domain_users.no_group");
      }
    },
    passwordExpirationPolicyEnabled() {
      return (
        this.user &&
        this.user.password_expiration &&
        this.user.password_expiration.toString() === "-1"
      );
    },
  },
  watch: {
    isShown: function () {
      if (this.isShown) {
        this.clearErrors();
        this.listPasswordPolicy();
        if (!this.isEditing) {
          this.newPassword = "";
          this.clearConfirmPasswordCommand++;
          this.mail = "";
          this.phoneExtension = "";
          this.mustChangePassword = false;
          this.noPasswordExpirationPolicy = false;
        } else {
          // edit user
          this.username = this.user.user;
          this.displayName = this.user.display_name;
          this.selectedGroups = [];
          this.getDomainUser();
          this.mail = this.user.mail || "";
          this.phoneExtension = this.user.phone_extension || "";
          this.noPasswordExpirationPolicy =
            this.passwordExpirationPolicyEnabled;
        }
      } else {
        // hiding modal
        if (this.isEditing) {
          this.clearFields();
        }
      }
    },
  },
  methods: {
    async listPasswordPolicy() {
      this.loading.listPasswordPolicy = true;
      this.error.listPasswordPolicy = "";
      const taskAction = "get-password-policy";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.listPasswordPolicyCompleted
      );
      const res = await to(
        this.createModuleTaskForApp(this.mainProvider, {
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.listPasswordPolicy = this.getErrorMessage(err);
        return;
      }
    },
    listPasswordPolicyCompleted(taskContext, taskResult) {
      const config = taskResult.output;
      this.policy.expiration.enforced = config.expiration.enforced;
      this.policy.strength.enforced = config.strength.enforced;
      this.policy.strength.complexity_check = config.strength.complexity_check;
      this.policy.strength.password_min_length =
        config.strength.password_min_length.toString();
      this.loading.listPasswordPolicy = false;
    },
    createOrEditUser() {
      if (this.isEditing) {
        this.alterUser();
      } else {
        this.addUser();
      }
    },
    validateAddUser() {
      this.clearErrors();
      let isValidationOk = true;
      if (!this.username) {
        this.error.user = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("user");
          isValidationOk = false;
        }
      }
      if (!this.displayName) {
        this.error.display_name = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("display_name");
          isValidationOk = false;
        }
      }
      if (!this.newPassword) {
        this.error.newPassword = this.$t("common.required");
        if (isValidationOk) {
          this.focusPasswordField = { element: "newPassword" };
          isValidationOk = false;
        }
      } else {
        if (this.currentPassword === this.newPassword) {
          if (!this.error.newPassword) {
            this.error.newPassword = this.$t(
              "password.old_new_passwords_must_be_different"
            );
          }
          if (isValidationOk) {
            this.focusPasswordField = { element: "newPassword" };
            isValidationOk = false;
          }
        }
        if (
          !this.passwordValidation.isLengthOk ||
          !this.passwordValidation.isLowercaseOk ||
          !this.passwordValidation.isUppercaseOk ||
          !this.passwordValidation.isNumberOk ||
          !this.passwordValidation.isSymbolOk
        ) {
          if (!this.error.newPassword) {
            this.error.newPassword = this.$t("password.password_not_secure");
          }
          if (isValidationOk) {
            this.focusPasswordField = { element: "newPassword" };
            isValidationOk = false;
          }
        }
        if (!this.passwordValidation.isEqualOk) {
          if (!this.error.newPassword) {
            this.error.newPassword = this.$t("password.passwords_do_not_match");
          }
          if (!this.error.confirmPassword) {
            this.error.confirmPassword = this.$t(
              "password.passwords_do_not_match"
            );
          }
          if (isValidationOk) {
            this.focusPasswordField = { element: "confirmPassword" };
            isValidationOk = false;
          }
        }
      }
      return isValidationOk;
    },
    async addUser() {
      if (!this.validateAddUser()) {
        return;
      }
      this.loading.addUser = true;
      this.error.addUser = "";
      const taskAction = "add-user";
      const eventId = this.getUuid();
      this.$root.$once(`${taskAction}-aborted-${eventId}`, this.addUserAborted);
      this.$root.$once(
        `${taskAction}-validation-ok-${eventId}`,
        this.addUserValidationOk
      );
      this.$root.$once(
        `${taskAction}-validation-failed-${eventId}`,
        this.addUserValidationFailed
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.addUserCompleted
      );
      const res = await to(
        this.createModuleTaskForApp(this.mainProvider, {
          action: taskAction,
          data: {
            user: this.username,
            display_name: this.displayName,
            password: this.newPassword,
            locked: false,
            groups: this.selectedGroups,
            mail: this.mail ? this.mail : "",
            phone_extension: this.phoneExtension ? this.phoneExtension : "",
            must_change_password: this.mustChangePassword,
            no_password_expiration: this.noPasswordExpirationPolicy,
          },
          extra: {
            title: this.$t("domain_users.create_user_user", {
              user: this.username,
            }),
            description: this.$t("common.processing"),
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.addUser = this.getErrorMessage(err);
        this.loading.addUser = false;
        return;
      }
    },
    addUserAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.loading.addUser = false;
      this.$emit("hide");
    },
    addUserValidationOk() {
      this.loading.addUser = false;
      this.$emit("hide");
    },
    addUserValidationFailed(validationErrors) {
      this.loading.addUser = false;
      let focusAlreadySet = false;
      for (const validationError of validationErrors) {
        const param = validationError.parameter;
        this.error[param] = this.$t("domain_users." + validationError.error, {
          tok: validationError.value,
        });
        if (!focusAlreadySet) {
          this.focusElement(param);
          focusAlreadySet = true;
        }
      }
    },
    addUserCompleted() {
      this.clearFields();
      this.loading.addUser = false;
      this.$emit("reloadUsers");
    },
    async alterUser() {
      this.loading.alterUser = true;
      this.error.alterUser = "";
      const taskAction = "alter-user";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.alterUserAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.alterUserCompleted
      );
      this.$root.$once(
        `${taskAction}-validation-ok-${eventId}`,
        this.alterUserValidationOk
      );
      this.$root.$once(
        `${taskAction}-validation-failed-${eventId}`,
        this.alterUserValidationFailed
      );
      const res = await to(
        this.createModuleTaskForApp(this.mainProvider, {
          action: taskAction,
          data: {
            user: this.user.user,
            display_name: this.displayName,
            groups: this.selectedGroups,
            mail: this.mail ? this.mail : "",
            phone_extension: this.phoneExtension ? this.phoneExtension : "",
            no_password_expiration: this.noPasswordExpirationPolicy,
          },
          extra: {
            title: this.$t("domain_users.edit_user_user", {
              user: this.user.user,
            }),
            description: this.$t("common.processing"),
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.alterUser = this.getErrorMessage(err);
        this.loading.alterUser = false;
        return;
      }
    },
    alterUserAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.loading.alterUser = false;
    },
    alterUserCompleted() {
      this.loading.alterUser = false;
      this.$emit("reloadUsers");
    },
    alterUserValidationOk() {
      this.loading.alterUser = false;
      this.$emit("hide");
    },
    alterUserValidationFailed(validationErrors) {
      this.loading.alterUser = false;
      let focusAlreadySet = false;
      for (const validationError of validationErrors) {
        const param = validationError.parameter;
        this.error[param] = this.$t("domain_users." + validationError.error, {
          tok: validationError.value,
        });
        if (!focusAlreadySet) {
          this.focusElement(param);
          focusAlreadySet = true;
        }
      }
    },
    onModalHidden() {
      this.clearErrors();
      this.$emit("hide");
    },
    onPasswordValidation(passwordValidation) {
      this.passwordValidation = passwordValidation;
    },
    async getDomainUser() {
      this.loading.getDomainUser = true;
      this.error.getDomainUser = "";
      const taskAction = "get-domain-user";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.getDomainUserAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.getDomainUserCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {
            domain: this.domain.name,
            user: this.user.user,
          },
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.getDomainUser = this.getErrorMessage(err);
        return;
      }
    },
    getDomainUserAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.getDomainUser = this.$t("error.generic_error");
      this.loading.getDomainUser = false;
    },
    getDomainUserCompleted(taskContext, taskResult) {
      const groups = taskResult.output.user.groups;
      this.selectedGroups = groups.map((g) => g.group);
      this.loading.getDomainUser = false;
    },
    clearFields() {
      this.username = "";
      this.displayName = "";
      this.selectedGroups = [];
      // clear password fields
      this.newPassword = "";
      this.clearConfirmPasswordCommand++;
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
.mg-bottom-14 {
  margin-bottom: 14rem;
}
</style>
</file>

<file path="core/ui/src/components/domains/DeleteSambaProviderModal.vue">
<template>
  <NsModal
    kind="danger"
    size="default"
    :visible="isShown"
    :isLoading="loading.removeInternalProvider"
    @modal-hidden="onModalHidden"
    @primary-click="removeInternalProvider"
  >
    <template slot="title">{{
      $t("domain_configuration.delete_provider")
    }}</template>
    <template slot="content">
      <NsInlineNotification
        kind="warning"
        :title="$t('common.please_read_carefully')"
        :showCloseButton="false"
      />
      <div>
        {{
          $t("domain_configuration.delete_provider_confirm", {
            name: provider.id,
          })
        }}
      </div>
      <cv-form @submit.prevent="removeInternalProvider" class="mg-top-2">
        <NsTextInput
          :label="$t('samba.adminuser')"
          v-model.trim="adminuser"
          :helper-text="$t('samba.enter_samba_admin_username')"
          :invalid-message="$t(error.adminuser)"
          :disabled="loading.removeInternalProvider"
          ref="adminuser"
        >
        </NsTextInput>
        <NsTextInput
          :label="$t('samba.adminpass')"
          type="password"
          v-model="adminpass"
          :helper-text="$t('samba.enter_samba_admin_password')"
          :invalid-message="$t(error.adminpass)"
          :disabled="loading.removeInternalProvider"
          :password-hide-label="$t('password.hide_password')"
          :password-show-label="$t('password.show_password')"
          ref="adminpass"
          name="adminpass"
        ></NsTextInput>
      </cv-form>
      <NsInlineNotification
        v-if="error.removeInternalProvider"
        kind="error"
        :title="$t('action.remove-internal-provider')"
        :description="error.removeInternalProvider"
        :showCloseButton="false"
      />
    </template>
    <template slot="secondary-button">{{ $t("common.cancel") }}</template>
    <template slot="primary-button">{{
      $t("common.understood_delete")
    }}</template>
  </NsModal>
</template>
⋮----
<template slot="title">{{
      $t("domain_configuration.delete_provider")
    }}</template>
<template slot="content">
      <NsInlineNotification
        kind="warning"
        :title="$t('common.please_read_carefully')"
        :showCloseButton="false"
      />
      <div>
        {{
          $t("domain_configuration.delete_provider_confirm", {
            name: provider.id,
          })
        }}
      </div>
      <cv-form @submit.prevent="removeInternalProvider" class="mg-top-2">
        <NsTextInput
          :label="$t('samba.adminuser')"
          v-model.trim="adminuser"
          :helper-text="$t('samba.enter_samba_admin_username')"
          :invalid-message="$t(error.adminuser)"
          :disabled="loading.removeInternalProvider"
          ref="adminuser"
        >
        </NsTextInput>
        <NsTextInput
          :label="$t('samba.adminpass')"
          type="password"
          v-model="adminpass"
          :helper-text="$t('samba.enter_samba_admin_password')"
          :invalid-message="$t(error.adminpass)"
          :disabled="loading.removeInternalProvider"
          :password-hide-label="$t('password.hide_password')"
          :password-show-label="$t('password.show_password')"
          ref="adminpass"
          name="adminpass"
        ></NsTextInput>
      </cv-form>
      <NsInlineNotification
        v-if="error.removeInternalProvider"
        kind="error"
        :title="$t('action.remove-internal-provider')"
        :description="error.removeInternalProvider"
        :showCloseButton="false"
      />
    </template>
⋮----
{{
          $t("domain_configuration.delete_provider_confirm", {
            name: provider.id,
          })
        }}
⋮----
<template slot="secondary-button">{{ $t("common.cancel") }}</template>
<template slot="primary-button">{{
      $t("common.understood_delete")
    }}</template>
⋮----
<script>
import { TaskService, UtilService } from "@nethserver/ns8-ui-lib";
import to from "await-to-js";
export default {
  name: "DeleteSambaProviderModal",
  mixins: [TaskService, UtilService],
  props: {
    isShown: {
      type: Boolean,
      default: true,
    },
    provider: { type: Object },
  },
  data() {
    return {
      adminuser: "",
      adminpass: "",
      loading: {
        removeInternalProvider: false,
      },
      error: {
        adminuser: "",
        adminpass: "",
        removeInternalProvider: "",
      },
    };
  },
  watch: {
    isShown: function () {
      if (this.isShown) {
        this.adminuser = "";
        this.adminpass = "";
        setTimeout(() => {
          this.focusElement("adminuser");
        }, 300);
      }
    },
  },
  methods: {
    onModalHidden() {
      this.$emit("hide");
    },
    validateRemoveInternalProvider() {
      this.clearErrors();
      let isValidationOk = true;
      if (!this.adminuser) {
        this.error.adminuser = "common.required";
        if (isValidationOk) {
          this.focusElement("adminuser");
          isValidationOk = false;
        }
      }
      if (!this.adminpass) {
        this.error.adminpass = "common.required";
        if (isValidationOk) {
          this.focusElement("adminpass");
          isValidationOk = false;
        }
      }
      return isValidationOk;
    },
    async removeInternalProvider() {
      const isValidationOk = this.validateRemoveInternalProvider();
      if (!isValidationOk) {
        return;
      }
      this.loading.removeInternalProvider = true;
      this.error.removeInternalProvider = "";
      const taskAction = "remove-internal-provider";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.removeInternalProviderAborted
      );
      this.$root.$once(
        `${taskAction}-validation-failed-${eventId}`,
        this.removeInternalProviderValidationFailed
      );
      this.$root.$once(
        `${taskAction}-validation-ok-${eventId}`,
        this.removeInternalProviderValidationOk
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.removeInternalProviderCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {
            module_id: this.provider.id,
            adminuser: this.adminuser,
            adminpass: this.adminpass,
          },
          extra: {
            title: this.$t("action." + taskAction),
            description: this.$t("common.processing"),
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.removeInternalProvider = this.getErrorMessage(err);
        this.loading.removeInternalProvider = false;
        return;
      }
    },
    removeInternalProviderAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.loading.removeInternalProvider = false;
      this.$emit("hide");
    },
    removeInternalProviderValidationOk() {
      this.$emit("hide");
    },
    removeInternalProviderValidationFailed(validationErrors) {
      this.loading.removeInternalProvider = false;
      let focusAlreadySet = false;
      for (const validationError of validationErrors) {
        const param = validationError.parameter;
        this.error.samba[param] = "domains." + validationError.error;
        if (!focusAlreadySet) {
          this.focusElement(param);
          focusAlreadySet = true;
        }
      }
    },
    removeInternalProviderCompleted() {
      this.loading.removeInternalProvider = false;
      this.$emit("hide");
      this.$emit("reloadDomains");
      this.$root.$emit("reloadAppDrawer");
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
.mg-top-2 {
  margin-top: 2rem;
}
</style>
</file>

<file path="core/ui/src/components/domains/DomainGroups.vue">
<template>
  <div>
    <cv-tile light>
      <cv-grid fullWidth class="no-padding">
        <cv-row v-if="groups.length" class="toolbar">
          <cv-column>
            <NsButton
              v-if="domain && domain.location === 'internal'"
              kind="primary"
              :icon="Add20"
              @click="showCreateGroupModal"
              >{{ $t("domain_users.create_group") }}
            </NsButton>
            <cv-tooltip
              v-else
              alignment="center"
              direction="right"
              :tip="
                $t('domain_users.cannot_make_changes_to_an_external_domain')
              "
            >
              <NsButton kind="primary" :icon="Add20" disabled
                >{{ $t("domain_users.create_group") }}
              </NsButton>
            </cv-tooltip>
          </cv-column>
        </cv-row>
        <cv-row>
          <cv-column>
            <NsDataTable
              :allRows="groups"
              :columns="i18nTableColumns"
              :rawColumns="tableColumns"
              :sortable="true"
              :pageSizes="[10, 25, 50, 100]"
              :overflow-menu="domain && domain.location == 'internal'"
              isSearchable
              :searchPlaceholder="$t('domain_users.search_group')"
              :searchClearLabel="$t('common.clear_search')"
              :noSearchResultsLabel="$t('common.no_search_results')"
              :noSearchResultsDescription="
                $t('common.no_search_results_description')
              "
              :isLoading="!domain || loading.listDomainGroups"
              :skeletonRows="5"
              :isErrorShown="!!error.listDomainGroups"
              :errorTitle="$t('action.list-domain-groups')"
              :errorDescription="error.listDomainGroups"
              :itemsPerPageLabel="$t('pagination.items_per_page')"
              :rangeOfTotalItemsLabel="$t('pagination.range_of_total_items')"
              :ofTotalPagesLabel="$t('pagination.of_total_pages')"
              :backwardText="$t('pagination.previous_page')"
              :forwardText="$t('pagination.next_page')"
              :pageNumberLabel="$t('pagination.page_number')"
              @updatePage="tablePage = $event"
            >
              <template slot="empty-state">
                <NsEmptyState :title="$t('domain_users.no_group')">
                  <template #pictogram>
                    <GroupPictogram />
                  </template>
                  <template #description>
                    <div>{{ $t("domain_users.no_group_description") }}</div>
                    <NsButton
                      kind="primary"
                      :icon="Add20"
                      @click="showCreateGroupModal"
                      class="empty-state-button"
                      >{{ $t("domain_users.create_group") }}
                    </NsButton>
                  </template>
                </NsEmptyState>
              </template>
              <template slot="data">
                <cv-data-table-row
                  v-for="(row, rowIndex) in tablePage"
                  :key="`${rowIndex}`"
                  :value="`${rowIndex}`"
                >
                  <cv-data-table-cell>{{ row.group }}</cv-data-table-cell>
                  <cv-data-table-cell>{{ row.description }}</cv-data-table-cell>
                  <cv-data-table-cell
                    v-if="domain && domain.location == 'internal'"
                    class="table-overflow-menu-cell"
                  >
                    <cv-overflow-menu
                      flip-menu
                      class="table-overflow-menu"
                      :data-test-id="row.group + '-menu'"
                    >
                      <cv-overflow-menu-item
                        @click="showEditGroupModal(row)"
                        :data-test-id="row.group + '-edit'"
                      >
                        <NsMenuItem :icon="Edit20" :label="$t('common.edit')" />
                      </cv-overflow-menu-item>
                      <NsMenuDivider />
                      <cv-overflow-menu-item
                        danger
                        :disabled="row.group.toLowerCase() === 'domain admins'"
                        @click="showDeleteGroupModal(row)"
                        :data-test-id="row.group + '-delete'"
                      >
                        <NsMenuItem
                          :icon="TrashCan20"
                          :label="$t('common.delete')"
                        />
                      </cv-overflow-menu-item>
                    </cv-overflow-menu>
                  </cv-data-table-cell>
                </cv-data-table-row>
              </template>
            </NsDataTable>
          </cv-column>
        </cv-row>
      </cv-grid>
    </cv-tile>
    <CreateOrEditGroupModal
      :isShown="isShownCreateOrEditGroupModal"
      :isEditing="isEditingGroup"
      :domain="domain"
      :group="currentGroup"
      :allUsers="users"
      @hide="hideCreateOrEditGroupModal"
      @reloadGroups="onReloadGroups"
    />
    <NsDangerDeleteModal
      :isShown="isShownDeleteGroupModal"
      :name="groupToDelete ? groupToDelete.group : ''"
      :title="
        $t('domain_users.delete_group_group', {
          group: groupToDelete ? groupToDelete.group : '',
        })
      "
      :warning="$t('common.please_read_carefully')"
      :description="
        $t('domain_users.delete_group_description', {
          name: groupToDelete ? groupToDelete.group : '',
        })
      "
      :typeToConfirm="
        $t('common.type_to_confirm', {
          name: groupToDelete ? groupToDelete.group : '',
        })
      "
      :isErrorShown="!!error.removeGroup"
      :errorTitle="$t('action.remove-group')"
      :errorDescription="error.removeGroup"
      @hide="hideDeleteGroupModal"
      @confirmDelete="removeGroup"
      data-test-id="delete-group-modal"
    />
  </div>
</template>
⋮----
>{{ $t("domain_users.create_group") }}
⋮----
>{{ $t("domain_users.create_group") }}
⋮----
<template slot="empty-state">
                <NsEmptyState :title="$t('domain_users.no_group')">
                  <template #pictogram>
                    <GroupPictogram />
                  </template>
                  <template #description>
                    <div>{{ $t("domain_users.no_group_description") }}</div>
                    <NsButton
                      kind="primary"
                      :icon="Add20"
                      @click="showCreateGroupModal"
                      class="empty-state-button"
                      >{{ $t("domain_users.create_group") }}
                    </NsButton>
                  </template>
                </NsEmptyState>
              </template>
⋮----
<template #pictogram>
                    <GroupPictogram />
                  </template>
<template #description>
                    <div>{{ $t("domain_users.no_group_description") }}</div>
                    <NsButton
                      kind="primary"
                      :icon="Add20"
                      @click="showCreateGroupModal"
                      class="empty-state-button"
                      >{{ $t("domain_users.create_group") }}
                    </NsButton>
                  </template>
⋮----
<div>{{ $t("domain_users.no_group_description") }}</div>
⋮----
>{{ $t("domain_users.create_group") }}
⋮----
<template slot="data">
                <cv-data-table-row
                  v-for="(row, rowIndex) in tablePage"
                  :key="`${rowIndex}`"
                  :value="`${rowIndex}`"
                >
                  <cv-data-table-cell>{{ row.group }}</cv-data-table-cell>
                  <cv-data-table-cell>{{ row.description }}</cv-data-table-cell>
                  <cv-data-table-cell
                    v-if="domain && domain.location == 'internal'"
                    class="table-overflow-menu-cell"
                  >
                    <cv-overflow-menu
                      flip-menu
                      class="table-overflow-menu"
                      :data-test-id="row.group + '-menu'"
                    >
                      <cv-overflow-menu-item
                        @click="showEditGroupModal(row)"
                        :data-test-id="row.group + '-edit'"
                      >
                        <NsMenuItem :icon="Edit20" :label="$t('common.edit')" />
                      </cv-overflow-menu-item>
                      <NsMenuDivider />
                      <cv-overflow-menu-item
                        danger
                        :disabled="row.group.toLowerCase() === 'domain admins'"
                        @click="showDeleteGroupModal(row)"
                        :data-test-id="row.group + '-delete'"
                      >
                        <NsMenuItem
                          :icon="TrashCan20"
                          :label="$t('common.delete')"
                        />
                      </cv-overflow-menu-item>
                    </cv-overflow-menu>
                  </cv-data-table-cell>
                </cv-data-table-row>
              </template>
⋮----
<cv-data-table-cell>{{ row.group }}</cv-data-table-cell>
<cv-data-table-cell>{{ row.description }}</cv-data-table-cell>
⋮----
<script>
import { UtilService, IconService, TaskService } from "@nethserver/ns8-ui-lib";
import CreateOrEditGroupModal from "@/components/domains/CreateOrEditGroupModal";
import to from "await-to-js";
export default {
  name: "DomainGroups",
  components: { CreateOrEditGroupModal },
  mixins: [UtilService, IconService, TaskService],
  props: {
    domain: { type: Object },
    users: { type: Array, required: true },
  },
  data() {
    return {
      isShownCreateOrEditGroupModal: false,
      isShownDeleteGroupModal: false,
      isEditingGroup: false,
      currentGroup: null,
      groupToDelete: null,
      tableColumns: ["group", "description"],
      tablePage: [],
      loading: {
        listDomainGroups: false,
        removeGroup: false,
      },
      error: {
        listDomainGroups: "",
        removeGroup: "",
      },
      groups: [],
    };
  },
  computed: {
    i18nTableColumns() {
      return this.tableColumns.map((column) => {
        return this.$t("domain_users." + column);
      });
    },
    mainProvider() {
      return this.domain.providers[0].id;
    },
  },
  watch: {
    domain: function () {
      if (this.domain) {
        this.listDomainGroups();
      }
    },
  },
  created() {
    if (this.domain) {
      this.listDomainGroups();
    }
  },
  methods: {
    showCreateGroupModal() {
      this.isEditingGroup = false;
      this.isShownCreateOrEditGroupModal = true;
    },
    showEditGroupModal(group) {
      this.currentGroup = group;
      this.isEditingGroup = true;
      this.isShownCreateOrEditGroupModal = true;
    },
    hideCreateOrEditGroupModal() {
      this.isShownCreateOrEditGroupModal = false;
    },
    showDeleteGroupModal(group) {
      this.groupToDelete = group;
      this.error.removeGroup = "";
      this.isShownDeleteGroupModal = true;
    },
    hideDeleteGroupModal() {
      this.isShownDeleteGroupModal = false;
    },
    async removeGroup() {
      this.loading.removeGroup = true;
      this.error.removeGroup = "";
      const taskAction = "remove-group";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.removeGroupAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.removeGroupCompleted
      );
      const res = await to(
        this.createModuleTaskForApp(this.mainProvider, {
          action: taskAction,
          data: {
            group: this.groupToDelete.group,
          },
          extra: {
            title: this.$t("domain_users.delete_group_group", {
              group: this.groupToDelete.group,
            }),
            description: this.$t("common.processing"),
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.removeGroup = this.getErrorMessage(err);
        this.loading.removeGroup = false;
        return;
      }
      this.hideDeleteGroupModal();
    },
    removeGroupAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.removeGroup = this.$t("error.generic_error");
      this.loading.removeGroup = false;
    },
    removeGroupCompleted() {
      this.loading.removeGroup = false;
      this.listDomainGroups();
    },
    async listDomainGroups() {
      this.loading.listDomainGroups = true;
      this.error.listDomainGroups = "";
      const taskAction = "list-domain-groups";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.listDomainGroupsAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.listDomainGroupsCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {
            domain: this.domain.name,
          },
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.listDomainGroups = this.getErrorMessage(err);
        return;
      }
    },
    listDomainGroupsAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.listDomainGroups = this.$t("error.generic_error");
      this.loading.listDomainGroups = false;
    },
    listDomainGroupsCompleted(taskContext, taskResult) {
      this.groups = taskResult.output.groups;
      this.$emit("groupsLoaded", this.groups);
      this.loading.listDomainGroups = false;
    },
    onReloadGroups() {
      this.listDomainGroups();
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
</style>
</file>

<file path="core/ui/src/components/domains/DomainUsers.vue">
<template>
  <div>
    <cv-tile light>
      <cv-grid fullWidth class="no-padding">
        <cv-row v-if="users.length" class="toolbar">
          <cv-column>
            <NsButton
              v-if="domain && domain.location === 'internal'"
              kind="primary"
              :icon="Add20"
              @click="showCreateUserModal"
              >{{ $t("domain_users.create_user") }}
            </NsButton>
            <cv-tooltip
              v-else
              alignment="center"
              direction="right"
              :tip="
                $t('domain_users.cannot_make_changes_to_an_external_domain')
              "
            >
              <NsButton kind="primary" :icon="Add20" disabled
                >{{ $t("domain_users.create_user") }}
              </NsButton>
            </cv-tooltip>
          </cv-column>
        </cv-row>
        <cv-row>
          <cv-column>
            <NsDataTable
              :allRows="users"
              :columns="i18nTableColumns"
              :rawColumns="tableColumns"
              :sortable="true"
              :pageSizes="[10, 25, 50, 100]"
              :overflow-menu="domain && domain.location == 'internal'"
              isSearchable
              :searchPlaceholder="$t('domain_users.search_user')"
              :searchClearLabel="$t('common.clear_search')"
              :noSearchResultsLabel="$t('common.no_search_results')"
              :noSearchResultsDescription="
                $t('common.no_search_results_description')
              "
              :isLoading="
                !domain || loading.listDomainUsers || loading.listPasswordPolicy
              "
              :skeletonRows="5"
              :isErrorShown="!!error.listDomainUsers"
              :errorTitle="$t('action.list-domain-users')"
              :errorDescription="error.listDomainUsers"
              :itemsPerPageLabel="$t('pagination.items_per_page')"
              :rangeOfTotalItemsLabel="$t('pagination.range_of_total_items')"
              :ofTotalPagesLabel="$t('pagination.of_total_pages')"
              :backwardText="$t('pagination.previous_page')"
              :forwardText="$t('pagination.next_page')"
              :pageNumberLabel="$t('pagination.page_number')"
              @updatePage="tablePage = $event"
            >
              <template slot="empty-state">
                <NsEmptyState :title="$t('domain_users.no_user')">
                  <template #pictogram>
                    <UserPictogram />
                  </template>
                  <template #description>
                    <div>{{ $t("domain_users.no_user_description") }}</div>
                    <NsButton
                      kind="primary"
                      :icon="Add20"
                      @click="showCreateUserModal"
                      class="empty-state-button"
                      >{{ $t("domain_users.create_user") }}
                    </NsButton>
                  </template>
                </NsEmptyState>
              </template>
              <template slot="data">
                <cv-data-table-row
                  v-for="(row, rowIndex) in tablePage"
                  :key="`${rowIndex}`"
                  :value="`${rowIndex}`"
                >
                  <cv-data-table-cell>
                    <span>{{ row.user }}</span>
                  </cv-data-table-cell>
                  <cv-data-table-cell>
                    {{ row.display_name }}
                  </cv-data-table-cell>
                  <cv-data-table-cell>
                    {{ row.mail ? row.mail : "-" }}
                  </cv-data-table-cell>
                  <cv-data-table-cell>
                    {{ row.phone_extension ? row.phone_extension : "-" }}
                  </cv-data-table-cell>
                  <cv-data-table-cell>
                    <cv-tag
                      v-if="row.locked"
                      kind="high-contrast"
                      :label="$t('common.disabled')"
                      size="sm"
                      class="disabled-tag"
                    ></cv-tag>
                    <cv-tag
                      v-if="row.must_change && isActiveDirectory"
                      kind="high-contrast"
                      :label="$t('domains.must_change_password_on_next_login')"
                      size="sm"
                    ></cv-tag>
                    <cv-tag
                      v-if="row.expired && row.password_expiration > 0"
                      kind="high-contrast"
                      :label="$t('domains.password_expired')"
                      size="sm"
                    ></cv-tag>
                    <cv-tag
                      v-if="
                        row.password_expiration === -1 &&
                        policy.expiration.enforced
                      "
                      kind="gray"
                      :label="$t('domains.password_does_not_expire')"
                      size="sm"
                    ></cv-tag>
                  </cv-data-table-cell>
                  <cv-data-table-cell
                    v-if="domain && domain.location == 'internal'"
                    class="table-overflow-menu-cell"
                  >
                    <cv-overflow-menu
                      flip-menu
                      class="table-overflow-menu"
                      :data-test-id="row.user + '-menu'"
                    >
                      <cv-overflow-menu-item
                        @click="showEditUserModal(row)"
                        :data-test-id="row.user + '-edit'"
                      >
                        <NsMenuItem :icon="Edit20" :label="$t('common.edit')" />
                      </cv-overflow-menu-item>
                      <cv-overflow-menu-item
                        @click="showChangeUserPasswordModal(row)"
                      >
                        <NsMenuItem
                          :icon="Password20"
                          :label="$t('domain_users.change_password')"
                        />
                      </cv-overflow-menu-item>
                      <cv-overflow-menu-item
                        :disabled="loading.alterUser"
                        @click="enableOrDisableUser(row)"
                      >
                        <NsMenuItem
                          :icon="Power20"
                          :label="
                            row.locked
                              ? $t('domain_users.enable')
                              : $t('domain_users.disable')
                          "
                        />
                      </cv-overflow-menu-item>
                      <NsMenuDivider />
                      <cv-overflow-menu-item
                        danger
                        :disabled="row.user.toLowerCase() === 'administrator'"
                        @click="showDeleteUserModal(row)"
                        :data-test-id="row.user + '-delete'"
                      >
                        <NsMenuItem
                          :icon="TrashCan20"
                          :label="$t('common.delete')"
                        />
                      </cv-overflow-menu-item>
                    </cv-overflow-menu>
                  </cv-data-table-cell>
                </cv-data-table-row>
              </template>
            </NsDataTable>
          </cv-column>
        </cv-row>
      </cv-grid>
    </cv-tile>
    <CreateOrEditUserModal
      :isShown="isShownCreateOrEditUserModal"
      :isEditing="isEditingUser"
      :domain="domain"
      :user="currentUser"
      :allGroups="groups"
      @hide="hideCreateOrEditUserModal"
      @reloadUsers="onReloadUsers"
    />
    <ChangeUserPasswordModal
      :isShown="isShownChangeUserPasswordModal"
      :domain="domain"
      :user="currentUser"
      @hide="hideChangeUserPasswordModal"
      @reloadUsers="onReloadUsers"
    />
    <NsDangerDeleteModal
      :isShown="isShownDeleteUserModal"
      :name="userToDelete ? userToDelete.user : ''"
      :title="
        $t('domain_users.delete_user_user', {
          user: userToDelete ? userToDelete.user : '',
        })
      "
      :warning="$t('common.please_read_carefully')"
      :description="
        $t('domain_users.delete_user_description', {
          name: userToDeleteLabel,
        })
      "
      :typeToConfirm="
        $t('common.type_to_confirm', {
          name: userToDelete ? userToDelete.user : '',
        })
      "
      :isErrorShown="!!error.removeUser"
      :errorTitle="$t('action.remove-user')"
      :errorDescription="error.removeUser"
      @hide="hideDeleteUserModal"
      @confirmDelete="removeUser"
      data-test-id="delete-user-modal"
    />
  </div>
</template>
⋮----
>{{ $t("domain_users.create_user") }}
⋮----
>{{ $t("domain_users.create_user") }}
⋮----
<template slot="empty-state">
                <NsEmptyState :title="$t('domain_users.no_user')">
                  <template #pictogram>
                    <UserPictogram />
                  </template>
                  <template #description>
                    <div>{{ $t("domain_users.no_user_description") }}</div>
                    <NsButton
                      kind="primary"
                      :icon="Add20"
                      @click="showCreateUserModal"
                      class="empty-state-button"
                      >{{ $t("domain_users.create_user") }}
                    </NsButton>
                  </template>
                </NsEmptyState>
              </template>
⋮----
<template #pictogram>
                    <UserPictogram />
                  </template>
<template #description>
                    <div>{{ $t("domain_users.no_user_description") }}</div>
                    <NsButton
                      kind="primary"
                      :icon="Add20"
                      @click="showCreateUserModal"
                      class="empty-state-button"
                      >{{ $t("domain_users.create_user") }}
                    </NsButton>
                  </template>
⋮----
<div>{{ $t("domain_users.no_user_description") }}</div>
⋮----
>{{ $t("domain_users.create_user") }}
⋮----
<template slot="data">
                <cv-data-table-row
                  v-for="(row, rowIndex) in tablePage"
                  :key="`${rowIndex}`"
                  :value="`${rowIndex}`"
                >
                  <cv-data-table-cell>
                    <span>{{ row.user }}</span>
                  </cv-data-table-cell>
                  <cv-data-table-cell>
                    {{ row.display_name }}
                  </cv-data-table-cell>
                  <cv-data-table-cell>
                    {{ row.mail ? row.mail : "-" }}
                  </cv-data-table-cell>
                  <cv-data-table-cell>
                    {{ row.phone_extension ? row.phone_extension : "-" }}
                  </cv-data-table-cell>
                  <cv-data-table-cell>
                    <cv-tag
                      v-if="row.locked"
                      kind="high-contrast"
                      :label="$t('common.disabled')"
                      size="sm"
                      class="disabled-tag"
                    ></cv-tag>
                    <cv-tag
                      v-if="row.must_change && isActiveDirectory"
                      kind="high-contrast"
                      :label="$t('domains.must_change_password_on_next_login')"
                      size="sm"
                    ></cv-tag>
                    <cv-tag
                      v-if="row.expired && row.password_expiration > 0"
                      kind="high-contrast"
                      :label="$t('domains.password_expired')"
                      size="sm"
                    ></cv-tag>
                    <cv-tag
                      v-if="
                        row.password_expiration === -1 &&
                        policy.expiration.enforced
                      "
                      kind="gray"
                      :label="$t('domains.password_does_not_expire')"
                      size="sm"
                    ></cv-tag>
                  </cv-data-table-cell>
                  <cv-data-table-cell
                    v-if="domain && domain.location == 'internal'"
                    class="table-overflow-menu-cell"
                  >
                    <cv-overflow-menu
                      flip-menu
                      class="table-overflow-menu"
                      :data-test-id="row.user + '-menu'"
                    >
                      <cv-overflow-menu-item
                        @click="showEditUserModal(row)"
                        :data-test-id="row.user + '-edit'"
                      >
                        <NsMenuItem :icon="Edit20" :label="$t('common.edit')" />
                      </cv-overflow-menu-item>
                      <cv-overflow-menu-item
                        @click="showChangeUserPasswordModal(row)"
                      >
                        <NsMenuItem
                          :icon="Password20"
                          :label="$t('domain_users.change_password')"
                        />
                      </cv-overflow-menu-item>
                      <cv-overflow-menu-item
                        :disabled="loading.alterUser"
                        @click="enableOrDisableUser(row)"
                      >
                        <NsMenuItem
                          :icon="Power20"
                          :label="
                            row.locked
                              ? $t('domain_users.enable')
                              : $t('domain_users.disable')
                          "
                        />
                      </cv-overflow-menu-item>
                      <NsMenuDivider />
                      <cv-overflow-menu-item
                        danger
                        :disabled="row.user.toLowerCase() === 'administrator'"
                        @click="showDeleteUserModal(row)"
                        :data-test-id="row.user + '-delete'"
                      >
                        <NsMenuItem
                          :icon="TrashCan20"
                          :label="$t('common.delete')"
                        />
                      </cv-overflow-menu-item>
                    </cv-overflow-menu>
                  </cv-data-table-cell>
                </cv-data-table-row>
              </template>
⋮----
<span>{{ row.user }}</span>
⋮----
{{ row.display_name }}
⋮----
{{ row.mail ? row.mail : "-" }}
⋮----
{{ row.phone_extension ? row.phone_extension : "-" }}
⋮----
<script>
import { UtilService, IconService, TaskService } from "@nethserver/ns8-ui-lib";
import CreateOrEditUserModal from "@/components/domains/CreateOrEditUserModal";
import ChangeUserPasswordModal from "@/components/domains/ChangeUserPasswordModal";
import to from "await-to-js";
export default {
  name: "DomainUsers",
  components: { CreateOrEditUserModal, ChangeUserPasswordModal },
  mixins: [UtilService, IconService, TaskService],
  props: {
    domain: { type: Object },
    groups: { type: Array, required: true },
  },
  data() {
    return {
      isShownCreateOrEditUserModal: false,
      isShownChangeUserPasswordModal: false,
      isShownDeleteUserModal: false,
      isEditingUser: false,
      currentUser: null,
      userToDelete: null,
      tableColumns: [
        "user",
        "display_name",
        "mail",
        "phone_extension",
        "attributes",
      ],
      tablePage: [],
      loading: {
        listDomainUsers: false,
        removeUser: false,
        alterUser: false,
        listPasswordPolicy: false,
      },
      error: {
        listDomainUsers: "",
        removeUser: "",
        alterUser: "",
        listPasswordPolicy: "",
      },
      users: [],
      policy: { expiration: { enforced: false } },
    };
  },
  computed: {
    i18nTableColumns() {
      return this.tableColumns.map((column) => {
        return this.$t("domain_users." + column);
      });
    },
    userToDeleteLabel() {
      if (!this.userToDelete) {
        return "";
      }
      return this.userToDelete.display_name
        ? `${this.userToDelete.user} (${this.userToDelete.display_name})`
        : this.userToDelete.user;
    },
    mainProvider() {
      return this.domain.providers[0].id;
    },
    isActiveDirectory() {
      return this.domain && this.domain.schema === "ad";
    },
  },
  watch: {
    domain: function () {
      if (this.domain) {
        this.listDomainUsers();
      }
    },
  },
  created() {
    if (this.domain) {
      this.listDomainUsers();
    }
  },
  mounted() {
    this.$root.$on("password-policy-updated", this.listDomainUsers);
  },
  beforeDestroy() {
    this.$root.$off("password-policy-updated", this.listDomainUsers);
  },
  methods: {
    async listPasswordPolicy() {
      this.loading.listPasswordPolicy = true;
      this.error.listPasswordPolicy = "";
      const taskAction = "get-password-policy";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.listPasswordPolicyCompleted
      );
      const res = await to(
        this.createModuleTaskForApp(this.mainProvider, {
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.listPasswordPolicy = this.getErrorMessage(err);
        return;
      }
    },
    listPasswordPolicyCompleted(taskContext, taskResult) {
      const config = taskResult.output;
      this.policy.expiration.enforced = config.expiration.enforced;
      this.loading.listPasswordPolicy = false;
    },
    showCreateUserModal() {
      this.isEditingUser = false;
      this.isShownCreateOrEditUserModal = true;
    },
    showEditUserModal(user) {
      this.currentUser = user;
      this.isEditingUser = true;
      this.isShownCreateOrEditUserModal = true;
    },
    hideCreateOrEditUserModal() {
      this.isShownCreateOrEditUserModal = false;
    },
    showChangeUserPasswordModal(user) {
      this.currentUser = user;
      this.isShownChangeUserPasswordModal = true;
    },
    hideChangeUserPasswordModal() {
      this.isShownChangeUserPasswordModal = false;
    },
    showDeleteUserModal(user) {
      this.userToDelete = user;
      this.error.removeUser = "";
      this.isShownDeleteUserModal = true;
    },
    hideDeleteUserModal() {
      this.isShownDeleteUserModal = false;
    },
    async enableOrDisableUser(user) {
      this.loading.alterUser = true;
      this.error.alterUser = "";
      const taskAction = "alter-user";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.alterUserAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.alterUserCompleted
      );
      const notificationTitle = user.locked
        ? this.$t("domain_users.enable_user_user", { user: user.user })
        : this.$t("domain_users.disable_user_user", { user: user.user });
      const res = await to(
        this.createModuleTaskForApp(this.mainProvider, {
          action: taskAction,
          data: {
            user: user.user,
            locked: !user.locked,
          },
          extra: {
            title: notificationTitle,
            description: this.$t("common.processing"),
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.alterUser = this.getErrorMessage(err);
        this.loading.alterUser = false;
        return;
      }
    },
    alterUserAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.alterUser = this.$t("error.generic_error");
      this.loading.alterUser = false;
    },
    alterUserCompleted() {
      this.loading.alterUser = false;
      this.listDomainUsers();
    },
    async removeUser() {
      this.loading.removeUser = true;
      this.error.removeUser = "";
      const taskAction = "remove-user";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.removeUserAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.removeUserCompleted
      );
      const res = await to(
        this.createModuleTaskForApp(this.mainProvider, {
          action: taskAction,
          data: {
            user: this.userToDelete.user,
          },
          extra: {
            title: this.$t("domain_users.delete_user_user", {
              user: this.userToDelete.user,
            }),
            description: this.$t("common.processing"),
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.removeUser = this.getErrorMessage(err);
        this.loading.removeUser = false;
        return;
      }
      this.hideDeleteUserModal();
    },
    removeUserAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.removeUser = this.$t("error.generic_error");
      this.loading.removeUser = false;
    },
    removeUserCompleted() {
      this.loading.removeUser = false;
      this.listDomainUsers();
    },
    async listDomainUsers() {
      this.loading.listDomainUsers = true;
      this.error.listDomainUsers = "";
      const taskAction = "list-domain-users";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.listDomainUsersAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.listDomainUsersCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {
            domain: this.domain.name,
          },
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.listDomainUsers = this.getErrorMessage(err);
        return;
      }
    },
    listDomainUsersAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.listDomainUsers = this.$t("error.generic_error");
      this.loading.listDomainUsers = false;
    },
    listDomainUsersCompleted(taskContext, taskResult) {
      this.users = taskResult.output.users;
      this.$emit("usersLoaded", this.users);
      this.loading.listDomainUsers = false;
      if (this.domain && this.domain.location === "internal") {
        this.listPasswordPolicy();
      }
    },
    onReloadUsers() {
      this.listDomainUsers();
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
</style>
</file>

<file path="core/ui/src/components/domains/DomainUsersAndGroups.vue">
<template>
  <div>
    <cv-grid fullWidth>
      <cv-row>
        <cv-column>
          <cv-breadcrumb
            aria-label="breadcrumb"
            :no-trailing-slash="true"
            class="breadcrumb"
          >
            <cv-breadcrumb-item>
              <cv-link to="/domains">{{ $t("domains.title") }}</cv-link>
            </cv-breadcrumb-item>
            <cv-breadcrumb-item>
              <span> {{ domainName }}</span>
            </cv-breadcrumb-item>
          </cv-breadcrumb>
        </cv-column>
      </cv-row>
      <cv-row>
        <cv-column>
          <div class="flex flex-wrap items-center justify-between">
            <div class="subpage-title">
              <h3>
                {{ domainName }}
              </h3>
            </div>
            <div class="page-toolbar flex gap-4">
              <NsButton
                v-if="domain && domain.location == 'internal'"
                kind="secondary"
                size="field"
                :icon="Export20"
                @click="exportUsersData()"
                class="subpage-toolbar-item"
                >{{ $t("domain_users.export_data") }}
              </NsButton>
              <NsButton
                v-if="domain && domain.location == 'internal'"
                kind="secondary"
                size="field"
                :icon="Upload20"
                @click="showImportUsersModal()"
                class="subpage-toolbar-item"
                >{{ $t("domain_users.import_data") }}
              </NsButton>
            </div>
          </div>
        </cv-column>
      </cv-row>
      <cv-row v-if="error.listUserDomains">
        <cv-column>
          <NsInlineNotification
            kind="error"
            :title="$t('action.list-user-domains')"
            :description="error.listUserDomains"
            :showCloseButton="false"
          />
        </cv-column>
      </cv-row>
      <cv-row>
        <cv-column>
          <NsInlineNotification
            kind="warning"
            :title="$t('common.use_landscape_mode')"
            :description="$t('common.use_landscape_mode_description')"
            class="landscape-warning"
          />
        </cv-column>
      </cv-row>
      <cv-row>
        <cv-column>
          <NsTabs
            :container="false"
            :aria-label="$t('common.tab_navigation')"
            :noDefaultToFirst="true"
            @tab-selected="tabSelected"
          >
            <cv-tab
              id="tab-1"
              :label="$t('domain_users.users')"
              :selected="q.view === 'users'"
            >
              <DomainUsers
                :domain="domain"
                :groups="groups"
                @usersLoaded="onUsersLoaded"
              />
            </cv-tab>
            <cv-tab
              id="tab-2"
              :label="$t('domain_users.groups')"
              :selected="q.view === 'groups'"
            >
              <DomainGroups
                :domain="domain"
                :users="users"
                @groupsLoaded="onGroupsLoaded"
              />
            </cv-tab>
            <cv-tab
              id="tab-3"
              :label="$t('domain_configuration.configuration')"
              :selected="q.view === 'configuration'"
            >
              <DomainConfiguration :domainName="domainName" />
            </cv-tab>
          </NsTabs>
        </cv-column>
      </cv-row>
    </cv-grid>
    <ImportUsersModal
      :isShown="isShownImportUsersModal"
      :domain="importData.domain"
      @hide="hideImportUsersModal"
      @reloadDomains="listUserDomains"
    />
  </div>
</template>
⋮----
<cv-link to="/domains">{{ $t("domains.title") }}</cv-link>
⋮----
<span> {{ domainName }}</span>
⋮----
{{ domainName }}
⋮----
>{{ $t("domain_users.export_data") }}
⋮----
>{{ $t("domain_users.import_data") }}
⋮----
<script>
import {
  QueryParamService,
  UtilService,
  TaskService,
  IconService,
  PageTitleService,
} from "@nethserver/ns8-ui-lib";
import DomainUsers from "@/components/domains/DomainUsers";
import DomainGroups from "@/components/domains/DomainGroups";
import DomainConfiguration from "@/views/DomainConfiguration.vue";
import Upload20 from "@carbon/icons-vue/es/upload/20";
import Export20 from "@carbon/icons-vue/es/export/20";
import ImportUsersModal from "@/components/domains/ImportUsersModal";
import to from "await-to-js";
import Papa from "papaparse";
export default {
  name: "DomainUsersAndGroups",
  components: {
    DomainUsers,
    DomainGroups,
    DomainConfiguration,
    ImportUsersModal,
  },
  mixins: [
    TaskService,
    UtilService,
    QueryParamService,
    IconService,
    PageTitleService,
  ],
  pageTitle() {
    return this.$t("domain_users.title");
  },
  data() {
    return {
      q: {
        view: "",
      },
      domainName: "",
      domain: null,
      users: [],
      groups: [],
      loading: {
        listUserDomains: false,
      },
      error: {
        listUserDomains: "",
        downloadCsvFile: "",
      },
      Upload20,
      Export20,
      importData: {
        domain: {},
      },
      isShownImportUsersModal: false,
      downloadCsv: {
        name: "",
      },
    };
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.watchQueryData(vm);
      vm.queryParamsToDataForCore(vm, to.query);
    });
  },
  beforeRouteUpdate(to, from, next) {
    this.queryParamsToDataForCore(this, to.query);
    next();
  },
  created() {
    this.domainName = this.$route.params.domainName;
    this.listUserDomains();
  },
  mounted() {
    if (!this.q.view) {
      this.q.view = "users";
    }
  },
  methods: {
    async exportUsersData() {
      this.loading.downloadCsvFile = true;
      this.error.downloadCsvFile = "";
      this.downloadCsv.name = this.domain.name;
      const taskAction = "export-users";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.exportUsersDataAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.exportUsersDataCompleted
      );
      this.$root.$once(
        `${taskAction}-validation-ok-${eventId}`,
        this.exportUsersDataValidationOk
      );
      this.$root.$once(
        `${taskAction}-validation-failed-${eventId}`,
        this.exportUsersDataValidationFailed
      );
      const res = await to(
        this.createModuleTaskForApp(this.domain.providers[0].id, {
          action: taskAction,
          data: {},
          extra: {
            title: this.$t("action.export-users"),
            description: this.$t("common.processing"),
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.downloadCsvFile = this.getErrorMessage(err);
        this.loading.downloadCsvFile = false;
        return;
      }
    },
    exportUsersDataAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.loading.downloadCsvFile = false;
    },
    exportUsersDataCompleted(taskContext, taskResult) {
      const jsonData = taskResult.output.records;
      let records = jsonData;
      if (typeof jsonData === "string") {
        try {
          records = JSON.parse(jsonData);
        } catch (err) {
          console.error("Error parsing JSON records:", err);
          this.loading.downloadCsvFile = false;
          return;
        }
      }
      let columnOrder = [
        "user",
        "display_name",
        "password",
        "mail",
        "groups",
        "locked",
        "must_change_password",
        "no_password_expiration",
      ];
      const csvRecords = records.map((record) => {
        const orderedRecord = {};
        columnOrder.forEach((column) => {
          if (column === "groups" && Array.isArray(record[column])) {
            orderedRecord[column] = record[column].join("|");
          } else {
            orderedRecord[column] = record[column];
          }
        });
        return orderedRecord;
      });
      const csv = Papa.unparse(csvRecords, {
        header: true,
        columns: columnOrder,
      });
      const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });
      const link = document.createElement("a");
      const url = URL.createObjectURL(blob);
      const now = new Date();
      const pad = (n) => String(n).padStart(2, "0");
      const timestamp = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(
        now.getDate()
      )}${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
      link.setAttribute("href", url);
      link.setAttribute(
        "download",
        `${this.downloadCsv.name}_${timestamp}.csv`
      );
      link.style.visibility = "hidden";
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);
      this.loading.downloadCsvFile = false;
    },
    exportUsersDataValidationOk() {
      this.loading.downloadCsvFile = false;
    },
    exportUsersDataValidationFailed(validationErrors) {
      this.loading.downloadCsvFile = false;
      let focusAlreadySet = false;
      for (const validationError of validationErrors) {
        const param = validationError.parameter;
        this.error[param] = this.$t("domain_users." + validationError.error, {
          tok: validationError.value,
        });
        if (!focusAlreadySet) {
          this.focusElement(param);
          focusAlreadySet = true;
        }
      }
    },
    showImportUsersModal() {
      this.importData.domain = this.domain;
      this.isShownImportUsersModal = true;
    },
    hideImportUsersModal() {
      this.isShownImportUsersModal = false;
    },
    async listUserDomains() {
      this.loading.listUserDomains = true;
      this.error.listUserDomains = "";
      const taskAction = "list-user-domains";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.listUserDomainsAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.listUserDomainsCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.listUserDomains = this.getErrorMessage(err);
        return;
      }
    },
    listUserDomainsAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.listUserDomains = this.$t("error.generic_error");
      this.loading.listUserDomains = false;
    },
    listUserDomainsCompleted(taskContext, taskResult) {
      let domains = taskResult.output.domains;
      this.domain = domains.find((domain) => domain.name === this.domainName);
      this.loading.listUserDomains = false;
    },
    onUsersLoaded(users) {
      this.users = users;
      setTimeout(() => {
        this.checkAndScrollToAnchor();
      }, 100);
    },
    onGroupsLoaded(groups) {
      this.groups = groups;
    },
    tabSelected(tabNum) {
      if (tabNum == 0) {
        this.q.view = "users";
      } else if (tabNum == 1) {
        this.q.view = "groups";
      } else if (tabNum == 2) {
        this.q.view = "configuration";
      }
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
</style>
</file>

<file path="core/ui/src/components/domains/EditExternalDomainModal.vue">
<template>
  <NsModal
    size="default"
    :visible="isShown"
    @modal-hidden="$emit('hide')"
    @primary-click="alterExternalDomain"
  >
    <template slot="title">{{ $t("domains.edit_external_domain") }}</template>
    <template slot="content">
      <cv-form @submit.prevent="alterExternalDomain">
        <NsTextInput
          :label="$t('domains.bind_dn')"
          v-model.trim="bind_dn"
          :invalid-message="$t(error.bind_dn)"
          :disabled="loading.alterExternalDomain"
          ref="bind_dn"
        >
        </NsTextInput>
        <NsTextInput
          type="password"
          :label="$t('domains.bind_password')"
          v-model="bind_password"
          :invalid-message="$t(error.bind_password)"
          :password-hide-label="$t('password.hide_password')"
          :password-show-label="$t('password.show_password')"
          :disabled="loading.alterExternalDomain"
          ref="bind_password"
        >
        </NsTextInput>
        <NsToggle
          :label="$t('domains.tls')"
          value="tlsValue"
          :form-item="true"
          v-model="tls"
          :disabled="loading.alterExternalDomain"
          ref="tls"
        >
          <template slot="text-left">{{ $t("common.disabled") }}</template>
          <template slot="text-right">{{ $t("common.enabled") }}</template>
        </NsToggle>
        <NsInlineNotification
          v-if="error.tls"
          kind="error"
          :title="$t(error.tls)"
          :showCloseButton="false"
        />
        <template v-if="tls">
          <NsToggle
            :label="$t('domains.tls_verify')"
            value="tls_verifyValue"
            :form-item="true"
            v-model="tls_verify"
            :disabled="
              loading.alterExternalDomain || domain.providers.length > 1
            "
            ref="tls_verify"
          >
            <template slot="text-left">{{ $t("common.disabled") }}</template>
            <template slot="text-right">{{ $t("common.enabled") }}</template>
          </NsToggle>
          <NsInlineNotification
            v-if="error.tls_verify"
            kind="error"
            :title="$t(error.tls_verify)"
            :showCloseButton="false"
          />
        </template>
      </cv-form>
    </template>
    <template slot="secondary-button">{{ $t("common.cancel") }}</template>
    <template slot="primary-button">{{
      $t("domains.edit_external_domain")
    }}</template>
  </NsModal>
</template>
⋮----
<template slot="title">{{ $t("domains.edit_external_domain") }}</template>
<template slot="content">
      <cv-form @submit.prevent="alterExternalDomain">
        <NsTextInput
          :label="$t('domains.bind_dn')"
          v-model.trim="bind_dn"
          :invalid-message="$t(error.bind_dn)"
          :disabled="loading.alterExternalDomain"
          ref="bind_dn"
        >
        </NsTextInput>
        <NsTextInput
          type="password"
          :label="$t('domains.bind_password')"
          v-model="bind_password"
          :invalid-message="$t(error.bind_password)"
          :password-hide-label="$t('password.hide_password')"
          :password-show-label="$t('password.show_password')"
          :disabled="loading.alterExternalDomain"
          ref="bind_password"
        >
        </NsTextInput>
        <NsToggle
          :label="$t('domains.tls')"
          value="tlsValue"
          :form-item="true"
          v-model="tls"
          :disabled="loading.alterExternalDomain"
          ref="tls"
        >
          <template slot="text-left">{{ $t("common.disabled") }}</template>
          <template slot="text-right">{{ $t("common.enabled") }}</template>
        </NsToggle>
        <NsInlineNotification
          v-if="error.tls"
          kind="error"
          :title="$t(error.tls)"
          :showCloseButton="false"
        />
        <template v-if="tls">
          <NsToggle
            :label="$t('domains.tls_verify')"
            value="tls_verifyValue"
            :form-item="true"
            v-model="tls_verify"
            :disabled="
              loading.alterExternalDomain || domain.providers.length > 1
            "
            ref="tls_verify"
          >
            <template slot="text-left">{{ $t("common.disabled") }}</template>
            <template slot="text-right">{{ $t("common.enabled") }}</template>
          </NsToggle>
          <NsInlineNotification
            v-if="error.tls_verify"
            kind="error"
            :title="$t(error.tls_verify)"
            :showCloseButton="false"
          />
        </template>
      </cv-form>
    </template>
⋮----
<template slot="text-left">{{ $t("common.disabled") }}</template>
<template slot="text-right">{{ $t("common.enabled") }}</template>
⋮----
<template v-if="tls">
          <NsToggle
            :label="$t('domains.tls_verify')"
            value="tls_verifyValue"
            :form-item="true"
            v-model="tls_verify"
            :disabled="
              loading.alterExternalDomain || domain.providers.length > 1
            "
            ref="tls_verify"
          >
            <template slot="text-left">{{ $t("common.disabled") }}</template>
            <template slot="text-right">{{ $t("common.enabled") }}</template>
          </NsToggle>
          <NsInlineNotification
            v-if="error.tls_verify"
            kind="error"
            :title="$t(error.tls_verify)"
            :showCloseButton="false"
          />
        </template>
⋮----
<template slot="text-left">{{ $t("common.disabled") }}</template>
<template slot="text-right">{{ $t("common.enabled") }}</template>
⋮----
<template slot="secondary-button">{{ $t("common.cancel") }}</template>
<template slot="primary-button">{{
      $t("domains.edit_external_domain")
    }}</template>
⋮----
<script>
import { UtilService, TaskService, IconService } from "@nethserver/ns8-ui-lib";
import to from "await-to-js";
export default {
  name: "EditExternalDomainModal",
  mixins: [UtilService, TaskService, IconService],
  props: {
    isShown: Boolean,
    domain: { type: [Object, null] },
  },
  data() {
    return {
      loading: {
        alterExternalDomain: false,
      },
      bind_dn: "",
      bind_password: "",
      tls: "",
      tls_verify: "",
      error: {
        bind_dn: "",
        bind_password: "",
        tls: "",
        tls_verify: "",
      },
    };
  },
  watch: {
    isShown: function () {
      if (this.isShown) {
        this.clearErrors(this);
        setTimeout(() => {
          this.focusElement("bind_dn");
        }, 300);
      }
      this.bind_dn = this.domain.bind_dn;
      this.bind_password = this.domain.bind_password;
      this.tls = this.domain.tls;
      this.tls_verify = this.domain.tls_verify;
    },
  },
  methods: {
    validateAlterExternalDomain() {
      this.clearErrors(this);
      let isValidationOk = true;
      if (!this.bind_dn) {
        this.error.bind_dn = "common.required";
        if (isValidationOk) {
          this.focusElement("bind_dn");
          isValidationOk = false;
        }
      }
      if (!this.bind_password) {
        this.error.bind_password = "common.required";
        if (isValidationOk) {
          this.focusElement("bind_password");
          isValidationOk = false;
        }
      }
      return isValidationOk;
    },
    async alterExternalDomain() {
      if (!this.validateAlterExternalDomain()) {
        return;
      }
      this.loading.alterExternalDomain = true;
      this.error.alterExternalDomain = "";
      const taskAction = "alter-external-domain";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.alterExternalDomainAborted
      );
      this.$root.$once(
        `${taskAction}-validation-failed-${eventId}`,
        this.alterExternalDomainValidationFailed
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.alterExternalDomainCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {
            domain: this.domain.name,
            protocol: this.domain.protocol,
            bind_dn: this.bind_dn,
            bind_password: this.bind_password,
            tls: this.tls,
            tls_verify: this.tls_verify,
          },
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.alterExternalDomain = this.getErrorMessage(err);
        this.loading.alterExternalDomain = false;
        return;
      }
    },
    alterExternalDomainAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.loading.alterExternalDomain = false;
    },
    alterExternalDomainValidationFailed(validationErrors) {
      this.loading.alterExternalDomain = false;
      for (const validationError of validationErrors) {
        const param = validationError.parameter;
        this.error[param] = this.$t("domains." + validationError.error);
      }
    },
    alterExternalDomainCompleted() {
      this.loading.alterExternalDomain = false;
      this.$emit("reload");
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
</style>
</file>

<file path="core/ui/src/components/domains/EditPasswordPolicy.vue">
<template>
  <NsModal
    size="default"
    :visible="isShown"
    @modal-hidden="$emit('hide')"
    @primary-click="$emit('confirm')"
  >
    <template slot="title">{{ $t("domains.edit_password_policy") }}</template>
    <template slot="content">
      <cv-form @submit.prevent="setPasswordPolicy">
        <NsToggle
          :label="$t('domains.password_expiration')"
          class="mg-left"
          value="expiration_enforced"
          :form-item="true"
          v-model="policy.expiration.enforced"
          ref="expiration_enforced"
        >
          <template slot="tooltip">
            <span>{{ $t("domains.enable_the_password_expiration") }}</span>
          </template>
          <template slot="text-left">{{ $t("common.disabled") }}</template>
          <template slot="text-right">{{ $t("common.enabled") }}</template>
        </NsToggle>
        <NsSlider
          v-if="policy.expiration.enforced"
          :label="$t('domains.expiration_min_age')"
          class="left-margin"
          v-model="policy.expiration.min_age"
          min="0"
          :max="policy.expiration.max_age"
          step="1"
          stepMultiplier="10"
          minLabel=""
          maxLabel=""
          :limitedLabel="$t('domains.specify_duration')"
          :invalidMessage="error.expiration.max_age"
          :unitLabel="$t('domains.days')"
        />
        <NsSlider
          v-if="policy.expiration.enforced"
          :label="$t('domains.expiration_max_age')"
          class="left-margin"
          v-model="policy.expiration.max_age"
          min="0"
          max="1000"
          step="1"
          stepMultiplier="10"
          minLabel=""
          maxLabel=""
          :limitedLabel="$t('domains.specify_duration')"
          :invalidMessage="error.expiration.max_age"
          :unitLabel="$t('domains.days')"
        />
        <NsToggle
          :label="$t('domains.enable_the_policy_strength')"
          class="mg-left"
          value="expiration_enforced"
          :form-item="true"
          v-model="policy.strength.enforced"
          ref="strength_enforced"
        >
          <template slot="tooltip">
            <span>{{ $t("domains.enable_the_policy_strength_tips") }}</span>
          </template>
          <template slot="text-left">{{ $t("common.disabled") }}</template>
          <template slot="text-right">{{ $t("common.enabled") }}</template>
        </NsToggle>
        <NsSlider
          v-if="policy.strength.enforced"
          :label="$t('domains.strength_history_length')"
          class="left-margin"
          v-model="policy.strength.history_length"
          min="0"
          max="24"
          step="1"
          stepMultiplier="10"
          minLabel=""
          maxLabel=""
          :limitedLabel="$t('domains.specify_duration')"
          :invalidMessage="error.strength.history_length"
          :unitLabel="$t('domains.times')"
        />
        <NsSlider
          v-if="policy.strength.enforced"
          :label="$t('domains.strength_password_min_length')"
          class="left-margin"
          v-model="policy.strength.password_min_length"
          min="0"
          max="14"
          step="1"
          stepMultiplier="10"
          minLabel=""
          maxLabel=""
          :limitedLabel="$t('domains.specify_times')"
          :invalidMessage="error.strength.password_min_length"
          :unitLabel="$t('domains.unit_characters')"
        />
        <NsToggle
          v-if="policy.strength.enforced"
          :label="$t('domains.strength_complexity_check')"
          class="left-margin"
          value="complexity_check"
          :form-item="true"
          v-model="policy.strength.complexity_check"
          ref="complexity_check"
        >
          <template slot="tooltip">
            <span>{{ $t("domains.enable_complexity_check_tips") }}</span>
          </template>
          <template slot="text-left">{{ $t("common.disabled") }}</template>
          <template slot="text-right">{{ $t("common.enabled") }}</template>
        </NsToggle>
        <NsInlineNotification
          v-if="error.setPasswordPolicy"
          kind="error"
          :title="$t('action.set-name')"
          :description="error.setPasswordPolicy"
          :showCloseButton="false"
        />
      </cv-form>
    </template>
    <template slot="secondary-button">{{ $t("common.cancel") }}</template>
    <template slot="primary-button">{{
      $t("domains.edit_password_policy")
    }}</template>
  </NsModal>
</template>
⋮----
<template slot="title">{{ $t("domains.edit_password_policy") }}</template>
<template slot="content">
      <cv-form @submit.prevent="setPasswordPolicy">
        <NsToggle
          :label="$t('domains.password_expiration')"
          class="mg-left"
          value="expiration_enforced"
          :form-item="true"
          v-model="policy.expiration.enforced"
          ref="expiration_enforced"
        >
          <template slot="tooltip">
            <span>{{ $t("domains.enable_the_password_expiration") }}</span>
          </template>
          <template slot="text-left">{{ $t("common.disabled") }}</template>
          <template slot="text-right">{{ $t("common.enabled") }}</template>
        </NsToggle>
        <NsSlider
          v-if="policy.expiration.enforced"
          :label="$t('domains.expiration_min_age')"
          class="left-margin"
          v-model="policy.expiration.min_age"
          min="0"
          :max="policy.expiration.max_age"
          step="1"
          stepMultiplier="10"
          minLabel=""
          maxLabel=""
          :limitedLabel="$t('domains.specify_duration')"
          :invalidMessage="error.expiration.max_age"
          :unitLabel="$t('domains.days')"
        />
        <NsSlider
          v-if="policy.expiration.enforced"
          :label="$t('domains.expiration_max_age')"
          class="left-margin"
          v-model="policy.expiration.max_age"
          min="0"
          max="1000"
          step="1"
          stepMultiplier="10"
          minLabel=""
          maxLabel=""
          :limitedLabel="$t('domains.specify_duration')"
          :invalidMessage="error.expiration.max_age"
          :unitLabel="$t('domains.days')"
        />
        <NsToggle
          :label="$t('domains.enable_the_policy_strength')"
          class="mg-left"
          value="expiration_enforced"
          :form-item="true"
          v-model="policy.strength.enforced"
          ref="strength_enforced"
        >
          <template slot="tooltip">
            <span>{{ $t("domains.enable_the_policy_strength_tips") }}</span>
          </template>
          <template slot="text-left">{{ $t("common.disabled") }}</template>
          <template slot="text-right">{{ $t("common.enabled") }}</template>
        </NsToggle>
        <NsSlider
          v-if="policy.strength.enforced"
          :label="$t('domains.strength_history_length')"
          class="left-margin"
          v-model="policy.strength.history_length"
          min="0"
          max="24"
          step="1"
          stepMultiplier="10"
          minLabel=""
          maxLabel=""
          :limitedLabel="$t('domains.specify_duration')"
          :invalidMessage="error.strength.history_length"
          :unitLabel="$t('domains.times')"
        />
        <NsSlider
          v-if="policy.strength.enforced"
          :label="$t('domains.strength_password_min_length')"
          class="left-margin"
          v-model="policy.strength.password_min_length"
          min="0"
          max="14"
          step="1"
          stepMultiplier="10"
          minLabel=""
          maxLabel=""
          :limitedLabel="$t('domains.specify_times')"
          :invalidMessage="error.strength.password_min_length"
          :unitLabel="$t('domains.unit_characters')"
        />
        <NsToggle
          v-if="policy.strength.enforced"
          :label="$t('domains.strength_complexity_check')"
          class="left-margin"
          value="complexity_check"
          :form-item="true"
          v-model="policy.strength.complexity_check"
          ref="complexity_check"
        >
          <template slot="tooltip">
            <span>{{ $t("domains.enable_complexity_check_tips") }}</span>
          </template>
          <template slot="text-left">{{ $t("common.disabled") }}</template>
          <template slot="text-right">{{ $t("common.enabled") }}</template>
        </NsToggle>
        <NsInlineNotification
          v-if="error.setPasswordPolicy"
          kind="error"
          :title="$t('action.set-name')"
          :description="error.setPasswordPolicy"
          :showCloseButton="false"
        />
      </cv-form>
    </template>
⋮----
<template slot="tooltip">
            <span>{{ $t("domains.enable_the_password_expiration") }}</span>
          </template>
⋮----
<span>{{ $t("domains.enable_the_password_expiration") }}</span>
⋮----
<template slot="text-left">{{ $t("common.disabled") }}</template>
<template slot="text-right">{{ $t("common.enabled") }}</template>
⋮----
<template slot="tooltip">
            <span>{{ $t("domains.enable_the_policy_strength_tips") }}</span>
          </template>
⋮----
<span>{{ $t("domains.enable_the_policy_strength_tips") }}</span>
⋮----
<template slot="text-left">{{ $t("common.disabled") }}</template>
<template slot="text-right">{{ $t("common.enabled") }}</template>
⋮----
<template slot="tooltip">
            <span>{{ $t("domains.enable_complexity_check_tips") }}</span>
          </template>
⋮----
<span>{{ $t("domains.enable_complexity_check_tips") }}</span>
⋮----
<template slot="text-left">{{ $t("common.disabled") }}</template>
<template slot="text-right">{{ $t("common.enabled") }}</template>
⋮----
<template slot="secondary-button">{{ $t("common.cancel") }}</template>
<template slot="primary-button">{{
      $t("domains.edit_password_policy")
    }}</template>
⋮----
<script>
import { UtilService, IconService } from "@nethserver/ns8-ui-lib";
export default {
  name: "EditPasswordPolicy",
  mixins: [UtilService, IconService],
  props: {
    isShown: Boolean,
    policy: { type: [Object, null] },
  },
  data() {
    return {
      error: {
        expiration: { max_age: "", min_age: "", enforced: "" },
        strength: { password_min_length: "", history_length: "" },
      },
    };
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
.left-margin {
  margin-left: 1rem;
}
</style>
</file>

<file path="core/ui/src/components/domains/EditPasswordWarningModal.vue">
<template>
  <NsModal
    size="default"
    :visible="isShown"
    @modal-hidden="$emit('hide')"
    @primary-click="$emit('confirm')"
    :primaryButtonDisabled="
      !policy.expiration.enforced || !policy.warning.smtp_enabled
    "
  >
    <template slot="title">{{ $t("domains.edit_password_warning") }}</template>
    <template slot="content">
      <cv-form
        v-if="policy.expiration.enforced && policy.warning.smtp_enabled"
        @submit.prevent="setPasswordWarning"
      >
        <NsToggle
          :label="$t('domains.warning_enable')"
          class="mg-left"
          value="expiration_notification"
          :form-item="true"
          v-model="policy.warning.notification"
          ref="expiration_notification"
        >
          <template slot="tooltip">
            <span>{{ $t("domains.warning_enable_tip") }}</span>
          </template>
          <template slot="text-left">{{ $t("common.disabled") }}</template>
          <template slot="text-right">{{ $t("common.enabled") }}</template>
        </NsToggle>
        <cv-text-input
          v-if="policy.warning.notification"
          :label="$t('domains.warning_days')"
          v-model.number="policy.warning.days"
          type="number"
          min="1"
          max="1000"
          :form-item="true"
          :invalidMessage="error.warningDays"
          :unitLabel="$t('domains.days')"
        />
        <cv-text-input
          v-if="policy.warning.notification"
          :label="$t('domains.warning_sender')"
          v-model="policy.warning.mail_from"
          type="email"
          :form-item="true"
        />
        <cv-select
          v-if="policy.warning.notification"
          :label="$t('domains.warning_template')"
          v-model="policy.warning.mail_template_name"
          :form-item="true"
        >
          <cv-select-option value="default_en">
            {{ $t("domains.warning_template_default_en") }}
          </cv-select-option>
          <cv-select-option value="default_it">
            {{ $t("domains.warning_template_default_it") }}
          </cv-select-option>
          <cv-select-option value="custom">
            {{ $t("domains.warning_template_custom") }}
          </cv-select-option>
        </cv-select>
        <cv-text-input
          v-if="
            policy.warning.notification &&
            policy.warning.mail_template_name === 'custom'
          "
          :label="$t('domains.warning_template_subject')"
          v-model="policy.warning.mail_subject"
          :form-item="true"
          :helper-text="$t('domains.warning_template_subject_tip')"
          :invalid-message="error.warningMailSubject"
        />
        <cv-text-area
          v-if="
            policy.warning.notification &&
            policy.warning.mail_template_name === 'custom'
          "
          :label="$t('domains.warning_template_content')"
          v-model="policy.warning.mail_template_content"
          :form-item="true"
          :helper-text="$t('domains.warning_template_content_tip')"
          rows="10"
          :invalid-message="error.warningMailTemplateContent"
        />
        <NsInlineNotification
          v-if="error.setPasswordWarning"
          kind="error"
          :title="$t('action.set-password-warning')"
          :description="error.setPasswordWarning"
          :showCloseButton="false"
        />
      </cv-form>
      <NsInlineNotification
        v-if="!policy.warning.smtp_enabled"
        kind="info"
        :title="$t('domains.warning_smtp_disabled_title')"
        :description="$t('domains.warning_smtp_disabled_description')"
        :showCloseButton="false"
        :actionLabel="$t('domains.go_to_smtp_settings')"
        @action="goToSmtpSettings"
      />
      <NsInlineNotification
        v-if="!policy.expiration.enforced"
        kind="info"
        :title="$t('domains.warning_disabled_title')"
        :description="$t('domains.warning_disabled_description')"
        :showCloseButton="false"
      />
    </template>
    <template slot="secondary-button">{{ $t("common.cancel") }}</template>
    <template slot="primary-button">{{
      $t("domains.edit_password_warning")
    }}</template>
  </NsModal>
</template>
⋮----
<template slot="title">{{ $t("domains.edit_password_warning") }}</template>
<template slot="content">
      <cv-form
        v-if="policy.expiration.enforced && policy.warning.smtp_enabled"
        @submit.prevent="setPasswordWarning"
      >
        <NsToggle
          :label="$t('domains.warning_enable')"
          class="mg-left"
          value="expiration_notification"
          :form-item="true"
          v-model="policy.warning.notification"
          ref="expiration_notification"
        >
          <template slot="tooltip">
            <span>{{ $t("domains.warning_enable_tip") }}</span>
          </template>
          <template slot="text-left">{{ $t("common.disabled") }}</template>
          <template slot="text-right">{{ $t("common.enabled") }}</template>
        </NsToggle>
        <cv-text-input
          v-if="policy.warning.notification"
          :label="$t('domains.warning_days')"
          v-model.number="policy.warning.days"
          type="number"
          min="1"
          max="1000"
          :form-item="true"
          :invalidMessage="error.warningDays"
          :unitLabel="$t('domains.days')"
        />
        <cv-text-input
          v-if="policy.warning.notification"
          :label="$t('domains.warning_sender')"
          v-model="policy.warning.mail_from"
          type="email"
          :form-item="true"
        />
        <cv-select
          v-if="policy.warning.notification"
          :label="$t('domains.warning_template')"
          v-model="policy.warning.mail_template_name"
          :form-item="true"
        >
          <cv-select-option value="default_en">
            {{ $t("domains.warning_template_default_en") }}
          </cv-select-option>
          <cv-select-option value="default_it">
            {{ $t("domains.warning_template_default_it") }}
          </cv-select-option>
          <cv-select-option value="custom">
            {{ $t("domains.warning_template_custom") }}
          </cv-select-option>
        </cv-select>
        <cv-text-input
          v-if="
            policy.warning.notification &&
            policy.warning.mail_template_name === 'custom'
          "
          :label="$t('domains.warning_template_subject')"
          v-model="policy.warning.mail_subject"
          :form-item="true"
          :helper-text="$t('domains.warning_template_subject_tip')"
          :invalid-message="error.warningMailSubject"
        />
        <cv-text-area
          v-if="
            policy.warning.notification &&
            policy.warning.mail_template_name === 'custom'
          "
          :label="$t('domains.warning_template_content')"
          v-model="policy.warning.mail_template_content"
          :form-item="true"
          :helper-text="$t('domains.warning_template_content_tip')"
          rows="10"
          :invalid-message="error.warningMailTemplateContent"
        />
        <NsInlineNotification
          v-if="error.setPasswordWarning"
          kind="error"
          :title="$t('action.set-password-warning')"
          :description="error.setPasswordWarning"
          :showCloseButton="false"
        />
      </cv-form>
      <NsInlineNotification
        v-if="!policy.warning.smtp_enabled"
        kind="info"
        :title="$t('domains.warning_smtp_disabled_title')"
        :description="$t('domains.warning_smtp_disabled_description')"
        :showCloseButton="false"
        :actionLabel="$t('domains.go_to_smtp_settings')"
        @action="goToSmtpSettings"
      />
      <NsInlineNotification
        v-if="!policy.expiration.enforced"
        kind="info"
        :title="$t('domains.warning_disabled_title')"
        :description="$t('domains.warning_disabled_description')"
        :showCloseButton="false"
      />
    </template>
⋮----
<template slot="tooltip">
            <span>{{ $t("domains.warning_enable_tip") }}</span>
          </template>
⋮----
<span>{{ $t("domains.warning_enable_tip") }}</span>
⋮----
<template slot="text-left">{{ $t("common.disabled") }}</template>
<template slot="text-right">{{ $t("common.enabled") }}</template>
⋮----
{{ $t("domains.warning_template_default_en") }}
⋮----
{{ $t("domains.warning_template_default_it") }}
⋮----
{{ $t("domains.warning_template_custom") }}
⋮----
<template slot="secondary-button">{{ $t("common.cancel") }}</template>
<template slot="primary-button">{{
      $t("domains.edit_password_warning")
    }}</template>
⋮----
<script>
import { UtilService, IconService } from "@nethserver/ns8-ui-lib";
export default {
  name: "EditPasswordWarningModal",
  mixins: [UtilService, IconService],
  props: {
    isShown: Boolean,
    policy: { type: [Object, null] },
    error: { type: Object },
  },
  methods: {
    goToSmtpSettings() {
      this.$router.replace("/settings/smarthost");
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
.left-margin {
  margin-left: 1rem;
}
</style>
</file>

<file path="core/ui/src/components/domains/ImportUsersModal.vue">
<template>
  <NsWizard
    size="large"
    :visible="isShown"
    :cancelLabel="$t('common.cancel')"
    :previousLabel="$t('common.previous')"
    :nextLabel="isLastStep ? $t('import_users.import') : $t('common.next')"
    :isPreviousDisabled="isFirstStep || loading.uploadCsvFile"
    :isNextDisabled="isNextButtonDisabled"
    :isNextLoading="loading.uploadCsvFile"
    @modal-hidden="onModalHidden"
    @cancel="onModalHidden"
    @previousStep="previousStep"
    @nextStep="nextStep"
  >
    <template slot="title">{{ $t("import_users.import_data") }}</template>
    <template slot="content">
      <cv-form @submit.prevent="nextStep">
        <NsInlineNotification
          v-if="error.importDataCsv"
          kind="error"
          :title="$t('import_users.import_error')"
          :description="error.importDataCsv"
          :showCloseButton="false"
        />
        <NsProgress :stepId="step" :steps="progressSteps" class="progress" />
        <template v-if="step == 'importData'">
          <p class="mg-bottom-lg">
            {{ $t("import_users.upload_csv_file_description") }}
          </p>
          <span class="label font-bold">
            {{ $t("import_users.csv_upload_label") }}
          </span>
          <div :class="{ 'file-uploader-wrapper': error.uploadCsvFile }">
            <cv-file-uploader
              :helper-text="$t('import_users.csv_upload_helper_text')"
              :multiple="false"
              :removable="true"
              :clear-on-reselect="true"
              :drop-target-label="$t('common.drag_and_drop_or_click_to_upload')"
              @change="convertFileToJson"
              v-model="csvFile"
            ></cv-file-uploader>
          </div>
          <div
            v-if="error.uploadCsvFile"
            class="validation-failed-invalid-message"
          >
            {{ $t(error.uploadCsvFile) }}
          </div>
          <label class="bx--label">
            {{ $t("import_users.manage_existing_users") }}
            <cv-interactive-tooltip
              alignment="center"
              direction="top"
              class="info"
            >
              <template slot="content">
                <div>
                  {{ $t("import_users.manage_existing_users_tooltip") }}
                </div>
              </template>
            </cv-interactive-tooltip>
          </label>
          <cv-radio-group vertical>
            <cv-radio-button
              v-model="existingPolicy"
              value="skip"
              :label="$t('import_users.skip_existing_users')"
              checked
            ></cv-radio-button>
            <cv-radio-button
              v-model="existingPolicy"
              value="overwrite"
              :label="$t('import_users.overwrite_existing_users')"
            ></cv-radio-button>
          </cv-radio-group>
        </template>
        <template v-if="step == 'previewData'">
          <cv-skeleton-text
            v-if="loading.getPreviewData"
            heading
            paragraph
            :line-count="6"
          />
          <template v-else>
            <div class="mg-bottom-md">
              {{
                $t("import_users.preview_description", {
                  users: userCount,
                  groups: groupCount,
                })
              }}
            </div>
            <div class="font-bold mg-bottom-md">
              {{ $t("import_users.preview") }}
            </div>
            <cv-tile light>
              <NsDataTable
                :allRows="previewRows"
                :columns="i18nTableColumns"
                :rawColumns="tableColumns"
                :sortable="true"
                :pageSizes="[]"
                :searchPlaceholder="$t('domain_users.search_user')"
                :searchClearLabel="$t('common.clear_search')"
                :noSearchResultsLabel="$t('common.no_search_results')"
                :noSearchResultsDescription="
                  $t('common.no_search_results_description')
                "
                :isLoading="loading.getPreviewData"
                :skeletonRows="5"
                :isErrorShown="!!error.getPreviewData"
                :errorTitle="$t('action.list-domain-users')"
                :errorDescription="error.getPreviewData"
                :itemsPerPageLabel="$t('pagination.items_per_page')"
                :rangeOfTotalItemsLabel="$t('pagination.range_of_total_items')"
                :ofTotalPagesLabel="$t('pagination.of_total_pages')"
                :backwardText="$t('pagination.previous_page')"
                :forwardText="$t('pagination.next_page')"
                :pageNumberLabel="$t('pagination.page_number')"
                @updatePage="tablePage = $event"
              >
                <template slot="empty-state">
                  <NsEmptyState :title="$t('import_users.no_import_users')">
                    <template #description>
                      <div>
                        {{ $t("import_users.no_import_users_description") }}
                      </div>
                    </template>
                  </NsEmptyState>
                </template>
                <template slot="data">
                  <cv-data-table-row
                    v-for="(row, rowIndex) in tablePage"
                    :key="`${rowIndex}`"
                    :value="`${rowIndex}`"
                  >
                    <cv-data-table-cell>
                      <span>{{ row.user }}</span>
                    </cv-data-table-cell>
                    <cv-data-table-cell>
                      {{ row.display_name }}
                    </cv-data-table-cell>
                    <cv-data-table-cell>
                      {{ row.password }}
                    </cv-data-table-cell>
                    <cv-data-table-cell>
                      {{ row.mail }}
                    </cv-data-table-cell>
                    <cv-data-table-cell>
                      {{ row.groups.join(", ") }}
                    </cv-data-table-cell>
                    <cv-data-table-cell>
                      {{ row.locked }}
                    </cv-data-table-cell>
                    <cv-data-table-cell>
                      {{ row.must_change_password }}
                    </cv-data-table-cell>
                    <cv-data-table-cell>
                      {{ row.no_password_expiration }}
                    </cv-data-table-cell>
                  </cv-data-table-row>
                </template>
              </NsDataTable>
            </cv-tile>
            <NsInlineNotification
              kind="info"
              :title="$t('import_users.delete_your_file_after_import')"
              :description="
                $t('import_users.delete_your_file_after_import_description')
              "
              :showCloseButton="false"
            />
          </template>
        </template>
      </cv-form>
    </template>
  </NsWizard>
</template>
⋮----
<template slot="title">{{ $t("import_users.import_data") }}</template>
<template slot="content">
      <cv-form @submit.prevent="nextStep">
        <NsInlineNotification
          v-if="error.importDataCsv"
          kind="error"
          :title="$t('import_users.import_error')"
          :description="error.importDataCsv"
          :showCloseButton="false"
        />
        <NsProgress :stepId="step" :steps="progressSteps" class="progress" />
        <template v-if="step == 'importData'">
          <p class="mg-bottom-lg">
            {{ $t("import_users.upload_csv_file_description") }}
          </p>
          <span class="label font-bold">
            {{ $t("import_users.csv_upload_label") }}
          </span>
          <div :class="{ 'file-uploader-wrapper': error.uploadCsvFile }">
            <cv-file-uploader
              :helper-text="$t('import_users.csv_upload_helper_text')"
              :multiple="false"
              :removable="true"
              :clear-on-reselect="true"
              :drop-target-label="$t('common.drag_and_drop_or_click_to_upload')"
              @change="convertFileToJson"
              v-model="csvFile"
            ></cv-file-uploader>
          </div>
          <div
            v-if="error.uploadCsvFile"
            class="validation-failed-invalid-message"
          >
            {{ $t(error.uploadCsvFile) }}
          </div>
          <label class="bx--label">
            {{ $t("import_users.manage_existing_users") }}
            <cv-interactive-tooltip
              alignment="center"
              direction="top"
              class="info"
            >
              <template slot="content">
                <div>
                  {{ $t("import_users.manage_existing_users_tooltip") }}
                </div>
              </template>
            </cv-interactive-tooltip>
          </label>
          <cv-radio-group vertical>
            <cv-radio-button
              v-model="existingPolicy"
              value="skip"
              :label="$t('import_users.skip_existing_users')"
              checked
            ></cv-radio-button>
            <cv-radio-button
              v-model="existingPolicy"
              value="overwrite"
              :label="$t('import_users.overwrite_existing_users')"
            ></cv-radio-button>
          </cv-radio-group>
        </template>
        <template v-if="step == 'previewData'">
          <cv-skeleton-text
            v-if="loading.getPreviewData"
            heading
            paragraph
            :line-count="6"
          />
          <template v-else>
            <div class="mg-bottom-md">
              {{
                $t("import_users.preview_description", {
                  users: userCount,
                  groups: groupCount,
                })
              }}
            </div>
            <div class="font-bold mg-bottom-md">
              {{ $t("import_users.preview") }}
            </div>
            <cv-tile light>
              <NsDataTable
                :allRows="previewRows"
                :columns="i18nTableColumns"
                :rawColumns="tableColumns"
                :sortable="true"
                :pageSizes="[]"
                :searchPlaceholder="$t('domain_users.search_user')"
                :searchClearLabel="$t('common.clear_search')"
                :noSearchResultsLabel="$t('common.no_search_results')"
                :noSearchResultsDescription="
                  $t('common.no_search_results_description')
                "
                :isLoading="loading.getPreviewData"
                :skeletonRows="5"
                :isErrorShown="!!error.getPreviewData"
                :errorTitle="$t('action.list-domain-users')"
                :errorDescription="error.getPreviewData"
                :itemsPerPageLabel="$t('pagination.items_per_page')"
                :rangeOfTotalItemsLabel="$t('pagination.range_of_total_items')"
                :ofTotalPagesLabel="$t('pagination.of_total_pages')"
                :backwardText="$t('pagination.previous_page')"
                :forwardText="$t('pagination.next_page')"
                :pageNumberLabel="$t('pagination.page_number')"
                @updatePage="tablePage = $event"
              >
                <template slot="empty-state">
                  <NsEmptyState :title="$t('import_users.no_import_users')">
                    <template #description>
                      <div>
                        {{ $t("import_users.no_import_users_description") }}
                      </div>
                    </template>
                  </NsEmptyState>
                </template>
                <template slot="data">
                  <cv-data-table-row
                    v-for="(row, rowIndex) in tablePage"
                    :key="`${rowIndex}`"
                    :value="`${rowIndex}`"
                  >
                    <cv-data-table-cell>
                      <span>{{ row.user }}</span>
                    </cv-data-table-cell>
                    <cv-data-table-cell>
                      {{ row.display_name }}
                    </cv-data-table-cell>
                    <cv-data-table-cell>
                      {{ row.password }}
                    </cv-data-table-cell>
                    <cv-data-table-cell>
                      {{ row.mail }}
                    </cv-data-table-cell>
                    <cv-data-table-cell>
                      {{ row.groups.join(", ") }}
                    </cv-data-table-cell>
                    <cv-data-table-cell>
                      {{ row.locked }}
                    </cv-data-table-cell>
                    <cv-data-table-cell>
                      {{ row.must_change_password }}
                    </cv-data-table-cell>
                    <cv-data-table-cell>
                      {{ row.no_password_expiration }}
                    </cv-data-table-cell>
                  </cv-data-table-row>
                </template>
              </NsDataTable>
            </cv-tile>
            <NsInlineNotification
              kind="info"
              :title="$t('import_users.delete_your_file_after_import')"
              :description="
                $t('import_users.delete_your_file_after_import_description')
              "
              :showCloseButton="false"
            />
          </template>
        </template>
      </cv-form>
    </template>
⋮----
<template v-if="step == 'importData'">
          <p class="mg-bottom-lg">
            {{ $t("import_users.upload_csv_file_description") }}
          </p>
          <span class="label font-bold">
            {{ $t("import_users.csv_upload_label") }}
          </span>
          <div :class="{ 'file-uploader-wrapper': error.uploadCsvFile }">
            <cv-file-uploader
              :helper-text="$t('import_users.csv_upload_helper_text')"
              :multiple="false"
              :removable="true"
              :clear-on-reselect="true"
              :drop-target-label="$t('common.drag_and_drop_or_click_to_upload')"
              @change="convertFileToJson"
              v-model="csvFile"
            ></cv-file-uploader>
          </div>
          <div
            v-if="error.uploadCsvFile"
            class="validation-failed-invalid-message"
          >
            {{ $t(error.uploadCsvFile) }}
          </div>
          <label class="bx--label">
            {{ $t("import_users.manage_existing_users") }}
            <cv-interactive-tooltip
              alignment="center"
              direction="top"
              class="info"
            >
              <template slot="content">
                <div>
                  {{ $t("import_users.manage_existing_users_tooltip") }}
                </div>
              </template>
            </cv-interactive-tooltip>
          </label>
          <cv-radio-group vertical>
            <cv-radio-button
              v-model="existingPolicy"
              value="skip"
              :label="$t('import_users.skip_existing_users')"
              checked
            ></cv-radio-button>
            <cv-radio-button
              v-model="existingPolicy"
              value="overwrite"
              :label="$t('import_users.overwrite_existing_users')"
            ></cv-radio-button>
          </cv-radio-group>
        </template>
⋮----
{{ $t("import_users.upload_csv_file_description") }}
⋮----
{{ $t("import_users.csv_upload_label") }}
⋮----
{{ $t(error.uploadCsvFile) }}
⋮----
{{ $t("import_users.manage_existing_users") }}
⋮----
<template slot="content">
                <div>
                  {{ $t("import_users.manage_existing_users_tooltip") }}
                </div>
              </template>
⋮----
{{ $t("import_users.manage_existing_users_tooltip") }}
⋮----
<template v-if="step == 'previewData'">
          <cv-skeleton-text
            v-if="loading.getPreviewData"
            heading
            paragraph
            :line-count="6"
          />
          <template v-else>
            <div class="mg-bottom-md">
              {{
                $t("import_users.preview_description", {
                  users: userCount,
                  groups: groupCount,
                })
              }}
            </div>
            <div class="font-bold mg-bottom-md">
              {{ $t("import_users.preview") }}
            </div>
            <cv-tile light>
              <NsDataTable
                :allRows="previewRows"
                :columns="i18nTableColumns"
                :rawColumns="tableColumns"
                :sortable="true"
                :pageSizes="[]"
                :searchPlaceholder="$t('domain_users.search_user')"
                :searchClearLabel="$t('common.clear_search')"
                :noSearchResultsLabel="$t('common.no_search_results')"
                :noSearchResultsDescription="
                  $t('common.no_search_results_description')
                "
                :isLoading="loading.getPreviewData"
                :skeletonRows="5"
                :isErrorShown="!!error.getPreviewData"
                :errorTitle="$t('action.list-domain-users')"
                :errorDescription="error.getPreviewData"
                :itemsPerPageLabel="$t('pagination.items_per_page')"
                :rangeOfTotalItemsLabel="$t('pagination.range_of_total_items')"
                :ofTotalPagesLabel="$t('pagination.of_total_pages')"
                :backwardText="$t('pagination.previous_page')"
                :forwardText="$t('pagination.next_page')"
                :pageNumberLabel="$t('pagination.page_number')"
                @updatePage="tablePage = $event"
              >
                <template slot="empty-state">
                  <NsEmptyState :title="$t('import_users.no_import_users')">
                    <template #description>
                      <div>
                        {{ $t("import_users.no_import_users_description") }}
                      </div>
                    </template>
                  </NsEmptyState>
                </template>
                <template slot="data">
                  <cv-data-table-row
                    v-for="(row, rowIndex) in tablePage"
                    :key="`${rowIndex}`"
                    :value="`${rowIndex}`"
                  >
                    <cv-data-table-cell>
                      <span>{{ row.user }}</span>
                    </cv-data-table-cell>
                    <cv-data-table-cell>
                      {{ row.display_name }}
                    </cv-data-table-cell>
                    <cv-data-table-cell>
                      {{ row.password }}
                    </cv-data-table-cell>
                    <cv-data-table-cell>
                      {{ row.mail }}
                    </cv-data-table-cell>
                    <cv-data-table-cell>
                      {{ row.groups.join(", ") }}
                    </cv-data-table-cell>
                    <cv-data-table-cell>
                      {{ row.locked }}
                    </cv-data-table-cell>
                    <cv-data-table-cell>
                      {{ row.must_change_password }}
                    </cv-data-table-cell>
                    <cv-data-table-cell>
                      {{ row.no_password_expiration }}
                    </cv-data-table-cell>
                  </cv-data-table-row>
                </template>
              </NsDataTable>
            </cv-tile>
            <NsInlineNotification
              kind="info"
              :title="$t('import_users.delete_your_file_after_import')"
              :description="
                $t('import_users.delete_your_file_after_import_description')
              "
              :showCloseButton="false"
            />
          </template>
        </template>
⋮----
<template v-else>
            <div class="mg-bottom-md">
              {{
                $t("import_users.preview_description", {
                  users: userCount,
                  groups: groupCount,
                })
              }}
            </div>
            <div class="font-bold mg-bottom-md">
              {{ $t("import_users.preview") }}
            </div>
            <cv-tile light>
              <NsDataTable
                :allRows="previewRows"
                :columns="i18nTableColumns"
                :rawColumns="tableColumns"
                :sortable="true"
                :pageSizes="[]"
                :searchPlaceholder="$t('domain_users.search_user')"
                :searchClearLabel="$t('common.clear_search')"
                :noSearchResultsLabel="$t('common.no_search_results')"
                :noSearchResultsDescription="
                  $t('common.no_search_results_description')
                "
                :isLoading="loading.getPreviewData"
                :skeletonRows="5"
                :isErrorShown="!!error.getPreviewData"
                :errorTitle="$t('action.list-domain-users')"
                :errorDescription="error.getPreviewData"
                :itemsPerPageLabel="$t('pagination.items_per_page')"
                :rangeOfTotalItemsLabel="$t('pagination.range_of_total_items')"
                :ofTotalPagesLabel="$t('pagination.of_total_pages')"
                :backwardText="$t('pagination.previous_page')"
                :forwardText="$t('pagination.next_page')"
                :pageNumberLabel="$t('pagination.page_number')"
                @updatePage="tablePage = $event"
              >
                <template slot="empty-state">
                  <NsEmptyState :title="$t('import_users.no_import_users')">
                    <template #description>
                      <div>
                        {{ $t("import_users.no_import_users_description") }}
                      </div>
                    </template>
                  </NsEmptyState>
                </template>
                <template slot="data">
                  <cv-data-table-row
                    v-for="(row, rowIndex) in tablePage"
                    :key="`${rowIndex}`"
                    :value="`${rowIndex}`"
                  >
                    <cv-data-table-cell>
                      <span>{{ row.user }}</span>
                    </cv-data-table-cell>
                    <cv-data-table-cell>
                      {{ row.display_name }}
                    </cv-data-table-cell>
                    <cv-data-table-cell>
                      {{ row.password }}
                    </cv-data-table-cell>
                    <cv-data-table-cell>
                      {{ row.mail }}
                    </cv-data-table-cell>
                    <cv-data-table-cell>
                      {{ row.groups.join(", ") }}
                    </cv-data-table-cell>
                    <cv-data-table-cell>
                      {{ row.locked }}
                    </cv-data-table-cell>
                    <cv-data-table-cell>
                      {{ row.must_change_password }}
                    </cv-data-table-cell>
                    <cv-data-table-cell>
                      {{ row.no_password_expiration }}
                    </cv-data-table-cell>
                  </cv-data-table-row>
                </template>
              </NsDataTable>
            </cv-tile>
            <NsInlineNotification
              kind="info"
              :title="$t('import_users.delete_your_file_after_import')"
              :description="
                $t('import_users.delete_your_file_after_import_description')
              "
              :showCloseButton="false"
            />
          </template>
⋮----
{{
                $t("import_users.preview_description", {
                  users: userCount,
                  groups: groupCount,
                })
              }}
⋮----
{{ $t("import_users.preview") }}
⋮----
<template slot="empty-state">
                  <NsEmptyState :title="$t('import_users.no_import_users')">
                    <template #description>
                      <div>
                        {{ $t("import_users.no_import_users_description") }}
                      </div>
                    </template>
                  </NsEmptyState>
                </template>
⋮----
<template #description>
                      <div>
                        {{ $t("import_users.no_import_users_description") }}
                      </div>
                    </template>
⋮----
{{ $t("import_users.no_import_users_description") }}
⋮----
<template slot="data">
                  <cv-data-table-row
                    v-for="(row, rowIndex) in tablePage"
                    :key="`${rowIndex}`"
                    :value="`${rowIndex}`"
                  >
                    <cv-data-table-cell>
                      <span>{{ row.user }}</span>
                    </cv-data-table-cell>
                    <cv-data-table-cell>
                      {{ row.display_name }}
                    </cv-data-table-cell>
                    <cv-data-table-cell>
                      {{ row.password }}
                    </cv-data-table-cell>
                    <cv-data-table-cell>
                      {{ row.mail }}
                    </cv-data-table-cell>
                    <cv-data-table-cell>
                      {{ row.groups.join(", ") }}
                    </cv-data-table-cell>
                    <cv-data-table-cell>
                      {{ row.locked }}
                    </cv-data-table-cell>
                    <cv-data-table-cell>
                      {{ row.must_change_password }}
                    </cv-data-table-cell>
                    <cv-data-table-cell>
                      {{ row.no_password_expiration }}
                    </cv-data-table-cell>
                  </cv-data-table-row>
                </template>
⋮----
<span>{{ row.user }}</span>
⋮----
{{ row.display_name }}
⋮----
{{ row.password }}
⋮----
{{ row.mail }}
⋮----
{{ row.groups.join(", ") }}
⋮----
{{ row.locked }}
⋮----
{{ row.must_change_password }}
⋮----
{{ row.no_password_expiration }}
⋮----
<script>
import { UtilService, TaskService, IconService } from "@nethserver/ns8-ui-lib";
import to from "await-to-js";
import TwoFaService from "@/mixins/2fa";
import Papa from "papaparse";
import _isEmpty from "lodash/isEmpty";
export default {
  name: "ImportUsersModal",
  components: {},
  mixins: [UtilService, TaskService, IconService, TwoFaService],
  props: {
    isShown: {
      type: Boolean,
      default: true,
    },
    domain: {
      type: Object,
      default: null,
    },
  },
  data() {
    return {
      step: "",
      steps: ["importData", "previewData"],
      progressSteps: [
        {
          id: "importData",
          label: this.$t("import_users.csv_upload_label"),
        },
        {
          id: "previewData",
          label: this.$t("import_users.preview"),
        },
      ],
      csvFile: null,
      existingPolicy: "skip",
      loading: {
        uploadCsvFile: false,
        getPreviewData: false,
      },
      error: {
        uploadCsvFile: "",
        getPreviewData: "",
        importDataCsv: "",
      },
      previewRows: [],
      tablePage: [],
      userCount: 0,
      groupCount: 0,
      tableColumns: [
        "user",
        "display_name",
        "password",
        "mail",
        "groups",
        "locked",
        "must_change_password",
        "no_password_expiration",
      ],
    };
  },
  computed: {
    mainProvider() {
      if (this.domain && this.domain.providers && this.domain.providers[0]) {
        return this.domain.providers[0].id;
      }
      return "";
    },
    i18nTableColumns() {
      return this.tableColumns.map((column) => {
        return this.$t("domain_users." + column);
      });
    },
    areFileSelected: function () {
      return !_isEmpty(this.csvFile);
    },
    stepIndex() {
      return this.steps.indexOf(this.step);
    },
    isFirstStep() {
      return this.stepIndex == 0;
    },
    isLastStep() {
      return this.stepIndex == this.steps.length - 1;
    },
    isNextButtonDisabled() {
      return (
        (this.step == "importData" && !this.areFileSelected) ||
        !!this.error.uploadCsvFile
      );
    },
  },
  watch: {
    isShown: function () {
      if (this.isShown) {
        this.step = this.steps[0];
        this.clearErrors();
        this.importData = "";
        this.csvFile = null;
      }
    },
  },
  methods: {
    onModalHidden() {
      this.$emit("hide");
      this.clearErrors();
      this.importData = "";
      this.csvFile = null;
      this.existingPolicy = "skip";
    },
    convertFileToJson() {
      this.loading.getPreviewData = true;
      this.error.uploadCsvFile = "";
      if (this.csvFile && this.csvFile.length > 0) {
        const file = this.csvFile[0].file;
        const reader = new FileReader();
        reader.onload = (e) => {
          try {
            const csvContent = e.target.result;
            const results = Papa.parse(csvContent, {
              header: false, // Important: no header, we process columns by index
              skipEmptyLines: true,
            });
            // Check if Papa parse encountered errors
            if (results.errors && results.errors.length > 0) {
              this.error.uploadCsvFile = "import_users.invalid_csv_format";
              this.loading.getPreviewData = false;
              return;
            }
            const headerString =
              "user,display_name,password,mail,groups,locked,must_change_password,no_password_expiration";
            if (
              results.data.length > 0 &&
              results.data[0].join(",") === headerString
            ) {
              results.data = results.data.slice(1);
            }
            let expectedColumns = this.tableColumns.length;
            for (let i = 0; i < results.data.length; i++) {
              if (results.data[i].length !== expectedColumns) {
                this.error.uploadCsvFile =
                  "import_users.invalid_csv_format_not_expected_columns";
                this.loading.getPreviewData = false;
                return;
              }
            }
            let COLUMN_MAPPING = {
              0: "user",
              1: "display_name",
              2: "password",
              3: "mail",
              4: "groups",
              5: "locked",
              6: "must_change_password",
              7: "no_password_expiration",
            };
            const booleanFields = [
              "locked",
              "must_change_password",
              "no_password_expiration",
            ];
            this.importData = results.data.map((row) => {
              const obj = {};
              Object.entries(COLUMN_MAPPING).forEach(([index, key]) => {
                let value = row[index];
                if (typeof value === "string") {
                  value = value.trim();
                }
                if (key === "groups") {
                  value = value
                    ? value
                        .split("|")
                        .map((g) => g.trim())
                        .filter((g) => g)
                    : [];
                } else if (booleanFields.includes(key)) {
                  value =
                    value === "true" || value === "1" || value === true
                      ? true
                      : false;
                } else if (value === "true") {
                  value = true;
                } else if (value === "false") {
                  value = false;
                }
                obj[key] = value;
              });
              return obj;
            });
            this.previewRows = this.importData.slice(0, 5);
            this.userCount = this.importData.length;
            if (this.userCount > 10000) {
              this.error.uploadCsvFile = "import_users.too_many_users";
              this.loading.getPreviewData = false;
              return;
            }
            const uniqueGroups = new Set();
            this.importData.forEach((user) => {
              user.groups.forEach((group) => {
                uniqueGroups.add(group);
              });
            });
            this.groupCount = uniqueGroups.size;
          } catch (err) {
            console.error("Error converting CSV to JSON:", err);
            this.error.uploadCsvFile = "import_users.invalid_csv_format";
          } finally {
            this.loading.getPreviewData = false;
          }
        };
        reader.onerror = () => {
          console.error("Error reading file");
          this.error.uploadCsvFile = "import_users.file_read_error";
          this.loading.getPreviewData = false;
        };
        reader.readAsText(file);
      } else {
        this.importData = [];
        this.previewRows = [];
        this.loading.getPreviewData = false;
      }
    },
    nextStep() {
      if (this.isNextButtonDisabled) {
        return;
      }
      if (this.isLastStep) {
        this.importDataCsv();
      } else {
        this.step = this.steps[this.stepIndex + 1];
      }
    },
    previousStep() {
      if (!this.isFirstStep) {
        this.step = this.steps[this.stepIndex - 1];
      }
    },
    async importDataCsv() {
      this.loading.uploadCsvFile = true;
      this.error.importDataCsv = "";
      const taskAction = "import-users";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.importDataAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.importDataCompleted
      );
      this.$root.$once(
        `${taskAction}-validation-ok-${eventId}`,
        this.importDataValidationOk
      );
      this.$root.$once(
        `${taskAction}-validation-failed-${eventId}`,
        this.importDataValidationFailed
      );
      const res = await to(
        this.createModuleTaskForApp(this.mainProvider, {
          action: taskAction,
          data: {
            skip_existing: this.existingPolicy === "skip",
            records: this.importData,
          },
          extra: {
            title: this.$t("action.import-users"),
            description: this.$t("import_users.importing_data_on_domain_name", {
              name: this.domain.name,
            }),
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.importDataCsv = this.getErrorMessage(err);
        this.loading.uploadCsvFile = false;
        return;
      }
      this.$emit("hide");
    },
    importDataAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.loading.uploadCsvFile = false;
    },
    importDataCompleted() {
      this.loading.uploadCsvFile = false;
      this.$emit("reloadDomains");
    },
    importDataValidationOk() {
      this.loading.uploadCsvFile = false;
      this.onModalHidden();
    },
    importDataValidationFailed() {
      this.loading.uploadCsvFile = false;
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
.font-bold {
  font-weight: bold;
}
.validation-failed-invalid-message {
  margin-bottom: 10px;
  margin-left: 0;
  padding-bottom: $spacing-05;
  font-size: 12px;
  font-weight: 600;
  color: #da1e28;
}
.file-uploader-wrapper {
  ::v-deep .bx--file-container {
    border: 2px solid #da1e28;
    border-radius: 4px;
    padding: $spacing-02;
    max-width: 320px;
  }
}
.progress {
  margin-top: 1rem;
  margin-bottom: 3rem;
}
</style>
</file>

<file path="core/ui/src/components/error/TaskErrorInfo.vue">
<template>
  <div>
    <h6 class="mg-top-lg mg-bottom-sm">
      {{ taskTitle }}
    </h6>
    <div>
      {{ $t("task.task_id") }}:
      <cv-tooltip
        alignment="center"
        direction="top"
        :tip="
          justCopied
            ? $t('common.copied_to_clipboard')
            : $t('common.copy_to_clipboard')
        "
      >
        <cv-link
          v-clipboard:copy="task.context.id"
          v-clipboard:success="onCopy"
          v-clipboard:error="onCopyError"
        >
          {{ task.context.id }}
        </cv-link></cv-tooltip
      >
    </div>
    <div
      v-if="task.result && task.result.error && task.result.exit_code != 0"
      class="mg-top-sm"
    >
      <NsCodeSnippet
        :copyTooltip="$t('common.copy_to_clipboard')"
        :copy-feedback="$t('common.copied_to_clipboard')"
        :feedback-aria-label="$t('common.copied_to_clipboard')"
        :wrap-text="true"
        :moreText="$t('common.show_more')"
        :lessText="$t('common.show_less')"
        light
        >{{ task.result.error }}</NsCodeSnippet
      >
    </div>
    <TaskErrorInfoHierarchy
      v-if="task.subTasks.length"
      :subTasks="task.subTasks"
    >
    </TaskErrorInfoHierarchy>
  </div>
</template>
⋮----
{{ taskTitle }}
⋮----
{{ $t("task.task_id") }}:
⋮----
{{ task.context.id }}
⋮----
>{{ task.result.error }}</NsCodeSnippet
⋮----
<script>
import { TaskService } from "@nethserver/ns8-ui-lib";
import TaskErrorInfoHierarchy from "./TaskErrorInfoHierarchy";
export default {
  name: "TaskErrorInfo",
  mixins: [TaskService],
  components: { TaskErrorInfoHierarchy },
  props: {
    task: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      justCopied: false,
    };
  },
  computed: {
    taskTitle() {
      const agent = this.task.context.queue
        ? this.task.context.queue.split("/tasks")[0]
        : "cluster";
      return `${agent}/${this.task.context.action}`;
    },
  },
  methods: {
    onCopy() {
      this.justCopied = true;
      setTimeout(() => {
        this.justCopied = false;
      }, 3000);
    },
    onCopyError() {
      console.error("cannot copy to clipboard");
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
</style>
</file>

<file path="core/ui/src/components/error/TaskErrorInfoHierarchy.vue">
<template>
  <div class="mg-left-07">
    <div v-for="task in subTasks" :key="task.context.id">
      <TaskErrorInfo :task="task" />
    </div>
  </div>
</template>
⋮----
<script>
import { TaskService } from "@nethserver/ns8-ui-lib";
export default {
  name: "TaskErrorInfoHierarchy",
  mixins: [TaskService],
  components: {},
  props: {
    subTasks: {
      type: Array,
      required: true,
    },
  },
  beforeCreate: function () {
    this.$options.components.TaskErrorInfo =
      require("./TaskErrorInfo.vue").default;
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
.mg-left-07 {
  margin-left: $spacing-07;
}
</style>
</file>

<file path="core/ui/src/components/error/TaskErrorModal.vue">
<template>
  <NsModal
    size="default"
    :visible="isTaskErrorShown"
    @modal-hidden="taskErrorModalHidden"
    @primary-click="onPrimaryClick"
    class="task-error-modal"
  >
    <template slot="title">{{ getTaskTitle(taskErrorToShow) }}</template>
    <template slot="content" v-if="taskErrorToShow">
      <div class="task-item">
        <component
          :is="getTaskIcon(taskErrorToShow)"
          :class="`bx--inline-notification__icon ${taskErrorToShow.status} task-icon`"
        />
        <div>
          <span>{{ getTaskStatusDescription(taskErrorToShow, true) }}</span>
        </div>
      </div>
      <div v-if="subTasks.length">
        <TaskTreeHierarchy
          :subTasks="subTasks"
          :isMoreInfoShown="isMoreInfoShown"
          class="task-hierarchy"
        />
      </div>
      <cv-tooltip
        alignment="center"
        direction="right"
        :tip="
          justCopied
            ? $t('common.copied_to_clipboard')
            : $t('common.copy_to_clipboard')
        "
        class="mg-top-md"
      >
        <cv-link
          v-clipboard:copy="JSON.stringify(taskErrorToShow)"
          v-clipboard:success="onCopy"
          v-clipboard:error="onCopyError"
        >
          {{ $t("task.copy_task_data_to_clipboard") }}
        </cv-link></cv-tooltip
      >
      <cv-toggle
        value="moreInfoValue"
        :form-item="true"
        v-model="isMoreInfoShown"
        hide-label
        class="mg-top-sm mg-bottom-md"
      >
        <template slot="text-left">{{ $t("common.more_info") }}</template>
        <template slot="text-right">{{ $t("common.more_info") }}</template>
      </cv-toggle>
      <template v-if="isMoreInfoShown">
        <TaskErrorInfo :task="taskErrorToShow" />
      </template>
    </template>
    <template v-if="isLogAvailable">
      <template slot="secondary-button">{{ $t("common.close") }}</template>
      <template slot="primary-button">{{
        $t("common.view_instance_logs", {
          instance: taskErrorToShow.context.extra.logs.instance,
        })
      }}</template>
    </template>
    <template v-else>
      <template slot="primary-button">{{ $t("common.close") }}</template>
    </template>
  </NsModal>
</template>
⋮----
<template slot="title">{{ getTaskTitle(taskErrorToShow) }}</template>
<template slot="content" v-if="taskErrorToShow">
      <div class="task-item">
        <component
          :is="getTaskIcon(taskErrorToShow)"
          :class="`bx--inline-notification__icon ${taskErrorToShow.status} task-icon`"
        />
        <div>
          <span>{{ getTaskStatusDescription(taskErrorToShow, true) }}</span>
        </div>
      </div>
      <div v-if="subTasks.length">
        <TaskTreeHierarchy
          :subTasks="subTasks"
          :isMoreInfoShown="isMoreInfoShown"
          class="task-hierarchy"
        />
      </div>
      <cv-tooltip
        alignment="center"
        direction="right"
        :tip="
          justCopied
            ? $t('common.copied_to_clipboard')
            : $t('common.copy_to_clipboard')
        "
        class="mg-top-md"
      >
        <cv-link
          v-clipboard:copy="JSON.stringify(taskErrorToShow)"
          v-clipboard:success="onCopy"
          v-clipboard:error="onCopyError"
        >
          {{ $t("task.copy_task_data_to_clipboard") }}
        </cv-link></cv-tooltip
      >
      <cv-toggle
        value="moreInfoValue"
        :form-item="true"
        v-model="isMoreInfoShown"
        hide-label
        class="mg-top-sm mg-bottom-md"
      >
        <template slot="text-left">{{ $t("common.more_info") }}</template>
        <template slot="text-right">{{ $t("common.more_info") }}</template>
      </cv-toggle>
      <template v-if="isMoreInfoShown">
        <TaskErrorInfo :task="taskErrorToShow" />
      </template>
    </template>
⋮----
<span>{{ getTaskStatusDescription(taskErrorToShow, true) }}</span>
⋮----
{{ $t("task.copy_task_data_to_clipboard") }}
⋮----
<template slot="text-left">{{ $t("common.more_info") }}</template>
<template slot="text-right">{{ $t("common.more_info") }}</template>
⋮----
<template v-if="isMoreInfoShown">
        <TaskErrorInfo :task="taskErrorToShow" />
      </template>
⋮----
<template v-if="isLogAvailable">
      <template slot="secondary-button">{{ $t("common.close") }}</template>
      <template slot="primary-button">{{
        $t("common.view_instance_logs", {
          instance: taskErrorToShow.context.extra.logs.instance,
        })
      }}</template>
    </template>
⋮----
<template slot="secondary-button">{{ $t("common.close") }}</template>
<template slot="primary-button">{{
        $t("common.view_instance_logs", {
          instance: taskErrorToShow.context.extra.logs.instance,
        })
      }}</template>
⋮----
<template v-else>
      <template slot="primary-button">{{ $t("common.close") }}</template>
    </template>
⋮----
<template slot="primary-button">{{ $t("common.close") }}</template>
⋮----
<script>
import { mapState } from "vuex";
import TaskTreeHierarchy from "./TaskTreeHierarchy";
import TaskErrorInfoHierarchy from "./TaskErrorInfoHierarchy";
import TaskErrorInfo from "./TaskErrorInfo";
import {
  TaskService,
  StorageService,
  IconService,
} from "@nethserver/ns8-ui-lib";
export default {
  name: "TaskErrorModal",
  components: { TaskTreeHierarchy, TaskErrorInfoHierarchy, TaskErrorInfo },
  mixins: [TaskService, StorageService, IconService],
  props: {},
  data() {
    return {
      isMoreInfoShown: false,
      justCopied: false,
    };
  },
  computed: {
    ...mapState(["taskErrorToShow", "isTaskErrorShown"]),
    subTasks: function () {
      if (this.taskErrorToShow && this.taskErrorToShow.subTasks) {
        return this.taskErrorToShow.subTasks;
      } else {
        return [];
      }
    },
    isLogAvailable: function () {
      return (
        this.taskErrorToShow &&
        this.taskErrorToShow.context &&
        this.taskErrorToShow.context.extra &&
        this.taskErrorToShow.context.extra.logs
      );
    },
  },
  watch: {
    taskErrorToShow: function () {
      if (this.taskErrorToShow) {
        this.isMoreInfoShown = false;
      }
    },
  },
  methods: {
    taskErrorModalHidden() {
      this.$emit("hide");
    },
    getTaskError() {
      if (this.taskErrorToShow && this.taskErrorToShow.subTasks) {
        return this.taskErrorToShow.result.error;
      } else {
        return "";
      }
    },
    onCopy() {
      this.justCopied = true;
      setTimeout(() => {
        this.justCopied = false;
      }, 3000);
    },
    onCopyError() {
      console.error("cannot copy to clipboard");
    },
    goToLogs() {
      this.$router.push(
        "/system-logs" + this.taskErrorToShow.context.extra.logs.path
      );
      this.$emit("hide");
    },
    onPrimaryClick() {
      if (this.isLogAvailable) {
        this.goToLogs();
      } else {
        this.$emit("hide");
      }
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
.task-hierarchy {
  margin-left: -0.8rem;
}
</style>
⋮----
<style lang="scss">
@import "../../styles/carbon-utils";
.task-error-modal .bx--modal-content {
  margin-top: $spacing-05;
}
.task-error-modal .bx--inline-notification__icon {
  margin-top: 0;
  margin-right: $spacing-02;
  fill: $support-04;
}
.task-error-modal .bx--inline-notification__icon.aborted,
.task-error-modal .bx--inline-notification__icon.validation-failed {
  fill: $danger-01;
}
.task-error-modal .bx--inline-notification__icon.completed {
  fill: $support-02;
}
.task-error-modal .bx--inline-notification__icon.pending {
  fill: $support-03;
}
.task-error-modal .task-item {
  display: flex;
  align-items: center;
  padding-top: 0.5rem;
  padding-bottom: 0.5rem;
}
</style>
</file>

<file path="core/ui/src/components/error/TaskTreeHierarchy.vue">
<template>
  <ul>
    <li v-for="(subTask, index) in subTasks" :key="index">
      <div class="task-item">
        <component
          :is="getTaskIcon(subTask)"
          :class="`bx--inline-notification__icon ${subTask.status}`"
        />
        <span>
          <span>{{ getTaskStatusDescription(subTask, false) }}</span>
        </span>
      </div>
      <TaskTreeHierarchy
        v-if="subTask.subTasks.length"
        :subTasks="subTask.subTasks"
        :isMoreInfoShown="isMoreInfoShown"
      />
    </li>
  </ul>
</template>
⋮----
<span>{{ getTaskStatusDescription(subTask, false) }}</span>
⋮----
<script>
import { TaskService } from "@nethserver/ns8-ui-lib";
export default {
  name: "TaskTreeHierarchy",
  mixins: [TaskService],
  components: {},
  props: {
    subTasks: {
      type: Array,
      required: true,
    },
    isMoreInfoShown: Boolean,
  },
  data() {
    return {
      justCopied: false,
    };
  },
  methods: {
    onCopy() {
      this.justCopied = true;
      setTimeout(() => {
        this.justCopied = false;
      }, 3000);
    },
    onCopyError() {
      console.error("cannot copy to clipboard");
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
ul {
  padding: 0;
  margin: 0;
  list-style-type: none;
  position: relative;
}
li {
  list-style-type: none;
  border-left: 1px solid #000;
  margin-left: 1.3rem;
}
li div {
  padding-left: 1em;
  position: relative;
}
li div::before {
  content: "";
  position: absolute;
  top: 0;
  left: -1px;
  bottom: 50%;
  width: 0.75em;
  border: 1px solid #000;
  border-top: 0 none transparent;
  border-right: 0 none transparent;
}
ul > li:last-child {
  border-left: 1px solid transparent;
}
</style>
</file>

<file path="core/ui/src/components/initialize-cluster/SetFqdn.vue">
<template>
  <div>
    <cv-row>
      <cv-column class="welcome">
        <div>
          <h2>
            {{
              action === "create"
                ? $t("init.create_cluster")
                : $t("init.join_cluster")
            }}
          </h2>
          <div class="title-description">
            {{
              action === "create"
                ? $t("init.create_cluster_description")
                : $t("init.join_cluster_description")
            }}
          </div>
        </div>
        <WelcomeLogo />
      </cv-column>
    </cv-row>
    <cv-row>
      <cv-column>
        <NsInlineNotification
          kind="info"
          :title="
            $t(
              action === 'create'
                ? 'init.review_leader_fqdn_title'
                : 'init.review_worker_fqdn_title'
            )
          "
          :description="
            $t(
              action === 'create'
                ? 'init.review_leader_fqdn_description'
                : 'init.review_worker_fqdn_description'
            )
          "
          :showCloseButton="false"
        />
      </cv-column>
    </cv-row>
    <cv-row>
      <cv-column>
        <cv-tile light>
          <NsInlineNotification
            v-if="error.getFqdn"
            kind="error"
            :title="$t('action.get-fqdn')"
            :description="error.getFqdn"
            :showCloseButton="false"
          />
          <cv-form v-else @submit.prevent="setFqdn">
            <cv-skeleton-text
              v-if="loading.getFqdn"
              :paragraph="true"
              :line-count="5"
              heading
            ></cv-skeleton-text>
            <template v-else>
              <cv-text-input
                :label="
                  action === 'create'
                    ? $t('init.leader_node_hostname')
                    : $t('init.worker_node_hostname')
                "
                v-model.trim="hostname"
                :invalid-message="error.hostname"
                :disabled="loading.getFqdn || loading.setFqdn"
                ref="hostname"
              >
              </cv-text-input>
              <cv-text-input
                :label="
                  action === 'create'
                    ? $t('init.leader_node_domain')
                    : $t('init.worker_node_domain')
                "
                v-model.trim="domain"
                placeholder="example.org"
                :invalid-message="error.domain"
                :disabled="loading.getFqdn || loading.setFqdn"
                ref="domain"
              >
              </cv-text-input>
            </template>
            <cv-button-set class="footer-buttons">
              <NsButton
                type="button"
                kind="secondary"
                :icon="ChevronLeft20"
                size="lg"
                @click="goBack"
                >{{ $t("common.go_back") }}
              </NsButton>
              <NsButton
                kind="primary"
                :icon="ChevronRight20"
                :loading="loading.setFqdn"
                :disabled="loading.getFqdn || loading.setFqdn"
                size="lg"
                >{{ $t("init.set_fqdn") }}
              </NsButton>
            </cv-button-set>
          </cv-form>
          <NsInlineNotification
            v-if="error.setFqdn"
            kind="error"
            :title="$t('action.set-fqdn')"
            :description="error.setFqdn"
            :showCloseButton="false"
          />
        </cv-tile>
      </cv-column>
    </cv-row>
  </div>
</template>
⋮----
{{
              action === "create"
                ? $t("init.create_cluster")
                : $t("init.join_cluster")
            }}
⋮----
{{
              action === "create"
                ? $t("init.create_cluster_description")
                : $t("init.join_cluster_description")
            }}
⋮----
<template v-else>
              <cv-text-input
                :label="
                  action === 'create'
                    ? $t('init.leader_node_hostname')
                    : $t('init.worker_node_hostname')
                "
                v-model.trim="hostname"
                :invalid-message="error.hostname"
                :disabled="loading.getFqdn || loading.setFqdn"
                ref="hostname"
              >
              </cv-text-input>
              <cv-text-input
                :label="
                  action === 'create'
                    ? $t('init.leader_node_domain')
                    : $t('init.worker_node_domain')
                "
                v-model.trim="domain"
                placeholder="example.org"
                :invalid-message="error.domain"
                :disabled="loading.getFqdn || loading.setFqdn"
                ref="domain"
              >
              </cv-text-input>
            </template>
⋮----
>{{ $t("common.go_back") }}
⋮----
>{{ $t("init.set_fqdn") }}
⋮----
<script>
import { UtilService, IconService, TaskService } from "@nethserver/ns8-ui-lib";
import to from "await-to-js";
import WelcomeLogo from "@/components/initialize-cluster/WelcomeLogo";
export default {
  name: "SetFqdn",
  components: { WelcomeLogo },
  mixins: [UtilService, IconService, TaskService],
  props: {
    action: String,
  },
  data() {
    return {
      hostname: "",
      domain: "",
      loading: {
        getFqdn: false,
        setFqdn: false,
      },
      error: {
        getFqdn: "",
        setFqdn: "",
        hostname: "",
        domain: "",
      },
    };
  },
  created() {
    this.getFqdn();
  },
  methods: {
    async getFqdn() {
      this.error.getFqdn = "";
      this.loading.getFqdn = true;
      const taskAction = "get-fqdn";
      const eventId = this.getUuid();
      this.$root.$once(`${taskAction}-aborted-${eventId}`, this.getFqdnAborted);
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.getFqdnCompleted
      );
      const res = await to(
        this.createNodeTask(1, {
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            toastTimeout: 0,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        const notification = {
          title: this.$t("task.cannot_create_task", { action: taskAction }),
          description: this.getErrorMessage(err),
          type: "error",
          toastTimeout: 0,
        };
        this.createNotification(notification);
        return;
      }
    },
    getFqdnCompleted(taskContext, taskResult) {
      this.hostname = taskResult.output.hostname;
      this.domain = taskResult.output.domain;
      this.loading.getFqdn = false;
      this.focusElement("hostname");
    },
    getFqdnAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.loading.getFqdn = false;
    },
    validateSetFqdn() {
      this.error.hostname = "";
      this.error.domain = "";
      let isValidationOk = true;
      // hostname
      if (!this.hostname) {
        this.error.hostname = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("hostname");
          isValidationOk = false;
        }
      }
      if (!this.domain) {
        this.error.domain = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("domain");
          isValidationOk = false;
        }
      }
      return isValidationOk;
    },
    async setFqdn() {
      if (!this.validateSetFqdn()) {
        return;
      }
      this.loading.setFqdn = true;
      this.error.setFqdn = "";
      const taskAction = "set-fqdn";
      const eventId = this.getUuid();
      this.$root.$once(`${taskAction}-aborted-${eventId}`, this.setFqdnAborted);
      this.$root.$once(
        `${taskAction}-validation-failed-${eventId}`,
        this.setFqdnValidationFailed
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.setFqdnCompleted
      );
      const res = await to(
        this.createNodeTask(1, {
          action: taskAction,
          data: {
            hostname: this.hostname,
            domain: this.domain,
          },
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            toastTimeout: 0,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.setFqdn = this.getErrorMessage(err);
        this.loading.setFqdn = false;
        return;
      }
    },
    setFqdnAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.loading.setFqdn = false;
    },
    setFqdnValidationFailed(validationErrors) {
      this.loading.setFqdn = false;
      let focusAlreadySet = false;
      for (const validationError of validationErrors) {
        const param = validationError.parameter;
        this.error[param] = this.getI18nStringWithFallback(
          "init." + validationError.error,
          "error." + validationError.error
        );
        if (!focusAlreadySet) {
          this.focusElement(param);
          focusAlreadySet = true;
        }
      }
    },
    setFqdnCompleted() {
      this.loading.setFqdn = false;
      this.$emit("fqdnSet");
    },
    goBack() {
      this.$emit("goBack");
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
</style>
</file>

<file path="core/ui/src/components/initialize-cluster/SkipRestoreAppsModal.vue">
<template>
  <NsModal
    size="default"
    :visible="isShown"
    @modal-hidden="$emit('hide')"
    @primary-click="$emit('confirm')"
  >
    <template slot="title">{{ $t("init.skip_apps_restore") }}</template>
    <template slot="content">
      <div class="mg-bottom-md">{{ $t("init.skip_apps_restore_1") }}</div>
      <div>{{ $t("init.skip_apps_restore_2") }}</div>
    </template>
    <template slot="secondary-button">{{ $t("common.cancel") }}</template>
    <template slot="primary-button">{{
      $t("init.skip_apps_restore")
    }}</template>
  </NsModal>
</template>
⋮----
<template slot="title">{{ $t("init.skip_apps_restore") }}</template>
<template slot="content">
      <div class="mg-bottom-md">{{ $t("init.skip_apps_restore_1") }}</div>
      <div>{{ $t("init.skip_apps_restore_2") }}</div>
    </template>
⋮----
<div class="mg-bottom-md">{{ $t("init.skip_apps_restore_1") }}</div>
<div>{{ $t("init.skip_apps_restore_2") }}</div>
⋮----
<template slot="secondary-button">{{ $t("common.cancel") }}</template>
<template slot="primary-button">{{
      $t("init.skip_apps_restore")
    }}</template>
⋮----
<script>
import { UtilService, IconService } from "@nethserver/ns8-ui-lib";
export default {
  name: "SkipRestoreAppsModal",
  mixins: [UtilService, IconService],
  props: {
    isShown: Boolean,
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
</style>
</file>

<file path="core/ui/src/components/initialize-cluster/WelcomeLogo.vue">
<template>
  <div class="logo">
    <img
      :src="require('@/assets/logo.png')"
      :alt="this.$root.config.PRODUCT_NAME + ' logo'"
    />
  </div>
</template>
⋮----
<script>
import { UtilService, IconService } from "@nethserver/ns8-ui-lib";
export default {
  name: "WelcomeLogo",
  mixins: [UtilService, IconService],
  props: {
    isShown: Boolean,
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
.logo {
  height: 4rem;
  flex-shrink: 0;
}
.logo img {
  width: 100%;
  height: 100%;
}
</style>
</file>

<file path="core/ui/src/components/nodes/NewLeaderModal.vue">
<template>
  <NsModal
    size="default"
    :visible="isShown"
    @modal-hidden="$emit('hide')"
    @primary-click="goToClusterAdmin()"
  >
    <template slot="title">{{ $t("nodes.promote_node_to_leader") }}</template>
    <template slot="content">
      <NsInlineNotification
        kind="success"
        :title="$t('nodes.promotion_completed')"
        :description="
          $t('nodes.new_cluster_admin_message', {
            endpointAddress,
          })
        "
        :showCloseButton="false"
      />
    </template>
    <template slot="primary-button">{{
      $t("nodes.go_to_cluster_admin")
    }}</template>
  </NsModal>
</template>
⋮----
<template slot="title">{{ $t("nodes.promote_node_to_leader") }}</template>
<template slot="content">
      <NsInlineNotification
        kind="success"
        :title="$t('nodes.promotion_completed')"
        :description="
          $t('nodes.new_cluster_admin_message', {
            endpointAddress,
          })
        "
        :showCloseButton="false"
      />
    </template>
<template slot="primary-button">{{
      $t("nodes.go_to_cluster_admin")
    }}</template>
⋮----
<script>
import { UtilService, IconService } from "@nethserver/ns8-ui-lib";
export default {
  name: "NewLeaderModal",
  mixins: [UtilService, IconService],
  props: {
    isShown: Boolean,
    endpointAddress: {
      type: String,
      required: true,
    },
  },
  methods: {
    goToClusterAdmin() {
      window.location.href = `https://${this.endpointAddress}/cluster-admin/`;
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
</style>
</file>

<file path="core/ui/src/components/nodes/NodeCard.vue">
<template>
  <cv-tile kind="standard" :light="light" class="node-card ns-card">
    <slot name="menu"></slot>
    <div class="row">
      <NsSvg :svg="Chip32" />
    </div>
    <div class="row">
      <h3 class="title ellipsis">
        {{
          nodeLabel ? nodeLabel : $t("common.node") + " " + nodeId.toString()
        }}
      </h3>
    </div>
    <div class="row">
      <cv-tag v-if="isLeader" kind="green" :label="leaderLabel"></cv-tag>
      <cv-tag
        v-else-if="role === 'ns7migration'"
        kind="gray"
        :label="ns7MigrationLabel"
      ></cv-tag>
      <cv-tag v-else kind="blue" :label="workerLabel"></cv-tag>
    </div>
    <div v-if="!online" class="row offline">
      <NsInlineNotification
        kind="error"
        :title="$t('nodes.node_is_offline')"
        :showCloseButton="false"
      />
    </div>
    <div v-else-if="loading" class="row node-card-skeleton">
      <cv-skeleton-text
        :paragraph="true"
        :line-count="6"
        heading
      ></cv-skeleton-text>
    </div>
    <div
      v-else-if="!loading && online && role !== 'ns7migration'"
      class="table-wrapper"
    >
      <div class="table">
        <div v-if="nodeLabel" class="tr">
          <div class="td label">{{ $t("nodes.node_id") }}</div>
          <div class="td">
            {{ nodeId }}
          </div>
        </div>
        <div class="tr long-text-row">
          <div class="td label">{{ fqdnLabel }}</div>
          <div class="td long-text-cell">
            <cv-interactive-tooltip
              v-if="isLongFqdn"
              alignment="center"
              direction="top"
            >
              <template slot="content">
                {{ fqdn }}
              </template>
              <template slot="trigger">
                <span class="long-text-ellipsis long-text-span">{{
                  fqdn
                }}</span>
              </template>
            </cv-interactive-tooltip>
            <span v-else class="long-text-ellipsis long-text-span">{{
              fqdn
            }}</span>
          </div>
        </div>
        <div class="tr long-text-row">
          <div class="td label">{{ $t("nodes.ip_address") }}</div>
          <div class="td long-text-cell">
            <cv-interactive-tooltip
              v-if="isLongIpAddress"
              alignment="center"
              direction="top"
            >
              <template slot="content">
                {{ ip_address }}
              </template>
              <template slot="trigger">
                <span class="long-text-ellipsis long-text-span">{{
                  ip_address
                }}</span>
              </template>
            </cv-interactive-tooltip>
            <span v-else class="long-text-ellipsis long-text-span">{{
              ip_address
            }}</span>
          </div>
        </div>
        <div class="tr">
          <div class="td label">{{ $t("nodes.applications") }}</div>
          <div class="td">
            <cv-link v-if="applications" @click.prevent="goToApplications">
              {{ applications }}
            </cv-link>
            <span v-else>-</span>
          </div>
        </div>
      </div>
    </div>
    <template v-if="!loading && online && role === 'ns7migration'">
      <div v-if="nodeLabel" class="tr mg-top-sm">
        <div class="td label">{{ $t("nodes.node_id") }}</div>
        <div class="td">
          {{ nodeId }}
        </div>
      </div>
      <div class="row mg-top-sm simple-field">
        <div class="mg-top-sm icon-and-text-compact mg-bottom-lg">
          <cv-interactive-tooltip
            alignment="center"
            direction="top"
            class="icon ns-info"
          >
            <template slot="content">
              {{ $t("nodes.ns7_migration_tooltip") }}
            </template>
            <template slot="trigger">
              <NsSvg :svg="InformationFilled16" class="icon ns-info" />
            </template>
          </cv-interactive-tooltip>
          <span>{{ $t("nodes.ns7_migration_in_progress") }}</span>
        </div>
      </div>
    </template>
    <template v-if="!loading && online && role !== 'ns7migration'">
      <div class="card-row icon-and-text mg-top-md">
        <NsSvg
          :svg="alertsCount > 0 ? Warning16 : CheckmarkFilled16"
          :class="alertsCount > 0 ? 'icon ns-warning' : 'icon ns-success'"
        />
        <span>
          <template v-if="alertsCount > 0">
            {{ alertsCount }} {{ alertsLabel }}
          </template>
          <template v-else>
            {{ $t("nodes.no_alerts") }}
          </template>
        </span>
      </div>
    </template>
    <div class="row slot">
      <slot name="content"></slot>
    </div>
  </cv-tile>
</template>
⋮----
{{
          nodeLabel ? nodeLabel : $t("common.node") + " " + nodeId.toString()
        }}
⋮----
<div class="td label">{{ $t("nodes.node_id") }}</div>
⋮----
{{ nodeId }}
⋮----
<div class="td label">{{ fqdnLabel }}</div>
⋮----
<template slot="content">
                {{ fqdn }}
              </template>
⋮----
{{ fqdn }}
⋮----
<template slot="trigger">
                <span class="long-text-ellipsis long-text-span">{{
                  fqdn
                }}</span>
              </template>
⋮----
<span class="long-text-ellipsis long-text-span">{{
                  fqdn
                }}</span>
⋮----
<span v-else class="long-text-ellipsis long-text-span">{{
              fqdn
            }}</span>
⋮----
<div class="td label">{{ $t("nodes.ip_address") }}</div>
⋮----
<template slot="content">
                {{ ip_address }}
              </template>
⋮----
{{ ip_address }}
⋮----
<template slot="trigger">
                <span class="long-text-ellipsis long-text-span">{{
                  ip_address
                }}</span>
              </template>
⋮----
<span class="long-text-ellipsis long-text-span">{{
                  ip_address
                }}</span>
⋮----
<span v-else class="long-text-ellipsis long-text-span">{{
              ip_address
            }}</span>
⋮----
<div class="td label">{{ $t("nodes.applications") }}</div>
⋮----
{{ applications }}
⋮----
<template v-if="!loading && online && role === 'ns7migration'">
      <div v-if="nodeLabel" class="tr mg-top-sm">
        <div class="td label">{{ $t("nodes.node_id") }}</div>
        <div class="td">
          {{ nodeId }}
        </div>
      </div>
      <div class="row mg-top-sm simple-field">
        <div class="mg-top-sm icon-and-text-compact mg-bottom-lg">
          <cv-interactive-tooltip
            alignment="center"
            direction="top"
            class="icon ns-info"
          >
            <template slot="content">
              {{ $t("nodes.ns7_migration_tooltip") }}
            </template>
            <template slot="trigger">
              <NsSvg :svg="InformationFilled16" class="icon ns-info" />
            </template>
          </cv-interactive-tooltip>
          <span>{{ $t("nodes.ns7_migration_in_progress") }}</span>
        </div>
      </div>
    </template>
⋮----
<div class="td label">{{ $t("nodes.node_id") }}</div>
⋮----
{{ nodeId }}
⋮----
<template slot="content">
              {{ $t("nodes.ns7_migration_tooltip") }}
            </template>
⋮----
{{ $t("nodes.ns7_migration_tooltip") }}
⋮----
<template slot="trigger">
              <NsSvg :svg="InformationFilled16" class="icon ns-info" />
            </template>
⋮----
<span>{{ $t("nodes.ns7_migration_in_progress") }}</span>
⋮----
<template v-if="!loading && online && role !== 'ns7migration'">
      <div class="card-row icon-and-text mg-top-md">
        <NsSvg
          :svg="alertsCount > 0 ? Warning16 : CheckmarkFilled16"
          :class="alertsCount > 0 ? 'icon ns-warning' : 'icon ns-success'"
        />
        <span>
          <template v-if="alertsCount > 0">
            {{ alertsCount }} {{ alertsLabel }}
          </template>
          <template v-else>
            {{ $t("nodes.no_alerts") }}
          </template>
        </span>
      </div>
    </template>
⋮----
<template v-if="alertsCount > 0">
            {{ alertsCount }} {{ alertsLabel }}
          </template>
⋮----
{{ alertsCount }} {{ alertsLabel }}
⋮----
<template v-else>
            {{ $t("nodes.no_alerts") }}
          </template>
⋮----
{{ $t("nodes.no_alerts") }}
⋮----
<script>
import { UtilService, IconService } from "@nethserver/ns8-ui-lib";
export default {
  name: "NodeCard",
  mixins: [UtilService, IconService],
  props: {
    nodeId: {
      type: Number,
      required: true,
    },
    nodeLabel: {
      type: String,
      default: "",
    },
    isLeader: Boolean,
    role: {
      type: String,
      default: "Worker",
    },
    leaderLabel: {
      type: String,
      default: "Leader",
    },
    workerLabel: {
      type: String,
      default: "Worker",
    },
    ns7MigrationLabel: {
      type: String,
      default: "Migrating",
    },
    fqdn: {
      type: String,
      default: "",
    },
    fqdnLabel: {
      type: String,
      default: "FQDN",
    },
    ip_addressLabel: {
      type: String,
      default: "IP addresses",
    },
    applicationsLabel: {
      type: String,
      default: "Applications",
    },
    ip_address: {
      type: String,
      default: "",
    },
    applications: {
      type: Number,
      default: 0,
    },
    alertsCount: {
      type: Number,
      default: 0,
    },
    alertsLabel: {
      type: String,
      default: "Alerts",
    },
    online: {
      type: Boolean,
      default: true,
    },
    loading: Boolean,
    light: Boolean,
    longTextThreshold: {
      type: Number,
      default: 32,
    },
  },
  data() {
    return {
      showAllDisks: false,
    };
  },
  computed: {
    isLongFqdn() {
      return this.fqdn && this.fqdn.length > this.longTextThreshold;
    },
    isLongIpAddress() {
      return this.ip_address && this.ip_address.length > this.longTextThreshold;
    },
  },
  methods: {
    goToApplications() {
      this.$router.push({
        path: "/applications-center",
        query: { selectedNodeId: this.nodeId },
      });
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
.node-card {
  display: flex;
  flex-direction: column;
  justify-content: center;
  min-height: 7rem;
  position: relative;
}
.node-card--ns7 {
  justify-content: flex-start;
  align-items: center;
}
.row {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 0.25rem;
}
.node-card-skeleton {
  margin: 1rem 3rem;
}
.label {
  padding-right: 0.75rem;
  font-weight: bold;
  text-align: right;
  padding-bottom: 0.5rem;
}
.slot {
  margin-top: 0.5rem;
}
.offline {
  margin-top: 1rem;
}
.show-all-disks {
  text-align: center;
}
.long-text-row {
  align-items: flex-start;
}
.long-text-cell {
  word-break: break-all;
  white-space: normal;
  overflow-wrap: anywhere;
  max-width: 100%;
  text-align: left;
  line-height: 1.3;
}
.long-text-ellipsis,
.long-text-span {
  display: inline-block;
  max-width: 10rem;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  vertical-align: bottom;
}
.icon-and-text-compact {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin-top: 0.5rem;
  margin-bottom: 0.5rem;
}
.icon-and-text-compact .icon {
  flex-shrink: 0;
  width: 1rem;
  height: 1rem;
}
</style>
</file>

<file path="core/ui/src/components/nodes/NodeSelector.vue">
<template>
  <div class="node-selector">
    <div class="card-grid grid-cols-1 sm:grid-cols-2 3xl:grid-cols-3">
      <NsTile
        v-for="node in internalNodes"
        :key="node.id"
        :light="true"
        kind="selectable"
        v-model="node.selected"
        value="nodeValue"
        :footerIcon="Chip20"
        @click="deselectOtherNodes(node)"
        class="min-height-card"
        :disabled="loading || disabledNodes.includes(node.id)"
      >
        <h6>
          <span v-if="node.ui_name">
            {{ node.ui_name }} ({{ $t("common.node") }} {{ node.id }})
          </span>
          <span v-else> {{ $t("common.node") }} {{ node.id }} </span>
        </h6>
        <cv-skeleton-text
          v-if="loading"
          :paragraph="true"
          :line-count="2"
          class="mg-top-lg"
        ></cv-skeleton-text>
        <div v-if="!loading && $slots[`node-${node.id}`]" class="mg-top-md">
          <slot :name="`node-${node.id}`"></slot>
        </div>
        <div
          v-if="!loading && nodesWithAdditionalStorage.includes(node.id)"
          class="node-tile-footer node-tile-footer-additional"
        >
          <div class="icon-text-container mg-top-sm">
            <VmdkDisk20 />
            {{ $t("software_center.additional_storage_available") }}
          </div>
        </div>
        <div
          v-if="
            !loading &&
            nodesDefaultDiskInfo[node.id] &&
            !nodesWithAdditionalStorage.includes(node.id)
          "
          class="node-tile-footer"
        >
          <div class="mg-top-sm">
            {{
              $t(
                "software_center.node_volume_usage_free_vs_total",
                getStorageInfo(nodesDefaultDiskInfo[node.id])
              )
            }}
          </div>
          <div class="mg-top-sm">
            {{
              $t(
                "software_center.node_volume_usage_percentage_used",
                getStorageInfo(nodesDefaultDiskInfo[node.id])
              )
            }}
          </div>
          <div class="mg-top-sm">
            <NsProgressBar
              :value="
                (nodesDefaultDiskInfo[node.id].used /
                  nodesDefaultDiskInfo[node.id].size) *
                100
              "
              :loading="loading"
              :warningThreshold="70"
              :dangerThreshold="90"
              :height="'5px'"
              :useHealthyColor="false"
            />
          </div>
        </div>
      </NsTile>
    </div>
  </div>
</template>
⋮----
{{ node.ui_name }} ({{ $t("common.node") }} {{ node.id }})
⋮----
<span v-else> {{ $t("common.node") }} {{ node.id }} </span>
⋮----
{{ $t("software_center.additional_storage_available") }}
⋮----
{{
              $t(
                "software_center.node_volume_usage_free_vs_total",
                getStorageInfo(nodesDefaultDiskInfo[node.id])
              )
            }}
⋮----
{{
              $t(
                "software_center.node_volume_usage_percentage_used",
                getStorageInfo(nodesDefaultDiskInfo[node.id])
              )
            }}
⋮----
<script>
import { UtilService, IconService } from "@nethserver/ns8-ui-lib";
import _cloneDeep from "lodash/cloneDeep";
import { mapState } from "vuex";
import VmdkDisk20 from "@carbon/icons-vue/es/vmdk-disk/20";
export default {
  name: "NodeSelector",
  components: {
    VmdkDisk20,
  },
  mixins: [UtilService, IconService],
  props: {
    disabledNodes: {
      type: Array,
      default: () => [],
    },
    nodesWithAdditionalStorage: {
      type: Array,
      default: () => [],
    },
    nodesDefaultDiskInfo: {
      type: Object,
      default: () => ({}),
    },
    loading: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      internalNodes: [],
    };
  },
  computed: {
    ...mapState(["clusterNodes"]),
    selectedNode() {
      return this.internalNodes.find((n) => n.selected);
    },
  },
  watch: {
    selectedNode: function () {
      this.$emit("selectNode", this.selectedNode);
    },
    disabledNodes: function () {
      this.updateNodes();
    },
  },
  created() {
    this.updateNodes();
  },
  methods: {
    updateNodes() {
      const nodes = _cloneDeep(this.clusterNodes);
      for (const node of nodes) {
        node.selected = false;
      }
      if (nodes.length == 1 && !this.disabledNodes.includes(nodes[0].id)) {
        nodes[0].selected = true;
      }
      this.internalNodes = nodes;
      this.$emit("selectNode", this.selectedNode);
    },
    deselectOtherNodes(node) {
      for (let n of this.internalNodes) {
        if (n.id !== node.id) {
          n.selected = false;
        }
      }
    },
    getStorageInfo(storage) {
      return {
        available: this.$options.filters.byteFormat(storage.available),
        used: this.$options.filters.byteFormat(storage.used),
        total: this.$options.filters.byteFormat(storage.size),
        percentage: Math.round((storage.used / storage.size) * 100),
      };
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
.icon-text-container {
  display: flex;
  align-items: flex-start;
  gap: 0.2rem;
  line-height: 1.5;
}
</style>
</file>

<file path="core/ui/src/components/nodes/PromoteNodeModal.vue">
<template>
  <NsModal
    size="default"
    :visible="isShown"
    :isLoading="loading.promoteNode"
    @modal-hidden="onModalHidden"
    @primary-click="promoteNode"
    :primary-button-disabled="userInput !== 'node' + (node ? node.id : '')"
  >
    <template slot="title">{{ $t("nodes.promote_node_to_leader") }}</template>
    <template slot="content">
      <NsInlineNotification
        kind="info"
        :title="$t('common.remember')"
        :description="$t('nodes.reset_backup_encryption_password_info')"
        :showCloseButton="false"
      />
      <div ref="getNodeInfoError">
        <NsInlineNotification
          v-if="error.getNodeInfo"
          kind="error"
          :title="$t('nodes.cannot_retrieve_node_info')"
          :description="error.getNodeInfo"
          :showCloseButton="false"
          class="mg-top-lg"
        />
      </div>
      <div>
        {{
          $t("nodes.promote_node_confirm", {
            name: node ? this.getNodeLabel(node) : "",
          })
        }}
      </div>
      <cv-skeleton-text
        v-if="loading.getNodeInfo"
        :paragraph="true"
        :line-count="10"
        heading
        class="mg-top-lg"
      ></cv-skeleton-text>
      <cv-form v-else @submit.prevent="promoteNode" class="mg-top-lg">
        <NsCheckbox
          :label="
            $t('nodes.check_node_connectivity_promote', {
              fqdn: this.vpnEndpointAddress,
            })
          "
          v-model="checkNodeConnectivity"
          :disabled="loading.promoteNode"
          value="checkNodeConnectivity"
        />
        <div class="mg-top-xlg">
          {{
            $t("nodes.type_to_confirm_promotion", {
              name: "node" + (node ? node.id : ""),
            })
          }}
        </div>
        <NsTextInput
          v-model="userInput"
          :disabled="loading.promoteNode"
          class="mg-bottom-md"
          ref="userInput"
        >
        </NsTextInput>
      </cv-form>
      <div ref="promoteNodeError">
        <NsInlineNotification
          v-if="error.promoteNode"
          kind="error"
          :title="$t('nodes.cannot_promote_node')"
          :description="error.promoteNode"
          :showCloseButton="false"
          class="mg-top-lg"
        />
      </div>
    </template>
    <template slot="secondary-button">{{ $t("common.cancel") }}</template>
    <template slot="primary-button">{{
      $t("nodes.understood_promote_node")
    }}</template>
  </NsModal>
</template>
⋮----
<template slot="title">{{ $t("nodes.promote_node_to_leader") }}</template>
<template slot="content">
      <NsInlineNotification
        kind="info"
        :title="$t('common.remember')"
        :description="$t('nodes.reset_backup_encryption_password_info')"
        :showCloseButton="false"
      />
      <div ref="getNodeInfoError">
        <NsInlineNotification
          v-if="error.getNodeInfo"
          kind="error"
          :title="$t('nodes.cannot_retrieve_node_info')"
          :description="error.getNodeInfo"
          :showCloseButton="false"
          class="mg-top-lg"
        />
      </div>
      <div>
        {{
          $t("nodes.promote_node_confirm", {
            name: node ? this.getNodeLabel(node) : "",
          })
        }}
      </div>
      <cv-skeleton-text
        v-if="loading.getNodeInfo"
        :paragraph="true"
        :line-count="10"
        heading
        class="mg-top-lg"
      ></cv-skeleton-text>
      <cv-form v-else @submit.prevent="promoteNode" class="mg-top-lg">
        <NsCheckbox
          :label="
            $t('nodes.check_node_connectivity_promote', {
              fqdn: this.vpnEndpointAddress,
            })
          "
          v-model="checkNodeConnectivity"
          :disabled="loading.promoteNode"
          value="checkNodeConnectivity"
        />
        <div class="mg-top-xlg">
          {{
            $t("nodes.type_to_confirm_promotion", {
              name: "node" + (node ? node.id : ""),
            })
          }}
        </div>
        <NsTextInput
          v-model="userInput"
          :disabled="loading.promoteNode"
          class="mg-bottom-md"
          ref="userInput"
        >
        </NsTextInput>
      </cv-form>
      <div ref="promoteNodeError">
        <NsInlineNotification
          v-if="error.promoteNode"
          kind="error"
          :title="$t('nodes.cannot_promote_node')"
          :description="error.promoteNode"
          :showCloseButton="false"
          class="mg-top-lg"
        />
      </div>
    </template>
⋮----
{{
          $t("nodes.promote_node_confirm", {
            name: node ? this.getNodeLabel(node) : "",
          })
        }}
⋮----
{{
            $t("nodes.type_to_confirm_promotion", {
              name: "node" + (node ? node.id : ""),
            })
          }}
⋮----
<template slot="secondary-button">{{ $t("common.cancel") }}</template>
<template slot="primary-button">{{
      $t("nodes.understood_promote_node")
    }}</template>
⋮----
<script>
import { TaskService, UtilService } from "@nethserver/ns8-ui-lib";
import to from "await-to-js";
export default {
  name: "PromoteNodeModal",
  mixins: [TaskService, UtilService],
  props: {
    isShown: {
      type: Boolean,
      default: true,
    },
    node: { type: Object },
  },
  data() {
    return {
      vpnEndpointAddress: "",
      vpnEndpointPort: "",
      userInput: "",
      checkNodeConnectivity: true,
      loading: {
        promoteNode: false,
        getNodeInfo: false,
      },
      error: {
        promoteNode: "",
        getNodeInfo: "",
        endpoint_address: "",
        endpoint_port: "",
      },
    };
  },
  watch: {
    isShown: function () {
      if (this.isShown) {
        this.userInput = "";
        this.clearErrors();
        this.getNodeInfo();
      }
    },
    "error.promoteNode": function () {
      if (this.error.promoteNode) {
        this.$nextTick(() => {
          const el = this.$refs.promoteNodeError;
          this.scrollToElement(el);
        });
      }
    },
    "error.getNodeInfo": function () {
      if (this.error.getNodeInfo) {
        this.$nextTick(() => {
          const el = this.$refs.getNodeInfoError;
          this.scrollToElement(el);
        });
      }
    },
  },
  methods: {
    onModalHidden() {
      this.$emit("hide");
    },
    async getNodeInfo() {
      this.error.getNodeInfo = "";
      this.loading.getNodeInfo = true;
      const taskAction = "get-info";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.getNodeInfoAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.getNodeInfoCompleted
      );
      const res = await to(
        this.createNodeTask(this.node.id, {
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.getNodeInfo = this.getErrorMessage(err);
        return;
      }
    },
    getNodeInfoAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.getNodeInfo = this.$t("error.generic_error");
      this.loading.getNodeInfo = false;
    },
    getNodeInfoCompleted(taskContext, taskResult) {
      this.vpnEndpointAddress = taskResult.output.hostname;
      this.vpnEndpointPort = taskResult.output.vpn_port;
      this.loading.getNodeInfo = false;
    },
    async promoteNode() {
      if (this.userInput !== "node" + this.node.id) {
        return;
      }
      this.clearErrors();
      this.loading.promoteNode = true;
      this.error.promoteNode = "";
      const taskAction = "promote-node";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.promoteNodeAborted
      );
      this.$root.$once(
        `${taskAction}-validation-failed-${eventId}`,
        this.promoteNodeValidationFailed
      );
      this.$root.$once(
        `${taskAction}-validation-ok-${eventId}`,
        this.promoteNodeValidationOk
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.promoteNodeCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {
            node_id: this.node.id,
            endpoint_address: this.vpnEndpointAddress,
            endpoint_port: this.vpnEndpointPort,
            endpoint_validation: this.checkNodeConnectivity,
          },
          extra: {
            title: this.$t("action." + taskAction),
            description: this.$t("common.processing"),
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.promoteNode = this.getErrorMessage(err);
        this.loading.promoteNode = false;
        return;
      }
    },
    promoteNodeAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.loading.promoteNode = false;
    },
    promoteNodeValidationOk() {
      this.$emit("hide");
    },
    promoteNodeValidationFailed(validationErrors) {
      this.loading.promoteNode = false;
      let focusAlreadySet = false;
      for (const validationError of validationErrors) {
        if (
          validationError.parameter === "node_id" ||
          validationError.error === "endpoint_address_not_reachable"
        ) {
          this.error.promoteNode = this.$t(
            "nodes.validation_" + validationError.error
          );
        } else {
          const param = validationError.parameter;
          this.error[param] = this.$t(
            "nodes.validation_" + validationError.error
          );
          if (!focusAlreadySet) {
            this.focusElement(param);
            focusAlreadySet = true;
          }
        }
      }
    },
    promoteNodeCompleted() {
      this.loading.promoteNode = false;
      this.$emit("hide");
      this.$emit("nodePromoted", this.vpnEndpointAddress);
    },
  },
};
</script>
⋮----
<style scoped lang="scss"></style>
</file>

<file path="core/ui/src/components/nodes/RemoveNodeModal.vue">
<template>
  <NsModal
    kind="danger"
    size="default"
    :visible="isShown"
    :isLoading="loading.removeNode"
    @modal-hidden="onModalHidden"
    @primary-click="removeNode"
    :primary-button-disabled="userInput !== 'node' + (node ? node.id : '')"
  >
    <template slot="title">{{ $t("nodes.remove_node_from_cluster") }}</template>
    <template slot="content">
      <cv-skeleton-text
        v-if="loading.listInstalledModules"
        :paragraph="true"
        :line-count="4"
        heading
      ></cv-skeleton-text>
      <template v-else-if="!error.listInstalledModules">
        <NsInlineNotification
          kind="warning"
          :title="$t('common.please_read_carefully')"
          :description="
            nodeApps.length
              ? $tc('nodes.remove_node_apps_confirm', nodeApps.length, {
                  node: node ? this.getNodeLabel(node) : '',
                  nodeApps: nodeApps.join(', '),
                })
              : ''
          "
          :showCloseButton="false"
        />
        <NsInlineNotification
          v-if="nodeApps.length"
          kind="info"
          :title="$t('common.remember')"
          :description="
            $t('nodes.shutdown_node_after_removal', {
              node: node ? this.getNodeLabel(node) : '',
            })
          "
          :showCloseButton="false"
        />
        <div>
          {{
            $t("nodes.remove_node_confirm", {
              name: node ? this.getNodeLabel(node) : "",
            })
          }}
        </div>
        <div class="mg-top-xlg">
          {{
            $t("common.type_to_confirm", {
              name: "node" + (node ? node.id : ""),
            })
          }}
        </div>
        <cv-form @submit.prevent="removeNode">
          <NsTextInput
            v-model="userInput"
            :disabled="loading.removeNode"
            class="mg-bottom-md hide-label"
            ref="userInput"
          >
          </NsTextInput>
        </cv-form>
      </template>
      <div ref="listInstalledModulesError">
        <NsInlineNotification
          v-if="error.listInstalledModules"
          kind="error"
          :title="$t('action.list-installed-modules')"
          :description="error.listInstalledModules"
          :showCloseButton="false"
          class="mg-top-lg"
        />
      </div>
      <div ref="removeNodeError">
        <NsInlineNotification
          v-if="error.removeNode"
          kind="error"
          :title="$t('action.remove-node')"
          :description="error.removeNode"
          :showCloseButton="false"
          class="mg-top-lg"
        />
      </div>
    </template>
    <template slot="secondary-button">{{ $t("common.cancel") }}</template>
    <template slot="primary-button">{{
      $t("nodes.understood_remove_node")
    }}</template>
  </NsModal>
</template>
⋮----
<template slot="title">{{ $t("nodes.remove_node_from_cluster") }}</template>
<template slot="content">
      <cv-skeleton-text
        v-if="loading.listInstalledModules"
        :paragraph="true"
        :line-count="4"
        heading
      ></cv-skeleton-text>
      <template v-else-if="!error.listInstalledModules">
        <NsInlineNotification
          kind="warning"
          :title="$t('common.please_read_carefully')"
          :description="
            nodeApps.length
              ? $tc('nodes.remove_node_apps_confirm', nodeApps.length, {
                  node: node ? this.getNodeLabel(node) : '',
                  nodeApps: nodeApps.join(', '),
                })
              : ''
          "
          :showCloseButton="false"
        />
        <NsInlineNotification
          v-if="nodeApps.length"
          kind="info"
          :title="$t('common.remember')"
          :description="
            $t('nodes.shutdown_node_after_removal', {
              node: node ? this.getNodeLabel(node) : '',
            })
          "
          :showCloseButton="false"
        />
        <div>
          {{
            $t("nodes.remove_node_confirm", {
              name: node ? this.getNodeLabel(node) : "",
            })
          }}
        </div>
        <div class="mg-top-xlg">
          {{
            $t("common.type_to_confirm", {
              name: "node" + (node ? node.id : ""),
            })
          }}
        </div>
        <cv-form @submit.prevent="removeNode">
          <NsTextInput
            v-model="userInput"
            :disabled="loading.removeNode"
            class="mg-bottom-md hide-label"
            ref="userInput"
          >
          </NsTextInput>
        </cv-form>
      </template>
      <div ref="listInstalledModulesError">
        <NsInlineNotification
          v-if="error.listInstalledModules"
          kind="error"
          :title="$t('action.list-installed-modules')"
          :description="error.listInstalledModules"
          :showCloseButton="false"
          class="mg-top-lg"
        />
      </div>
      <div ref="removeNodeError">
        <NsInlineNotification
          v-if="error.removeNode"
          kind="error"
          :title="$t('action.remove-node')"
          :description="error.removeNode"
          :showCloseButton="false"
          class="mg-top-lg"
        />
      </div>
    </template>
⋮----
<template v-else-if="!error.listInstalledModules">
        <NsInlineNotification
          kind="warning"
          :title="$t('common.please_read_carefully')"
          :description="
            nodeApps.length
              ? $tc('nodes.remove_node_apps_confirm', nodeApps.length, {
                  node: node ? this.getNodeLabel(node) : '',
                  nodeApps: nodeApps.join(', '),
                })
              : ''
          "
          :showCloseButton="false"
        />
        <NsInlineNotification
          v-if="nodeApps.length"
          kind="info"
          :title="$t('common.remember')"
          :description="
            $t('nodes.shutdown_node_after_removal', {
              node: node ? this.getNodeLabel(node) : '',
            })
          "
          :showCloseButton="false"
        />
        <div>
          {{
            $t("nodes.remove_node_confirm", {
              name: node ? this.getNodeLabel(node) : "",
            })
          }}
        </div>
        <div class="mg-top-xlg">
          {{
            $t("common.type_to_confirm", {
              name: "node" + (node ? node.id : ""),
            })
          }}
        </div>
        <cv-form @submit.prevent="removeNode">
          <NsTextInput
            v-model="userInput"
            :disabled="loading.removeNode"
            class="mg-bottom-md hide-label"
            ref="userInput"
          >
          </NsTextInput>
        </cv-form>
      </template>
⋮----
{{
            $t("nodes.remove_node_confirm", {
              name: node ? this.getNodeLabel(node) : "",
            })
          }}
⋮----
{{
            $t("common.type_to_confirm", {
              name: "node" + (node ? node.id : ""),
            })
          }}
⋮----
<template slot="secondary-button">{{ $t("common.cancel") }}</template>
<template slot="primary-button">{{
      $t("nodes.understood_remove_node")
    }}</template>
⋮----
<script>
import { TaskService, UtilService } from "@nethserver/ns8-ui-lib";
import to from "await-to-js";
import NodeService from "@/mixins/node";
export default {
  name: "RemoveNodeModal",
  mixins: [TaskService, UtilService, NodeService],
  props: {
    isShown: {
      type: Boolean,
      default: true,
    },
    node: { type: Object },
  },
  data() {
    return {
      userInput: "",
      nodeApps: [],
      loading: {
        removeNode: false,
        listInstalledModules: false,
      },
      error: {
        removeNode: "",
        listInstalledModules: "",
      },
    };
  },
  watch: {
    isShown: function () {
      if (this.isShown) {
        this.userInput = "";
        this.clearErrors();
        this.listInstalledModules();
      }
    },
    "error.listInstalledModules": function () {
      if (this.error.listInstalledModules) {
        this.$nextTick(() => {
          const el = this.$refs.listInstalledModulesError;
          this.scrollToElement(el);
        });
      }
    },
    "error.removeNode": function () {
      if (this.error.removeNode) {
        this.$nextTick(() => {
          const el = this.$refs.removeNodeError;
          this.scrollToElement(el);
        });
      }
    },
  },
  methods: {
    onModalHidden() {
      this.$emit("hide");
    },
    async removeNode() {
      if (this.userInput !== "node" + this.node.id) {
        return;
      }
      this.loading.removeNode = true;
      this.error.removeNode = "";
      const taskAction = "remove-node";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.removeNodeAborted
      );
      this.$root.$once(
        `${taskAction}-validation-failed-${eventId}`,
        this.removeNodeValidationFailed
      );
      this.$root.$once(
        `${taskAction}-validation-ok-${eventId}`,
        this.removeNodeValidationOk
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.removeNodeCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {
            node_id: this.node.id,
          },
          extra: {
            title: this.$t("action." + taskAction),
            description: this.$t("common.processing"),
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.removeNode = this.getErrorMessage(err);
        this.loading.removeNode = false;
        return;
      }
    },
    removeNodeAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.loading.removeNode = false;
    },
    removeNodeValidationOk() {
      this.$emit("hide");
    },
    removeNodeValidationFailed(validationErrors) {
      this.loading.removeNode = false;
      for (const validationError of validationErrors) {
        if (validationError.error === "node_in_use") {
          const apps = validationError.value.join(", ");
          this.error.removeNode = this.$tc(
            "nodes.validation_node_in_use",
            apps.length,
            { apps }
          );
        } else {
          this.error.removeNode = this.$t(
            "nodes.validation_" + validationError.error
          );
        }
      }
    },
    removeNodeCompleted() {
      this.loading.removeNode = false;
      this.$emit("hide");
      this.$emit("nodeRemoved");
      this.$root.$emit("reloadAppDrawer");
    },
    async listInstalledModules() {
      this.loading.listInstalledModules = true;
      const taskAction = "list-installed-modules";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.listInstalledModulesAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.listInstalledModulesCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        const errMessage = this.getErrorMessage(err);
        this.error.listInstalledModules = errMessage;
        this.loading.listInstalledModules = false;
        return;
      }
    },
    listInstalledModulesAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.listInstalledModules = this.$t("error.generic_error");
      this.loading.listInstalledModules = false;
    },
    listInstalledModulesCompleted(taskContext, taskResult) {
      const appsByNode = this.getInstalledAppsByNode(taskResult.output);
      let nodeApps = [];
      if (this.node.id in appsByNode) {
        nodeApps = appsByNode[this.node.id];
      }
      nodeApps = nodeApps.filter((app) => {
        return (
          !app.flags.includes("core_module") ||
          app.flags.includes("account_provider")
        );
      });
      this.nodeApps = nodeApps.map((app) => {
        return app.ui_name ? `${app.ui_name} (${app.id})` : app.id;
      });
      this.loading.listInstalledModules = false;
      this.focusElement("userInput");
    },
  },
};
</script>
⋮----
<style scoped lang="scss"></style>
</file>

<file path="core/ui/src/components/nodes/SetFqdnModal.vue">
<template>
  <NsModal
    size="default"
    :visible="isShown"
    :isLoading="loading.setFqdn"
    :primaryButtonDisabled="loading.getFqdn || loading.setFqdn"
    @modal-hidden="onModalHidden"
    @primary-click="setFqdn"
  >
    <template slot="title">{{ $t("nodes.set_fqdn") }}</template>
    <template slot="content">
      <NsInlineNotification
        v-if="isLeaderNode"
        kind="warning"
        :title="$t('nodes.vpn_endpoint_warning_title')"
        :description="$t('nodes.vpn_endpoint_warning_description')"
        :showCloseButton="false"
      />
      <NsInlineNotification
        v-if="error.getFqdn"
        kind="error"
        :title="$t('action.get-fqdn')"
        :description="error.getFqdn"
        :showCloseButton="false"
      />
      <cv-skeleton-text
        v-if="loading.getFqdn"
        :paragraph="true"
        :line-count="5"
        heading
      ></cv-skeleton-text>
      <cv-form v-else @submit.prevent="setFqdn">
        <template>
          <cv-text-input
            :label="
              $t('nodes.node_name_hostname', {
                node: this.nodeLabel,
              })
            "
            v-model.trim="hostname"
            :invalid-message="error.hostname"
            :disabled="loading.getFqdn || loading.setFqdn"
            ref="hostname"
          >
          </cv-text-input>
          <cv-text-input
            :label="
              $t('nodes.node_name_domain', {
                node: this.nodeLabel,
              })
            "
            v-model.trim="domain"
            placeholder="example.org"
            :invalid-message="error.domain"
            :disabled="loading.getFqdn || loading.setFqdn"
            ref="domain"
          >
          </cv-text-input>
          <NsCheckbox
            v-if="isLeaderNode"
            :label="$t('nodes.check_node_connectivity')"
            v-model="checkNodeConnectivity"
            :disabled="loading.getFqdn || loading.setFqdn"
            value="checkNodeConnectivity"
          />
        </template>
      </cv-form>
      <NsInlineNotification
        v-if="error.checkNodeConnectivity"
        kind="error"
        :title="$t('nodes.connectivity_check_failed')"
        :description="error.checkNodeConnectivity"
        :showCloseButton="false"
      />
      <NsInlineNotification
        v-if="error.setFqdn"
        kind="error"
        :title="$t('action.set-fqdn')"
        :description="error.setFqdn"
        :showCloseButton="false"
      />
    </template>
    <template slot="secondary-button">{{ $t("common.cancel") }}</template>
    <template slot="primary-button">{{ $t("nodes.set_fqdn") }}</template>
  </NsModal>
</template>
⋮----
<template slot="title">{{ $t("nodes.set_fqdn") }}</template>
<template slot="content">
      <NsInlineNotification
        v-if="isLeaderNode"
        kind="warning"
        :title="$t('nodes.vpn_endpoint_warning_title')"
        :description="$t('nodes.vpn_endpoint_warning_description')"
        :showCloseButton="false"
      />
      <NsInlineNotification
        v-if="error.getFqdn"
        kind="error"
        :title="$t('action.get-fqdn')"
        :description="error.getFqdn"
        :showCloseButton="false"
      />
      <cv-skeleton-text
        v-if="loading.getFqdn"
        :paragraph="true"
        :line-count="5"
        heading
      ></cv-skeleton-text>
      <cv-form v-else @submit.prevent="setFqdn">
        <template>
          <cv-text-input
            :label="
              $t('nodes.node_name_hostname', {
                node: this.nodeLabel,
              })
            "
            v-model.trim="hostname"
            :invalid-message="error.hostname"
            :disabled="loading.getFqdn || loading.setFqdn"
            ref="hostname"
          >
          </cv-text-input>
          <cv-text-input
            :label="
              $t('nodes.node_name_domain', {
                node: this.nodeLabel,
              })
            "
            v-model.trim="domain"
            placeholder="example.org"
            :invalid-message="error.domain"
            :disabled="loading.getFqdn || loading.setFqdn"
            ref="domain"
          >
          </cv-text-input>
          <NsCheckbox
            v-if="isLeaderNode"
            :label="$t('nodes.check_node_connectivity')"
            v-model="checkNodeConnectivity"
            :disabled="loading.getFqdn || loading.setFqdn"
            value="checkNodeConnectivity"
          />
        </template>
      </cv-form>
      <NsInlineNotification
        v-if="error.checkNodeConnectivity"
        kind="error"
        :title="$t('nodes.connectivity_check_failed')"
        :description="error.checkNodeConnectivity"
        :showCloseButton="false"
      />
      <NsInlineNotification
        v-if="error.setFqdn"
        kind="error"
        :title="$t('action.set-fqdn')"
        :description="error.setFqdn"
        :showCloseButton="false"
      />
    </template>
⋮----
<template>
          <cv-text-input
            :label="
              $t('nodes.node_name_hostname', {
                node: this.nodeLabel,
              })
            "
            v-model.trim="hostname"
            :invalid-message="error.hostname"
            :disabled="loading.getFqdn || loading.setFqdn"
            ref="hostname"
          >
          </cv-text-input>
          <cv-text-input
            :label="
              $t('nodes.node_name_domain', {
                node: this.nodeLabel,
              })
            "
            v-model.trim="domain"
            placeholder="example.org"
            :invalid-message="error.domain"
            :disabled="loading.getFqdn || loading.setFqdn"
            ref="domain"
          >
          </cv-text-input>
          <NsCheckbox
            v-if="isLeaderNode"
            :label="$t('nodes.check_node_connectivity')"
            v-model="checkNodeConnectivity"
            :disabled="loading.getFqdn || loading.setFqdn"
            value="checkNodeConnectivity"
          />
        </template>
⋮----
<template slot="secondary-button">{{ $t("common.cancel") }}</template>
<template slot="primary-button">{{ $t("nodes.set_fqdn") }}</template>
⋮----
<script>
import { UtilService, IconService, TaskService } from "@nethserver/ns8-ui-lib";
import to from "await-to-js";
import { mapState } from "vuex";
export default {
  name: "SetFqdnModal",
  components: {},
  mixins: [UtilService, IconService, TaskService],
  props: {
    isShown: {
      type: Boolean,
      default: true,
    },
    node: { type: Object },
  },
  data() {
    return {
      hostname: "",
      domain: "",
      checkNodeConnectivity: true,
      loading: {
        getFqdn: false,
        setFqdn: false,
      },
      error: {
        getFqdn: "",
        setFqdn: "",
        hostname: "",
        domain: "",
        checkNodeConnectivity: "",
      },
    };
  },
  computed: {
    ...mapState(["clusterNodes"]),
    isLeaderNode() {
      return this.node && this.node.local;
    },
    nodeLabel() {
      if (this.node) {
        return this.getShortNodeLabel(this.node);
      } else {
        return "";
      }
    },
  },
  watch: {
    isShown: function () {
      if (this.isShown) {
        this.clearErrors();
        this.getFqdn();
        this.checkNodeConnectivity = true;
      }
    },
  },
  methods: {
    onModalHidden() {
      this.$emit("hide");
    },
    async getFqdn() {
      this.error.getFqdn = "";
      this.loading.getFqdn = true;
      const taskAction = "get-fqdn";
      const eventId = this.getUuid();
      this.$root.$once(`${taskAction}-aborted-${eventId}`, this.getFqdnAborted);
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.getFqdnCompleted
      );
      const res = await to(
        this.createNodeTask(this.node.id, {
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.getFqdn = this.getErrorMessage(err);
        return;
      }
    },
    getFqdnCompleted(taskContext, taskResult) {
      this.hostname = taskResult.output.hostname;
      this.domain = taskResult.output.domain;
      this.loading.getFqdn = false;
      setTimeout(() => {
        this.focusElement("hostname");
      }, 300);
    },
    getFqdnAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.loading.getFqdn = false;
      this.$emit("hide");
    },
    validateSetFqdn() {
      this.error.hostname = "";
      this.error.domain = "";
      let isValidationOk = true;
      // hostname
      if (!this.hostname) {
        this.error.hostname = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("hostname");
          isValidationOk = false;
        }
      }
      if (!this.domain) {
        this.error.domain = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("domain");
          isValidationOk = false;
        }
      }
      return isValidationOk;
    },
    async setFqdn() {
      if (!this.validateSetFqdn()) {
        return;
      }
      this.loading.setFqdn = true;
      this.error.setFqdn = "";
      const taskAction = "set-fqdn";
      const eventId = this.getUuid();
      this.$root.$once(`${taskAction}-aborted-${eventId}`, this.setFqdnAborted);
      this.$root.$once(
        `${taskAction}-validation-failed-${eventId}`,
        this.setFqdnValidationFailed
      );
      this.$root.$once(
        `${taskAction}-validation-ok-${eventId}`,
        this.setFqdnValidationOk
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.setFqdnCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {
            node: this.node.id,
            hostname: this.hostname,
            domain: this.domain,
            reachability_check: this.checkNodeConnectivity,
          },
          extra: {
            title: this.$t("action." + taskAction),
            description: this.$t("common.processing"),
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.setFqdn = this.getErrorMessage(err);
        this.loading.setFqdn = false;
        return;
      }
    },
    setFqdnAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.loading.setFqdn = false;
      this.$emit("hide");
    },
    setFqdnValidationOk() {
      this.$emit("hide");
    },
    setFqdnValidationFailed(validationErrors) {
      this.loading.setFqdn = false;
      let focusAlreadySet = false;
      for (const validationError of validationErrors) {
        const param = validationError.parameter;
        if (validationError.error == "reachability_check_failed") {
          const failedNodeId = validationError.value;
          const failedNode = this.clusterNodes.find(
            (node) => node.id == failedNodeId
          );
          if (failedNode) {
            const failedNodeLabel = this.getNodeLabel(failedNode);
            this.error.checkNodeConnectivity = this.$t(
              "nodes.connectivity_check_failed_description",
              { fqdn: `${this.hostname}.${this.domain}`, node: failedNodeLabel }
            );
          }
        } else {
          this.error[param] = this.getI18nStringWithFallback(
            "init." + validationError.error,
            "error." + validationError.error
          );
          if (!focusAlreadySet) {
            this.focusElement(param);
            focusAlreadySet = true;
          }
        }
      }
    },
    setFqdnCompleted() {
      this.loading.setFqdn = false;
      this.$emit("hide");
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
</style>
</file>

<file path="core/ui/src/components/settings/2FaQrCodeModal.vue">
<template>
  <NsModal
    size="default"
    :visible="isShown"
    @modal-hidden="onModalHidden"
    @primary-click="onModalHidden"
  >
    <template slot="title">{{ $t("settings_account.2fa_qr_code") }}</template>
    <template slot="content">
      <NsInlineNotification
        v-if="error.get2FaQrCode"
        kind="error"
        :title="$t('settings_account.cannot_retrieve_2fa_qr_code')"
        :description="error.get2FaQrCode"
        :showCloseButton="false"
      />
      <cv-skeleton-text
        v-else-if="loading.get2FaQrCode"
        heading
        paragraph
        :line-count="6"
      />
      <template v-else>
        <div class="flex-centered">
          <div class="qr-code-container">
            <qrcode-vue :value="qrCodeUrl" :size="qrCodeSize" level="H" />
          </div>
        </div>
        <p class="mg-top-lg">
          {{ $t("settings_account.qr_code_description") }}
          <cv-interactive-tooltip
            alignment="center"
            direction="right"
            class="info"
          >
            <template slot="trigger">
              <Information16 />
            </template>
            <template slot="content">
              <div>
                {{ $t("settings_account.qr_code_description_tooltip") }}
              </div>
            </template>
          </cv-interactive-tooltip>
        </p>
        <p class="mg-top-md">
          <span>{{ $t("settings_account.store_setup_key_suggestion") }}</span
          >&nbsp;
          <cv-link @click="toggleSetupKey">
            {{
              isShownSetupKey
                ? $t("settings_account.hide_setup_key")
                : $t("settings_account.show_setup_key")
            }}
          </cv-link>
          <NsCodeSnippet
            v-if="isShownSetupKey"
            light
            copyTipPosition="left"
            copyTipAlignment="center"
            :copyTooltip="$t('common.copy_to_clipboard')"
            :copy-feedback="$t('common.copied_to_clipboard')"
            :feedback-aria-label="$t('common.copied_to_clipboard')"
            :wrap-text="true"
            :moreText="$t('common.show_more')"
            :lessText="$t('common.show_less')"
            hideExpandButton
            class="mg-top-sm"
            >{{ setupKey }}</NsCodeSnippet
          >
        </p>
      </template>
    </template>
    <template slot="primary-button">{{ $t("common.done") }}</template>
  </NsModal>
</template>
⋮----
<template slot="title">{{ $t("settings_account.2fa_qr_code") }}</template>
<template slot="content">
      <NsInlineNotification
        v-if="error.get2FaQrCode"
        kind="error"
        :title="$t('settings_account.cannot_retrieve_2fa_qr_code')"
        :description="error.get2FaQrCode"
        :showCloseButton="false"
      />
      <cv-skeleton-text
        v-else-if="loading.get2FaQrCode"
        heading
        paragraph
        :line-count="6"
      />
      <template v-else>
        <div class="flex-centered">
          <div class="qr-code-container">
            <qrcode-vue :value="qrCodeUrl" :size="qrCodeSize" level="H" />
          </div>
        </div>
        <p class="mg-top-lg">
          {{ $t("settings_account.qr_code_description") }}
          <cv-interactive-tooltip
            alignment="center"
            direction="right"
            class="info"
          >
            <template slot="trigger">
              <Information16 />
            </template>
            <template slot="content">
              <div>
                {{ $t("settings_account.qr_code_description_tooltip") }}
              </div>
            </template>
          </cv-interactive-tooltip>
        </p>
        <p class="mg-top-md">
          <span>{{ $t("settings_account.store_setup_key_suggestion") }}</span
          >&nbsp;
          <cv-link @click="toggleSetupKey">
            {{
              isShownSetupKey
                ? $t("settings_account.hide_setup_key")
                : $t("settings_account.show_setup_key")
            }}
          </cv-link>
          <NsCodeSnippet
            v-if="isShownSetupKey"
            light
            copyTipPosition="left"
            copyTipAlignment="center"
            :copyTooltip="$t('common.copy_to_clipboard')"
            :copy-feedback="$t('common.copied_to_clipboard')"
            :feedback-aria-label="$t('common.copied_to_clipboard')"
            :wrap-text="true"
            :moreText="$t('common.show_more')"
            :lessText="$t('common.show_less')"
            hideExpandButton
            class="mg-top-sm"
            >{{ setupKey }}</NsCodeSnippet
          >
        </p>
      </template>
    </template>
⋮----
<template v-else>
        <div class="flex-centered">
          <div class="qr-code-container">
            <qrcode-vue :value="qrCodeUrl" :size="qrCodeSize" level="H" />
          </div>
        </div>
        <p class="mg-top-lg">
          {{ $t("settings_account.qr_code_description") }}
          <cv-interactive-tooltip
            alignment="center"
            direction="right"
            class="info"
          >
            <template slot="trigger">
              <Information16 />
            </template>
            <template slot="content">
              <div>
                {{ $t("settings_account.qr_code_description_tooltip") }}
              </div>
            </template>
          </cv-interactive-tooltip>
        </p>
        <p class="mg-top-md">
          <span>{{ $t("settings_account.store_setup_key_suggestion") }}</span
          >&nbsp;
          <cv-link @click="toggleSetupKey">
            {{
              isShownSetupKey
                ? $t("settings_account.hide_setup_key")
                : $t("settings_account.show_setup_key")
            }}
          </cv-link>
          <NsCodeSnippet
            v-if="isShownSetupKey"
            light
            copyTipPosition="left"
            copyTipAlignment="center"
            :copyTooltip="$t('common.copy_to_clipboard')"
            :copy-feedback="$t('common.copied_to_clipboard')"
            :feedback-aria-label="$t('common.copied_to_clipboard')"
            :wrap-text="true"
            :moreText="$t('common.show_more')"
            :lessText="$t('common.show_less')"
            hideExpandButton
            class="mg-top-sm"
            >{{ setupKey }}</NsCodeSnippet
          >
        </p>
      </template>
⋮----
{{ $t("settings_account.qr_code_description") }}
⋮----
<template slot="trigger">
              <Information16 />
            </template>
<template slot="content">
              <div>
                {{ $t("settings_account.qr_code_description_tooltip") }}
              </div>
            </template>
⋮----
{{ $t("settings_account.qr_code_description_tooltip") }}
⋮----
<span>{{ $t("settings_account.store_setup_key_suggestion") }}</span
⋮----
{{
              isShownSetupKey
                ? $t("settings_account.hide_setup_key")
                : $t("settings_account.show_setup_key")
            }}
⋮----
>{{ setupKey }}</NsCodeSnippet
⋮----
<template slot="primary-button">{{ $t("common.done") }}</template>
⋮----
<script>
import to from "await-to-js";
import { UtilService, TaskService } from "@nethserver/ns8-ui-lib";
import TwoFaService from "@/mixins/2fa";
import QrcodeVue from "qrcode.vue";
import Information16 from "@carbon/icons-vue/es/information/16";
export default {
  name: "TwoFaQrCodeModal",
  components: { QrcodeVue, Information16 },
  mixins: [UtilService, TaskService, TwoFaService],
  props: {
    isShown: Boolean,
  },
  data() {
    return {
      qrCodeUrl: "",
      setupKey: "",
      qrCodeSize: 300,
      isShownSetupKey: false,
      loading: {
        get2FaQrCode: false,
      },
      error: {
        get2FaQrCode: "",
      },
    };
  },
  watch: {
    isShown: function () {
      if (this.isShown) {
        this.isShownSetupKey = false;
        this.retrieve2FaQrCode();
      }
    },
  },
  methods: {
    onModalHidden() {
      this.$emit("hide");
    },
    async retrieve2FaQrCode() {
      this.loading.get2FaQrCode = true;
      this.error.get2FaQrCode = "";
      const [err2FaQrCode, response2FaQrCode] = await to(this.get2FaQrCode());
      this.loading.get2FaQrCode = false;
      if (err2FaQrCode) {
        console.error("error retrieving 2FA QR code", err2FaQrCode);
        this.error.get2FaQrCode = this.getErrorMessage(err2FaQrCode);
        return;
      }
      this.qrCodeUrl = response2FaQrCode.data.data.url;
      this.setupKey = response2FaQrCode.data.data.key;
    },
    toggleSetupKey() {
      this.isShownSetupKey = !this.isShownSetupKey;
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
.flex-centered {
  display: flex;
  justify-content: center;
}
.qr-code-container {
  display: inline-block;
  text-align: center;
  padding: $spacing-08;
  background-color: white;
}
</style>
</file>

<file path="core/ui/src/components/settings/AcmeSettingsPanel.vue">
<template>
  <div>
    <cv-tile light>
      <NsInlineNotification
        v-for="instance in offlineTraefikInstances"
        :key="instance.id"
        kind="error"
        :title="
          $t('settings_tls_certificates.node_is_offline', {
            node: getOfflineNodeLabel(instance),
          })
        "
        :description="
          $t('settings_acme_servers.acme_settings_not_displayed', {
            instanceId: instance.id,
          })
        "
        :showCloseButton="false"
      />
      <NsInlineNotification
        v-if="tableError && servers.length"
        kind="error"
        :title="tableErrorTitle"
        :description="tableErrorDescription"
        :showCloseButton="false"
      />
      <NsDataTable
        :allRows="servers"
        :columns="i18nTableColumns"
        :rawColumns="tableColumns"
        :sortable="true"
        :pageSizes="[10, 25, 50, 100]"
        :overflow-menu="true"
        isSearchable
        :searchPlaceholder="$t('settings_acme_servers.search_acme_settings')"
        :searchClearLabel="$t('common.clear_search')"
        :noSearchResultsLabel="$t('common.no_search_results')"
        :noSearchResultsDescription="$t('common.no_search_results_description')"
        :isLoading="loadingServers"
        :skeletonRows="5"
        :isErrorShown="!!tableError && !servers.length"
        :errorTitle="tableErrorTitle"
        :errorDescription="tableErrorDescription"
        :itemsPerPageLabel="$t('pagination.items_per_page')"
        :rangeOfTotalItemsLabel="$t('pagination.range_of_total_items')"
        :ofTotalPagesLabel="$t('pagination.of_total_pages')"
        :backwardText="$t('pagination.previous_page')"
        :forwardText="$t('pagination.next_page')"
        :pageNumberLabel="$t('pagination.page_number')"
        @updatePage="tablePage = $event"
      >
        <template slot="empty-state">
          <NsEmptyState :title="$t('settings_acme_servers.no_acme_settings')">
            <template #description>
              <div>
                {{ $t("settings_acme_servers.no_acme_settings_description") }}
              </div>
            </template>
          </NsEmptyState>
        </template>
        <template slot="data">
          <cv-data-table-row
            v-for="(row, rowIndex) in tablePage"
            :key="`${rowIndex}`"
            :value="`${rowIndex}`"
          >
            <cv-data-table-cell>
              <span>{{ row.node }}</span>
            </cv-data-table-cell>
            <cv-data-table-cell>
              <span>
                {{ row.url }}
              </span>
            </cv-data-table-cell>
            <cv-data-table-cell>
              <NsTag
                v-if="row.challenge"
                :kind="getChallengeTagKind(row.challenge)"
                size="sm"
                :label="getChallengeLabel(row.challenge)"
              />
            </cv-data-table-cell>
            <cv-data-table-cell>
              <div class="flex justify-end">
                <NsButton
                  kind="ghost"
                  :icon="Edit20"
                  size="small"
                  @click="showEditServerModal(row)"
                  :data-test-id="row.nodeId + '-edit'"
                  >{{ $t("common.edit") }}
                </NsButton>
              </div>
            </cv-data-table-cell>
          </cv-data-table-row>
        </template>
      </NsDataTable>
    </cv-tile>
    <EditAcmeServerModal
      :isShown="isShownEditServerModal"
      :server="currentServer"
      @hide="hideEditServerModal"
      @reloadServers="onReloadServers"
    />
  </div>
</template>
⋮----
<template slot="empty-state">
          <NsEmptyState :title="$t('settings_acme_servers.no_acme_settings')">
            <template #description>
              <div>
                {{ $t("settings_acme_servers.no_acme_settings_description") }}
              </div>
            </template>
          </NsEmptyState>
        </template>
⋮----
<template #description>
              <div>
                {{ $t("settings_acme_servers.no_acme_settings_description") }}
              </div>
            </template>
⋮----
{{ $t("settings_acme_servers.no_acme_settings_description") }}
⋮----
<template slot="data">
          <cv-data-table-row
            v-for="(row, rowIndex) in tablePage"
            :key="`${rowIndex}`"
            :value="`${rowIndex}`"
          >
            <cv-data-table-cell>
              <span>{{ row.node }}</span>
            </cv-data-table-cell>
            <cv-data-table-cell>
              <span>
                {{ row.url }}
              </span>
            </cv-data-table-cell>
            <cv-data-table-cell>
              <NsTag
                v-if="row.challenge"
                :kind="getChallengeTagKind(row.challenge)"
                size="sm"
                :label="getChallengeLabel(row.challenge)"
              />
            </cv-data-table-cell>
            <cv-data-table-cell>
              <div class="flex justify-end">
                <NsButton
                  kind="ghost"
                  :icon="Edit20"
                  size="small"
                  @click="showEditServerModal(row)"
                  :data-test-id="row.nodeId + '-edit'"
                  >{{ $t("common.edit") }}
                </NsButton>
              </div>
            </cv-data-table-cell>
          </cv-data-table-row>
        </template>
⋮----
<span>{{ row.node }}</span>
⋮----
{{ row.url }}
⋮----
>{{ $t("common.edit") }}
⋮----
<script>
import to from "await-to-js";
import { UtilService, TaskService, IconService } from "@nethserver/ns8-ui-lib";
import EditAcmeServerModal, {
  ACME_CHALLENGE_TYPES,
} from "@/components/settings/EditAcmeServerModal.vue";
export default {
  name: "AcmeSettingsPanel",
  components: { EditAcmeServerModal },
  mixins: [TaskService, UtilService, IconService],
  props: {
    traefikInstances: {
      type: Array,
      default: () => [],
    },
    isLoadingInstances: Boolean,
    instancesError: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      tablePage: [],
      tableColumns: ["node", "url", "challenge"],
      tableColumnLabelKeys: [
        "settings_acme_servers.node",
        "settings_acme_servers.acme_directory_url",
        "settings_acme_servers.challenge",
      ],
      servers: [],
      offlineTraefikInstances: [],
      isShownEditServerModal: false,
      currentErrorAction: "",
      currentErrorDescription: "",
      currentServer: null,
      taskListeners: [],
      loading: {
        getAcmeServerNum: 0,
      },
      error: {
        getAcmeServer: "",
      },
    };
  },
  computed: {
    i18nTableColumns() {
      return this.tableColumnLabelKeys.map((key) => this.$t(key));
    },
    loadingServers() {
      return this.isLoadingInstances || this.loading.getAcmeServerNum > 0;
    },
    tableError() {
      return this.instancesError || this.error.getAcmeServer;
    },
    tableErrorTitle() {
      return this.instancesError
        ? this.$t("action.list-installed-modules")
        : this.currentErrorAction;
    },
    tableErrorDescription() {
      return this.instancesError || this.currentErrorDescription;
    },
  },
  watch: {
    traefikInstances: function () {
      this.getAcmeServer();
    },
  },
  created() {
    if (this.traefikInstances.length) {
      this.getAcmeServer();
    }
  },
  beforeDestroy() {
    this.clearTaskListeners();
  },
  methods: {
    registerTaskListener(eventName, handler) {
      this.$root.$once(eventName, handler);
      this.taskListeners.push([eventName, handler]);
    },
    clearTaskListeners() {
      this.taskListeners.forEach(([eventName, handler]) => {
        this.$root.$off(eventName, handler);
      });
      this.taskListeners = [];
    },
    getChallengeType(challenge) {
      return ACME_CHALLENGE_TYPES.find((type) => type.value === challenge);
    },
    getChallengeTagKind(challenge) {
      const challengeType = this.getChallengeType(challenge);
      return challengeType ? challengeType.tagKind : "gray";
    },
    getChallengeLabel(challenge) {
      const challengeType = this.getChallengeType(challenge);
      return challengeType ? this.$t(challengeType.labelKey) : challenge;
    },
    showEditServerModal(server) {
      this.currentServer = server;
      this.isShownEditServerModal = true;
    },
    hideEditServerModal() {
      this.isShownEditServerModal = false;
    },
    getOfflineNodeLabel(instance) {
      return this.getNodeLabel({
        id: instance.node,
        ui_name: instance.node_ui_name,
      });
    },
    clearTableError() {
      this.error.getAcmeServer = "";
      this.currentErrorAction = "";
      this.currentErrorDescription = "";
    },
    async getAcmeServer() {
      // a handler of a previous round would decrement the counter of this one
      this.clearTaskListeners();
      this.servers = [];
      this.offlineTraefikInstances = [];
      // otherwise a transient error sticks after the nodes answer again
      this.clearTableError();
      // count upfront: the counter must not hit zero between two iterations
      this.loading.getAcmeServerNum = this.traefikInstances.length;
      for (const traefikInstance of this.traefikInstances) {
        const taskAction = "get-acme-server";
        const eventId = this.getUuid();
        this.registerTaskListener(
          `${taskAction}-aborted-${eventId}`,
          this.getAcmeServerAborted
        );
        this.registerTaskListener(
          `${taskAction}-completed-${eventId}`,
          this.getAcmeServerCompleted
        );
        const res = await to(
          this.createModuleTaskForApp(traefikInstance.id, {
            action: taskAction,
            data: {
              expand_list: true,
            },
            extra: {
              title: this.$t("action." + taskAction),
              isNotificationHidden: true,
              traefikInstance: traefikInstance,
              eventId,
            },
          })
        );
        const err = res[0];
        if (err) {
          console.error(`error creating task ${taskAction}`, err);
          this.$root.$off(`${taskAction}-aborted-${eventId}`);
          this.$root.$off(`${taskAction}-completed-${eventId}`);
          if (err.response && err.response.status === 404) {
            if (
              !this.offlineTraefikInstances.find(
                (instance) => instance.id === traefikInstance.id
              )
            ) {
              this.offlineTraefikInstances.push(traefikInstance);
            }
          } else {
            const errMessage = this.getErrorMessage(err);
            this.error.getAcmeServer = errMessage;
            this.currentErrorAction = this.$t("action." + taskAction);
            this.currentErrorDescription = errMessage;
          }
          this.loading.getAcmeServerNum--;
        }
      }
    },
    getAcmeServerAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.getAcmeServer = this.$t("error.generic_error");
      this.currentErrorAction = this.$t("action." + taskContext.action);
      this.currentErrorDescription = this.$t("error.generic_error");
      this.loading.getAcmeServerNum--;
    },
    getAcmeServerCompleted(taskContext, taskResult) {
      const server = taskResult.output;
      const traefikId = taskContext.extra.traefikInstance.id;
      const nodeId = taskContext.extra.traefikInstance.node;
      const nodeUiName = taskContext.extra.traefikInstance.node_ui_name;
      const node = { id: nodeId, ui_name: nodeUiName };
      const nodeLabel = this.getShortNodeLabel(node) + ` (${traefikId})`;
      server.node = nodeLabel;
      server.nodeId = nodeId;
      server.longNodeLabel = this.getNodeLabel(node);
      server.traefikInstance = traefikId;
      const index = this.servers.findIndex(
        (existing) => existing.traefikInstance === traefikId
      );
      if (index > -1) {
        this.servers.splice(index, 1, server);
      } else {
        this.servers.push(server);
      }
      this.servers.sort(this.sortByProperty("node"));
      this.loading.getAcmeServerNum--;
    },
    onReloadServers() {
      this.getAcmeServer();
    },
  },
};
</script>
</file>

<file path="core/ui/src/components/settings/ChangeAdminPasswordModal.vue">
<template>
  <NsModal
    size="default"
    :visible="isShown"
    @modal-hidden="onModalHidden"
    @primary-click="alterUser"
    :primary-button-disabled="loading.alterUser"
  >
    <template v-if="admin" slot="title">{{
      $t("settings_cluster_admins.change_password_for_admin", {
        admin: admin.user,
      })
    }}</template>
    <template slot="content">
      <cv-form @submit.prevent="alterUser">
        <NsPasswordInput
          :newPasswordLabel="$t('password.new_password')"
          :confirmPasswordLabel="$t('password.re_enter_new_password')"
          v-model="newPassword"
          @passwordValidation="onPasswordValidation"
          :newPasswordInvalidMessage="$t(error.newPassword)"
          :confirmPasswordInvalidMessage="$t(error.confirmPassword)"
          :passwordHideLabel="$t('password.hide_password')"
          :passwordShowLabel="$t('password.show_password')"
          :lengthLabel="$t('password.long_enough')"
          :lowercaseLabel="$t('password.lowercase_letter')"
          :uppercaseLabel="$t('password.uppercase_letter')"
          :numberLabel="$t('password.number')"
          :symbolLabel="$t('password.symbol')"
          :equalLabel="$t('password.equal')"
          :focus="focusPasswordField"
          :clearConfirmPasswordCommand="clearConfirmPasswordCommand"
        />
        <div v-if="error.alterUser">
          <NsInlineNotification
            kind="error"
            :title="$t('action.alter-user')"
            :description="error.alterUser"
            :showCloseButton="false"
          />
        </div>
      </cv-form>
    </template>
    <template slot="secondary-button">{{ $t("common.cancel") }}</template>
    <template slot="primary-button">{{
      $t("settings_cluster_admins.change_password")
    }}</template>
  </NsModal>
</template>
⋮----
<template v-if="admin" slot="title">{{
      $t("settings_cluster_admins.change_password_for_admin", {
        admin: admin.user,
      })
    }}</template>
<template slot="content">
      <cv-form @submit.prevent="alterUser">
        <NsPasswordInput
          :newPasswordLabel="$t('password.new_password')"
          :confirmPasswordLabel="$t('password.re_enter_new_password')"
          v-model="newPassword"
          @passwordValidation="onPasswordValidation"
          :newPasswordInvalidMessage="$t(error.newPassword)"
          :confirmPasswordInvalidMessage="$t(error.confirmPassword)"
          :passwordHideLabel="$t('password.hide_password')"
          :passwordShowLabel="$t('password.show_password')"
          :lengthLabel="$t('password.long_enough')"
          :lowercaseLabel="$t('password.lowercase_letter')"
          :uppercaseLabel="$t('password.uppercase_letter')"
          :numberLabel="$t('password.number')"
          :symbolLabel="$t('password.symbol')"
          :equalLabel="$t('password.equal')"
          :focus="focusPasswordField"
          :clearConfirmPasswordCommand="clearConfirmPasswordCommand"
        />
        <div v-if="error.alterUser">
          <NsInlineNotification
            kind="error"
            :title="$t('action.alter-user')"
            :description="error.alterUser"
            :showCloseButton="false"
          />
        </div>
      </cv-form>
    </template>
<template slot="secondary-button">{{ $t("common.cancel") }}</template>
<template slot="primary-button">{{
      $t("settings_cluster_admins.change_password")
    }}</template>
⋮----
<script>
import { UtilService, TaskService, IconService } from "@nethserver/ns8-ui-lib";
import to from "await-to-js";
export default {
  name: "ChangeAdminPasswordModal",
  mixins: [UtilService, TaskService, IconService],
  props: {
    isShown: Boolean,
    admin: { type: [Object, null] },
  },
  data() {
    return {
      newPassword: "",
      passwordValidation: null,
      focusPasswordField: { element: "" },
      clearConfirmPasswordCommand: 0,
      loading: {
        alterUser: false,
      },
      error: {
        alterUser: "",
        newPassword: "",
        confirmPassword: "",
      },
    };
  },
  watch: {
    isShown: function () {
      if (this.isShown) {
        // clear password fields
        this.newPassword = "";
        this.clearConfirmPasswordCommand++;
        setTimeout(() => {
          this.focusPasswordField = { element: "newPassword" };
        }, 400);
      }
    },
  },
  methods: {
    validateAlterUser() {
      this.clearErrors();
      let isValidationOk = true;
      if (!this.newPassword) {
        this.error.newPassword = this.$t("common.required");
        if (isValidationOk) {
          this.focusPasswordField = { element: "newPassword" };
          isValidationOk = false;
        }
      } else {
        if (this.currentPassword === this.newPassword) {
          if (!this.error.newPassword) {
            this.error.newPassword = this.$t(
              "password.old_new_passwords_must_be_different"
            );
          }
          if (isValidationOk) {
            this.focusPasswordField = { element: "newPassword" };
            isValidationOk = false;
          }
        }
        if (
          !this.passwordValidation.isLengthOk ||
          !this.passwordValidation.isLowercaseOk ||
          !this.passwordValidation.isUppercaseOk ||
          !this.passwordValidation.isNumberOk ||
          !this.passwordValidation.isSymbolOk
        ) {
          if (!this.error.newPassword) {
            this.error.newPassword = this.$t("password.password_not_secure");
          }
          if (isValidationOk) {
            this.focusPasswordField = { element: "newPassword" };
            isValidationOk = false;
          }
        }
        if (!this.passwordValidation.isEqualOk) {
          if (!this.error.newPassword) {
            this.error.newPassword = this.$t("password.passwords_do_not_match");
          }
          if (!this.error.confirmPassword) {
            this.error.confirmPassword = this.$t(
              "password.passwords_do_not_match"
            );
          }
          if (isValidationOk) {
            this.focusPasswordField = { element: "confirmPassword" };
            isValidationOk = false;
          }
        }
      }
      return isValidationOk;
    },
    async alterUser() {
      if (!this.validateAlterUser()) {
        return;
      }
      this.loading.alterUser = true;
      this.error.alterUser = "";
      const taskAction = "alter-user";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.alterUserAborted
      );
      this.$root.$once(
        `${taskAction}-validation-ok-${eventId}`,
        this.alterUserValidationOk
      );
      this.$root.$once(
        `${taskAction}-validation-failed-${eventId}`,
        this.alterUserValidationFailed
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.alterUserCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {
            user: this.admin.user,
            set: { password: this.newPassword },
            revoke: [],
            grant: [],
          },
          extra: {
            title: this.$t(
              "settings_cluster_admins.change_password_for_admin",
              {
                admin: this.admin.user,
              }
            ),
            description: this.$t("common.processing"),
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.alterUser = this.getErrorMessage(err);
        this.loading.alterUser = false;
        return;
      }
    },
    alterUserAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.loading.alterUser = false;
      this.$emit("hide");
    },
    alterUserValidationOk() {
      this.loading.alterUser = false;
      this.$emit("hide");
    },
    alterUserValidationFailed(validationErrors) {
      this.loading.alterUser = false;
      let focusAlreadySet = false;
      for (const validationError of validationErrors) {
        const param = validationError.parameter;
        this.error[param] = this.$t(
          "settings_cluster_admins." + validationError.error
        );
        if (!focusAlreadySet) {
          this.focusElement(param);
          focusAlreadySet = true;
        }
      }
    },
    alterUserCompleted() {
      this.loading.alterUser = false;
    },
    onModalHidden() {
      this.clearErrors();
      this.$emit("hide");
    },
    onPasswordValidation(passwordValidation) {
      this.passwordValidation = passwordValidation;
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
</style>
</file>

<file path="core/ui/src/components/settings/CloudLogManagerConfigureModal.vue">
<template>
  <NsModal
    size="default"
    :visible="isShown"
    :isLoading="loading.setCloudLogManager"
    :primaryButtonDisabled="!subscription"
    @modal-hidden="onModalHidden"
    @modal-shown="onModalShown"
    @primary-click="setCloudLogManager"
  >
    <template slot="title">{{
      $t("cloud_log_manager_forwarder.configure_export_to_cloud_log_manager")
    }}</template>
    <template slot="content">
      <cv-form v-if="subscription">
        <NsInlineNotification
          v-if="clusterId"
          kind="info"
          :description="
            $t('cloud_log_manager_forwarder.cluster_id_notification', {
              clusterId: clusterId,
            })
          "
          :showCloseButton="false"
        />
        <NsToggle
          :label="$t('cloud_log_manager_forwarder.export_to_cloud_log_manager')"
          v-model="toggleEnabled"
          value="toggleEnabled"
        >
          <template slot="text-left">{{ $t("common.disabled") }}</template>
          <template slot="text-right">{{ $t("common.enabled") }}</template>
        </NsToggle>
        <NsTextInput
          v-if="toggleEnabled"
          :label="$t('cloud_log_manager_forwarder.address')"
          :placeholder="$t('cloud_log_manager_forwarder.address_placeholder')"
          v-model="address"
          :invalid-message="error.address"
        />
        <NsTextInput
          v-if="toggleEnabled"
          :label="$t('cloud_log_manager_forwarder.tenant')"
          v-model="tenant"
          :invalid-message="error.tenant"
        >
          <template slot="tooltip">
            <span>{{ $t("cloud_log_manager_forwarder.tenant_tooltip") }}</span>
          </template>
        </NsTextInput>
        <div v-if="toggleEnabled && this.configuration.last_timestamp != ''">
          <label for="startTime" :class="`${carbonPrefix}--label`">{{
            $t("cloud_log_manager_forwarder.export_starting_date")
          }}</label>
          <cv-radio-group :vertical="true">
            <cv-radio-button
              ref="radioVal"
              :label="
                $t('cloud_log_manager_forwarder.use_last_timestamp', {
                  timestamp: this.lastTimestampFormatted,
                })
              "
              value="last_timestamp"
              v-model="radioVal"
            />
            <cv-radio-button
              ref="radioVal"
              :label="$t('cloud_log_manager_forwarder.choose_a_datetime')"
              value="choose_date_time"
              v-model="radioVal"
            />
          </cv-radio-group>
        </div>
        <cv-row v-if="radioVal == 'choose_date_time' && toggleEnabled">
          <cv-column>
            <cv-date-picker
              kind="single"
              :date-label="$t('cloud_log_manager_forwarder.start_date')"
              class="interval-date mg-bottom-md"
              :cal-options="calOptions"
              v-model="date"
            >
            </cv-date-picker>
            <NsTimePicker
              hideClearButton
              dropDirection="up"
              :label="$t('cloud_log_manager_forwarder.start_time')"
              class="interval-time"
              v-model="time"
            >
            </NsTimePicker>
          </cv-column>
        </cv-row>
      </cv-form>
      <NsInlineNotification
        v-else
        kind="info"
        :title="
          $t('cloud_log_manager_forwarder.available_with_subscription_title')
        "
        :description="
          $t('cloud_log_manager_forwarder.available_with_subscription')
        "
        :showCloseButton="false"
        :actionLabel="$t('cloud_log_manager_forwarder.learn_more')"
        @action="goToMoreDetails"
      />
      <NsInlineNotification
        v-if="error.setCloudLogManager"
        kind="error"
        :title="$t('system_logs.loki.cannot_configure_forwarder')"
        :description="error.setCloudLogManager"
        :showCloseButton="false"
      />
    </template>
    <template slot="secondary-button">{{ $t("common.cancel") }}</template>
    <template slot="primary-button">{{ $t("common.configure") }}</template>
  </NsModal>
</template>
⋮----
<template slot="title">{{
      $t("cloud_log_manager_forwarder.configure_export_to_cloud_log_manager")
    }}</template>
<template slot="content">
      <cv-form v-if="subscription">
        <NsInlineNotification
          v-if="clusterId"
          kind="info"
          :description="
            $t('cloud_log_manager_forwarder.cluster_id_notification', {
              clusterId: clusterId,
            })
          "
          :showCloseButton="false"
        />
        <NsToggle
          :label="$t('cloud_log_manager_forwarder.export_to_cloud_log_manager')"
          v-model="toggleEnabled"
          value="toggleEnabled"
        >
          <template slot="text-left">{{ $t("common.disabled") }}</template>
          <template slot="text-right">{{ $t("common.enabled") }}</template>
        </NsToggle>
        <NsTextInput
          v-if="toggleEnabled"
          :label="$t('cloud_log_manager_forwarder.address')"
          :placeholder="$t('cloud_log_manager_forwarder.address_placeholder')"
          v-model="address"
          :invalid-message="error.address"
        />
        <NsTextInput
          v-if="toggleEnabled"
          :label="$t('cloud_log_manager_forwarder.tenant')"
          v-model="tenant"
          :invalid-message="error.tenant"
        >
          <template slot="tooltip">
            <span>{{ $t("cloud_log_manager_forwarder.tenant_tooltip") }}</span>
          </template>
        </NsTextInput>
        <div v-if="toggleEnabled && this.configuration.last_timestamp != ''">
          <label for="startTime" :class="`${carbonPrefix}--label`">{{
            $t("cloud_log_manager_forwarder.export_starting_date")
          }}</label>
          <cv-radio-group :vertical="true">
            <cv-radio-button
              ref="radioVal"
              :label="
                $t('cloud_log_manager_forwarder.use_last_timestamp', {
                  timestamp: this.lastTimestampFormatted,
                })
              "
              value="last_timestamp"
              v-model="radioVal"
            />
            <cv-radio-button
              ref="radioVal"
              :label="$t('cloud_log_manager_forwarder.choose_a_datetime')"
              value="choose_date_time"
              v-model="radioVal"
            />
          </cv-radio-group>
        </div>
        <cv-row v-if="radioVal == 'choose_date_time' && toggleEnabled">
          <cv-column>
            <cv-date-picker
              kind="single"
              :date-label="$t('cloud_log_manager_forwarder.start_date')"
              class="interval-date mg-bottom-md"
              :cal-options="calOptions"
              v-model="date"
            >
            </cv-date-picker>
            <NsTimePicker
              hideClearButton
              dropDirection="up"
              :label="$t('cloud_log_manager_forwarder.start_time')"
              class="interval-time"
              v-model="time"
            >
            </NsTimePicker>
          </cv-column>
        </cv-row>
      </cv-form>
      <NsInlineNotification
        v-else
        kind="info"
        :title="
          $t('cloud_log_manager_forwarder.available_with_subscription_title')
        "
        :description="
          $t('cloud_log_manager_forwarder.available_with_subscription')
        "
        :showCloseButton="false"
        :actionLabel="$t('cloud_log_manager_forwarder.learn_more')"
        @action="goToMoreDetails"
      />
      <NsInlineNotification
        v-if="error.setCloudLogManager"
        kind="error"
        :title="$t('system_logs.loki.cannot_configure_forwarder')"
        :description="error.setCloudLogManager"
        :showCloseButton="false"
      />
    </template>
⋮----
<template slot="text-left">{{ $t("common.disabled") }}</template>
<template slot="text-right">{{ $t("common.enabled") }}</template>
⋮----
<template slot="tooltip">
            <span>{{ $t("cloud_log_manager_forwarder.tenant_tooltip") }}</span>
          </template>
⋮----
<span>{{ $t("cloud_log_manager_forwarder.tenant_tooltip") }}</span>
⋮----
<label for="startTime" :class="`${carbonPrefix}--label`">{{
            $t("cloud_log_manager_forwarder.export_starting_date")
          }}</label>
⋮----
<template slot="secondary-button">{{ $t("common.cancel") }}</template>
<template slot="primary-button">{{ $t("common.configure") }}</template>
⋮----
<script>
import to from "await-to-js";
import { NsToggle, TaskService, DateTimeService } from "@nethserver/ns8-ui-lib";
import { carbonPrefixMixin } from "@carbon/vue/src/mixins";
export default {
  name: "CloudLogManagerConfigureModal",
  props: {
    isShown: {
      type: Boolean,
      required: true,
    },
    lokiToEdit: {
      type: Object,
      required: true,
    },
    configuration: {
      type: Object,
      required: true,
    },
    subscription: {
      type: Boolean,
      required: true,
    },
  },
  components: {
    NsToggle,
  },
  mixins: [carbonPrefixMixin, TaskService, DateTimeService],
  data() {
    return {
      radioVal: "last_timestamp",
      toggleEnabled: false,
      address: "",
      tenant: "",
      clusterId: "",
      date: "",
      time: "",
      lastTimestampFormatted: "",
      loading: {
        setCloudLogManager: false,
      },
      error: {
        address: "",
        tenant: "",
        setCloudLogManager: "",
      },
      calOptions: {
        dateFormat: "Y-m-d",
      },
    };
  },
  methods: {
    onModalHidden() {
      this.$emit("hide");
      this.resetModal();
    },
    resetModal() {
      this.radioVal = "last_timestamp";
      this.toggleEnabled = false;
      this.address = "";
      this.tenant = "";
      this.date = "";
      this.time = "";
      this.lastTimestampFormatted = "";
    },
    goToMoreDetails() {
      window.open(
        "https:
        "_blank"
      );
    },
    onModalShown() {
      if (
        this.configuration.status == "active" ||
        this.configuration.status == "failed"
      ) {
        this.toggleEnabled = true;
      }
      if (this.configuration.address == "") {
        this.address = "https:
      } else {
        this.address = this.configuration.address;
      }
      if (!this.configuration.tenant == "") {
        this.tenant = this.configuration.tenant;
      }
      if (this.configuration.cluster_id) {
        this.clusterId = this.configuration.cluster_id;
      }
      if (this.configuration.last_timestamp == "") {
        this.radioVal = "choose_date_time";
      } else {
        const last_timestamp_date = new Date(this.configuration.last_timestamp);
        this.lastTimestampFormatted = this.formatDate(
          last_timestamp_date,
          "Pp"
        );
      }
      this.date = this.formatDate(new Date(), "yyyy-MM-dd");
      this.time = "00:00";
    },
    validateCloudLogManagerInput() {
      this.clearErrors(this);
      let isValidationOk = true;
      if (!this.address) {
        this.error.address = this.$t("common.required");
        isValidationOk = false;
      } else if (
        !this.address.startsWith("http://") &&
        !this.address.startsWith("https://")
      ) {
        this.error.address = this.$t("error.invalid_url");
        isValidationOk = false;
      } else {
        try {
          const urlObj = new URL(this.address);
          const hostname = urlObj.hostname;
          const fqdnRegex = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.[a-zA-Z]{2,}$/;
          if (!fqdnRegex.test(hostname)) {
            this.error.address = this.$t("error.invalid_fqdn");
            isValidationOk = false;
          }
        } catch (e) {
          this.error.address = this.$t("error.invalid_url");
          isValidationOk = false;
        }
      }
      if (!this.tenant) {
        this.error.tenant = this.$t("common.required");
        isValidationOk = false;
      }
      return isValidationOk;
    },
    async setCloudLogManager() {
      if (this.toggleEnabled && !this.validateCloudLogManagerInput()) {
        return;
      }
      this.loading.setCloudLogManager = true;
      this.error.setCloudLogManager = "";
      const taskAction = "set-clm-forwarder";
      this.$root.$once(taskAction + "-aborted", this.setCloudLogManagerAborted);
      this.$root.$once(
        taskAction + "-completed",
        this.setCloudLogManagerCompleted
      );
      if (this.radioVal == "choose_date_time") {
        this.start_time = new Date("".concat(this.date, " ", this.time));
      } else {
        this.start_time = "";
      }
      if (this.toggleEnabled) {
        this.active = true;
      } else {
        this.active = false;
      }
      const res = await to(
        this.createModuleTaskForApp(this.lokiToEdit.instance_id, {
          action: taskAction,
          data: {
            active: this.active,
            address: this.address,
            tenant: this.tenant,
            start_time: this.start_time,
          },
          extra: {
            title: this.$t("action." + taskAction),
            description: this.$t("common.processing"),
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.setCloudLogManager = this.getErrorMessage(err);
        return;
      }
    },
    setCloudLogManagerAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.setCloudLogManager = this.$t("error.generic_error");
      this.loading.setCloudLogManager = false;
    },
    setCloudLogManagerCompleted() {
      this.loading.setCloudLogManager = false;
      this.onModalHidden();
      this.$emit("configure");
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
.interval-date {
  display: inline-flex;
  margin-right: $spacing-06;
}
.interval-time {
  display: inline-flex;
}
</style>
</file>

<file path="core/ui/src/components/settings/ConfigureFrontendProxyModal.vue">
<template>
  <NsModal
    size="default"
    :visible="isShown"
    :primary-button-disabled="loading.setTrustedProxies"
    :isLoading="loading.setTrustedProxies"
    @modal-hidden="onModalHidden"
    @primary-click="setTrustedProxies"
  >
    <template slot="title">{{
      isEditing
        ? $t("settings_http_routes.edit_frontend_proxy_node", {
            node: proxyConfig ? proxyConfig.nodeLabel : "",
          })
        : $t("settings_http_routes.add_frontend_proxy")
    }}</template>
    <template slot="content">
      <cv-form @submit.prevent="setTrustedProxies">
        <NsComboBox
          v-if="!isEditing"
          :key="nodeComboBoxKey"
          v-model="selectedNodeId"
          :label="$t('settings_http_routes.choose_node')"
          :title="$t('common.node')"
          :auto-filter="true"
          :auto-highlight="true"
          :options="nodes"
          :disabled="loading.setTrustedProxies"
          :invalid-message="error.node"
          light
          ref="node"
        />
        <cv-text-area
          v-model.trim="proxies_str"
          :placeholder="$t('common.eg_value', { value: '192.168.1.10' })"
          :label="$t('settings_http_routes.frontend_proxies')"
          :helper-text="$t('settings_http_routes.frontend_proxies_helper')"
          :invalid-message="error.proxies"
          :disabled="loading.setTrustedProxies"
          rows="4"
          ref="proxies"
        />
        <div class="bx--label label-with-tooltip">
          {{ $t("settings_http_routes.trust_depth") }}
          <cv-interactive-tooltip
            alignment="start"
            direction="top"
            class="info"
          >
            <template slot="content">
              {{ $t("settings_http_routes.trust_depth_tooltip") }}
            </template>
          </cv-interactive-tooltip>
        </div>
        <cv-number-input
          v-model="depth"
          :label="''"
          :aria-label="$t('settings_http_routes.trust_depth')"
          :helper-text="$t('settings_http_routes.trust_depth_helper')"
          :invalid-message="error.depth"
          :disabled="loading.setTrustedProxies"
          :min="1"
          :step="1"
          class="trust-depth"
          ref="depth"
        />
        <NsInlineNotification
          v-if="selectedNodeLabel"
          kind="warning"
          :title="$t('settings_http_routes.traefik_will_be_restarted')"
          :description="
            $t('settings_http_routes.frontend_proxy_restart_message', {
              node: selectedNodeLabel,
            })
          "
          :showCloseButton="false"
        />
        <div ref="setTrustedProxiesError">
          <NsInlineNotification
            v-if="error.setTrustedProxies"
            kind="error"
            :title="$t('action.set-trusted-proxies')"
            :description="error.setTrustedProxies"
            :showCloseButton="false"
          />
        </div>
      </cv-form>
    </template>
    <template slot="secondary-button">{{ $t("common.cancel") }}</template>
    <template slot="primary-button">{{
      isEditing
        ? $t("common.save")
        : $t("settings_http_routes.add_frontend_proxy")
    }}</template>
  </NsModal>
</template>
⋮----
<template slot="title">{{
      isEditing
        ? $t("settings_http_routes.edit_frontend_proxy_node", {
            node: proxyConfig ? proxyConfig.nodeLabel : "",
          })
        : $t("settings_http_routes.add_frontend_proxy")
    }}</template>
<template slot="content">
      <cv-form @submit.prevent="setTrustedProxies">
        <NsComboBox
          v-if="!isEditing"
          :key="nodeComboBoxKey"
          v-model="selectedNodeId"
          :label="$t('settings_http_routes.choose_node')"
          :title="$t('common.node')"
          :auto-filter="true"
          :auto-highlight="true"
          :options="nodes"
          :disabled="loading.setTrustedProxies"
          :invalid-message="error.node"
          light
          ref="node"
        />
        <cv-text-area
          v-model.trim="proxies_str"
          :placeholder="$t('common.eg_value', { value: '192.168.1.10' })"
          :label="$t('settings_http_routes.frontend_proxies')"
          :helper-text="$t('settings_http_routes.frontend_proxies_helper')"
          :invalid-message="error.proxies"
          :disabled="loading.setTrustedProxies"
          rows="4"
          ref="proxies"
        />
        <div class="bx--label label-with-tooltip">
          {{ $t("settings_http_routes.trust_depth") }}
          <cv-interactive-tooltip
            alignment="start"
            direction="top"
            class="info"
          >
            <template slot="content">
              {{ $t("settings_http_routes.trust_depth_tooltip") }}
            </template>
          </cv-interactive-tooltip>
        </div>
        <cv-number-input
          v-model="depth"
          :label="''"
          :aria-label="$t('settings_http_routes.trust_depth')"
          :helper-text="$t('settings_http_routes.trust_depth_helper')"
          :invalid-message="error.depth"
          :disabled="loading.setTrustedProxies"
          :min="1"
          :step="1"
          class="trust-depth"
          ref="depth"
        />
        <NsInlineNotification
          v-if="selectedNodeLabel"
          kind="warning"
          :title="$t('settings_http_routes.traefik_will_be_restarted')"
          :description="
            $t('settings_http_routes.frontend_proxy_restart_message', {
              node: selectedNodeLabel,
            })
          "
          :showCloseButton="false"
        />
        <div ref="setTrustedProxiesError">
          <NsInlineNotification
            v-if="error.setTrustedProxies"
            kind="error"
            :title="$t('action.set-trusted-proxies')"
            :description="error.setTrustedProxies"
            :showCloseButton="false"
          />
        </div>
      </cv-form>
    </template>
⋮----
{{ $t("settings_http_routes.trust_depth") }}
⋮----
<template slot="content">
              {{ $t("settings_http_routes.trust_depth_tooltip") }}
            </template>
⋮----
{{ $t("settings_http_routes.trust_depth_tooltip") }}
⋮----
<template slot="secondary-button">{{ $t("common.cancel") }}</template>
<template slot="primary-button">{{
      isEditing
        ? $t("common.save")
        : $t("settings_http_routes.add_frontend_proxy")
    }}</template>
⋮----
<script>
import to from "await-to-js";
import { UtilService, TaskService } from "@nethserver/ns8-ui-lib";
import { mapState } from "vuex";
import IpAddressService from "@/mixins/ipAddress";
export default {
  name: "ConfigureFrontendProxyModal",
  mixins: [UtilService, TaskService, IpAddressService],
  props: {
    isShown: Boolean,
    nodes: {
      type: Array,
      required: true,
    },
    proxyConfig: { type: [Object, null], default: null },
    isEditing: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      selectedNodeId: "",
      // [eventName, handler] pairs registered on $root, cleared on destroy
      setTrustedProxiesListeners: [],
      nodeComboBoxKey: 0,
      proxies_str: "",
      depth: 1,
      loading: {
        setTrustedProxies: false,
      },
      error: {
        node: "",
        proxies: "",
        depth: "",
        setTrustedProxies: "",
      },
    };
  },
  computed: {
    ...mapState(["isWebsocketConnected"]),
    selectedNode() {
      return this.nodes.find((node) => node.value === this.selectedNodeId);
    },
    selectedNodeLabel() {
      return this.selectedNode ? this.selectedNode.label : "";
    },
  },
  watch: {
    isWebsocketConnected: function (isConnected) {
      // safety net: nothing else clears the pending state if the request was cut off
      if (isConnected && this.loading.setTrustedProxies) {
        this.loading.setTrustedProxies = false;
        this.$emit("hide");
      }
    },
    isShown: function () {
      if (this.isShown) {
        this.clearErrors();
        if (this.isEditing && this.proxyConfig) {
          this.selectedNodeId = this.proxyConfig.nodeId;
          this.proxies_str = this.proxyConfig.proxies_str;
          this.depth = this.proxyConfig.depth;
        } else {
          this.selectedNodeId = "";
          this.proxies_str = "";
          this.depth = 1;
          this.nodeComboBoxKey++;
        }
      }
    },
    "error.setTrustedProxies": function () {
      if (this.error.setTrustedProxies) {
        this.$nextTick(() => {
          const el = this.$refs.setTrustedProxiesError;
          this.scrollToElement(el);
        });
      }
    },
  },
  beforeDestroy() {
    this.clearListeners(this.setTrustedProxiesListeners);
  },
  methods: {
    registerListener(eventName, handler) {
      this.$root.$once(eventName, handler);
      this.setTrustedProxiesListeners.push([eventName, handler]);
    },
    clearListeners(listeners) {
      listeners.forEach(([eventName, handler]) => {
        this.$root.$off(eventName, handler);
      });
      listeners.splice(0);
    },
    onModalHidden() {
      this.clearErrors();
      this.$emit("hide");
    },
    getProxyList() {
      return this.proxies_str
        .split("\n")
        .map((proxy) => proxy.trim())
        .filter((proxy) => proxy !== "");
    },
    validateSetTrustedProxies() {
      this.clearErrors();
      let isValidationOk = true;
      // the node field is only rendered when adding
      // check selectedNode, not selectedNodeId: the parent drops nodes from the
      // options as soon as they get a configuration, even while the modal is open
      if (!this.isEditing && !this.selectedNode) {
        this.error.node = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("node");
          isValidationOk = false;
        }
      }
      const proxyList = this.getProxyList();
      if (!proxyList.length) {
        this.error.proxies = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("proxies");
          isValidationOk = false;
        }
      } else {
        for (const proxy of proxyList) {
          if (!this.isIpAddress(proxy)) {
            this.error.proxies = this.$t(
              this.looksLikeIpv6(proxy)
                ? "settings_http_routes.invalid_ipv6"
                : "settings_http_routes.invalid_ipv4",
              { ip: proxy }
            );
            if (isValidationOk) {
              this.focusElement("proxies");
              isValidationOk = false;
            }
            break;
          }
        }
      }
      const depth = Number(this.depth);
      if (this.depth === "" || this.depth === null || Number.isNaN(depth)) {
        this.error.depth = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("depth");
          isValidationOk = false;
        }
      } else if (!Number.isInteger(depth) || depth < 1) {
        this.error.depth = this.$t("settings_http_routes.trust_depth_invalid");
        if (isValidationOk) {
          this.focusElement("depth");
          isValidationOk = false;
        }
      }
      return isValidationOk;
    },
    async setTrustedProxies() {
      if (!this.validateSetTrustedProxies()) {
        return;
      }
      const traefikInstanceId = this.isEditing
        ? this.proxyConfig.traefikInstance
        : this.selectedNode.traefikInstance;
      this.loading.setTrustedProxies = true;
      this.error.setTrustedProxies = "";
      const taskAction = "set-trusted-proxies";
      const eventId = this.getUuid();
      this.clearListeners(this.setTrustedProxiesListeners);
      this.registerListener(
        `${taskAction}-aborted-${eventId}`,
        this.setTrustedProxiesAborted
      );
      this.registerListener(
        `${taskAction}-validation-failed-${eventId}`,
        this.setTrustedProxiesValidationFailed
      );
      this.registerListener(
        `${taskAction}-validation-ok-${eventId}`,
        this.setTrustedProxiesValidationOk
      );
      this.registerListener(
        `${taskAction}-completed-${eventId}`,
        this.setTrustedProxiesCompleted
      );
      const res = await to(
        this.createModuleTaskForApp(traefikInstanceId, {
          action: taskAction,
          data: {
            proxies: this.getProxyList(),
            depth: Number(this.depth),
          },
          extra: {
            title: this.$t("action." + taskAction),
            description: this.$t("common.processing"),
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.setTrustedProxies = this.getErrorMessage(err);
        this.loading.setTrustedProxies = false;
        return;
      }
    },
    setTrustedProxiesAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.loading.setTrustedProxies = false;
      this.$emit("hide");
    },
    setTrustedProxiesValidationOk() {
      this.loading.setTrustedProxies = false;
      this.$emit("hide");
    },
    setTrustedProxiesValidationFailed(validationErrors) {
      this.loading.setTrustedProxies = false;
      let focusAlreadySet = false;
      for (const validationError of validationErrors) {
        const param = validationError.parameter;
        this.error[param] = this.getI18nStringWithFallback(
          "settings_http_routes." + validationError.error,
          "error." + validationError.error
        );
        if (!focusAlreadySet) {
          this.focusElement(param);
          focusAlreadySet = true;
        }
      }
    },
    setTrustedProxiesCompleted() {
      this.loading.setTrustedProxies = false;
      this.$emit("reloadTrustedProxies");
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
.label-with-tooltip {
  display: flex;
  align-items: center;
}
.label-with-tooltip ::v-deep .bx--tooltip__trigger {
  display: flex;
  margin-left: 0.25rem;
}
.bx--inline-notification {
  max-width: 38rem;
}
.trust-depth {
  max-width: 15rem;
}
.trust-depth ::v-deep input[type="number"] {
  font-family: inherit;
  font-size: 0.875rem;
  line-height: 1.42857;
  letter-spacing: 0.16px;
}
</style>
</file>

<file path="core/ui/src/components/settings/ConfirmRevoke2FaModal.vue">
<template>
  <NsModal
    size="default"
    :visible="isShown"
    @modal-hidden="$emit('hide')"
    @primary-click="$emit('confirm')"
  >
    <template slot="title">{{ $t("settings_account.revoke_2fa") }}</template>
    <template slot="content">
      <div>{{ $t("settings_account.confirm_revoke_2fa") }}</div>
    </template>
    <template slot="secondary-button">{{ $t("common.cancel") }}</template>
    <template slot="primary-button">{{
      $t("settings_account.revoke_2fa")
    }}</template>
  </NsModal>
</template>
⋮----
<template slot="title">{{ $t("settings_account.revoke_2fa") }}</template>
<template slot="content">
      <div>{{ $t("settings_account.confirm_revoke_2fa") }}</div>
    </template>
⋮----
<div>{{ $t("settings_account.confirm_revoke_2fa") }}</div>
⋮----
<template slot="secondary-button">{{ $t("common.cancel") }}</template>
<template slot="primary-button">{{
      $t("settings_account.revoke_2fa")
    }}</template>
⋮----
<script>
import { UtilService, IconService } from "@nethserver/ns8-ui-lib";
export default {
  name: "ConfirmRevoke2FaModal",
  mixins: [UtilService, IconService],
  props: {
    isShown: Boolean,
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
</style>
</file>

<file path="core/ui/src/components/settings/CreateAdminModal.vue">
<template>
  <NsModal
    size="default"
    :visible="isShown"
    :primary-button-disabled="loading.addUser"
    :isLoading="loading.addUser"
    @modal-hidden="onModalHidden"
    @primary-click="addUser"
    class="no-pad-modal"
  >
    <template slot="title">{{
      $t("settings_cluster_admins.create_admin")
    }}</template>
    <template slot="content">
      <cv-form @submit.prevent="addUser">
        <NsTextInput
          v-model.trim="username"
          :label="$t('settings_cluster_admins.username')"
          :invalid-message="error.user"
          :disabled="loading.addUser"
          data-modal-primary-focus
          ref="user"
        />
        <NsTextInput
          v-model.trim="displayName"
          :label="
            $t('settings_cluster_admins.display_name') +
            ' (' +
            $t('common.optional') +
            ')'
          "
          :invalid-message="error.display_name"
          :disabled="loading.addUser"
          ref="display_name"
        />
        <NsPasswordInput
          :newPasswordLabel="$t('password.password')"
          :confirmPasswordLabel="$t('password.re_enter_password')"
          v-model="newPassword"
          @passwordValidation="onPasswordValidation"
          :newPasswordInvalidMessage="$t(error.newPassword)"
          :confirmPasswordInvalidMessage="$t(error.confirmPassword)"
          :passwordHideLabel="$t('password.hide_password')"
          :passwordShowLabel="$t('password.show_password')"
          :lengthLabel="$t('password.long_enough')"
          :lowercaseLabel="$t('password.lowercase_letter')"
          :uppercaseLabel="$t('password.uppercase_letter')"
          :numberLabel="$t('password.number')"
          :symbolLabel="$t('password.symbol')"
          :equalLabel="$t('password.equal')"
          :focus="focusPasswordField"
          :clearConfirmPasswordCommand="clearConfirmPasswordCommand"
        />
        <div ref="addUserError">
          <NsInlineNotification
            v-if="error.addUser"
            kind="error"
            :title="$t('settings_cluster_admins.create_admin')"
            :description="error.addUser"
            :showCloseButton="false"
          />
        </div>
      </cv-form>
    </template>
    <template slot="secondary-button">{{ $t("common.cancel") }}</template>
    <template slot="primary-button">{{
      $t("settings_cluster_admins.create_admin")
    }}</template>
  </NsModal>
</template>
⋮----
<template slot="title">{{
      $t("settings_cluster_admins.create_admin")
    }}</template>
<template slot="content">
      <cv-form @submit.prevent="addUser">
        <NsTextInput
          v-model.trim="username"
          :label="$t('settings_cluster_admins.username')"
          :invalid-message="error.user"
          :disabled="loading.addUser"
          data-modal-primary-focus
          ref="user"
        />
        <NsTextInput
          v-model.trim="displayName"
          :label="
            $t('settings_cluster_admins.display_name') +
            ' (' +
            $t('common.optional') +
            ')'
          "
          :invalid-message="error.display_name"
          :disabled="loading.addUser"
          ref="display_name"
        />
        <NsPasswordInput
          :newPasswordLabel="$t('password.password')"
          :confirmPasswordLabel="$t('password.re_enter_password')"
          v-model="newPassword"
          @passwordValidation="onPasswordValidation"
          :newPasswordInvalidMessage="$t(error.newPassword)"
          :confirmPasswordInvalidMessage="$t(error.confirmPassword)"
          :passwordHideLabel="$t('password.hide_password')"
          :passwordShowLabel="$t('password.show_password')"
          :lengthLabel="$t('password.long_enough')"
          :lowercaseLabel="$t('password.lowercase_letter')"
          :uppercaseLabel="$t('password.uppercase_letter')"
          :numberLabel="$t('password.number')"
          :symbolLabel="$t('password.symbol')"
          :equalLabel="$t('password.equal')"
          :focus="focusPasswordField"
          :clearConfirmPasswordCommand="clearConfirmPasswordCommand"
        />
        <div ref="addUserError">
          <NsInlineNotification
            v-if="error.addUser"
            kind="error"
            :title="$t('settings_cluster_admins.create_admin')"
            :description="error.addUser"
            :showCloseButton="false"
          />
        </div>
      </cv-form>
    </template>
<template slot="secondary-button">{{ $t("common.cancel") }}</template>
<template slot="primary-button">{{
      $t("settings_cluster_admins.create_admin")
    }}</template>
⋮----
<script>
import { UtilService, TaskService, IconService } from "@nethserver/ns8-ui-lib";
import to from "await-to-js";
export default {
  name: "CreateAdminModal",
  mixins: [UtilService, TaskService, IconService],
  props: {
    isShown: Boolean,
    admin: { type: [Object, null] },
  },
  data() {
    return {
      username: "",
      displayName: "",
      selectedGroups: [],
      newPassword: "",
      passwordValidation: null,
      focusPasswordField: { element: "" },
      clearConfirmPasswordCommand: 0,
      loading: {
        addUser: false,
      },
      error: {
        addUser: "",
        user: "",
        display_name: "",
        newPassword: "",
        confirmPassword: "",
        groups: "",
      },
    };
  },
  watch: {
    isShown: function () {
      if (this.isShown) {
        this.clearErrors();
        this.username = "";
        this.displayName = "";
        this.newPassword = "";
        this.clearConfirmPasswordCommand++;
      }
    },
    "error.addUser": function () {
      if (this.error.addUser) {
        this.$nextTick(() => {
          const el = this.$refs.addUserError;
          this.scrollToElement(el);
        });
      }
    },
  },
  methods: {
    validateAddUser() {
      this.clearErrors();
      let isValidationOk = true;
      if (!this.username) {
        this.error.user = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("user");
          isValidationOk = false;
        }
      }
      if (!this.newPassword) {
        this.error.newPassword = this.$t("common.required");
        if (isValidationOk) {
          this.focusPasswordField = { element: "newPassword" };
          isValidationOk = false;
        }
      } else {
        if (this.currentPassword === this.newPassword) {
          if (!this.error.newPassword) {
            this.error.newPassword = this.$t(
              "password.old_new_passwords_must_be_different"
            );
          }
          if (isValidationOk) {
            this.focusPasswordField = { element: "newPassword" };
            isValidationOk = false;
          }
        }
        if (
          !this.passwordValidation.isLengthOk ||
          !this.passwordValidation.isLowercaseOk ||
          !this.passwordValidation.isUppercaseOk ||
          !this.passwordValidation.isNumberOk ||
          !this.passwordValidation.isSymbolOk
        ) {
          if (!this.error.newPassword) {
            this.error.newPassword = this.$t("password.password_not_secure");
          }
          if (isValidationOk) {
            this.focusPasswordField = { element: "newPassword" };
            isValidationOk = false;
          }
        }
        if (!this.passwordValidation.isEqualOk) {
          if (!this.error.newPassword) {
            this.error.newPassword = this.$t("password.passwords_do_not_match");
          }
          if (!this.error.confirmPassword) {
            this.error.confirmPassword = this.$t(
              "password.passwords_do_not_match"
            );
          }
          if (isValidationOk) {
            this.focusPasswordField = { element: "confirmPassword" };
            isValidationOk = false;
          }
        }
      }
      return isValidationOk;
    },
    async addUser() {
      if (!this.validateAddUser()) {
        return;
      }
      this.loading.addUser = true;
      this.error.addUser = "";
      const taskAction = "add-user";
      const eventId = this.getUuid();
      this.$root.$once(`${taskAction}-aborted-${eventId}`, this.addUserAborted);
      this.$root.$once(
        `${taskAction}-validation-ok-${eventId}`,
        this.addUserValidationOk
      );
      this.$root.$once(
        `${taskAction}-validation-failed-${eventId}`,
        this.addUserValidationFailed
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.addUserCompleted
      );
      const [errPasswordHash, passwordHash] = await to(
        this.getSha256(this.newPassword)
      );
      if (errPasswordHash) {
        console.error(`error getting password sha256`, errPasswordHash);
        this.error.addUser = this.getErrorMessage(errPasswordHash);
        this.loading.addUser = false;
        return;
      }
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {
            user: this.username,
            set: {
              display_name: this.displayName,
            },
            password_hash: passwordHash,
            grant: [
              {
                role: "owner",
                on: "*",
              },
            ],
          },
          extra: {
            title: this.$t("settings_cluster_admins.create_admin_admin", {
              admin: this.username,
            }),
            description: this.$t("common.processing"),
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.addUser = this.getErrorMessage(err);
        this.loading.addUser = false;
        return;
      }
    },
    addUserAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.loading.addUser = false;
      this.$emit("hide");
    },
    addUserValidationOk() {
      this.loading.addUser = false;
      this.$emit("hide");
    },
    addUserValidationFailed(validationErrors) {
      this.loading.addUser = false;
      let focusAlreadySet = false;
      for (const validationError of validationErrors) {
        const param = validationError.parameter;
        this.error[param] = this.$t(
          "settings_cluster_admins." + validationError.error
        );
        if (!focusAlreadySet) {
          this.focusElement(param);
          focusAlreadySet = true;
        }
      }
    },
    addUserCompleted() {
      this.loading.addUser = false;
      this.$emit("adminCreated");
    },
    onModalHidden() {
      this.clearErrors();
      this.$emit("hide");
    },
    onPasswordValidation(passwordValidation) {
      this.passwordValidation = passwordValidation;
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
</style>
</file>

<file path="core/ui/src/components/settings/CreateOrEditHttpRouteModal.vue">
<template>
  <NsModal
    size="default"
    :visible="isShown"
    :primary-button-disabled="loading.setRoute"
    :isLoading="loading.setRoute"
    @modal-hidden="onModalHidden"
    @primary-click="createOrEditRoute"
  >
    <template slot="title">{{
      isEditing
        ? $t("settings_http_routes.edit_route_route", { route: route.instance })
        : $t("settings_http_routes.create_route")
    }}</template>
    <template slot="content">
      <cv-form @submit.prevent="createOrEditRoute">
        <NsTextInput
          v-model.trim="instance"
          :placeholder="$t('settings_http_routes.name_placeholder')"
          :label="$t('settings_http_routes.name')"
          :invalid-message="error.instance"
          :disabled="isEditing || loading.setRoute"
          data-modal-primary-focus
          ref="instance"
        />
        <NsComboBox
          v-if="user_created"
          v-model="selectedNodeId"
          :label="$t('common.choose')"
          :title="$t('common.node')"
          :auto-filter="true"
          :auto-highlight="true"
          :options="nodes"
          :disabled="isEditing || loading.setRoute"
          :invalid-message="error.node"
          light
          tooltipAlignment="start"
          tooltipDirection="top"
          ref="node"
        >
          <template slot="tooltip">
            {{ $t("settings_http_routes.node_helper") }}
          </template>
        </NsComboBox>
        <NsTextInput
          v-if="user_created"
          v-model.trim="url"
          :placeholder="$t('settings_http_routes.url_placeholder')"
          :label="$t('settings_http_routes.url')"
          :helper-text="$t('settings_http_routes.url_helper')"
          :invalid-message="error.url"
          :disabled="loading.setRoute || !user_created"
          ref="url"
        >
          <template slot="tooltip">
            <span>{{ $t("settings_http_routes.url_tooltip") }}</span>
          </template>
        </NsTextInput>
        <NsToggle
          v-if="user_created"
          class="toggle-dependent"
          :label="$t('settings_http_routes.skip_cert_verify')"
          value="stripPrefixValue"
          :form-item="true"
          v-model="skip_cert_verify"
          :disabled="
            loading.setRoute || !url.startsWith('https://') || !user_created
          "
          ref="skip_cert_verify"
        >
          <template slot="tooltip">
            <span>{{ $t("settings_http_routes.skipCertVerify_tooltip") }}</span>
          </template>
          <template slot="text-left">{{ $t("common.disabled") }}</template>
          <template slot="text-right">{{ $t("common.enabled") }}</template>
        </NsToggle>
        <NsTextInput
          v-if="user_created"
          v-model.trim="host"
          :placeholder="$t('settings_http_routes.host_placeholder')"
          :label="
            $t('settings_http_routes.host') + ' (' + $t('common.optional') + ')'
          "
          :helper-text="$t('settings_http_routes.host_helper')"
          :invalid-message="error.host"
          :disabled="loading.setRoute || !user_created"
          ref="host"
        >
          <template slot="tooltip">
            <span>{{ $t("settings_http_routes.host_tooltip") }}</span>
          </template>
        </NsTextInput>
        <NsToggle
          v-if="user_created"
          :label="$t('settings_http_routes.request_lets_encrypt_certificate')"
          value="letsEncryptValue"
          class="toggle-dependent"
          :form-item="true"
          v-model="lets_encrypt"
          :disabled="loading.setRoute || !user_created || !host"
          ref="lets_encrypt"
        >
          <template slot="text-left">{{ $t("common.disabled") }}</template>
          <template slot="text-right">{{ $t("common.enabled") }}</template>
        </NsToggle>
        <NsInlineNotification
          v-if="isEditing && route.lets_encrypt && !lets_encrypt"
          kind="warning"
          :title="$t('settings_http_routes.traefik_will_be_restarted')"
          :description="
            $t('settings_http_routes.revoke_certificate_message', {
              node: route.node,
            })
          "
          :showCloseButton="false"
        />
        <NsTextInput
          v-if="user_created"
          v-model.trim="path"
          :placeholder="$t('settings_http_routes.path_placeholder')"
          :label="
            $t('settings_http_routes.path') + ' (' + $t('common.optional') + ')'
          "
          :invalid-message="error.path"
          :disabled="loading.setRoute || !user_created"
          ref="path"
        >
          <template slot="tooltip">
            <span>{{ $t("settings_http_routes.path_tooltip") }}</span>
          </template>
        </NsTextInput>
        <NsToggle
          v-if="user_created"
          :label="$t('settings_http_routes.strip_prefix')"
          value="stripPrefixValue"
          class="toggle-dependent"
          :form-item="true"
          v-model="strip_prefix"
          :disabled="loading.setRoute || !user_created || !path"
          ref="strip_prefix"
        >
          <template slot="tooltip">
            <i18n path="settings_http_routes.strip_prefix_tooltip" tag="span">
              <template v-slot:traefikPrefixesOption>
                <cv-link
                  href="https://doc.traefik.io/traefik/middlewares/http/stripprefix/"
                  target="_blank"
                  rel="noreferrer"
                >
                  {{ $t("settings_http_routes.traefik_prefixes_option") }}
                </cv-link>
              </template>
            </i18n>
          </template>
          <template slot="text-left">{{ $t("common.disabled") }}</template>
          <template slot="text-right">{{ $t("common.enabled") }}</template>
        </NsToggle>
        <NsToggle
          v-if="user_created"
          :label="$t('settings_http_routes.slash_redirect')"
          value="slashRedirectValue"
          class="toggle-dependent"
          :form-item="true"
          v-model="slash_redirect"
          :disabled="loading.setRoute || !user_created || !path"
          ref="slash_redirect"
        >
          <template slot="tooltip">
            {{ $t("settings_http_routes.slash_redirect_tooltip") }}
          </template>
          <template slot="text-left">{{ $t("common.disabled") }}</template>
          <template slot="text-right">{{ $t("common.enabled") }}</template>
        </NsToggle>
        <template v-if="user_created">
          <cv-accordion ref="accordion" class="maxwidth mg-bottom">
            <cv-accordion-item
              :open="isAccordionOpen"
              @click="toggleAccordionStatus"
            >
              <template slot="title">{{ $t("common.advanced") }}</template>
              <template slot="content">
                <NsToggle
                  v-if="user_created"
                  :label="$t('settings_http_routes.http2https')"
                  value="http2httpsValue"
                  :form-item="true"
                  v-model="http2https"
                  :disabled="loading.setRoute || !user_created"
                  ref="http2https"
                >
                  <template slot="text-left">{{
                    $t("common.disabled")
                  }}</template>
                  <template slot="text-right">{{
                    $t("common.enabled")
                  }}</template>
                </NsToggle>
                <cv-text-area
                  v-model.trim="ip_allowlist_str"
                  :placeholder="
                    $t('settings_http_routes.ip_allowlist_placeholder')
                  "
                  :label="$t('settings_http_routes.ip_allowlist')"
                  :invalid-message="error.ip_allowlist"
                  :disabled="loading.setRoute"
                  ref="ip_allowlist"
                  :helper-text="$t('settings_http_routes.ip_allowlist_helper')"
              /></template>
            </cv-accordion-item>
          </cv-accordion>
        </template>
        <template v-else>
          <cv-text-area
            v-model.trim="ip_allowlist_str"
            :placeholder="$t('settings_http_routes.ip_allowlist_placeholder')"
            :label="$t('settings_http_routes.ip_allowlist')"
            :invalid-message="error.ip_allowlist"
            :disabled="loading.setRoute"
            ref="ip_allowlist"
            :helper-text="$t('settings_http_routes.ip_allowlist_helper')"
        /></template>
        <div ref="setRouteError">
          <NsInlineNotification
            v-if="error.setRoute"
            kind="error"
            :title="$t('action.set-route')"
            :description="error.setRoute"
            :showCloseButton="false"
          />
          <NsInlineNotification
            v-if="validationErrorDetails.length"
            kind="error"
            :title="$t('settings_tls_certificates.cannot_obtain_certificate')"
            :showCloseButton="false"
          >
            <template #description>
              <div class="flex flex-col gap-2">
                <p
                  v-for="(detail, index) in validationErrorDetails"
                  :key="index"
                >
                  {{ detail }}
                </p>
              </div>
            </template>
          </NsInlineNotification>
        </div>
      </cv-form>
    </template>
    <template slot="secondary-button">{{ $t("common.cancel") }}</template>
    <template slot="primary-button">{{
      isEditing
        ? $t("settings_http_routes.save_route")
        : $t("settings_http_routes.create_route")
    }}</template>
  </NsModal>
</template>
⋮----
<template slot="title">{{
      isEditing
        ? $t("settings_http_routes.edit_route_route", { route: route.instance })
        : $t("settings_http_routes.create_route")
    }}</template>
<template slot="content">
      <cv-form @submit.prevent="createOrEditRoute">
        <NsTextInput
          v-model.trim="instance"
          :placeholder="$t('settings_http_routes.name_placeholder')"
          :label="$t('settings_http_routes.name')"
          :invalid-message="error.instance"
          :disabled="isEditing || loading.setRoute"
          data-modal-primary-focus
          ref="instance"
        />
        <NsComboBox
          v-if="user_created"
          v-model="selectedNodeId"
          :label="$t('common.choose')"
          :title="$t('common.node')"
          :auto-filter="true"
          :auto-highlight="true"
          :options="nodes"
          :disabled="isEditing || loading.setRoute"
          :invalid-message="error.node"
          light
          tooltipAlignment="start"
          tooltipDirection="top"
          ref="node"
        >
          <template slot="tooltip">
            {{ $t("settings_http_routes.node_helper") }}
          </template>
        </NsComboBox>
        <NsTextInput
          v-if="user_created"
          v-model.trim="url"
          :placeholder="$t('settings_http_routes.url_placeholder')"
          :label="$t('settings_http_routes.url')"
          :helper-text="$t('settings_http_routes.url_helper')"
          :invalid-message="error.url"
          :disabled="loading.setRoute || !user_created"
          ref="url"
        >
          <template slot="tooltip">
            <span>{{ $t("settings_http_routes.url_tooltip") }}</span>
          </template>
        </NsTextInput>
        <NsToggle
          v-if="user_created"
          class="toggle-dependent"
          :label="$t('settings_http_routes.skip_cert_verify')"
          value="stripPrefixValue"
          :form-item="true"
          v-model="skip_cert_verify"
          :disabled="
            loading.setRoute || !url.startsWith('https://') || !user_created
          "
          ref="skip_cert_verify"
        >
          <template slot="tooltip">
            <span>{{ $t("settings_http_routes.skipCertVerify_tooltip") }}</span>
          </template>
          <template slot="text-left">{{ $t("common.disabled") }}</template>
          <template slot="text-right">{{ $t("common.enabled") }}</template>
        </NsToggle>
        <NsTextInput
          v-if="user_created"
          v-model.trim="host"
          :placeholder="$t('settings_http_routes.host_placeholder')"
          :label="
            $t('settings_http_routes.host') + ' (' + $t('common.optional') + ')'
          "
          :helper-text="$t('settings_http_routes.host_helper')"
          :invalid-message="error.host"
          :disabled="loading.setRoute || !user_created"
          ref="host"
        >
          <template slot="tooltip">
            <span>{{ $t("settings_http_routes.host_tooltip") }}</span>
          </template>
        </NsTextInput>
        <NsToggle
          v-if="user_created"
          :label="$t('settings_http_routes.request_lets_encrypt_certificate')"
          value="letsEncryptValue"
          class="toggle-dependent"
          :form-item="true"
          v-model="lets_encrypt"
          :disabled="loading.setRoute || !user_created || !host"
          ref="lets_encrypt"
        >
          <template slot="text-left">{{ $t("common.disabled") }}</template>
          <template slot="text-right">{{ $t("common.enabled") }}</template>
        </NsToggle>
        <NsInlineNotification
          v-if="isEditing && route.lets_encrypt && !lets_encrypt"
          kind="warning"
          :title="$t('settings_http_routes.traefik_will_be_restarted')"
          :description="
            $t('settings_http_routes.revoke_certificate_message', {
              node: route.node,
            })
          "
          :showCloseButton="false"
        />
        <NsTextInput
          v-if="user_created"
          v-model.trim="path"
          :placeholder="$t('settings_http_routes.path_placeholder')"
          :label="
            $t('settings_http_routes.path') + ' (' + $t('common.optional') + ')'
          "
          :invalid-message="error.path"
          :disabled="loading.setRoute || !user_created"
          ref="path"
        >
          <template slot="tooltip">
            <span>{{ $t("settings_http_routes.path_tooltip") }}</span>
          </template>
        </NsTextInput>
        <NsToggle
          v-if="user_created"
          :label="$t('settings_http_routes.strip_prefix')"
          value="stripPrefixValue"
          class="toggle-dependent"
          :form-item="true"
          v-model="strip_prefix"
          :disabled="loading.setRoute || !user_created || !path"
          ref="strip_prefix"
        >
          <template slot="tooltip">
            <i18n path="settings_http_routes.strip_prefix_tooltip" tag="span">
              <template v-slot:traefikPrefixesOption>
                <cv-link
                  href="https://doc.traefik.io/traefik/middlewares/http/stripprefix/"
                  target="_blank"
                  rel="noreferrer"
                >
                  {{ $t("settings_http_routes.traefik_prefixes_option") }}
                </cv-link>
              </template>
            </i18n>
          </template>
          <template slot="text-left">{{ $t("common.disabled") }}</template>
          <template slot="text-right">{{ $t("common.enabled") }}</template>
        </NsToggle>
        <NsToggle
          v-if="user_created"
          :label="$t('settings_http_routes.slash_redirect')"
          value="slashRedirectValue"
          class="toggle-dependent"
          :form-item="true"
          v-model="slash_redirect"
          :disabled="loading.setRoute || !user_created || !path"
          ref="slash_redirect"
        >
          <template slot="tooltip">
            {{ $t("settings_http_routes.slash_redirect_tooltip") }}
          </template>
          <template slot="text-left">{{ $t("common.disabled") }}</template>
          <template slot="text-right">{{ $t("common.enabled") }}</template>
        </NsToggle>
        <template v-if="user_created">
          <cv-accordion ref="accordion" class="maxwidth mg-bottom">
            <cv-accordion-item
              :open="isAccordionOpen"
              @click="toggleAccordionStatus"
            >
              <template slot="title">{{ $t("common.advanced") }}</template>
              <template slot="content">
                <NsToggle
                  v-if="user_created"
                  :label="$t('settings_http_routes.http2https')"
                  value="http2httpsValue"
                  :form-item="true"
                  v-model="http2https"
                  :disabled="loading.setRoute || !user_created"
                  ref="http2https"
                >
                  <template slot="text-left">{{
                    $t("common.disabled")
                  }}</template>
                  <template slot="text-right">{{
                    $t("common.enabled")
                  }}</template>
                </NsToggle>
                <cv-text-area
                  v-model.trim="ip_allowlist_str"
                  :placeholder="
                    $t('settings_http_routes.ip_allowlist_placeholder')
                  "
                  :label="$t('settings_http_routes.ip_allowlist')"
                  :invalid-message="error.ip_allowlist"
                  :disabled="loading.setRoute"
                  ref="ip_allowlist"
                  :helper-text="$t('settings_http_routes.ip_allowlist_helper')"
              /></template>
            </cv-accordion-item>
          </cv-accordion>
        </template>
        <template v-else>
          <cv-text-area
            v-model.trim="ip_allowlist_str"
            :placeholder="$t('settings_http_routes.ip_allowlist_placeholder')"
            :label="$t('settings_http_routes.ip_allowlist')"
            :invalid-message="error.ip_allowlist"
            :disabled="loading.setRoute"
            ref="ip_allowlist"
            :helper-text="$t('settings_http_routes.ip_allowlist_helper')"
        /></template>
        <div ref="setRouteError">
          <NsInlineNotification
            v-if="error.setRoute"
            kind="error"
            :title="$t('action.set-route')"
            :description="error.setRoute"
            :showCloseButton="false"
          />
          <NsInlineNotification
            v-if="validationErrorDetails.length"
            kind="error"
            :title="$t('settings_tls_certificates.cannot_obtain_certificate')"
            :showCloseButton="false"
          >
            <template #description>
              <div class="flex flex-col gap-2">
                <p
                  v-for="(detail, index) in validationErrorDetails"
                  :key="index"
                >
                  {{ detail }}
                </p>
              </div>
            </template>
          </NsInlineNotification>
        </div>
      </cv-form>
    </template>
⋮----
<template slot="tooltip">
            {{ $t("settings_http_routes.node_helper") }}
          </template>
⋮----
{{ $t("settings_http_routes.node_helper") }}
⋮----
<template slot="tooltip">
            <span>{{ $t("settings_http_routes.url_tooltip") }}</span>
          </template>
⋮----
<span>{{ $t("settings_http_routes.url_tooltip") }}</span>
⋮----
<template slot="tooltip">
            <span>{{ $t("settings_http_routes.skipCertVerify_tooltip") }}</span>
          </template>
⋮----
<span>{{ $t("settings_http_routes.skipCertVerify_tooltip") }}</span>
⋮----
<template slot="text-left">{{ $t("common.disabled") }}</template>
<template slot="text-right">{{ $t("common.enabled") }}</template>
⋮----
<template slot="tooltip">
            <span>{{ $t("settings_http_routes.host_tooltip") }}</span>
          </template>
⋮----
<span>{{ $t("settings_http_routes.host_tooltip") }}</span>
⋮----
<template slot="text-left">{{ $t("common.disabled") }}</template>
<template slot="text-right">{{ $t("common.enabled") }}</template>
⋮----
<template slot="tooltip">
            <span>{{ $t("settings_http_routes.path_tooltip") }}</span>
          </template>
⋮----
<span>{{ $t("settings_http_routes.path_tooltip") }}</span>
⋮----
<template slot="tooltip">
            <i18n path="settings_http_routes.strip_prefix_tooltip" tag="span">
              <template v-slot:traefikPrefixesOption>
                <cv-link
                  href="https://doc.traefik.io/traefik/middlewares/http/stripprefix/"
                  target="_blank"
                  rel="noreferrer"
                >
                  {{ $t("settings_http_routes.traefik_prefixes_option") }}
                </cv-link>
              </template>
            </i18n>
          </template>
⋮----
<template v-slot:traefikPrefixesOption>
                <cv-link
                  href="https://doc.traefik.io/traefik/middlewares/http/stripprefix/"
                  target="_blank"
                  rel="noreferrer"
                >
                  {{ $t("settings_http_routes.traefik_prefixes_option") }}
                </cv-link>
              </template>
⋮----
{{ $t("settings_http_routes.traefik_prefixes_option") }}
⋮----
<template slot="text-left">{{ $t("common.disabled") }}</template>
<template slot="text-right">{{ $t("common.enabled") }}</template>
⋮----
<template slot="tooltip">
            {{ $t("settings_http_routes.slash_redirect_tooltip") }}
          </template>
⋮----
{{ $t("settings_http_routes.slash_redirect_tooltip") }}
⋮----
<template slot="text-left">{{ $t("common.disabled") }}</template>
<template slot="text-right">{{ $t("common.enabled") }}</template>
⋮----
<template v-if="user_created">
          <cv-accordion ref="accordion" class="maxwidth mg-bottom">
            <cv-accordion-item
              :open="isAccordionOpen"
              @click="toggleAccordionStatus"
            >
              <template slot="title">{{ $t("common.advanced") }}</template>
              <template slot="content">
                <NsToggle
                  v-if="user_created"
                  :label="$t('settings_http_routes.http2https')"
                  value="http2httpsValue"
                  :form-item="true"
                  v-model="http2https"
                  :disabled="loading.setRoute || !user_created"
                  ref="http2https"
                >
                  <template slot="text-left">{{
                    $t("common.disabled")
                  }}</template>
                  <template slot="text-right">{{
                    $t("common.enabled")
                  }}</template>
                </NsToggle>
                <cv-text-area
                  v-model.trim="ip_allowlist_str"
                  :placeholder="
                    $t('settings_http_routes.ip_allowlist_placeholder')
                  "
                  :label="$t('settings_http_routes.ip_allowlist')"
                  :invalid-message="error.ip_allowlist"
                  :disabled="loading.setRoute"
                  ref="ip_allowlist"
                  :helper-text="$t('settings_http_routes.ip_allowlist_helper')"
              /></template>
            </cv-accordion-item>
          </cv-accordion>
        </template>
⋮----
<template slot="title">{{ $t("common.advanced") }}</template>
<template slot="content">
                <NsToggle
                  v-if="user_created"
                  :label="$t('settings_http_routes.http2https')"
                  value="http2httpsValue"
                  :form-item="true"
                  v-model="http2https"
                  :disabled="loading.setRoute || !user_created"
                  ref="http2https"
                >
                  <template slot="text-left">{{
                    $t("common.disabled")
                  }}</template>
                  <template slot="text-right">{{
                    $t("common.enabled")
                  }}</template>
                </NsToggle>
                <cv-text-area
                  v-model.trim="ip_allowlist_str"
                  :placeholder="
                    $t('settings_http_routes.ip_allowlist_placeholder')
                  "
                  :label="$t('settings_http_routes.ip_allowlist')"
                  :invalid-message="error.ip_allowlist"
                  :disabled="loading.setRoute"
                  ref="ip_allowlist"
                  :helper-text="$t('settings_http_routes.ip_allowlist_helper')"
              /></template>
⋮----
<template slot="text-left">{{
                    $t("common.disabled")
                  }}</template>
<template slot="text-right">{{
                    $t("common.enabled")
                  }}</template>
⋮----
<template v-else>
          <cv-text-area
            v-model.trim="ip_allowlist_str"
            :placeholder="$t('settings_http_routes.ip_allowlist_placeholder')"
            :label="$t('settings_http_routes.ip_allowlist')"
            :invalid-message="error.ip_allowlist"
            :disabled="loading.setRoute"
            ref="ip_allowlist"
            :helper-text="$t('settings_http_routes.ip_allowlist_helper')"
        /></template>
⋮----
<template #description>
              <div class="flex flex-col gap-2">
                <p
                  v-for="(detail, index) in validationErrorDetails"
                  :key="index"
                >
                  {{ detail }}
                </p>
              </div>
            </template>
⋮----
{{ detail }}
⋮----
<template slot="secondary-button">{{ $t("common.cancel") }}</template>
<template slot="primary-button">{{
      isEditing
        ? $t("settings_http_routes.save_route")
        : $t("settings_http_routes.create_route")
    }}</template>
⋮----
<script>
import to from "await-to-js";
import { UtilService, TaskService } from "@nethserver/ns8-ui-lib";
import IpAddressService from "@/mixins/ipAddress";
export default {
  name: "CreateOrEditHttpRouteModal",
  mixins: [UtilService, TaskService, IpAddressService],
  props: {
    isShown: Boolean,
    nodes: {
      type: Array,
      required: true,
    },
    defaultNodeId: {
      type: String,
      default: "",
    },
    allRoutes: {
      type: Array,
      required: true,
    },
    route: { type: [Object, null] },
    isEditing: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      instance: "",
      selectedNodeId: "",
      url: "",
      host: "",
      path: "",
      skip_cert_verify: false,
      lets_encrypt: false,
      http2https: true,
      strip_prefix: false,
      slash_redirect: false,
      ip_allowlist: "",
      ip_allowlist_str: "",
      user_created: true,
      isAccordionOpen: false,
      validationErrorDetails: [],
      loading: {
        setRoute: false,
      },
      error: {
        skip_cert_verify: "",
        setRoute: "",
        instance: "",
        node: "",
        url: "",
        host: "",
        path: "",
        ip_allowlist: "",
      },
    };
  },
  watch: {
    defaultNodeId: function () {
      this.updateSelectedNodeId();
    },
    url(newUrl) {
      if (!newUrl.startsWith("https:
        this.skip_cert_verify = false;
      }
    },
    host(newHost) {
      if (!newHost) {
        this.lets_encrypt = false;
      }
    },
    path(newPath) {
      if (!newPath) {
        this.strip_prefix = false;
        this.slash_redirect = false;
      }
    },
    isShown: function () {
      if (this.isShown) {
        this.clearErrors();
        this.validationErrorDetails = [];
        this.isAccordionOpen = false;
        if (this.isEditing) {
          this.instance = this.route.instance;
          this.selectedNodeId = this.route.nodeId;
          this.url = this.route.url;
          this.host = this.route.host;
          this.path = this.route.path;
          this.strip_prefix = this.route.strip_prefix;
          this.slash_redirect = this.route.slash_redirect;
          this.lets_encrypt = this.route.lets_encrypt;
          this.http2https = this.route.http2https;
          this.skip_cert_verify = this.route.skip_cert_verify;
          this.ip_allowlist_str = this.route.ip_allowlist_str;
          this.user_created = this.route.user_created;
          if (this.http2https || this.ip_allowlist_str) {
            this.$nextTick(() => {
              this.isAccordionOpen = true;
            });
          }
        } else {
          this.clearFields();
          this.isAccordionOpen = false;
        }
      }
    },
    "error.setRoute": function () {
      if (this.error.setRoute) {
        this.$nextTick(() => {
          const el = this.$refs.setRouteError;
          this.scrollToElement(el);
        });
      }
    },
    validationErrorDetails: function () {
      if (this.validationErrorDetails.length) {
        this.$nextTick(() => {
          const el = this.$refs.setRouteError;
          this.scrollToElement(el);
        });
      }
    },
  },
  created() {
    this.updateSelectedNodeId();
  },
  methods: {
    toggleAccordionStatus() {
      this.isAccordionOpen = !this.isAccordionOpen;
    },
    updateSelectedNodeId() {
      if (this.defaultNodeId != "all") {
        this.selectedNodeId = this.defaultNodeId;
      } else {
        this.selectedNodeId = "";
      }
    },
    onModalHidden() {
      this.clearErrors();
      this.validationErrorDetails = [];
      this.$emit("hide");
    },
    validateSetRoute(isEditingRoute) {
      this.clearErrors();
      this.validationErrorDetails = [];
      let isValidationOk = true;
      if (!this.instance) {
        this.error.instance = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("instance");
          isValidationOk = false;
        }
      }
      if (!isEditingRoute) {
        const duplicatedRoute = this.allRoutes.find(
          (route) => route.instance === this.instance
        );
        if (duplicatedRoute) {
          this.error.instance = this.$t(
            "settings_http_routes.route_already_exists"
          );
          if (isValidationOk) {
            this.focusElement("instance");
            isValidationOk = false;
          }
        }
      }
      if (!this.selectedNodeId) {
        this.error.node = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("node");
          isValidationOk = false;
        }
      }
      if (!this.url) {
        this.error.url = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("url");
          isValidationOk = false;
        }
      }
      if (!this.host && !this.path) {
        this.error.host = this.$t("settings_http_routes.host_or_path_required");
        this.error.path = this.$t("settings_http_routes.host_or_path_required");
        if (isValidationOk) {
          this.focusElement("host");
          isValidationOk = false;
        }
      } else {
        if (this.path && !this.path.startsWith("/")) {
          this.error.path = this.$t(
            "settings_http_routes.path_must_start_with_slash"
          );
          if (isValidationOk) {
            this.focusElement("path");
            isValidationOk = false;
          }
        }
      }
      if (this.ip_allowlist_str) {
        const ipList = this.ip_allowlist_str.split("\n").map((ip) => ip.trim());
        for (const ip of ipList) {
          if (!this.isIpAddressOrCidr(ip)) {
            this.error.ip_allowlist = this.$t(
              this.looksLikeIpv6(ip)
                ? "settings_http_routes.invalid_ipv6"
                : "settings_http_routes.invalid_ipv4",
              { ip: ip }
            );
            if (isValidationOk) {
              this.focusElement("ip_allowlist");
              isValidationOk = false;
              break;
            }
          }
        }
      }
      return isValidationOk;
    },
    createOrEditRoute() {
      if (!this.isEditing) {
        this.setRoute(false);
      } else {
        this.setRoute(true);
      }
    },
    async setRoute(isEditingRoute) {
      if (!this.validateSetRoute(isEditingRoute)) {
        return;
      }
      this.loading.setRoute = true;
      this.error.setRoute = "";
      const taskAction = "set-route";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.setRouteAborted
      );
      this.$root.$once(
        `${taskAction}-validation-ok-${eventId}`,
        this.setRouteValidationOk
      );
      this.$root.$once(
        `${taskAction}-validation-failed-${eventId}`,
        this.setRouteValidationFailed
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.setRouteCompleted
      );
      const selectedNode = this.nodes.find(
        (node) => node.value === this.selectedNodeId
      );
      const traefikInstance = selectedNode.traefikInstance;
      let setRouteData = {
        instance: this.instance,
        url: this.url,
        lets_encrypt: this.lets_encrypt,
        lets_encrypt_check: true,
        lets_encrypt_cleanup: true,
        http2https: this.http2https,
        user_created: this.user_created,
        skip_cert_verify: this.skip_cert_verify,
        ip_allowlist: this.ip_allowlist_str
          ? this.ip_allowlist_str.split("\n").map((ip) => ip.trim())
          : [],
      };
      if (this.host) {
        setRouteData.host = this.host;
      } else {
        setRouteData.host = null;
      }
      if (this.path) {
        setRouteData.path = this.path;
        setRouteData.strip_prefix = this.strip_prefix;
        setRouteData.slash_redirect = this.slash_redirect;
      } else {
        setRouteData.path = null;
        setRouteData.strip_prefix = false;
        setRouteData.slash_redirect = false;
      }
      const notificationTitle = isEditingRoute
        ? this.$t("settings_http_routes.edit_route_route", {
            route: this.instance,
          })
        : this.$t("settings_http_routes.create_route_route", {
            route: this.instance,
          });
      const res = await to(
        this.createModuleTaskForApp(traefikInstance, {
          action: taskAction,
          data: setRouteData,
          extra: {
            title: notificationTitle,
            description: this.$t("common.processing"),
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.setRoute = this.getErrorMessage(err);
        this.loading.setRoute = false;
        return;
      }
    },
    setRouteAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.loading.setRoute = false;
      this.$emit("hide");
    },
    setRouteValidationOk() {
      this.loading.setRoute = false;
      this.$emit("hide");
    },
    setRouteValidationFailed(validationErrors) {
      this.loading.setRoute = false;
      let focusAlreadySet = false;
      for (const validationError of validationErrors) {
        const param = validationError.parameter;
        if (validationError.details) {
          this.validationErrorDetails = validationError.details
            .split("\n")
            .filter((detail) => detail.trim() !== "");
        } else {
          // set i18n error message
          this.error[param] = this.getI18nStringWithFallback(
            "settings_http_routes." + validationError.error,
            "error." + validationError.error
          );
          if (!focusAlreadySet) {
            this.focusElement(param);
            focusAlreadySet = true;
          }
        }
      }
    },
    setRouteCompleted() {
      this.loading.setRoute = false;
      this.clearFields();
      // reload routes
      this.$emit("reloadRoutes");
    },
    clearFields() {
      this.instance = "";
      this.selectedNodeId = "";
      this.url = "";
      this.host = "";
      this.path = "";
      this.lets_encrypt = false;
      this.http2https = true;
      this.strip_prefix = false;
      this.slash_redirect = false;
      this.skip_cert_verify = false;
      this.ip_allowlist_str = "";
      this.user_created = true;
      if (this.$refs.node) {
        this.$refs.node.clearValue();
      }
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
.maxwidth {
  max-width: 38rem;
}
.toggle-dependent {
  margin-bottom: $spacing-07;
}
</style>
</file>

<file path="core/ui/src/components/settings/DeleteObsoleteCertificatesModal.vue">
<template>
  <NsModal
    kind="danger"
    size="default"
    :visible="isShown"
    :primary-button-disabled="loading.deleteCertificate"
    :isLoading="loading.deleteCertificate"
    @modal-hidden="onModalHidden"
    @primary-click="deleteCertificate"
  >
    <template slot="title">{{
      $t("settings_tls_certificates.delete_obsolete_certificates")
    }}</template>
    <template slot="content">
      <cv-form @submit.prevent="deleteCertificate">
        <p class="mb-2">
          {{ $t("settings_tls_certificates.obsolete_certificates_message_1") }}
        </p>
        <p class="mb-6">
          {{ $t("settings_tls_certificates.obsolete_certificates_message_2") }}
        </p>
        <NsComboBox
          v-model="selectedNodeId"
          :label="$t('common.choose')"
          :title="$t('common.node')"
          :auto-filter="true"
          :auto-highlight="true"
          :options="nodes"
          :disabled="loading.deleteCertificate"
          :invalid-message="error.node"
          light
          ref="node"
        />
        <NsInlineNotification
          kind="warning"
          :title="$t('settings_tls_certificates.traefik_will_be_restarted')"
          :description="
            $t('settings_tls_certificates.delete_obsolete_certificates_message')
          "
          :showCloseButton="false"
        />
        <NsInlineNotification
          v-if="error.deleteCertificate"
          kind="error"
          :title="
            $t('settings_tls_certificates.cannot_delete_obsolete_certificates')
          "
          :description="error.deleteCertificate"
          :showCloseButton="false"
        />
      </cv-form>
    </template>
    <template slot="secondary-button">{{ $t("common.cancel") }}</template>
    <template slot="primary-button">{{
      $t("settings_tls_certificates.delete_obsolete_certificates")
    }}</template>
  </NsModal>
</template>
⋮----
<template slot="title">{{
      $t("settings_tls_certificates.delete_obsolete_certificates")
    }}</template>
<template slot="content">
      <cv-form @submit.prevent="deleteCertificate">
        <p class="mb-2">
          {{ $t("settings_tls_certificates.obsolete_certificates_message_1") }}
        </p>
        <p class="mb-6">
          {{ $t("settings_tls_certificates.obsolete_certificates_message_2") }}
        </p>
        <NsComboBox
          v-model="selectedNodeId"
          :label="$t('common.choose')"
          :title="$t('common.node')"
          :auto-filter="true"
          :auto-highlight="true"
          :options="nodes"
          :disabled="loading.deleteCertificate"
          :invalid-message="error.node"
          light
          ref="node"
        />
        <NsInlineNotification
          kind="warning"
          :title="$t('settings_tls_certificates.traefik_will_be_restarted')"
          :description="
            $t('settings_tls_certificates.delete_obsolete_certificates_message')
          "
          :showCloseButton="false"
        />
        <NsInlineNotification
          v-if="error.deleteCertificate"
          kind="error"
          :title="
            $t('settings_tls_certificates.cannot_delete_obsolete_certificates')
          "
          :description="error.deleteCertificate"
          :showCloseButton="false"
        />
      </cv-form>
    </template>
⋮----
{{ $t("settings_tls_certificates.obsolete_certificates_message_1") }}
⋮----
{{ $t("settings_tls_certificates.obsolete_certificates_message_2") }}
⋮----
<template slot="secondary-button">{{ $t("common.cancel") }}</template>
<template slot="primary-button">{{
      $t("settings_tls_certificates.delete_obsolete_certificates")
    }}</template>
⋮----
<script>
import to from "await-to-js";
import { UtilService, TaskService } from "@nethserver/ns8-ui-lib";
export default {
  name: "DeleteObsoleteCertificatesModal",
  mixins: [UtilService, TaskService],
  props: {
    isShown: Boolean,
    nodes: {
      type: Array,
      required: true,
    },
  },
  data() {
    return {
      names: "",
      selectedNodeId: null,
      loading: {
        deleteCertificate: false,
      },
      error: {
        deleteCertificate: "",
        node: "",
      },
    };
  },
  watch: {
    isShown: function () {
      if (this.isShown) {
        this.clearErrors();
        this.clearFields();
      }
    },
  },
  methods: {
    onModalHidden() {
      this.clearErrors();
      this.$emit("hide");
    },
    validateDeleteCertificate() {
      this.clearErrors();
      let isValidationOk = true;
      if (!this.selectedNodeId) {
        this.error.node = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("node");
          isValidationOk = false;
        }
      }
      return isValidationOk;
    },
    async deleteCertificate() {
      this.error.deleteCertificate = "";
      if (!this.validateDeleteCertificate()) {
        return;
      }
      this.loading.deleteCertificate = true;
      const taskAction = "delete-certificate";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.deleteCertificateAborted
      );
      this.$root.$once(
        `${taskAction}-validation-ok-${eventId}`,
        this.deleteCertificateValidationOk
      );
      this.$root.$once(
        `${taskAction}-validation-failed-${eventId}`,
        this.deleteCertificateValidationFailed
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.deleteCertificateCompleted
      );
      const selectedNode = this.nodes.find(
        (node) => node.value === this.selectedNodeId
      );
      const traefikInstance = selectedNode.traefikInstance;
      const node = selectedNode.label;
      const res = await to(
        this.createModuleTaskForApp(traefikInstance, {
          action: taskAction,
          data: {
            obsolete: true,
            type: "internal",
          },
          extra: {
            title: this.$t(
              "settings_tls_certificates.delete_obsolete_certificates_for_node",
              {
                node,
              }
            ),
            description: this.$t("common.processing"),
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.deleteCertificate = this.getErrorMessage(err);
        this.loading.deleteCertificate = false;
        return;
      }
    },
    deleteCertificateAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.deleteCertificate = this.$t("error.generic_error");
      this.loading.deleteCertificate = false;
      this.$root.$emit("reloadCertificates");
    },
    deleteCertificateValidationOk() {
      this.loading.deleteCertificate = false;
      this.clearFields();
      this.$emit("hide");
    },
    deleteCertificateValidationFailed(validationErrors) {
      this.loading.deleteCertificate = false;
      let focusAlreadySet = false;
      for (const validationError of validationErrors) {
        const param = validationError.parameter;
        this.error[param] = this.getI18nStringWithFallback(
          "settings_tls_certificates." + validationError.error,
          "error." + validationError.error,
          null,
          { value: validationError.value }
        );
        if (!focusAlreadySet) {
          this.focusElement(param);
          focusAlreadySet = true;
        }
      }
    },
    deleteCertificateCompleted() {
      this.loading.deleteCertificate = false;
      this.clearFields();
      this.$root.$emit("reloadCertificates");
    },
    clearFields() {
      this.names = "";
      this.selectedNodeId = "";
      if (this.$refs.node) {
        this.$refs.node.clearValue();
      }
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
</style>
</file>

<file path="core/ui/src/components/settings/EditAcmeServerModal.vue">
<template>
  <NsModal
    size="default"
    :visible="isShown"
    :primary-button-disabled="loading.setAcmeServer"
    :isLoading="loading.setAcmeServer"
    @modal-hidden="onModalHidden"
    @primary-click="setAcmeServer"
  >
    <template slot="title">{{
      $t("settings_acme_servers.edit_acme_settings")
    }}</template>
    <template slot="content">
      <cv-form @submit.prevent="setAcmeServer">
        <div class="mg-bottom-md">
          {{
            $t("settings_acme_servers.acme_settings_for_node", {
              node: server ? server.node : "",
            })
          }}
        </div>
        <NsInlineNotification
          v-if="server"
          kind="warning"
          :title="$t('settings_tls_certificates.traefik_will_be_restarted')"
          :description="
            $t('settings_acme_servers.acme_restart_message', {
              node: server.node,
            })
          "
          :showCloseButton="false"
        />
        <NsTextInput
          v-model.trim="url"
          :label="$t('settings_acme_servers.acme_directory_url')"
          :helper-text="$t('settings_acme_servers.acme_directory_url_helper')"
          :invalid-message="error.url"
          :disabled="loading.setAcmeServer"
          data-modal-primary-focus
          ref="url"
        />
        <div
          v-if="isChallengeSupported"
          class="mg-top-md"
          tabindex="-1"
          ref="challenge"
        >
          <label id="acme-challenge-label" class="bx--label">{{
            $t("settings_acme_servers.challenge")
          }}</label>
          <div role="group" aria-labelledby="acme-challenge-label">
            <cv-radio-group :vertical="true">
              <cv-radio-button
                v-for="challengeType in challengeTypes"
                :key="challengeType.value"
                :label="$t(challengeType.labelKey)"
                :value="challengeType.value"
                name="acme-challenge"
                v-model="challenge"
                :disabled="loading.setAcmeServer"
              />
            </cv-radio-group>
          </div>
          <div
            v-if="error.challenge"
            class="bx--form-requirement challenge-error"
          >
            {{ error.challenge }}
          </div>
        </div>
        <NsInlineNotification
          v-if="error.setAcmeServer"
          kind="error"
          :title="$t('action.set-acme-server')"
          :description="error.setAcmeServer"
          :showCloseButton="false"
        />
      </cv-form>
    </template>
    <template slot="secondary-button">{{ $t("common.cancel") }}</template>
    <template slot="primary-button">{{ $t("common.save") }}</template>
  </NsModal>
</template>
⋮----
<template slot="title">{{
      $t("settings_acme_servers.edit_acme_settings")
    }}</template>
<template slot="content">
      <cv-form @submit.prevent="setAcmeServer">
        <div class="mg-bottom-md">
          {{
            $t("settings_acme_servers.acme_settings_for_node", {
              node: server ? server.node : "",
            })
          }}
        </div>
        <NsInlineNotification
          v-if="server"
          kind="warning"
          :title="$t('settings_tls_certificates.traefik_will_be_restarted')"
          :description="
            $t('settings_acme_servers.acme_restart_message', {
              node: server.node,
            })
          "
          :showCloseButton="false"
        />
        <NsTextInput
          v-model.trim="url"
          :label="$t('settings_acme_servers.acme_directory_url')"
          :helper-text="$t('settings_acme_servers.acme_directory_url_helper')"
          :invalid-message="error.url"
          :disabled="loading.setAcmeServer"
          data-modal-primary-focus
          ref="url"
        />
        <div
          v-if="isChallengeSupported"
          class="mg-top-md"
          tabindex="-1"
          ref="challenge"
        >
          <label id="acme-challenge-label" class="bx--label">{{
            $t("settings_acme_servers.challenge")
          }}</label>
          <div role="group" aria-labelledby="acme-challenge-label">
            <cv-radio-group :vertical="true">
              <cv-radio-button
                v-for="challengeType in challengeTypes"
                :key="challengeType.value"
                :label="$t(challengeType.labelKey)"
                :value="challengeType.value"
                name="acme-challenge"
                v-model="challenge"
                :disabled="loading.setAcmeServer"
              />
            </cv-radio-group>
          </div>
          <div
            v-if="error.challenge"
            class="bx--form-requirement challenge-error"
          >
            {{ error.challenge }}
          </div>
        </div>
        <NsInlineNotification
          v-if="error.setAcmeServer"
          kind="error"
          :title="$t('action.set-acme-server')"
          :description="error.setAcmeServer"
          :showCloseButton="false"
        />
      </cv-form>
    </template>
⋮----
{{
            $t("settings_acme_servers.acme_settings_for_node", {
              node: server ? server.node : "",
            })
          }}
⋮----
<label id="acme-challenge-label" class="bx--label">{{
            $t("settings_acme_servers.challenge")
          }}</label>
⋮----
{{ error.challenge }}
⋮----
<template slot="secondary-button">{{ $t("common.cancel") }}</template>
<template slot="primary-button">{{ $t("common.save") }}</template>
⋮----
<script>
import to from "await-to-js";
import { UtilService, TaskService } from "@nethserver/ns8-ui-lib";
import { mapState } from "vuex";
export const ACME_CHALLENGE_TYPES = [
  {
    value: "HTTP-01",
    labelKey: "settings_acme_servers.challenge_http_01",
    tagKind: "blue",
  },
  {
    value: "TLS-ALPN-01",
    labelKey: "settings_acme_servers.challenge_tls_alpn_01",
    tagKind: "purple",
  },
];
export const DEFAULT_ACME_CHALLENGE_TYPE = "HTTP-01";
export default {
  name: "EditAcmeServerModal",
  mixins: [UtilService, TaskService],
  props: {
    isShown: Boolean,
    server: {
      type: [Object, null],
    },
  },
  data() {
    return {
      url: "",
      challenge: DEFAULT_ACME_CHALLENGE_TYPE,
      loading: {
        setAcmeServer: false,
      },
      error: {
        setAcmeServer: "",
        url: "",
        challenge: "",
      },
      taskListeners: [],
    };
  },
  computed: {
    ...mapState(["isWebsocketConnected"]),
    challengeTypes() {
      return ACME_CHALLENGE_TYPES;
    },
    isChallengeSupported() {
      return !!this.server && this.server.challenge !== undefined;
    },
  },
  watch: {
    isWebsocketConnected: function (isConnected) {
      if (isConnected && this.loading.setAcmeServer) {
        this.clearTaskListeners();
        this.loading.setAcmeServer = false;
        this.error.setAcmeServer = this.$t(
          "settings_acme_servers.save_result_unknown"
        );
        this.$emit("reloadServers");
      }
    },
    isShown: function () {
      if (this.isShown) {
        this.url = this.server.url;
        this.challenge =
          this.server.challenge === undefined
            ? DEFAULT_ACME_CHALLENGE_TYPE
            : this.server.challenge;
      }
    },
  },
  beforeDestroy() {
    this.clearTaskListeners();
  },
  methods: {
    registerTaskListener(eventName, handler) {
      this.$root.$once(eventName, handler);
      this.taskListeners.push([eventName, handler]);
    },
    clearTaskListeners() {
      this.taskListeners.forEach(([eventName, handler]) => {
        this.$root.$off(eventName, handler);
      });
      this.taskListeners = [];
    },
    onModalHidden() {
      this.clearErrors();
      this.$emit("hide");
    },
    validateSetAcmeServer() {
      this.clearErrors();
      let isValidationOk = true;
      if (!this.url) {
        this.error.url = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("url");
          isValidationOk = false;
        }
      }
      if (this.isChallengeSupported && !this.challenge) {
        this.error.challenge = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("challenge");
          isValidationOk = false;
        }
      }
      return isValidationOk;
    },
    async setAcmeServer() {
      if (!this.validateSetAcmeServer()) {
        return;
      }
      this.loading.setAcmeServer = true;
      this.error.setAcmeServer = "";
      const taskAction = "set-acme-server";
      const eventId = this.getUuid();
      this.registerTaskListener(
        `${taskAction}-aborted-${eventId}`,
        this.setAcmeServerAborted
      );
      this.registerTaskListener(
        `${taskAction}-validation-ok-${eventId}`,
        this.setAcmeServerValidationOk
      );
      this.registerTaskListener(
        `${taskAction}-validation-failed-${eventId}`,
        this.setAcmeServerValidationFailed
      );
      this.registerTaskListener(
        `${taskAction}-completed-${eventId}`,
        this.setAcmeServerCompleted
      );
      const data = { url: this.url };
      if (this.isChallengeSupported) {
        data.challenge = this.challenge;
      }
      if (this.server.email) {
        data.email = this.server.email;
      }
      const res = await to(
        this.createModuleTaskForApp(this.server.traefikInstance, {
          action: taskAction,
          data: data,
          extra: {
            title: this.$t("settings_acme_servers.edit_acme_settings"),
            description: this.$t("common.processing"),
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.setAcmeServer = this.getErrorMessage(err);
        this.loading.setAcmeServer = false;
        return;
      }
    },
    setAcmeServerAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.loading.setAcmeServer = false;
      this.$emit("hide");
    },
    setAcmeServerValidationOk() {
      this.loading.setAcmeServer = false;
      this.$emit("hide");
    },
    setAcmeServerValidationFailed(validationErrors) {
      this.loading.setAcmeServer = false;
      let focusAlreadySet = false;
      for (const validationError of validationErrors) {
        const param = validationError.parameter;
        const message = this.getI18nStringWithFallback(
          "settings_acme_servers." + validationError.error,
          "error." + validationError.error
        );
        if (param in this.error && this.$refs[param]) {
          this.error[param] = message;
          if (!focusAlreadySet) {
            this.focusElement(param);
            focusAlreadySet = true;
          }
        } else {
          this.error.setAcmeServer = message;
        }
      }
    },
    setAcmeServerCompleted() {
      this.loading.setAcmeServer = false;
      this.$emit("reloadServers");
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
.bx--inline-notification {
  max-width: 38rem;
}
.challenge-error {
  display: block;
  max-height: none;
  overflow: visible;
  color: #da1e28;
}
</style>
</file>

<file path="core/ui/src/components/settings/EditAdminDisplayNameModal.vue">
<template>
  <NsModal
    size="default"
    :visible="isShown"
    :primary-button-disabled="loading.alterUser"
    @modal-hidden="onModalHidden"
    @primary-click="alterUser"
  >
    <template v-if="admin" slot="title">{{
      $t("settings_cluster_admins.edit_display_name_for_admin", {
        admin: admin.user,
      })
    }}</template>
    <template slot="content">
      <cv-form @submit.prevent="alterUser">
        <NsTextInput
          :label="
            $t('settings_cluster_admins.display_name') +
            ' (' +
            $t('common.optional') +
            ')'
          "
          :placeholder="$t('settings_cluster_admins.no_display_name')"
          v-model.trim="newDisplayName"
          :invalid-message="error.display_name"
          :disabled="loading.alterUser"
          data-modal-primary-focus
          ref="display_name"
        />
        <div v-if="error.alterUser">
          <NsInlineNotification
            kind="error"
            :title="$t('action.alter-user')"
            :description="error.alterUser"
            :showCloseButton="false"
          />
        </div>
      </cv-form>
    </template>
    <template slot="secondary-button">{{ $t("common.cancel") }}</template>
    <template slot="primary-button">{{
      $t("settings_cluster_admins.edit_display_name")
    }}</template>
  </NsModal>
</template>
⋮----
<template v-if="admin" slot="title">{{
      $t("settings_cluster_admins.edit_display_name_for_admin", {
        admin: admin.user,
      })
    }}</template>
<template slot="content">
      <cv-form @submit.prevent="alterUser">
        <NsTextInput
          :label="
            $t('settings_cluster_admins.display_name') +
            ' (' +
            $t('common.optional') +
            ')'
          "
          :placeholder="$t('settings_cluster_admins.no_display_name')"
          v-model.trim="newDisplayName"
          :invalid-message="error.display_name"
          :disabled="loading.alterUser"
          data-modal-primary-focus
          ref="display_name"
        />
        <div v-if="error.alterUser">
          <NsInlineNotification
            kind="error"
            :title="$t('action.alter-user')"
            :description="error.alterUser"
            :showCloseButton="false"
          />
        </div>
      </cv-form>
    </template>
<template slot="secondary-button">{{ $t("common.cancel") }}</template>
<template slot="primary-button">{{
      $t("settings_cluster_admins.edit_display_name")
    }}</template>
⋮----
<script>
import to from "await-to-js";
import { UtilService, TaskService } from "@nethserver/ns8-ui-lib";
export default {
  name: "EditAdminDisplayNameModal",
  mixins: [UtilService, TaskService],
  props: {
    isShown: Boolean,
    admin: {
      type: [Object, null],
    },
  },
  data() {
    return {
      newDisplayName: "",
      loading: {
        alterUser: false,
      },
      error: {
        alterUser: "",
        display_name: "",
      },
    };
  },
  watch: {
    isShown: function () {
      if (this.isShown) {
        this.newDisplayName = this.admin.display_name;
      }
    },
  },
  methods: {
    onModalHidden() {
      this.clearErrors();
      this.$emit("hide");
    },
    async alterUser() {
      this.loading.alterUser = true;
      this.error.alterUser = "";
      const taskAction = "alter-user";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.alterUserAborted
      );
      this.$root.$once(
        `${taskAction}-validation-ok-${eventId}`,
        this.alterUserValidationOk
      );
      this.$root.$once(
        `${taskAction}-validation-failed-${eventId}`,
        this.alterUserValidationFailed
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.alterUserCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {
            user: this.admin.user,
            set: { display_name: this.newDisplayName },
            revoke: [],
            grant: [],
          },
          extra: {
            title: this.$t(
              "settings_cluster_admins.edit_display_name_for_admin",
              {
                admin: this.admin.user,
              }
            ),
            description: this.$t("common.processing"),
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.alterUser = this.getErrorMessage(err);
        this.loading.alterUser = false;
        return;
      }
    },
    alterUserAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.loading.alterUser = false;
      this.$emit("hide");
    },
    alterUserValidationOk() {
      this.loading.alterUser = false;
      this.$emit("hide");
    },
    alterUserValidationFailed(validationErrors) {
      this.loading.alterUser = false;
      let focusAlreadySet = false;
      for (const validationError of validationErrors) {
        const param = validationError.parameter;
        this.error[param] = this.getI18nStringWithFallback(
          "settings_cluster_admins." + validationError.error,
          "error." + validationError.error
        );
        if (!focusAlreadySet) {
          this.focusElement(param);
          focusAlreadySet = true;
        }
      }
    },
    alterUserCompleted() {
      this.loading.alterUser = false;
      this.$emit("displayNameUpdated");
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
</style>
</file>

<file path="core/ui/src/components/settings/Enable2FaModal.vue">
<template>
  <NsWizard
    size="default"
    :visible="isShown"
    :cancelLabel="$t('common.cancel')"
    :previousLabel="$t('common.previous')"
    :nextLabel="
      isLastStep ? $t('settings_account.verify_code') : $t('common.next')
    "
    :isPreviousDisabled="isFirstStep || loading.verify2FaCode"
    :isNextDisabled="isNextButtonDisabled"
    :isNextLoading="loading.verify2FaCode"
    @modal-hidden="$emit('hide')"
    @cancel="$emit('hide')"
    @previousStep="previousStep"
    @nextStep="nextStep"
  >
    <template slot="title">{{ $t("settings_account.enable_2fa") }}</template>
    <template slot="content">
      <cv-form @submit.prevent="nextStep">
        <NsInlineNotification
          v-if="error.get2FaQrCode"
          kind="error"
          :title="$t('settings_account.cannot_retrieve_2fa_qr_code')"
          :description="error.get2FaQrCode"
          :showCloseButton="false"
        />
        <template v-if="step == 'setupKey'">
          <p class="mg-bottom-lg">
            {{ $t("settings_account.store_setup_key_description") }}
          </p>
          <cv-link @click="toggleSetupKey">
            {{
              isShownSetupKey
                ? $t("settings_account.hide_setup_key")
                : $t("settings_account.show_setup_key")
            }}
          </cv-link>
          <NsCodeSnippet
            v-if="isShownSetupKey"
            light
            copyTipPosition="left"
            copyTipAlignment="center"
            :copyTooltip="$t('common.copy_to_clipboard')"
            :copy-feedback="$t('common.copied_to_clipboard')"
            :feedback-aria-label="$t('common.copied_to_clipboard')"
            :wrap-text="true"
            :moreText="$t('common.show_more')"
            :lessText="$t('common.show_less')"
            hideExpandButton
            class="mg-top-sm"
            >{{ setupKey }}</NsCodeSnippet
          >
          <NsCheckbox
            :label="$t('settings_account.i_have_stored_setup_key')"
            v-model="isSetupKeyStored"
            value="checkSetupKeyStored"
            class="mg-top-lg"
          />
        </template>
        <template v-if="step == 'qrCode'">
          <cv-skeleton-text
            v-if="loading.get2FaQrCode"
            heading
            paragraph
            :line-count="6"
          />
          <template v-else>
            <div class="flex-centered">
              <div class="qr-code-container">
                <qrcode-vue :value="qrCodeUrl" :size="qrCodeSize" level="H" />
              </div>
            </div>
            <p class="mg-top-lg">
              <span>{{ $t("settings_account.qr_code_description") }}</span>
              <cv-interactive-tooltip
                alignment="center"
                direction="right"
                class="info"
              >
                <template slot="trigger">
                  <Information16 />
                </template>
                <template slot="content">
                  <div>
                    {{ $t("settings_account.qr_code_description_tooltip") }}
                  </div>
                </template>
              </cv-interactive-tooltip>
            </p>
          </template>
        </template>
        <template v-if="step == 'verify'">
          <NsInlineNotification
            v-if="error.verify2FaCode"
            kind="error"
            :title="$t('settings_account.cannot_verify_code')"
            :description="error.verify2FaCode"
            :showCloseButton="false"
          />
          <div class="mg-bottom-lg">
            {{ $t("login.2fa_description") }}
          </div>
          <NsTextInput
            :label="$t('login.6_digit_code')"
            v-model.trim="twoFaCode"
            :invalid-message="error.twoFaCode"
            :disabled="loading.verify2FaCode"
            maxlength="6"
            ref="twoFaCode"
          />
        </template>
      </cv-form>
    </template>
  </NsWizard>
</template>
⋮----
<template slot="title">{{ $t("settings_account.enable_2fa") }}</template>
<template slot="content">
      <cv-form @submit.prevent="nextStep">
        <NsInlineNotification
          v-if="error.get2FaQrCode"
          kind="error"
          :title="$t('settings_account.cannot_retrieve_2fa_qr_code')"
          :description="error.get2FaQrCode"
          :showCloseButton="false"
        />
        <template v-if="step == 'setupKey'">
          <p class="mg-bottom-lg">
            {{ $t("settings_account.store_setup_key_description") }}
          </p>
          <cv-link @click="toggleSetupKey">
            {{
              isShownSetupKey
                ? $t("settings_account.hide_setup_key")
                : $t("settings_account.show_setup_key")
            }}
          </cv-link>
          <NsCodeSnippet
            v-if="isShownSetupKey"
            light
            copyTipPosition="left"
            copyTipAlignment="center"
            :copyTooltip="$t('common.copy_to_clipboard')"
            :copy-feedback="$t('common.copied_to_clipboard')"
            :feedback-aria-label="$t('common.copied_to_clipboard')"
            :wrap-text="true"
            :moreText="$t('common.show_more')"
            :lessText="$t('common.show_less')"
            hideExpandButton
            class="mg-top-sm"
            >{{ setupKey }}</NsCodeSnippet
          >
          <NsCheckbox
            :label="$t('settings_account.i_have_stored_setup_key')"
            v-model="isSetupKeyStored"
            value="checkSetupKeyStored"
            class="mg-top-lg"
          />
        </template>
        <template v-if="step == 'qrCode'">
          <cv-skeleton-text
            v-if="loading.get2FaQrCode"
            heading
            paragraph
            :line-count="6"
          />
          <template v-else>
            <div class="flex-centered">
              <div class="qr-code-container">
                <qrcode-vue :value="qrCodeUrl" :size="qrCodeSize" level="H" />
              </div>
            </div>
            <p class="mg-top-lg">
              <span>{{ $t("settings_account.qr_code_description") }}</span>
              <cv-interactive-tooltip
                alignment="center"
                direction="right"
                class="info"
              >
                <template slot="trigger">
                  <Information16 />
                </template>
                <template slot="content">
                  <div>
                    {{ $t("settings_account.qr_code_description_tooltip") }}
                  </div>
                </template>
              </cv-interactive-tooltip>
            </p>
          </template>
        </template>
        <template v-if="step == 'verify'">
          <NsInlineNotification
            v-if="error.verify2FaCode"
            kind="error"
            :title="$t('settings_account.cannot_verify_code')"
            :description="error.verify2FaCode"
            :showCloseButton="false"
          />
          <div class="mg-bottom-lg">
            {{ $t("login.2fa_description") }}
          </div>
          <NsTextInput
            :label="$t('login.6_digit_code')"
            v-model.trim="twoFaCode"
            :invalid-message="error.twoFaCode"
            :disabled="loading.verify2FaCode"
            maxlength="6"
            ref="twoFaCode"
          />
        </template>
      </cv-form>
    </template>
⋮----
<template v-if="step == 'setupKey'">
          <p class="mg-bottom-lg">
            {{ $t("settings_account.store_setup_key_description") }}
          </p>
          <cv-link @click="toggleSetupKey">
            {{
              isShownSetupKey
                ? $t("settings_account.hide_setup_key")
                : $t("settings_account.show_setup_key")
            }}
          </cv-link>
          <NsCodeSnippet
            v-if="isShownSetupKey"
            light
            copyTipPosition="left"
            copyTipAlignment="center"
            :copyTooltip="$t('common.copy_to_clipboard')"
            :copy-feedback="$t('common.copied_to_clipboard')"
            :feedback-aria-label="$t('common.copied_to_clipboard')"
            :wrap-text="true"
            :moreText="$t('common.show_more')"
            :lessText="$t('common.show_less')"
            hideExpandButton
            class="mg-top-sm"
            >{{ setupKey }}</NsCodeSnippet
          >
          <NsCheckbox
            :label="$t('settings_account.i_have_stored_setup_key')"
            v-model="isSetupKeyStored"
            value="checkSetupKeyStored"
            class="mg-top-lg"
          />
        </template>
⋮----
{{ $t("settings_account.store_setup_key_description") }}
⋮----
{{
              isShownSetupKey
                ? $t("settings_account.hide_setup_key")
                : $t("settings_account.show_setup_key")
            }}
⋮----
>{{ setupKey }}</NsCodeSnippet
⋮----
<template v-if="step == 'qrCode'">
          <cv-skeleton-text
            v-if="loading.get2FaQrCode"
            heading
            paragraph
            :line-count="6"
          />
          <template v-else>
            <div class="flex-centered">
              <div class="qr-code-container">
                <qrcode-vue :value="qrCodeUrl" :size="qrCodeSize" level="H" />
              </div>
            </div>
            <p class="mg-top-lg">
              <span>{{ $t("settings_account.qr_code_description") }}</span>
              <cv-interactive-tooltip
                alignment="center"
                direction="right"
                class="info"
              >
                <template slot="trigger">
                  <Information16 />
                </template>
                <template slot="content">
                  <div>
                    {{ $t("settings_account.qr_code_description_tooltip") }}
                  </div>
                </template>
              </cv-interactive-tooltip>
            </p>
          </template>
        </template>
⋮----
<template v-else>
            <div class="flex-centered">
              <div class="qr-code-container">
                <qrcode-vue :value="qrCodeUrl" :size="qrCodeSize" level="H" />
              </div>
            </div>
            <p class="mg-top-lg">
              <span>{{ $t("settings_account.qr_code_description") }}</span>
              <cv-interactive-tooltip
                alignment="center"
                direction="right"
                class="info"
              >
                <template slot="trigger">
                  <Information16 />
                </template>
                <template slot="content">
                  <div>
                    {{ $t("settings_account.qr_code_description_tooltip") }}
                  </div>
                </template>
              </cv-interactive-tooltip>
            </p>
          </template>
⋮----
<span>{{ $t("settings_account.qr_code_description") }}</span>
⋮----
<template slot="trigger">
                  <Information16 />
                </template>
<template slot="content">
                  <div>
                    {{ $t("settings_account.qr_code_description_tooltip") }}
                  </div>
                </template>
⋮----
{{ $t("settings_account.qr_code_description_tooltip") }}
⋮----
<template v-if="step == 'verify'">
          <NsInlineNotification
            v-if="error.verify2FaCode"
            kind="error"
            :title="$t('settings_account.cannot_verify_code')"
            :description="error.verify2FaCode"
            :showCloseButton="false"
          />
          <div class="mg-bottom-lg">
            {{ $t("login.2fa_description") }}
          </div>
          <NsTextInput
            :label="$t('login.6_digit_code')"
            v-model.trim="twoFaCode"
            :invalid-message="error.twoFaCode"
            :disabled="loading.verify2FaCode"
            maxlength="6"
            ref="twoFaCode"
          />
        </template>
⋮----
{{ $t("login.2fa_description") }}
⋮----
<script>
import { UtilService, TaskService, IconService } from "@nethserver/ns8-ui-lib";
import to from "await-to-js";
import TwoFaService from "@/mixins/2fa";
import Information16 from "@carbon/icons-vue/es/information/16";
import QrcodeVue from "qrcode.vue";
export default {
  name: "Enable2FaModal",
  components: { Information16, QrcodeVue },
  mixins: [UtilService, TaskService, IconService, TwoFaService],
  props: {
    isShown: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      step: "",
      steps: ["setupKey", "qrCode", "verify"],
      setupKey: "",
      qrCodeUrl: "",
      qrCodeSize: 300,
      twoFaCode: "",
      isShownSetupKey: false,
      isSetupKeyStored: false,
      loading: {
        verify2FaCode: false,
        get2FaQrCode: false,
      },
      error: {
        verify2FaCode: "",
        get2FaQrCode: "",
        twoFaCode: "",
      },
    };
  },
  computed: {
    stepIndex() {
      return this.steps.indexOf(this.step);
    },
    isFirstStep() {
      return this.stepIndex == 0;
    },
    isLastStep() {
      return this.stepIndex == this.steps.length - 1;
    },
    isNextButtonDisabled() {
      return (
        this.loading.get2FaQrCode ||
        this.loading.verify2FaCode ||
        (this.step == "setupKey" && !this.isSetupKeyStored) ||
        (this.step == "verify" && this.twoFaCode.length < 6)
      );
    },
  },
  watch: {
    isShown: function () {
      if (this.isShown) {
        this.step = this.steps[0];
        this.clearErrors();
        this.isShownSetupKey = false;
        this.isSetupKeyStored = false;
        this.setupKey = "";
        this.qrCodeUrl = "";
        this.twoFaCode = "";
        this.retrieve2FaQrCode();
      }
    },
    step: function () {
      if (this.step == "verify") {
        this.focusElement("twoFaCode");
      }
    },
  },
  methods: {
    nextStep() {
      if (this.isNextButtonDisabled) {
        return;
      }
      if (this.isLastStep) {
        this.check2FaCode();
      } else {
        this.step = this.steps[this.stepIndex + 1];
      }
    },
    previousStep() {
      if (!this.isFirstStep) {
        this.step = this.steps[this.stepIndex - 1];
      }
    },
    toggleSetupKey() {
      this.isShownSetupKey = !this.isShownSetupKey;
    },
    async retrieve2FaQrCode() {
      this.loading.get2FaQrCode = true;
      this.error.get2FaQrCode = "";
      const [err2FaQrCode, response2FaQrCode] = await to(this.get2FaQrCode());
      this.loading.get2FaQrCode = false;
      if (err2FaQrCode) {
        console.error("error retrieving 2FA QR code", err2FaQrCode);
        this.error.get2FaQrCode = this.getErrorMessage(err2FaQrCode);
        return;
      }
      this.qrCodeUrl = response2FaQrCode.data.data.url;
      this.setupKey = response2FaQrCode.data.data.key;
    },
    async check2FaCode() {
      this.error.twoFaCode = "";
      this.error.verify2FaCode = "";
      if (!this.twoFaCode.trim()) {
        this.error.twoFaCode = this.$t("login.2fa_code_required");
        this.focusElement("twoFaCode");
        return;
      }
      this.loading.verify2FaCode = true;
      const [verify2FaCodeError] = await to(
        this.verify2FaSecret(this.setupKey, this.twoFaCode)
      );
      this.loading.verify2FaCode = false;
      if (verify2FaCodeError) {
        this.handleVerify2FaError(verify2FaCodeError);
        return;
      }
      this.$emit("twoFaEnabled");
    },
    handleVerify2FaError(error) {
      let errorMessage = this.$t("error.generic_error");
      if (error.response) {
        switch (error.response.data.code) {
          case 400:
            errorMessage = this.$t("login.incorrect_code");
            break;
        }
      } else if (error.message === "Network Error") {
        errorMessage = this.$t("error.network_error");
      }
      this.error.verify2FaCode = errorMessage;
      this.twoFaCode = "";
      this.focusElement("twoFaCode");
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
.flex-centered {
  display: flex;
  justify-content: center;
}
.qr-code-container {
  display: inline-block;
  text-align: center;
  padding: $spacing-08;
  background-color: white;
}
</style>
</file>

<file path="core/ui/src/components/settings/HttpFrontendProxiesPanel.vue">
<template>
  <div>
    <cv-tile light>
      <cv-grid fullWidth class="no-padding">
        <cv-row>
          <cv-column>
            <p class="title-description mg-bottom-md">
              {{ $t("settings_http_routes.frontend_proxies_description") }}
            </p>
          </cv-column>
        </cv-row>
        <cv-row v-if="proxyConfigs.length" class="toolbar">
          <cv-column>
            <NsButton
              v-if="unconfiguredNodes.length || loadingProxies"
              kind="primary"
              :icon="Add20"
              :disabled="loadingProxies"
              @click="showAddProxyModal"
              data-test-id="add-frontend-proxy"
              >{{ $t("settings_http_routes.add_frontend_proxy") }}
            </NsButton>
            <cv-tooltip
              v-else
              alignment="start"
              direction="top"
              :tip="
                $t('settings_http_routes.add_frontend_proxy_disabled_message')
              "
            >
              <NsButton
                kind="primary"
                :icon="Add20"
                disabled
                data-test-id="add-frontend-proxy"
                >{{ $t("settings_http_routes.add_frontend_proxy") }}
              </NsButton>
            </cv-tooltip>
          </cv-column>
        </cv-row>
        <cv-row>
          <cv-column>
            <div class="data-table-filters">
              <cv-search
                :label="$t('common.search')"
                :placeholder="
                  $t('settings_http_routes.filter_frontend_proxies')
                "
                :clear-aria-label="$t('common.clear_search')"
                v-model="filter.text"
                :disabled="loadingProxies"
                size="large"
                ref="tableSearch"
                class="self-end filter-field"
              >
              </cv-search>
              <NsComboBox
                v-model="filter.nodeId"
                :label="$t('common.choose')"
                :title="$t('common.node')"
                :auto-filter="false"
                :auto-highlight="true"
                :options="nodesForFilter"
                :disabled="loadingProxies"
                class="filter-field"
              >
              </NsComboBox>
              <cv-link @click="clearFilters()" class="self-end mb-3 shrink-0"
                >{{ $t("common.clear_filters") }}
              </cv-link>
            </div>
          </cv-column>
        </cv-row>
        <cv-row>
          <cv-column>
            <NsInlineNotification
              v-if="tableError && proxyConfigs.length"
              kind="error"
              :title="tableErrorTitle"
              :description="tableErrorDescription"
              :showCloseButton="false"
            />
            <NsDataTable
              :allRows="filteredProxyConfigs"
              :columns="i18nTableColumns"
              :rawColumns="tableColumns"
              :sortable="true"
              :pageSizes="[10, 25, 50, 100]"
              :overflow-menu="true"
              :isSearchable="false"
              :noSearchResultsLabel="$t('common.no_search_results')"
              :noSearchResultsDescription="
                $t('common.no_search_results_description')
              "
              :isLoading="loadingProxies"
              :skeletonRows="3"
              :isErrorShown="!!tableError && !proxyConfigs.length"
              :errorTitle="tableErrorTitle"
              :errorDescription="tableErrorDescription"
              :itemsPerPageLabel="$t('pagination.items_per_page')"
              :rangeOfTotalItemsLabel="$t('pagination.range_of_total_items')"
              :ofTotalPagesLabel="$t('pagination.of_total_pages')"
              :backwardText="$t('pagination.previous_page')"
              :forwardText="$t('pagination.next_page')"
              :pageNumberLabel="$t('pagination.page_number')"
              @updatePage="tablePage = $event"
            >
              <template slot="empty-state">
                <template v-if="hasActiveFilters && proxyConfigs.length">
                  <NsEmptyState
                    :title="$t('common.no_search_results')"
                    key="no-results-empty-state"
                  >
                    <template #description>
                      <div class="flex flex-col items-center text-center gap-2">
                        <p>
                          {{ $t("common.no_search_results_description") }}
                        </p>
                        <NsButton
                          kind="ghost"
                          size="field"
                          @click="clearFilters()"
                          >{{ $t("common.clear_filters") }}
                        </NsButton>
                      </div>
                    </template>
                  </NsEmptyState>
                </template>
                <template v-else>
                  <NsEmptyState
                    :title="$t('settings_http_routes.no_frontend_proxy')"
                    key="no-frontend-proxy-empty-state"
                  >
                    <template #pictogram>
                      <NetworkPictogram />
                    </template>
                    <template #description>
                      <div class="flex flex-col items-center gap-4">
                        <p>
                          {{
                            $t(
                              "settings_http_routes.no_frontend_proxy_description"
                            )
                          }}
                        </p>
                        <NsButton
                          v-if="unconfiguredNodes.length || loadingProxies"
                          kind="primary"
                          :icon="Add20"
                          :disabled="loadingProxies"
                          @click="showAddProxyModal"
                          data-test-id="add-frontend-proxy-empty-state"
                          >{{ $t("settings_http_routes.add_frontend_proxy") }}
                        </NsButton>
                        <cv-tooltip
                          v-else
                          alignment="start"
                          direction="top"
                          :tip="
                            $t(
                              'settings_http_routes.add_frontend_proxy_no_node_message'
                            )
                          "
                        >
                          <NsButton
                            kind="primary"
                            :icon="Add20"
                            disabled
                            data-test-id="add-frontend-proxy-empty-state"
                            >{{ $t("settings_http_routes.add_frontend_proxy") }}
                          </NsButton>
                        </cv-tooltip>
                      </div>
                    </template>
                  </NsEmptyState>
                </template>
              </template>
              <template slot="data">
                <cv-data-table-row
                  v-for="(row, rowIndex) in tablePage"
                  :key="`${rowIndex}`"
                  :value="`${rowIndex}`"
                >
                  <cv-data-table-cell>
                    <span>{{ row.node }}</span>
                  </cv-data-table-cell>
                  <cv-data-table-cell>
                    <div class="flex flex-col">
                      <span v-for="proxy in row.proxies" :key="proxy">
                        {{ proxy }}
                      </span>
                    </div>
                  </cv-data-table-cell>
                  <cv-data-table-cell>
                    <span>{{ row.depth }}</span>
                  </cv-data-table-cell>
                  <cv-data-table-cell class="table-overflow-menu-cell">
                    <cv-overflow-menu
                      flip-menu
                      class="table-overflow-menu"
                      :data-test-id="row.node + '-menu'"
                    >
                      <cv-overflow-menu-item
                        @click="showEditProxyModal(row)"
                        :data-test-id="row.node + '-edit'"
                      >
                        <NsMenuItem :icon="Edit20" :label="$t('common.edit')" />
                      </cv-overflow-menu-item>
                      <cv-overflow-menu-item
                        danger
                        @click="showDeleteProxyModal(row)"
                        :data-test-id="row.node + '-delete'"
                      >
                        <NsMenuItem
                          :icon="TrashCan20"
                          :label="$t('common.delete')"
                        />
                      </cv-overflow-menu-item>
                    </cv-overflow-menu>
                  </cv-data-table-cell>
                </cv-data-table-row>
              </template>
            </NsDataTable>
          </cv-column>
        </cv-row>
      </cv-grid>
    </cv-tile>
    <ConfigureFrontendProxyModal
      :isShown="isShownConfigureProxyModal"
      :nodes="isEditingProxy ? internalNodes : unconfiguredNodes"
      :proxyConfig="currentProxyConfig"
      :isEditing="isEditingProxy"
      @hide="hideConfigureProxyModal"
      @reloadTrustedProxies="getTrustedProxies"
    />
    <NsDangerDeleteModal
      :isShown="isShownDeleteProxyModal"
      :name="proxyConfigToDelete ? 'node' + proxyConfigToDelete.nodeId : ''"
      :title="
        $t('settings_http_routes.delete_frontend_proxy_node', {
          node: proxyConfigToDelete ? proxyConfigToDelete.node : '',
        })
      "
      :warning="$t('common.please_read_carefully')"
      :description="
        $t('settings_http_routes.delete_frontend_proxy_description', {
          node: proxyConfigToDelete ? proxyConfigToDelete.node : '',
        })
      "
      :typeToConfirm="
        $t('common.type_to_confirm', {
          name: proxyConfigToDelete ? 'node' + proxyConfigToDelete.nodeId : '',
        })
      "
      :loading="loading.deleteTrustedProxies"
      :isErrorShown="!!error.deleteTrustedProxies"
      :errorTitle="$t('action.set-trusted-proxies')"
      :errorDescription="error.deleteTrustedProxies"
      :isWarningShown="false"
      @hide="hideDeleteProxyModal"
      @confirmDelete="deleteTrustedProxies"
      data-test-id="delete-frontend-proxy-modal"
    >
      <template #explanation>
        <div class="mt-4">
          <NsInlineNotification
            kind="warning"
            :title="$t('settings_http_routes.traefik_will_be_restarted')"
            :description="
              $t('settings_http_routes.frontend_proxy_restart_message', {
                node: proxyConfigToDelete ? proxyConfigToDelete.node : '',
              })
            "
            :showCloseButton="false"
          />
        </div>
      </template>
    </NsDangerDeleteModal>
  </div>
</template>
⋮----
{{ $t("settings_http_routes.frontend_proxies_description") }}
⋮----
>{{ $t("settings_http_routes.add_frontend_proxy") }}
⋮----
>{{ $t("settings_http_routes.add_frontend_proxy") }}
⋮----
>{{ $t("common.clear_filters") }}
⋮----
<template slot="empty-state">
                <template v-if="hasActiveFilters && proxyConfigs.length">
                  <NsEmptyState
                    :title="$t('common.no_search_results')"
                    key="no-results-empty-state"
                  >
                    <template #description>
                      <div class="flex flex-col items-center text-center gap-2">
                        <p>
                          {{ $t("common.no_search_results_description") }}
                        </p>
                        <NsButton
                          kind="ghost"
                          size="field"
                          @click="clearFilters()"
                          >{{ $t("common.clear_filters") }}
                        </NsButton>
                      </div>
                    </template>
                  </NsEmptyState>
                </template>
                <template v-else>
                  <NsEmptyState
                    :title="$t('settings_http_routes.no_frontend_proxy')"
                    key="no-frontend-proxy-empty-state"
                  >
                    <template #pictogram>
                      <NetworkPictogram />
                    </template>
                    <template #description>
                      <div class="flex flex-col items-center gap-4">
                        <p>
                          {{
                            $t(
                              "settings_http_routes.no_frontend_proxy_description"
                            )
                          }}
                        </p>
                        <NsButton
                          v-if="unconfiguredNodes.length || loadingProxies"
                          kind="primary"
                          :icon="Add20"
                          :disabled="loadingProxies"
                          @click="showAddProxyModal"
                          data-test-id="add-frontend-proxy-empty-state"
                          >{{ $t("settings_http_routes.add_frontend_proxy") }}
                        </NsButton>
                        <cv-tooltip
                          v-else
                          alignment="start"
                          direction="top"
                          :tip="
                            $t(
                              'settings_http_routes.add_frontend_proxy_no_node_message'
                            )
                          "
                        >
                          <NsButton
                            kind="primary"
                            :icon="Add20"
                            disabled
                            data-test-id="add-frontend-proxy-empty-state"
                            >{{ $t("settings_http_routes.add_frontend_proxy") }}
                          </NsButton>
                        </cv-tooltip>
                      </div>
                    </template>
                  </NsEmptyState>
                </template>
              </template>
⋮----
<template v-if="hasActiveFilters && proxyConfigs.length">
                  <NsEmptyState
                    :title="$t('common.no_search_results')"
                    key="no-results-empty-state"
                  >
                    <template #description>
                      <div class="flex flex-col items-center text-center gap-2">
                        <p>
                          {{ $t("common.no_search_results_description") }}
                        </p>
                        <NsButton
                          kind="ghost"
                          size="field"
                          @click="clearFilters()"
                          >{{ $t("common.clear_filters") }}
                        </NsButton>
                      </div>
                    </template>
                  </NsEmptyState>
                </template>
⋮----
<template #description>
                      <div class="flex flex-col items-center text-center gap-2">
                        <p>
                          {{ $t("common.no_search_results_description") }}
                        </p>
                        <NsButton
                          kind="ghost"
                          size="field"
                          @click="clearFilters()"
                          >{{ $t("common.clear_filters") }}
                        </NsButton>
                      </div>
                    </template>
⋮----
{{ $t("common.no_search_results_description") }}
⋮----
>{{ $t("common.clear_filters") }}
⋮----
<template v-else>
                  <NsEmptyState
                    :title="$t('settings_http_routes.no_frontend_proxy')"
                    key="no-frontend-proxy-empty-state"
                  >
                    <template #pictogram>
                      <NetworkPictogram />
                    </template>
                    <template #description>
                      <div class="flex flex-col items-center gap-4">
                        <p>
                          {{
                            $t(
                              "settings_http_routes.no_frontend_proxy_description"
                            )
                          }}
                        </p>
                        <NsButton
                          v-if="unconfiguredNodes.length || loadingProxies"
                          kind="primary"
                          :icon="Add20"
                          :disabled="loadingProxies"
                          @click="showAddProxyModal"
                          data-test-id="add-frontend-proxy-empty-state"
                          >{{ $t("settings_http_routes.add_frontend_proxy") }}
                        </NsButton>
                        <cv-tooltip
                          v-else
                          alignment="start"
                          direction="top"
                          :tip="
                            $t(
                              'settings_http_routes.add_frontend_proxy_no_node_message'
                            )
                          "
                        >
                          <NsButton
                            kind="primary"
                            :icon="Add20"
                            disabled
                            data-test-id="add-frontend-proxy-empty-state"
                            >{{ $t("settings_http_routes.add_frontend_proxy") }}
                          </NsButton>
                        </cv-tooltip>
                      </div>
                    </template>
                  </NsEmptyState>
                </template>
⋮----
<template #pictogram>
                      <NetworkPictogram />
                    </template>
<template #description>
                      <div class="flex flex-col items-center gap-4">
                        <p>
                          {{
                            $t(
                              "settings_http_routes.no_frontend_proxy_description"
                            )
                          }}
                        </p>
                        <NsButton
                          v-if="unconfiguredNodes.length || loadingProxies"
                          kind="primary"
                          :icon="Add20"
                          :disabled="loadingProxies"
                          @click="showAddProxyModal"
                          data-test-id="add-frontend-proxy-empty-state"
                          >{{ $t("settings_http_routes.add_frontend_proxy") }}
                        </NsButton>
                        <cv-tooltip
                          v-else
                          alignment="start"
                          direction="top"
                          :tip="
                            $t(
                              'settings_http_routes.add_frontend_proxy_no_node_message'
                            )
                          "
                        >
                          <NsButton
                            kind="primary"
                            :icon="Add20"
                            disabled
                            data-test-id="add-frontend-proxy-empty-state"
                            >{{ $t("settings_http_routes.add_frontend_proxy") }}
                          </NsButton>
                        </cv-tooltip>
                      </div>
                    </template>
⋮----
{{
                            $t(
                              "settings_http_routes.no_frontend_proxy_description"
                            )
                          }}
⋮----
>{{ $t("settings_http_routes.add_frontend_proxy") }}
⋮----
>{{ $t("settings_http_routes.add_frontend_proxy") }}
⋮----
<template slot="data">
                <cv-data-table-row
                  v-for="(row, rowIndex) in tablePage"
                  :key="`${rowIndex}`"
                  :value="`${rowIndex}`"
                >
                  <cv-data-table-cell>
                    <span>{{ row.node }}</span>
                  </cv-data-table-cell>
                  <cv-data-table-cell>
                    <div class="flex flex-col">
                      <span v-for="proxy in row.proxies" :key="proxy">
                        {{ proxy }}
                      </span>
                    </div>
                  </cv-data-table-cell>
                  <cv-data-table-cell>
                    <span>{{ row.depth }}</span>
                  </cv-data-table-cell>
                  <cv-data-table-cell class="table-overflow-menu-cell">
                    <cv-overflow-menu
                      flip-menu
                      class="table-overflow-menu"
                      :data-test-id="row.node + '-menu'"
                    >
                      <cv-overflow-menu-item
                        @click="showEditProxyModal(row)"
                        :data-test-id="row.node + '-edit'"
                      >
                        <NsMenuItem :icon="Edit20" :label="$t('common.edit')" />
                      </cv-overflow-menu-item>
                      <cv-overflow-menu-item
                        danger
                        @click="showDeleteProxyModal(row)"
                        :data-test-id="row.node + '-delete'"
                      >
                        <NsMenuItem
                          :icon="TrashCan20"
                          :label="$t('common.delete')"
                        />
                      </cv-overflow-menu-item>
                    </cv-overflow-menu>
                  </cv-data-table-cell>
                </cv-data-table-row>
              </template>
⋮----
<span>{{ row.node }}</span>
⋮----
{{ proxy }}
⋮----
<span>{{ row.depth }}</span>
⋮----
<template #explanation>
        <div class="mt-4">
          <NsInlineNotification
            kind="warning"
            :title="$t('settings_http_routes.traefik_will_be_restarted')"
            :description="
              $t('settings_http_routes.frontend_proxy_restart_message', {
                node: proxyConfigToDelete ? proxyConfigToDelete.node : '',
              })
            "
            :showCloseButton="false"
          />
        </div>
      </template>
⋮----
<script>
import to from "await-to-js";
import { UtilService, TaskService, IconService } from "@nethserver/ns8-ui-lib";
import _cloneDeep from "lodash/cloneDeep";
import { mapState } from "vuex";
import ConfigureFrontendProxyModal from "@/components/settings/ConfigureFrontendProxyModal.vue";
export default {
  name: "HttpFrontendProxiesPanel",
  components: {
    ConfigureFrontendProxyModal,
  },
  mixins: [TaskService, UtilService, IconService],
  props: {
    nodes: {
      type: Array,
      required: true,
    },
    traefikInstances: {
      type: Array,
      required: true,
    },
    isLoadingInstances: {
      type: Boolean,
      default: false,
    },
    instancesError: {
      type: String,
      default: "",
    },
    selectedNodeId: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      tablePage: [],
      // must match row properties: NsDataTable searches and sorts on them
      tableColumns: ["node", "proxies", "depth"],
      proxyConfigs: [],
      filter: {
        text: "",
        // set to the "all" sentinel by repaintNodeFilter(), once the options exist
        nodeId: "",
      },
      currentProxyConfig: null,
      proxyConfigToDelete: null,
      isShownConfigureProxyModal: false,
      isShownDeleteProxyModal: false,
      isEditingProxy: false,
      currentErrorAction: "",
      currentErrorDescription: "",
      // [eventName, handler] pairs registered on $root
      readListeners: [],
      // bumped by every read batch: an older one bails out when it resumes
      readGeneration: 0,
      deleteListeners: [],
      loading: {
        getTrustedProxiesNum: 0,
        deleteTrustedProxies: false,
      },
      error: {
        getTrustedProxies: "",
        deleteTrustedProxies: "",
      },
    };
  },
  computed: {
    ...mapState(["isWebsocketConnected"]),
    i18nTableColumns() {
      return this.tableColumns.map((column) => {
        return this.$t("settings_http_routes." + column);
      });
    },
    loadingProxies() {
      return this.isLoadingInstances || this.loading.getTrustedProxiesNum > 0;
    },
    tableError() {
      return this.instancesError || this.error.getTrustedProxies;
    },
    tableErrorTitle() {
      return this.instancesError
        ? this.$t("action.list-installed-modules")
        : this.currentErrorAction;
    },
    tableErrorDescription() {
      return this.instancesError || this.currentErrorDescription;
    },
    internalNodes() {
      return this.nodes.filter((node) => node.traefikInstance);
    },
    unconfiguredNodes() {
      const configuredNodeIds = this.proxyConfigs.map(
        (proxyConfig) => proxyConfig.nodeId
      );
      return this.internalNodes.filter(
        (node) => !configuredNodeIds.includes(node.value)
      );
    },
    nodesForFilter() {
      if (!this.internalNodes.length) {
        return [];
      }
      const nodes = _cloneDeep(this.internalNodes);
      nodes.unshift({
        name: "all",
        label: this.$t("common.any_node"),
        value: "all",
      });
      return nodes;
    },
    filteredProxyConfigs() {
      let proxyConfigs = this.proxyConfigs;
      if (this.filter.nodeId && this.filter.nodeId !== "all") {
        proxyConfigs = proxyConfigs.filter((proxyConfig) => {
          return proxyConfig.nodeId === this.filter.nodeId;
        });
      }
      if (this.filter.text.trim()) {
        const searchText = this.filter.text.toLowerCase().trim();
        proxyConfigs = proxyConfigs.filter((proxyConfig) => {
          return (
            proxyConfig.node.toLowerCase().includes(searchText) ||
            proxyConfig.proxies.some((proxy) =>
              proxy.toLowerCase().includes(searchText)
            ) ||
            proxyConfig.depth.toString().includes(searchText)
          );
        });
      }
      return proxyConfigs;
    },
    hasActiveFilters() {
      return (
        (this.filter.text && this.filter.text.trim() !== "") ||
        (this.filter.nodeId && this.filter.nodeId !== "all")
      );
    },
  },
  watch: {
    selectedNodeId: function (selectedNodeId) {
      if (selectedNodeId !== this.filter.nodeId) {
        this.filter.nodeId = selectedNodeId;
      }
    },
    "filter.nodeId": function (nodeId) {
      if (nodeId && nodeId !== this.selectedNodeId) {
        this.$emit("update:selectedNodeId", nodeId);
      }
    },
    nodesForFilter: function (nodesForFilter) {
      if (nodesForFilter.length) {
        this.repaintNodeFilter();
      }
    },
    traefikInstances: function () {
      this.getTrustedProxies();
    },
    instancesError: function (instancesError) {
      if (instancesError) {
        this.clearListeners(this.readListeners);
        this.loading.getTrustedProxiesNum = 0;
      }
    },
    isWebsocketConnected: function (isConnected) {
      if (isConnected && this.loading.deleteTrustedProxies) {
        this.loading.deleteTrustedProxies = false;
        this.hideDeleteProxyModal();
      }
    },
  },
  created() {
    this.filter.nodeId = this.selectedNodeId;
    if (this.traefikInstances.length) {
      this.getTrustedProxies();
    }
  },
  beforeDestroy() {
    this.clearListeners(this.readListeners);
    this.clearListeners(this.deleteListeners);
  },
  methods: {
    registerListener(listeners, eventName, handler) {
      this.$root.$once(eventName, handler);
      listeners.push([eventName, handler]);
    },
    clearListeners(listeners) {
      listeners.forEach(([eventName, handler]) => {
        this.$root.$off(eventName, handler);
      });
      listeners.splice(0);
    },
    clearTableError() {
      this.error.getTrustedProxies = "";
      this.currentErrorAction = "";
      this.currentErrorDescription = "";
    },
    clearFilters() {
      this.filter.text = "";
      // "all", not "": NsComboBox only repaints its text on a matching option
      this.filter.nodeId = "all";
    },
    repaintNodeFilter() {
      const nodeId = this.filter.nodeId || "all";
      this.filter.nodeId = "";
      this.$nextTick(() => {
        this.filter.nodeId = nodeId;
      });
    },
    showAddProxyModal() {
      this.isEditingProxy = false;
      this.currentProxyConfig = null;
      this.isShownConfigureProxyModal = true;
    },
    showEditProxyModal(proxyConfig) {
      this.isEditingProxy = true;
      this.currentProxyConfig = proxyConfig;
      this.isShownConfigureProxyModal = true;
    },
    hideConfigureProxyModal() {
      this.isShownConfigureProxyModal = false;
    },
    showDeleteProxyModal(proxyConfig) {
      this.error.deleteTrustedProxies = "";
      this.proxyConfigToDelete = proxyConfig;
      this.isShownDeleteProxyModal = true;
    },
    hideDeleteProxyModal() {
      this.isShownDeleteProxyModal = false;
    },
    async getTrustedProxies() {
      // a handler of a previous round would decrement the counter of this one
      this.clearListeners(this.readListeners);
      const generation = ++this.readGeneration;
      this.proxyConfigs = [];
      // otherwise a transient error sticks after the nodes answer again
      this.clearTableError();
      // count the whole batch upfront: the counter must not reach zero between
      // two iterations
      this.loading.getTrustedProxiesNum = this.traefikInstances.length;
      for (const traefikInstance of this.traefikInstances) {
        const taskAction = "get-trusted-proxies";
        const eventId = this.getUuid();
        this.registerListener(
          this.readListeners,
          `${taskAction}-aborted-${eventId}`,
          this.getTrustedProxiesAborted
        );
        this.registerListener(
          this.readListeners,
          `${taskAction}-completed-${eventId}`,
          this.getTrustedProxiesCompleted
        );
        const res = await to(
          this.createModuleTaskForApp(traefikInstance.id, {
            action: taskAction,
            extra: {
              title: this.$t("action." + taskAction),
              isNotificationHidden: true,
              traefikInstance: traefikInstance,
              eventId,
            },
          })
        );
        if (generation !== this.readGeneration) {
          return;
        }
        const err = res[0];
        if (err) {
          console.error(`error creating task ${taskAction}`, err);
          const errMessage = this.getErrorMessage(err);
          this.error.getTrustedProxies = errMessage;
          this.currentErrorAction = this.$t("action." + taskAction);
          this.currentErrorDescription = errMessage;
          this.loading.getTrustedProxiesNum--;
        }
      }
    },
    getTrustedProxiesAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.getTrustedProxies = this.$t("error.generic_error");
      this.currentErrorAction = this.$t("action." + taskContext.action);
      this.currentErrorDescription = this.$t("error.generic_error");
      this.loading.getTrustedProxiesNum--;
    },
    getTrustedProxiesCompleted(taskContext, taskResult) {
      const traefikId = taskContext.extra.traefikInstance.id;
      const nodeId = taskContext.extra.traefikInstance.node;
      const nodeUiName = taskContext.extra.traefikInstance.node_ui_name;
      const proxies = (taskResult.output.proxies || []).sort();
      this.proxyConfigs = this.proxyConfigs.filter(
        (proxyConfig) => proxyConfig.nodeId !== nodeId
      );
      if (proxies.length) {
        const node = { id: nodeId, ui_name: nodeUiName };
        this.proxyConfigs.push({
          nodeId: nodeId,
          node: this.getShortNodeLabel(node) + ` (${traefikId})`,
          nodeLabel: this.getShortNodeLabel(node),
          traefikInstance: traefikId,
          proxies: proxies,
          proxies_str: proxies.join("\n"),
          depth: taskResult.output.depth || 0,
        });
        this.proxyConfigs.sort(this.sortByProperty("node"));
      }
      this.loading.getTrustedProxiesNum--;
    },
    async deleteTrustedProxies() {
      this.loading.deleteTrustedProxies = true;
      this.error.deleteTrustedProxies = "";
      const taskAction = "set-trusted-proxies";
      const eventId = this.getUuid();
      this.registerListener(
        this.deleteListeners,
        `${taskAction}-aborted-${eventId}`,
        this.deleteTrustedProxiesAborted
      );
      this.registerListener(
        this.deleteListeners,
        `${taskAction}-completed-${eventId}`,
        this.deleteTrustedProxiesCompleted
      );
      const res = await to(
        this.createModuleTaskForApp(this.proxyConfigToDelete.traefikInstance, {
          action: taskAction,
          data: {
            proxies: [],
            depth: 0,
          },
          extra: {
            title: this.$t("settings_http_routes.delete_frontend_proxy_node", {
              node: this.proxyConfigToDelete.node,
            }),
            description: this.$t("common.processing"),
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.deleteTrustedProxies = this.getErrorMessage(err);
        this.loading.deleteTrustedProxies = false;
        return;
      }
    },
    deleteTrustedProxiesAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.deleteTrustedProxies = this.$t("error.generic_error");
      this.loading.deleteTrustedProxies = false;
      this.getTrustedProxies();
    },
    deleteTrustedProxiesCompleted() {
      this.loading.deleteTrustedProxies = false;
      this.hideDeleteProxyModal();
      this.getTrustedProxies();
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
.filter-field {
  max-width: 18rem;
  width: 100%;
}
</style>
</file>

<file path="core/ui/src/components/settings/HttpRouteDetailModal.vue">
<template>
  <NsModal size="default" :visible="isShown" @modal-hidden="$emit('hide')">
    <template slot="title">{{
      $t("settings_http_routes.http_route_details")
    }}</template>
    <template v-if="route" slot="content">
      <div class="key-value-setting">
        <span class="label">{{ $t("settings_http_routes.name") }}</span>
        <span class="value">{{ route.name }}</span>
      </div>
      <div class="key-value-setting">
        <span class="label">{{ $t("settings_http_routes.url") }}</span>
        <span class="value">{{ route.url }}</span>
      </div>
      <div class="key-value-setting">
        <span class="label">{{
          $t("settings_http_routes.skip_cert_verify")
        }}</span>
        <span class="value">
          <cv-tag
            :kind="route.skip_cert_verify ? 'green' : 'high-contrast'"
            size="sm"
            :label="
              route.skip_cert_verify
                ? $t('common.enabled')
                : $t('common.disabled')
            "
            class="no-margin"
          ></cv-tag>
        </span>
      </div>
      <div v-if="route.host" class="key-value-setting">
        <span class="label">{{ $t("settings_http_routes.host") }}</span>
        <span class="value">{{ route.host }}</span>
      </div>
      <div v-if="route.path" class="key-value-setting">
        <span class="label">{{ $t("settings_http_routes.path") }}</span>
        <span class="value">{{ route.path }}</span>
      </div>
      <div v-if="route.path" class="key-value-setting">
        <span class="label">{{ $t("settings_http_routes.strip_prefix") }}</span>
        <span class="value">
          <cv-tag
            :kind="route.strip_prefix ? 'green' : 'high-contrast'"
            size="sm"
            :label="
              route.strip_prefix ? $t('common.enabled') : $t('common.disabled')
            "
            class="no-margin"
          ></cv-tag>
        </span>
      </div>
      <div v-if="route.path" class="key-value-setting">
        <span class="label">{{
          $t("settings_http_routes.slash_redirect")
        }}</span>
        <span class="value">
          <cv-tag
            :kind="route.slash_redirect ? 'green' : 'high-contrast'"
            size="sm"
            :label="
              route.slash_redirect
                ? $t('common.enabled')
                : $t('common.disabled')
            "
            class="no-margin"
          ></cv-tag>
        </span>
      </div>
      <div class="key-value-setting">
        <span class="label">{{
          $t("settings_http_routes.request_lets_encrypt_certificate")
        }}</span>
        <span class="value">
          <cv-tag
            :kind="route.lets_encrypt ? 'green' : 'high-contrast'"
            size="sm"
            :label="
              route.lets_encrypt ? $t('common.enabled') : $t('common.disabled')
            "
            class="no-margin"
          ></cv-tag>
        </span>
      </div>
      <div class="key-value-setting">
        <span class="label">{{ $t("settings_http_routes.http2https") }}</span>
        <span class="value">
          <cv-tag
            :kind="route.http2https ? 'green' : 'high-contrast'"
            size="sm"
            :label="
              route.http2https ? $t('common.enabled') : $t('common.disabled')
            "
            class="no-margin"
          ></cv-tag>
        </span>
      </div>
      <div class="key-value-setting">
        <span class="label">{{ $t("settings_http_routes.ip_allowlist") }}</span>
        <span class="value">{{
          route.ip_allowlist && route.ip_allowlist.length
            ? route.ip_allowlist.join(", ")
            : "-"
        }}</span>
      </div>
      <div class="key-value-setting">
        <span class="label">{{ $t("settings_http_routes.node") }}</span>
        <span class="value">{{ route.longNodeLabel }}</span>
      </div>
      <div class="key-value-setting">
        <span class="label">{{
          $t("settings_http_routes.traefik_instance")
        }}</span>
        <span class="value">{{ route.traefikInstance }}</span>
      </div>
    </template>
    <template slot="primary-button">{{ $t("common.close") }}</template>
  </NsModal>
</template>
⋮----
<template slot="title">{{
      $t("settings_http_routes.http_route_details")
    }}</template>
<template v-if="route" slot="content">
      <div class="key-value-setting">
        <span class="label">{{ $t("settings_http_routes.name") }}</span>
        <span class="value">{{ route.name }}</span>
      </div>
      <div class="key-value-setting">
        <span class="label">{{ $t("settings_http_routes.url") }}</span>
        <span class="value">{{ route.url }}</span>
      </div>
      <div class="key-value-setting">
        <span class="label">{{
          $t("settings_http_routes.skip_cert_verify")
        }}</span>
        <span class="value">
          <cv-tag
            :kind="route.skip_cert_verify ? 'green' : 'high-contrast'"
            size="sm"
            :label="
              route.skip_cert_verify
                ? $t('common.enabled')
                : $t('common.disabled')
            "
            class="no-margin"
          ></cv-tag>
        </span>
      </div>
      <div v-if="route.host" class="key-value-setting">
        <span class="label">{{ $t("settings_http_routes.host") }}</span>
        <span class="value">{{ route.host }}</span>
      </div>
      <div v-if="route.path" class="key-value-setting">
        <span class="label">{{ $t("settings_http_routes.path") }}</span>
        <span class="value">{{ route.path }}</span>
      </div>
      <div v-if="route.path" class="key-value-setting">
        <span class="label">{{ $t("settings_http_routes.strip_prefix") }}</span>
        <span class="value">
          <cv-tag
            :kind="route.strip_prefix ? 'green' : 'high-contrast'"
            size="sm"
            :label="
              route.strip_prefix ? $t('common.enabled') : $t('common.disabled')
            "
            class="no-margin"
          ></cv-tag>
        </span>
      </div>
      <div v-if="route.path" class="key-value-setting">
        <span class="label">{{
          $t("settings_http_routes.slash_redirect")
        }}</span>
        <span class="value">
          <cv-tag
            :kind="route.slash_redirect ? 'green' : 'high-contrast'"
            size="sm"
            :label="
              route.slash_redirect
                ? $t('common.enabled')
                : $t('common.disabled')
            "
            class="no-margin"
          ></cv-tag>
        </span>
      </div>
      <div class="key-value-setting">
        <span class="label">{{
          $t("settings_http_routes.request_lets_encrypt_certificate")
        }}</span>
        <span class="value">
          <cv-tag
            :kind="route.lets_encrypt ? 'green' : 'high-contrast'"
            size="sm"
            :label="
              route.lets_encrypt ? $t('common.enabled') : $t('common.disabled')
            "
            class="no-margin"
          ></cv-tag>
        </span>
      </div>
      <div class="key-value-setting">
        <span class="label">{{ $t("settings_http_routes.http2https") }}</span>
        <span class="value">
          <cv-tag
            :kind="route.http2https ? 'green' : 'high-contrast'"
            size="sm"
            :label="
              route.http2https ? $t('common.enabled') : $t('common.disabled')
            "
            class="no-margin"
          ></cv-tag>
        </span>
      </div>
      <div class="key-value-setting">
        <span class="label">{{ $t("settings_http_routes.ip_allowlist") }}</span>
        <span class="value">{{
          route.ip_allowlist && route.ip_allowlist.length
            ? route.ip_allowlist.join(", ")
            : "-"
        }}</span>
      </div>
      <div class="key-value-setting">
        <span class="label">{{ $t("settings_http_routes.node") }}</span>
        <span class="value">{{ route.longNodeLabel }}</span>
      </div>
      <div class="key-value-setting">
        <span class="label">{{
          $t("settings_http_routes.traefik_instance")
        }}</span>
        <span class="value">{{ route.traefikInstance }}</span>
      </div>
    </template>
⋮----
<span class="label">{{ $t("settings_http_routes.name") }}</span>
<span class="value">{{ route.name }}</span>
⋮----
<span class="label">{{ $t("settings_http_routes.url") }}</span>
<span class="value">{{ route.url }}</span>
⋮----
<span class="label">{{
          $t("settings_http_routes.skip_cert_verify")
        }}</span>
⋮----
<span class="label">{{ $t("settings_http_routes.host") }}</span>
<span class="value">{{ route.host }}</span>
⋮----
<span class="label">{{ $t("settings_http_routes.path") }}</span>
<span class="value">{{ route.path }}</span>
⋮----
<span class="label">{{ $t("settings_http_routes.strip_prefix") }}</span>
⋮----
<span class="label">{{
          $t("settings_http_routes.slash_redirect")
        }}</span>
⋮----
<span class="label">{{
          $t("settings_http_routes.request_lets_encrypt_certificate")
        }}</span>
⋮----
<span class="label">{{ $t("settings_http_routes.http2https") }}</span>
⋮----
<span class="label">{{ $t("settings_http_routes.ip_allowlist") }}</span>
<span class="value">{{
          route.ip_allowlist && route.ip_allowlist.length
            ? route.ip_allowlist.join(", ")
            : "-"
        }}</span>
⋮----
<span class="label">{{ $t("settings_http_routes.node") }}</span>
<span class="value">{{ route.longNodeLabel }}</span>
⋮----
<span class="label">{{
          $t("settings_http_routes.traefik_instance")
        }}</span>
<span class="value">{{ route.traefikInstance }}</span>
⋮----
<template slot="primary-button">{{ $t("common.close") }}</template>
⋮----
<script>
import { UtilService } from "@nethserver/ns8-ui-lib";
export default {
  name: "HttpRouteDetailModal",
  mixins: [UtilService],
  props: {
    isShown: Boolean,
    route: Object,
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
</style>
</file>

<file path="core/ui/src/components/settings/HttpRoutesPanel.vue">
<template>
  <div>
    <cv-tile light>
      <cv-grid fullWidth class="no-padding">
        <cv-row class="toolbar">
          <cv-column>
            <NsButton
              kind="primary"
              :icon="Add20"
              @click="showCreateRouteModal"
              data-test-id="create-route"
              >{{ $t("settings_http_routes.create_route") }}
            </NsButton>
          </cv-column>
        </cv-row>
        <cv-row>
          <cv-column>
            <div class="data-table-filters">
              <cv-search
                :label="$t('common.search')"
                :placeholder="$t('settings_http_routes.search_route')"
                :clear-aria-label="$t('common.clear_search')"
                v-model="filter.text"
                :disabled="loadingRoutes"
                size="large"
                ref="tableSearch"
                class="self-end filter-field"
              >
              </cv-search>
              <NsComboBox
                v-model="internalSelectedNodeId"
                :label="$t('common.choose')"
                :title="$t('common.node')"
                :auto-filter="false"
                :auto-highlight="true"
                :options="nodesForFilter"
                :disabled="isLoadingInstances"
                class="filter-field"
              >
              </NsComboBox>
              <cv-link @click="clearFilters()" class="self-end mb-3 shrink-0"
                >{{ $t("common.clear_filters") }}
              </cv-link>
            </div>
          </cv-column>
        </cv-row>
        <cv-row>
          <cv-column>
            <NsInlineNotification
              v-if="tableError && routes.length"
              kind="error"
              :title="tableErrorTitle"
              :description="tableErrorDescription"
              :showCloseButton="false"
            />
            <NsDataTable
              :allRows="filteredRoutes"
              :columns="i18nTableColumns"
              :rawColumns="tableColumns"
              :sortable="true"
              :pageSizes="[10, 25, 50, 100]"
              :overflow-menu="true"
              :isSearchable="false"
              :noSearchResultsLabel="$t('common.no_search_results')"
              :noSearchResultsDescription="
                $t('common.no_search_results_description')
              "
              :isLoading="loadingRoutes"
              :skeletonRows="5"
              :isErrorShown="!!tableError && !routes.length"
              :errorTitle="tableErrorTitle"
              :errorDescription="tableErrorDescription"
              :itemsPerPageLabel="$t('pagination.items_per_page')"
              :rangeOfTotalItemsLabel="$t('pagination.range_of_total_items')"
              :ofTotalPagesLabel="$t('pagination.of_total_pages')"
              :backwardText="$t('pagination.previous_page')"
              :forwardText="$t('pagination.next_page')"
              :pageNumberLabel="$t('pagination.page_number')"
              :customSortTable="sortHttpRoutes"
              @updatePage="tablePage = $event"
            >
              <template slot="empty-state">
                <template v-if="hasActiveFilters && routes.length">
                  <NsEmptyState
                    :title="$t('common.no_search_results')"
                    key="no-results-empty-state"
                  >
                    <template #description>
                      <div class="flex flex-col items-center text-center gap-2">
                        <p>
                          {{ $t("common.no_search_results_description") }}
                        </p>
                        <NsButton
                          kind="ghost"
                          size="field"
                          @click="clearFilters()"
                          >{{ $t("common.clear_filters") }}
                        </NsButton>
                      </div>
                    </template>
                  </NsEmptyState>
                </template>
                <template v-else>
                  <NsEmptyState
                    :title="$t('settings_http_routes.no_http_route')"
                    key="no-http-route-empty-state"
                  >
                    <template #pictogram>
                      <NetworkPictogram />
                    </template>
                    <template #description>
                      <div>
                        {{
                          $t("settings_http_routes.no_http_route_description")
                        }}
                      </div>
                    </template>
                  </NsEmptyState>
                </template>
              </template>
              <template slot="data">
                <cv-data-table-row
                  v-for="(row, rowIndex) in tablePage"
                  :key="`${rowIndex}`"
                  :value="`${rowIndex}`"
                >
                  <cv-data-table-cell>
                    <div class="flex items-center gap-2">
                      <span v-if="row.host && row.path">
                        {{ row.host }}{{ row.path }}
                      </span>
                      <span v-else>
                        {{ row.host || row.path }}
                      </span>
                      <cv-interactive-tooltip
                        v-if="row.lets_encrypt_status === 'pending'"
                        alignment="center"
                        direction="top"
                        class="shrink-0"
                      >
                        <template #trigger>
                          <WarningAltFilled16 class="ns-warning" />
                        </template>
                        <template #content>
                          {{
                            $t(
                              "settings_http_routes.cannot_obtain_tls_certificate"
                            )
                          }}
                          <cv-link @click="goToPendingCertificateLogs(row)">
                            {{ $t("settings_http_routes.show_logs") }}
                          </cv-link>
                        </template>
                      </cv-interactive-tooltip>
                    </div>
                  </cv-data-table-cell>
                  <cv-data-table-cell>
                    <cv-link @click="showRouteDetailModal(row)">
                      {{ row.name }}
                    </cv-link>
                  </cv-data-table-cell>
                  <cv-data-table-cell>
                    <span>
                      {{ $t(`settings_http_routes.${row.type}`) }}
                    </span>
                  </cv-data-table-cell>
                  <cv-data-table-cell>
                    <span>{{ row.node }}</span>
                  </cv-data-table-cell>
                  <cv-data-table-cell>
                    <NsTag
                      v-if="!row.user_created"
                      kind="gray"
                      size="sm"
                      :label="$t('settings_http_routes.automatic')"
                    />
                    <NsTag
                      v-if="
                        row.ip_allowlist !== undefined &&
                        row.ip_allowlist.length > 0
                      "
                      kind="high-contrast"
                      size="sm"
                      :label="$t('settings_http_routes.restricted')"
                      class="no-margin"
                    />
                  </cv-data-table-cell>
                  <cv-data-table-cell class="table-overflow-menu-cell">
                    <cv-overflow-menu
                      flip-menu
                      class="table-overflow-menu"
                      :data-test-id="row.name + '-menu'"
                    >
                      <cv-overflow-menu-item
                        @click="showRouteDetailModal(row)"
                        :data-test-id="row.name + '-details'"
                      >
                        <NsMenuItem
                          :icon="ArrowRight20"
                          :label="$t('common.see_details')"
                        />
                      </cv-overflow-menu-item>
                      <cv-overflow-menu-item
                        @click="showEditRouteModal(row)"
                        :data-test-id="row.name + '-edit'"
                      >
                        <NsMenuItem :icon="Edit20" :label="$t('common.edit')" />
                      </cv-overflow-menu-item>
                      <cv-overflow-menu-item
                        danger
                        @click="showDeleteRouteModal(row)"
                        :disabled="!row.user_created"
                        :data-test-id="row.name + '-delete'"
                      >
                        <NsMenuItem
                          :icon="TrashCan20"
                          :label="$t('common.delete')"
                        />
                      </cv-overflow-menu-item>
                    </cv-overflow-menu>
                  </cv-data-table-cell>
                </cv-data-table-row>
              </template>
            </NsDataTable>
          </cv-column>
        </cv-row>
      </cv-grid>
    </cv-tile>
    <HttpRouteDetailModal
      :isShown="isShownRouteDetailModal"
      :route="currentRoute"
      @hide="hideRouteDetailModal"
    />
    <CreateOrEditHttpRouteModal
      :isShown="isShownCreateOrEditRouteModal"
      :nodes="nodes"
      :defaultNodeId="internalSelectedNodeId"
      :allRoutes="routes"
      :route="currentRoute"
      :isEditing="isEditingRoute"
      @hide="hideCreateRouteModal"
      @reloadRoutes="onReloadRoutes"
    />
    <NsDangerDeleteModal
      :isShown="isShownDeleteRouteModal"
      :name="routeToDelete ? routeToDelete.name : ''"
      :title="
        $t('settings_http_routes.delete_route_route', {
          route: routeToDelete ? routeToDelete.name : '',
        })
      "
      :warning="$t('common.please_read_carefully')"
      :description="
        $t('settings_http_routes.delete_route_description', {
          name: routeToDelete ? routeToDelete.name : '',
        })
      "
      :typeToConfirm="
        $t('common.type_to_confirm', {
          name: routeToDelete ? routeToDelete.name : '',
        })
      "
      :isErrorShown="!!error.deleteRoute"
      :errorTitle="$t('action.delete-route')"
      :errorDescription="error.deleteRoute"
      :isWarningShown="false"
      @hide="hideDeleteRouteModal"
      @confirmDelete="deleteRoute"
      data-test-id="delete-route-modal"
    >
      <template v-if="routeToDelete && routeToDelete.lets_encrypt" #explanation>
        <div class="mt-4">
          <NsInlineNotification
            kind="warning"
            :title="$t('settings_http_routes.traefik_will_be_restarted')"
            :description="
              $t('settings_http_routes.delete_route_with_certificate_message', {
                node: routeToDelete.node,
              })
            "
            :showCloseButton="false"
          />
        </div>
      </template>
    </NsDangerDeleteModal>
  </div>
</template>
⋮----
>{{ $t("settings_http_routes.create_route") }}
⋮----
>{{ $t("common.clear_filters") }}
⋮----
<template slot="empty-state">
                <template v-if="hasActiveFilters && routes.length">
                  <NsEmptyState
                    :title="$t('common.no_search_results')"
                    key="no-results-empty-state"
                  >
                    <template #description>
                      <div class="flex flex-col items-center text-center gap-2">
                        <p>
                          {{ $t("common.no_search_results_description") }}
                        </p>
                        <NsButton
                          kind="ghost"
                          size="field"
                          @click="clearFilters()"
                          >{{ $t("common.clear_filters") }}
                        </NsButton>
                      </div>
                    </template>
                  </NsEmptyState>
                </template>
                <template v-else>
                  <NsEmptyState
                    :title="$t('settings_http_routes.no_http_route')"
                    key="no-http-route-empty-state"
                  >
                    <template #pictogram>
                      <NetworkPictogram />
                    </template>
                    <template #description>
                      <div>
                        {{
                          $t("settings_http_routes.no_http_route_description")
                        }}
                      </div>
                    </template>
                  </NsEmptyState>
                </template>
              </template>
⋮----
<template v-if="hasActiveFilters && routes.length">
                  <NsEmptyState
                    :title="$t('common.no_search_results')"
                    key="no-results-empty-state"
                  >
                    <template #description>
                      <div class="flex flex-col items-center text-center gap-2">
                        <p>
                          {{ $t("common.no_search_results_description") }}
                        </p>
                        <NsButton
                          kind="ghost"
                          size="field"
                          @click="clearFilters()"
                          >{{ $t("common.clear_filters") }}
                        </NsButton>
                      </div>
                    </template>
                  </NsEmptyState>
                </template>
⋮----
<template #description>
                      <div class="flex flex-col items-center text-center gap-2">
                        <p>
                          {{ $t("common.no_search_results_description") }}
                        </p>
                        <NsButton
                          kind="ghost"
                          size="field"
                          @click="clearFilters()"
                          >{{ $t("common.clear_filters") }}
                        </NsButton>
                      </div>
                    </template>
⋮----
{{ $t("common.no_search_results_description") }}
⋮----
>{{ $t("common.clear_filters") }}
⋮----
<template v-else>
                  <NsEmptyState
                    :title="$t('settings_http_routes.no_http_route')"
                    key="no-http-route-empty-state"
                  >
                    <template #pictogram>
                      <NetworkPictogram />
                    </template>
                    <template #description>
                      <div>
                        {{
                          $t("settings_http_routes.no_http_route_description")
                        }}
                      </div>
                    </template>
                  </NsEmptyState>
                </template>
⋮----
<template #pictogram>
                      <NetworkPictogram />
                    </template>
<template #description>
                      <div>
                        {{
                          $t("settings_http_routes.no_http_route_description")
                        }}
                      </div>
                    </template>
⋮----
{{
                          $t("settings_http_routes.no_http_route_description")
                        }}
⋮----
<template slot="data">
                <cv-data-table-row
                  v-for="(row, rowIndex) in tablePage"
                  :key="`${rowIndex}`"
                  :value="`${rowIndex}`"
                >
                  <cv-data-table-cell>
                    <div class="flex items-center gap-2">
                      <span v-if="row.host && row.path">
                        {{ row.host }}{{ row.path }}
                      </span>
                      <span v-else>
                        {{ row.host || row.path }}
                      </span>
                      <cv-interactive-tooltip
                        v-if="row.lets_encrypt_status === 'pending'"
                        alignment="center"
                        direction="top"
                        class="shrink-0"
                      >
                        <template #trigger>
                          <WarningAltFilled16 class="ns-warning" />
                        </template>
                        <template #content>
                          {{
                            $t(
                              "settings_http_routes.cannot_obtain_tls_certificate"
                            )
                          }}
                          <cv-link @click="goToPendingCertificateLogs(row)">
                            {{ $t("settings_http_routes.show_logs") }}
                          </cv-link>
                        </template>
                      </cv-interactive-tooltip>
                    </div>
                  </cv-data-table-cell>
                  <cv-data-table-cell>
                    <cv-link @click="showRouteDetailModal(row)">
                      {{ row.name }}
                    </cv-link>
                  </cv-data-table-cell>
                  <cv-data-table-cell>
                    <span>
                      {{ $t(`settings_http_routes.${row.type}`) }}
                    </span>
                  </cv-data-table-cell>
                  <cv-data-table-cell>
                    <span>{{ row.node }}</span>
                  </cv-data-table-cell>
                  <cv-data-table-cell>
                    <NsTag
                      v-if="!row.user_created"
                      kind="gray"
                      size="sm"
                      :label="$t('settings_http_routes.automatic')"
                    />
                    <NsTag
                      v-if="
                        row.ip_allowlist !== undefined &&
                        row.ip_allowlist.length > 0
                      "
                      kind="high-contrast"
                      size="sm"
                      :label="$t('settings_http_routes.restricted')"
                      class="no-margin"
                    />
                  </cv-data-table-cell>
                  <cv-data-table-cell class="table-overflow-menu-cell">
                    <cv-overflow-menu
                      flip-menu
                      class="table-overflow-menu"
                      :data-test-id="row.name + '-menu'"
                    >
                      <cv-overflow-menu-item
                        @click="showRouteDetailModal(row)"
                        :data-test-id="row.name + '-details'"
                      >
                        <NsMenuItem
                          :icon="ArrowRight20"
                          :label="$t('common.see_details')"
                        />
                      </cv-overflow-menu-item>
                      <cv-overflow-menu-item
                        @click="showEditRouteModal(row)"
                        :data-test-id="row.name + '-edit'"
                      >
                        <NsMenuItem :icon="Edit20" :label="$t('common.edit')" />
                      </cv-overflow-menu-item>
                      <cv-overflow-menu-item
                        danger
                        @click="showDeleteRouteModal(row)"
                        :disabled="!row.user_created"
                        :data-test-id="row.name + '-delete'"
                      >
                        <NsMenuItem
                          :icon="TrashCan20"
                          :label="$t('common.delete')"
                        />
                      </cv-overflow-menu-item>
                    </cv-overflow-menu>
                  </cv-data-table-cell>
                </cv-data-table-row>
              </template>
⋮----
{{ row.host }}{{ row.path }}
⋮----
{{ row.host || row.path }}
⋮----
<template #trigger>
                          <WarningAltFilled16 class="ns-warning" />
                        </template>
<template #content>
                          {{
                            $t(
                              "settings_http_routes.cannot_obtain_tls_certificate"
                            )
                          }}
                          <cv-link @click="goToPendingCertificateLogs(row)">
                            {{ $t("settings_http_routes.show_logs") }}
                          </cv-link>
                        </template>
⋮----
{{
                            $t(
                              "settings_http_routes.cannot_obtain_tls_certificate"
                            )
                          }}
⋮----
{{ $t("settings_http_routes.show_logs") }}
⋮----
{{ row.name }}
⋮----
{{ $t(`settings_http_routes.${row.type}`) }}
⋮----
<span>{{ row.node }}</span>
⋮----
<template v-if="routeToDelete && routeToDelete.lets_encrypt" #explanation>
        <div class="mt-4">
          <NsInlineNotification
            kind="warning"
            :title="$t('settings_http_routes.traefik_will_be_restarted')"
            :description="
              $t('settings_http_routes.delete_route_with_certificate_message', {
                node: routeToDelete.node,
              })
            "
            :showCloseButton="false"
          />
        </div>
      </template>
⋮----
<script>
import to from "await-to-js";
import {
  UtilService,
  TaskService,
  IconService,
  DateTimeService,
} from "@nethserver/ns8-ui-lib";
import _cloneDeep from "lodash/cloneDeep";
import HttpRouteDetailModal from "@/components/settings/HttpRouteDetailModal.vue";
import CreateOrEditHttpRouteModal from "@/components/settings/CreateOrEditHttpRouteModal.vue";
import WarningAltFilled16 from "@carbon/icons-vue/es/warning--alt--filled/16";
export default {
  name: "HttpRoutesPanel",
  components: {
    HttpRouteDetailModal,
    CreateOrEditHttpRouteModal,
    WarningAltFilled16,
  },
  mixins: [TaskService, UtilService, IconService, DateTimeService],
  props: {
    nodes: {
      type: Array,
      required: true,
    },
    traefikInstances: {
      type: Array,
      required: true,
    },
    isLoadingInstances: {
      type: Boolean,
      default: false,
    },
    instancesError: {
      type: String,
      default: "",
    },
    // the node filter is a query param: the view owns it, this panel mirrors it
    selectedNodeId: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      // repainting the combo box needs a synchronous write, which a round trip
      // through the query param cannot guarantee
      internalSelectedNodeId: "",
      filter: {
        text: "",
      },
      tablePage: [],
      tableColumns: ["route", "name", "type", "node", "attributes"],
      routes: [],
      isShownCreateOrEditRouteModal: false,
      isShownRouteDetailModal: false,
      isShownDeleteRouteModal: false,
      currentErrorAction: "",
      currentErrorDescription: "",
      currentRoute: null,
      routeToDelete: null,
      isEditingRoute: false,
      // [eventName, handler] pairs registered on $root, cleared on destroy
      readListeners: [],
      // bumped by every read batch: an older one bails out when it resumes
      readGeneration: 0,
      deleteListeners: [],
      pendingCertificatesLogsPath: {},
      loading: {
        listRoutesNum: 0,
        deleteRoute: false,
      },
      error: {
        listRoutes: "",
        deleteRoute: "",
      },
    };
  },
  computed: {
    i18nTableColumns() {
      return this.tableColumns.map((column) => {
        return this.$t("settings_http_routes." + column);
      });
    },
    loadingRoutes() {
      return this.isLoadingInstances || this.loading.listRoutesNum > 0;
    },
    tableError() {
      return this.instancesError || this.error.listRoutes;
    },
    tableErrorTitle() {
      return this.instancesError
        ? this.$t("action.list-installed-modules")
        : this.currentErrorAction;
    },
    tableErrorDescription() {
      return this.instancesError || this.currentErrorDescription;
    },
    filteredRoutes() {
      let routes = this.routes;
      if (
        this.internalSelectedNodeId &&
        this.internalSelectedNodeId !== "all"
      ) {
        routes = routes.filter((route) => {
          return route.nodeId === this.internalSelectedNodeId;
        });
      }
      if (this.filter.text.trim()) {
        const cleanRegex = /[^a-zA-Z0-9]/g;
        const queryText = this.filter.text.replace(cleanRegex, "");
        const searchFields = ["host", "path", "name", "type", "node"];
        routes = routes.filter((route) => {
          if (route.host && route.path) {
            const hostAndPath = `${route.host}${route.path}`;
            if (
              new RegExp(queryText, "i").test(
                hostAndPath.replace(cleanRegex, "")
              )
            ) {
              return true;
            }
          }
          return searchFields.some((searchField) => {
            const searchValue = route[searchField];
            return searchValue
              ? new RegExp(queryText, "i").test(
                  searchValue.replace(cleanRegex, "")
                )
              : false;
          });
        });
      }
      return routes;
    },
    hasActiveFilters() {
      return (
        (this.filter.text && this.filter.text.trim() !== "") ||
        (this.internalSelectedNodeId && this.internalSelectedNodeId !== "all")
      );
    },
    nodesForFilter() {
      if (!this.nodes.length) {
        return [];
      }
      const nodes = _cloneDeep(this.nodes);
      nodes.unshift({
        name: "all",
        label: this.$t("common.any_node"),
        value: "all",
      });
      return nodes;
    },
  },
  watch: {
    selectedNodeId: function (selectedNodeId) {
      if (selectedNodeId !== this.internalSelectedNodeId) {
        this.internalSelectedNodeId = selectedNodeId;
      }
    },
    internalSelectedNodeId: function (internalSelectedNodeId) {
      if (
        internalSelectedNodeId &&
        internalSelectedNodeId !== this.selectedNodeId
      ) {
        this.$emit("update:selectedNodeId", internalSelectedNodeId);
      }
    },
    nodesForFilter: function (nodesForFilter) {
      if (nodesForFilter.length) {
        this.repaintNodeFilter();
      }
    },
    traefikInstances: function () {
      this.listRoutes();
    },
    instancesError: function (instancesError) {
      if (instancesError) {
        this.clearListeners(this.readListeners);
        this.loading.listRoutesNum = 0;
      }
    },
  },
  created() {
    this.internalSelectedNodeId = this.selectedNodeId;
    if (this.traefikInstances.length) {
      this.listRoutes();
    }
  },
  beforeDestroy() {
    this.clearListeners(this.readListeners);
    this.clearListeners(this.deleteListeners);
  },
  methods: {
    showCreateRouteModal() {
      this.isEditingRoute = false;
      this.isShownCreateOrEditRouteModal = true;
    },
    showEditRouteModal(route) {
      this.isEditingRoute = true;
      this.currentRoute = route;
      this.isShownCreateOrEditRouteModal = true;
    },
    hideCreateRouteModal() {
      this.isShownCreateOrEditRouteModal = false;
    },
    showRouteDetailModal(route) {
      this.currentRoute = route;
      this.isShownRouteDetailModal = true;
    },
    hideRouteDetailModal() {
      this.isShownRouteDetailModal = false;
    },
    showDeleteRouteModal(route) {
      this.error.deleteRoute = "";
      this.routeToDelete = route;
      this.isShownDeleteRouteModal = true;
    },
    hideDeleteRouteModal() {
      this.isShownDeleteRouteModal = false;
    },
    repaintNodeFilter() {
      this.$nextTick(() => {
        if (!this.internalSelectedNodeId) {
          // initially show all nodes
          this.internalSelectedNodeId = "all";
          return;
        }
        const nodeId = this.internalSelectedNodeId;
        this.internalSelectedNodeId = "";
        this.$nextTick(() => {
          this.internalSelectedNodeId = nodeId;
        });
      });
    },
    registerListener(listeners, eventName, handler) {
      this.$root.$once(eventName, handler);
      listeners.push([eventName, handler]);
    },
    clearListeners(listeners) {
      listeners.forEach(([eventName, handler]) => {
        this.$root.$off(eventName, handler);
      });
      listeners.splice(0);
    },
    async listRoutes() {
      // a handler of a previous chain would decrement the counter of this one
      this.clearListeners(this.readListeners);
      const generation = ++this.readGeneration;
      this.routes = [];
      // otherwise a transient error sticks after the nodes answer again
      this.error.listRoutes = "";
      this.currentErrorAction = "";
      this.currentErrorDescription = "";
      // count the whole batch upfront: the counter must not reach zero between
      // two iterations
      this.loading.listRoutesNum = this.traefikInstances.length;
      for (const traefikInstance of this.traefikInstances) {
        const taskAction = "list-routes";
        const eventId = this.getUuid();
        this.registerListener(
          this.readListeners,
          `${taskAction}-aborted-${eventId}`,
          this.listRoutesAborted
        );
        this.registerListener(
          this.readListeners,
          `${taskAction}-completed-${eventId}`,
          this.listRoutesCompleted
        );
        const res = await to(
          this.createModuleTaskForApp(traefikInstance.id, {
            action: taskAction,
            data: {
              expand_list: true,
            },
            extra: {
              title: this.$t("action." + taskAction),
              isNotificationHidden: true,
              traefikInstance: traefikInstance,
              eventId,
            },
          })
        );
        if (generation !== this.readGeneration) {
          return;
        }
        const err = res[0];
        if (err) {
          console.error(`error creating task ${taskAction}`, err);
          const errMessage = this.getErrorMessage(err);
          this.error.listRoutes = errMessage;
          this.currentErrorAction = this.$t("action." + taskAction);
          this.currentErrorDescription = errMessage;
          this.loading.listRoutesNum--;
        }
      }
    },
    listRoutesAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.listRoutes = this.$t("error.generic_error");
      this.currentErrorAction = this.$t("action." + taskContext.action);
      this.currentErrorDescription = this.$t("error.generic_error");
      this.loading.listRoutesNum--;
    },
    listRoutesCompleted(taskContext, taskResult) {
      const routes = [];
      const traefikId = taskContext.extra.traefikInstance.id;
      const nodeId = taskContext.extra.traefikInstance.node;
      const nodeUiName = taskContext.extra.traefikInstance.node_ui_name;
      for (let route of taskResult.output) {
        route.name = route.instance;
        let type = "";
        if (route.host && route.path) {
          type = "host_and_path";
        } else if (route.host) {
          type = "host";
        } else if (route.path) {
          type = "path";
        }
        route.type = type;
        route.ip_allowlist = route.ip_allowlist ? route.ip_allowlist : [];
        route.ip_allowlist_str = route.ip_allowlist
          ? route.ip_allowlist.join("\n")
          : "";
        const node = { id: nodeId, ui_name: nodeUiName };
        const nodeLabel = this.getShortNodeLabel(node) + ` (${traefikId})`;
        route.node = nodeLabel;
        route.nodeId = nodeId;
        route.longNodeLabel = this.getNodeLabel(node);
        route.traefikInstance = traefikId;
        routes.push(route);
      }
      // drop the previous routes of this instance: a late event must not duplicate them
      this.routes = this.routes
        .filter((route) => route.traefikInstance !== traefikId)
        .concat(routes)
        .sort(this.sortByProperty("name"));
      this.loading.listRoutesNum--;
      const now = new Date();
      const threeDaysAgo = new Date(now.getTime() - 72 * 60 * 60 * 1000);
      const startDate = this.formatDate(threeDaysAgo, "yyyy-MM-dd");
      const startHours = this.formatDate(threeDaysAgo, "HH");
      const startMins = this.formatDate(threeDaysAgo, "mm");
      const startTime = `${startHours}%3A${startMins}`;
      const endDate = this.formatDate(now, "yyyy-MM-dd");
      const endHours = this.formatDate(now, "HH");
      const endMins = this.formatDate(now, "mm");
      const endTime = `${endHours}%3A${endMins}`;
      const maxLines = 10;
      this.pendingCertificatesLogsPath[
        traefikId
      ] = `?searchQuery=acmeCA%3D&context=module&selectedAppId=${traefikId}&followLogs=false&startDate=${startDate}&startTime=${startTime}&endDate=${endDate}&endTime=${endTime}&maxLines=${maxLines}&autoStartSearch=true`;
    },
    clearFilters() {
      this.filter.text = "";
      // "all", not "": NsComboBox only repaints its text on a matching option
      this.internalSelectedNodeId = "all";
    },
    onReloadRoutes() {
      this.listRoutes();
    },
    async deleteRoute() {
      this.loading.deleteRoute = true;
      this.error.deleteRoute = "";
      const taskAction = "delete-route";
      const eventId = this.getUuid();
      this.registerListener(
        this.deleteListeners,
        `${taskAction}-aborted-${eventId}`,
        this.deleteRouteAborted
      );
      this.registerListener(
        this.deleteListeners,
        `${taskAction}-completed-${eventId}`,
        this.deleteRouteCompleted
      );
      const res = await to(
        this.createModuleTaskForApp(this.routeToDelete.traefikInstance, {
          action: taskAction,
          data: {
            instance: this.routeToDelete.name,
            lets_encrypt_cleanup: true,
          },
          extra: {
            title: this.$t("settings_http_routes.delete_route_route", {
              route: this.routeToDelete.name,
            }),
            description: this.$t("common.processing"),
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.deleteRoute = this.getErrorMessage(err);
        this.loading.deleteRoute = false;
        return;
      }
      this.hideDeleteRouteModal();
    },
    deleteRouteAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.loading.deleteRoute = false;
    },
    deleteRouteCompleted() {
      this.loading.deleteRoute = false;
      this.listRoutes();
    },
    sortHttpRoutes(sortProperty) {
      if (sortProperty != "route") {
        return this.sortByProperty(sortProperty);
      }
      return function (a, b) {
        const valueA = a.host || a.path;
        const valueB = b.host || b.path;
        if (valueA < valueB) {
          return -1;
        }
        if (valueA > valueB) {
          return 1;
        }
        return 0;
      };
    },
    goToPendingCertificateLogs(route) {
      this.$router.push(
        `/system-logs${this.pendingCertificatesLogsPath[route.traefikInstance]}`
      );
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
.filter-field {
  max-width: 18rem;
  width: 100%;
}
</style>
</file>

<file path="core/ui/src/components/settings/LokiCard.vue">
<template>
  <cv-tile kind="standard" :light="true" class="loki-card ns-card">
    <slot name="menu"></slot>
    <div class="row">
      <NsSvg :svg="Catalog32" />
    </div>
    <div class="row">
      <h3 class="title ellipsis">
        {{ instanceLabel ? instanceLabel : instanceId }}
      </h3>
    </div>
    <div class="row loki-card">
      <span class="row" v-if="instanceLabel">{{ instanceId }}</span>
      <span class="row margin-top" v-if="!offline">{{
        `${$t("system_logs.loki.active_from")} ${activeFromFormatted} ${
          activeToFormatted
            ? `${$t("system_logs.loki.active_to")} ${activeToFormatted}`
            : ""
        }`
      }}</span>
      <div class="row">
        <NsSvg :svg="Chip20" />
        <span class="margin-left">
          {{ nodeLabel ? nodeLabel : $t("common.node") + " " + nodeId }}
        </span>
      </div>
      <div class="row" v-if="showStatusBadge">
        <cv-tag v-if="active" kind="green" :label="activeText"></cv-tag>
        <cv-tag v-else-if="offline" kind="red" :label="offlineText"></cv-tag>
        <cv-tag v-else kind="gray" :label="inactiveText"></cv-tag>
      </div>
      <div
        class="card-row mg-top-sm icon-and-text"
        v-if="cloudLogManagerForwarderStatus == 'active'"
      >
        <NsSvg :svg="CheckmarkFilled16" class="icon ns-success" />
        <span class="margin-left">{{
          $t("cloud_log_manager_forwarder.cloud_log_manager_export_enabled")
        }}</span>
      </div>
      <div
        class="card-row mg-top-sm icon-and-text"
        v-if="cloudLogManagerForwarderStatus == 'failed'"
      >
        <NsSvg :svg="ErrorFilled16" class="icon ns-error" />
        <span class="margin-left">{{
          $t("cloud_log_manager_forwarder.cloud_log_manager_export_failed")
        }}</span>
      </div>
      <div
        class="card-row mg-top-sm icon-and-text"
        v-if="syslogForwarderStatus == 'active'"
      >
        <NsSvg :svg="CheckmarkFilled16" class="icon ns-success" />
        <span>{{ $t("syslog_forwarder.syslog_export_enabled") }}</span>
      </div>
      <div
        class="card-row mg-top-sm icon-and-text"
        v-if="syslogForwarderStatus == 'failed'"
      >
        <NsSvg :svg="ErrorFilled16" class="icon ns-error" />
        <span>{{ $t("syslog_forwarder.syslog_export_failed") }}</span>
      </div>
      <div class="card-row mg-top-sm icon-and-text" v-if="!offline">
        <NsSvg :svg="InformationFilled16" class="icon ns-info" />
        <span>{{ $tc("system_logs.loki.retention_days", retentionDays) }}</span>
      </div>
      <div class="row" v-if="noLogs">
        <NsSvg :svg="InformationFilled16" class="icon ns-info" />
        <span>{{ $t("system_logs.loki.no_logs") }}</span>
      </div>
    </div>
  </cv-tile>
</template>
⋮----
{{ instanceLabel ? instanceLabel : instanceId }}
⋮----
<span class="row" v-if="instanceLabel">{{ instanceId }}</span>
<span class="row margin-top" v-if="!offline">{{
        `${$t("system_logs.loki.active_from")} ${activeFromFormatted} ${
          activeToFormatted
            ? `${$t("system_logs.loki.active_to")} ${activeToFormatted}`
            : ""
        }`
      }}</span>
⋮----
{{ nodeLabel ? nodeLabel : $t("common.node") + " " + nodeId }}
⋮----
<span class="margin-left">{{
          $t("cloud_log_manager_forwarder.cloud_log_manager_export_enabled")
        }}</span>
⋮----
<span class="margin-left">{{
          $t("cloud_log_manager_forwarder.cloud_log_manager_export_failed")
        }}</span>
⋮----
<span>{{ $t("syslog_forwarder.syslog_export_enabled") }}</span>
⋮----
<span>{{ $t("syslog_forwarder.syslog_export_failed") }}</span>
⋮----
<span>{{ $tc("system_logs.loki.retention_days", retentionDays) }}</span>
⋮----
<span>{{ $t("system_logs.loki.no_logs") }}</span>
⋮----
<script>
import {
  UtilService,
  IconService,
  DateTimeService,
  LottieService,
  PageTitleService,
} from "@nethserver/ns8-ui-lib";
export default {
  name: "LokiCard",
  mixins: [
    DateTimeService,
    IconService,
    UtilService,
    LottieService,
    PageTitleService,
  ],
  props: {
    instanceId: {
      type: String,
      required: true,
    },
    instanceLabel: {
      type: String,
      default: "",
    },
    nodeId: {
      type: String,
      required: true,
    },
    nodeLabel: {
      type: String,
      default: "",
    },
    active: {
      type: Boolean,
      required: true,
    },
    offline: {
      type: Boolean,
      required: true,
    },
    retentionDays: {
      type: Number,
      default: 0,
    },
    activeFrom: {
      type: String,
      default: "",
    },
    activeTo: {
      type: String,
      default: "",
    },
    showStatusBadge: {
      type: Boolean,
      required: true,
    },
    cloudLogManagerForwarderStatus: {
      type: String,
      default: "inactive",
    },
    syslogForwarderStatus: {
      type: String,
      default: "inactive",
    },
  },
  computed: {
    activeFromFormatted() {
      return this.activeFrom
        ? new Intl.DateTimeFormat(navigator.language).format(
            new Date(this.activeFrom)
          )
        : "";
    },
    activeToFormatted() {
      return this.activeTo
        ? new Intl.DateTimeFormat(navigator.language).format(
            new Date(this.activeTo)
          )
        : "";
    },
    activeText() {
      return this.$t("system_logs.loki.active");
    },
    inactiveText() {
      return this.$t("system_logs.loki.inactive");
    },
    offlineText() {
      return this.$t("system_logs.loki.offline");
    },
    noLogs() {
      if (!this.offline) {
        const retentionDate = new Date(this.activeTo);
        retentionDate.setDate(retentionDate.getDate() + this.retentionDays);
        return retentionDate < new Date();
      }
      return false;
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
.loki-card {
  display: flex;
  flex-direction: column;
  position: relative;
  row-gap: 0.75rem;
}
.margin-left {
  margin-left: 0.25rem;
}
.row {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 0.25rem;
}
.label {
  padding-right: 0.75rem;
  font-weight: bold;
  text-align: right;
  padding-bottom: 0.5rem;
}
.margin-top {
  margin-top: 0.5rem;
}
</style>
</file>

<file path="core/ui/src/components/settings/RequestTlsCertificateModal.vue">
<template>
  <NsModal
    size="default"
    :visible="isShown"
    :primary-button-disabled="loading.setCertificate"
    :isLoading="loading.setCertificate"
    @modal-hidden="onModalHidden"
    @primary-click="setCertificate"
  >
    <template slot="title">{{
      certificate
        ? $t("settings_tls_certificates.manage_names")
        : $t("settings_tls_certificates.request_certificate")
    }}</template>
    <template slot="content">
      <cv-form @submit.prevent="setCertificate">
        <div v-show="loading.setCertificate">
          <NsEmptyState
            :title="
              $t('settings_tls_certificates.checking_certificate_requirements')
            "
            :animationData="GearsLottie"
            animationTitle="gears"
            :loop="true"
            class="checking-certificate"
          />
        </div>
        <div v-show="!loading.setCertificate">
          <NsInlineNotification
            v-if="certificate"
            kind="info"
            :showCloseButton="false"
          >
            <template #description>
              <p>
                {{ $t("settings_tls_certificates.manage_names_message_1") }}
              </p>
              <ul class="unordered-list">
                <li>
                  {{ $t("settings_tls_certificates.manage_names_message_2") }}
                </li>
                <li>
                  {{ $t("settings_tls_certificates.manage_names_message_3") }}
                </li>
              </ul>
            </template>
          </NsInlineNotification>
          <p v-else class="mb-6">
            {{
              $t("settings_tls_certificates.request_certificate_description")
            }}
          </p>
          <NsTextInput
            v-if="certificate"
            v-model="certificate.node"
            :label="$t('common.node')"
            disabled
            light
          />
          <NsComboBox
            v-else
            v-model="selectedNodeId"
            :label="$t('common.choose_a_node')"
            :title="$t('common.node')"
            :auto-filter="true"
            :auto-highlight="true"
            :options="nodes"
            :disabled="loading.setCertificate || !!certificate"
            :invalid-message="error.node"
            tooltipAlignment="start"
            tooltipDirection="right"
            light
            ref="node"
          >
            <template #tooltip>
              {{ $t("settings_tls_certificates.node_tooltip") }}
            </template>
          </NsComboBox>
          <div class="names">
            <label for="names" class="bx--label mb-1">
              <div class="label-with-tooltip">
                {{ $t("settings_tls_certificates.names") }}
                <cv-interactive-tooltip
                  alignment="start"
                  direction="right"
                  class="info"
                >
                  <template slot="content">
                    {{ $t("settings_tls_certificates.names_tooltip") }}
                  </template>
                </cv-interactive-tooltip>
              </div>
            </label>
            <cv-text-area
              id="names"
              v-model.trim="names"
              :invalid-message="$t(error.names)"
              :helper-text="$t('settings_tls_certificates.names_helper')"
              class="names"
              ref="names"
            >
            </cv-text-area>
          </div>
          <NsInlineNotification
            v-if="error.setCertificate"
            kind="error"
            :title="$t('settings_tls_certificates.cannot_obtain_certificate')"
            :description="error.setCertificate"
            :showCloseButton="false"
          />
          <NsInlineNotification
            v-if="validationErrorDetails.length"
            kind="error"
            :title="$t('settings_tls_certificates.cannot_obtain_certificate')"
            :showCloseButton="false"
          >
            <template #description>
              <div class="flex flex-col gap-2">
                <p>
                  {{ $t("settings_tls_certificates.validation_error_message") }}
                </p>
                <p
                  v-for="(detail, index) in validationErrorDetails"
                  :key="index"
                >
                  {{ detail }}
                </p>
              </div>
            </template>
          </NsInlineNotification>
        </div>
      </cv-form>
    </template>
    <template slot="secondary-button">{{ $t("common.cancel") }}</template>
    <template slot="primary-button">{{
      certificate
        ? $t("common.save")
        : $t("settings_tls_certificates.request_certificate")
    }}</template>
  </NsModal>
</template>
⋮----
<template slot="title">{{
      certificate
        ? $t("settings_tls_certificates.manage_names")
        : $t("settings_tls_certificates.request_certificate")
    }}</template>
<template slot="content">
      <cv-form @submit.prevent="setCertificate">
        <div v-show="loading.setCertificate">
          <NsEmptyState
            :title="
              $t('settings_tls_certificates.checking_certificate_requirements')
            "
            :animationData="GearsLottie"
            animationTitle="gears"
            :loop="true"
            class="checking-certificate"
          />
        </div>
        <div v-show="!loading.setCertificate">
          <NsInlineNotification
            v-if="certificate"
            kind="info"
            :showCloseButton="false"
          >
            <template #description>
              <p>
                {{ $t("settings_tls_certificates.manage_names_message_1") }}
              </p>
              <ul class="unordered-list">
                <li>
                  {{ $t("settings_tls_certificates.manage_names_message_2") }}
                </li>
                <li>
                  {{ $t("settings_tls_certificates.manage_names_message_3") }}
                </li>
              </ul>
            </template>
          </NsInlineNotification>
          <p v-else class="mb-6">
            {{
              $t("settings_tls_certificates.request_certificate_description")
            }}
          </p>
          <NsTextInput
            v-if="certificate"
            v-model="certificate.node"
            :label="$t('common.node')"
            disabled
            light
          />
          <NsComboBox
            v-else
            v-model="selectedNodeId"
            :label="$t('common.choose_a_node')"
            :title="$t('common.node')"
            :auto-filter="true"
            :auto-highlight="true"
            :options="nodes"
            :disabled="loading.setCertificate || !!certificate"
            :invalid-message="error.node"
            tooltipAlignment="start"
            tooltipDirection="right"
            light
            ref="node"
          >
            <template #tooltip>
              {{ $t("settings_tls_certificates.node_tooltip") }}
            </template>
          </NsComboBox>
          <div class="names">
            <label for="names" class="bx--label mb-1">
              <div class="label-with-tooltip">
                {{ $t("settings_tls_certificates.names") }}
                <cv-interactive-tooltip
                  alignment="start"
                  direction="right"
                  class="info"
                >
                  <template slot="content">
                    {{ $t("settings_tls_certificates.names_tooltip") }}
                  </template>
                </cv-interactive-tooltip>
              </div>
            </label>
            <cv-text-area
              id="names"
              v-model.trim="names"
              :invalid-message="$t(error.names)"
              :helper-text="$t('settings_tls_certificates.names_helper')"
              class="names"
              ref="names"
            >
            </cv-text-area>
          </div>
          <NsInlineNotification
            v-if="error.setCertificate"
            kind="error"
            :title="$t('settings_tls_certificates.cannot_obtain_certificate')"
            :description="error.setCertificate"
            :showCloseButton="false"
          />
          <NsInlineNotification
            v-if="validationErrorDetails.length"
            kind="error"
            :title="$t('settings_tls_certificates.cannot_obtain_certificate')"
            :showCloseButton="false"
          >
            <template #description>
              <div class="flex flex-col gap-2">
                <p>
                  {{ $t("settings_tls_certificates.validation_error_message") }}
                </p>
                <p
                  v-for="(detail, index) in validationErrorDetails"
                  :key="index"
                >
                  {{ detail }}
                </p>
              </div>
            </template>
          </NsInlineNotification>
        </div>
      </cv-form>
    </template>
⋮----
<template #description>
              <p>
                {{ $t("settings_tls_certificates.manage_names_message_1") }}
              </p>
              <ul class="unordered-list">
                <li>
                  {{ $t("settings_tls_certificates.manage_names_message_2") }}
                </li>
                <li>
                  {{ $t("settings_tls_certificates.manage_names_message_3") }}
                </li>
              </ul>
            </template>
⋮----
{{ $t("settings_tls_certificates.manage_names_message_1") }}
⋮----
{{ $t("settings_tls_certificates.manage_names_message_2") }}
⋮----
{{ $t("settings_tls_certificates.manage_names_message_3") }}
⋮----
{{
              $t("settings_tls_certificates.request_certificate_description")
            }}
⋮----
<template #tooltip>
              {{ $t("settings_tls_certificates.node_tooltip") }}
            </template>
⋮----
{{ $t("settings_tls_certificates.node_tooltip") }}
⋮----
{{ $t("settings_tls_certificates.names") }}
⋮----
<template slot="content">
                    {{ $t("settings_tls_certificates.names_tooltip") }}
                  </template>
⋮----
{{ $t("settings_tls_certificates.names_tooltip") }}
⋮----
<template #description>
              <div class="flex flex-col gap-2">
                <p>
                  {{ $t("settings_tls_certificates.validation_error_message") }}
                </p>
                <p
                  v-for="(detail, index) in validationErrorDetails"
                  :key="index"
                >
                  {{ detail }}
                </p>
              </div>
            </template>
⋮----
{{ $t("settings_tls_certificates.validation_error_message") }}
⋮----
{{ detail }}
⋮----
<template slot="secondary-button">{{ $t("common.cancel") }}</template>
<template slot="primary-button">{{
      certificate
        ? $t("common.save")
        : $t("settings_tls_certificates.request_certificate")
    }}</template>
⋮----
<script>
import to from "await-to-js";
import {
  UtilService,
  TaskService,
  DateTimeService,
  LottieService,
} from "@nethserver/ns8-ui-lib";
export default {
  name: "RequestTlsCertificateModal",
  mixins: [UtilService, TaskService, DateTimeService, LottieService],
  props: {
    isShown: Boolean,
    nodes: {
      type: Array,
      required: true,
    },
    allCertificates: {
      type: Array,
      required: true,
    },
    certificate: {
      type: Object,
      default: null,
    },
  },
  data() {
    return {
      names: "",
      selectedNodeId: null,
      validationErrorDetails: [],
      loading: {
        setCertificate: false,
      },
      error: {
        setCertificate: "",
        names: "",
        node: "",
      },
    };
  },
  watch: {
    isShown: function () {
      if (this.isShown) {
        this.clearErrors();
        this.validationErrorDetails = [];
        if (this.certificate) {
          this.names = this.certificate.names.join("\n");
          this.$nextTick(() => {
            this.focusElement("names");
          });
        } else {
          this.clearFields();
        }
      }
    },
  },
  methods: {
    onModalHidden() {
      this.clearErrors();
      this.validationErrorDetails = [];
      this.$emit("hide");
    },
    validateSetCertificate() {
      this.clearErrors();
      this.validationErrorDetails = [];
      let isValidationOk = true;
      if (!this.names) {
        this.error.names = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("names");
          isValidationOk = false;
        }
      }
      if (!this.certificate && !this.selectedNodeId) {
        this.error.node = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("node");
          isValidationOk = false;
        }
      }
      return isValidationOk;
    },
    async setCertificate() {
      if (!this.validateSetCertificate()) {
        return;
      }
      this.loading.setCertificate = true;
      this.error.setCertificate = "";
      const taskAction = "set-default-certificate";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.setCertificateAborted
      );
      this.$root.$once(
        `${taskAction}-validation-ok-${eventId}`,
        this.setCertificateValidationOk
      );
      this.$root.$once(
        `${taskAction}-validation-failed-${eventId}`,
        this.setCertificateValidationFailed
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.setCertificateCompleted
      );
      let traefikInstance = null;
      let node = null;
      if (this.certificate) {
        traefikInstance = this.certificate.traefikInstance;
        node = this.certificate.longNodeLabel;
      } else {
        const selectedNode = this.nodes.find(
          (node) => node.value === this.selectedNodeId
        );
        traefikInstance = selectedNode.traefikInstance;
        node = selectedNode.label;
      }
      const logsStartDate = this.formatDate(new Date(), "yyyy-MM-dd");
      const logsHours = this.formatDate(new Date(), "HH");
      const logsMins = this.formatDate(new Date(), "mm");
      const logsStartTime = `${logsHours}%3A${logsMins}`;
      const res = await to(
        this.createModuleTaskForApp(traefikInstance, {
          action: taskAction,
          data: {
            names: this.names
              .split("\n")
              .filter((detail) => detail.trim() !== ""),
          },
          extra: {
            title: this.$t(
              "settings_tls_certificates.request_certificate_for_node",
              {
                node,
              }
            ),
            description: this.$t("common.processing"),
            eventId,
            logs: {
              path: `?searchQuery=&context=module&selectedAppId=${traefikInstance}&followLogs=false&startDate=${logsStartDate}&startTime=${logsStartTime}&autoStartSearch=true`,
              instance: traefikInstance,
            },
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.setCertificate = this.getErrorMessage(err);
        this.loading.setCertificate = false;
        return;
      }
    },
    setCertificateAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.setCertificate = this.getSetCertificateErrorMessage(
        taskResult.error
      );
      this.loading.setCertificate = false;
      this.$root.$emit("reloadCertificates");
    },
    getSetCertificateErrorMessage(errorMessage) {
      if (errorMessage.includes("Invalid identifiers requested")) {
        return this.$t(
          "settings_tls_certificates.invalid_identifiers_requested_error"
        );
      } else if (
        /no valid A records found|check that a DNS record exists/.test(
          errorMessage
        )
      ) {
        return this.$t("settings_tls_certificates.dns_record_error");
      } else if (
        errorMessage.includes("refuses to issue a certificate for this domain")
      ) {
        return this.$t(
          "settings_tls_certificates.refuses_to_issue_certificate_error"
        );
      } else if (errorMessage.includes("tls: unrecognized name")) {
        return this.$t(
          "settings_tls_certificates.ensure_node_matches_fqdn_error"
        );
      } else {
        return this.$t(
          "settings_tls_certificates.set_certificate_unknown_error"
        );
      }
    },
    setCertificateValidationOk() {
      this.loading.setCertificate = false;
      this.clearFields();
      this.$emit("hide");
    },
    setCertificateValidationFailed(validationErrors) {
      this.loading.setCertificate = false;
      let focusAlreadySet = false;
      for (const validationError of validationErrors) {
        const param = validationError.parameter;
        if (validationError.details) {
          this.validationErrorDetails = validationError.details
            .split("\n")
            .filter((detail) => detail.trim() !== "");
        } else {
          // set i18n error message
          this.error[param] = this.getI18nStringWithFallback(
            "settings_tls_certificates." + validationError.error,
            "error." + validationError.error,
            null,
            { value: validationError.value }
          );
          if (!focusAlreadySet) {
            this.focusElement(param);
            focusAlreadySet = true;
          }
        }
      }
    },
    setCertificateCompleted() {
      this.loading.setCertificate = false;
      this.clearFields();
      // reload certificates
      this.$root.$emit("reloadCertificates");
    },
    clearFields() {
      this.names = "";
      this.selectedNodeId = "";
      if (this.$refs.node) {
        this.$refs.node.clearValue();
      }
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
.names {
  margin-bottom: 4rem;
}
.checking-certificate {
  margin-top: 4rem;
  margin-bottom: 4rem;
}
.label-with-tooltip {
  display: flex;
  align-items: baseline;
}
@media (min-width: $breakpoint-medium) {
  .cv-text-area {
    max-width: 38rem;
  }
}
</style>
⋮----
<style lang="scss">
@import "../../styles/carbon-utils";
.names textarea {
  min-height: 7rem;
}
.names .bx--tooltip__label .bx--tooltip__trigger {
  margin-left: 0.25rem;
}
</style>
</file>

<file path="core/ui/src/components/settings/SyslogConfigureModal.vue">
<template>
  <NsModal
    size="default"
    :visible="isShown"
    :isLoading="loading.setSyslog"
    @modal-hidden="onModalHidden"
    @modal-shown="onModalShown"
    @primary-click="setSyslog"
  >
    <template slot="title">{{
      $t("syslog_forwarder.configure_export_to_syslog")
    }}</template>
    <template slot="content">
      <cv-form>
        <NsToggle
          :label="$t('syslog_forwarder.export_to_syslog')"
          v-model="toggleEnabled"
          value="toggleEnabled"
        >
          <template slot="text-left">{{ $t("common.disabled") }}</template>
          <template slot="text-right">{{ $t("common.enabled") }}</template>
        </NsToggle>
        <template v-if="toggleEnabled">
          <NsTextInput
            :label="$t('syslog_forwarder.hostname_ip_address')"
            v-model="address"
            :invalid-message="error.address"
          />
          <NsTextInput
            :label="$t('syslog_forwarder.port_number')"
            :placeholder="$t('syslog_forwarder.port_placeholder')"
            v-model="port"
            :invalid-message="error.port"
          />
          <div>
            <label for="filter" :class="`${carbonPrefix}--label`">{{
              $t("syslog_forwarder.filter")
            }}</label>
            <cv-radio-group :vertical="true">
              <cv-radio-button
                ref="filterVal"
                :label="$t('syslog_forwarder.full')"
                value=""
                v-model="filterVal"
              />
              <cv-radio-button
                ref="filterVal"
                :label="$t('syslog_forwarder.security')"
                value="security"
                v-model="filterVal"
              />
            </cv-radio-group>
          </div>
          <div>
            <label for="protocol" :class="`${carbonPrefix}--label`">{{
              $t("syslog_forwarder.protocol")
            }}</label>
            <cv-radio-group :vertical="true">
              <cv-radio-button
                ref="protocolVal"
                :label="$t('syslog_forwarder.udp')"
                value="udp"
                v-model="protocolVal"
              />
              <cv-radio-button
                ref="protocolVal"
                :label="$t('syslog_forwarder.tcp')"
                value="tcp"
                v-model="protocolVal"
              />
            </cv-radio-group>
          </div>
          <div>
            <label for="format" :class="`${carbonPrefix}--label`">{{
              $t("syslog_forwarder.format")
            }}</label>
            <cv-interactive-tooltip class="info mg-left-xs">
              <template slot="content">
                <a
                  href="https://www.rfc-editor.org/rfc/rfc3164"
                  target="_blank"
                  >{{ $t("syslog_forwarder.rfc3164") }}</a
                >
                <br />
                <a
                  href="https://www.rfc-editor.org/rfc/rfc5424"
                  target="_blank"
                  >{{ $t("syslog_forwarder.rfc5424") }}</a
                >
              </template>
            </cv-interactive-tooltip>
            <cv-radio-group :vertical="true">
              <cv-radio-button
                ref="formatVal"
                :label="$t('syslog_forwarder.rfc3164')"
                value="rfc3164"
                v-model="formatVal"
              />
              <cv-radio-button
                ref="formatVal"
                :label="$t('syslog_forwarder.rfc5424')"
                value="rfc5424"
                v-model="formatVal"
              />
            </cv-radio-group>
          </div>
        </template>
        <div v-if="toggleEnabled && this.configuration.last_timestamp != ''">
          <label for="startTime" :class="`${carbonPrefix}--label`">{{
            $t("syslog_forwarder.export_starting_date")
          }}</label>
          <cv-radio-group :vertical="true">
            <cv-radio-button
              ref="dateVal"
              :label="
                $t('syslog_forwarder.use_last_timestamp', {
                  timestamp: this.lastTimestampFormatted,
                })
              "
              value="last_timestamp"
              v-model="dateVal"
            />
            <cv-radio-button
              ref="dateVal"
              :label="$t('syslog_forwarder.choose_a_datetime')"
              value="choose_date_time"
              v-model="dateVal"
            />
          </cv-radio-group>
        </div>
        <cv-row v-if="dateVal == 'choose_date_time' && toggleEnabled">
          <cv-column>
            <cv-date-picker
              kind="single"
              :date-label="$t('syslog_forwarder.start_date')"
              class="interval-date mg-bottom-md"
              :cal-options="calOptions"
              v-model="date"
            >
            </cv-date-picker>
            <NsTimePicker
              hideClearButton
              dropDirection="up"
              :label="$t('syslog_forwarder.start_time')"
              class="interval-time"
              v-model="time"
            >
            </NsTimePicker>
          </cv-column>
        </cv-row>
      </cv-form>
      <NsInlineNotification
        v-if="error.setSyslog"
        kind="error"
        :title="$t('system_logs.loki.cannot_configure_forwarder')"
        :description="error.setSyslog"
        :showCloseButton="false"
      />
    </template>
    <template slot="secondary-button">{{ $t("common.cancel") }}</template>
    <template slot="primary-button">{{ $t("common.configure") }}</template>
  </NsModal>
</template>
⋮----
<template slot="title">{{
      $t("syslog_forwarder.configure_export_to_syslog")
    }}</template>
<template slot="content">
      <cv-form>
        <NsToggle
          :label="$t('syslog_forwarder.export_to_syslog')"
          v-model="toggleEnabled"
          value="toggleEnabled"
        >
          <template slot="text-left">{{ $t("common.disabled") }}</template>
          <template slot="text-right">{{ $t("common.enabled") }}</template>
        </NsToggle>
        <template v-if="toggleEnabled">
          <NsTextInput
            :label="$t('syslog_forwarder.hostname_ip_address')"
            v-model="address"
            :invalid-message="error.address"
          />
          <NsTextInput
            :label="$t('syslog_forwarder.port_number')"
            :placeholder="$t('syslog_forwarder.port_placeholder')"
            v-model="port"
            :invalid-message="error.port"
          />
          <div>
            <label for="filter" :class="`${carbonPrefix}--label`">{{
              $t("syslog_forwarder.filter")
            }}</label>
            <cv-radio-group :vertical="true">
              <cv-radio-button
                ref="filterVal"
                :label="$t('syslog_forwarder.full')"
                value=""
                v-model="filterVal"
              />
              <cv-radio-button
                ref="filterVal"
                :label="$t('syslog_forwarder.security')"
                value="security"
                v-model="filterVal"
              />
            </cv-radio-group>
          </div>
          <div>
            <label for="protocol" :class="`${carbonPrefix}--label`">{{
              $t("syslog_forwarder.protocol")
            }}</label>
            <cv-radio-group :vertical="true">
              <cv-radio-button
                ref="protocolVal"
                :label="$t('syslog_forwarder.udp')"
                value="udp"
                v-model="protocolVal"
              />
              <cv-radio-button
                ref="protocolVal"
                :label="$t('syslog_forwarder.tcp')"
                value="tcp"
                v-model="protocolVal"
              />
            </cv-radio-group>
          </div>
          <div>
            <label for="format" :class="`${carbonPrefix}--label`">{{
              $t("syslog_forwarder.format")
            }}</label>
            <cv-interactive-tooltip class="info mg-left-xs">
              <template slot="content">
                <a
                  href="https://www.rfc-editor.org/rfc/rfc3164"
                  target="_blank"
                  >{{ $t("syslog_forwarder.rfc3164") }}</a
                >
                <br />
                <a
                  href="https://www.rfc-editor.org/rfc/rfc5424"
                  target="_blank"
                  >{{ $t("syslog_forwarder.rfc5424") }}</a
                >
              </template>
            </cv-interactive-tooltip>
            <cv-radio-group :vertical="true">
              <cv-radio-button
                ref="formatVal"
                :label="$t('syslog_forwarder.rfc3164')"
                value="rfc3164"
                v-model="formatVal"
              />
              <cv-radio-button
                ref="formatVal"
                :label="$t('syslog_forwarder.rfc5424')"
                value="rfc5424"
                v-model="formatVal"
              />
            </cv-radio-group>
          </div>
        </template>
        <div v-if="toggleEnabled && this.configuration.last_timestamp != ''">
          <label for="startTime" :class="`${carbonPrefix}--label`">{{
            $t("syslog_forwarder.export_starting_date")
          }}</label>
          <cv-radio-group :vertical="true">
            <cv-radio-button
              ref="dateVal"
              :label="
                $t('syslog_forwarder.use_last_timestamp', {
                  timestamp: this.lastTimestampFormatted,
                })
              "
              value="last_timestamp"
              v-model="dateVal"
            />
            <cv-radio-button
              ref="dateVal"
              :label="$t('syslog_forwarder.choose_a_datetime')"
              value="choose_date_time"
              v-model="dateVal"
            />
          </cv-radio-group>
        </div>
        <cv-row v-if="dateVal == 'choose_date_time' && toggleEnabled">
          <cv-column>
            <cv-date-picker
              kind="single"
              :date-label="$t('syslog_forwarder.start_date')"
              class="interval-date mg-bottom-md"
              :cal-options="calOptions"
              v-model="date"
            >
            </cv-date-picker>
            <NsTimePicker
              hideClearButton
              dropDirection="up"
              :label="$t('syslog_forwarder.start_time')"
              class="interval-time"
              v-model="time"
            >
            </NsTimePicker>
          </cv-column>
        </cv-row>
      </cv-form>
      <NsInlineNotification
        v-if="error.setSyslog"
        kind="error"
        :title="$t('system_logs.loki.cannot_configure_forwarder')"
        :description="error.setSyslog"
        :showCloseButton="false"
      />
    </template>
⋮----
<template slot="text-left">{{ $t("common.disabled") }}</template>
<template slot="text-right">{{ $t("common.enabled") }}</template>
⋮----
<template v-if="toggleEnabled">
          <NsTextInput
            :label="$t('syslog_forwarder.hostname_ip_address')"
            v-model="address"
            :invalid-message="error.address"
          />
          <NsTextInput
            :label="$t('syslog_forwarder.port_number')"
            :placeholder="$t('syslog_forwarder.port_placeholder')"
            v-model="port"
            :invalid-message="error.port"
          />
          <div>
            <label for="filter" :class="`${carbonPrefix}--label`">{{
              $t("syslog_forwarder.filter")
            }}</label>
            <cv-radio-group :vertical="true">
              <cv-radio-button
                ref="filterVal"
                :label="$t('syslog_forwarder.full')"
                value=""
                v-model="filterVal"
              />
              <cv-radio-button
                ref="filterVal"
                :label="$t('syslog_forwarder.security')"
                value="security"
                v-model="filterVal"
              />
            </cv-radio-group>
          </div>
          <div>
            <label for="protocol" :class="`${carbonPrefix}--label`">{{
              $t("syslog_forwarder.protocol")
            }}</label>
            <cv-radio-group :vertical="true">
              <cv-radio-button
                ref="protocolVal"
                :label="$t('syslog_forwarder.udp')"
                value="udp"
                v-model="protocolVal"
              />
              <cv-radio-button
                ref="protocolVal"
                :label="$t('syslog_forwarder.tcp')"
                value="tcp"
                v-model="protocolVal"
              />
            </cv-radio-group>
          </div>
          <div>
            <label for="format" :class="`${carbonPrefix}--label`">{{
              $t("syslog_forwarder.format")
            }}</label>
            <cv-interactive-tooltip class="info mg-left-xs">
              <template slot="content">
                <a
                  href="https://www.rfc-editor.org/rfc/rfc3164"
                  target="_blank"
                  >{{ $t("syslog_forwarder.rfc3164") }}</a
                >
                <br />
                <a
                  href="https://www.rfc-editor.org/rfc/rfc5424"
                  target="_blank"
                  >{{ $t("syslog_forwarder.rfc5424") }}</a
                >
              </template>
            </cv-interactive-tooltip>
            <cv-radio-group :vertical="true">
              <cv-radio-button
                ref="formatVal"
                :label="$t('syslog_forwarder.rfc3164')"
                value="rfc3164"
                v-model="formatVal"
              />
              <cv-radio-button
                ref="formatVal"
                :label="$t('syslog_forwarder.rfc5424')"
                value="rfc5424"
                v-model="formatVal"
              />
            </cv-radio-group>
          </div>
        </template>
⋮----
<label for="filter" :class="`${carbonPrefix}--label`">{{
              $t("syslog_forwarder.filter")
            }}</label>
⋮----
<label for="protocol" :class="`${carbonPrefix}--label`">{{
              $t("syslog_forwarder.protocol")
            }}</label>
⋮----
<label for="format" :class="`${carbonPrefix}--label`">{{
              $t("syslog_forwarder.format")
            }}</label>
⋮----
<template slot="content">
                <a
                  href="https://www.rfc-editor.org/rfc/rfc3164"
                  target="_blank"
                  >{{ $t("syslog_forwarder.rfc3164") }}</a
                >
                <br />
                <a
                  href="https://www.rfc-editor.org/rfc/rfc5424"
                  target="_blank"
                  >{{ $t("syslog_forwarder.rfc5424") }}</a
                >
              </template>
⋮----
>{{ $t("syslog_forwarder.rfc3164") }}</a
⋮----
>{{ $t("syslog_forwarder.rfc5424") }}</a
⋮----
<label for="startTime" :class="`${carbonPrefix}--label`">{{
            $t("syslog_forwarder.export_starting_date")
          }}</label>
⋮----
<template slot="secondary-button">{{ $t("common.cancel") }}</template>
<template slot="primary-button">{{ $t("common.configure") }}</template>
⋮----
<script>
import to from "await-to-js";
import { NsToggle, TaskService, DateTimeService } from "@nethserver/ns8-ui-lib";
import { carbonPrefixMixin } from "@carbon/vue/src/mixins";
export default {
  name: "SyslogConfigureModal",
  props: {
    isShown: {
      type: Boolean,
      required: true,
    },
    lokiToEdit: {
      type: null,
      required: true,
    },
    configuration: {
      type: Object,
      required: true,
    },
  },
  components: {
    NsToggle,
  },
  mixins: [carbonPrefixMixin, TaskService, DateTimeService],
  data() {
    return {
      dateVal: "last_timestamp",
      protocolVal: "udp",
      filterVal: "",
      formatVal: "rfc3164",
      toggleEnabled: false,
      address: "",
      port: "",
      date: "",
      time: "",
      lastTimestampFormatted: "",
      loading: {
        setSyslog: false,
      },
      error: {
        address: "",
        port: "",
        setSyslog: "",
      },
      calOptions: {
        dateFormat: "Y-m-d",
      },
    };
  },
  methods: {
    onModalHidden() {
      this.$emit("hide");
      this.resetModal();
    },
    resetModal() {
      this.dateVal = "last_timestamp";
      this.protocolVal = "udp";
      this.filterVal = "";
      this.formatVal = "rfc3164";
      this.toggleEnabled = false;
      this.address = "";
      this.port = "";
      this.date = "";
      this.time = "";
      this.lastTimestampFormatted = "";
    },
    onModalShown() {
      if (
        this.configuration.status == "active" ||
        this.configuration.status == "failed"
      ) {
        this.toggleEnabled = true;
      }
      if (this.configuration.address != "") {
        this.address = this.configuration.address;
      }
      if (this.configuration.port != "") {
        this.port = this.configuration.port;
      }
      if (this.configuration.protocol != "") {
        this.protocolVal = this.configuration.protocol;
      }
      if (this.configuration.filter != "") {
        this.filterVal = this.configuration.filter;
      }
      if (this.configuration.format != "") {
        this.formatVal = this.configuration.format;
      }
      if (this.configuration.last_timestamp == "") {
        this.dateVal = "choose_date_time";
      } else {
        const last_timestamp_date = new Date(this.configuration.last_timestamp);
        this.lastTimestampFormatted = this.formatDate(
          last_timestamp_date,
          "Pp"
        );
      }
      this.date = this.formatDate(new Date(), "yyyy-MM-dd");
      this.time = "00:00";
    },
    validateSyslogInput() {
      this.clearErrors(this);
      let isValidationOk = true;
      if (!this.address) {
        this.error.address = this.$t("common.required");
        isValidationOk = false;
      }
      if (!this.port) {
        this.error.port = this.$t("common.required");
        isValidationOk = false;
      }
      if (this.port && isNaN(this.port)) {
        this.error.port = this.$t("system_logs.loki.valid_number");
        isValidationOk = false;
      }
      if (this.port && this.port <= 0) {
        this.error.port = this.$t("system_logs.loki.greater_than_0");
        isValidationOk = false;
      }
      return isValidationOk;
    },
    async setSyslog() {
      if (this.toggleEnabled && !this.validateSyslogInput()) {
        return;
      }
      this.loading.setSyslog = true;
      this.error.setSyslog = "";
      const taskAction = "set-syslog-forwarder";
      this.$root.$once(taskAction + "-aborted", this.setSyslogAborted);
      this.$root.$once(taskAction + "-completed", this.setSyslogCompleted);
      if (this.dateVal == "choose_date_time") {
        this.start_time = new Date("".concat(this.date, " ", this.time));
      } else {
        this.start_time = "";
      }
      if (this.toggleEnabled) {
        this.active = true;
      } else {
        this.active = false;
      }
      const res = await to(
        this.createModuleTaskForApp(this.lokiToEdit.instance_id, {
          action: taskAction,
          data: {
            active: this.active,
            address: this.address,
            port: this.port,
            protocol: this.protocolVal,
            filter: this.filterVal,
            format: this.formatVal,
            start_time: this.start_time,
          },
          extra: {
            title: this.$t("action." + taskAction),
            description: this.$t("common.processing"),
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.setSyslog = this.getErrorMessage(err);
        return;
      }
    },
    setSyslogAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.setSyslog = this.$t("error.generic_error");
      this.loading.setSyslog = false;
    },
    setSyslogCompleted() {
      this.loading.setSyslog = false;
      this.onModalHidden();
      this.$emit("configure");
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
.interval-date {
  display: inline-flex;
  margin-right: $spacing-06;
}
.interval-time {
  display: inline-flex;
}
</style>
</file>

<file path="core/ui/src/components/settings/TlsCertificatesPanel.vue">
<template>
  <div>
    <cv-tile light>
      <div v-if="offlineTraefikInstances.length">
        <NsInlineNotification
          v-for="instance in offlineTraefikInstances"
          :key="instance.id"
          kind="error"
          :title="
            $t('settings_tls_certificates.node_is_offline', {
              node: getNodeLabel(instance),
            })
          "
          :description="getOfflineInstanceDescription(instance)"
          :showCloseButton="false"
        />
      </div>
      <div v-if="listCertificatesErrors.length">
        <NsInlineNotification
          v-for="(error, index) in listCertificatesErrors"
          :key="index"
          kind="error"
          :title="error.title"
          :description="error.description"
          :showCloseButton="false"
        />
      </div>
      <div class="toolbar gap-2 flex-wrap" v-if="certificates.length">
        <NsButton
          v-if="nodesWithoutCertificate.length"
          kind="primary"
          :icon="Add20"
          :disabled="loadingCertificates"
          @click="showRequestCertificateModal"
          >{{ $t("settings_tls_certificates.request_certificate") }}
        </NsButton>
        <cv-tooltip
          v-else
          alignment="center"
          direction="top"
          :tip="
            $t('settings_tls_certificates.request_certificate_disabled_message')
          "
        >
          <NsButton
            kind="primary"
            :icon="Add20"
            disabled
            @click="showRequestCertificateModal"
            >{{ $t("settings_tls_certificates.request_certificate") }}
          </NsButton>
        </cv-tooltip>
        <NsButton
          kind="secondary"
          :icon="Upload20"
          @click="uploadTlsCertificateState.setVisible(true)"
          >{{ $t("settings_tls_certificates.add_custom_certificate") }}
        </NsButton>
        <NsButton
          kind="tertiary"
          :icon="TrashCan20"
          @click="showDeleteObsoleteCertificatesModal"
          :disabled="!nodesWithObsoleteCertificates.length"
          >{{ $t("settings_tls_certificates.delete_obsolete_certificates") }}
        </NsButton>
      </div>
      <div>
        <div>
          <div class="data-table-filters">
            <cv-search
              :label="$t('common.search')"
              :placeholder="$t('settings_tls_certificates.filter_certificates')"
              :clear-aria-label="$t('common.clear_search')"
              v-model="filter.text"
              :disabled="loadingCertificates"
              size="large"
              ref="tableSearch"
              class="self-end"
              @input="onSearchInput"
            >
            </cv-search>
            <NsComboBox
              v-model="filter.certificateType"
              :label="$t('common.choose')"
              :title="$t('settings_tls_certificates.ui_type')"
              :auto-filter="true"
              :auto-highlight="true"
              :options="typeOptions"
              :disabled="loadingCertificates"
            >
            </NsComboBox>
            <NsComboBox
              v-model="filter.certificateStatus"
              :label="$t('common.choose')"
              :title="$t('settings_tls_certificates.status')"
              :auto-filter="true"
              :auto-highlight="true"
              :options="statusOptions"
              :disabled="loadingCertificates"
            >
            </NsComboBox>
            <NsComboBox
              :value="selectedNodeId"
              @change="$emit('update:selectedNodeId', $event)"
              :label="$t('common.choose')"
              :title="$t('common.node')"
              :auto-filter="true"
              :auto-highlight="true"
              :options="nodesForFilter"
              :disabled="loadingCertificates"
            >
            </NsComboBox>
            <cv-link @click="clearFilters()" class="self-end mb-3 shrink-0"
              >{{ $t("common.clear_filters") }}
            </cv-link>
          </div>
          <NsDataTable
            :allRows="filteredCertificates"
            :columns="i18nTableColumns"
            :rawColumns="tableColumns"
            :sortable="true"
            :pageSizes="[10, 25, 50, 100]"
            :overflow-menu="true"
            :isSearchable="false"
            :noSearchResultsLabel="$t('common.no_search_results')"
            :noSearchResultsDescription="
              $t('common.no_search_results_description')
            "
            :isLoading="loadingCertificates"
            :skeletonRows="5"
            :isErrorShown="!!instancesError"
            :errorTitle="$t('action.list-installed-modules')"
            :errorDescription="instancesError"
            :itemsPerPageLabel="$t('pagination.items_per_page')"
            :rangeOfTotalItemsLabel="$t('pagination.range_of_total_items')"
            :ofTotalPagesLabel="$t('pagination.of_total_pages')"
            :backwardText="$t('pagination.previous_page')"
            :forwardText="$t('pagination.next_page')"
            :pageNumberLabel="$t('pagination.page_number')"
            ref="certificatesTable"
            @updatePage="tablePage = $event"
          >
            <template slot="empty-state">
              <template v-if="hasActiveFilters && certificates.length">
                <NsEmptyState
                  :title="$t('common.no_search_results')"
                  key="no-results-empty-state"
                >
                  <template #description>
                    <div class="flex flex-col items-center text-center gap-2">
                      <p>
                        {{ $t("common.no_search_results_description") }}
                      </p>
                      <NsButton
                        kind="ghost"
                        size="field"
                        @click="clearFilters()"
                        >{{ $t("common.clear_filters") }}
                      </NsButton>
                    </div>
                  </template>
                </NsEmptyState>
              </template>
              <template v-else>
                <NsEmptyState
                  :title="$t('settings_tls_certificates.no_tls_certificate')"
                  key="no-certificates-empty-state"
                >
                  <template #pictogram>
                    <DocumentSecurityPictogram />
                  </template>
                  <template #description>
                    <div class="flex flex-col items-center gap-4">
                      <p>
                        {{
                          $t(
                            "settings_tls_certificates.no_tls_certificate_description"
                          )
                        }}
                      </p>
                      <div class="flex flex-col items-center gap-2">
                        <NsButton
                          v-if="nodesWithoutCertificate.length"
                          kind="primary"
                          :icon="Add20"
                          :disabled="loadingCertificates"
                          @click="showRequestCertificateModal"
                          >{{
                            $t("settings_tls_certificates.request_certificate")
                          }}
                        </NsButton>
                        <NsButton
                          kind="ghost"
                          :icon="Upload20"
                          @click="uploadTlsCertificateState.setVisible(true)"
                          >{{
                            $t(
                              "settings_tls_certificates.add_custom_certificate"
                            )
                          }}
                        </NsButton>
                      </div>
                    </div>
                  </template>
                </NsEmptyState>
              </template>
            </template>
            <template slot="data">
              <cv-data-table-row
                v-for="(row, rowIndex) in tablePage"
                :key="`${rowIndex}`"
                :value="`${rowIndex}`"
              >
                <cv-data-table-cell>
                  <span>
                    {{ row.ui_name }}
                  </span>
                </cv-data-table-cell>
                <cv-data-table-cell>
                  <cv-interactive-tooltip
                    v-if="row.ui_type === 'obsolete'"
                    alignment="start"
                    direction="right"
                    class="info clickable-tag"
                  >
                    <template #trigger>
                      <cv-tag
                        kind="high-contrast"
                        :label="$t('settings_tls_certificates.obsolete')"
                        class="no-margin"
                      ></cv-tag>
                    </template>
                    <template #content>
                      {{ $t("settings_tls_certificates.obsolete_tooltip") }}
                    </template>
                  </cv-interactive-tooltip>
                  <cv-tag
                    v-else-if="row.ui_type === 'automatic'"
                    kind="gray"
                    :label="$t('settings_tls_certificates.automatic')"
                    class="no-margin"
                  ></cv-tag>
                  <span v-else>
                    {{ $t("settings_tls_certificates." + row.ui_type) }}
                  </span>
                </cv-data-table-cell>
                <cv-data-table-cell>
                  <cv-interactive-tooltip
                    v-if="row.ui_issuer !== row.issuer"
                    alignment="center"
                    direction="top"
                    class="info"
                  >
                    <template #trigger>
                      <cv-link>{{ row.ui_issuer }}</cv-link>
                    </template>
                    <template #content>
                      {{ row.issuer }}
                    </template>
                  </cv-interactive-tooltip>
                  <span v-else>
                    {{ row.issuer }}
                  </span>
                </cv-data-table-cell>
                <cv-data-table-cell>
                  <div class="flex items-center gap-2">
                    <span>
                      {{ row.expiration }}
                    </span>
                    <cv-interactive-tooltip
                      v-if="row.status === 'expiring'"
                      alignment="center"
                      direction="top"
                      class="shrink-0"
                    >
                      <template #trigger>
                        <WarningAltFilled16 class="ns-warning" />
                      </template>
                      <template #content>
                        {{ $t("settings_tls_certificates.expiring_warning") }}
                      </template>
                    </cv-interactive-tooltip>
                  </div>
                </cv-data-table-cell>
                <cv-data-table-cell>
                  <cv-tag
                    :kind="getTagKind(row.status)"
                    :label="
                      row.status === 'expiring'
                        ? $t('settings_tls_certificates.valid')
                        : $t('settings_tls_certificates.' + row.status)
                    "
                    class="no-margin"
                  >
                  </cv-tag>
                </cv-data-table-cell>
                <cv-data-table-cell>
                  <template v-if="row.names.length > 3">
                    <div v-for="name in row.names.slice(0, 3)" :key="name">
                      {{ name }}
                    </div>
                    <cv-interactive-tooltip
                      alignment="center"
                      direction="top"
                      class="info"
                    >
                      <template #trigger>
                        <cv-link>
                          {{
                            $tc("common.plus_others", row.names.length - 3, {
                              num: row.names.length - 3,
                            })
                          }}
                        </cv-link>
                      </template>
                      <template #content>
                        <ul class="unordered-list">
                          <li v-for="name in row.names" :key="name">
                            {{ name }}
                          </li>
                        </ul>
                      </template>
                    </cv-interactive-tooltip>
                  </template>
                  <template v-else>
                    <div v-for="name in row.names" :key="name">
                      {{ name }}
                    </div>
                  </template>
                </cv-data-table-cell>
                <cv-data-table-cell>
                  <span>{{ row.node }}</span>
                </cv-data-table-cell>
                <cv-data-table-cell class="table-overflow-menu-cell">
                  <cv-overflow-menu
                    flip-menu
                    class="table-overflow-menu"
                    :data-test-id="row.name + '-menu'"
                  >
                    <cv-overflow-menu-item
                      v-if="row.default && row.type === 'internal'"
                      @click="showManageNamesModal(row)"
                    >
                      <NsMenuItem
                        :icon="Edit20"
                        :label="$t('settings_tls_certificates.manage_names')"
                      />
                    </cv-overflow-menu-item>
                    <cv-overflow-menu-item
                      danger
                      @click="showDeleteCertificateModal(row)"
                    >
                      <NsMenuItem
                        :icon="TrashCan20"
                        :label="$t('common.delete')"
                      />
                    </cv-overflow-menu-item>
                  </cv-overflow-menu>
                </cv-data-table-cell>
              </cv-data-table-row>
            </template>
          </NsDataTable>
        </div>
      </div>
    </cv-tile>
    <UploadTlsCertificateModal
      :state="uploadTlsCertificateState"
      @upload-certificate-submit="uploadCustomCertificate($event)"
      ref="uploadTlsCertificateModal"
    />
    <RequestTlsCertificateModal
      :isShown="isShownRequestCertificateModal"
      :nodes="nodesWithoutCertificate"
      :allCertificates="certificates"
      :certificate="currentCertificate"
      @hide="hideRequestCertificateModal"
    />
    <NsDangerDeleteModal
      :isShown="isShownDeleteCertificateModal"
      :name="currentCertificate ? currentCertificate.ui_name : ''"
      :title="$t('settings_tls_certificates.delete_certificate')"
      :deleteLabel="$t('common.delete')"
      :description="
        $t('settings_tls_certificates.delete_certificate_description', {
          name: currentCertificate ? currentCertificate.ui_name : '',
        })
      "
      :typeToConfirm="
        $t('common.type_to_confirm', {
          name: currentCertificate ? currentCertificate.ui_name : '',
        })
      "
      :isErrorShown="!!error.deleteCertificate"
      :errorTitle="$t('action.delete-certificate')"
      :errorDescription="error.deleteCertificate"
      :isWarningShown="false"
      @hide="hideDeleteCertificateModal"
      @confirmDelete="deleteCertificate"
    >
      <template slot="explanation">
        <p
          v-if="currentCertificate && currentCertificate.automatic"
          class="mg-top-sm"
        >
          {{ $t("settings_tls_certificates.automatic_cert_warning") }}
        </p>
        <NsInlineNotification
          v-if="
            currentCertificate &&
            ['internal', 'custom'].includes(currentCertificate.type)
          "
          kind="warning"
          :title="$t('settings_tls_certificates.traefik_will_be_restarted')"
          :description="
            $t('settings_tls_certificates.delete_certificate_message', {
              node: currentCertificate.node,
            })
          "
          :showCloseButton="false"
        />
      </template>
    </NsDangerDeleteModal>
    <DeleteObsoleteCertificatesModal
      :isShown="isShownDeleteObsoleteCertificatesModal"
      :nodes="nodesWithObsoleteCertificates"
      @hide="hideDeleteObsoleteCertificatesModal"
    />
  </div>
</template>
⋮----
>{{ $t("settings_tls_certificates.request_certificate") }}
⋮----
>{{ $t("settings_tls_certificates.request_certificate") }}
⋮----
>{{ $t("settings_tls_certificates.add_custom_certificate") }}
⋮----
>{{ $t("settings_tls_certificates.delete_obsolete_certificates") }}
⋮----
>{{ $t("common.clear_filters") }}
⋮----
<template slot="empty-state">
              <template v-if="hasActiveFilters && certificates.length">
                <NsEmptyState
                  :title="$t('common.no_search_results')"
                  key="no-results-empty-state"
                >
                  <template #description>
                    <div class="flex flex-col items-center text-center gap-2">
                      <p>
                        {{ $t("common.no_search_results_description") }}
                      </p>
                      <NsButton
                        kind="ghost"
                        size="field"
                        @click="clearFilters()"
                        >{{ $t("common.clear_filters") }}
                      </NsButton>
                    </div>
                  </template>
                </NsEmptyState>
              </template>
              <template v-else>
                <NsEmptyState
                  :title="$t('settings_tls_certificates.no_tls_certificate')"
                  key="no-certificates-empty-state"
                >
                  <template #pictogram>
                    <DocumentSecurityPictogram />
                  </template>
                  <template #description>
                    <div class="flex flex-col items-center gap-4">
                      <p>
                        {{
                          $t(
                            "settings_tls_certificates.no_tls_certificate_description"
                          )
                        }}
                      </p>
                      <div class="flex flex-col items-center gap-2">
                        <NsButton
                          v-if="nodesWithoutCertificate.length"
                          kind="primary"
                          :icon="Add20"
                          :disabled="loadingCertificates"
                          @click="showRequestCertificateModal"
                          >{{
                            $t("settings_tls_certificates.request_certificate")
                          }}
                        </NsButton>
                        <NsButton
                          kind="ghost"
                          :icon="Upload20"
                          @click="uploadTlsCertificateState.setVisible(true)"
                          >{{
                            $t(
                              "settings_tls_certificates.add_custom_certificate"
                            )
                          }}
                        </NsButton>
                      </div>
                    </div>
                  </template>
                </NsEmptyState>
              </template>
            </template>
⋮----
<template v-if="hasActiveFilters && certificates.length">
                <NsEmptyState
                  :title="$t('common.no_search_results')"
                  key="no-results-empty-state"
                >
                  <template #description>
                    <div class="flex flex-col items-center text-center gap-2">
                      <p>
                        {{ $t("common.no_search_results_description") }}
                      </p>
                      <NsButton
                        kind="ghost"
                        size="field"
                        @click="clearFilters()"
                        >{{ $t("common.clear_filters") }}
                      </NsButton>
                    </div>
                  </template>
                </NsEmptyState>
              </template>
⋮----
<template #description>
                    <div class="flex flex-col items-center text-center gap-2">
                      <p>
                        {{ $t("common.no_search_results_description") }}
                      </p>
                      <NsButton
                        kind="ghost"
                        size="field"
                        @click="clearFilters()"
                        >{{ $t("common.clear_filters") }}
                      </NsButton>
                    </div>
                  </template>
⋮----
{{ $t("common.no_search_results_description") }}
⋮----
>{{ $t("common.clear_filters") }}
⋮----
<template v-else>
                <NsEmptyState
                  :title="$t('settings_tls_certificates.no_tls_certificate')"
                  key="no-certificates-empty-state"
                >
                  <template #pictogram>
                    <DocumentSecurityPictogram />
                  </template>
                  <template #description>
                    <div class="flex flex-col items-center gap-4">
                      <p>
                        {{
                          $t(
                            "settings_tls_certificates.no_tls_certificate_description"
                          )
                        }}
                      </p>
                      <div class="flex flex-col items-center gap-2">
                        <NsButton
                          v-if="nodesWithoutCertificate.length"
                          kind="primary"
                          :icon="Add20"
                          :disabled="loadingCertificates"
                          @click="showRequestCertificateModal"
                          >{{
                            $t("settings_tls_certificates.request_certificate")
                          }}
                        </NsButton>
                        <NsButton
                          kind="ghost"
                          :icon="Upload20"
                          @click="uploadTlsCertificateState.setVisible(true)"
                          >{{
                            $t(
                              "settings_tls_certificates.add_custom_certificate"
                            )
                          }}
                        </NsButton>
                      </div>
                    </div>
                  </template>
                </NsEmptyState>
              </template>
⋮----
<template #pictogram>
                    <DocumentSecurityPictogram />
                  </template>
<template #description>
                    <div class="flex flex-col items-center gap-4">
                      <p>
                        {{
                          $t(
                            "settings_tls_certificates.no_tls_certificate_description"
                          )
                        }}
                      </p>
                      <div class="flex flex-col items-center gap-2">
                        <NsButton
                          v-if="nodesWithoutCertificate.length"
                          kind="primary"
                          :icon="Add20"
                          :disabled="loadingCertificates"
                          @click="showRequestCertificateModal"
                          >{{
                            $t("settings_tls_certificates.request_certificate")
                          }}
                        </NsButton>
                        <NsButton
                          kind="ghost"
                          :icon="Upload20"
                          @click="uploadTlsCertificateState.setVisible(true)"
                          >{{
                            $t(
                              "settings_tls_certificates.add_custom_certificate"
                            )
                          }}
                        </NsButton>
                      </div>
                    </div>
                  </template>
⋮----
{{
                          $t(
                            "settings_tls_certificates.no_tls_certificate_description"
                          )
                        }}
⋮----
>{{
                            $t("settings_tls_certificates.request_certificate")
                          }}
⋮----
>{{
                            $t(
                              "settings_tls_certificates.add_custom_certificate"
                            )
                          }}
⋮----
<template slot="data">
              <cv-data-table-row
                v-for="(row, rowIndex) in tablePage"
                :key="`${rowIndex}`"
                :value="`${rowIndex}`"
              >
                <cv-data-table-cell>
                  <span>
                    {{ row.ui_name }}
                  </span>
                </cv-data-table-cell>
                <cv-data-table-cell>
                  <cv-interactive-tooltip
                    v-if="row.ui_type === 'obsolete'"
                    alignment="start"
                    direction="right"
                    class="info clickable-tag"
                  >
                    <template #trigger>
                      <cv-tag
                        kind="high-contrast"
                        :label="$t('settings_tls_certificates.obsolete')"
                        class="no-margin"
                      ></cv-tag>
                    </template>
                    <template #content>
                      {{ $t("settings_tls_certificates.obsolete_tooltip") }}
                    </template>
                  </cv-interactive-tooltip>
                  <cv-tag
                    v-else-if="row.ui_type === 'automatic'"
                    kind="gray"
                    :label="$t('settings_tls_certificates.automatic')"
                    class="no-margin"
                  ></cv-tag>
                  <span v-else>
                    {{ $t("settings_tls_certificates." + row.ui_type) }}
                  </span>
                </cv-data-table-cell>
                <cv-data-table-cell>
                  <cv-interactive-tooltip
                    v-if="row.ui_issuer !== row.issuer"
                    alignment="center"
                    direction="top"
                    class="info"
                  >
                    <template #trigger>
                      <cv-link>{{ row.ui_issuer }}</cv-link>
                    </template>
                    <template #content>
                      {{ row.issuer }}
                    </template>
                  </cv-interactive-tooltip>
                  <span v-else>
                    {{ row.issuer }}
                  </span>
                </cv-data-table-cell>
                <cv-data-table-cell>
                  <div class="flex items-center gap-2">
                    <span>
                      {{ row.expiration }}
                    </span>
                    <cv-interactive-tooltip
                      v-if="row.status === 'expiring'"
                      alignment="center"
                      direction="top"
                      class="shrink-0"
                    >
                      <template #trigger>
                        <WarningAltFilled16 class="ns-warning" />
                      </template>
                      <template #content>
                        {{ $t("settings_tls_certificates.expiring_warning") }}
                      </template>
                    </cv-interactive-tooltip>
                  </div>
                </cv-data-table-cell>
                <cv-data-table-cell>
                  <cv-tag
                    :kind="getTagKind(row.status)"
                    :label="
                      row.status === 'expiring'
                        ? $t('settings_tls_certificates.valid')
                        : $t('settings_tls_certificates.' + row.status)
                    "
                    class="no-margin"
                  >
                  </cv-tag>
                </cv-data-table-cell>
                <cv-data-table-cell>
                  <template v-if="row.names.length > 3">
                    <div v-for="name in row.names.slice(0, 3)" :key="name">
                      {{ name }}
                    </div>
                    <cv-interactive-tooltip
                      alignment="center"
                      direction="top"
                      class="info"
                    >
                      <template #trigger>
                        <cv-link>
                          {{
                            $tc("common.plus_others", row.names.length - 3, {
                              num: row.names.length - 3,
                            })
                          }}
                        </cv-link>
                      </template>
                      <template #content>
                        <ul class="unordered-list">
                          <li v-for="name in row.names" :key="name">
                            {{ name }}
                          </li>
                        </ul>
                      </template>
                    </cv-interactive-tooltip>
                  </template>
                  <template v-else>
                    <div v-for="name in row.names" :key="name">
                      {{ name }}
                    </div>
                  </template>
                </cv-data-table-cell>
                <cv-data-table-cell>
                  <span>{{ row.node }}</span>
                </cv-data-table-cell>
                <cv-data-table-cell class="table-overflow-menu-cell">
                  <cv-overflow-menu
                    flip-menu
                    class="table-overflow-menu"
                    :data-test-id="row.name + '-menu'"
                  >
                    <cv-overflow-menu-item
                      v-if="row.default && row.type === 'internal'"
                      @click="showManageNamesModal(row)"
                    >
                      <NsMenuItem
                        :icon="Edit20"
                        :label="$t('settings_tls_certificates.manage_names')"
                      />
                    </cv-overflow-menu-item>
                    <cv-overflow-menu-item
                      danger
                      @click="showDeleteCertificateModal(row)"
                    >
                      <NsMenuItem
                        :icon="TrashCan20"
                        :label="$t('common.delete')"
                      />
                    </cv-overflow-menu-item>
                  </cv-overflow-menu>
                </cv-data-table-cell>
              </cv-data-table-row>
            </template>
⋮----
{{ row.ui_name }}
⋮----
<template #trigger>
                      <cv-tag
                        kind="high-contrast"
                        :label="$t('settings_tls_certificates.obsolete')"
                        class="no-margin"
                      ></cv-tag>
                    </template>
<template #content>
                      {{ $t("settings_tls_certificates.obsolete_tooltip") }}
                    </template>
⋮----
{{ $t("settings_tls_certificates.obsolete_tooltip") }}
⋮----
{{ $t("settings_tls_certificates." + row.ui_type) }}
⋮----
<template #trigger>
                      <cv-link>{{ row.ui_issuer }}</cv-link>
                    </template>
⋮----
<cv-link>{{ row.ui_issuer }}</cv-link>
⋮----
<template #content>
                      {{ row.issuer }}
                    </template>
⋮----
{{ row.issuer }}
⋮----
{{ row.issuer }}
⋮----
{{ row.expiration }}
⋮----
<template #trigger>
                        <WarningAltFilled16 class="ns-warning" />
                      </template>
<template #content>
                        {{ $t("settings_tls_certificates.expiring_warning") }}
                      </template>
⋮----
{{ $t("settings_tls_certificates.expiring_warning") }}
⋮----
<template v-if="row.names.length > 3">
                    <div v-for="name in row.names.slice(0, 3)" :key="name">
                      {{ name }}
                    </div>
                    <cv-interactive-tooltip
                      alignment="center"
                      direction="top"
                      class="info"
                    >
                      <template #trigger>
                        <cv-link>
                          {{
                            $tc("common.plus_others", row.names.length - 3, {
                              num: row.names.length - 3,
                            })
                          }}
                        </cv-link>
                      </template>
                      <template #content>
                        <ul class="unordered-list">
                          <li v-for="name in row.names" :key="name">
                            {{ name }}
                          </li>
                        </ul>
                      </template>
                    </cv-interactive-tooltip>
                  </template>
⋮----
{{ name }}
⋮----
<template #trigger>
                        <cv-link>
                          {{
                            $tc("common.plus_others", row.names.length - 3, {
                              num: row.names.length - 3,
                            })
                          }}
                        </cv-link>
                      </template>
⋮----
{{
                            $tc("common.plus_others", row.names.length - 3, {
                              num: row.names.length - 3,
                            })
                          }}
⋮----
<template #content>
                        <ul class="unordered-list">
                          <li v-for="name in row.names" :key="name">
                            {{ name }}
                          </li>
                        </ul>
                      </template>
⋮----
{{ name }}
⋮----
<template v-else>
                    <div v-for="name in row.names" :key="name">
                      {{ name }}
                    </div>
                  </template>
⋮----
{{ name }}
⋮----
<span>{{ row.node }}</span>
⋮----
<template slot="explanation">
        <p
          v-if="currentCertificate && currentCertificate.automatic"
          class="mg-top-sm"
        >
          {{ $t("settings_tls_certificates.automatic_cert_warning") }}
        </p>
        <NsInlineNotification
          v-if="
            currentCertificate &&
            ['internal', 'custom'].includes(currentCertificate.type)
          "
          kind="warning"
          :title="$t('settings_tls_certificates.traefik_will_be_restarted')"
          :description="
            $t('settings_tls_certificates.delete_certificate_message', {
              node: currentCertificate.node,
            })
          "
          :showCloseButton="false"
        />
      </template>
⋮----
{{ $t("settings_tls_certificates.automatic_cert_warning") }}
⋮----
<script>
import to from "await-to-js";
import { UtilService, TaskService, IconService } from "@nethserver/ns8-ui-lib";
import _cloneDeep from "lodash/cloneDeep";
import RequestTlsCertificateModal from "@/components/settings/RequestTlsCertificateModal.vue";
import UploadTlsCertificateModal from "@/components/settings/UploadTlsCertificateModal.vue";
import { StateManager as UploadTlsCertificateState } from "@/components/settings/UploadTlsCertificateModal.vue";
import Upload20 from "@carbon/icons-vue/es/upload/20";
import DeleteObsoleteCertificatesModal from "@/components/settings/DeleteObsoleteCertificatesModal.vue";
import WarningAltFilled16 from "@carbon/icons-vue/es/warning--alt--filled/16";
export default {
  name: "TlsCertificatesPanel",
  components: {
    RequestTlsCertificateModal,
    UploadTlsCertificateModal,
    DeleteObsoleteCertificatesModal,
    WarningAltFilled16,
  },
  mixins: [TaskService, UtilService, IconService],
  props: {
    traefikInstances: Array,
    internalNodes: Array,
    isLoadingInstances: Boolean,
    instancesError: {
      type: String,
      default: "",
    },
    // owned by the parent: bound to a query param
    selectedNodeId: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      tablePage: [],
      tableColumns: [
        "ui_name",
        "ui_type",
        "ui_issuer",
        "valid_to",
        "status",
        "names",
        "node",
      ],
      certificatesByTraefikId: {},
      isShownRequestCertificateModal: false,
      isShownDeleteCertificateModal: false,
      isShownDeleteObsoleteCertificatesModal: false,
      currentCertificate: null,
      taskListeners: [],
      filter: {
        text: "",
        certificateType: "",
        certificateStatus: "",
      },
      typeOptions: [
        {
          name: "any",
          label: this.$t("settings_tls_certificates.any_type"),
          value: "any",
        },
        {
          name: "requested",
          label: this.$t("settings_tls_certificates.requested"),
          value: "requested",
        },
        {
          name: "uploaded",
          label: this.$t("settings_tls_certificates.uploaded"),
          value: "uploaded",
        },
        {
          name: "automatic",
          label: this.$t("settings_tls_certificates.automatic"),
          value: "automatic",
        },
        {
          name: "obsolete",
          label: this.$t("settings_tls_certificates.obsolete"),
          value: "obsolete",
        },
      ],
      statusOptions: [
        {
          name: "any",
          label: this.$t("settings_tls_certificates.any_status"),
          value: "any",
        },
        {
          name: "valid",
          label: this.$t("settings_tls_certificates.valid"),
          value: "valid",
        },
        {
          name: "expiring",
          label: this.$t("settings_tls_certificates.expiring"),
          value: "expiring",
        },
        {
          name: "expired",
          label: this.$t("settings_tls_certificates.expired"),
          value: "expired",
        },
      ],
      Upload20,
      loading: {
        listCertificatesNum: 0,
        deleteCertificate: false,
      },
      error: {
        deleteCertificate: "",
      },
      listCertificatesErrors: [],
      offlineTraefikInstances: [],
      uploadTlsCertificateState: new UploadTlsCertificateState(),
    };
  },
  computed: {
    i18nTableColumns() {
      return this.tableColumns.map((column) => {
        return this.$t("settings_tls_certificates." + column);
      });
    },
    loadingCertificates() {
      return this.isLoadingInstances || this.loading.listCertificatesNum > 0;
    },
    filteredCertificates() {
      let certificates = this.certificates;
      // filter by node
      if (this.selectedNodeId && this.selectedNodeId !== "any") {
        certificates = certificates.filter((certificate) => {
          return certificate.nodeId === this.selectedNodeId;
        });
      }
      if (this.filter.text.trim()) {
        const searchText = this.filter.text.toLowerCase().trim();
        certificates = certificates.filter((cert) => {
          return (
            cert.ui_name.toLowerCase().includes(searchText) ||
            cert.ui_type.toLowerCase().includes(searchText) ||
            cert.ui_issuer.toLowerCase().includes(searchText) ||
            cert.expiration.toLowerCase().includes(searchText) ||
            cert.status.toLowerCase().includes(searchText) ||
            cert.serial.toLowerCase().includes(searchText) ||
            cert.names.some((name) =>
              name.toLowerCase().includes(searchText)
            ) ||
            cert.node.toLowerCase().includes(searchText)
          );
        });
      }
      if (
        this.filter.certificateType &&
        this.filter.certificateType !== "any"
      ) {
        certificates = certificates.filter((certificate) => {
          return certificate.ui_type === this.filter.certificateType;
        });
      }
      if (
        this.filter.certificateStatus &&
        this.filter.certificateStatus !== "any"
      ) {
        certificates = certificates.filter((certificate) => {
          return certificate.status === this.filter.certificateStatus;
        });
      }
      return certificates;
    },
    nodesForFilter() {
      if (!this.internalNodes.length) {
        return [];
      }
      const nodes = _cloneDeep(this.internalNodes);
      nodes.unshift({
        name: "any",
        label: this.$t("common.any_node"),
        value: "any",
      });
      return nodes;
    },
    certificates() {
      return Object.values(this.certificatesByTraefikId)
        .flat()
        .sort(this.sortCertificates);
    },
    nodesWithoutCertificate() {
      const nodesWithDefaultCert = [
        ...new Set(
          this.certificates
            .filter((cert) => cert.default && cert.type === "internal")
            .map((cert) => cert.nodeId)
        ),
      ];
      return this.internalNodes.filter(
        (node) => !nodesWithDefaultCert.includes(node.value)
      );
    },
    nodesWithObsoleteCertificates() {
      const nodesWithObsoleteCert = [
        ...new Set(
          this.certificates
            .filter((cert) => cert.ui_type === "obsolete")
            .map((cert) => cert.nodeId)
        ),
      ];
      return this.internalNodes.filter((node) =>
        nodesWithObsoleteCert.includes(node.value)
      );
    },
    hasActiveFilters() {
      return (
        (this.filter.text && this.filter.text.trim() !== "") ||
        (this.filter.certificateType &&
          this.filter.certificateType !== "any") ||
        (this.filter.certificateStatus &&
          this.filter.certificateStatus !== "any") ||
        (this.selectedNodeId && this.selectedNodeId !== "any")
      );
    },
  },
  watch: {
    traefikInstances: function () {
      this.listCertificates();
    },
    internalNodes: function (nodes) {
      this.uploadTlsCertificateState.setNodes(nodes);
    },
    instancesError: function (error) {
      if (error) {
        this.loading.listCertificatesNum = 0;
      }
    },
  },
  created() {
    this.$root.$on("reloadCertificates", this.onReloadCertificates);
    this.$nextTick(() => {
      this.filter.certificateType = "any";
      this.filter.certificateStatus = "any";
    });
  },
  beforeDestroy() {
    this.$root.$off("reloadCertificates");
    this.clearTaskListeners();
  },
  methods: {
    registerTaskListener(eventName, handler) {
      this.$root.$once(eventName, handler);
      this.taskListeners.push([eventName, handler]);
    },
    clearTaskListeners() {
      this.taskListeners.forEach(([eventName, handler]) => {
        this.$root.$off(eventName, handler);
      });
      this.taskListeners = [];
    },
    showRequestCertificateModal() {
      this.currentCertificate = null;
      this.isShownRequestCertificateModal = true;
    },
    hideRequestCertificateModal() {
      this.isShownRequestCertificateModal = false;
    },
    showManageNamesModal(certificate) {
      this.currentCertificate = certificate;
      this.isShownRequestCertificateModal = true;
    },
    showDeleteCertificateModal(certificate) {
      this.currentCertificate = certificate;
      this.isShownDeleteCertificateModal = true;
    },
    hideDeleteCertificateModal() {
      this.isShownDeleteCertificateModal = false;
    },
    showDeleteObsoleteCertificatesModal() {
      this.isShownDeleteObsoleteCertificatesModal = true;
    },
    hideDeleteObsoleteCertificatesModal() {
      this.isShownDeleteObsoleteCertificatesModal = false;
    },
    async listCertificates() {
      this.clearTaskListeners();
      this.offlineTraefikInstances = [];
      this.listCertificatesErrors = [];
      this.loading.listCertificatesNum = this.traefikInstances.length;
      for (const traefikInstance of this.traefikInstances) {
        const taskAction = "list-certificates";
        const eventId = this.getUuid();
        this.registerTaskListener(
          `${taskAction}-aborted-${eventId}`,
          (taskResult, taskContext) => {
            this.listCertificatesAborted(
              taskResult,
              taskContext,
              traefikInstance
            );
          }
        );
        this.registerTaskListener(
          `${taskAction}-completed-${eventId}`,
          this.listCertificatesCompleted
        );
        const res = await to(
          this.createModuleTaskForApp(traefikInstance.id, {
            action: taskAction,
            data: {
              expand_list: true,
            },
            extra: {
              title: this.$t("action." + taskAction),
              isNotificationHidden: true,
              traefikInstance: traefikInstance,
              eventId,
            },
          })
        );
        const err = res[0];
        if (err) {
          console.error(
            `error creating task ${taskAction} for instance ${traefikInstance.id} on node ${traefikInstance.node}`,
            err
          );
          this.$root.$off(`${taskAction}-aborted-${eventId}`);
          this.$root.$off(`${taskAction}-completed-${eventId}`);
          if (err.response && err.response.status === 404) {
            if (
              traefikInstance &&
              !this.offlineTraefikInstances.find(
                (instance) => instance.id === traefikInstance.id
              )
            ) {
              this.offlineTraefikInstances.push(traefikInstance);
            }
          } else {
            this.listCertificatesErrors.push({
              title: this.$t("action." + taskAction),
              description: `${this.$t(
                "error.generic_error"
              )} (${this.getTraefikInstanceLabel(
                traefikInstance
              )} - ${this.getNodeLabel(traefikInstance)})`,
            });
          }
          this.loading.listCertificatesNum--;
        }
      }
    },
    listCertificatesAborted(taskResult, taskContext, traefikInstance) {
      console.error(
        `${taskContext.action} aborted for instance ${traefikInstance.id} on node ${traefikInstance.node}`,
        taskResult
      );
      this.listCertificatesErrors.push({
        title: this.$t("action." + taskContext.action),
        description: `${this.$t(
          "error.generic_error"
        )} (${this.getTraefikInstanceLabel(
          traefikInstance
        )} - ${this.getNodeLabel(traefikInstance)})`,
      });
      this.loading.listCertificatesNum--;
    },
    listCertificatesCompleted(taskContext, taskResult) {
      const traefikId = taskContext.extra.traefikInstance.id;
      const nodeId = taskContext.extra.traefikInstance.node;
      const nodeUiName = taskContext.extra.traefikInstance.node_ui_name;
      const node = { id: nodeId, ui_name: nodeUiName };
      const nodeLabel = this.getShortNodeLabel(node) + ` (${traefikId})`;
      const certs = [];
      for (let certificate of taskResult.output.certificates) {
        if (certificate.default && certificate.type === "internal") {
          certificate.ui_name = this.$t(
            "settings_tls_certificates.node_name_certificate",
            { node: this.getShortNodeLabel(node) }
          );
        } else {
          certificate.ui_name = certificate.subject;
        }
        let ui_type = "";
        if (certificate.type === "custom") {
          ui_type = "uploaded";
        } else if (certificate.automatic) {
          ui_type = "automatic";
        } else if (certificate.default && certificate.type === "internal") {
          ui_type = "requested";
        } else if (!certificate.default && !certificate.automatic) {
          ui_type = "obsolete";
        }
        certificate.ui_type = ui_type;
        const matched = certificate.issuer.match(/,O=(.+?)(?:,|$)/);
        if (matched && matched.length > 1) {
          certificate.ui_issuer = matched[1];
        } else {
          certificate.ui_issuer = certificate.issuer;
        }
        certificate.status = certificate.validity;
        certificate.node = nodeLabel;
        certificate.nodeId = nodeId;
        certificate.longNodeLabel = this.getNodeLabel(node);
        certificate.traefikInstance = traefikId;
        const validTo = new Date(certificate.valid_to);
        const formattedValidTo = validTo.toLocaleDateString(
          navigator.language,
          {
            year: "numeric",
            month: "long",
            day: "numeric",
          }
        );
        certificate.expiration = formattedValidTo;
        certs.push(certificate);
      }
      this.$set(this.certificatesByTraefikId, traefikId, certs);
      this.loading.listCertificatesNum--;
    },
    getTagKind(status) {
      switch (status) {
        case "valid":
        case "expiring":
          return "green";
        case "expired":
          return "red";
        default:
          return "gray";
      }
    },
    getNodeLabel(instance) {
      const nodeLabel = instance.node_ui_name
        ? instance.node_ui_name +
          " (" +
          this.$t("common.node") +
          " " +
          instance.node +
          ")"
        : this.$t("common.node") + " " + instance.node;
      return nodeLabel;
    },
    getTraefikInstanceLabel(instance) {
      let label = instance.id;
      if (instance.ui_name && instance.ui_name.trim()) {
        label = `${instance.ui_name}(${instance.id})`;
      }
      return label;
    },
    getOfflineInstanceDescription(instance) {
      return this.$t("settings_tls_certificates.certificates_not_displayed", {
        instanceId: this.getTraefikInstanceLabel(instance),
      });
    },
    clearFilters() {
      this.$emit("update:selectedNodeId", "any");
      this.filter.text = "";
      this.filter.certificateType = "any";
      this.filter.certificateStatus = "any";
    },
    onReloadCertificates() {
      this.clearFilters();
      this.listCertificates();
    },
    async deleteCertificate() {
      this.loading.deleteCertificate = true;
      this.error.deleteCertificate = "";
      const taskAction = "delete-certificate";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.deleteCertificateAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.deleteCertificateCompleted
      );
      const payload = {
        type: this.currentCertificate.type,
      };
      if (this.currentCertificate.type === "custom") {
        payload.path = this.currentCertificate.path;
      } else {
        payload.serial = this.currentCertificate.serial;
      }
      const res = await to(
        this.createModuleTaskForApp(this.currentCertificate.traefikInstance, {
          action: taskAction,
          data: payload,
          extra: {
            title: this.$t("settings_tls_certificates.delete_certificate"),
            description: this.$t("common.processing"),
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.deleteCertificate = this.getErrorMessage(err);
        this.loading.deleteCertificate = false;
        return;
      }
      this.hideDeleteCertificateModal();
    },
    deleteCertificateAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.loading.deleteCertificate = false;
    },
    deleteCertificateCompleted() {
      this.loading.deleteCertificate = false;
      this.listCertificates();
    },
    async uploadCustomCertificate(event) {
      this.uploadTlsCertificateState.setLoading(true);
      this.uploadTlsCertificateState.errors.keyFile = null;
      this.uploadTlsCertificateState.errors.certFile = null;
      this.uploadTlsCertificateState.errors.chainFile = null;
      let keyFileDecoded = await new Promise((result) => {
        let keyFileReader = new FileReader();
        keyFileReader.readAsBinaryString(event.keyFile);
        keyFileReader.onerror = () => {
          throw Error();
        };
        keyFileReader.onload = () => {
          result(window.btoa(keyFileReader.result));
        };
      }).catch(() => {
        this.uploadTlsCertificateState.setKeyFileError(
          this.$t("settings_tls_certificates.cannot_load_key_file")
        );
        this.uploadTlsCertificateState.setLoading(false);
      });
      let certFileText = await new Promise((result) => {
        let certFileReader = new FileReader();
        certFileReader.readAsBinaryString(event.certFile);
        certFileReader.onerror = () => {
          throw Error();
        };
        certFileReader.onload = () => {
          result(certFileReader.result);
        };
      }).catch(() => {
        this.uploadTlsCertificateState.setCertFileErrors(
          this.$t("settings_tls_certificates.cannot_load_cert_file")
        );
        this.uploadTlsCertificateState.setLoading(false);
      });
      if (event.chainFile) {
        let chainFileText = await new Promise((result) => {
          let chainFileReader = new FileReader();
          chainFileReader.readAsBinaryString(event.chainFile);
          chainFileReader.onerror = () => {
            throw Error();
          };
          chainFileReader.onload = () => {
            result(chainFileReader.result);
          };
        }).catch(() => {
          this.uploadTlsCertificateState.setCertFileErrors(
            this.$t("settings_tls_certificates.cannot_load_chain_file")
          );
          this.uploadTlsCertificateState.setLoading(false);
        });
        certFileText += `\n${chainFileText}`;
      }
      const certFileDecoded = window.btoa(certFileText);
      const taskAction = "upload-certificate";
      const eventId = this.getUuid();
      this.$root.$once(`${taskAction}-aborted-${eventId}`, (error) => {
        this.uploadTlsCertificateState.setLoading(false);
        switch (error.exit_code) {
          case 2:
          case 3:
            this.uploadTlsCertificateState.setKeyFileError(error.output);
            break;
          case 4:
            this.uploadTlsCertificateState.setCertFileError(error.output);
            break;
          default:
            this.uploadTlsCertificateState.setKeyFileError(error.error);
            break;
        }
      });
      this.$root.$once(`${taskAction}-validation-ok-${eventId}`, () => {
        this.uploadTlsCertificateState.setLoading(false);
        this.uploadTlsCertificateState.setVisible(false);
        this.$refs.uploadTlsCertificateModal.clear();
      });
      this.$root.$once(
        `${taskAction}-validation-failed-${eventId}`,
        (validationErrors) => {
          this.uploadTlsCertificateState.setLoading(false);
          for (const validationError of validationErrors) {
            const param = validationError.parameter;
            const errorMessage = this.getI18nStringWithFallback(
              "settings_tls_certificates." + validationError.error,
              "error." + validationError.error,
              null,
              { value: validationError.value }
            );
            switch (param) {
              case "keyFile":
                this.uploadTlsCertificateState.setKeyFileError(errorMessage);
                break;
              case "certFile":
                this.uploadTlsCertificateState.setCertFileError(errorMessage);
                break;
              case "chainFile":
                this.uploadTlsCertificateState.setChainFileError(errorMessage);
                break;
              default:
                break;
            }
          }
        }
      );
      this.$root.$once(`${taskAction}-completed-${eventId}`, () => {
        this.$refs.uploadTlsCertificateModal.clear();
        this.onReloadCertificates();
      });
      const res = await to(
        this.createModuleTaskForApp(event.targetInstance, {
          action: taskAction,
          data: {
            keyFile: keyFileDecoded,
            certFile: certFileDecoded,
          },
          extra: {
            title: this.$t("settings_tls_certificates.add_custom_certificate"),
            description: this.$t("common.processing"),
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.uploadTlsCertificateState.setKeyFileError(
          this.$t("error.generic_error")
        );
        this.uploadTlsCertificateState.setLoading(false);
      }
    },
    onSearchInput() {
      if (!this.searchFilter) {
        this.$refs.certificatesTable.goToFirstPage();
        this.focusElement("tableSearch");
      }
    },
    sortCertificates(a, b) {
      if (a.ui_type !== b.ui_type) {
        return b.ui_type.localeCompare(a.ui_type);
      }
      return a.valid_to.localeCompare(b.valid_to);
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
.clickable-tag ::v-deep .bx--tag {
  cursor: pointer;
}
</style>
</file>

<file path="core/ui/src/components/settings/UploadTlsCertificateModal.vue">
<template>
  <NsModal
    :visible="state.visible"
    :primaryButtonDisabled="
      state.isLoading() || !areFileSelected || !selectedNodeId
    "
    :isLoading="state.isLoading()"
    @primary-click="uploadCerts()"
    v-on:modal-hide-request="clear()"
    autoHideOff
    hasFormContent
  >
    <template slot="title"
      >{{ $t("settings_tls_certificates.add_custom_certificate") }}
    </template>
    <template slot="content">
      <cv-form @submit.prevent="">
        <p class="mb-6">
          {{
            $t(
              "settings_tls_certificates.upload_custom_certificate_description"
            )
          }}
        </p>
        <NsComboBox
          v-model="selectedNodeId"
          :label="$t('common.choose_a_node')"
          :title="$t('common.node')"
          :auto-filter="true"
          :auto-highlight="true"
          :options="state.nodes"
          light
          ref="node"
        />
        <cv-file-uploader
          :label="$t('settings_tls_certificates.key_upload_label')"
          :multiple="false"
          :removable="true"
          :clear-on-reselect="true"
          :drop-target-label="$t('common.drag_and_drop_or_click_to_upload')"
          v-model="keyFile"
        ></cv-file-uploader>
        <cv-file-uploader
          :label="$t('settings_tls_certificates.cert_upload_label')"
          :multiple="false"
          :removable="true"
          :clear-on-reselect="true"
          :drop-target-label="$t('common.drag_and_drop_or_click_to_upload')"
          v-model="certFile"
        ></cv-file-uploader>
        <cv-file-uploader
          :label="
            $t('settings_tls_certificates.chain_file') +
            ' (' +
            $t('common.optional') +
            ')'
          "
          :multiple="false"
          :removable="true"
          :clear-on-reselect="true"
          :drop-target-label="$t('common.drag_and_drop_or_click_to_upload')"
          v-model="chainFile"
        ></cv-file-uploader>
      </cv-form>
    </template>
    <template slot="primary-button">
      {{ $t("settings_tls_certificates.upload") }}
    </template>
  </NsModal>
</template>
⋮----
<template slot="title"
      >{{ $t("settings_tls_certificates.add_custom_certificate") }}
    </template>
⋮----
>{{ $t("settings_tls_certificates.add_custom_certificate") }}
⋮----
<template slot="content">
      <cv-form @submit.prevent="">
        <p class="mb-6">
          {{
            $t(
              "settings_tls_certificates.upload_custom_certificate_description"
            )
          }}
        </p>
        <NsComboBox
          v-model="selectedNodeId"
          :label="$t('common.choose_a_node')"
          :title="$t('common.node')"
          :auto-filter="true"
          :auto-highlight="true"
          :options="state.nodes"
          light
          ref="node"
        />
        <cv-file-uploader
          :label="$t('settings_tls_certificates.key_upload_label')"
          :multiple="false"
          :removable="true"
          :clear-on-reselect="true"
          :drop-target-label="$t('common.drag_and_drop_or_click_to_upload')"
          v-model="keyFile"
        ></cv-file-uploader>
        <cv-file-uploader
          :label="$t('settings_tls_certificates.cert_upload_label')"
          :multiple="false"
          :removable="true"
          :clear-on-reselect="true"
          :drop-target-label="$t('common.drag_and_drop_or_click_to_upload')"
          v-model="certFile"
        ></cv-file-uploader>
        <cv-file-uploader
          :label="
            $t('settings_tls_certificates.chain_file') +
            ' (' +
            $t('common.optional') +
            ')'
          "
          :multiple="false"
          :removable="true"
          :clear-on-reselect="true"
          :drop-target-label="$t('common.drag_and_drop_or_click_to_upload')"
          v-model="chainFile"
        ></cv-file-uploader>
      </cv-form>
    </template>
⋮----
{{
            $t(
              "settings_tls_certificates.upload_custom_certificate_description"
            )
          }}
⋮----
<template slot="primary-button">
      {{ $t("settings_tls_certificates.upload") }}
    </template>
⋮----
{{ $t("settings_tls_certificates.upload") }}
⋮----
<script>
import { NsModal } from "@nethserver/ns8-ui-lib";
import _isEmpty from "lodash/isEmpty";
export class StateManager {
  constructor() {
    this.visible = false;
    this.loading = false;
    this.errors = {
      keyFile: null,
      certFile: null,
      chainFile: null,
    };
    this.nodes = [];
    this.selectedNodeId = "";
  }
  /**
   * @argument {boolean} isVisible
   */
  setVisible(isVisible) {
    this.visible = isVisible;
  }
  /**
   * @returns {boolean}
   */
  getVisible() {
    return this.visible;
  }
  /**
   * @argument {boolean} isLoading
   */
  setLoading(isLoading) {
    this.loading = isLoading;
  }
  /**
   * @returns {boolean}
   */
  isLoading() {
    return this.loading;
  }
  /**
   * @argument {string} error Error to show in keyFile file picker.
   */
  setKeyFileError(error) {
    this.errors.keyFile = error;
  }
  /**
   * @argument {string} error Error to show in certFile file picker.
   */
  setCertFileError(error) {
    this.errors.certFile = error;
  }
  /**
   * @argument {string} error Error to show in chainFile file picker.
   */
  setChainFileError(error) {
    this.errors.chainFile = error;
  }
  /**
   * @argument {array} instances Array listing the instances of Traefik.
   */
  setNodes(nodes) {
    this.nodes = nodes;
  }
  /**
   * Clear the state of the component.
   */
  clear() {
    this.visible = false;
    this.loading = false;
    this.errors = {
      keyFile: null,
      certFile: null,
      chainFile: null,
    };
  }
}
function initialData() {
  return {
    keyFile: null,
    certFile: null,
    chainFile: null,
    selectedNodeId: "",
  };
}
export default {
  name: "UploadTLSCertificateModal",
  components: { NsModal },
  props: {
    state: {
      type: StateManager,
      required: true,
    },
  },
  data() {
    return initialData();
  },
  methods: {
    uploadCerts() {
      this.$emit("upload-certificate-submit", {
        keyFile: this.keyFile?.[0]?.file ?? null,
        certFile: this.certFile?.[0]?.file ?? null,
        chainFile: this.chainFile?.[0]?.file ?? null,
        targetInstance: this.traefikInstance,
      });
    },
    clear() {
      this.state.clear();
      this.clearNodeSelection();
    },
    clearNodeSelection() {
      this.selectedNodeId = "";
      if (this.$refs.node) {
        this.$refs.node.clearValue();
      }
    },
  },
  computed: {
    areFileSelected: function () {
      return !_isEmpty(this.keyFile) && !_isEmpty(this.certFile);
    },
    traefikInstance: function () {
      const node = this.state.nodes.find((node) => {
        return node.value === this.selectedNodeId;
      });
      if (!node) {
        return null;
      }
      return node.traefikInstance;
    },
  },
  watch: {
    "state.visible": function () {
      Object.assign(this.$data, initialData());
    },
    "state.errors.keyFile": function (val) {
      if (this.keyFile && this.keyFile[0]) {
        this.keyFile[0].invalidMessage = val;
      }
    },
    "state.errors.certFile": function (val) {
      if (this.certFile && this.certFile[0]) {
        this.certFile[0].invalidMessage = val;
      }
    },
    "state.errors.chainFile": function (val) {
      if (this.chainFile && this.chainFile[0]) {
        this.chainFile[0].invalidMessage = val;
      }
    },
  },
};
</script>
</file>

<file path="core/ui/src/components/shell/AppDrawer.vue">
<template>
  <transition name="slide-app-drawer">
    <div
      v-if="isAppDrawerShown"
      v-click-outside="clickOutside"
      :class="['app-drawer', { list: csbListSelected }]"
    >
      <NsInlineNotification
        v-if="error.apps"
        kind="error"
        :title="$t('error.cannot_retrieve_installed_apps')"
        :description="error.apps"
        :showCloseButton="false"
      />
      <div v-else>
        <div v-if="loading.apps" class="loader-large app-drawer-loader"></div>
        <NsEmptyState
          v-else-if="!apps.length"
          :title="$t('app_drawer.no_apps')"
        >
          <template #description>
            <div>{{ $t("app_drawer.no_apps_description") }}</div>
            <NsButton
              kind="ghost"
              :icon="Application20"
              @click="goToSoftwareCenter"
              class="empty-state-button ghost-button-dark-bg"
              >{{ $t("software_center.title") }}</NsButton
            >
          </template>
        </NsEmptyState>
        <template v-else>
          <div class="search-container">
            <cv-search
              :label="$t('app_drawer.search_placeholder')"
              :placeholder="$t('app_drawer.search_placeholder')"
              :clear-aria-label="$t('common.clear_search')"
              v-model.trim="searchQuery"
              v-debounce="searchApp"
              @input="onSearchInput"
              class="app-drawer-search"
              ref="appSearch"
            >
            </cv-search>
            <cv-icon-button
              kind="secondary"
              :icon="Star20"
              :label="$t('app_drawer.edit_favorite_apps')"
              tip-position="bottom"
              tip-alignment="end"
              @click="toggleEditFavorites"
            />
          </div>
          <template v-if="isEditingFavoriteApps">
            <NsButton
              kind="primary"
              :icon="Checkmark20"
              size="field"
              @click="doneEditFavorites"
              class="done-edit-favorites-button"
              >{{ $t("app_drawer.done_edit_favorites") }}</NsButton
            >
            <div class="bx--grid bx--grid--full-width app-grid">
              <div class="bx--row">
                <div class="bx--col">
                  <div class="app-divider no-mg-top">
                    {{ $t("app_drawer.set_favorite_apps") }}
                  </div>
                </div>
              </div>
              <div class="bx--row">
                <div
                  class="bx--col app-cell"
                  v-for="(app, index) in apps"
                  :key="index"
                >
                  <div class="app">
                    <div @click="toggleFavorite(app)">
                      <div class="app-icon">
                        <img
                          :src="
                            app.logo
                              ? app.logo
                              : require('@/assets/module_default_logo.png')
                          "
                          :alt="app.id + ' logo'"
                        />
                      </div>
                      <div>
                        {{ app.ui_name ? app.ui_name : app.id }}
                      </div>
                    </div>
                    <cv-toggle
                      value="favorite"
                      small
                      :checked="app.isFavorite"
                      class="toggle-app-favorite"
                      @click="toggleFavorite(app)"
                    >
                      <template slot="text-left">{{
                        $t("app_drawer.favorite")
                      }}</template>
                      <template slot="text-right">{{
                        $t("app_drawer.favorite")
                      }}</template>
                    </cv-toggle>
                  </div>
                </div>
              </div>
            </div>
          </template>
          <template v-else>
            <cv-content-switcher
              size="sm"
              class="view-switcher"
              @selected="contentSwitcherSelected"
            >
              <cv-content-switcher-button
                owner-id="grid"
                :selected="csbGridSelected"
                >{{ $t("app_drawer.grid") }}</cv-content-switcher-button
              >
              <cv-content-switcher-button
                owner-id="list"
                :selected="csbListSelected"
                >{{ $t("app_drawer.list") }}</cv-content-switcher-button
              >
            </cv-content-switcher>
            <NsEmptyState
              v-if="!appsToDisplay.length"
              :title="$t('common.no_search_results')"
              :animationData="GhostDarkBgLottie"
              animationTitle="ghost"
              :loop="1"
            >
              <template #description>
                <div>{{ $t("common.no_search_results_description") }}</div>
              </template>
            </NsEmptyState>
            <section v-else>
              <div
                v-if="csbGridSelected"
                class="bx--grid bx--grid--full-width app-grid"
              >
                <template v-if="favoriteApps.length && !isSearchActive">
                  <div class="bx--row">
                    <div class="bx--col">
                      <div class="app-divider no-mg-top">
                        {{ $t("app_drawer.favorites") }}
                      </div>
                    </div>
                  </div>
                  <div class="bx--row">
                    <div
                      class="bx--col app-cell"
                      v-for="(app, index) in favoriteApps"
                      :key="index"
                    >
                      <div class="app" @click="openApp(app)">
                        <div class="app-icon">
                          <img
                            :src="
                              app.logo
                                ? app.logo
                                : require('@/assets/module_default_logo.png')
                            "
                            :alt="app.id + ' logo'"
                          />
                        </div>
                        {{ app.ui_name ? app.ui_name : app.id }}
                      </div>
                    </div>
                  </div>
                  <div class="bx--row">
                    <div class="bx--col">
                      <div class="app-divider">
                        {{ $t("app_drawer.all_apps") }}
                      </div>
                    </div>
                  </div>
                </template>
                <div v-if="isSearchActive" class="bx--row">
                  <div class="bx--col">
                    <div class="app-divider no-mg-top">
                      {{ $t("app_drawer.search_results") }}
                    </div>
                  </div>
                </div>
                <div class="bx--row">
                  <div
                    class="bx--col app-cell"
                    v-for="(app, index) in appsToDisplay"
                    :key="index"
                  >
                    <div class="app" @click="openApp(app)">
                      <div class="app-icon">
                        <img
                          :src="
                            app.logo
                              ? app.logo
                              : require('@/assets/module_default_logo.png')
                          "
                          :alt="app.id + ' logo'"
                        />
                      </div>
                      {{ app.ui_name ? app.ui_name : app.id }}
                    </div>
                  </div>
                </div>
              </div>
              <div v-if="csbListSelected">
                <template v-if="favoriteApps.length && !isSearchActive">
                  <h6 class="app-divider-list">
                    {{ $t("app_drawer.favorites") }}
                  </h6>
                  <cv-structured-list class="app-list">
                    <template slot="items">
                      <cv-structured-list-item
                        v-for="(app, index) in favoriteApps"
                        :key="index"
                      >
                        <cv-structured-list-data class="app-list-element">
                          <div class="app" @click="openApp(app)">
                            <div class="app-icon">
                              <img
                                :src="
                                  app.logo
                                    ? app.logo
                                    : require('@/assets/module_default_logo.png')
                                "
                                :alt="app.id + ' logo'"
                              />
                            </div>
                            <span>{{
                              app.ui_name ? app.ui_name : app.id
                            }}</span>
                          </div></cv-structured-list-data
                        >
                      </cv-structured-list-item>
                    </template>
                  </cv-structured-list>
                  <h6 class="app-divider-list">
                    {{ $t("app_drawer.all_apps") }}
                  </h6>
                </template>
                <h6 v-if="isSearchActive" class="app-divider-list">
                  {{ $t("app_drawer.search_results") }}
                </h6>
                <cv-structured-list class="app-list">
                  <template slot="items">
                    <cv-structured-list-item
                      v-for="(app, index) in appsToDisplay"
                      :key="index"
                    >
                      <cv-structured-list-data class="app-drawer-app">
                        <div class="app" @click="openApp(app)">
                          <div class="app-icon">
                            <img
                              :src="
                                app.logo
                                  ? app.logo
                                  : require('@/assets/module_default_logo.png')
                              "
                              :alt="app.id + ' logo'"
                            />
                          </div>
                          <span>{{ app.ui_name ? app.ui_name : app.id }}</span>
                        </div></cv-structured-list-data
                      >
                    </cv-structured-list-item>
                  </template>
                </cv-structured-list>
              </div>
            </section>
          </template>
        </template>
      </div>
    </div>
  </transition>
</template>
⋮----
<template #description>
            <div>{{ $t("app_drawer.no_apps_description") }}</div>
            <NsButton
              kind="ghost"
              :icon="Application20"
              @click="goToSoftwareCenter"
              class="empty-state-button ghost-button-dark-bg"
              >{{ $t("software_center.title") }}</NsButton
            >
          </template>
⋮----
<div>{{ $t("app_drawer.no_apps_description") }}</div>
⋮----
>{{ $t("software_center.title") }}</NsButton
⋮----
<template v-else>
          <div class="search-container">
            <cv-search
              :label="$t('app_drawer.search_placeholder')"
              :placeholder="$t('app_drawer.search_placeholder')"
              :clear-aria-label="$t('common.clear_search')"
              v-model.trim="searchQuery"
              v-debounce="searchApp"
              @input="onSearchInput"
              class="app-drawer-search"
              ref="appSearch"
            >
            </cv-search>
            <cv-icon-button
              kind="secondary"
              :icon="Star20"
              :label="$t('app_drawer.edit_favorite_apps')"
              tip-position="bottom"
              tip-alignment="end"
              @click="toggleEditFavorites"
            />
          </div>
          <template v-if="isEditingFavoriteApps">
            <NsButton
              kind="primary"
              :icon="Checkmark20"
              size="field"
              @click="doneEditFavorites"
              class="done-edit-favorites-button"
              >{{ $t("app_drawer.done_edit_favorites") }}</NsButton
            >
            <div class="bx--grid bx--grid--full-width app-grid">
              <div class="bx--row">
                <div class="bx--col">
                  <div class="app-divider no-mg-top">
                    {{ $t("app_drawer.set_favorite_apps") }}
                  </div>
                </div>
              </div>
              <div class="bx--row">
                <div
                  class="bx--col app-cell"
                  v-for="(app, index) in apps"
                  :key="index"
                >
                  <div class="app">
                    <div @click="toggleFavorite(app)">
                      <div class="app-icon">
                        <img
                          :src="
                            app.logo
                              ? app.logo
                              : require('@/assets/module_default_logo.png')
                          "
                          :alt="app.id + ' logo'"
                        />
                      </div>
                      <div>
                        {{ app.ui_name ? app.ui_name : app.id }}
                      </div>
                    </div>
                    <cv-toggle
                      value="favorite"
                      small
                      :checked="app.isFavorite"
                      class="toggle-app-favorite"
                      @click="toggleFavorite(app)"
                    >
                      <template slot="text-left">{{
                        $t("app_drawer.favorite")
                      }}</template>
                      <template slot="text-right">{{
                        $t("app_drawer.favorite")
                      }}</template>
                    </cv-toggle>
                  </div>
                </div>
              </div>
            </div>
          </template>
          <template v-else>
            <cv-content-switcher
              size="sm"
              class="view-switcher"
              @selected="contentSwitcherSelected"
            >
              <cv-content-switcher-button
                owner-id="grid"
                :selected="csbGridSelected"
                >{{ $t("app_drawer.grid") }}</cv-content-switcher-button
              >
              <cv-content-switcher-button
                owner-id="list"
                :selected="csbListSelected"
                >{{ $t("app_drawer.list") }}</cv-content-switcher-button
              >
            </cv-content-switcher>
            <NsEmptyState
              v-if="!appsToDisplay.length"
              :title="$t('common.no_search_results')"
              :animationData="GhostDarkBgLottie"
              animationTitle="ghost"
              :loop="1"
            >
              <template #description>
                <div>{{ $t("common.no_search_results_description") }}</div>
              </template>
            </NsEmptyState>
            <section v-else>
              <div
                v-if="csbGridSelected"
                class="bx--grid bx--grid--full-width app-grid"
              >
                <template v-if="favoriteApps.length && !isSearchActive">
                  <div class="bx--row">
                    <div class="bx--col">
                      <div class="app-divider no-mg-top">
                        {{ $t("app_drawer.favorites") }}
                      </div>
                    </div>
                  </div>
                  <div class="bx--row">
                    <div
                      class="bx--col app-cell"
                      v-for="(app, index) in favoriteApps"
                      :key="index"
                    >
                      <div class="app" @click="openApp(app)">
                        <div class="app-icon">
                          <img
                            :src="
                              app.logo
                                ? app.logo
                                : require('@/assets/module_default_logo.png')
                            "
                            :alt="app.id + ' logo'"
                          />
                        </div>
                        {{ app.ui_name ? app.ui_name : app.id }}
                      </div>
                    </div>
                  </div>
                  <div class="bx--row">
                    <div class="bx--col">
                      <div class="app-divider">
                        {{ $t("app_drawer.all_apps") }}
                      </div>
                    </div>
                  </div>
                </template>
                <div v-if="isSearchActive" class="bx--row">
                  <div class="bx--col">
                    <div class="app-divider no-mg-top">
                      {{ $t("app_drawer.search_results") }}
                    </div>
                  </div>
                </div>
                <div class="bx--row">
                  <div
                    class="bx--col app-cell"
                    v-for="(app, index) in appsToDisplay"
                    :key="index"
                  >
                    <div class="app" @click="openApp(app)">
                      <div class="app-icon">
                        <img
                          :src="
                            app.logo
                              ? app.logo
                              : require('@/assets/module_default_logo.png')
                          "
                          :alt="app.id + ' logo'"
                        />
                      </div>
                      {{ app.ui_name ? app.ui_name : app.id }}
                    </div>
                  </div>
                </div>
              </div>
              <div v-if="csbListSelected">
                <template v-if="favoriteApps.length && !isSearchActive">
                  <h6 class="app-divider-list">
                    {{ $t("app_drawer.favorites") }}
                  </h6>
                  <cv-structured-list class="app-list">
                    <template slot="items">
                      <cv-structured-list-item
                        v-for="(app, index) in favoriteApps"
                        :key="index"
                      >
                        <cv-structured-list-data class="app-list-element">
                          <div class="app" @click="openApp(app)">
                            <div class="app-icon">
                              <img
                                :src="
                                  app.logo
                                    ? app.logo
                                    : require('@/assets/module_default_logo.png')
                                "
                                :alt="app.id + ' logo'"
                              />
                            </div>
                            <span>{{
                              app.ui_name ? app.ui_name : app.id
                            }}</span>
                          </div></cv-structured-list-data
                        >
                      </cv-structured-list-item>
                    </template>
                  </cv-structured-list>
                  <h6 class="app-divider-list">
                    {{ $t("app_drawer.all_apps") }}
                  </h6>
                </template>
                <h6 v-if="isSearchActive" class="app-divider-list">
                  {{ $t("app_drawer.search_results") }}
                </h6>
                <cv-structured-list class="app-list">
                  <template slot="items">
                    <cv-structured-list-item
                      v-for="(app, index) in appsToDisplay"
                      :key="index"
                    >
                      <cv-structured-list-data class="app-drawer-app">
                        <div class="app" @click="openApp(app)">
                          <div class="app-icon">
                            <img
                              :src="
                                app.logo
                                  ? app.logo
                                  : require('@/assets/module_default_logo.png')
                              "
                              :alt="app.id + ' logo'"
                            />
                          </div>
                          <span>{{ app.ui_name ? app.ui_name : app.id }}</span>
                        </div></cv-structured-list-data
                      >
                    </cv-structured-list-item>
                  </template>
                </cv-structured-list>
              </div>
            </section>
          </template>
        </template>
⋮----
<template v-if="isEditingFavoriteApps">
            <NsButton
              kind="primary"
              :icon="Checkmark20"
              size="field"
              @click="doneEditFavorites"
              class="done-edit-favorites-button"
              >{{ $t("app_drawer.done_edit_favorites") }}</NsButton
            >
            <div class="bx--grid bx--grid--full-width app-grid">
              <div class="bx--row">
                <div class="bx--col">
                  <div class="app-divider no-mg-top">
                    {{ $t("app_drawer.set_favorite_apps") }}
                  </div>
                </div>
              </div>
              <div class="bx--row">
                <div
                  class="bx--col app-cell"
                  v-for="(app, index) in apps"
                  :key="index"
                >
                  <div class="app">
                    <div @click="toggleFavorite(app)">
                      <div class="app-icon">
                        <img
                          :src="
                            app.logo
                              ? app.logo
                              : require('@/assets/module_default_logo.png')
                          "
                          :alt="app.id + ' logo'"
                        />
                      </div>
                      <div>
                        {{ app.ui_name ? app.ui_name : app.id }}
                      </div>
                    </div>
                    <cv-toggle
                      value="favorite"
                      small
                      :checked="app.isFavorite"
                      class="toggle-app-favorite"
                      @click="toggleFavorite(app)"
                    >
                      <template slot="text-left">{{
                        $t("app_drawer.favorite")
                      }}</template>
                      <template slot="text-right">{{
                        $t("app_drawer.favorite")
                      }}</template>
                    </cv-toggle>
                  </div>
                </div>
              </div>
            </div>
          </template>
⋮----
>{{ $t("app_drawer.done_edit_favorites") }}</NsButton
⋮----
{{ $t("app_drawer.set_favorite_apps") }}
⋮----
{{ app.ui_name ? app.ui_name : app.id }}
⋮----
<template slot="text-left">{{
                        $t("app_drawer.favorite")
                      }}</template>
<template slot="text-right">{{
                        $t("app_drawer.favorite")
                      }}</template>
⋮----
<template v-else>
            <cv-content-switcher
              size="sm"
              class="view-switcher"
              @selected="contentSwitcherSelected"
            >
              <cv-content-switcher-button
                owner-id="grid"
                :selected="csbGridSelected"
                >{{ $t("app_drawer.grid") }}</cv-content-switcher-button
              >
              <cv-content-switcher-button
                owner-id="list"
                :selected="csbListSelected"
                >{{ $t("app_drawer.list") }}</cv-content-switcher-button
              >
            </cv-content-switcher>
            <NsEmptyState
              v-if="!appsToDisplay.length"
              :title="$t('common.no_search_results')"
              :animationData="GhostDarkBgLottie"
              animationTitle="ghost"
              :loop="1"
            >
              <template #description>
                <div>{{ $t("common.no_search_results_description") }}</div>
              </template>
            </NsEmptyState>
            <section v-else>
              <div
                v-if="csbGridSelected"
                class="bx--grid bx--grid--full-width app-grid"
              >
                <template v-if="favoriteApps.length && !isSearchActive">
                  <div class="bx--row">
                    <div class="bx--col">
                      <div class="app-divider no-mg-top">
                        {{ $t("app_drawer.favorites") }}
                      </div>
                    </div>
                  </div>
                  <div class="bx--row">
                    <div
                      class="bx--col app-cell"
                      v-for="(app, index) in favoriteApps"
                      :key="index"
                    >
                      <div class="app" @click="openApp(app)">
                        <div class="app-icon">
                          <img
                            :src="
                              app.logo
                                ? app.logo
                                : require('@/assets/module_default_logo.png')
                            "
                            :alt="app.id + ' logo'"
                          />
                        </div>
                        {{ app.ui_name ? app.ui_name : app.id }}
                      </div>
                    </div>
                  </div>
                  <div class="bx--row">
                    <div class="bx--col">
                      <div class="app-divider">
                        {{ $t("app_drawer.all_apps") }}
                      </div>
                    </div>
                  </div>
                </template>
                <div v-if="isSearchActive" class="bx--row">
                  <div class="bx--col">
                    <div class="app-divider no-mg-top">
                      {{ $t("app_drawer.search_results") }}
                    </div>
                  </div>
                </div>
                <div class="bx--row">
                  <div
                    class="bx--col app-cell"
                    v-for="(app, index) in appsToDisplay"
                    :key="index"
                  >
                    <div class="app" @click="openApp(app)">
                      <div class="app-icon">
                        <img
                          :src="
                            app.logo
                              ? app.logo
                              : require('@/assets/module_default_logo.png')
                          "
                          :alt="app.id + ' logo'"
                        />
                      </div>
                      {{ app.ui_name ? app.ui_name : app.id }}
                    </div>
                  </div>
                </div>
              </div>
              <div v-if="csbListSelected">
                <template v-if="favoriteApps.length && !isSearchActive">
                  <h6 class="app-divider-list">
                    {{ $t("app_drawer.favorites") }}
                  </h6>
                  <cv-structured-list class="app-list">
                    <template slot="items">
                      <cv-structured-list-item
                        v-for="(app, index) in favoriteApps"
                        :key="index"
                      >
                        <cv-structured-list-data class="app-list-element">
                          <div class="app" @click="openApp(app)">
                            <div class="app-icon">
                              <img
                                :src="
                                  app.logo
                                    ? app.logo
                                    : require('@/assets/module_default_logo.png')
                                "
                                :alt="app.id + ' logo'"
                              />
                            </div>
                            <span>{{
                              app.ui_name ? app.ui_name : app.id
                            }}</span>
                          </div></cv-structured-list-data
                        >
                      </cv-structured-list-item>
                    </template>
                  </cv-structured-list>
                  <h6 class="app-divider-list">
                    {{ $t("app_drawer.all_apps") }}
                  </h6>
                </template>
                <h6 v-if="isSearchActive" class="app-divider-list">
                  {{ $t("app_drawer.search_results") }}
                </h6>
                <cv-structured-list class="app-list">
                  <template slot="items">
                    <cv-structured-list-item
                      v-for="(app, index) in appsToDisplay"
                      :key="index"
                    >
                      <cv-structured-list-data class="app-drawer-app">
                        <div class="app" @click="openApp(app)">
                          <div class="app-icon">
                            <img
                              :src="
                                app.logo
                                  ? app.logo
                                  : require('@/assets/module_default_logo.png')
                              "
                              :alt="app.id + ' logo'"
                            />
                          </div>
                          <span>{{ app.ui_name ? app.ui_name : app.id }}</span>
                        </div></cv-structured-list-data
                      >
                    </cv-structured-list-item>
                  </template>
                </cv-structured-list>
              </div>
            </section>
          </template>
⋮----
>{{ $t("app_drawer.grid") }}</cv-content-switcher-button
⋮----
>{{ $t("app_drawer.list") }}</cv-content-switcher-button
⋮----
<template #description>
                <div>{{ $t("common.no_search_results_description") }}</div>
              </template>
⋮----
<div>{{ $t("common.no_search_results_description") }}</div>
⋮----
<template v-if="favoriteApps.length && !isSearchActive">
                  <div class="bx--row">
                    <div class="bx--col">
                      <div class="app-divider no-mg-top">
                        {{ $t("app_drawer.favorites") }}
                      </div>
                    </div>
                  </div>
                  <div class="bx--row">
                    <div
                      class="bx--col app-cell"
                      v-for="(app, index) in favoriteApps"
                      :key="index"
                    >
                      <div class="app" @click="openApp(app)">
                        <div class="app-icon">
                          <img
                            :src="
                              app.logo
                                ? app.logo
                                : require('@/assets/module_default_logo.png')
                            "
                            :alt="app.id + ' logo'"
                          />
                        </div>
                        {{ app.ui_name ? app.ui_name : app.id }}
                      </div>
                    </div>
                  </div>
                  <div class="bx--row">
                    <div class="bx--col">
                      <div class="app-divider">
                        {{ $t("app_drawer.all_apps") }}
                      </div>
                    </div>
                  </div>
                </template>
⋮----
{{ $t("app_drawer.favorites") }}
⋮----
{{ app.ui_name ? app.ui_name : app.id }}
⋮----
{{ $t("app_drawer.all_apps") }}
⋮----
{{ $t("app_drawer.search_results") }}
⋮----
{{ app.ui_name ? app.ui_name : app.id }}
⋮----
<template v-if="favoriteApps.length && !isSearchActive">
                  <h6 class="app-divider-list">
                    {{ $t("app_drawer.favorites") }}
                  </h6>
                  <cv-structured-list class="app-list">
                    <template slot="items">
                      <cv-structured-list-item
                        v-for="(app, index) in favoriteApps"
                        :key="index"
                      >
                        <cv-structured-list-data class="app-list-element">
                          <div class="app" @click="openApp(app)">
                            <div class="app-icon">
                              <img
                                :src="
                                  app.logo
                                    ? app.logo
                                    : require('@/assets/module_default_logo.png')
                                "
                                :alt="app.id + ' logo'"
                              />
                            </div>
                            <span>{{
                              app.ui_name ? app.ui_name : app.id
                            }}</span>
                          </div></cv-structured-list-data
                        >
                      </cv-structured-list-item>
                    </template>
                  </cv-structured-list>
                  <h6 class="app-divider-list">
                    {{ $t("app_drawer.all_apps") }}
                  </h6>
                </template>
⋮----
{{ $t("app_drawer.favorites") }}
⋮----
<template slot="items">
                      <cv-structured-list-item
                        v-for="(app, index) in favoriteApps"
                        :key="index"
                      >
                        <cv-structured-list-data class="app-list-element">
                          <div class="app" @click="openApp(app)">
                            <div class="app-icon">
                              <img
                                :src="
                                  app.logo
                                    ? app.logo
                                    : require('@/assets/module_default_logo.png')
                                "
                                :alt="app.id + ' logo'"
                              />
                            </div>
                            <span>{{
                              app.ui_name ? app.ui_name : app.id
                            }}</span>
                          </div></cv-structured-list-data
                        >
                      </cv-structured-list-item>
                    </template>
⋮----
<span>{{
                              app.ui_name ? app.ui_name : app.id
                            }}</span>
⋮----
{{ $t("app_drawer.all_apps") }}
⋮----
{{ $t("app_drawer.search_results") }}
⋮----
<template slot="items">
                    <cv-structured-list-item
                      v-for="(app, index) in appsToDisplay"
                      :key="index"
                    >
                      <cv-structured-list-data class="app-drawer-app">
                        <div class="app" @click="openApp(app)">
                          <div class="app-icon">
                            <img
                              :src="
                                app.logo
                                  ? app.logo
                                  : require('@/assets/module_default_logo.png')
                              "
                              :alt="app.id + ' logo'"
                            />
                          </div>
                          <span>{{ app.ui_name ? app.ui_name : app.id }}</span>
                        </div></cv-structured-list-data
                      >
                    </cv-structured-list-item>
                  </template>
⋮----
<span>{{ app.ui_name ? app.ui_name : app.id }}</span>
⋮----
<script>
import { mapState, mapActions } from "vuex";
import {
  StorageService,
  IconService,
  UtilService,
  TaskService,
  LottieService,
} from "@nethserver/ns8-ui-lib";
import to from "await-to-js";
export default {
  name: "AppDrawer",
  mixins: [
    StorageService,
    IconService,
    UtilService,
    TaskService,
    LottieService,
  ],
  data() {
    return {
      view: "grid",
      isTransitioning: false,
      searchQuery: "",
      apps: [],
      searchResults: [],
      isSearchActive: false,
      searchFields: ["id", "ui_name"],
      loading: {
        apps: true,
      },
      error: {
        apps: "",
      },
    };
  },
  computed: {
    ...mapState(["isAppDrawerShown", "isEditingFavoriteApps"]),
    csbGridSelected() {
      return this.view === "grid";
    },
    csbListSelected() {
      return this.view === "list";
    },
    appsToDisplay() {
      if (this.isSearchActive) {
        return this.searchResults;
      } else {
        return this.apps;
      }
    },
    favoriteApps() {
      return this.apps.filter((app) => app.isFavorite);
    },
  },
  watch: {
    isAppDrawerShown: function () {
      this.isTransitioning = true;
      setTimeout(() => {
        this.isTransitioning = false;
      }, 300);
      if (this.isAppDrawerShown) {
        if (!this.loading.apps && this.apps.length) {
          this.focusElement("appSearch");
        }
      } else {
        if (this.isEditingFavoriteApps) {
          this.doneEditFavorites();
        }
        this.listInstalledModules();
      }
    },
    "loading.apps": function () {
      if (!this.loading.apps && this.isAppDrawerShown && this.apps.length) {
        this.focusElement("appSearch");
      }
    },
  },
  created() {
    this.$root.$on("reloadAppDrawer", this.listInstalledModules);
    this.listInstalledModules();
    this.loadAppDrawerViewFromStorage();
  },
  beforeDestroy() {
    this.$root.$off("reloadAppDrawer");
  },
  methods: {
    ...mapActions([
      "setAppDrawerShownInStore",
      "setEditingFavoriteAppsInStore",
      "setFavoriteAppsInStore",
      "setMigratingAppsInStore",
    ]),
    loadAppDrawerViewFromStorage() {
      const appDrawerView = this.getFromStorage("appDrawerView");
      if (appDrawerView) {
        this.view = appDrawerView;
      }
    },
    clickOutside() {
      if (!this.isTransitioning) {
        this.setAppDrawerShownInStore(false);
      }
    },
    contentSwitcherSelected(value) {
      this.view = value;
      this.saveToStorage("appDrawerView", this.view);
    },
    goToSoftwareCenter() {
      this.$router.push("/software-center");
      this.setAppDrawerShownInStore(false);
    },
    openApp(instance) {
      this.$router.push(`/apps/${instance.id}`);
      this.setAppDrawerShownInStore(false);
    },
    async listInstalledModules() {
      this.loading.apps = true;
      const taskAction = "list-installed-modules";
      this.$root.$off(taskAction + "-aborted");
      this.$root.$once(
        taskAction + "-aborted",
        this.listInstalledModulesAborted
      );
      this.$root.$off(taskAction + "-completed");
      this.$root.$once(
        taskAction + "-completed",
        this.listInstalledModulesCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
          },
        })
      );
      const err = res[0];
      if (err) {
        this.error.apps = this.getErrorMessage(err);
        this.createErrorNotification(
          err,
          this.$t("task.cannot_create_task", { action: taskAction })
        );
        return;
      }
    },
    listInstalledModulesAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.apps = this.$t("error.generic_error");
      this.loading.apps = false;
    },
    listInstalledModulesCompleted(taskContext, taskResult) {
      this.loading.apps = false;
      let apps = [];
      const migratingApps = [];
      for (let instanceList of Object.values(taskResult.output)) {
        for (let instance of instanceList) {
          if (
            !instance.flags.includes("core_module") ||
            (instance.flags.includes("account_provider") &&
              instance.flags.includes("file_server"))
          ) {
            apps.push(instance);
          }
          if (instance.flags.includes("import_started")) {
            migratingApps.push(instance.id);
          }
        }
      }
      this.setMigratingAppsInStore(migratingApps);
      for (let app of apps) {
        app.isFavorite = false;
      }
      this.listFavorites();
      apps.sort(this.sortModuleInstances());
      this.apps = apps;
    },
    searchApp() {
      const cleanRegex = /[^a-zA-Z0-9]/g;
      const queryText = this.searchQuery.replace(cleanRegex, "");
      // empty search
      if (queryText.length == 0) {
        this.isSearchActive = false;
        return;
      }
      // show search results
      this.isSearchActive = true;
      // search
      this.searchResults = this.apps.filter((app) => {
        // compare query text with all search fields of option
        return this.searchFields.some((searchField) => {
          const searchValue = app[searchField];
          if (searchValue) {
            return new RegExp(queryText, "i").test(
              searchValue.replace(cleanRegex, "")
            );
          }
        });
      }, this);
    },
    toggleEditFavorites() {
      if (!this.isEditingFavoriteApps) {
        this.enableEditFavorites();
      } else {
        this.doneEditFavorites();
      }
    },
    enableEditFavorites() {
      this.view = "grid";
      this.setEditingFavoriteAppsInStore(true);
    },
    doneEditFavorites() {
      setTimeout(() => {
        this.setEditingFavoriteAppsInStore(false);
        this.loadAppDrawerViewFromStorage();
      }, 100);
    },
    onSearchInput() {
      if (!this.searchQuery.length) {
        this.searchApp();
      }
    },
    toggleFavorite(app) {
      app.isFavorite = !app.isFavorite;
      if (app.isFavorite) {
        this.addFavorite(app);
      } else {
        this.removeFavorite(app);
      }
    },
    async addFavorite(app) {
      const taskAction = "add-favorite";
      this.$root.$off(taskAction + "-aborted");
      this.$root.$once(taskAction + "-aborted", this.addFavoriteAborted);
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {
            instance: app.id,
          },
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
          },
        })
      );
      const err = res[0];
      if (err) {
        this.error.apps = this.getErrorMessage(err);
        this.createErrorNotification(
          err,
          this.$t("task.cannot_create_task", { action: taskAction })
        );
        return;
      }
    },
    addFavoriteAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.listInstalledModules();
    },
    async removeFavorite(app) {
      const taskAction = "remove-favorite";
      this.$root.$off(taskAction + "-aborted");
      this.$root.$once(taskAction + "-aborted", this.removeFavoriteAborted);
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {
            instance: app.id,
          },
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
          },
        })
      );
      const err = res[0];
      if (err) {
        this.error.apps = this.getErrorMessage(err);
        this.createErrorNotification(
          err,
          this.$t("task.cannot_create_task", { action: taskAction })
        );
        return;
      }
    },
    removeFavoriteAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.listInstalledModules();
    },
    async listFavorites() {
      const taskAction = "list-favorites";
      this.$root.$once(taskAction + "-completed", this.listFavoritesCompleted);
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
          },
        })
      );
      const err = res[0];
      if (err) {
        this.error.apps = this.getErrorMessage(err);
        this.createErrorNotification(
          err,
          this.$t("task.cannot_create_task", { action: taskAction })
        );
        return;
      }
    },
    listFavoritesCompleted(taskContext, taskResult) {
      const favorites = taskResult.output;
      const favoritesForStore = favorites.map((fav) => fav.id);
      this.setFavoriteAppsInStore(favoritesForStore);
      for (const favorite of favorites) {
        const favoriteApp = this.apps.find((app) => app.id === favorite.id);
        if (favoriteApp) {
          favoriteApp.isFavorite = true;
        }
      }
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
.app-drawer {
  background-color: $ui-05;
  border-left: 1px solid $interactive-02;
  border-bottom: 1px solid $interactive-02;
  color: $ui-01;
  width: $app-drawer-width;
  height: calc(100vh - 3rem);
  position: fixed;
  top: 3rem;
  right: 0;
  overflow: auto;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.5);
  z-index: 10000;
  padding-bottom: 3rem;
}
.app-drawer-loader {
  margin: $spacing-07 auto;
}
.app-drawer.list {
  width: $notification-drawer-width-small-screen;
}
.slide-app-drawer-enter-active,
.slide-app-drawer-leave-active {
  transition: all 0.3s ease;
}
.slide-app-drawer-enter,
.slide-app-drawer-leave-to {
  transform: translateX($app-drawer-width);
}
.search-container {
  display: flex;
}
.view-switcher {
  margin: $spacing-07 $spacing-05;
  width: auto;
}
.bx--content-switcher-btn.bx--content-switcher--selected {
  color: $ui-05;
  background-color: $ui-01;
}
.bx--content-switcher-btn.bx--content-switcher--selected::after {
  color: $ui-05;
  background-color: $ui-01;
}
.bx--content-switcher-btn {
  color: $active-ui;
  background-color: #262626;
}
.bx--content-switcher-btn:focus {
  border-color: #fff;
  box-shadow: inset 0 0 0 2px #fff, inset 0 0 0 3px #262626;
}
.bx--content-switcher-btn:active,
.bx--content-switcher-btn:hover {
  color: $ui-01;
  background-color: #353535;
}
.bx--content-switcher-btn.bx--content-switcher--selected:active,
.bx--content-switcher-btn.bx--content-switcher--selected:hover {
  color: $ui-05;
  background-color: $ui-01;
}
.app-divider {
  margin: $spacing-07 0 $spacing-03;
  padding-bottom: $spacing-02;
  border-bottom: 1px solid $text-02;
  color: $active-ui;
}
.app-divider span {
  font-size: 0.75rem;
  font-weight: 400;
  line-height: 1.34;
  letter-spacing: 0.32px;
  color: $active-ui;
}
.app-divider-list {
  margin: $spacing-07 $spacing-05 $spacing-05;
}
.app-grid {
  padding-top: 0;
  padding-bottom: $spacing-05;
  padding-left: $spacing-05;
  padding-right: $spacing-05;
}
.app-grid .app-cell {
  padding-left: 0.5rem;
  padding-right: 0.5rem;
}
.app-grid .app {
  width: 6.8rem;
  margin: auto;
  text-align: center;
  padding-top: $spacing-05;
  padding-bottom: $spacing-05;
  cursor: pointer;
}
.app-grid .app:hover {
  background-color: #353535;
}
.app-grid .app-icon {
  display: block;
  margin-left: auto;
  margin-right: auto;
  margin-bottom: $spacing-04;
}
.app-list .app {
  display: flex;
  align-items: center;
  cursor: pointer;
  width: 100%;
  height: 100%;
}
.app-list .app-icon {
  margin-right: $spacing-03;
}
.app-icon {
  width: 4rem;
  height: 4rem;
  flex-shrink: 0;
}
@media (max-width: $breakpoint-medium) {
  .app-icon {
    width: 3rem;
    height: 3rem;
  }
}
.app-icon img {
  width: 100%;
  height: 100%;
}
.no-mg-top {
  margin-top: 0;
}
.done-edit-favorites-button {
  margin: $spacing-05;
}
@media (max-width: $breakpoint-medium) {
  .slide-app-drawer-enter,
  .slide-app-drawer-leave-to {
    transform: translateX($app-drawer-width-small-screen);
  }
  .app-drawer {
    width: $app-drawer-width-small-screen;
  }
}
</style>
⋮----
<style lang="scss">
@import "../../styles/carbon-utils";
.app-drawer .bx--structured-list-td,
.app-drawer .empty-state {
  background-color: $ui-05 !important;
  color: $ui-01 !important;
}
.app-drawer
  .bx--structured-list.bx--structured-list--condensed
  .bx--structured-list-td,
.app-drawer
  .bx--structured-list.bx--structured-list--condensed
  .bx--structured-list-th {
  padding: $spacing-05 !important;
}
.app-drawer .bx--structured-list-row {
  border-color: #393939;
}
.app-drawer .bx--structured-list {
  margin-bottom: 0;
}
.app-drawer
  .cv-structured-list-data.bx--structured-list-td.app-list-element:hover {
  background-color: #353535 !important;
}
.app-drawer .toggle-app-favorite .bx--toggle-input__label {
  color: $text-03;
}
.app-drawer .toggle-app-favorite .bx--toggle-input__label .bx--toggle__switch {
  margin-top: $spacing-03;
}
.app-drawer .view-switcher,
.app-drawer .view-switcher *,
.app-drawer .view-switcher *::before,
.app-drawer .view-switcher *::after {
  transition: none !important;
  animation: none !important;
}
</style>
</file>

<file path="core/ui/src/components/shell/GlobalSearch.vue">
<template>
  <div class="global-search" v-click-outside="clickOutside">
    <cv-search
      :label="$t('shell.search_placeholder')"
      :placeholder="$t('shell.search_placeholder')"
      :clear-aria-label="$t('common.clear_search')"
      v-model="query"
      @input="onSearchInput"
      v-debounce="search"
      ref="global-search"
      @keydown.enter.native="openResult(selectedResult)"
      @keydown.esc.native="closeSearch"
      @keydown.down.prevent="selectNextResult"
      @keydown.up.prevent="selectPreviousResult"
    >
    </cv-search>
    <div v-if="showResults" class="search-results">
      <NsEmptyState
        v-if="!results.length"
        :title="$t('common.no_search_results')"
        :animationData="GhostDarkBgLottie"
        animationTitle="ghost"
        :loop="1"
      >
        <template #description>
          {{ $t("common.no_search_results_description") }}</template
        >
      </NsEmptyState>
      <div
        v-else
        v-for="(result, index) in results"
        :key="index"
        :class="[
          'search-result',
          { 'selected-result': result.path === selectedResult.path },
        ]"
        @click="openResult(result)"
        @mouseover="selectResult(result)"
      >
        <div class="search-result-column name">
          <div class="flex">
            <Settings20 class="result-icon" />
            <span class="font-weight-600">{{ result.name }}</span>
          </div>
          <div
            v-if="result.source != 'core' && result.source !== result.name"
            class="source"
          >
            {{ result.source }}
          </div>
        </div>
        <div class="search-result-column description">
          <div class="flex">
            <span>{{ result.description }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
⋮----
<template #description>
          {{ $t("common.no_search_results_description") }}</template
        >
⋮----
{{ $t("common.no_search_results_description") }}</template
⋮----
<span class="font-weight-600">{{ result.name }}</span>
⋮----
{{ result.source }}
⋮----
<span>{{ result.description }}</span>
⋮----
<script>
import Settings20 from "@carbon/icons-vue/es/settings/20";
import {
  UtilService,
  TaskService,
  LottieService,
} from "@nethserver/ns8-ui-lib";
import to from "await-to-js";
export default {
  name: "GlobalSearch",
  components: { Settings20 },
  mixins: [UtilService, TaskService, LottieService],
  data() {
    return {
      query: "",
      showResults: false,
      results: [],
      selectedResult: {},
      searchFields: ["name", "description", "source", "tags", "label"],
      minChars: 2,
      maxResults: 10,
      actionsResults: [],
      openAppResults: [],
      allResults: [],
      isClickOutsideEnabled: false,
    };
  },
  watch: {
    actionsResults: function () {
      this.allResults = this.actionsResults.concat(this.openAppResults);
    },
    openAppResults: function () {
      this.allResults = this.actionsResults.concat(this.openAppResults);
    },
  },
  created() {
    this.listShortcuts();
    this.listInstalledModules();
  },
  mounted() {
    this.focusElement("global-search");
    setTimeout(() => {
      this.isClickOutsideEnabled = true;
    }, 200);
  },
  methods: {
    async listShortcuts() {
      const taskAction = "list-shortcuts";
      this.$root.$once(taskAction + "-completed", this.listShortcutsCompleted);
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
          },
        })
      );
      const err = res[0];
      if (err) {
        this.createErrorNotification(
          err,
          this.$t("task.cannot_create_task", { action: taskAction })
        );
        return;
      }
    },
    listShortcutsCompleted(taskContext, taskResult) {
      const actionsResults = [];
      for (const searchResult of taskResult.output) {
        actionsResults.push({
          name: this.getI18nAttribute(searchResult, "name"),
          description: this.getI18nAttribute(searchResult, "description"),
          path: searchResult.path,
          source: searchResult.source,
          tags: this.getI18nAttribute(searchResult, "tags"),
        });
      }
      this.actionsResults = actionsResults;
    },
    async listInstalledModules() {
      const taskAction = "list-installed-modules";
      this.$root.$once(
        taskAction + "-completed",
        this.listInstalledModulesCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
          },
        })
      );
      const err = res[0];
      if (err) {
        this.error.apps = this.getErrorMessage(err);
        this.createErrorNotification(
          err,
          this.$t("task.cannot_create_task", { action: taskAction })
        );
        return;
      }
    },
    listInstalledModulesCompleted(taskContext, taskResult) {
      let openAppResults = [];
      for (let instanceList of Object.values(taskResult.output)) {
        for (let instance of instanceList) {
          if (
            !instance.flags.includes("account_provider") &&
            !instance.flags.includes("core_module")
          ) {
            const openAppResult = {
              name: instance.ui_name ? instance.ui_name : instance.id,
              description: this.$t("shell.open_app", { app: instance.module }),
              path: "/apps/" + instance.id,
              source: instance.id,
              tags: [],
              label: instance.ui_name,
            };
            openAppResults.push(openAppResult);
          }
        }
      }
      this.openAppResults = openAppResults;
    },
    clickOutside() {
      if (this.isClickOutsideEnabled) {
        this.closeSearch();
      }
    },
    closeSearch() {
      this.$emit("closeSearch");
    },
    search() {
      const cleanRegex = /[^a-zA-Z0-9]/g;
      const queryText = this.query.replace(cleanRegex, "");
      if (queryText.length < this.minChars) {
        this.results = [];
        this.showResults = false;
        return;
      }
      // search
      this.results = this.allResults.filter((option) => {
        // compare query text with all search fields of option
        return this.searchFields.some((searchField) => {
          const searchValue = option[searchField];
          if (searchValue) {
            if (Array.isArray(searchValue)) {
              // search field is an array (e.g. tags)
              return searchValue.some((elem) => {
                return new RegExp(queryText, "i").test(
                  elem.replace(cleanRegex, "")
                );
              });
            } else {
              // search field is a simple string
              return new RegExp(queryText, "i").test(
                searchValue.replace(cleanRegex, "")
              );
            }
          } else {
            return false;
          }
        });
      }, this);
      if (this.results.length) {
        // select first result
        this.selectedResult = this.results[0];
        // limit maximum number of results
        if (this.results.length > this.maxResults) {
          this.results = this.results.slice(0, this.maxResults);
        }
      }
      this.showResults = true;
    },
    onSearchInput() {
      // needed to manage clear search button
      if (!this.query.length) {
        this.search();
      }
    },
    openResult(result) {
      if (result.path) {
        this.$router.push(result.path);
        this.closeSearch();
      }
    },
    selectResult(result) {
      this.selectedResult = result;
    },
    selectNextResult() {
      const currentIndex = this.results.findIndex(
        (result) => result.path === this.selectedResult.path
      );
      const newIndex = currentIndex + 1;
      if (this.results.length > newIndex) {
        this.selectedResult = this.results[newIndex];
      } else {
        this.selectedResult = this.results[0];
      }
    },
    selectPreviousResult() {
      const currentIndex = this.results.findIndex(
        (result) => result.path === this.selectedResult.path
      );
      const newIndex = currentIndex - 1;
      if (newIndex >= 0) {
        this.selectedResult = this.results[newIndex];
      } else {
        this.selectedResult = this.results[this.results.length - 1];
      }
    },
    //// move to ui-lib
    getI18nAttribute(obj, attribute) {
      //// add vueContext param
      const langCode = this.$root.$i18n.locale;
      let attributeValue = obj[attribute][langCode];
      if (!attributeValue) {
        // fallback to english
        attributeValue = obj[attribute].en;
      }
      return attributeValue;
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
.global-search {
  width: 50%;
  background-color: $ui-05;
  color: $ui-01;
}
@media (max-width: $breakpoint-large) {
  .global-search {
    width: 75%;
  }
}
@media (max-width: $breakpoint-medium) {
  .global-search {
    position: absolute;
    top: 3rem;
    width: 100%;
  }
}
.global-search {
  animation: animate-search 0.3s ease;
}
@keyframes animate-search {
  0% {
    transform: scaleX(0);
    transform-origin: right;
  }
  100% {
    transform: scaleX(1);
    transform-origin: right;
  }
}
.global-search .search-results {
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.5);
  background-color: $ui-05;
  max-height: 60vh;
  overflow-y: auto;
}
.search-result {
  display: flex;
  justify-content: space-between;
  cursor: pointer;
  line-height: 1.29;
}
.search-result-column {
  display: flex;
  align-items: center;
  padding: $spacing-07 $spacing-05;
  width: 50%;
}
.flex {
  display: flex;
  align-items: center;
}
.search-result-column.name {
  flex-direction: column;
  align-items: stretch;
}
.search-result-column.description,
.search-result-column.category,
.source {
  color: #c6c6c6;
}
.font-weight-600 {
  font-weight: 600;
}
.source {
  display: inline-block;
  margin-top: $spacing-03;
  justify-content: flex-end;
}
.result-icon {
  margin-right: $spacing-03;
  display: none;
}
@media (max-width: $breakpoint-large) {
  .result-icon {
    display: none;
  }
}
.selected-result {
  box-shadow: inset 0px 0px 0px 2px $focus;
}
@media (max-width: $breakpoint-medium) {
  .search-result-column.description {
    text-align: right;
    justify-content: flex-end;
  }
}
</style>
⋮----
<style lang="scss">
@import "../../styles/carbon-utils";
.global-search .bx--structured-list {
  margin-bottom: 0;
}
.global-search .search-results .bx--structured-list-td {
  color: $ui-01 !important;
}
.global-search .search-results .bx--structured-list-tbody,
.global-search .search-results .empty-state {
  background-color: $ui-05 !important;
}
.global-search
  .bx--structured-list.bx--structured-list--condensed
  .bx--structured-list-td,
.global-search
  .bx--structured-list.bx--structured-list--condensed
  .bx--structured-list-th {
  padding: $spacing-05 !important;
}
.global-search .bx--structured-list-row {
  border-color: #393939;
}
.global-search .cv-structured-list-data.bx--structured-list-td {
  padding: 0;
}
</style>
</file>

<file path="core/ui/src/components/shell/HeaderGlobalMenu.vue">
<template>
  <div
    data-overflow-menu
    :class="[`cv-overflow-menu`, 'header-global-menu']"
    :id="uid"
  >
    <button
      :class="[
        `${carbonPrefix}--overflow-menu__trigger ${carbonPrefix}--tooltip__trigger`,
        `${carbonPrefix}--tooltip--a11y`,
        'bx--btn--primary',
        'bx--btn',
        'bx--btn--icon-only',
        'bx--header__action',
        {
          [`${this.carbonPrefix}--tooltip--${tipPosition}`]: label,
          [`${this.carbonPrefix}--tooltip--align-${tipAlignment}`]: label,
          [`${carbonPrefix}--overflow-menu--open`]: open,
        },
      ]"
      aria-haspopup
      type="button"
      :aria-expanded="open ? 'true' : 'false'"
      :aria-controls="`${uid}-menu`"
      :id="`${uid}-trigger`"
      ref="trigger"
      @click="doToggle"
      @keydown.space.prevent
      @keyup.space.prevent="doToggle"
      @keydown.enter.prevent="doToggle"
      @keydown.tab="onOverflowMenuTab"
    >
      <span :class="`${carbonPrefix}--assistive-text`" v-if="label && !open">{{
        label
      }}</span>
      <slot name="trigger"> </slot>
    </button>
    <div
      :class="[
        `${carbonPrefix}--overflow-menu-options`,
        {
          [`${carbonPrefix}--overflow-menu--flip`]: flipMenu,
          [`${carbonPrefix}--overflow-menu-options--open`]: open,
        },
      ]"
      tabindex="-1"
      ref="popup"
      :aria-labelledby="`${uid}-trigger`"
      :id="`${uid}-menu`"
      :style="{ left: left + 'px', top: top + 'px' }"
      @focusout="checkFocusOut"
      @mousedown.prevent="preventFocusOut"
    >
      <div
        class="cv-overflow-menu__before-content"
        ref="beforeContent"
        tabindex="0"
        style="position: absolute; height: 1px; width: 1px; left: -9999px"
        @focus="focusBeforeContent"
      />
      <ul :class="`${carbonPrefix}--overflow-menu-options__content`">
        <slot></slot>
      </ul>
      <div
        class="cv-overflow-menu__after-content"
        ref="afterContent"
        tabindex="0"
        style="position: absolute; height: 1px; width: 1px; left: -9999px"
        @focus="focusAfterContent"
      />
    </div>
  </div>
</template>
⋮----
<span :class="`${carbonPrefix}--assistive-text`" v-if="label && !open">{{
        label
      }}</span>
⋮----
<script>
import { CvOverflowMenu } from "@carbon/vue";
export default {
  name: "HeaderGlobalMenu",
  extends: CvOverflowMenu,
  props: {
    label: String,
    flipMenu: Boolean,
    up: Boolean,
    offset: {
      type: Object,
      validator(value) {
        return value && value.left !== undefined && value.top !== undefined;
      },
    },
    tipPosition: {
      type: String,
      default: "right",
      validator: (val) => ["top", "left", "bottom", "right".includes(val)],
    },
    tipAlignment: {
      type: String,
      default: "center",
      validator: (val) => ["start", "center", "end"].includes(val),
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
</style>
⋮----
<style lang="scss">
@import "../../styles/carbon-utils";
.header-global-menu .bx--tooltip__trigger svg {
  fill: currentColor !important;
}
.header-global-menu .bx--overflow-menu__trigger {
  width: 3rem;
  height: 3rem;
}
</style>
</file>

<file path="core/ui/src/components/shell/MobileSideMenu.vue">
<template>
  <transition name="slide-menu">
    <div
      v-if="isMobileSideMenuShown"
      v-click-outside="clickOutside"
      class="core-side-nav mobile-side-menu cv-side-nav bx--side-nav bx--side-nav__navigation bx--side-nav--expanded"
    >
      <SideMenuContent />
    </div>
  </transition>
</template>
⋮----
<script>
import SideMenuContent from "@/components/shell/SideMenuContent";
import { mapState, mapActions } from "vuex";
export default {
  name: "MobileSideMenu",
  components: { SideMenuContent },
  data() {
    return {
      isTransitioning: false,
    };
  },
  computed: {
    ...mapState(["isMobileSideMenuShown"]),
  },
  watch: {
    isMobileSideMenuShown: function () {
      this.isTransitioning = true;
      setTimeout(() => {
        this.isTransitioning = false;
      }, 300);
    },
  },
  methods: {
    ...mapActions(["setMobileSideMenuShownInStore"]),
    clickOutside() {
      if (!this.isTransitioning) {
        this.setMobileSideMenuShownInStore(false);
      }
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
.mobile-side-menu {
  width: $side-menu-width;
  height: calc(100vh - 3rem);
  position: fixed;
  top: 3rem;
  left: 0;
  z-index: 10000;
  overflow: auto;
}
.slide-menu-enter-active,
.slide-menu-leave-active {
  transition: all 0.3s ease;
}
.slide-menu-enter,
.slide-menu-leave-to {
  transform: translateX(-$side-menu-width);
}
</style>
</file>

<file path="core/ui/src/components/shell/NotificationDrawer.vue">
<template>
  <transition name="slide-notifications">
    <div
      v-if="isNotificationDrawerShown"
      v-click-outside="clickOutside"
      class="notification-drawer"
    >
      <h5>{{ $t("notification.notifications") }}</h5>
      <div v-if="ongoingNotifications.length" class="notification-divider">
        {{ $t("notification.ongoing") }}
      </div>
      <div v-for="notification in ongoingNotifications" :key="notification.id">
        <NsToastNotification
          :kind="notification.type"
          :title="notification.title"
          :description="notification.description"
          :lowContrast="false"
          :showCloseButton="false"
          :actionLabel="notification.actionLabel"
          :action="notification.action"
          @notificationAction="handleNotificationAction"
          @cancelTask="handleCancelTask"
          :isCancelShown="isCancelShownForNotification(notification)"
          :cancelLabel="$t('notification.abort')"
          :confirmCancelLabel="$t('notification.confirm_abort')"
          :confirmCancelText="$t('notification.confirm_cancel_text')"
          :keepRunningLabel="$t('notification.keep_running')"
          :isRead="notification.isRead"
          :progress="notification.task.progress"
          :isProgressShown="true"
          :timestamp="notification.timestamp"
          :id="notification.id"
        />
      </div>
      <div class="notification-divider">{{ $t("notification.recent") }}</div>
      <NsEmptyState
        v-if="!recentNotifications.length"
        :title="$t('notification.no_notifications')"
      >
        <template #description>{{
          $t("notification.no_notifications_description")
        }}</template>
      </NsEmptyState>
      <div
        v-else
        v-for="notification in recentNotificationsLoaded"
        :key="notification.id"
      >
        <NsToastNotification
          :kind="notification.type"
          :title="notification.title"
          :description="notification.description"
          :lowContrast="false"
          :showCloseButton="false"
          :actionLabel="notification.actionLabel"
          :action="notification.action"
          @notificationAction="handleNotificationAction"
          :isCancelShown="false"
          :cancelLabel="$t('notification.abort')"
          :confirmCancelLabel="$t('notification.confirm_abort')"
          :confirmCancelText="$t('notification.confirm_cancel_text')"
          :keepRunningLabel="$t('notification.keep_running')"
          :isRead="notification.isRead"
          :timestamp="notification.timestamp"
          :id="notification.id"
        />
      </div>
      <infinite-loading @infinite="infiniteScrollHandler"></infinite-loading>
    </div>
  </transition>
</template>
⋮----
<h5>{{ $t("notification.notifications") }}</h5>
⋮----
{{ $t("notification.ongoing") }}
⋮----
<div class="notification-divider">{{ $t("notification.recent") }}</div>
⋮----
<template #description>{{
          $t("notification.no_notifications_description")
        }}</template>
⋮----
<script>
import { mapState, mapActions, mapGetters } from "vuex";
import NotificationService from "@/mixins/notification";
export default {
  name: "NotificationDrawer",
  components: {},
  mixins: [NotificationService],
  data() {
    return {
      isNotificationDetailsShown: false,
      isTransitioning: false,
      recentNotificationsLoaded: [],
      pageNum: 0,
      pageSize: 50,
    };
  },
  computed: {
    ...mapState(["isNotificationDrawerShown"]),
    ...mapGetters([
      "unreadNotifications",
      "unreadNotificationsCount",
      "ongoingNotifications",
      "recentNotifications",
    ]),
  },
  watch: {
    isNotificationDrawerShown: function () {
      this.isTransitioning = true;
      setTimeout(() => {
        this.isTransitioning = false;
      }, 300);
    },
    recentNotifications: function () {
      this.recentNotificationsLoaded = [];
      this.pageNum = 0;
      this.infiniteScrollHandler();
    },
  },
  methods: {
    ...mapActions(["setNotificationDrawerShownInStore"]),
    notificationDetailsHidden() {
      this.isNotificationDetailsShown = false;
    },
    clickOutside() {
      if (
        !this.isTransitioning &&
        document.activeElement &&
        document.activeElement.parentElement.id !== "overflow-item"
      ) {
        this.setNotificationDrawerShownInStore(false);
      }
    },
    infiniteScrollHandler($state) {
      const pageNotifications = this.recentNotifications.slice(
        this.pageNum * this.pageSize,
        (this.pageNum + 1) * this.pageSize
      );
      if (pageNotifications.length) {
        this.pageNum++;
        this.recentNotificationsLoaded.push(...pageNotifications);
        if ($state) {
          $state.loaded();
        }
      } else {
        if ($state) {
          $state.complete();
        }
      }
    },
    isCancelShownForNotification(notification) {
      const actionsWithCancel = [
        "clone-module",
        "run-backup",
        "restore-module",
      ];
      return (
        notification.task &&
        notification.task &&
        notification.task.context &&
        actionsWithCancel.includes(notification.task.context.action)
      );
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
.slide-notifications-enter-active,
.slide-notifications-leave-active {
  transition: all 0.3s ease;
}
.slide-notifications-enter,
.slide-notifications-leave-to {
  transform: translateX($notification-drawer-width);
}
.notification-drawer {
  background-color: $ui-05;
  border-left: 1px solid $interactive-02;
  color: $ui-01;
  width: $notification-drawer-width;
  height: calc(100vh - 3rem);
  position: fixed;
  top: 3rem;
  right: 0;
  z-index: 10000;
  overflow: auto;
  padding: 1rem;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.5);
}
.close-notifications-button {
  margin: 0;
  width: auto;
  min-width: auto;
  height: auto;
  min-height: auto;
}
.notification-drawer__header {
  display: flex;
  justify-content: space-between;
  align-items: baseline;
}
.notification-divider:first-of-type {
  margin-top: $spacing-06;
}
.notification-divider {
  margin: $spacing-07 0 $spacing-03;
  padding-bottom: $spacing-02;
  border-bottom: 1px solid $text-02;
  color: $active-ui;
}
.notification-divider span {
  font-size: 0.75rem;
  font-weight: 400;
  line-height: 1.34;
  letter-spacing: 0.32px;
  color: $active-ui;
}
@media (max-width: $breakpoint-medium) {
  .slide-notifications-enter,
  .slide-notifications-leave-to {
    transform: translateX($notification-drawer-width-small-screen);
  }
  .notification-drawer {
    width: $notification-drawer-width-small-screen;
  }
}
</style>
⋮----
<style lang="scss">
@import "../../styles/carbon-utils";
.Vue-Toastification__toast {
  border-radius: 0 !important;
  min-width: $notification-drawer-width-small-screen !important;
  font-family: "IBM Plex Sans", "Helvetica Neue", Arial, sans-serif !important;
}
.Vue-Toastification__container.top-right.toastification-container {
  top: 4rem;
  z-index: 7999;
}
.Vue-Toastification__toast--default.toastification-toast {
  background-color: transparent;
  padding: 0;
}
.bx--toast-notification .bx--inline-notification__action-button.bx--btn--ghost {
  color: $inverse-link;
}
.cv-notifiation.bx--toast-notification.notification {
  min-width: 0 !important;
}
.overflow-menu-dark-bg.cv-overflow-menu .bx--tooltip__trigger svg {
  fill: $ui-01 !important;
}
.overflow-menu-dark-bg.cv-overflow-menu .bx--tooltip__trigger:hover svg,
.overflow-menu-dark-bg.cv-overflow-menu .bx--tooltip__trigger:focus svg {
  fill: $ui-01 !important;
}
.overflow-menu-dark-bg.cv-overflow-menu.bx--overflow-menu:hover,
.overflow-menu-dark-bg.cv-overflow-menu.bx--overflow-menu__trigger:hover {
  background-color: #393939 !important;
}
@media (max-width: $breakpoint-large) {
  .cv-notifiation.bx--toast-notification.notification {
    width: 20rem !important;
  }
  .notification-drawer .cv-notifiation.bx--toast-notification.notification {
    width: 100% !important;
  }
}
@media (max-width: $breakpoint-medium) {
  .cv-notifiation.bx--toast-notification.notification {
    width: 100% !important;
  }
}
</style>
</file>

<file path="core/ui/src/components/shell/ShellHeader.vue">
<template>
  <cv-header aria-label="header">
    <cv-header-menu-button
      aria-label="Header menu"
      aria-controls="side-nav"
      @click="toggleMobileSideMenuShownInStore"
    />
    <cv-skip-to-content href="#main-content">{{
      $t("shell.skip_to_content")
    }}</cv-skip-to-content>
    <cv-header-name to="/" prefix="">
      <span class="cluster-or-product-name">{{
        clusterLabel ? clusterLabel : $root.config.PRODUCT_NAME
      }}</span></cv-header-name
    >
    <cv-header-nav> </cv-header-nav>
    <template slot="header-global">
      <cv-header-global-action
        v-if="!isSearchExpanded"
        :label="$t('shell.search') + ' (CTRL+SHIFT+F)'"
        :aria-label="$t('shell.search')"
        @click="expandSearch"
      >
        <Search20 />
      </cv-header-global-action>
      <GlobalSearch v-else @closeSearch="closeSearch" />
      <cv-header-global-action
        :label="$t('notification.notifications')"
        :aria-label="$t('notification.notifications')"
        class="notifications-button"
        @click="toggleNotificationDrawerShownInStore"
      >
        <Notification20 v-if="ongoingNotificationsCount == 0" />
        <span v-else class="notifications-badge-ongoing"></span>
      </cv-header-global-action>
      <cv-header-global-action
        :label="$t('shell.app_launcher') + ' (CTRL+SHIFT+A)'"
        :aria-label="$t('shell.app_launcher')"
        @click="toggleAppDrawerShownInStore"
        tipPosition="bottom"
        tipAlignment="end"
      >
        <Switcher20 />
      </cv-header-global-action>
      <HeaderGlobalMenu
        flip-menu
        :label="loggedUser || $t('shell.account')"
        tipPosition="bottom"
        tipAlignment="end"
      >
        <template v-slot:trigger>
          <UserAvatar20 />
        </template>
        <cv-overflow-menu-item @click="goToAccountSettings">
          <NsMenuItem :label="$t('shell.account_settings')">
            <template slot="icon">
              <Settings20 />
            </template>
          </NsMenuItem>
        </cv-overflow-menu-item>
        <cv-overflow-menu-item @click="logout">
          <NsMenuItem :label="$t('shell.logout')">
            <template slot="icon">
              <Logout20 />
            </template>
          </NsMenuItem>
        </cv-overflow-menu-item>
      </HeaderGlobalMenu>
    </template>
    <AppDrawer />
    <NotificationDrawer />
  </cv-header>
</template>
⋮----
<cv-skip-to-content href="#main-content">{{
      $t("shell.skip_to_content")
    }}</cv-skip-to-content>
⋮----
<span class="cluster-or-product-name">{{
        clusterLabel ? clusterLabel : $root.config.PRODUCT_NAME
      }}</span></cv-header-name
⋮----
<template slot="header-global">
      <cv-header-global-action
        v-if="!isSearchExpanded"
        :label="$t('shell.search') + ' (CTRL+SHIFT+F)'"
        :aria-label="$t('shell.search')"
        @click="expandSearch"
      >
        <Search20 />
      </cv-header-global-action>
      <GlobalSearch v-else @closeSearch="closeSearch" />
      <cv-header-global-action
        :label="$t('notification.notifications')"
        :aria-label="$t('notification.notifications')"
        class="notifications-button"
        @click="toggleNotificationDrawerShownInStore"
      >
        <Notification20 v-if="ongoingNotificationsCount == 0" />
        <span v-else class="notifications-badge-ongoing"></span>
      </cv-header-global-action>
      <cv-header-global-action
        :label="$t('shell.app_launcher') + ' (CTRL+SHIFT+A)'"
        :aria-label="$t('shell.app_launcher')"
        @click="toggleAppDrawerShownInStore"
        tipPosition="bottom"
        tipAlignment="end"
      >
        <Switcher20 />
      </cv-header-global-action>
      <HeaderGlobalMenu
        flip-menu
        :label="loggedUser || $t('shell.account')"
        tipPosition="bottom"
        tipAlignment="end"
      >
        <template v-slot:trigger>
          <UserAvatar20 />
        </template>
        <cv-overflow-menu-item @click="goToAccountSettings">
          <NsMenuItem :label="$t('shell.account_settings')">
            <template slot="icon">
              <Settings20 />
            </template>
          </NsMenuItem>
        </cv-overflow-menu-item>
        <cv-overflow-menu-item @click="logout">
          <NsMenuItem :label="$t('shell.logout')">
            <template slot="icon">
              <Logout20 />
            </template>
          </NsMenuItem>
        </cv-overflow-menu-item>
      </HeaderGlobalMenu>
    </template>
⋮----
<template v-slot:trigger>
          <UserAvatar20 />
        </template>
⋮----
<template slot="icon">
              <Settings20 />
            </template>
⋮----
<template slot="icon">
              <Logout20 />
            </template>
⋮----
<script>
import Notification20 from "@carbon/icons-vue/es/notification/20";
import UserAvatar20 from "@carbon/icons-vue/es/user--avatar/20";
import Switcher20 from "@carbon/icons-vue/es/switcher/20";
import Search20 from "@carbon/icons-vue/es/search/20";
import Logout20 from "@carbon/icons-vue/es/logout/20";
import { mapState, mapActions, mapGetters } from "vuex";
import GlobalSearch from "@/components/shell/GlobalSearch";
import AppDrawer from "@/components/shell/AppDrawer";
import LoginService from "@/mixins/login";
import WebSocketService from "@/mixins/websocket";
import NotificationDrawer from "@/components/shell/NotificationDrawer";
import { StorageService } from "@nethserver/ns8-ui-lib";
import HeaderGlobalMenu from "@/components/shell/HeaderGlobalMenu";
import Settings20 from "@carbon/icons-vue/es/settings/20";
export default {
  name: "ShellHeader",
  components: {
    Notification20,
    UserAvatar20,
    Switcher20,
    Search20,
    Logout20,
    GlobalSearch,
    AppDrawer,
    NotificationDrawer,
    HeaderGlobalMenu,
    Settings20,
  },
  mixins: [StorageService, LoginService, WebSocketService],
  data() {
    return {};
  },
  computed: {
    ...mapState([
      "notifications",
      "isSearchExpanded",
      "clusterLabel",
      "loggedUser",
    ]),
    ...mapGetters(["unreadNotificationsCount", "ongoingNotificationsCount"]),
  },
  methods: {
    ...mapActions([
      "toggleMobileSideMenuShownInStore",
      "toggleAppDrawerShownInStore",
      "toggleNotificationDrawerShownInStore",
      "setSearchExpandedInStore",
    ]),
    logout() {
      this.$root.$emit("logout");
    },
    expandSearch() {
      this.setSearchExpandedInStore(true);
    },
    closeSearch() {
      this.setSearchExpandedInStore(false);
    },
    goToClusterStatus() {
      this.$router.push("/status");
    },
    goToAccountSettings() {
      this.$router.push("/settings/account");
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
.notifications-button {
  position: relative;
}
.notifications-badge-ongoing {
  position: absolute;
  inset: 13px;
  border: 2px solid transparent;
  border-radius: 50%;
  border-top: 2px solid $ui-02;
  border-right: 2px solid $ui-02;
  border-bottom: 2px solid $ui-02;
  animation: ongoing-task-spin 0.5s linear infinite;
}
@keyframes ongoing-task-spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
@media (max-width: $breakpoint-medium) {
  .cluster-or-product-name {
    max-width: 23vw;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
</style>
</file>

<file path="core/ui/src/components/shell/SideMenu.vue">
<template>
  <cv-side-nav
    id="side-nav"
    :fixed="!isExternalApp"
    :expanded="!isExternalApp"
    :rail="isExternalApp"
    class="core-side-nav"
  >
    <SideMenuContent />
  </cv-side-nav>
</template>
⋮----
<script>
import SideMenuContent from "@/components/shell/SideMenuContent";
export default {
  name: "SideMenu",
  components: { SideMenuContent },
  computed: {
    isExternalApp() {
      return this.$route.path.includes("/apps/");
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
@media (max-width: $breakpoint-large) {
  #side-nav {
    display: none;
  }
}
</style>
⋮----
<style lang="scss">
@import "../../styles/carbon-utils";
.core-side-nav.bx--side-nav {
  background-color: $ui-05;
  color: $ui-01;
}
.core-side-nav .bx--side-nav__submenu {
  color: $ui-01;
}
.core-side-nav a.bx--side-nav__link > .bx--side-nav__link-text,
.core-side-nav.bx--side-nav a.bx--header__menu-item .bx--text-truncate-end {
  color: $ui-01;
}
.core-side-nav .bx--side-nav__menu a.bx--side-nav__link--current > span,
.core-side-nav
  .bx--side-nav__menu
  a.bx--side-nav__link[aria-current="page"]
  > span,
.core-side-nav a.bx--side-nav__link--current > span {
  color: $ui-01;
}
.core-side-nav .bx--side-nav__icon > svg {
  width: 20px;
  height: 20px;
  fill: $ui-01;
}
.core-side-nav .bx--side-nav__menu a.bx--side-nav__link--current,
.core-side-nav .bx--side-nav__menu a.bx--side-nav__link[aria-current="page"],
.core-side-nav a.bx--side-nav__link--current {
  background-color: $interactive-02;
}
.core-side-nav .bx--side-nav__submenu:hover {
  color: $ui-01;
  background-color: $interactive-02;
}
.core-side-nav
  .bx--side-nav__item:not(.bx--side-nav__item--active):hover
  .bx--side-nav__item:not(.bx--side-nav__item--active)
  > .bx--side-nav__submenu:hover,
.core-side-nav
  .bx--side-nav__item:not(.bx--side-nav__item--active)
  > .bx--side-nav__link:hover,
.core-side-nav
  .bx--side-nav__menu
  a.bx--side-nav__link:not(.bx--side-nav__link--current):not(
    [aria-current="page"]
  ):hover,
.core-side-nav .bx--side-nav a.bx--header__menu-item:hover,
.core-side-nav
  .bx--side-nav
  .bx--header__menu-title[aria-expanded="true"]:hover {
  color: $ui-01;
  background-color: $interactive-02;
}
.core-side-nav
  .bx--side-nav__item:not(.bx--side-nav__item--active)
  > .bx--side-nav__link:hover
  > span,
.core-side-nav
  .bx--side-nav__item:not(.bx--side-nav__item--active)
  .bx--side-nav__menu-item
  > .bx--side-nav__link:hover
  > span {
  color: $ui-01;
}
.core-side-nav a.bx--side-nav__link[aria-current="page"]::before,
.core-side-nav a.bx--side-nav__link--current::before {
  background-color: $inverse-support-04;
}
.core-side-nav .bx--side-nav__submenu {
  height: 3rem;
}
.core-side-nav .cv-side-nav-item-link.bx--side-nav__link {
  height: 3rem;
}
.core-side-nav a.bx--side-nav__link[aria-current="page"],
.core-side-nav a.bx--side-nav__link--current {
  background-color: $inverse-02;
}
.core-side-nav
  a.bx--side-nav__link[aria-current="page"]
  .bx--side-nav__link-text,
.core-side-nav a.bx--side-nav__link--current .bx--side-nav__link-text {
  color: $ui-01;
}
.core-side-nav .bx--side-nav--rail {
  width: $side-menu-collapsed-width;
}
.core-side-nav .bx--side-nav__divider {
  background-color: $inverse-02;
}
</style>
</file>

<file path="core/ui/src/components/shell/SideMenuContent.vue">
<template>
  <div>
    <cv-side-nav-items>
      <cv-side-nav-link
        @click="goTo('/status')"
        :active="isLinkActive('/status')"
      >
        <template v-slot:nav-icon><Activity20 /></template>
        <span>{{ $t("cluster_status.title") }}</span>
      </cv-side-nav-link>
      <cv-side-nav-link
        @click="goTo('/nodes')"
        :active="isLinkActive('/nodes')"
      >
        <template v-slot:nav-icon><Chip20 /></template>
        <span>{{ $t("nodes.title") }}</span>
      </cv-side-nav-link>
      <cv-side-nav-divider />
      <cv-side-nav-link
        @click="goTo('/domains')"
        :active="isLinkActive('/domains')"
      >
        <template v-slot:nav-icon><Events20 /></template>
        <span>{{ $t("domains.title") }}</span>
      </cv-side-nav-link>
      <cv-side-nav-link
        @click="goTo('/software-center')"
        :active="isLinkActive('/software-center')"
      >
        <template v-slot:nav-icon><ShoppingCatalog20 /></template>
        <span>{{ $t("software_center.title") }}</span>
      </cv-side-nav-link>
      <cv-side-nav-link
        @click="goTo('/applications-center')"
        :active="isLinkActive('/applications-center')"
      >
        <template v-slot:nav-icon><Application20 /></template>
        <span>{{ $t("applications.title") }}</span>
      </cv-side-nav-link>
      <cv-side-nav-link
        @click="goTo('/backup')"
        :active="isLinkActive('/backup')"
      >
        <template v-slot:nav-icon><Save20 /></template>
        {{ $t("backup.title") }}
      </cv-side-nav-link>
      <cv-side-nav-divider />
      <cv-side-nav-link
        @click="goTo('/system-logs')"
        :active="isLinkActive('/#/system-logs')"
      >
        <template v-slot:nav-icon><Catalog20 /></template>
        {{ $t("system_logs.title") }}
      </cv-side-nav-link>
      <cv-side-nav-link
        @click="goTo('/audit-trail')"
        :active="isLinkActive('/audit-trail')"
      >
        <template v-slot:nav-icon><Police20 /></template>
        {{ $t("audit_trail.title") }}
      </cv-side-nav-link>
      <cv-side-nav-link
        @click="goTo('/settings')"
        :active="isLinkActive('/settings')"
      >
        <template v-slot:nav-icon><Settings20 /></template>
        {{ $t("settings.title") }}
      </cv-side-nav-link>
      <cv-side-nav-link
        @click="goTo('/about')"
        :active="isLinkActive('/about')"
      >
        <template v-slot:nav-icon><Information20 /></template>
        {{ $t("about.title") }}
      </cv-side-nav-link>
    </cv-side-nav-items>
  </div>
</template>
⋮----
<template v-slot:nav-icon><Activity20 /></template>
<span>{{ $t("cluster_status.title") }}</span>
⋮----
<template v-slot:nav-icon><Chip20 /></template>
<span>{{ $t("nodes.title") }}</span>
⋮----
<template v-slot:nav-icon><Events20 /></template>
<span>{{ $t("domains.title") }}</span>
⋮----
<template v-slot:nav-icon><ShoppingCatalog20 /></template>
<span>{{ $t("software_center.title") }}</span>
⋮----
<template v-slot:nav-icon><Application20 /></template>
<span>{{ $t("applications.title") }}</span>
⋮----
<template v-slot:nav-icon><Save20 /></template>
{{ $t("backup.title") }}
⋮----
<template v-slot:nav-icon><Catalog20 /></template>
{{ $t("system_logs.title") }}
⋮----
<template v-slot:nav-icon><Police20 /></template>
{{ $t("audit_trail.title") }}
⋮----
<template v-slot:nav-icon><Settings20 /></template>
{{ $t("settings.title") }}
⋮----
<template v-slot:nav-icon><Information20 /></template>
{{ $t("about.title") }}
⋮----
<script>
import Events20 from "@carbon/icons-vue/es/events/20";
import Save20 from "@carbon/icons-vue/es/save/20";
import Settings20 from "@carbon/icons-vue/es/settings/20";
import Catalog20 from "@carbon/icons-vue/es/catalog/20";
import Application20 from "@carbon/icons-vue/es/application/20";
import Activity20 from "@carbon/icons-vue/es/activity/20";
import Chip20 from "@carbon/icons-vue/es/chip/20";
import Information20 from "@carbon/icons-vue/es/information/20";
import Police20 from "@carbon/icons-vue/es/police/20";
import ShoppingCatalog20 from "@carbon/icons-vue/es/shopping--catalog/20";
import { mapActions } from "vuex";
import CvSideNavDivider from "@carbon/vue/src/components/cv-ui-shell/cv-side-nav-divider.vue";
export default {
  name: "SideMenuContent",
  components: {
    Save20,
    Events20,
    Catalog20,
    Settings20,
    Application20,
    Activity20,
    Chip20,
    Information20,
    CvSideNavDivider,
    Police20,
    ShoppingCatalog20,
  },
  data() {
    return {};
  },
  methods: {
    ...mapActions(["setMobileSideMenuShownInStore"]),
    isLinkActive(path) {
      return this.$route.path.includes(path);
    },
    goTo(path) {
      if (this.$route.fullPath !== path) {
        this.$router.push(path);
      }
      this.setMobileSideMenuShownInStore(false);
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
</style>
</file>

<file path="core/ui/src/components/software-center/AdditionalVolumesSelector.vue">
<template>
  <div class="volume-selector">
    <div class="volume-list">
      <div v-if="loading">
        <cv-tile
          v-for="index in 2"
          :key="index"
          :light="light"
          class="volume-tile"
        >
          <cv-skeleton-text
            :paragraph="true"
            :line-count="3"
          ></cv-skeleton-text>
        </cv-tile>
      </div>
      <NsEmptyState
        v-else-if="!additionalVolumes.length"
        :title="$t('software_center.no_volumes_to_restore')"
      />
      <NsTile
        v-else
        v-for="(volume, index) of additionalVolumes"
        :key="index"
        :light="light"
        kind="selectable"
        v-model="volume.selected"
        value="snapshotValue"
        @click="deselectOtherVolumes(volume)"
        class="volume-tile"
        :footerIcon="VmdkDisk20"
      >
        <div class="mg-bottom-md">
          <strong v-if="volume.default">
            {{ $t("software_center.default_storage") }}
          </strong>
          <strong v-else>
            {{ volume.label ? volume.label : volume.ui_name }}
          </strong>
        </div>
        <div class="mg-bottom-sm">{{ volume.path }}</div>
        <div class="mg-bottom-sm">
          {{ $t("software_center.volume_usage", getVolumeInfo(volume)) }}
        </div>
        <NsProgressBar
          :value="loading ? 0 : volume.usage"
          :loading="loading"
          :warningThreshold="70"
          :dangerThreshold="90"
          :height="'5px'"
          :useHealthyColor="false"
          class="mg-bottom-lg"
        />
      </NsTile>
    </div>
  </div>
</template>
⋮----
{{ $t("software_center.default_storage") }}
⋮----
{{ volume.label ? volume.label : volume.ui_name }}
⋮----
<div class="mg-bottom-sm">{{ volume.path }}</div>
⋮----
{{ $t("software_center.volume_usage", getVolumeInfo(volume)) }}
⋮----
<script>
import { UtilService, DateTimeService } from "@nethserver/ns8-ui-lib";
import _cloneDeep from "lodash/cloneDeep";
import VmdkDisk20 from "@carbon/icons-vue/es/vmdk-disk/16";
export default {
  name: "AdditionalVolumesSelector",
  components: {},
  mixins: [UtilService, DateTimeService],
  props: {
    volumes: {
      type: Array,
      required: true,
    },
    loading: {
      type: Boolean,
      default: false,
    },
    light: Boolean,
  },
  data() {
    return {
      VmdkDisk20,
      additionalVolumes: [],
    };
  },
  computed: {
    selectedVolume() {
      return this.additionalVolumes.find((i) => i.selected);
    },
  },
  watch: {
    selectedVolume: function () {
      this.$emit("selectVolume", this.selectedVolume);
    },
    volumes: function () {
      this.updateInternalVolumes();
    },
  },
  created() {
    this.updateInternalVolumes();
  },
  methods: {
    getVolumeInfo(volume) {
      return {
        available: this.$options.filters.byteFormat(volume.available),
        used: this.$options.filters.byteFormat(volume.used),
        total: this.$options.filters.byteFormat(volume.size || volume.total),
        percentage: volume.usage,
      };
    },
    updateInternalVolumes() {
      let additionalVolumes = _cloneDeep(this.volumes);
      additionalVolumes.forEach((volume, index) => {
        volume.selected = index === 0;
        const total = Number(volume.size || volume.total);
        const avail = Number(volume.available);
        volume.usage =
          total > 0 && Number.isFinite(avail)
            ? Math.round(((total - avail) / total) * 100)
            : 0;
      });
      this.additionalVolumes = additionalVolumes;
    },
    deselectOtherVolumes(volume) {
      for (let s of this.additionalVolumes) {
        if (s.path !== volume.path) {
          s.selected = false;
        }
      }
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
.volume-selector {
  display: flex;
  flex-direction: column;
}
.volume-list {
  overflow-y: auto;
  max-height: 30rem;
}
.ns-tile.volume-tile,
.cv-tile.volume-tile {
  margin-bottom: $spacing-03;
}
.secondary-row {
  margin-top: $spacing-02;
  color: $ui-04;
}
</style>
</file>

<file path="core/ui/src/components/software-center/AppInfoModal.vue">
<template>
  <div v-if="app">
    <NsModal
      size="default"
      :visible="isShown"
      @modal-hidden="$emit('close')"
      class="no-pad-modal"
    >
      <template slot="title">{{ $t("software_center.app_info") }}</template>
      <template v-if="isShown" slot="content">
        <div class="mg-bottom-md">
          <div class="logo-and-name">
            <div class="app-logo">
              <img
                :src="
                  app.logo
                    ? app.logo
                    : require('@/assets/module_default_logo.png')
                "
                :alt="app.name + ' logo'"
              />
            </div>
            <div class="app-name">
              <h3 data-modal-primary-focus>{{ app.name || app.id }}</h3>
            </div>
          </div>
        </div>
        <div v-if="app.screenshots.length" class="mg-bottom-md">
          <div class="screenshots">
            <ImageGallery :fullScreen="true" :images="app.screenshots" />
          </div>
        </div>
        <div class="description">
          {{ getApplicationDescription(app) }}
        </div>
        <NsInlineNotification
          v-if="app.rootfull && app.certification_level < 3"
          kind="warning"
          :title="$t('software_center.rootfull_app_warning_title')"
          :description="
            $t('software_center.rootfull_app_warning_description', {
              appName: app.name,
            })
          "
          :showCloseButton="false"
        />
        <div class="key-value-setting">
          <span class="label">
            {{ $t("software_center.certification") }}
          </span>
          <span class="value">
            <CertificationLevelBadge :level="app.certification_level" />
          </span>
        </div>
        <div class="key-value-setting">
          <div>
            <span class="label">{{
              $tc("software_center.categories", app.categories.length)
            }}</span>
            <span class="value">
              {{ getApplicationCategories(app) }}
            </span>
          </div>
        </div>
        <div class="key-value-setting">
          <div>
            <span class="label">
              {{ $t("software_center.latest_version") }}
            </span>
            <span class="value">
              {{
                app.versions.length
                  ? app.versions[0].tag
                  : $t("common.not_available")
              }}
              <span v-if="app.upstream_name"> ({{ app.upstream_name }}) </span>
            </span>
          </div>
        </div>
        <div class="key-value-setting">
          <div>
            <span class="label">{{ $t("software_center.repository") }}</span>
            <span class="value">
              {{ app.repository || "-" }}
            </span>
          </div>
        </div>
        <div class="key-value-setting">
          <span class="label"
            >{{ $tc("software_center.authors", app.authors.length) }}
          </span>
          <span class="value">
            <span v-if="app.authors.length == 1">
              <cv-link :href="'mailto:' + app.authors[0].email" target="_blank">
                {{ app.authors[0].name }}
              </cv-link>
            </span>
            <ul v-else>
              <li v-for="(author, index) in app.authors" :key="index">
                <cv-link :href="'mailto:' + author.email" target="_blank">
                  {{ author.name }}
                </cv-link>
              </li>
            </ul>
          </span>
        </div>
        <div class="key-value-setting">
          <div>
            <span class="label">
              {{ $t("software_center.images_label") }}
            </span>
            <span class="value">
              <ul class="image-list unordered-list">
                <li>
                  {{ app.source }}:{{
                    app.versions.length ? app.versions[0].tag : "-"
                  }}
                </li>
                <li v-for="(image, index) in appImages" :key="index">
                  {{ image }}
                </li>
              </ul>
            </span>
          </div>
        </div>
        <div v-if="appPermissions.length" class="key-value-setting">
          <div>
            <span class="label">
              {{ $t("software_center.permissions_label") }}
            </span>
          </div>
          <NsTile :light="true" class="permission-tile">
            <NsDataTable
              :allRows="appPermissions"
              :columns="permissionColumnLabels"
              :rawColumns="permissionColumns"
              :sortable="true"
              :pageSizes="[10, 25, 50, 100]"
              :itemsPerPageLabel="$t('pagination.items_per_page')"
              :rangeOfTotalItemsLabel="$t('pagination.range_of_total_items')"
              :ofTotalPagesLabel="$t('pagination.of_total_pages')"
              :backwardText="$t('pagination.previous_page')"
              :forwardText="$t('pagination.next_page')"
              :pageNumberLabel="$t('pagination.page_number')"
              @updatePage="permissionTablePage = $event"
            >
              <template slot="data">
                <cv-data-table-row
                  v-for="perm in permissionTablePage"
                  :key="perm.raw"
                  :value="perm.raw"
                >
                  <cv-data-table-cell>{{
                    perm.description
                  }}</cv-data-table-cell>
                  <cv-data-table-cell>{{ perm.target }}</cv-data-table-cell>
                  <cv-data-table-cell>{{ perm.raw }}</cv-data-table-cell>
                </cv-data-table-row>
              </template>
            </NsDataTable>
          </NsTile>
        </div>
        <div class="info-divider"></div>
        <div class="key-value-setting">
          <div>
            <span>
              <cv-link :href="app.docs.documentation_url" target="_blank">
                {{ $t("software_center.documentation") }}
              </cv-link>
            </span>
            &bull;
            <span>
              <cv-link :href="app.docs.bug_url" target="_blank">
                {{ $t("software_center.bugs") }}
              </cv-link>
            </span>
            &bull;
            <span>
              <cv-link :href="app.docs.code_url" target="_blank">
                {{ $t("software_center.source_code") }}
              </cv-link>
            </span>
            <template v-if="app.docs.terms_url">
              &bull;
              <span>
                <cv-link :href="app.docs.terms_url" target="_blank">
                  {{ $t("common.terms_and_conditions") }}
                </cv-link>
              </span>
            </template>
            <template v-if="app.docs.relnotes_url">
              &bull;
              <span>
                <cv-link :href="app.docs.relnotes_url" target="_blank">
                  {{ $t("common.release_notes") }}
                </cv-link>
              </span>
            </template>
          </div>
        </div>
      </template>
      <template slot="secondary-button">{{ $t("common.close") }}</template>
    </NsModal>
  </div>
</template>
⋮----
<template slot="title">{{ $t("software_center.app_info") }}</template>
⋮----
<template v-if="isShown" slot="content">
        <div class="mg-bottom-md">
          <div class="logo-and-name">
            <div class="app-logo">
              <img
                :src="
                  app.logo
                    ? app.logo
                    : require('@/assets/module_default_logo.png')
                "
                :alt="app.name + ' logo'"
              />
            </div>
            <div class="app-name">
              <h3 data-modal-primary-focus>{{ app.name || app.id }}</h3>
            </div>
          </div>
        </div>
        <div v-if="app.screenshots.length" class="mg-bottom-md">
          <div class="screenshots">
            <ImageGallery :fullScreen="true" :images="app.screenshots" />
          </div>
        </div>
        <div class="description">
          {{ getApplicationDescription(app) }}
        </div>
        <NsInlineNotification
          v-if="app.rootfull && app.certification_level < 3"
          kind="warning"
          :title="$t('software_center.rootfull_app_warning_title')"
          :description="
            $t('software_center.rootfull_app_warning_description', {
              appName: app.name,
            })
          "
          :showCloseButton="false"
        />
        <div class="key-value-setting">
          <span class="label">
            {{ $t("software_center.certification") }}
          </span>
          <span class="value">
            <CertificationLevelBadge :level="app.certification_level" />
          </span>
        </div>
        <div class="key-value-setting">
          <div>
            <span class="label">{{
              $tc("software_center.categories", app.categories.length)
            }}</span>
            <span class="value">
              {{ getApplicationCategories(app) }}
            </span>
          </div>
        </div>
        <div class="key-value-setting">
          <div>
            <span class="label">
              {{ $t("software_center.latest_version") }}
            </span>
            <span class="value">
              {{
                app.versions.length
                  ? app.versions[0].tag
                  : $t("common.not_available")
              }}
              <span v-if="app.upstream_name"> ({{ app.upstream_name }}) </span>
            </span>
          </div>
        </div>
        <div class="key-value-setting">
          <div>
            <span class="label">{{ $t("software_center.repository") }}</span>
            <span class="value">
              {{ app.repository || "-" }}
            </span>
          </div>
        </div>
        <div class="key-value-setting">
          <span class="label"
            >{{ $tc("software_center.authors", app.authors.length) }}
          </span>
          <span class="value">
            <span v-if="app.authors.length == 1">
              <cv-link :href="'mailto:' + app.authors[0].email" target="_blank">
                {{ app.authors[0].name }}
              </cv-link>
            </span>
            <ul v-else>
              <li v-for="(author, index) in app.authors" :key="index">
                <cv-link :href="'mailto:' + author.email" target="_blank">
                  {{ author.name }}
                </cv-link>
              </li>
            </ul>
          </span>
        </div>
        <div class="key-value-setting">
          <div>
            <span class="label">
              {{ $t("software_center.images_label") }}
            </span>
            <span class="value">
              <ul class="image-list unordered-list">
                <li>
                  {{ app.source }}:{{
                    app.versions.length ? app.versions[0].tag : "-"
                  }}
                </li>
                <li v-for="(image, index) in appImages" :key="index">
                  {{ image }}
                </li>
              </ul>
            </span>
          </div>
        </div>
        <div v-if="appPermissions.length" class="key-value-setting">
          <div>
            <span class="label">
              {{ $t("software_center.permissions_label") }}
            </span>
          </div>
          <NsTile :light="true" class="permission-tile">
            <NsDataTable
              :allRows="appPermissions"
              :columns="permissionColumnLabels"
              :rawColumns="permissionColumns"
              :sortable="true"
              :pageSizes="[10, 25, 50, 100]"
              :itemsPerPageLabel="$t('pagination.items_per_page')"
              :rangeOfTotalItemsLabel="$t('pagination.range_of_total_items')"
              :ofTotalPagesLabel="$t('pagination.of_total_pages')"
              :backwardText="$t('pagination.previous_page')"
              :forwardText="$t('pagination.next_page')"
              :pageNumberLabel="$t('pagination.page_number')"
              @updatePage="permissionTablePage = $event"
            >
              <template slot="data">
                <cv-data-table-row
                  v-for="perm in permissionTablePage"
                  :key="perm.raw"
                  :value="perm.raw"
                >
                  <cv-data-table-cell>{{
                    perm.description
                  }}</cv-data-table-cell>
                  <cv-data-table-cell>{{ perm.target }}</cv-data-table-cell>
                  <cv-data-table-cell>{{ perm.raw }}</cv-data-table-cell>
                </cv-data-table-row>
              </template>
            </NsDataTable>
          </NsTile>
        </div>
        <div class="info-divider"></div>
        <div class="key-value-setting">
          <div>
            <span>
              <cv-link :href="app.docs.documentation_url" target="_blank">
                {{ $t("software_center.documentation") }}
              </cv-link>
            </span>
            &bull;
            <span>
              <cv-link :href="app.docs.bug_url" target="_blank">
                {{ $t("software_center.bugs") }}
              </cv-link>
            </span>
            &bull;
            <span>
              <cv-link :href="app.docs.code_url" target="_blank">
                {{ $t("software_center.source_code") }}
              </cv-link>
            </span>
            <template v-if="app.docs.terms_url">
              &bull;
              <span>
                <cv-link :href="app.docs.terms_url" target="_blank">
                  {{ $t("common.terms_and_conditions") }}
                </cv-link>
              </span>
            </template>
            <template v-if="app.docs.relnotes_url">
              &bull;
              <span>
                <cv-link :href="app.docs.relnotes_url" target="_blank">
                  {{ $t("common.release_notes") }}
                </cv-link>
              </span>
            </template>
          </div>
        </div>
      </template>
⋮----
<h3 data-modal-primary-focus>{{ app.name || app.id }}</h3>
⋮----
{{ getApplicationDescription(app) }}
⋮----
{{ $t("software_center.certification") }}
⋮----
<span class="label">{{
              $tc("software_center.categories", app.categories.length)
            }}</span>
⋮----
{{ getApplicationCategories(app) }}
⋮----
{{ $t("software_center.latest_version") }}
⋮----
{{
                app.versions.length
                  ? app.versions[0].tag
                  : $t("common.not_available")
              }}
<span v-if="app.upstream_name"> ({{ app.upstream_name }}) </span>
⋮----
<span class="label">{{ $t("software_center.repository") }}</span>
⋮----
{{ app.repository || "-" }}
⋮----
>{{ $tc("software_center.authors", app.authors.length) }}
⋮----
{{ app.authors[0].name }}
⋮----
{{ author.name }}
⋮----
{{ $t("software_center.images_label") }}
⋮----
{{ app.source }}:{{
⋮----
{{ image }}
⋮----
{{ $t("software_center.permissions_label") }}
⋮----
<template slot="data">
                <cv-data-table-row
                  v-for="perm in permissionTablePage"
                  :key="perm.raw"
                  :value="perm.raw"
                >
                  <cv-data-table-cell>{{
                    perm.description
                  }}</cv-data-table-cell>
                  <cv-data-table-cell>{{ perm.target }}</cv-data-table-cell>
                  <cv-data-table-cell>{{ perm.raw }}</cv-data-table-cell>
                </cv-data-table-row>
              </template>
⋮----
<cv-data-table-cell>{{
                    perm.description
                  }}</cv-data-table-cell>
<cv-data-table-cell>{{ perm.target }}</cv-data-table-cell>
<cv-data-table-cell>{{ perm.raw }}</cv-data-table-cell>
⋮----
{{ $t("software_center.documentation") }}
⋮----
{{ $t("software_center.bugs") }}
⋮----
{{ $t("software_center.source_code") }}
⋮----
<template v-if="app.docs.terms_url">
              &bull;
              <span>
                <cv-link :href="app.docs.terms_url" target="_blank">
                  {{ $t("common.terms_and_conditions") }}
                </cv-link>
              </span>
            </template>
⋮----
{{ $t("common.terms_and_conditions") }}
⋮----
<template v-if="app.docs.relnotes_url">
              &bull;
              <span>
                <cv-link :href="app.docs.relnotes_url" target="_blank">
                  {{ $t("common.release_notes") }}
                </cv-link>
              </span>
            </template>
⋮----
{{ $t("common.release_notes") }}
⋮----
<template slot="secondary-button">{{ $t("common.close") }}</template>
⋮----
<script>
import { UtilService } from "@nethserver/ns8-ui-lib";
import ImageGallery from "./ImageGallery";
import CertificationLevelBadge from "./CertificationLevelBadge.vue";
export default {
  name: "AppInfoModal",
  components: { ImageGallery, CertificationLevelBadge },
  mixins: [UtilService],
  props: {
    isShown: Boolean,
    app: { type: [Object, null] },
  },
  data() {
    return {
      permissionColumns: ["description", "target", "raw"],
      permissionTablePage: [],
    };
  },
  computed: {
    permissionColumnLabels() {
      return [
        this.$t("software_center.permission_description"),
        this.$t("software_center.permission_target"),
        this.$t("software_center.permission_label"),
      ];
    },
    appImages() {
      if (
        this.app &&
        this.app.versions.length &&
        this.app.versions[0]["labels"]["org.nethserver.images"]
      ) {
        return this.app.versions[0]["labels"]["org.nethserver.images"]
          .trim()
          .replace(/\s+/g, " ")
          .split(" ");
      } else {
        return [];
      }
    },
    appPermissions() {
      if (!this.app) {
        return [];
      }
      const permissions = [];
      if (this.app.rootfull) {
        permissions.push({
          raw: "org.nethserver.rootfull",
          description: this.$t("software_center.app_permission_rootfull"),
          target: this.$t("software_center.app_permission_targets.node"),
        });
      }
      if (!this.app.versions.length) {
        return permissions;
      }
      const labels = this.app.versions[0]["labels"];
      const label = (labels && labels["org.nethserver.authorizations"]) || "";
      // core keeps only the last entry of a repeated selector, roles are not merged
      const rolesBySelector = new Map();
      for (const entry of label.trim().split(/\s+/)) {
        const sep = entry.indexOf(":");
        if (sep < 1) {
          continue;
        }
        const selector = entry.slice(0, sep);
        rolesBySelector.delete(selector);
        rolesBySelector.set(selector, entry.slice(sep + 1).split(","));
      }
      for (const [selector, roles] of rolesBySelector) {
        const at = selector.indexOf("@");
        const module = at < 0 ? selector : selector.slice(0, at);
        const scope = at < 0 ? "" : selector.slice(at + 1);
        for (const role of new Set(roles)) {
          // core grants self:selfadm to every app, it gives nothing on other components
          if (!role || (module === "self" && role === "selfadm")) {
            continue;
          }
          permissions.push(
            this.describePermission(module, scope, role, `${selector}:${role}`)
          );
        }
      }
      return permissions;
    },
  },
  methods: {
    getApplicationDescription(app) {
      return this.getAppDescription(app, this);
    },
    getApplicationCategories(app) {
      return this.getAppCategories(app, this);
    },
    describePermission(module, scope, role, raw) {
      const nodeId = !scope && /^\d+$/.test(module) ? module : "";
      const agentType = nodeId ? "node" : module;
      const resolved = scope || agentType === "node" || agentType === "cluster";
      const moduleName = module.charAt(0).toUpperCase() + module.slice(1);
      const pairKey = `software_center.app_permissions.${agentType}_${role}`;
      const coreRoleKey = `software_center.app_permission_core_roles.${role}`;
      let description;
      if (resolved && this.$te(pairKey)) {
        description = this.$t(pairKey);
      } else if (resolved && this.$te(coreRoleKey)) {
        description = this.$t(coreRoleKey, { module: moduleName });
      } else {
        description = this.$t("software_center.app_permission_generic", {
          role,
          module: moduleName,
        });
      }
      let target = moduleName;
      if (nodeId) {
        target = this.$t("software_center.app_permission_targets.node_id", {
          id: nodeId,
        });
      } else {
        const targetKey = scope
          ? `software_center.app_permission_scopes.${scope}`
          : `software_center.app_permission_targets.${module}`;
        if (this.$te(targetKey)) {
          target = this.$t(targetKey, { module: moduleName });
        }
      }
      return { raw, description, target };
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
.logo-and-name {
  display: flex;
  align-items: center;
  margin-top: $spacing-05;
  margin-bottom: $spacing-05;
}
.app-logo {
  width: 4rem;
  height: 4rem;
  margin-right: $spacing-05;
  flex-shrink: 0;
}
.app-logo img {
  width: 100%;
  height: 100%;
}
.description {
  margin-bottom: $spacing-06;
}
.info-divider {
  margin-top: $spacing-02;
  margin-bottom: $spacing-03;
  border-bottom: 1px solid $ui-04;
}
.image-list {
  margin-left: $spacing-03;
}
.permission-tile {
  margin-top: $spacing-03;
  margin-left: $spacing-03;
}
</style>
</file>

<file path="core/ui/src/components/software-center/AppList.vue">
<template>
  <div>
    <div class="app-list">
      <div
        v-if="skeleton"
        class="card-grid grid-cols-1 sm:grid-cols-2 2xl:grid-cols-3 3xl:grid-cols-4"
      >
        <cv-tile
          v-for="index in 8"
          :key="index"
          kind="standard"
          class="app"
          :light="light"
        >
          <cv-skeleton-text
            :paragraph="true"
            :line-count="7"
            heading
          ></cv-skeleton-text>
        </cv-tile>
      </div>
      <div
        v-else
        class="card-grid grid-cols-1 sm:grid-cols-2 2xl:grid-cols-3 3xl:grid-cols-4"
      >
        <cv-tile
          v-for="(app, index) in apps"
          :key="index"
          kind="standard"
          class="app"
          :light="light"
          :id="app.id"
        >
          <div class="app-logo app-row">
            <a v-if="app.id !== 'core'" @click="showAppInfo(app)">
              <img
                :src="
                  app.logo
                    ? app.logo
                    : require('@/assets/module_default_logo.png')
                "
                :alt="app.name + ' logo'"
              />
            </a>
            <img
              v-else
              :src="
                app.logo
                  ? app.logo
                  : require('@/assets/module_default_logo.png')
              "
              :alt="app.name + ' logo'"
            />
          </div>
          <div class="app-name app-row">
            <a v-if="app.id !== 'core'" @click="showAppInfo(app)">{{
              app.name
            }}</a>
            <span v-else>{{ app.name }}</span>
          </div>
          <div v-if="app.id !== 'core'" class="app-row">
            <CertificationLevelBadge :level="app.certification_level" />
          </div>
          <div
            v-if="app.categories && getApplicationCategories(app).length"
            class="app-categories app-row"
          >
            <span
              v-for="(category, index) in getApplicationCategories(app)"
              :key="category"
            >
              {{ category }}
              <span v-if="index < getApplicationCategories(app).length - 1"
                >&bull;</span
              >
            </span>
          </div>
          <div v-if="app.id == 'core'" class="app-row">
            <NsButton
              kind="ghost"
              :icon="ArrowRight20"
              size="field"
              @click="showSoftwareCenterCoreApps()"
              >{{ $t("software_center.review_and_update") }}</NsButton
            >
          </div>
          <div
            v-else-if="isAccountProviderApp(app)"
            class="app-row icon-and-text"
          >
            <NsSvg :svg="InformationFilled16" class="icon ns-info" />
            <span
              >{{ $t("software_center.app_managed_in") }}
              <cv-link to="/domains">{{ $t("domains.title") }}</cv-link>
            </span>
          </div>
          <div v-else-if="tab == 'updates'" class="app-row">
            <NsButton
              kind="ghost"
              :icon="ArrowRight20"
              size="field"
              @click="goToSoftwareCenterAppInstances(app)"
              >{{ $t("software_center.review_and_update") }}</NsButton
            >
          </div>
          <div
            v-else-if="app.installed && app.installed.length"
            class="app-row"
          >
            <NsButton
              kind="ghost"
              :icon="Application20"
              size="field"
              @click="goToSoftwareCenterAppInstances(app)"
              >{{ $t("software_center.instances") }}</NsButton
            >
          </div>
          <div v-else class="app-row">
            <div class="flex items-center">
              <NsButton
                kind="secondary"
                size="field"
                :icon="Download20"
                :disabled="!app.versions.length"
                @click="installInstance(app)"
                >{{ $t("software_center.install") }}</NsButton
              >
              <cv-interactive-tooltip
                v-if="app.no_version_reason && app.no_version_reason.message"
                alignment="center"
                direction="bottom"
                class="info mg-left-sm"
              >
                <template slot="trigger">
                  <Information16 />
                </template>
                <template slot="content">
                  {{
                    $t(
                      `software_center.no_version_reason.${app.no_version_reason.message}`,
                      app.no_version_reason.params
                    )
                  }}
                </template>
              </cv-interactive-tooltip>
            </div>
          </div>
        </cv-tile>
      </div>
    </div>
    <AppInfoModal
      :app="appInfo.app"
      :isShown="appInfo.isShown"
      @close="onClose"
    />
  </div>
</template>
⋮----
<a v-if="app.id !== 'core'" @click="showAppInfo(app)">{{
              app.name
            }}</a>
<span v-else>{{ app.name }}</span>
⋮----
{{ category }}
⋮----
>{{ $t("software_center.review_and_update") }}</NsButton
⋮----
>{{ $t("software_center.app_managed_in") }}
<cv-link to="/domains">{{ $t("domains.title") }}</cv-link>
⋮----
>{{ $t("software_center.review_and_update") }}</NsButton
⋮----
>{{ $t("software_center.instances") }}</NsButton
⋮----
>{{ $t("software_center.install") }}</NsButton
⋮----
<template slot="trigger">
                  <Information16 />
                </template>
<template slot="content">
                  {{
                    $t(
                      `software_center.no_version_reason.${app.no_version_reason.message}`,
                      app.no_version_reason.params
                    )
                  }}
                </template>
⋮----
{{
                    $t(
                      `software_center.no_version_reason.${app.no_version_reason.message}`,
                      app.no_version_reason.params
                    )
                  }}
⋮----
<script>
import { IconService, UtilService } from "@nethserver/ns8-ui-lib";
import AppInfoModal from "./AppInfoModal";
import CertificationLevelBadge from "./CertificationLevelBadge.vue";
import Information16 from "@carbon/icons-vue/es/information/16";
export default {
  name: "AppList",
  components: { AppInfoModal, CertificationLevelBadge, Information16 },
  mixins: [IconService, UtilService],
  props: {
    apps: {
      type: Array,
      required: true,
    },
    tab: {
      type: String,
      required: true,
    },
    skeleton: Boolean,
    light: Boolean,
  },
  data() {
    return {
      appInfo: {
        isShown: false,
        app: null,
      },
    };
  },
  computed: {
    coreApp() {
      return this.apps.find((app) => app.id == "core");
    },
  },
  methods: {
    installInstance(app) {
      this.$emit("install", app);
    },
    openApp(instance) {
      this.$router.push(`/apps/${instance.id}`);
    },
    showAppInfo(app) {
      this.appInfo.isShown = true;
      this.appInfo.app = app;
    },
    onClose() {
      const context = this;
      setTimeout(() => {
        context.appInfo.isShown = false;
      }, 250);
    },
    getApplicationCategories(app) {
      let categories = [];
      for (const category of app.categories) {
        if (category === "unknown") {
          continue;
        }
        categories.push(this.$t("software_center.app_categories." + category));
      }
      return categories;
    },
    goToSoftwareCenterAppInstances(app) {
      this.$router.push({
        name: "SoftwareCenterAppInstances",
        params: { appName: app.name },
      });
    },
    isAccountProviderApp(app) {
      if (
        app.versions &&
        app.versions[0] &&
        app.versions[0].labels["org.nethserver.flags"]
      ) {
        const flags = app.versions[0].labels["org.nethserver.flags"];
        return flags.includes("account_provider");
      }
      return false;
    },
    showSoftwareCenterCoreApps() {
      this.$router.push("/software-center/core-apps");
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
.app-list .app {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.app-row {
  margin-top: $spacing-03;
  margin-bottom: $spacing-03;
}
.app-logo {
  width: 4rem;
  height: 4rem;
  flex-shrink: 0;
}
.app-logo img {
  width: 100%;
  height: 100%;
}
.app-name {
  font-weight: bold;
}
.app-categories {
  color: $text-02;
  font-style: italic;
}
.overflow-menu {
  display: inline-flex;
}
.instance {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid $ui-03;
  color: $text-02;
}
.instance-name {
  margin-left: 5rem;
}
</style>
</file>

<file path="core/ui/src/components/software-center/AutomaticUpdatesModal.vue">
<template>
  <NsModal
    size="default"
    :visible="visible"
    :isLoading="loading"
    :primaryButtonDisabled="loading"
    autoHideOff
    v-on:modal-hide-request="onModalHideRequest"
    @secondary-click="onModalHideRequest"
    @primary-click="applyAutomaticUpdates"
  >
    <template slot="title">
      {{ title }}
    </template>
    <template slot="content">
      <p class="mg-bottom-md">
        {{ description1 }}
      </p>
      <p>
        {{ description2 }}
      </p>
      <div v-if="error.setAutomaticUpdates" class="mg-top-md">
        <NsInlineNotification
          kind="error"
          :title="$t('action.set-automatic-updates')"
          :description="error.setAutomaticUpdates"
          :showCloseButton="false"
        />
      </div>
    </template>
    <template slot="secondary-button">{{ $t("common.cancel") }}</template>
    <template slot="primary-button">{{
      pendingEnable ? $t("common.enable") : $t("common.disable")
    }}</template>
  </NsModal>
</template>
⋮----
<template slot="title">
      {{ title }}
    </template>
⋮----
{{ title }}
⋮----
<template slot="content">
      <p class="mg-bottom-md">
        {{ description1 }}
      </p>
      <p>
        {{ description2 }}
      </p>
      <div v-if="error.setAutomaticUpdates" class="mg-top-md">
        <NsInlineNotification
          kind="error"
          :title="$t('action.set-automatic-updates')"
          :description="error.setAutomaticUpdates"
          :showCloseButton="false"
        />
      </div>
    </template>
⋮----
{{ description1 }}
⋮----
{{ description2 }}
⋮----
<template slot="secondary-button">{{ $t("common.cancel") }}</template>
<template slot="primary-button">{{
      pendingEnable ? $t("common.enable") : $t("common.disable")
    }}</template>
⋮----
<script>
import to from "await-to-js";
import { UtilService, TaskService } from "@nethserver/ns8-ui-lib";
export default {
  name: "AutomaticUpdatesModal",
  mixins: [UtilService, TaskService],
  props: {
    visible: Boolean,
    enable: Boolean,
    instance: {
      type: Object,
      default: null,
    },
  },
  data() {
    return {
      loading: false,
      pendingEnable: false,
      error: {
        setAutomaticUpdates: "",
      },
    };
  },
  computed: {
    title() {
      return this.pendingEnable
        ? this.$t("software_center.enable_automatic_updates")
        : this.$t("software_center.disable_automatic_updates");
    },
    instanceName() {
      if (!this.instance) {
        return "";
      }
      return this.instance.ui_name || this.instance.id;
    },
    description1() {
      if (this.instance) {
        return this.pendingEnable
          ? this.$t(
              "software_center.enable_instance_automatic_updates_description1",
              { instance: this.instanceName }
            )
          : this.$t(
              "software_center.disable_instance_automatic_updates_description1",
              { instance: this.instanceName }
            );
      }
      return this.pendingEnable
        ? this.$t("software_center.enable_automatic_updates_description1")
        : this.$t("software_center.disable_automatic_updates_description1");
    },
    description2() {
      if (this.instance) {
        return this.pendingEnable
          ? this.$t(
              "software_center.enable_instance_automatic_updates_description2"
            )
          : this.$t(
              "software_center.disable_instance_automatic_updates_description2"
            );
      }
      return this.pendingEnable
        ? this.$t("software_center.enable_automatic_updates_description2")
        : this.$t("software_center.disable_automatic_updates_description2");
    },
  },
  watch: {
    visible(newVal) {
      if (newVal) {
        this.error.setAutomaticUpdates = "";
        this.pendingEnable = this.enable;
      }
    },
  },
  methods: {
    async applyAutomaticUpdates() {
      this.error.setAutomaticUpdates = "";
      this.loading = true;
      const data = this.instance
        ? { instances: { [this.instance.id]: this.pendingEnable } }
        : { apply_updates_is_active: this.pendingEnable };
      const taskAction = "set-automatic-updates";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.setAutomaticUpdatesCompleted
      );
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.setAutomaticUpdatesAborted
      );
      this.$root.$once(
        `${taskAction}-validation-failed-${eventId}`,
        this.setAutomaticUpdatesValidationFailed
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data,
          extra: {
            title: this.title,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.setAutomaticUpdates = this.getErrorMessage(err);
        this.loading = false;
      }
    },
    setAutomaticUpdatesAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.setAutomaticUpdates = this.$t("error.generic_error");
      this.loading = false;
    },
    setAutomaticUpdatesValidationFailed(validationErrors) {
      console.error(
        "set-automatic-updates validation failed",
        validationErrors
      );
      this.error.setAutomaticUpdates = this.$t("error.generic_error");
      this.loading = false;
    },
    setAutomaticUpdatesCompleted() {
      this.loading = false;
      this.$emit("hide");
      this.$emit("completed", this.pendingEnable);
    },
    onModalHideRequest() {
      if (this.loading) {
        return;
      }
      this.error.setAutomaticUpdates = "";
      this.$emit("hide");
    },
  },
};
</script>
</file>

<file path="core/ui/src/components/software-center/CertificationLevelBadge.vue">
<template>
  <cv-interactive-tooltip alignment="center" direction="top">
    <template slot="trigger">
      <NsTag
        :label="
          $t('software_center.level_level', {
            level: `${level}/5`,
          })
        "
        :kind="getLevelColor()"
        :icon="getLevelIcon()"
        class="level-tooltip"
      />
    </template>
    <template slot="content">
      <h6 class="mg-bottom-sm">
        {{ $t("software_center.level_level", { level }) }}
      </h6>
      <p class="mg-bottom-sm">
        {{ $t(`software_center.level_${level}_description`) }}
      </p>
      <cv-link
        href="https://docs.nethserver.org/projects/ns8/en/latest/software_center.html#certification-levels"
        target="_blank"
        rel="noreferrer"
        class="inline"
      >
        {{ $t("common.more_info") }}
      </cv-link>
    </template>
  </cv-interactive-tooltip>
</template>
⋮----
<template slot="trigger">
      <NsTag
        :label="
          $t('software_center.level_level', {
            level: `${level}/5`,
          })
        "
        :kind="getLevelColor()"
        :icon="getLevelIcon()"
        class="level-tooltip"
      />
    </template>
<template slot="content">
      <h6 class="mg-bottom-sm">
        {{ $t("software_center.level_level", { level }) }}
      </h6>
      <p class="mg-bottom-sm">
        {{ $t(`software_center.level_${level}_description`) }}
      </p>
      <cv-link
        href="https://docs.nethserver.org/projects/ns8/en/latest/software_center.html#certification-levels"
        target="_blank"
        rel="noreferrer"
        class="inline"
      >
        {{ $t("common.more_info") }}
      </cv-link>
    </template>
⋮----
{{ $t("software_center.level_level", { level }) }}
⋮----
{{ $t(`software_center.level_${level}_description`) }}
⋮----
{{ $t("common.more_info") }}
⋮----
<script>
import Security16 from "@carbon/icons-vue/es/security/16";
import WarningAlt16 from "@carbon/icons-vue/es/warning--alt/16";
import Error16 from "@carbon/icons-vue/es/error/16";
import Rule16 from "@carbon/icons-vue/es/rule/16";
export default {
  name: "CertificationLevelBadge",
  props: {
    level: {
      type: Number,
      required: true,
    },
  },
  data() {
    return {
      Security16,
      WarningAlt16,
      Rule16,
      Error16,
    };
  },
  methods: {
    getLevelColor() {
      if (this.level > 0 && this.level < 5) {
        return "blue";
      } else if (this.level == 5) {
        return "green";
      } else {
        return "gray";
      }
    },
    getLevelIcon() {
      switch (this.level) {
        case 1:
          return this.WarningAlt16;
        case 2:
        case 3:
        case 4:
          return this.Rule16;
        case 5:
          return this.Security16;
        default:
          return this.Error16;
      }
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
.level-tooltip {
  cursor: pointer;
}
</style>
</file>

<file path="core/ui/src/components/software-center/CloneOrMoveAppModal.vue">
<template>
  <NsWizard
    size="default"
    :visible="isShown"
    @modal-shown="onModalShown"
    class="no-pad-modal"
    :cancelLabel="$t('common.cancel')"
    :previousLabel="$t('common.previous')"
    :nextLabel="
      isLastStep || shouldShowCloneOrMoveLabel
        ? isClone
          ? $t('software_center.clone_app')
          : $t('software_center.move_app')
        : $t('common.next')
    "
    :isPreviousDisabled="isFirstStep || isLoading"
    @previousStep="previousStep"
    @nextStep="nextStep"
    @cancel="onModalHidden"
    @modal-hidden="onModalHidden"
    :isPreviousShown="hasAdditionalStorageAvailable"
    :isNextDisabled="isNextButtonDisabled"
    :isLastStep="isLastStep"
  >
    <template slot="title">{{
      isClone ? $t("software_center.clone_app") : $t("software_center.move_app")
    }}</template>
    <template slot="content">
      <cv-form @submit.prevent="nextStep">
        <template v-if="step == 'node'">
          <div class="mg-bottom-md">
            {{
              isClone
                ? $t("software_center.clone_app_description", {
                    instanceLabel,
                  })
                : $t("software_center.move_app_description", { instanceLabel })
            }}
          </div>
          <NsInlineNotification
            v-if="error.getClusterStatus"
            kind="error"
            :title="$t('action.get-cluster-status')"
            :description="error.getClusterStatus"
            :showCloseButton="false"
          />
          <NsInlineNotification
            v-if="error.nodesList"
            kind="error"
            :title="$t('action.list-nodes')"
            :description="error.nodesList"
            :showCloseButton="false"
          />
          <NsInlineNotification
            v-if="error.listMountPoints"
            kind="error"
            :title="$t('action.list-mountpoints')"
            :description="error.listMountPoints"
            :showCloseButton="false"
          />
          <div>{{ $t("software_center.select_destination_node") }}:</div>
          <NsInlineNotification
            v-if="clusterNodesCount == disabledNodes.length && !isLoading"
            kind="info"
            :title="
              isClone
                ? $t('software_center.no_node_eligible_for_instance_cloning')
                : $t('software_center.no_node_eligible_for_instance_migration')
            "
            :showCloseButton="false"
          />
          <NodeSelector
            class="mg-top-xlg"
            @selectNode="onSelectNode"
            :disabledNodes="disabledNodes"
            :loading="isLoading"
            :nodesWithAdditionalStorage="nodesWithAdditionalStorage"
            :nodesDefaultDiskInfo="nodesDefaultDiskInfo"
          >
            <template v-for="(nodeMessages, nodeId) in nodesInfo">
              <template :slot="`node-${nodeId}`">
                <div
                  v-for="(nodeMessage, index) in nodeMessages"
                  :key="index"
                  class="node-message"
                >
                  {{ nodeMessage }}
                </div>
              </template>
            </template>
          </NodeSelector>
        </template>
        <template v-else-if="step == 'volumes' && selectedNode">
          <div>
            {{
              $t("software_center.select_node_volume_for_installation", {
                node: this.getNodeLabel(selectedNode) || "",
              })
            }}. {{ $t("software_center.other_files_remain_on_default_volume") }}
          </div>
          <AdditionalVolumesSelector
            @selectVolume="onSelectVolume"
            :volumes="additionalVolumes"
            :light="true"
            class="mg-top-lg"
          />
        </template>
        <NsInlineNotification
          v-if="error.cloneModule"
          kind="error"
          :title="$t('action.clone-module')"
          :description="error.cloneModule"
          :showCloseButton="false"
        />
      </cv-form>
    </template>
  </NsWizard>
</template>
⋮----
<template slot="title">{{
      isClone ? $t("software_center.clone_app") : $t("software_center.move_app")
    }}</template>
<template slot="content">
      <cv-form @submit.prevent="nextStep">
        <template v-if="step == 'node'">
          <div class="mg-bottom-md">
            {{
              isClone
                ? $t("software_center.clone_app_description", {
                    instanceLabel,
                  })
                : $t("software_center.move_app_description", { instanceLabel })
            }}
          </div>
          <NsInlineNotification
            v-if="error.getClusterStatus"
            kind="error"
            :title="$t('action.get-cluster-status')"
            :description="error.getClusterStatus"
            :showCloseButton="false"
          />
          <NsInlineNotification
            v-if="error.nodesList"
            kind="error"
            :title="$t('action.list-nodes')"
            :description="error.nodesList"
            :showCloseButton="false"
          />
          <NsInlineNotification
            v-if="error.listMountPoints"
            kind="error"
            :title="$t('action.list-mountpoints')"
            :description="error.listMountPoints"
            :showCloseButton="false"
          />
          <div>{{ $t("software_center.select_destination_node") }}:</div>
          <NsInlineNotification
            v-if="clusterNodesCount == disabledNodes.length && !isLoading"
            kind="info"
            :title="
              isClone
                ? $t('software_center.no_node_eligible_for_instance_cloning')
                : $t('software_center.no_node_eligible_for_instance_migration')
            "
            :showCloseButton="false"
          />
          <NodeSelector
            class="mg-top-xlg"
            @selectNode="onSelectNode"
            :disabledNodes="disabledNodes"
            :loading="isLoading"
            :nodesWithAdditionalStorage="nodesWithAdditionalStorage"
            :nodesDefaultDiskInfo="nodesDefaultDiskInfo"
          >
            <template v-for="(nodeMessages, nodeId) in nodesInfo">
              <template :slot="`node-${nodeId}`">
                <div
                  v-for="(nodeMessage, index) in nodeMessages"
                  :key="index"
                  class="node-message"
                >
                  {{ nodeMessage }}
                </div>
              </template>
            </template>
          </NodeSelector>
        </template>
        <template v-else-if="step == 'volumes' && selectedNode">
          <div>
            {{
              $t("software_center.select_node_volume_for_installation", {
                node: this.getNodeLabel(selectedNode) || "",
              })
            }}. {{ $t("software_center.other_files_remain_on_default_volume") }}
          </div>
          <AdditionalVolumesSelector
            @selectVolume="onSelectVolume"
            :volumes="additionalVolumes"
            :light="true"
            class="mg-top-lg"
          />
        </template>
        <NsInlineNotification
          v-if="error.cloneModule"
          kind="error"
          :title="$t('action.clone-module')"
          :description="error.cloneModule"
          :showCloseButton="false"
        />
      </cv-form>
    </template>
⋮----
<template v-if="step == 'node'">
          <div class="mg-bottom-md">
            {{
              isClone
                ? $t("software_center.clone_app_description", {
                    instanceLabel,
                  })
                : $t("software_center.move_app_description", { instanceLabel })
            }}
          </div>
          <NsInlineNotification
            v-if="error.getClusterStatus"
            kind="error"
            :title="$t('action.get-cluster-status')"
            :description="error.getClusterStatus"
            :showCloseButton="false"
          />
          <NsInlineNotification
            v-if="error.nodesList"
            kind="error"
            :title="$t('action.list-nodes')"
            :description="error.nodesList"
            :showCloseButton="false"
          />
          <NsInlineNotification
            v-if="error.listMountPoints"
            kind="error"
            :title="$t('action.list-mountpoints')"
            :description="error.listMountPoints"
            :showCloseButton="false"
          />
          <div>{{ $t("software_center.select_destination_node") }}:</div>
          <NsInlineNotification
            v-if="clusterNodesCount == disabledNodes.length && !isLoading"
            kind="info"
            :title="
              isClone
                ? $t('software_center.no_node_eligible_for_instance_cloning')
                : $t('software_center.no_node_eligible_for_instance_migration')
            "
            :showCloseButton="false"
          />
          <NodeSelector
            class="mg-top-xlg"
            @selectNode="onSelectNode"
            :disabledNodes="disabledNodes"
            :loading="isLoading"
            :nodesWithAdditionalStorage="nodesWithAdditionalStorage"
            :nodesDefaultDiskInfo="nodesDefaultDiskInfo"
          >
            <template v-for="(nodeMessages, nodeId) in nodesInfo">
              <template :slot="`node-${nodeId}`">
                <div
                  v-for="(nodeMessage, index) in nodeMessages"
                  :key="index"
                  class="node-message"
                >
                  {{ nodeMessage }}
                </div>
              </template>
            </template>
          </NodeSelector>
        </template>
⋮----
{{
              isClone
                ? $t("software_center.clone_app_description", {
                    instanceLabel,
                  })
                : $t("software_center.move_app_description", { instanceLabel })
            }}
⋮----
<div>{{ $t("software_center.select_destination_node") }}:</div>
⋮----
<template v-for="(nodeMessages, nodeId) in nodesInfo">
              <template :slot="`node-${nodeId}`">
                <div
                  v-for="(nodeMessage, index) in nodeMessages"
                  :key="index"
                  class="node-message"
                >
                  {{ nodeMessage }}
                </div>
              </template>
            </template>
⋮----
<template :slot="`node-${nodeId}`">
                <div
                  v-for="(nodeMessage, index) in nodeMessages"
                  :key="index"
                  class="node-message"
                >
                  {{ nodeMessage }}
                </div>
              </template>
⋮----
{{ nodeMessage }}
⋮----
<template v-else-if="step == 'volumes' && selectedNode">
          <div>
            {{
              $t("software_center.select_node_volume_for_installation", {
                node: this.getNodeLabel(selectedNode) || "",
              })
            }}. {{ $t("software_center.other_files_remain_on_default_volume") }}
          </div>
          <AdditionalVolumesSelector
            @selectVolume="onSelectVolume"
            :volumes="additionalVolumes"
            :light="true"
            class="mg-top-lg"
          />
        </template>
⋮----
{{
              $t("software_center.select_node_volume_for_installation", {
                node: this.getNodeLabel(selectedNode) || "",
              })
            }}. {{ $t("software_center.other_files_remain_on_default_volume") }}
⋮----
}}. {{ $t("software_center.other_files_remain_on_default_volume") }}
⋮----
<script>
import { UtilService, IconService, TaskService } from "@nethserver/ns8-ui-lib";
import { mapState } from "vuex";
import NodeSelector from "@/components/nodes/NodeSelector";
import AdditionalVolumesSelector from "@/components/software-center/AdditionalVolumesSelector.vue";
import to from "await-to-js";
export default {
  name: "CloneOrMoveAppModal",
  components: { NodeSelector, AdditionalVolumesSelector },
  mixins: [UtilService, IconService, TaskService],
  props: {
    isShown: {
      type: Boolean,
      default: false,
    },
    isClone: {
      type: Boolean,
      required: true,
    },
    instanceId: {
      type: String,
      required: true,
    },
    instanceUiName: {
      type: String,
      default: "",
    },
    installationNode: {
      type: Number,
      required: true,
    },
    app: {
      type: Object,
      default: null,
    },
  },
  data() {
    return {
      selectedNode: null,
      step: "node",
      steps: ["node", "volumes"],
      clusterStatus: [],
      nodesList: [],
      selectedVolume: {},
      nodesDefaultDiskInfo: {},
      nodesAdditionalDiskInfo: {},
      loading: {
        cloneModule: false,
        getClusterStatus: true,
        nodesList: true,
      },
      error: {
        cloneModule: "",
        getClusterStatus: "",
        nodesList: "",
        listMountPoints: "",
      },
    };
  },
  computed: {
    ...mapState(["clusterNodes"]),
    isLoading() {
      return this.loading.getClusterStatus || this.loading.nodesList;
    },
    clusterNodesCount() {
      return this.clusterNodes.length;
    },
    stepIndex() {
      return this.steps.indexOf(this.step);
    },
    isFirstStep() {
      return this.stepIndex == 0;
    },
    isLastStep() {
      if (this.step == "node" && this.selectedNode) {
        if (
          !this.nodesWithAdditionalStorage.includes(this.selectedNode.id) ||
          this.appVolumes.length === 0
        ) {
          return true;
        }
      }
      return this.stepIndex == this.steps.length - 1;
    },
    shouldShowCloneOrMoveLabel() {
      return (
        this.step == "node" &&
        this.selectedNode &&
        !this.nodesWithAdditionalStorage.includes(this.selectedNode.id)
      );
    },
    nodesWithAdditionalStorage() {
      const nodeIds = [];
      if (this.appVolumes.length === 0) {
        return nodeIds;
      }
      if (this.nodesList && Array.isArray(this.nodesList)) {
        for (const node of this.nodesList) {
          if (node.additional_disk_count > 0) {
            nodeIds.push(node.node_id);
          }
        }
      }
      return nodeIds;
    },
    hasAdditionalStorageAvailable() {
      return this.nodesWithAdditionalStorage.length > 0;
    },
    isNextButtonDisabled() {
      if (this.step == "node") {
        return (
          !this.selectedNode ||
          (!this.isClone && this.installationNode == this.selectedNode.id) ||
          this.loading.cloneModule ||
          this.loading.getClusterStatus ||
          this.clusterNodesCount == this.disabledNodes.length
        );
      } else if (this.step == "volumes") {
        return (
          !this.selectedNode ||
          !this.selectedVolume ||
          Object.keys(this.selectedVolume).length === 0
        );
      }
      return false;
    },
    instanceLabel() {
      if (this.instanceUiName) {
        return `${this.instanceUiName} (${this.instanceId})`;
      } else {
        return this.instanceId;
      }
    },
    nodesInfo() {
      if (!this.app) {
        return {};
      }
      const nodesInfo = {};
      if (this.app) {
        for (const nodeInfo of this.app.install_destinations) {
          const nodeMessages = [];
          if (nodeInfo.node_id === this.installationNode) {
            nodeMessages.push(this.$t("software_center.current_node"));
          }
          if (!nodeInfo.eligible) {
            const rejectReason = nodeInfo.reject_reason;
            if (rejectReason.message === "max_per_node_limit") {
              const numMaxInstances = rejectReason.parameter;
              nodeMessages.push(
                this.$tc(
                  `software_center.reason_${rejectReason.message}`,
                  numMaxInstances,
                  { param: numMaxInstances }
                )
              );
            } else {
              nodeMessages.push(
                this.$t(`software_center.reason_${rejectReason.message}`, {
                  param: rejectReason.parameter,
                })
              );
            }
          } else if (nodeInfo.instances) {
            nodeMessages.push(
              this.$tc(
                "software_center.num_instances_installed",
                nodeInfo.instances,
                { num: nodeInfo.instances }
              )
            );
          }
          nodesInfo[nodeInfo.node_id] = nodeMessages;
        }
        for (const node of this.clusterStatus) {
          if (!node.online) {
            if (!nodesInfo[node.id]) {
              nodesInfo[node.id] = [];
            }
            nodesInfo[node.id].push(this.$t("software_center.node_offline"));
          }
        }
      }
      return nodesInfo;
    },
    disabledNodes() {
      if (!this.app) {
        return [];
      }
      const ineligibleNodes = this.app.install_destinations
        .filter((nodeInfo) => !nodeInfo.eligible)
        .map((nodeInfo) => nodeInfo.node_id);
      const offlineNodeIds = this.clusterStatus
        .filter((node) => !node.online)
        .map((node) => node.id);
      if (this.isClone) {
        return [...new Set([...ineligibleNodes, ...offlineNodeIds])];
      } else {
        return [
          ...new Set([
            ...ineligibleNodes.concat(this.installationNode),
            ...offlineNodeIds,
          ]),
        ];
      }
    },
    additionalVolumes() {
      const output = this.nodesAdditionalDiskInfo[this.selectedNode?.id];
      if (!output) return [];
      const volumes = [...output.mountpoints];
      if (output.default_disk) {
        volumes.push({ ...output.default_disk, default: true });
      }
      return volumes;
    },
    appVolumes() {
      if (
        this.app &&
        this.app.versions &&
        this.app.versions.length &&
        this.app.versions[0].labels &&
        this.app.versions[0].labels["org.nethserver.volumes"]
      ) {
        const volumesString =
          this.app.versions[0].labels["org.nethserver.volumes"];
        return volumesString.split(" ").map((v) => v.trim());
      }
      return [];
    },
  },
  methods: {
    nextStep() {
      if (this.isNextButtonDisabled) {
        return;
      }
      if (this.isLastStep) {
        this.cloneOrMove(this.selectedVolume);
      } else {
        if (
          this.step == "node" &&
          (!this.nodesWithAdditionalStorage.includes(this.selectedNode.id) ||
            this.appVolumes.length === 0)
        ) {
          this.cloneOrMove();
        } else {
          this.step = this.steps[this.stepIndex + 1];
        }
      }
    },
    previousStep() {
      if (!this.isFirstStep) {
        this.selectedVolume = {};
        this.step = this.steps[this.stepIndex - 1];
      }
    },
    onModalShown() {
      this.selectedNode = null;
      this.selectedVolume = {};
      this.clusterStatus = [];
      this.nodesDefaultDiskInfo = {};
      this.nodesAdditionalDiskInfo = {};
      if (this.clusterNodesCount == 1) {
        const firstNode = this.clusterNodes[0];
        this.selectedNode = { ...firstNode, selected: true };
      }
      this.listNodes();
      this.getClusterStatus();
    },
    onModalHidden() {
      this.$emit("hide");
      this.clearErrors();
      this.selectedNode = null;
      this.selectedVolume = {};
      this.clusterStatus = [];
      this.nodesList = [];
      this.nodesAdditionalDiskInfo = {};
      this.step = this.steps[0];
    },
    async listNodes() {
      this.error.nodesList = "";
      const taskAction = "list-nodes";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.listNodesAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.listNodesCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.nodesList = this.getErrorMessage(err);
        return;
      }
    },
    listNodesAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.nodesList = this.$t("error.generic_error");
      this.loading.nodesList = false;
    },
    listNodesCompleted(taskContext, taskResult) {
      this.nodesList = taskResult.output.nodes;
      this.loading.nodesList = false;
    },
    async getClusterStatus() {
      this.loading.getClusterStatus = true;
      this.error.getClusterStatus = "";
      const taskAction = "get-cluster-status";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.getClusterStatusAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.getClusterStatusCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.getClusterStatus = this.getErrorMessage(err);
        return;
      }
    },
    getClusterStatusAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.getClusterStatus = this.$t("error.generic_error");
      this.loading.getClusterStatus = false;
    },
    getClusterStatusCompleted(taskContext, taskResult) {
      this.clusterStatus = taskResult.output.nodes;
      for (const node of this.clusterStatus.filter((n) => n.online)) {
        this.listMountPoints(node.id);
      }
      this.loading.getClusterStatus = false;
    },
    async listMountPoints(nodeId) {
      const taskAction = "list-mountpoints";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.listMountPointsAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        (taskContext, taskResult) =>
          this.listMountPointsCompleted(taskContext, taskResult, nodeId)
      );
      const res = await to(
        this.createNodeTask(nodeId, {
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(
          `error creating task ${taskAction} for node ${nodeId}`,
          err
        );
        this.error.listMountPoints = this.getErrorMessage(err);
        return;
      }
    },
    listMountPointsAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.listMountPoints = this.$t("error.generic_error");
    },
    listMountPointsCompleted(taskContext, taskResult, nodeId) {
      const output = taskResult.output;
      this.$set(this.nodesAdditionalDiskInfo, nodeId, output);
      if (output.default_disk) {
        this.$set(this.nodesDefaultDiskInfo, nodeId, output.default_disk);
      }
    },
    async cloneOrMove(volumes) {
      this.loading.cloneModule = true;
      const taskAction = "clone-module";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.cloneModuleAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.cloneModuleCompleted
      );
      const shortInstanceLabel = this.instanceUiName || this.instanceId;
      const shortNodeLabel =
        this.selectedNode.ui_name ||
        this.$t("common.node") + ` ${this.selectedNode.id}`;
      const notificationTitle = this.isClone
        ? this.$t("software_center.clone_app")
        : this.$t("software_center.move_app");
      const notificationDescription = this.isClone
        ? this.$t("software_center.cloning_app_to_node", {
            instance: shortInstanceLabel,
            node: shortNodeLabel,
          })
        : this.$t("software_center.moving_app_to_node", {
            instance: shortInstanceLabel,
            node: shortNodeLabel,
          });
      let completionString = "";
      if (this.instanceUiName) {
        if (this.isClone) {
          completionString = "software_center.app_with_ui_name_cloned_to_node";
        } else {
          completionString = "software_center.app_with_ui_name_moved_to_node";
        }
      } else {
        if (this.isClone) {
          completionString =
            "software_center.app_without_ui_name_cloned_to_node";
        } else {
          completionString =
            "software_center.app_without_ui_name_moved_to_node";
        }
      }
      const data = {
        module: this.instanceId,
        node: parseInt(this.selectedNode.id),
        replace: !this.isClone,
      };
      if (volumes?.path && this.appVolumes.length) {
        data.volumes = {};
        this.appVolumes.forEach((volume) => {
          data.volumes[volume] = volumes.path;
        });
      }
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data,
          extra: {
            title: notificationTitle,
            description: notificationDescription,
            instance: shortInstanceLabel,
            node: shortNodeLabel,
            completion: {
              i18nString: completionString,
              extraTextParams: ["node", "instance"],
              outputTextParams: ["module_id"],
            },
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.cloneModule = this.getErrorMessage(err);
        this.loading.cloneModule = false;
        return;
      }
      this.loading.cloneModule = false;
      this.$emit("hide");
    },
    cloneModuleAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.loading.cloneModule = false;
    },
    cloneModuleCompleted(taskContext, taskResult) {
      const newModuleId = taskResult.output.module_id;
      this.clearErrors();
      this.onModalHidden();
      this.$emit("cloneOrMoveCompleted", newModuleId);
      this.$root.$emit("reloadAppDrawer");
    },
    onSelectNode(selectedNode) {
      this.selectedNode = selectedNode;
    },
    onSelectVolume(selectedVolume) {
      this.selectedVolume = selectedVolume;
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
.node-message {
  margin-bottom: $spacing-05;
}
.node-message:last-child {
  margin-bottom: 0;
}
</style>
</file>

<file path="core/ui/src/components/software-center/ImageGallery.vue">
<template>
  <div>
    <VueGallery
      :images="images"
      :index="index"
      @close="index = null"
      :options="{ fullScreen: fullScreen }"
    ></VueGallery>
    <div class="previews">
      <div
        class="image"
        v-for="(image, imageIndex) in images"
        :key="imageIndex"
        @click="index = imageIndex"
        :style="{
          backgroundImage: 'url(' + image + ')',
        }"
      ></div>
    </div>
  </div>
</template>
⋮----
<script>
import VueGallery from "vue-gallery";
export default {
  name: "ImageGallery",
  components: { VueGallery },
  props: {
    images: Array,
    fullScreen: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      index: null,
    };
  },
  created() {
    document.addEventListener("fullscreenchange", this.fullScreenChange, false);
    document.addEventListener(
      "mozfullscreenchange",
      this.fullScreenChange,
      false
    );
    document.addEventListener(
      "MSFullscreenChange",
      this.fullScreenChange,
      false
    );
    document.addEventListener(
      "webkitfullscreenchange",
      this.fullScreenChange,
      false
    );
  },
  beforeDestroy() {
    document.removeEventListener("fullscreenchange", this.fullScreenChange);
    document.removeEventListener("mozfullscreenchange", this.fullScreenChange);
    document.removeEventListener("MSFullscreenChange", this.fullScreenChange);
    document.removeEventListener(
      "webkitfullscreenchange",
      this.fullScreenChange
    );
  },
  methods: {
    fullScreenChange() {
      if (
        document.webkitIsFullScreen === false ||
        document.mozFullScreen === false ||
        document.msFullscreenElement === false
      ) {
        this.index = null;
      }
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
.previews {
  display: flex;
  overflow-x: auto;
}
.image {
  width: 300px;
  height: 200px;
  flex-shrink: 0;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center center;
  border: 1px solid $ui-03;
  margin: 0 $spacing-03 $spacing-03 0;
  cursor: pointer;
}
.image:last-child {
  margin-right: 0;
}
</style>
</file>

<file path="core/ui/src/components/software-center/InstallAppModal.vue">
<template>
  <NsWizard
    size="default"
    :visible="isShown"
    @modal-hidden="onModalHidden"
    @modal-shown="onModalShown"
    class="no-pad-modal"
    :cancelLabel="$t('common.cancel')"
    :previousLabel="$t('common.previous')"
    :nextLabel="
      isLastStep || shouldShowInstallLabel
        ? $t('software_center.install')
        : $t('common.next')
    "
    :isPreviousDisabled="isFirstStep || isLoading"
    @previousStep="previousStep"
    @nextStep="nextStep"
    @cancel="onModalHidden"
    :isNextDisabled="isNextButtonDisabled"
    :isPreviousShown="hasAdditionalStorageAvailable"
    :isLastStep="isLastStep"
  >
    <template slot="title">{{
      app ? $t("software_center.app_installation", { app: app.name }) : ""
    }}</template>
    <template v-if="app" slot="content">
      <cv-form @submit.prevent="nextStep">
        <template v-if="step == 'node'">
          <NsInlineNotification
            v-if="app.rootfull && app.certification_level < 3"
            kind="warning"
            :title="$t('software_center.rootfull_app_warning_title')"
            :description="
              $t('software_center.rootfull_app_warning_description', {
                appName: app.name,
              })
            "
            :showCloseButton="false"
          />
          <div v-if="clusterNodesCount > 1">
            {{
              $t("software_center.choose_node_for_installation", {
                app: app.name,
                version: appVersion,
              })
            }}
          </div>
          <div v-else>
            {{
              $t("software_center.installation_node_for_app", {
                app: app.name,
                version: appVersion,
              })
            }}
          </div>
          <NsInlineNotification
            v-if="error.getClusterStatus"
            kind="error"
            :title="$t('action.get-cluster-status')"
            :description="error.getClusterStatus"
            :showCloseButton="false"
          />
          <NsInlineNotification
            v-if="error.nodesList"
            kind="error"
            :title="$t('action.list-nodes')"
            :description="error.nodesList"
            :showCloseButton="false"
          />
          <NsInlineNotification
            v-if="error.listMountPoints"
            kind="error"
            :title="$t('action.list-mountpoints')"
            :description="error.listMountPoints"
            :showCloseButton="false"
          />
          <NsInlineNotification
            v-if="clusterNodesCount == disabledNodes.length && !isLoading"
            kind="info"
            :title="$t('software_center.no_node_eligible_for_app_installation')"
            :showCloseButton="false"
          />
          <NodeSelector
            @selectNode="onSelectNode"
            :disabledNodes="disabledNodes"
            :nodesWithAdditionalStorage="nodesWithAdditionalStorage"
            :nodesDefaultDiskInfo="nodesDefaultDiskInfo"
            :loading="isLoading"
            class="mg-top-lg"
          >
            <template v-for="(nodeInfoMessage, nodeId) in nodesInfo">
              <template :slot="`node-${nodeId}`">
                {{ nodeInfoMessage }}
              </template>
            </template>
          </NodeSelector>
          <NsCheckbox
            v-if="app.docs.terms_url"
            v-model="agreeTerms"
            value="checkTerms"
          >
            <template slot="label">
              <i18n
                path="software_center.agree_terms_before_install"
                tag="span"
              >
                <template v-slot:appName>
                  {{ app.name }}
                </template>
                <template v-slot:terms>
                  <cv-link
                    :href="app.docs.terms_url"
                    target="_blank"
                    rel="noreferrer"
                    class="inline"
                  >
                    {{ $t("common.terms_and_conditions") }}
                  </cv-link>
                </template>
              </i18n>
            </template>
          </NsCheckbox>
        </template>
        <template v-else-if="step == 'volumes' && selectedNode">
          <div>
            {{
              $t("software_center.select_node_volume_for_installation", {
                node: this.getNodeLabel(selectedNode) || "",
              })
            }}. {{ $t("software_center.other_files_remain_on_default_volume") }}
          </div>
          <AdditionalVolumesSelector
            @selectVolume="onSelectVolume"
            :volumes="additionalVolumes"
            :light="true"
            class="mg-top-lg"
          />
        </template>
        <NsInlineNotification
          v-if="error.addModule"
          kind="error"
          :title="$t('action.add-module')"
          :description="error.addModule"
          :showCloseButton="false"
        />
      </cv-form>
    </template>
  </NsWizard>
</template>
⋮----
<template slot="title">{{
      app ? $t("software_center.app_installation", { app: app.name }) : ""
    }}</template>
⋮----
<template v-if="app" slot="content">
      <cv-form @submit.prevent="nextStep">
        <template v-if="step == 'node'">
          <NsInlineNotification
            v-if="app.rootfull && app.certification_level < 3"
            kind="warning"
            :title="$t('software_center.rootfull_app_warning_title')"
            :description="
              $t('software_center.rootfull_app_warning_description', {
                appName: app.name,
              })
            "
            :showCloseButton="false"
          />
          <div v-if="clusterNodesCount > 1">
            {{
              $t("software_center.choose_node_for_installation", {
                app: app.name,
                version: appVersion,
              })
            }}
          </div>
          <div v-else>
            {{
              $t("software_center.installation_node_for_app", {
                app: app.name,
                version: appVersion,
              })
            }}
          </div>
          <NsInlineNotification
            v-if="error.getClusterStatus"
            kind="error"
            :title="$t('action.get-cluster-status')"
            :description="error.getClusterStatus"
            :showCloseButton="false"
          />
          <NsInlineNotification
            v-if="error.nodesList"
            kind="error"
            :title="$t('action.list-nodes')"
            :description="error.nodesList"
            :showCloseButton="false"
          />
          <NsInlineNotification
            v-if="error.listMountPoints"
            kind="error"
            :title="$t('action.list-mountpoints')"
            :description="error.listMountPoints"
            :showCloseButton="false"
          />
          <NsInlineNotification
            v-if="clusterNodesCount == disabledNodes.length && !isLoading"
            kind="info"
            :title="$t('software_center.no_node_eligible_for_app_installation')"
            :showCloseButton="false"
          />
          <NodeSelector
            @selectNode="onSelectNode"
            :disabledNodes="disabledNodes"
            :nodesWithAdditionalStorage="nodesWithAdditionalStorage"
            :nodesDefaultDiskInfo="nodesDefaultDiskInfo"
            :loading="isLoading"
            class="mg-top-lg"
          >
            <template v-for="(nodeInfoMessage, nodeId) in nodesInfo">
              <template :slot="`node-${nodeId}`">
                {{ nodeInfoMessage }}
              </template>
            </template>
          </NodeSelector>
          <NsCheckbox
            v-if="app.docs.terms_url"
            v-model="agreeTerms"
            value="checkTerms"
          >
            <template slot="label">
              <i18n
                path="software_center.agree_terms_before_install"
                tag="span"
              >
                <template v-slot:appName>
                  {{ app.name }}
                </template>
                <template v-slot:terms>
                  <cv-link
                    :href="app.docs.terms_url"
                    target="_blank"
                    rel="noreferrer"
                    class="inline"
                  >
                    {{ $t("common.terms_and_conditions") }}
                  </cv-link>
                </template>
              </i18n>
            </template>
          </NsCheckbox>
        </template>
        <template v-else-if="step == 'volumes' && selectedNode">
          <div>
            {{
              $t("software_center.select_node_volume_for_installation", {
                node: this.getNodeLabel(selectedNode) || "",
              })
            }}. {{ $t("software_center.other_files_remain_on_default_volume") }}
          </div>
          <AdditionalVolumesSelector
            @selectVolume="onSelectVolume"
            :volumes="additionalVolumes"
            :light="true"
            class="mg-top-lg"
          />
        </template>
        <NsInlineNotification
          v-if="error.addModule"
          kind="error"
          :title="$t('action.add-module')"
          :description="error.addModule"
          :showCloseButton="false"
        />
      </cv-form>
    </template>
⋮----
<template v-if="step == 'node'">
          <NsInlineNotification
            v-if="app.rootfull && app.certification_level < 3"
            kind="warning"
            :title="$t('software_center.rootfull_app_warning_title')"
            :description="
              $t('software_center.rootfull_app_warning_description', {
                appName: app.name,
              })
            "
            :showCloseButton="false"
          />
          <div v-if="clusterNodesCount > 1">
            {{
              $t("software_center.choose_node_for_installation", {
                app: app.name,
                version: appVersion,
              })
            }}
          </div>
          <div v-else>
            {{
              $t("software_center.installation_node_for_app", {
                app: app.name,
                version: appVersion,
              })
            }}
          </div>
          <NsInlineNotification
            v-if="error.getClusterStatus"
            kind="error"
            :title="$t('action.get-cluster-status')"
            :description="error.getClusterStatus"
            :showCloseButton="false"
          />
          <NsInlineNotification
            v-if="error.nodesList"
            kind="error"
            :title="$t('action.list-nodes')"
            :description="error.nodesList"
            :showCloseButton="false"
          />
          <NsInlineNotification
            v-if="error.listMountPoints"
            kind="error"
            :title="$t('action.list-mountpoints')"
            :description="error.listMountPoints"
            :showCloseButton="false"
          />
          <NsInlineNotification
            v-if="clusterNodesCount == disabledNodes.length && !isLoading"
            kind="info"
            :title="$t('software_center.no_node_eligible_for_app_installation')"
            :showCloseButton="false"
          />
          <NodeSelector
            @selectNode="onSelectNode"
            :disabledNodes="disabledNodes"
            :nodesWithAdditionalStorage="nodesWithAdditionalStorage"
            :nodesDefaultDiskInfo="nodesDefaultDiskInfo"
            :loading="isLoading"
            class="mg-top-lg"
          >
            <template v-for="(nodeInfoMessage, nodeId) in nodesInfo">
              <template :slot="`node-${nodeId}`">
                {{ nodeInfoMessage }}
              </template>
            </template>
          </NodeSelector>
          <NsCheckbox
            v-if="app.docs.terms_url"
            v-model="agreeTerms"
            value="checkTerms"
          >
            <template slot="label">
              <i18n
                path="software_center.agree_terms_before_install"
                tag="span"
              >
                <template v-slot:appName>
                  {{ app.name }}
                </template>
                <template v-slot:terms>
                  <cv-link
                    :href="app.docs.terms_url"
                    target="_blank"
                    rel="noreferrer"
                    class="inline"
                  >
                    {{ $t("common.terms_and_conditions") }}
                  </cv-link>
                </template>
              </i18n>
            </template>
          </NsCheckbox>
        </template>
⋮----
{{
              $t("software_center.choose_node_for_installation", {
                app: app.name,
                version: appVersion,
              })
            }}
⋮----
{{
              $t("software_center.installation_node_for_app", {
                app: app.name,
                version: appVersion,
              })
            }}
⋮----
<template v-for="(nodeInfoMessage, nodeId) in nodesInfo">
              <template :slot="`node-${nodeId}`">
                {{ nodeInfoMessage }}
              </template>
            </template>
⋮----
<template :slot="`node-${nodeId}`">
                {{ nodeInfoMessage }}
              </template>
⋮----
{{ nodeInfoMessage }}
⋮----
<template slot="label">
              <i18n
                path="software_center.agree_terms_before_install"
                tag="span"
              >
                <template v-slot:appName>
                  {{ app.name }}
                </template>
                <template v-slot:terms>
                  <cv-link
                    :href="app.docs.terms_url"
                    target="_blank"
                    rel="noreferrer"
                    class="inline"
                  >
                    {{ $t("common.terms_and_conditions") }}
                  </cv-link>
                </template>
              </i18n>
            </template>
⋮----
<template v-slot:appName>
                  {{ app.name }}
                </template>
⋮----
{{ app.name }}
⋮----
<template v-slot:terms>
                  <cv-link
                    :href="app.docs.terms_url"
                    target="_blank"
                    rel="noreferrer"
                    class="inline"
                  >
                    {{ $t("common.terms_and_conditions") }}
                  </cv-link>
                </template>
⋮----
{{ $t("common.terms_and_conditions") }}
⋮----
<template v-else-if="step == 'volumes' && selectedNode">
          <div>
            {{
              $t("software_center.select_node_volume_for_installation", {
                node: this.getNodeLabel(selectedNode) || "",
              })
            }}. {{ $t("software_center.other_files_remain_on_default_volume") }}
          </div>
          <AdditionalVolumesSelector
            @selectVolume="onSelectVolume"
            :volumes="additionalVolumes"
            :light="true"
            class="mg-top-lg"
          />
        </template>
⋮----
{{
              $t("software_center.select_node_volume_for_installation", {
                node: this.getNodeLabel(selectedNode) || "",
              })
            }}. {{ $t("software_center.other_files_remain_on_default_volume") }}
⋮----
}}. {{ $t("software_center.other_files_remain_on_default_volume") }}
⋮----
<script>
import { UtilService, TaskService, IconService } from "@nethserver/ns8-ui-lib";
import to from "await-to-js";
import NotificationService from "@/mixins/notification";
import NodeSelector from "@/components/nodes/NodeSelector";
import AdditionalVolumesSelector from "@/components/software-center/AdditionalVolumesSelector.vue";
import { mapState } from "vuex";
export default {
  name: "InstallAppModal",
  components: { NodeSelector, AdditionalVolumesSelector },
  mixins: [UtilService, TaskService, IconService, NotificationService],
  props: {
    isShown: Boolean,
    app: { type: [Object, null] },
  },
  data() {
    return {
      selectedNode: null,
      agreeTerms: false,
      step: "node",
      steps: ["node", "volumes"],
      loading: {
        getClusterStatus: true,
        nodesList: true,
      },
      clusterStatus: [],
      nodesList: [],
      selectedVolume: {},
      nodesDefaultDiskInfo: {},
      nodesAdditionalDiskInfo: {},
      error: {
        addModule: "",
        getClusterStatus: "",
        nodesList: "",
        listMountPoints: "",
      },
    };
  },
  computed: {
    ...mapState(["clusterNodes"]),
    isLoading() {
      return this.loading.getClusterStatus || this.loading.nodesList;
    },
    clusterNodesCount() {
      return this.clusterNodes.length;
    },
    stepIndex() {
      return this.steps.indexOf(this.step);
    },
    isFirstStep() {
      return this.stepIndex == 0;
    },
    isLastStep() {
      if (this.step == "node" && this.selectedNode) {
        if (
          !this.nodesWithAdditionalStorage.includes(this.selectedNode.id) ||
          this.appVolumes.length === 0
        ) {
          return true;
        }
      }
      return this.stepIndex == this.steps.length - 1;
    },
    shouldShowInstallLabel() {
      return (
        this.step == "node" &&
        this.selectedNode &&
        (!this.nodesWithAdditionalStorage.includes(this.selectedNode.id) ||
          this.appVolumes.length === 0)
      );
    },
    isNextButtonDisabled() {
      if (this.step == "node") {
        return (
          this.isLoading ||
          !this.selectedNode ||
          this.clusterNodesCount == this.disabledNodes.length ||
          (this.app && this.app.docs.terms_url && !this.agreeTerms)
        );
      } else if (this.step == "volumes") {
        return (
          !this.selectedNode ||
          !this.selectedVolume ||
          Object.keys(this.selectedVolume).length === 0
        );
      }
      return false;
    },
    firstNodeLabel() {
      if (this.clusterNodesCount && this.clusterNodes[0]) {
        if (this.clusterNodes[0].ui_name) {
          return `${this.clusterNodes[0].ui_name} (${this.$t("common.node")} ${
            this.clusterNodes[0].id
          })`;
        } else {
          return `${this.$t("common.node")} ${this.clusterNodes[0].id}`;
        }
      } else {
        return "";
      }
    },
    appVersion() {
      if (this.app.versions.length) {
        return this.app.versions[0].tag;
      } else {
        return "-"; // this value is never sent. It would fail the backend validation
      }
    },
    canInstallOnSingleNode() {
      const installDestination = this.app.install_destinations.find(
        (nodeInfo) => nodeInfo.node_id == this.clusterNodes[0].id
      );
      return installDestination?.eligible;
    },
    nodesInfo() {
      const nodesInfo = {};
      if (this.app) {
        for (const nodeInfo of this.app.install_destinations) {
          if (!nodeInfo.eligible) {
            // show reason why node is not eligible
            const rejectReason = nodeInfo.reject_reason;
            if (rejectReason.message === "max_per_node_limit") {
              const numMaxInstances = rejectReason.parameter;
              nodesInfo[nodeInfo.node_id] = this.$tc(
                `software_center.reason_${rejectReason.message}`,
                numMaxInstances,
                { param: numMaxInstances }
              );
            } else {
              nodesInfo[nodeInfo.node_id] = this.$t(
                `software_center.reason_${rejectReason.message}`,
                { param: rejectReason.parameter }
              );
            }
          } else if (nodeInfo.instances) {
            nodesInfo[nodeInfo.node_id] = this.$tc(
              "software_center.num_instances_installed",
              nodeInfo.instances,
              { num: nodeInfo.instances }
            );
          }
        }
        for (const node of this.clusterStatus) {
          if (!node.online) {
            nodesInfo[node.id] = this.$t("software_center.node_offline");
          }
        }
      }
      return nodesInfo;
    },
    disabledNodes() {
      const nonEligibleNodeIds = this.app.install_destinations
        .filter((nodeInfo) => !nodeInfo.eligible)
        .map((nodeInfo) => nodeInfo.node_id);
      const offlineNodeIds = this.clusterStatus
        .filter((node) => !node.online)
        .map((node) => node.id);
      return [...new Set([...nonEligibleNodeIds, ...offlineNodeIds])];
    },
    nodesWithAdditionalStorage() {
      if (this.appVolumes.length === 0) {
        return [];
      }
      if (!Array.isArray(this.nodesList)) {
        return [];
      }
      return this.nodesList
        .filter((node) => node.additional_disk_count > 0)
        .map((node) => node.node_id);
    },
    hasAdditionalStorageAvailable() {
      return this.nodesWithAdditionalStorage.length > 0;
    },
    additionalVolumes() {
      const output = this.nodesAdditionalDiskInfo[this.selectedNode?.id];
      if (!output) return [];
      const volumes = [...output.mountpoints];
      if (output.default_disk) {
        volumes.push({ ...output.default_disk, default: true });
      }
      return volumes;
    },
    appVolumes() {
      if (
        this.app &&
        this.app.versions &&
        this.app.versions.length &&
        this.app.versions[0].labels &&
        this.app.versions[0].labels["org.nethserver.volumes"]
      ) {
        const volumesString =
          this.app.versions[0].labels["org.nethserver.volumes"];
        return volumesString.split(" ").map((v) => v.trim());
      }
      return [];
    },
  },
  methods: {
    nextStep() {
      if (this.isNextButtonDisabled) {
        return;
      }
      if (this.isLastStep) {
        this.installInstance(this.selectedVolume);
      } else {
        if (
          this.step == "node" &&
          (!this.nodesWithAdditionalStorage.includes(this.selectedNode.id) ||
            this.appVolumes.length === 0)
        ) {
          this.installInstance();
        } else {
          this.step = this.steps[this.stepIndex + 1];
        }
      }
    },
    previousStep() {
      if (!this.isFirstStep) {
        this.selectedVolume = {};
        this.step = this.steps[this.stepIndex - 1];
      }
    },
    onModalShown() {
      this.agreeTerms = false;
      this.clearErrors();
      this.clusterStatus = [];
      this.nodesList = [];
      this.selectedVolume = {};
      this.nodesDefaultDiskInfo = {};
      this.nodesAdditionalDiskInfo = {};
      if (this.clusterNodesCount == 1 && this.canInstallOnSingleNode) {
        this.selectedNode = { ...this.clusterNodes[0], selected: true };
      } else {
        this.selectedNode = null;
      }
      this.listNodes();
      this.getClusterStatus();
    },
    async getClusterStatus() {
      this.loading.getClusterStatus = true;
      this.error.getClusterStatus = "";
      const taskAction = "get-cluster-status";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.getClusterStatusAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.getClusterStatusCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.getClusterStatus = this.getErrorMessage(err);
        return;
      }
    },
    getClusterStatusAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.getClusterStatus = this.$t("error.generic_error");
      this.loading.getClusterStatus = false;
    },
    getClusterStatusCompleted(taskContext, taskResult) {
      this.clusterStatus = taskResult.output.nodes;
      for (const node of this.clusterStatus.filter((n) => n.online)) {
        this.listMountPoints(node.id);
      }
      this.loading.getClusterStatus = false;
    },
    async listNodes() {
      this.error.nodesList = "";
      this.loading.nodesList = true;
      const taskAction = "list-nodes";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.listNodesAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.listNodesCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.nodesList = this.getErrorMessage(err);
        return;
      }
    },
    listNodesAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.nodesList = this.$t("error.generic_error");
      this.loading.nodesList = false;
    },
    listNodesCompleted(taskContext, taskResult) {
      this.nodesList = taskResult.output.nodes;
      this.loading.nodesList = false;
    },
    async listMountPoints(nodeId) {
      const taskAction = "list-mountpoints";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.listMountPointsAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        (taskContext, taskResult) =>
          this.listMountPointsCompleted(taskContext, taskResult, nodeId)
      );
      const res = await to(
        this.createNodeTask(nodeId, {
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(
          `error creating task ${taskAction} for node ${nodeId}`,
          err
        );
        this.error.listMountPoints = this.getErrorMessage(err);
        return;
      }
    },
    listMountPointsAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.listMountPoints = this.$t("error.generic_error");
    },
    listMountPointsCompleted(taskContext, taskResult, nodeId) {
      const output = taskResult.output;
      this.$set(this.nodesAdditionalDiskInfo, nodeId, output);
      if (output.default_disk) {
        this.$set(this.nodesDefaultDiskInfo, nodeId, output.default_disk);
      }
    },
    async installInstance(volumes) {
      this.error.addModule = "";
      const taskAction = "add-module";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.addModuleAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.addModuleCompleted
      );
      const nodeName =
        this.selectedNode.ui_name ||
        this.$t("common.node") + ` ${this.selectedNode.id}`;
      const data = {
        image: this.app.source + ":" + this.appVersion,
        node: parseInt(this.selectedNode.id),
      };
      if (volumes?.path && this.appVolumes.length) {
        data.volumes = {};
        this.appVolumes.forEach((volume) => {
          data.volumes[volume] = volumes.path;
        });
      }
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data,
          extra: {
            title: this.$t("software_center.app_installation", {
              app: this.app.name,
            }),
            description: this.$t("software_center.installing_on_node", {
              node: nodeName,
            }),
            node: nodeName,
            eventId,
            completion: {
              i18nString: "software_center.instance_installed_on_node",
              extraTextParams: ["node"],
              outputTextParams: ["module_id"],
            },
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.addModule = this.getErrorMessage(err);
        return;
      }
      this.$emit("close");
    },
    addModuleAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
    },
    addModuleCompleted(taskContext, taskResult) {
      const moduleId = taskResult.output.module_id;
      this.$emit("installationCompleted", moduleId);
      this.$root.$emit("reloadAppDrawer");
      setTimeout(() => {
        const notification = {
          title: this.$t("backup.schedule_backup"),
          description: this.$t("backup.schedule_backup_for_instance", {
            instance: moduleId,
          }),
          type: "info",
          actionLabel: this.$t("backup.schedule_action"),
          action: {
            type: "changeRoute",
            url: `/backup`,
          },
        };
        this.createNotification(notification);
      }, 15000);
    },
    onModalHidden() {
      this.$emit("close");
      this.clearErrors();
      this.selectedNode = null;
      this.selectedVolume = {};
      this.clusterStatus = [];
      this.nodesList = [];
      this.nodesAdditionalDiskInfo = {};
      this.step = this.steps[0];
    },
    onSelectNode(selectedNode) {
      this.selectedNode = selectedNode;
    },
    onSelectVolume(selectedVolume) {
      this.selectedVolume = selectedVolume;
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
</style>
</file>

<file path="core/ui/src/components/software-center/RestartModuleModal.vue">
<template>
  <NsModal
    size="default"
    :visible="visible"
    :isLoading="loading.restartModule"
    @modal-hidden="onModalHidden"
    @primary-click="restartModule"
    kind="danger"
    :primary-button-disabled="loading.restartModule ? true : false"
  >
    <template slot="title">
      {{ $t("software_center.restart_application") }}
    </template>
    <template slot="content">
      <p>
        {{
          $t("software_center.restart_app", {
            name: appName,
          })
        }}
      </p>
      <div v-if="error.restartModule">
        <NsInlineNotification
          kind="error"
          :title="$t('action.restart-module')"
          :description="error.restartModule"
          :showCloseButton="false"
        />
      </div>
    </template>
    <template slot="secondary-button">{{ $t("common.cancel") }}</template>
    <template slot="primary-button">{{
      $t("software_center.restart_application")
    }}</template>
  </NsModal>
</template>
⋮----
<template slot="title">
      {{ $t("software_center.restart_application") }}
    </template>
⋮----
{{ $t("software_center.restart_application") }}
⋮----
<template slot="content">
      <p>
        {{
          $t("software_center.restart_app", {
            name: appName,
          })
        }}
      </p>
      <div v-if="error.restartModule">
        <NsInlineNotification
          kind="error"
          :title="$t('action.restart-module')"
          :description="error.restartModule"
          :showCloseButton="false"
        />
      </div>
    </template>
⋮----
{{
          $t("software_center.restart_app", {
            name: appName,
          })
        }}
⋮----
<template slot="secondary-button">{{ $t("common.cancel") }}</template>
<template slot="primary-button">{{
      $t("software_center.restart_application")
    }}</template>
⋮----
<script>
import { UtilService, TaskService, IconService } from "@nethserver/ns8-ui-lib";
import to from "await-to-js";
export default {
  name: "RestartModuleModal",
  mixins: [UtilService, TaskService, IconService],
  props: {
    visible: {
      type: Boolean,
      required: true,
    },
    instanceToRestart: {
      type: Object,
      default: null,
    },
  },
  data() {
    return { error: { restartModule: "" }, loading: { restartModule: false } };
  },
  computed: {
    appName() {
      if (!this.instanceToRestart) {
        return "";
      }
      return this.instanceToRestart.ui_name
        ? this.instanceToRestart.ui_name +
            " (" +
            this.instanceToRestart.id +
            ")"
        : this.instanceToRestart.id;
    },
  },
  methods: {
    async restartModule() {
      this.error.restartModule = "";
      this.loading.restartModule = true;
      const taskAction = "restart-module";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.restartModuleAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.restartModuleCompleted
      );
      const res = await to(
        this.createNodeTask(this.instanceToRestart.node, {
          action: taskAction,
          data: {
            module_id: this.instanceToRestart.id,
          },
          extra: {
            title: this.$t("applications.restart_instance_name", {
              instance: this.instanceToRestart.ui_name
                ? this.instanceToRestart.ui_name
                : this.instanceToRestart.id,
            }),
            description: this.$t("applications.restarting"),
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.restartModule = this.getErrorMessage(err);
        this.loading.restartModule = false;
        return;
      }
      this.$emit("hide");
    },
    restartModuleAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.restartModule = this.$t("error.generic_error");
      this.loading.restartModule = false;
    },
    restartModuleCompleted() {
      this.loading.restartModule = false;
      this.$emit("hide");
    },
    onModalHidden() {
      this.clearErrors();
      this.$emit("hide");
    },
  },
};
</script>
</file>

<file path="core/ui/src/components/software-center/SetInstanceLabelModal.vue">
<template>
  <NsModal
    size="default"
    :visible="visible"
    :isLoading="loading"
    @modal-hidden="onModalHidden"
    @primary-click="setInstanceLabel"
  >
    <template slot="title">
      {{ $t("software_center.edit_instance_label") }}
    </template>
    <template slot="content">
      <template v-if="currentInstance">
        <NsTextInput
          ref="inputLabel"
          :label="
            $t('software_center.instance_label') +
            ' (' +
            $t('common.optional') +
            ')'
          "
          v-model="inputLabel"
          :placeholder="$t('common.no_label')"
          :helper-text="$t('software_center.instance_label_tooltip')"
          :disabled="loading"
          maxlength="24"
          data-modal-primary-focus
        />
        <div v-if="error.setInstanceLabel">
          <NsInlineNotification
            kind="error"
            :title="$t('action.set-instance-label')"
            :description="error.setInstanceLabel"
            :showCloseButton="false"
          />
        </div>
      </template>
    </template>
    <template slot="secondary-button">{{ $t("common.cancel") }}</template>
    <template slot="primary-button">{{ $t("common.save") }}</template>
  </NsModal>
</template>
⋮----
<template slot="title">
      {{ $t("software_center.edit_instance_label") }}
    </template>
⋮----
{{ $t("software_center.edit_instance_label") }}
⋮----
<template slot="content">
      <template v-if="currentInstance">
        <NsTextInput
          ref="inputLabel"
          :label="
            $t('software_center.instance_label') +
            ' (' +
            $t('common.optional') +
            ')'
          "
          v-model="inputLabel"
          :placeholder="$t('common.no_label')"
          :helper-text="$t('software_center.instance_label_tooltip')"
          :disabled="loading"
          maxlength="24"
          data-modal-primary-focus
        />
        <div v-if="error.setInstanceLabel">
          <NsInlineNotification
            kind="error"
            :title="$t('action.set-instance-label')"
            :description="error.setInstanceLabel"
            :showCloseButton="false"
          />
        </div>
      </template>
    </template>
⋮----
<template v-if="currentInstance">
        <NsTextInput
          ref="inputLabel"
          :label="
            $t('software_center.instance_label') +
            ' (' +
            $t('common.optional') +
            ')'
          "
          v-model="inputLabel"
          :placeholder="$t('common.no_label')"
          :helper-text="$t('software_center.instance_label_tooltip')"
          :disabled="loading"
          maxlength="24"
          data-modal-primary-focus
        />
        <div v-if="error.setInstanceLabel">
          <NsInlineNotification
            kind="error"
            :title="$t('action.set-instance-label')"
            :description="error.setInstanceLabel"
            :showCloseButton="false"
          />
        </div>
      </template>
⋮----
<template slot="secondary-button">{{ $t("common.cancel") }}</template>
<template slot="primary-button">{{ $t("common.save") }}</template>
⋮----
<script>
import { UtilService, TaskService, IconService } from "@nethserver/ns8-ui-lib";
import to from "await-to-js";
export default {
  name: "SetInstanceLabelModal",
  mixins: [UtilService, TaskService, IconService],
  props: {
    visible: Boolean,
    currentInstance: Object,
    newInstanceLabel: String,
  },
  data() {
    return {
      inputLabel: this.newInstanceLabel || "",
      loading: false,
      error: {
        setInstanceLabel: "",
      },
    };
  },
  watch: {
    newInstanceLabel(newVal) {
      this.inputLabel = newVal || "";
    },
    visible(newVal) {
      // When modal is opened, reset inputLabel to prop value
      if (newVal) {
        this.inputLabel = this.newInstanceLabel || "";
      }
    },
  },
  methods: {
    async setInstanceLabel() {
      this.error.setInstanceLabel = "";
      this.loading = true;
      const taskAction = "set-name";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.setInstanceLabelCompleted
      );
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.setInstanceLabelAborted
      );
      const res = await to(
        this.createModuleTaskForApp(this.currentInstance.id, {
          action: taskAction,
          data: {
            name: this.inputLabel,
          },
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.setInstanceLabel = this.getErrorMessage(err);
        return;
      }
      this.$emit("hide");
    },
    setInstanceLabelAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.setInstanceLabel = this.$t("error.generic_error");
      this.loading = false;
    },
    setInstanceLabelCompleted() {
      this.loading = false;
      this.$emit("hide");
      this.$root.$emit("reloadAppDrawer");
      this.$emit("setInstanceLabelCompleted");
    },
    onModalHidden() {
      this.clearErrors();
      this.$emit("hide");
    },
  },
};
</script>
</file>

<file path="core/ui/src/components/software-center/UpdateAppModal.vue">
<template>
  <NsModal
    size="default"
    :visible="isShown"
    @modal-hidden="onModalHidden"
    @primary-click="updateModule"
    class="no-pad-modal"
  >
    <template slot="title">{{
      app ? $t("software_center.update_app", { app: app.name }) : ""
    }}</template>
    <template v-if="app && instance" slot="content">
      <cv-form @submit.prevent="updateModule">
        <NsInlineNotification
          v-if="isUpdatingToTestingVersion"
          kind="warning"
          :title="$t('software_center.update_to_testing_version')"
          :description="
            $t('software_center.update_to_testing_version_warning', {
              appName: app.name,
            })
          "
          :showCloseButton="false"
        />
        <div>
          {{
            $t(
              isUpdatingToTestingVersion
                ? "software_center.about_to_update_app_to_testing_version"
                : "software_center.about_to_update_app",
              {
                app: instanceLabel,
                version: instance.version,
                newVersion: appVersion,
              }
            )
          }}
        </div>
        <div v-if="error.updateModule">
          <NsInlineNotification
            kind="error"
            :title="$t('action.update-module')"
            :description="error.updateModule"
            :showCloseButton="false"
          />
        </div>
      </cv-form>
    </template>
    <template slot="secondary-button">{{ $t("common.cancel") }}</template>
    <template slot="primary-button">{{
      $t("software_center.update")
    }}</template>
  </NsModal>
</template>
⋮----
<template slot="title">{{
      app ? $t("software_center.update_app", { app: app.name }) : ""
    }}</template>
<template v-if="app && instance" slot="content">
      <cv-form @submit.prevent="updateModule">
        <NsInlineNotification
          v-if="isUpdatingToTestingVersion"
          kind="warning"
          :title="$t('software_center.update_to_testing_version')"
          :description="
            $t('software_center.update_to_testing_version_warning', {
              appName: app.name,
            })
          "
          :showCloseButton="false"
        />
        <div>
          {{
            $t(
              isUpdatingToTestingVersion
                ? "software_center.about_to_update_app_to_testing_version"
                : "software_center.about_to_update_app",
              {
                app: instanceLabel,
                version: instance.version,
                newVersion: appVersion,
              }
            )
          }}
        </div>
        <div v-if="error.updateModule">
          <NsInlineNotification
            kind="error"
            :title="$t('action.update-module')"
            :description="error.updateModule"
            :showCloseButton="false"
          />
        </div>
      </cv-form>
    </template>
⋮----
{{
            $t(
              isUpdatingToTestingVersion
                ? "software_center.about_to_update_app_to_testing_version"
                : "software_center.about_to_update_app",
              {
                app: instanceLabel,
                version: instance.version,
                newVersion: appVersion,
              }
            )
          }}
⋮----
<template slot="secondary-button">{{ $t("common.cancel") }}</template>
<template slot="primary-button">{{
      $t("software_center.update")
    }}</template>
⋮----
<script>
import { UtilService, TaskService, IconService } from "@nethserver/ns8-ui-lib";
import to from "await-to-js";
export default {
  name: "UpdateAppModal",
  mixins: [UtilService, TaskService, IconService],
  props: {
    isShown: Boolean,
    app: { type: [Object, null] },
    instance: { type: [Object, null] },
    isUpdatingToTestingVersion: { type: Boolean, default: false },
  },
  data() {
    return {
      error: {
        updateModule: "",
      },
    };
  },
  computed: {
    instanceLabel() {
      if (!this.instance) {
        return "";
      }
      if (this.instance.ui_name) {
        return `${this.instance.ui_name} (${this.instance.id})`;
      } else {
        return this.instance.id;
      }
    },
    appVersion() {
      if (this.isUpdatingToTestingVersion) {
        // update to testing version
        if (this.app.updates.length) {
          const testingUpdateFound = this.app.updates.find(
            (update) => update.testing_update
          );
          if (testingUpdateFound) {
            return testingUpdateFound.testing_update;
          }
        }
        return "latest";
      } else {
        if (this.app.updates.length) {
          const stableUpdateFound = this.app.updates.find(
            (update) => update.update
          );
          if (stableUpdateFound) {
            return stableUpdateFound.update;
          }
        }
        return "latest";
      }
    },
  },
  methods: {
    async updateModule() {
      this.error.updateModule = "";
      const taskAction = "update-module";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.updateModuleAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.updateModuleCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {
            module_url: this.app.source + ":" + this.appVersion,
            instances: [this.instance.id],
          },
          extra: {
            title: this.$t("software_center.update_app", {
              app: this.instance.ui_name || this.instance.id,
            }),
            description: this.$t("software_center.updating_to_version", {
              version: this.appVersion,
            }),
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.updateModule = this.getErrorMessage(err);
        return;
      }
      this.$emit("hide");
    },
    updateModuleAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
    },
    updateModuleCompleted() {
      this.$emit("updateCompleted");
    },
    onModalHidden() {
      this.clearErrors();
      this.$emit("hide");
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
</style>
</file>

<file path="core/ui/src/components/system-logs/LogHighlightMark.vue">
<template>
  <mark :class="levelClass"
    ><span v-if="beforeTag" class="log-timestamp"
      ><template v-for="(part, i) in beforeParts"
        ><mark v-if="part.isMatch" :key="'b' + i" class="log-search-match">{{
          part.text
        }}</mark
        ><template v-else>{{ part.text }}</template></template
      ></span
    ><span v-if="tagText" class="log-process-tag"
      ><template v-for="(part, i) in tagParts"
        ><mark v-if="part.isMatch" :key="'t' + i" class="log-search-match">{{
          part.text
        }}</mark
        ><template v-else>{{ part.text }}</template></template
      ></span
    ><template v-for="(part, i) in restParts"
      ><mark v-if="part.isMatch" :key="'r' + i" class="log-search-match">{{
        part.text
      }}</mark
      ><template v-else>{{ part.text }}</template></template
    ></mark
  >
</template>
⋮----
><template v-for="(part, i) in beforeParts"
        ><mark v-if="part.isMatch" :key="'b' + i" class="log-search-match">{{
          part.text
        }}</mark
        ><template v-else>{{ part.text }}</template></template
      ></span
⋮----
><mark v-if="part.isMatch" :key="'b' + i" class="log-search-match">{{
          part.text
        }}</mark
><template v-else>{{ part.text }}</template></template
⋮----
><template v-for="(part, i) in tagParts"
        ><mark v-if="part.isMatch" :key="'t' + i" class="log-search-match">{{
          part.text
        }}</mark
        ><template v-else>{{ part.text }}</template></template
      ></span
⋮----
><mark v-if="part.isMatch" :key="'t' + i" class="log-search-match">{{
          part.text
        }}</mark
><template v-else>{{ part.text }}</template></template
⋮----
><template v-for="(part, i) in restParts"
      ><mark v-if="part.isMatch" :key="'r' + i" class="log-search-match">{{
        part.text
      }}</mark
      ><template v-else>{{ part.text }}</template></template
    ></mark
⋮----
><mark v-if="part.isMatch" :key="'r' + i" class="log-search-match">{{
        part.text
      }}</mark
><template v-else>{{ part.text }}</template></template
⋮----
<script>
const LOG_LEVEL_CLASSIFIERS = [
  {
    class: "log-level-error",
    pattern: /\b(?:error|err|fatal|crit|critical)\b/i,
  },
  { class: "log-level-warn", pattern: /\b(?:warn|warning)\b/i },
  { class: "log-level-info", pattern: /\b(?:info|information|notice)\b/i },
  { class: "log-level-debug", pattern: /\b(?:debug|trace)\b/i },
];
const PROCESS_TAG_PATTERN = /^(\S+\s+)(\[[^\]]*\])/;
function escapeRegExp(str) {
  return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
export default {
  name: "LogHighlightMark",
  props: {
    text: {
      type: String,
      required: true,
    },
    searchTerm: {
      type: String,
      default: "",
    },
  },
  computed: {
    levelClass() {
      const level = LOG_LEVEL_CLASSIFIERS.find((l) =>
        l.pattern.test(this.text)
      );
      return level ? level.class : "";
    },
    tagMatch() {
      return PROCESS_TAG_PATTERN.exec(this.text);
    },
    beforeTag() {
      return this.tagMatch ? this.tagMatch[1] : "";
    },
    tagText() {
      return this.tagMatch ? this.tagMatch[2] : "";
    },
    afterTag() {
      return this.tagMatch
        ? this.text.slice(this.tagMatch[0].length)
        : this.text;
    },
    beforeParts() {
      return this.splitBySearchTerm(this.beforeTag);
    },
    tagParts() {
      return this.splitBySearchTerm(this.tagText);
    },
    restParts() {
      return this.splitBySearchTerm(this.afterTag);
    },
  },
  methods: {
    // splits a piece of text so the search term keeps its own clickable
    // mark, even when the whole containing line is also colorized by level
    splitBySearchTerm(text) {
      if (!this.searchTerm) {
        return [{ text, isMatch: false }];
      }
      const re = new RegExp(`(${escapeRegExp(this.searchTerm)})`, "gi");
      return text
        .split(re)
        .filter((part) => part !== "")
        .map((part) => ({
          text: part,
          isMatch: part.toLowerCase() === this.searchTerm.toLowerCase(),
        }));
    },
  },
};
</script>
</file>

<file path="core/ui/src/components/system-logs/LogOutput.vue">
<template>
  <div
    class="logs-output cv-code-snippet-multiline"
    :class="[
      { 'reduced-output-height': numSearches > 1 && !verticalLayout },
      `bx--snippet`,
      `bx--snippet--multi`,
      {
        'bx--snippet--disabled': disabled,
        'bx--snippet--wraptext': wrapText,
        'bx--snippet--light': isLight,
      },
    ]"
    data-code-snippet
  >
    <cv-skeleton-text
      v-if="loading"
      :paragraph="true"
      :line-count="4"
    ></cv-skeleton-text>
    <NsEmptyState
      v-else-if="noLogsFound"
      :title="$t('system_logs.no_log_found')"
      :animationData="GhostDarkBgLottie"
      animationTitle="ghost"
      :loop="1"
      class="margin-auto"
    >
      <template #description>
        <div>{{ $t("system_logs.try_changing_search_filters") }}</div>
      </template>
    </NsEmptyState>
    <div
      v-else
      class="bx--snippet-container"
      :ref="'logsContainer-' + searchId"
      :key="'logsContainer-' + searchId"
    >
      <pre><text-highlight
        :queries="highlightQueries"
        :highlight-component="highlightComponent"
        :search-term="highlight"
      >{{ logText }}</text-highlight></pre>
    </div>
  </div>
</template>
⋮----
<template #description>
        <div>{{ $t("system_logs.try_changing_search_filters") }}</div>
      </template>
⋮----
<div>{{ $t("system_logs.try_changing_search_filters") }}</div>
⋮----
>{{ logText }}</text-highlight></pre>
⋮----
<script>
import { carbonPrefixMixin, themeMixin } from "@carbon/vue/src/mixins";
import { UtilService, LottieService } from "@nethserver/ns8-ui-lib";
import LogHighlightMark from "./LogHighlightMark.vue";
const LOG_LEVEL_QUERIES = [
  /^.*\b(?:ERROR|ERR|FATAL|CRIT(?:ICAL)?)\b.*$/im,
  /^.*\b(?:WARN(?:ING)?)\b.*$/im,
  /^.*\b(?:INFO(?:RMATION)?|NOTICE)\b.*$/im,
  /^.*\b(?:DEBUG|TRACE)\b.*$/im,
];
const PROCESS_TAG_QUERY = /^\S+\s+\[[^\]]*\]/im;
export default {
  name: "LogOutput",
  props: {
    searchId: {
      type: String,
      required: true,
    },
    outputLines: {
      type: Array,
      required: true,
    },
    scrollToBottom: {
      type: Boolean,
      default: true,
    },
    numSearches: {
      type: Number,
      default: 1,
    },
    highlight: {
      type: String,
      default: "",
    },
    verticalLayout: Boolean,
    loading: Boolean,
    wrapText: Boolean,
    light: Boolean,
    disabled: Boolean,
    noLogsFound: Boolean,
  },
  mixins: [carbonPrefixMixin, themeMixin, UtilService, LottieService],
  data() {
    return {
      highlightComponent: LogHighlightMark,
    };
  },
  computed: {
    logText() {
      return this.outputLines.join("\n");
    },
    highlightQueries() {
      return [this.highlight, ...LOG_LEVEL_QUERIES, PROCESS_TAG_QUERY];
    },
  },
  watch: {
    searchId: function () {
      this.$root.$on(`logsStart-${this.searchId}`, this.logsUpdated);
    },
  },
  created() {
    this.$root.$on(`logsUpdated-${this.searchId}`, this.logsUpdated);
  },
  beforeDestroy() {
    this.$root.$off(`logsUpdated-${this.searchId}`);
  },
  methods: {
    logsUpdated() {
      setTimeout(() => {
        if (this.scrollToBottom) {
          this.scrollToBottomOfContainer();
        }
      }, 50);
    },
    scrollToBottomOfContainer() {
      const el = this.$refs[`logsContainer-${this.searchId}`];
      if (el) {
        el.scrollTop = el.scrollHeight;
      }
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
.logs-output.bx--snippet--multi {
  max-width: none;
  min-height: 4rem;
  max-height: 35rem;
  background-color: #161616 !important;
  color: #f4f4f4 !important;
}
.logs-output.reduced-output-height.bx--snippet--multi {
  max-height: 20rem;
}
.margin-auto {
  margin: auto;
}
</style>
⋮----
<style lang="scss">
@import "../../styles/carbon-utils";
.bx--snippet--multi .bx--snippet-container pre {
  overflow-x: visible;
}
.system-logs .logs-output.bx--snippet--multi .bx--snippet-container pre::after {
  background-image: none;
}
.system-logs .logs-output.bx--snippet--multi .bx--snippet-container {
  overflow-y: auto !important;
  flex: 1 1 auto;
}
.logs-output {
  mark.text__highlight {
    background: transparent;
  }
  mark.log-level-error {
    background: transparent;
    color: $inverse-support-01;
    font-weight: 600;
  }
  mark.log-level-warn {
    background: transparent;
    color: $inverse-support-03;
    font-weight: 600;
  }
  mark.log-level-info {
    background: transparent;
    color: $inverse-support-04;
    font-weight: 600;
  }
  mark.log-level-debug {
    background: transparent;
    color: $ui-02;
    font-weight: 600;
  }
  .log-timestamp,
  .log-process-tag {
    color: $ui-02;
    font-weight: 700;
  }
}
</style>
</file>

<file path="core/ui/src/components/system-logs/LogSearch.vue">
<template>
  <cv-tile class="log-search" :light="light">
    <button
      v-if="showCloseButton"
      class="bx--modal-close"
      type="button"
      @click="onClose"
      :aria-label="closeAriaLabel"
    >
      <Close16 class="bx--modal-close__icon" />
    </button>
    <cv-grid
      fullWidth
      :class="['no-padding', { 'mg-top-md': showCloseButton }]"
    >
      <template v-if="filtersShown">
        <cv-row>
          <cv-column :md="verticalLayout ? 8 : 4">
            <label class="bx--label">
              {{ $t("system_logs.context") }}
            </label>
            <cv-content-switcher
              class="mg-bottom-lg"
              @selected="onContextSelected"
            >
              <cv-content-switcher-button
                owner-id="cluster"
                :selected="csbClusterSelected"
                >{{
                  $t("system_logs.context_cluster")
                }}</cv-content-switcher-button
              >
              <cv-content-switcher-button
                owner-id="node"
                :selected="csbNodeSelected"
                >{{
                  $t("system_logs.context_node")
                }}</cv-content-switcher-button
              >
              <cv-content-switcher-button
                owner-id="module"
                :selected="csbModuleSelected"
                >{{
                  $t("system_logs.context_module")
                }}</cv-content-switcher-button
              >
            </cv-content-switcher>
          </cv-column>
          <cv-column v-show="csbNodeSelected" :md="verticalLayout ? 8 : 4">
            <cv-combo-box
              v-model="internalSelectedNodeId"
              :label="$t('common.choose')"
              :title="$t('system_logs.context_node')"
              :invalid-message="error.selectedNode"
              :auto-filter="true"
              :auto-highlight="true"
              :options="nodes"
              class="mg-bottom-lg"
              key="csbNode"
            >
            </cv-combo-box>
          </cv-column>
          <cv-column v-show="csbModuleSelected" :md="verticalLayout ? 8 : 4">
            <cv-combo-box
              v-model="internalSelectedAppId"
              :label="$t('common.choose')"
              :title="$t('system_logs.context_module')"
              :invalid-message="error.selectedApp"
              :auto-filter="true"
              :auto-highlight="true"
              :options="apps"
              :disabled="loadingApps"
              class="mg-bottom-lg"
              key="csbApp"
            >
            </cv-combo-box>
          </cv-column>
        </cv-row>
        <cv-row>
          <cv-column :md="verticalLayout ? 8 : 4">
            <cv-text-input
              :label="
                $t('system_logs.search_query') +
                ' (' +
                $t('common.optional') +
                ')'
              "
              v-model.trim="internalSearchQuery"
              :placeholder="searchPlaceholder"
              :helper-text="searchHelperText"
              @keypress.enter="onEnterKeyPress()"
              class="search-query mg-bottom-lg"
            >
            </cv-text-input>
          </cv-column>
          <cv-column :md="verticalLayout ? 8 : 4">
            <NsToggle
              :label="$t('system_logs.regexp')"
              value="regexp"
              :form-item="true"
              v-model="internalRegexp"
              class="mg-bottom-lg"
              ref="regexp"
            >
              <template slot="text-left">{{ $t("common.disabled") }}</template>
              <template slot="text-right">{{ $t("common.enabled") }}</template>
            </NsToggle>
          </cv-column>
        </cv-row>
        <cv-row>
          <cv-column :md="verticalLayout ? 4 : 2">
            <label class="bx--label">
              {{ $t("system_logs.mode") }}
            </label>
            <cv-content-switcher
              class="mg-bottom-lg"
              @selected="onModeSelected"
            >
              <cv-content-switcher-button
                owner-id="dump"
                :selected="csbDumpModeSelected"
                >{{ $t("system_logs.dump") }}</cv-content-switcher-button
              >
              <cv-content-switcher-button
                owner-id="follow"
                :selected="csbFollowModeSelected"
                >{{ $t("system_logs.follow") }}</cv-content-switcher-button
              >
            </cv-content-switcher>
          </cv-column>
          <cv-column v-if="!internalFollowLogs" :md="verticalLayout ? 4 : 2">
            <cv-text-input
              :label="$t('system_logs.max_lines')"
              v-model="internalMaxLines"
              :invalid-message="error.maxLines"
              type="number"
              min="1"
              :max="MAX_LINES_LIMIT"
              @keypress.enter="onEnterKeyPress()"
              class="mg-bottom-lg"
            >
            </cv-text-input>
          </cv-column>
        </cv-row>
        <cv-row v-if="!internalFollowLogs">
          <cv-column :md="verticalLayout ? 8 : 4">
            <div class="interval-group mg-bottom-lg">
              <cv-date-picker
                kind="single"
                :cal-options="calOptions"
                :date-label="$t('system_logs.start_date')"
                v-model="internalStartDate"
                class="interval-date"
                :invalid-message="error.startDate"
              >
              </cv-date-picker>
              <div class="interval-time">
                <NsTimePicker
                  hideClearButton
                  v-model="internalStartTime"
                  :label="$t('system_logs.start_time_label')"
                ></NsTimePicker>
                <div class="bx--form__helper-text">
                  {{ $t("system_logs.time_format_helper") }}
                </div>
              </div>
            </div>
          </cv-column>
          <cv-column :md="verticalLayout ? 8 : 4">
            <div class="interval-group mg-bottom-lg">
              <cv-date-picker
                kind="single"
                :cal-options="calOptions"
                :date-label="$t('system_logs.end_date')"
                v-model="internalEndDate"
                class="interval-date"
                :invalid-message="error.endDate"
              >
              </cv-date-picker>
              <div class="interval-time">
                <NsTimePicker
                  hideClearButton
                  v-model="internalEndTime"
                  :label="$t('system_logs.end_time_label')"
                ></NsTimePicker>
                <div class="bx--form__helper-text">
                  {{ $t("system_logs.time_format_helper") }}
                </div>
              </div>
            </div>
          </cv-column>
        </cv-row>
        <cv-row v-if="!internalFollowLogs">
          <cv-column :md="verticalLayout ? 8 : 4">
            <cv-select
              :label="$t('system_logs.timezone')"
              class="mg-bottom-lg"
              v-model="internalTimezone"
            >
              <cv-select-option disabled selected hidden>{{
                $t("system_logs.select_timezone")
              }}</cv-select-option>
              <cv-select-option value="local">
                {{ $t("system_logs.local") }}
              </cv-select-option>
              <cv-select-option value="utc">
                {{ $t("system_logs.utc") }}
              </cv-select-option>
            </cv-select>
          </cv-column>
        </cv-row>
        <cv-row v-if="lokiInstances.length > 1">
          <cv-column :md="verticalLayout ? 8 : 4">
            <NsInlineNotification
              kind="info"
              :title="$t('system_logs.loki_instance_title')"
              :description="$t('system_logs.loki_instance_description')"
              :showCloseButton="false"
            />
          </cv-column>
        </cv-row>
        <cv-row v-if="lokiInstances.length > 1">
          <cv-column :md="verticalLayout ? 8 : 4">
            <NsComboBox
              v-model="internalSelectedLokiId"
              :label="$t('common.choose')"
              :title="$t('system_logs.loki_instance')"
              :invalid-message="error.selectedLoki"
              :auto-filter="true"
              :auto-highlight="true"
              :options="lokiInstances"
              :disabled="loadingLoki"
              class="mg-bottom-lg"
              tooltipAlignment="center"
              tooltipDirection="top"
              ><template slot="tooltip">
                {{ $t("system_logs.loki_tooltip") }}
              </template>
            </NsComboBox>
          </cv-column>
        </cv-row>
      </template>
    </cv-grid>
    <cv-grid fullWidth class="no-padding">
      <cv-row v-if="!filtersShown" class="mg-bottom-md">
        <cv-column>
          <div
            :class="[
              'paragraph-line-height',
              { 'pad-right-lg': showCloseButton },
            ]"
          >
            <span class="filter-collapsed">
              <strong>{{ $t("system_logs.context") }}</strong
              >:
              <span v-if="internalContext == 'cluster'">{{
                $t("system_logs.context_cluster")
              }}</span>
              <span v-else-if="internalContext == 'node'">
                {{ selectedNode ? selectedNode.label : "-" }}
              </span>
              <span v-else-if="internalContext == 'module'">
                {{ selectedApp ? selectedApp.label : "-" }}</span
              >
            </span>
            <span class="filter-collapsed"
              ><strong>{{ $t("system_logs.search_query") }}</strong
              >: "<span>{{ internalSearchQuery }}</span
              >"</span
            >
            <span class="filter-collapsed"
              ><strong>{{ $t("system_logs.regexp") }}</strong
              >:
              <span>{{
                internalRegexp ? $t("common.enabled") : $t("common.disabled")
              }}</span></span
            >
            <span class="filter-collapsed"
              ><strong>{{ $t("system_logs.start") }}</strong
              >:
              <span>{{
                internalStartDate + " " + internalStartTime
              }}</span></span
            >
            <span class="filter-collapsed"
              ><strong>{{ $t("system_logs.end") }}</strong
              >:
              <span>{{ internalEndDate + " " + internalEndTime }}</span></span
            >
            <span class="filter-collapsed"
              ><strong>{{ $t("system_logs.max_lines") }}</strong
              >: <span>{{ internalMaxLines }}</span></span
            >
            <span class="filter-collapsed"
              ><strong>{{ $t("system_logs.follow_logs") }}</strong
              >:
              <span>{{
                internalFollowLogs
                  ? $t("common.enabled")
                  : $t("common.disabled")
              }}</span></span
            >
            <span v-if="!internalFollowLogs" class="filter-collapsed"
              ><strong>{{ $t("system_logs.timezone") }}</strong
              >: <span>{{ internalTimezone }}</span></span
            >
          </div>
        </cv-column>
      </cv-row>
      <cv-row>
        <cv-column class="logs-output-toolbar">
          <NsButton
            v-if="isFollowing"
            kind="primary"
            class="search-button mg-bottom-sm"
            :icon="Close20"
            :loading="loading.stopFollowing"
            :disabled="loading.stopFollowing"
            @click="logsStop"
            key="stop-following"
            >{{ $t("system_logs.stop_following") }}</NsButton
          >
          <NsButton
            v-else
            kind="primary"
            class="search-button mg-bottom-sm"
            :icon="Search20"
            :loading="loading.logs"
            :disabled="
              !isWebsocketConnected ||
              loading.logs ||
              loadingApps ||
              loadingLoki
            "
            @click="logsStart"
            key="search"
            >{{
              internalFollowLogs
                ? $t("system_logs.follow")
                : $t("system_logs.search")
            }}</NsButton
          >
          <template v-if="searchStarted">
            <NsButton
              kind="secondary"
              :icon="Erase20"
              @click="clearLogs"
              class="mg-right mg-bottom-sm"
              >{{ $t("system_logs.clear_logs") }}</NsButton
            >
            <cv-tooltip
              alignment="center"
              direction="top"
              :tip="
                justCopied
                  ? $t('system_logs.copied_to_clipboard')
                  : $t('common.copy_to_clipboard')
              "
              class="mg-right mg-bottom-sm"
            >
              <NsButton
                kind="tertiary"
                :icon="Copy20"
                :disabled="!outputLines.length || loading.logs"
                @click="copyLogs"
                >{{ $t("system_logs.copy_output") }}</NsButton
              >
            </cv-tooltip>
            <div class="checkbox-filter">
              <cv-checkbox
                :label="$t('system_logs.wrap_text')"
                v-model="wrapText"
                value="checkWrapText"
                class="mg-right mg-bottom-sm"
              />
            </div>
            <div class="checkbox-filter">
              <cv-checkbox
                :label="$t('system_logs.scroll_to_bottom')"
                v-model="scrollToBottom"
                value="checkScrollToBottom"
                class="item mg-bottom-sm"
              />
            </div>
          </template>
          <span
            v-if="searchStarted && !loading.logs && outputLines.length"
            class="results-feedback mg-bottom-sm"
          >
            {{ resultsFeedback }}
          </span>
        </cv-column>
      </cv-row>
      <cv-row v-if="searchStarted">
        <cv-column>
          <LogOutput
            :searchId="searchId"
            :scrollToBottom="scrollToBottom"
            :wrapText="wrapText"
            :loading="loading.logs"
            :verticalLayout="verticalLayout"
            :numSearches="numSearches"
            :noLogsFound="noLogsFound"
            :light="false"
            :outputLines="outputLines"
            :highlight="highlight"
            :key="'logOutput-' + searchId"
          />
        </cv-column>
      </cv-row>
    </cv-grid>
  </cv-tile>
</template>
⋮----
<template v-if="filtersShown">
        <cv-row>
          <cv-column :md="verticalLayout ? 8 : 4">
            <label class="bx--label">
              {{ $t("system_logs.context") }}
            </label>
            <cv-content-switcher
              class="mg-bottom-lg"
              @selected="onContextSelected"
            >
              <cv-content-switcher-button
                owner-id="cluster"
                :selected="csbClusterSelected"
                >{{
                  $t("system_logs.context_cluster")
                }}</cv-content-switcher-button
              >
              <cv-content-switcher-button
                owner-id="node"
                :selected="csbNodeSelected"
                >{{
                  $t("system_logs.context_node")
                }}</cv-content-switcher-button
              >
              <cv-content-switcher-button
                owner-id="module"
                :selected="csbModuleSelected"
                >{{
                  $t("system_logs.context_module")
                }}</cv-content-switcher-button
              >
            </cv-content-switcher>
          </cv-column>
          <cv-column v-show="csbNodeSelected" :md="verticalLayout ? 8 : 4">
            <cv-combo-box
              v-model="internalSelectedNodeId"
              :label="$t('common.choose')"
              :title="$t('system_logs.context_node')"
              :invalid-message="error.selectedNode"
              :auto-filter="true"
              :auto-highlight="true"
              :options="nodes"
              class="mg-bottom-lg"
              key="csbNode"
            >
            </cv-combo-box>
          </cv-column>
          <cv-column v-show="csbModuleSelected" :md="verticalLayout ? 8 : 4">
            <cv-combo-box
              v-model="internalSelectedAppId"
              :label="$t('common.choose')"
              :title="$t('system_logs.context_module')"
              :invalid-message="error.selectedApp"
              :auto-filter="true"
              :auto-highlight="true"
              :options="apps"
              :disabled="loadingApps"
              class="mg-bottom-lg"
              key="csbApp"
            >
            </cv-combo-box>
          </cv-column>
        </cv-row>
        <cv-row>
          <cv-column :md="verticalLayout ? 8 : 4">
            <cv-text-input
              :label="
                $t('system_logs.search_query') +
                ' (' +
                $t('common.optional') +
                ')'
              "
              v-model.trim="internalSearchQuery"
              :placeholder="searchPlaceholder"
              :helper-text="searchHelperText"
              @keypress.enter="onEnterKeyPress()"
              class="search-query mg-bottom-lg"
            >
            </cv-text-input>
          </cv-column>
          <cv-column :md="verticalLayout ? 8 : 4">
            <NsToggle
              :label="$t('system_logs.regexp')"
              value="regexp"
              :form-item="true"
              v-model="internalRegexp"
              class="mg-bottom-lg"
              ref="regexp"
            >
              <template slot="text-left">{{ $t("common.disabled") }}</template>
              <template slot="text-right">{{ $t("common.enabled") }}</template>
            </NsToggle>
          </cv-column>
        </cv-row>
        <cv-row>
          <cv-column :md="verticalLayout ? 4 : 2">
            <label class="bx--label">
              {{ $t("system_logs.mode") }}
            </label>
            <cv-content-switcher
              class="mg-bottom-lg"
              @selected="onModeSelected"
            >
              <cv-content-switcher-button
                owner-id="dump"
                :selected="csbDumpModeSelected"
                >{{ $t("system_logs.dump") }}</cv-content-switcher-button
              >
              <cv-content-switcher-button
                owner-id="follow"
                :selected="csbFollowModeSelected"
                >{{ $t("system_logs.follow") }}</cv-content-switcher-button
              >
            </cv-content-switcher>
          </cv-column>
          <cv-column v-if="!internalFollowLogs" :md="verticalLayout ? 4 : 2">
            <cv-text-input
              :label="$t('system_logs.max_lines')"
              v-model="internalMaxLines"
              :invalid-message="error.maxLines"
              type="number"
              min="1"
              :max="MAX_LINES_LIMIT"
              @keypress.enter="onEnterKeyPress()"
              class="mg-bottom-lg"
            >
            </cv-text-input>
          </cv-column>
        </cv-row>
        <cv-row v-if="!internalFollowLogs">
          <cv-column :md="verticalLayout ? 8 : 4">
            <div class="interval-group mg-bottom-lg">
              <cv-date-picker
                kind="single"
                :cal-options="calOptions"
                :date-label="$t('system_logs.start_date')"
                v-model="internalStartDate"
                class="interval-date"
                :invalid-message="error.startDate"
              >
              </cv-date-picker>
              <div class="interval-time">
                <NsTimePicker
                  hideClearButton
                  v-model="internalStartTime"
                  :label="$t('system_logs.start_time_label')"
                ></NsTimePicker>
                <div class="bx--form__helper-text">
                  {{ $t("system_logs.time_format_helper") }}
                </div>
              </div>
            </div>
          </cv-column>
          <cv-column :md="verticalLayout ? 8 : 4">
            <div class="interval-group mg-bottom-lg">
              <cv-date-picker
                kind="single"
                :cal-options="calOptions"
                :date-label="$t('system_logs.end_date')"
                v-model="internalEndDate"
                class="interval-date"
                :invalid-message="error.endDate"
              >
              </cv-date-picker>
              <div class="interval-time">
                <NsTimePicker
                  hideClearButton
                  v-model="internalEndTime"
                  :label="$t('system_logs.end_time_label')"
                ></NsTimePicker>
                <div class="bx--form__helper-text">
                  {{ $t("system_logs.time_format_helper") }}
                </div>
              </div>
            </div>
          </cv-column>
        </cv-row>
        <cv-row v-if="!internalFollowLogs">
          <cv-column :md="verticalLayout ? 8 : 4">
            <cv-select
              :label="$t('system_logs.timezone')"
              class="mg-bottom-lg"
              v-model="internalTimezone"
            >
              <cv-select-option disabled selected hidden>{{
                $t("system_logs.select_timezone")
              }}</cv-select-option>
              <cv-select-option value="local">
                {{ $t("system_logs.local") }}
              </cv-select-option>
              <cv-select-option value="utc">
                {{ $t("system_logs.utc") }}
              </cv-select-option>
            </cv-select>
          </cv-column>
        </cv-row>
        <cv-row v-if="lokiInstances.length > 1">
          <cv-column :md="verticalLayout ? 8 : 4">
            <NsInlineNotification
              kind="info"
              :title="$t('system_logs.loki_instance_title')"
              :description="$t('system_logs.loki_instance_description')"
              :showCloseButton="false"
            />
          </cv-column>
        </cv-row>
        <cv-row v-if="lokiInstances.length > 1">
          <cv-column :md="verticalLayout ? 8 : 4">
            <NsComboBox
              v-model="internalSelectedLokiId"
              :label="$t('common.choose')"
              :title="$t('system_logs.loki_instance')"
              :invalid-message="error.selectedLoki"
              :auto-filter="true"
              :auto-highlight="true"
              :options="lokiInstances"
              :disabled="loadingLoki"
              class="mg-bottom-lg"
              tooltipAlignment="center"
              tooltipDirection="top"
              ><template slot="tooltip">
                {{ $t("system_logs.loki_tooltip") }}
              </template>
            </NsComboBox>
          </cv-column>
        </cv-row>
      </template>
⋮----
{{ $t("system_logs.context") }}
⋮----
>{{
                  $t("system_logs.context_cluster")
                }}</cv-content-switcher-button
⋮----
>{{
                  $t("system_logs.context_node")
                }}</cv-content-switcher-button
⋮----
>{{
                  $t("system_logs.context_module")
                }}</cv-content-switcher-button
⋮----
<template slot="text-left">{{ $t("common.disabled") }}</template>
<template slot="text-right">{{ $t("common.enabled") }}</template>
⋮----
{{ $t("system_logs.mode") }}
⋮----
>{{ $t("system_logs.dump") }}</cv-content-switcher-button
⋮----
>{{ $t("system_logs.follow") }}</cv-content-switcher-button
⋮----
{{ $t("system_logs.time_format_helper") }}
⋮----
{{ $t("system_logs.time_format_helper") }}
⋮----
<cv-select-option disabled selected hidden>{{
                $t("system_logs.select_timezone")
              }}</cv-select-option>
⋮----
{{ $t("system_logs.local") }}
⋮----
{{ $t("system_logs.utc") }}
⋮----
><template slot="tooltip">
                {{ $t("system_logs.loki_tooltip") }}
              </template>
⋮----
{{ $t("system_logs.loki_tooltip") }}
⋮----
<strong>{{ $t("system_logs.context") }}</strong
⋮----
<span v-if="internalContext == 'cluster'">{{
                $t("system_logs.context_cluster")
              }}</span>
⋮----
{{ selectedNode ? selectedNode.label : "-" }}
⋮----
{{ selectedApp ? selectedApp.label : "-" }}</span
⋮----
><strong>{{ $t("system_logs.search_query") }}</strong
>: "<span>{{ internalSearchQuery }}</span
⋮----
><strong>{{ $t("system_logs.regexp") }}</strong
⋮----
<span>{{
                internalRegexp ? $t("common.enabled") : $t("common.disabled")
              }}</span></span
⋮----
><strong>{{ $t("system_logs.start") }}</strong
⋮----
<span>{{
                internalStartDate + " " + internalStartTime
              }}</span></span
⋮----
><strong>{{ $t("system_logs.end") }}</strong
⋮----
<span>{{ internalEndDate + " " + internalEndTime }}</span></span
⋮----
><strong>{{ $t("system_logs.max_lines") }}</strong
>: <span>{{ internalMaxLines }}</span></span
⋮----
><strong>{{ $t("system_logs.follow_logs") }}</strong
⋮----
<span>{{
                internalFollowLogs
                  ? $t("common.enabled")
                  : $t("common.disabled")
              }}</span></span
⋮----
><strong>{{ $t("system_logs.timezone") }}</strong
>: <span>{{ internalTimezone }}</span></span
⋮----
>{{ $t("system_logs.stop_following") }}</NsButton
⋮----
>{{
              internalFollowLogs
                ? $t("system_logs.follow")
                : $t("system_logs.search")
            }}</NsButton
⋮----
<template v-if="searchStarted">
            <NsButton
              kind="secondary"
              :icon="Erase20"
              @click="clearLogs"
              class="mg-right mg-bottom-sm"
              >{{ $t("system_logs.clear_logs") }}</NsButton
            >
            <cv-tooltip
              alignment="center"
              direction="top"
              :tip="
                justCopied
                  ? $t('system_logs.copied_to_clipboard')
                  : $t('common.copy_to_clipboard')
              "
              class="mg-right mg-bottom-sm"
            >
              <NsButton
                kind="tertiary"
                :icon="Copy20"
                :disabled="!outputLines.length || loading.logs"
                @click="copyLogs"
                >{{ $t("system_logs.copy_output") }}</NsButton
              >
            </cv-tooltip>
            <div class="checkbox-filter">
              <cv-checkbox
                :label="$t('system_logs.wrap_text')"
                v-model="wrapText"
                value="checkWrapText"
                class="mg-right mg-bottom-sm"
              />
            </div>
            <div class="checkbox-filter">
              <cv-checkbox
                :label="$t('system_logs.scroll_to_bottom')"
                v-model="scrollToBottom"
                value="checkScrollToBottom"
                class="item mg-bottom-sm"
              />
            </div>
          </template>
⋮----
>{{ $t("system_logs.clear_logs") }}</NsButton
⋮----
>{{ $t("system_logs.copy_output") }}</NsButton
⋮----
{{ resultsFeedback }}
⋮----
<script>
import { mapState } from "vuex";
import LogOutput from "./LogOutput.vue";
import {
  UtilService,
  IconService,
  DateTimeService,
} from "@nethserver/ns8-ui-lib";
import Close16 from "@carbon/icons-vue/es/close/16";
const LOG_TIMESTAMP_PATTERN = /^(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2})/;
export default {
  name: "LogSearch",
  props: {
    searchId: {
      type: String,
      required: true,
    },
    nodes: {
      type: Array,
      required: true,
    },
    apps: {
      type: Array,
      required: true,
    },
    lokiInstances: {
      type: Array,
      required: true,
    },
    numSearches: {
      type: Number,
      default: 1,
    },
    searchQuery: {
      type: String,
      default: "",
    },
    context: {
      type: String,
      default: "cluster",
      validator: (val) => ["cluster", "node", "module"].includes(val),
    },
    selectedNodeId: {
      type: String,
      default: "",
    },
    selectedAppId: {
      type: String,
      default: "",
    },
    selectedLokiId: {
      type: String,
      default: "",
    },
    maxLines: {
      type: String,
      default: "500",
    },
    startDate: {
      type: String,
      default: "",
    },
    startTime: {
      type: String,
      default: "",
    },
    endDate: {
      type: String,
      default: "",
    },
    endTime: {
      type: String,
      default: "",
    },
    timezone: {
      type: String,
      default: "",
    },
    startSearchCommand: {
      type: Number,
      default: 0,
    },
    mainSearch: Boolean,
    followLogs: Boolean,
    regexp: Boolean,
    filtersShown: {
      type: Boolean,
      default: true,
    },
    verticalLayout: Boolean,
    loadingApps: Boolean,
    loadingLoki: Boolean,
    nodesInfo: {
      type: Array,
      default: () => [],
    },
    closeAriaLabel: { type: String, default: "Close modal" },
    light: Boolean,
  },
  components: { LogOutput, Close16 },
  mixins: [UtilService, IconService, DateTimeService],
  data() {
    return {
      MAX_LINES_LIMIT: 2000,
      internalContext: "",
      internalSearchQuery: "",
      internalRegexp: false,
      calOptions: {
        dateFormat: "Y-m-d",
      },
      internalStartDate: "",
      internalEndDate: "",
      internalStartTime: "",
      internalEndTime: "",
      internalMaxLines: "",
      internalTimezone: "",
      wrapText: true,
      internalFollowLogs: false,
      outputLines: [],
      isFollowing: false,
      internalSelectedNodeId: "",
      internalSelectedAppId: "",
      internalSelectedLokiId: "",
      scrollToBottom: true,
      searchStarted: false,
      noLogsFound: false,
      highlight: "",
      // filters of the search that ran, the form may have changed since
      searchedCriteria: {
        context: "",
        nodeId: "",
        appId: "",
        query: "",
        regexp: false,
        followLogs: false,
        startDate: "",
        startTime: "",
        endDate: "",
        endTime: "",
        maxLines: "",
        timezone: "",
        lokiId: "",
      },
      bufferTruncated: false,
      abortReason: "",
      justCopied: false,
      copiedTimer: null,
      loading: {
        logs: false,
        stopFollowing: false,
      },
      error: {
        startDate: "",
        startTime: "",
        endDate: "",
        endTime: "",
        maxLines: "",
        selectedNode: "",
        selectedApp: "",
        selectedLoki: "",
      },
    };
  },
  computed: {
    ...mapState(["isWebsocketConnected"]),
    csbClusterSelected() {
      return this.internalContext === "cluster";
    },
    csbNodeSelected() {
      return this.internalContext === "node";
    },
    csbModuleSelected() {
      return this.internalContext === "module";
    },
    selectedApp() {
      return this.apps.find((app) => app.value == this.internalSelectedAppId);
    },
    selectedLoki() {
      return this.lokiInstances.find(
        (instance) => instance.value == this.internalSelectedLokiId
      );
    },
    selectedNode() {
      return this.nodes.find(
        (node) => node.value == this.internalSelectedNodeId
      );
    },
    showCloseButton() {
      return this.numSearches > 1;
    },
    csbDumpModeSelected() {
      return !this.internalFollowLogs;
    },
    csbFollowModeSelected() {
      return this.internalFollowLogs;
    },
    searchPlaceholder() {
      return this.internalRegexp
        ? this.$t("common.eg_value", { value: "(?i)(error|failed)" })
        : this.$t("common.eg_value", { value: "Connect call failed" });
    },
    searchHelperText() {
      return this.internalRegexp
        ? this.$t("system_logs.regexp_helper")
        : this.$t("system_logs.substring_helper");
    },
    logsInterval() {
      const boundaries = [
        this.findTimestamp(false),
        this.findTimestamp(true),
      ].filter(Boolean);
      if (!boundaries.length) {
        return null;
      }
      boundaries.sort();
      return {
        from: boundaries[0],
        to: boundaries[boundaries.length - 1],
      };
    },
    resultsFeedback() {
      const numLines = this.outputLines.length;
      const interval = this.logsInterval;
      if (this.searchedCriteria.followLogs) {
        return interval
          ? this.$t("system_logs.showing_lines", {
              n: numLines,
              from: interval.from,
              to: interval.to,
            })
          : this.$t("system_logs.showing_lines_no_interval", { n: numLines });
      }
      return interval
        ? this.$t("system_logs.showing_lines_of", {
            n: numLines,
            max: this.searchedCriteria.maxLines,
            from: interval.from,
            to: interval.to,
          })
        : this.$t("system_logs.showing_lines_of_no_interval", {
            n: numLines,
            max: this.searchedCriteria.maxLines,
          });
    },
  },
  watch: {
    searchQuery: function () {
      if (this.mainSearch) {
        this.internalSearchQuery = this.searchQuery;
      }
    },
    internalSearchQuery: function () {
      if (this.mainSearch) {
        this.$emit("updateSearchQuery", this.internalSearchQuery);
      }
    },
    regexp: function () {
      if (this.mainSearch) {
        this.internalRegexp = this.regexp;
      }
    },
    internalRegexp: function () {
      if (this.mainSearch) {
        this.$emit("updateRegexp", this.internalRegexp);
      }
    },
    isWebsocketConnected: function () {
      if (
        this.isWebsocketConnected ||
        !(this.loading.logs || this.isFollowing)
      ) {
        return;
      }
      this.onQueryAborted(
        this.$t("system_logs.websocket_disconnected"),
        "connection to the server lost"
      );
    },
    timezone: function () {
      if (this.mainSearch) {
        this.internalTimezone = this.timezone;
      }
    },
    internalTimezone: function () {
      if (this.mainSearch) {
        this.$emit("updateTimezone", this.internalTimezone);
      }
    },
    context: function () {
      if (this.mainSearch) {
        this.internalContext = this.context;
      }
    },
    internalContext: function () {
      if (this.mainSearch) {
        this.$emit("updateContext", this.internalContext);
      }
    },
    selectedNodeId: function () {
      if (this.mainSearch && this.nodes.length) {
        this.$nextTick(() => {
          this.internalSelectedNodeId = this.selectedNodeId;
        });
      }
    },
    internalSelectedNodeId: function () {
      if (this.mainSearch) {
        this.$emit("updateSelectedNodeId", this.internalSelectedNodeId);
      }
    },
    nodes: function () {
      if (this.mainSearch && this.nodes.length) {
        this.$nextTick(() => {
          this.internalSelectedNodeId = this.selectedNodeId;
        });
      }
    },
    selectedAppId: function () {
      if (this.mainSearch && this.apps.length) {
        this.$nextTick(() => {
          this.internalSelectedAppId = this.selectedAppId;
        });
      }
    },
    internalSelectedAppId: function () {
      if (this.mainSearch) {
        this.$emit("updateSelectedAppId", this.internalSelectedAppId);
      }
    },
    apps: function () {
      if (this.mainSearch && this.apps.length) {
        this.$nextTick(() => {
          this.internalSelectedAppId = this.selectedAppId;
        });
      }
    },
    lokiInstances: function () {
      if (this.mainSearch && this.lokiInstances.length) {
        this.$nextTick(() => {
          this.internalSelectedLokiId = this.selectedLokiId;
        });
      }
    },
    selectedLokiId: function () {
      if (this.mainSearch && this.lokiInstances.length) {
        this.$nextTick(() => {
          this.internalSelectedLokiId = this.selectedLokiId;
        });
      }
    },
    internalSelectedLokiId: function () {
      if (this.mainSearch && this.lokiInstances.length) {
        this.$emit("updateSelectedLokiId", this.internalSelectedLokiId);
      }
    },
    followLogs: function () {
      if (this.mainSearch) {
        this.internalFollowLogs = this.followLogs;
      }
    },
    internalFollowLogs: function () {
      if (this.mainSearch) {
        this.$emit("updateFollowLogs", this.internalFollowLogs);
      }
    },
    maxLines: function () {
      if (this.mainSearch) {
        this.internalMaxLines = this.maxLines;
      }
    },
    internalMaxLines: function () {
      if (this.mainSearch) {
        this.$emit("updateMaxLines", this.internalMaxLines);
      }
    },
    startDate: function () {
      if (this.mainSearch) {
        this.internalStartDate = this.startDate;
      }
    },
    internalStartDate: function () {
      if (this.mainSearch) {
        this.$emit("updateStartDate", this.internalStartDate);
      }
    },
    endDate: function () {
      if (this.mainSearch) {
        this.internalEndDate = this.endDate;
      }
    },
    internalEndDate: function () {
      if (this.mainSearch) {
        this.$emit("updateEndDate", this.internalEndDate);
      }
    },
    startTime: function () {
      if (this.mainSearch) {
        this.internalStartTime = this.startTime;
      }
    },
    internalStartTime: function () {
      if (this.mainSearch) {
        this.$emit("updateStartTime", this.internalStartTime);
      }
    },
    endTime: function () {
      if (this.mainSearch) {
        this.internalEndTime = this.endTime;
      }
    },
    internalEndTime: function () {
      if (this.mainSearch) {
        this.$emit("updateEndTime", this.internalEndTime);
      }
    },
    startSearchCommand: function () {
      if (this.mainSearch && this.startSearchCommand > 0) {
        this.logsStart();
      }
    },
  },
  created() {
    this.initFilters();
    this.$root.$on("logSearchClosed", this.onLogSearchClosed);
  },
  beforeDestroy() {
    this.$root.$off(`logsStart-${this.searchId}`);
    this.$root.$off(`logsStop-${this.searchId}`);
    this.$root.$off("logSearchClosed");
    clearTimeout(this.copiedTimer);
    if (this.pid) {
      this.logsStop();
    }
  },
  methods: {
    findTimestamp(fromEnd) {
      const numLines = this.outputLines.length;
      for (let i = 0; i < numLines; i++) {
        const line = this.outputLines[fromEnd ? numLines - 1 - i : i];
        const match = LOG_TIMESTAMP_PATTERN.exec(line);
        if (match) {
          return `${match[1]} ${match[2]}`;
        }
      }
      return null;
    },
    onContextSelected(value) {
      this.internalContext = value;
    },
    initFilters() {
      this.clearErrors(this);
      this.internalStartDate = this.formatDate(
        this.subDays(new Date(), 1),
        "yyyy-MM-dd"
      );
      this.internalEndDate = this.formatDate(new Date(), "yyyy-MM-dd");
      this.internalStartTime = "00:00";
      this.internalEndTime = "23:59";
      this.internalContext = "cluster";
      this.internalSelectedAppId = "";
      this.internalSelectedLokiId = this.selectedLokiId;
      this.internalSelectedNodeId = "";
      this.internalSearchQuery = "";
      this.internalTimezone = "local";
      this.internalMaxLines = "500";
      this.internalFollowLogs = false;
      this.internalRegexp = false;
    },
    validateSearchLogs() {
      this.clearErrors();
      let isValidationOk = true;
      if (this.internalContext == "node" && !this.internalSelectedNodeId) {
        this.error.selectedNode = this.$t("common.required");
        isValidationOk = false;
      }
      if (this.internalContext == "module" && !this.internalSelectedAppId) {
        this.error.selectedApp = this.$t("common.required");
        isValidationOk = false;
      }
      if (!this.internalSelectedLokiId) {
        this.error.selectedLoki = this.$t("common.required");
        isValidationOk = false;
      }
      if (!this.internalFollowLogs) {
        if (!this.internalStartTime) {
          this.error.startTime = this.$t("common.required");
          isValidationOk = false;
        }
        if (!this.internalEndTime) {
          this.error.endTime = this.$t("common.required");
          isValidationOk = false;
        }
        if (this.internalStartTime && this.internalEndTime) {
          const startLocal = new Date(
            this.internalStartDate + "T" + this.internalStartTime + ":00"
          );
          const endLocal = new Date(
            this.internalEndDate + "T" + this.internalEndTime + ":59"
          );
          if (this.dateIsBefore(endLocal, startLocal)) {
            this.error.startDate = this.$t("error.invalid_time_interval");
            this.error.startTime = this.$t("error.invalid_time_interval");
            this.error.endDate = this.$t("error.invalid_time_interval");
            this.error.endTime = this.$t("error.invalid_time_interval");
            isValidationOk = false;
          }
        }
        if (
          this.internalMaxLines < 1 ||
          this.internalMaxLines > this.MAX_LINES_LIMIT
        ) {
          this.error.maxLines = this.$t("error.must_be_between", {
            min: 1,
            max: this.MAX_LINES_LIMIT,
          });
          isValidationOk = false;
        }
      }
      return isValidationOk;
    },
    logsStart() {
      if (!this.validateSearchLogs()) {
        return;
      }
      this.loading.logs = true;
      this.noLogsFound = false;
      this.searchStarted = true;
      const mode = this.internalFollowLogs ? "tail" : "dump";
      const startLocal = new Date(
        this.internalStartDate + "T" + this.internalStartTime + ":00"
      );
      const endLocal = new Date(
        this.internalEndDate + "T" + this.internalEndTime + ":59"
      );
      const format = "yyyy-MM-dd'T'HH:mm:ssX";
      const startUtcString = this.formatInTimeZone(startLocal, format, "UTC");
      const endUtcString = this.formatInTimeZone(endLocal, format, "UTC");
      this.highlight = this.internalRegexp ? "" : this.internalSearchQuery;
      this.clearLogs();
      let entityName;
      let timezone = "UTC";
      switch (this.internalContext) {
        case "cluster":
          entityName = "";
          break;
        case "node":
          entityName = this.internalSelectedNodeId;
          break;
        case "module":
          entityName = this.internalSelectedAppId;
          break;
      }
      if (this.internalFollowLogs) {
        this.$root.$on(`logsStart-${this.searchId}`, this.onLogsStartFollow);
        this.$root.$once(`logsStop-${this.searchId}`, this.onLogsStop);
      } else {
        this.$root.$once(`logsStart-${this.searchId}`, this.onLogsStartDump);
      }
      if (this.internalFollowLogs || this.internalTimezone == "local") {
        timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
      }
      this.searchedCriteria = {
        context: this.internalContext,
        nodeId: this.internalSelectedNodeId,
        appId: this.internalSelectedAppId,
        query: this.internalSearchQuery,
        regexp: this.internalRegexp,
        followLogs: this.internalFollowLogs,
        startDate: this.internalStartDate,
        startTime: this.internalStartTime,
        endDate: this.internalEndDate,
        endTime: this.internalEndTime,
        maxLines: this.internalMaxLines,
        timezone,
        lokiId: this.internalSelectedLokiId,
      };
      this.$emit("searchStarted");
      const logsStartObj = {
        action: "logs-start",
        payload: {
          mode: mode,
          lines: this.internalMaxLines,
          filter: this.internalSearchQuery,
          from: startUtcString,
          to: endUtcString,
          entity: this.internalContext,
          entity_name: String(entityName),
          id: this.searchId,
          timezone: timezone,
          instance: this.internalSelectedLokiId,
          regexp: this.internalRegexp,
        },
      };
      this.$socket.sendObj(logsStartObj);
    },
    logsStop() {
      this.loading.stopFollowing = true;
      this.$root.$off(`logsStart-${this.searchId}`);
      this.$root.$once(`logsStop-${this.searchId}`, this.onLogsStop);
      const logsStopObj = {
        action: "logs-stop",
        payload: {
          pid: this.pid,
          id: this.searchId,
        },
      };
      this.$socket.sendObj(logsStopObj);
    },
    onLogsStop() {
      this.loading.logs = false;
      this.loading.stopFollowing = false;
      this.isFollowing = false;
      this.pid = "";
      this.$root.$off(`logsStart-${this.searchId}`);
    },
    onLogsStartDump(payload) {
      this.loading.logs = false;
      if (!payload.message.length) {
        // show empty state in LogsOutput
        this.noLogsFound = true;
      } else {
        this.outputLines = [...this.outputLines, ...payload.message];
      }
      // signal LogOutput
      this.$root.$emit(`logsUpdated-${this.searchId}`);
    },
    // a query dying in the browser reads like one dying on the server: the
    // reason is printed where the logs are
    // the reason is kept in English: the copied text is not translated
    onQueryAborted(message, reason) {
      this.loading.logs = false;
      this.loading.stopFollowing = false;
      this.isFollowing = false;
      this.pid = "";
      this.noLogsFound = false;
      this.outputLines = [...this.outputLines, message];
      this.abortReason = reason;
      this.$root.$off(`logsStart-${this.searchId}`);
      this.$root.$emit(`logsUpdated-${this.searchId}`);
    },
    onLogsStartFollow(payload) {
      if (this.loading.logs) {
        this.loading.logs = false;
        this.isFollowing = true;
        this.pid = payload.pid;
      }
      if (payload.message.length) {
        this.outputLines = [...this.outputLines, ...payload.message];
      }
      // limit output buffer
      if (this.outputLines.length > this.MAX_LINES_LIMIT) {
        const numLinesToDelete = this.outputLines.length - this.MAX_LINES_LIMIT;
        this.outputLines.splice(0, numLinesToDelete);
        this.bufferTruncated = true;
      }
      // signal LogOutput
      this.$root.$emit(`logsUpdated-${this.searchId}`);
    },
    clearLogs() {
      this.outputLines = [];
      this.bufferTruncated = false;
      this.abortReason = "";
    },
    // built on click: joining up to MAX_LINES_LIMIT lines on every follow
    // update would be wasted work
    copyLogs() {
      this.$copyText(this.buildClipboardText()).then(
        this.onCopy,
        this.onCopyError
      );
    },
    onCopy() {
      this.justCopied = true;
      clearTimeout(this.copiedTimer);
      this.copiedTimer = setTimeout(() => {
        this.justCopied = false;
      }, 3000);
    },
    onCopyError() {
      console.error("cannot copy to clipboard");
    },
    buildClipboardText() {
      const c = this.searchedCriteria;
      const logLines = this.abortReason
        ? this.outputLines.slice(0, -1)
        : this.outputLines;
      const numLines = logLines.length;
      const interval = this.logsInterval;
      const lines = [
        `${this.$root.config.PRODUCT_NAME} - System logs`,
        `Copied at: ${this.formatInTimeZone(
          new Date(),
          "yyyy-MM-dd HH:mm:ss",
          c.timezone
        )} (${c.timezone})`,
        "",
      ];
      // node details are read now: their tasks may answer after the search
      const nodeLines = (node) => [
        `${
          node.uiName ? `${node.uiName} (Node ${node.id})` : `Node ${node.id}`
        }:`,
        `  FQDN: ${node.fqdn || "unknown"}`,
        `  Core version: ${node.coreVersion || "unknown"}`,
      ];
      const findNode = (nodeId) =>
        this.nodesInfo.find((node) => node.id == nodeId) || { id: nodeId };
      switch (c.context) {
        case "module": {
          const app = this.apps.find((app) => app.value == c.appId) || {};
          lines.push(
            "Context: Application",
            `  Instance: ${
              app.uiName ? `${app.uiName} (${c.appId})` : c.appId
            }`,
            `  Version: ${app.version || "unknown"}`
          );
          if (app.node) {
            lines.push(...nodeLines(findNode(app.node)));
          }
          break;
        }
        case "node":
          lines.push("Context: Node", ...nodeLines(findNode(c.nodeId)));
          break;
        default:
          lines.push("Context: Cluster");
          for (const node of this.nodesInfo) {
            lines.push(...nodeLines(node));
          }
      }
      lines.push(
        "",
        `Search query: ${c.query ? `"${c.query}"` : "(none)"} ` +
          `(regular expression: ${c.regexp ? "yes" : "no"})`
      );
      lines.push(`Mode: ${c.followLogs ? "Follow" : "Dump"}`);
      if (!c.followLogs) {
        // the date inputs are read as browser time, whatever the timezone field
        const browserTimezone =
          Intl.DateTimeFormat().resolvedOptions().timeZone;
        lines.push(
          `From: ${c.startDate} ${c.startTime} to ${c.endDate} ${c.endTime} ` +
            `(${browserTimezone})`
        );
        lines.push(`Timezone: ${c.timezone}`);
      }
      const loki = this.lokiInstances.find((loki) => loki.value == c.lokiId);
      lines.push(
        `Loki instance: ${c.lokiId}${loki && loki.active ? " (active)" : ""}`
      );
      let result = c.followLogs
        ? `Result: showing ${numLines} lines`
        : `Result: showing ${numLines} of ${c.maxLines} lines`;
      if (interval) {
        result += ` from ${interval.from} to ${interval.to}`;
      }
      if (c.followLogs && this.bufferTruncated) {
        result += " (oldest lines dropped)";
      } else if (!c.followLogs && numLines >= Number(c.maxLines)) {
        result += " (max lines reached)";
      }
      if (!c.followLogs) {
        lines.push(`Max lines: ${c.maxLines}`);
      }
      lines.push(result);
      if (this.abortReason) {
        lines.push(`Aborted: ${this.abortReason}`);
      }
      lines.push("----", ...logLines);
      return lines.join("\n");
    },
    onEnterKeyPress() {
      if (!this.isFollowing) {
        this.logsStart();
      }
    },
    onClose() {
      this.$emit("close", this.searchId);
      this.$root.$emit("logSearchClosed");
    },
    onLogSearchClosed() {
      this.$nextTick(() => {
        if (this.mainSearch) {
          this.$emit("updateSearchQuery", this.internalSearchQuery);
          this.$emit("updateContext", this.internalContext);
          this.$emit("updateSelectedNodeId", this.internalSelectedNodeId);
          this.$emit("updateSelectedAppId", this.internalSelectedAppId);
          this.$emit("updateSelectedLokiId", this.internalSelectedLokiId);
          this.$emit("updateFollowLogs", this.internalFollowLogs);
          this.$emit("updateMaxLines", this.internalMaxLines);
          this.$emit("updateStartDate", this.internalStartDate);
          this.$emit("updateEndDate", this.internalEndDate);
          this.$emit("updateStartTime", this.internalStartTime);
          this.$emit("updateEndTime", this.internalEndTime);
          this.$emit("updateTimezone", this.internalTimezone);
        }
      });
    },
    onModeSelected(value) {
      if (value == "dump") {
        this.internalFollowLogs = false;
      } else if (value == "follow") {
        this.internalFollowLogs = true;
      }
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
.log-search {
  position: relative;
}
.interval-group {
  display: flex;
  gap: $spacing-07;
}
.interval-date,
.interval-time {
  flex: 1 1 0;
  min-width: 0;
}
.checkbox-filter {
  display: flex;
  align-items: center;
}
.results-feedback {
  margin-left: auto;
  color: $text-02;
  font-size: 0.875rem;
}
.filter-collapsed {
  margin-right: $spacing-05;
}
.pad-right-lg {
  padding-right: $spacing-07;
}
.logs-output-toolbar {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  margin-top: $spacing-03;
  margin-bottom: $spacing-06;
  .mg-right {
    margin-right: $spacing-06;
  }
}
</style>
⋮----
<style lang="scss">
@import "../../styles/carbon-utils";
@media (min-width: $breakpoint-medium) {
  .system-logs .log-search .bx--text-input,
  .system-logs .log-search .bx--text-input__field-wrapper,
  .system-logs .log-search .cv-select,
  .system-logs .log-search .cv-combo-box {
    max-width: none;
  }
}
.system-logs .interval-date,
.system-logs .interval-date .bx--date-picker,
.system-logs .interval-date .bx--date-picker-container,
.system-logs .interval-date .bx--date-picker__input {
  width: 100%;
}
.system-logs .interval-time .bx--time-picker,
.system-logs .interval-time .bx--time-picker__input {
  width: 100%;
}
.system-logs .interval-time .time-picker-field.narrow-width {
  width: 100% !important;
}
.system-logs .interval-time .time-picker-field.narrow-width input {
  width: 100% !important;
}
.system-logs .log-search .bx--content-switcher {
  width: 100%;
}
</style>
</file>

<file path="core/ui/src/i18n/index.js">
export async function loadLanguage(lang)
</file>

<file path="core/ui/src/mixins/2fa.js">
get2FaStatus()
get2FaQrCode()
verify2FaSecret(secret, otp)
⋮----
// enable 2FA flag, if OTP check is successful
⋮----
revoke2Fa()
</file>

<file path="core/ui/src/mixins/audit.js">
getAuditUsers()
getAuditActions()
getAuditTrail(users, actions, data, from, to, limit)
</file>

<file path="core/ui/src/mixins/ipAddress.js">
isIpv4Address(value)
isIpv6Address(value)
⋮----
isIpAddress(value)
isIpAddressOrCidr(value)
⋮----
looksLikeIpv6(value)
</file>

<file path="core/ui/src/mixins/login.js">
executeLogin(username, password, otp)
executeLogout()
</file>

<file path="core/ui/src/mixins/node.js">
getNodes()
⋮----
getInstalledAppsByNode(listInstalledModulesOutput)
</file>

<file path="core/ui/src/mixins/notification.js">
createNotification(notification)
hideNotification(notificationId)
deleteNotification(notificationId)
showNotification(notification)
notificationExists(notification)
putNotification(notification)
async handleCancelTask(notificationId)
cancelTaskAborted(taskResult, taskContext)
handleNotificationAction(notificationId)
getTaskEventName(taskContext, result)
⋮----
// e.g. get-cluster-status-completed-f5d24fcd-819c-4b1d-98ad-a1b2ebcee8cf
⋮----
async fetchTaskContext(taskPath, taskId, payload)
⋮----
// clear on failure too, so a failed request never blocks later retries
⋮----
async handleProgressTaskMessage(taskPath, taskId, payload)
getCustomCompletionText(taskExtra, taskOutput)
shouldShowNotification(notification, taskStatus)
getActionParams(taskContext, taskStatus, taskResult)
</file>

<file path="core/ui/src/mixins/websocket.js">
initWebSocket()
closeWebSocket()
onOpen()
onError(error)
onMessage(message)
handleTaskMessage(messageData)
handleActionMessage(messageData)
splitLogLines(logLinesString)
onClose(event)
</file>

<file path="core/ui/src/router/index.js">
component: ()
</file>

<file path="core/ui/src/store/index.js">
unreadNotifications: (state, getters) =>
unreadNotificationsCount: (state, getters) =>
ongoingNotifications: (state) =>
ongoingNotificationsCount: (state, getters) =>
recentNotifications: (state) =>
getNotificationById: (state) => (id) =>
getTaskById: (state) => (taskId) =>
leaderNode: (state) =>
isCancellingTask: (state) => (taskId) =>
⋮----
setPollingTimerForTask(state, obj)
createNotification(state, notification)
setNotificationDrawerShown(state, value)
toggleNotificationDrawerShown(state)
setMobileSideMenuShown(state, value)
toggleMobileSideMenuShown(state)
setAppDrawerShown(state, value)
toggleAppDrawerShown(state)
setEditingFavoriteApps(state, value)
setSearchExpanded(state, value)
toggleSearchExpanded(state)
setTaskErrorToShow(state, task)
setTaskErrorShown(state, value)
setNotificationRead(state, notificationId)
updateNotification(state, notification)
setLoggedUser(state, username)
setClusterInitialized(state, value)
setLeaderListenPort(state, value)
setWebsocketConnected(state, value)
markAllNotificationsRead(state, unreadNotifications)
setFavoriteApps(state, favoriteApps)
setClusterLabel(state, clusterLabel)
setClusterNodes(state, clusterNodes)
setUpdateInProgress(state, value)
setLogoutInfo(state, logoutInfo)
deleteNotification(state, notificationId)
setMigratingApps(state, migratingApps)
refreshTaskContextInCache(state, payload)
setTaskContextInCache(state, payload)
addCancellingTask(state, taskId)
removeCancellingTask(state, taskId)
⋮----
setPollingTimerForTaskInStore(context, obj)
createNotificationInStore(context, notification)
setNotificationDrawerShownInStore(context, value)
toggleNotificationDrawerShownInStore(context)
setMobileSideMenuShownInStore(context, value)
toggleMobileSideMenuShownInStore(context)
setAppDrawerShownInStore(context, value)
toggleAppDrawerShownInStore(context)
setEditingFavoriteAppsInStore(context, value)
setSearchExpandedInStore(context, value)
toggleSearchExpandedInStore(context)
showTaskErrorInStore(context, task)
hideTaskErrorInStore(context)
setNotificationReadInStore(context, notificationId)
updateNotificationInStore(context, notification)
setLoggedUserInStore(context, username)
setClusterInitializedInStore(context, value)
setLeaderListenPortInStore(context, value)
setWebsocketConnectedInStore(context, value)
markAllNotificationsReadInStore(context)
setFavoriteAppsInStore(context, favoriteApps)
setClusterLabelInStore(context, clusterLabel)
setClusterNodesInStore(context, clusterNodes)
setUpdateInProgressInStore(context, value)
setLogoutInfoInStore(context, logoutInfo)
deleteNotificationInStore(context, notificationId)
setMigratingAppsInStore(context, migratingApps)
getTaskContextFromCache: (context, taskId) =>
addCancellingTaskInStore(context, taskId)
removeCancellingTaskInStore(context, taskId)
⋮----
function searchTask(taskId, tasks)
</file>

<file path="core/ui/src/views/settings/ClusterAdmins.vue">
<template>
  <div>
    <cv-grid fullWidth>
      <cv-row>
        <cv-column>
          <cv-breadcrumb
            aria-label="breadcrumb"
            :no-trailing-slash="true"
            class="breadcrumb"
          >
            <cv-breadcrumb-item>
              <cv-link to="/settings">{{ $t("settings.title") }}</cv-link>
            </cv-breadcrumb-item>
            <cv-breadcrumb-item>
              <span>{{ $t("settings_cluster_admins.title") }}</span>
            </cv-breadcrumb-item>
          </cv-breadcrumb>
        </cv-column>
      </cv-row>
      <cv-row>
        <cv-column class="subpage-title">
          <h3>{{ $t("settings_cluster_admins.title") }}</h3>
        </cv-column>
      </cv-row>
      <cv-row>
        <cv-column>
          <NsInlineNotification
            v-if="error.listUsers"
            kind="error"
            :title="$t('action.list-users')"
            :description="error.listUsers"
            :showCloseButton="false"
          />
        </cv-column>
      </cv-row>
      <cv-row>
        <cv-column>
          <NsInlineNotification
            v-if="error.removeUser"
            kind="error"
            :title="$t('settings_cluster_admins.delete_admin')"
            :description="error.removeUser"
            :showCloseButton="false"
          />
        </cv-column>
      </cv-row>
      <cv-row>
        <cv-column>
          <NsInlineNotification
            kind="warning"
            :title="$t('common.use_landscape_mode')"
            :description="$t('common.use_landscape_mode_description')"
            class="landscape-warning"
          />
        </cv-column>
      </cv-row>
      <cv-row class="toolbar">
        <cv-column>
          <NsButton
            kind="secondary"
            :icon="Add20"
            @click="showCreateAdminModal"
            :disabled="loading.listUsers"
            >{{ $t("settings_cluster_admins.create_admin") }}
          </NsButton>
        </cv-column>
      </cv-row>
      <cv-row v-if="loading.listUsers">
        <cv-column>
          <div
            class="card-grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 3xl:grid-cols-4"
          >
            <cv-tile v-for="index in 4" :key="index" light>
              <cv-skeleton-text paragraph :line-count="7"></cv-skeleton-text>
            </cv-tile>
          </div>
        </cv-column>
      </cv-row>
      <cv-row v-else>
        <cv-column>
          <div
            class="card-grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 3xl:grid-cols-4"
          >
            <NsInfoCard
              v-for="admin in admins"
              :key="admin.user"
              light
              :title="admin.user"
              :icon="UserMilitary32"
            >
              <template #menu>
                <cv-overflow-menu
                  :flip-menu="true"
                  tip-position="top"
                  tip-alignment="end"
                  class="top-right-overflow-menu"
                >
                  <cv-overflow-menu-item
                    @click="showChangePasswordModal(admin)"
                  >
                    <NsMenuItem
                      :icon="Password20"
                      :label="$t('settings_cluster_admins.change_password')"
                    />
                  </cv-overflow-menu-item>
                  <NsMenuDivider />
                  <cv-overflow-menu-item
                    danger
                    :disabled="
                      admin.user === 'admin' || admin.user === loggedUser
                    "
                    @click="showDeleteAdminModal(admin)"
                  >
                    <NsMenuItem
                      :icon="TrashCan20"
                      :label="$t('common.delete')"
                    />
                  </cv-overflow-menu-item>
                </cv-overflow-menu>
              </template>
              <template #content>
                <div class="admin-card-content">
                  <div class="row">
                    <span>{{ admin.display_name }}</span>
                  </div>
                  <div v-if="loggedUser == admin.user" class="row">
                    <NsTag
                      kind="high-contrast"
                      size="sm"
                      :label="$t('settings_cluster_admins.you')"
                      class="no-margin"
                    />
                  </div>
                  <div class="row actions">
                    <NsButton
                      kind="ghost"
                      :icon="Edit20"
                      @click="showEditDisplayNameModal(admin)"
                      >{{ $t("settings_cluster_admins.edit_display_name") }}
                    </NsButton>
                  </div>
                </div>
              </template>
            </NsInfoCard>
          </div>
        </cv-column>
      </cv-row>
    </cv-grid>
    <CreateAdminModal
      :isShown="isShownCreateAdminModal"
      :admin="currentAdmin"
      @hide="hideCreateAdminModal"
      @adminCreated="listUsers"
    />
    <EditAdminDisplayNameModal
      :isShown="isShownEditDisplayNameModal"
      :admin="currentAdmin"
      @hide="hideEditDisplayNameModal"
      @displayNameUpdated="listUsers"
    />
    <ChangeAdminPasswordModal
      :isShown="isShownChangePasswordModal"
      :admin="currentAdmin"
      @hide="hideChangeAdminPasswordModal"
      @passwordChanged="listUsers"
    />
    <NsDangerDeleteModal
      :isShown="isShownDeleteAdminModal"
      :name="currentAdmin ? currentAdmin.user : ''"
      :title="
        $t('settings_cluster_admins.delete_admin_admin', {
          admin: currentAdmin ? currentAdmin.user : '',
        })
      "
      :warning="$t('common.please_read_carefully')"
      :description="
        $t('settings_cluster_admins.delete_admin_description', {
          name: currentAdmin ? currentAdmin.user : '',
        })
      "
      :typeToConfirm="
        $t('common.type_to_confirm', {
          name: currentAdmin ? currentAdmin.user : '',
        })
      "
      :isErrorShown="!!error.removeUser"
      :errorTitle="$t('settings_cluster_admins.delete_admin')"
      :errorDescription="error.removeUser"
      @hide="hideDeleteAdminModal"
      @confirmDelete="removeUser"
      data-test-id="delete-group-modal"
    />
  </div>
</template>
⋮----
<cv-link to="/settings">{{ $t("settings.title") }}</cv-link>
⋮----
<span>{{ $t("settings_cluster_admins.title") }}</span>
⋮----
<h3>{{ $t("settings_cluster_admins.title") }}</h3>
⋮----
>{{ $t("settings_cluster_admins.create_admin") }}
⋮----
<template #menu>
                <cv-overflow-menu
                  :flip-menu="true"
                  tip-position="top"
                  tip-alignment="end"
                  class="top-right-overflow-menu"
                >
                  <cv-overflow-menu-item
                    @click="showChangePasswordModal(admin)"
                  >
                    <NsMenuItem
                      :icon="Password20"
                      :label="$t('settings_cluster_admins.change_password')"
                    />
                  </cv-overflow-menu-item>
                  <NsMenuDivider />
                  <cv-overflow-menu-item
                    danger
                    :disabled="
                      admin.user === 'admin' || admin.user === loggedUser
                    "
                    @click="showDeleteAdminModal(admin)"
                  >
                    <NsMenuItem
                      :icon="TrashCan20"
                      :label="$t('common.delete')"
                    />
                  </cv-overflow-menu-item>
                </cv-overflow-menu>
              </template>
<template #content>
                <div class="admin-card-content">
                  <div class="row">
                    <span>{{ admin.display_name }}</span>
                  </div>
                  <div v-if="loggedUser == admin.user" class="row">
                    <NsTag
                      kind="high-contrast"
                      size="sm"
                      :label="$t('settings_cluster_admins.you')"
                      class="no-margin"
                    />
                  </div>
                  <div class="row actions">
                    <NsButton
                      kind="ghost"
                      :icon="Edit20"
                      @click="showEditDisplayNameModal(admin)"
                      >{{ $t("settings_cluster_admins.edit_display_name") }}
                    </NsButton>
                  </div>
                </div>
              </template>
⋮----
<span>{{ admin.display_name }}</span>
⋮----
>{{ $t("settings_cluster_admins.edit_display_name") }}
⋮----
<script>
import to from "await-to-js";
import {
  QueryParamService,
  UtilService,
  TaskService,
  IconService,
  PageTitleService,
} from "@nethserver/ns8-ui-lib";
import CreateAdminModal from "@/components/settings/CreateAdminModal.vue";
import EditAdminDisplayNameModal from "@/components/settings/EditAdminDisplayNameModal.vue";
import ChangeAdminPasswordModal from "@/components/settings/ChangeAdminPasswordModal.vue";
import { mapState } from "vuex";
export default {
  name: "ClusterAdmins",
  components: {
    CreateAdminModal,
    EditAdminDisplayNameModal,
    ChangeAdminPasswordModal,
  },
  mixins: [
    TaskService,
    UtilService,
    IconService,
    QueryParamService,
    PageTitleService,
  ],
  pageTitle() {
    return this.$t("settings_cluster_admins.title");
  },
  data() {
    return {
      isShownCreateAdminModal: false,
      isShownEditDisplayNameModal: false,
      isShownChangePasswordModal: false,
      isShownDeleteAdminModal: false,
      currentAdmin: null,
      admins: [],
      loading: {
        listUsers: false,
        removeUser: false,
        alterUser: false,
      },
      error: {
        listUsers: "",
        removeUser: "",
        alterUser: "",
      },
    };
  },
  computed: {
    ...mapState(["loggedUser"]),
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.watchQueryData(vm);
      vm.queryParamsToDataForCore(vm, to.query);
    });
  },
  beforeRouteUpdate(to, from, next) {
    this.queryParamsToDataForCore(this, to.query);
    next();
  },
  created() {
    this.listUsers();
  },
  methods: {
    async listUsers() {
      this.loading.listUsers = true;
      this.error.listUsers = "";
      const taskAction = "list-users";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.listUsersAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.listUsersCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.listUsers = this.getErrorMessage(err);
        return;
      }
    },
    listUsersAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.listUsers = this.$t("error.generic_error");
      this.loading.listUsers = false;
    },
    listUsersCompleted(taskContext, taskResult) {
      this.admins = taskResult.output;
      this.loading.listUsers = false;
    },
    showCreateAdminModal() {
      this.isShownCreateAdminModal = true;
    },
    hideCreateAdminModal() {
      this.isShownCreateAdminModal = false;
    },
    showEditDisplayNameModal(admin) {
      this.currentAdmin = admin;
      this.isShownEditDisplayNameModal = true;
    },
    hideEditDisplayNameModal() {
      this.isShownEditDisplayNameModal = false;
    },
    showChangePasswordModal(admin) {
      this.currentAdmin = admin;
      this.isShownChangePasswordModal = true;
    },
    hideChangeAdminPasswordModal() {
      this.isShownChangePasswordModal = false;
    },
    showDeleteAdminModal(admin) {
      this.currentAdmin = admin;
      this.error.removeUser = "";
      this.isShownDeleteAdminModal = true;
    },
    hideDeleteAdminModal() {
      this.isShownDeleteAdminModal = false;
    },
    async removeUser() {
      this.loading.removeUser = true;
      this.error.removeUser = "";
      const taskAction = "remove-user";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.removeUserAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.removeUserCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {
            user: this.currentAdmin.user,
          },
          extra: {
            title: this.$t("settings_cluster_admins.delete_admin_admin", {
              admin: this.currentAdmin.user,
            }),
            description: this.$t("common.processing"),
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.removeUser = this.getErrorMessage(err);
        this.loading.removeUser = false;
        return;
      }
      this.hideDeleteAdminModal();
    },
    removeUserAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.removeUser = this.$t("error.generic_error");
      this.loading.removeUser = false;
    },
    removeUserCompleted() {
      this.loading.removeUser = false;
      this.listUsers();
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
.admin-card-content .row {
  margin-bottom: $spacing-05;
  text-align: center;
}
.admin-card-content .row:last-child {
  margin-bottom: 0;
}
</style>
</file>

<file path="core/ui/src/views/settings/Settings.vue">
<template>
  <cv-grid fullWidth>
    <cv-row>
      <cv-column class="page-title">
        <h2>{{ $t("settings.title") }}</h2>
      </cv-column>
    </cv-row>
    <cv-row>
      <cv-column :md="4" :xlg="4">
        <NsTile
          :light="true"
          kind="clickable"
          @click="goTo('/settings/cluster')"
          :icon="EdgeCluster32"
        >
          <h6>{{ $t("settings_cluster.title") }}</h6>
        </NsTile>
      </cv-column>
      <cv-column :md="4" :xlg="4">
        <NsTile
          :light="true"
          kind="clickable"
          @click="goTo('/settings/account')"
          :icon="UserAvatar32"
        >
          <h6>{{ $t("settings_account.title") }}</h6>
        </NsTile>
      </cv-column>
      <cv-column :md="4" :xlg="4">
        <NsTile
          :light="true"
          kind="clickable"
          @click="goTo('/settings/subscription')"
          :icon="Badge32"
        >
          <h6>{{ $t("settings_subscription.title") }}</h6>
        </NsTile>
      </cv-column>
      <cv-column :md="4" :xlg="4">
        <NsTile
          :light="true"
          kind="clickable"
          @click="goTo('/settings/software-repository')"
          :icon="Application32"
        >
          <h6>{{ $t("settings_sw_repositories.title") }}</h6>
        </NsTile>
      </cv-column>
      <cv-column :md="4" :xlg="4">
        <NsTile
          :light="true"
          kind="clickable"
          @click="goTo('/settings/http-routes')"
          :icon="Router32"
        >
          <h6>{{ $t("settings_http_routes.title") }}</h6>
        </NsTile>
      </cv-column>
      <cv-column :md="4" :xlg="4">
        <NsTile
          :light="true"
          kind="clickable"
          @click="goTo('/settings/tls-certificates')"
          :icon="Certificate32"
        >
          <h6>{{ $t("settings_tls_certificates.title") }}</h6>
        </NsTile>
      </cv-column>
      <cv-column :md="4" :xlg="4">
        <NsTile
          :light="true"
          kind="clickable"
          @click="goTo('/settings/smarthost')"
          :icon="Email32"
        >
          <h6>{{ $t("smarthost.title") }}</h6>
        </NsTile>
      </cv-column>
      <cv-column :md="4" :xlg="4">
        <NsTile
          :light="true"
          kind="clickable"
          @click="goTo('/settings/cluster-admins')"
          :icon="UserMilitary32"
        >
          <h6>{{ $t("settings_cluster_admins.title") }}</h6>
        </NsTile>
      </cv-column>
      <cv-column :md="4" :xlg="4">
        <NsTile
          :light="true"
          kind="clickable"
          @click="goTo('/settings/firewall')"
          :icon="Firewall32"
        >
          <h6>{{ $t("firewall.title") }}</h6>
        </NsTile>
      </cv-column>
      <cv-column :md="4" :xlg="4">
        <NsTile
          :light="true"
          kind="clickable"
          @click="goTo('/settings/metrics')"
          :icon="Dashboard32"
        >
          <h6>
            {{ $t("settings_metrics.title") }}
          </h6>
        </NsTile>
      </cv-column>
      <cv-column :md="4" :xlg="4">
        <NsTile
          :light="true"
          kind="clickable"
          @click="goTo('/settings/system-logs')"
          :icon="Catalog32"
        >
          <h6>{{ $t("system_logs.title") }}</h6>
        </NsTile>
      </cv-column>
    </cv-row>
  </cv-grid>
</template>
⋮----
<h2>{{ $t("settings.title") }}</h2>
⋮----
<h6>{{ $t("settings_cluster.title") }}</h6>
⋮----
<h6>{{ $t("settings_account.title") }}</h6>
⋮----
<h6>{{ $t("settings_subscription.title") }}</h6>
⋮----
<h6>{{ $t("settings_sw_repositories.title") }}</h6>
⋮----
<h6>{{ $t("settings_http_routes.title") }}</h6>
⋮----
<h6>{{ $t("settings_tls_certificates.title") }}</h6>
⋮----
<h6>{{ $t("smarthost.title") }}</h6>
⋮----
<h6>{{ $t("settings_cluster_admins.title") }}</h6>
⋮----
<h6>{{ $t("firewall.title") }}</h6>
⋮----
{{ $t("settings_metrics.title") }}
⋮----
<h6>{{ $t("system_logs.title") }}</h6>
⋮----
<script>
import {
  QueryParamService,
  UtilService,
  IconService,
  PageTitleService,
} from "@nethserver/ns8-ui-lib";
import Dashboard32 from "@carbon/icons-vue/es/dashboard/32";
export default {
  name: "Settings",
  data() {
    return {
      Dashboard32,
    };
  },
  mixins: [UtilService, IconService, QueryParamService, PageTitleService],
  pageTitle() {
    return this.$t("settings.title");
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.watchQueryData(vm);
      vm.queryParamsToDataForCore(vm, to.query);
    });
  },
  beforeRouteUpdate(to, from, next) {
    this.queryParamsToDataForCore(this, to.query);
    next();
  },
  methods: {
    goTo(path) {
      this.$router.push(path);
    },
  },
};
</script>
</file>

<file path="core/ui/src/views/settings/SettingsAccount.vue">
<template>
  <div>
    <cv-grid fullWidth>
      <cv-row>
        <cv-column>
          <cv-breadcrumb
            aria-label="breadcrumb"
            :no-trailing-slash="true"
            class="breadcrumb"
          >
            <cv-breadcrumb-item>
              <cv-link to="/settings">{{ $t("settings.title") }}</cv-link>
            </cv-breadcrumb-item>
            <cv-breadcrumb-item>
              <span>{{ $t("settings_account.title") }}</span>
            </cv-breadcrumb-item>
          </cv-breadcrumb>
        </cv-column>
      </cv-row>
      <cv-row>
        <cv-column class="subpage-title">
          <h3>{{ $t("settings_account.title") }}</h3>
        </cv-column>
      </cv-row>
      <cv-row>
        <cv-column>
          <NsInlineNotification
            v-if="error.userInfo"
            kind="error"
            :title="$t('action.get-user-info')"
            :description="error.userInfo"
            :showCloseButton="false"
          />
        </cv-column>
      </cv-row>
      <cv-row>
        <cv-column>
          <cv-tile light>
            <cv-skeleton-text
              v-if="loading.getUserInfo"
              paragraph
              :line-count="3"
              width="70%"
            ></cv-skeleton-text>
            <div v-else class="user-info">
              <NsPictogram title="user avatar" class="avatar">
                <UserProfilePictogram />
              </NsPictogram>
              <div class="user-details">
                <div v-if="userInfo.display_name" class="display-name">
                  {{ userInfo.display_name }}
                </div>
                <div>{{ currentUsername }}</div>
              </div>
            </div>
            <NsButton
              kind="secondary"
              :icon="Edit20"
              @click="showEditDisplayNameModal"
              :disabled="loading.getUserInfo"
              class="mg-top-lg"
              >{{ $t("settings_account.edit_display_name") }}
            </NsButton>
          </cv-tile>
        </cv-column>
      </cv-row>
      <cv-row>
        <cv-column>
          <cv-tile light>
            <h4 class="mg-bottom-md">
              {{ $t("settings_account.change_password") }}
            </h4>
            <cv-form @submit.prevent="changeUserPassword">
              <NsTextInput
                :label="
                  $t('settings_account.current_user_password', {
                    user: currentUsername,
                  })
                "
                v-model="currentPassword"
                :invalid-message="$t(error.currentPassword)"
                type="password"
                ref="currentPassword"
              >
              </NsTextInput>
              <NsPasswordInput
                :newPasswordLabel="
                  $t('settings_account.new_user_password', {
                    user: currentUsername,
                  })
                "
                :confirmPasswordLabel="
                  $t('settings_account.new_user_password_confirm', {
                    user: currentUsername,
                  })
                "
                v-model="newPassword"
                @passwordValidation="onPasswordValidation"
                :newPasswordInvalidMessage="error.newPassword"
                :confirmPasswordInvalidMessage="error.confirmPassword"
                :passwordHideLabel="$t('password.hide_password')"
                :passwordShowLabel="$t('password.show_password')"
                :lengthLabel="$t('password.long_enough')"
                :lowercaseLabel="$t('password.lowercase_letter')"
                :uppercaseLabel="$t('password.uppercase_letter')"
                :numberLabel="$t('password.number')"
                :symbolLabel="$t('password.symbol')"
                :equalLabel="$t('password.equal')"
                :focus="focusPasswordField"
                :clearConfirmPasswordCommand="clearConfirmPasswordCommand"
              />
              <NsInlineNotification
                v-if="error.changeUserPassword"
                kind="error"
                :title="$t('action.change-user-password')"
                :description="error.changeUserPassword"
                :showCloseButton="false"
              />
              <NsButton
                kind="primary"
                :loading="loading.changeUserPassword"
                :disabled="loading.changeUserPassword"
                :icon="Password20"
                >{{ $t("settings_account.change_password") }}
              </NsButton>
            </cv-form>
          </cv-tile>
          <cv-tile light>
            <h4>
              {{ $t("settings_account.2fa_title_with_acronym") }}
            </h4>
            <div class="title-description mg-bottom-xlg">
              {{ $t("settings_account.2fa_description") }}
            </div>
            <NsInlineNotification
              v-if="error.get2FaStatus"
              kind="error"
              :title="$t('settings_account.cannot_retrieve_2fa_status')"
              :description="error.get2FaStatus"
              :showCloseButton="false"
            />
            <cv-button-skeleton v-else-if="loading.get2FaStatus" />
            <template v-else>
              <template v-if="twoFaEnabled">
                <div class="icon-and-text mg-bottom-lg">
                  <NsSvg :svg="CheckmarkFilled16" class="icon ns-success" />
                  <span>{{ $t("settings_account.2fa_is_enabled") }}</span>
                </div>
                <div class="mg-bottom-lg">
                  <span>
                    {{ $t("settings_account.need_to_reconfigure_2fa") }}
                  </span>
                  <cv-link @click="show2FaQrCodeModal">
                    {{ $t("settings_account.show_qr_code") }}
                  </cv-link>
                </div>
                <div>
                  <NsInlineNotification
                    v-if="error.revoke2Fa"
                    kind="error"
                    :title="$t('settings_account.cannot_revoke_2fa')"
                    :description="error.revoke2Fa"
                    :showCloseButton="false"
                  />
                  <NsButton
                    kind="danger"
                    :icon="Power20"
                    @click="showConfirmRevoke2FaModal"
                  >
                    {{ $t("settings_account.revoke_2fa") }}
                  </NsButton>
                </div>
              </template>
              <template v-else>
                <div class="icon-and-text mg-bottom-lg">
                  <NsSvg :svg="InformationFilled16" class="icon ns-info" />
                  <span>{{ $t("settings_account.2fa_is_disabled") }}</span>
                </div>
                <NsButton
                  kind="secondary"
                  :icon="Power20"
                  @click="showEnable2FaModal"
                >
                  {{ $t("settings_account.enable_2fa") }}
                </NsButton>
              </template>
            </template>
          </cv-tile>
        </cv-column>
      </cv-row>
    </cv-grid>
    <Enable2FaModal
      :isShown="isShownEnable2FaModal"
      @hide="hideEnable2FaModal"
      @twoFaEnabled="onTwoFaEnabled"
    />
    <TwoFaQrCodeModal
      :isShown="isShown2FaQrCodeModal"
      @hide="hide2FaQrCodeModal"
    />
    <ConfirmRevoke2FaModal
      :isShown="isShownConfirmRevoke2FaModal"
      @hide="hideConfirmRevoke2FaModal"
      @confirm="disable2Fa"
    />
    <EditAdminDisplayNameModal
      :isShown="isShownEditDisplayNameModal"
      :admin="account"
      @hide="hideEditDisplayNameModal"
      @displayNameUpdated="getUserInfo"
    />
  </div>
</template>
⋮----
<cv-link to="/settings">{{ $t("settings.title") }}</cv-link>
⋮----
<span>{{ $t("settings_account.title") }}</span>
⋮----
<h3>{{ $t("settings_account.title") }}</h3>
⋮----
{{ userInfo.display_name }}
⋮----
<div>{{ currentUsername }}</div>
⋮----
>{{ $t("settings_account.edit_display_name") }}
⋮----
{{ $t("settings_account.change_password") }}
⋮----
>{{ $t("settings_account.change_password") }}
⋮----
{{ $t("settings_account.2fa_title_with_acronym") }}
⋮----
{{ $t("settings_account.2fa_description") }}
⋮----
<template v-else>
              <template v-if="twoFaEnabled">
                <div class="icon-and-text mg-bottom-lg">
                  <NsSvg :svg="CheckmarkFilled16" class="icon ns-success" />
                  <span>{{ $t("settings_account.2fa_is_enabled") }}</span>
                </div>
                <div class="mg-bottom-lg">
                  <span>
                    {{ $t("settings_account.need_to_reconfigure_2fa") }}
                  </span>
                  <cv-link @click="show2FaQrCodeModal">
                    {{ $t("settings_account.show_qr_code") }}
                  </cv-link>
                </div>
                <div>
                  <NsInlineNotification
                    v-if="error.revoke2Fa"
                    kind="error"
                    :title="$t('settings_account.cannot_revoke_2fa')"
                    :description="error.revoke2Fa"
                    :showCloseButton="false"
                  />
                  <NsButton
                    kind="danger"
                    :icon="Power20"
                    @click="showConfirmRevoke2FaModal"
                  >
                    {{ $t("settings_account.revoke_2fa") }}
                  </NsButton>
                </div>
              </template>
              <template v-else>
                <div class="icon-and-text mg-bottom-lg">
                  <NsSvg :svg="InformationFilled16" class="icon ns-info" />
                  <span>{{ $t("settings_account.2fa_is_disabled") }}</span>
                </div>
                <NsButton
                  kind="secondary"
                  :icon="Power20"
                  @click="showEnable2FaModal"
                >
                  {{ $t("settings_account.enable_2fa") }}
                </NsButton>
              </template>
            </template>
⋮----
<template v-if="twoFaEnabled">
                <div class="icon-and-text mg-bottom-lg">
                  <NsSvg :svg="CheckmarkFilled16" class="icon ns-success" />
                  <span>{{ $t("settings_account.2fa_is_enabled") }}</span>
                </div>
                <div class="mg-bottom-lg">
                  <span>
                    {{ $t("settings_account.need_to_reconfigure_2fa") }}
                  </span>
                  <cv-link @click="show2FaQrCodeModal">
                    {{ $t("settings_account.show_qr_code") }}
                  </cv-link>
                </div>
                <div>
                  <NsInlineNotification
                    v-if="error.revoke2Fa"
                    kind="error"
                    :title="$t('settings_account.cannot_revoke_2fa')"
                    :description="error.revoke2Fa"
                    :showCloseButton="false"
                  />
                  <NsButton
                    kind="danger"
                    :icon="Power20"
                    @click="showConfirmRevoke2FaModal"
                  >
                    {{ $t("settings_account.revoke_2fa") }}
                  </NsButton>
                </div>
              </template>
⋮----
<span>{{ $t("settings_account.2fa_is_enabled") }}</span>
⋮----
{{ $t("settings_account.need_to_reconfigure_2fa") }}
⋮----
{{ $t("settings_account.show_qr_code") }}
⋮----
{{ $t("settings_account.revoke_2fa") }}
⋮----
<template v-else>
                <div class="icon-and-text mg-bottom-lg">
                  <NsSvg :svg="InformationFilled16" class="icon ns-info" />
                  <span>{{ $t("settings_account.2fa_is_disabled") }}</span>
                </div>
                <NsButton
                  kind="secondary"
                  :icon="Power20"
                  @click="showEnable2FaModal"
                >
                  {{ $t("settings_account.enable_2fa") }}
                </NsButton>
              </template>
⋮----
<span>{{ $t("settings_account.2fa_is_disabled") }}</span>
⋮----
{{ $t("settings_account.enable_2fa") }}
⋮----
<script>
import to from "await-to-js";
import {
  QueryParamService,
  UtilService,
  TaskService,
  IconService,
  PageTitleService,
} from "@nethserver/ns8-ui-lib";
import TwoFaQrCodeModal from "@/components/settings/2FaQrCodeModal";
import Enable2FaModal from "@/components/settings/Enable2FaModal";
import ConfirmRevoke2FaModal from "@/components/settings/ConfirmRevoke2FaModal";
import TwoFaService from "@/mixins/2fa";
import NotificationService from "@/mixins/notification";
import EditAdminDisplayNameModal from "@/components/settings/EditAdminDisplayNameModal.vue";
export default {
  name: "SettingsAccount",
  components: {
    TwoFaQrCodeModal,
    Enable2FaModal,
    ConfirmRevoke2FaModal,
    EditAdminDisplayNameModal,
  },
  mixins: [
    TaskService,
    UtilService,
    IconService,
    QueryParamService,
    PageTitleService,
    TwoFaService,
    NotificationService,
  ],
  pageTitle() {
    return this.$t("settings_account.title");
  },
  data() {
    return {
      currentUsername: "",
      currentPassword: "",
      newPassword: "",
      passwordValidation: null,
      focusPasswordField: { element: "" },
      clearConfirmPasswordCommand: 0,
      isShown2FaQrCodeModal: false,
      isShownEnable2FaModal: false,
      twoFaEnabled: false,
      isShownConfirmRevoke2FaModal: false,
      userInfo: {},
      isShownEditDisplayNameModal: false,
      loading: {
        changeUserPassword: false,
        get2FaStatus: false,
        revoke2Fa: false,
        getUserInfo: false,
      },
      error: {
        changeUserPassword: "",
        currentPassword: "",
        newPassword: "",
        confirmPassword: "",
        get2FaStatus: "",
        revoke2Fa: "",
        getUserInfo: "",
      },
    };
  },
  computed: {
    account() {
      return {
        user: this.currentUsername,
        display_name: this.userInfo ? this.userInfo.display_name : "",
      };
    },
  },
  created() {
    const loginInfo = this.getFromStorage("loginInfo");
    if (loginInfo) {
      this.currentUsername = loginInfo.username;
    }
    this.retrieve2FaStatus();
    this.getUserInfo();
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.watchQueryData(vm);
      vm.queryParamsToDataForCore(vm, to.query);
    });
  },
  beforeRouteUpdate(to, from, next) {
    this.queryParamsToDataForCore(this, to.query);
    next();
  },
  methods: {
    onPasswordValidation(passwordValidation) {
      this.passwordValidation = passwordValidation;
    },
    validateChangeUserPassword() {
      this.clearErrors(this);
      let isValidationOk = true;
      if (!this.currentPassword) {
        this.error.currentPassword = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("currentPassword");
          isValidationOk = false;
        }
      }
      if (!this.newPassword) {
        this.error.newPassword = this.$t("common.required");
        if (isValidationOk) {
          this.focusPasswordField = { element: "newPassword" };
          isValidationOk = false;
        }
      } else {
        if (this.currentPassword === this.newPassword) {
          if (!this.error.newPassword) {
            this.error.newPassword = this.$t(
              "password.old_new_passwords_must_be_different"
            );
          }
          if (isValidationOk) {
            this.focusPasswordField = { element: "newPassword" };
            isValidationOk = false;
          }
        }
        if (
          !this.passwordValidation.isLengthOk ||
          !this.passwordValidation.isLowercaseOk ||
          !this.passwordValidation.isUppercaseOk ||
          !this.passwordValidation.isNumberOk ||
          !this.passwordValidation.isSymbolOk
        ) {
          if (!this.error.newPassword) {
            this.error.newPassword = this.$t("password.password_not_secure");
          }
          if (isValidationOk) {
            this.focusPasswordField = { element: "newPassword" };
            isValidationOk = false;
          }
        }
        if (!this.passwordValidation.isEqualOk) {
          if (!this.error.newPassword) {
            this.error.newPassword = this.$t("password.passwords_do_not_match");
          }
          if (!this.error.confirmPassword) {
            this.error.confirmPassword = this.$t(
              "password.passwords_do_not_match"
            );
          }
          if (isValidationOk) {
            this.focusPasswordField = { element: "confirmPassword" };
            isValidationOk = false;
          }
        }
      }
      return isValidationOk;
    },
    async changeUserPassword() {
      if (!this.validateChangeUserPassword()) {
        return;
      }
      this.loading.changeUserPassword = true;
      const taskAction = "change-user-password";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.changeUserPasswordAborted
      );
      this.$root.$once(
        `${taskAction}-validation-failed-${eventId}`,
        this.changeUserPasswordValidationFailed
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.changeUserPasswordCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {
            user: this.currentUsername,
            current_password: this.currentPassword,
            new_password: this.newPassword,
          },
          extra: {
            title: this.$t("action." + taskAction),
            description: this.$t("common.processing"),
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.changeUserPassword = this.getErrorMessage(err);
        this.loading.changeUserPassword = false;
        return;
      }
    },
    changeUserPasswordAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.changeUserPassword = this.$t("error.generic_error");
      this.loading.changeUserPassword = false;
    },
    changeUserPasswordValidationFailed(validationErrors) {
      this.loading.changeUserPassword = false;
      for (const validationError of validationErrors) {
        this.error.currentPassword = this.$t(
          "password." + validationError.error
        );
        this.focusElement("currentPassword");
      }
    },
    changeUserPasswordCompleted() {
      this.currentPassword = "";
      this.newPassword = "";
      this.clearConfirmPasswordCommand++;
      this.loading.changeUserPassword = false;
    },
    show2FaQrCodeModal() {
      this.isShown2FaQrCodeModal = true;
    },
    hide2FaQrCodeModal() {
      this.isShown2FaQrCodeModal = false;
    },
    showEnable2FaModal() {
      this.isShownEnable2FaModal = true;
    },
    hideEnable2FaModal() {
      this.isShownEnable2FaModal = false;
    },
    showConfirmRevoke2FaModal() {
      this.isShownConfirmRevoke2FaModal = true;
    },
    hideConfirmRevoke2FaModal() {
      this.isShownConfirmRevoke2FaModal = false;
    },
    async retrieve2FaStatus() {
      this.loading.get2FaStatus = true;
      this.error.get2FaStatus = "";
      const [err2FaStatus, response2FaStatus] = await to(this.get2FaStatus());
      this.loading.get2FaStatus = false;
      if (err2FaStatus) {
        console.error("error retrieving 2FA status", err2FaStatus);
        this.error.get2FaStatus = this.getErrorMessage(err2FaStatus);
        return;
      }
      this.twoFaEnabled = response2FaStatus.data.data;
    },
    async disable2Fa() {
      this.hideConfirmRevoke2FaModal();
      this.loading.revoke2Fa = true;
      this.error.revoke2Fa = "";
      const errRevoke = await to(this.revoke2Fa())[0];
      this.loading.revoke2Fa = false;
      if (errRevoke) {
        console.error("error revoking 2FA", errRevoke);
        this.error.revoke2Fa = this.getErrorMessage(errRevoke);
        return;
      }
      const notification = {
        title: this.$t("settings_account.2fa_disabled"),
        description: this.$t("task.completed"),
        type: "success",
      };
      this.createNotification(notification);
      this.retrieve2FaStatus();
    },
    onTwoFaEnabled() {
      const notification = {
        title: this.$t("settings_account.2fa_enabled"),
        description: this.$t("task.completed"),
        type: "success",
      };
      this.createNotification(notification);
      this.isShownEnable2FaModal = false;
      this.retrieve2FaStatus();
    },
    async getUserInfo() {
      this.loading.getUserInfo = true;
      this.error.getUserInfo = "";
      const taskAction = "get-user-info";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.getUserInfoAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.getUserInfoCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {
            user: this.currentUsername,
          },
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.getUserInfo = this.getErrorMessage(err);
        return;
      }
    },
    getUserInfoAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.getUserInfo = this.$t("error.generic_error");
      this.loading.getUserInfo = false;
    },
    getUserInfoCompleted(taskContext, taskResult) {
      this.userInfo = taskResult.output;
      this.loading.getUserInfo = false;
    },
    showEditDisplayNameModal() {
      this.isShownEditDisplayNameModal = true;
    },
    hideEditDisplayNameModal() {
      this.isShownEditDisplayNameModal = false;
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
.icon-and-text {
  justify-content: flex-start;
}
.user-info {
  display: flex;
  align-items: center;
  .avatar {
    margin-right: $spacing-05;
  }
  .display-name {
    font-weight: bold;
    margin-bottom: $spacing-03;
  }
}
</style>
</file>

<file path="core/ui/src/views/settings/SettingsCluster.vue">
<template>
  <div class="bx--grid bx--grid--full-width">
    <div class="bx--row">
      <div class="bx--col-lg-16">
        <cv-breadcrumb
          aria-label="breadcrumb"
          :no-trailing-slash="true"
          class="breadcrumb"
        >
          <cv-breadcrumb-item>
            <cv-link to="/settings">{{ $t("settings.title") }}</cv-link>
          </cv-breadcrumb-item>
          <cv-breadcrumb-item>
            <span>{{ $t("settings_cluster.title") }}</span>
          </cv-breadcrumb-item>
        </cv-breadcrumb>
      </div>
    </div>
    <div class="bx--row">
      <div class="bx--col-lg-16 subpage-title">
        <h3>{{ $t("settings_cluster.title") }}</h3>
      </div>
    </div>
    <div v-if="error.getClusterStatus" class="bx--row">
      <div class="bx--col">
        <NsInlineNotification
          kind="error"
          :title="$t('action.get-cluster-status')"
          :description="error.getClusterStatus"
          :showCloseButton="false"
        />
      </div>
    </div>
    <div class="bx--row">
      <div class="bx--col">
        <cv-tile :light="true">
          <cv-form @submit.prevent="saveSettings">
            <cv-text-input
              :label="
                $t('common.cluster_label') + ' (' + $t('common.optional') + ')'
              "
              v-model.trim="newClusterLabel"
              :placeholder="$t('common.no_label')"
              :helper-text="$t('common.cluster_label_tooltip')"
              :invalid-message="$t(error.clusterLabel)"
              :disabled="loading.getClusterStatus || loading.setClusterLabel"
              maxlength="24"
              ref="clusterLabel"
            >
            </cv-text-input>
            <div v-if="error.setClusterLabel" class="bx--row">
              <div class="bx--col">
                <NsInlineNotification
                  kind="error"
                  :title="$t('action.set-name')"
                  :description="error.setClusterLabel"
                  :showCloseButton="false"
                />
              </div>
            </div>
            <NsButton
              kind="primary"
              :icon="Save20"
              :loading="loading.setClusterLabel"
              :disabled="isLoadingSettings"
              >{{ $t("common.save_settings") }}</NsButton
            >
          </cv-form>
        </cv-tile>
      </div>
    </div>
  </div>
</template>
⋮----
<cv-link to="/settings">{{ $t("settings.title") }}</cv-link>
⋮----
<span>{{ $t("settings_cluster.title") }}</span>
⋮----
<h3>{{ $t("settings_cluster.title") }}</h3>
⋮----
>{{ $t("common.save_settings") }}</NsButton
⋮----
<script>
import to from "await-to-js";
import {
  QueryParamService,
  UtilService,
  TaskService,
  IconService,
  PageTitleService,
} from "@nethserver/ns8-ui-lib";
import { mapActions } from "vuex";
export default {
  name: "SettingsCluster",
  mixins: [
    TaskService,
    UtilService,
    IconService,
    QueryParamService,
    PageTitleService,
  ],
  pageTitle() {
    return this.$t("settings_cluster.title");
  },
  data() {
    return {
      q: {},
      clusterLabel: "",
      newClusterLabel: "",
      loading: {
        getClusterStatus: true,
        setClusterLabel: false,
      },
      error: {
        getClusterStatus: "",
        clusterLabel: "",
        setClusterLabel: "",
      },
    };
  },
  computed: {
    isLoadingSettings() {
      return this.loading.getClusterStatus || this.loading.setClusterLabel;
    },
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.watchQueryData(vm);
      vm.queryParamsToDataForCore(vm, to.query);
    });
  },
  beforeRouteUpdate(to, from, next) {
    this.queryParamsToDataForCore(this, to.query);
    next();
  },
  created() {
    this.getClusterStatus();
  },
  methods: {
    ...mapActions(["setClusterLabelInStore"]),
    async getClusterStatus() {
      this.error.getClusterStatus = "";
      this.loading.getClusterStatus = true;
      const taskAction = "get-cluster-status";
      this.$root.$once(
        taskAction + "-completed",
        this.getClusterStatusCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.getClusterStatus = this.getErrorMessage(err);
        this.loading.getClusterStatus = false;
        return;
      }
    },
    getClusterStatusCompleted(taskContext, taskResult) {
      const clusterStatus = taskResult.output;
      this.clusterLabel = clusterStatus.ui_name;
      this.newClusterLabel = this.clusterLabel;
      this.loading.getClusterStatus = false;
      this.setClusterLabelInStore(this.clusterLabel);
    },
    saveSettings() {
      this.setClusterLabel();
    },
    async setClusterLabel() {
      this.error.setClusterLabel = "";
      this.loading.setClusterLabel = true;
      const taskAction = "set-name";
      this.$root.$once(
        taskAction + "-completed",
        this.setClusterLabelCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {
            name: this.newClusterLabel,
          },
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.setClusterLabel = this.getErrorMessage(err);
        this.loading.setClusterLabel = false;
        return;
      }
    },
    setClusterLabelCompleted() {
      this.loading.setClusterLabel = false;
      this.getClusterStatus();
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
.break-word {
  word-wrap: break-word;
  max-width: 20vw;
}
</style>
</file>

<file path="core/ui/src/views/settings/SettingsFirewall.vue">
<template>
  <cv-grid fullWidth>
    <cv-row>
      <cv-column>
        <cv-breadcrumb
          aria-label="breadcrumb"
          :no-trailing-slash="true"
          class="breadcrumb"
        >
          <cv-breadcrumb-item>
            <cv-link to="/settings">{{ $t("settings.title") }}</cv-link>
          </cv-breadcrumb-item>
          <cv-breadcrumb-item>
            <span>{{ $t("firewall.title") }}</span>
          </cv-breadcrumb-item>
        </cv-breadcrumb>
      </cv-column>
    </cv-row>
    <cv-row>
      <cv-column class="page-title">
        <h2>{{ $t("firewall.title") }}</h2>
      </cv-column>
    </cv-row>
    <cv-row v-if="loading.nodes">
      <cv-column>
        <div
          class="card-grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 3xl:grid-cols-4"
        >
          <NsTile v-for="index in 4" :key="index" :light="true">
            <cv-skeleton-text
              :paragraph="true"
              :line-count="2"
              heading
            ></cv-skeleton-text>
          </NsTile>
        </div>
      </cv-column>
    </cv-row>
    <cv-row v-else>
      <cv-column>
        <div
          class="card-grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 3xl:grid-cols-4"
        >
          <NsTile
            v-for="node in nodes"
            :key="node.id"
            :light="true"
            kind="clickable"
            @click="goToFirewall(node)"
            :icon="Chip32"
          >
            <h6>
              {{
                (node.ui_name
                  ? node.ui_name
                  : $t("common.node") + " " + node.id.toString()) +
                " " +
                $t("firewall.title")
              }}
            </h6>
          </NsTile>
        </div>
      </cv-column>
    </cv-row>
  </cv-grid>
</template>
⋮----
<cv-link to="/settings">{{ $t("settings.title") }}</cv-link>
⋮----
<span>{{ $t("firewall.title") }}</span>
⋮----
<h2>{{ $t("firewall.title") }}</h2>
⋮----
{{
                (node.ui_name
                  ? node.ui_name
                  : $t("common.node") + " " + node.id.toString()) +
                " " +
                $t("firewall.title")
              }}
⋮----
<script>
import {
  QueryParamService,
  UtilService,
  IconService,
  PageTitleService,
  TaskService,
} from "@nethserver/ns8-ui-lib";
import to from "await-to-js";
export default {
  name: "SettingsFirewall",
  mixins: [
    TaskService,
    UtilService,
    IconService,
    QueryParamService,
    PageTitleService,
  ],
  pageTitle() {
    return this.$t("firewall.title");
  },
  data() {
    return {
      q: {},
      nodes: [],
      loading: {
        nodes: true,
      },
      error: {
        getClusterStatus: "",
      },
    };
  },
  computed: {
    isLoadingNodes() {
      return this.loading.nodes;
    },
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.watchQueryData(vm);
      vm.queryParamsToDataForCore(vm, to.query);
    });
  },
  beforeRouteUpdate(to, from, next) {
    this.queryParamsToDataForCore(this, to.query);
    next();
  },
  created() {
    this.getClusterStatus();
  },
  methods: {
    async getClusterStatus() {
      this.error.getClusterStatus = "";
      const taskAction = "get-cluster-status";
      this.$root.$once(
        taskAction + "-completed",
        this.getClusterStatusCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            isNotificationHidden: true,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.getClusterStatus = this.getErrorMessage(err);
        return;
      }
    },
    getClusterStatusCompleted(taskContext, taskResult) {
      const clusterStatus = taskResult.output;
      this.nodes = clusterStatus.nodes.sort(this.sortByProperty("id"));
      this.loading.nodes = false;
    },
    goToFirewall(node) {
      this.$router.push({
        name: "SettingsNodeFirewall",
        params: { nodeId: node.id },
      });
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
</style>
</file>

<file path="core/ui/src/views/settings/SettingsHttpRoutes.vue">
<template>
  <div>
    <cv-grid fullWidth>
      <cv-row>
        <cv-column>
          <cv-breadcrumb
            aria-label="breadcrumb"
            :no-trailing-slash="true"
            class="breadcrumb"
          >
            <cv-breadcrumb-item>
              <cv-link to="/settings">{{ $t("settings.title") }}</cv-link>
            </cv-breadcrumb-item>
            <cv-breadcrumb-item>
              <span>{{ $t("settings_http_routes.title") }}</span>
            </cv-breadcrumb-item>
          </cv-breadcrumb>
        </cv-column>
      </cv-row>
      <cv-row>
        <cv-column class="subpage-title">
          <h3>{{ $t("settings_http_routes.title") }}</h3>
        </cv-column>
      </cv-row>
      <cv-row>
        <cv-column>
          <NsInlineNotification
            kind="warning"
            :title="$t('common.use_landscape_mode')"
            :description="$t('common.use_landscape_mode_description')"
            class="landscape-warning"
          />
        </cv-column>
      </cv-row>
      <cv-row>
        <cv-column>
          <NsTabs
            :container="false"
            :aria-label="$t('common.tab_navigation')"
            :noDefaultToFirst="true"
            @tab-selected="tabSelected"
          >
            <cv-tab
              id="tab-1"
              :label="$t('settings_http_routes.routes')"
              :selected="q.view === 'routes'"
            >
              <HttpRoutesPanel
                :nodes="internalNodes"
                :traefikInstances="traefikInstances"
                :isLoadingInstances="loading.listInstalledModules"
                :instancesError="error.listInstalledModules"
                :selectedNodeId.sync="q.selectedNodeId"
              />
            </cv-tab>
            <cv-tab
              id="tab-2"
              :label="$t('settings_http_routes.frontend_proxies')"
              :selected="q.view === 'frontend-proxies'"
            >
              <HttpFrontendProxiesPanel
                :nodes="internalNodes"
                :traefikInstances="traefikInstances"
                :isLoadingInstances="loading.listInstalledModules"
                :instancesError="error.listInstalledModules"
                :selectedNodeId.sync="q.proxyNodeId"
              />
            </cv-tab>
          </NsTabs>
        </cv-column>
      </cv-row>
    </cv-grid>
  </div>
</template>
⋮----
<cv-link to="/settings">{{ $t("settings.title") }}</cv-link>
⋮----
<span>{{ $t("settings_http_routes.title") }}</span>
⋮----
<h3>{{ $t("settings_http_routes.title") }}</h3>
⋮----
<script>
import to from "await-to-js";
import {
  QueryParamService,
  UtilService,
  TaskService,
  PageTitleService,
} from "@nethserver/ns8-ui-lib";
import { mapState } from "vuex";
import HttpRoutesPanel from "@/components/settings/HttpRoutesPanel.vue";
import HttpFrontendProxiesPanel from "@/components/settings/HttpFrontendProxiesPanel.vue";
const VIEWS = ["routes", "frontend-proxies"];
export default {
  name: "SettingsHttpRoutes",
  components: {
    HttpRoutesPanel,
    HttpFrontendProxiesPanel,
  },
  mixins: [TaskService, UtilService, QueryParamService, PageTitleService],
  pageTitle() {
    return this.$t("settings_http_routes.title");
  },
  data() {
    return {
      q: {
        view: "",
        selectedNodeId: "",
        // one param per tab: the two tables filter independently
        proxyNodeId: "",
      },
      traefikInstances: [],
      // [eventName, handler] pairs registered on $root for the read chain
      readListeners: [],
      loading: {
        listInstalledModules: false,
      },
      error: {
        listInstalledModules: "",
      },
    };
  },
  computed: {
    ...mapState(["clusterNodes", "isWebsocketConnected"]),
    internalNodes() {
      return this.clusterNodes.map((node) => {
        const nodeId = node.id.toString();
        const traefikInstance = this.traefikInstances.find(
          (instance) => instance.node === nodeId
        );
        const internalNode = {
          name: nodeId,
          label: this.getShortNodeLabel(node),
          value: nodeId,
        };
        if (traefikInstance) {
          internalNode.label += ` (${traefikInstance.id})`;
          internalNode.traefikInstance = traefikInstance.id;
        }
        return internalNode;
      });
    },
  },
  watch: {
    isWebsocketConnected: function (isConnected) {
      if (isConnected) {
        this.listInstalledModules();
      }
    },
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.watchQueryData(vm);
      vm.queryParamsToDataForCore(vm, to.query);
    });
  },
  beforeRouteUpdate(to, from, next) {
    this.queryParamsToDataForCore(this, to.query);
    next();
  },
  created() {
    if (this.isWebsocketConnected) {
      this.listInstalledModules();
    }
  },
  beforeDestroy() {
    this.clearListeners(this.readListeners);
  },
  mounted() {
    if (!VIEWS.includes(this.q.view)) {
      this.q.view = "routes";
    }
  },
  methods: {
    tabSelected(tabNum) {
      this.q.view = VIEWS[tabNum];
    },
    registerListener(listeners, eventName, handler) {
      this.$root.$once(eventName, handler);
      listeners.push([eventName, handler]);
    },
    clearListeners(listeners) {
      listeners.forEach(([eventName, handler]) => {
        this.$root.$off(eventName, handler);
      });
      listeners.splice(0);
    },
    async listInstalledModules() {
      this.clearListeners(this.readListeners);
      this.loading.listInstalledModules = true;
      this.error.listInstalledModules = "";
      const taskAction = "list-installed-modules";
      const eventId = this.getUuid();
      this.registerListener(
        this.readListeners,
        `${taskAction}-aborted-${eventId}`,
        this.listInstalledModulesAborted
      );
      this.registerListener(
        this.readListeners,
        `${taskAction}-completed-${eventId}`,
        this.listInstalledModulesCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.listInstalledModules = this.getErrorMessage(err);
        this.loading.listInstalledModules = false;
      }
    },
    listInstalledModulesAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.listInstalledModules = this.$t("error.generic_error");
      this.loading.listInstalledModules = false;
    },
    listInstalledModulesCompleted(taskContext, taskResult) {
      let traefikInstances = [];
      for (let instanceList of Object.values(taskResult.output)) {
        for (let instance of instanceList) {
          if (instance.id.startsWith("traefik")) {
            traefikInstances.push(instance);
          }
        }
      }
      this.traefikInstances = traefikInstances;
      this.loading.listInstalledModules = false;
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
</style>
</file>

<file path="core/ui/src/views/settings/SettingsMetrics.vue">
<template>
  <div>
    <cv-grid fullWidth>
      <cv-row>
        <cv-column>
          <cv-breadcrumb
            aria-label="breadcrumb"
            :no-trailing-slash="true"
            class="breadcrumb"
          >
            <cv-breadcrumb-item>
              <cv-link to="/settings">{{ $t("settings.title") }}</cv-link>
            </cv-breadcrumb-item>
            <cv-breadcrumb-item>
              <span>{{ $t("settings_metrics.title") }}</span>
            </cv-breadcrumb-item>
          </cv-breadcrumb>
        </cv-column>
      </cv-row>
      <cv-row>
        <cv-column class="subpage-title">
          <h3>{{ $t("settings_metrics.title") }}</h3>
        </cv-column>
      </cv-row>
      <cv-row>
        <cv-column>
          <NsInlineNotification
            v-if="error.getMetricsId"
            kind="error"
            :title="$t('action.get-metrics-ids')"
            :description="error.getMetricsId"
            :showCloseButton="false"
          />
        </cv-column>
        <cv-column>
          <NsInlineNotification
            v-if="error.getConfiguration"
            kind="error"
            :title="$t('action.get-metrics-configuration')"
            :description="error.getConfiguration"
            :showCloseButton="false"
          />
        </cv-column>
        <cv-column>
          <NsInlineNotification
            v-if="error.getSubscription"
            kind="error"
            :title="$t('action.get-subscription')"
            :description="error.getSubscription"
            :showCloseButton="false"
          />
        </cv-column>
        <cv-column>
          <NsInlineNotification
            v-if="error.getSmarthost"
            kind="error"
            :title="$t('action.get-smarthost')"
            :description="error.getSmarthost"
            :showCloseButton="false"
          />
        </cv-column>
      </cv-row>
      <cv-row>
        <cv-column>
          <cv-tile light>
            <h4 class="mg-bottom-md">
              {{ $t("settings_metrics.grafana") }}
            </h4>
            <div class="title-description mg-bottom-md">
              {{ $t("settings_metrics.grafana_description") }}
            </div>
            <div
              v-if="grafana_path && enable_grafana"
              class="title-description mg-bottom-md"
            >
              <a
                :href="'https://' + hostname"
                target="_blank"
                class="external-link-button"
              >
                <NsButton
                  :disabled="isGrafanaSectionLoading"
                  kind="ghost"
                  :icon="Launch20"
                >
                  {{ $t("settings_metrics.grafana_link") }}
                </NsButton>
              </a>
            </div>
            <cv-form @submit.prevent="setGrafana">
              <NsInlineNotification
                v-if="error.setGrafana"
                kind="error"
                :title="$t('action.set-metrics-configuration')"
                :description="error.setGrafana"
                :showCloseButton="false"
              />
              <NsToggle
                :label="$t('settings_metrics.access_grafana')"
                value="enable_grafana"
                :form-item="true"
                v-model="enable_grafana"
                :disabled="isGrafanaSectionLoading"
                ref="enable_grafana"
              >
                <template slot="tooltip">
                  <span>{{ $t("settings_metrics.grafana_tooltip") }}</span>
                </template>
                <template slot="text-left">{{
                  $t("common.disabled")
                }}</template>
                <template slot="text-right">{{
                  $t("common.enabled")
                }}</template>
              </NsToggle>
              <template v-if="enable_grafana">
                <div class="mg-top-sm icon-and-text mg-bottom-lg">
                  <NsSvg :svg="InformationFilled16" class="icon ns-info" />
                  <span>{{
                    $t(
                      "settings_metrics.note_on_grafana_cluster_admin_credentials"
                    )
                  }}</span>
                </div>
              </template>
              <NsInlineNotification
                v-if="error.setGrafana"
                kind="error"
                :title="$t('action.set-metrics-configuration')"
                :description="error.setGrafana"
                :showCloseButton="false"
              />
              <NsButton
                kind="secondary"
                :disabled="isGrafanaSectionLoading"
                :loading="isGrafanaSectionLoading"
                :icon="Save20"
                >{{ $t("settings_metrics.save") }}
              </NsButton>
            </cv-form>
          </cv-tile>
        </cv-column>
      </cv-row>
      <cv-row>
        <cv-column>
          <cv-tile light>
            <h4 class="mg-bottom-md">
              {{ $t("settings_metrics.alert_notifications") }}
            </h4>
            <div class="title-description mg-bottom-md">
              {{ $t("settings_metrics.alert_notifications_description") }}
            </div>
            <div class="maxwidth" v-if="!smarthost_enabled">
              <NsInlineNotification
                kind="info"
                :title="$t('settings_metrics.disabled_email_notification')"
                :description="
                  $t(
                    'settings_metrics.disabled_email_notifications_description'
                  )
                "
                :showCloseButton="false"
                @click="goToSettingsSmarthost"
                :actionLabel="$t('settings_metrics.go_to_email_notifications')"
              />
            </div>
            <div class="maxwidth" v-if="subscription.status === 'active'">
              <NsInlineNotification
                kind="info"
                :title="
                  $t('settings_metrics.notification_enabled_on_my_nethesis')
                "
                :description="
                  $t('settings_metrics.linked_to_an_active_subscription')
                "
                :showCloseButton="false"
              />
            </div>
            <cv-form @submit.prevent="setNotifications">
              <NsToggle
                v-if="subscription.status !== 'active'"
                :label="$t('settings_metrics.status_notifications')"
                value="status_notifications"
                :form-item="true"
                v-model="status_notifications"
                :disabled="isNotificationsSectionLoading || !smarthost_enabled"
                ref="status_notifications"
              >
                <template slot="tooltip">
                  <span>{{
                    $t("settings_metrics.notifications_tooltip")
                  }}</span>
                </template>
                <template slot="text-left">{{
                  $t("common.disabled")
                }}</template>
                <template slot="text-right">{{
                  $t("common.enabled")
                }}</template>
              </NsToggle>
              <template
                v-if="status_notifications || subscription.status === 'active'"
              >
                <NsTextInput
                  v-model="mail_from"
                  :label="$t('settings_metrics.mail_from')"
                  :form-item="true"
                  :placeholder="$t('settings_metrics.mail_from_placeholder')"
                  :invalid-message="error.mail_from"
                  :disabled="
                    isNotificationsSectionLoading || !smarthost_enabled
                  "
                  ref="mail_from"
                >
                </NsTextInput>
                <cv-text-area
                  :label="$t('settings_metrics.mail_to')"
                  v-model.trim="mail_to"
                  :invalid-message="error.mail_to"
                  :helper-text="$t('settings_metrics.mail_to_helper_text')"
                  :value="mail_to"
                  class="maxwidth textarea"
                  ref="mail_to"
                  :disabled="
                    isNotificationsSectionLoading || !smarthost_enabled
                  "
                >
                </cv-text-area>
              </template>
              <NsInlineNotification
                v-if="error.setNotifications"
                kind="error"
                :title="$t('action.set-metrics-notifications')"
                :description="error.setNotifications"
                :showCloseButton="false"
              />
              <NsButton
                kind="secondary"
                :loading="isNotificationsSectionLoading"
                :disabled="isNotificationsSectionLoading || !smarthost_enabled"
                :icon="Save20"
                >{{ $t("settings_metrics.save") }}
              </NsButton>
            </cv-form>
          </cv-tile>
        </cv-column>
      </cv-row>
    </cv-grid>
  </div>
</template>
⋮----
<cv-link to="/settings">{{ $t("settings.title") }}</cv-link>
⋮----
<span>{{ $t("settings_metrics.title") }}</span>
⋮----
<h3>{{ $t("settings_metrics.title") }}</h3>
⋮----
{{ $t("settings_metrics.grafana") }}
⋮----
{{ $t("settings_metrics.grafana_description") }}
⋮----
{{ $t("settings_metrics.grafana_link") }}
⋮----
<template slot="tooltip">
                  <span>{{ $t("settings_metrics.grafana_tooltip") }}</span>
                </template>
⋮----
<span>{{ $t("settings_metrics.grafana_tooltip") }}</span>
⋮----
<template slot="text-left">{{
                  $t("common.disabled")
                }}</template>
<template slot="text-right">{{
                  $t("common.enabled")
                }}</template>
⋮----
<template v-if="enable_grafana">
                <div class="mg-top-sm icon-and-text mg-bottom-lg">
                  <NsSvg :svg="InformationFilled16" class="icon ns-info" />
                  <span>{{
                    $t(
                      "settings_metrics.note_on_grafana_cluster_admin_credentials"
                    )
                  }}</span>
                </div>
              </template>
⋮----
<span>{{
                    $t(
                      "settings_metrics.note_on_grafana_cluster_admin_credentials"
                    )
                  }}</span>
⋮----
>{{ $t("settings_metrics.save") }}
⋮----
{{ $t("settings_metrics.alert_notifications") }}
⋮----
{{ $t("settings_metrics.alert_notifications_description") }}
⋮----
<template slot="tooltip">
                  <span>{{
                    $t("settings_metrics.notifications_tooltip")
                  }}</span>
                </template>
⋮----
<span>{{
                    $t("settings_metrics.notifications_tooltip")
                  }}</span>
⋮----
<template slot="text-left">{{
                  $t("common.disabled")
                }}</template>
<template slot="text-right">{{
                  $t("common.enabled")
                }}</template>
⋮----
<template
                v-if="status_notifications || subscription.status === 'active'"
              >
                <NsTextInput
                  v-model="mail_from"
                  :label="$t('settings_metrics.mail_from')"
                  :form-item="true"
                  :placeholder="$t('settings_metrics.mail_from_placeholder')"
                  :invalid-message="error.mail_from"
                  :disabled="
                    isNotificationsSectionLoading || !smarthost_enabled
                  "
                  ref="mail_from"
                >
                </NsTextInput>
                <cv-text-area
                  :label="$t('settings_metrics.mail_to')"
                  v-model.trim="mail_to"
                  :invalid-message="error.mail_to"
                  :helper-text="$t('settings_metrics.mail_to_helper_text')"
                  :value="mail_to"
                  class="maxwidth textarea"
                  ref="mail_to"
                  :disabled="
                    isNotificationsSectionLoading || !smarthost_enabled
                  "
                >
                </cv-text-area>
              </template>
⋮----
>{{ $t("settings_metrics.save") }}
⋮----
<script>
import to from "await-to-js";
import {
  QueryParamService,
  UtilService,
  TaskService,
  IconService,
  PageTitleService,
} from "@nethserver/ns8-ui-lib";
import { mapGetters } from "vuex";
import NotificationService from "@/mixins/notification";
export default {
  name: "SettingsMetrics",
  components: {},
  mixins: [
    TaskService,
    UtilService,
    IconService,
    QueryParamService,
    PageTitleService,
    NotificationService,
  ],
  pageTitle() {
    return this.$t("settings_metrics.title");
  },
  data() {
    return {
      metricsId: "metrics1",
      prometheus_path: "",
      grafana_path: "",
      mail_to: [],
      mail_from: "",
      enable_grafana: false,
      status_notifications: false,
      hostname: "",
      smarthost_enabled: true,
      subscription: {
        auth_token: "",
        system_id: "",
        plan_name: { name: "", description: "" },
        expires: true,
        expire_date: "",
        status: "inactive",
        with_remote_support: false,
        error: "",
      },
      loading: {
        getGrafana: false,
        setGrafana: false,
        setNotifications: false,
        getConfiguration: false,
        getSubscription: false,
        getSmarthost: false,
      },
      error: {
        getGrafana: "",
        setGrafana: "",
        prometheus_path: "",
        grafana_path: "",
        mail_to: "",
        mail_from: "",
        enable_grafana: false,
        status_notifications: false,
        hostname: "",
        getConfiguration: "",
        getMetricsId: "",
        setNotifications: "",
        getSmarthost: "",
      },
    };
  },
  computed: {
    ...mapGetters(["leaderNode"]),
    isGrafanaSectionLoading() {
      return (
        this.loading.getGrafana ||
        this.loading.setGrafana ||
        this.loading.getSubscription ||
        this.loading.getSmarthost
      );
    },
    isNotificationsSectionLoading() {
      return (
        this.loading.getGrafana ||
        this.loading.setNotifications ||
        this.loading.getSubscription ||
        this.loading.getSmarthost
      );
    },
  },
  created() {
    this.getMetricsId();
    this.getSubscription();
    this.getSmarthost();
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.watchQueryData(vm);
      vm.queryParamsToDataForCore(vm, to.query);
    });
  },
  beforeRouteUpdate(to, from, next) {
    this.queryParamsToDataForCore(this, to.query);
    next();
  },
  methods: {
    goToSettingsSmarthost() {
      this.$router.push("/settings/smarthost");
    },
    async getSmarthost() {
      this.error.getSmarthost = "";
      this.loading.getSmarthost = true;
      const taskAction = "get-smarthost";
      const eventId = this.getUuid();
      this.$root.$once(
        taskAction + "-completed-" + eventId,
        this.getSmarthostCompleted
      );
      this.$root.$once(
        taskAction + "-aborted-" + eventId,
        this.getSmarthostAborted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.getSmarthost = this.getErrorMessage(err);
        this.loading.getSmarthost = false;
        return;
      }
    },
    getSmarthostAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.getSmarthost = this.core.$t("error.generic_error");
      this.loading.getSmarthost = false;
    },
    getSmarthostCompleted(taskContext, taskResult) {
      const smarthost = taskResult.output;
      this.smarthost_enabled = smarthost.enabled;
      this.loading.getSmarthost = false;
    },
    async getSubscription() {
      this.error.getSubscription = "";
      this.loading.getSubscription = true;
      const taskAction = "get-subscription";
      const eventId = this.getUuid();
      this.$root.$once(
        taskAction + "-completed-" + eventId,
        this.getSubscriptionCompleted
      );
      this.$root.$once(
        taskAction + "-aborted-" + eventId,
        this.getSubscriptionAborted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.getSubscription = this.getErrorMessage(err);
        this.loading.getSubscription = false;
        return;
      }
    },
    getSubscriptionAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.getSubscription = this.core.$t("error.generic_error");
      this.loading.getSubscription = false;
    },
    getSubscriptionCompleted(taskContext, taskResult) {
      const output = taskResult.output;
      this.termsUrl = output.terms_url;
      if (output.subscription == null) {
        this.subscription.status = "inactive";
        this.subscription.error = output.error;
        this.loading.getSubscription = false;
        return;
      }
      this.subscription = output.subscription;
      this.status_notifications = true;
      this.loading.getSubscription = false;
    },
    async getMetricsId() {
      this.error.getGrafana = "";
      this.loading.getGrafana = true;
      const taskAction = "get-metrics-id";
      const eventId = this.getUuid();
      this.$root.$once(
        taskAction + "-completed-" + eventId,
        this.getMetricsIdCompleted
      );
      this.$root.$once(
        taskAction + "-aborted-" + eventId,
        this.getMetricsIdAborted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.getMetricsId = this.getErrorMessage(err);
        this.loading.getGrafana = false;
        return;
      }
    },
    getMetricsIdAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.getMetricsId = this.core.$t("error.generic_error");
      this.loading.getMetricsId = false;
    },
    getMetricsIdCompleted(taskContext, taskResult) {
      const output = taskResult.output;
      this.metricsId = output.metrics_id;
      this.getConfiguration();
    },
    async getConfiguration() {
      this.error.getConfiguration = "";
      const taskAction = "get-configuration";
      const eventId = this.getUuid();
      this.$root.$once(
        taskAction + "-aborted-" + eventId,
        this.getConfigurationAborted
      );
      this.$root.$once(
        taskAction + "-completed-" + eventId,
        this.getConfigurationCompleted
      );
      const res = await to(
        this.createModuleTaskForApp(this.metricsId, {
          action: taskAction,
          extra: {
            title: this.$t("action.get-metrics-configuration"),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.getConfiguration = this.getErrorMessage(err);
        this.loading.getGrafana = false;
        return;
      }
    },
    getConfigurationAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.getConfiguration = this.core.$t("error.generic_error");
      this.loading.getGrafana = false;
    },
    getConfigurationCompleted(taskContext, taskResult) {
      const config = taskResult.output;
      this.grafana_path = config.grafana_path;
      this.hostname = window.location.hostname + "/" + config.grafana_path;
      this.enable_grafana = this.grafana_path ? true : false;
      this.prometheus_path = config.prometheus_path;
      this.mail_to = config.mail_to ? config.mail_to.join("\n") : [];
      this.status_notifications = this.mail_to.length > 0;
      const leaderHostname = this.leaderNode.vpn.endpoint.split(":")[0];
      this.mail_from = config.mail_from
        ? config.mail_from
        : "alertmanager@" + leaderHostname;
      this.loading.getGrafana = false;
    },
    async setGrafana() {
      this.error.setGrafana = "";
      this.loading.setGrafana = true;
      const taskAction = "configure-module";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.setGrafanaCompleted
      );
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.setGrafanaAborted
      );
      this.$root.$once(
        `${taskAction}-validation-failed-${eventId}`,
        this.setGrafanaValidationFailed
      );
      const res = await to(
        this.createModuleTaskForApp(this.metricsId, {
          action: taskAction,
          data: {
            grafana_path: this.enable_grafana ? "grafana" : "",
            prometheus_path: "",
          },
          extra: {
            title: this.$t("action.set-metrics-configuration"),
            isNotificationHidden: false,
            eventId,
            description: this.$t("common.processing"),
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.setGrafana = this.getErrorMessage(err);
        this.loading.setGrafana = false;
        return;
      }
    },
    setGrafanaAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.setGrafana = this.$t("error.generic_error");
      this.loading.setGrafana = false;
    },
    setGrafanaValidationFailed(validationErrors) {
      this.loading.setGrafana = false;
      let focusAlreadySet = false;
      for (const validationError of validationErrors) {
        const param = validationError.parameter;
        this.error[param] = this.getI18nStringWithFallback(
          "settings_metrics." + validationError.error
        );
        if (!focusAlreadySet) {
          this.focusElement(param);
          focusAlreadySet = true;
        }
      }
    },
    setGrafanaCompleted() {
      this.loading.setGrafana = false;
      this.getMetricsId();
    },
    validateSetNotifications() {
      this.clearErrors(this);
      let isValidationOk = true;
      if (this.mail_to.length === 0) {
        this.error.mail_to = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("mail_to");
          isValidationOk = false;
        }
      }
      if (!this.mail_from) {
        this.error.mail_from = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("mail_from");
          isValidationOk = false;
        }
      }
      return isValidationOk;
    },
    async setNotifications() {
      const isValidationOk = this.validateSetNotifications();
      if (!isValidationOk) {
        return;
      }
      this.error.setNotifications = "";
      this.loading.setNotifications = true;
      const taskAction = "configure-module";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.setNotificationsCompleted
      );
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.setNotificationsAborted
      );
      this.$root.$once(
        `${taskAction}-validation-failed-${eventId}`,
        this.setNotificationsValidationFailed
      );
      const res = await to(
        this.createModuleTaskForApp(this.metricsId, {
          action: taskAction,
          data: {
            grafana_path: this.grafana_path ? this.grafana_path : "",
            prometheus_path: "",
            mail_to:
              this.status_notifications || this.subscription.status === "active"
                ? this.mail_to.split("\n")
                : [],
            mail_from: this.mail_from,
          },
          extra: {
            title: this.$t("action.set-metrics-notifications"),
            isNotificationHidden: false,
            eventId,
            description: this.$t("common.processing"),
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.setNotifications = this.getErrorMessage(err);
        this.loading.setNotifications = false;
        return;
      }
    },
    setNotificationsAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.setNotifications = this.$t("error.generic_error");
      this.loading.setNotifications = false;
    },
    setNotificationsValidationFailed(validationErrors) {
      this.loading.setNotifications = false;
      let focusAlreadySet = false;
      for (const validationError of validationErrors) {
        const param = validationError.parameter;
        this.error[param] = this.getI18nStringWithFallback(
          "settings_metrics." + validationError.error
        );
        if (!focusAlreadySet) {
          this.focusElement(param);
          focusAlreadySet = true;
        }
      }
    },
    setNotificationsCompleted() {
      this.loading.setNotifications = false;
      this.getMetricsId();
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
.icon-and-text {
  justify-content: flex-start;
}
.maxwidth {
  max-width: 38rem;
}
</style>
</file>

<file path="core/ui/src/views/settings/SettingsSmartHost.vue">
<template>
  <cv-grid fullWidth>
    <cv-row>
      <cv-column>
        <cv-breadcrumb
          aria-label="breadcrumb"
          :no-trailing-slash="true"
          class="breadcrumb"
        >
          <cv-breadcrumb-item>
            <cv-link to="/settings">{{ $t("settings.title") }}</cv-link>
          </cv-breadcrumb-item>
          <cv-breadcrumb-item>
            <span>{{ $t("smarthost.title") }}</span>
          </cv-breadcrumb-item>
        </cv-breadcrumb>
      </cv-column>
    </cv-row>
    <cv-row>
      <cv-column class="subpage-title">
        <h3>{{ $t("smarthost.title") }}</h3>
      </cv-column>
      <cv-column :md="4" :xlg="6">
        <div class="page-toolbar">
          <cv-tooltip
            alignment="center"
            direction="left"
            :tip="$t('smarthost.alert_notifications_tooltip')"
          >
            <NsButton
              kind="tertiary"
              size="field"
              :icon="ArrowRight20"
              class="subpage-toolbar-item"
              @click="goToAlertNotifications()"
              >{{ $t("smarthost.open_alert_notifications") }}
            </NsButton>
          </cv-tooltip>
        </div>
      </cv-column>
    </cv-row>
    <cv-row v-if="error.getSmarthost">
      <cv-column>
        <NsInlineNotification
          kind="error"
          :title="$t('action.get-smarthost')"
          :description="error.getSmarthost"
          :showCloseButton="false"
        />
      </cv-column>
    </cv-row>
    <cv-row>
      <cv-column>
        <cv-tile :light="true">
          <cv-form @submit.prevent="saveSettings">
            <cv-toggle
              :label="$t('smarthost.enabled')"
              value="statusValue"
              :form-item="true"
              v-model="enabled"
              :disabled="loading.getSmarthost || loading.setSmarthost"
            >
              <template slot="text-left">
                {{ $t("common.disabled") }}
              </template>
              <template slot="text-right">
                {{ $t("common.enabled") }}
              </template>
            </cv-toggle>
            <template v-if="enabled">
              <label class="bx--label">
                {{ $t("smarthost.configuration") }}
              </label>
              <cv-radio-group vertical>
                <cv-radio-button
                  v-model="manual_configuration"
                  value="manual"
                  :label="$t('smarthost.manual_configuration')"
                  ref="manual_configuration"
                  checked
                ></cv-radio-button>
                <cv-radio-button
                  v-model="manual_configuration"
                  value="app"
                  :label="$t('smarthost.mail_app_instance')"
                  ref="manual_configuration"
                ></cv-radio-button>
              </cv-radio-group>
            </template>
            <template v-if="enabled && manual_configuration === 'app'">
              <NsInlineNotification
                v-if="!mail_server.length > 0"
                kind="info"
                :title="$t('smarthost.no_mail_app_instance')"
                :description="$t('smarthost.no_mail_app_instance_description')"
                :showCloseButton="false"
                :actionLabel="$t('smarthost.go_to_software_center')"
                @action="goToSoftwareCenter"
              />
              <NsComboBox
                key="app"
                :options="combobox_mail_server"
                v-model="selected_mail_id"
                :autoFilter="true"
                :autoHighlight="true"
                :title="$t('smarthost.mail_app_instance')"
                :label="$t('smarthost.choose_instance')"
                :acceptUserInput="false"
                :showItemType="false"
                :invalid-message="$t(error.selected_mail_id)"
                :disabled="
                  loading.getSmarthost ||
                  loading.setSmarthost ||
                  !mail_server.length > 0
                "
                ref="selected_mail_id"
              />
            </template>
            <template v-else-if="enabled && manual_configuration === 'manual'">
              <NsTextInput
                v-model.trim="host"
                :placeholder="$t('smarthost.hostname_placeholder')"
                :label="$t('smarthost.hostname_label')"
                :invalid-message="error.host"
                :disabled="loading.getSmarthost || loading.setSmarthost"
                ref="host"
              >
              </NsTextInput>
              <NsTextInput
                v-model.trim="port"
                :label="$t('smarthost.port_label')"
                :placeholder="$t('smarthost.port_placeholder')"
                :invalid-message="error.port"
                :disabled="loading.getSmarthost || loading.setSmarthost"
                ref="port"
              >
              </NsTextInput>
              <NsComboBox
                key="manual"
                v-model="encrypt_smtp"
                :autoFilter="true"
                :autoHighlight="true"
                :title="$t('smarthost.encrypt_smtp')"
                :label="$t('smarthost.choose')"
                :options="combobox_encrypt_smtp"
                :acceptUserInput="false"
                :showItemType="false"
                :invalid-message="error.encrypt_smtp"
                :disabled="loading.getSmarthost || loading.setSmarthost"
                ref="encrypt_smtp"
              />
              <template v-if="encrypt_smtp != 'none'">
                <cv-toggle
                  :label="$t('smarthost.tls_verify')"
                  value="statusValue"
                  :form-item="true"
                  v-model="tls_verify"
                  :disabled="loading.getSmarthost || loading.setSmarthost"
                >
                  <template slot="text-left">
                    {{ $t("common.disabled") }}
                  </template>
                  <template slot="text-right">
                    {{ $t("common.enabled") }}
                  </template>
                </cv-toggle>
              </template>
              <NsTextInput
                v-model.trim="username"
                :placeholder="$t('smarthost.username_placeholder')"
                :label="$t('smarthost.username_label')"
                :helper-text="$t('smarthost.username_helper')"
                :invalid-message="error.username"
                :disabled="loading.getSmarthost || loading.setSmarthost"
                autocomplete="off"
                ref="username"
              >
              </NsTextInput>
              <NsTextInput
                :label="$t('smarthost.password_label')"
                v-model="password"
                :invalid-message="$t(error.password)"
                type="password"
                autocomplete="new-password"
                ref="password"
              >
              </NsTextInput>
              <div ref="setSmarthostError">
                <cv-row v-if="error.test_smarthost">
                  <cv-column>
                    <NsInlineNotification
                      kind="error"
                      :title="$t('action.set-smarthost')"
                      :description="error.test_smarthost"
                      :showCloseButton="false"
                    />
                  </cv-column>
                </cv-row>
              </div>
            </template>
            <NsButton
              kind="primary"
              :icon="Save20"
              :loading="loading.setSmarthost"
              :disabled="
                isLoadingSettings ||
                (!mail_server.length > 0 && manual_configuration === 'app')
              "
              >{{ $t("common.save_settings") }}</NsButton
            >
          </cv-form>
        </cv-tile>
      </cv-column>
    </cv-row>
  </cv-grid>
</template>
⋮----
<cv-link to="/settings">{{ $t("settings.title") }}</cv-link>
⋮----
<span>{{ $t("smarthost.title") }}</span>
⋮----
<h3>{{ $t("smarthost.title") }}</h3>
⋮----
>{{ $t("smarthost.open_alert_notifications") }}
⋮----
<template slot="text-left">
                {{ $t("common.disabled") }}
              </template>
⋮----
{{ $t("common.disabled") }}
⋮----
<template slot="text-right">
                {{ $t("common.enabled") }}
              </template>
⋮----
{{ $t("common.enabled") }}
⋮----
<template v-if="enabled">
              <label class="bx--label">
                {{ $t("smarthost.configuration") }}
              </label>
              <cv-radio-group vertical>
                <cv-radio-button
                  v-model="manual_configuration"
                  value="manual"
                  :label="$t('smarthost.manual_configuration')"
                  ref="manual_configuration"
                  checked
                ></cv-radio-button>
                <cv-radio-button
                  v-model="manual_configuration"
                  value="app"
                  :label="$t('smarthost.mail_app_instance')"
                  ref="manual_configuration"
                ></cv-radio-button>
              </cv-radio-group>
            </template>
⋮----
{{ $t("smarthost.configuration") }}
⋮----
<template v-if="enabled && manual_configuration === 'app'">
              <NsInlineNotification
                v-if="!mail_server.length > 0"
                kind="info"
                :title="$t('smarthost.no_mail_app_instance')"
                :description="$t('smarthost.no_mail_app_instance_description')"
                :showCloseButton="false"
                :actionLabel="$t('smarthost.go_to_software_center')"
                @action="goToSoftwareCenter"
              />
              <NsComboBox
                key="app"
                :options="combobox_mail_server"
                v-model="selected_mail_id"
                :autoFilter="true"
                :autoHighlight="true"
                :title="$t('smarthost.mail_app_instance')"
                :label="$t('smarthost.choose_instance')"
                :acceptUserInput="false"
                :showItemType="false"
                :invalid-message="$t(error.selected_mail_id)"
                :disabled="
                  loading.getSmarthost ||
                  loading.setSmarthost ||
                  !mail_server.length > 0
                "
                ref="selected_mail_id"
              />
            </template>
<template v-else-if="enabled && manual_configuration === 'manual'">
              <NsTextInput
                v-model.trim="host"
                :placeholder="$t('smarthost.hostname_placeholder')"
                :label="$t('smarthost.hostname_label')"
                :invalid-message="error.host"
                :disabled="loading.getSmarthost || loading.setSmarthost"
                ref="host"
              >
              </NsTextInput>
              <NsTextInput
                v-model.trim="port"
                :label="$t('smarthost.port_label')"
                :placeholder="$t('smarthost.port_placeholder')"
                :invalid-message="error.port"
                :disabled="loading.getSmarthost || loading.setSmarthost"
                ref="port"
              >
              </NsTextInput>
              <NsComboBox
                key="manual"
                v-model="encrypt_smtp"
                :autoFilter="true"
                :autoHighlight="true"
                :title="$t('smarthost.encrypt_smtp')"
                :label="$t('smarthost.choose')"
                :options="combobox_encrypt_smtp"
                :acceptUserInput="false"
                :showItemType="false"
                :invalid-message="error.encrypt_smtp"
                :disabled="loading.getSmarthost || loading.setSmarthost"
                ref="encrypt_smtp"
              />
              <template v-if="encrypt_smtp != 'none'">
                <cv-toggle
                  :label="$t('smarthost.tls_verify')"
                  value="statusValue"
                  :form-item="true"
                  v-model="tls_verify"
                  :disabled="loading.getSmarthost || loading.setSmarthost"
                >
                  <template slot="text-left">
                    {{ $t("common.disabled") }}
                  </template>
                  <template slot="text-right">
                    {{ $t("common.enabled") }}
                  </template>
                </cv-toggle>
              </template>
              <NsTextInput
                v-model.trim="username"
                :placeholder="$t('smarthost.username_placeholder')"
                :label="$t('smarthost.username_label')"
                :helper-text="$t('smarthost.username_helper')"
                :invalid-message="error.username"
                :disabled="loading.getSmarthost || loading.setSmarthost"
                autocomplete="off"
                ref="username"
              >
              </NsTextInput>
              <NsTextInput
                :label="$t('smarthost.password_label')"
                v-model="password"
                :invalid-message="$t(error.password)"
                type="password"
                autocomplete="new-password"
                ref="password"
              >
              </NsTextInput>
              <div ref="setSmarthostError">
                <cv-row v-if="error.test_smarthost">
                  <cv-column>
                    <NsInlineNotification
                      kind="error"
                      :title="$t('action.set-smarthost')"
                      :description="error.test_smarthost"
                      :showCloseButton="false"
                    />
                  </cv-column>
                </cv-row>
              </div>
            </template>
⋮----
<template v-if="encrypt_smtp != 'none'">
                <cv-toggle
                  :label="$t('smarthost.tls_verify')"
                  value="statusValue"
                  :form-item="true"
                  v-model="tls_verify"
                  :disabled="loading.getSmarthost || loading.setSmarthost"
                >
                  <template slot="text-left">
                    {{ $t("common.disabled") }}
                  </template>
                  <template slot="text-right">
                    {{ $t("common.enabled") }}
                  </template>
                </cv-toggle>
              </template>
⋮----
<template slot="text-left">
                    {{ $t("common.disabled") }}
                  </template>
⋮----
{{ $t("common.disabled") }}
⋮----
<template slot="text-right">
                    {{ $t("common.enabled") }}
                  </template>
⋮----
{{ $t("common.enabled") }}
⋮----
>{{ $t("common.save_settings") }}</NsButton
⋮----
<script>
import to from "await-to-js";
import {
  QueryParamService,
  UtilService,
  TaskService,
  IconService,
  PageTitleService,
} from "@nethserver/ns8-ui-lib";
import { mapActions } from "vuex";
export default {
  name: "SettingsSmartHost",
  mixins: [
    TaskService,
    UtilService,
    IconService,
    QueryParamService,
    PageTitleService,
  ],
  pageTitle() {
    return this.$t("smarthost.title");
  },
  data() {
    return {
      q: {},
      port: "587",
      host: "",
      username: "",
      password: "",
      enabled: false,
      encrypt_smtp: "STARTTLS",
      tls_verify: true,
      manual_configuration: "manual",
      mail_server: [],
      combobox_mail_server: [],
      selected_mail_id: "",
      combobox_encrypt_smtp: [
        {
          name: "none",
          label: this.$t("smarthost.none"),
          value: "none",
        },
        {
          name: "starttls",
          label: this.$t("smarthost.starttls"),
          value: "starttls",
        },
        {
          name: "tls",
          label: this.$t("smarthost.tls"),
          value: "tls",
        },
      ],
      loading: {
        getSmarthost: true,
        setSmarthost: false,
      },
      error: {
        getSmarthost: "",
        port: "",
        host: "",
        username: "",
        password: "",
        enabled: "",
        tls_verify: "",
        setSmarthost: "",
        test_smarthost: "",
        encrypt_smtp: "",
        selected_mail_id: "",
      },
    };
  },
  computed: {
    isLoadingSettings() {
      return this.loading.getSmarthost || this.loading.setSmarthost;
    },
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.watchQueryData(vm);
      vm.queryParamsToDataForCore(vm, to.query);
    });
  },
  beforeRouteUpdate(to, from, next) {
    this.queryParamsToDataForCore(this, to.query);
    next();
  },
  watch: {
    "error.setSmarthost": function () {
      if (this.error.setSmarthost) {
        this.$nextTick(() => {
          const el = this.$refs.setSmarthostError;
          this.scrollToElement(el);
        });
      }
    },
  },
  created() {
    this.getSmarthost();
  },
  methods: {
    ...mapActions(["setSmarthostInStore"]),
    goToSoftwareCenter() {
      this.$router.push("/software-center");
    },
    goToAlertNotifications() {
      this.$router.push("/settings/metrics");
    },
    async getSmarthost() {
      for (const key of Object.keys(this.error)) {
        this.error[key] = "";
      }
      // this.error.getSmarthost = "";
      this.loading.getSmarthost = true;
      const taskAction = "get-smarthost";
      this.$root.$once(taskAction + "-completed", this.getSmarthostCompleted);
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.getSmarthost = this.getErrorMessage(err);
        this.loading.getSmarthost = false;
        return;
      }
    },
    convertToComboboxObject(server) {
      const label = `${server.mail_name ? server.mail_name : server.mail_id} (${
        server.node_name
          ? server.node_name
          : this.$t("smarthost.node", { nodeId: server.node })
      })`;
      return {
        name: label,
        label: label,
        value: server.mail_id,
      };
    },
    getSmarthostCompleted(taskContext, taskResult) {
      const smarthost = taskResult.output;
      this.manual_configuration = smarthost.manual_configuration
        ? "manual"
        : "app";
      this.host = smarthost.host;
      this.username = smarthost.username;
      this.password = smarthost.password;
      this.port = smarthost.port.toString();
      this.tls_verify = smarthost.tls_verify;
      this.enabled = smarthost.enabled;
      this.$nextTick(() => {
        this.encrypt_smtp = smarthost.encrypt_smtp;
      });
      this.mail_server = smarthost.mail_server;
      this.combobox_mail_server = smarthost.mail_server.map(
        this.convertToComboboxObject
      );
      this.$nextTick(() => {
        if (smarthost.mail_server) {
          const selected_mail_server = smarthost.mail_server.filter(
            (mail) => mail.host === smarthost.host
          )[0];
          this.selected_mail_id = selected_mail_server
            ? selected_mail_server.mail_id
            : "";
        }
      });
      this.loading.getSmarthost = false;
    },
    saveSettings() {
      this.setSmarthost();
    },
    async setSmarthost() {
      this.error.setSmarthost = false;
      this.error.test_smarthost = false;
      const isValidationOk = this.validateConfigureModule();
      if (!isValidationOk) {
        return;
      }
      this.loading.setSmarthost = true;
      const taskAction = "set-smarthost";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.setSmarthostCompleted
      );
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.setSmarthostAborted
      );
      this.$root.$once(
        `${taskAction}-validation-failed-${eventId}`,
        this.setSmarthostValidationFailed
      );
      let data = {};
      if (!this.enabled) {
        data = {
          host: "",
          username: "",
          password: "",
          port: 587,
          encrypt_smtp: "starttls",
          enabled: false,
          tls_verify: true,
        };
      } else if (this.manual_configuration === "manual") {
        data = {
          host: this.host,
          username: this.username,
          password: this.password,
          port: parseInt(this.port),
          encrypt_smtp: this.encrypt_smtp,
          enabled: true,
          tls_verify: this.encrypt_smtp === "none" ? false : this.tls_verify,
        };
      } else {
        const server_host = this.mail_server.filter(
          (mail) => mail.mail_id === this.selected_mail_id
        )[0].host;
        data = {
          host: server_host,
          username: "",
          password: "",
          port: 25,
          encrypt_smtp: "none",
          enabled: true,
          tls_verify: false,
        };
      }
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: data,
          extra: {
            title: this.$t("action." + taskAction),
            eventId,
            isNotificationHidden: false,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.setSmarthost = this.getErrorMessage(err);
        this.loading.setSmarthost = false;
        return;
      }
    },
    setSmarthostValidationFailed(validationErrors) {
      this.loading.setSmarthost = false;
      let focusAlreadySet = false;
      for (const validationError of validationErrors) {
        const param = validationError.parameter;
        this.error[param] = this.getI18nStringWithFallback(
          "smarthost." + validationError.error,
          "error." + validationError.error
        );
        if (!focusAlreadySet) {
          this.focusElement(param);
          focusAlreadySet = true;
        }
      }
    },
    setSmarthostCompleted() {
      this.loading.setSmarthost = false;
      this.getSmarthost();
    },
    setSmarthostAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.setSmarthost = this.$t("error.generic_error");
      this.loading.setSmarthost = false;
    },
    validateConfigureModule() {
      for (const key of Object.keys(this.error)) {
        this.error[key] = "";
      }
      let isValidationOk = true;
      if (this.manual_configuration === "manual" && !this.host) {
        this.error.host = this.getI18nStringWithFallback("smarthost.required");
        if (isValidationOk) {
          this.focusElement("host");
        }
        isValidationOk = false;
      }
      if (this.manual_configuration === "app" && !this.selected_mail_id) {
        this.error.selected_mail_id =
          this.getI18nStringWithFallback("smarthost.required");
        if (isValidationOk) {
          this.focusElement("selected_mail_id");
        }
        isValidationOk = false;
      }
      return isValidationOk;
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
</style>
</file>

<file path="core/ui/src/views/settings/SettingsSoftwareRepositories.vue">
<template>
  <div>
    <div class="bx--grid bx--grid--full-width">
      <div class="bx--row">
        <div class="bx--col-lg-16">
          <cv-breadcrumb
            aria-label="breadcrumb"
            :no-trailing-slash="true"
            class="breadcrumb"
          >
            <cv-breadcrumb-item>
              <cv-link to="/settings">{{ $t("settings.title") }}</cv-link>
            </cv-breadcrumb-item>
            <cv-breadcrumb-item>
              <span>{{ $t("settings_sw_repositories.title") }}</span>
            </cv-breadcrumb-item>
          </cv-breadcrumb>
        </div>
      </div>
      <div class="bx--row">
        <div class="bx--col-lg-16 subpage-title">
          <h3>{{ $t("settings_sw_repositories.title") }}</h3>
        </div>
      </div>
      <div class="bx--row landscape-warning">
        <div class="bx--col-lg-16">
          <NsInlineNotification
            kind="warning"
            :title="$t('common.use_landscape_mode')"
            :description="$t('common.use_landscape_mode_description')"
          />
        </div>
      </div>
      <div class="bx--row">
        <div class="bx--col-lg-16">
          <NsInlineNotification
            v-if="repoToDelete"
            kind="warning"
            :title="
              $t('settings_sw_repositories.repository_is_going_to_be_deleted', {
                object: repoToDelete.name,
              })
            "
            :actionLabel="$t('common.cancel')"
            @action="cancelDeleteRepository()"
            :showCloseButton="false"
            :timer="DELETE_DELAY"
          />
        </div>
      </div>
      <div class="bx--row">
        <div class="bx--col-lg-16">
          <cv-tile :light="true">
            <div class="toolbar">
              <NsButton
                v-if="repositories.length"
                kind="secondary"
                :icon="Add20"
                @click="showCreateRepoModal()"
                :disabled="loading.repositories"
                >{{
                  $t("settings_sw_repositories.create_repository")
                }}</NsButton
              >
            </div>
            <NsDataTable
              :allRows="repositories"
              :columns="i18nTableColumns"
              :rawColumns="tableColumns"
              :sortable="true"
              :isSearchable="false"
              :isLoading="loading.repositories"
              :skeletonRows="5"
              :overflow-menu="true"
              :isErrorShown="!!error.listRepositories"
              :errorTitle="$t('action.list-repositories')"
              :errorDescription="error.listRepositories"
              :itemsPerPageLabel="$t('pagination.items_per_page')"
              :rangeOfTotalItemsLabel="$t('pagination.range_of_total_items')"
              :ofTotalPagesLabel="$t('pagination.of_total_pages')"
              :backwardText="$t('pagination.previous_page')"
              :forwardText="$t('pagination.next_page')"
              :pageNumberLabel="$t('pagination.page_number')"
              @updatePage="tablePage = $event"
              ref="table"
            >
              <template slot="empty-state">
                <NsEmptyState
                  :title="$t('settings_sw_repositories.no_sw_repositories')"
                >
                  <template #description>
                    <div>
                      {{
                        $t(
                          "settings_sw_repositories.no_sw_repositories_description"
                        )
                      }}
                    </div>
                    <NsButton
                      kind="primary"
                      :icon="Add20"
                      @click="showCreateRepoModal()"
                      class="empty-state-button"
                      >{{
                        $t("settings_sw_repositories.create_repository")
                      }}</NsButton
                    ></template
                  >
                </NsEmptyState>
              </template>
              <template slot="data">
                <cv-data-table-row
                  v-for="(row, rowIndex) in tablePage"
                  :key="`${rowIndex}`"
                  :value="`${rowIndex}`"
                >
                  <cv-data-table-cell>{{ row.name }}</cv-data-table-cell>
                  <cv-data-table-cell class="break-word">{{
                    row.url
                  }}</cv-data-table-cell>
                  <cv-data-table-cell>
                    <cv-tag
                      v-if="row.status"
                      kind="green"
                      :label="$t('common.enabled')"
                      class="no-margin"
                    ></cv-tag>
                    <cv-tag
                      v-else
                      kind="high-contrast"
                      :label="$t('common.disabled')"
                      class="no-margin"
                    ></cv-tag>
                  </cv-data-table-cell>
                  <cv-data-table-cell class="table-overflow-menu-cell">
                    <cv-overflow-menu flip-menu class="table-overflow-menu">
                      <cv-overflow-menu-item
                        @click="toggleRepoStatus(row)"
                        :disabled="loading.editRepository"
                      >
                        <NsMenuItem
                          :icon="Power20"
                          :label="
                            row.status
                              ? $t('common.disable')
                              : $t('common.enable')
                          "
                        />
                      </cv-overflow-menu-item>
                      <NsMenuDivider />
                      <cv-overflow-menu-item
                        danger
                        @click="willDeleteRepository(row)"
                      >
                        <NsMenuItem
                          :icon="TrashCan20"
                          :label="$t('common.delete')"
                        />
                      </cv-overflow-menu-item>
                    </cv-overflow-menu>
                  </cv-data-table-cell>
                </cv-data-table-row>
              </template>
            </NsDataTable>
          </cv-tile>
        </div>
      </div>
    </div>
    <NsModal
      size="default"
      :visible="q.isShownCreateRepoModal"
      @modal-hidden="q.isShownCreateRepoModal = false"
      @primary-click="createRepository"
      :primary-button-disabled="loading.createRepository"
    >
      <template slot="title">{{
        $t("settings_sw_repositories.create_repository")
      }}</template>
      <template slot="content">
        <NsInlineNotification
          kind="warning"
          :title="
            $t('settings_sw_repositories.create_repository_warning_title')
          "
          :showCloseButton="false"
        >
          <template slot="description">
            <p class="mg-top-sm mg-bottom-sm">
              {{
                $t(
                  "settings_sw_repositories.create_repository_warning_description_1"
                )
              }}
            </p>
            <ul class="unordered-list">
              <li>
                {{
                  $t("settings_sw_repositories.create_repository_warning_li_1")
                }}
              </li>
              <li>
                {{
                  $t("settings_sw_repositories.create_repository_warning_li_2")
                }}
              </li>
              <li>
                {{
                  $t("settings_sw_repositories.create_repository_warning_li_3")
                }}
              </li>
              <li>
                {{
                  $t("settings_sw_repositories.create_repository_warning_li_4")
                }}
              </li>
              <li>
                {{
                  $t("settings_sw_repositories.create_repository_warning_li_5")
                }}
              </li>
              <p class="mg-top-sm">
                {{
                  $t(
                    "settings_sw_repositories.create_repository_warning_description_2"
                  )
                }}
              </p>
            </ul>
          </template>
        </NsInlineNotification>
        <cv-form @submit.prevent="createRepository">
          <cv-text-input
            :label="$t('settings_sw_repositories.name')"
            v-model.trim="q.newRepoName"
            :invalid-message="$t(error.name)"
            ref="name"
          >
          </cv-text-input>
          <cv-text-input
            :label="$t('settings_sw_repositories.url')"
            v-model.trim="q.newRepoUrl"
            :invalid-message="$t(error.url)"
            ref="url"
          >
          </cv-text-input>
          <cv-toggle
            :label="$t('settings_sw_repositories.status')"
            value="statusValue"
            :form-item="true"
            v-model="q.isNewRepoEnabled"
          >
            <template slot="text-left">{{ $t("common.disabled") }}</template>
            <template slot="text-right">{{ $t("common.enabled") }}</template>
          </cv-toggle>
        </cv-form>
        <NsInlineNotification
          v-if="error.addRepository"
          kind="error"
          :title="$t('action.add-repository')"
          :description="error.addRepository"
          :showCloseButton="false"
        />
      </template>
      <template slot="secondary-button">{{ $t("common.close") }}</template>
      <template slot="primary-button">{{
        $t("settings_sw_repositories.create_repository")
      }}</template>
    </NsModal>
  </div>
</template>
⋮----
<cv-link to="/settings">{{ $t("settings.title") }}</cv-link>
⋮----
<span>{{ $t("settings_sw_repositories.title") }}</span>
⋮----
<h3>{{ $t("settings_sw_repositories.title") }}</h3>
⋮----
>{{
                  $t("settings_sw_repositories.create_repository")
                }}</NsButton
⋮----
<template slot="empty-state">
                <NsEmptyState
                  :title="$t('settings_sw_repositories.no_sw_repositories')"
                >
                  <template #description>
                    <div>
                      {{
                        $t(
                          "settings_sw_repositories.no_sw_repositories_description"
                        )
                      }}
                    </div>
                    <NsButton
                      kind="primary"
                      :icon="Add20"
                      @click="showCreateRepoModal()"
                      class="empty-state-button"
                      >{{
                        $t("settings_sw_repositories.create_repository")
                      }}</NsButton
                    ></template
                  >
                </NsEmptyState>
              </template>
⋮----
<template #description>
                    <div>
                      {{
                        $t(
                          "settings_sw_repositories.no_sw_repositories_description"
                        )
                      }}
                    </div>
                    <NsButton
                      kind="primary"
                      :icon="Add20"
                      @click="showCreateRepoModal()"
                      class="empty-state-button"
                      >{{
                        $t("settings_sw_repositories.create_repository")
                      }}</NsButton
                    ></template
                  >
⋮----
{{
                        $t(
                          "settings_sw_repositories.no_sw_repositories_description"
                        )
                      }}
⋮----
>{{
                        $t("settings_sw_repositories.create_repository")
                      }}</NsButton
⋮----
<template slot="data">
                <cv-data-table-row
                  v-for="(row, rowIndex) in tablePage"
                  :key="`${rowIndex}`"
                  :value="`${rowIndex}`"
                >
                  <cv-data-table-cell>{{ row.name }}</cv-data-table-cell>
                  <cv-data-table-cell class="break-word">{{
                    row.url
                  }}</cv-data-table-cell>
                  <cv-data-table-cell>
                    <cv-tag
                      v-if="row.status"
                      kind="green"
                      :label="$t('common.enabled')"
                      class="no-margin"
                    ></cv-tag>
                    <cv-tag
                      v-else
                      kind="high-contrast"
                      :label="$t('common.disabled')"
                      class="no-margin"
                    ></cv-tag>
                  </cv-data-table-cell>
                  <cv-data-table-cell class="table-overflow-menu-cell">
                    <cv-overflow-menu flip-menu class="table-overflow-menu">
                      <cv-overflow-menu-item
                        @click="toggleRepoStatus(row)"
                        :disabled="loading.editRepository"
                      >
                        <NsMenuItem
                          :icon="Power20"
                          :label="
                            row.status
                              ? $t('common.disable')
                              : $t('common.enable')
                          "
                        />
                      </cv-overflow-menu-item>
                      <NsMenuDivider />
                      <cv-overflow-menu-item
                        danger
                        @click="willDeleteRepository(row)"
                      >
                        <NsMenuItem
                          :icon="TrashCan20"
                          :label="$t('common.delete')"
                        />
                      </cv-overflow-menu-item>
                    </cv-overflow-menu>
                  </cv-data-table-cell>
                </cv-data-table-row>
              </template>
⋮----
<cv-data-table-cell>{{ row.name }}</cv-data-table-cell>
<cv-data-table-cell class="break-word">{{
                    row.url
                  }}</cv-data-table-cell>
⋮----
<template slot="title">{{
        $t("settings_sw_repositories.create_repository")
      }}</template>
<template slot="content">
        <NsInlineNotification
          kind="warning"
          :title="
            $t('settings_sw_repositories.create_repository_warning_title')
          "
          :showCloseButton="false"
        >
          <template slot="description">
            <p class="mg-top-sm mg-bottom-sm">
              {{
                $t(
                  "settings_sw_repositories.create_repository_warning_description_1"
                )
              }}
            </p>
            <ul class="unordered-list">
              <li>
                {{
                  $t("settings_sw_repositories.create_repository_warning_li_1")
                }}
              </li>
              <li>
                {{
                  $t("settings_sw_repositories.create_repository_warning_li_2")
                }}
              </li>
              <li>
                {{
                  $t("settings_sw_repositories.create_repository_warning_li_3")
                }}
              </li>
              <li>
                {{
                  $t("settings_sw_repositories.create_repository_warning_li_4")
                }}
              </li>
              <li>
                {{
                  $t("settings_sw_repositories.create_repository_warning_li_5")
                }}
              </li>
              <p class="mg-top-sm">
                {{
                  $t(
                    "settings_sw_repositories.create_repository_warning_description_2"
                  )
                }}
              </p>
            </ul>
          </template>
        </NsInlineNotification>
        <cv-form @submit.prevent="createRepository">
          <cv-text-input
            :label="$t('settings_sw_repositories.name')"
            v-model.trim="q.newRepoName"
            :invalid-message="$t(error.name)"
            ref="name"
          >
          </cv-text-input>
          <cv-text-input
            :label="$t('settings_sw_repositories.url')"
            v-model.trim="q.newRepoUrl"
            :invalid-message="$t(error.url)"
            ref="url"
          >
          </cv-text-input>
          <cv-toggle
            :label="$t('settings_sw_repositories.status')"
            value="statusValue"
            :form-item="true"
            v-model="q.isNewRepoEnabled"
          >
            <template slot="text-left">{{ $t("common.disabled") }}</template>
            <template slot="text-right">{{ $t("common.enabled") }}</template>
          </cv-toggle>
        </cv-form>
        <NsInlineNotification
          v-if="error.addRepository"
          kind="error"
          :title="$t('action.add-repository')"
          :description="error.addRepository"
          :showCloseButton="false"
        />
      </template>
⋮----
<template slot="description">
            <p class="mg-top-sm mg-bottom-sm">
              {{
                $t(
                  "settings_sw_repositories.create_repository_warning_description_1"
                )
              }}
            </p>
            <ul class="unordered-list">
              <li>
                {{
                  $t("settings_sw_repositories.create_repository_warning_li_1")
                }}
              </li>
              <li>
                {{
                  $t("settings_sw_repositories.create_repository_warning_li_2")
                }}
              </li>
              <li>
                {{
                  $t("settings_sw_repositories.create_repository_warning_li_3")
                }}
              </li>
              <li>
                {{
                  $t("settings_sw_repositories.create_repository_warning_li_4")
                }}
              </li>
              <li>
                {{
                  $t("settings_sw_repositories.create_repository_warning_li_5")
                }}
              </li>
              <p class="mg-top-sm">
                {{
                  $t(
                    "settings_sw_repositories.create_repository_warning_description_2"
                  )
                }}
              </p>
            </ul>
          </template>
⋮----
{{
                $t(
                  "settings_sw_repositories.create_repository_warning_description_1"
                )
              }}
⋮----
{{
                  $t("settings_sw_repositories.create_repository_warning_li_1")
                }}
⋮----
{{
                  $t("settings_sw_repositories.create_repository_warning_li_2")
                }}
⋮----
{{
                  $t("settings_sw_repositories.create_repository_warning_li_3")
                }}
⋮----
{{
                  $t("settings_sw_repositories.create_repository_warning_li_4")
                }}
⋮----
{{
                  $t("settings_sw_repositories.create_repository_warning_li_5")
                }}
⋮----
{{
                  $t(
                    "settings_sw_repositories.create_repository_warning_description_2"
                  )
                }}
⋮----
<template slot="text-left">{{ $t("common.disabled") }}</template>
<template slot="text-right">{{ $t("common.enabled") }}</template>
⋮----
<template slot="secondary-button">{{ $t("common.close") }}</template>
<template slot="primary-button">{{
        $t("settings_sw_repositories.create_repository")
      }}</template>
⋮----
<script>
import to from "await-to-js";
import {
  QueryParamService,
  UtilService,
  TaskService,
  IconService,
  PageTitleService,
} from "@nethserver/ns8-ui-lib";
export default {
  name: "SettingsSoftwareRepositories",
  mixins: [
    TaskService,
    UtilService,
    IconService,
    QueryParamService,
    PageTitleService,
  ],
  pageTitle() {
    return this.$t("settings_sw_repositories.title");
  },
  data() {
    return {
      q: {
        isShownCreateRepoModal: false,
        newRepoName: "",
        newRepoUrl: "",
        isNewRepoEnabled: true,
      },
      repositories: [],
      tablePage: [],
      tableColumns: ["name", "url", "status"],
      repoToDelete: null,
      loading: {
        repositories: true,
        createRepository: false,
        editRepository: false,
      },
      error: {
        name: "",
        url: "",
        listRepositories: "",
        addRepository: "",
        alterRepository: "",
      },
    };
  },
  computed: {
    i18nTableColumns() {
      return this.tableColumns.map((column) => {
        return this.$t("settings_sw_repositories." + column);
      });
    },
  },
  watch: {
    "q.isShownCreateRepoModal": function () {
      if (this.q.isShownCreateRepoModal) {
        setTimeout(() => {
          this.focusElement("name");
        }, 300);
      }
    },
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.watchQueryData(vm);
      vm.queryParamsToDataForCore(vm, to.query);
    });
  },
  beforeRouteUpdate(to, from, next) {
    this.queryParamsToDataForCore(this, to.query);
    next();
  },
  created() {
    this.listRepositories();
  },
  methods: {
    addRepositoryValidationFailed(validationErrors) {
      this.loading.createRepository = false;
      this.loading.editRepository = false;
      let focusAlreadySet = false;
      for (const validationError of validationErrors) {
        const param = validationError.parameter;
        this.error[param] = "settings_sw_repositories." + validationError.error;
        if (!focusAlreadySet) {
          this.focusElement(param);
          focusAlreadySet = true;
        }
      }
    },
    showCreateRepoModal() {
      this.clearErrors(this);
      this.q.isShownCreateRepoModal = true;
    },
    async listRepositories() {
      this.loading.repositories = true;
      this.error.listRepositories = "";
      const taskAction = "list-repositories";
      this.$root.$once(
        taskAction + "-completed",
        this.listRepositoriesCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.listRepositories = this.getErrorMessage(err);
        this.loading.repositories = false;
        return;
      }
    },
    listRepositoriesCompleted(taskContext, taskResult) {
      const repositories = taskResult.output;
      this.repositories = repositories.sort(this.sortByProperty("name"));
      this.loading.repositories = false;
    },
    validateNewRepository() {
      this.clearErrors(this);
      let isValidationOk = true;
      if (!this.q.newRepoName) {
        this.error.name = "common.required";
        isValidationOk = false;
      }
      if (!this.q.newRepoUrl) {
        this.error.url = "common.required";
        isValidationOk = false;
      }
      return isValidationOk;
    },
    async createRepository() {
      this.loading.createRepository = true;
      this.error.addRepository = "";
      if (!this.validateNewRepository()) {
        this.loading.createRepository = false;
        return;
      }
      const taskAction = "add-repository";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.addRepositoryAborted
      );
      this.$root.$once(
        `${taskAction}-validation-ok-${eventId}`,
        this.addRepositoryValidationOk
      );
      this.$root.$once(
        `${taskAction}-validation-failed-${eventId}`,
        this.addRepositoryValidationFailed
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.addRepositoryCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {
            name: this.q.newRepoName,
            url: this.q.newRepoUrl,
            status: this.q.isNewRepoEnabled,
          },
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.addRepository = this.getErrorMessage(err);
        this.loading.createRepository = false;
        return;
      }
    },
    addRepositoryAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.addRepository = this.$t("error.generic_error");
      this.loading.createRepository = false;
      this.q.isShownCreateRepoModal = false;
    },
    addRepositoryValidationOk() {
      this.q.isShownCreateRepoModal = false;
      this.loading.createRepository = false;
    },
    alterRepositoryValidationOk() {
      this.loading.editRepository = false;
    },
    async toggleRepoStatus(repo) {
      this.loading.editRepository = true;
      this.error.alterRepository = "";
      const taskAction = "alter-repository";
      this.$root.$off(taskAction + "-validation-ok");
      this.$root.$once(
        taskAction + "-validation-ok",
        this.alterRepositoryValidationOk
      );
      this.$root.$off(taskAction + "-completed");
      this.$root.$once(
        taskAction + "-completed",
        this.alterRepositoryCompleted
      );
      const notificationTitle = repo.status
        ? this.$t("settings_sw_repositories.disable_repository", {
            name: repo.name,
          })
        : this.$t("settings_sw_repositories.enable_repository", {
            name: repo.name,
          });
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {
            name: repo.name,
            status: !repo.status,
          },
          extra: {
            title: notificationTitle,
            description: this.$t("common.processing"),
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.alterRepository = this.getErrorMessage(err);
        this.loading.editRepository = false;
        return;
      }
    },
    addRepositoryCompleted() {
      this.q.newRepoName = "";
      this.q.newRepoUrl = "";
      this.q.isNewRepoEnabled = true;
      this.listRepositories();
    },
    alterRepositoryAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.alterRepository = this.$t("error.generic_error");
      this.loading.editRepository = false;
    },
    alterRepositoryCompleted() {
      this.listRepositories();
    },
    willDeleteRepository(repo) {
      const timeout = setTimeout(() => {
        this.deleteRepository(repo);
        this.repoToDelete = null;
      }, this.DELETE_DELAY);
      repo.timeout = timeout;
      this.repoToDelete = repo;
      this.repositories = this.repositories.filter((r) => {
        return r.name != repo.name;
      });
    },
    async deleteRepository(repo) {
      const taskAction = "remove-repository";
      this.$root.$on(taskAction + "-completed", this.removeRepositoryCompleted);
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {
            name: repo.name,
          },
          extra: {
            title: this.$t("action." + taskAction),
            description: this.$t("common.processing"),
          },
        })
      );
      const err = res[0];
      if (err) {
        this.createErrorNotification(
          err,
          this.$t("task.cannot_create_task", { action: taskAction })
        );
        return;
      }
    },
    removeRepositoryCompleted() {
      this.listRepositories();
    },
    cancelDeleteRepository() {
      clearTimeout(this.repoToDelete.timeout);
      this.repoToDelete = null;
      this.listRepositories();
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
.break-word {
  word-wrap: break-word;
  max-width: 20vw;
}
</style>
</file>

<file path="core/ui/src/views/settings/SettingsSubscription.vue">
<template>
  <div>
    <cv-grid fullWidth>
      <cv-row>
        <cv-column>
          <cv-breadcrumb
            aria-label="breadcrumb"
            :no-trailing-slash="true"
            class="breadcrumb"
          >
            <cv-breadcrumb-item>
              <cv-link to="/settings">{{ $t("settings.title") }}</cv-link>
            </cv-breadcrumb-item>
            <cv-breadcrumb-item>
              <span>{{ $t("settings_subscription.title") }}</span>
            </cv-breadcrumb-item>
          </cv-breadcrumb>
        </cv-column>
      </cv-row>
      <cv-row>
        <cv-column class="subpage-title">
          <h3>{{ $t("settings_subscription.title") }}</h3>
        </cv-column>
      </cv-row>
      <cv-row>
        <cv-column>
          <NsInlineNotification
            v-if="error.getSubscription"
            kind="error"
            :title="$t('action.get-subscription')"
            :description="error.getSubscription"
            :showCloseButton="false"
          />
        </cv-column>
      </cv-row>
      <cv-row>
        <cv-column>
          <NsInlineNotification
            v-if="subscription.error === 'os_not_supported'"
            kind="info"
            :title="$t('settings_subscription.subscription_cannot_be_enabled')"
            :description="$t('settings_subscription.os_not_supported')"
            :showCloseButton="false"
          />
        </cv-column>
      </cv-row>
      <cv-row>
        <cv-column>
          <cv-tile light>
            <h4 class="mg-bottom-md">
              {{ $t("settings_subscription.cluster_subscription") }}
            </h4>
            <div class="title-description mg-bottom-md">
              <i18n
                path="settings_subscription.cluster_subscription_description"
                tag="p"
              >
                <template v-slot:enterprise>
                  <cv-link
                    href="https://my.nethesis.it"
                    target="_blank"
                    rel="noreferrer"
                  >
                    my.nethesis.it
                  </cv-link>
                </template>
                <template v-slot:subscription>
                  <cv-link
                    href="https://my.nethserver.com"
                    target="_blank"
                    rel="noreferrer"
                  >
                    my.nethserver.com
                  </cv-link>
                </template>
              </i18n>
            </div>
            <cv-form @submit.prevent="setSubscription">
              <cv-skeleton-text
                v-if="loading.getSubscription"
                :paragraph="true"
                :line-count="6"
                width="80%"
              ></cv-skeleton-text>
              <template
                v-if="
                  !loading.getSubscription && subscription.status == 'inactive'
                "
              >
                <NsTextInput
                  :disabled="subscription.error === 'os_not_supported'"
                  :label="$t('settings_subscription.authentication_token')"
                  v-model.trim="subscription.auth_token"
                  :invalid-message="error.auth_token"
                  :placeholder="
                    $t('settings_subscription.authentication_token_placeholder')
                  "
                  ref="auth_token"
                  :helper-text="
                    $t('settings_subscription.authentication_token_helper')
                  "
                >
                </NsTextInput>
                <div class="mg-bottom-lg">
                  <NsCheckbox
                    v-model="agreeTerms"
                    value="checkTerms"
                    class="no-mg-bottom"
                  >
                    <template slot="label">
                      <i18n
                        path="settings_subscription.agree_terms_before_register"
                        tag="span"
                      >
                        <template v-slot:terms>
                          <cv-link
                            :href="termsUrl"
                            target="_blank"
                            rel="noreferrer"
                            class="inline"
                          >
                            {{ $t("common.terms_and_conditions") }}
                          </cv-link>
                        </template>
                      </i18n>
                    </template>
                  </NsCheckbox>
                  <div
                    v-if="error.agreeTerms"
                    class="validation-failed-invalid-message"
                  >
                    {{ error.agreeTerms }}
                  </div>
                </div>
              </template>
              <div
                v-if="
                  !loading.getSubscription && subscription.status == 'active'
                "
                class="subscription-details"
              >
                <div class="key-value-setting">
                  <span class="label">{{
                    $t("settings_subscription.system_id")
                  }}</span>
                  <span class="value">
                    <cv-link
                      v-if="subscription.system_url"
                      :href="subscription.system_url"
                      target="_blank"
                      >{{ subscription.system_id }}</cv-link
                    >
                    <template v-else>{{ subscription.system_id }}</template>
                  </span>
                </div>
                <div class="key-value-setting">
                  <span class="label">{{
                    $t("settings_subscription.plan_name")
                  }}</span>
                  <span class="value">{{ subscription.plan_name }}</span>
                </div>
                <div v-if="subscription.company" class="key-value-setting">
                  <span class="label">{{
                    $t("settings_subscription.company")
                  }}</span>
                  <span class="value">{{ subscription.company }}</span>
                </div>
                <div class="key-value-setting">
                  <span class="label">{{
                    $t("settings_subscription.expire_date")
                  }}</span>
                  <span class="value">{{
                    !subscription.expires ||
                    !subscription.expire_date ||
                    subscription.expire_date === "-1"
                      ? $t("settings_subscription.no_expiration")
                      : formatDate(
                          new Date(subscription.expire_date),
                          "yyyy-MM-dd"
                        )
                  }}</span>
                </div>
                <div class="key-value-setting">
                  <span class="label">{{
                    $t("settings_subscription.status")
                  }}</span>
                  <span class="value">
                    <cv-tag
                      v-if="subscription.status"
                      kind="green"
                      :label="$t('common.active')"
                      size="sm"
                      class="no-margin"
                    ></cv-tag>
                    <cv-tag
                      v-else
                      kind="high-contrast"
                      :label="$t('common.not_active')"
                      size="sm"
                      class="no-margin"
                    ></cv-tag>
                  </span>
                </div>
              </div>
              <template
                v-if="
                  !loading.getSubscription && subscription.status == 'pending'
                "
              >
                <NsInlineNotification
                  kind="warning"
                  :title="$t('settings_subscription.migration_pending_title')"
                  :description="
                    $t('settings_subscription.migration_pending_description')
                  "
                  :showCloseButton="false"
                />
                <NsInlineNotification
                  v-if="error.migrateSubscription"
                  kind="error"
                  :title="$t('action.migrate-subscription')"
                  :description="error.migrateSubscription"
                  :showCloseButton="false"
                />
                <NsButton
                  kind="primary"
                  :loading="loading.migrateSubscription"
                  :disabled="loading.migrateSubscription"
                  :icon="Restart20"
                  @click="migrateSubscription"
                  >{{ $t("settings_subscription.complete_migration") }}
                </NsButton>
              </template>
              <NsInlineNotification
                v-if="error.setSubscription"
                kind="error"
                :title="$t('action.register-cluster-subscription')"
                :description="error.setSubscription"
                :showCloseButton="false"
              />
              <NsButton
                kind="primary"
                v-if="
                  !loading.getSubscription && subscription.status == 'inactive'
                "
                :loading="loading.getSubscription || loading.setSubscription"
                :disabled="
                  loading.getSubscription ||
                  loading.setSubscription ||
                  subscription.error === 'os_not_supported'
                "
                :icon="Badge20"
                >{{ $t("settings_subscription.request_subscription") }}
              </NsButton>
            </cv-form>
            <NsButton
              v-if="subscription.status == 'active'"
              kind="tertiary"
              :loading="loading.getSubscription || loading.setSubscription"
              :disabled="loading.getSubscription || loading.setSubscription"
              @click="showRemoveSubcriptionModal"
              :icon="TrashCan20"
              >{{ $t("settings_subscription.remove_subscription") }}
            </NsButton>
          </cv-tile>
        </cv-column>
      </cv-row>
      <cv-row
        v-if="
          subscription.with_remote_support && subscription.status == 'active'
        "
      >
        <cv-column>
          <cv-tile light>
            <h4>
              {{ $t("settings_subscription.remote_support") }}
            </h4>
            <div class="title-description mg-bottom-xlg">
              {{
                $t("settings_subscription.remote_support_description", {
                  productName: $root.config.PRODUCT_NAME,
                })
              }}
            </div>
            <NsInlineNotification
              v-if="error.getSupportSession"
              kind="error"
              :title="
                $t('settings_subscription.cannot_retrieve_get_support_status')
              "
              :description="error.getSupportSession"
              :showCloseButton="false"
            />
            <template v-if="!active">
              <div>
                <NsInlineNotification
                  v-if="error.request_support"
                  kind="error"
                  :title="$t('settings_subscription.cannot_request_support')"
                  :description="error.request_support"
                  :showCloseButton="false"
                />
                <NsButton
                  :loading="loading.startSessionSupport"
                  :disabled="loading.startSessionSupport"
                  kind="secondary"
                  :icon="Play20"
                  @click="startSessionSupport"
                >
                  {{ $t("settings_subscription.start_session_support") }}
                </NsButton>
              </div>
            </template>
            <template v-else>
              <span class="label">
                {{ $t("settings_subscription.session_id") }}
              </span>
              <NsCodeSnippet
                :copyTooltip="$t('common.copy_to_clipboard')"
                :copy-feedback="$t('common.copied_to_clipboard')"
                :feedback-aria-label="$t('common.copied_to_clipboard')"
                :wrap-text="true"
                :moreText="$t('common.show_more')"
                :lessText="$t('common.show_less')"
                hideExpandButton
                class="mg-top-sm"
                >{{ session_id }}</NsCodeSnippet
              >
              <div class="mg-top-sm mg-bottom-lg helper-text">
                {{
                  $t("settings_subscription.paste_session_id_to_support_team")
                }}
              </div>
              <div class="mg-top-sm icon-and-text mg-bottom-lg">
                <NsSvg :svg="InformationFilled16" class="icon ns-info" />
                <span>{{
                  $t(
                    "settings_subscription.remote_support_in_progress_with_expiration",
                    {
                      time: formatExpiryDate(sessionExpireDate),
                    }
                  )
                }}</span>
              </div>
              <NsButton
                :loading="loading.stopSessionSupport"
                :disabled="loading.stopSessionSupport"
                class="mg-top-sm mg-bottom-lg"
                kind="primary"
                :icon="Stop20"
                @click="stopSessionSupport"
              >
                {{ $t("settings_subscription.stop_session_support") }}
              </NsButton>
            </template>
          </cv-tile>
        </cv-column>
      </cv-row>
    </cv-grid>
    <NsModal
      size="default"
      kind="danger"
      :visible="isShownRemoveSubcription"
      @modal-hidden="hideRemoveSubcriptionModal"
      @primary-click="removeSubscription"
    >
      <template slot="title">{{
        $t("settings_subscription.remove_cluster_subscription_title")
      }}</template>
      <template slot="content">
        <NsInlineNotification
          kind="warning"
          :title="
            $t(
              'settings_subscription.remove_cluster_subscription_irreversible_title'
            )
          "
          :description="
            $t('settings_subscription.remove_cluster_subscription_irreversible')
          "
          :showCloseButton="false"
        />
        <div class="mg-top-md">
          {{
            $t("settings_subscription.remove_cluster_subscription_description")
          }}
        </div>
      </template>
      <template slot="secondary-button">{{ $t("common.cancel") }}</template>
      <template slot="primary-button">{{ $t("common.remove") }}</template>
    </NsModal>
  </div>
</template>
⋮----
<cv-link to="/settings">{{ $t("settings.title") }}</cv-link>
⋮----
<span>{{ $t("settings_subscription.title") }}</span>
⋮----
<h3>{{ $t("settings_subscription.title") }}</h3>
⋮----
{{ $t("settings_subscription.cluster_subscription") }}
⋮----
<template v-slot:enterprise>
                  <cv-link
                    href="https://my.nethesis.it"
                    target="_blank"
                    rel="noreferrer"
                  >
                    my.nethesis.it
                  </cv-link>
                </template>
<template v-slot:subscription>
                  <cv-link
                    href="https://my.nethserver.com"
                    target="_blank"
                    rel="noreferrer"
                  >
                    my.nethserver.com
                  </cv-link>
                </template>
⋮----
<template
                v-if="
                  !loading.getSubscription && subscription.status == 'inactive'
                "
              >
                <NsTextInput
                  :disabled="subscription.error === 'os_not_supported'"
                  :label="$t('settings_subscription.authentication_token')"
                  v-model.trim="subscription.auth_token"
                  :invalid-message="error.auth_token"
                  :placeholder="
                    $t('settings_subscription.authentication_token_placeholder')
                  "
                  ref="auth_token"
                  :helper-text="
                    $t('settings_subscription.authentication_token_helper')
                  "
                >
                </NsTextInput>
                <div class="mg-bottom-lg">
                  <NsCheckbox
                    v-model="agreeTerms"
                    value="checkTerms"
                    class="no-mg-bottom"
                  >
                    <template slot="label">
                      <i18n
                        path="settings_subscription.agree_terms_before_register"
                        tag="span"
                      >
                        <template v-slot:terms>
                          <cv-link
                            :href="termsUrl"
                            target="_blank"
                            rel="noreferrer"
                            class="inline"
                          >
                            {{ $t("common.terms_and_conditions") }}
                          </cv-link>
                        </template>
                      </i18n>
                    </template>
                  </NsCheckbox>
                  <div
                    v-if="error.agreeTerms"
                    class="validation-failed-invalid-message"
                  >
                    {{ error.agreeTerms }}
                  </div>
                </div>
              </template>
⋮----
<template slot="label">
                      <i18n
                        path="settings_subscription.agree_terms_before_register"
                        tag="span"
                      >
                        <template v-slot:terms>
                          <cv-link
                            :href="termsUrl"
                            target="_blank"
                            rel="noreferrer"
                            class="inline"
                          >
                            {{ $t("common.terms_and_conditions") }}
                          </cv-link>
                        </template>
                      </i18n>
                    </template>
⋮----
<template v-slot:terms>
                          <cv-link
                            :href="termsUrl"
                            target="_blank"
                            rel="noreferrer"
                            class="inline"
                          >
                            {{ $t("common.terms_and_conditions") }}
                          </cv-link>
                        </template>
⋮----
{{ $t("common.terms_and_conditions") }}
⋮----
{{ error.agreeTerms }}
⋮----
<span class="label">{{
                    $t("settings_subscription.system_id")
                  }}</span>
⋮----
>{{ subscription.system_id }}</cv-link
⋮----
<template v-else>{{ subscription.system_id }}</template>
⋮----
<span class="label">{{
                    $t("settings_subscription.plan_name")
                  }}</span>
<span class="value">{{ subscription.plan_name }}</span>
⋮----
<span class="label">{{
                    $t("settings_subscription.company")
                  }}</span>
<span class="value">{{ subscription.company }}</span>
⋮----
<span class="label">{{
                    $t("settings_subscription.expire_date")
                  }}</span>
<span class="value">{{
                    !subscription.expires ||
                    !subscription.expire_date ||
                    subscription.expire_date === "-1"
                      ? $t("settings_subscription.no_expiration")
                      : formatDate(
                          new Date(subscription.expire_date),
                          "yyyy-MM-dd"
                        )
                  }}</span>
⋮----
<span class="label">{{
                    $t("settings_subscription.status")
                  }}</span>
⋮----
<template
                v-if="
                  !loading.getSubscription && subscription.status == 'pending'
                "
              >
                <NsInlineNotification
                  kind="warning"
                  :title="$t('settings_subscription.migration_pending_title')"
                  :description="
                    $t('settings_subscription.migration_pending_description')
                  "
                  :showCloseButton="false"
                />
                <NsInlineNotification
                  v-if="error.migrateSubscription"
                  kind="error"
                  :title="$t('action.migrate-subscription')"
                  :description="error.migrateSubscription"
                  :showCloseButton="false"
                />
                <NsButton
                  kind="primary"
                  :loading="loading.migrateSubscription"
                  :disabled="loading.migrateSubscription"
                  :icon="Restart20"
                  @click="migrateSubscription"
                  >{{ $t("settings_subscription.complete_migration") }}
                </NsButton>
              </template>
⋮----
>{{ $t("settings_subscription.complete_migration") }}
⋮----
>{{ $t("settings_subscription.request_subscription") }}
⋮----
>{{ $t("settings_subscription.remove_subscription") }}
⋮----
{{ $t("settings_subscription.remote_support") }}
⋮----
{{
                $t("settings_subscription.remote_support_description", {
                  productName: $root.config.PRODUCT_NAME,
                })
              }}
⋮----
<template v-if="!active">
              <div>
                <NsInlineNotification
                  v-if="error.request_support"
                  kind="error"
                  :title="$t('settings_subscription.cannot_request_support')"
                  :description="error.request_support"
                  :showCloseButton="false"
                />
                <NsButton
                  :loading="loading.startSessionSupport"
                  :disabled="loading.startSessionSupport"
                  kind="secondary"
                  :icon="Play20"
                  @click="startSessionSupport"
                >
                  {{ $t("settings_subscription.start_session_support") }}
                </NsButton>
              </div>
            </template>
⋮----
{{ $t("settings_subscription.start_session_support") }}
⋮----
<template v-else>
              <span class="label">
                {{ $t("settings_subscription.session_id") }}
              </span>
              <NsCodeSnippet
                :copyTooltip="$t('common.copy_to_clipboard')"
                :copy-feedback="$t('common.copied_to_clipboard')"
                :feedback-aria-label="$t('common.copied_to_clipboard')"
                :wrap-text="true"
                :moreText="$t('common.show_more')"
                :lessText="$t('common.show_less')"
                hideExpandButton
                class="mg-top-sm"
                >{{ session_id }}</NsCodeSnippet
              >
              <div class="mg-top-sm mg-bottom-lg helper-text">
                {{
                  $t("settings_subscription.paste_session_id_to_support_team")
                }}
              </div>
              <div class="mg-top-sm icon-and-text mg-bottom-lg">
                <NsSvg :svg="InformationFilled16" class="icon ns-info" />
                <span>{{
                  $t(
                    "settings_subscription.remote_support_in_progress_with_expiration",
                    {
                      time: formatExpiryDate(sessionExpireDate),
                    }
                  )
                }}</span>
              </div>
              <NsButton
                :loading="loading.stopSessionSupport"
                :disabled="loading.stopSessionSupport"
                class="mg-top-sm mg-bottom-lg"
                kind="primary"
                :icon="Stop20"
                @click="stopSessionSupport"
              >
                {{ $t("settings_subscription.stop_session_support") }}
              </NsButton>
            </template>
⋮----
{{ $t("settings_subscription.session_id") }}
⋮----
>{{ session_id }}</NsCodeSnippet
⋮----
{{
                  $t("settings_subscription.paste_session_id_to_support_team")
                }}
⋮----
<span>{{
                  $t(
                    "settings_subscription.remote_support_in_progress_with_expiration",
                    {
                      time: formatExpiryDate(sessionExpireDate),
                    }
                  )
                }}</span>
⋮----
{{ $t("settings_subscription.stop_session_support") }}
⋮----
<template slot="title">{{
        $t("settings_subscription.remove_cluster_subscription_title")
      }}</template>
<template slot="content">
        <NsInlineNotification
          kind="warning"
          :title="
            $t(
              'settings_subscription.remove_cluster_subscription_irreversible_title'
            )
          "
          :description="
            $t('settings_subscription.remove_cluster_subscription_irreversible')
          "
          :showCloseButton="false"
        />
        <div class="mg-top-md">
          {{
            $t("settings_subscription.remove_cluster_subscription_description")
          }}
        </div>
      </template>
⋮----
{{
            $t("settings_subscription.remove_cluster_subscription_description")
          }}
⋮----
<template slot="secondary-button">{{ $t("common.cancel") }}</template>
<template slot="primary-button">{{ $t("common.remove") }}</template>
⋮----
<script>
import to from "await-to-js";
import {
  QueryParamService,
  UtilService,
  TaskService,
  IconService,
  PageTitleService,
  DateTimeService,
} from "@nethserver/ns8-ui-lib";
import { mapGetters } from "vuex";
import NotificationService from "@/mixins/notification";
import Play20 from "@carbon/icons-vue/es/play/20";
import Stop20 from "@carbon/icons-vue/es/stop/20";
export default {
  name: "SettingsSubscription",
  components: {},
  mixins: [
    TaskService,
    UtilService,
    IconService,
    QueryParamService,
    PageTitleService,
    NotificationService,
    DateTimeService,
  ],
  pageTitle() {
    return this.$t("settings_subscription.title");
  },
  data() {
    return {
      isShownRemoveSubcription: false,
      Play20,
      Stop20,
      enterprise_link:
        "<a href='https://my.nethesis.it' target=_blank'>my.nethesis.it</a>",
      subscription_link:
        "<a href='https://my.nethserver.com' target=_blank'>my.nethserver.com</a>",
      subscription: {
        auth_token: "",
        system_id: "",
        plan_name: { name: "", description: "" },
        expires: true,
        expire_date: "",
        status: "inactive",
        with_remote_support: false,
        error: "",
      },
      active: false,
      session_id: "",
      termsUrl: "",
      agreeTerms: false,
      sessionExpireDate: "",
      loading: {
        getSubscription: false,
        setSubscription: false,
        startSessionSupport: false,
        stopSessionSupport: false,
        migrateSubscription: false,
      },
      error: {
        status: "",
        auth_token: "",
        getSubscription: "",
        setSubscription: "",
        request_support: "",
        startSessionSupport: "",
        removeSubscription: "",
        unknown_token: "",
        agreeTerms: "",
        migrateSubscription: "",
      },
    };
  },
  computed: { ...mapGetters(["leaderNode"]) },
  created() {
    this.getSubscription();
    this.getSupportSession();
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.watchQueryData(vm);
      vm.queryParamsToDataForCore(vm, to.query);
    });
  },
  beforeRouteUpdate(to, from, next) {
    this.queryParamsToDataForCore(this, to.query);
    next();
  },
  methods: {
    formatExpiryDate(dateString) {
      const end = new Date(dateString);
      const diffMs = Math.max(0, end - Date.now());
      const days = Math.floor(diffMs / (1000 * 60 * 60 * 24));
      const hours = Math.floor(
        (diffMs % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
      );
      const dateTimeStr = new Intl.DateTimeFormat(navigator.language, {
        hour: "2-digit",
        minute: "2-digit",
        day: "2-digit",
        month: "2-digit",
        year: "numeric",
      }).format(end);
      const durationStr = new Intl.DurationFormat(navigator.language, {
        style: "long",
      }).format({ days, hours });
      return `${durationStr} (${dateTimeStr})`;
    },
    showRemoveSubcriptionModal() {
      this.isShownRemoveSubcription = true;
    },
    hideRemoveSubcriptionModal() {
      this.isShownRemoveSubcription = false;
    },
    async getSubscription() {
      this.error.getSubscription = "";
      this.loading.getSubscription = true;
      const taskAction = "get-subscription";
      this.$root.$once(
        taskAction + "-completed",
        this.getSubscriptionCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.getSubscription = this.getErrorMessage(err);
        this.loading.getSubscription = false;
        return;
      }
    },
    getSubscriptionCompleted(taskContext, taskResult) {
      const output = taskResult.output;
      this.termsUrl = output.terms_url;
      if (output.subscription == null) {
        this.subscription.status = "inactive";
        this.subscription.error = output.error;
        this.loading.getSubscription = false;
        return;
      }
      this.subscription = output.subscription;
      this.loading.getSubscription = false;
    },
    validateSetSubscription() {
      this.clearErrors(this);
      let isValidationOk = true;
      if (!this.subscription.auth_token) {
        this.error.auth_token = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("auth_token");
          isValidationOk = false;
        }
      } else {
        if (
          this.subscription.auth_token.length <= 32 ||
          this.subscription.auth_token.length > 128
        ) {
          this.error.auth_token = this.$t(
            "settings_subscription.must_be_32_chars_but_less_than_128"
          );
          if (isValidationOk) {
            this.focusElement("auth_token");
            isValidationOk = false;
          }
        }
      }
      if (!this.agreeTerms) {
        this.error.agreeTerms = this.$t("common.terms_required");
        isValidationOk = false;
      }
      return isValidationOk;
    },
    async setSubscription() {
      const isValidationOk = this.validateSetSubscription();
      if (!isValidationOk) {
        return;
      }
      this.error.setSubscription = "";
      this.error.auth_token = "";
      this.loading.setSubscription = true;
      const taskAction = "set-subscription";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.setSubscriptionCompleted
      );
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.setSubscriptionAborted
      );
      this.$root.$once(
        `${taskAction}-validation-failed-${eventId}`,
        this.setSubscriptionValidationFailed
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {
            subscription: { auth_token: this.subscription.auth_token },
          },
          extra: {
            title: this.$t("action." + taskAction),
            description: this.$t("common.processing"),
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.setSubscription = this.getErrorMessage(err);
        this.loading.setSubscription = false;
        return;
      }
    },
    setSubscriptionAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.setSubscription = this.$t("error.generic_error");
      this.loading.setSubscription = false;
    },
    setSubscriptionValidationFailed(validationErrors) {
      this.loading.setSubscription = false;
      this.subscription.status = "inactive";
      let focusAlreadySet = false;
      for (const validationError of validationErrors) {
        this.error.auth_token = this.getI18nStringWithFallback(
          "settings_subscription." + validationError.error
        );
        if (!focusAlreadySet) {
          this.focusElement("auth_token");
          focusAlreadySet = true;
        }
      }
    },
    setSubscriptionCompleted() {
      this.subscription.auth_token = "";
      this.loading.setSubscription = false;
      this.agreeTerms = false;
      this.getSubscription();
    },
    async migrateSubscription() {
      this.error.migrateSubscription = "";
      this.loading.migrateSubscription = true;
      const taskAction = "migrate-subscription";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.migrateSubscriptionCompleted
      );
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.migrateSubscriptionAborted
      );
      this.$root.$once(
        `${taskAction}-validation-failed-${eventId}`,
        this.migrateSubscriptionValidationFailed
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            description: this.$t("common.processing"),
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.migrateSubscription = this.getErrorMessage(err);
        this.loading.migrateSubscription = false;
        return;
      }
    },
    migrateSubscriptionCompleted() {
      this.loading.migrateSubscription = false;
      this.getSubscription();
    },
    migrateSubscriptionAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.migrateSubscription = this.$t(
        "settings_subscription.migration_failed"
      );
      this.loading.migrateSubscription = false;
    },
    migrateSubscriptionValidationFailed(validationErrors) {
      this.loading.migrateSubscription = false;
      this.error.migrateSubscription = this.getI18nStringWithFallback(
        "settings_subscription." + validationErrors[0].error,
        "error." + validationErrors[0].error
      );
    },
    async removeSubscription() {
      this.error.removeSubscription = "";
      this.loading.setSubscription = true;
      const taskAction = "set-subscription";
      this.$root.$once(
        taskAction + "-completed",
        this.removeSubscriptionCompleted
      );
      this.$root.$once(
        taskAction + "validation-failed",
        this.removeSubscriptionFailed
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {
            subscription: null,
          },
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: false,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.removeSubscription = this.getErrorMessage(err);
        this.loading.setSubscription = false;
        return;
      }
    },
    removeSubscriptionFailed(validationErrors) {
      this.loading.setSubscription = false;
      let focusAlreadySet = false;
      for (const validationError of validationErrors) {
        const param = validationError.parameter;
        this.error[param] = this.getI18nStringWithFallback(
          "settings_subscription." + validationError.error,
          "error." + validationError.error
        );
        if (!focusAlreadySet) {
          this.focusElement(param);
          focusAlreadySet = true;
        }
      }
    },
    removeSubscriptionCompleted() {
      this.stopSessionSupport();
      this.subscription.auth_token = "";
      this.loading.setSubscription = false;
      this.hideRemoveSubcriptionModal();
      this.getSubscription();
    },
    async getSupportSession() {
      this.error.getSupportSession = "";
      this.active = false;
      const taskAction = "get-support-session";
      this.$root.$once(
        taskAction + "-completed",
        this.getSupportSessionCompleted
      );
      const res = await to(
        this.createNodeTask(this.leaderNode.id, {
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.getSupportSession = this.getErrorMessage(err);
        this.loading.getSupportSession = false;
        return;
      }
    },
    getSupportSessionCompleted(taskContext, taskResult) {
      const output = taskResult.output;
      this.session_id = output.session_id;
      this.active = output.active;
      this.sessionExpireDate = output.expires_at;
    },
    async startSessionSupport() {
      this.error.request_support = "";
      this.loading.startSessionSupport = true;
      const taskAction = "start-support-session";
      this.$root.$once(
        taskAction + "-completed",
        this.startSessionSupportCompleted
      );
      this.$root.$once(
        taskAction + "validation-failed",
        this.startSessionSupportFailed
      );
      const res = await to(
        this.createNodeTask(this.leaderNode.id, {
          action: taskAction,
          data: {
            session_id: this.session_id,
          },
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.request_support = this.getErrorMessage(err);
        this.loading.startSessionSupport = false;
        return;
      }
    },
    startSessionSupportFailed(validationErrors) {
      this.loading.startSessionSupport = false;
      let focusAlreadySet = false;
      for (const validationError of validationErrors) {
        const param = validationError.parameter;
        this.error[param] = this.getI18nStringWithFallback(
          "settings_subscription." + validationError.error,
          "error." + validationError.error
        );
        if (!focusAlreadySet) {
          this.focusElement(param);
          focusAlreadySet = true;
        }
      }
    },
    startSessionSupportCompleted() {
      this.loading.startSessionSupport = false;
      this.getSupportSession();
    },
    async stopSessionSupport() {
      this.error.request_support = "";
      this.loading.stopSessionSupport = true;
      const taskAction = "stop-support-session";
      this.$root.$once(
        taskAction + "-completed",
        this.stopSessionSupportCompleted
      );
      this.$root.$once(
        taskAction + "validation-failed",
        this.stopSessionSupportFailed
      );
      const res = await to(
        this.createNodeTask(this.leaderNode.id, {
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.request_support = this.getErrorMessage(err);
        this.loading.stopSessionSupport = false;
        return;
      }
    },
    stopSessionSupportFailed(validationErrors) {
      this.loading.stopSessionSupport = false;
      let focusAlreadySet = false;
      for (const validationError of validationErrors) {
        const param = validationError.parameter;
        this.error[param] = this.getI18nStringWithFallback(
          "settings_subscription." + validationError.error,
          "error." + validationError.error
        );
        if (!focusAlreadySet) {
          this.focusElement(param);
          focusAlreadySet = true;
        }
      }
    },
    stopSessionSupportCompleted() {
      this.loading.stopSessionSupport = false;
      this.getSupportSession();
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
.subscription-details {
  display: grid;
  grid-template-columns: max-content 1fr;
  column-gap: 2rem;
  row-gap: 0.75rem;
  align-items: center;
  margin-bottom: 1rem;
}
.subscription-details .key-value-setting {
  display: contents;
}
.icon-and-text {
  justify-content: flex-start;
}
.helper-text {
  font-size: 0.75rem;
  line-height: 1.33333;
  letter-spacing: 0.32px;
  z-index: 0;
  width: 100%;
  margin-top: 0.25rem;
  color: #525252;
  opacity: 1;
}
</style>
</file>

<file path="core/ui/src/views/settings/SettingsSystemLogs.vue">
<template>
  <cv-grid fullWidth>
    <cv-row>
      <cv-column>
        <cv-breadcrumb
          aria-label="breadcrumb"
          :no-trailing-slash="true"
          class="breadcrumb"
        >
          <cv-breadcrumb-item>
            <cv-link to="/settings">{{ $t("settings.title") }}</cv-link>
          </cv-breadcrumb-item>
          <cv-breadcrumb-item>
            <span>{{ $t("system_logs.title") }}</span>
          </cv-breadcrumb-item>
        </cv-breadcrumb>
      </cv-column>
    </cv-row>
    <cv-row>
      <cv-column class="page-title">
        <h2>
          {{ $t("system_logs.title") }}
          <cv-interactive-tooltip
            alignment="center"
            direction="bottom"
            class="info"
          >
            <template slot="trigger">
              <Information16 />
            </template>
            <template slot="content">
              {{ $t("system_logs.loki.tooltip") }}
            </template>
          </cv-interactive-tooltip>
        </h2>
      </cv-column>
    </cv-row>
    <NsInlineNotification
      v-if="error.lokiInstances"
      kind="error"
      :title="$t('system_logs.loki.cannot_retrieve_loki_instances')"
      :description="error.lokiInstances"
      :showCloseButton="false"
    />
    <NsInlineNotification
      v-if="error.subscription"
      kind="error"
      :title="$t('error.cannot_retrieve_subscription_status')"
      :description="error.subscription"
      :showCloseButton="false"
    />
    <cv-row v-if="loading.lokiInstances && loading.subscription">
      <cv-column>
        <div
          class="card-grid grid-cols-1 md:grid-cols-2 2xl:grid-cols-3 3xl:grid-cols-4"
        >
          <NsTile :light="true" :icon="Catalog32">
            <cv-skeleton-text
              :paragraph="false"
              :line-count="1"
              heading
            ></cv-skeleton-text>
            <cv-skeleton-text
              :paragraph="true"
              :line-count="9"
            ></cv-skeleton-text>
          </NsTile>
        </div>
      </cv-column>
    </cv-row>
    <cv-row v-else-if="lokiInstances.length">
      <cv-column>
        <div
          class="card-grid grid-cols-1 md:grid-cols-2 2xl:grid-cols-3 3xl:grid-cols-4"
        >
          <LokiCard
            v-for="instance in lokiInstances"
            :key="instance.instance_id"
            :instanceId="instance.instance_id"
            :instanceLabel="instance.instance_label"
            :nodeId="instance.node_id"
            :nodeLabel="instance.node_label"
            :active="instance.active"
            :offline="instance.offline"
            :retentionDays="instance.retention_days"
            :activeFrom="instance.active_from"
            :activeTo="instance.active_to"
            :showStatusBadge="lokiInstances.length > 1"
            :cloudLogManagerForwarderStatus="instance.cloud_log_manager.status"
            :syslogForwarderStatus="instance.syslog.status"
          >
            <template #menu>
              <cv-overflow-menu
                :flip-menu="true"
                tip-position="top"
                tip-alignment="end"
                class="top-right-overflow-menu"
              >
                <cv-overflow-menu-item
                  v-if="instance.active"
                  @click="
                    isEditRetentionDialogOpen = true;
                    lokiToEdit = instance;
                    newRetention = instance.retention_days;
                  "
                  :disabled="instance.offline"
                >
                  <NsMenuItem
                    :icon="Edit20"
                    :label="$t('system_logs.loki.edit_retention')"
                  />
                </cv-overflow-menu-item>
                <cv-overflow-menu-item
                  @click="
                    isEditLabelDialogOpen = true;
                    lokiToEdit = instance;
                    newLabel = instance.instance_label;
                  "
                  :disabled="instance.offline"
                >
                  <NsMenuItem
                    :icon="Edit20"
                    :label="$t('system_logs.loki.edit_label')"
                  />
                </cv-overflow-menu-item>
                <cv-overflow-menu-item
                  v-if="instance.active"
                  @click="
                    isCloudLogManagerConfigureDialogOpen = true;
                    lokiToEdit = instance;
                  "
                >
                  <NsMenuItem
                    :icon="DocumentExport16"
                    :label="
                      $t(
                        'system_logs.loki.configure_cloud_log_manager_forwarder'
                      )
                    "
                  />
                </cv-overflow-menu-item>
                <cv-overflow-menu-item
                  v-if="instance.active"
                  @click="
                    isSyslogConfigureDialogOpen = true;
                    lokiToEdit = instance;
                  "
                >
                  <NsMenuItem
                    :icon="DocumentExport16"
                    :label="$t('system_logs.loki.configure_syslog_forwarder')"
                  />
                </cv-overflow-menu-item>
                <cv-overflow-menu-item
                  v-if="!instance.active"
                  danger
                  @click="
                    isUninstallDialogOpen = true;
                    lokiToUninstall = instance;
                  "
                  :disabled="instance.offline"
                >
                  <NsMenuItem
                    :icon="TrashCan20"
                    :label="$t('system_logs.loki.uninstall')"
                  />
                </cv-overflow-menu-item>
              </cv-overflow-menu>
            </template>
          </LokiCard>
        </div>
      </cv-column>
    </cv-row>
    <NsModal
      size="default"
      :visible="isEditRetentionDialogOpen"
      @modal-hidden="isEditRetentionDialogOpen = false"
      @primary-click="setLokiInstanceRetention"
      :primaryButtonDisabled="loading.setLokiInstanceRetention"
      :isLoading="loading.setLokiInstanceRetention"
    >
      <template slot="title">{{
        $t("system_logs.loki.edit_retention")
      }}</template>
      <template slot="content">
        <template v-if="lokiToEdit">
          <cv-form @submit.prevent="setLokiInstanceRetention">
            <cv-text-input
              :label="$t('system_logs.loki.retention')"
              v-model="newRetention"
              :helper-text="$t('system_logs.loki.days')"
              ref="newRetention"
              :invalid-message="error.newRetention"
              data-modal-primary-focus
            >
            </cv-text-input>
            <div v-if="error.setLokiInstanceRetention">
              <NsInlineNotification
                kind="error"
                :title="$t('action.set-retention')"
                :description="error.setLokiInstanceRetention"
                :showCloseButton="false"
              />
            </div>
          </cv-form>
        </template>
      </template>
      <template slot="secondary-button">{{ $t("common.cancel") }}</template>
      <template slot="primary-button">{{ $t("common.save") }}</template>
    </NsModal>
    <NsModal
      size="default"
      :visible="isEditLabelDialogOpen"
      @modal-hidden="isEditLabelDialogOpen = false"
      @primary-click="setLokiInstanceLabel"
      :primaryButtonDisabled="loading.setLokiInstanceLabel"
      :isLoading="loading.setLokiInstanceLabel"
    >
      <template slot="title">{{ $t("system_logs.loki.edit_label") }}</template>
      <template slot="content">
        <template v-if="lokiToEdit">
          <cv-form @submit.prevent="setLokiInstanceLabel">
            <cv-text-input
              :label="
                $t('system_logs.loki.loki_label') +
                ' (' +
                $t('common.optional') +
                ')'
              "
              v-model.trim="newLabel"
              maxlength="24"
              ref="newLabel"
              :invalid-message="error.newLabel"
              data-modal-primary-focus
            >
            </cv-text-input>
            <div v-if="error.setLokiInstanceLabel">
              <NsInlineNotification
                kind="error"
                :title="$t('action.set-name')"
                :description="error.setLokiInstanceLabel"
                :showCloseButton="false"
              />
            </div>
          </cv-form>
        </template>
      </template>
      <template slot="secondary-button">{{ $t("common.cancel") }}</template>
      <template slot="primary-button">{{ $t("common.save") }}</template>
    </NsModal>
    <NsModal
      kind="danger"
      size="default"
      :visible="isUninstallDialogOpen"
      :isLoading="loading.uninstallLokiInstance"
      @modal-hidden="isUninstallDialogOpen = false"
      @primary-click="uninstallLokiInstance"
      :primary-button-disabled="
        userInputUninstall !==
        (lokiToUninstall ? lokiToUninstall.instance_id : 0)
      "
    >
      <template slot="title">{{
        $tc("system_logs.loki.uninstall_instance", lokiToUninstall, {
          name: lokiToUninstall
            ? lokiToUninstall.instance_label
              ? lokiToUninstall.instance_label
              : lokiToUninstall.instance_id
            : undefined,
        })
      }}</template>
      <template slot="content">
        <template>
          <NsInlineNotification
            kind="warning"
            :title="$t('common.please_read_carefully')"
            :showCloseButton="false"
          />
          <div>
            {{
              $t("system_logs.loki.uninstall_description", {
                name: lokiToUninstall
                  ? lokiToUninstall.instance_label
                    ? lokiToUninstall.instance_label
                    : lokiToUninstall.instance_id
                  : undefined,
              })
            }}
          </div>
          <div class="mg-top-xlg">
            {{
              $t("system_logs.loki.type_to_confirm", {
                name: lokiToUninstall ? lokiToUninstall.instance_id : undefined,
              })
            }}
          </div>
          <cv-form @submit.prevent="uninstallLokiInstance">
            <NsTextInput
              v-model="userInputUninstall"
              :disabled="loading.uninstallLokiInstance"
              class="mg-bottom-md hide-label"
              ref="userInputUninstall"
            >
            </NsTextInput>
          </cv-form>
        </template>
      </template>
      <template slot="secondary-button">{{ $t("common.cancel") }}</template>
      <template slot="primary-button">{{
        $t("system_logs.loki.understood_uninstall")
      }}</template>
    </NsModal>
    <CloudLogManagerConfigureModal
      :isShown="isCloudLogManagerConfigureDialogOpen"
      :lokiToEdit="lokiToEdit"
      :configuration="cloudLogManagerConfiguration"
      :subscription="subscription"
      @hide="isCloudLogManagerConfigureDialogOpen = false"
      @configure="getClusterLokiInstances"
    />
    <SyslogConfigureModal
      :isShown="isSyslogConfigureDialogOpen"
      :lokiToEdit="lokiToEdit"
      :configuration="syslogConfiguration"
      @hide="isSyslogConfigureDialogOpen = false"
      @configure="getClusterLokiInstances"
    />
  </cv-grid>
</template>
⋮----
<cv-link to="/settings">{{ $t("settings.title") }}</cv-link>
⋮----
<span>{{ $t("system_logs.title") }}</span>
⋮----
{{ $t("system_logs.title") }}
⋮----
<template slot="trigger">
              <Information16 />
            </template>
<template slot="content">
              {{ $t("system_logs.loki.tooltip") }}
            </template>
⋮----
{{ $t("system_logs.loki.tooltip") }}
⋮----
<template #menu>
              <cv-overflow-menu
                :flip-menu="true"
                tip-position="top"
                tip-alignment="end"
                class="top-right-overflow-menu"
              >
                <cv-overflow-menu-item
                  v-if="instance.active"
                  @click="
                    isEditRetentionDialogOpen = true;
                    lokiToEdit = instance;
                    newRetention = instance.retention_days;
                  "
                  :disabled="instance.offline"
                >
                  <NsMenuItem
                    :icon="Edit20"
                    :label="$t('system_logs.loki.edit_retention')"
                  />
                </cv-overflow-menu-item>
                <cv-overflow-menu-item
                  @click="
                    isEditLabelDialogOpen = true;
                    lokiToEdit = instance;
                    newLabel = instance.instance_label;
                  "
                  :disabled="instance.offline"
                >
                  <NsMenuItem
                    :icon="Edit20"
                    :label="$t('system_logs.loki.edit_label')"
                  />
                </cv-overflow-menu-item>
                <cv-overflow-menu-item
                  v-if="instance.active"
                  @click="
                    isCloudLogManagerConfigureDialogOpen = true;
                    lokiToEdit = instance;
                  "
                >
                  <NsMenuItem
                    :icon="DocumentExport16"
                    :label="
                      $t(
                        'system_logs.loki.configure_cloud_log_manager_forwarder'
                      )
                    "
                  />
                </cv-overflow-menu-item>
                <cv-overflow-menu-item
                  v-if="instance.active"
                  @click="
                    isSyslogConfigureDialogOpen = true;
                    lokiToEdit = instance;
                  "
                >
                  <NsMenuItem
                    :icon="DocumentExport16"
                    :label="$t('system_logs.loki.configure_syslog_forwarder')"
                  />
                </cv-overflow-menu-item>
                <cv-overflow-menu-item
                  v-if="!instance.active"
                  danger
                  @click="
                    isUninstallDialogOpen = true;
                    lokiToUninstall = instance;
                  "
                  :disabled="instance.offline"
                >
                  <NsMenuItem
                    :icon="TrashCan20"
                    :label="$t('system_logs.loki.uninstall')"
                  />
                </cv-overflow-menu-item>
              </cv-overflow-menu>
            </template>
⋮----
<template slot="title">{{
        $t("system_logs.loki.edit_retention")
      }}</template>
<template slot="content">
        <template v-if="lokiToEdit">
          <cv-form @submit.prevent="setLokiInstanceRetention">
            <cv-text-input
              :label="$t('system_logs.loki.retention')"
              v-model="newRetention"
              :helper-text="$t('system_logs.loki.days')"
              ref="newRetention"
              :invalid-message="error.newRetention"
              data-modal-primary-focus
            >
            </cv-text-input>
            <div v-if="error.setLokiInstanceRetention">
              <NsInlineNotification
                kind="error"
                :title="$t('action.set-retention')"
                :description="error.setLokiInstanceRetention"
                :showCloseButton="false"
              />
            </div>
          </cv-form>
        </template>
      </template>
⋮----
<template v-if="lokiToEdit">
          <cv-form @submit.prevent="setLokiInstanceRetention">
            <cv-text-input
              :label="$t('system_logs.loki.retention')"
              v-model="newRetention"
              :helper-text="$t('system_logs.loki.days')"
              ref="newRetention"
              :invalid-message="error.newRetention"
              data-modal-primary-focus
            >
            </cv-text-input>
            <div v-if="error.setLokiInstanceRetention">
              <NsInlineNotification
                kind="error"
                :title="$t('action.set-retention')"
                :description="error.setLokiInstanceRetention"
                :showCloseButton="false"
              />
            </div>
          </cv-form>
        </template>
⋮----
<template slot="secondary-button">{{ $t("common.cancel") }}</template>
<template slot="primary-button">{{ $t("common.save") }}</template>
⋮----
<template slot="title">{{ $t("system_logs.loki.edit_label") }}</template>
<template slot="content">
        <template v-if="lokiToEdit">
          <cv-form @submit.prevent="setLokiInstanceLabel">
            <cv-text-input
              :label="
                $t('system_logs.loki.loki_label') +
                ' (' +
                $t('common.optional') +
                ')'
              "
              v-model.trim="newLabel"
              maxlength="24"
              ref="newLabel"
              :invalid-message="error.newLabel"
              data-modal-primary-focus
            >
            </cv-text-input>
            <div v-if="error.setLokiInstanceLabel">
              <NsInlineNotification
                kind="error"
                :title="$t('action.set-name')"
                :description="error.setLokiInstanceLabel"
                :showCloseButton="false"
              />
            </div>
          </cv-form>
        </template>
      </template>
⋮----
<template v-if="lokiToEdit">
          <cv-form @submit.prevent="setLokiInstanceLabel">
            <cv-text-input
              :label="
                $t('system_logs.loki.loki_label') +
                ' (' +
                $t('common.optional') +
                ')'
              "
              v-model.trim="newLabel"
              maxlength="24"
              ref="newLabel"
              :invalid-message="error.newLabel"
              data-modal-primary-focus
            >
            </cv-text-input>
            <div v-if="error.setLokiInstanceLabel">
              <NsInlineNotification
                kind="error"
                :title="$t('action.set-name')"
                :description="error.setLokiInstanceLabel"
                :showCloseButton="false"
              />
            </div>
          </cv-form>
        </template>
⋮----
<template slot="secondary-button">{{ $t("common.cancel") }}</template>
<template slot="primary-button">{{ $t("common.save") }}</template>
⋮----
<template slot="title">{{
        $tc("system_logs.loki.uninstall_instance", lokiToUninstall, {
          name: lokiToUninstall
            ? lokiToUninstall.instance_label
              ? lokiToUninstall.instance_label
              : lokiToUninstall.instance_id
            : undefined,
        })
      }}</template>
<template slot="content">
        <template>
          <NsInlineNotification
            kind="warning"
            :title="$t('common.please_read_carefully')"
            :showCloseButton="false"
          />
          <div>
            {{
              $t("system_logs.loki.uninstall_description", {
                name: lokiToUninstall
                  ? lokiToUninstall.instance_label
                    ? lokiToUninstall.instance_label
                    : lokiToUninstall.instance_id
                  : undefined,
              })
            }}
          </div>
          <div class="mg-top-xlg">
            {{
              $t("system_logs.loki.type_to_confirm", {
                name: lokiToUninstall ? lokiToUninstall.instance_id : undefined,
              })
            }}
          </div>
          <cv-form @submit.prevent="uninstallLokiInstance">
            <NsTextInput
              v-model="userInputUninstall"
              :disabled="loading.uninstallLokiInstance"
              class="mg-bottom-md hide-label"
              ref="userInputUninstall"
            >
            </NsTextInput>
          </cv-form>
        </template>
      </template>
⋮----
<template>
          <NsInlineNotification
            kind="warning"
            :title="$t('common.please_read_carefully')"
            :showCloseButton="false"
          />
          <div>
            {{
              $t("system_logs.loki.uninstall_description", {
                name: lokiToUninstall
                  ? lokiToUninstall.instance_label
                    ? lokiToUninstall.instance_label
                    : lokiToUninstall.instance_id
                  : undefined,
              })
            }}
          </div>
          <div class="mg-top-xlg">
            {{
              $t("system_logs.loki.type_to_confirm", {
                name: lokiToUninstall ? lokiToUninstall.instance_id : undefined,
              })
            }}
          </div>
          <cv-form @submit.prevent="uninstallLokiInstance">
            <NsTextInput
              v-model="userInputUninstall"
              :disabled="loading.uninstallLokiInstance"
              class="mg-bottom-md hide-label"
              ref="userInputUninstall"
            >
            </NsTextInput>
          </cv-form>
        </template>
⋮----
{{
              $t("system_logs.loki.uninstall_description", {
                name: lokiToUninstall
                  ? lokiToUninstall.instance_label
                    ? lokiToUninstall.instance_label
                    : lokiToUninstall.instance_id
                  : undefined,
              })
            }}
⋮----
{{
              $t("system_logs.loki.type_to_confirm", {
                name: lokiToUninstall ? lokiToUninstall.instance_id : undefined,
              })
            }}
⋮----
<template slot="secondary-button">{{ $t("common.cancel") }}</template>
<template slot="primary-button">{{
        $t("system_logs.loki.understood_uninstall")
      }}</template>
⋮----
<script>
import {
  QueryParamService,
  UtilService,
  IconService,
  PageTitleService,
  TaskService,
} from "@nethserver/ns8-ui-lib";
import to from "await-to-js";
import LokiCard from "@/components/settings/LokiCard";
import Information16 from "@carbon/icons-vue/es/information/16";
import DocumentExport16 from "@carbon/icons-vue/es/document--export/16";
import SyslogConfigureModal from "@/components/settings/SyslogConfigureModal.vue";
import CloudLogManagerConfigureModal from "@/components/settings/CloudLogManagerConfigureModal.vue";
export default {
  name: "SettingsSystemLogs",
  components: {
    LokiCard,
    Information16,
    SyslogConfigureModal,
    CloudLogManagerConfigureModal,
  },
  mixins: [
    TaskService,
    UtilService,
    IconService,
    QueryParamService,
    PageTitleService,
  ],
  pageTitle() {
    return this.$t("system_logs.title");
  },
  data() {
    return {
      DocumentExport16,
      q: {},
      lokiInstances: [],
      cloudLogManagerConfiguration: {},
      syslogConfiguration: {},
      lokiToEdit: {},
      subscription: false,
      isEditLabelDialogOpen: false,
      isEditRetentionDialogOpen: false,
      isSyslogConfigureDialogOpen: false,
      isCloudLogManagerConfigureDialogOpen: false,
      isUninstallDialogOpen: false,
      lokiToUninstall: null,
      userInputUninstall: "",
      newRetention: null,
      newLabel: "",
      loading: {
        lokiInstances: false,
        subscription: false,
        setLokiInstanceRetention: false,
        setLokiInstanceLabel: false,
        uninstallLokiInstance: false,
      },
      error: {
        lokiInstances: "",
        subscription: "",
        setLokiInstanceRetention: "",
        setLokiInstanceLabel: "",
        uninstallLokiInstance: "",
        newRetention: "",
        newLabel: "",
      },
    };
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.watchQueryData(vm);
      vm.queryParamsToDataForCore(vm, to.query);
    });
  },
  beforeRouteUpdate(to, from, next) {
    this.queryParamsToDataForCore(this, to.query);
    next();
  },
  created() {
    this.getClusterLokiInstances();
    this.getSubscription();
  },
  methods: {
    async getClusterLokiInstances() {
      this.loading.lokiInstances = true;
      this.error.lokiInstances = "";
      const taskAction = "list-loki-instances";
      this.$root.$once(
        taskAction + "-aborted",
        this.getClusterLokiInstancesAborted
      );
      this.$root.$once(
        taskAction + "-completed",
        this.getClusterLokiInstancesCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            isNotificationHidden: true,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.lokiInstances = this.getErrorMessage(err);
        return;
      }
    },
    getClusterLokiInstancesAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.lokiInstances = this.$t("error.generic_error");
      this.loading.lokiInstances = false;
    },
    getClusterLokiInstancesCompleted(taskContext, taskResult) {
      this.lokiInstances = taskResult.output.instances;
      for (const instance of this.lokiInstances) {
        if (instance.active) {
          this.cloudLogManagerConfiguration = instance.cloud_log_manager;
          this.syslogConfiguration = instance.syslog;
        }
      }
      this.loading.lokiInstances = false;
    },
    validateLokiInstanceRetention() {
      this.clearErrors(this);
      let isValidationOk = true;
      if (!this.newRetention) {
        this.error.newRetention = this.$t("common.required");
        isValidationOk = false;
      }
      if (this.newRetention && isNaN(this.newRetention)) {
        this.error.newRetention = this.$t("system_logs.loki.valid_number");
        isValidationOk = false;
      }
      if (this.newRetention && this.newRetention <= 0) {
        this.error.newRetention = this.$t("system_logs.loki.greater_than_0");
        isValidationOk = false;
      }
      return isValidationOk;
    },
    async setLokiInstanceRetention() {
      const isValidationOk = this.validateLokiInstanceRetention();
      if (!isValidationOk) {
        return;
      }
      this.error.setLokiInstanceRetention = "";
      this.loading.setLokiInstanceRetention = true;
      const taskAction = "configure-module";
      this.$root.$once(
        taskAction + "-aborted",
        this.setLokiInstanceRetentionAborted
      );
      this.$root.$once(
        taskAction + "-completed",
        this.setLokiInstanceRetentionCompleted
      );
      const res = await to(
        this.createModuleTaskForApp(this.lokiToEdit.instance_id, {
          action: taskAction,
          data: {
            retention_days: parseInt(this.newRetention),
          },
          extra: {
            isNotificationHidden: true,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.setLokiInstanceRetention = this.getErrorMessage(err);
        return;
      }
    },
    setLokiInstanceRetentionAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.setLokiInstanceRetention = this.$t("error.generic_error");
      this.loading.setLokiInstanceRetention = false;
    },
    setLokiInstanceRetentionCompleted() {
      this.loading.setLokiInstanceRetention = false;
      this.isEditRetentionDialogOpen = false;
      this.newRetention = null;
      this.getClusterLokiInstances();
    },
    async setLokiInstanceLabel() {
      this.error.setLokiInstanceLabel = "";
      this.loading.setLokiInstanceLabel = true;
      const taskAction = "set-name";
      this.$root.$once(
        taskAction + "-aborted",
        this.setLokiInstanceLabelAborted
      );
      this.$root.$once(
        taskAction + "-completed",
        this.setLokiInstanceLabelCompleted
      );
      const res = await to(
        this.createModuleTaskForApp(this.lokiToEdit.instance_id, {
          action: taskAction,
          data: {
            name: this.newLabel,
          },
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.setLokiInstanceLabel = this.getErrorMessage(err);
        this.loading.setLokiInstanceLabel = false;
        return;
      }
    },
    setLokiInstanceLabelAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.setLokiInstanceLabel = this.$t("error.generic_error");
      this.loading.setLokiInstanceLabel = false;
    },
    setLokiInstanceLabelCompleted() {
      this.loading.setLokiInstanceLabel = false;
      this.isEditLabelDialogOpen = false;
      this.newLabel = "";
      this.getClusterLokiInstances();
    },
    async uninstallLokiInstance() {
      this.error.uninstallLokiInstance = "";
      const taskAction = "remove-module";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.uninstallLokiInstanceAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.uninstallLokiInstanceCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {
            module_id: this.lokiToUninstall.instance_id,
            preserve_data: false,
          },
          extra: {
            title: this.$t("software_center.instance_uninstallation", {
              instance: this.lokiToUninstall.instance_label
                ? this.lokiToUninstall.instance_label
                : this.lokiToUninstall.instance_id,
            }),
            description: this.$t("software_center.uninstalling"),
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.uninstallLokiInstance = this.getErrorMessage(err);
        return;
      }
      this.isUninstallDialogOpen = false;
    },
    uninstallLokiInstanceAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.uninstallLokiInstance = this.$t("error.generic_error");
    },
    uninstallLokiInstanceCompleted() {
      this.getClusterLokiInstances();
    },
    async getSubscription() {
      this.loading.subscription = true;
      this.error.subscription = "";
      const taskAction = "get-subscription";
      this.$root.$once(taskAction + "-aborted", this.getSubscriptionAborted);
      this.$root.$once(
        taskAction + "-completed",
        this.getSubscriptionCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.subscription = this.getErrorMessage(err);
        return;
      }
    },
    getSubscriptionAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.subscription = this.$t("error.generic_error");
      this.loading.subscription = false;
    },
    getSubscriptionCompleted(taskContext, taskResult) {
      const output = taskResult.output;
      if (output.subscription != null) {
        this.subscription = true;
      }
      this.loading.subscription = false;
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../../styles/carbon-utils";
</style>
</file>

<file path="core/ui/src/views/settings/SettingsTlsCertificates.vue">
<template>
  <div>
    <cv-grid fullWidth>
      <cv-row>
        <cv-column>
          <cv-breadcrumb
            aria-label="breadcrumb"
            :no-trailing-slash="true"
            class="breadcrumb"
          >
            <cv-breadcrumb-item>
              <cv-link to="/settings">{{ $t("settings.title") }}</cv-link>
            </cv-breadcrumb-item>
            <cv-breadcrumb-item>
              <span>{{ $t("settings_tls_certificates.title") }}</span>
            </cv-breadcrumb-item>
          </cv-breadcrumb>
        </cv-column>
      </cv-row>
      <cv-row>
        <cv-column class="subpage-title">
          <h3>{{ $t("settings_tls_certificates.title") }}</h3>
        </cv-column>
      </cv-row>
      <cv-row>
        <cv-column>
          <NsInlineNotification
            kind="warning"
            :title="$t('common.use_landscape_mode')"
            :description="$t('common.use_landscape_mode_description')"
            class="landscape-warning"
          />
        </cv-column>
      </cv-row>
    </cv-grid>
    <cv-grid fullWidth>
      <cv-row>
        <cv-column>
          <NsTabs
            :container="false"
            :aria-label="$t('common.tab_navigation')"
            :noDefaultToFirst="true"
            @tab-selected="tabSelected"
          >
            <cv-tab
              id="tab-1"
              :label="$t('settings_tls_certificates.certificates')"
              :selected="q.view === 'certificates'"
            >
              <cv-row>
                <cv-column>
                  <TlsCertificatesPanel
                    :traefikInstances="traefikInstances"
                    :internalNodes="internalNodes"
                    :isLoadingInstances="loading.listInstalledModules"
                    :instancesError="error.listInstalledModules"
                    :selectedNodeId.sync="q.selectedNodeId"
                  />
                </cv-column>
              </cv-row>
            </cv-tab>
            <cv-tab
              id="tab-2"
              :label="$t('settings_acme_servers.acme_settings')"
              :selected="q.view === 'acme'"
            >
              <cv-row>
                <cv-column>
                  <AcmeSettingsPanel
                    v-if="acmeTabVisited"
                    :traefikInstances="traefikInstances"
                    :isLoadingInstances="loading.listInstalledModules"
                    :instancesError="error.listInstalledModules"
                  />
                </cv-column>
              </cv-row>
            </cv-tab>
          </NsTabs>
        </cv-column>
      </cv-row>
    </cv-grid>
  </div>
</template>
⋮----
<cv-link to="/settings">{{ $t("settings.title") }}</cv-link>
⋮----
<span>{{ $t("settings_tls_certificates.title") }}</span>
⋮----
<h3>{{ $t("settings_tls_certificates.title") }}</h3>
⋮----
<script>
import to from "await-to-js";
import {
  QueryParamService,
  UtilService,
  TaskService,
  PageTitleService,
} from "@nethserver/ns8-ui-lib";
import { mapState } from "vuex";
import TlsCertificatesPanel from "@/components/settings/TlsCertificatesPanel.vue";
import AcmeSettingsPanel from "@/components/settings/AcmeSettingsPanel.vue";
const TAB_VIEWS = ["certificates", "acme"];
export default {
  name: "SettingsTlsCertificates",
  components: {
    TlsCertificatesPanel,
    AcmeSettingsPanel,
  },
  mixins: [TaskService, UtilService, QueryParamService, PageTitleService],
  pageTitle() {
    return this.$t("settings_tls_certificates.title");
  },
  data() {
    return {
      q: {
        view: "",
        selectedNodeId: "",
      },
      // mount once and keep alive: a v-if would re-run the task chain
      acmeTabVisited: false,
      internalNodes: [],
      traefikInstances: [],
      taskListeners: [],
      loading: {
        listInstalledModules: false,
      },
      error: {
        listInstalledModules: "",
      },
    };
  },
  computed: {
    ...mapState(["clusterNodes", "isWebsocketConnected"]),
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.watchQueryData(vm);
      vm.queryParamsToDataForCore(vm, to.query);
      vm.normalizeView();
    });
  },
  beforeRouteUpdate(to, from, next) {
    this.queryParamsToDataForCore(this, to.query);
    if (typeof to.query.view === "undefined") {
      this.q.view = TAB_VIEWS[0];
    }
    this.normalizeView();
    next();
  },
  watch: {
    isWebsocketConnected: function (isConnected) {
      if (isConnected) {
        this.listInstalledModules();
      }
    },
    "q.view": function (view) {
      if (view === "acme") {
        this.acmeTabVisited = true;
      }
    },
  },
  created() {
    this.listInstalledModules();
  },
  beforeDestroy() {
    this.clearTaskListeners();
  },
  methods: {
    registerTaskListener(eventName, handler) {
      this.$root.$once(eventName, handler);
      this.taskListeners.push([eventName, handler]);
    },
    clearTaskListeners() {
      for (const [eventName, handler] of this.taskListeners) {
        this.$root.$off(eventName, handler);
      }
      this.taskListeners = [];
    },
    normalizeView() {
      if (!TAB_VIEWS.includes(this.q.view)) {
        this.q.view = TAB_VIEWS[0];
      }
    },
    async listInstalledModules() {
      this.clearTaskListeners();
      this.loading.listInstalledModules = true;
      this.error.listInstalledModules = "";
      const taskAction = "list-installed-modules";
      const eventId = this.getUuid();
      this.registerTaskListener(
        `${taskAction}-aborted-${eventId}`,
        this.listInstalledModulesAborted
      );
      this.registerTaskListener(
        `${taskAction}-completed-${eventId}`,
        this.listInstalledModulesCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        const errMessage = this.getErrorMessage(err);
        this.error.listInstalledModules = errMessage;
        this.loading.listInstalledModules = false;
        return;
      }
    },
    listInstalledModulesAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.listInstalledModules = this.$t("error.generic_error");
      this.loading.listInstalledModules = false;
    },
    listInstalledModulesCompleted(taskContext, taskResult) {
      let nodes = [];
      for (let node of this.clusterNodes) {
        nodes.push({
          name: node.id.toString(),
          label: this.getShortNodeLabel(node),
          value: node.id.toString(),
        });
      }
      let traefikInstances = [];
      for (let instanceList of Object.values(taskResult.output)) {
        for (let instance of instanceList) {
          if (instance.id.startsWith("traefik")) {
            traefikInstances.push(instance);
            const node = nodes.find((node) => node.value === instance.node);
            if (node) {
              node.label += ` (${instance.id})`;
              node.traefikInstance = instance.id;
              instance.node_id = node.name;
            }
          }
        }
      }
      this.internalNodes = nodes;
      this.traefikInstances = traefikInstances;
      this.loading.listInstalledModules = false;
      this.$nextTick(() => {
        if (!this.q.selectedNodeId) {
          this.q.selectedNodeId = "any";
        } else {
          const nodeId = this.q.selectedNodeId;
          this.q.selectedNodeId = "";
          this.$nextTick(() => {
            this.q.selectedNodeId = nodeId;
          });
        }
      });
    },
    tabSelected(tabNum) {
      if (tabNum == 0) {
        this.q.view = "certificates";
      } else if (tabNum == 1) {
        this.q.view = "acme";
      }
    },
  },
};
</script>
</file>

<file path="core/ui/src/views/About.vue">
<template>
  <div class="about">
    <div class="bx--grid bx--grid--full-width">
      <div class="bx--row">
        <div class="bx--col-lg-16 page-title">
          <h2>{{ $t("about.title") }}</h2>
        </div>
      </div>
    </div>
    <div class="bx--grid bx--grid--full-width">
      <cv-tile kind="standard" :light="true" class="about-content">
        <div class="logo">
          <img
            :src="require('@/assets/logo.png')"
            :alt="this.$root.config.PRODUCT_NAME + ' logo'"
          />
        </div>
        <div>
          <cv-link
            v-if="$root.config.PRODUCT_URL"
            :href="$root.config.PRODUCT_URL"
            target="_blank"
          >
            <h4 class="bx--col-lg-16 mg-bottom-md">
              {{ $root.config.PRODUCT_NAME }}
            </h4>
          </cv-link>
        </div>
        <div>
          <div class="bx--col-lg-16 mg-bottom-xlg">
            <template v-if="$root.config.COMPANY_NAME">
              {{ $t("about.by_company") }}
              <cv-link
                v-if="$root.config.COMPANY_URL"
                :href="$root.config.COMPANY_URL"
                target="_blank"
              >
                {{ $root.config.COMPANY_NAME }}
              </cv-link>
              <span v-else>
                {{ $root.config.COMPANY_NAME }}
              </span>
            </template>
          </div>
        </div>
        <div>
          <span v-if="$root.config.DOCS_URL" class="docs-button">
            <a
              :href="$root.config.DOCS_URL"
              target="_blank"
              class="external-link-button"
            >
              <NsButton kind="tertiary" :icon="Launch20">
                {{ $t("about.documentation") }}
              </NsButton>
            </a>
          </span>
          <div v-if="$root.config.HELPDESK_URL" class="helpdesk-button">
            <a
              :href="$root.config.HELPDESK_URL"
              target="_blank"
              class="external-link-button"
            >
              <NsButton kind="tertiary" :icon="Launch20">
                {{ $t("about.helpdesk") }}
              </NsButton>
            </a>
          </div>
        </div>
        <div>
          <div class="bx--col-lg-16 mg-bottom-xlg icons-8">
            {{ $t("about.animated_icons_by") }}
            <cv-link href="https://icons8.com/" target="_blank">
              icons8
            </cv-link>
          </div>
        </div>
      </cv-tile>
    </div>
  </div>
</template>
⋮----
<h2>{{ $t("about.title") }}</h2>
⋮----
{{ $root.config.PRODUCT_NAME }}
⋮----
<template v-if="$root.config.COMPANY_NAME">
              {{ $t("about.by_company") }}
              <cv-link
                v-if="$root.config.COMPANY_URL"
                :href="$root.config.COMPANY_URL"
                target="_blank"
              >
                {{ $root.config.COMPANY_NAME }}
              </cv-link>
              <span v-else>
                {{ $root.config.COMPANY_NAME }}
              </span>
            </template>
⋮----
{{ $t("about.by_company") }}
⋮----
{{ $root.config.COMPANY_NAME }}
⋮----
{{ $root.config.COMPANY_NAME }}
⋮----
{{ $t("about.documentation") }}
⋮----
{{ $t("about.helpdesk") }}
⋮----
{{ $t("about.animated_icons_by") }}
⋮----
<script>
import {
  QueryParamService,
  UtilService,
  IconService,
  PageTitleService,
} from "@nethserver/ns8-ui-lib";
export default {
  name: "About",
  mixins: [UtilService, IconService, QueryParamService, PageTitleService],
  pageTitle() {
    return this.$t("settings.title");
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.watchQueryData(vm);
      vm.queryParamsToDataForCore(vm, to.query);
    });
  },
  beforeRouteUpdate(to, from, next) {
    this.queryParamsToDataForCore(this, to.query);
    next();
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../styles/carbon-utils";
.logo {
  margin-top: $spacing-07 !important;
  margin-bottom: $spacing-07 !important;
}
.about-content {
  text-align: center;
}
.docs-button {
  display: inline-block;
  margin-left: $spacing-03;
  margin-right: $spacing-03;
  margin-bottom: $spacing-05;
}
.helpdesk-button {
  display: inline-block;
  margin-left: $spacing-03;
  margin-right: $spacing-03;
  margin-bottom: $spacing-07;
}
.icons-8 {
  font-size: 80%;
}
</style>
⋮----
<style lang="scss">
@import "../styles/carbon-utils";
.icons-8 .bx--link {
  font-size: inherit;
}
</style>
</file>

<file path="core/ui/src/views/Applications.vue">
<template>
  <div class="apps">
    <div v-if="migratingApps.includes(appId)" class="migrating-app">
      <h2>{{ appId }}</h2>
      <NsInlineNotification
        kind="info"
        :title="$t('software_center.migrating_app_title')"
        :description="
          $t('software_center.migrating_app_description', {
            name: appId,
          })
        "
        :showCloseButton="false"
      />
    </div>
    <iframe
      v-else
      id="app-frame"
      class="iframe-embedded"
      :src="iframePath"
    ></iframe>
  </div>
</template>
⋮----
<h2>{{ appId }}</h2>
⋮----
<script>
import { mapState } from "vuex";
export default {
  name: "Applications",
  computed: {
    ...mapState(["migratingApps"]),
    appId() {
      return this.$route.params.appId;
    },
    iframePath() {
      return `apps/${this.appId}/index.html`;
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../styles/carbon-utils";
#app-frame {
  width: calc(100% - #{$side-menu-collapsed-width});
  height: calc(100% - 3rem);
}
@media (max-width: $breakpoint-large) {
  #app-frame {
    width: 100%;
  }
}
.iframe-embedded {
  position: absolute;
  border: none;
  z-index: 1;
}
.migrating-app {
  padding: 2rem;
}
</style>
</file>

<file path="core/ui/src/views/ApplicationsCenter.vue">
<template>
  <div>
    <cv-grid fullWidth>
      <cv-row>
        <cv-column :md="4" :xlg="10" class="page-title">
          <h2>
            {{ $t("applications.title") }}
            <cv-interactive-tooltip
              alignment="start"
              direction="right"
              class="info"
            >
              <template slot="content">
                <i18n path="applications.title_tooltip" tag="p">
                  <template v-slot:software>
                    <cv-link @click="goToSoftwareCenter">
                      {{ $t("software_center.title") }}
                    </cv-link>
                  </template>
                </i18n>
              </template>
            </cv-interactive-tooltip>
          </h2>
        </cv-column>
        <cv-column :md="4" :xlg="6">
          <div class="page-toolbar">
            <NsButton
              kind="tertiary"
              size="field"
              :icon="ArrowRight20"
              @click="showSoftwareCenterCoreApps()"
              class="page-toolbar-item"
              >{{ $t("software_center.go_to_core_applications") }}</NsButton
            >
            <NsIconMenu
              :flipMenu="true"
              tipPosition="top"
              tipAlignment="end"
              class="page-toolbar-item"
            >
              <cv-overflow-menu-item
                v-if="subscriptionIsActive"
                @click="toggleAutomaticUpdates()"
              >
                <NsMenuItem
                  :icon="applyUpdatesIsActive ? PauseOutline20 : PlayOutline20"
                  :label="
                    applyUpdatesIsActive
                      ? $t('software_center.disable_automatic_updates')
                      : $t('software_center.enable_automatic_updates')
                  "
                />
              </cv-overflow-menu-item>
              <cv-overflow-menu-item @click="goToSoftwareCenter()">
                <NsMenuItem
                  :icon="ArrowRight20"
                  :label="$t('applications.go_to_software_center')"
                />
              </cv-overflow-menu-item>
            </NsIconMenu>
          </div>
        </cv-column>
      </cv-row>
      <cv-row v-if="error.listModules">
        <cv-column>
          <NsInlineNotification
            kind="error"
            :title="$t('action.list-modules')"
            :description="error.listModules"
            :showCloseButton="false"
          />
        </cv-column>
      </cv-row>
      <cv-row v-if="subscriptionIsActive && !applyUpdatesIsActive">
        <cv-column>
          <NsInlineNotification
            kind="warning"
            :title="$t('software_center.automatic_updates_disabled_title')"
            :description="
              $t('software_center.automatic_updates_disabled_description')
            "
            :actionLabel="$t('software_center.enable_automatic_updates')"
            @action="toggleAutomaticUpdates"
            :showCloseButton="false"
          />
        </cv-column>
      </cv-row>
      <cv-row v-if="error.addFavorite">
        <cv-column>
          <NsInlineNotification
            kind="error"
            :title="$t('action.add-favorite')"
            :description="error.addFavorite"
            :showCloseButton="false"
          />
        </cv-column>
      </cv-row>
      <cv-row v-if="error.removeFavorite">
        <cv-column>
          <NsInlineNotification
            kind="error"
            :title="$t('action.remove-favorite')"
            :description="error.removeFavorite"
            :showCloseButton="false"
          />
        </cv-column>
      </cv-row>
    </cv-grid>
    <cv-grid fullWidth>
      <cv-row>
        <cv-column>
          <cv-tile light>
            <div class="data-table-filters">
              <cv-search
                :label="$t('common.search')"
                :placeholder="$t('applications.filter_applications')"
                :clear-aria-label="$t('common.clear_search')"
                v-model="filter.text"
                :disabled="loading.listModules"
                size="large"
                ref="tableSearch"
                class="self-end search-limited-width"
              >
              </cv-search>
              <NsComboBox
                v-model="filter.moduleType"
                :label="$t('common.choose')"
                :title="$t('applications.type')"
                :auto-filter="true"
                :auto-highlight="true"
                :options="moduleTypeOptions"
                :disabled="loading.listModules"
              >
              </NsComboBox>
              <NsComboBox
                v-model="q.selectedNodeId"
                :label="$t('common.choose')"
                :title="$t('common.node')"
                :auto-filter="true"
                :auto-highlight="true"
                :options="nodesTypeOptions"
                :disabled="loading.listModules"
              >
              </NsComboBox>
              <cv-link @click="clearFilters()" class="self-end mb-3 shrink-0"
                >{{ $t("common.clear_filters") }}
              </cv-link>
            </div>
            <NsDataTable
              :allRows="filteredModules"
              :columns="i18nTableColumns"
              :rawColumns="tableColumns"
              :sortable="true"
              :pageSizes="[10, 25, 50, 100]"
              :isSearchable="false"
              :overflow-menu="true"
              :searchPlaceholder="$t('common.search')"
              :searchClearLabel="$t('common.clear_search')"
              :noSearchResultsLabel="$t('common.no_search_results')"
              :noSearchResultsDescription="
                $t('common.no_search_results_description')
              "
              :isLoading="loading.listModules"
              :skeletonRows="5"
              :isErrorShown="!!error.listModules"
              :errorTitle="$t('action.list-modules')"
              :errorDescription="error.listModules"
              :itemsPerPageLabel="$t('pagination.items_per_page')"
              :rangeOfTotalItemsLabel="$t('pagination.range_of_total_items')"
              :ofTotalPagesLabel="$t('pagination.of_total_pages')"
              :backwardText="$t('pagination.previous_page')"
              :forwardText="$t('pagination.next_page')"
              :pageNumberLabel="$t('pagination.page_number')"
              @updatePage="tablePage = $event"
            >
              <template slot="empty-state">
                <template v-if="hasActiveFilters && modules.length">
                  <NsEmptyState
                    :title="$t('common.no_search_results')"
                    key="no-results-empty-state"
                  >
                    <template #description>
                      <div class="flex flex-col items-center text-center gap-2">
                        <p>
                          {{ $t("common.no_search_results_description") }}
                        </p>
                        <NsButton
                          kind="ghost"
                          size="field"
                          @click="clearFilters()"
                          >{{ $t("common.clear_filters") }}
                        </NsButton>
                      </div>
                    </template>
                  </NsEmptyState>
                </template>
                <template v-else>
                  <NsEmptyState :title="$t('applications.no_application')">
                    <template #pictogram>
                      <AppsPictogram />
                    </template>
                    <template #description>
                      <div>
                        {{ $t("applications.no_application_description") }}
                      </div>
                      <NsButton
                        kind="primary"
                        class="empty-state-button"
                        :icon="ArrowRight20"
                        @click="goToSoftwareCenter"
                        :disabled="loading.listModules"
                        >{{ $t("applications.go_to_software_center") }}
                      </NsButton>
                    </template>
                  </NsEmptyState>
                </template>
              </template>
              <template slot="data">
                <cv-data-table-row
                  v-for="(row, rowIndex) in tablePage"
                  :key="`${rowIndex}`"
                  :value="`${rowIndex}`"
                >
                  <cv-data-table-cell>
                    <span>
                      <a class="app-name" @click="openInstance(row)">
                        {{
                          row.ui_name
                            ? row.ui_name + " (" + row.id + ")"
                            : row.id
                        }}
                      </a>
                    </span>
                    <cv-interactive-tooltip
                      v-if="row.ui_note"
                      alignment="start"
                      direction="right"
                      class="info margin-left-sm"
                    >
                      <template slot="content">
                        <span class="underline-tooltip">
                          {{ row.ui_note }}
                        </span>
                      </template>
                    </cv-interactive-tooltip>
                  </cv-data-table-cell>
                  <cv-data-table-cell>
                    <a @click="showAppInfo(row.appInfoData)">
                      <img
                        :src="
                          row.logo
                            ? row.logo
                            : require('@/assets/module_default_logo.png')
                        "
                        :alt="row.name + ' logo'"
                        class="module-logo"
                      />
                      <span class="app-name">{{ row.module }}</span>
                    </a>
                  </cv-data-table-cell>
                  <cv-data-table-cell>
                    <span>{{
                      row.node_ui_name
                        ? row.node_ui_name +
                          " (" +
                          $t("common.node") +
                          " " +
                          row.node +
                          ")"
                        : $t("common.node") + " " + row.node
                    }}</span>
                  </cv-data-table-cell>
                  <cv-data-table-cell>
                    <div class="flex items-center">
                      <span>{{ row.version }}</span>
                      <cv-tag
                        v-if="row.update"
                        class="mg-left-sm"
                        kind="green"
                        :label="$t('applications.update_available')"
                      />
                      <cv-tag
                        v-if="isUpdatesDisabledShown(row)"
                        class="mg-left-sm"
                        kind="high-contrast"
                        :label="$t('software_center.updates_disabled')"
                      />
                    </div>
                  </cv-data-table-cell>
                  <cv-data-table-cell class="table-overflow-menu-cell">
                    <cv-overflow-menu flip-menu class="table-overflow-menu">
                      <cv-overflow-menu-item
                        primary-focus
                        @click="openInstance(row)"
                      >
                        <NsMenuItem
                          :icon="Application20"
                          :label="$t('applications.open')"
                        />
                      </cv-overflow-menu-item>
                      <cv-overflow-menu-item
                        @click="showSetInstanceLabelModal(row)"
                      >
                        <NsMenuItem
                          :icon="Edit20"
                          :label="$t('applications.edit_label')"
                        />
                      </cv-overflow-menu-item>
                      <cv-overflow-menu-item @click="showAddNoteModal(row)">
                        <NsMenuItem
                          :label="
                            row.ui_note
                              ? $t('applications.edit_note')
                              : $t('applications.add_note')
                          "
                        >
                          <template slot="icon">
                            <RequestQuote20 />
                          </template>
                        </NsMenuItem>
                      </cv-overflow-menu-item>
                      <cv-overflow-menu-item
                        v-if="row.update"
                        :disabled="isUpdateInProgress"
                        @click="updateInstance(row, false)"
                      >
                        <NsMenuItem
                          :icon="Upgrade20"
                          :label="$t('applications.update')"
                        />
                      </cv-overflow-menu-item>
                      <cv-overflow-menu-item
                        v-if="isTestingUpdateAvailable(row)"
                        :disabled="isUpdateInProgress"
                        @click="updateInstance(row, true)"
                      >
                        <NsMenuItem
                          :icon="Upgrade20"
                          :label="
                            $t('software_center.update_to_testing_version')
                          "
                        />
                      </cv-overflow-menu-item>
                      <cv-overflow-menu-item
                        v-if="isAutomaticUpdatesToggleShown(row)"
                        @click="toggleInstanceAutomaticUpdates(row)"
                      >
                        <NsMenuItem
                          :icon="
                            row.automatic_updates
                              ? PauseOutline20
                              : PlayOutline20
                          "
                          :label="
                            row.automatic_updates
                              ? $t('software_center.disable_automatic_updates')
                              : $t('software_center.enable_automatic_updates')
                          "
                        />
                      </cv-overflow-menu-item>
                      <cv-overflow-menu-item
                        v-if="!favoriteApps.includes(row.id)"
                        @click="addFavorite(row)"
                      >
                        <NsMenuItem
                          :icon="Star20"
                          :label="$t('software_center.add_to_favorites')"
                        />
                      </cv-overflow-menu-item>
                      <cv-overflow-menu-item
                        v-if="favoriteApps.includes(row.id)"
                        @click="removeFavorite(row)"
                      >
                        <NsMenuItem
                          :icon="Star20"
                          :label="$t('software_center.remove_from_favorites')"
                        />
                      </cv-overflow-menu-item>
                      <cv-overflow-menu-item @click="showCloneAppModal(row)">
                        <NsMenuItem
                          :icon="Copy20"
                          :label="$t('applications.clone')"
                        />
                      </cv-overflow-menu-item>
                      <cv-overflow-menu-item
                        @click="showMoveAppModal(row)"
                        :disabled="clusterNodes.length < 2"
                      >
                        <NsMenuItem
                          :icon="ArrowRight20"
                          :label="$t('applications.move')"
                        />
                      </cv-overflow-menu-item>
                      <cv-overflow-menu-item
                        @click="showRestartModuleModal(row)"
                      >
                        <NsMenuItem
                          :icon="Restart20"
                          :label="$t('applications.restart')"
                        />
                      </cv-overflow-menu-item>
                      <NsMenuDivider />
                      <cv-overflow-menu-item
                        danger
                        @click="showUninstallModal(row)"
                      >
                        <NsMenuItem
                          :icon="TrashCan20"
                          :label="$t('applications.uninstall')"
                        />
                      </cv-overflow-menu-item>
                    </cv-overflow-menu>
                  </cv-data-table-cell>
                </cv-data-table-row>
              </template>
            </NsDataTable>
          </cv-tile>
        </cv-column>
      </cv-row>
    </cv-grid>
    <SetInstanceLabelModal
      :visible="isShownEditInstanceLabel"
      :currentInstance="currentInstance"
      :newInstanceLabel="newInstanceLabel"
      @hide="hideSetInstanceLabelModal"
      @setInstanceLabelCompleted="listModules"
    />
    <NsDangerDeleteModal
      :isShown="isShownUninstallModal"
      :name="instanceToUninstall ? instanceToUninstall.id : ''"
      :title="
        $t('applications.app_uninstallation', {
          app: instanceToUninstallLabel,
        })
      "
      :warning="$t('common.please_read_carefully')"
      :description="
        $t('applications.uninstall_app', {
          name: instanceToUninstallLabel,
        })
      "
      :typeToConfirm="
        $t('common.type_to_confirm', {
          name: instanceToUninstall ? instanceToUninstall.id : '',
        })
      "
      :isErrorShown="!!error.removeModule"
      :errorTitle="$t('action.remove-module')"
      :errorDescription="error.removeModule"
      @hide="isShownUninstallModal = false"
      @confirmDelete="uninstallInstance"
    />
    <AutomaticUpdatesModal
      :visible="isShownAutomaticUpdatesModal"
      :enable="enableAutomaticUpdates"
      :instance="instanceToToggleAutomaticUpdates"
      @hide="isShownAutomaticUpdatesModal = false"
      @completed="onAutomaticUpdatesChanged"
    />
    <RestartModuleModal
      :visible="isShowRestartModuleModal"
      :instanceToRestart="instanceToRestart"
      @hide="hideRestartModuleModal"
    />
    <CloneOrMoveAppModal
      :isShown="cloneOrMove.isModalShown"
      :isClone="cloneOrMove.isClone"
      :instanceId="cloneOrMove.instanceId"
      :instanceUiName="cloneOrMove.instanceUiName"
      :installationNode="cloneOrMove.installationNode"
      :app="appInfoData"
      @hide="cloneOrMove.isModalShown = false"
      @cloneOrMoveCompleted="listModules"
    />
    <UpdateAppModal
      :isShown="isShownUpdateModal"
      :app="app"
      :instance="instanceToUpdate"
      :isUpdatingToTestingVersion="isUpdatingToTestingVersion"
      @hide="isShownUpdateModal = false"
      @updateCompleted="listModules"
    />
    <AddNoteModal
      :visible="isShowNote"
      :isEdit="noteText.length > 0"
      :currentNote="noteText"
      :noteInstance="noteInstance"
      @hide="hideAddNoteModal"
      @saveNoteCompleted="listModules"
    />
    <AppInfoModal
      :app="appInfo.app"
      :isShown="appInfo.isShown"
      @close="onClose"
    />
  </div>
</template>
⋮----
{{ $t("applications.title") }}
⋮----
<template slot="content">
                <i18n path="applications.title_tooltip" tag="p">
                  <template v-slot:software>
                    <cv-link @click="goToSoftwareCenter">
                      {{ $t("software_center.title") }}
                    </cv-link>
                  </template>
                </i18n>
              </template>
⋮----
<template v-slot:software>
                    <cv-link @click="goToSoftwareCenter">
                      {{ $t("software_center.title") }}
                    </cv-link>
                  </template>
⋮----
{{ $t("software_center.title") }}
⋮----
>{{ $t("software_center.go_to_core_applications") }}</NsButton
⋮----
>{{ $t("common.clear_filters") }}
⋮----
<template slot="empty-state">
                <template v-if="hasActiveFilters && modules.length">
                  <NsEmptyState
                    :title="$t('common.no_search_results')"
                    key="no-results-empty-state"
                  >
                    <template #description>
                      <div class="flex flex-col items-center text-center gap-2">
                        <p>
                          {{ $t("common.no_search_results_description") }}
                        </p>
                        <NsButton
                          kind="ghost"
                          size="field"
                          @click="clearFilters()"
                          >{{ $t("common.clear_filters") }}
                        </NsButton>
                      </div>
                    </template>
                  </NsEmptyState>
                </template>
                <template v-else>
                  <NsEmptyState :title="$t('applications.no_application')">
                    <template #pictogram>
                      <AppsPictogram />
                    </template>
                    <template #description>
                      <div>
                        {{ $t("applications.no_application_description") }}
                      </div>
                      <NsButton
                        kind="primary"
                        class="empty-state-button"
                        :icon="ArrowRight20"
                        @click="goToSoftwareCenter"
                        :disabled="loading.listModules"
                        >{{ $t("applications.go_to_software_center") }}
                      </NsButton>
                    </template>
                  </NsEmptyState>
                </template>
              </template>
⋮----
<template v-if="hasActiveFilters && modules.length">
                  <NsEmptyState
                    :title="$t('common.no_search_results')"
                    key="no-results-empty-state"
                  >
                    <template #description>
                      <div class="flex flex-col items-center text-center gap-2">
                        <p>
                          {{ $t("common.no_search_results_description") }}
                        </p>
                        <NsButton
                          kind="ghost"
                          size="field"
                          @click="clearFilters()"
                          >{{ $t("common.clear_filters") }}
                        </NsButton>
                      </div>
                    </template>
                  </NsEmptyState>
                </template>
⋮----
<template #description>
                      <div class="flex flex-col items-center text-center gap-2">
                        <p>
                          {{ $t("common.no_search_results_description") }}
                        </p>
                        <NsButton
                          kind="ghost"
                          size="field"
                          @click="clearFilters()"
                          >{{ $t("common.clear_filters") }}
                        </NsButton>
                      </div>
                    </template>
⋮----
{{ $t("common.no_search_results_description") }}
⋮----
>{{ $t("common.clear_filters") }}
⋮----
<template v-else>
                  <NsEmptyState :title="$t('applications.no_application')">
                    <template #pictogram>
                      <AppsPictogram />
                    </template>
                    <template #description>
                      <div>
                        {{ $t("applications.no_application_description") }}
                      </div>
                      <NsButton
                        kind="primary"
                        class="empty-state-button"
                        :icon="ArrowRight20"
                        @click="goToSoftwareCenter"
                        :disabled="loading.listModules"
                        >{{ $t("applications.go_to_software_center") }}
                      </NsButton>
                    </template>
                  </NsEmptyState>
                </template>
⋮----
<template #pictogram>
                      <AppsPictogram />
                    </template>
<template #description>
                      <div>
                        {{ $t("applications.no_application_description") }}
                      </div>
                      <NsButton
                        kind="primary"
                        class="empty-state-button"
                        :icon="ArrowRight20"
                        @click="goToSoftwareCenter"
                        :disabled="loading.listModules"
                        >{{ $t("applications.go_to_software_center") }}
                      </NsButton>
                    </template>
⋮----
{{ $t("applications.no_application_description") }}
⋮----
>{{ $t("applications.go_to_software_center") }}
⋮----
<template slot="data">
                <cv-data-table-row
                  v-for="(row, rowIndex) in tablePage"
                  :key="`${rowIndex}`"
                  :value="`${rowIndex}`"
                >
                  <cv-data-table-cell>
                    <span>
                      <a class="app-name" @click="openInstance(row)">
                        {{
                          row.ui_name
                            ? row.ui_name + " (" + row.id + ")"
                            : row.id
                        }}
                      </a>
                    </span>
                    <cv-interactive-tooltip
                      v-if="row.ui_note"
                      alignment="start"
                      direction="right"
                      class="info margin-left-sm"
                    >
                      <template slot="content">
                        <span class="underline-tooltip">
                          {{ row.ui_note }}
                        </span>
                      </template>
                    </cv-interactive-tooltip>
                  </cv-data-table-cell>
                  <cv-data-table-cell>
                    <a @click="showAppInfo(row.appInfoData)">
                      <img
                        :src="
                          row.logo
                            ? row.logo
                            : require('@/assets/module_default_logo.png')
                        "
                        :alt="row.name + ' logo'"
                        class="module-logo"
                      />
                      <span class="app-name">{{ row.module }}</span>
                    </a>
                  </cv-data-table-cell>
                  <cv-data-table-cell>
                    <span>{{
                      row.node_ui_name
                        ? row.node_ui_name +
                          " (" +
                          $t("common.node") +
                          " " +
                          row.node +
                          ")"
                        : $t("common.node") + " " + row.node
                    }}</span>
                  </cv-data-table-cell>
                  <cv-data-table-cell>
                    <div class="flex items-center">
                      <span>{{ row.version }}</span>
                      <cv-tag
                        v-if="row.update"
                        class="mg-left-sm"
                        kind="green"
                        :label="$t('applications.update_available')"
                      />
                      <cv-tag
                        v-if="isUpdatesDisabledShown(row)"
                        class="mg-left-sm"
                        kind="high-contrast"
                        :label="$t('software_center.updates_disabled')"
                      />
                    </div>
                  </cv-data-table-cell>
                  <cv-data-table-cell class="table-overflow-menu-cell">
                    <cv-overflow-menu flip-menu class="table-overflow-menu">
                      <cv-overflow-menu-item
                        primary-focus
                        @click="openInstance(row)"
                      >
                        <NsMenuItem
                          :icon="Application20"
                          :label="$t('applications.open')"
                        />
                      </cv-overflow-menu-item>
                      <cv-overflow-menu-item
                        @click="showSetInstanceLabelModal(row)"
                      >
                        <NsMenuItem
                          :icon="Edit20"
                          :label="$t('applications.edit_label')"
                        />
                      </cv-overflow-menu-item>
                      <cv-overflow-menu-item @click="showAddNoteModal(row)">
                        <NsMenuItem
                          :label="
                            row.ui_note
                              ? $t('applications.edit_note')
                              : $t('applications.add_note')
                          "
                        >
                          <template slot="icon">
                            <RequestQuote20 />
                          </template>
                        </NsMenuItem>
                      </cv-overflow-menu-item>
                      <cv-overflow-menu-item
                        v-if="row.update"
                        :disabled="isUpdateInProgress"
                        @click="updateInstance(row, false)"
                      >
                        <NsMenuItem
                          :icon="Upgrade20"
                          :label="$t('applications.update')"
                        />
                      </cv-overflow-menu-item>
                      <cv-overflow-menu-item
                        v-if="isTestingUpdateAvailable(row)"
                        :disabled="isUpdateInProgress"
                        @click="updateInstance(row, true)"
                      >
                        <NsMenuItem
                          :icon="Upgrade20"
                          :label="
                            $t('software_center.update_to_testing_version')
                          "
                        />
                      </cv-overflow-menu-item>
                      <cv-overflow-menu-item
                        v-if="isAutomaticUpdatesToggleShown(row)"
                        @click="toggleInstanceAutomaticUpdates(row)"
                      >
                        <NsMenuItem
                          :icon="
                            row.automatic_updates
                              ? PauseOutline20
                              : PlayOutline20
                          "
                          :label="
                            row.automatic_updates
                              ? $t('software_center.disable_automatic_updates')
                              : $t('software_center.enable_automatic_updates')
                          "
                        />
                      </cv-overflow-menu-item>
                      <cv-overflow-menu-item
                        v-if="!favoriteApps.includes(row.id)"
                        @click="addFavorite(row)"
                      >
                        <NsMenuItem
                          :icon="Star20"
                          :label="$t('software_center.add_to_favorites')"
                        />
                      </cv-overflow-menu-item>
                      <cv-overflow-menu-item
                        v-if="favoriteApps.includes(row.id)"
                        @click="removeFavorite(row)"
                      >
                        <NsMenuItem
                          :icon="Star20"
                          :label="$t('software_center.remove_from_favorites')"
                        />
                      </cv-overflow-menu-item>
                      <cv-overflow-menu-item @click="showCloneAppModal(row)">
                        <NsMenuItem
                          :icon="Copy20"
                          :label="$t('applications.clone')"
                        />
                      </cv-overflow-menu-item>
                      <cv-overflow-menu-item
                        @click="showMoveAppModal(row)"
                        :disabled="clusterNodes.length < 2"
                      >
                        <NsMenuItem
                          :icon="ArrowRight20"
                          :label="$t('applications.move')"
                        />
                      </cv-overflow-menu-item>
                      <cv-overflow-menu-item
                        @click="showRestartModuleModal(row)"
                      >
                        <NsMenuItem
                          :icon="Restart20"
                          :label="$t('applications.restart')"
                        />
                      </cv-overflow-menu-item>
                      <NsMenuDivider />
                      <cv-overflow-menu-item
                        danger
                        @click="showUninstallModal(row)"
                      >
                        <NsMenuItem
                          :icon="TrashCan20"
                          :label="$t('applications.uninstall')"
                        />
                      </cv-overflow-menu-item>
                    </cv-overflow-menu>
                  </cv-data-table-cell>
                </cv-data-table-row>
              </template>
⋮----
{{
                          row.ui_name
                            ? row.ui_name + " (" + row.id + ")"
                            : row.id
                        }}
⋮----
<template slot="content">
                        <span class="underline-tooltip">
                          {{ row.ui_note }}
                        </span>
                      </template>
⋮----
{{ row.ui_note }}
⋮----
<span class="app-name">{{ row.module }}</span>
⋮----
<span>{{
                      row.node_ui_name
                        ? row.node_ui_name +
                          " (" +
                          $t("common.node") +
                          " " +
                          row.node +
                          ")"
                        : $t("common.node") + " " + row.node
                    }}</span>
⋮----
<span>{{ row.version }}</span>
⋮----
<template slot="icon">
                            <RequestQuote20 />
                          </template>
⋮----
<script>
import to from "await-to-js";
import CloneOrMoveAppModal from "@/components/software-center/CloneOrMoveAppModal";
import UpdateAppModal from "../components/software-center/UpdateAppModal";
import SetInstanceLabelModal from "@/components/software-center/SetInstanceLabelModal.vue";
import RestartModuleModal from "@/components/software-center/RestartModuleModal.vue";
import AddNoteModal from "@/components/applications-center/AddNoteModal.vue";
import RequestQuote20 from "@carbon/icons-vue/es/request-quote/20";
import PauseOutline20 from "@carbon/icons-vue/es/pause--outline/20";
import PlayOutline20 from "@carbon/icons-vue/es/play--outline/20";
import AppInfoModal from "@/components/software-center/AppInfoModal.vue";
import AutomaticUpdatesModal from "@/components/software-center/AutomaticUpdatesModal";
import {
  QueryParamService,
  UtilService,
  TaskService,
  IconService,
  LottieService,
  PageTitleService,
} from "@nethserver/ns8-ui-lib";
import { mapState, mapActions } from "vuex";
export default {
  name: "ApplicationsCenter",
  components: {
    CloneOrMoveAppModal,
    UpdateAppModal,
    SetInstanceLabelModal,
    RestartModuleModal,
    AddNoteModal,
    RequestQuote20,
    AppInfoModal,
    AutomaticUpdatesModal,
  },
  mixins: [
    IconService,
    QueryParamService,
    UtilService,
    TaskService,
    LottieService,
    PageTitleService,
  ],
  pageTitle() {
    return this.$t("applications.title");
  },
  data() {
    return {
      q: {
        selectedNodeId: "",
      },
      isShownEditInstanceLabel: false,
      currentInstance: null,
      newInstanceLabel: "",
      instanceToUninstall: null,
      isShownUninstallModal: false,
      isShowRestartModuleModal: false,
      instanceToRestart: null,
      cloneOrMove: {
        isModalShown: false,
        isClone: false,
        instanceId: "",
        instanceUiName: null,
        installationNode: 1,
      },
      appInfoData: {
        install_destinations: [],
      },
      instanceToUpdate: null,
      isShownUpdateModal: false,
      isUpdatingToTestingVersion: false,
      appUpdates: [],
      app: null,
      modules: [],
      PauseOutline20,
      PlayOutline20,
      subscriptionIsActive: false,
      applyUpdatesIsActive: false,
      isShownAutomaticUpdatesModal: false,
      instanceToToggleAutomaticUpdates: null,
      tableColumns: ["name", "type", "node", "version"],
      tablePage: [],
      filter: {
        moduleType: "",
        text: "",
      },
      moduleTypeOptions: [],
      nodesTypeOptions: [],
      loading: {
        listModules: true,
        addNote: false,
      },
      error: {
        listModules: "",
        removeModule: "",
        addNote: "",
        addFavorite: "",
        removeFavorite: "",
      },
      isShowNote: false,
      noteInstance: null,
      noteText: "",
      appInfo: {
        isShown: false,
        app: null,
      },
    };
  },
  computed: {
    ...mapState(["isUpdateInProgress", "clusterNodes", "favoriteApps"]),
    instanceToUninstallLabel() {
      if (!this.instanceToUninstall) {
        return "";
      }
      return this.instanceToUninstall.ui_name
        ? `${this.instanceToUninstall.ui_name} (${this.instanceToUninstall.id})`
        : this.instanceToUninstall.id;
    },
    i18nTableColumns() {
      return this.tableColumns.map((column) => {
        return this.$t("applications." + column);
      });
    },
    hasActiveFilters() {
      return (
        (this.filter.text && this.filter.text.trim() !== "") ||
        (this.filter.moduleType && this.filter.moduleType !== "any") ||
        (this.q.selectedNodeId && this.q.selectedNodeId !== "any")
      );
    },
    filteredModules() {
      let filteredModules = this.modules;
      if (
        this.filter.moduleType &&
        this.filter.moduleType !== "any" &&
        this.filter.moduleType.length > 0
      ) {
        filteredModules = filteredModules.filter(
          (module) => module.module === this.filter.moduleType
        );
      }
      if (
        this.q.selectedNodeId &&
        this.q.selectedNodeId !== "any" &&
        this.q.selectedNodeId.length > 0
      ) {
        filteredModules = filteredModules.filter(
          (module) => module.node === this.q.selectedNodeId
        );
      }
      if (this.filter.text && this.filter.text.length > 0) {
        const searchText = this.filter.text.toLowerCase();
        filteredModules = filteredModules.filter((module) => {
          return (
            (module.ui_name &&
              module.ui_name.toLowerCase().includes(searchText)) ||
            module.id.toLowerCase().includes(searchText) ||
            module.module.toLowerCase().includes(searchText) ||
            (module.node_ui_name &&
              module.node_ui_name.toLowerCase().includes(searchText)) ||
            module.node.toLowerCase().includes(searchText) ||
            module.version.toLowerCase().includes(searchText)
          );
        });
      }
      return filteredModules;
    },
    isAutomaticUpdatesOptOutAvailable() {
      return this.subscriptionIsActive && this.applyUpdatesIsActive;
    },
    enableAutomaticUpdates() {
      const instance = this.instanceToToggleAutomaticUpdates;
      return instance
        ? instance.automatic_updates === false
        : !this.applyUpdatesIsActive;
    },
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.watchQueryData(vm);
      vm.queryParamsToDataForCore(vm, to.query);
    });
  },
  beforeRouteUpdate(to, from, next) {
    this.queryParamsToDataForCore(this, to.query);
    next();
  },
  created() {
    this.listModules();
  },
  methods: {
    ...mapActions(["setUpdateInProgressInStore", "setAppDrawerShownInStore"]),
    showAppInfo(app) {
      this.appInfo.isShown = true;
      this.appInfo.app = app;
    },
    isUpdatesDisabledShown(row) {
      return (
        this.isAutomaticUpdatesOptOutAvailable &&
        row.automatic_updates === false
      );
    },
    isAutomaticUpdatesToggleShown(row) {
      return (
        this.isAutomaticUpdatesOptOutAvailable &&
        (row.appInfoData.certification_level >= 5 ||
          row.automatic_updates === false)
      );
    },
    toggleInstanceAutomaticUpdates(row) {
      this.instanceToToggleAutomaticUpdates = row;
      this.isShownAutomaticUpdatesModal = true;
    },
    toggleAutomaticUpdates() {
      this.instanceToToggleAutomaticUpdates = null;
      this.isShownAutomaticUpdatesModal = true;
    },
    onAutomaticUpdatesChanged(enable) {
      if (this.instanceToToggleAutomaticUpdates) {
        this.instanceToToggleAutomaticUpdates.automatic_updates = enable;
      } else {
        this.applyUpdatesIsActive = enable;
      }
    },
    onClose() {
      const context = this;
      setTimeout(() => {
        context.appInfo.isShown = false;
      }, 250);
    },
    clearFilters() {
      this.q.selectedNodeId = "any";
      this.filter.text = "";
      this.filter.moduleType = "any";
    },
    updateInstance(instance, isUpdatingToTestingVersion = false) {
      this.instanceToUpdate = instance;
      this.isUpdatingToTestingVersion = isUpdatingToTestingVersion;
      this.app = this.appUpdates.find(
        (app) => app.id === instance.appInfoData.id
      );
      this.isShownUpdateModal = true;
    },
    isTestingUpdateAvailable(instance) {
      const app = this.appUpdates.find((a) => a.id === instance.appInfoData.id);
      if (!app || !app.updates) {
        return false;
      }
      return app.updates.find((update) => {
        return update.id === instance.id && update.testing_update;
      });
    },
    addFavoriteCompleted() {
      this.$root.$emit("reloadAppDrawer");
      this.setAppDrawerShownInStore(true);
    },
    addFavoriteAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.addFavorite = this.$t("error.generic_error");
    },
    async addFavorite(app) {
      this.error.addFavorite = "";
      const taskAction = "add-favorite";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.addFavoriteAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.addFavoriteCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: { instance: app.id },
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.addFavorite = this.getErrorMessage(err);
        this.$root.$off(
          `${taskAction}-completed-${eventId}`,
          this.addFavoriteCompleted
        );
        this.$root.$off(
          `${taskAction}-aborted-${eventId}`,
          this.addFavoriteAborted
        );
        return;
      }
    },
    removeFavoriteCompleted() {
      this.$root.$emit("reloadAppDrawer");
      this.setAppDrawerShownInStore(true);
    },
    removeFavoriteAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.removeFavorite = this.$t("error.generic_error");
    },
    async removeFavorite(app) {
      this.error.removeFavorite = "";
      const taskAction = "remove-favorite";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.removeFavoriteAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.removeFavoriteCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: { instance: app.id },
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.removeFavorite = this.getErrorMessage(err);
        this.$root.$off(
          `${taskAction}-completed-${eventId}`,
          this.removeFavoriteCompleted
        );
        this.$root.$off(
          `${taskAction}-aborted-${eventId}`,
          this.removeFavoriteAborted
        );
        return;
      }
    },
    showCloneAppModal(instance) {
      this.cloneOrMove.isClone = true;
      this.cloneOrMove.instanceId = instance.id;
      this.cloneOrMove.instanceUiName = instance.ui_name;
      this.cloneOrMove.installationNode = parseInt(instance.node);
      this.appInfoData = instance.appInfoData;
      this.cloneOrMove.isModalShown = true;
    },
    showMoveAppModal(instance) {
      this.cloneOrMove.isClone = false;
      this.cloneOrMove.instanceId = instance.id;
      this.cloneOrMove.instanceUiName = instance.ui_name;
      this.cloneOrMove.installationNode = parseInt(instance.node);
      this.appInfoData = instance.appInfoData;
      this.cloneOrMove.isModalShown = true;
    },
    showRestartModuleModal(instance) {
      this.instanceToRestart = instance;
      this.isShowRestartModuleModal = true;
    },
    hideRestartModuleModal() {
      this.isShowRestartModuleModal = false;
    },
    showUninstallModal(instance) {
      this.instanceToUninstall = instance;
      this.error.removeModule = "";
      this.isShownUninstallModal = true;
    },
    async uninstallInstance() {
      this.error.removeModule = "";
      const taskAction = "remove-module";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.removeModuleAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.removeModuleCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {
            module_id: this.instanceToUninstall.id,
            preserve_data: false,
          },
          extra: {
            title: this.$t("applications.instance_uninstallation", {
              instance: this.instanceToUninstall.ui_name
                ? this.instanceToUninstall.ui_name
                : this.instanceToUninstall.id,
            }),
            description: this.$t("applications.uninstalling"),
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.removeModule = this.getErrorMessage(err);
        return;
      }
      this.isShownUninstallModal = false;
    },
    removeModuleAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.removeModule = this.$t("error.generic_error");
    },
    removeModuleCompleted() {
      this.listModules();
      this.$root.$emit("reloadAppDrawer");
    },
    showSetInstanceLabelModal(instance) {
      this.currentInstance = instance;
      this.newInstanceLabel = instance.ui_name;
      this.isShownEditInstanceLabel = true;
    },
    hideSetInstanceLabelModal() {
      this.isShownEditInstanceLabel = false;
    },
    openInstance(instance) {
      this.$router.push(`/apps/${instance.id}`);
    },
    goToSoftwareCenter() {
      this.$router.push("/software-center");
    },
    async listModules() {
      this.loading.listModules = true;
      this.error.listModules = "";
      const taskAction = "list-modules";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.listModulesCompleted
      );
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.listModulesAborted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.listModules = this.getErrorMessage(err);
        this.loading.listModules = false;
        return;
      }
    },
    listModulesAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.listModules = this.$t("error.generic_error");
      this.loading.listModules = false;
    },
    listModulesCompleted(taskContext, taskResult) {
      let modules = taskResult.output;
      let appUpdates = [];
      for (const module of modules) {
        const hasStableUpdate = module.updates.some((update) => update.update);
        const hasTestingUpdate = module.updates.some(
          (update) => update.testing_update
        );
        if (hasStableUpdate || hasTestingUpdate) {
          appUpdates.push(module);
        }
        module.installed.sort(this.sortModuleInstances());
      }
      this.appUpdates = appUpdates;
      const extractedModules = [];
      for (const moduleData of modules) {
        const updates = moduleData.updates;
        for (const item of moduleData.installed) {
          const updateEntry = updates.find((u) => u.id === item.id);
          const installedData = updateEntry || item;
          extractedModules.push({
            id: installedData.id || "",
            logo: moduleData.logo || "",
            module: moduleData.name || "", // we want a humanized module name
            node: installedData.node || "",
            node_ui_name: installedData.node_ui_name || "",
            ui_name: installedData.ui_name || "",
            ui_note: installedData.ui_note || "",
            version: installedData.version || "",
            update: installedData.update || "",
            automatic_updates: item.automatic_updates,
            appInfoData: moduleData, // needed for clone/move/info modals
          });
        }
      }
      // sort by id
      extractedModules.sort(this.sortByProperty("id"));
      this.modules = extractedModules;
      if (modules.length) {
        this.subscriptionIsActive = !!modules[0].subscription_is_active;
        this.applyUpdatesIsActive = !!modules[0].apply_updates_is_active;
      }
      const moduleTypes = [
        {
          name: "any",
          label: this.$t("common.any"),
          value: "any",
        },
        ...Array.from(
          new Map(
            this.modules.map((m) => [
              m.module,
              {
                name: m.module,
                value: m.module,
                label: m.module.charAt(0).toUpperCase() + m.module.slice(1),
              },
            ])
          ).values()
        ),
      ];
      this.moduleTypeOptions = moduleTypes;
      const nodesForFilter = [
        {
          name: "any",
          label: this.$t("common.any"),
          value: "any",
        },
        ...Array.from(
          new Map(
            this.modules.map((m) => [
              m.node,
              {
                name: m.node,
                value: m.node,
                label: m.node_ui_name
                  ? `${m.node_ui_name} (${this.$t("common.node")} ${m.node})`
                  : `${this.$t("common.node")} ${m.node}`,
              },
            ])
          ).values()
        ),
      ];
      this.nodesTypeOptions = nodesForFilter;
      this.$nextTick(() => {
        if (!this.q.selectedNodeId) {
          this.q.selectedNodeId = "any";
        } else {
          const nodeId = this.q.selectedNodeId;
          this.q.selectedNodeId = "";
          this.$nextTick(() => {
            this.q.selectedNodeId = nodeId;
          });
        }
        if (!this.filter.moduleType) {
          this.filter.moduleType = "any";
        } else {
          const moduleType = this.filter.moduleType;
          this.filter.moduleType = "";
          this.$nextTick(() => {
            this.filter.moduleType = moduleType;
          });
        }
      });
      this.loading.listModules = false;
    },
    showSoftwareCenterCoreApps() {
      this.$router.push("/software-center/core-apps");
    },
    hideAddNoteModal() {
      this.isShowNote = false;
    },
    showAddNoteModal(instance) {
      this.noteInstance = instance;
      this.noteText = instance.ui_note || "";
      this.isShowNote = true;
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../styles/carbon-utils";
.app-search {
  margin-bottom: $spacing-07;
}
.switcher {
  margin-bottom: $spacing-05;
}
.search-results-title {
  margin-top: $spacing-07;
  margin-bottom: $spacing-03;
}
.search-limited-width {
  max-width: 16.625rem;
  min-width: 11.25rem;
}
.module-logo {
  height: 32px;
  vertical-align: middle;
  margin-right: 8px;
}
.app-name {
  font-weight: 600;
}
</style>
</file>

<file path="core/ui/src/views/AuditTrail.vue">
<template>
  <cv-grid fullWidth>
    <cv-row>
      <cv-column class="page-title">
        <h2>{{ $t("audit_trail.title") }}</h2>
      </cv-column>
    </cv-row>
    <cv-row class="landscape-warning">
      <cv-column>
        <NsInlineNotification
          kind="warning"
          :title="$t('common.use_landscape_mode')"
          :description="$t('common.use_landscape_mode_description')"
        />
      </cv-column>
    </cv-row>
    <cv-row>
      <cv-column>
        <cv-tile :light="true">
          <cv-grid fullWidth class="no-padding">
            <cv-row>
              <cv-column :lg="8">
                <cv-date-picker
                  kind="single"
                  :cal-options="calOptions"
                  :date-label="$t('audit_trail.start_date')"
                  v-model="startDateString"
                  class="interval-date mg-bottom-md"
                  :invalid-message="error.startDate"
                >
                </cv-date-picker>
                <NsTimePicker
                  hideClearButton
                  v-model="startTime"
                  :label="$t('audit_trail.start_time_label')"
                  class="interval-time mg-bottom-md"
                ></NsTimePicker>
              </cv-column>
              <cv-column :lg="8">
                <cv-date-picker
                  kind="single"
                  :cal-options="calOptions"
                  :date-label="$t('audit_trail.end_date')"
                  v-model="endDateString"
                  class="interval-date mg-bottom-md"
                  :invalid-message="error.endDate"
                >
                </cv-date-picker>
                <NsTimePicker
                  hideClearButton
                  v-model="endTime"
                  :label="$t('audit_trail.end_time_label')"
                  class="interval-time mg-bottom-md"
                ></NsTimePicker>
              </cv-column>
            </cv-row>
            <cv-row>
              <cv-column :lg="8">
                <cv-multi-select
                  v-model="usersSelected"
                  :options="users"
                  :title="
                    $t('audit_trail.users') + ' (' + $t('common.optional') + ')'
                  "
                  :label="$t('audit_trail.users_label')"
                  :helper-text="usersHelperText"
                  class="mg-bottom-md"
                >
                </cv-multi-select>
                <NsInlineNotification
                  v-if="error.auditUsers"
                  kind="error"
                  :title="$t('audit_trail.cannot_retrieve_audit_users')"
                  :description="error.auditUsers"
                  :showCloseButton="false"
                />
              </cv-column>
              <cv-column :lg="8">
                <cv-multi-select
                  v-model="actionsSelected"
                  :options="actions"
                  :title="
                    $t('audit_trail.actions') +
                    ' (' +
                    $t('common.optional') +
                    ')'
                  "
                  :label="$t('audit_trail.actions_label')"
                  :helper-text="actionsHelperText"
                  class="mg-bottom-md"
                >
                </cv-multi-select>
                <NsInlineNotification
                  v-if="error.auditActions"
                  kind="error"
                  :title="$t('audit_trail.cannot_retrieve_audit_actions')"
                  :description="error.auditActions"
                  :showCloseButton="false"
                />
              </cv-column>
            </cv-row>
            <cv-row>
              <cv-column :lg="8">
                <cv-text-input
                  :label="
                    $t('audit_trail.auditInfo') +
                    ' (' +
                    $t('common.optional') +
                    ')'
                  "
                  v-model="auditInfo"
                  :placeholder="$t('audit_trail.audit_info_placeholder')"
                  @keypress.enter="searchLogs()"
                  class="mg-bottom-md"
                >
                </cv-text-input>
              </cv-column>
              <cv-column :lg="8">
                <cv-text-input
                  :label="$t('audit_trail.max_results')"
                  v-model="maxResults"
                  :invalid-message="error.maxResults"
                  type="number"
                  min="1"
                  :max="MAX_RESULTS_LIMIT"
                  @keypress.enter="searchLogs()"
                  class="narrow mg-bottom-md"
                  ref="maxResults"
                >
                </cv-text-input>
              </cv-column>
            </cv-row>
            <cv-row class="search-button">
              <cv-column>
                <NsButton
                  kind="primary"
                  :icon="Search20"
                  :loading="loading.auditTrail"
                  :disabled="loading.auditTrail"
                  @click="searchLogs"
                  >{{ $t("audit_trail.search") }}</NsButton
                >
              </cv-column>
            </cv-row>
          </cv-grid>
          <cv-grid fullWidth class="no-padding">
            <cv-row>
              <cv-column>
                <NsDataTable
                  :allRows="logs"
                  :columns="i18nTableColumns"
                  :rawColumns="tableColumns"
                  :sortable="true"
                  :isSearchable="false"
                  :isLoading="loading.auditTrail"
                  :isErrorShown="!!error.auditTrail"
                  :errorTitle="$t('audit_trail.cannot_retrieve_audit_trail')"
                  :errorDescription="error.auditTrail"
                  :itemsPerPageLabel="$t('pagination.items_per_page')"
                  :rangeOfTotalItemsLabel="
                    $t('pagination.range_of_total_items')
                  "
                  :ofTotalPagesLabel="$t('pagination.of_total_pages')"
                  :backwardText="$t('pagination.previous_page')"
                  :forwardText="$t('pagination.next_page')"
                  :pageNumberLabel="$t('pagination.page_number')"
                  @updatePage="tablePage = $event"
                  ref="table"
                >
                  <template slot="empty-state">
                    <NsEmptyState
                      :title="$t('audit_trail.no_log_found')"
                      :animationData="GhostLottie"
                      animationTitle="ghost"
                      :loop="1"
                    >
                      <template #description>
                        <div>
                          {{ $t("audit_trail.no_log_found_description") }}
                        </div>
                      </template>
                    </NsEmptyState>
                  </template>
                  <template slot="data">
                    <cv-data-table-row
                      v-for="(row, rowIndex) in tablePage"
                      :key="`${rowIndex}`"
                      :value="`${rowIndex}`"
                    >
                      <cv-data-table-cell>{{
                        row.timestamp
                      }}</cv-data-table-cell>
                      <cv-data-table-cell>{{ row.user }}</cv-data-table-cell>
                      <cv-data-table-cell>{{ row.action }}</cv-data-table-cell>
                      <cv-data-table-cell
                        :class="{
                          'audit-info-collapsed': row.auditInfoCollapsed,
                        }"
                      >
                        <cv-icon-button
                          v-if="row.auditInfo"
                          kind="ghost"
                          size="sm"
                          :icon="
                            row.auditInfoCollapsed ? RowExpand20 : RowCollapse20
                          "
                          :label="
                            row.auditInfoCollapsed
                              ? $t('common.expand')
                              : $t('common.collapse')
                          "
                          @click="
                            row.auditInfoCollapsed = !row.auditInfoCollapsed
                          "
                          tip-position="left"
                          class="expand-audit-info-button"
                        />
                        <code>
                          <pre
                            v-if="!row.auditInfoCollapsed"
                            class="audit-info-pre"
                            >{{ tryParseJson(row.auditInfo) }}</pre
                          >
                          <span v-else :id="'audit-info-' + row.id">{{
                            tryParseJson(row.auditInfo)
                          }}</span>
                        </code>
                      </cv-data-table-cell>
                    </cv-data-table-row>
                  </template>
                </NsDataTable>
              </cv-column>
            </cv-row>
          </cv-grid>
        </cv-tile>
      </cv-column>
    </cv-row>
  </cv-grid>
</template>
⋮----
<h2>{{ $t("audit_trail.title") }}</h2>
⋮----
>{{ $t("audit_trail.search") }}</NsButton
⋮----
<template slot="empty-state">
                    <NsEmptyState
                      :title="$t('audit_trail.no_log_found')"
                      :animationData="GhostLottie"
                      animationTitle="ghost"
                      :loop="1"
                    >
                      <template #description>
                        <div>
                          {{ $t("audit_trail.no_log_found_description") }}
                        </div>
                      </template>
                    </NsEmptyState>
                  </template>
⋮----
<template #description>
                        <div>
                          {{ $t("audit_trail.no_log_found_description") }}
                        </div>
                      </template>
⋮----
{{ $t("audit_trail.no_log_found_description") }}
⋮----
<template slot="data">
                    <cv-data-table-row
                      v-for="(row, rowIndex) in tablePage"
                      :key="`${rowIndex}`"
                      :value="`${rowIndex}`"
                    >
                      <cv-data-table-cell>{{
                        row.timestamp
                      }}</cv-data-table-cell>
                      <cv-data-table-cell>{{ row.user }}</cv-data-table-cell>
                      <cv-data-table-cell>{{ row.action }}</cv-data-table-cell>
                      <cv-data-table-cell
                        :class="{
                          'audit-info-collapsed': row.auditInfoCollapsed,
                        }"
                      >
                        <cv-icon-button
                          v-if="row.auditInfo"
                          kind="ghost"
                          size="sm"
                          :icon="
                            row.auditInfoCollapsed ? RowExpand20 : RowCollapse20
                          "
                          :label="
                            row.auditInfoCollapsed
                              ? $t('common.expand')
                              : $t('common.collapse')
                          "
                          @click="
                            row.auditInfoCollapsed = !row.auditInfoCollapsed
                          "
                          tip-position="left"
                          class="expand-audit-info-button"
                        />
                        <code>
                          <pre
                            v-if="!row.auditInfoCollapsed"
                            class="audit-info-pre"
                            >{{ tryParseJson(row.auditInfo) }}</pre
                          >
                          <span v-else :id="'audit-info-' + row.id">{{
                            tryParseJson(row.auditInfo)
                          }}</span>
                        </code>
                      </cv-data-table-cell>
                    </cv-data-table-row>
                  </template>
⋮----
<cv-data-table-cell>{{
                        row.timestamp
                      }}</cv-data-table-cell>
<cv-data-table-cell>{{ row.user }}</cv-data-table-cell>
<cv-data-table-cell>{{ row.action }}</cv-data-table-cell>
⋮----
>{{ tryParseJson(row.auditInfo) }}</pre
⋮----
<span v-else :id="'audit-info-' + row.id">{{
                            tryParseJson(row.auditInfo)
                          }}</span>
⋮----
<script>
import AuditService from "../mixins/audit";
import to from "await-to-js";
import {
  UtilService,
  IconService,
  DateTimeService,
  LottieService,
  PageTitleService,
} from "@nethserver/ns8-ui-lib";
export default {
  name: "AuditTrail",
  mixins: [
    DateTimeService,
    IconService,
    AuditService,
    UtilService,
    LottieService,
    PageTitleService,
  ],
  pageTitle() {
    return this.$t("audit_trail.title");
  },
  data() {
    return {
      MAX_RESULTS_LIMIT: 2000,
      maxResults: 0,
      startDateString: "",
      endDateString: "",
      startTime: "",
      endTime: "",
      calOptions: {
        dateFormat: "Y-m-d",
      },
      logs: [],
      users: [],
      usersSelected: [],
      actions: [],
      actionsSelected: [],
      auditInfo: "",
      tableColumns: ["timestamp", "user", "action", "auditInfo"],
      tablePage: [],
      loading: {
        auditTrail: true,
      },
      error: {
        auditUsers: "",
        auditActions: "",
        auditTrail: "",
        startDate: "",
        startTime: "",
        endDate: "",
        endTime: "",
        maxResults: "",
      },
    };
  },
  computed: {
    usersHelperText() {
      if (!this.usersSelected.length) {
        return "";
      } else {
        return (
          this.$t("common.selected") + ": " + this.usersSelected.join(", ")
        );
      }
    },
    actionsHelperText() {
      if (!this.actionsSelected.length) {
        return "";
      } else {
        return (
          this.$t("common.selected") + ": " + this.actionsSelected.join(", ")
        );
      }
    },
    i18nTableColumns() {
      return this.tableColumns.map((column) => {
        return this.$t("audit_trail." + column);
      });
    },
  },
  created() {
    this.initFilters();
    this.getAuditData();
  },
  methods: {
    initFilters() {
      this.clearErrors(this);
      this.startDateString = this.formatDate(
        this.subDays(new Date(), 1),
        "yyyy-MM-dd"
      );
      this.endDateString = this.formatDate(new Date(), "yyyy-MM-dd");
      this.startTime = "00:00";
      this.endTime = "23:59";
      this.usersSelected = [];
      this.actionsSelected = [];
      this.auditInfo = "";
      this.maxResults = "100";
    },
    async getAuditData() {
      const [errUsers, responseUsers] = await to(this.getAuditUsers());
      if (errUsers) {
        console.error("error retrieving audit users", errUsers);
        this.error.auditUsers = this.getErrorMessage(errUsers);
        this.loading.auditTrail = false;
        return;
      }
      const users = responseUsers.data.data.users;
      this.users = users.map((u) => {
        return { label: u, value: u, name: u };
      });
      const [errActions, responseActions] = await to(this.getAuditActions());
      if (errActions) {
        console.error("error retrieving audit actions", errActions);
        this.error.auditActions = this.getErrorMessage(errActions);
        this.loading.auditTrail = false;
        return;
      }
      const actions = responseActions.data.data.actions;
      this.actions = actions.map((u) => {
        return { label: u, value: u, name: u };
      });
      this.searchLogs();
    },
    getAuditParams() {
      const startLocal = new Date(
        this.startDateString + "T" + this.startTime + ":00"
      );
      const endLocal = new Date(
        this.endDateString + "T" + this.endTime + ":59"
      );
      const format = "yyyy-MM-dd'T'HH:mm:ssX";
      const startUtcString = this.formatInTimeZone(startLocal, format, "UTC");
      const endUtcString = this.formatInTimeZone(endLocal, format, "UTC");
      return {
        from: startUtcString,
        to: endUtcString,
        users: this.usersSelected,
        actions: this.actionsSelected,
        data: this.auditInfo,
        limit: this.maxResults,
      };
    },
    validateSearchLogs() {
      this.clearErrors(this);
      let isValidationOk = true;
      if (!this.startTime) {
        this.error.startTime = this.$t("common.required");
        isValidationOk = false;
      }
      if (!this.endTime) {
        this.error.endTime = this.$t("common.required");
        isValidationOk = false;
      }
      if (this.startTime && this.endTime) {
        const startLocal = new Date(
          this.startDateString + "T" + this.startTime + ":00"
        );
        const endLocal = new Date(
          this.endDateString + "T" + this.endTime + ":59"
        );
        if (this.dateIsBefore(endLocal, startLocal)) {
          this.error.startDate = this.$t("error.invalid_time_interval");
          this.error.startTime = this.$t("error.invalid_time_interval");
          this.error.endDate = this.$t("error.invalid_time_interval");
          this.error.endTime = this.$t("error.invalid_time_interval");
          isValidationOk = false;
        }
      }
      if (this.maxResults < 1 || this.maxResults > this.MAX_RESULTS_LIMIT) {
        this.error.maxResults = this.$t("error.must_be_between", {
          min: 1,
          max: this.MAX_RESULTS_LIMIT,
        });
        isValidationOk = false;
      }
      return isValidationOk;
    },
    async searchLogs() {
      if (!this.validateSearchLogs()) {
        return;
      }
      const auditParams = this.getAuditParams();
      this.loading.auditTrail = true;
      const [err, response] = await to(
        this.getAuditTrail(
          auditParams.users,
          auditParams.actions,
          auditParams.data,
          auditParams.from,
          auditParams.to,
          auditParams.limit
        )
      );
      this.loading.auditTrail = false;
      if (err) {
        console.error("error retrieving audit trail", err);
        this.error.auditTrail = this.getErrorMessage(err);
        return;
      }
      const audits = response.data.data.audits ? response.data.data.audits : [];
      this.logs = audits.map((audit) => {
        const localTimestamp = this.formatDate(
          this.parseIsoDate(audit.timestamp),
          "yyyy-MM-dd HH:mm:ss"
        );
        return {
          timestamp: localTimestamp,
          user: audit.user,
          action: audit.action,
          auditInfo: audit.data ? audit.data : "",
          auditInfoCollapsed: true,
          id: audit.id,
        };
      });
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../styles/carbon-utils";
.interval-date {
  display: inline-flex;
  margin-right: $spacing-06;
}
.interval-time {
  display: inline-flex;
}
.audit-info-collapsed {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 15rem;
}
.audit-info-pre {
  white-space: pre-wrap;
}
.expand-audit-info-button {
  float: right;
}
.search-button {
  margin-top: $spacing-05;
  margin-bottom: $spacing-07;
}
</style>
</file>

<file path="core/ui/src/views/Backup.vue">
<template>
  <div>
    <cv-grid fullWidth>
      <cv-row>
        <cv-column class="page-title">
          <h2>
            {{ $t("backup.title") }}
          </h2>
        </cv-column>
      </cv-row>
      <cv-row>
        <cv-column>
          <NsTabs
            :container="false"
            :aria-label="$t('common.tab_navigation')"
            :noDefaultToFirst="true"
            @tab-selected="tabSelected"
          >
            <cv-tab
              id="tab-1"
              :label="$t('backup.backup')"
              :selected="q.view === 'backup'"
            >
              <cv-row class="mg-bottom-lg">
                <cv-column
                  v-if="
                    !isSetClusterBackupPassword &&
                    !loading.listBackupRepositories
                  "
                >
                  <cv-tile kind="standard" :light="true">
                    <NsEmptyState
                      :title="$t('backup.cluster_backup_password_warning')"
                    >
                      <template #pictogram>
                        <ExclamationMarkPictogram />
                      </template>
                      <template #description>
                        <div class="mg-bottom-lg">
                          <p>
                            {{
                              $t(
                                "backup.cluster_backup_password_warning_description_1"
                              )
                            }}
                          </p>
                          <p>
                            {{
                              $t(
                                "backup.cluster_backup_password_warning_description_2"
                              )
                            }}
                          </p>
                        </div>
                        <div>
                          <NsButton
                            kind="primary"
                            :icon="Password20"
                            @click="showBackupPasswordModal()"
                            >{{ $t("backup.set_cluster_backup_password") }}
                          </NsButton>
                        </div>
                      </template>
                    </NsEmptyState>
                  </cv-tile>
                </cv-column>
                <cv-column
                  v-if="
                    isSetClusterBackupPassword &&
                    !loading.listBackupRepositories
                  "
                >
                  <div class="mg-bottom-md">
                    {{
                      $t(
                        "backup.configure_manage_backups_for_your_applications"
                      )
                    }}
                  </div>
                  <NsButton
                    kind="primary"
                    :icon="Download20"
                    @click="downloadClusterConfigurationBackup()"
                    :disabled="loading.downloadClusterBackup"
                    :loading="loading.downloadClusterBackup"
                    >{{ $t("backup.download_cluster_configuration_backup") }}
                  </NsButton>
                  <NsButton
                    kind="tertiary"
                    :icon="Password20"
                    @click="showBackupPasswordModal()"
                    class="mg-left-md"
                    :disabled="loading.downloadClusterBackup"
                    >{{ $t("backup.change_cluster_backup_password") }}
                  </NsButton>
                </cv-column>
              </cv-row>
              <cv-row v-if="isSetClusterBackupPassword">
                <cv-column>
                  <h4 class="mg-bottom-lg">
                    {{ $t("backup.backup_destinations") }}
                  </h4>
                  <div class="mg-bottom-lg">
                    {{
                      $t("backup.backup_destinations_stored_local_or_remote")
                    }}
                  </div>
                </cv-column>
              </cv-row>
              <template
                v-if="loading.listBackupRepositories || loading.listBackups"
              >
                <cv-row>
                  <cv-column>
                    <cv-skeleton-text heading width="40%"></cv-skeleton-text>
                  </cv-column>
                </cv-row>
                <cv-row>
                  <cv-column>
                    <div
                      class="card-grid grid-cols-1 md:grid-cols-2 2xl:grid-cols-3 3xl:grid-cols-4"
                    >
                      <cv-tile v-for="index in 2" :key="index" light>
                        <cv-skeleton-text
                          :paragraph="true"
                          :line-count="8"
                        ></cv-skeleton-text>
                      </cv-tile>
                    </div>
                  </cv-column>
                </cv-row>
                <cv-row>
                  <cv-column>
                    <cv-skeleton-text heading width="40%"></cv-skeleton-text>
                  </cv-column>
                </cv-row>
                <cv-row>
                  <cv-column>
                    <div
                      class="card-grid grid-cols-1 md:grid-cols-2 2xl:grid-cols-3 3xl:grid-cols-4"
                    >
                      <cv-tile v-for="index in 2" :key="index" light>
                        <cv-skeleton-text
                          :paragraph="true"
                          :line-count="8"
                        ></cv-skeleton-text>
                      </cv-tile>
                    </div>
                  </cv-column>
                </cv-row>
              </template>
              <cv-row
                v-else-if="isSetClusterBackupPassword && !repositories.length"
              >
                <cv-column>
                  <cv-tile kind="standard" :light="true">
                    <NsEmptyState :title="$t('backup.no_backup_repository')">
                      <template #pictogram>
                        <HardDrivePictogram />
                      </template>
                      <template #description>
                        <div>
                          {{ $t("backup.empty_state_repository_description") }}
                        </div>
                        <NsButton
                          kind="secondary"
                          :icon="Add20"
                          @click="showAddRepoModal()"
                          class="empty-state-button mb-4"
                          >{{ $t("backup.add_repository") }}
                        </NsButton>
                        <div>
                          <NsButton
                            kind="ghost"
                            :icon="Upload20"
                            @click="showImportBackupDestinationModal()"
                            >{{ $t("backup.import_destinations") }}
                          </NsButton>
                        </div>
                      </template>
                    </NsEmptyState>
                  </cv-tile>
                </cv-column>
              </cv-row>
              <template v-if="isSetClusterBackupPassword">
                <cv-row v-if="!loading.listBackups && erroredBackups.length">
                  <cv-column>
                    <NsInlineNotification
                      kind="error"
                      :title="$t('backup.some_backups_failed')"
                      :description="$t('backup.errored_backups_description')"
                      :showCloseButton="false"
                    />
                  </cv-column>
                </cv-row>
                <cv-row v-if="!loading.listBackups && disabledBackups.length">
                  <cv-column>
                    <NsInlineNotification
                      kind="warning"
                      :title="$t('backup.disabled_backups')"
                      :description="
                        $tc(
                          'backup.disabled_backups_description',
                          disabledBackups.length,
                          {
                            num: disabledBackups.length,
                          }
                        )
                      "
                      :showCloseButton="false"
                    />
                  </cv-column>
                </cv-row>
                <cv-row v-if="error.listBackupRepositories">
                  <cv-column>
                    <NsInlineNotification
                      kind="error"
                      :title="$t('action.list-backup-repositories')"
                      :description="error.listBackupRepositories"
                      :showCloseButton="false"
                    />
                  </cv-column>
                </cv-row>
                <cv-row v-if="error.removeBackupRepository">
                  <cv-column>
                    <NsInlineNotification
                      kind="error"
                      :title="$t('action.remove-backup-repository')"
                      :description="error.removeBackupRepository"
                      :showCloseButton="false"
                    />
                  </cv-column>
                </cv-row>
                <cv-row v-if="repositories.length" class="toolbar">
                  <cv-column>
                    <NsButton
                      kind="secondary"
                      :icon="Add20"
                      @click="showAddRepoModal()"
                      >{{ $t("backup.add_repository") }}
                    </NsButton>
                    <NsButton
                      kind="tertiary"
                      :icon="Upload20"
                      @click="showImportBackupDestinationModal()"
                      class="mg-left-md"
                      >{{ $t("backup.import_destinations") }}
                    </NsButton>
                  </cv-column>
                </cv-row>
                <cv-row>
                  <cv-column>
                    <div
                      class="card-grid grid-cols-1 md:grid-cols-2 2xl:grid-cols-3 3xl:grid-cols-4"
                    >
                      <NsInfoCard
                        v-for="repo in repositories"
                        :key="repo.id"
                        light
                        :title="repo.name"
                        :icon="DataBase32"
                      >
                        <template #menu>
                          <cv-overflow-menu
                            :flip-menu="true"
                            tip-position="top"
                            tip-alignment="end"
                            class="top-right-overflow-menu"
                          >
                            <cv-overflow-menu-item
                              danger
                              @click="showDeleteRepoModal(repo)"
                            >
                              <NsMenuItem
                                :icon="TrashCan20"
                                :label="$t('common.delete')"
                              />
                            </cv-overflow-menu-item>
                          </cv-overflow-menu>
                        </template>
                        <template #content>
                          <div class="card-content-backup">
                            <div class="row">
                              {{ $t("backup." + repo.provider) }}
                            </div>
                            <div class="row">
                              {{ repo.url }}
                            </div>
                            <div class="row actions">
                              <NsButton
                                kind="ghost"
                                :icon="Edit20"
                                @click="showEditRepoModal(repo)"
                                >{{ $t("common.edit") }}
                              </NsButton>
                            </div>
                          </div>
                        </template>
                      </NsInfoCard>
                    </div>
                  </cv-column>
                </cv-row>
                <cv-row>
                  <cv-column>
                    <h4 class="mg-bottom-lg">{{ $t("backup.schedules") }}</h4>
                    <div class="mg-bottom-lg">
                      {{
                        $t(
                          "backup.schedule_regular_backups_and_select_the_applications_to_include"
                        )
                      }}
                    </div>
                  </cv-column>
                </cv-row>
                <cv-row>
                  <cv-column>
                    <NsButton
                      kind="secondary"
                      :icon="Add20"
                      class="mg-bottom-md"
                      @click="showCreateOrEditBackupModal('')"
                      :disabled="!repositories.length"
                      >{{ $t("backup.schedule_backup") }}
                    </NsButton>
                  </cv-column>
                </cv-row>
                <cv-row v-if="error.listBackups">
                  <cv-column>
                    <NsInlineNotification
                      kind="error"
                      :title="$t('action.list-backups')"
                      :description="error.listBackups"
                      :showCloseButton="false"
                    />
                  </cv-column>
                </cv-row>
                <cv-row v-if="error.removeBackup">
                  <cv-column>
                    <NsInlineNotification
                      kind="error"
                      :title="$t('action.remove-backup')"
                      :description="error.removeBackup"
                      :showCloseButton="false"
                    />
                  </cv-column>
                </cv-row>
                <cv-row v-if="error.runBackup">
                  <cv-column>
                    <NsInlineNotification
                      kind="error"
                      :title="$t('action.run-backup')"
                      :description="error.runBackup"
                      :showCloseButton="false"
                    />
                  </cv-column>
                </cv-row>
                <cv-row v-if="error.alterBackup">
                  <cv-column>
                    <NsInlineNotification
                      kind="error"
                      :title="$t('action.alter-backup')"
                      :description="error.alterBackup"
                      :showCloseButton="false"
                    />
                  </cv-column>
                </cv-row>
                <cv-row v-if="error.cancelBackup">
                  <cv-column>
                    <NsInlineNotification
                      kind="error"
                      :title="$t('backup.cancel_backup_failed')"
                      :description="error.cancelBackup"
                      :showCloseButton="false"
                    />
                  </cv-column>
                </cv-row>
                <template v-if="repositories.length">
                  <cv-row v-if="!backups.length">
                    <cv-column>
                      <cv-row
                        v-if="
                          !loading.listBackups && unconfiguredInstances.length
                        "
                      >
                        <cv-column>
                          <NsInlineNotification
                            kind="warning"
                            :title="$t('backup.app_instances_not_backed_up')"
                            :description="
                              $tc(
                                'backup.app_instances_not_backed_up_description',
                                unconfiguredInstances.length,
                                {
                                  numInstances: unconfiguredInstances.length,
                                }
                              )
                            "
                            :showCloseButton="false"
                          />
                        </cv-column>
                      </cv-row>
                    </cv-column>
                  </cv-row>
                  <template v-else>
                    <cv-row
                      v-if="
                        !loading.listBackups && unconfiguredInstances.length
                      "
                    >
                      <cv-column>
                        <NsInlineNotification
                          kind="warning"
                          :title="$t('backup.app_instances_not_backed_up')"
                          :description="
                            $tc(
                              'backup.app_instances_not_backed_up_description',
                              unconfiguredInstances.length,
                              {
                                numInstances: unconfiguredInstances.length,
                              }
                            )
                          "
                          :showCloseButton="false"
                        />
                      </cv-column>
                    </cv-row>
                    <cv-row>
                      <cv-column>
                        <div
                          class="card-grid grid-cols-1 md:grid-cols-2 2xl:grid-cols-3 3xl:grid-cols-4"
                        >
                          <NsInfoCard
                            v-for="backup in backups"
                            :key="backup.id"
                            light
                            :title="backup.name"
                            :icon="Save32"
                          >
                            <template #menu>
                              <cv-overflow-menu
                                :flip-menu="true"
                                tip-position="top"
                                tip-alignment="end"
                                class="top-right-overflow-menu"
                              >
                                <cv-overflow-menu-item
                                  v-if="isBackupRunning(backup.id)"
                                  @click="cancelBackupTask(backup)"
                                >
                                  <NsMenuItem
                                    :icon="Close20"
                                    :label="$t('backup.cancel_backup')"
                                  />
                                </cv-overflow-menu-item>
                                <template v-else>
                                  <cv-overflow-menu-item
                                    @click="runBackup(backup)"
                                    :disabled="!backup.enabled"
                                  >
                                    <NsMenuItem
                                      :icon="Save20"
                                      :label="$t('backup.run_backup_now')"
                                    />
                                  </cv-overflow-menu-item>
                                  <cv-overflow-menu-item
                                    @click="toggleBackupStatus(backup)"
                                    :disabled="loading.alterBackup"
                                  >
                                    <NsMenuItem
                                      :icon="Power20"
                                      :label="
                                        backup.enabled
                                          ? $t('common.disable')
                                          : $t('common.enable')
                                      "
                                    />
                                  </cv-overflow-menu-item>
                                  <cv-overflow-menu-item
                                    @click="showEditBackupModal(backup)"
                                  >
                                    <NsMenuItem
                                      :icon="Edit20"
                                      :label="$t('common.edit')"
                                    />
                                  </cv-overflow-menu-item>
                                  <NsMenuDivider />
                                  <cv-overflow-menu-item
                                    danger
                                    @click="showDeleteBackupModal(backup)"
                                  >
                                    <NsMenuItem
                                      :icon="TrashCan20"
                                      :label="$t('common.delete')"
                                    />
                                  </cv-overflow-menu-item>
                                </template>
                              </cv-overflow-menu>
                            </template>
                            <template #content>
                              <div class="card-content-backup">
                                <div class="row instance-to-repo">
                                  <div class="backup-source">
                                    <NsSvg :svg="Application20" class="icon" />
                                    <span v-if="backup.instances.length === 1">
                                      {{
                                        backup.instances[0].ui_name
                                          ? backup.instances[0].ui_name
                                          : backup.instances[0].module_id
                                      }}
                                    </span>
                                    <span v-else>
                                      {{
                                        backup.instances.length +
                                        " " +
                                        $tc(
                                          "backup.applications",
                                          backup.instances.length
                                        )
                                      }}
                                    </span>
                                  </div>
                                  <div class="arrow-right">
                                    <NsSvg :svg="ArrowRight20" />
                                  </div>
                                  <div class="backup-destination">
                                    <NsSvg :svg="DataBase20" class="icon" />
                                    <span :title="$t('backup.repository')">{{
                                      backup.repoName
                                    }}</span>
                                  </div>
                                </div>
                                <div class="row">
                                  <cv-tag
                                    v-if="backup.enabled"
                                    kind="green"
                                    :label="$t('common.enabled')"
                                    :title="$t('backup.backup_enabled')"
                                  ></cv-tag>
                                  <cv-tag
                                    v-else
                                    kind="high-contrast"
                                    :label="$t('common.disabled')"
                                    :title="$t('backup.backup_disabled')"
                                  ></cv-tag>
                                </div>
                                <div
                                  v-if="backup.errorInstances.length"
                                  class="row icon-and-text"
                                >
                                  <NsSvg
                                    :svg="ErrorFilled16"
                                    class="icon ns-error"
                                  />
                                  <span>
                                    {{
                                      $tc(
                                        "backup.backup_of_instances_failed_c",
                                        backup.errorInstances.length,
                                        {
                                          instance: backup.errorInstances[0]
                                            .ui_name
                                            ? backup.errorInstances[0].ui_name
                                            : backup.errorInstances[0]
                                                .module_id,
                                          num: backup.errorInstances.length,
                                        }
                                      )
                                    }}
                                  </span>
                                </div>
                                <div class="row actions">
                                  <NsButton
                                    kind="ghost"
                                    :icon="ArrowRight20"
                                    @click="showBackupDetailsModal(backup)"
                                    >{{ $t("common.see_details") }}
                                  </NsButton>
                                </div>
                              </div>
                            </template>
                          </NsInfoCard>
                        </div>
                      </cv-column>
                    </cv-row>
                  </template>
                </template>
              </template>
            </cv-tab>
            <cv-tab
              id="tab-2"
              :label="$t('backup.restore')"
              :selected="q.view === 'restore'"
            >
              <cv-row>
                <cv-column>
                  <div class="mg-bottom-sm">
                    {{
                      $t("backup.restore_applications_from_existing_backups")
                    }}
                  </div>
                  <div class="mg-bottom-lg">
                    {{
                      $t(
                        "backup.cluster_restore_during_initial_cluster_configuration"
                      )
                    }}
                  </div>
                </cv-column>
              </cv-row>
              <cv-row>
                <cv-column>
                  <template
                    v-if="!repositories.length && isSetClusterBackupPassword"
                  >
                    <NsInlineNotification
                      kind="warning"
                      class="mg-bottom-lg"
                      :title="$t('backup.no_backup_repository')"
                      :description="
                        $t(
                          'backup.configure_a_destination_to_restore_applications'
                        )
                      "
                      :actionLabel="$t('backup.add_repository')"
                      @action="goToBackupTabAndOpenRepositoryModal()"
                      :showCloseButton="false"
                    />
                  </template>
                  <template v-if="!isSetClusterBackupPassword">
                    <NsInlineNotification
                      kind="warning"
                      class="mg-bottom-lg"
                      :title="$t('backup.no_cluster_backup_password')"
                      :description="
                        $t(
                          'backup.set_cluster_backup_password_to_restore_applications'
                        )
                      "
                      :actionLabel="$t('backup.set_cluster_backup_password')"
                      @action="showBackupTabAndOpenPasswordModal()"
                      :showCloseButton="false"
                    />
                  </template>
                  <NsButton
                    kind="primary"
                    :icon="Reset20"
                    @click="showRestoreModal()"
                    :disabled="!repositories.length"
                    class="mg-bottom-xlg"
                    >{{ $t("backup.restore_app") }}
                  </NsButton>
                </cv-column>
              </cv-row>
            </cv-tab>
          </NsTabs>
        </cv-column>
      </cv-row>
    </cv-grid>
    <NsDangerDeleteModal
      :isShown="isShownDeleteRepoModal"
      :name="currentRepo.name"
      :title="$t('backup.delete_destination')"
      :isWarningShown="false"
      :description="
        $t('backup.delete_repository_confirm', {
          name: currentRepo.name,
        })
      "
      :deleteLabel="$t('common.delete')"
      :typeToConfirm="$t('common.type_to_confirm', { name: currentRepo.name })"
      @hide="hideDeleteRepoModal"
      @confirmDelete="deleteRepo(currentRepo)"
    >
      <template slot="description">
        <NsInlineNotification
          kind="warning"
          :title="$t('backup.delete_repo_notice_title')"
          :showCloseButton="false"
          :loadingAction="loading.downloadClusterBackupNotice"
          v-if="currentRepo.password"
          @action="downloadClusterConfigurationBackup(false, true)"
          :actionLabel="$t('backup.download_cluster_configuration_backup')"
          :description="$t('backup.delete_repo_notice_description')"
        />
        <p class="mg-top-sm">
          {{
            $t("backup.delete_repository_confirm", {
              name: currentRepo.name,
            })
          }}
        </p>
      </template>
      <template slot="explanation">
        <p class="mg-top-sm">{{ $t("backup.delete_repo_explanation_1") }}</p>
      </template>
    </NsDangerDeleteModal>
    <AddRepositoryModal
      :isShown="q.isShownAddRepoModal"
      :repositories="repositories"
      @hide="hideAddRepoModal"
      @repoCreated="listBackupRepositories"
    />
    <CreateOrEditBackupModal
      :isShown="isShownCreateOrEditBackupModal"
      :isEditing="isEditingBackup"
      :repositories="repositories"
      :instanceSelection="instanceSelection"
      :instancesNotBackedUp="unconfiguredInstances"
      :backup="currentBackup"
      :backups="backups"
      @hide="hideCreateOrEditBackupModal"
      @backupCreated="onBackupCreated"
      @backupAltered="onBackupAltered"
    />
    <NsDangerDeleteModal
      :isShown="isShownDeleteBackupModal"
      :name="currentBackup.name"
      :title="$t('backup.delete_scheduled_backup')"
      :warning="$t('common.please_read_carefully')"
      :description="
        $t('backup.delete_scheduled_backup_confirm', {
          name: currentBackup.name,
        })
      "
      :typeToConfirm="
        $t('common.type_to_confirm', { name: currentBackup.name })
      "
      @hide="hideDeleteBackupModal"
      @confirmDelete="deleteBackup(currentBackup)"
    >
      <template slot="explanation">
        <p v-if="currentBackup.instances.length" class="mg-top-sm">
          {{
            $tc(
              "backup.delete_backup_explanation_1",
              currentBackup.instances.length,
              {
                numInstances: currentBackup.instances.length,
                instanceName: currentBackup.instances[0].ui_name
                  ? currentBackup.instances[0].ui_name
                  : currentBackup.instances[0].module_id,
              }
            )
          }}
        </p>
        <p class="mg-top-sm">{{ $t("backup.delete_backup_explanation_2") }}</p>
      </template>
    </NsDangerDeleteModal>
    <EditRepositoryModal
      :isShown="isShownEditRepoModal"
      :repository="currentRepo"
      @hide="hideEditRepoModal"
      @repoAltered="listBackupRepositories"
    />
    <BackupDetailsModal
      :isShown="isShownBackupDetailsModal"
      :backup="currentBackup"
      @hide="hideBackupDetailsModal"
    />
    <RestoreSingleInstanceModal
      :isShown="isShownRestoreModal"
      @hide="hideRestoreModal"
    />
    <BackupPasswordModal
      :isShown="isShownBackupPasswordModal"
      @hide="hideBackupPasswordModal"
      @password-set.once="reloadBackupRepositories"
    />
    <ImportBackupDestinationModal
      :visible="isShownImportBackupDestinationModal"
      :loading="isLoadingImportBackupDestination"
      :backupFileError="importBackupDestinationFileError"
      @import-backup-submit="onImportBackupSubmit"
      @hide="hideImportBackupDestinationModal"
    />
  </div>
</template>
⋮----
{{ $t("backup.title") }}
⋮----
<template #pictogram>
                        <ExclamationMarkPictogram />
                      </template>
<template #description>
                        <div class="mg-bottom-lg">
                          <p>
                            {{
                              $t(
                                "backup.cluster_backup_password_warning_description_1"
                              )
                            }}
                          </p>
                          <p>
                            {{
                              $t(
                                "backup.cluster_backup_password_warning_description_2"
                              )
                            }}
                          </p>
                        </div>
                        <div>
                          <NsButton
                            kind="primary"
                            :icon="Password20"
                            @click="showBackupPasswordModal()"
                            >{{ $t("backup.set_cluster_backup_password") }}
                          </NsButton>
                        </div>
                      </template>
⋮----
{{
                              $t(
                                "backup.cluster_backup_password_warning_description_1"
                              )
                            }}
⋮----
{{
                              $t(
                                "backup.cluster_backup_password_warning_description_2"
                              )
                            }}
⋮----
>{{ $t("backup.set_cluster_backup_password") }}
⋮----
{{
                      $t(
                        "backup.configure_manage_backups_for_your_applications"
                      )
                    }}
⋮----
>{{ $t("backup.download_cluster_configuration_backup") }}
⋮----
>{{ $t("backup.change_cluster_backup_password") }}
⋮----
{{ $t("backup.backup_destinations") }}
⋮----
{{
                      $t("backup.backup_destinations_stored_local_or_remote")
                    }}
⋮----
<template
                v-if="loading.listBackupRepositories || loading.listBackups"
              >
                <cv-row>
                  <cv-column>
                    <cv-skeleton-text heading width="40%"></cv-skeleton-text>
                  </cv-column>
                </cv-row>
                <cv-row>
                  <cv-column>
                    <div
                      class="card-grid grid-cols-1 md:grid-cols-2 2xl:grid-cols-3 3xl:grid-cols-4"
                    >
                      <cv-tile v-for="index in 2" :key="index" light>
                        <cv-skeleton-text
                          :paragraph="true"
                          :line-count="8"
                        ></cv-skeleton-text>
                      </cv-tile>
                    </div>
                  </cv-column>
                </cv-row>
                <cv-row>
                  <cv-column>
                    <cv-skeleton-text heading width="40%"></cv-skeleton-text>
                  </cv-column>
                </cv-row>
                <cv-row>
                  <cv-column>
                    <div
                      class="card-grid grid-cols-1 md:grid-cols-2 2xl:grid-cols-3 3xl:grid-cols-4"
                    >
                      <cv-tile v-for="index in 2" :key="index" light>
                        <cv-skeleton-text
                          :paragraph="true"
                          :line-count="8"
                        ></cv-skeleton-text>
                      </cv-tile>
                    </div>
                  </cv-column>
                </cv-row>
              </template>
⋮----
<template #pictogram>
                        <HardDrivePictogram />
                      </template>
<template #description>
                        <div>
                          {{ $t("backup.empty_state_repository_description") }}
                        </div>
                        <NsButton
                          kind="secondary"
                          :icon="Add20"
                          @click="showAddRepoModal()"
                          class="empty-state-button mb-4"
                          >{{ $t("backup.add_repository") }}
                        </NsButton>
                        <div>
                          <NsButton
                            kind="ghost"
                            :icon="Upload20"
                            @click="showImportBackupDestinationModal()"
                            >{{ $t("backup.import_destinations") }}
                          </NsButton>
                        </div>
                      </template>
⋮----
{{ $t("backup.empty_state_repository_description") }}
⋮----
>{{ $t("backup.add_repository") }}
⋮----
>{{ $t("backup.import_destinations") }}
⋮----
<template v-if="isSetClusterBackupPassword">
                <cv-row v-if="!loading.listBackups && erroredBackups.length">
                  <cv-column>
                    <NsInlineNotification
                      kind="error"
                      :title="$t('backup.some_backups_failed')"
                      :description="$t('backup.errored_backups_description')"
                      :showCloseButton="false"
                    />
                  </cv-column>
                </cv-row>
                <cv-row v-if="!loading.listBackups && disabledBackups.length">
                  <cv-column>
                    <NsInlineNotification
                      kind="warning"
                      :title="$t('backup.disabled_backups')"
                      :description="
                        $tc(
                          'backup.disabled_backups_description',
                          disabledBackups.length,
                          {
                            num: disabledBackups.length,
                          }
                        )
                      "
                      :showCloseButton="false"
                    />
                  </cv-column>
                </cv-row>
                <cv-row v-if="error.listBackupRepositories">
                  <cv-column>
                    <NsInlineNotification
                      kind="error"
                      :title="$t('action.list-backup-repositories')"
                      :description="error.listBackupRepositories"
                      :showCloseButton="false"
                    />
                  </cv-column>
                </cv-row>
                <cv-row v-if="error.removeBackupRepository">
                  <cv-column>
                    <NsInlineNotification
                      kind="error"
                      :title="$t('action.remove-backup-repository')"
                      :description="error.removeBackupRepository"
                      :showCloseButton="false"
                    />
                  </cv-column>
                </cv-row>
                <cv-row v-if="repositories.length" class="toolbar">
                  <cv-column>
                    <NsButton
                      kind="secondary"
                      :icon="Add20"
                      @click="showAddRepoModal()"
                      >{{ $t("backup.add_repository") }}
                    </NsButton>
                    <NsButton
                      kind="tertiary"
                      :icon="Upload20"
                      @click="showImportBackupDestinationModal()"
                      class="mg-left-md"
                      >{{ $t("backup.import_destinations") }}
                    </NsButton>
                  </cv-column>
                </cv-row>
                <cv-row>
                  <cv-column>
                    <div
                      class="card-grid grid-cols-1 md:grid-cols-2 2xl:grid-cols-3 3xl:grid-cols-4"
                    >
                      <NsInfoCard
                        v-for="repo in repositories"
                        :key="repo.id"
                        light
                        :title="repo.name"
                        :icon="DataBase32"
                      >
                        <template #menu>
                          <cv-overflow-menu
                            :flip-menu="true"
                            tip-position="top"
                            tip-alignment="end"
                            class="top-right-overflow-menu"
                          >
                            <cv-overflow-menu-item
                              danger
                              @click="showDeleteRepoModal(repo)"
                            >
                              <NsMenuItem
                                :icon="TrashCan20"
                                :label="$t('common.delete')"
                              />
                            </cv-overflow-menu-item>
                          </cv-overflow-menu>
                        </template>
                        <template #content>
                          <div class="card-content-backup">
                            <div class="row">
                              {{ $t("backup." + repo.provider) }}
                            </div>
                            <div class="row">
                              {{ repo.url }}
                            </div>
                            <div class="row actions">
                              <NsButton
                                kind="ghost"
                                :icon="Edit20"
                                @click="showEditRepoModal(repo)"
                                >{{ $t("common.edit") }}
                              </NsButton>
                            </div>
                          </div>
                        </template>
                      </NsInfoCard>
                    </div>
                  </cv-column>
                </cv-row>
                <cv-row>
                  <cv-column>
                    <h4 class="mg-bottom-lg">{{ $t("backup.schedules") }}</h4>
                    <div class="mg-bottom-lg">
                      {{
                        $t(
                          "backup.schedule_regular_backups_and_select_the_applications_to_include"
                        )
                      }}
                    </div>
                  </cv-column>
                </cv-row>
                <cv-row>
                  <cv-column>
                    <NsButton
                      kind="secondary"
                      :icon="Add20"
                      class="mg-bottom-md"
                      @click="showCreateOrEditBackupModal('')"
                      :disabled="!repositories.length"
                      >{{ $t("backup.schedule_backup") }}
                    </NsButton>
                  </cv-column>
                </cv-row>
                <cv-row v-if="error.listBackups">
                  <cv-column>
                    <NsInlineNotification
                      kind="error"
                      :title="$t('action.list-backups')"
                      :description="error.listBackups"
                      :showCloseButton="false"
                    />
                  </cv-column>
                </cv-row>
                <cv-row v-if="error.removeBackup">
                  <cv-column>
                    <NsInlineNotification
                      kind="error"
                      :title="$t('action.remove-backup')"
                      :description="error.removeBackup"
                      :showCloseButton="false"
                    />
                  </cv-column>
                </cv-row>
                <cv-row v-if="error.runBackup">
                  <cv-column>
                    <NsInlineNotification
                      kind="error"
                      :title="$t('action.run-backup')"
                      :description="error.runBackup"
                      :showCloseButton="false"
                    />
                  </cv-column>
                </cv-row>
                <cv-row v-if="error.alterBackup">
                  <cv-column>
                    <NsInlineNotification
                      kind="error"
                      :title="$t('action.alter-backup')"
                      :description="error.alterBackup"
                      :showCloseButton="false"
                    />
                  </cv-column>
                </cv-row>
                <cv-row v-if="error.cancelBackup">
                  <cv-column>
                    <NsInlineNotification
                      kind="error"
                      :title="$t('backup.cancel_backup_failed')"
                      :description="error.cancelBackup"
                      :showCloseButton="false"
                    />
                  </cv-column>
                </cv-row>
                <template v-if="repositories.length">
                  <cv-row v-if="!backups.length">
                    <cv-column>
                      <cv-row
                        v-if="
                          !loading.listBackups && unconfiguredInstances.length
                        "
                      >
                        <cv-column>
                          <NsInlineNotification
                            kind="warning"
                            :title="$t('backup.app_instances_not_backed_up')"
                            :description="
                              $tc(
                                'backup.app_instances_not_backed_up_description',
                                unconfiguredInstances.length,
                                {
                                  numInstances: unconfiguredInstances.length,
                                }
                              )
                            "
                            :showCloseButton="false"
                          />
                        </cv-column>
                      </cv-row>
                    </cv-column>
                  </cv-row>
                  <template v-else>
                    <cv-row
                      v-if="
                        !loading.listBackups && unconfiguredInstances.length
                      "
                    >
                      <cv-column>
                        <NsInlineNotification
                          kind="warning"
                          :title="$t('backup.app_instances_not_backed_up')"
                          :description="
                            $tc(
                              'backup.app_instances_not_backed_up_description',
                              unconfiguredInstances.length,
                              {
                                numInstances: unconfiguredInstances.length,
                              }
                            )
                          "
                          :showCloseButton="false"
                        />
                      </cv-column>
                    </cv-row>
                    <cv-row>
                      <cv-column>
                        <div
                          class="card-grid grid-cols-1 md:grid-cols-2 2xl:grid-cols-3 3xl:grid-cols-4"
                        >
                          <NsInfoCard
                            v-for="backup in backups"
                            :key="backup.id"
                            light
                            :title="backup.name"
                            :icon="Save32"
                          >
                            <template #menu>
                              <cv-overflow-menu
                                :flip-menu="true"
                                tip-position="top"
                                tip-alignment="end"
                                class="top-right-overflow-menu"
                              >
                                <cv-overflow-menu-item
                                  v-if="isBackupRunning(backup.id)"
                                  @click="cancelBackupTask(backup)"
                                >
                                  <NsMenuItem
                                    :icon="Close20"
                                    :label="$t('backup.cancel_backup')"
                                  />
                                </cv-overflow-menu-item>
                                <template v-else>
                                  <cv-overflow-menu-item
                                    @click="runBackup(backup)"
                                    :disabled="!backup.enabled"
                                  >
                                    <NsMenuItem
                                      :icon="Save20"
                                      :label="$t('backup.run_backup_now')"
                                    />
                                  </cv-overflow-menu-item>
                                  <cv-overflow-menu-item
                                    @click="toggleBackupStatus(backup)"
                                    :disabled="loading.alterBackup"
                                  >
                                    <NsMenuItem
                                      :icon="Power20"
                                      :label="
                                        backup.enabled
                                          ? $t('common.disable')
                                          : $t('common.enable')
                                      "
                                    />
                                  </cv-overflow-menu-item>
                                  <cv-overflow-menu-item
                                    @click="showEditBackupModal(backup)"
                                  >
                                    <NsMenuItem
                                      :icon="Edit20"
                                      :label="$t('common.edit')"
                                    />
                                  </cv-overflow-menu-item>
                                  <NsMenuDivider />
                                  <cv-overflow-menu-item
                                    danger
                                    @click="showDeleteBackupModal(backup)"
                                  >
                                    <NsMenuItem
                                      :icon="TrashCan20"
                                      :label="$t('common.delete')"
                                    />
                                  </cv-overflow-menu-item>
                                </template>
                              </cv-overflow-menu>
                            </template>
                            <template #content>
                              <div class="card-content-backup">
                                <div class="row instance-to-repo">
                                  <div class="backup-source">
                                    <NsSvg :svg="Application20" class="icon" />
                                    <span v-if="backup.instances.length === 1">
                                      {{
                                        backup.instances[0].ui_name
                                          ? backup.instances[0].ui_name
                                          : backup.instances[0].module_id
                                      }}
                                    </span>
                                    <span v-else>
                                      {{
                                        backup.instances.length +
                                        " " +
                                        $tc(
                                          "backup.applications",
                                          backup.instances.length
                                        )
                                      }}
                                    </span>
                                  </div>
                                  <div class="arrow-right">
                                    <NsSvg :svg="ArrowRight20" />
                                  </div>
                                  <div class="backup-destination">
                                    <NsSvg :svg="DataBase20" class="icon" />
                                    <span :title="$t('backup.repository')">{{
                                      backup.repoName
                                    }}</span>
                                  </div>
                                </div>
                                <div class="row">
                                  <cv-tag
                                    v-if="backup.enabled"
                                    kind="green"
                                    :label="$t('common.enabled')"
                                    :title="$t('backup.backup_enabled')"
                                  ></cv-tag>
                                  <cv-tag
                                    v-else
                                    kind="high-contrast"
                                    :label="$t('common.disabled')"
                                    :title="$t('backup.backup_disabled')"
                                  ></cv-tag>
                                </div>
                                <div
                                  v-if="backup.errorInstances.length"
                                  class="row icon-and-text"
                                >
                                  <NsSvg
                                    :svg="ErrorFilled16"
                                    class="icon ns-error"
                                  />
                                  <span>
                                    {{
                                      $tc(
                                        "backup.backup_of_instances_failed_c",
                                        backup.errorInstances.length,
                                        {
                                          instance: backup.errorInstances[0]
                                            .ui_name
                                            ? backup.errorInstances[0].ui_name
                                            : backup.errorInstances[0]
                                                .module_id,
                                          num: backup.errorInstances.length,
                                        }
                                      )
                                    }}
                                  </span>
                                </div>
                                <div class="row actions">
                                  <NsButton
                                    kind="ghost"
                                    :icon="ArrowRight20"
                                    @click="showBackupDetailsModal(backup)"
                                    >{{ $t("common.see_details") }}
                                  </NsButton>
                                </div>
                              </div>
                            </template>
                          </NsInfoCard>
                        </div>
                      </cv-column>
                    </cv-row>
                  </template>
                </template>
              </template>
⋮----
>{{ $t("backup.add_repository") }}
⋮----
>{{ $t("backup.import_destinations") }}
⋮----
<template #menu>
                          <cv-overflow-menu
                            :flip-menu="true"
                            tip-position="top"
                            tip-alignment="end"
                            class="top-right-overflow-menu"
                          >
                            <cv-overflow-menu-item
                              danger
                              @click="showDeleteRepoModal(repo)"
                            >
                              <NsMenuItem
                                :icon="TrashCan20"
                                :label="$t('common.delete')"
                              />
                            </cv-overflow-menu-item>
                          </cv-overflow-menu>
                        </template>
<template #content>
                          <div class="card-content-backup">
                            <div class="row">
                              {{ $t("backup." + repo.provider) }}
                            </div>
                            <div class="row">
                              {{ repo.url }}
                            </div>
                            <div class="row actions">
                              <NsButton
                                kind="ghost"
                                :icon="Edit20"
                                @click="showEditRepoModal(repo)"
                                >{{ $t("common.edit") }}
                              </NsButton>
                            </div>
                          </div>
                        </template>
⋮----
{{ $t("backup." + repo.provider) }}
⋮----
{{ repo.url }}
⋮----
>{{ $t("common.edit") }}
⋮----
<h4 class="mg-bottom-lg">{{ $t("backup.schedules") }}</h4>
⋮----
{{
                        $t(
                          "backup.schedule_regular_backups_and_select_the_applications_to_include"
                        )
                      }}
⋮----
>{{ $t("backup.schedule_backup") }}
⋮----
<template v-if="repositories.length">
                  <cv-row v-if="!backups.length">
                    <cv-column>
                      <cv-row
                        v-if="
                          !loading.listBackups && unconfiguredInstances.length
                        "
                      >
                        <cv-column>
                          <NsInlineNotification
                            kind="warning"
                            :title="$t('backup.app_instances_not_backed_up')"
                            :description="
                              $tc(
                                'backup.app_instances_not_backed_up_description',
                                unconfiguredInstances.length,
                                {
                                  numInstances: unconfiguredInstances.length,
                                }
                              )
                            "
                            :showCloseButton="false"
                          />
                        </cv-column>
                      </cv-row>
                    </cv-column>
                  </cv-row>
                  <template v-else>
                    <cv-row
                      v-if="
                        !loading.listBackups && unconfiguredInstances.length
                      "
                    >
                      <cv-column>
                        <NsInlineNotification
                          kind="warning"
                          :title="$t('backup.app_instances_not_backed_up')"
                          :description="
                            $tc(
                              'backup.app_instances_not_backed_up_description',
                              unconfiguredInstances.length,
                              {
                                numInstances: unconfiguredInstances.length,
                              }
                            )
                          "
                          :showCloseButton="false"
                        />
                      </cv-column>
                    </cv-row>
                    <cv-row>
                      <cv-column>
                        <div
                          class="card-grid grid-cols-1 md:grid-cols-2 2xl:grid-cols-3 3xl:grid-cols-4"
                        >
                          <NsInfoCard
                            v-for="backup in backups"
                            :key="backup.id"
                            light
                            :title="backup.name"
                            :icon="Save32"
                          >
                            <template #menu>
                              <cv-overflow-menu
                                :flip-menu="true"
                                tip-position="top"
                                tip-alignment="end"
                                class="top-right-overflow-menu"
                              >
                                <cv-overflow-menu-item
                                  v-if="isBackupRunning(backup.id)"
                                  @click="cancelBackupTask(backup)"
                                >
                                  <NsMenuItem
                                    :icon="Close20"
                                    :label="$t('backup.cancel_backup')"
                                  />
                                </cv-overflow-menu-item>
                                <template v-else>
                                  <cv-overflow-menu-item
                                    @click="runBackup(backup)"
                                    :disabled="!backup.enabled"
                                  >
                                    <NsMenuItem
                                      :icon="Save20"
                                      :label="$t('backup.run_backup_now')"
                                    />
                                  </cv-overflow-menu-item>
                                  <cv-overflow-menu-item
                                    @click="toggleBackupStatus(backup)"
                                    :disabled="loading.alterBackup"
                                  >
                                    <NsMenuItem
                                      :icon="Power20"
                                      :label="
                                        backup.enabled
                                          ? $t('common.disable')
                                          : $t('common.enable')
                                      "
                                    />
                                  </cv-overflow-menu-item>
                                  <cv-overflow-menu-item
                                    @click="showEditBackupModal(backup)"
                                  >
                                    <NsMenuItem
                                      :icon="Edit20"
                                      :label="$t('common.edit')"
                                    />
                                  </cv-overflow-menu-item>
                                  <NsMenuDivider />
                                  <cv-overflow-menu-item
                                    danger
                                    @click="showDeleteBackupModal(backup)"
                                  >
                                    <NsMenuItem
                                      :icon="TrashCan20"
                                      :label="$t('common.delete')"
                                    />
                                  </cv-overflow-menu-item>
                                </template>
                              </cv-overflow-menu>
                            </template>
                            <template #content>
                              <div class="card-content-backup">
                                <div class="row instance-to-repo">
                                  <div class="backup-source">
                                    <NsSvg :svg="Application20" class="icon" />
                                    <span v-if="backup.instances.length === 1">
                                      {{
                                        backup.instances[0].ui_name
                                          ? backup.instances[0].ui_name
                                          : backup.instances[0].module_id
                                      }}
                                    </span>
                                    <span v-else>
                                      {{
                                        backup.instances.length +
                                        " " +
                                        $tc(
                                          "backup.applications",
                                          backup.instances.length
                                        )
                                      }}
                                    </span>
                                  </div>
                                  <div class="arrow-right">
                                    <NsSvg :svg="ArrowRight20" />
                                  </div>
                                  <div class="backup-destination">
                                    <NsSvg :svg="DataBase20" class="icon" />
                                    <span :title="$t('backup.repository')">{{
                                      backup.repoName
                                    }}</span>
                                  </div>
                                </div>
                                <div class="row">
                                  <cv-tag
                                    v-if="backup.enabled"
                                    kind="green"
                                    :label="$t('common.enabled')"
                                    :title="$t('backup.backup_enabled')"
                                  ></cv-tag>
                                  <cv-tag
                                    v-else
                                    kind="high-contrast"
                                    :label="$t('common.disabled')"
                                    :title="$t('backup.backup_disabled')"
                                  ></cv-tag>
                                </div>
                                <div
                                  v-if="backup.errorInstances.length"
                                  class="row icon-and-text"
                                >
                                  <NsSvg
                                    :svg="ErrorFilled16"
                                    class="icon ns-error"
                                  />
                                  <span>
                                    {{
                                      $tc(
                                        "backup.backup_of_instances_failed_c",
                                        backup.errorInstances.length,
                                        {
                                          instance: backup.errorInstances[0]
                                            .ui_name
                                            ? backup.errorInstances[0].ui_name
                                            : backup.errorInstances[0]
                                                .module_id,
                                          num: backup.errorInstances.length,
                                        }
                                      )
                                    }}
                                  </span>
                                </div>
                                <div class="row actions">
                                  <NsButton
                                    kind="ghost"
                                    :icon="ArrowRight20"
                                    @click="showBackupDetailsModal(backup)"
                                    >{{ $t("common.see_details") }}
                                  </NsButton>
                                </div>
                              </div>
                            </template>
                          </NsInfoCard>
                        </div>
                      </cv-column>
                    </cv-row>
                  </template>
                </template>
⋮----
<template v-else>
                    <cv-row
                      v-if="
                        !loading.listBackups && unconfiguredInstances.length
                      "
                    >
                      <cv-column>
                        <NsInlineNotification
                          kind="warning"
                          :title="$t('backup.app_instances_not_backed_up')"
                          :description="
                            $tc(
                              'backup.app_instances_not_backed_up_description',
                              unconfiguredInstances.length,
                              {
                                numInstances: unconfiguredInstances.length,
                              }
                            )
                          "
                          :showCloseButton="false"
                        />
                      </cv-column>
                    </cv-row>
                    <cv-row>
                      <cv-column>
                        <div
                          class="card-grid grid-cols-1 md:grid-cols-2 2xl:grid-cols-3 3xl:grid-cols-4"
                        >
                          <NsInfoCard
                            v-for="backup in backups"
                            :key="backup.id"
                            light
                            :title="backup.name"
                            :icon="Save32"
                          >
                            <template #menu>
                              <cv-overflow-menu
                                :flip-menu="true"
                                tip-position="top"
                                tip-alignment="end"
                                class="top-right-overflow-menu"
                              >
                                <cv-overflow-menu-item
                                  v-if="isBackupRunning(backup.id)"
                                  @click="cancelBackupTask(backup)"
                                >
                                  <NsMenuItem
                                    :icon="Close20"
                                    :label="$t('backup.cancel_backup')"
                                  />
                                </cv-overflow-menu-item>
                                <template v-else>
                                  <cv-overflow-menu-item
                                    @click="runBackup(backup)"
                                    :disabled="!backup.enabled"
                                  >
                                    <NsMenuItem
                                      :icon="Save20"
                                      :label="$t('backup.run_backup_now')"
                                    />
                                  </cv-overflow-menu-item>
                                  <cv-overflow-menu-item
                                    @click="toggleBackupStatus(backup)"
                                    :disabled="loading.alterBackup"
                                  >
                                    <NsMenuItem
                                      :icon="Power20"
                                      :label="
                                        backup.enabled
                                          ? $t('common.disable')
                                          : $t('common.enable')
                                      "
                                    />
                                  </cv-overflow-menu-item>
                                  <cv-overflow-menu-item
                                    @click="showEditBackupModal(backup)"
                                  >
                                    <NsMenuItem
                                      :icon="Edit20"
                                      :label="$t('common.edit')"
                                    />
                                  </cv-overflow-menu-item>
                                  <NsMenuDivider />
                                  <cv-overflow-menu-item
                                    danger
                                    @click="showDeleteBackupModal(backup)"
                                  >
                                    <NsMenuItem
                                      :icon="TrashCan20"
                                      :label="$t('common.delete')"
                                    />
                                  </cv-overflow-menu-item>
                                </template>
                              </cv-overflow-menu>
                            </template>
                            <template #content>
                              <div class="card-content-backup">
                                <div class="row instance-to-repo">
                                  <div class="backup-source">
                                    <NsSvg :svg="Application20" class="icon" />
                                    <span v-if="backup.instances.length === 1">
                                      {{
                                        backup.instances[0].ui_name
                                          ? backup.instances[0].ui_name
                                          : backup.instances[0].module_id
                                      }}
                                    </span>
                                    <span v-else>
                                      {{
                                        backup.instances.length +
                                        " " +
                                        $tc(
                                          "backup.applications",
                                          backup.instances.length
                                        )
                                      }}
                                    </span>
                                  </div>
                                  <div class="arrow-right">
                                    <NsSvg :svg="ArrowRight20" />
                                  </div>
                                  <div class="backup-destination">
                                    <NsSvg :svg="DataBase20" class="icon" />
                                    <span :title="$t('backup.repository')">{{
                                      backup.repoName
                                    }}</span>
                                  </div>
                                </div>
                                <div class="row">
                                  <cv-tag
                                    v-if="backup.enabled"
                                    kind="green"
                                    :label="$t('common.enabled')"
                                    :title="$t('backup.backup_enabled')"
                                  ></cv-tag>
                                  <cv-tag
                                    v-else
                                    kind="high-contrast"
                                    :label="$t('common.disabled')"
                                    :title="$t('backup.backup_disabled')"
                                  ></cv-tag>
                                </div>
                                <div
                                  v-if="backup.errorInstances.length"
                                  class="row icon-and-text"
                                >
                                  <NsSvg
                                    :svg="ErrorFilled16"
                                    class="icon ns-error"
                                  />
                                  <span>
                                    {{
                                      $tc(
                                        "backup.backup_of_instances_failed_c",
                                        backup.errorInstances.length,
                                        {
                                          instance: backup.errorInstances[0]
                                            .ui_name
                                            ? backup.errorInstances[0].ui_name
                                            : backup.errorInstances[0]
                                                .module_id,
                                          num: backup.errorInstances.length,
                                        }
                                      )
                                    }}
                                  </span>
                                </div>
                                <div class="row actions">
                                  <NsButton
                                    kind="ghost"
                                    :icon="ArrowRight20"
                                    @click="showBackupDetailsModal(backup)"
                                    >{{ $t("common.see_details") }}
                                  </NsButton>
                                </div>
                              </div>
                            </template>
                          </NsInfoCard>
                        </div>
                      </cv-column>
                    </cv-row>
                  </template>
⋮----
<template #menu>
                              <cv-overflow-menu
                                :flip-menu="true"
                                tip-position="top"
                                tip-alignment="end"
                                class="top-right-overflow-menu"
                              >
                                <cv-overflow-menu-item
                                  v-if="isBackupRunning(backup.id)"
                                  @click="cancelBackupTask(backup)"
                                >
                                  <NsMenuItem
                                    :icon="Close20"
                                    :label="$t('backup.cancel_backup')"
                                  />
                                </cv-overflow-menu-item>
                                <template v-else>
                                  <cv-overflow-menu-item
                                    @click="runBackup(backup)"
                                    :disabled="!backup.enabled"
                                  >
                                    <NsMenuItem
                                      :icon="Save20"
                                      :label="$t('backup.run_backup_now')"
                                    />
                                  </cv-overflow-menu-item>
                                  <cv-overflow-menu-item
                                    @click="toggleBackupStatus(backup)"
                                    :disabled="loading.alterBackup"
                                  >
                                    <NsMenuItem
                                      :icon="Power20"
                                      :label="
                                        backup.enabled
                                          ? $t('common.disable')
                                          : $t('common.enable')
                                      "
                                    />
                                  </cv-overflow-menu-item>
                                  <cv-overflow-menu-item
                                    @click="showEditBackupModal(backup)"
                                  >
                                    <NsMenuItem
                                      :icon="Edit20"
                                      :label="$t('common.edit')"
                                    />
                                  </cv-overflow-menu-item>
                                  <NsMenuDivider />
                                  <cv-overflow-menu-item
                                    danger
                                    @click="showDeleteBackupModal(backup)"
                                  >
                                    <NsMenuItem
                                      :icon="TrashCan20"
                                      :label="$t('common.delete')"
                                    />
                                  </cv-overflow-menu-item>
                                </template>
                              </cv-overflow-menu>
                            </template>
⋮----
<template v-else>
                                  <cv-overflow-menu-item
                                    @click="runBackup(backup)"
                                    :disabled="!backup.enabled"
                                  >
                                    <NsMenuItem
                                      :icon="Save20"
                                      :label="$t('backup.run_backup_now')"
                                    />
                                  </cv-overflow-menu-item>
                                  <cv-overflow-menu-item
                                    @click="toggleBackupStatus(backup)"
                                    :disabled="loading.alterBackup"
                                  >
                                    <NsMenuItem
                                      :icon="Power20"
                                      :label="
                                        backup.enabled
                                          ? $t('common.disable')
                                          : $t('common.enable')
                                      "
                                    />
                                  </cv-overflow-menu-item>
                                  <cv-overflow-menu-item
                                    @click="showEditBackupModal(backup)"
                                  >
                                    <NsMenuItem
                                      :icon="Edit20"
                                      :label="$t('common.edit')"
                                    />
                                  </cv-overflow-menu-item>
                                  <NsMenuDivider />
                                  <cv-overflow-menu-item
                                    danger
                                    @click="showDeleteBackupModal(backup)"
                                  >
                                    <NsMenuItem
                                      :icon="TrashCan20"
                                      :label="$t('common.delete')"
                                    />
                                  </cv-overflow-menu-item>
                                </template>
⋮----
<template #content>
                              <div class="card-content-backup">
                                <div class="row instance-to-repo">
                                  <div class="backup-source">
                                    <NsSvg :svg="Application20" class="icon" />
                                    <span v-if="backup.instances.length === 1">
                                      {{
                                        backup.instances[0].ui_name
                                          ? backup.instances[0].ui_name
                                          : backup.instances[0].module_id
                                      }}
                                    </span>
                                    <span v-else>
                                      {{
                                        backup.instances.length +
                                        " " +
                                        $tc(
                                          "backup.applications",
                                          backup.instances.length
                                        )
                                      }}
                                    </span>
                                  </div>
                                  <div class="arrow-right">
                                    <NsSvg :svg="ArrowRight20" />
                                  </div>
                                  <div class="backup-destination">
                                    <NsSvg :svg="DataBase20" class="icon" />
                                    <span :title="$t('backup.repository')">{{
                                      backup.repoName
                                    }}</span>
                                  </div>
                                </div>
                                <div class="row">
                                  <cv-tag
                                    v-if="backup.enabled"
                                    kind="green"
                                    :label="$t('common.enabled')"
                                    :title="$t('backup.backup_enabled')"
                                  ></cv-tag>
                                  <cv-tag
                                    v-else
                                    kind="high-contrast"
                                    :label="$t('common.disabled')"
                                    :title="$t('backup.backup_disabled')"
                                  ></cv-tag>
                                </div>
                                <div
                                  v-if="backup.errorInstances.length"
                                  class="row icon-and-text"
                                >
                                  <NsSvg
                                    :svg="ErrorFilled16"
                                    class="icon ns-error"
                                  />
                                  <span>
                                    {{
                                      $tc(
                                        "backup.backup_of_instances_failed_c",
                                        backup.errorInstances.length,
                                        {
                                          instance: backup.errorInstances[0]
                                            .ui_name
                                            ? backup.errorInstances[0].ui_name
                                            : backup.errorInstances[0]
                                                .module_id,
                                          num: backup.errorInstances.length,
                                        }
                                      )
                                    }}
                                  </span>
                                </div>
                                <div class="row actions">
                                  <NsButton
                                    kind="ghost"
                                    :icon="ArrowRight20"
                                    @click="showBackupDetailsModal(backup)"
                                    >{{ $t("common.see_details") }}
                                  </NsButton>
                                </div>
                              </div>
                            </template>
⋮----
{{
                                        backup.instances[0].ui_name
                                          ? backup.instances[0].ui_name
                                          : backup.instances[0].module_id
                                      }}
⋮----
{{
                                        backup.instances.length +
                                        " " +
                                        $tc(
                                          "backup.applications",
                                          backup.instances.length
                                        )
                                      }}
⋮----
<span :title="$t('backup.repository')">{{
                                      backup.repoName
                                    }}</span>
⋮----
{{
                                      $tc(
                                        "backup.backup_of_instances_failed_c",
                                        backup.errorInstances.length,
                                        {
                                          instance: backup.errorInstances[0]
                                            .ui_name
                                            ? backup.errorInstances[0].ui_name
                                            : backup.errorInstances[0]
                                                .module_id,
                                          num: backup.errorInstances.length,
                                        }
                                      )
                                    }}
⋮----
>{{ $t("common.see_details") }}
⋮----
{{
                      $t("backup.restore_applications_from_existing_backups")
                    }}
⋮----
{{
                      $t(
                        "backup.cluster_restore_during_initial_cluster_configuration"
                      )
                    }}
⋮----
<template
                    v-if="!repositories.length && isSetClusterBackupPassword"
                  >
                    <NsInlineNotification
                      kind="warning"
                      class="mg-bottom-lg"
                      :title="$t('backup.no_backup_repository')"
                      :description="
                        $t(
                          'backup.configure_a_destination_to_restore_applications'
                        )
                      "
                      :actionLabel="$t('backup.add_repository')"
                      @action="goToBackupTabAndOpenRepositoryModal()"
                      :showCloseButton="false"
                    />
                  </template>
<template v-if="!isSetClusterBackupPassword">
                    <NsInlineNotification
                      kind="warning"
                      class="mg-bottom-lg"
                      :title="$t('backup.no_cluster_backup_password')"
                      :description="
                        $t(
                          'backup.set_cluster_backup_password_to_restore_applications'
                        )
                      "
                      :actionLabel="$t('backup.set_cluster_backup_password')"
                      @action="showBackupTabAndOpenPasswordModal()"
                      :showCloseButton="false"
                    />
                  </template>
⋮----
>{{ $t("backup.restore_app") }}
⋮----
<template slot="description">
        <NsInlineNotification
          kind="warning"
          :title="$t('backup.delete_repo_notice_title')"
          :showCloseButton="false"
          :loadingAction="loading.downloadClusterBackupNotice"
          v-if="currentRepo.password"
          @action="downloadClusterConfigurationBackup(false, true)"
          :actionLabel="$t('backup.download_cluster_configuration_backup')"
          :description="$t('backup.delete_repo_notice_description')"
        />
        <p class="mg-top-sm">
          {{
            $t("backup.delete_repository_confirm", {
              name: currentRepo.name,
            })
          }}
        </p>
      </template>
⋮----
{{
            $t("backup.delete_repository_confirm", {
              name: currentRepo.name,
            })
          }}
⋮----
<template slot="explanation">
        <p class="mg-top-sm">{{ $t("backup.delete_repo_explanation_1") }}</p>
      </template>
⋮----
<p class="mg-top-sm">{{ $t("backup.delete_repo_explanation_1") }}</p>
⋮----
<template slot="explanation">
        <p v-if="currentBackup.instances.length" class="mg-top-sm">
          {{
            $tc(
              "backup.delete_backup_explanation_1",
              currentBackup.instances.length,
              {
                numInstances: currentBackup.instances.length,
                instanceName: currentBackup.instances[0].ui_name
                  ? currentBackup.instances[0].ui_name
                  : currentBackup.instances[0].module_id,
              }
            )
          }}
        </p>
        <p class="mg-top-sm">{{ $t("backup.delete_backup_explanation_2") }}</p>
      </template>
⋮----
{{
            $tc(
              "backup.delete_backup_explanation_1",
              currentBackup.instances.length,
              {
                numInstances: currentBackup.instances.length,
                instanceName: currentBackup.instances[0].ui_name
                  ? currentBackup.instances[0].ui_name
                  : currentBackup.instances[0].module_id,
              }
            )
          }}
⋮----
<p class="mg-top-sm">{{ $t("backup.delete_backup_explanation_2") }}</p>
⋮----
<script>
import {
  QueryParamService,
  UtilService,
  TaskService,
  IconService,
  DateTimeService,
  PageTitleService,
} from "@nethserver/ns8-ui-lib";
import { mapGetters } from "vuex";
import AddRepositoryModal from "@/components/backup/AddRepositoryModal";
import CreateOrEditBackupModal from "@/components/backup/CreateOrEditBackupModal";
import BackupDetailsModal from "@/components/backup/BackupDetailsModal";
import EditRepositoryModal from "@/components/backup/EditRepositoryModal";
import RestoreSingleInstanceModal from "@/components/backup/RestoreSingleInstanceModal";
import BackupPasswordModal from "@/components/backup/BackupPasswordModal";
import ImportBackupDestinationModal from "@/components/backup/ImportBackupDestinationModal";
import to from "await-to-js";
import Upload20 from "@carbon/icons-vue/es/upload/20";
import NotificationService from "@/mixins/notification";
export default {
  name: "Backup",
  components: {
    AddRepositoryModal,
    CreateOrEditBackupModal,
    BackupDetailsModal,
    EditRepositoryModal,
    RestoreSingleInstanceModal,
    BackupPasswordModal,
    ImportBackupDestinationModal,
  },
  mixins: [
    NotificationService,
    TaskService,
    UtilService,
    IconService,
    QueryParamService,
    DateTimeService,
    PageTitleService,
  ],
  pageTitle() {
    return this.$t("backup.title");
  },
  data() {
    return {
      q: {
        isShownAddRepoModal: false,
        view: "",
      },
      Upload20,
      isShownCreateOrEditBackupModal: false,
      isShownDeleteRepoModal: false,
      isShownEditRepoModal: false,
      isShownDeleteBackupModal: false,
      isShownBackupDetailsModal: false,
      isShownRestoreModal: false,
      isShownBackupPasswordModal: false,
      isShownImportBackupDestinationModal: false,
      isLoadingImportBackupDestination: false,
      importBackupDestinationFileError: null,
      repositories: [],
      backups: [],
      unconfiguredInstances: [],
      instanceSelection: "",
      isEditingBackup: false,
      isSetClusterBackupPassword: false,
      currentRepo: {
        name: "",
        password: "",
      },
      currentBackup: {
        name: "",
        instances: [],
      },
      loading: {
        listBackupRepositories: true,
        listBackups: true,
        alterBackup: false,
        downloadClusterBackup: false,
        downloadClusterBackupNotice: false,
        passwordClusterBackup: false,
      },
      error: {
        listBackupRepositories: "",
        listBackups: "",
        removeBackupRepository: "",
        removeBackup: "",
        runBackup: "",
        alterBackup: "",
        downloadClusterBackup: "",
        passwordClusterBackup: "",
        cancelBackup: "",
      },
    };
  },
  computed: {
    ...mapGetters(["ongoingNotifications"]),
    disabledBackups() {
      return this.backups.filter((b) => !b.enabled);
    },
    erroredBackups() {
      return this.backups.filter((b) => b.errorInstances.length);
    },
    runningBackupTasksFromStore() {
      const runningTasks = {};
      this.ongoingNotifications.forEach((notification) => {
        if (
          notification.task &&
          notification.task.context &&
          notification.task.context.action === "run-backup" &&
          notification.task.context.extra &&
          notification.task.context.extra.backupId
        ) {
          const backupId = notification.task.context.extra.backupId;
          runningTasks[backupId] = notification.task.context.id;
        }
      });
      return runningTasks;
    },
    isBackupRunning() {
      return (backupId) => {
        return !!this.runningBackupTasksFromStore[backupId];
      };
    },
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.watchQueryData(vm);
      vm.queryParamsToDataForCore(vm, to.query);
    });
  },
  beforeRouteUpdate(to, from, next) {
    this.queryParamsToDataForCore(this, to.query);
    next();
  },
  created() {
    this.listBackupRepositories();
  },
  mounted() {
    if (!this.q.view) {
      this.q.view = "backup";
    }
  },
  methods: {
    tabSelected(tabNum) {
      if (tabNum === 0) {
        this.q.view = "backup";
      } else if (tabNum === 1) {
        this.q.view = "restore";
      }
    },
    async listBackupRepositories() {
      this.loading.listBackupRepositories = true;
      this.error.listBackupRepositories = "";
      const taskAction = "list-backup-repositories";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.listBackupRepositoriesCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.listBackupRepositories = this.getErrorMessage(err);
        return;
      }
    },
    listBackupRepositoriesCompleted(taskContext, taskResult) {
      let repositories = taskResult.output.repositories.sort(
        this.sortByProperty("name")
      );
      this.repositories = repositories;
      this.loading.listBackupRepositories = false;
      this.isSetClusterBackupPassword = taskResult.output.password_exists;
      this.listBackups();
    },
    async listBackups() {
      this.loading.listBackups = true;
      this.error.listBackups = "";
      const taskAction = "list-backups";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.listBackupsCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.listBackups = this.getErrorMessage(err);
        return;
      }
    },
    listBackupsCompleted(taskContext, taskResult) {
      this.unconfiguredInstances = taskResult.output.unconfigured_instances;
      let backups = taskResult.output.backups;
      backups.sort(this.sortByProperty("name"));
      for (const backup of backups) {
        const repo = this.repositories.find((r) => r.id == backup.repository);
        if (repo) {
          backup.repoName = repo.name;
        }
        backup.scheduleExpression = backup.schedule;
        backup.schedule = backup.schedule_hint;
        backup.errorInstances = backup.instances.filter(
          (i) => i.status && i.status.success == false
        );
      }
      this.backups = backups;
      this.loading.listBackups = false;
    },
    goToBackupTabAndOpenRepositoryModal() {
      this.q.view = "backup";
      this.showAddRepoModal();
    },
    showAddRepoModal() {
      this.q.isShownAddRepoModal = true;
    },
    hideAddRepoModal() {
      this.q.isShownAddRepoModal = false;
    },
    showDeleteRepoModal(repo) {
      this.currentRepo = repo;
      this.isShownDeleteRepoModal = true;
    },
    hideDeleteRepoModal() {
      this.isShownDeleteRepoModal = false;
    },
    showEditRepoModal(repo) {
      this.currentRepo = repo;
      this.isShownEditRepoModal = true;
    },
    hideEditRepoModal() {
      this.isShownEditRepoModal = false;
    },
    showCreateOrEditBackupModal(instanceSelection = "") {
      this.instanceSelection = instanceSelection;
      this.isEditingBackup = false;
      this.isShownCreateOrEditBackupModal = true;
    },
    hideCreateOrEditBackupModal() {
      this.isShownCreateOrEditBackupModal = false;
    },
    showEditBackupModal(backup) {
      this.currentBackup = backup;
      this.isEditingBackup = true;
      this.isShownCreateOrEditBackupModal = true;
    },
    showDeleteBackupModal(backup) {
      this.currentBackup = backup;
      this.isShownDeleteBackupModal = true;
    },
    hideDeleteBackupModal() {
      this.isShownDeleteBackupModal = false;
    },
    showBackupDetailsModal(backup) {
      this.currentBackup = backup;
      this.isShownBackupDetailsModal = true;
    },
    hideBackupDetailsModal() {
      this.isShownBackupDetailsModal = false;
    },
    showRestoreModal() {
      this.isShownRestoreModal = true;
    },
    hideRestoreModal() {
      this.isShownRestoreModal = false;
    },
    showBackupTabAndOpenPasswordModal() {
      this.q.view = "backup";
      this.showBackupPasswordModal();
    },
    showBackupPasswordModal() {
      this.isShownBackupPasswordModal = true;
    },
    hideBackupPasswordModal() {
      this.isShownBackupPasswordModal = false;
    },
    showImportBackupDestinationModal() {
      this.isShownImportBackupDestinationModal = true;
    },
    hideImportBackupDestinationModal() {
      this.isShownImportBackupDestinationModal = false;
    },
    onImportBackupSubmit(data) {
      if (data.backupFile && data.backupPassword) {
        this.importBackupDestination(data);
      }
    },
    async importBackupDestination(data) {
      this.isLoadingImportBackupDestination = true;
      this.importBackupDestinationFileError = null;
      const taskAction = "import-backup-destinations";
      const eventId = this.getUuid();
      try {
        const fileDataUri = await this.fileToBase64(data.backupFile);
        const fileContent = fileDataUri.split(";base64,")[1];
        this.$root.$once(
          `${taskAction}-completed-${eventId}`,
          this.importBackupDestinationCompleted
        );
        this.$root.$once(
          `${taskAction}-aborted-${eventId}`,
          this.importBackupDestinationAborted
        );
        this.$root.$once(
          `${taskAction}-validation-failed-${eventId}`,
          this.importBackupDestinationValidationFailed
        );
        const res = await to(
          this.createClusterTask({
            action: taskAction,
            data: {
              backup_data: fileContent,
              backup_password: data.backupPassword,
            },
            extra: {
              title: this.$t("action." + taskAction),
              description: this.$t("common.processing"),
              eventId,
            },
          })
        );
        const err = res[0];
        if (err) {
          console.error(`error creating task ${taskAction}`, err);
          this.isLoadingImportBackupDestination = false;
          this.importBackupDestinationFileError = this.getErrorMessage(err);
          return;
        }
      } catch (error) {
        console.error("Error reading backup file", error);
        this.importBackupDestinationFileError =
          this.$t("backup.error_reading_backup_file") ||
          "Error reading backup file";
        this.isLoadingImportBackupDestination = false;
      }
    },
    importBackupDestinationCompleted() {
      this.isLoadingImportBackupDestination = false;
      this.isShownImportBackupDestinationModal = false;
      this.listBackupRepositories();
    },
    importBackupDestinationAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.isLoadingImportBackupDestination = false;
      this.importBackupDestinationFileError = this.$t("error.generic_error");
    },
    importBackupDestinationValidationFailed(validationErrors) {
      this.isLoadingImportBackupDestination = false;
      const errorKey = validationErrors?.[0]?.error || "import_failed";
      this.importBackupDestinationFileError = this.$t("backup." + errorKey);
    },
    async deleteRepo(repo) {
      this.error.removeBackupRepository = "";
      const taskAction = "remove-backup-repository";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.removeBackupRepositoryCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {
            id: repo.id,
          },
          extra: {
            title: this.$t("action." + taskAction),
            description: this.$t("common.processing"),
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.removeBackupRepository = this.getErrorMessage(err);
        return;
      }
      this.isShownDeleteRepoModal = false;
    },
    removeBackupRepositoryCompleted() {
      this.listBackupRepositories();
    },
    async deleteBackup(backup) {
      this.error.removeBackup = "";
      const taskAction = "remove-backup";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.removeBackupCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {
            id: backup.id,
          },
          extra: {
            title: this.$t("action." + taskAction),
            description: this.$t("common.processing"),
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.removeBackup = this.getErrorMessage(err);
        return;
      }
      this.isShownDeleteBackupModal = false;
    },
    removeBackupCompleted() {
      this.listBackupRepositories();
    },
    async runBackup(backup) {
      this.error.runBackup = "";
      const taskAction = "run-backup";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.runBackupCompleted
      );
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.runBackupAborted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {
            id: backup.id,
          },
          extra: {
            eventId,
            backupId: backup.id,
            title: this.$t("action." + taskAction),
            description: this.$t("backup.running_backup_name", {
              backupName: backup.name,
            }),
            backupName: backup.name,
            completion: {
              i18nString: "backup.backup_completed_successfully",
              extraTextParams: ["backupName"],
            },
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.runBackup = this.getErrorMessage(err);
        return;
      }
    },
    runBackupCompleted() {
      this.listBackups();
    },
    runBackupAborted() {
      this.listBackups();
    },
    async cancelBackupTask(backup) {
      let taskId = this.runningBackupTasksFromStore[backup.id];
      if (typeof taskId !== "string" || !taskId) {
        console.warn("Cannot cancel backup: task ID not yet available", {
          backupId: backup && backup.id,
          taskId: taskId,
        });
        return;
      }
      this.handleCancelTask(taskId);
    },
    onBackupCreated(runBackupOnFinish, createdBackup) {
      this.listBackupRepositories();
      if (runBackupOnFinish) {
        this.runBackup(createdBackup);
      }
    },
    onBackupAltered(runBackupOnFinish, createdBackup) {
      this.listBackupRepositories();
      if (runBackupOnFinish) {
        this.runBackup(createdBackup);
      }
    },
    async toggleBackupStatus(backup) {
      this.error.alterBackup = "";
      this.loading.alterBackup = true;
      const taskAction = "alter-backup";
      const taskDescription = backup.enabled
        ? this.$t("backup.disabling_backup", { backupName: backup.name })
        : this.$t("backup.enabling_backup", { backupName: backup.name });
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.alterBackupCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {
            id: backup.id,
            name: backup.name,
            schedule: backup.scheduleExpression,
            schedule_hint: backup.schedule,
            retention: backup.retention,
            instances: backup.instances.map((i) => i.module_id),
            enabled: !backup.enabled,
          },
          extra: {
            title: this.$t("action." + taskAction),
            description: taskDescription,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.alterBackup = this.getErrorMessage(err);
        return;
      }
    },
    alterBackupCompleted() {
      this.loading.alterBackup = false;
      this.listBackups();
    },
    async downloadClusterConfigurationBackup(
      showLoading = true,
      showNoticeLoading = false
    ) {
      if (showLoading) {
        this.loading.downloadClusterBackup = true;
      }
      if (showNoticeLoading) {
        this.loading.downloadClusterBackupNotice = true;
      }
      const taskAction = "download-cluster-backup";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.downloadClusterBackupAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.downloadClusterBackupCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: { password: this.clusterPassword },
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.downloadClusterBackup = this.getErrorMessage(err);
        this.loading.downloadClusterBackup = false;
        this.loading.downloadClusterBackupNotice = false;
        return;
      }
    },
    downloadClusterBackupAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.loading.downloadClusterBackup = false;
      this.loading.downloadClusterBackupNotice = false;
    },
    downloadClusterBackupCompleted(taskContext, taskResult) {
      this.loading.downloadClusterBackup = false;
      this.loading.downloadClusterBackupNotice = false;
      const path = taskResult && taskResult.output && taskResult.output.path;
      if (!path) {
        this.error.downloadClusterBackup = this.$t(
          "error.cannot_retrieve_task_status"
        );
        return;
      }
      const apiBase = this.$root.apiUrl.replace(/\/api$/, "");
      const downloadUrl = `${apiBase}/backup/${path}`;
      const fileName =
        "cluster-configuration-backup " +
        this.formatDate(new Date(), "yyyy-MM-dd HH.mm") +
        ".json.gz.gpg";
      this.axios({
        url: downloadUrl,
        method: "GET",
        responseType: "blob",
        timeout: 60000,
      })
        .then((response) => {
          const blobUrl = window.URL.createObjectURL(new Blob([response.data]));
          const link = document.createElement("a");
          link.href = blobUrl;
          link.setAttribute("download", fileName);
          document.body.appendChild(link);
          link.click();
          link.remove();
          window.URL.revokeObjectURL(blobUrl);
        })
        .catch((err) => {
          console.error("downloadClusterBackupCompleted", err);
          this.error.downloadClusterBackup = this.getErrorMessage(err);
        });
    },
    reloadBackupRepositories() {
      this.isSetClusterBackupPassword = true;
      this.listBackupRepositories();
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../styles/carbon-utils";
.card-content-backup {
  flex-grow: 1;
}
.card-content-backup .row {
  margin-bottom: $spacing-05;
  text-align: center;
}
.card-content-backup .row:last-child {
  margin-bottom: 0;
}
.instance-to-repo {
  display: flex;
  align-items: center;
  justify-content: center;
}
.arrow-right {
  margin-left: $spacing-05;
  margin-right: $spacing-05;
  flex-grow: 1;
  flex-basis: 0;
}
.instance-to-repo .icon {
  margin-right: $spacing-02;
}
.backup-source {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  flex-grow: 6;
  flex-basis: 0;
}
.backup-destination {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  flex-grow: 6;
  flex-basis: 0;
}
.inline {
  display: inline;
}
</style>
</file>

<file path="core/ui/src/views/ClusterStatus.vue">
<template>
  <cv-grid fullWidth v-if="isClusterInitialized">
    <cv-row>
      <cv-column class="page-title">
        <h2>
          {{ $t("cluster_status.title") }}
          <cv-interactive-tooltip
            alignment="center"
            direction="bottom"
            class="info"
          >
            <template slot="trigger">
              <Information16 />
            </template>
            <template slot="content">
              {{ $t("common.global_shortcut") + ": CTRL+SHIFT+S" }}
            </template>
          </cv-interactive-tooltip>
        </h2>
      </cv-column>
    </cv-row>
    <cv-row>
      <cv-column>
        <div
          class="card-grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 3xl:grid-cols-4"
        >
          <NsInfoCard
            light
            :title="numUpdates.toString()"
            :description="$tc('cluster_status.updated_available_c', numUpdates)"
            :icon="Upgrade32"
            :loading="loading.listModules || loading.listCoreModules"
            :isErrorShown="error.listCoreModules"
            :errorTitle="$t('error.cannot_retrieve_available_apps')"
            :errorDescription="error.listCoreModules"
            class="min-height-card"
          >
            <template slot="content">
              <div class="card-rows">
                <div
                  v-if="isCoreUpdateAvailable"
                  class="card-row mg-top-sm icon-and-text"
                >
                  <NsSvg :svg="Warning16" class="icon ns-warning" />
                  <span>{{ $t("cluster_status.core_update_available") }}</span>
                </div>
                <div class="card-row">
                  <NsButton
                    kind="ghost"
                    :icon="ArrowRight20"
                    @click="
                      $router.push('/software-center?search=&view=updates')
                    "
                  >
                    {{ $t("cluster_status.go_to_software_center") }}
                  </NsButton>
                </div>
              </div>
            </template>
          </NsInfoCard>
          <NsInfoCard
            light
            :title="installedModules.length.toString()"
            :description="
              $tc('cluster_status.apps_installed_c', installedModules.length)
            "
            :icon="Application32"
            :loading="loading.listModules"
            :isErrorShown="error.listModules"
            :errorTitle="$t('error.cannot_retrieve_available_apps')"
            :errorDescription="error.listModules"
            class="min-height-card"
          >
            <template slot="content">
              <NsButton
                kind="ghost"
                :icon="ArrowRight20"
                @click="$router.push('/applications-center')"
              >
                {{ $t("cluster_status.go_to_applications") }}
              </NsButton>
            </template>
          </NsInfoCard>
          <NsInfoCard
            light
            :title="nodes.length.toString()"
            :description="$tc('common.nodes_c', nodes.length)"
            :icon="Chip32"
            :loading="loading.getClusterStatus"
            :isErrorShown="error.getClusterStatus"
            :errorTitle="$t('error.cannot_retrieve_cluster_nodes')"
            :errorDescription="error.getClusterStatus"
            class="min-height-card"
          >
            <template slot="content">
              <div class="card-rows">
                <div
                  class="card-row"
                  v-if="!loading.getClusterStatus && nodes.length > 1"
                >
                  <div class="mg-top-sm">
                    <div
                      v-if="nodesOffline.length"
                      class="card-row icon-and-text"
                    >
                      <NsSvg :svg="ErrorFilled16" class="icon ns-error" />
                      <span>
                        {{
                          $tc("nodes.nodes_offline_c", nodesOffline.length, {
                            num: nodesOffline.length,
                          })
                        }}
                      </span>
                    </div>
                    <div v-else class="card-row icon-and-text">
                      <NsSvg :svg="CheckmarkFilled16" class="icon ns-success" />
                      <span>
                        {{ $t("nodes.nodes_online_cluster_status") }}
                      </span>
                    </div>
                  </div>
                </div>
                <div class="card-row">
                  <NsButton
                    kind="ghost"
                    :icon="ArrowRight20"
                    @click="$router.push('/nodes')"
                  >
                    {{ $t("cluster_status.go_to_nodes") }}
                  </NsButton>
                </div>
              </div>
            </template>
          </NsInfoCard>
          <NsInfoCard
            light
            :title="enabledBackupSchedules.length.toString()"
            :description="$tc('backup.backups_scheduled_c', backups.length)"
            :icon="Save32"
            :loading="loading.listBackups"
            :isErrorShown="error.listBackups"
            :errorTitle="$t('error.cannot_retrieve_backups')"
            :errorDescription="error.listBackups"
            class="min-height-card"
          >
            <template slot="content">
              <div class="card-rows mg-top-sm">
                <div
                  v-if="!loading.listBackups && !error.listBackups"
                  class="mg-bottom-sm"
                >
                  <template
                    v-if="
                      erroredBackups.length ||
                      disabledBackupSchedules.length ||
                      instancesNotBackedUp.length
                    "
                  >
                    <div
                      v-if="erroredBackups.length"
                      class="card-row icon-and-text"
                    >
                      <NsSvg :svg="ErrorFilled16" class="icon ns-error" />
                      <span>
                        {{
                          $tc(
                            "cluster_status.backups_failed_c",
                            erroredBackups.length,
                            { num: erroredBackups.length }
                          )
                        }}
                      </span>
                    </div>
                    <div
                      v-if="disabledBackupSchedules.length"
                      class="card-row icon-and-text"
                    >
                      <NsSvg :svg="Warning16" class="icon ns-warning" />
                      <span>
                        {{
                          $tc(
                            "cluster_status.backup_disabled_c",
                            disabledBackupSchedules.length,
                            { num: disabledBackupSchedules.length }
                          )
                        }}
                      </span>
                    </div>
                    <div
                      v-if="instancesNotBackedUp.length"
                      class="card-row icon-and-text"
                    >
                      <NsSvg :svg="Warning16" class="icon ns-warning" />
                      <span>
                        {{
                          $tc(
                            "cluster_status.instances_not_backed_up_c",
                            instancesNotBackedUp.length,
                            { num: instancesNotBackedUp.length }
                          )
                        }}
                      </span>
                    </div>
                  </template>
                  <template v-else>
                    <div class="card-row icon-and-text">
                      <NsSvg :svg="CheckmarkFilled16" class="icon ns-success" />
                      <span>{{ $t("common.all_good") }}</span>
                    </div>
                  </template>
                </div>
                <div class="card-row">
                  <NsButton
                    kind="ghost"
                    :icon="ArrowRight20"
                    @click="$router.push('/backup')"
                  >
                    {{ $t("cluster_status.go_to_backup") }}
                  </NsButton>
                </div>
              </div>
            </template>
          </NsInfoCard>
          <NsInfoCard
            light
            :title="$t('cluster_status.email_notification')"
            :icon="Email32"
            :loading="loading.getEmailNotification"
            :isErrorShown="error.getEmailNotification"
            :errorTitle="$t('error.cannot_retrieve_email_notification_status')"
            :errorDescription="error.getEmailNotification"
            class="min-height-card"
          >
            <template slot="content">
              <div class="card-rows">
                <div class="card-row">
                  <div v-if="!loading.getEmailNotification" class="card-row">
                    <cv-tag
                      v-if="emailNotificationEnabled"
                      kind="green"
                      :label="$t('common.enabled')"
                    ></cv-tag>
                    <cv-tag
                      v-else
                      kind="high-contrast"
                      :label="$t('common.disabled')"
                    ></cv-tag>
                  </div>
                </div>
                <div class="card-row">
                  <NsButton
                    kind="ghost"
                    :icon="ArrowRight20"
                    @click="$router.push('/settings/smarthost')"
                  >
                    {{ $t("cluster_status.go_to_settings") }}
                  </NsButton>
                </div>
              </div>
            </template>
          </NsInfoCard>
          <NsInfoCard
            light
            :title="$t('cluster_status.system_logs')"
            :description="
              $tc('cluster_status.active_instance', activeLokiInstance, {
                instance: activeLokiInstance,
              })
            "
            :icon="Catalog32"
            :loading="loading.lokiInstance"
            :isErrorShown="error.lokiInstance"
            :errorTitle="
              $t('system_logs.loki.cannot_retrieve_system_logs_status')
            "
            :errorDescription="error.lokiInstance"
            class="min-height-card"
          >
            <template slot="content">
              <div class="card-rows">
                <div
                  v-if="cloudLogManagerForwarderStatus == 'active'"
                  class="card-row mg-top-sm icon-and-text"
                >
                  <NsSvg :svg="CheckmarkFilled16" class="icon ns-success" />
                  <span>{{
                    $t(
                      "cloud_log_manager_forwarder.cloud_log_manager_export_enabled"
                    )
                  }}</span>
                </div>
                <div
                  v-if="cloudLogManagerForwarderStatus == 'failed'"
                  class="card-row mg-top-sm icon-and-text"
                >
                  <NsSvg :svg="ErrorFilled16" class="icon ns-error" />
                  <span>{{
                    $t(
                      "cloud_log_manager_forwarder.cloud_log_manager_export_failed"
                    )
                  }}</span>
                </div>
                <div
                  v-if="syslogForwarderStatus == 'active'"
                  class="card-row mg-top-sm icon-and-text"
                >
                  <NsSvg :svg="CheckmarkFilled16" class="icon ns-success" />
                  <span>{{
                    $t("syslog_forwarder.syslog_export_enabled")
                  }}</span>
                </div>
                <div
                  v-if="syslogForwarderStatus == 'failed'"
                  class="card-row mg-top-sm icon-and-text"
                >
                  <NsSvg :svg="ErrorFilled16" class="icon ns-error" />
                  <span>{{ $t("syslog_forwarder.syslog_export_failed") }}</span>
                </div>
                <div class="card-row">
                  <NsButton
                    kind="ghost"
                    :icon="ArrowRight20"
                    @click="$router.push('/settings/system-logs')"
                  >
                    {{ $t("cluster_status.go_to_system_logs") }}
                  </NsButton>
                </div>
              </div>
            </template>
          </NsInfoCard>
          <NsInfoCard
            light
            :title="$t('cluster_status.subscription_status')"
            :icon="Badge32"
            :loading="loading.getSubscription"
            :isErrorShown="error.getSubscription"
            :errorTitle="$t('error.cannot_retrieve_subscription_status')"
            :errorDescription="error.getSubscription"
            class="min-height-card"
          >
            <template slot="content">
              <div class="card-rows">
                <div class="card-row">
                  <div v-if="!loading.getSubscription" class="card-row">
                    <cv-tag
                      v-if="subscription_status === 'active'"
                      kind="green"
                      :label="$t('common.active')"
                    ></cv-tag>
                    <cv-tag
                      v-else
                      kind="high-contrast"
                      :label="$t('common.not_active')"
                    ></cv-tag>
                  </div>
                </div>
                <div
                  v-if="support_active && !loading.getSubscription"
                  class="card-row"
                >
                  <div class="mg-top-sm icon-and-text">
                    <NsSvg
                      :svg="InformationFilled16"
                      class="icon ns-info shrink-0"
                    />
                    <span>{{
                      $t("settings_subscription.remote_support_in_progress")
                    }}</span>
                  </div>
                </div>
                <div v-if="!loading.getSubscription" class="card-row">
                  <NsButton
                    kind="ghost"
                    :icon="ArrowRight20"
                    @click="$router.push('/settings/subscription')"
                  >
                    {{ $t("cluster_status.go_to_subscription") }}
                  </NsButton>
                </div>
              </div>
            </template>
          </NsInfoCard>
        </div>
      </cv-column>
    </cv-row>
  </cv-grid>
</template>
⋮----
{{ $t("cluster_status.title") }}
⋮----
<template slot="trigger">
              <Information16 />
            </template>
<template slot="content">
              {{ $t("common.global_shortcut") + ": CTRL+SHIFT+S" }}
            </template>
⋮----
{{ $t("common.global_shortcut") + ": CTRL+SHIFT+S" }}
⋮----
<template slot="content">
              <div class="card-rows">
                <div
                  v-if="isCoreUpdateAvailable"
                  class="card-row mg-top-sm icon-and-text"
                >
                  <NsSvg :svg="Warning16" class="icon ns-warning" />
                  <span>{{ $t("cluster_status.core_update_available") }}</span>
                </div>
                <div class="card-row">
                  <NsButton
                    kind="ghost"
                    :icon="ArrowRight20"
                    @click="
                      $router.push('/software-center?search=&view=updates')
                    "
                  >
                    {{ $t("cluster_status.go_to_software_center") }}
                  </NsButton>
                </div>
              </div>
            </template>
⋮----
<span>{{ $t("cluster_status.core_update_available") }}</span>
⋮----
{{ $t("cluster_status.go_to_software_center") }}
⋮----
<template slot="content">
              <NsButton
                kind="ghost"
                :icon="ArrowRight20"
                @click="$router.push('/applications-center')"
              >
                {{ $t("cluster_status.go_to_applications") }}
              </NsButton>
            </template>
⋮----
{{ $t("cluster_status.go_to_applications") }}
⋮----
<template slot="content">
              <div class="card-rows">
                <div
                  class="card-row"
                  v-if="!loading.getClusterStatus && nodes.length > 1"
                >
                  <div class="mg-top-sm">
                    <div
                      v-if="nodesOffline.length"
                      class="card-row icon-and-text"
                    >
                      <NsSvg :svg="ErrorFilled16" class="icon ns-error" />
                      <span>
                        {{
                          $tc("nodes.nodes_offline_c", nodesOffline.length, {
                            num: nodesOffline.length,
                          })
                        }}
                      </span>
                    </div>
                    <div v-else class="card-row icon-and-text">
                      <NsSvg :svg="CheckmarkFilled16" class="icon ns-success" />
                      <span>
                        {{ $t("nodes.nodes_online_cluster_status") }}
                      </span>
                    </div>
                  </div>
                </div>
                <div class="card-row">
                  <NsButton
                    kind="ghost"
                    :icon="ArrowRight20"
                    @click="$router.push('/nodes')"
                  >
                    {{ $t("cluster_status.go_to_nodes") }}
                  </NsButton>
                </div>
              </div>
            </template>
⋮----
{{
                          $tc("nodes.nodes_offline_c", nodesOffline.length, {
                            num: nodesOffline.length,
                          })
                        }}
⋮----
{{ $t("nodes.nodes_online_cluster_status") }}
⋮----
{{ $t("cluster_status.go_to_nodes") }}
⋮----
<template slot="content">
              <div class="card-rows mg-top-sm">
                <div
                  v-if="!loading.listBackups && !error.listBackups"
                  class="mg-bottom-sm"
                >
                  <template
                    v-if="
                      erroredBackups.length ||
                      disabledBackupSchedules.length ||
                      instancesNotBackedUp.length
                    "
                  >
                    <div
                      v-if="erroredBackups.length"
                      class="card-row icon-and-text"
                    >
                      <NsSvg :svg="ErrorFilled16" class="icon ns-error" />
                      <span>
                        {{
                          $tc(
                            "cluster_status.backups_failed_c",
                            erroredBackups.length,
                            { num: erroredBackups.length }
                          )
                        }}
                      </span>
                    </div>
                    <div
                      v-if="disabledBackupSchedules.length"
                      class="card-row icon-and-text"
                    >
                      <NsSvg :svg="Warning16" class="icon ns-warning" />
                      <span>
                        {{
                          $tc(
                            "cluster_status.backup_disabled_c",
                            disabledBackupSchedules.length,
                            { num: disabledBackupSchedules.length }
                          )
                        }}
                      </span>
                    </div>
                    <div
                      v-if="instancesNotBackedUp.length"
                      class="card-row icon-and-text"
                    >
                      <NsSvg :svg="Warning16" class="icon ns-warning" />
                      <span>
                        {{
                          $tc(
                            "cluster_status.instances_not_backed_up_c",
                            instancesNotBackedUp.length,
                            { num: instancesNotBackedUp.length }
                          )
                        }}
                      </span>
                    </div>
                  </template>
                  <template v-else>
                    <div class="card-row icon-and-text">
                      <NsSvg :svg="CheckmarkFilled16" class="icon ns-success" />
                      <span>{{ $t("common.all_good") }}</span>
                    </div>
                  </template>
                </div>
                <div class="card-row">
                  <NsButton
                    kind="ghost"
                    :icon="ArrowRight20"
                    @click="$router.push('/backup')"
                  >
                    {{ $t("cluster_status.go_to_backup") }}
                  </NsButton>
                </div>
              </div>
            </template>
⋮----
<template
                    v-if="
                      erroredBackups.length ||
                      disabledBackupSchedules.length ||
                      instancesNotBackedUp.length
                    "
                  >
                    <div
                      v-if="erroredBackups.length"
                      class="card-row icon-and-text"
                    >
                      <NsSvg :svg="ErrorFilled16" class="icon ns-error" />
                      <span>
                        {{
                          $tc(
                            "cluster_status.backups_failed_c",
                            erroredBackups.length,
                            { num: erroredBackups.length }
                          )
                        }}
                      </span>
                    </div>
                    <div
                      v-if="disabledBackupSchedules.length"
                      class="card-row icon-and-text"
                    >
                      <NsSvg :svg="Warning16" class="icon ns-warning" />
                      <span>
                        {{
                          $tc(
                            "cluster_status.backup_disabled_c",
                            disabledBackupSchedules.length,
                            { num: disabledBackupSchedules.length }
                          )
                        }}
                      </span>
                    </div>
                    <div
                      v-if="instancesNotBackedUp.length"
                      class="card-row icon-and-text"
                    >
                      <NsSvg :svg="Warning16" class="icon ns-warning" />
                      <span>
                        {{
                          $tc(
                            "cluster_status.instances_not_backed_up_c",
                            instancesNotBackedUp.length,
                            { num: instancesNotBackedUp.length }
                          )
                        }}
                      </span>
                    </div>
                  </template>
⋮----
{{
                          $tc(
                            "cluster_status.backups_failed_c",
                            erroredBackups.length,
                            { num: erroredBackups.length }
                          )
                        }}
⋮----
{{
                          $tc(
                            "cluster_status.backup_disabled_c",
                            disabledBackupSchedules.length,
                            { num: disabledBackupSchedules.length }
                          )
                        }}
⋮----
{{
                          $tc(
                            "cluster_status.instances_not_backed_up_c",
                            instancesNotBackedUp.length,
                            { num: instancesNotBackedUp.length }
                          )
                        }}
⋮----
<template v-else>
                    <div class="card-row icon-and-text">
                      <NsSvg :svg="CheckmarkFilled16" class="icon ns-success" />
                      <span>{{ $t("common.all_good") }}</span>
                    </div>
                  </template>
⋮----
<span>{{ $t("common.all_good") }}</span>
⋮----
{{ $t("cluster_status.go_to_backup") }}
⋮----
<template slot="content">
              <div class="card-rows">
                <div class="card-row">
                  <div v-if="!loading.getEmailNotification" class="card-row">
                    <cv-tag
                      v-if="emailNotificationEnabled"
                      kind="green"
                      :label="$t('common.enabled')"
                    ></cv-tag>
                    <cv-tag
                      v-else
                      kind="high-contrast"
                      :label="$t('common.disabled')"
                    ></cv-tag>
                  </div>
                </div>
                <div class="card-row">
                  <NsButton
                    kind="ghost"
                    :icon="ArrowRight20"
                    @click="$router.push('/settings/smarthost')"
                  >
                    {{ $t("cluster_status.go_to_settings") }}
                  </NsButton>
                </div>
              </div>
            </template>
⋮----
{{ $t("cluster_status.go_to_settings") }}
⋮----
<template slot="content">
              <div class="card-rows">
                <div
                  v-if="cloudLogManagerForwarderStatus == 'active'"
                  class="card-row mg-top-sm icon-and-text"
                >
                  <NsSvg :svg="CheckmarkFilled16" class="icon ns-success" />
                  <span>{{
                    $t(
                      "cloud_log_manager_forwarder.cloud_log_manager_export_enabled"
                    )
                  }}</span>
                </div>
                <div
                  v-if="cloudLogManagerForwarderStatus == 'failed'"
                  class="card-row mg-top-sm icon-and-text"
                >
                  <NsSvg :svg="ErrorFilled16" class="icon ns-error" />
                  <span>{{
                    $t(
                      "cloud_log_manager_forwarder.cloud_log_manager_export_failed"
                    )
                  }}</span>
                </div>
                <div
                  v-if="syslogForwarderStatus == 'active'"
                  class="card-row mg-top-sm icon-and-text"
                >
                  <NsSvg :svg="CheckmarkFilled16" class="icon ns-success" />
                  <span>{{
                    $t("syslog_forwarder.syslog_export_enabled")
                  }}</span>
                </div>
                <div
                  v-if="syslogForwarderStatus == 'failed'"
                  class="card-row mg-top-sm icon-and-text"
                >
                  <NsSvg :svg="ErrorFilled16" class="icon ns-error" />
                  <span>{{ $t("syslog_forwarder.syslog_export_failed") }}</span>
                </div>
                <div class="card-row">
                  <NsButton
                    kind="ghost"
                    :icon="ArrowRight20"
                    @click="$router.push('/settings/system-logs')"
                  >
                    {{ $t("cluster_status.go_to_system_logs") }}
                  </NsButton>
                </div>
              </div>
            </template>
⋮----
<span>{{
                    $t(
                      "cloud_log_manager_forwarder.cloud_log_manager_export_enabled"
                    )
                  }}</span>
⋮----
<span>{{
                    $t(
                      "cloud_log_manager_forwarder.cloud_log_manager_export_failed"
                    )
                  }}</span>
⋮----
<span>{{
                    $t("syslog_forwarder.syslog_export_enabled")
                  }}</span>
⋮----
<span>{{ $t("syslog_forwarder.syslog_export_failed") }}</span>
⋮----
{{ $t("cluster_status.go_to_system_logs") }}
⋮----
<template slot="content">
              <div class="card-rows">
                <div class="card-row">
                  <div v-if="!loading.getSubscription" class="card-row">
                    <cv-tag
                      v-if="subscription_status === 'active'"
                      kind="green"
                      :label="$t('common.active')"
                    ></cv-tag>
                    <cv-tag
                      v-else
                      kind="high-contrast"
                      :label="$t('common.not_active')"
                    ></cv-tag>
                  </div>
                </div>
                <div
                  v-if="support_active && !loading.getSubscription"
                  class="card-row"
                >
                  <div class="mg-top-sm icon-and-text">
                    <NsSvg
                      :svg="InformationFilled16"
                      class="icon ns-info shrink-0"
                    />
                    <span>{{
                      $t("settings_subscription.remote_support_in_progress")
                    }}</span>
                  </div>
                </div>
                <div v-if="!loading.getSubscription" class="card-row">
                  <NsButton
                    kind="ghost"
                    :icon="ArrowRight20"
                    @click="$router.push('/settings/subscription')"
                  >
                    {{ $t("cluster_status.go_to_subscription") }}
                  </NsButton>
                </div>
              </div>
            </template>
⋮----
<span>{{
                      $t("settings_subscription.remote_support_in_progress")
                    }}</span>
⋮----
{{ $t("cluster_status.go_to_subscription") }}
⋮----
<script>
import NotificationService from "@/mixins/notification";
import Information16 from "@carbon/icons-vue/es/information/16";
import { mapState, mapActions } from "vuex";
import to from "await-to-js";
import WebSocketService from "@/mixins/websocket";
import { mapGetters } from "vuex";
import {
  QueryParamService,
  UtilService,
  TaskService,
  IconService,
  StorageService,
  PageTitleService,
} from "@nethserver/ns8-ui-lib";
export default {
  name: "ClusterStatus",
  components: { Information16 },
  mixins: [
    NotificationService,
    QueryParamService,
    UtilService,
    TaskService,
    WebSocketService,
    IconService,
    StorageService,
    PageTitleService,
  ],
  pageTitle() {
    return this.$t("cluster_status.title");
  },
  data() {
    return {
      q: {
        testInput: "",
        testToggle: false,
        moduleToAdd: "",
        name: "",
        email: "",
      },
      nodes: [],
      apps: [],
      updates: [],
      backups: [],
      instancesNotBackedUp: [],
      isCoreUpdateAvailable: false,
      subscription_status: "inactive",
      emailNotificationEnabled: false,
      support_active: false,
      activeLokiInstance: "",
      cloudLogManagerForwarderStatus: "inactive",
      syslogForwarderStatus: "inactive",
      loading: {
        getClusterStatus: true,
        listModules: true,
        listBackups: true,
        listCoreModules: true,
        getSubscription: true,
        getEmailNotification: true,
        getSupportSession: true,
        lokiInstance: true,
      },
      error: {
        name: "",
        email: "",
        getClusterStatus: "",
        listModules: "",
        listBackups: "",
        listCoreModules: "",
        getSubscription: "",
        getEmailNotification: "",
        lokiInstance: "",
      },
    };
  },
  computed: {
    ...mapState([
      "notifications",
      "loggedUser",
      "isWebsocketConnected",
      "isClusterInitialized",
    ]),
    ...mapGetters(["leaderNode"]),
    erroredBackups() {
      const erroredInstances = [];
      for (const backup of this.backups) {
        if (!backup.enabled) {
          continue;
        }
        for (const instance of backup.instances) {
          if (instance.status && instance.status.success == false) {
            erroredInstances.push(instance.module_id);
          }
        }
      }
      return erroredInstances;
    },
    disabledBackupSchedules() {
      return this.backups.filter((b) => !b.enabled);
    },
    enabledBackupSchedules() {
      return this.backups.filter((b) => b.enabled);
    },
    nodesOffline() {
      return this.nodes.filter((n) => n.online == false);
    },
    installedModules() {
      let installedModules = [];
      for (const app of this.apps) {
        for (const installedModule of app.installed) {
          if (
            !installedModule.flags.includes("account_provider") &&
            !installedModule.flags.includes("core_module")
          ) {
            installedModules.push(installedModule);
          }
        }
      }
      return installedModules;
    },
    moduleUpdates() {
      let moduleUpdates = [];
      for (const appUpdate of this.updates) {
        for (const moduleUpdate of appUpdate.updates) {
          if (
            !moduleUpdate.flags.includes("account_provider") &&
            !moduleUpdate.flags.includes("core_module")
          ) {
            moduleUpdates.push(moduleUpdate);
          }
        }
      }
      return moduleUpdates;
    },
    numUpdates() {
      if (this.isCoreUpdateAvailable) {
        return this.moduleUpdates.length + 1;
      } else {
        return this.moduleUpdates.length;
      }
    },
  },
  watch: {
    isWebsocketConnected: function () {
      if (this.isWebsocketConnected && this.loggedUser) {
        this.retrieveData();
      }
    },
    loggedUser: function () {
      if (this.isWebsocketConnected && this.loggedUser) {
        this.retrieveData();
      }
    },
  },
  created() {
    if (this.isWebsocketConnected && this.loggedUser) {
      this.retrieveData();
    }
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.watchQueryData(vm);
      vm.queryParamsToDataForCore(vm, to.query);
    });
  },
  beforeRouteUpdate(to, from, next) {
    this.queryParamsToDataForCore(this, to.query);
    next();
  },
  methods: {
    ...mapActions(["setClusterNodesInStore"]),
    retrieveData() {
      this.getActiveLokiInstance();
      this.getClusterStatus();
      this.listModules();
      this.listCoreModules();
      this.listBackups();
      this.getSubscription();
      this.getEmailNotification();
    },
    async getSupportSession() {
      if (!this.leaderNode) {
        return;
      }
      this.error.getSupportSession = "";
      this.loading.getSupportSession = true;
      const taskAction = "get-support-session";
      this.$root.$once(
        taskAction + "-completed",
        this.getSupportSessionCompleted
      );
      const res = await to(
        this.createNodeTask(this.leaderNode.id, {
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.getSupportSession = this.getErrorMessage(err);
        this.loading.getSupportSession = false;
        return;
      }
    },
    getSupportSessionCompleted(taskContext, taskResult) {
      const output = taskResult.output;
      this.support_active = output.active;
      this.loading.getSupportSession = false;
    },
    async getSubscription() {
      this.clearErrors();
      this.loading.getSubscription = true;
      const taskAction = "get-subscription";
      this.$root.$once(
        taskAction + "-completed",
        this.getSubscriptionCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.getSubscription = this.getErrorMessage(err);
        this.loading.getSubscription = false;
        return;
      }
    },
    getSubscriptionCompleted(taskContext, taskResult) {
      const output = taskResult.output;
      if (output.subscription == null) {
        this.status = "inactive";
        this.loading.getSubscription = false;
        return;
      }
      this.getSupportSession();
      this.subscription_status = output.subscription.status;
      this.loading.getSubscription = false;
    },
    async getEmailNotification() {
      this.clearErrors();
      this.loading.getEmailNotification = true;
      const taskAction = "get-smarthost";
      this.$root.$once(
        taskAction + "-completed",
        this.getEmailNotificationCompleted
      );
      this.$root.$once(
        taskAction + "-aborted",
        this.getEmailNotificationAborted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.getEmailNotification = this.getErrorMessage(err);
        this.loading.getEmailNotification = false;
        return;
      }
    },
    getEmailNotificationCompleted(taskContext, taskResult) {
      this.emailNotificationEnabled = taskResult.output.enabled;
      this.getSupportSession();
      this.loading.getEmailNotification = false;
    },
    getEmailNotificationAborted(taskContext, taskResult) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.getEmailNotification = this.$t("error.generic_error");
      this.loading.getEmailNotification = false;
    },
    async getClusterStatus() {
      this.error.getClusterStatus = "";
      this.loading.getClusterStatus = true;
      const taskAction = "get-cluster-status";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.getClusterStatusAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.getClusterStatusCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.getClusterStatus = this.getErrorMessage(err);
        this.loading.getClusterStatus = false;
        return;
      }
    },
    getClusterStatusAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.getClusterStatus = this.$t("error.generic_error");
      this.loading.getClusterStatus = false;
    },
    getClusterStatusCompleted(taskContext, taskResult) {
      const clusterStatus = taskResult.output;
      const nodes = clusterStatus.nodes.sort(this.sortByProperty("id"));
      this.setClusterNodesInStore(nodes);
      this.nodes = nodes;
      this.setClusterNodesInStore(this.nodes);
      this.loading.getClusterStatus = false;
    },
    async listModules() {
      this.loading.listModules = true;
      this.error.listModules = "";
      const taskAction = "list-modules";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.listModulesAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.listModulesCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.listModules = this.getErrorMessage(err);
        this.loading.listModules = false;
        return;
      }
    },
    listModulesAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.listModules = this.$t("error.generic_error");
      this.loading.listModules = false;
    },
    listModulesCompleted(taskContext, taskResult) {
      let apps = taskResult.output;
      apps.sort(this.sortByProperty("name"));
      let updates = [];
      for (const app of apps) {
        const hasStableUpdate = app.updates.some((update) => update.update);
        if (hasStableUpdate) {
          updates.push(app);
        }
        app.installed.sort(this.sortModuleInstances());
      }
      this.updates = updates;
      this.apps = apps;
      this.loading.listModules = false;
    },
    async listCoreModules() {
      this.error.listCoreModules = "";
      this.loading.listCoreModules = true;
      const taskAction = "list-core-modules";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.listCoreModulesAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.listCoreModulesCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.listCoreModules = this.getErrorMessage(err);
        this.loading.listCoreModules = false;
        return;
      }
    },
    listCoreModulesAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.listCoreModules = this.$t("error.generic_error");
      this.loading.listCoreModules = false;
    },
    listCoreModulesCompleted(taskContext, taskResult) {
      const coreApps = taskResult.output;
      let isCoreUpdateAvailable = false;
      for (const coreApp of coreApps) {
        for (const coreInstance of coreApp.instances) {
          if (coreInstance.update) {
            isCoreUpdateAvailable = true;
          }
        }
      }
      this.isCoreUpdateAvailable = isCoreUpdateAvailable;
      this.loading.listCoreModules = false;
    },
    async listBackups() {
      this.loading.listBackups = true;
      this.error.listBackups = "";
      const taskAction = "list-backups";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.listBackupsAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.listBackupsCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.listBackups = this.getErrorMessage(err);
        return;
      }
    },
    listBackupsAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.listBackups = this.$t("error.generic_error");
      this.loading.listBackups = false;
    },
    listBackupsCompleted(taskContext, taskResult) {
      this.instancesNotBackedUp = taskResult.output.unconfigured_instances;
      this.backups = taskResult.output.backups;
      this.loading.listBackups = false;
    },
    async getActiveLokiInstance() {
      this.loading.lokiInstance = true;
      this.error.lokiInstance = "";
      const taskAction = "list-loki-instances";
      this.$root.$once(
        taskAction + "-aborted",
        this.getClusterLokiInstancesAborted
      );
      this.$root.$once(
        taskAction + "-completed",
        this.getClusterLokiInstancesCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            isNotificationHidden: true,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.lokiInstance = this.getErrorMessage(err);
        return;
      }
    },
    getClusterLokiInstancesAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.lokiInstance = this.$t("error.generic_error");
      this.loading.lokiInstance = false;
    },
    getClusterLokiInstancesCompleted(taskContext, taskResult) {
      for (const instance of taskResult.output.instances) {
        if (instance.active) {
          if (instance.instance_label != "") {
            this.activeLokiInstance = instance.instance_label;
          } else {
            this.activeLokiInstance = instance.instance_id;
          }
          this.cloudLogManagerForwarderStatus =
            instance.cloud_log_manager.status;
          this.syslogForwarderStatus = instance.syslog.status;
        }
      }
      this.loading.lokiInstance = false;
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../styles/carbon-utils";
.card-rows {
  display: flex;
  flex-direction: column;
}
.card-row {
  margin-bottom: $spacing-05;
  display: flex;
  justify-content: center;
}
.card-row:last-child {
  margin-bottom: 0;
}
</style>
</file>

<file path="core/ui/src/views/DomainConfiguration.vue">
<template>
  <div>
    <cv-grid fullWidth class="no-padding">
      <cv-row>
        <cv-column>
          <div class="card-grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3">
            <cv-tile v-if="!domain" light>
              <cv-skeleton-text
                :paragraph="true"
                :line-count="7"
              ></cv-skeleton-text>
            </cv-tile>
            <cv-tile v-else light>
              <div class="flex items-center justify-between relative">
                <cv-overflow-menu
                  v-if="domain.location === 'external'"
                  :flip-menu="true"
                  tip-position="top"
                  tip-alignment="end"
                  class="domain-menu top-right-overflow-menu"
                >
                  <cv-overflow-menu-item @click="showEditExternalDomain()">
                    <NsMenuItem
                      :icon="Edit20"
                      :label="$t('domains.edit_external_domain')"
                    />
                  </cv-overflow-menu-item>
                </cv-overflow-menu>
                <h3 class="title">{{ $t("domains.domain_settings") }}</h3>
              </div>
              <div class="key-value-setting top-margin">
                <span class="label">{{ $t("domains.schema") }}</span>
                <span class="value">{{ domain.schema }}</span>
              </div>
              <div class="key-value-setting">
                <span class="label">{{ $t("domains.base_dn") }}</span>
                <span class="value break-all">{{ domain.base_dn }}</span>
              </div>
              <div class="key-value-setting">
                <span class="label">{{ $t("domains.bind_dn") }}</span>
                <span class="value break-all">{{ domain.bind_dn }}</span>
              </div>
              <div class="key-value-setting">
                <span class="label">{{ $t("domains.bind_password") }}</span>
                <cv-link @click="toggleBindPassword">
                  {{
                    isShownBindPassword ? $t("common.hide") : $t("common.show")
                  }}
                </cv-link>
                <NsCodeSnippet
                  v-if="isShownBindPassword"
                  :copyTooltip="$t('common.copy_to_clipboard')"
                  :copy-feedback="$t('common.copied_to_clipboard')"
                  :feedback-aria-label="$t('common.copied_to_clipboard')"
                  :wrap-text="true"
                  :moreText="$t('common.show_more')"
                  :lessText="$t('common.show_less')"
                  hideExpandButton
                  class="password-snippet"
                  >{{ domain.bind_password }}</NsCodeSnippet
                >
              </div>
              <div class="key-value-setting">
                <span class="label">{{ $t("domains.tls") }}</span>
                <span class="value">
                  <cv-tag
                    v-if="domain.tls"
                    kind="green"
                    :label="$t('common.enabled')"
                    size="sm"
                    class="no-margin"
                  ></cv-tag>
                  <cv-tag
                    v-else
                    kind="high-contrast"
                    :label="$t('common.disabled')"
                    size="sm"
                    class="no-margin"
                  ></cv-tag>
                </span>
              </div>
              <div class="key-value-setting">
                <span class="label">{{ $t("domains.tls_verify") }}</span>
                <span class="value">
                  <cv-tag
                    v-if="domain.tls_verify"
                    kind="green"
                    :label="$t('common.enabled')"
                    size="sm"
                    class="no-margin"
                  ></cv-tag>
                  <cv-tag
                    v-else
                    kind="high-contrast"
                    :label="$t('common.disabled')"
                    size="sm"
                    class="no-margin"
                  ></cv-tag>
                </span>
              </div>
            </cv-tile>
            <template v-if="domain.location === 'internal'">
              <cv-tile
                v-if="loading.ListPasswordPolicy || loading.getPasswordWarning"
                light
              >
                <cv-skeleton-text
                  :paragraph="true"
                  :line-count="7"
                ></cv-skeleton-text>
              </cv-tile>
              <NsInfoCard
                v-else
                light
                :title="$t('domains.policy_password')"
                :icon="Password32"
              >
                <template #menu>
                  <cv-overflow-menu
                    :flip-menu="true"
                    tip-position="top"
                    tip-alignment="end"
                    class="top-right-overflow-menu"
                  >
                    <cv-overflow-menu-item @click="showPasswordPolicy()">
                      <NsMenuItem
                        :icon="Edit20"
                        :label="$t('domains.edit_password_policy')"
                      />
                    </cv-overflow-menu-item>
                    <cv-overflow-menu-item @click="showPasswordWarning()">
                      <NsMenuItem
                        :icon="Edit20"
                        :label="$t('domains.edit_password_warning')"
                        :disabled="!policy.expiration.enforced"
                      />
                    </cv-overflow-menu-item>
                  </cv-overflow-menu>
                </template>
                <template #content>
                  <div class="provider-card-content">
                    <div class="row">
                      <span class="label right-margin">{{
                        $t("domains.expiration")
                      }}</span>
                      <cv-tag
                        v-if="policy.expiration.enforced"
                        kind="green"
                        :label="$t('common.enabled')"
                        size="sm"
                        class="no-margin"
                      ></cv-tag>
                      <cv-tag
                        v-else
                        kind="high-contrast"
                        :label="$t('common.disabled')"
                        size="sm"
                        class="no-margin"
                      ></cv-tag>
                    </div>
                    <div class="row">
                      <span class="label right-margin">{{
                        $t("domains.strength")
                      }}</span>
                      <cv-tag
                        v-if="policy.strength.enforced"
                        kind="green"
                        :label="$t('common.enabled')"
                        size="sm"
                      ></cv-tag>
                      <cv-tag
                        v-else
                        kind="high-contrast"
                        :label="$t('common.disabled')"
                        size="sm"
                      ></cv-tag>
                    </div>
                    <div class="row">
                      <span class="label right-margin">{{
                        $t("domains.password_warning")
                      }}</span>
                      <cv-tag
                        v-if="
                          policy.warning.notification &&
                          policy.expiration.enforced &&
                          policy.warning.smtp_enabled
                        "
                        kind="green"
                        :label="$t('common.enabled')"
                        size="sm"
                      ></cv-tag>
                      <cv-tag
                        v-else
                        kind="high-contrast"
                        :label="$t('common.disabled')"
                        size="sm"
                      ></cv-tag>
                    </div>
                  </div>
                </template>
              </NsInfoCard>
            </template>
            <NsInfoCard
              v-if="domain.location === 'internal'"
              light
              :title="$t('domains.users_admin_page_title')"
              :titleTooltip="$t('domains.users_admin_page_tooltips')"
              titleTooltipAlignment="center"
              titleTooltipDirection="bottom"
              :description="$t('domains.users_admin_page_description')"
              :icon="Wikis32"
              :loading="loading.getFqdn"
              :isErrorShown="!!error.getFqdn"
              :errorTitle="
                $t('error.cannot_retrieve_users_admin_configuration')
              "
              :errorDescription="error.getFqdn"
            >
              <template slot="content">
                <NsButton
                  v-show="!loading.getFqdn"
                  kind="ghost"
                  :icon="Launch20"
                  @click="goToUserAdminPage()"
                >
                  {{ $t("domains.open_users_admin_portal") }}
                </NsButton>
              </template>
            </NsInfoCard>
          </div>
        </cv-column>
      </cv-row>
      <cv-row>
        <cv-column>
          <h4
            ref="providers"
            :class="[
              'mg-bottom-md',
              { 'highlight-anchor': highlightAnchor == 'providers' },
            ]"
          >
            {{ $t("domain_configuration.providers") }}
          </h4>
        </cv-column>
      </cv-row>
      <cv-row v-if="error.listUserDomains">
        <cv-column>
          <NsInlineNotification
            kind="error"
            :title="$t('action.list-user-domains')"
            :description="error.listUserDomains"
            :showCloseButton="false"
          />
        </cv-column>
      </cv-row>
      <cv-row v-if="error.setProviderLabel">
        <cv-column>
          <NsInlineNotification
            kind="error"
            :title="$t('action.set-name')"
            :description="error.setProviderLabel"
            :showCloseButton="false"
          />
        </cv-column>
      </cv-row>
      <cv-row v-if="error.removeInternalProvider">
        <cv-column>
          <NsInlineNotification
            kind="error"
            :title="$t('action.remove-internal-provider')"
            :description="error.removeInternalProvider"
            :showCloseButton="false"
          />
        </cv-column>
      </cv-row>
      <cv-row v-if="error.removeExternalProvider">
        <cv-column>
          <NsInlineNotification
            kind="error"
            :title="$t('action.remove-external-provider')"
            :description="error.removeExternalProvider"
            :showCloseButton="false"
          />
        </cv-column>
      </cv-row>
      <cv-row v-if="unconfiguredProviders.length">
        <cv-column>
          <NsInlineNotification
            kind="warning"
            :title="$t('domain_configuration.unconfigured_providers_title')"
            :description="
              $t('domain_configuration.unconfigured_providers_description')
            "
            :showCloseButton="false"
          />
        </cv-column>
      </cv-row>
      <cv-row v-if="providerToDelete">
        <cv-column>
          <NsInlineNotification
            kind="warning"
            :title="
              $t('domain_configuration.provider_is_going_to_be_deleted', {
                object: providerToDelete.id,
              })
            "
            :actionLabel="$t('common.cancel')"
            @action="cancelDeleteUnconfiguredProvider()"
            :showCloseButton="false"
            :timer="DELETE_DELAY"
          />
        </cv-column>
      </cv-row>
      <cv-row v-if="loading.listUserDomains">
        <cv-column>
          <div
            class="card-grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 3xl:grid-cols-4"
          >
            <cv-tile v-for="index in 2" :key="index" light>
              <cv-skeleton-text
                :paragraph="true"
                :line-count="7"
              ></cv-skeleton-text>
            </cv-tile>
          </div>
        </cv-column>
      </cv-row>
      <template v-else-if="domain">
        <cv-row class="toolbar">
          <cv-column>
            <NsButton
              v-if="
                domain.location === 'internal' ||
                (domain.location === 'external' && !domain.tls_verify)
              "
              kind="secondary"
              :icon="Add20"
              @click="showAddProviderModal()"
              :disabled="
                loading.listUserDomains ||
                (domain.location === 'external' && domain.tls_verify)
              "
              >{{ $t("domain_configuration.add_provider") }}
            </NsButton>
            <cv-tooltip
              v-else
              alignment="center"
              direction="right"
              :tip="
                $t(
                  `domain_configuration.external_providers_tooltip_description`
                )
              "
            >
              <NsButton kind="secondary" :icon="Add20" disabled
                >{{ $t("domain_configuration.add_provider") }}
              </NsButton>
            </cv-tooltip>
          </cv-column>
        </cv-row>
        <cv-row>
          <cv-column>
            <div
              class="card-grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 3xl:grid-cols-4"
            >
              <template v-for="provider in unconfiguredProviders">
                <NsInfoCard
                  v-if="!provider.host"
                  :key="provider.id"
                  light
                  :title="$t('domain_configuration.unconfigured_provider')"
                  :icon="WarningAlt32"
                >
                  <template #menu>
                    <cv-overflow-menu
                      :flip-menu="true"
                      tip-position="top"
                      tip-alignment="end"
                      class="top-right-overflow-menu"
                    >
                      <cv-overflow-menu-item
                        @click="showSetProviderLabelModal(provider)"
                      >
                        <NsMenuItem
                          :icon="Edit20"
                          :label="
                            $t('domain_configuration.edit_provider_label')
                          "
                        />
                      </cv-overflow-menu-item>
                      <NsMenuDivider />
                      <cv-overflow-menu-item
                        danger
                        @click="willDeleteUnconfiguredProvider(provider)"
                      >
                        <NsMenuItem
                          :icon="TrashCan20"
                          :label="$t('common.delete')"
                        />
                      </cv-overflow-menu-item>
                    </cv-overflow-menu>
                  </template>
                  <template #content>
                    <div class="provider-card-content">
                      <div class="row icon-and-text">
                        <NsSvg :svg="Application20" class="icon" />
                        <span>{{
                          provider.ui_name
                            ? provider.ui_name + " (" + provider.id + ")"
                            : provider.id
                        }}</span>
                      </div>
                      <div v-if="provider.node" class="row icon-and-text">
                        <NsSvg :svg="Chip20" class="icon" />
                        <span>{{ getNodeLabel(provider.node) }}</span>
                      </div>
                      <div v-if="provider.host" class="row icon-and-text">
                        <NsSvg :svg="Network_220" class="icon" />
                        <span>{{ provider.host }}</span>
                        <span v-if="provider.port">:{{ provider.port }}</span>
                      </div>
                      <div class="row actions">
                        <NsButton
                          kind="ghost"
                          :icon="Tools20"
                          @click="showUnconfiguredProviderModal(provider)"
                          >{{ $t("domains.resume_configuration") }}
                        </NsButton>
                      </div>
                    </div>
                  </template>
                </NsInfoCard>
              </template>
              <NsInfoCard
                v-for="provider in configuredProviders"
                :key="provider.id"
                light
                :title="provider.ui_name ? provider.ui_name : provider.id"
                :icon="domain.location == 'internal' ? Application32 : Link32"
              >
                <template #menu>
                  <cv-overflow-menu
                    :flip-menu="true"
                    tip-position="top"
                    tip-alignment="end"
                    class="top-right-overflow-menu"
                  >
                    <cv-overflow-menu-item
                      @click="showSetProviderLabelModal(provider)"
                    >
                      <NsMenuItem
                        :icon="Edit20"
                        :label="$t('domain_configuration.edit_provider_label')"
                      />
                    </cv-overflow-menu-item>
                    <NsMenuDivider />
                    <cv-overflow-menu-item
                      danger
                      @click="showDeleteProviderModal(provider)"
                    >
                      <NsMenuItem
                        :icon="TrashCan20"
                        :label="$t('common.delete')"
                      />
                    </cv-overflow-menu-item>
                  </cv-overflow-menu>
                </template>
                <template #content>
                  <div class="provider-card-content">
                    <div v-if="provider.ui_name" class="row">
                      {{ provider.id }}
                    </div>
                    <div v-if="provider.node" class="row icon-and-text">
                      <NsSvg :svg="Chip20" class="icon" />
                      <span>{{ getNodeLabel(provider.node) }}</span>
                    </div>
                    <div v-if="provider.host" class="row icon-and-text">
                      <NsSvg :svg="Network_220" class="icon" />
                      <span>{{ provider.host }}</span>
                      <span v-if="provider.port">:{{ provider.port }}</span>
                    </div>
                    <div v-if="provider.file_server" class="row actions">
                      <NsButton
                        kind="ghost"
                        :icon="Application20"
                        @click="goToFileServer(provider)"
                        >{{ $t("samba.open_file_server") }}</NsButton
                      >
                    </div>
                  </div>
                </template>
              </NsInfoCard>
            </div>
          </cv-column>
        </cv-row>
      </template>
    </cv-grid>
    <NsModal
      size="default"
      :visible="isShownLastProviderModal"
      @modal-hidden="isShownLastProviderModal = false"
    >
      <template slot="title">{{
        $t("domain_configuration.cannot_delete_provider")
      }}</template>
      <template slot="content">
        <NsInlineNotification
          kind="info"
          :title="$t('domain_configuration.cannot_delete_only_provider')"
          :description="
            $t('domain_configuration.cannot_delete_provider_description')
          "
          :showCloseButton="false"
        />
      </template>
      <template slot="secondary-button">{{ $t("common.got_it") }}</template>
    </NsModal>
    <template v-if="domain">
      <AddInternalProviderModal
        v-if="domain.location == 'internal'"
        :isShown="isShownAddInternalProviderModal"
        :domain="domain"
        :domains="domains"
        :isResumeConfiguration="addProvider.isResumeConfiguration"
        :providerId="addProvider.providerId"
        @hide="hideAddInternalProviderModal"
        @reloadDomains="listUserDomains"
      />
      <AddExternalProviderModal
        v-else
        :isShown="isShownAddExternalProviderModal"
        :domain="domain"
        @hide="hideAddExternalProviderModal"
        @reloadDomains="listUserDomains"
      />
    </template>
    <NsDangerDeleteModal
      :isShown="isShownDeleteLdapProviderModal"
      :name="currentProvider.id"
      :title="$t('domain_configuration.delete_provider')"
      :warning="$t('common.please_read_carefully')"
      :description="
        $t('domain_configuration.delete_provider_confirm', {
          name: currentProvider.id,
        })
      "
      :typeToConfirm="
        $t('common.type_to_confirm', { name: currentProvider.id })
      "
      @hide="hideDeleteLdapProviderModal"
      @confirmDelete="deleteLdapProvider"
    />
    <DeleteSambaProviderModal
      :isShown="isShownDeleteSambaProviderModal"
      :provider="currentProvider"
      @hide="hideDeleteSambaProviderModal"
      @reloadDomains="listUserDomains"
    />
    <EditPasswordPolicy
      :isShown="isShownPasswordPolicyModal"
      :policy="policy"
      @hide="hideisShownPasswordPolicyModal"
      @confirm="setPasswordPolicy()"
    />
    <EditPasswordWarningModal
      :isShown="isShownPasswordWarningModal"
      :policy="policy"
      :error="error"
      @hide="hideisShownPasswordWarningModal"
      @confirm="setPasswordWarning()"
    />
    <EditExternalDomainModal
      :isShown="isShownEditExternalDomainModal"
      :domain="domain"
      @hide="hideisShownEditExternalDomainModal"
      @reload="reloadExternalDomain"
    />
    <NsModal
      size="default"
      :visible="isShownSetProviderLabelModal"
      @modal-hidden="hideSetProviderLabelModal"
      @primary-click="setProviderLabel"
    >
      <template slot="title">{{
        $t("domain_configuration.edit_provider_label")
      }}</template>
      <template slot="content">
        <template v-if="currentProvider">
          <cv-form @submit.prevent="setProviderLabel">
            <cv-text-input
              :label="
                $t('domain_configuration.provider_label') +
                ' (' +
                $t('common.optional') +
                ')'
              "
              v-model.trim="newProviderLabel"
              :placeholder="$t('common.no_label')"
              :helper-text="$t('domain_configuration.provider_label_tooltip')"
              maxlength="24"
              ref="newProviderLabel"
            >
            </cv-text-input>
            <NsInlineNotification
              v-if="error.setProviderLabel"
              kind="error"
              :title="$t('action.set-name')"
              :description="error.setProviderLabel"
              :showCloseButton="false"
            />
          </cv-form>
        </template>
      </template>
      <template slot="secondary-button">{{ $t("common.cancel") }}</template>
      <template slot="primary-button">{{
        $t("domain_configuration.edit_provider_label")
      }}</template>
    </NsModal>
  </div>
</template>
⋮----
<h3 class="title">{{ $t("domains.domain_settings") }}</h3>
⋮----
<span class="label">{{ $t("domains.schema") }}</span>
<span class="value">{{ domain.schema }}</span>
⋮----
<span class="label">{{ $t("domains.base_dn") }}</span>
<span class="value break-all">{{ domain.base_dn }}</span>
⋮----
<span class="label">{{ $t("domains.bind_dn") }}</span>
<span class="value break-all">{{ domain.bind_dn }}</span>
⋮----
<span class="label">{{ $t("domains.bind_password") }}</span>
⋮----
{{
                    isShownBindPassword ? $t("common.hide") : $t("common.show")
                  }}
⋮----
>{{ domain.bind_password }}</NsCodeSnippet
⋮----
<span class="label">{{ $t("domains.tls") }}</span>
⋮----
<span class="label">{{ $t("domains.tls_verify") }}</span>
⋮----
<template v-if="domain.location === 'internal'">
              <cv-tile
                v-if="loading.ListPasswordPolicy || loading.getPasswordWarning"
                light
              >
                <cv-skeleton-text
                  :paragraph="true"
                  :line-count="7"
                ></cv-skeleton-text>
              </cv-tile>
              <NsInfoCard
                v-else
                light
                :title="$t('domains.policy_password')"
                :icon="Password32"
              >
                <template #menu>
                  <cv-overflow-menu
                    :flip-menu="true"
                    tip-position="top"
                    tip-alignment="end"
                    class="top-right-overflow-menu"
                  >
                    <cv-overflow-menu-item @click="showPasswordPolicy()">
                      <NsMenuItem
                        :icon="Edit20"
                        :label="$t('domains.edit_password_policy')"
                      />
                    </cv-overflow-menu-item>
                    <cv-overflow-menu-item @click="showPasswordWarning()">
                      <NsMenuItem
                        :icon="Edit20"
                        :label="$t('domains.edit_password_warning')"
                        :disabled="!policy.expiration.enforced"
                      />
                    </cv-overflow-menu-item>
                  </cv-overflow-menu>
                </template>
                <template #content>
                  <div class="provider-card-content">
                    <div class="row">
                      <span class="label right-margin">{{
                        $t("domains.expiration")
                      }}</span>
                      <cv-tag
                        v-if="policy.expiration.enforced"
                        kind="green"
                        :label="$t('common.enabled')"
                        size="sm"
                        class="no-margin"
                      ></cv-tag>
                      <cv-tag
                        v-else
                        kind="high-contrast"
                        :label="$t('common.disabled')"
                        size="sm"
                        class="no-margin"
                      ></cv-tag>
                    </div>
                    <div class="row">
                      <span class="label right-margin">{{
                        $t("domains.strength")
                      }}</span>
                      <cv-tag
                        v-if="policy.strength.enforced"
                        kind="green"
                        :label="$t('common.enabled')"
                        size="sm"
                      ></cv-tag>
                      <cv-tag
                        v-else
                        kind="high-contrast"
                        :label="$t('common.disabled')"
                        size="sm"
                      ></cv-tag>
                    </div>
                    <div class="row">
                      <span class="label right-margin">{{
                        $t("domains.password_warning")
                      }}</span>
                      <cv-tag
                        v-if="
                          policy.warning.notification &&
                          policy.expiration.enforced &&
                          policy.warning.smtp_enabled
                        "
                        kind="green"
                        :label="$t('common.enabled')"
                        size="sm"
                      ></cv-tag>
                      <cv-tag
                        v-else
                        kind="high-contrast"
                        :label="$t('common.disabled')"
                        size="sm"
                      ></cv-tag>
                    </div>
                  </div>
                </template>
              </NsInfoCard>
            </template>
⋮----
<template #menu>
                  <cv-overflow-menu
                    :flip-menu="true"
                    tip-position="top"
                    tip-alignment="end"
                    class="top-right-overflow-menu"
                  >
                    <cv-overflow-menu-item @click="showPasswordPolicy()">
                      <NsMenuItem
                        :icon="Edit20"
                        :label="$t('domains.edit_password_policy')"
                      />
                    </cv-overflow-menu-item>
                    <cv-overflow-menu-item @click="showPasswordWarning()">
                      <NsMenuItem
                        :icon="Edit20"
                        :label="$t('domains.edit_password_warning')"
                        :disabled="!policy.expiration.enforced"
                      />
                    </cv-overflow-menu-item>
                  </cv-overflow-menu>
                </template>
<template #content>
                  <div class="provider-card-content">
                    <div class="row">
                      <span class="label right-margin">{{
                        $t("domains.expiration")
                      }}</span>
                      <cv-tag
                        v-if="policy.expiration.enforced"
                        kind="green"
                        :label="$t('common.enabled')"
                        size="sm"
                        class="no-margin"
                      ></cv-tag>
                      <cv-tag
                        v-else
                        kind="high-contrast"
                        :label="$t('common.disabled')"
                        size="sm"
                        class="no-margin"
                      ></cv-tag>
                    </div>
                    <div class="row">
                      <span class="label right-margin">{{
                        $t("domains.strength")
                      }}</span>
                      <cv-tag
                        v-if="policy.strength.enforced"
                        kind="green"
                        :label="$t('common.enabled')"
                        size="sm"
                      ></cv-tag>
                      <cv-tag
                        v-else
                        kind="high-contrast"
                        :label="$t('common.disabled')"
                        size="sm"
                      ></cv-tag>
                    </div>
                    <div class="row">
                      <span class="label right-margin">{{
                        $t("domains.password_warning")
                      }}</span>
                      <cv-tag
                        v-if="
                          policy.warning.notification &&
                          policy.expiration.enforced &&
                          policy.warning.smtp_enabled
                        "
                        kind="green"
                        :label="$t('common.enabled')"
                        size="sm"
                      ></cv-tag>
                      <cv-tag
                        v-else
                        kind="high-contrast"
                        :label="$t('common.disabled')"
                        size="sm"
                      ></cv-tag>
                    </div>
                  </div>
                </template>
⋮----
<span class="label right-margin">{{
                        $t("domains.expiration")
                      }}</span>
⋮----
<span class="label right-margin">{{
                        $t("domains.strength")
                      }}</span>
⋮----
<span class="label right-margin">{{
                        $t("domains.password_warning")
                      }}</span>
⋮----
<template slot="content">
                <NsButton
                  v-show="!loading.getFqdn"
                  kind="ghost"
                  :icon="Launch20"
                  @click="goToUserAdminPage()"
                >
                  {{ $t("domains.open_users_admin_portal") }}
                </NsButton>
              </template>
⋮----
{{ $t("domains.open_users_admin_portal") }}
⋮----
{{ $t("domain_configuration.providers") }}
⋮----
<template v-else-if="domain">
        <cv-row class="toolbar">
          <cv-column>
            <NsButton
              v-if="
                domain.location === 'internal' ||
                (domain.location === 'external' && !domain.tls_verify)
              "
              kind="secondary"
              :icon="Add20"
              @click="showAddProviderModal()"
              :disabled="
                loading.listUserDomains ||
                (domain.location === 'external' && domain.tls_verify)
              "
              >{{ $t("domain_configuration.add_provider") }}
            </NsButton>
            <cv-tooltip
              v-else
              alignment="center"
              direction="right"
              :tip="
                $t(
                  `domain_configuration.external_providers_tooltip_description`
                )
              "
            >
              <NsButton kind="secondary" :icon="Add20" disabled
                >{{ $t("domain_configuration.add_provider") }}
              </NsButton>
            </cv-tooltip>
          </cv-column>
        </cv-row>
        <cv-row>
          <cv-column>
            <div
              class="card-grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 3xl:grid-cols-4"
            >
              <template v-for="provider in unconfiguredProviders">
                <NsInfoCard
                  v-if="!provider.host"
                  :key="provider.id"
                  light
                  :title="$t('domain_configuration.unconfigured_provider')"
                  :icon="WarningAlt32"
                >
                  <template #menu>
                    <cv-overflow-menu
                      :flip-menu="true"
                      tip-position="top"
                      tip-alignment="end"
                      class="top-right-overflow-menu"
                    >
                      <cv-overflow-menu-item
                        @click="showSetProviderLabelModal(provider)"
                      >
                        <NsMenuItem
                          :icon="Edit20"
                          :label="
                            $t('domain_configuration.edit_provider_label')
                          "
                        />
                      </cv-overflow-menu-item>
                      <NsMenuDivider />
                      <cv-overflow-menu-item
                        danger
                        @click="willDeleteUnconfiguredProvider(provider)"
                      >
                        <NsMenuItem
                          :icon="TrashCan20"
                          :label="$t('common.delete')"
                        />
                      </cv-overflow-menu-item>
                    </cv-overflow-menu>
                  </template>
                  <template #content>
                    <div class="provider-card-content">
                      <div class="row icon-and-text">
                        <NsSvg :svg="Application20" class="icon" />
                        <span>{{
                          provider.ui_name
                            ? provider.ui_name + " (" + provider.id + ")"
                            : provider.id
                        }}</span>
                      </div>
                      <div v-if="provider.node" class="row icon-and-text">
                        <NsSvg :svg="Chip20" class="icon" />
                        <span>{{ getNodeLabel(provider.node) }}</span>
                      </div>
                      <div v-if="provider.host" class="row icon-and-text">
                        <NsSvg :svg="Network_220" class="icon" />
                        <span>{{ provider.host }}</span>
                        <span v-if="provider.port">:{{ provider.port }}</span>
                      </div>
                      <div class="row actions">
                        <NsButton
                          kind="ghost"
                          :icon="Tools20"
                          @click="showUnconfiguredProviderModal(provider)"
                          >{{ $t("domains.resume_configuration") }}
                        </NsButton>
                      </div>
                    </div>
                  </template>
                </NsInfoCard>
              </template>
              <NsInfoCard
                v-for="provider in configuredProviders"
                :key="provider.id"
                light
                :title="provider.ui_name ? provider.ui_name : provider.id"
                :icon="domain.location == 'internal' ? Application32 : Link32"
              >
                <template #menu>
                  <cv-overflow-menu
                    :flip-menu="true"
                    tip-position="top"
                    tip-alignment="end"
                    class="top-right-overflow-menu"
                  >
                    <cv-overflow-menu-item
                      @click="showSetProviderLabelModal(provider)"
                    >
                      <NsMenuItem
                        :icon="Edit20"
                        :label="$t('domain_configuration.edit_provider_label')"
                      />
                    </cv-overflow-menu-item>
                    <NsMenuDivider />
                    <cv-overflow-menu-item
                      danger
                      @click="showDeleteProviderModal(provider)"
                    >
                      <NsMenuItem
                        :icon="TrashCan20"
                        :label="$t('common.delete')"
                      />
                    </cv-overflow-menu-item>
                  </cv-overflow-menu>
                </template>
                <template #content>
                  <div class="provider-card-content">
                    <div v-if="provider.ui_name" class="row">
                      {{ provider.id }}
                    </div>
                    <div v-if="provider.node" class="row icon-and-text">
                      <NsSvg :svg="Chip20" class="icon" />
                      <span>{{ getNodeLabel(provider.node) }}</span>
                    </div>
                    <div v-if="provider.host" class="row icon-and-text">
                      <NsSvg :svg="Network_220" class="icon" />
                      <span>{{ provider.host }}</span>
                      <span v-if="provider.port">:{{ provider.port }}</span>
                    </div>
                    <div v-if="provider.file_server" class="row actions">
                      <NsButton
                        kind="ghost"
                        :icon="Application20"
                        @click="goToFileServer(provider)"
                        >{{ $t("samba.open_file_server") }}</NsButton
                      >
                    </div>
                  </div>
                </template>
              </NsInfoCard>
            </div>
          </cv-column>
        </cv-row>
      </template>
⋮----
>{{ $t("domain_configuration.add_provider") }}
⋮----
>{{ $t("domain_configuration.add_provider") }}
⋮----
<template v-for="provider in unconfiguredProviders">
                <NsInfoCard
                  v-if="!provider.host"
                  :key="provider.id"
                  light
                  :title="$t('domain_configuration.unconfigured_provider')"
                  :icon="WarningAlt32"
                >
                  <template #menu>
                    <cv-overflow-menu
                      :flip-menu="true"
                      tip-position="top"
                      tip-alignment="end"
                      class="top-right-overflow-menu"
                    >
                      <cv-overflow-menu-item
                        @click="showSetProviderLabelModal(provider)"
                      >
                        <NsMenuItem
                          :icon="Edit20"
                          :label="
                            $t('domain_configuration.edit_provider_label')
                          "
                        />
                      </cv-overflow-menu-item>
                      <NsMenuDivider />
                      <cv-overflow-menu-item
                        danger
                        @click="willDeleteUnconfiguredProvider(provider)"
                      >
                        <NsMenuItem
                          :icon="TrashCan20"
                          :label="$t('common.delete')"
                        />
                      </cv-overflow-menu-item>
                    </cv-overflow-menu>
                  </template>
                  <template #content>
                    <div class="provider-card-content">
                      <div class="row icon-and-text">
                        <NsSvg :svg="Application20" class="icon" />
                        <span>{{
                          provider.ui_name
                            ? provider.ui_name + " (" + provider.id + ")"
                            : provider.id
                        }}</span>
                      </div>
                      <div v-if="provider.node" class="row icon-and-text">
                        <NsSvg :svg="Chip20" class="icon" />
                        <span>{{ getNodeLabel(provider.node) }}</span>
                      </div>
                      <div v-if="provider.host" class="row icon-and-text">
                        <NsSvg :svg="Network_220" class="icon" />
                        <span>{{ provider.host }}</span>
                        <span v-if="provider.port">:{{ provider.port }}</span>
                      </div>
                      <div class="row actions">
                        <NsButton
                          kind="ghost"
                          :icon="Tools20"
                          @click="showUnconfiguredProviderModal(provider)"
                          >{{ $t("domains.resume_configuration") }}
                        </NsButton>
                      </div>
                    </div>
                  </template>
                </NsInfoCard>
              </template>
⋮----
<template #menu>
                    <cv-overflow-menu
                      :flip-menu="true"
                      tip-position="top"
                      tip-alignment="end"
                      class="top-right-overflow-menu"
                    >
                      <cv-overflow-menu-item
                        @click="showSetProviderLabelModal(provider)"
                      >
                        <NsMenuItem
                          :icon="Edit20"
                          :label="
                            $t('domain_configuration.edit_provider_label')
                          "
                        />
                      </cv-overflow-menu-item>
                      <NsMenuDivider />
                      <cv-overflow-menu-item
                        danger
                        @click="willDeleteUnconfiguredProvider(provider)"
                      >
                        <NsMenuItem
                          :icon="TrashCan20"
                          :label="$t('common.delete')"
                        />
                      </cv-overflow-menu-item>
                    </cv-overflow-menu>
                  </template>
<template #content>
                    <div class="provider-card-content">
                      <div class="row icon-and-text">
                        <NsSvg :svg="Application20" class="icon" />
                        <span>{{
                          provider.ui_name
                            ? provider.ui_name + " (" + provider.id + ")"
                            : provider.id
                        }}</span>
                      </div>
                      <div v-if="provider.node" class="row icon-and-text">
                        <NsSvg :svg="Chip20" class="icon" />
                        <span>{{ getNodeLabel(provider.node) }}</span>
                      </div>
                      <div v-if="provider.host" class="row icon-and-text">
                        <NsSvg :svg="Network_220" class="icon" />
                        <span>{{ provider.host }}</span>
                        <span v-if="provider.port">:{{ provider.port }}</span>
                      </div>
                      <div class="row actions">
                        <NsButton
                          kind="ghost"
                          :icon="Tools20"
                          @click="showUnconfiguredProviderModal(provider)"
                          >{{ $t("domains.resume_configuration") }}
                        </NsButton>
                      </div>
                    </div>
                  </template>
⋮----
<span>{{
                          provider.ui_name
                            ? provider.ui_name + " (" + provider.id + ")"
                            : provider.id
                        }}</span>
⋮----
<span>{{ getNodeLabel(provider.node) }}</span>
⋮----
<span>{{ provider.host }}</span>
<span v-if="provider.port">:{{ provider.port }}</span>
⋮----
>{{ $t("domains.resume_configuration") }}
⋮----
<template #menu>
                  <cv-overflow-menu
                    :flip-menu="true"
                    tip-position="top"
                    tip-alignment="end"
                    class="top-right-overflow-menu"
                  >
                    <cv-overflow-menu-item
                      @click="showSetProviderLabelModal(provider)"
                    >
                      <NsMenuItem
                        :icon="Edit20"
                        :label="$t('domain_configuration.edit_provider_label')"
                      />
                    </cv-overflow-menu-item>
                    <NsMenuDivider />
                    <cv-overflow-menu-item
                      danger
                      @click="showDeleteProviderModal(provider)"
                    >
                      <NsMenuItem
                        :icon="TrashCan20"
                        :label="$t('common.delete')"
                      />
                    </cv-overflow-menu-item>
                  </cv-overflow-menu>
                </template>
<template #content>
                  <div class="provider-card-content">
                    <div v-if="provider.ui_name" class="row">
                      {{ provider.id }}
                    </div>
                    <div v-if="provider.node" class="row icon-and-text">
                      <NsSvg :svg="Chip20" class="icon" />
                      <span>{{ getNodeLabel(provider.node) }}</span>
                    </div>
                    <div v-if="provider.host" class="row icon-and-text">
                      <NsSvg :svg="Network_220" class="icon" />
                      <span>{{ provider.host }}</span>
                      <span v-if="provider.port">:{{ provider.port }}</span>
                    </div>
                    <div v-if="provider.file_server" class="row actions">
                      <NsButton
                        kind="ghost"
                        :icon="Application20"
                        @click="goToFileServer(provider)"
                        >{{ $t("samba.open_file_server") }}</NsButton
                      >
                    </div>
                  </div>
                </template>
⋮----
{{ provider.id }}
⋮----
<span>{{ getNodeLabel(provider.node) }}</span>
⋮----
<span>{{ provider.host }}</span>
<span v-if="provider.port">:{{ provider.port }}</span>
⋮----
>{{ $t("samba.open_file_server") }}</NsButton
⋮----
<template slot="title">{{
        $t("domain_configuration.cannot_delete_provider")
      }}</template>
<template slot="content">
        <NsInlineNotification
          kind="info"
          :title="$t('domain_configuration.cannot_delete_only_provider')"
          :description="
            $t('domain_configuration.cannot_delete_provider_description')
          "
          :showCloseButton="false"
        />
      </template>
<template slot="secondary-button">{{ $t("common.got_it") }}</template>
⋮----
<template v-if="domain">
      <AddInternalProviderModal
        v-if="domain.location == 'internal'"
        :isShown="isShownAddInternalProviderModal"
        :domain="domain"
        :domains="domains"
        :isResumeConfiguration="addProvider.isResumeConfiguration"
        :providerId="addProvider.providerId"
        @hide="hideAddInternalProviderModal"
        @reloadDomains="listUserDomains"
      />
      <AddExternalProviderModal
        v-else
        :isShown="isShownAddExternalProviderModal"
        :domain="domain"
        @hide="hideAddExternalProviderModal"
        @reloadDomains="listUserDomains"
      />
    </template>
⋮----
<template slot="title">{{
        $t("domain_configuration.edit_provider_label")
      }}</template>
<template slot="content">
        <template v-if="currentProvider">
          <cv-form @submit.prevent="setProviderLabel">
            <cv-text-input
              :label="
                $t('domain_configuration.provider_label') +
                ' (' +
                $t('common.optional') +
                ')'
              "
              v-model.trim="newProviderLabel"
              :placeholder="$t('common.no_label')"
              :helper-text="$t('domain_configuration.provider_label_tooltip')"
              maxlength="24"
              ref="newProviderLabel"
            >
            </cv-text-input>
            <NsInlineNotification
              v-if="error.setProviderLabel"
              kind="error"
              :title="$t('action.set-name')"
              :description="error.setProviderLabel"
              :showCloseButton="false"
            />
          </cv-form>
        </template>
      </template>
⋮----
<template v-if="currentProvider">
          <cv-form @submit.prevent="setProviderLabel">
            <cv-text-input
              :label="
                $t('domain_configuration.provider_label') +
                ' (' +
                $t('common.optional') +
                ')'
              "
              v-model.trim="newProviderLabel"
              :placeholder="$t('common.no_label')"
              :helper-text="$t('domain_configuration.provider_label_tooltip')"
              maxlength="24"
              ref="newProviderLabel"
            >
            </cv-text-input>
            <NsInlineNotification
              v-if="error.setProviderLabel"
              kind="error"
              :title="$t('action.set-name')"
              :description="error.setProviderLabel"
              :showCloseButton="false"
            />
          </cv-form>
        </template>
⋮----
<template slot="secondary-button">{{ $t("common.cancel") }}</template>
<template slot="primary-button">{{
        $t("domain_configuration.edit_provider_label")
      }}</template>
⋮----
<script>
import {
  QueryParamService,
  UtilService,
  TaskService,
  IconService,
  PageTitleService,
} from "@nethserver/ns8-ui-lib";
import to from "await-to-js";
import AddInternalProviderModal from "@/components/domains/AddInternalProviderModal";
import AddExternalProviderModal from "@/components/domains/AddExternalProviderModal";
import DeleteSambaProviderModal from "@/components/domains/DeleteSambaProviderModal";
import EditPasswordPolicy from "@/components/domains/EditPasswordPolicy";
import EditPasswordWarningModal from "@/components/domains/EditPasswordWarningModal";
import EditExternalDomainModal from "@/components/domains/EditExternalDomainModal";
import Password32 from "@carbon/icons-vue/es/password/32";
import { mapState } from "vuex";
export default {
  name: "DomainConfiguration",
  components: {
    AddInternalProviderModal,
    AddExternalProviderModal,
    DeleteSambaProviderModal,
    EditPasswordPolicy,
    EditPasswordWarningModal,
    EditExternalDomainModal,
  },
  mixins: [
    TaskService,
    UtilService,
    QueryParamService,
    IconService,
    PageTitleService,
  ],
  props: {
    domainName: { type: String, required: true },
  },
  pageTitle() {
    return this.$t("domain_configuration.title");
  },
  data() {
    return {
      Password32,
      q: {},
      isShownAddInternalProviderModal: false,
      isShownAddExternalProviderModal: false,
      isShownDeleteLdapProviderModal: false,
      isShownDeleteSambaProviderModal: false,
      isShownPasswordPolicyModal: false,
      isShownPasswordWarningModal: false,
      isShownEditExternalDomainModal: false,
      hostnameNode: "",
      domainNode: "",
      policy: {
        expiration: {
          enforced: false,
          min_age: 0,
          max_age: 0,
        },
        warning: {
          notification: false,
          days: "7",
          mail_from: "",
          mail_subject: "",
          mail_template_name: "default_en",
          mail_template_content: "",
          domain: "",
          smtp_enabled: false,
        },
        strength: {
          complexity_check: false,
          enforced: false,
          history_length: 5,
          password_min_length: 8,
        },
      },
      domain: {
        location: "",
      },
      isShownLastProviderModal: false,
      currentProvider: {
        id: "",
      },
      isShownSetProviderLabelModal: false,
      newProviderLabel: "",
      addProvider: {
        isResumeConfiguration: false,
        providerId: "",
      },
      isShownBindPassword: false,
      providerToDelete: null,
      domains: [],
      loading: {
        listUserDomains: true,
        ListPasswordPolicy: true,
        setProviderLabel: false,
        addExternalProvider: false,
        getFqdn: true,
        getPasswordWarning: false,
      },
      error: {
        listUserDomains: "",
        removeInternalProvider: "",
        setProviderLabel: "",
        removeExternalProvider: "",
        ListPasswordPolicy: "",
        setPasswordPolicy: "",
        getFqdn: "",
        getPasswordWarning: "",
        warningMailSubject: "",
        warningMailTemplateContent: "",
        warningDays: "",
      },
    };
  },
  computed: {
    ...mapState(["clusterNodes"]),
    mainProvider() {
      return this.domain.providers[0].id;
    },
    mainNode() {
      return this.domain.providers[0].node;
    },
    unconfiguredProviders() {
      if (!this.domain?.providers) {
        return [];
      }
      let unconfiguredProviders = this.domain.providers.filter((p) => !p.host);
      return unconfiguredProviders.sort(this.sortModuleInstances());
    },
    configuredProviders() {
      if (!this.domain) {
        return [];
      }
      let configuredProviders = this.domain.providers.filter((p) => p.host);
      return configuredProviders.sort(this.sortModuleInstances());
    },
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.watchQueryData(vm);
      vm.queryParamsToDataForCore(vm, to.query);
    });
  },
  beforeRouteUpdate(to, from, next) {
    this.queryParamsToDataForCore(this, to.query);
    next();
  },
  created() {
    this.domainName = this.$route.params.domainName;
    this.listUserDomains();
  },
  methods: {
    async listUserDomains() {
      this.loading.listUserDomains = true;
      this.error.listUserDomains = "";
      const taskAction = "list-user-domains";
      this.$root.$once(
        taskAction + "-completed",
        this.listUserDomainsCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.listUserDomains = this.getErrorMessage(err);
        return;
      }
    },
    listUserDomainsCompleted(taskContext, taskResult) {
      this.domains = taskResult.output.domains;
      this.domain = taskResult.output.domains.find(
        (d) => d.name == this.domainName
      );
      if (this.domain.location === "internal") {
        this.listPasswordPolicy();
        this.getFqdn();
      }
      this.loading.listUserDomains = false;
      setTimeout(() => {
        this.checkAndScrollToAnchor();
      }, 100);
    },
    reloadExternalDomain() {
      this.isShownEditExternalDomainModal = false;
      this.listUserDomains();
    },
    async listPasswordPolicy() {
      this.loading.ListPasswordPolicy = true;
      this.error.ListPasswordPolicy = "";
      const taskAction = "get-password-policy";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.ListPasswordPolicyCompleted
      );
      const res = await to(
        this.createModuleTaskForApp(this.mainProvider, {
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.ListPasswordPolicy = this.getErrorMessage(err);
        return;
      }
    },
    ListPasswordPolicyCompleted(taskContext, taskResult) {
      const Config = taskResult.output;
      this.policy.expiration.enforced = Config.expiration.enforced;
      this.policy.expiration.max_age = Config.expiration.max_age.toString();
      this.policy.expiration.min_age = Config.expiration.min_age.toString();
      this.policy.strength.enforced = Config.strength.enforced;
      this.policy.strength.complexity_check = Config.strength.complexity_check;
      this.policy.strength.history_length =
        Config.strength.history_length.toString();
      this.policy.strength.password_min_length =
        Config.strength.password_min_length.toString();
      this.loading.ListPasswordPolicy = false;
      this.getPasswordWarning();
    },
    async getFqdn() {
      this.error.getFqdn = "";
      this.loading.getFqdn = true;
      const taskAction = "get-fqdn";
      const eventId = this.getUuid();
      this.$root.$once(`${taskAction}-aborted-${eventId}`, this.getFqdnAborted);
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.getFqdnCompleted
      );
      const res = await to(
        this.createNodeTask(this.mainNode, {
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.getFqdn = this.getErrorMessage(err);
        return;
      }
    },
    getFqdnCompleted(taskContext, taskResult) {
      this.hostnameNode = taskResult.output.hostname;
      this.domainNode = taskResult.output.domain;
      this.loading.getFqdn = false;
    },
    getFqdnAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.loading.getFqdn = false;
    },
    async getPasswordWarning() {
      this.loading.getPasswordWarning = true;
      this.error.getPasswordWarning = "";
      const taskAction = "get-password-warning";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.getPasswordWarningAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.getPasswordWarningCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: { domain: this.domainName },
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.getPasswordWarning = this.getErrorMessage(err);
        return;
      }
    },
    getPasswordWarningCompleted(taskContext, taskResult) {
      taskResult.output.days = taskResult.output.days.toString();
      this.policy.warning = taskResult.output;
      this.loading.getPasswordWarning = false;
    },
    getPasswordWarningAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.loading.getPasswordWarning = false;
    },
    validatePasswordWarning() {
      this.error.warningMailSubject = "";
      this.error.warningMailTemplateContent = "";
      this.error.warningDays = "";
      if (!this.policy.warning.days) {
        this.error.warningDays = this.$t("error.warning_days_required");
        return false;
      }
      if (
        parseInt(this.policy.warning.days) < 1 ||
        parseInt(this.policy.warning.days) > 1000
      ) {
        this.error.warningDays = this.$t("error.warning_days_range");
        return false;
      }
      if (this.policy.warning.mail_template_name == "custom") {
        if (!this.policy.warning.mail_subject) {
          this.error.warningMailSubject = this.$t(
            "error.warning_mail_subject_required"
          );
          return false;
        }
        if (!this.policy.warning.mail_template_content) {
          this.error.warningMailTemplateContent = this.$t(
            "error.warning_mail_template_content_required"
          );
          return false;
        }
      }
      return true;
    },
    async setPasswordWarning() {
      this.loading.getPasswordWarning = true;
      this.error.getPasswordWarning = "";
      const taskAction = "set-password-warning";
      const eventId = this.getUuid();
      var payload;
      if (!this.validatePasswordWarning()) {
        this.loading.getPasswordWarning = false;
        return;
      }
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.setPasswordWarningAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.setPasswordWarningCompleted
      );
      this.$root.$once(
        `${taskAction}-validation-failed-${eventId}`,
        this.setPasswordWarningValidationFailed
      );
      payload = {
        domain: this.domainName,
        notification: this.policy.warning.notification,
        days: parseInt(this.policy.warning.days),
        mail_from: this.policy.warning.mail_from,
        mail_template_name: this.policy.warning.mail_template_name,
      };
      if (this.policy.warning.mail_template_name == "custom") {
        payload.mail_template_content = Buffer.from(
          this.policy.warning.mail_template_content
        ).toString("base64");
        payload.mail_subject = this.policy.warning.mail_subject;
      }
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: payload,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.setPasswordWarning = this.getErrorMessage(err);
        this.loading.getPasswordWarning = false;
        this.isShownPasswordWarningModal = false;
        this.hideisShownPasswordWarningModal();
        return;
      }
    },
    setPasswordWarningValidationFailed(validationErrors) {
      this.loading.getPasswordWarning = false;
      this.hideisShownPasswordWarningModal();
      for (const validationError of validationErrors) {
        const param = validationError.parameter;
        this.error[param] = this.$t("domains." + validationError.error);
      }
    },
    setPasswordWarningAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.loading.setPasswordWarning = false;
      this.hideisShownPasswordWarningModal();
    },
    setPasswordWarningCompleted() {
      this.hideisShownPasswordWarningModal();
      this.listUserDomains();
    },
    async setPasswordPolicy() {
      this.loading.ListPasswordPolicy = true;
      this.error.setPasswordPolicy = "";
      const taskAction = "set-password-policy";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.setPasswordPolicyAborted
      );
      this.$root.$once(
        `${taskAction}-validation-failed-${eventId}`,
        this.setPasswordPolicyValidationFailed
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.setPasswordPolicyCompleted
      );
      const res = await to(
        this.createModuleTaskForApp(this.mainProvider, {
          action: taskAction,
          data: {
            expiration: {
              enforced: this.policy.expiration.enforced,
              min_age: parseInt(this.policy.expiration.min_age),
              max_age: parseInt(this.policy.expiration.max_age),
            },
            strength: {
              complexity_check: this.policy.strength.complexity_check,
              enforced: this.policy.strength.enforced,
              history_length: parseInt(this.policy.strength.history_length),
              password_min_length: parseInt(
                this.policy.strength.password_min_length
              ),
            },
          },
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.setPasswordPolicy = this.getErrorMessage(err);
        this.loading.ListPasswordPolicy = false;
        this.isShownPasswordPolicyModal = false;
        this.hideisShownPasswordPolicyModal();
        return;
      }
    },
    setPasswordPolicyAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.loading.ListPasswordPolicy = false;
      this.hideisShownPasswordPolicyModal();
    },
    setPasswordPolicyValidationFailed(validationErrors) {
      this.loading.ListPasswordPolicy = false;
      this.hideisShownPasswordPolicyModal();
      for (const validationError of validationErrors) {
        const param = validationError.parameter;
        this.error[param] = this.$t("domains." + validationError.error);
      }
    },
    setPasswordPolicyCompleted() {
      this.hideisShownPasswordPolicyModal();
      this.listUserDomains();
      this.$root.$emit("password-policy-updated");
    },
    showAddProviderModal() {
      if (this.domain.location == "internal") {
        this.showAddInternalProviderModal();
      } else {
        this.showAddExternalProviderModal();
      }
    },
    showAddInternalProviderModal() {
      this.addProvider.isResumeConfiguration = false;
      this.addProvider.providerId = "";
      this.$nextTick(() => {
        this.isShownAddInternalProviderModal = true;
      });
    },
    showAddExternalProviderModal() {
      this.isShownAddExternalProviderModal = true;
    },
    deleteLdapProvider() {
      if (this.domain.location == "internal") {
        this.deleteLdapInternalProvider();
      } else {
        this.deleteLdapExternalProvider();
      }
    },
    async deleteLdapInternalProvider() {
      this.error.removeInternalProvider = "";
      const taskAction = "remove-internal-provider";
      this.$root.$once(
        taskAction + "-completed",
        this.deleteLdapProviderCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {
            module_id: this.currentProvider.id,
          },
          extra: {
            title: this.$t("action." + taskAction),
            description: this.$t("common.processing"),
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.removeInternalProvider = this.getErrorMessage(err);
        return;
      }
      this.isShownDeleteLdapProviderModal = false;
    },
    async deleteLdapExternalProvider() {
      this.error.removeExternalProvider = "";
      const taskAction = "remove-external-provider";
      this.$root.$once(
        taskAction + "-completed",
        this.deleteLdapProviderCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {
            domain: this.domainName,
            protocol: "ldap",
            host: this.currentProvider.host,
            port: this.currentProvider.port,
          },
          extra: {
            title: this.$t("action." + taskAction),
            description: this.$t("common.processing"),
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.removeExternalProvider = this.getErrorMessage(err);
        return;
      }
      this.isShownDeleteLdapProviderModal = false;
    },
    deleteLdapProviderCompleted() {
      this.listUserDomains();
    },
    hideAddInternalProviderModal() {
      this.isShownAddInternalProviderModal = false;
    },
    hideAddExternalProviderModal() {
      this.isShownAddExternalProviderModal = false;
    },
    showDeleteProviderModal(provider) {
      if (provider.host && this.configuredProviders.length == 1) {
        this.isShownLastProviderModal = true;
        return;
      }
      this.currentProvider = provider;
      if (this.domain.schema === "ad" && this.domain.location == "internal") {
        this.isShownDeleteSambaProviderModal = true;
      } else {
        this.isShownDeleteLdapProviderModal = true;
      }
    },
    hideDeleteSambaProviderModal() {
      this.isShownDeleteSambaProviderModal = false;
    },
    hideDeleteLdapProviderModal() {
      this.isShownDeleteLdapProviderModal = false;
    },
    hideSetProviderLabelModal() {
      this.isShownSetProviderLabelModal = false;
    },
    hideisShownPasswordPolicyModal() {
      this.isShownPasswordPolicyModal = false;
    },
    hideisShownPasswordWarningModal() {
      this.isShownPasswordWarningModal = false;
    },
    hideisShownEditExternalDomainModal() {
      this.isShownEditExternalDomainModal = false;
    },
    showSetProviderLabelModal(provider) {
      this.currentProvider = provider;
      this.newProviderLabel = provider.ui_name;
      this.isShownSetProviderLabelModal = true;
      setTimeout(() => {
        this.focusElement("newProviderLabel");
      }, 300);
    },
    showPasswordPolicy() {
      this.isShownPasswordPolicyModal = true;
    },
    showPasswordWarning() {
      this.isShownPasswordWarningModal = true;
    },
    showEditExternalDomain() {
      this.isShownEditExternalDomainModal = true;
    },
    setProviderLabel() {
      if (this.domain.location == "internal") {
        this.setInternalProviderLabel();
      } else {
        this.setExternalProviderLabel();
      }
    },
    async setInternalProviderLabel() {
      this.error.setProviderLabel = "";
      this.loading.setProviderLabel = true;
      const taskAction = "set-name";
      this.$root.$once(
        taskAction + "-completed",
        this.setProviderLabelCompleted
      );
      const res = await to(
        this.createModuleTaskForApp(this.currentProvider.id, {
          action: taskAction,
          data: {
            name: this.newProviderLabel,
          },
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.setProviderLabel = this.getErrorMessage(err);
        this.loading.setProviderLabel = false;
        return;
      }
    },
    async setExternalProviderLabel() {
      this.error.setProviderLabel = "";
      this.loading.setProviderLabel = true;
      const taskAction = "set-external-provider-name";
      this.$root.$once(
        taskAction + "-completed",
        this.setProviderLabelCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {
            domain: this.domainName,
            protocol: "ldap",
            host: this.currentProvider.host,
            port: this.currentProvider.port,
            ui_name: this.newProviderLabel,
          },
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.setProviderLabel = this.getErrorMessage(err);
        this.loading.setProviderLabel = false;
        return;
      }
    },
    setProviderLabelCompleted() {
      this.loading.setProviderLabel = false;
      this.hideSetProviderLabelModal();
      this.listUserDomains();
    },
    showUnconfiguredProviderModal(unconfiguredProvider) {
      this.addProvider.isResumeConfiguration = true;
      this.addProvider.providerId = unconfiguredProvider.id;
      this.$nextTick(() => {
        this.isShownAddInternalProviderModal = true;
      });
    },
    toggleBindPassword() {
      this.isShownBindPassword = !this.isShownBindPassword;
    },
    willDeleteUnconfiguredProvider(provider) {
      const timeout = setTimeout(() => {
        this.deleteUnconfiguredProvider(provider);
        this.providerToDelete = null;
      }, this.DELETE_DELAY);
      provider.timeout = timeout;
      this.providerToDelete = provider;
      this.domain.providers = this.domain.providers.filter((p) => {
        return p.id != provider.id;
      });
    },
    cancelDeleteUnconfiguredProvider() {
      clearTimeout(this.providerToDelete.timeout);
      this.providerToDelete = null;
      this.listUserDomains();
    },
    async deleteUnconfiguredProvider(provider) {
      this.error.removeInternalProvider = "";
      const taskAction = "remove-internal-provider";
      this.$root.$on(
        taskAction + "-completed",
        this.deleteUnconfiguredProviderCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {
            module_id: provider.id,
          },
          extra: {
            title: this.$t("action." + taskAction),
            description: this.$t("common.processing"),
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.removeInternalProvider = this.getErrorMessage(err);
        return;
      }
    },
    deleteUnconfiguredProviderCompleted() {
      this.listUserDomains();
    },
    goToUserAdminPage() {
      window.open(
        "https://" +
          this.hostnameNode +
          "." +
          this.domainNode +
          "/users-admin/" +
          this.domainName +
          "/",
        "_blank"
      );
    },
    getNodeLabel(nodeId) {
      const node = this.clusterNodes.find((n) => n.id == nodeId);
      if (node) {
        if (node.ui_name) {
          return (
            node.ui_name + " (" + this.$t("common.node") + " " + nodeId + ")"
          );
        } else {
          return this.$t("common.node") + " " + nodeId;
        }
      }
      return this.$t("common.node") + " " + nodeId;
    },
    goToFileServer(provider) {
      this.$router.push(`/apps/${provider.id}`);
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../styles/carbon-utils";
.provider-card-content .row {
  margin-bottom: $spacing-05;
  text-align: center;
}
.provider-card-content .row:last-child {
  margin-bottom: 0;
}
.password-snippet {
  margin-bottom: $spacing-07;
}
.right-margin {
  margin-right: 1rem;
}
.top-margin {
  margin-top: 1rem;
}
.title {
  margin-right: 0.25rem;
  margin-bottom: 0.5rem;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.domain-menu {
  position: absolute;
  top: -1rem !important;
  right: -1rem !important;
  width: 3rem;
  height: 3rem;
}
.relative {
  position: relative;
}
</style>
</file>

<file path="core/ui/src/views/Domains.vue">
<template>
  <div>
    <cv-grid fullWidth>
      <cv-row>
        <cv-column class="page-title">
          <h2>{{ $t("domains.title") }}</h2>
        </cv-column>
      </cv-row>
      <cv-row v-if="error.listUserDomains">
        <cv-column>
          <NsInlineNotification
            kind="error"
            :title="$t('action.list-user-domains')"
            :description="error.listUserDomains"
            :showCloseButton="false"
          />
        </cv-column>
      </cv-row>
      <cv-row v-if="error.removeModule">
        <cv-column>
          <NsInlineNotification
            kind="error"
            :title="$t('action.remove-module')"
            :description="error.removeModule"
            :showCloseButton="false"
          />
        </cv-column>
      </cv-row>
      <cv-row v-if="error.removeExternalDomain">
        <cv-column>
          <NsInlineNotification
            kind="error"
            :title="$t('action.remove-external-domain')"
            :description="error.removeExternalDomain"
            :showCloseButton="false"
          />
        </cv-column>
      </cv-row>
      <cv-row v-if="hasUnconfiguredDomainsOrProviders">
        <cv-column>
          <NsInlineNotification
            kind="warning"
            :title="$t('domains.unconfigured_domains_or_providers_title')"
            :description="
              $t('domains.unconfigured_domains_or_providers_description')
            "
            :showCloseButton="false"
          />
        </cv-column>
      </cv-row>
      <cv-row v-if="domainToDelete">
        <cv-column>
          <NsInlineNotification
            kind="warning"
            :title="
              $t('domains.domain_is_going_to_be_deleted', {
                object: domainToDelete.module_id,
              })
            "
            :actionLabel="$t('common.cancel')"
            @action="cancelDeleteUnconfiguredDomain()"
            :showCloseButton="false"
            :timer="DELETE_DELAY"
          />
        </cv-column>
      </cv-row>
      <cv-row v-if="loading.listUserDomains">
        <cv-column>
          <div class="card-grid grid-cols-1 md:grid-cols-2 2xl:grid-cols-3">
            <cv-tile v-for="index in 2" :key="index" light>
              <cv-skeleton-text
                :paragraph="true"
                :line-count="6"
                heading
              ></cv-skeleton-text>
            </cv-tile>
          </div>
        </cv-column>
      </cv-row>
      <template v-else>
        <template v-if="unconfiguredDomains.length">
          <cv-row>
            <cv-column>
              <h4 class="mg-bottom-md">
                {{ $t("domains.unconfigured_domains") }}
              </h4>
            </cv-column>
          </cv-row>
          <cv-row>
            <cv-column>
              <div class="card-grid grid-cols-1 md:grid-cols-2 2xl:grid-cols-3">
                <NsInfoCard
                  v-for="(unconfiguredDomain, index) in unconfiguredDomains"
                  :key="index"
                  light
                  :title="$t('domains.unconfigured_domain')"
                  :icon="WarningAlt32"
                  :wrapTitle="true"
                >
                  <template #menu>
                    <cv-overflow-menu
                      :flip-menu="true"
                      tip-position="top"
                      tip-alignment="end"
                      class="top-right-overflow-menu"
                    >
                      <cv-overflow-menu-item
                        danger
                        @click="
                          willDeleteUnconfiguredDomain(unconfiguredDomain)
                        "
                      >
                        <NsMenuItem
                          :icon="TrashCan20"
                          :label="$t('common.delete')"
                        />
                      </cv-overflow-menu-item>
                    </cv-overflow-menu>
                  </template>
                  <template #content>
                    <div class="domain-card-content">
                      <div class="row">
                        <span>{{
                          $t("domains." + unconfiguredDomain.location)
                        }}</span>
                        <template
                          v-if="unconfiguredDomain.location == 'internal'"
                        >
                          <span v-if="unconfiguredDomain.schema == 'rfc2307'">
                            {{ $t("domains.openldap") }}
                          </span>
                          <span v-else-if="unconfiguredDomain.schema == 'ad'">
                            {{ $t("domains.samba") }}
                          </span>
                        </template>
                        <template v-else>
                          {{ $t("domains.ldap") }}
                        </template>
                        <span>{{
                          " (" +
                          (unconfiguredDomain.ui_name
                            ? unconfiguredDomain.ui_name
                            : unconfiguredDomain.module_id) +
                          ")"
                        }}</span>
                      </div>
                      <div class="row icon-and-text">
                        <NsSvg :svg="Chip20" class="icon" />
                        <span
                          >{{ $t("common.node") }}
                          {{ unconfiguredDomain.node }}</span
                        >
                      </div>
                      <div class="row actions">
                        <NsButton
                          kind="ghost"
                          :icon="Tools20"
                          @click="
                            showUnconfiguredDomainModal(unconfiguredDomain)
                          "
                          >{{ $t("domains.resume_configuration") }}
                        </NsButton>
                      </div>
                    </div>
                  </template>
                </NsInfoCard>
              </div>
            </cv-column>
          </cv-row>
          <cv-row>
            <cv-column>
              <h4 class="mg-bottom-md">
                {{ $t("domains.configured_domains") }}
              </h4>
            </cv-column>
          </cv-row>
        </template>
        <cv-row v-if="!domains.length">
          <cv-column>
            <cv-tile kind="standard" :light="true">
              <NsEmptyState :title="$t('domains.no_domain_configured')">
                <template #pictogram>
                  <GroupPictogram />
                </template>
                <template #description>
                  <div>{{ $t("domains.empty_state_domains_description") }}</div>
                  <NsButton
                    kind="primary"
                    :icon="Add20"
                    @click="showCreateDomainModal()"
                    class="empty-state-button"
                    >{{ $t("domains.create_domain") }}
                  </NsButton>
                </template>
              </NsEmptyState>
            </cv-tile>
          </cv-column>
        </cv-row>
        <template v-else>
          <cv-row class="toolbar">
            <cv-column>
              <NsButton
                kind="secondary"
                :icon="Add20"
                @click="showCreateDomainModal()"
                :disabled="loading.listUserDomains"
                >{{ $t("domains.create_domain") }}
              </NsButton>
            </cv-column>
          </cv-row>
          <cv-row>
            <cv-column>
              <div class="card-grid grid-cols-1 md:grid-cols-2 2xl:grid-cols-3">
                <NsInfoCard
                  v-for="domain in domains"
                  :key="domain.name"
                  light
                  :title="domain.name"
                  :icon="Events32"
                  :wrapTitle="true"
                >
                  <template #menu>
                    <cv-overflow-menu
                      :flip-menu="true"
                      tip-position="top"
                      tip-alignment="end"
                      class="top-right-overflow-menu"
                      :data-test-id="domain.name + '-menu'"
                    >
                      <cv-overflow-menu-item
                        v-if="domain.location == 'internal'"
                        @click="showImportUsersModal(domain)"
                        :data-test-id="domain.name + '-import-data'"
                      >
                        <NsMenuItem
                          :icon="Upload20"
                          :label="$t('domain_users.import_data')"
                        />
                      </cv-overflow-menu-item>
                      <cv-overflow-menu-item
                        v-if="domain.location == 'internal'"
                        @click="exportUsersData(domain)"
                        :data-test-id="domain.name + '-export-data'"
                      >
                        <NsMenuItem
                          :icon="Export20"
                          :label="$t('domain_users.export_data')"
                        />
                      </cv-overflow-menu-item>
                      <cv-overflow-menu-item
                        danger
                        @click="showDeleteDomainModal(domain)"
                        :data-test-id="domain.name + '-delete'"
                      >
                        <NsMenuItem
                          :icon="TrashCan20"
                          :label="$t('common.delete')"
                        />
                      </cv-overflow-menu-item>
                    </cv-overflow-menu>
                  </template>
                  <template #content>
                    <div class="domain-card-content">
                      <div class="row">
                        <span>{{ $t("domains." + domain.location) }}</span>
                        <template v-if="domain.location == 'internal'">
                          <span v-if="domain.schema == 'rfc2307'">
                            {{ $t("domains.openldap") }}
                          </span>
                          <span v-else-if="domain.schema == 'ad'">
                            {{ $t("domains.samba") }}
                          </span>
                        </template>
                        <template v-else>
                          {{ $t("domains.ldap") }}
                        </template>
                      </div>
                      <div v-if="domain.counters" class="row">
                        <cv-link
                          v-if="domain.counters.users != null"
                          @click="goToDomainUsersAndGroups(domain)"
                        >
                          <span>{{
                            $tc(
                              "domain_users.num_users_c",
                              domain.counters.users,
                              {
                                num: domain.counters.users,
                              }
                            )
                          }}</span>
                        </cv-link>
                        <template v-if="domain.counters.groups != null">
                          <span class="bullet-separator">&bull;</span>
                          <cv-link
                            @click="goToDomainUsersAndGroups(domain, 'groups')"
                          >
                            <span>{{
                              $tc(
                                "domain_users.num_groups_c",
                                domain.counters.groups,
                                {
                                  num: domain.counters.groups,
                                }
                              )
                            }}</span>
                          </cv-link>
                        </template>
                      </div>
                      <div
                        v-if="domain.hasUnconfiguredProviders"
                        class="row icon-and-text"
                      >
                        <NsSvg :svg="Warning16" class="icon ns-warning" />
                        <cv-link @click="goToDomainConfiguration(domain)">
                          <span>{{ $t("domains.unconfigured_provider") }}</span>
                        </cv-link>
                      </div>
                      <div v-else class="row">
                        <cv-link @click="goToDomainConfiguration(domain)">
                          {{ domain.providers.length }}
                          {{
                            $tc("domains.providers", domain.providers.length)
                          }}
                        </cv-link>
                        <template v-if="domain.fileServerProvider">
                          <span class="bullet-separator">&bull;</span>
                          <cv-link
                            @click="goToFileServer(domain.fileServerProvider)"
                          >
                            <span>{{ $t("samba.file_server") }}</span>
                          </cv-link>
                        </template>
                      </div>
                      <div class="row actions">
                        <NsButton
                          kind="ghost"
                          :icon="ArrowRight20"
                          @click="goToDomainUsersAndGroups(domain)"
                          :data-test-id="domain.name + '-users-and-groups'"
                          >{{ $t("common.see_details") }}</NsButton
                        >
                      </div>
                    </div>
                  </template>
                </NsInfoCard>
              </div>
            </cv-column>
          </cv-row>
        </template>
      </template>
    </cv-grid>
    <ImportUsersModal
      :isShown="isShownImportUsersModal"
      :domain="importData.domain"
      @hide="hideImportUsersModal"
      @reloadDomains="listUserDomains"
    />
    <CreateDomainModal
      :isShown="isShownCreateDomainModal"
      :isResumeConfiguration="createDomain.isResumeConfiguration"
      :providerId="createDomain.providerId"
      :isOpenLdap="createDomain.isOpenLdap"
      :isSamba="createDomain.isSamba"
      :domains="domains"
      @hide="hideCreateDomainModal"
      @reloadDomains="listUserDomains"
    />
    <NsDangerDeleteModal
      :isShown="isShownDeleteDomainModal"
      :name="currentDomain.name"
      :title="$t('domains.delete_domain')"
      :warning="$t('common.please_read_carefully')"
      :description="
        currentDomain.location == 'internal'
          ? $t('domains.delete_internal_domain_confirm', {
              name: currentDomain.name,
            })
          : $t('domains.delete_external_domain_confirm', {
              name: currentDomain.name,
            })
      "
      :typeToConfirm="
        $t('common.type_to_confirm', { name: currentDomain.name })
      "
      @hide="hideDeleteDomainModal"
      @confirmDelete="deleteDomain(currentDomain)"
    />
  </div>
</template>
⋮----
<h2>{{ $t("domains.title") }}</h2>
⋮----
<template v-else>
        <template v-if="unconfiguredDomains.length">
          <cv-row>
            <cv-column>
              <h4 class="mg-bottom-md">
                {{ $t("domains.unconfigured_domains") }}
              </h4>
            </cv-column>
          </cv-row>
          <cv-row>
            <cv-column>
              <div class="card-grid grid-cols-1 md:grid-cols-2 2xl:grid-cols-3">
                <NsInfoCard
                  v-for="(unconfiguredDomain, index) in unconfiguredDomains"
                  :key="index"
                  light
                  :title="$t('domains.unconfigured_domain')"
                  :icon="WarningAlt32"
                  :wrapTitle="true"
                >
                  <template #menu>
                    <cv-overflow-menu
                      :flip-menu="true"
                      tip-position="top"
                      tip-alignment="end"
                      class="top-right-overflow-menu"
                    >
                      <cv-overflow-menu-item
                        danger
                        @click="
                          willDeleteUnconfiguredDomain(unconfiguredDomain)
                        "
                      >
                        <NsMenuItem
                          :icon="TrashCan20"
                          :label="$t('common.delete')"
                        />
                      </cv-overflow-menu-item>
                    </cv-overflow-menu>
                  </template>
                  <template #content>
                    <div class="domain-card-content">
                      <div class="row">
                        <span>{{
                          $t("domains." + unconfiguredDomain.location)
                        }}</span>
                        <template
                          v-if="unconfiguredDomain.location == 'internal'"
                        >
                          <span v-if="unconfiguredDomain.schema == 'rfc2307'">
                            {{ $t("domains.openldap") }}
                          </span>
                          <span v-else-if="unconfiguredDomain.schema == 'ad'">
                            {{ $t("domains.samba") }}
                          </span>
                        </template>
                        <template v-else>
                          {{ $t("domains.ldap") }}
                        </template>
                        <span>{{
                          " (" +
                          (unconfiguredDomain.ui_name
                            ? unconfiguredDomain.ui_name
                            : unconfiguredDomain.module_id) +
                          ")"
                        }}</span>
                      </div>
                      <div class="row icon-and-text">
                        <NsSvg :svg="Chip20" class="icon" />
                        <span
                          >{{ $t("common.node") }}
                          {{ unconfiguredDomain.node }}</span
                        >
                      </div>
                      <div class="row actions">
                        <NsButton
                          kind="ghost"
                          :icon="Tools20"
                          @click="
                            showUnconfiguredDomainModal(unconfiguredDomain)
                          "
                          >{{ $t("domains.resume_configuration") }}
                        </NsButton>
                      </div>
                    </div>
                  </template>
                </NsInfoCard>
              </div>
            </cv-column>
          </cv-row>
          <cv-row>
            <cv-column>
              <h4 class="mg-bottom-md">
                {{ $t("domains.configured_domains") }}
              </h4>
            </cv-column>
          </cv-row>
        </template>
        <cv-row v-if="!domains.length">
          <cv-column>
            <cv-tile kind="standard" :light="true">
              <NsEmptyState :title="$t('domains.no_domain_configured')">
                <template #pictogram>
                  <GroupPictogram />
                </template>
                <template #description>
                  <div>{{ $t("domains.empty_state_domains_description") }}</div>
                  <NsButton
                    kind="primary"
                    :icon="Add20"
                    @click="showCreateDomainModal()"
                    class="empty-state-button"
                    >{{ $t("domains.create_domain") }}
                  </NsButton>
                </template>
              </NsEmptyState>
            </cv-tile>
          </cv-column>
        </cv-row>
        <template v-else>
          <cv-row class="toolbar">
            <cv-column>
              <NsButton
                kind="secondary"
                :icon="Add20"
                @click="showCreateDomainModal()"
                :disabled="loading.listUserDomains"
                >{{ $t("domains.create_domain") }}
              </NsButton>
            </cv-column>
          </cv-row>
          <cv-row>
            <cv-column>
              <div class="card-grid grid-cols-1 md:grid-cols-2 2xl:grid-cols-3">
                <NsInfoCard
                  v-for="domain in domains"
                  :key="domain.name"
                  light
                  :title="domain.name"
                  :icon="Events32"
                  :wrapTitle="true"
                >
                  <template #menu>
                    <cv-overflow-menu
                      :flip-menu="true"
                      tip-position="top"
                      tip-alignment="end"
                      class="top-right-overflow-menu"
                      :data-test-id="domain.name + '-menu'"
                    >
                      <cv-overflow-menu-item
                        v-if="domain.location == 'internal'"
                        @click="showImportUsersModal(domain)"
                        :data-test-id="domain.name + '-import-data'"
                      >
                        <NsMenuItem
                          :icon="Upload20"
                          :label="$t('domain_users.import_data')"
                        />
                      </cv-overflow-menu-item>
                      <cv-overflow-menu-item
                        v-if="domain.location == 'internal'"
                        @click="exportUsersData(domain)"
                        :data-test-id="domain.name + '-export-data'"
                      >
                        <NsMenuItem
                          :icon="Export20"
                          :label="$t('domain_users.export_data')"
                        />
                      </cv-overflow-menu-item>
                      <cv-overflow-menu-item
                        danger
                        @click="showDeleteDomainModal(domain)"
                        :data-test-id="domain.name + '-delete'"
                      >
                        <NsMenuItem
                          :icon="TrashCan20"
                          :label="$t('common.delete')"
                        />
                      </cv-overflow-menu-item>
                    </cv-overflow-menu>
                  </template>
                  <template #content>
                    <div class="domain-card-content">
                      <div class="row">
                        <span>{{ $t("domains." + domain.location) }}</span>
                        <template v-if="domain.location == 'internal'">
                          <span v-if="domain.schema == 'rfc2307'">
                            {{ $t("domains.openldap") }}
                          </span>
                          <span v-else-if="domain.schema == 'ad'">
                            {{ $t("domains.samba") }}
                          </span>
                        </template>
                        <template v-else>
                          {{ $t("domains.ldap") }}
                        </template>
                      </div>
                      <div v-if="domain.counters" class="row">
                        <cv-link
                          v-if="domain.counters.users != null"
                          @click="goToDomainUsersAndGroups(domain)"
                        >
                          <span>{{
                            $tc(
                              "domain_users.num_users_c",
                              domain.counters.users,
                              {
                                num: domain.counters.users,
                              }
                            )
                          }}</span>
                        </cv-link>
                        <template v-if="domain.counters.groups != null">
                          <span class="bullet-separator">&bull;</span>
                          <cv-link
                            @click="goToDomainUsersAndGroups(domain, 'groups')"
                          >
                            <span>{{
                              $tc(
                                "domain_users.num_groups_c",
                                domain.counters.groups,
                                {
                                  num: domain.counters.groups,
                                }
                              )
                            }}</span>
                          </cv-link>
                        </template>
                      </div>
                      <div
                        v-if="domain.hasUnconfiguredProviders"
                        class="row icon-and-text"
                      >
                        <NsSvg :svg="Warning16" class="icon ns-warning" />
                        <cv-link @click="goToDomainConfiguration(domain)">
                          <span>{{ $t("domains.unconfigured_provider") }}</span>
                        </cv-link>
                      </div>
                      <div v-else class="row">
                        <cv-link @click="goToDomainConfiguration(domain)">
                          {{ domain.providers.length }}
                          {{
                            $tc("domains.providers", domain.providers.length)
                          }}
                        </cv-link>
                        <template v-if="domain.fileServerProvider">
                          <span class="bullet-separator">&bull;</span>
                          <cv-link
                            @click="goToFileServer(domain.fileServerProvider)"
                          >
                            <span>{{ $t("samba.file_server") }}</span>
                          </cv-link>
                        </template>
                      </div>
                      <div class="row actions">
                        <NsButton
                          kind="ghost"
                          :icon="ArrowRight20"
                          @click="goToDomainUsersAndGroups(domain)"
                          :data-test-id="domain.name + '-users-and-groups'"
                          >{{ $t("common.see_details") }}</NsButton
                        >
                      </div>
                    </div>
                  </template>
                </NsInfoCard>
              </div>
            </cv-column>
          </cv-row>
        </template>
      </template>
⋮----
<template v-if="unconfiguredDomains.length">
          <cv-row>
            <cv-column>
              <h4 class="mg-bottom-md">
                {{ $t("domains.unconfigured_domains") }}
              </h4>
            </cv-column>
          </cv-row>
          <cv-row>
            <cv-column>
              <div class="card-grid grid-cols-1 md:grid-cols-2 2xl:grid-cols-3">
                <NsInfoCard
                  v-for="(unconfiguredDomain, index) in unconfiguredDomains"
                  :key="index"
                  light
                  :title="$t('domains.unconfigured_domain')"
                  :icon="WarningAlt32"
                  :wrapTitle="true"
                >
                  <template #menu>
                    <cv-overflow-menu
                      :flip-menu="true"
                      tip-position="top"
                      tip-alignment="end"
                      class="top-right-overflow-menu"
                    >
                      <cv-overflow-menu-item
                        danger
                        @click="
                          willDeleteUnconfiguredDomain(unconfiguredDomain)
                        "
                      >
                        <NsMenuItem
                          :icon="TrashCan20"
                          :label="$t('common.delete')"
                        />
                      </cv-overflow-menu-item>
                    </cv-overflow-menu>
                  </template>
                  <template #content>
                    <div class="domain-card-content">
                      <div class="row">
                        <span>{{
                          $t("domains." + unconfiguredDomain.location)
                        }}</span>
                        <template
                          v-if="unconfiguredDomain.location == 'internal'"
                        >
                          <span v-if="unconfiguredDomain.schema == 'rfc2307'">
                            {{ $t("domains.openldap") }}
                          </span>
                          <span v-else-if="unconfiguredDomain.schema == 'ad'">
                            {{ $t("domains.samba") }}
                          </span>
                        </template>
                        <template v-else>
                          {{ $t("domains.ldap") }}
                        </template>
                        <span>{{
                          " (" +
                          (unconfiguredDomain.ui_name
                            ? unconfiguredDomain.ui_name
                            : unconfiguredDomain.module_id) +
                          ")"
                        }}</span>
                      </div>
                      <div class="row icon-and-text">
                        <NsSvg :svg="Chip20" class="icon" />
                        <span
                          >{{ $t("common.node") }}
                          {{ unconfiguredDomain.node }}</span
                        >
                      </div>
                      <div class="row actions">
                        <NsButton
                          kind="ghost"
                          :icon="Tools20"
                          @click="
                            showUnconfiguredDomainModal(unconfiguredDomain)
                          "
                          >{{ $t("domains.resume_configuration") }}
                        </NsButton>
                      </div>
                    </div>
                  </template>
                </NsInfoCard>
              </div>
            </cv-column>
          </cv-row>
          <cv-row>
            <cv-column>
              <h4 class="mg-bottom-md">
                {{ $t("domains.configured_domains") }}
              </h4>
            </cv-column>
          </cv-row>
        </template>
⋮----
{{ $t("domains.unconfigured_domains") }}
⋮----
<template #menu>
                    <cv-overflow-menu
                      :flip-menu="true"
                      tip-position="top"
                      tip-alignment="end"
                      class="top-right-overflow-menu"
                    >
                      <cv-overflow-menu-item
                        danger
                        @click="
                          willDeleteUnconfiguredDomain(unconfiguredDomain)
                        "
                      >
                        <NsMenuItem
                          :icon="TrashCan20"
                          :label="$t('common.delete')"
                        />
                      </cv-overflow-menu-item>
                    </cv-overflow-menu>
                  </template>
<template #content>
                    <div class="domain-card-content">
                      <div class="row">
                        <span>{{
                          $t("domains." + unconfiguredDomain.location)
                        }}</span>
                        <template
                          v-if="unconfiguredDomain.location == 'internal'"
                        >
                          <span v-if="unconfiguredDomain.schema == 'rfc2307'">
                            {{ $t("domains.openldap") }}
                          </span>
                          <span v-else-if="unconfiguredDomain.schema == 'ad'">
                            {{ $t("domains.samba") }}
                          </span>
                        </template>
                        <template v-else>
                          {{ $t("domains.ldap") }}
                        </template>
                        <span>{{
                          " (" +
                          (unconfiguredDomain.ui_name
                            ? unconfiguredDomain.ui_name
                            : unconfiguredDomain.module_id) +
                          ")"
                        }}</span>
                      </div>
                      <div class="row icon-and-text">
                        <NsSvg :svg="Chip20" class="icon" />
                        <span
                          >{{ $t("common.node") }}
                          {{ unconfiguredDomain.node }}</span
                        >
                      </div>
                      <div class="row actions">
                        <NsButton
                          kind="ghost"
                          :icon="Tools20"
                          @click="
                            showUnconfiguredDomainModal(unconfiguredDomain)
                          "
                          >{{ $t("domains.resume_configuration") }}
                        </NsButton>
                      </div>
                    </div>
                  </template>
⋮----
<span>{{
                          $t("domains." + unconfiguredDomain.location)
                        }}</span>
<template
                          v-if="unconfiguredDomain.location == 'internal'"
                        >
                          <span v-if="unconfiguredDomain.schema == 'rfc2307'">
                            {{ $t("domains.openldap") }}
                          </span>
                          <span v-else-if="unconfiguredDomain.schema == 'ad'">
                            {{ $t("domains.samba") }}
                          </span>
                        </template>
⋮----
{{ $t("domains.openldap") }}
⋮----
{{ $t("domains.samba") }}
⋮----
<template v-else>
                          {{ $t("domains.ldap") }}
                        </template>
⋮----
{{ $t("domains.ldap") }}
⋮----
<span>{{
                          " (" +
                          (unconfiguredDomain.ui_name
                            ? unconfiguredDomain.ui_name
                            : unconfiguredDomain.module_id) +
                          ")"
                        }}</span>
⋮----
>{{ $t("common.node") }}
{{ unconfiguredDomain.node }}</span
⋮----
>{{ $t("domains.resume_configuration") }}
⋮----
{{ $t("domains.configured_domains") }}
⋮----
<template #pictogram>
                  <GroupPictogram />
                </template>
<template #description>
                  <div>{{ $t("domains.empty_state_domains_description") }}</div>
                  <NsButton
                    kind="primary"
                    :icon="Add20"
                    @click="showCreateDomainModal()"
                    class="empty-state-button"
                    >{{ $t("domains.create_domain") }}
                  </NsButton>
                </template>
⋮----
<div>{{ $t("domains.empty_state_domains_description") }}</div>
⋮----
>{{ $t("domains.create_domain") }}
⋮----
<template v-else>
          <cv-row class="toolbar">
            <cv-column>
              <NsButton
                kind="secondary"
                :icon="Add20"
                @click="showCreateDomainModal()"
                :disabled="loading.listUserDomains"
                >{{ $t("domains.create_domain") }}
              </NsButton>
            </cv-column>
          </cv-row>
          <cv-row>
            <cv-column>
              <div class="card-grid grid-cols-1 md:grid-cols-2 2xl:grid-cols-3">
                <NsInfoCard
                  v-for="domain in domains"
                  :key="domain.name"
                  light
                  :title="domain.name"
                  :icon="Events32"
                  :wrapTitle="true"
                >
                  <template #menu>
                    <cv-overflow-menu
                      :flip-menu="true"
                      tip-position="top"
                      tip-alignment="end"
                      class="top-right-overflow-menu"
                      :data-test-id="domain.name + '-menu'"
                    >
                      <cv-overflow-menu-item
                        v-if="domain.location == 'internal'"
                        @click="showImportUsersModal(domain)"
                        :data-test-id="domain.name + '-import-data'"
                      >
                        <NsMenuItem
                          :icon="Upload20"
                          :label="$t('domain_users.import_data')"
                        />
                      </cv-overflow-menu-item>
                      <cv-overflow-menu-item
                        v-if="domain.location == 'internal'"
                        @click="exportUsersData(domain)"
                        :data-test-id="domain.name + '-export-data'"
                      >
                        <NsMenuItem
                          :icon="Export20"
                          :label="$t('domain_users.export_data')"
                        />
                      </cv-overflow-menu-item>
                      <cv-overflow-menu-item
                        danger
                        @click="showDeleteDomainModal(domain)"
                        :data-test-id="domain.name + '-delete'"
                      >
                        <NsMenuItem
                          :icon="TrashCan20"
                          :label="$t('common.delete')"
                        />
                      </cv-overflow-menu-item>
                    </cv-overflow-menu>
                  </template>
                  <template #content>
                    <div class="domain-card-content">
                      <div class="row">
                        <span>{{ $t("domains." + domain.location) }}</span>
                        <template v-if="domain.location == 'internal'">
                          <span v-if="domain.schema == 'rfc2307'">
                            {{ $t("domains.openldap") }}
                          </span>
                          <span v-else-if="domain.schema == 'ad'">
                            {{ $t("domains.samba") }}
                          </span>
                        </template>
                        <template v-else>
                          {{ $t("domains.ldap") }}
                        </template>
                      </div>
                      <div v-if="domain.counters" class="row">
                        <cv-link
                          v-if="domain.counters.users != null"
                          @click="goToDomainUsersAndGroups(domain)"
                        >
                          <span>{{
                            $tc(
                              "domain_users.num_users_c",
                              domain.counters.users,
                              {
                                num: domain.counters.users,
                              }
                            )
                          }}</span>
                        </cv-link>
                        <template v-if="domain.counters.groups != null">
                          <span class="bullet-separator">&bull;</span>
                          <cv-link
                            @click="goToDomainUsersAndGroups(domain, 'groups')"
                          >
                            <span>{{
                              $tc(
                                "domain_users.num_groups_c",
                                domain.counters.groups,
                                {
                                  num: domain.counters.groups,
                                }
                              )
                            }}</span>
                          </cv-link>
                        </template>
                      </div>
                      <div
                        v-if="domain.hasUnconfiguredProviders"
                        class="row icon-and-text"
                      >
                        <NsSvg :svg="Warning16" class="icon ns-warning" />
                        <cv-link @click="goToDomainConfiguration(domain)">
                          <span>{{ $t("domains.unconfigured_provider") }}</span>
                        </cv-link>
                      </div>
                      <div v-else class="row">
                        <cv-link @click="goToDomainConfiguration(domain)">
                          {{ domain.providers.length }}
                          {{
                            $tc("domains.providers", domain.providers.length)
                          }}
                        </cv-link>
                        <template v-if="domain.fileServerProvider">
                          <span class="bullet-separator">&bull;</span>
                          <cv-link
                            @click="goToFileServer(domain.fileServerProvider)"
                          >
                            <span>{{ $t("samba.file_server") }}</span>
                          </cv-link>
                        </template>
                      </div>
                      <div class="row actions">
                        <NsButton
                          kind="ghost"
                          :icon="ArrowRight20"
                          @click="goToDomainUsersAndGroups(domain)"
                          :data-test-id="domain.name + '-users-and-groups'"
                          >{{ $t("common.see_details") }}</NsButton
                        >
                      </div>
                    </div>
                  </template>
                </NsInfoCard>
              </div>
            </cv-column>
          </cv-row>
        </template>
⋮----
>{{ $t("domains.create_domain") }}
⋮----
<template #menu>
                    <cv-overflow-menu
                      :flip-menu="true"
                      tip-position="top"
                      tip-alignment="end"
                      class="top-right-overflow-menu"
                      :data-test-id="domain.name + '-menu'"
                    >
                      <cv-overflow-menu-item
                        v-if="domain.location == 'internal'"
                        @click="showImportUsersModal(domain)"
                        :data-test-id="domain.name + '-import-data'"
                      >
                        <NsMenuItem
                          :icon="Upload20"
                          :label="$t('domain_users.import_data')"
                        />
                      </cv-overflow-menu-item>
                      <cv-overflow-menu-item
                        v-if="domain.location == 'internal'"
                        @click="exportUsersData(domain)"
                        :data-test-id="domain.name + '-export-data'"
                      >
                        <NsMenuItem
                          :icon="Export20"
                          :label="$t('domain_users.export_data')"
                        />
                      </cv-overflow-menu-item>
                      <cv-overflow-menu-item
                        danger
                        @click="showDeleteDomainModal(domain)"
                        :data-test-id="domain.name + '-delete'"
                      >
                        <NsMenuItem
                          :icon="TrashCan20"
                          :label="$t('common.delete')"
                        />
                      </cv-overflow-menu-item>
                    </cv-overflow-menu>
                  </template>
<template #content>
                    <div class="domain-card-content">
                      <div class="row">
                        <span>{{ $t("domains." + domain.location) }}</span>
                        <template v-if="domain.location == 'internal'">
                          <span v-if="domain.schema == 'rfc2307'">
                            {{ $t("domains.openldap") }}
                          </span>
                          <span v-else-if="domain.schema == 'ad'">
                            {{ $t("domains.samba") }}
                          </span>
                        </template>
                        <template v-else>
                          {{ $t("domains.ldap") }}
                        </template>
                      </div>
                      <div v-if="domain.counters" class="row">
                        <cv-link
                          v-if="domain.counters.users != null"
                          @click="goToDomainUsersAndGroups(domain)"
                        >
                          <span>{{
                            $tc(
                              "domain_users.num_users_c",
                              domain.counters.users,
                              {
                                num: domain.counters.users,
                              }
                            )
                          }}</span>
                        </cv-link>
                        <template v-if="domain.counters.groups != null">
                          <span class="bullet-separator">&bull;</span>
                          <cv-link
                            @click="goToDomainUsersAndGroups(domain, 'groups')"
                          >
                            <span>{{
                              $tc(
                                "domain_users.num_groups_c",
                                domain.counters.groups,
                                {
                                  num: domain.counters.groups,
                                }
                              )
                            }}</span>
                          </cv-link>
                        </template>
                      </div>
                      <div
                        v-if="domain.hasUnconfiguredProviders"
                        class="row icon-and-text"
                      >
                        <NsSvg :svg="Warning16" class="icon ns-warning" />
                        <cv-link @click="goToDomainConfiguration(domain)">
                          <span>{{ $t("domains.unconfigured_provider") }}</span>
                        </cv-link>
                      </div>
                      <div v-else class="row">
                        <cv-link @click="goToDomainConfiguration(domain)">
                          {{ domain.providers.length }}
                          {{
                            $tc("domains.providers", domain.providers.length)
                          }}
                        </cv-link>
                        <template v-if="domain.fileServerProvider">
                          <span class="bullet-separator">&bull;</span>
                          <cv-link
                            @click="goToFileServer(domain.fileServerProvider)"
                          >
                            <span>{{ $t("samba.file_server") }}</span>
                          </cv-link>
                        </template>
                      </div>
                      <div class="row actions">
                        <NsButton
                          kind="ghost"
                          :icon="ArrowRight20"
                          @click="goToDomainUsersAndGroups(domain)"
                          :data-test-id="domain.name + '-users-and-groups'"
                          >{{ $t("common.see_details") }}</NsButton
                        >
                      </div>
                    </div>
                  </template>
⋮----
<span>{{ $t("domains." + domain.location) }}</span>
<template v-if="domain.location == 'internal'">
                          <span v-if="domain.schema == 'rfc2307'">
                            {{ $t("domains.openldap") }}
                          </span>
                          <span v-else-if="domain.schema == 'ad'">
                            {{ $t("domains.samba") }}
                          </span>
                        </template>
⋮----
{{ $t("domains.openldap") }}
⋮----
{{ $t("domains.samba") }}
⋮----
<template v-else>
                          {{ $t("domains.ldap") }}
                        </template>
⋮----
{{ $t("domains.ldap") }}
⋮----
<span>{{
                            $tc(
                              "domain_users.num_users_c",
                              domain.counters.users,
                              {
                                num: domain.counters.users,
                              }
                            )
                          }}</span>
⋮----
<template v-if="domain.counters.groups != null">
                          <span class="bullet-separator">&bull;</span>
                          <cv-link
                            @click="goToDomainUsersAndGroups(domain, 'groups')"
                          >
                            <span>{{
                              $tc(
                                "domain_users.num_groups_c",
                                domain.counters.groups,
                                {
                                  num: domain.counters.groups,
                                }
                              )
                            }}</span>
                          </cv-link>
                        </template>
⋮----
<span>{{
                              $tc(
                                "domain_users.num_groups_c",
                                domain.counters.groups,
                                {
                                  num: domain.counters.groups,
                                }
                              )
                            }}</span>
⋮----
<span>{{ $t("domains.unconfigured_provider") }}</span>
⋮----
{{ domain.providers.length }}
{{
                            $tc("domains.providers", domain.providers.length)
                          }}
⋮----
<template v-if="domain.fileServerProvider">
                          <span class="bullet-separator">&bull;</span>
                          <cv-link
                            @click="goToFileServer(domain.fileServerProvider)"
                          >
                            <span>{{ $t("samba.file_server") }}</span>
                          </cv-link>
                        </template>
⋮----
<span>{{ $t("samba.file_server") }}</span>
⋮----
>{{ $t("common.see_details") }}</NsButton
⋮----
<script>
import {
  QueryParamService,
  UtilService,
  TaskService,
  IconService,
  PageTitleService,
} from "@nethserver/ns8-ui-lib";
import CreateDomainModal from "@/components/domains/CreateDomainModal";
import ImportUsersModal from "@/components/domains/ImportUsersModal";
import Upload20 from "@carbon/icons-vue/es/upload/20";
import Export20 from "@carbon/icons-vue/es/export/20";
import to from "await-to-js";
import { mapState } from "vuex";
import Papa from "papaparse";
export default {
  name: "Domains",
  components: { CreateDomainModal, ImportUsersModal },
  mixins: [
    TaskService,
    UtilService,
    IconService,
    QueryParamService,
    PageTitleService,
  ],
  pageTitle() {
    return this.$t("domains.title");
  },
  data() {
    return {
      q: {},
      isShownCreateDomainModal: false,
      domains: [],
      unconfiguredDomains: [],
      isShownDeleteDomainModal: false,
      currentDomain: {
        name: "",
        location: "",
      },
      createDomain: {
        isResumeConfiguration: false,
        isOpenLdap: false,
        isSamba: false,
        providerId: "",
      },
      domainToDelete: null,
      loading: {
        listUserDomains: true,
      },
      error: {
        listUserDomains: "",
        removeModule: "",
        removeExternalDomain: "",
        removeInternalDomain: "",
        downloadCsvFile: "",
      },
      Upload20,
      Export20,
      importData: {
        domain: {},
      },
      downloadCsv: {
        name: "",
      },
      isShownImportUsersModal: false,
    };
  },
  computed: {
    ...mapState(["clusterNodes"]),
    hasUnconfiguredDomainsOrProviders() {
      return (
        this.unconfiguredDomains.length ||
        this.domains.find((d) => d.hasUnconfiguredProviders)
      );
    },
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.watchQueryData(vm);
      vm.queryParamsToDataForCore(vm, to.query);
    });
  },
  beforeRouteUpdate(to, from, next) {
    this.queryParamsToDataForCore(this, to.query);
    next();
  },
  created() {
    this.listUserDomains();
  },
  methods: {
    goTo(path) {
      this.$router.push(path);
    },
    async listUserDomains() {
      this.loading.listUserDomains = true;
      this.error.listUserDomains = "";
      const taskAction = "list-user-domains";
      this.$root.$once(
        taskAction + "-completed",
        this.listUserDomainsCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.listUserDomains = this.getErrorMessage(err);
        return;
      }
    },
    listUserDomainsCompleted(taskContext, taskResult) {
      let domains = taskResult.output.domains;
      if (domains.length) {
        domains.sort(this.sortByProperty("name"));
      }
      for (const domain of domains) {
        const unconfiguredProvidersFound = domain.providers.find(
          (p) => !p.host
        );
        if (unconfiguredProvidersFound) {
          domain.hasUnconfiguredProviders = true;
        } else {
          domain.hasUnconfiguredProviders = false;
        }
        const fileServerProviderFound = domain.providers.find(
          (p) => p.file_server
        );
        if (fileServerProviderFound) {
          domain.fileServerProvider = fileServerProviderFound;
        }
      }
      this.domains = domains;
      let unconfiguredDomains = taskResult.output.unconfigured_domains;
      if (unconfiguredDomains.length) {
        unconfiguredDomains.sort(this.sortByProperty("module_id"));
      }
      this.unconfiguredDomains = unconfiguredDomains;
      this.loading.listUserDomains = false;
    },
    async exportUsersData(domain) {
      this.loading.downloadCsvFile = true;
      this.error.downloadCsvFile = "";
      this.downloadCsv.name = domain.name;
      const taskAction = "export-users";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.exportUsersDataAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.exportUsersDataCompleted
      );
      this.$root.$once(
        `${taskAction}-validation-ok-${eventId}`,
        this.exportUsersDataValidationOk
      );
      this.$root.$once(
        `${taskAction}-validation-failed-${eventId}`,
        this.exportUsersDataValidationFailed
      );
      const res = await to(
        this.createModuleTaskForApp(domain.providers[0].id, {
          action: taskAction,
          data: {},
          extra: {
            title: this.$t("action.export-users"),
            description: this.$t("common.processing"),
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.downloadCsvFile = this.getErrorMessage(err);
        this.loading.downloadCsvFile = false;
        return;
      }
    },
    exportUsersDataAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.loading.downloadCsvFile = false;
    },
    exportUsersDataCompleted(taskContext, taskResult) {
      const jsonData = taskResult.output.records;
      let records = jsonData;
      if (typeof jsonData === "string") {
        try {
          records = JSON.parse(jsonData);
        } catch (err) {
          console.error("Error parsing JSON records:", err);
          this.loading.downloadCsvFile = false;
          return;
        }
      }
      let columnOrder = [
        "user",
        "display_name",
        "password",
        "mail",
        "groups",
        "locked",
        "must_change_password",
        "no_password_expiration",
      ];
      const csvRecords = records.map((record) => {
        const orderedRecord = {};
        columnOrder.forEach((column) => {
          if (column === "groups" && Array.isArray(record[column])) {
            orderedRecord[column] = record[column].join("|");
          } else {
            orderedRecord[column] = record[column];
          }
        });
        return orderedRecord;
      });
      const csv = Papa.unparse(csvRecords, {
        header: true,
        columns: columnOrder,
      });
      const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });
      const link = document.createElement("a");
      const url = URL.createObjectURL(blob);
      const now = new Date();
      const pad = (n) => String(n).padStart(2, "0");
      const timestamp = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(
        now.getDate()
      )}${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
      link.setAttribute("href", url);
      link.setAttribute(
        "download",
        `${this.downloadCsv.name}_${timestamp}.csv`
      );
      link.style.visibility = "hidden";
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);
      this.loading.downloadCsvFile = false;
    },
    exportUsersDataValidationOk() {
      this.loading.downloadCsvFile = false;
    },
    exportUsersDataValidationFailed(validationErrors) {
      this.loading.downloadCsvFile = false;
      let focusAlreadySet = false;
      for (const validationError of validationErrors) {
        const param = validationError.parameter;
        this.error[param] = this.$t("domain_users." + validationError.error, {
          tok: validationError.value,
        });
        if (!focusAlreadySet) {
          this.focusElement(param);
          focusAlreadySet = true;
        }
      }
    },
    showImportUsersModal(domain) {
      this.importData.domain = domain;
      this.$nextTick(() => {
        this.isShownImportUsersModal = true;
      });
    },
    hideImportUsersModal() {
      this.isShownImportUsersModal = false;
    },
    showCreateDomainModal() {
      this.createDomain.isResumeConfiguration = false;
      this.createDomain.providerId = "";
      this.$nextTick(() => {
        this.isShownCreateDomainModal = true;
      });
    },
    hideCreateDomainModal() {
      this.isShownCreateDomainModal = false;
    },
    showDeleteDomainModal(domain) {
      this.isShownDeleteDomainModal = true;
      this.currentDomain = domain;
    },
    hideDeleteDomainModal() {
      this.isShownDeleteDomainModal = false;
    },
    goToDomainUsersAndGroups(domain, view) {
      this.$router.push({
        name: "DomainUsersAndGroups",
        params: { domainName: domain.name },
        query: { view: view },
      });
    },
    deleteDomain(domain) {
      this.isShownDeleteDomainModal = false;
      if (domain.location == "internal") {
        this.removeInternalDomain(domain);
      } else {
        this.removeExternalDomain(domain);
      }
    },
    async removeInternalDomain(domain) {
      this.error.removeInternalDomain = "";
      const taskAction = "remove-internal-domain";
      this.$root.$once(
        taskAction + "-completed",
        this.removeInternalDomainCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {
            domain: domain.name,
          },
          extra: {
            title: this.$t("action." + taskAction),
            description: this.$t("common.processing"),
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.removeInternalDomain = this.getErrorMessage(err);
        return;
      }
    },
    removeInternalDomainCompleted() {
      this.listUserDomains();
      this.$root.$emit("reloadAppDrawer");
    },
    async removeExternalDomain(domain) {
      this.error.removeExternalDomain = "";
      const taskAction = "remove-external-domain";
      this.$root.$once(
        taskAction + "-completed",
        this.removeExternalDomainCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {
            domain: domain.name,
          },
          extra: {
            title: this.$t("action." + taskAction),
            description: this.$t("common.processing"),
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.removeExternalDomain = this.getErrorMessage(err);
        return;
      }
    },
    removeExternalDomainCompleted() {
      this.listUserDomains();
    },
    willDeleteUnconfiguredDomain(domain) {
      const timeout = setTimeout(() => {
        this.deleteUnconfiguredDomain(domain);
        this.domainToDelete = null;
      }, this.DELETE_DELAY);
      domain.timeout = timeout;
      this.domainToDelete = domain;
      this.unconfiguredDomains = this.unconfiguredDomains.filter((d) => {
        return d.module_id != domain.module_id;
      });
    },
    async deleteUnconfiguredDomain(domain) {
      this.error.removeModule = "";
      const taskAction = "remove-internal-provider";
      this.$root.$on(
        taskAction + "-completed",
        this.deleteUnconfiguredDomainCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {
            module_id: domain.module_id,
          },
          extra: {
            title: this.$t("action." + taskAction),
            description: this.$t("common.processing"),
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.removeModule = this.getErrorMessage(err);
        return;
      }
    },
    deleteUnconfiguredDomainCompleted() {
      this.listUserDomains();
    },
    showUnconfiguredDomainModal(unconfiguredDomain) {
      if (unconfiguredDomain.schema == "rfc2307") {
        this.createDomain.isOpenLdap = true;
        this.createDomain.isSamba = false;
      } else if (unconfiguredDomain.schema == "ad") {
        this.createDomain.isOpenLdap = false;
        this.createDomain.isSamba = true;
      }
      this.createDomain.isResumeConfiguration = true;
      this.createDomain.providerId = unconfiguredDomain.module_id;
      this.$nextTick(() => {
        this.isShownCreateDomainModal = true;
      });
    },
    cancelDeleteUnconfiguredDomain() {
      clearTimeout(this.domainToDelete.timeout);
      this.domainToDelete = null;
      this.listUserDomains();
    },
    goToDomainConfiguration(domain) {
      this.$router.push({
        name: "DomainUsersAndGroups",
        params: { domainName: domain.name },
        query: { view: "configuration" },
      });
    },
    goToFileServer(fileServerProvider) {
      this.$router.push(`/apps/${fileServerProvider.id}`);
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../styles/carbon-utils";
.domain-card-content .row {
  margin-bottom: $spacing-05;
  text-align: center;
}
.domain-card-content .row:last-child {
  margin-bottom: 0;
}
.actions {
  margin-top: $spacing-06;
}
</style>
</file>

<file path="core/ui/src/views/InitializeCluster.vue">
<template>
  <div class="initialize-cluster">
    <cv-grid class="welcome-grid">
      <cv-loading :active="isJoiningCluster" :overlay="true"></cv-loading>
      <template v-if="q.page === 'welcome'">
        <cv-row>
          <cv-column class="welcome">
            <h2>
              {{
                $t("init.welcome", { product: this.$root.config.PRODUCT_NAME })
              }}
            </h2>
            <WelcomeLogo />
          </cv-column>
        </cv-row>
        <cv-row>
          <cv-column>
            <cv-tile light>
              <cv-grid fullWidth class="mg-top-xlg">
                <NsInlineNotification
                  v-if="error.listMountPoints"
                  kind="error"
                  :title="$t('action.list-mountpoints')"
                  :description="error.listMountPoints"
                  :showCloseButton="false"
                />
                <template v-if="!loading.listMountPoints">
                  <cv-row>
                    <cv-column>
                      <NsTile
                        kind="clickable"
                        :icon="EdgeCluster32"
                        @click="selectCreateCluster"
                        large
                      >
                        <h6 class="mg-bottom-sm">
                          {{ $t("init.create_cluster") }}
                        </h6>
                        <div class="tile-description">
                          {{ $t("init.create_cluster_description") }}
                        </div>
                      </NsTile>
                    </cv-column>
                    <cv-column>
                      <NsTile
                        kind="clickable"
                        :icon="Connect32"
                        @click="selectJoinCluster"
                        large
                      >
                        <h6 class="mg-bottom-sm">
                          {{ $t("init.join_cluster") }}
                        </h6>
                        <div class="tile-description">
                          {{ $t("init.join_cluster_description") }}
                        </div>
                      </NsTile>
                    </cv-column>
                    <cv-column>
                      <NsTile
                        kind="clickable"
                        :icon="Reset32"
                        @click="selectRestoreCluster"
                        large
                      >
                        <h6 class="mg-bottom-sm">
                          {{ $t("init.restore_cluster") }}
                        </h6>
                        <div class="tile-description">
                          {{ $t("init.restore_cluster_description") }}
                        </div>
                      </NsTile>
                    </cv-column>
                  </cv-row>
                </template>
                <cv-skeleton-text v-else :paragraph="true" :line-count="5" />
              </cv-grid>
            </cv-tile>
          </cv-column>
        </cv-row>
      </template>
      <template v-else-if="q.page === 'fqdn'">
        <template
          v-if="isPasswordChangeNeeded && $route.query.action === 'create'"
        >
          <cv-row>
            <cv-column class="welcome">
              <div>
                <h2>{{ $t("init.create_cluster") }}</h2>
                <div class="title-description">
                  {{ $t("init.create_cluster_description") }}
                </div>
              </div>
              <WelcomeLogo />
            </cv-column>
          </cv-row>
          <cv-row>
            <cv-column>
              <NsInlineNotification
                kind="info"
                :title="$t('init.change_admin_password')"
                :description="$t('init.change_admin_password_description')"
                :showCloseButton="false"
              />
            </cv-column>
          </cv-row>
          <cv-row>
            <cv-column>
              <cv-tile light>
                <cv-form @submit.prevent="changePassword">
                  <cv-text-input
                    :label="$t('init.current_password')"
                    v-model="currentPassword"
                    :invalid-message="$t(error.currentPassword)"
                    type="password"
                    ref="currentPassword"
                  >
                  </cv-text-input>
                  <NsPasswordInput
                    :newPasswordLabel="$t('init.new_password')"
                    :confirmPasswordLabel="$t('init.new_password_confirm')"
                    v-model="newPassword"
                    @passwordValidation="onPasswordValidation"
                    :newPasswordInvalidMessage="$t(error.newPassword)"
                    :confirmPasswordInvalidMessage="$t(error.confirmPassword)"
                    :passwordHideLabel="$t('password.hide_password')"
                    :passwordShowLabel="$t('password.show_password')"
                    :lengthLabel="$t('password.long_enough')"
                    :lowercaseLabel="$t('password.lowercase_letter')"
                    :uppercaseLabel="$t('password.uppercase_letter')"
                    :numberLabel="$t('password.number')"
                    :symbolLabel="$t('password.symbol')"
                    :equalLabel="$t('password.equal')"
                    :focus="focusPasswordField"
                  />
                  <cv-button-set class="footer-buttons">
                    <NsButton
                      type="button"
                      kind="secondary"
                      :icon="ChevronLeft20"
                      size="lg"
                      @click="goToWelcomePage"
                      >{{ $t("common.go_back") }}
                    </NsButton>
                    <NsButton
                      kind="primary"
                      :loading="isChangingPassword"
                      :disabled="isChangingPassword"
                      :icon="Password20"
                      size="lg"
                      >{{ $t("init.change_password") }}
                    </NsButton>
                  </cv-button-set>
                </cv-form>
              </cv-tile>
            </cv-column>
          </cv-row>
        </template>
        <template v-else>
          <SetFqdn
            :action="$route.query.action"
            @goBack="goToWelcomePage"
            @fqdnSet="onFqdnSet"
          />
        </template>
      </template>
      <template v-else-if="q.page === 'create'">
        <template>
          <cv-row>
            <cv-column class="welcome">
              <div>
                <h2>{{ $t("init.create_cluster") }}</h2>
                <div class="title-description">
                  {{ $t("init.create_cluster_description") }}
                </div>
              </div>
              <WelcomeLogo />
            </cv-column>
          </cv-row>
          <cv-row v-if="error.networkCheckCreateCluster">
            <cv-column>
              <NsInlineNotification
                kind="error"
                :title="$t('action.create-cluster')"
                :description="error.networkCheckCreateCluster"
                :showCloseButton="false"
              />
            </cv-column>
          </cv-row>
          <cv-row v-if="!isCreatingCluster">
            <cv-column>
              <NsInlineNotification
                kind="info"
                :title="$t('init.vpn_network')"
                :description="$t('init.vpn_cidr_tooltip')"
                :showCloseButton="false"
              />
            </cv-column>
          </cv-row>
          <cv-row>
            <cv-column>
              <cv-tile light>
                <template v-if="!isCreatingCluster">
                  <NsInlineNotification
                    v-if="error.getDefaults"
                    kind="error"
                    :title="$t('action.get-defaults')"
                    :description="error.getFqdn"
                    :showCloseButton="false"
                  />
                  <cv-form v-else @submit.prevent="createCluster">
                    <cv-skeleton-text
                      v-if="loading.getDefaults"
                      :paragraph="true"
                      :line-count="3"
                      heading
                    ></cv-skeleton-text>
                    <template v-else>
                      <NsTextInput
                        :label="$t('init.vpn_cidr')"
                        v-model.trim="network"
                        :invalid-message="$t(error.network)"
                        :disabled="loading.getDefaults || isCreatingCluster"
                        tooltipAlignment="end"
                        tooltipDirection="right"
                        class="narrow"
                        ref="network"
                      />
                    </template>
                    <cv-button-set class="footer-buttons">
                      <NsButton
                        type="button"
                        kind="secondary"
                        :icon="ChevronLeft20"
                        size="lg"
                        @click="goToFqdnPage"
                        >{{ $t("common.go_back") }}
                      </NsButton>
                      <NsButton
                        kind="primary"
                        :loading="isCreatingCluster"
                        :disabled="loading.getDefaults || isCreatingCluster"
                        :icon="EdgeCluster20"
                        size="lg"
                        >{{ $t("init.create_cluster") }}
                      </NsButton>
                    </cv-button-set>
                  </cv-form>
                </template>
                <template v-else>
                  <NsInlineNotification
                    v-if="error.createCluster"
                    kind="error"
                    :title="$t('action.create-cluster')"
                    :description="error.createCluster"
                    :showCloseButton="false"
                  />
                  <NsEmptyState
                    :title="$t('init.creating_cluster')"
                    :animationData="GearsLottie"
                    animationTitle="gears"
                    :loop="true"
                  />
                  <NsProgressBar
                    :value="createClusterProgress"
                    :indeterminate="!createClusterProgress"
                    class="mg-bottom-xlg"
                  />
                </template>
              </cv-tile>
            </cv-column>
          </cv-row>
        </template>
      </template>
      <template v-else-if="q.page === 'join'">
        <cv-row>
          <cv-column class="welcome">
            <div>
              <h2>{{ $t("init.join_cluster") }}</h2>
              <div class="title-description">
                {{ $t("init.join_cluster_description") }}
              </div>
            </div>
            <WelcomeLogo />
          </cv-column>
        </cv-row>
        <cv-row>
          <cv-column>
            <cv-tile light>
              <cv-form @submit.prevent="joinCluster">
                <cv-text-area
                  :label="$t('common.join_code')"
                  v-model.trim="joinCode"
                  :invalid-message="$t(error.joinCode)"
                  :helper-text="
                    $t('init.join_code_helper_text') +
                    ' https://LEADER_NODE_IP/cluster-admin/#/nodes?isShownAddNodeModal=true'
                  "
                  class="join-code"
                  ref="joinCode"
                >
                </cv-text-area>
                <cv-checkbox
                  :label="$t('init.tls_verify')"
                  v-model="tlsVerify"
                  value="checkTlsVerify"
                />
                <cv-button-set class="footer-buttons">
                  <NsButton
                    type="button"
                    kind="secondary"
                    :icon="ChevronLeft20"
                    size="lg"
                    @click="goToFqdnPage"
                    >{{ $t("common.go_back") }}
                  </NsButton>
                  <NsButton
                    kind="primary"
                    :loading="isJoiningCluster"
                    :disabled="isJoiningCluster"
                    :icon="Connect20"
                    size="lg"
                    >{{ $t("init.join_cluster") }}
                  </NsButton>
                </cv-button-set>
              </cv-form>
            </cv-tile>
          </cv-column>
        </cv-row>
      </template>
      <template v-else-if="q.page === 'restore'">
        <template v-if="isPasswordChangeNeeded">
          <cv-row>
            <cv-column class="welcome">
              <div>
                <h2>{{ $t("init.restore_cluster") }}</h2>
                <div class="title-description">
                  {{ $t("init.restore_cluster_description") }}
                </div>
              </div>
              <WelcomeLogo />
            </cv-column>
          </cv-row>
          <cv-row>
            <cv-column>
              <NsInlineNotification
                kind="info"
                :title="$t('init.change_admin_password')"
                :description="$t('init.change_admin_password_description')"
                :showCloseButton="false"
              />
            </cv-column>
          </cv-row>
          <cv-row>
            <cv-column>
              <cv-tile light>
                <cv-form @submit.prevent="changePassword">
                  <cv-text-input
                    :label="$t('init.current_password')"
                    v-model="currentPassword"
                    :invalid-message="$t(error.currentPassword)"
                    type="password"
                    ref="currentPassword"
                  >
                  </cv-text-input>
                  <NsPasswordInput
                    :newPasswordLabel="$t('init.new_password')"
                    :confirmPasswordLabel="$t('init.new_password_confirm')"
                    v-model="newPassword"
                    @passwordValidation="onPasswordValidation"
                    :newPasswordInvalidMessage="$t(error.newPassword)"
                    :confirmPasswordInvalidMessage="$t(error.confirmPassword)"
                    :passwordHideLabel="$t('password.hide_password')"
                    :passwordShowLabel="$t('password.show_password')"
                    :lengthLabel="$t('password.long_enough')"
                    :lowercaseLabel="$t('password.lowercase_letter')"
                    :uppercaseLabel="$t('password.uppercase_letter')"
                    :numberLabel="$t('password.number')"
                    :symbolLabel="$t('password.symbol')"
                    :equalLabel="$t('password.equal')"
                    :focus="focusPasswordField"
                  />
                  <cv-button-set class="footer-buttons">
                    <NsButton
                      type="button"
                      kind="secondary"
                      :icon="ChevronLeft20"
                      size="lg"
                      @click="goToWelcomePage"
                      >{{ $t("common.go_back") }}
                    </NsButton>
                    <NsButton
                      kind="primary"
                      :loading="isChangingPassword"
                      :disabled="isChangingPassword"
                      :icon="Password20"
                      size="lg"
                      >{{ $t("init.change_password") }}
                    </NsButton>
                  </cv-button-set>
                </cv-form>
              </cv-tile>
            </cv-column>
          </cv-row>
        </template>
        <template v-else>
          <cv-row>
            <cv-column class="welcome">
              <div>
                <h2>{{ $t("init.restore_cluster") }}</h2>
                <div class="title-description">
                  {{ $t("init.restore_cluster_description") }}
                </div>
              </div>
              <WelcomeLogo />
            </cv-column>
          </cv-row>
          <template v-if="restore.step == 'type'">
            <cv-row>
              <cv-column>
                <cv-tile light>
                  <cv-grid fullWidth class="mg-top-xlg no-padding">
                    <cv-row>
                      <cv-column :md="4">
                        <NsTile
                          kind="clickable"
                          :icon="Link32"
                          @click="goToRestoreFromUrl"
                          large
                        >
                          <h6>
                            {{ $t("init.restore_from_remote_url") }}
                          </h6>
                        </NsTile>
                      </cv-column>
                      <cv-column :md="4">
                        <NsTile
                          kind="clickable"
                          :icon="Document32"
                          @click="goToRestoreFromFile"
                          large
                        >
                          <h6>
                            {{ $t("init.restore_from_cluster_backup_file") }}
                          </h6>
                        </NsTile>
                      </cv-column>
                    </cv-row>
                  </cv-grid>
                  <cv-button-set class="footer-buttons">
                    <NsButton
                      type="button"
                      kind="secondary"
                      :icon="ChevronLeft20"
                      size="lg"
                      @click="goToWelcomePage"
                      >{{ $t("common.go_back") }}
                    </NsButton>
                  </cv-button-set>
                </cv-tile>
              </cv-column>
            </cv-row>
          </template>
          <template v-else-if="restore.step == 'url'">
            <cv-row>
              <cv-column>
                <cv-tile light>
                  <h5 class="mg-bottom-md">
                    {{ $t("init.restore_from_remote_url") }}
                  </h5>
                  <cv-form @submit.prevent="retrieveClusterBackupFromUrl">
                    <NsTextInput
                      v-model.trim="restore.url"
                      :label="$t('init.remote_url')"
                      placeholder="https://myserver/cluster-backup.json.gz.gpg"
                      :invalid-message="error.restore.url"
                      :disabled="loading.retrieveClusterBackup"
                      class="mg-bottom-sm"
                      ref="url"
                    />
                    <cv-checkbox
                      :label="$t('init.tls_verify')"
                      v-model="restore.tlsVerify"
                      value="checkTlsVerify"
                    />
                    <NsTextInput
                      type="password"
                      :password-hide-label="$t('password.hide_password')"
                      :password-show-label="$t('password.show_password')"
                      v-model="restore.backupPassword"
                      :label="$t('init.backup_password')"
                      :invalid-message="error.restore.backup_password"
                      :disabled="loading.retrieveClusterBackup"
                      tooltipAlignment="center"
                      tooltipDirection="right"
                      ref="backup_password"
                      class="mg-top-md"
                    >
                      <template #tooltip>
                        <span>{{ $t("init.backup_password_tooltip") }}</span>
                      </template>
                    </NsTextInput>
                    <cv-button-set class="footer-buttons">
                      <NsButton
                        type="button"
                        kind="secondary"
                        :icon="ChevronLeft20"
                        size="lg"
                        @click="goToRestoreType"
                        >{{ $t("common.go_back") }}
                      </NsButton>
                      <NsButton
                        kind="primary"
                        :loading="loading.retrieveClusterBackup"
                        :disabled="loading.retrieveClusterBackup"
                        :icon="ChevronRight20"
                        size="lg"
                        >{{ $t("common.next") }}
                      </NsButton>
                    </cv-button-set>
                  </cv-form>
                </cv-tile>
              </cv-column>
            </cv-row>
          </template>
          <template v-else-if="restore.step == 'file'">
            <cv-row>
              <cv-column>
                <cv-tile light>
                  <h5 class="mg-bottom-md">
                    {{ $t("init.restore_from_cluster_backup_file") }}
                  </h5>
                  <cv-form @submit.prevent="retrieveClusterBackupFromFile">
                    <div>
                      {{ $t("init.upload_cluster_backup_file") }}
                    </div>
                    <cv-file-uploader
                      :drop-target-label="$t('common.upload_drop_target_text')"
                      accept=".json.gz.gpg,.bin,.gpg"
                      :clear-on-reselect="true"
                      :multiple="false"
                      :removable="true"
                      :remove-aria-label="$t('common.remove')"
                      v-model="restore.filesUploaded"
                      @change="onFileUpload"
                      :class="[
                        'file-uploader',
                        { 'validation-failed': error.restore.backup_file },
                      ]"
                      ref="backup_file"
                    >
                    </cv-file-uploader>
                    <div
                      v-if="error.restore.backup_file"
                      class="validation-failed-invalid-message"
                    >
                      {{ error.restore.backup_file }}
                    </div>
                    <NsTextInput
                      type="password"
                      :password-hide-label="$t('password.hide_password')"
                      :password-show-label="$t('password.show_password')"
                      v-model="restore.backupPassword"
                      :label="$t('init.backup_password')"
                      :invalid-message="error.restore.backup_password"
                      :disabled="loading.retrieveClusterBackup"
                      tooltipAlignment="center"
                      tooltipDirection="right"
                      ref="backup_password"
                      class="mg-top-md"
                    >
                      <template #tooltip>
                        <span>{{ $t("init.backup_password_tooltip") }}</span>
                      </template>
                    </NsTextInput>
                    <NsInlineNotification
                      v-if="error.retrieveClusterBackup"
                      kind="error"
                      :title="$t('action.retrieve-cluster-backup')"
                      :description="error.retrieveClusterBackup"
                      :showCloseButton="false"
                    />
                    <cv-button-set class="footer-buttons">
                      <NsButton
                        type="button"
                        kind="secondary"
                        :icon="ChevronLeft20"
                        size="lg"
                        @click="goToRestoreType"
                        >{{ $t("common.go_back") }}
                      </NsButton>
                      <NsButton
                        kind="primary"
                        :loading="loading.retrieveClusterBackup"
                        :disabled="loading.retrieveClusterBackup"
                        :icon="ChevronRight20"
                        size="lg"
                        >{{ $t("common.next") }}
                      </NsButton>
                    </cv-button-set>
                  </cv-form>
                </cv-tile>
              </cv-column>
            </cv-row>
          </template>
          <template v-else-if="restore.step == 'summary'">
            <cv-row>
              <cv-column>
                <cv-tile light>
                  <h5 class="mg-bottom-md">
                    {{ $t("init.restore_summary") }}
                  </h5>
                  <cv-form @submit.prevent="restoreCluster">
                    <div
                      v-if="restore.summary.cluster"
                      class="key-value-setting"
                    >
                      <span class="label">{{ $t("init.cluster_label") }}</span>
                      <span class="value">{{ restore.summary.cluster }}</span>
                    </div>
                    <div class="key-value-setting">
                      <span class="label">{{ $t("init.vpn_endpoint") }}</span>
                      <span class="value">{{ restore.summary.vpn }}</span>
                    </div>
                    <div class="key-value-setting">
                      <span class="label">{{
                        $t("init.external_domains")
                      }}</span>
                      <span class="value">{{ restore.summary.domains }}</span>
                    </div>
                    <div class="key-value-setting">
                      <span class="label">{{
                        $t("init.backup_repositories")
                      }}</span>
                      <span class="value">{{
                        restore.summary.backup_repositories
                      }}</span>
                    </div>
                    <NsInlineNotification
                      kind="info"
                      :title="$t('init.apps_restoration')"
                      :description="
                        restore.summary.single_node_cluster
                          ? $t('init.apps_restoration_single_node_description')
                          : $t('init.apps_restoration_multi_node_description')
                      "
                      :showCloseButton="false"
                      class="mg-top-lg"
                    />
                    <NsInlineNotification
                      v-if="error.restoreCluster"
                      kind="error"
                      :title="$t('action.restore-cluster')"
                      :description="error.restoreCluster"
                      :showCloseButton="false"
                    />
                    <cv-button-set class="footer-buttons">
                      <NsButton
                        type="button"
                        kind="secondary"
                        :icon="ChevronLeft20"
                        size="lg"
                        @click="goToRestoreFromFileOrUrl"
                        >{{ $t("common.go_back") }}
                      </NsButton>
                      <NsButton
                        kind="primary"
                        :loading="loading.restoreCluster"
                        :disabled="loading.restoreCluster"
                        :icon="Reset20"
                        size="lg"
                        >{{ $t("init.restore_cluster") }}
                      </NsButton>
                    </cv-button-set>
                  </cv-form>
                </cv-tile>
              </cv-column>
            </cv-row>
          </template>
          <template v-if="restore.step == 'restoringCluster'">
            <NsInlineNotification
              v-if="error.restoreCluster"
              kind="error"
              :title="$t('action.restore-cluster')"
              :description="error.restoreCluster"
              :showCloseButton="false"
            />
            <NsInlineNotification
              v-if="error.readBackupRepositories"
              kind="error"
              :title="$t('action.read-backup-repositories')"
              :description="error.readBackupRepositories"
              :showCloseButton="false"
            />
            <cv-row
              v-if="!error.restoreCluster && !error.readBackupRepositories"
            >
              <cv-column>
                <cv-tile light>
                  <NsEmptyState
                    :title="$t('init.restoring_cluster')"
                    :animationData="GearsLottie"
                    animationTitle="gears"
                    :loop="true"
                  >
                    <template #description>
                      <span v-if="restore.progress < 100">
                        {{ $t("init.traveling_back_in_time") }}
                      </span>
                      <span v-else-if="loading.readBackupRepositories">
                        {{ $t("init.reading_backup_repositories") }}
                      </span>
                      <span v-else>&nbsp;</span>
                    </template>
                  </NsEmptyState>
                  <NsProgressBar
                    :value="restore.progress"
                    :indeterminate="!restore.progress"
                    class="mg-bottom-md"
                  />
                </cv-tile>
              </cv-column>
            </cv-row>
          </template>
          <template v-if="restore.step == 'apps'">
            <cv-row>
              <cv-column>
                <NsInlineNotification
                  v-if="error.listCoreModules"
                  kind="error"
                  :title="$t('action.list-core-modules')"
                  :description="error.listCoreModules"
                  :showCloseButton="false"
                />
                <NsInlineNotification
                  v-if="!additionalVolumes"
                  kind="info"
                  :title="$t('init.select_apps_to_restore')"
                  :description="$t('init.select_apps_to_restore_description')"
                  :showCloseButton="false"
                />
                <NsInlineNotification
                  v-else
                  kind="info"
                  :title="$t('init.only_core_applications_can_be_restored')"
                  :description="
                    $t('init.other_applications_can_be_restored_later')
                  "
                  :showCloseButton="false"
                />
                <cv-tile light>
                  <cv-form @submit.prevent>
                    <RestoreMultipleInstancesSelector
                      v-if="!loading.listCoreModules"
                      :instances="restore.instances"
                      selection="all"
                      :coreApps="coreApps"
                      :loading="loading.retrieveClusterBackup"
                      :additionalVolumes="additionalVolumes"
                      @select="onSelectInstances"
                      :light="false"
                    />
                    <cv-skeleton-text
                      v-else
                      :paragraph="true"
                      :line-count="5"
                    />
                    <NsInlineNotification
                      v-if="error.restoreModules"
                      kind="error"
                      :title="$t('action.restore-modules')"
                      :description="error.restoreModules"
                      :showCloseButton="false"
                    />
                    <cv-button-set class="footer-buttons">
                      <NsButton
                        type="button"
                        kind="secondary"
                        :icon="ChevronRight20"
                        size="lg"
                        @click="showSkipRestoreAppsModal"
                        :disabled="loading.restoreModules"
                        >{{ $t("common.skip") }}
                      </NsButton>
                      <NsButton
                        kind="primary"
                        :loading="loading.restoreModules"
                        :disabled="
                          loading.restoreModules ||
                          !restore.selectedInstances.length
                        "
                        :icon="Reset20"
                        size="lg"
                        type="button"
                        @click.prevent="restoreModules"
                      >
                        {{
                          $tc(
                            "init.restore_num_apps",
                            restore.selectedInstances.length,
                            { num: restore.selectedInstances.length }
                          )
                        }}
                      </NsButton>
                    </cv-button-set>
                  </cv-form>
                </cv-tile>
              </cv-column>
            </cv-row>
          </template>
          <template v-if="restore.step == 'restoringApps'">
            <NsInlineNotification
              v-if="error.restoreModules"
              kind="error"
              :title="$t('action.restore-modules')"
              :description="error.restoreModules"
              :showCloseButton="false"
              @click="goToLogs"
              :actionLabel="
                $t('common.go_to_page', { page: $t('system_logs.title') })
              "
            />
            <cv-row v-if="!error.restoreModules">
              <cv-column>
                <cv-tile light>
                  <NsEmptyState
                    :title="$t('init.restoring_applications')"
                    :animationData="GearsLottie"
                    animationTitle="gears"
                    :loop="true"
                  >
                  </NsEmptyState>
                  <NsProgressBar
                    :value="restore.progress"
                    :indeterminate="!restore.progress"
                    class="mg-bottom-md"
                  />
                </cv-tile>
              </cv-column>
            </cv-row>
          </template>
        </template>
      </template>
      <template v-else-if="q.page === 'redirect'">
        <cv-row>
          <cv-column class="welcome">
            <h2>{{ $t("init.redirect_cluster") }}</h2>
            <WelcomeLogo />
          </cv-column>
        </cv-row>
        <cv-tile light>
          <cv-row>
            <cv-column>
              <div>
                {{ $t("init.redirect_cluster_description") }}
              </div>
            </cv-column>
          </cv-row>
          <cv-row class="mg-top-xlg">
            <cv-column>
              <a
                :href="this.joinEndpoint + '/cluster-admin/'"
                class="external-link-button"
              >
                <NsButton kind="primary" :icon="ArrowRight20">
                  {{ $t("init.redirect_cluster_link") }}
                </NsButton>
              </a>
            </cv-column>
          </cv-row>
        </cv-tile>
      </template>
    </cv-grid>
    <SkipRestoreAppsModal
      :isShown="restore.isShownSkipRestoreAppsModal"
      @hide="hideSkipRestoreAppsModal"
      @confirm="skipRestoreApps"
    />
  </div>
</template>
⋮----
<template v-if="q.page === 'welcome'">
        <cv-row>
          <cv-column class="welcome">
            <h2>
              {{
                $t("init.welcome", { product: this.$root.config.PRODUCT_NAME })
              }}
            </h2>
            <WelcomeLogo />
          </cv-column>
        </cv-row>
        <cv-row>
          <cv-column>
            <cv-tile light>
              <cv-grid fullWidth class="mg-top-xlg">
                <NsInlineNotification
                  v-if="error.listMountPoints"
                  kind="error"
                  :title="$t('action.list-mountpoints')"
                  :description="error.listMountPoints"
                  :showCloseButton="false"
                />
                <template v-if="!loading.listMountPoints">
                  <cv-row>
                    <cv-column>
                      <NsTile
                        kind="clickable"
                        :icon="EdgeCluster32"
                        @click="selectCreateCluster"
                        large
                      >
                        <h6 class="mg-bottom-sm">
                          {{ $t("init.create_cluster") }}
                        </h6>
                        <div class="tile-description">
                          {{ $t("init.create_cluster_description") }}
                        </div>
                      </NsTile>
                    </cv-column>
                    <cv-column>
                      <NsTile
                        kind="clickable"
                        :icon="Connect32"
                        @click="selectJoinCluster"
                        large
                      >
                        <h6 class="mg-bottom-sm">
                          {{ $t("init.join_cluster") }}
                        </h6>
                        <div class="tile-description">
                          {{ $t("init.join_cluster_description") }}
                        </div>
                      </NsTile>
                    </cv-column>
                    <cv-column>
                      <NsTile
                        kind="clickable"
                        :icon="Reset32"
                        @click="selectRestoreCluster"
                        large
                      >
                        <h6 class="mg-bottom-sm">
                          {{ $t("init.restore_cluster") }}
                        </h6>
                        <div class="tile-description">
                          {{ $t("init.restore_cluster_description") }}
                        </div>
                      </NsTile>
                    </cv-column>
                  </cv-row>
                </template>
                <cv-skeleton-text v-else :paragraph="true" :line-count="5" />
              </cv-grid>
            </cv-tile>
          </cv-column>
        </cv-row>
      </template>
⋮----
{{
                $t("init.welcome", { product: this.$root.config.PRODUCT_NAME })
              }}
⋮----
<template v-if="!loading.listMountPoints">
                  <cv-row>
                    <cv-column>
                      <NsTile
                        kind="clickable"
                        :icon="EdgeCluster32"
                        @click="selectCreateCluster"
                        large
                      >
                        <h6 class="mg-bottom-sm">
                          {{ $t("init.create_cluster") }}
                        </h6>
                        <div class="tile-description">
                          {{ $t("init.create_cluster_description") }}
                        </div>
                      </NsTile>
                    </cv-column>
                    <cv-column>
                      <NsTile
                        kind="clickable"
                        :icon="Connect32"
                        @click="selectJoinCluster"
                        large
                      >
                        <h6 class="mg-bottom-sm">
                          {{ $t("init.join_cluster") }}
                        </h6>
                        <div class="tile-description">
                          {{ $t("init.join_cluster_description") }}
                        </div>
                      </NsTile>
                    </cv-column>
                    <cv-column>
                      <NsTile
                        kind="clickable"
                        :icon="Reset32"
                        @click="selectRestoreCluster"
                        large
                      >
                        <h6 class="mg-bottom-sm">
                          {{ $t("init.restore_cluster") }}
                        </h6>
                        <div class="tile-description">
                          {{ $t("init.restore_cluster_description") }}
                        </div>
                      </NsTile>
                    </cv-column>
                  </cv-row>
                </template>
⋮----
{{ $t("init.create_cluster") }}
⋮----
{{ $t("init.create_cluster_description") }}
⋮----
{{ $t("init.join_cluster") }}
⋮----
{{ $t("init.join_cluster_description") }}
⋮----
{{ $t("init.restore_cluster") }}
⋮----
{{ $t("init.restore_cluster_description") }}
⋮----
<template v-else-if="q.page === 'fqdn'">
        <template
          v-if="isPasswordChangeNeeded && $route.query.action === 'create'"
        >
          <cv-row>
            <cv-column class="welcome">
              <div>
                <h2>{{ $t("init.create_cluster") }}</h2>
                <div class="title-description">
                  {{ $t("init.create_cluster_description") }}
                </div>
              </div>
              <WelcomeLogo />
            </cv-column>
          </cv-row>
          <cv-row>
            <cv-column>
              <NsInlineNotification
                kind="info"
                :title="$t('init.change_admin_password')"
                :description="$t('init.change_admin_password_description')"
                :showCloseButton="false"
              />
            </cv-column>
          </cv-row>
          <cv-row>
            <cv-column>
              <cv-tile light>
                <cv-form @submit.prevent="changePassword">
                  <cv-text-input
                    :label="$t('init.current_password')"
                    v-model="currentPassword"
                    :invalid-message="$t(error.currentPassword)"
                    type="password"
                    ref="currentPassword"
                  >
                  </cv-text-input>
                  <NsPasswordInput
                    :newPasswordLabel="$t('init.new_password')"
                    :confirmPasswordLabel="$t('init.new_password_confirm')"
                    v-model="newPassword"
                    @passwordValidation="onPasswordValidation"
                    :newPasswordInvalidMessage="$t(error.newPassword)"
                    :confirmPasswordInvalidMessage="$t(error.confirmPassword)"
                    :passwordHideLabel="$t('password.hide_password')"
                    :passwordShowLabel="$t('password.show_password')"
                    :lengthLabel="$t('password.long_enough')"
                    :lowercaseLabel="$t('password.lowercase_letter')"
                    :uppercaseLabel="$t('password.uppercase_letter')"
                    :numberLabel="$t('password.number')"
                    :symbolLabel="$t('password.symbol')"
                    :equalLabel="$t('password.equal')"
                    :focus="focusPasswordField"
                  />
                  <cv-button-set class="footer-buttons">
                    <NsButton
                      type="button"
                      kind="secondary"
                      :icon="ChevronLeft20"
                      size="lg"
                      @click="goToWelcomePage"
                      >{{ $t("common.go_back") }}
                    </NsButton>
                    <NsButton
                      kind="primary"
                      :loading="isChangingPassword"
                      :disabled="isChangingPassword"
                      :icon="Password20"
                      size="lg"
                      >{{ $t("init.change_password") }}
                    </NsButton>
                  </cv-button-set>
                </cv-form>
              </cv-tile>
            </cv-column>
          </cv-row>
        </template>
        <template v-else>
          <SetFqdn
            :action="$route.query.action"
            @goBack="goToWelcomePage"
            @fqdnSet="onFqdnSet"
          />
        </template>
      </template>
⋮----
<template
          v-if="isPasswordChangeNeeded && $route.query.action === 'create'"
        >
          <cv-row>
            <cv-column class="welcome">
              <div>
                <h2>{{ $t("init.create_cluster") }}</h2>
                <div class="title-description">
                  {{ $t("init.create_cluster_description") }}
                </div>
              </div>
              <WelcomeLogo />
            </cv-column>
          </cv-row>
          <cv-row>
            <cv-column>
              <NsInlineNotification
                kind="info"
                :title="$t('init.change_admin_password')"
                :description="$t('init.change_admin_password_description')"
                :showCloseButton="false"
              />
            </cv-column>
          </cv-row>
          <cv-row>
            <cv-column>
              <cv-tile light>
                <cv-form @submit.prevent="changePassword">
                  <cv-text-input
                    :label="$t('init.current_password')"
                    v-model="currentPassword"
                    :invalid-message="$t(error.currentPassword)"
                    type="password"
                    ref="currentPassword"
                  >
                  </cv-text-input>
                  <NsPasswordInput
                    :newPasswordLabel="$t('init.new_password')"
                    :confirmPasswordLabel="$t('init.new_password_confirm')"
                    v-model="newPassword"
                    @passwordValidation="onPasswordValidation"
                    :newPasswordInvalidMessage="$t(error.newPassword)"
                    :confirmPasswordInvalidMessage="$t(error.confirmPassword)"
                    :passwordHideLabel="$t('password.hide_password')"
                    :passwordShowLabel="$t('password.show_password')"
                    :lengthLabel="$t('password.long_enough')"
                    :lowercaseLabel="$t('password.lowercase_letter')"
                    :uppercaseLabel="$t('password.uppercase_letter')"
                    :numberLabel="$t('password.number')"
                    :symbolLabel="$t('password.symbol')"
                    :equalLabel="$t('password.equal')"
                    :focus="focusPasswordField"
                  />
                  <cv-button-set class="footer-buttons">
                    <NsButton
                      type="button"
                      kind="secondary"
                      :icon="ChevronLeft20"
                      size="lg"
                      @click="goToWelcomePage"
                      >{{ $t("common.go_back") }}
                    </NsButton>
                    <NsButton
                      kind="primary"
                      :loading="isChangingPassword"
                      :disabled="isChangingPassword"
                      :icon="Password20"
                      size="lg"
                      >{{ $t("init.change_password") }}
                    </NsButton>
                  </cv-button-set>
                </cv-form>
              </cv-tile>
            </cv-column>
          </cv-row>
        </template>
⋮----
<h2>{{ $t("init.create_cluster") }}</h2>
⋮----
{{ $t("init.create_cluster_description") }}
⋮----
>{{ $t("common.go_back") }}
⋮----
>{{ $t("init.change_password") }}
⋮----
<template v-else>
          <SetFqdn
            :action="$route.query.action"
            @goBack="goToWelcomePage"
            @fqdnSet="onFqdnSet"
          />
        </template>
⋮----
<template v-else-if="q.page === 'create'">
        <template>
          <cv-row>
            <cv-column class="welcome">
              <div>
                <h2>{{ $t("init.create_cluster") }}</h2>
                <div class="title-description">
                  {{ $t("init.create_cluster_description") }}
                </div>
              </div>
              <WelcomeLogo />
            </cv-column>
          </cv-row>
          <cv-row v-if="error.networkCheckCreateCluster">
            <cv-column>
              <NsInlineNotification
                kind="error"
                :title="$t('action.create-cluster')"
                :description="error.networkCheckCreateCluster"
                :showCloseButton="false"
              />
            </cv-column>
          </cv-row>
          <cv-row v-if="!isCreatingCluster">
            <cv-column>
              <NsInlineNotification
                kind="info"
                :title="$t('init.vpn_network')"
                :description="$t('init.vpn_cidr_tooltip')"
                :showCloseButton="false"
              />
            </cv-column>
          </cv-row>
          <cv-row>
            <cv-column>
              <cv-tile light>
                <template v-if="!isCreatingCluster">
                  <NsInlineNotification
                    v-if="error.getDefaults"
                    kind="error"
                    :title="$t('action.get-defaults')"
                    :description="error.getFqdn"
                    :showCloseButton="false"
                  />
                  <cv-form v-else @submit.prevent="createCluster">
                    <cv-skeleton-text
                      v-if="loading.getDefaults"
                      :paragraph="true"
                      :line-count="3"
                      heading
                    ></cv-skeleton-text>
                    <template v-else>
                      <NsTextInput
                        :label="$t('init.vpn_cidr')"
                        v-model.trim="network"
                        :invalid-message="$t(error.network)"
                        :disabled="loading.getDefaults || isCreatingCluster"
                        tooltipAlignment="end"
                        tooltipDirection="right"
                        class="narrow"
                        ref="network"
                      />
                    </template>
                    <cv-button-set class="footer-buttons">
                      <NsButton
                        type="button"
                        kind="secondary"
                        :icon="ChevronLeft20"
                        size="lg"
                        @click="goToFqdnPage"
                        >{{ $t("common.go_back") }}
                      </NsButton>
                      <NsButton
                        kind="primary"
                        :loading="isCreatingCluster"
                        :disabled="loading.getDefaults || isCreatingCluster"
                        :icon="EdgeCluster20"
                        size="lg"
                        >{{ $t("init.create_cluster") }}
                      </NsButton>
                    </cv-button-set>
                  </cv-form>
                </template>
                <template v-else>
                  <NsInlineNotification
                    v-if="error.createCluster"
                    kind="error"
                    :title="$t('action.create-cluster')"
                    :description="error.createCluster"
                    :showCloseButton="false"
                  />
                  <NsEmptyState
                    :title="$t('init.creating_cluster')"
                    :animationData="GearsLottie"
                    animationTitle="gears"
                    :loop="true"
                  />
                  <NsProgressBar
                    :value="createClusterProgress"
                    :indeterminate="!createClusterProgress"
                    class="mg-bottom-xlg"
                  />
                </template>
              </cv-tile>
            </cv-column>
          </cv-row>
        </template>
      </template>
⋮----
<template>
          <cv-row>
            <cv-column class="welcome">
              <div>
                <h2>{{ $t("init.create_cluster") }}</h2>
                <div class="title-description">
                  {{ $t("init.create_cluster_description") }}
                </div>
              </div>
              <WelcomeLogo />
            </cv-column>
          </cv-row>
          <cv-row v-if="error.networkCheckCreateCluster">
            <cv-column>
              <NsInlineNotification
                kind="error"
                :title="$t('action.create-cluster')"
                :description="error.networkCheckCreateCluster"
                :showCloseButton="false"
              />
            </cv-column>
          </cv-row>
          <cv-row v-if="!isCreatingCluster">
            <cv-column>
              <NsInlineNotification
                kind="info"
                :title="$t('init.vpn_network')"
                :description="$t('init.vpn_cidr_tooltip')"
                :showCloseButton="false"
              />
            </cv-column>
          </cv-row>
          <cv-row>
            <cv-column>
              <cv-tile light>
                <template v-if="!isCreatingCluster">
                  <NsInlineNotification
                    v-if="error.getDefaults"
                    kind="error"
                    :title="$t('action.get-defaults')"
                    :description="error.getFqdn"
                    :showCloseButton="false"
                  />
                  <cv-form v-else @submit.prevent="createCluster">
                    <cv-skeleton-text
                      v-if="loading.getDefaults"
                      :paragraph="true"
                      :line-count="3"
                      heading
                    ></cv-skeleton-text>
                    <template v-else>
                      <NsTextInput
                        :label="$t('init.vpn_cidr')"
                        v-model.trim="network"
                        :invalid-message="$t(error.network)"
                        :disabled="loading.getDefaults || isCreatingCluster"
                        tooltipAlignment="end"
                        tooltipDirection="right"
                        class="narrow"
                        ref="network"
                      />
                    </template>
                    <cv-button-set class="footer-buttons">
                      <NsButton
                        type="button"
                        kind="secondary"
                        :icon="ChevronLeft20"
                        size="lg"
                        @click="goToFqdnPage"
                        >{{ $t("common.go_back") }}
                      </NsButton>
                      <NsButton
                        kind="primary"
                        :loading="isCreatingCluster"
                        :disabled="loading.getDefaults || isCreatingCluster"
                        :icon="EdgeCluster20"
                        size="lg"
                        >{{ $t("init.create_cluster") }}
                      </NsButton>
                    </cv-button-set>
                  </cv-form>
                </template>
                <template v-else>
                  <NsInlineNotification
                    v-if="error.createCluster"
                    kind="error"
                    :title="$t('action.create-cluster')"
                    :description="error.createCluster"
                    :showCloseButton="false"
                  />
                  <NsEmptyState
                    :title="$t('init.creating_cluster')"
                    :animationData="GearsLottie"
                    animationTitle="gears"
                    :loop="true"
                  />
                  <NsProgressBar
                    :value="createClusterProgress"
                    :indeterminate="!createClusterProgress"
                    class="mg-bottom-xlg"
                  />
                </template>
              </cv-tile>
            </cv-column>
          </cv-row>
        </template>
⋮----
<h2>{{ $t("init.create_cluster") }}</h2>
⋮----
{{ $t("init.create_cluster_description") }}
⋮----
<template v-if="!isCreatingCluster">
                  <NsInlineNotification
                    v-if="error.getDefaults"
                    kind="error"
                    :title="$t('action.get-defaults')"
                    :description="error.getFqdn"
                    :showCloseButton="false"
                  />
                  <cv-form v-else @submit.prevent="createCluster">
                    <cv-skeleton-text
                      v-if="loading.getDefaults"
                      :paragraph="true"
                      :line-count="3"
                      heading
                    ></cv-skeleton-text>
                    <template v-else>
                      <NsTextInput
                        :label="$t('init.vpn_cidr')"
                        v-model.trim="network"
                        :invalid-message="$t(error.network)"
                        :disabled="loading.getDefaults || isCreatingCluster"
                        tooltipAlignment="end"
                        tooltipDirection="right"
                        class="narrow"
                        ref="network"
                      />
                    </template>
                    <cv-button-set class="footer-buttons">
                      <NsButton
                        type="button"
                        kind="secondary"
                        :icon="ChevronLeft20"
                        size="lg"
                        @click="goToFqdnPage"
                        >{{ $t("common.go_back") }}
                      </NsButton>
                      <NsButton
                        kind="primary"
                        :loading="isCreatingCluster"
                        :disabled="loading.getDefaults || isCreatingCluster"
                        :icon="EdgeCluster20"
                        size="lg"
                        >{{ $t("init.create_cluster") }}
                      </NsButton>
                    </cv-button-set>
                  </cv-form>
                </template>
⋮----
<template v-else>
                      <NsTextInput
                        :label="$t('init.vpn_cidr')"
                        v-model.trim="network"
                        :invalid-message="$t(error.network)"
                        :disabled="loading.getDefaults || isCreatingCluster"
                        tooltipAlignment="end"
                        tooltipDirection="right"
                        class="narrow"
                        ref="network"
                      />
                    </template>
⋮----
>{{ $t("common.go_back") }}
⋮----
>{{ $t("init.create_cluster") }}
⋮----
<template v-else>
                  <NsInlineNotification
                    v-if="error.createCluster"
                    kind="error"
                    :title="$t('action.create-cluster')"
                    :description="error.createCluster"
                    :showCloseButton="false"
                  />
                  <NsEmptyState
                    :title="$t('init.creating_cluster')"
                    :animationData="GearsLottie"
                    animationTitle="gears"
                    :loop="true"
                  />
                  <NsProgressBar
                    :value="createClusterProgress"
                    :indeterminate="!createClusterProgress"
                    class="mg-bottom-xlg"
                  />
                </template>
⋮----
<template v-else-if="q.page === 'join'">
        <cv-row>
          <cv-column class="welcome">
            <div>
              <h2>{{ $t("init.join_cluster") }}</h2>
              <div class="title-description">
                {{ $t("init.join_cluster_description") }}
              </div>
            </div>
            <WelcomeLogo />
          </cv-column>
        </cv-row>
        <cv-row>
          <cv-column>
            <cv-tile light>
              <cv-form @submit.prevent="joinCluster">
                <cv-text-area
                  :label="$t('common.join_code')"
                  v-model.trim="joinCode"
                  :invalid-message="$t(error.joinCode)"
                  :helper-text="
                    $t('init.join_code_helper_text') +
                    ' https://LEADER_NODE_IP/cluster-admin/#/nodes?isShownAddNodeModal=true'
                  "
                  class="join-code"
                  ref="joinCode"
                >
                </cv-text-area>
                <cv-checkbox
                  :label="$t('init.tls_verify')"
                  v-model="tlsVerify"
                  value="checkTlsVerify"
                />
                <cv-button-set class="footer-buttons">
                  <NsButton
                    type="button"
                    kind="secondary"
                    :icon="ChevronLeft20"
                    size="lg"
                    @click="goToFqdnPage"
                    >{{ $t("common.go_back") }}
                  </NsButton>
                  <NsButton
                    kind="primary"
                    :loading="isJoiningCluster"
                    :disabled="isJoiningCluster"
                    :icon="Connect20"
                    size="lg"
                    >{{ $t("init.join_cluster") }}
                  </NsButton>
                </cv-button-set>
              </cv-form>
            </cv-tile>
          </cv-column>
        </cv-row>
      </template>
⋮----
<h2>{{ $t("init.join_cluster") }}</h2>
⋮----
{{ $t("init.join_cluster_description") }}
⋮----
>{{ $t("common.go_back") }}
⋮----
>{{ $t("init.join_cluster") }}
⋮----
<template v-else-if="q.page === 'restore'">
        <template v-if="isPasswordChangeNeeded">
          <cv-row>
            <cv-column class="welcome">
              <div>
                <h2>{{ $t("init.restore_cluster") }}</h2>
                <div class="title-description">
                  {{ $t("init.restore_cluster_description") }}
                </div>
              </div>
              <WelcomeLogo />
            </cv-column>
          </cv-row>
          <cv-row>
            <cv-column>
              <NsInlineNotification
                kind="info"
                :title="$t('init.change_admin_password')"
                :description="$t('init.change_admin_password_description')"
                :showCloseButton="false"
              />
            </cv-column>
          </cv-row>
          <cv-row>
            <cv-column>
              <cv-tile light>
                <cv-form @submit.prevent="changePassword">
                  <cv-text-input
                    :label="$t('init.current_password')"
                    v-model="currentPassword"
                    :invalid-message="$t(error.currentPassword)"
                    type="password"
                    ref="currentPassword"
                  >
                  </cv-text-input>
                  <NsPasswordInput
                    :newPasswordLabel="$t('init.new_password')"
                    :confirmPasswordLabel="$t('init.new_password_confirm')"
                    v-model="newPassword"
                    @passwordValidation="onPasswordValidation"
                    :newPasswordInvalidMessage="$t(error.newPassword)"
                    :confirmPasswordInvalidMessage="$t(error.confirmPassword)"
                    :passwordHideLabel="$t('password.hide_password')"
                    :passwordShowLabel="$t('password.show_password')"
                    :lengthLabel="$t('password.long_enough')"
                    :lowercaseLabel="$t('password.lowercase_letter')"
                    :uppercaseLabel="$t('password.uppercase_letter')"
                    :numberLabel="$t('password.number')"
                    :symbolLabel="$t('password.symbol')"
                    :equalLabel="$t('password.equal')"
                    :focus="focusPasswordField"
                  />
                  <cv-button-set class="footer-buttons">
                    <NsButton
                      type="button"
                      kind="secondary"
                      :icon="ChevronLeft20"
                      size="lg"
                      @click="goToWelcomePage"
                      >{{ $t("common.go_back") }}
                    </NsButton>
                    <NsButton
                      kind="primary"
                      :loading="isChangingPassword"
                      :disabled="isChangingPassword"
                      :icon="Password20"
                      size="lg"
                      >{{ $t("init.change_password") }}
                    </NsButton>
                  </cv-button-set>
                </cv-form>
              </cv-tile>
            </cv-column>
          </cv-row>
        </template>
        <template v-else>
          <cv-row>
            <cv-column class="welcome">
              <div>
                <h2>{{ $t("init.restore_cluster") }}</h2>
                <div class="title-description">
                  {{ $t("init.restore_cluster_description") }}
                </div>
              </div>
              <WelcomeLogo />
            </cv-column>
          </cv-row>
          <template v-if="restore.step == 'type'">
            <cv-row>
              <cv-column>
                <cv-tile light>
                  <cv-grid fullWidth class="mg-top-xlg no-padding">
                    <cv-row>
                      <cv-column :md="4">
                        <NsTile
                          kind="clickable"
                          :icon="Link32"
                          @click="goToRestoreFromUrl"
                          large
                        >
                          <h6>
                            {{ $t("init.restore_from_remote_url") }}
                          </h6>
                        </NsTile>
                      </cv-column>
                      <cv-column :md="4">
                        <NsTile
                          kind="clickable"
                          :icon="Document32"
                          @click="goToRestoreFromFile"
                          large
                        >
                          <h6>
                            {{ $t("init.restore_from_cluster_backup_file") }}
                          </h6>
                        </NsTile>
                      </cv-column>
                    </cv-row>
                  </cv-grid>
                  <cv-button-set class="footer-buttons">
                    <NsButton
                      type="button"
                      kind="secondary"
                      :icon="ChevronLeft20"
                      size="lg"
                      @click="goToWelcomePage"
                      >{{ $t("common.go_back") }}
                    </NsButton>
                  </cv-button-set>
                </cv-tile>
              </cv-column>
            </cv-row>
          </template>
          <template v-else-if="restore.step == 'url'">
            <cv-row>
              <cv-column>
                <cv-tile light>
                  <h5 class="mg-bottom-md">
                    {{ $t("init.restore_from_remote_url") }}
                  </h5>
                  <cv-form @submit.prevent="retrieveClusterBackupFromUrl">
                    <NsTextInput
                      v-model.trim="restore.url"
                      :label="$t('init.remote_url')"
                      placeholder="https://myserver/cluster-backup.json.gz.gpg"
                      :invalid-message="error.restore.url"
                      :disabled="loading.retrieveClusterBackup"
                      class="mg-bottom-sm"
                      ref="url"
                    />
                    <cv-checkbox
                      :label="$t('init.tls_verify')"
                      v-model="restore.tlsVerify"
                      value="checkTlsVerify"
                    />
                    <NsTextInput
                      type="password"
                      :password-hide-label="$t('password.hide_password')"
                      :password-show-label="$t('password.show_password')"
                      v-model="restore.backupPassword"
                      :label="$t('init.backup_password')"
                      :invalid-message="error.restore.backup_password"
                      :disabled="loading.retrieveClusterBackup"
                      tooltipAlignment="center"
                      tooltipDirection="right"
                      ref="backup_password"
                      class="mg-top-md"
                    >
                      <template #tooltip>
                        <span>{{ $t("init.backup_password_tooltip") }}</span>
                      </template>
                    </NsTextInput>
                    <cv-button-set class="footer-buttons">
                      <NsButton
                        type="button"
                        kind="secondary"
                        :icon="ChevronLeft20"
                        size="lg"
                        @click="goToRestoreType"
                        >{{ $t("common.go_back") }}
                      </NsButton>
                      <NsButton
                        kind="primary"
                        :loading="loading.retrieveClusterBackup"
                        :disabled="loading.retrieveClusterBackup"
                        :icon="ChevronRight20"
                        size="lg"
                        >{{ $t("common.next") }}
                      </NsButton>
                    </cv-button-set>
                  </cv-form>
                </cv-tile>
              </cv-column>
            </cv-row>
          </template>
          <template v-else-if="restore.step == 'file'">
            <cv-row>
              <cv-column>
                <cv-tile light>
                  <h5 class="mg-bottom-md">
                    {{ $t("init.restore_from_cluster_backup_file") }}
                  </h5>
                  <cv-form @submit.prevent="retrieveClusterBackupFromFile">
                    <div>
                      {{ $t("init.upload_cluster_backup_file") }}
                    </div>
                    <cv-file-uploader
                      :drop-target-label="$t('common.upload_drop_target_text')"
                      accept=".json.gz.gpg,.bin,.gpg"
                      :clear-on-reselect="true"
                      :multiple="false"
                      :removable="true"
                      :remove-aria-label="$t('common.remove')"
                      v-model="restore.filesUploaded"
                      @change="onFileUpload"
                      :class="[
                        'file-uploader',
                        { 'validation-failed': error.restore.backup_file },
                      ]"
                      ref="backup_file"
                    >
                    </cv-file-uploader>
                    <div
                      v-if="error.restore.backup_file"
                      class="validation-failed-invalid-message"
                    >
                      {{ error.restore.backup_file }}
                    </div>
                    <NsTextInput
                      type="password"
                      :password-hide-label="$t('password.hide_password')"
                      :password-show-label="$t('password.show_password')"
                      v-model="restore.backupPassword"
                      :label="$t('init.backup_password')"
                      :invalid-message="error.restore.backup_password"
                      :disabled="loading.retrieveClusterBackup"
                      tooltipAlignment="center"
                      tooltipDirection="right"
                      ref="backup_password"
                      class="mg-top-md"
                    >
                      <template #tooltip>
                        <span>{{ $t("init.backup_password_tooltip") }}</span>
                      </template>
                    </NsTextInput>
                    <NsInlineNotification
                      v-if="error.retrieveClusterBackup"
                      kind="error"
                      :title="$t('action.retrieve-cluster-backup')"
                      :description="error.retrieveClusterBackup"
                      :showCloseButton="false"
                    />
                    <cv-button-set class="footer-buttons">
                      <NsButton
                        type="button"
                        kind="secondary"
                        :icon="ChevronLeft20"
                        size="lg"
                        @click="goToRestoreType"
                        >{{ $t("common.go_back") }}
                      </NsButton>
                      <NsButton
                        kind="primary"
                        :loading="loading.retrieveClusterBackup"
                        :disabled="loading.retrieveClusterBackup"
                        :icon="ChevronRight20"
                        size="lg"
                        >{{ $t("common.next") }}
                      </NsButton>
                    </cv-button-set>
                  </cv-form>
                </cv-tile>
              </cv-column>
            </cv-row>
          </template>
          <template v-else-if="restore.step == 'summary'">
            <cv-row>
              <cv-column>
                <cv-tile light>
                  <h5 class="mg-bottom-md">
                    {{ $t("init.restore_summary") }}
                  </h5>
                  <cv-form @submit.prevent="restoreCluster">
                    <div
                      v-if="restore.summary.cluster"
                      class="key-value-setting"
                    >
                      <span class="label">{{ $t("init.cluster_label") }}</span>
                      <span class="value">{{ restore.summary.cluster }}</span>
                    </div>
                    <div class="key-value-setting">
                      <span class="label">{{ $t("init.vpn_endpoint") }}</span>
                      <span class="value">{{ restore.summary.vpn }}</span>
                    </div>
                    <div class="key-value-setting">
                      <span class="label">{{
                        $t("init.external_domains")
                      }}</span>
                      <span class="value">{{ restore.summary.domains }}</span>
                    </div>
                    <div class="key-value-setting">
                      <span class="label">{{
                        $t("init.backup_repositories")
                      }}</span>
                      <span class="value">{{
                        restore.summary.backup_repositories
                      }}</span>
                    </div>
                    <NsInlineNotification
                      kind="info"
                      :title="$t('init.apps_restoration')"
                      :description="
                        restore.summary.single_node_cluster
                          ? $t('init.apps_restoration_single_node_description')
                          : $t('init.apps_restoration_multi_node_description')
                      "
                      :showCloseButton="false"
                      class="mg-top-lg"
                    />
                    <NsInlineNotification
                      v-if="error.restoreCluster"
                      kind="error"
                      :title="$t('action.restore-cluster')"
                      :description="error.restoreCluster"
                      :showCloseButton="false"
                    />
                    <cv-button-set class="footer-buttons">
                      <NsButton
                        type="button"
                        kind="secondary"
                        :icon="ChevronLeft20"
                        size="lg"
                        @click="goToRestoreFromFileOrUrl"
                        >{{ $t("common.go_back") }}
                      </NsButton>
                      <NsButton
                        kind="primary"
                        :loading="loading.restoreCluster"
                        :disabled="loading.restoreCluster"
                        :icon="Reset20"
                        size="lg"
                        >{{ $t("init.restore_cluster") }}
                      </NsButton>
                    </cv-button-set>
                  </cv-form>
                </cv-tile>
              </cv-column>
            </cv-row>
          </template>
          <template v-if="restore.step == 'restoringCluster'">
            <NsInlineNotification
              v-if="error.restoreCluster"
              kind="error"
              :title="$t('action.restore-cluster')"
              :description="error.restoreCluster"
              :showCloseButton="false"
            />
            <NsInlineNotification
              v-if="error.readBackupRepositories"
              kind="error"
              :title="$t('action.read-backup-repositories')"
              :description="error.readBackupRepositories"
              :showCloseButton="false"
            />
            <cv-row
              v-if="!error.restoreCluster && !error.readBackupRepositories"
            >
              <cv-column>
                <cv-tile light>
                  <NsEmptyState
                    :title="$t('init.restoring_cluster')"
                    :animationData="GearsLottie"
                    animationTitle="gears"
                    :loop="true"
                  >
                    <template #description>
                      <span v-if="restore.progress < 100">
                        {{ $t("init.traveling_back_in_time") }}
                      </span>
                      <span v-else-if="loading.readBackupRepositories">
                        {{ $t("init.reading_backup_repositories") }}
                      </span>
                      <span v-else>&nbsp;</span>
                    </template>
                  </NsEmptyState>
                  <NsProgressBar
                    :value="restore.progress"
                    :indeterminate="!restore.progress"
                    class="mg-bottom-md"
                  />
                </cv-tile>
              </cv-column>
            </cv-row>
          </template>
          <template v-if="restore.step == 'apps'">
            <cv-row>
              <cv-column>
                <NsInlineNotification
                  v-if="error.listCoreModules"
                  kind="error"
                  :title="$t('action.list-core-modules')"
                  :description="error.listCoreModules"
                  :showCloseButton="false"
                />
                <NsInlineNotification
                  v-if="!additionalVolumes"
                  kind="info"
                  :title="$t('init.select_apps_to_restore')"
                  :description="$t('init.select_apps_to_restore_description')"
                  :showCloseButton="false"
                />
                <NsInlineNotification
                  v-else
                  kind="info"
                  :title="$t('init.only_core_applications_can_be_restored')"
                  :description="
                    $t('init.other_applications_can_be_restored_later')
                  "
                  :showCloseButton="false"
                />
                <cv-tile light>
                  <cv-form @submit.prevent>
                    <RestoreMultipleInstancesSelector
                      v-if="!loading.listCoreModules"
                      :instances="restore.instances"
                      selection="all"
                      :coreApps="coreApps"
                      :loading="loading.retrieveClusterBackup"
                      :additionalVolumes="additionalVolumes"
                      @select="onSelectInstances"
                      :light="false"
                    />
                    <cv-skeleton-text
                      v-else
                      :paragraph="true"
                      :line-count="5"
                    />
                    <NsInlineNotification
                      v-if="error.restoreModules"
                      kind="error"
                      :title="$t('action.restore-modules')"
                      :description="error.restoreModules"
                      :showCloseButton="false"
                    />
                    <cv-button-set class="footer-buttons">
                      <NsButton
                        type="button"
                        kind="secondary"
                        :icon="ChevronRight20"
                        size="lg"
                        @click="showSkipRestoreAppsModal"
                        :disabled="loading.restoreModules"
                        >{{ $t("common.skip") }}
                      </NsButton>
                      <NsButton
                        kind="primary"
                        :loading="loading.restoreModules"
                        :disabled="
                          loading.restoreModules ||
                          !restore.selectedInstances.length
                        "
                        :icon="Reset20"
                        size="lg"
                        type="button"
                        @click.prevent="restoreModules"
                      >
                        {{
                          $tc(
                            "init.restore_num_apps",
                            restore.selectedInstances.length,
                            { num: restore.selectedInstances.length }
                          )
                        }}
                      </NsButton>
                    </cv-button-set>
                  </cv-form>
                </cv-tile>
              </cv-column>
            </cv-row>
          </template>
          <template v-if="restore.step == 'restoringApps'">
            <NsInlineNotification
              v-if="error.restoreModules"
              kind="error"
              :title="$t('action.restore-modules')"
              :description="error.restoreModules"
              :showCloseButton="false"
              @click="goToLogs"
              :actionLabel="
                $t('common.go_to_page', { page: $t('system_logs.title') })
              "
            />
            <cv-row v-if="!error.restoreModules">
              <cv-column>
                <cv-tile light>
                  <NsEmptyState
                    :title="$t('init.restoring_applications')"
                    :animationData="GearsLottie"
                    animationTitle="gears"
                    :loop="true"
                  >
                  </NsEmptyState>
                  <NsProgressBar
                    :value="restore.progress"
                    :indeterminate="!restore.progress"
                    class="mg-bottom-md"
                  />
                </cv-tile>
              </cv-column>
            </cv-row>
          </template>
        </template>
      </template>
⋮----
<template v-if="isPasswordChangeNeeded">
          <cv-row>
            <cv-column class="welcome">
              <div>
                <h2>{{ $t("init.restore_cluster") }}</h2>
                <div class="title-description">
                  {{ $t("init.restore_cluster_description") }}
                </div>
              </div>
              <WelcomeLogo />
            </cv-column>
          </cv-row>
          <cv-row>
            <cv-column>
              <NsInlineNotification
                kind="info"
                :title="$t('init.change_admin_password')"
                :description="$t('init.change_admin_password_description')"
                :showCloseButton="false"
              />
            </cv-column>
          </cv-row>
          <cv-row>
            <cv-column>
              <cv-tile light>
                <cv-form @submit.prevent="changePassword">
                  <cv-text-input
                    :label="$t('init.current_password')"
                    v-model="currentPassword"
                    :invalid-message="$t(error.currentPassword)"
                    type="password"
                    ref="currentPassword"
                  >
                  </cv-text-input>
                  <NsPasswordInput
                    :newPasswordLabel="$t('init.new_password')"
                    :confirmPasswordLabel="$t('init.new_password_confirm')"
                    v-model="newPassword"
                    @passwordValidation="onPasswordValidation"
                    :newPasswordInvalidMessage="$t(error.newPassword)"
                    :confirmPasswordInvalidMessage="$t(error.confirmPassword)"
                    :passwordHideLabel="$t('password.hide_password')"
                    :passwordShowLabel="$t('password.show_password')"
                    :lengthLabel="$t('password.long_enough')"
                    :lowercaseLabel="$t('password.lowercase_letter')"
                    :uppercaseLabel="$t('password.uppercase_letter')"
                    :numberLabel="$t('password.number')"
                    :symbolLabel="$t('password.symbol')"
                    :equalLabel="$t('password.equal')"
                    :focus="focusPasswordField"
                  />
                  <cv-button-set class="footer-buttons">
                    <NsButton
                      type="button"
                      kind="secondary"
                      :icon="ChevronLeft20"
                      size="lg"
                      @click="goToWelcomePage"
                      >{{ $t("common.go_back") }}
                    </NsButton>
                    <NsButton
                      kind="primary"
                      :loading="isChangingPassword"
                      :disabled="isChangingPassword"
                      :icon="Password20"
                      size="lg"
                      >{{ $t("init.change_password") }}
                    </NsButton>
                  </cv-button-set>
                </cv-form>
              </cv-tile>
            </cv-column>
          </cv-row>
        </template>
⋮----
<h2>{{ $t("init.restore_cluster") }}</h2>
⋮----
{{ $t("init.restore_cluster_description") }}
⋮----
>{{ $t("common.go_back") }}
⋮----
>{{ $t("init.change_password") }}
⋮----
<template v-else>
          <cv-row>
            <cv-column class="welcome">
              <div>
                <h2>{{ $t("init.restore_cluster") }}</h2>
                <div class="title-description">
                  {{ $t("init.restore_cluster_description") }}
                </div>
              </div>
              <WelcomeLogo />
            </cv-column>
          </cv-row>
          <template v-if="restore.step == 'type'">
            <cv-row>
              <cv-column>
                <cv-tile light>
                  <cv-grid fullWidth class="mg-top-xlg no-padding">
                    <cv-row>
                      <cv-column :md="4">
                        <NsTile
                          kind="clickable"
                          :icon="Link32"
                          @click="goToRestoreFromUrl"
                          large
                        >
                          <h6>
                            {{ $t("init.restore_from_remote_url") }}
                          </h6>
                        </NsTile>
                      </cv-column>
                      <cv-column :md="4">
                        <NsTile
                          kind="clickable"
                          :icon="Document32"
                          @click="goToRestoreFromFile"
                          large
                        >
                          <h6>
                            {{ $t("init.restore_from_cluster_backup_file") }}
                          </h6>
                        </NsTile>
                      </cv-column>
                    </cv-row>
                  </cv-grid>
                  <cv-button-set class="footer-buttons">
                    <NsButton
                      type="button"
                      kind="secondary"
                      :icon="ChevronLeft20"
                      size="lg"
                      @click="goToWelcomePage"
                      >{{ $t("common.go_back") }}
                    </NsButton>
                  </cv-button-set>
                </cv-tile>
              </cv-column>
            </cv-row>
          </template>
          <template v-else-if="restore.step == 'url'">
            <cv-row>
              <cv-column>
                <cv-tile light>
                  <h5 class="mg-bottom-md">
                    {{ $t("init.restore_from_remote_url") }}
                  </h5>
                  <cv-form @submit.prevent="retrieveClusterBackupFromUrl">
                    <NsTextInput
                      v-model.trim="restore.url"
                      :label="$t('init.remote_url')"
                      placeholder="https://myserver/cluster-backup.json.gz.gpg"
                      :invalid-message="error.restore.url"
                      :disabled="loading.retrieveClusterBackup"
                      class="mg-bottom-sm"
                      ref="url"
                    />
                    <cv-checkbox
                      :label="$t('init.tls_verify')"
                      v-model="restore.tlsVerify"
                      value="checkTlsVerify"
                    />
                    <NsTextInput
                      type="password"
                      :password-hide-label="$t('password.hide_password')"
                      :password-show-label="$t('password.show_password')"
                      v-model="restore.backupPassword"
                      :label="$t('init.backup_password')"
                      :invalid-message="error.restore.backup_password"
                      :disabled="loading.retrieveClusterBackup"
                      tooltipAlignment="center"
                      tooltipDirection="right"
                      ref="backup_password"
                      class="mg-top-md"
                    >
                      <template #tooltip>
                        <span>{{ $t("init.backup_password_tooltip") }}</span>
                      </template>
                    </NsTextInput>
                    <cv-button-set class="footer-buttons">
                      <NsButton
                        type="button"
                        kind="secondary"
                        :icon="ChevronLeft20"
                        size="lg"
                        @click="goToRestoreType"
                        >{{ $t("common.go_back") }}
                      </NsButton>
                      <NsButton
                        kind="primary"
                        :loading="loading.retrieveClusterBackup"
                        :disabled="loading.retrieveClusterBackup"
                        :icon="ChevronRight20"
                        size="lg"
                        >{{ $t("common.next") }}
                      </NsButton>
                    </cv-button-set>
                  </cv-form>
                </cv-tile>
              </cv-column>
            </cv-row>
          </template>
          <template v-else-if="restore.step == 'file'">
            <cv-row>
              <cv-column>
                <cv-tile light>
                  <h5 class="mg-bottom-md">
                    {{ $t("init.restore_from_cluster_backup_file") }}
                  </h5>
                  <cv-form @submit.prevent="retrieveClusterBackupFromFile">
                    <div>
                      {{ $t("init.upload_cluster_backup_file") }}
                    </div>
                    <cv-file-uploader
                      :drop-target-label="$t('common.upload_drop_target_text')"
                      accept=".json.gz.gpg,.bin,.gpg"
                      :clear-on-reselect="true"
                      :multiple="false"
                      :removable="true"
                      :remove-aria-label="$t('common.remove')"
                      v-model="restore.filesUploaded"
                      @change="onFileUpload"
                      :class="[
                        'file-uploader',
                        { 'validation-failed': error.restore.backup_file },
                      ]"
                      ref="backup_file"
                    >
                    </cv-file-uploader>
                    <div
                      v-if="error.restore.backup_file"
                      class="validation-failed-invalid-message"
                    >
                      {{ error.restore.backup_file }}
                    </div>
                    <NsTextInput
                      type="password"
                      :password-hide-label="$t('password.hide_password')"
                      :password-show-label="$t('password.show_password')"
                      v-model="restore.backupPassword"
                      :label="$t('init.backup_password')"
                      :invalid-message="error.restore.backup_password"
                      :disabled="loading.retrieveClusterBackup"
                      tooltipAlignment="center"
                      tooltipDirection="right"
                      ref="backup_password"
                      class="mg-top-md"
                    >
                      <template #tooltip>
                        <span>{{ $t("init.backup_password_tooltip") }}</span>
                      </template>
                    </NsTextInput>
                    <NsInlineNotification
                      v-if="error.retrieveClusterBackup"
                      kind="error"
                      :title="$t('action.retrieve-cluster-backup')"
                      :description="error.retrieveClusterBackup"
                      :showCloseButton="false"
                    />
                    <cv-button-set class="footer-buttons">
                      <NsButton
                        type="button"
                        kind="secondary"
                        :icon="ChevronLeft20"
                        size="lg"
                        @click="goToRestoreType"
                        >{{ $t("common.go_back") }}
                      </NsButton>
                      <NsButton
                        kind="primary"
                        :loading="loading.retrieveClusterBackup"
                        :disabled="loading.retrieveClusterBackup"
                        :icon="ChevronRight20"
                        size="lg"
                        >{{ $t("common.next") }}
                      </NsButton>
                    </cv-button-set>
                  </cv-form>
                </cv-tile>
              </cv-column>
            </cv-row>
          </template>
          <template v-else-if="restore.step == 'summary'">
            <cv-row>
              <cv-column>
                <cv-tile light>
                  <h5 class="mg-bottom-md">
                    {{ $t("init.restore_summary") }}
                  </h5>
                  <cv-form @submit.prevent="restoreCluster">
                    <div
                      v-if="restore.summary.cluster"
                      class="key-value-setting"
                    >
                      <span class="label">{{ $t("init.cluster_label") }}</span>
                      <span class="value">{{ restore.summary.cluster }}</span>
                    </div>
                    <div class="key-value-setting">
                      <span class="label">{{ $t("init.vpn_endpoint") }}</span>
                      <span class="value">{{ restore.summary.vpn }}</span>
                    </div>
                    <div class="key-value-setting">
                      <span class="label">{{
                        $t("init.external_domains")
                      }}</span>
                      <span class="value">{{ restore.summary.domains }}</span>
                    </div>
                    <div class="key-value-setting">
                      <span class="label">{{
                        $t("init.backup_repositories")
                      }}</span>
                      <span class="value">{{
                        restore.summary.backup_repositories
                      }}</span>
                    </div>
                    <NsInlineNotification
                      kind="info"
                      :title="$t('init.apps_restoration')"
                      :description="
                        restore.summary.single_node_cluster
                          ? $t('init.apps_restoration_single_node_description')
                          : $t('init.apps_restoration_multi_node_description')
                      "
                      :showCloseButton="false"
                      class="mg-top-lg"
                    />
                    <NsInlineNotification
                      v-if="error.restoreCluster"
                      kind="error"
                      :title="$t('action.restore-cluster')"
                      :description="error.restoreCluster"
                      :showCloseButton="false"
                    />
                    <cv-button-set class="footer-buttons">
                      <NsButton
                        type="button"
                        kind="secondary"
                        :icon="ChevronLeft20"
                        size="lg"
                        @click="goToRestoreFromFileOrUrl"
                        >{{ $t("common.go_back") }}
                      </NsButton>
                      <NsButton
                        kind="primary"
                        :loading="loading.restoreCluster"
                        :disabled="loading.restoreCluster"
                        :icon="Reset20"
                        size="lg"
                        >{{ $t("init.restore_cluster") }}
                      </NsButton>
                    </cv-button-set>
                  </cv-form>
                </cv-tile>
              </cv-column>
            </cv-row>
          </template>
          <template v-if="restore.step == 'restoringCluster'">
            <NsInlineNotification
              v-if="error.restoreCluster"
              kind="error"
              :title="$t('action.restore-cluster')"
              :description="error.restoreCluster"
              :showCloseButton="false"
            />
            <NsInlineNotification
              v-if="error.readBackupRepositories"
              kind="error"
              :title="$t('action.read-backup-repositories')"
              :description="error.readBackupRepositories"
              :showCloseButton="false"
            />
            <cv-row
              v-if="!error.restoreCluster && !error.readBackupRepositories"
            >
              <cv-column>
                <cv-tile light>
                  <NsEmptyState
                    :title="$t('init.restoring_cluster')"
                    :animationData="GearsLottie"
                    animationTitle="gears"
                    :loop="true"
                  >
                    <template #description>
                      <span v-if="restore.progress < 100">
                        {{ $t("init.traveling_back_in_time") }}
                      </span>
                      <span v-else-if="loading.readBackupRepositories">
                        {{ $t("init.reading_backup_repositories") }}
                      </span>
                      <span v-else>&nbsp;</span>
                    </template>
                  </NsEmptyState>
                  <NsProgressBar
                    :value="restore.progress"
                    :indeterminate="!restore.progress"
                    class="mg-bottom-md"
                  />
                </cv-tile>
              </cv-column>
            </cv-row>
          </template>
          <template v-if="restore.step == 'apps'">
            <cv-row>
              <cv-column>
                <NsInlineNotification
                  v-if="error.listCoreModules"
                  kind="error"
                  :title="$t('action.list-core-modules')"
                  :description="error.listCoreModules"
                  :showCloseButton="false"
                />
                <NsInlineNotification
                  v-if="!additionalVolumes"
                  kind="info"
                  :title="$t('init.select_apps_to_restore')"
                  :description="$t('init.select_apps_to_restore_description')"
                  :showCloseButton="false"
                />
                <NsInlineNotification
                  v-else
                  kind="info"
                  :title="$t('init.only_core_applications_can_be_restored')"
                  :description="
                    $t('init.other_applications_can_be_restored_later')
                  "
                  :showCloseButton="false"
                />
                <cv-tile light>
                  <cv-form @submit.prevent>
                    <RestoreMultipleInstancesSelector
                      v-if="!loading.listCoreModules"
                      :instances="restore.instances"
                      selection="all"
                      :coreApps="coreApps"
                      :loading="loading.retrieveClusterBackup"
                      :additionalVolumes="additionalVolumes"
                      @select="onSelectInstances"
                      :light="false"
                    />
                    <cv-skeleton-text
                      v-else
                      :paragraph="true"
                      :line-count="5"
                    />
                    <NsInlineNotification
                      v-if="error.restoreModules"
                      kind="error"
                      :title="$t('action.restore-modules')"
                      :description="error.restoreModules"
                      :showCloseButton="false"
                    />
                    <cv-button-set class="footer-buttons">
                      <NsButton
                        type="button"
                        kind="secondary"
                        :icon="ChevronRight20"
                        size="lg"
                        @click="showSkipRestoreAppsModal"
                        :disabled="loading.restoreModules"
                        >{{ $t("common.skip") }}
                      </NsButton>
                      <NsButton
                        kind="primary"
                        :loading="loading.restoreModules"
                        :disabled="
                          loading.restoreModules ||
                          !restore.selectedInstances.length
                        "
                        :icon="Reset20"
                        size="lg"
                        type="button"
                        @click.prevent="restoreModules"
                      >
                        {{
                          $tc(
                            "init.restore_num_apps",
                            restore.selectedInstances.length,
                            { num: restore.selectedInstances.length }
                          )
                        }}
                      </NsButton>
                    </cv-button-set>
                  </cv-form>
                </cv-tile>
              </cv-column>
            </cv-row>
          </template>
          <template v-if="restore.step == 'restoringApps'">
            <NsInlineNotification
              v-if="error.restoreModules"
              kind="error"
              :title="$t('action.restore-modules')"
              :description="error.restoreModules"
              :showCloseButton="false"
              @click="goToLogs"
              :actionLabel="
                $t('common.go_to_page', { page: $t('system_logs.title') })
              "
            />
            <cv-row v-if="!error.restoreModules">
              <cv-column>
                <cv-tile light>
                  <NsEmptyState
                    :title="$t('init.restoring_applications')"
                    :animationData="GearsLottie"
                    animationTitle="gears"
                    :loop="true"
                  >
                  </NsEmptyState>
                  <NsProgressBar
                    :value="restore.progress"
                    :indeterminate="!restore.progress"
                    class="mg-bottom-md"
                  />
                </cv-tile>
              </cv-column>
            </cv-row>
          </template>
        </template>
⋮----
<h2>{{ $t("init.restore_cluster") }}</h2>
⋮----
{{ $t("init.restore_cluster_description") }}
⋮----
<template v-if="restore.step == 'type'">
            <cv-row>
              <cv-column>
                <cv-tile light>
                  <cv-grid fullWidth class="mg-top-xlg no-padding">
                    <cv-row>
                      <cv-column :md="4">
                        <NsTile
                          kind="clickable"
                          :icon="Link32"
                          @click="goToRestoreFromUrl"
                          large
                        >
                          <h6>
                            {{ $t("init.restore_from_remote_url") }}
                          </h6>
                        </NsTile>
                      </cv-column>
                      <cv-column :md="4">
                        <NsTile
                          kind="clickable"
                          :icon="Document32"
                          @click="goToRestoreFromFile"
                          large
                        >
                          <h6>
                            {{ $t("init.restore_from_cluster_backup_file") }}
                          </h6>
                        </NsTile>
                      </cv-column>
                    </cv-row>
                  </cv-grid>
                  <cv-button-set class="footer-buttons">
                    <NsButton
                      type="button"
                      kind="secondary"
                      :icon="ChevronLeft20"
                      size="lg"
                      @click="goToWelcomePage"
                      >{{ $t("common.go_back") }}
                    </NsButton>
                  </cv-button-set>
                </cv-tile>
              </cv-column>
            </cv-row>
          </template>
⋮----
{{ $t("init.restore_from_remote_url") }}
⋮----
{{ $t("init.restore_from_cluster_backup_file") }}
⋮----
>{{ $t("common.go_back") }}
⋮----
<template v-else-if="restore.step == 'url'">
            <cv-row>
              <cv-column>
                <cv-tile light>
                  <h5 class="mg-bottom-md">
                    {{ $t("init.restore_from_remote_url") }}
                  </h5>
                  <cv-form @submit.prevent="retrieveClusterBackupFromUrl">
                    <NsTextInput
                      v-model.trim="restore.url"
                      :label="$t('init.remote_url')"
                      placeholder="https://myserver/cluster-backup.json.gz.gpg"
                      :invalid-message="error.restore.url"
                      :disabled="loading.retrieveClusterBackup"
                      class="mg-bottom-sm"
                      ref="url"
                    />
                    <cv-checkbox
                      :label="$t('init.tls_verify')"
                      v-model="restore.tlsVerify"
                      value="checkTlsVerify"
                    />
                    <NsTextInput
                      type="password"
                      :password-hide-label="$t('password.hide_password')"
                      :password-show-label="$t('password.show_password')"
                      v-model="restore.backupPassword"
                      :label="$t('init.backup_password')"
                      :invalid-message="error.restore.backup_password"
                      :disabled="loading.retrieveClusterBackup"
                      tooltipAlignment="center"
                      tooltipDirection="right"
                      ref="backup_password"
                      class="mg-top-md"
                    >
                      <template #tooltip>
                        <span>{{ $t("init.backup_password_tooltip") }}</span>
                      </template>
                    </NsTextInput>
                    <cv-button-set class="footer-buttons">
                      <NsButton
                        type="button"
                        kind="secondary"
                        :icon="ChevronLeft20"
                        size="lg"
                        @click="goToRestoreType"
                        >{{ $t("common.go_back") }}
                      </NsButton>
                      <NsButton
                        kind="primary"
                        :loading="loading.retrieveClusterBackup"
                        :disabled="loading.retrieveClusterBackup"
                        :icon="ChevronRight20"
                        size="lg"
                        >{{ $t("common.next") }}
                      </NsButton>
                    </cv-button-set>
                  </cv-form>
                </cv-tile>
              </cv-column>
            </cv-row>
          </template>
⋮----
{{ $t("init.restore_from_remote_url") }}
⋮----
<template #tooltip>
                        <span>{{ $t("init.backup_password_tooltip") }}</span>
                      </template>
⋮----
<span>{{ $t("init.backup_password_tooltip") }}</span>
⋮----
>{{ $t("common.go_back") }}
⋮----
>{{ $t("common.next") }}
⋮----
<template v-else-if="restore.step == 'file'">
            <cv-row>
              <cv-column>
                <cv-tile light>
                  <h5 class="mg-bottom-md">
                    {{ $t("init.restore_from_cluster_backup_file") }}
                  </h5>
                  <cv-form @submit.prevent="retrieveClusterBackupFromFile">
                    <div>
                      {{ $t("init.upload_cluster_backup_file") }}
                    </div>
                    <cv-file-uploader
                      :drop-target-label="$t('common.upload_drop_target_text')"
                      accept=".json.gz.gpg,.bin,.gpg"
                      :clear-on-reselect="true"
                      :multiple="false"
                      :removable="true"
                      :remove-aria-label="$t('common.remove')"
                      v-model="restore.filesUploaded"
                      @change="onFileUpload"
                      :class="[
                        'file-uploader',
                        { 'validation-failed': error.restore.backup_file },
                      ]"
                      ref="backup_file"
                    >
                    </cv-file-uploader>
                    <div
                      v-if="error.restore.backup_file"
                      class="validation-failed-invalid-message"
                    >
                      {{ error.restore.backup_file }}
                    </div>
                    <NsTextInput
                      type="password"
                      :password-hide-label="$t('password.hide_password')"
                      :password-show-label="$t('password.show_password')"
                      v-model="restore.backupPassword"
                      :label="$t('init.backup_password')"
                      :invalid-message="error.restore.backup_password"
                      :disabled="loading.retrieveClusterBackup"
                      tooltipAlignment="center"
                      tooltipDirection="right"
                      ref="backup_password"
                      class="mg-top-md"
                    >
                      <template #tooltip>
                        <span>{{ $t("init.backup_password_tooltip") }}</span>
                      </template>
                    </NsTextInput>
                    <NsInlineNotification
                      v-if="error.retrieveClusterBackup"
                      kind="error"
                      :title="$t('action.retrieve-cluster-backup')"
                      :description="error.retrieveClusterBackup"
                      :showCloseButton="false"
                    />
                    <cv-button-set class="footer-buttons">
                      <NsButton
                        type="button"
                        kind="secondary"
                        :icon="ChevronLeft20"
                        size="lg"
                        @click="goToRestoreType"
                        >{{ $t("common.go_back") }}
                      </NsButton>
                      <NsButton
                        kind="primary"
                        :loading="loading.retrieveClusterBackup"
                        :disabled="loading.retrieveClusterBackup"
                        :icon="ChevronRight20"
                        size="lg"
                        >{{ $t("common.next") }}
                      </NsButton>
                    </cv-button-set>
                  </cv-form>
                </cv-tile>
              </cv-column>
            </cv-row>
          </template>
⋮----
{{ $t("init.restore_from_cluster_backup_file") }}
⋮----
{{ $t("init.upload_cluster_backup_file") }}
⋮----
{{ error.restore.backup_file }}
⋮----
<template #tooltip>
                        <span>{{ $t("init.backup_password_tooltip") }}</span>
                      </template>
⋮----
<span>{{ $t("init.backup_password_tooltip") }}</span>
⋮----
>{{ $t("common.go_back") }}
⋮----
>{{ $t("common.next") }}
⋮----
<template v-else-if="restore.step == 'summary'">
            <cv-row>
              <cv-column>
                <cv-tile light>
                  <h5 class="mg-bottom-md">
                    {{ $t("init.restore_summary") }}
                  </h5>
                  <cv-form @submit.prevent="restoreCluster">
                    <div
                      v-if="restore.summary.cluster"
                      class="key-value-setting"
                    >
                      <span class="label">{{ $t("init.cluster_label") }}</span>
                      <span class="value">{{ restore.summary.cluster }}</span>
                    </div>
                    <div class="key-value-setting">
                      <span class="label">{{ $t("init.vpn_endpoint") }}</span>
                      <span class="value">{{ restore.summary.vpn }}</span>
                    </div>
                    <div class="key-value-setting">
                      <span class="label">{{
                        $t("init.external_domains")
                      }}</span>
                      <span class="value">{{ restore.summary.domains }}</span>
                    </div>
                    <div class="key-value-setting">
                      <span class="label">{{
                        $t("init.backup_repositories")
                      }}</span>
                      <span class="value">{{
                        restore.summary.backup_repositories
                      }}</span>
                    </div>
                    <NsInlineNotification
                      kind="info"
                      :title="$t('init.apps_restoration')"
                      :description="
                        restore.summary.single_node_cluster
                          ? $t('init.apps_restoration_single_node_description')
                          : $t('init.apps_restoration_multi_node_description')
                      "
                      :showCloseButton="false"
                      class="mg-top-lg"
                    />
                    <NsInlineNotification
                      v-if="error.restoreCluster"
                      kind="error"
                      :title="$t('action.restore-cluster')"
                      :description="error.restoreCluster"
                      :showCloseButton="false"
                    />
                    <cv-button-set class="footer-buttons">
                      <NsButton
                        type="button"
                        kind="secondary"
                        :icon="ChevronLeft20"
                        size="lg"
                        @click="goToRestoreFromFileOrUrl"
                        >{{ $t("common.go_back") }}
                      </NsButton>
                      <NsButton
                        kind="primary"
                        :loading="loading.restoreCluster"
                        :disabled="loading.restoreCluster"
                        :icon="Reset20"
                        size="lg"
                        >{{ $t("init.restore_cluster") }}
                      </NsButton>
                    </cv-button-set>
                  </cv-form>
                </cv-tile>
              </cv-column>
            </cv-row>
          </template>
⋮----
{{ $t("init.restore_summary") }}
⋮----
<span class="label">{{ $t("init.cluster_label") }}</span>
<span class="value">{{ restore.summary.cluster }}</span>
⋮----
<span class="label">{{ $t("init.vpn_endpoint") }}</span>
<span class="value">{{ restore.summary.vpn }}</span>
⋮----
<span class="label">{{
                        $t("init.external_domains")
                      }}</span>
<span class="value">{{ restore.summary.domains }}</span>
⋮----
<span class="label">{{
                        $t("init.backup_repositories")
                      }}</span>
<span class="value">{{
                        restore.summary.backup_repositories
                      }}</span>
⋮----
>{{ $t("common.go_back") }}
⋮----
>{{ $t("init.restore_cluster") }}
⋮----
<template v-if="restore.step == 'restoringCluster'">
            <NsInlineNotification
              v-if="error.restoreCluster"
              kind="error"
              :title="$t('action.restore-cluster')"
              :description="error.restoreCluster"
              :showCloseButton="false"
            />
            <NsInlineNotification
              v-if="error.readBackupRepositories"
              kind="error"
              :title="$t('action.read-backup-repositories')"
              :description="error.readBackupRepositories"
              :showCloseButton="false"
            />
            <cv-row
              v-if="!error.restoreCluster && !error.readBackupRepositories"
            >
              <cv-column>
                <cv-tile light>
                  <NsEmptyState
                    :title="$t('init.restoring_cluster')"
                    :animationData="GearsLottie"
                    animationTitle="gears"
                    :loop="true"
                  >
                    <template #description>
                      <span v-if="restore.progress < 100">
                        {{ $t("init.traveling_back_in_time") }}
                      </span>
                      <span v-else-if="loading.readBackupRepositories">
                        {{ $t("init.reading_backup_repositories") }}
                      </span>
                      <span v-else>&nbsp;</span>
                    </template>
                  </NsEmptyState>
                  <NsProgressBar
                    :value="restore.progress"
                    :indeterminate="!restore.progress"
                    class="mg-bottom-md"
                  />
                </cv-tile>
              </cv-column>
            </cv-row>
          </template>
⋮----
<template #description>
                      <span v-if="restore.progress < 100">
                        {{ $t("init.traveling_back_in_time") }}
                      </span>
                      <span v-else-if="loading.readBackupRepositories">
                        {{ $t("init.reading_backup_repositories") }}
                      </span>
                      <span v-else>&nbsp;</span>
                    </template>
⋮----
{{ $t("init.traveling_back_in_time") }}
⋮----
{{ $t("init.reading_backup_repositories") }}
⋮----
<template v-if="restore.step == 'apps'">
            <cv-row>
              <cv-column>
                <NsInlineNotification
                  v-if="error.listCoreModules"
                  kind="error"
                  :title="$t('action.list-core-modules')"
                  :description="error.listCoreModules"
                  :showCloseButton="false"
                />
                <NsInlineNotification
                  v-if="!additionalVolumes"
                  kind="info"
                  :title="$t('init.select_apps_to_restore')"
                  :description="$t('init.select_apps_to_restore_description')"
                  :showCloseButton="false"
                />
                <NsInlineNotification
                  v-else
                  kind="info"
                  :title="$t('init.only_core_applications_can_be_restored')"
                  :description="
                    $t('init.other_applications_can_be_restored_later')
                  "
                  :showCloseButton="false"
                />
                <cv-tile light>
                  <cv-form @submit.prevent>
                    <RestoreMultipleInstancesSelector
                      v-if="!loading.listCoreModules"
                      :instances="restore.instances"
                      selection="all"
                      :coreApps="coreApps"
                      :loading="loading.retrieveClusterBackup"
                      :additionalVolumes="additionalVolumes"
                      @select="onSelectInstances"
                      :light="false"
                    />
                    <cv-skeleton-text
                      v-else
                      :paragraph="true"
                      :line-count="5"
                    />
                    <NsInlineNotification
                      v-if="error.restoreModules"
                      kind="error"
                      :title="$t('action.restore-modules')"
                      :description="error.restoreModules"
                      :showCloseButton="false"
                    />
                    <cv-button-set class="footer-buttons">
                      <NsButton
                        type="button"
                        kind="secondary"
                        :icon="ChevronRight20"
                        size="lg"
                        @click="showSkipRestoreAppsModal"
                        :disabled="loading.restoreModules"
                        >{{ $t("common.skip") }}
                      </NsButton>
                      <NsButton
                        kind="primary"
                        :loading="loading.restoreModules"
                        :disabled="
                          loading.restoreModules ||
                          !restore.selectedInstances.length
                        "
                        :icon="Reset20"
                        size="lg"
                        type="button"
                        @click.prevent="restoreModules"
                      >
                        {{
                          $tc(
                            "init.restore_num_apps",
                            restore.selectedInstances.length,
                            { num: restore.selectedInstances.length }
                          )
                        }}
                      </NsButton>
                    </cv-button-set>
                  </cv-form>
                </cv-tile>
              </cv-column>
            </cv-row>
          </template>
⋮----
>{{ $t("common.skip") }}
⋮----
{{
                          $tc(
                            "init.restore_num_apps",
                            restore.selectedInstances.length,
                            { num: restore.selectedInstances.length }
                          )
                        }}
⋮----
<template v-if="restore.step == 'restoringApps'">
            <NsInlineNotification
              v-if="error.restoreModules"
              kind="error"
              :title="$t('action.restore-modules')"
              :description="error.restoreModules"
              :showCloseButton="false"
              @click="goToLogs"
              :actionLabel="
                $t('common.go_to_page', { page: $t('system_logs.title') })
              "
            />
            <cv-row v-if="!error.restoreModules">
              <cv-column>
                <cv-tile light>
                  <NsEmptyState
                    :title="$t('init.restoring_applications')"
                    :animationData="GearsLottie"
                    animationTitle="gears"
                    :loop="true"
                  >
                  </NsEmptyState>
                  <NsProgressBar
                    :value="restore.progress"
                    :indeterminate="!restore.progress"
                    class="mg-bottom-md"
                  />
                </cv-tile>
              </cv-column>
            </cv-row>
          </template>
⋮----
<template v-else-if="q.page === 'redirect'">
        <cv-row>
          <cv-column class="welcome">
            <h2>{{ $t("init.redirect_cluster") }}</h2>
            <WelcomeLogo />
          </cv-column>
        </cv-row>
        <cv-tile light>
          <cv-row>
            <cv-column>
              <div>
                {{ $t("init.redirect_cluster_description") }}
              </div>
            </cv-column>
          </cv-row>
          <cv-row class="mg-top-xlg">
            <cv-column>
              <a
                :href="this.joinEndpoint + '/cluster-admin/'"
                class="external-link-button"
              >
                <NsButton kind="primary" :icon="ArrowRight20">
                  {{ $t("init.redirect_cluster_link") }}
                </NsButton>
              </a>
            </cv-column>
          </cv-row>
        </cv-tile>
      </template>
⋮----
<h2>{{ $t("init.redirect_cluster") }}</h2>
⋮----
{{ $t("init.redirect_cluster_description") }}
⋮----
{{ $t("init.redirect_cluster_link") }}
⋮----
<script>
import {
  QueryParamService,
  UtilService,
  IconService,
  StorageService,
  NsPasswordInput,
  TaskService,
  LottieService,
  PageTitleService,
} from "@nethserver/ns8-ui-lib";
import { mapActions } from "vuex";
import to from "await-to-js";
import NotificationService from "@/mixins/notification";
import RestoreMultipleInstancesSelector from "@/components/backup/RestoreMultipleInstancesSelector";
import SkipRestoreAppsModal from "@/components/initialize-cluster/SkipRestoreAppsModal";
import WelcomeLogo from "@/components/initialize-cluster/WelcomeLogo";
import SetFqdn from "@/components/initialize-cluster/SetFqdn";
export default {
  name: "InitializeCluster",
  components: {
    NsPasswordInput,
    RestoreMultipleInstancesSelector,
    SkipRestoreAppsModal,
    WelcomeLogo,
    SetFqdn,
  },
  mixins: [
    UtilService,
    IconService,
    QueryParamService,
    StorageService,
    TaskService,
    NotificationService,
    LottieService,
    PageTitleService,
  ],
  pageTitle() {
    return this.$t("init.welcome", { product: this.$root.config.PRODUCT_NAME });
  },
  data() {
    return {
      q: {
        page: "welcome",
        endpoint: null,
        action: null,
      },
      additionalVolumes: false,
      coreApps: [],
      isPasswordChangeNeeded: false,
      currentPassword: "",
      newPassword: "",
      passwordValidation: null,
      focusPasswordField: { element: "" },
      vpnEndpointAddress: "",
      vpnEndpointPort: "",
      network: "",
      joinCode: "",
      tlsVerify: true,
      joinEndpoint: this.$route.query.endpoint
        ? "https:
        : "",
      joinToken: "",
      isCreatingCluster: false,
      isJoiningCluster: false,
      isChangingPassword: false,
      isMaster: true,
      createClusterProgress: 0,
      isOpenCreateClusterAccordion: false,
      restore: {
        step: "type",
        type: "",
        url: "",
        tlsVerify: true,
        backupPassword: "",
        filesUploaded: [],
        base64FileUploaded: "",
        summary: {},
        progress: 0,
        instances: [],
        selectedInstances: [],
        isShownSkipRestoreAppsModal: false,
      },
      loading: {
        getDefaults: true,
        retrieveClusterBackup: false,
        restoreCluster: false,
        readBackupRepositories: false,
        restoreModules: false,
        listMountPoints: false,
        listCoreModules: false,
      },
      error: {
        currentPassword: "",
        newPassword: "",
        confirmPassword: "",
        vpnEndpointAddress: "",
        vpnEndpointPort: "",
        network: "",
        joinCode: "",
        retrieveClusterBackup: "",
        restoreCluster: "",
        readBackupRepositories: "",
        restoreModules: "",
        createCluster: "",
        networkCheckCreateCluster: "",
        getDefaults: "",
        restore: {
          url: "",
          backup_password: "",
          backup_file: "",
        },
        listMountPoints: "",
        listCoreModules: "",
      },
    };
  },
  watch: {
    "q.page": function () {
      if (this.q.page === "create") {
        this.getDefaults();
      }
    },
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.watchQueryData(vm);
      vm.queryParamsToDataForCore(vm, to.query);
    });
  },
  beforeRouteUpdate(to, from, next) {
    this.queryParamsToDataForCore(this, to.query);
    next();
  },
  created() {
    this.getClusterStatus();
    this.listMountPoints();
    this.getDefaults();
  },
  methods: {
    ...mapActions(["setClusterInitializedInStore"]),
    async getDefaults() {
      this.loading.getDefaults = true;
      const taskAction = "get-defaults";
      this.$root.$off(taskAction + "-aborted");
      this.$root.$once(taskAction + "-aborted", this.getDefaultsAborted);
      this.$root.$off(taskAction + "-completed");
      this.$root.$once(taskAction + "-completed", this.getDefaultsCompleted);
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            toastTimeout: 0,
          },
        })
      );
      const err = res[0];
      if (err) {
        if (err.response && err.response.status == 403) {
          this.isMaster = false;
        } else {
          const notification = {
            title: this.$t("task.cannot_create_task", { action: taskAction }),
            description: this.getErrorMessage(err),
            type: "error",
            toastTimeout: 0,
          };
          this.createNotification(notification);
          return;
        }
      }
    },
    getDefaultsAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.loading.getDefaults = false;
    },
    getDefaultsCompleted(taskContext, taskResult) {
      const defaults = taskResult.output;
      this.vpnEndpointAddress = defaults.vpn.host;
      this.vpnEndpointPort = defaults.vpn.port.toString();
      this.network = defaults.vpn.network;
      this.loading.getDefaults = false;
      if (this.q.page === "create") {
        this.focusElement("network");
      }
    },
    selectCreateCluster() {
      this.$router.push({
        path: "/init",
        query: { page: "fqdn", action: "create" },
      });
      if (this.isPasswordChangeNeeded) {
        this.focusElement("currentPassword");
      }
    },
    selectJoinCluster() {
      this.$router.push({
        path: "/init",
        query: { page: "fqdn", action: "join" },
      });
    },
    selectRestoreCluster() {
      this.$router.push({ path: "/init", query: { page: "restore" } });
      if (this.isPasswordChangeNeeded) {
        this.focusElement("currentPassword");
      }
    },
    goToRestoreType() {
      this.restore.step = "type";
      this.restore.type = "";
    },
    goToRestoreFromFile() {
      this.restore.step = "file";
      this.restore.type = "file";
    },
    goToRestoreFromUrl() {
      this.restore.step = "url";
      this.restore.type = "url";
    },
    goToRestoreFromFileOrUrl() {
      if (this.restore.type == "file") {
        this.goToRestoreFromFile();
      } else {
        this.goToRestoreFromUrl();
      }
    },
    goToWelcomePage() {
      this.$router.push({ path: "/init", query: { page: "welcome" } });
    },
    goToFqdnPage() {
      const action = this.$route.query.action;
      this.$router.push({
        path: "/init",
        query: { page: "fqdn", action: action },
      });
    },
    onFqdnSet() {
      const action = this.$route.query.action;
      this.error.networkCheckCreateCluster = "";
      this.error.createCluster = "";
      this.$router.push({
        path: "/init",
        query: { page: action, action: action },
      });
      if (action === "join") {
        this.focusElement("joinCode");
      }
    },
    async listCoreModules() {
      this.error.listCoreModules = "";
      this.loading.listCoreModules = true;
      const taskAction = "list-core-modules";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.listCoreModulesAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.listCoreModulesCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.listCoreModules = this.getErrorMessage(err);
        this.loading.listCoreModules = false;
        return;
      }
    },
    listCoreModulesAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.listCoreModules = this.$t("error.generic_error");
      this.loading.listCoreModules = false;
    },
    listCoreModulesCompleted(taskContext, taskResult) {
      this.coreApps = taskResult.output;
      this.loading.listCoreModules = false;
    },
    async listMountPoints() {
      this.error.listMountPoints = "";
      this.loading.listMountPoints = true;
      const taskAction = "list-mountpoints";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.listMountPointsAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.listMountPointsCompleted
      );
      const res = await to(
        this.createNodeTask(1, {
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.listMountPoints = this.getErrorMessage(err);
        this.loading.listMountPoints = false;
        return;
      }
    },
    listMountPointsAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.listMountPoints = this.$t("error.generic_error");
      this.loading.listMountPoints = false;
    },
    listMountPointsCompleted(taskContext, taskResult) {
      const additionalVolumes = taskResult.output.mountpoints;
      this.additionalVolumes = additionalVolumes.length > 0;
      this.loading.listMountPoints = false;
    },
    async getClusterStatus() {
      const taskAction = "get-cluster-status";
      this.$root.$once(
        taskAction + "-completed",
        this.getClusterStatusCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            toastTimeout: 0,
          },
        })
      );
      const err = res[0];
      if (err) {
        if (err.response && err.response.status == 403) {
          this.isMaster = false;
        } else {
          const notification = {
            title: this.$t("task.cannot_create_task", { action: taskAction }),
            description: this.getErrorMessage(err),
            type: "error",
            toastTimeout: 0,
          };
          this.createNotification(notification);
          return;
        }
      }
    },
    getClusterStatusCompleted(taskContext, taskResult) {
      const clusterStatus = taskResult.output;
      if (clusterStatus.initialized && this.isMaster) {
        this.setClusterInitializedInStore(true);
        this.$root.$emit("clusterInitialized");
        this.$router.replace("/status");
        return;
      }
      this.isPasswordChangeNeeded = clusterStatus.default_password;
    },
    onPasswordValidation(passwordValidation) {
      this.passwordValidation = passwordValidation;
    },
    validatePasswordChange() {
      this.clearErrors(this);
      let isValidationOk = true;
      if (!this.currentPassword) {
        this.error.currentPassword = "common.required";
        if (isValidationOk) {
          this.focusElement("currentPassword");
          isValidationOk = false;
        }
      }
      if (!this.newPassword) {
        this.error.newPassword = "common.required";
        if (isValidationOk) {
          this.focusPasswordField = { element: "newPassword" };
          isValidationOk = false;
        }
      } else {
        if (this.currentPassword === this.newPassword) {
          if (!this.error.newPassword) {
            this.error.newPassword =
              "password.old_new_passwords_must_be_different";
          }
          if (isValidationOk) {
            this.focusPasswordField = { element: "newPassword" };
            isValidationOk = false;
          }
        }
        if (
          !this.passwordValidation.isLengthOk ||
          !this.passwordValidation.isLowercaseOk ||
          !this.passwordValidation.isUppercaseOk ||
          !this.passwordValidation.isNumberOk ||
          !this.passwordValidation.isSymbolOk
        ) {
          if (!this.error.newPassword) {
            this.error.newPassword = "password.password_not_secure";
          }
          if (isValidationOk) {
            this.focusPasswordField = { element: "newPassword" };
            isValidationOk = false;
          }
        }
        if (!this.passwordValidation.isEqualOk) {
          if (!this.error.newPassword) {
            this.error.newPassword = "password.passwords_do_not_match";
          }
          if (!this.error.confirmPassword) {
            this.error.confirmPassword = "password.passwords_do_not_match";
          }
          if (isValidationOk) {
            this.focusPasswordField = { element: "confirmPassword" };
            isValidationOk = false;
          }
        }
      }
      return isValidationOk;
    },
    async changePassword() {
      this.isChangingPassword = true;
      if (!this.validatePasswordChange()) {
        this.isChangingPassword = false;
        return;
      }
      const loginInfo = this.getFromStorage("loginInfo");
      const taskAction = "change-user-password";
      this.$root.$off(taskAction + "-completed");
      this.$root.$once(
        taskAction + "-completed",
        this.changeUserPasswordCompleted
      );
      this.$root.$off(taskAction + "-validation-failed");
      this.$root.$once(
        taskAction + "-validation-failed",
        this.changeUserPasswordValidationFailed
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {
            user: loginInfo.username,
            current_password: this.currentPassword,
            new_password: this.newPassword,
          },
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            toastTimeout: 0,
          },
        })
      );
      const err = res[0];
      if (err) {
        if (err.response && err.response.status == 403) {
          this.isMaster = false;
        } else {
          const notification = {
            title: this.$t("task.cannot_create_task", { action: taskAction }),
            description: this.getErrorMessage(err),
            type: "error",
            toastTimeout: 0,
          };
          this.createNotification(notification);
          return;
        }
      }
    },
    changeUserPasswordCompleted() {
      this.isPasswordChangeNeeded = false;
    },
    changeUserPasswordValidationFailed(validationErrors) {
      this.isChangingPassword = false;
      for (const validationError of validationErrors) {
        this.error.currentPassword = "password." + validationError.error;
        this.focusElement("currentPassword");
      }
    },
    isFqdn(fqdn) {
      const fqdnRegex = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.[a-zA-Z]{2,}$/;
      return fqdnRegex.test(fqdn);
    },
    validateCreateCluster() {
      this.clearErrors(this);
      let isValidationOk = true;
      if (!this.network) {
        this.error.network = "common.required";
        if (isValidationOk) {
          this.focusElement("network");
          isValidationOk = false;
        }
      }
      return isValidationOk;
    },
    async createCluster() {
      if (!this.validateCreateCluster()) {
        return;
      }
      const taskAction = "create-cluster";
      const eventId = this.getUuid();
      this.createClusterProgress = 0;
      this.error.networkCheckCreateCluster = "";
      this.error.createCluster = "";
      // register to task validation
      this.$root.$once(
        `${taskAction}-validation-failed-${eventId}`,
        this.createClusterValidationFailed
      );
      // register to task error
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.createClusterAborted
      );
      // register to task completion
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.createClusterCompleted
      );
      // register to task progress to update progress bar
      this.$root.$on(
        `${taskAction}-progress-${eventId}`,
        this.createClusterProgressUpdated
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {
            network: this.network,
            endpoint: this.vpnEndpointAddress + ":" + this.vpnEndpointPort,
          },
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            toastTimeout: 0, // persistent notification
            isProgressNotified: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        if (err.response && err.response.status == 403) {
          this.isMaster = false;
        } else {
          console.error(`error creating task ${taskAction}`, err);
          this.error.createCluster = this.getErrorMessage(err);
          this.loading.getDefaults = false;
          return;
        }
      }
      this.isCreatingCluster = true;
    },
    createClusterValidationFailed(validationErrors) {
      this.loading.getDefaults = false;
      this.isCreatingCluster = false;
      let focusAlreadySet = false;
      for (const validationError of validationErrors) {
        const param = validationError.parameter;
        const errorMessage = this.getI18nStringWithFallback(
          "init." + validationError.error,
          "error." + validationError.error
        );
        if (validationError.error === "network_check_failed") {
          this.error.networkCheckCreateCluster = errorMessage;
        } else if (param) {
          this.error[param] = errorMessage;
          if (!focusAlreadySet) {
            this.focusElement(param);
            focusAlreadySet = true;
          }
        }
      }
    },
    createClusterCompleted(taskContext) {
      this.setClusterInitializedInStore(true);
      this.$root.$emit("clusterInitialized");
      this.$router.replace("/status");
      this.isCreatingCluster = false;
      this.$root.$off(
        `${taskContext.action}-progress-${taskContext.extra.eventId}`
      );
    },
    createClusterAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.createCluster = this.$t("error.generic_error");
      this.isCreatingCluster = false;
      this.$root.$off(
        `${taskContext.action}-progress-${taskContext.extra.eventId}`
      );
    },
    createClusterProgressUpdated(progress) {
      this.createClusterProgress = progress;
    },
    validateJoinCluster() {
      this.clearErrors(this);
      let isValidationOk = true;
      if (!this.joinCode) {
        this.error.joinCode = "common.required";
        if (isValidationOk) {
          this.focusElement("joinCode");
          isValidationOk = false;
        }
      } else {
        let decoded;
        try {
          decoded = atob(this.joinCode);
        } catch (DOMException) {
          this.error.joinCode = "init.the_join_code_can_not_be_decoded";
          if (isValidationOk) {
            this.focusElement("joinCode");
            isValidationOk = false;
          }
        }
        if (!decoded) {
          this.error.joinCode = "init.the_join_code_is_not_correctly_encoded";
          if (isValidationOk) {
            this.focusElement("joinCode");
            isValidationOk = false;
          }
        } else {
          let [endpoint, token] = decoded.split("|");
          if (!(endpoint && token)) {
            this.error.joinCode = "init.the_join_code_cannot_be_parsed";
            if (isValidationOk) {
              this.focusElement("joinCode");
              isValidationOk = false;
            }
          } else {
            this.joinEndpoint = endpoint;
            this.joinToken = token;
          }
        }
      }
      return isValidationOk;
    },
    async joinCluster() {
      if (!this.validateJoinCluster()) {
        return;
      }
      const taskAction = "join-cluster";
      this.$root.$off(taskAction + "-completed");
      this.$root.$once(taskAction + "-completed", this.joinClusterCompleted);
      this.$root.$off(taskAction + "-validation-failed");
      this.$root.$once(
        taskAction + "-validation-failed",
        this.joinClusterValidationFailed
      );
      this.$root.$off(taskAction + "-aborted");
      this.$root.$once(taskAction + "-aborted", this.joinClusterAborted);
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {
            url: this.joinEndpoint,
            jwt: this.joinToken,
            tls_verify: this.tlsVerify,
          },
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            toastTimeout: 0,
          },
        })
      );
      const err = res[0];
      if (err) {
        if (err.response && err.response.status == 403) {
          this.isMaster = false;
        } else {
          const notification = {
            title: this.$t("task.cannot_create_task", { action: taskAction }),
            description: this.getErrorMessage(err),
            type: "error",
            toastTimeout: 0,
          };
          this.createNotification(notification);
          return;
        }
      }
      this.isJoiningCluster = true;
    },
    joinClusterCompleted(taskContext, taskResult) {
      this.isJoiningCluster = false;
      this.$router.push("/init?page=redirect");
      const nodeId = taskResult.output.nodeId;
      const notification = {
        title: this.$t("action.join-cluster"),
        description: this.$t("init.node_added_to_cluster", { nodeId }),
        type: "success",
      };
      this.createNotification(notification);
    },
    joinClusterAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.isJoiningCluster = false;
    },
    joinClusterValidationFailed(validationErrors) {
      console.error("validation failed", validationErrors);
      this.isJoiningCluster = false;
      this.error.joinCode = this.$t("init." + validationErrors[0].error, {
        value: validationErrors[0].value,
      });
      this.focusElement("joinCode");
    },
    async onFileUpload(files) {
      this.error.restore.backup_file = "";
      this.restore.base64FileUploaded = "";
      if (files.length > 1) {
        // keep only last uploaded file
        this.$set(this.restore.filesUploaded, 0, files[files.length - 1]);
        this.restore.filesUploaded.splice(1);
      }
      const fileUploaded = this.restore.filesUploaded[0];
      if (!fileUploaded || fileUploaded.invalidMessageTitle) {
        // invalid file
        return;
      }
      const file = fileUploaded.file;
      const result = await this.fileToBase64(file).catch((e) => Error(e));
      if (result instanceof Error) {
        console.log("error converting file to base64:", result.message);
        return;
      } else {
        this.restore.base64FileUploaded = result.split(";base64,")[1];
      }
    },
    validateRetrieveClusterBackupFromFile() {
      let isValidationOk = true;
      this.clearErrors();
      if (
        !this.restore.filesUploaded.length ||
        !this.restore.base64FileUploaded
      ) {
        this.error.restore.backup_file = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("backup_file");
          isValidationOk = false;
        }
      }
      return isValidationOk;
    },
    validateRetrieveClusterBackupFromUrl() {
      let isValidationOk = true;
      this.clearErrors();
      if (!this.restore.url) {
        this.error.restore.url = this.$t("common.required");
        if (isValidationOk) {
          this.focusElement("url");
          isValidationOk = false;
        }
      }
      return isValidationOk;
    },
    retrieveClusterBackupFromFile() {
      if (!this.validateRetrieveClusterBackupFromFile()) {
        return;
      }
      const inputData = {
        type: "file",
        password: this.restore.backupPassword,
        file: this.restore.base64FileUploaded,
      };
      this.retrieveClusterBackup(inputData);
    },
    retrieveClusterBackupFromUrl() {
      if (!this.validateRetrieveClusterBackupFromUrl()) {
        return;
      }
      const inputData = {
        type: "url",
        password: this.restore.backupPassword,
        url: this.restore.url,
        tls_verify: this.restore.tlsVerify,
      };
      this.retrieveClusterBackup(inputData);
    },
    async retrieveClusterBackup(inputData) {
      this.error.retrieveClusterBackup = "";
      this.loading.retrieveClusterBackup = true;
      const taskAction = "retrieve-cluster-backup";
      this.$root.$off(taskAction + "-validation-failed");
      this.$root.$once(
        taskAction + "-validation-failed",
        this.retrieveClusterBackupValidationFailed
      );
      this.$root.$off(taskAction + "-aborted");
      this.$root.$once(
        taskAction + "-aborted",
        this.retrieveClusterBackupAborted
      );
      this.$root.$off(taskAction + "-completed");
      this.$root.$once(
        taskAction + "-completed",
        this.retrieveClusterBackupCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: inputData,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            toastTimeout: 0,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.retrieveClusterBackup = this.getErrorMessage(err);
        return;
      }
    },
    retrieveClusterBackupValidationFailed(validationErrors) {
      this.loading.retrieveClusterBackup = false;
      let focusAlreadySet = false;
      for (const validationError of validationErrors) {
        const param = validationError.parameter;
        if (param == "backup_password") {
          this.restore.isBackupPasswordAccordionOpenAndDisabled = true;
        }
        this.error.restore[param] = this.$t("init." + validationError.error);
        if (!focusAlreadySet) {
          this.focusElement(param);
          focusAlreadySet = true;
        }
      }
    },
    retrieveClusterBackupAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.loading.retrieveClusterBackup = false;
    },
    retrieveClusterBackupCompleted(taskContext, taskResult) {
      this.restore.summary = taskResult.output;
      this.restore.step = "summary";
      this.loading.retrieveClusterBackup = false;
      this.restore.backupPassword = "";
    },
    async restoreCluster() {
      this.error.restoreCluster = "";
      this.loading.restoreCluster = true;
      this.restore.step = "restoringCluster";
      const taskAction = "restore-cluster";
      const eventId = this.getUuid();
      this.restore.progress = 0;
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.restoreClusterAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.restoreClusterCompleted
      );
      this.$root.$on(
        `${taskAction}-progress-${eventId}`,
        this.restoreClusterProgress
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            isProgressNotified: true,
            toastTimeout: 0,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.restoreCluster = this.getErrorMessage(err);
        return;
      }
    },
    restoreClusterProgress(progress) {
      this.restore.progress = progress;
    },
    restoreClusterAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.loading.restoreCluster = false;
      this.error.restoreCluster = this.$t("error.generic_error");
      this.$root.$off(
        `${taskContext.action}-progress-${taskContext.extra.eventId}`
      );
    },
    restoreClusterCompleted(taskContext) {
      this.loading.restoreCluster = false;
      this.$root.$off(
        `${taskContext.action}-progress-${taskContext.extra.eventId}`
      );
      if (this.restore.summary.single_node_cluster) {
        this.readBackupRepositories();
      } else {
        this.getClusterStatus();
      }
    },
    async readBackupRepositories() {
      this.error.readBackupRepositories = "";
      this.loading.readBackupRepositories = true;
      const taskAction = "read-backup-repositories";
      this.$root.$off(taskAction + "-aborted");
      this.$root.$once(
        taskAction + "-aborted",
        this.readBackupRepositoriesAborted
      );
      this.$root.$off(taskAction + "-completed");
      this.$root.$once(
        taskAction + "-completed",
        this.readBackupRepositoriesCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            toastTimeout: 0,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.readBackupRepositories = this.getErrorMessage(err);
        return;
      }
    },
    readBackupRepositoriesAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.loading.readBackupRepositories = false;
    },
    readBackupRepositoriesCompleted(taskContext, taskResult) {
      let instances = taskResult.output;
      instances.sort(this.sortByProperty("timestamp")).reverse();
      this.restore.instances = instances;
      if (this.restore.instances.length) {
        this.restore.step = "apps";
        this.listCoreModules();
      } else {
        this.getClusterStatus();
      }
      this.loading.readBackupRepositories = false;
    },
    onSelectInstances(selectedInstances) {
      this.restore.selectedInstances = selectedInstances;
    },
    showSkipRestoreAppsModal() {
      this.restore.isShownSkipRestoreAppsModal = true;
    },
    hideSkipRestoreAppsModal() {
      this.restore.isShownSkipRestoreAppsModal = false;
    },
    prepareRestoreModulesData() {
      const data = [];
      for (const i of this.restore.selectedInstances) {
        const instance = {
          repository: i.repository_id,
          path: i.path,
          snapshot: "",
          node: 1,
        };
        data.push(instance);
      }
      return data;
    },
    async restoreModules() {
      const inputData = this.prepareRestoreModulesData();
      this.restore.progress = 0;
      this.error.restoreModules = "";
      this.loading.restoreModules = true;
      const taskAction = "restore-modules";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.restoreModulesAborted
      );
      this.$root.$once(
        `${taskAction}-validation-ok-${eventId}`,
        this.restoreModulesValidationOk
      );
      this.$root.$once(
        `${taskAction}-validation-failed-${eventId}`,
        this.restoreModulesValidationFailed
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.restoreModulesCompleted
      );
      this.$root.$on(
        `${taskAction}-progress-${eventId}`,
        this.restoreModulesProgress
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: inputData,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            isProgressNotified: true,
            toastTimeout: 0,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.restoreModules = this.getErrorMessage(err);
        return;
      }
    },
    restoreModulesProgress(progress) {
      this.restore.progress = progress;
    },
    restoreModulesAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.loading.restoreModules = false;
      this.error.restoreModules = this.$t("error.some_apps_cannot_be_restored");
      this.$root.$off(
        `${taskContext.action}-progress-${taskContext.extra.eventId}`
      );
    },
    restoreModulesValidationOk() {
      this.restore.step = "restoringApps";
    },
    restoreModulesValidationFailed() {
      this.loading.restoreModules = false;
      this.error.restoreModules = this.$t("error.some_apps_cannot_be_restored");
    },
    restoreModulesCompleted(taskContext) {
      this.$root.$emit("reloadAppDrawer");
      this.$root.$off(
        `${taskContext.action}-progress-${taskContext.extra.eventId}`
      );
      this.goToBackupRestore();
    },
    skipRestoreApps() {
      this.getClusterStatus();
    },
    goToBackupRestore() {
      this.setClusterInitializedInStore(true);
      this.$root.$emit("clusterInitialized");
      this.$router.push({
        path: "/backup",
        query: { isShownAddRepoModal: false, view: "restore" },
      });
    },
    goToLogs() {
      this.setClusterInitializedInStore(true);
      this.$root.$emit("clusterInitialized");
      this.$router.push({
        path: "/system-logs",
        query: {
          context: "node",
          selectedNodeId: "1",
          autoStartSearch: true,
        },
      });
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../styles/carbon-utils";
.welcome-grid {
  max-width: 56rem;
}
.bx--form .bx--form-item {
  margin-bottom: $spacing-06;
}
.file-uploader {
  margin-bottom: 0 !important;
}
@media (max-width: $breakpoint-medium) {
  .footer-buttons.bx--btn-set .bx--btn {
    max-width: 9rem;
  }
}
</style>
⋮----
<style lang="scss">
@import "../styles/carbon-utils";
.join-code textarea {
  min-height: 5rem;
}
.validation-failed .bx--file__selected-file {
  outline: 2px solid $danger-01;
  outline-offset: -2px;
}
.initialize-cluster .welcome {
  margin-top: 2rem;
  margin-bottom: 4rem;
  display: flex;
  align-items: flex-end;
  justify-content: space-between;
}
.initialize-cluster .tile-description {
  color: $text-02;
}
.initialize-cluster .footer-buttons {
  display: flex;
  justify-content: flex-end;
  margin-top: $spacing-07;
  .cv-button {
    position: relative;
    top: $spacing-05;
    left: $spacing-05;
  }
}
</style>
</file>

<file path="core/ui/src/views/Login.vue">
<template>
  <div>
    <div class="bx--grid bx--grid--full-width login-bg">
      <div class="bx--row">
        <div
          class="bx--offset-md-1 bx--col-md-6 bx--offset-lg-4 bx--col-lg-8 bx--offset-xlg-5 bx--col-xlg-6 bx--offset-max-6 bx--col-max-4"
        >
          <div class="test">
            <cv-tile :light="true" class="login-tile">
              <h2 class="login-title">{{ $t("login.title") }}</h2>
              <NsInlineNotification
                v-if="
                  logoutInfo.title && ['username', 'password'].includes(step)
                "
                kind="info"
                :title="logoutInfo.title"
                :description="logoutInfo.description"
                :showCloseButton="true"
                @close="clearLogoutInfo"
              />
              <div v-if="step === 'username'">
                <cv-form @submit.prevent="checkUsername" class="login-form">
                  <cv-text-input
                    :label="$t('login.username')"
                    v-model="username"
                    class="mg-bottom-md"
                    :placeholder="$t('login.username_placeholder')"
                    :invalid-message="error.username"
                    ref="usernameInput"
                    name="username"
                  ></cv-text-input>
                  <cv-checkbox
                    :label="$t('login.remember_username')"
                    class="mg-bottom-md"
                    v-model="rememberUsername"
                    value="checkRememberUsername"
                  />
                  <div class="login-footer">
                    <cv-button
                      kind="primary"
                      :icon="ArrowRight20"
                      class="login-button"
                      >{{ $t("login.continue") }}</cv-button
                    >
                  </div>
                </cv-form>
              </div>
              <div v-else-if="step === 'password'">
                <NsInlineNotification
                  v-if="error.login"
                  kind="error"
                  :title="$t('login.cannot_login')"
                  :description="error.login"
                  :showCloseButton="false"
                />
                <div class="login-as">
                  {{ $t("login.logging_in_as") }}
                  <strong>{{ username }}</strong>
                  <cv-link @click="goToUsername" class="not-you">{{
                    $t("login.not_you")
                  }}</cv-link>
                </div>
                <cv-form @submit.prevent="checkPassword" class="login-form">
                  <cv-text-input
                    v-model="username"
                    name="username"
                    class="hidden"
                  ></cv-text-input>
                  <cv-text-input
                    :label="$t('login.password')"
                    type="password"
                    v-model="password"
                    :placeholder="$t('login.password_placeholder')"
                    :invalid-message="error.password"
                    :password-hide-label="$t('password.hide_password')"
                    :password-show-label="$t('password.show_password')"
                    ref="passwordInput"
                    name="password"
                  ></cv-text-input>
                  <div class="login-footer">
                    <NsButton
                      kind="primary"
                      :icon="ArrowRight20"
                      class="login-button"
                      :loading="loading.login"
                      :disabled="loading.login"
                      >{{ $t("login.login") }}</NsButton
                    >
                  </div>
                </cv-form>
              </div>
              <div v-else-if="step === '2fa'">
                <NsInlineNotification
                  v-if="error.verify2FaCode"
                  kind="error"
                  :title="$t('login.cannot_login')"
                  :description="error.verify2FaCode"
                  :showCloseButton="false"
                />
                <h4>
                  {{ $t("login.2fa_title") }}
                </h4>
                <div class="title-description mg-bottom-lg">
                  {{ $t("login.2fa_description") }}
                </div>
                <cv-form @submit.prevent="check2FaCode" class="login-form">
                  <NsTextInput
                    :label="$t('login.6_digit_code')"
                    v-model.trim="twoFaCode"
                    :invalid-message="error.twoFaCode"
                    :disabled="loading.verify2FaCode"
                    maxlength="6"
                    ref="twoFaCode"
                    class="mg-bottom-xlg"
                  />
                  <cv-accordion ref="accordion">
                    <cv-accordion-item :open="toggleAccordion[0]">
                      <template slot="title">{{
                        $t("login.need_to_reconfigure_2fa")
                      }}</template>
                      <template slot="content">
                        <p class="mg-top-sm">
                          {{ $t("login.setup_key_instructions") }}
                        </p>
                      </template>
                    </cv-accordion-item>
                  </cv-accordion>
                  <div class="login-footer">
                    <NsButton
                      kind="primary"
                      :icon="ArrowRight20"
                      class="login-button"
                      :loading="loading.verify2FaCode"
                      :disabled="loading.verify2FaCode"
                      >{{ $t("login.verify_code") }}</NsButton
                    >
                  </div>
                </cv-form>
              </div>
            </cv-tile>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
⋮----
<h2 class="login-title">{{ $t("login.title") }}</h2>
⋮----
>{{ $t("login.continue") }}</cv-button
⋮----
{{ $t("login.logging_in_as") }}
<strong>{{ username }}</strong>
<cv-link @click="goToUsername" class="not-you">{{
                    $t("login.not_you")
                  }}</cv-link>
⋮----
>{{ $t("login.login") }}</NsButton
⋮----
{{ $t("login.2fa_title") }}
⋮----
{{ $t("login.2fa_description") }}
⋮----
<template slot="title">{{
                        $t("login.need_to_reconfigure_2fa")
                      }}</template>
<template slot="content">
                        <p class="mg-top-sm">
                          {{ $t("login.setup_key_instructions") }}
                        </p>
                      </template>
⋮----
{{ $t("login.setup_key_instructions") }}
⋮----
>{{ $t("login.verify_code") }}</NsButton
⋮----
<script>
import { IconService } from "@nethserver/ns8-ui-lib";
import LoginService from "@/mixins/login";
import { mapState, mapActions } from "vuex";
import to from "await-to-js";
import WebSocketService from "@/mixins/websocket";
import {
  QueryParamService,
  UtilService,
  StorageService,
  PageTitleService,
} from "@nethserver/ns8-ui-lib";
import TwoFaService from "@/mixins/2fa";
export default {
  name: "Login",
  mixins: [
    IconService,
    LoginService,
    StorageService,
    WebSocketService,
    UtilService,
    QueryParamService,
    PageTitleService,
    TwoFaService,
  ],
  pageTitle() {
    return this.$t("login.title");
  },
  data() {
    return {
      username: "",
      password: "",
      rememberUsername: false,
      step: "username",
      jwtToken: "",
      twoFaCode: "",
      error: {
        username: "",
        password: "",
        login: "",
        twoFaCode: "",
      },
      loading: {
        login: false,
        verify2FaCode: false,
      },
    };
  },
  computed: {
    ...mapState(["loggedUser", "logoutInfo"]),
  },
  created() {
    const rememberedUsername = this.getFromStorage("username");
    if (rememberedUsername) {
      this.rememberUsername = true;
      this.username = rememberedUsername;
      this.step = "password";
    }
  },
  mounted() {
    if (this.step === "username") {
      this.focusElement("usernameInput");
    } else {
      this.focusElement("passwordInput");
    }
  },
  methods: {
    ...mapActions(["setLoggedUserInStore", "setLogoutInfoInStore"]),
    checkUsername() {
      this.error.username = "";
      if (!this.username.trim()) {
        this.error.username = this.$t("login.username_required");
        this.focusElement("usernameInput");
      } else {
        this.step = "password";
        this.focusElement("passwordInput");
      }
    },
    async checkPassword() {
      this.clearErrors(this);
      if (!this.password.trim()) {
        this.error.password = this.$t("login.password_required");
        this.focusElement("passwordInput");
      } else {
        this.loading.login = true;
        const [loginError, response] = await to(
          this.executeLogin(this.username, this.password, "")
        );
        this.loading.login = false;
        if (loginError) {
          this.handleLoginError(loginError); // also enable OTP prompt, if 2FA is needed
          return;
        }
        if (this.rememberUsername) {
          this.saveToStorage("username", this.username);
        } else {
          this.deleteFromStorage("username");
        }
        this.jwtToken = response.data.token;
        this.loginSuccessful();
      }
    },
    handleLoginError(error) {
      let errorMessage = this.$t("error.generic_error");
      if (error.response?.data?.code == 401) {
        switch (error.response.data.message) {
          case "incorrect Username or Password":
            errorMessage = this.$t("error.invalid_username_or_password");
            break;
          case "missing OTP value":
            this.check2Fa();
            return;
        }
      } else if (error.message === "Network Error") {
        errorMessage = this.$t("error.network_error");
      }
      this.error.login = errorMessage;
      this.password = "";
      this.focusElement("passwordInput");
    },
    goToUsername() {
      this.step = "username";
      this.username = "";
      this.password = "";
      this.focusElement("usernameInput");
      this.error.login = "";
    },
    clearLogoutInfo() {
      const logoutInfo = {
        title: "",
        description: "",
      };
      this.setLogoutInfoInStore(logoutInfo);
    },
    check2Fa() {
      // Show the OTP input to the user
      this.step = "2fa";
      this.$nextTick(() => {
        this.focusElement("twoFaCode");
      });
    },
    loginSuccessful() {
      const loginInfo = {
        username: this.username,
        token: this.jwtToken,
      };
      this.saveToStorage("loginInfo", loginInfo);
      this.setLoggedUserInStore(this.username);
      const queryParams = this.getQueryParamsForCore();
      if (queryParams.redirect) {
        this.$router.replace(queryParams.redirect);
      } else {
        this.$router.replace("/status");
      }
      this.$root.$emit("login");
    },
    async check2FaCode() {
      if (!this.twoFaCode.trim()) {
        this.error.twoFaCode = this.$t("login.2fa_code_required");
        this.focusElement("twoFaCode");
        return;
      }
      this.loading.verify2FaCode = true;
      const [verify2FaCodeError, response] = await to(
        this.executeLogin(this.username, this.password, this.twoFaCode)
      );
      this.loading.verify2FaCode = false;
      if (verify2FaCodeError) {
        this.handleVerify2FaError(verify2FaCodeError);
        return;
      }
      this.jwtToken = response.data.token;
      this.loginSuccessful();
    },
    handleVerify2FaError(error) {
      let errorMessage = this.$t("error.generic_error");
      if (
        error.response.data?.code == 401 &&
        error.response.data?.message == "OTP check failed"
      ) {
        errorMessage = this.$t("login.incorrect_code");
      } else if (error.message === "Network Error") {
        errorMessage = this.$t("error.network_error");
      }
      this.error.verify2FaCode = errorMessage;
      this.twoFaCode = "";
      this.focusElement("twoFaCode");
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../styles/carbon-utils";
.login-bg {
  height: 100vh;
  background-color: $interactive-02;
}
.login-tile {
  margin-top: 25vh;
  padding-bottom: 0;
  margin-bottom: $spacing-03;
}
.login-title {
  margin-bottom: $spacing-06;
}
.login-form {
  margin-top: $spacing-07;
}
.login-footer {
  display: flex;
  height: 4rem;
  justify-content: flex-end;
  margin-top: $spacing-07;
}
.login-button {
  width: 50%;
  height: 100%;
  margin-right: -1rem;
}
.not-you {
  margin-left: $spacing-03;
}
.hidden {
  display: none;
}
</style>
</file>

<file path="core/ui/src/views/NodeDetail.vue">
<template>
  <div>
    <cv-grid fullWidth>
      <cv-row>
        <cv-column>
          <cv-breadcrumb
            aria-label="breadcrumb"
            :no-trailing-slash="true"
            class="breadcrumb"
          >
            <cv-breadcrumb-item>
              <cv-link to="/nodes">{{ $t("nodes.title") }}</cv-link>
            </cv-breadcrumb-item>
            <cv-breadcrumb-item>
              <span>{{
                nodeLabel
                  ? nodeLabel + " (" + $t("common.node") + " " + nodeId + ")"
                  : $t("common.node") + " " + nodeId
              }}</span>
            </cv-breadcrumb-item>
          </cv-breadcrumb>
        </cv-column>
      </cv-row>
      <cv-row>
        <cv-column class="subpage-title title-and-role">
          <h3 class="title">
            {{
              nodeLabel
                ? nodeLabel + " (" + $t("common.node") + " " + nodeId + ")"
                : $t("common.node") + " " + nodeId
            }}
          </h3>
          <cv-tag
            v-if="isLeader"
            kind="green"
            :label="$t('nodes.leader')"
          ></cv-tag>
          <cv-tag v-else kind="blue" :label="$t('nodes.worker')"></cv-tag>
        </cv-column>
      </cv-row>
      <cv-row v-if="!isOnline">
        <cv-column>
          <NsInlineNotification
            kind="error"
            :title="$t('nodes.node_is_offline')"
            :description="$t('nodes.node_is_offline_description')"
            :showCloseButton="false"
          />
        </cv-column>
      </cv-row>
      <cv-row v-if="error.getClusterStatus">
        <cv-column>
          <NsInlineNotification
            kind="error"
            :title="$t('action.get-cluster-status')"
            :description="error.getClusterStatus"
            :showCloseButton="false"
          />
        </cv-column>
      </cv-row>
      <cv-row v-if="error.listNodes">
        <cv-column>
          <NsInlineNotification
            kind="error"
            :title="$t('action.list-nodes')"
            :description="error.listNodes"
            :showCloseButton="false"
          />
        </cv-column>
      </cv-row>
      <cv-row v-if="error.listAlerts">
        <cv-column>
          <NsInlineNotification
            kind="error"
            :title="$t('action.list-alerts')"
            :description="error.listAlerts"
            :showCloseButton="false"
          />
        </cv-column>
      </cv-row>
      <cv-row>
        <cv-column>
          <h4 class="mg-bottom-md">
            {{ $t("node_detail.general_information") }}
          </h4>
        </cv-column>
      </cv-row>
      <cv-row>
        <cv-column>
          <div class="card-grid grid-cols-1 md:grid-cols-2 2xl:grid-cols-4">
            <cv-tile :light="true">
              <h4 class="mg-bottom-lg">{{ $t("node_detail.overview") }}</h4>
              <template v-if="loading.listNodes">
                <cv-skeleton-text
                  :paragraph="true"
                  :line-count="7"
                ></cv-skeleton-text>
              </template>
              <template v-else>
                <div class="mg-bottom-lg">
                  <span class="label">{{ $t("node_detail.node_id") }}</span>
                  <span>{{
                    loading.listNodes ? "-" : nodeStatus.node_id
                  }}</span>
                </div>
                <template v-if="!loading.listNodes && nodeStatus.fqdn">
                  <div class="mg-bottom-lg long-text-row">
                    <span class="label">{{ $t("node_detail.fqdn") }}</span>
                    <span class="long-text">{{ nodeStatus.fqdn }}</span>
                  </div>
                </template>
                <template v-if="!loading.listNodes && nodeStatus.app_count">
                  <div class="mg-bottom-lg">
                    <span class="label">{{
                      $t("node_detail.applications_count")
                    }}</span>
                    <cv-link @click.prevent="goToApplications">
                      {{ nodeStatus.app_count }}
                    </cv-link>
                  </div>
                </template>
                <template
                  v-if="
                    !loading.listNodes && nodeStatus.network_interface_count
                  "
                >
                  <div class="mg-bottom-lg">
                    <span class="label">{{
                      $t("node_detail.network_interface_count")
                    }}</span>
                    <cv-link @click.prevent="goToFirewall">
                      {{ nodeStatus.network_interface_count }}
                    </cv-link>
                  </div>
                </template>
              </template>
            </cv-tile>
            <cv-tile :light="true">
              <h4 class="mg-bottom-lg">{{ $t("node_detail.vpn") }}</h4>
              <template v-if="loading.listNodes">
                <cv-skeleton-text
                  :paragraph="true"
                  :line-count="7"
                ></cv-skeleton-text>
              </template>
              <template v-else>
                <template v-if="!loading.clusterStatus && vpnInfo.endpoint">
                  <div class="mg-bottom-lg long-text-row">
                    <span class="label">{{ $t("node_detail.endpoint") }}</span>
                    <span class="long-text">{{ vpnInfo.endpoint }}</span>
                  </div>
                </template>
                <div class="mg-bottom-lg">
                  <span class="label">{{ $t("node_detail.ip_address") }}</span>
                  <span>{{
                    loading.clusterStatus ? "-" : vpnInfo.ip_address
                  }}</span>
                </div>
                <template
                  v-if="!loading.listNodes && nodeStatus.vpn_listen_port"
                >
                  <div class="mg-bottom-lg">
                    <span class="label">{{
                      $t("node_detail.listen_port")
                    }}</span>
                    <span>{{ nodeStatus.vpn_listen_port }}</span>
                  </div>
                </template>
              </template>
            </cv-tile>
            <cv-tile class="md:col-span-2" :light="true">
              <h4 class="mg-bottom-lg">{{ $t("node_detail.alerts") }}</h4>
              <cv-row>
                <cv-column>
                  <NsDataTable
                    :allRows="alerts"
                    :columns="i18nTableColumnsAlarms"
                    :rawColumns="tableColumnsAlarms"
                    :sortable="true"
                    :pageSizes="[5]"
                    :overflow-menu="true"
                    :isSearchable="false"
                    :searchClearLabel="$t('common.clear_search')"
                    :noSearchResultsLabel="$t('common.no_search_results')"
                    :noSearchResultsDescription="
                      $t('common.no_search_results_description')
                    "
                    :isLoading="loading.listAlerts"
                    :skeletonRows="3"
                    :isErrorShown="!!error.listAlerts"
                    :errorTitle="$t('action.list-alerts')"
                    :errorDescription="error.listAlerts"
                    :itemsPerPageLabel="$t('pagination.items_per_page')"
                    :rangeOfTotalItemsLabel="
                      $t('pagination.range_of_total_items')
                    "
                    :ofTotalPagesLabel="$t('pagination.of_total_pages')"
                    :backwardText="$t('pagination.previous_page')"
                    :forwardText="$t('pagination.next_page')"
                    :pageNumberLabel="$t('pagination.page_number')"
                    @updatePage="tablePage = $event"
                  >
                    <template slot="empty-state">
                      <template v-if="!alerts.length">
                        <NsEmptyState :title="$t('node_detail.no_alerts')">
                          <template #pictogram>
                            <CircleCheckPictogram />
                          </template>
                        </NsEmptyState>
                      </template>
                    </template>
                    <template slot="data">
                      <cv-data-table-row
                        v-for="(row, rowIndex) in tablePage"
                        :key="`${rowIndex}`"
                        :value="`${rowIndex}`"
                      >
                        <cv-data-table-cell class="alerts-cell">
                          <span class="alerts-content">
                            <NsSvg
                              v-if="row.labels.severity === 'warning'"
                              :svg="Warning16"
                              class="icon ns-warning"
                            />
                            <NsSvg
                              v-else-if="row.labels.severity === 'critical'"
                              :svg="ErrorFilled16"
                              class="icon ns-error"
                            >
                            </NsSvg>
                            <NsSvg
                              v-else
                              :svg="InformationFilled16"
                              class="icon ns-info"
                            />
                            <span class="alerts-text">{{ row.summary }}</span>
                          </span>
                        </cv-data-table-cell>
                        <cv-data-table-cell class="alerts-cell">
                          <span class="alerts-content">
                            <span class="alerts-text">
                              {{ formatAlertDate(row.startsAt) }}
                            </span>
                          </span>
                        </cv-data-table-cell>
                      </cv-data-table-row>
                    </template>
                  </NsDataTable>
                </cv-column>
              </cv-row>
            </cv-tile>
          </div>
        </cv-column>
      </cv-row>
      <cv-row>
        <cv-column>
          <h4 class="mg-bottom-md">{{ $t("node_detail.system") }}</h4>
        </cv-column>
      </cv-row>
      <cv-row>
        <cv-column>
          <div
            class="card-grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 3xl:grid-cols-4"
          >
            <cv-tile :light="true">
              <h4 class="mg-bottom-lg">{{ $t("node_detail.cpu") }}</h4>
              <div class="mg-bottom-sm">
                <span class="label"
                  >{{ $t("node_detail.average_cpu_usage") }}
                  <cv-interactive-tooltip
                    alignment="start"
                    direction="bottom"
                    class="info"
                  >
                    <template slot="trigger">
                      <Information16 />
                    </template>
                    <template slot="content">
                      {{ $t("node_detail.average_cpu_usage_tooltip") }}
                    </template>
                  </cv-interactive-tooltip>
                </span>
                {{ loading.listNodes ? 0 : nodeStatus.cpu.usage }}%
              </div>
              <NsProgressBar
                :value="loading.listNodes ? 0 : nodeStatus.cpu.usage"
                :loading="loading.listNodes"
                :warningThreshold="70"
                :dangerThreshold="90"
                :height="'10px'"
                class="mg-bottom-lg"
                :useHealthyColor="false"
              />
              <div class="mg-bottom-lg">
                <span class="label">
                  {{ $t("node_detail.load") }}
                  <cv-interactive-tooltip
                    alignment="start"
                    direction="bottom"
                    class="info"
                  >
                    <template slot="trigger">
                      <Information16 />
                    </template>
                    <template slot="content">
                      {{ $t("nodes.cpu_load_tooltip") }}
                    </template>
                  </cv-interactive-tooltip>
                </span>
                <span v-if="loading.listNodes">- / - / -</span>
                <template v-else>
                  <span
                    :class="{
                      warning:
                        nodeStatus.load['1min'] / (nodeStatus.cpu.count || 1) >
                        5,
                    }"
                  >
                    {{ nodeStatus.load["1min"] }}
                  </span>
                  /
                  <span
                    :class="{
                      warning:
                        nodeStatus.load['5min'] / (nodeStatus.cpu.count || 1) >
                        5,
                    }"
                  >
                    {{ nodeStatus.load["5min"] }}
                  </span>
                  /
                  <span
                    :class="{
                      warning:
                        nodeStatus.load['15min'] / (nodeStatus.cpu.count || 1) >
                        5,
                    }"
                  >
                    {{ nodeStatus.load["15min"] }}
                  </span>
                </template>
              </div>
              <template v-if="!loading.listNodes">
                <template v-if="nodeStatus.cpu.info.length">
                  <span
                    v-if="nodeStatus.cpu.info.count == 1"
                    class="label mg-bottom-xs"
                    >{{ $t("node_detail.core") }}</span
                  >
                  <span v-else class="label mg-bottom-xs">{{
                    $t("node_detail.num_core", {
                      num: nodeStatus.cpu.count,
                    })
                  }}</span>
                  <span
                    >{{ nodeStatus.cpu.info[0].vendor }} -
                    {{ nodeStatus.cpu.info[0].model }}</span
                  >
                </template>
              </template>
            </cv-tile>
            <cv-tile :light="true">
              <h4 class="mg-bottom-lg">{{ $t("node_detail.memory") }}</h4>
              <div class="mg-bottom-sm">
                <span class="label">{{ $t("node_detail.usage") }}</span>
                {{ loading.listNodes ? 0 : nodeStatus.memory.usage }}%
              </div>
              <NsProgressBar
                :value="loading.listNodes ? 0 : nodeStatus.memory.usage"
                :loading="loading.listNodes"
                :warningThreshold="70"
                :dangerThreshold="90"
                :height="'10px'"
                class="mg-bottom-lg"
                :useHealthyColor="false"
              />
              <div class="mg-bottom-lg">
                <span class="label">{{ $t("node_detail.total") }}</span>
                <span>{{
                  loading.listNodes ? "-" : nodeStatus.memory.total | byteFormat
                }}</span>
              </div>
              <div class="mg-bottom-lg">
                <span class="label">{{ $t("node_detail.used") }}</span>
                <span>{{
                  loading.listNodes ? "-" : nodeStatus.memory.used | byteFormat
                }}</span>
              </div>
              <div class="mg-bottom-lg">
                <span class="label">{{ $t("node_detail.available") }}</span>
                <span>{{
                  loading.listNodes ? "-" : nodeStatus.memory.free | byteFormat
                }}</span>
              </div>
            </cv-tile>
            <cv-tile :light="true">
              <h4 class="mg-bottom-lg">{{ $t("node_detail.swap") }}</h4>
              <div class="mg-bottom-sm">
                <span class="label">{{ $t("node_detail.usage") }}</span>
                {{ loading.listNodes ? 0 : nodeStatus.swap.usage }}%
              </div>
              <NsProgressBar
                :value="
                  loading.listNodes || Number.isNaN(nodeStatus.swap.usage)
                    ? '-'
                    : nodeStatus.swap.usage
                "
                :loading="loading.listNodes"
                :warningThreshold="70"
                :dangerThreshold="90"
                :height="'10px'"
                class="mg-bottom-lg"
                :useHealthyColor="false"
              />
              <div class="mg-bottom-lg">
                <span class="label">{{ $t("node_detail.total") }}</span>
                <span>{{
                  loading.listNodes ? "-" : nodeStatus.swap.total | byteFormat
                }}</span>
              </div>
              <div class="mg-bottom-lg">
                <span class="label">{{ $t("node_detail.used") }}</span>
                <span>{{
                  loading.listNodes ? "-" : nodeStatus.swap.used | byteFormat
                }}</span>
              </div>
              <div class="mg-bottom-lg">
                <span class="label">{{ $t("node_detail.free") }}</span>
                <span>{{
                  loading.listNodes ? "-" : nodeStatus.swap.free | byteFormat
                }}</span>
              </div>
            </cv-tile>
          </div>
        </cv-column>
      </cv-row>
      <cv-row>
        <cv-column>
          <h4 class="mg-bottom-lg">{{ $t("node_detail.disks") }}</h4>
        </cv-column>
      </cv-row>
      <cv-row class="mb-6">
        <cv-column>
          <cv-tile :light="true">
            <NsDataTable
              :allRows="nodeStatus.disks"
              :columns="i18nTableColumnsDisks"
              :rawColumns="tableColumnsDisks"
              :sortable="true"
              :pageSizes="[5, 10, 15, 20]"
              :overflow-menu="true"
              :isSearchable="false"
              :searchClearLabel="$t('common.clear_search')"
              :noSearchResultsLabel="$t('common.no_search_results')"
              :noSearchResultsDescription="
                $t('common.no_search_results_description')
              "
              :isLoading="loading.listNodes"
              :skeletonRows="5"
              :isErrorShown="!!error.listNodes"
              :errorTitle="$t('action.list-nodes')"
              :errorDescription="error.listNodes"
              :itemsPerPageLabel="$t('pagination.items_per_page')"
              :rangeOfTotalItemsLabel="$t('pagination.range_of_total_items')"
              :ofTotalPagesLabel="$t('pagination.of_total_pages')"
              :backwardText="$t('pagination.previous_page')"
              :forwardText="$t('pagination.next_page')"
              :pageNumberLabel="$t('pagination.page_number')"
              @updatePage="tablePageDisks = $event"
            >
              <template slot="empty-state">
                <template v-if="!nodeStatus.disks.length">
                  <NsEmptyState :title="$t('node_detail.no_disks_info')">
                    <template #pictogram>
                      <ExclamationMarkPictogram />
                    </template>
                  </NsEmptyState>
                </template>
              </template>
              <template slot="data">
                <cv-data-table-row
                  v-for="(row, rowIndex) in tablePageDisks"
                  :key="`${rowIndex}`"
                  :value="`${rowIndex}`"
                >
                  <cv-data-table-cell>
                    {{ row.device }}
                  </cv-data-table-cell>
                  <cv-data-table-cell>
                    {{ row.mountpoint }}
                  </cv-data-table-cell>
                  <cv-data-table-cell>
                    {{ row.fstype }}
                  </cv-data-table-cell>
                  <cv-data-table-cell>
                    {{ row.total | byteFormat }}
                  </cv-data-table-cell>
                  <cv-data-table-cell>
                    {{ row.used | byteFormat }} ({{ row.usage }}%)
                    <NsProgressBar
                      :value="row.usage"
                      :warningThreshold="70"
                      :dangerThreshold="90"
                      :loading="loading.listNodes"
                      :useHealthyColor="false"
                    />
                  </cv-data-table-cell>
                  <cv-data-table-cell>
                    {{ row.free | byteFormat }}
                  </cv-data-table-cell>
                </cv-data-table-row>
              </template>
            </NsDataTable>
          </cv-tile>
        </cv-column>
      </cv-row>
    </cv-grid>
  </div>
</template>
⋮----
<cv-link to="/nodes">{{ $t("nodes.title") }}</cv-link>
⋮----
<span>{{
                nodeLabel
                  ? nodeLabel + " (" + $t("common.node") + " " + nodeId + ")"
                  : $t("common.node") + " " + nodeId
              }}</span>
⋮----
{{
              nodeLabel
                ? nodeLabel + " (" + $t("common.node") + " " + nodeId + ")"
                : $t("common.node") + " " + nodeId
            }}
⋮----
{{ $t("node_detail.general_information") }}
⋮----
<h4 class="mg-bottom-lg">{{ $t("node_detail.overview") }}</h4>
<template v-if="loading.listNodes">
                <cv-skeleton-text
                  :paragraph="true"
                  :line-count="7"
                ></cv-skeleton-text>
              </template>
<template v-else>
                <div class="mg-bottom-lg">
                  <span class="label">{{ $t("node_detail.node_id") }}</span>
                  <span>{{
                    loading.listNodes ? "-" : nodeStatus.node_id
                  }}</span>
                </div>
                <template v-if="!loading.listNodes && nodeStatus.fqdn">
                  <div class="mg-bottom-lg long-text-row">
                    <span class="label">{{ $t("node_detail.fqdn") }}</span>
                    <span class="long-text">{{ nodeStatus.fqdn }}</span>
                  </div>
                </template>
                <template v-if="!loading.listNodes && nodeStatus.app_count">
                  <div class="mg-bottom-lg">
                    <span class="label">{{
                      $t("node_detail.applications_count")
                    }}</span>
                    <cv-link @click.prevent="goToApplications">
                      {{ nodeStatus.app_count }}
                    </cv-link>
                  </div>
                </template>
                <template
                  v-if="
                    !loading.listNodes && nodeStatus.network_interface_count
                  "
                >
                  <div class="mg-bottom-lg">
                    <span class="label">{{
                      $t("node_detail.network_interface_count")
                    }}</span>
                    <cv-link @click.prevent="goToFirewall">
                      {{ nodeStatus.network_interface_count }}
                    </cv-link>
                  </div>
                </template>
              </template>
⋮----
<span class="label">{{ $t("node_detail.node_id") }}</span>
<span>{{
                    loading.listNodes ? "-" : nodeStatus.node_id
                  }}</span>
⋮----
<template v-if="!loading.listNodes && nodeStatus.fqdn">
                  <div class="mg-bottom-lg long-text-row">
                    <span class="label">{{ $t("node_detail.fqdn") }}</span>
                    <span class="long-text">{{ nodeStatus.fqdn }}</span>
                  </div>
                </template>
⋮----
<span class="label">{{ $t("node_detail.fqdn") }}</span>
<span class="long-text">{{ nodeStatus.fqdn }}</span>
⋮----
<template v-if="!loading.listNodes && nodeStatus.app_count">
                  <div class="mg-bottom-lg">
                    <span class="label">{{
                      $t("node_detail.applications_count")
                    }}</span>
                    <cv-link @click.prevent="goToApplications">
                      {{ nodeStatus.app_count }}
                    </cv-link>
                  </div>
                </template>
⋮----
<span class="label">{{
                      $t("node_detail.applications_count")
                    }}</span>
⋮----
{{ nodeStatus.app_count }}
⋮----
<template
                  v-if="
                    !loading.listNodes && nodeStatus.network_interface_count
                  "
                >
                  <div class="mg-bottom-lg">
                    <span class="label">{{
                      $t("node_detail.network_interface_count")
                    }}</span>
                    <cv-link @click.prevent="goToFirewall">
                      {{ nodeStatus.network_interface_count }}
                    </cv-link>
                  </div>
                </template>
⋮----
<span class="label">{{
                      $t("node_detail.network_interface_count")
                    }}</span>
⋮----
{{ nodeStatus.network_interface_count }}
⋮----
<h4 class="mg-bottom-lg">{{ $t("node_detail.vpn") }}</h4>
<template v-if="loading.listNodes">
                <cv-skeleton-text
                  :paragraph="true"
                  :line-count="7"
                ></cv-skeleton-text>
              </template>
<template v-else>
                <template v-if="!loading.clusterStatus && vpnInfo.endpoint">
                  <div class="mg-bottom-lg long-text-row">
                    <span class="label">{{ $t("node_detail.endpoint") }}</span>
                    <span class="long-text">{{ vpnInfo.endpoint }}</span>
                  </div>
                </template>
                <div class="mg-bottom-lg">
                  <span class="label">{{ $t("node_detail.ip_address") }}</span>
                  <span>{{
                    loading.clusterStatus ? "-" : vpnInfo.ip_address
                  }}</span>
                </div>
                <template
                  v-if="!loading.listNodes && nodeStatus.vpn_listen_port"
                >
                  <div class="mg-bottom-lg">
                    <span class="label">{{
                      $t("node_detail.listen_port")
                    }}</span>
                    <span>{{ nodeStatus.vpn_listen_port }}</span>
                  </div>
                </template>
              </template>
⋮----
<template v-if="!loading.clusterStatus && vpnInfo.endpoint">
                  <div class="mg-bottom-lg long-text-row">
                    <span class="label">{{ $t("node_detail.endpoint") }}</span>
                    <span class="long-text">{{ vpnInfo.endpoint }}</span>
                  </div>
                </template>
⋮----
<span class="label">{{ $t("node_detail.endpoint") }}</span>
<span class="long-text">{{ vpnInfo.endpoint }}</span>
⋮----
<span class="label">{{ $t("node_detail.ip_address") }}</span>
<span>{{
                    loading.clusterStatus ? "-" : vpnInfo.ip_address
                  }}</span>
⋮----
<template
                  v-if="!loading.listNodes && nodeStatus.vpn_listen_port"
                >
                  <div class="mg-bottom-lg">
                    <span class="label">{{
                      $t("node_detail.listen_port")
                    }}</span>
                    <span>{{ nodeStatus.vpn_listen_port }}</span>
                  </div>
                </template>
⋮----
<span class="label">{{
                      $t("node_detail.listen_port")
                    }}</span>
<span>{{ nodeStatus.vpn_listen_port }}</span>
⋮----
<h4 class="mg-bottom-lg">{{ $t("node_detail.alerts") }}</h4>
⋮----
<template slot="empty-state">
                      <template v-if="!alerts.length">
                        <NsEmptyState :title="$t('node_detail.no_alerts')">
                          <template #pictogram>
                            <CircleCheckPictogram />
                          </template>
                        </NsEmptyState>
                      </template>
                    </template>
⋮----
<template v-if="!alerts.length">
                        <NsEmptyState :title="$t('node_detail.no_alerts')">
                          <template #pictogram>
                            <CircleCheckPictogram />
                          </template>
                        </NsEmptyState>
                      </template>
⋮----
<template #pictogram>
                            <CircleCheckPictogram />
                          </template>
⋮----
<template slot="data">
                      <cv-data-table-row
                        v-for="(row, rowIndex) in tablePage"
                        :key="`${rowIndex}`"
                        :value="`${rowIndex}`"
                      >
                        <cv-data-table-cell class="alerts-cell">
                          <span class="alerts-content">
                            <NsSvg
                              v-if="row.labels.severity === 'warning'"
                              :svg="Warning16"
                              class="icon ns-warning"
                            />
                            <NsSvg
                              v-else-if="row.labels.severity === 'critical'"
                              :svg="ErrorFilled16"
                              class="icon ns-error"
                            >
                            </NsSvg>
                            <NsSvg
                              v-else
                              :svg="InformationFilled16"
                              class="icon ns-info"
                            />
                            <span class="alerts-text">{{ row.summary }}</span>
                          </span>
                        </cv-data-table-cell>
                        <cv-data-table-cell class="alerts-cell">
                          <span class="alerts-content">
                            <span class="alerts-text">
                              {{ formatAlertDate(row.startsAt) }}
                            </span>
                          </span>
                        </cv-data-table-cell>
                      </cv-data-table-row>
                    </template>
⋮----
<span class="alerts-text">{{ row.summary }}</span>
⋮----
{{ formatAlertDate(row.startsAt) }}
⋮----
<h4 class="mg-bottom-md">{{ $t("node_detail.system") }}</h4>
⋮----
<h4 class="mg-bottom-lg">{{ $t("node_detail.cpu") }}</h4>
⋮----
>{{ $t("node_detail.average_cpu_usage") }}
⋮----
<template slot="trigger">
                      <Information16 />
                    </template>
<template slot="content">
                      {{ $t("node_detail.average_cpu_usage_tooltip") }}
                    </template>
⋮----
{{ $t("node_detail.average_cpu_usage_tooltip") }}
⋮----
{{ loading.listNodes ? 0 : nodeStatus.cpu.usage }}%
⋮----
{{ $t("node_detail.load") }}
⋮----
<template slot="trigger">
                      <Information16 />
                    </template>
<template slot="content">
                      {{ $t("nodes.cpu_load_tooltip") }}
                    </template>
⋮----
{{ $t("nodes.cpu_load_tooltip") }}
⋮----
<template v-else>
                  <span
                    :class="{
                      warning:
                        nodeStatus.load['1min'] / (nodeStatus.cpu.count || 1) >
                        5,
                    }"
                  >
                    {{ nodeStatus.load["1min"] }}
                  </span>
                  /
                  <span
                    :class="{
                      warning:
                        nodeStatus.load['5min'] / (nodeStatus.cpu.count || 1) >
                        5,
                    }"
                  >
                    {{ nodeStatus.load["5min"] }}
                  </span>
                  /
                  <span
                    :class="{
                      warning:
                        nodeStatus.load['15min'] / (nodeStatus.cpu.count || 1) >
                        5,
                    }"
                  >
                    {{ nodeStatus.load["15min"] }}
                  </span>
                </template>
⋮----
{{ nodeStatus.load["1min"] }}
⋮----
{{ nodeStatus.load["5min"] }}
⋮----
{{ nodeStatus.load["15min"] }}
⋮----
<template v-if="!loading.listNodes">
                <template v-if="nodeStatus.cpu.info.length">
                  <span
                    v-if="nodeStatus.cpu.info.count == 1"
                    class="label mg-bottom-xs"
                    >{{ $t("node_detail.core") }}</span
                  >
                  <span v-else class="label mg-bottom-xs">{{
                    $t("node_detail.num_core", {
                      num: nodeStatus.cpu.count,
                    })
                  }}</span>
                  <span
                    >{{ nodeStatus.cpu.info[0].vendor }} -
                    {{ nodeStatus.cpu.info[0].model }}</span
                  >
                </template>
              </template>
⋮----
<template v-if="nodeStatus.cpu.info.length">
                  <span
                    v-if="nodeStatus.cpu.info.count == 1"
                    class="label mg-bottom-xs"
                    >{{ $t("node_detail.core") }}</span
                  >
                  <span v-else class="label mg-bottom-xs">{{
                    $t("node_detail.num_core", {
                      num: nodeStatus.cpu.count,
                    })
                  }}</span>
                  <span
                    >{{ nodeStatus.cpu.info[0].vendor }} -
                    {{ nodeStatus.cpu.info[0].model }}</span
                  >
                </template>
⋮----
>{{ $t("node_detail.core") }}</span
⋮----
<span v-else class="label mg-bottom-xs">{{
                    $t("node_detail.num_core", {
                      num: nodeStatus.cpu.count,
                    })
                  }}</span>
⋮----
>{{ nodeStatus.cpu.info[0].vendor }} -
{{ nodeStatus.cpu.info[0].model }}</span
⋮----
<h4 class="mg-bottom-lg">{{ $t("node_detail.memory") }}</h4>
⋮----
<span class="label">{{ $t("node_detail.usage") }}</span>
{{ loading.listNodes ? 0 : nodeStatus.memory.usage }}%
⋮----
<span class="label">{{ $t("node_detail.total") }}</span>
<span>{{
                  loading.listNodes ? "-" : nodeStatus.memory.total | byteFormat
                }}</span>
⋮----
<span class="label">{{ $t("node_detail.used") }}</span>
<span>{{
                  loading.listNodes ? "-" : nodeStatus.memory.used | byteFormat
                }}</span>
⋮----
<span class="label">{{ $t("node_detail.available") }}</span>
<span>{{
                  loading.listNodes ? "-" : nodeStatus.memory.free | byteFormat
                }}</span>
⋮----
<h4 class="mg-bottom-lg">{{ $t("node_detail.swap") }}</h4>
⋮----
<span class="label">{{ $t("node_detail.usage") }}</span>
{{ loading.listNodes ? 0 : nodeStatus.swap.usage }}%
⋮----
<span class="label">{{ $t("node_detail.total") }}</span>
<span>{{
                  loading.listNodes ? "-" : nodeStatus.swap.total | byteFormat
                }}</span>
⋮----
<span class="label">{{ $t("node_detail.used") }}</span>
<span>{{
                  loading.listNodes ? "-" : nodeStatus.swap.used | byteFormat
                }}</span>
⋮----
<span class="label">{{ $t("node_detail.free") }}</span>
<span>{{
                  loading.listNodes ? "-" : nodeStatus.swap.free | byteFormat
                }}</span>
⋮----
<h4 class="mg-bottom-lg">{{ $t("node_detail.disks") }}</h4>
⋮----
<template slot="empty-state">
                <template v-if="!nodeStatus.disks.length">
                  <NsEmptyState :title="$t('node_detail.no_disks_info')">
                    <template #pictogram>
                      <ExclamationMarkPictogram />
                    </template>
                  </NsEmptyState>
                </template>
              </template>
⋮----
<template v-if="!nodeStatus.disks.length">
                  <NsEmptyState :title="$t('node_detail.no_disks_info')">
                    <template #pictogram>
                      <ExclamationMarkPictogram />
                    </template>
                  </NsEmptyState>
                </template>
⋮----
<template #pictogram>
                      <ExclamationMarkPictogram />
                    </template>
⋮----
<template slot="data">
                <cv-data-table-row
                  v-for="(row, rowIndex) in tablePageDisks"
                  :key="`${rowIndex}`"
                  :value="`${rowIndex}`"
                >
                  <cv-data-table-cell>
                    {{ row.device }}
                  </cv-data-table-cell>
                  <cv-data-table-cell>
                    {{ row.mountpoint }}
                  </cv-data-table-cell>
                  <cv-data-table-cell>
                    {{ row.fstype }}
                  </cv-data-table-cell>
                  <cv-data-table-cell>
                    {{ row.total | byteFormat }}
                  </cv-data-table-cell>
                  <cv-data-table-cell>
                    {{ row.used | byteFormat }} ({{ row.usage }}%)
                    <NsProgressBar
                      :value="row.usage"
                      :warningThreshold="70"
                      :dangerThreshold="90"
                      :loading="loading.listNodes"
                      :useHealthyColor="false"
                    />
                  </cv-data-table-cell>
                  <cv-data-table-cell>
                    {{ row.free | byteFormat }}
                  </cv-data-table-cell>
                </cv-data-table-row>
              </template>
⋮----
{{ row.device }}
⋮----
{{ row.mountpoint }}
⋮----
{{ row.fstype }}
⋮----
{{ row.total | byteFormat }}
⋮----
{{ row.used | byteFormat }} ({{ row.usage }}%)
⋮----
{{ row.free | byteFormat }}
⋮----
<script>
import {
  QueryParamService,
  UtilService,
  TaskService,
  IconService,
  DateTimeService,
  PageTitleService,
} from "@nethserver/ns8-ui-lib";
import to from "await-to-js";
import Information16 from "@carbon/icons-vue/es/information/16";
import { mapActions } from "vuex";
export default {
  name: "NodeDetail",
  components: { Information16 },
  mixins: [
    TaskService,
    UtilService,
    IconService,
    QueryParamService,
    DateTimeService,
    PageTitleService,
  ],
  pageTitle() {
    return this.$t("node_detail.title");
  },
  data() {
    return {
      q: {},
      NODE_STATUS_TIME_INTERVAL: 30000,
      CLUSTER_STATUS_TIME_INTERVAL: 30000,
      LAST_SEEN_WARNING_TH: 5 * 60 * 1000,
      nodeId: "",
      nodeStatus: {
        cpu: {},
        load: {},
        memory: {},
        swap: {},
        disks: [],
      },
      alerts: [],
      listNodesInterval: null,
      listAlertsInterval: null,
      clusterStatusInterval: null,
      isLeader: false,
      vpnInfo: {},
      nodeLabel: "-",
      isOnline: true,
      loading: {
        listNodes: true,
        clusterStatus: true,
        listAlerts: true,
      },
      error: {
        getClusterStatus: "",
        listNodes: "",
        listAlerts: "",
      },
      tablePage: [],
      tablePageDisks: [],
      tableColumnsAlarms: ["summary", "startsAt"],
      tableColumnsDisks: [
        "device",
        "mountpoint",
        "fstype",
        "total",
        "used",
        "free",
      ],
    };
  },
  computed: {
    i18nTableColumnsAlarms() {
      return this.tableColumnsAlarms.map((column) => {
        return this.$t("node_detail.col_" + column);
      });
    },
    i18nTableColumnsDisks() {
      return this.tableColumnsDisks.map((column) => {
        return this.$t("node_detail.col_" + column);
      });
    },
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.watchQueryData(vm);
      vm.queryParamsToDataForCore(vm, to.query);
    });
  },
  beforeRouteUpdate(to, from, next) {
    this.queryParamsToDataForCore(this, to.query);
    next();
  },
  created() {
    this.nodeId = this.$route.params.nodeId;
    this.getClusterStatus();
    this.listNodes();
    this.listAlerts();
    this.listNodesInterval = setInterval(
      this.listNodes,
      this.NODE_STATUS_TIME_INTERVAL
    );
    this.listAlertsInterval = setInterval(
      this.listAlerts,
      this.NODE_STATUS_TIME_INTERVAL
    );
    this.clusterStatusInterval = setInterval(
      this.getClusterStatus,
      this.CLUSTER_STATUS_TIME_INTERVAL
    );
  },
  beforeDestroy() {
    clearInterval(this.listNodesInterval);
    clearInterval(this.listAlertsInterval);
    clearInterval(this.clusterStatusInterval);
  },
  methods: {
    ...mapActions(["setClusterNodesInStore"]),
    goToFirewall() {
      this.$router.push({
        name: "NodeFirewall",
        params: { nodeId: this.nodeId },
      });
    },
    goToApplications() {
      this.$router.push({
        path: "/applications-center",
        query: { node: this.nodeId },
      });
    },
    async listNodes() {
      if (!this.isOnline) {
        return;
      }
      this.error.listNodes = "";
      const taskAction = "list-nodes";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.listNodesAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.listNodesCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.listNodes = this.getErrorMessage(err);
        return;
      }
    },
    listNodesAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.listNodes = this.$t("error.generic_error");
      this.loading.listNodes = false;
    },
    listNodesCompleted(taskContext, taskResult) {
      const nodeStatus = taskResult.output.nodes.find(
        (node) => Number(node.node_id) == Number(this.nodeId)
      );
      nodeStatus.cpu = nodeStatus.cpu || {};
      const usageVal = Number(nodeStatus.cpu.usage);
      nodeStatus.cpu.usage = Number.isFinite(usageVal)
        ? Math.round(usageVal * (usageVal < 1 ? 100 : 1))
        : 0;
      nodeStatus.load = nodeStatus.load || { "1min": 0, "5min": 0, "15min": 0 };
      for (const k of ["1min", "5min", "15min"]) {
        const v = Number(nodeStatus.load[k]);
        nodeStatus.load[k] = Number.isFinite(v) ? v : 0;
      }
      if (!Array.isArray(nodeStatus.cpu.info)) {
        nodeStatus.cpu.info = [
          {
            vendor: nodeStatus.cpu.vendor || "",
            model: nodeStatus.cpu.model_name || nodeStatus.cpu.model || "",
            count: nodeStatus.cpu.count || null,
          },
        ];
      }
      nodeStatus.memory = nodeStatus.memory || {
        used: 0,
        total: 0,
        free: 0,
        usage: 0,
      };
      nodeStatus.swap = nodeStatus.swap || {
        used: 0,
        total: 0,
        free: 0,
        usage: 0,
      };
      nodeStatus.disks = Array.isArray(nodeStatus.disks)
        ? nodeStatus.disks
        : [];
      // Memory %
      if (Number(nodeStatus.memory.total) > 0) {
        nodeStatus.memory.usage = Math.round(
          (nodeStatus.memory.used / nodeStatus.memory.total) * 100
        );
        nodeStatus.memory.free =
          nodeStatus.memory.total - nodeStatus.memory.used;
      } else {
        nodeStatus.memory.usage = 0;
      }
      // Swap %
      if (Number(nodeStatus.swap.total) > 0) {
        // Guard null used
        const swapUsed = Number(nodeStatus.swap.used) || 0;
        nodeStatus.swap.usage = Math.round(
          (swapUsed / nodeStatus.swap.total) * 100
        );
        nodeStatus.swap.free = nodeStatus.swap.total - swapUsed;
      } else {
        nodeStatus.swap.usage = 0;
      }
      // Disk usage %
      for (const disk of nodeStatus.disks) {
        const total = Number(disk.total);
        const used = Number(disk.used);
        if (total > 0 && Number.isFinite(used)) {
          disk.usage = Math.round((used / total) * 100);
        } else {
          disk.usage = 0;
        }
      }
      this.nodeStatus = nodeStatus;
      this.loading.listNodes = false;
    },
    async listAlerts() {
      this.error.listAlerts = "";
      const taskAction = "list-alerts";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.listAlertsAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.listAlertsCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.listAlerts = this.getErrorMessage(err);
        return;
      }
    },
    listAlertsAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.listAlerts = this.$t("error.generic_error");
      this.loading.listAlerts = false;
    },
    getAlertsLocale() {
      const locale = this.$i18n.locale;
      if (locale === "en" || locale === "it") {
        return locale;
      } else {
        return "en";
      }
    },
    listAlertsCompleted(taskContext, taskResult) {
      const filtered = taskResult.output.alerts.filter(
        (alert) => Number(alert.node_id) === Number(this.nodeId)
      );
      const locale = this.getAlertsLocale();
      const simplified = filtered.map((alert) => ({
        description:
          alert.annotations?.[`description_${locale}`] ||
          alert.annotations?.description ||
          alert.description ||
          "",
        summary:
          alert.annotations?.[`summary_${locale}`] ||
          alert.annotations?.summary ||
          alert.summary ||
          "",
        endsAt: alert.endsAt || null,
        fingerprint: alert.fingerprint || null,
        receivers: alert.receivers || [],
        startsAt: alert.startsAt || null,
        status: alert.status || {},
        updatedAt: alert.updatedAt || null,
        generatorURL: alert.generatorURL || "",
        labels: alert.labels || {},
        name: alert.name || alert.labels?.alertname || "",
        category: alert.category || "",
        node_id: alert.node_id ?? Number(alert.labels?.node) ?? null,
        raw: alert, // keep original
      }));
      // Sort newest first
      simplified.sort(this.sortByProperty("startsAt"));
      this.alerts = simplified;
      this.loading.listAlerts = false;
    },
    async getClusterStatus() {
      this.error.getClusterStatus = "";
      const taskAction = "get-cluster-status";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.getClusterStatusAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.getClusterStatusCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.getClusterStatus = this.getErrorMessage(err);
        return;
      }
    },
    getClusterStatusAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.getClusterStatus = this.$t("error.generic_error");
      this.loading.clusterStatus = false;
    },
    getClusterStatusCompleted(taskContext, taskResult) {
      const clusterStatus = taskResult.output;
      const currentNode = clusterStatus.nodes.find(
        (node) => node.id == this.nodeId
      );
      this.isLeader = currentNode.local;
      this.vpnInfo = currentNode.vpn;
      this.nodeLabel = currentNode.ui_name;
      this.isOnline = currentNode.online;
      this.loading.clusterStatus = false;
      const nodes = clusterStatus.nodes.sort(this.sortByProperty("id"));
      this.setClusterNodesInStore(nodes);
    },
    formatAlertDate(dt) {
      if (!dt) return "-";
      const d = new Date(dt);
      if (isNaN(d)) return dt;
      return new Intl.DateTimeFormat(navigator.language, {
        dateStyle: "medium",
        timeStyle: "short",
      }).format(d);
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../styles/carbon-utils";
.label {
  font-weight: bold;
  display: inline-block;
  margin-right: $spacing-03;
}
.warning {
  color: $danger-01;
}
.title-and-role {
  display: flex;
  .title {
    margin-right: $spacing-05;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
.alerts-cell .icon {
  display: inline-block;
  width: 1.2rem;
  height: 1.2rem;
  margin-right: 0.5rem;
  vertical-align: middle;
}
.alerts-cell .alerts-content {
  display: inline-flex;
  align-items: center;
  line-height: 1.2;
}
.alerts-cell .alerts-text {
  line-height: 1.3;
}
@media (max-width: $breakpoint-medium) {
  .title-and-role .title {
    max-width: 15rem;
  }
}
.long-text-row {
  display: flex;
  align-items: baseline;
  flex-wrap: wrap;
}
.long-text {
  white-space: normal;
  word-break: break-all;
  overflow-wrap: anywhere;
  max-width: 100%;
}
</style>
</file>

<file path="core/ui/src/views/NodeFirewall.vue">
<template>
  <div>
    <cv-grid fullWidth>
      <cv-row>
        <cv-column>
          <cv-breadcrumb
            aria-label="breadcrumb"
            :no-trailing-slash="true"
            class="breadcrumb"
            v-if="route.includes('/nodes/')"
          >
            <cv-breadcrumb-item>
              <cv-link to="/nodes">{{ $t("nodes.title") }}</cv-link>
            </cv-breadcrumb-item>
            <cv-breadcrumb-item>
              <span>{{ title }}</span>
            </cv-breadcrumb-item>
          </cv-breadcrumb>
          <cv-breadcrumb
            aria-label="breadcrumb"
            :no-trailing-slash="true"
            class="breadcrumb"
            v-else
          >
            <cv-breadcrumb-item>
              <cv-link to="/settings">{{ $t("common.settings") }}</cv-link>
            </cv-breadcrumb-item>
            <cv-breadcrumb-item>
              <cv-link to="/settings/firewall">{{
                $t("firewall.title")
              }}</cv-link>
            </cv-breadcrumb-item>
            <cv-breadcrumb-item>
              <span>{{ title }}</span>
            </cv-breadcrumb-item>
          </cv-breadcrumb>
        </cv-column>
      </cv-row>
      <cv-row>
        <cv-column class="page-title">
          <h2>
            {{ title }}
          </h2>
        </cv-column>
      </cv-row>
      <cv-row class="landscape-warning">
        <cv-column>
          <NsInlineNotification
            kind="warning"
            :title="$t('common.use_landscape_mode')"
            :description="$t('common.use_landscape_mode_description')"
          />
        </cv-column>
      </cv-row>
      <cv-row v-if="error.getClusterStatus">
        <cv-column>
          <NsInlineNotification
            kind="error"
            :title="$t('action.get-cluster-status')"
            :description="error.getClusterStatus"
            :showCloseButton="false"
          />
        </cv-column>
      </cv-row>
      <cv-row v-if="error.getFirewallStatus">
        <cv-column>
          <NsInlineNotification
            kind="error"
            :title="$t('action.get-firewall-status')"
            :description="error.getFirewallStatus"
            :showCloseButton="false"
          />
        </cv-column>
      </cv-row>
      <cv-row>
        <cv-column>
          <h4 class="mg-bottom-md">
            {{ $t("firewall.public_zone_services") }}
          </h4>
        </cv-column>
      </cv-row>
      <cv-row>
        <cv-column>
          <cv-tile light>
            <cv-row>
              <cv-column>
                <NsDataTable
                  :allRows="servicesAndPorts"
                  :columns="i18nTableColumns"
                  :rawColumns="tableColumns"
                  :sortable="true"
                  :pageSizes="[10, 25, 50, 100]"
                  isSearchable
                  :searchPlaceholder="$t('firewall.search_service_or_port')"
                  :searchClearLabel="$t('common.clear_search')"
                  :noSearchResultsLabel="$t('common.no_search_results')"
                  :noSearchResultsDescription="
                    $t('common.no_search_results_description')
                  "
                  :isLoading="loading.getFirewallStatus"
                  :skeletonRows="5"
                  :isErrorShown="!!error.getFirewallStatus"
                  :errorTitle="$t('action.get-firewall-status')"
                  :errorDescription="error.getFirewallStatus"
                  :itemsPerPageLabel="$t('pagination.items_per_page')"
                  :rangeOfTotalItemsLabel="
                    $t('pagination.range_of_total_items')
                  "
                  :ofTotalPagesLabel="$t('pagination.of_total_pages')"
                  :backwardText="$t('pagination.previous_page')"
                  :forwardText="$t('pagination.next_page')"
                  :pageNumberLabel="$t('pagination.page_number')"
                  @updatePage="tablePage = $event"
                >
                  <template slot="empty-state">
                    <NsEmptyState :title="$t('firewall.no_service')">
                      <template #description>
                        <div>
                          {{ $t("firewall.no_service_description") }}
                        </div>
                      </template>
                    </NsEmptyState>
                  </template>
                  <template slot="data">
                    <cv-data-table-row
                      v-for="(row, rowIndex) in tablePage"
                      :key="`${rowIndex}`"
                      :value="`${rowIndex}`"
                    >
                      <cv-data-table-cell>
                        <span>
                          {{ row.name }}
                        </span>
                      </cv-data-table-cell>
                      <cv-data-table-cell>
                        <span>{{ row.tcp_ports }}</span>
                      </cv-data-table-cell>
                      <cv-data-table-cell>
                        <span>{{ row.udp_ports }}</span>
                      </cv-data-table-cell>
                    </cv-data-table-row>
                  </template>
                </NsDataTable>
              </cv-column>
            </cv-row>
          </cv-tile>
        </cv-column>
      </cv-row>
      <cv-row>
        <cv-column>
          <h4 class="mg-bottom-md">
            {{ $t("firewall.active_network_interfaces") }}
          </h4>
        </cv-column>
      </cv-row>
      <cv-row>
        <cv-column>
          <cv-tile light>
            <cv-row>
              <cv-column>
                <NsDataTable
                  :allRows="ipaddr"
                  :columns="i18nTableColumnsNetworkInterfaces"
                  :rawColumns="tableColumnsNetworkInterfaces"
                  :sortable="true"
                  :pageSizes="[5, 10, 15, 20]"
                  :searchPlaceholder="$t('firewall.search_service_or_port')"
                  :searchClearLabel="$t('common.clear_search')"
                  :noSearchResultsLabel="$t('common.no_search_results')"
                  :noSearchResultsDescription="
                    $t('common.no_search_results_description')
                  "
                  :isLoading="loading.getFirewallStatus"
                  :skeletonRows="3"
                  :isErrorShown="!!error.getFirewallStatus"
                  :errorTitle="$t('action.get-firewall-status')"
                  :errorDescription="error.getFirewallStatus"
                  :itemsPerPageLabel="$t('pagination.items_per_page')"
                  :rangeOfTotalItemsLabel="
                    $t('pagination.range_of_total_items')
                  "
                  :ofTotalPagesLabel="$t('pagination.of_total_pages')"
                  :backwardText="$t('pagination.previous_page')"
                  :forwardText="$t('pagination.next_page')"
                  :pageNumberLabel="$t('pagination.page_number')"
                  @updatePage="tablePageNetworkInterfaces = $event"
                >
                  <template slot="data">
                    <cv-data-table-row
                      v-for="(row, rowIndex) in tablePageNetworkInterfaces"
                      :key="`${rowIndex}`"
                      :value="`${rowIndex}`"
                    >
                      <cv-data-table-cell>
                        <span>
                          {{ row.ifname }}
                        </span>
                      </cv-data-table-cell>
                      <cv-data-table-cell>
                        <span v-if="row.addresses.length <= 3">
                          <div v-for="(addr, idx) in row.addresses" :key="idx">
                            {{ addr }}
                          </div>
                        </span>
                        <span v-else>
                          <div
                            v-for="(addr, idx) in row.addresses.slice(0, 3)"
                            :key="idx"
                          >
                            {{ addr }}
                          </div>
                          <cv-interactive-tooltip
                            alignment="center"
                            direction="top"
                          >
                            <template slot="trigger">
                              <a>
                                {{
                                  $tc(
                                    "common.plus_others",
                                    row.addresses.length - 3,
                                    {
                                      num: row.addresses.length - 3,
                                    }
                                  )
                                }}
                              </a>
                            </template>
                            <template slot="content">
                              <div
                                v-for="(addr, idx) in row.addresses.slice(3)"
                                :key="idx"
                              >
                                {{ addr }}
                              </div>
                            </template>
                          </cv-interactive-tooltip>
                        </span>
                      </cv-data-table-cell>
                    </cv-data-table-row>
                  </template>
                </NsDataTable>
              </cv-column>
            </cv-row>
          </cv-tile>
        </cv-column>
      </cv-row>
    </cv-grid>
  </div>
</template>
⋮----
<cv-link to="/nodes">{{ $t("nodes.title") }}</cv-link>
⋮----
<span>{{ title }}</span>
⋮----
<cv-link to="/settings">{{ $t("common.settings") }}</cv-link>
⋮----
<cv-link to="/settings/firewall">{{
                $t("firewall.title")
              }}</cv-link>
⋮----
<span>{{ title }}</span>
⋮----
{{ title }}
⋮----
{{ $t("firewall.public_zone_services") }}
⋮----
<template slot="empty-state">
                    <NsEmptyState :title="$t('firewall.no_service')">
                      <template #description>
                        <div>
                          {{ $t("firewall.no_service_description") }}
                        </div>
                      </template>
                    </NsEmptyState>
                  </template>
⋮----
<template #description>
                        <div>
                          {{ $t("firewall.no_service_description") }}
                        </div>
                      </template>
⋮----
{{ $t("firewall.no_service_description") }}
⋮----
<template slot="data">
                    <cv-data-table-row
                      v-for="(row, rowIndex) in tablePage"
                      :key="`${rowIndex}`"
                      :value="`${rowIndex}`"
                    >
                      <cv-data-table-cell>
                        <span>
                          {{ row.name }}
                        </span>
                      </cv-data-table-cell>
                      <cv-data-table-cell>
                        <span>{{ row.tcp_ports }}</span>
                      </cv-data-table-cell>
                      <cv-data-table-cell>
                        <span>{{ row.udp_ports }}</span>
                      </cv-data-table-cell>
                    </cv-data-table-row>
                  </template>
⋮----
{{ row.name }}
⋮----
<span>{{ row.tcp_ports }}</span>
⋮----
<span>{{ row.udp_ports }}</span>
⋮----
{{ $t("firewall.active_network_interfaces") }}
⋮----
<template slot="data">
                    <cv-data-table-row
                      v-for="(row, rowIndex) in tablePageNetworkInterfaces"
                      :key="`${rowIndex}`"
                      :value="`${rowIndex}`"
                    >
                      <cv-data-table-cell>
                        <span>
                          {{ row.ifname }}
                        </span>
                      </cv-data-table-cell>
                      <cv-data-table-cell>
                        <span v-if="row.addresses.length <= 3">
                          <div v-for="(addr, idx) in row.addresses" :key="idx">
                            {{ addr }}
                          </div>
                        </span>
                        <span v-else>
                          <div
                            v-for="(addr, idx) in row.addresses.slice(0, 3)"
                            :key="idx"
                          >
                            {{ addr }}
                          </div>
                          <cv-interactive-tooltip
                            alignment="center"
                            direction="top"
                          >
                            <template slot="trigger">
                              <a>
                                {{
                                  $tc(
                                    "common.plus_others",
                                    row.addresses.length - 3,
                                    {
                                      num: row.addresses.length - 3,
                                    }
                                  )
                                }}
                              </a>
                            </template>
                            <template slot="content">
                              <div
                                v-for="(addr, idx) in row.addresses.slice(3)"
                                :key="idx"
                              >
                                {{ addr }}
                              </div>
                            </template>
                          </cv-interactive-tooltip>
                        </span>
                      </cv-data-table-cell>
                    </cv-data-table-row>
                  </template>
⋮----
{{ row.ifname }}
⋮----
{{ addr }}
⋮----
{{ addr }}
⋮----
<template slot="trigger">
                              <a>
                                {{
                                  $tc(
                                    "common.plus_others",
                                    row.addresses.length - 3,
                                    {
                                      num: row.addresses.length - 3,
                                    }
                                  )
                                }}
                              </a>
                            </template>
⋮----
{{
                                  $tc(
                                    "common.plus_others",
                                    row.addresses.length - 3,
                                    {
                                      num: row.addresses.length - 3,
                                    }
                                  )
                                }}
⋮----
<template slot="content">
                              <div
                                v-for="(addr, idx) in row.addresses.slice(3)"
                                :key="idx"
                              >
                                {{ addr }}
                              </div>
                            </template>
⋮----
{{ addr }}
⋮----
<script>
import {
  QueryParamService,
  UtilService,
  TaskService,
  IconService,
  PageTitleService,
} from "@nethserver/ns8-ui-lib";
import to from "await-to-js";
import { mapActions } from "vuex";
export default {
  name: "NodeFirewall",
  mixins: [
    TaskService,
    UtilService,
    IconService,
    QueryParamService,
    PageTitleService,
  ],
  pageTitle() {
    return this.$t("firewall.title");
  },
  data() {
    return {
      q: {},
      nodeId: "",
      nodeLabel: "-",
      servicesAndPorts: [],
      interfaces: [],
      ipaddr: [],
      tablePage: [],
      tableColumns: ["name", "tcp_ports", "udp_ports"],
      tablePageNetworkInterfaces: [],
      tableColumnsNetworkInterfaces: ["interface", "ip_addresses"],
      loading: {
        getFirewallStatus: true,
        getClusterStatus: true,
      },
      error: {
        getFirewallStatus: "",
        getClusterStatus: "",
      },
    };
  },
  computed: {
    title() {
      return this.$t("firewall.node_firewall", {
        node: this.nodeLabel
          ? this.nodeLabel
          : this.$t("common.node") + " " + this.nodeId,
      });
    },
    route() {
      return this.$route.path;
    },
    i18nTableColumns() {
      return this.tableColumns.map((column) => {
        return this.$t("firewall." + column);
      });
    },
    i18nTableColumnsNetworkInterfaces() {
      return this.tableColumnsNetworkInterfaces.map((column) => {
        return this.$t("firewall." + column);
      });
    },
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.watchQueryData(vm);
      vm.queryParamsToDataForCore(vm, to.query);
    });
  },
  beforeRouteUpdate(to, from, next) {
    this.queryParamsToDataForCore(this, to.query);
    next();
  },
  created() {
    this.nodeId = this.$route.params.nodeId;
    this.getClusterStatus();
    this.getFirewallStatus();
  },
  methods: {
    ...mapActions(["setClusterNodesInStore"]),
    async getClusterStatus() {
      this.error.getClusterStatus = "";
      const taskAction = "get-cluster-status";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.getClusterStatusAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.getClusterStatusCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.getClusterStatus = this.getErrorMessage(err);
        return;
      }
    },
    getClusterStatusAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.getClusterStatus = this.$t("error.generic_error");
      this.loading.getClusterStatus = false;
    },
    getClusterStatusCompleted(taskContext, taskResult) {
      const clusterStatus = taskResult.output;
      const currentNode = clusterStatus.nodes.find(
        (node) => node.id == this.nodeId
      );
      this.nodeLabel = currentNode.ui_name;
      this.loading.clusterStatus = false;
      const nodes = clusterStatus.nodes.sort(this.sortByProperty("id"));
      this.setClusterNodesInStore(nodes);
    },
    async getFirewallStatus() {
      this.error.getFirewallStatus = "";
      const taskAction = "get-firewall-status";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.getFirewallStatusAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.getFirewallStatusCompleted
      );
      const res = await to(
        this.createNodeTask(this.nodeId, {
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.getFirewallStatus = this.getErrorMessage(err);
        return;
      }
    },
    getFirewallStatusAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.getFirewallStatus = this.$t("error.generic_error");
      this.loading.getFirewallStatus = false;
    },
    getFirewallStatusCompleted(taskContext, taskResult) {
      const firewallStatus = taskResult.output;
      this.ipaddr = Array.isArray(firewallStatus.ipaddr)
        ? firewallStatus.ipaddr.map((iface) => ({
            ifname: iface.ifname,
            addresses: Array.isArray(iface.addresses)
              ? iface.addresses
                  .map((addr) => `${addr.address}/${addr.prefixlen}`)
                  .sort()
              : [],
          }))
        : [];
      this.interfaces = firewallStatus.interfaces;
      const tcpPortRegex = /^(.+)\/tcp$/;
      const udpPortRegex = /^(.+)\/udp$/;
      for (const service of firewallStatus.services) {
        const tcpPorts = [];
        const udpPorts = [];
        for (const port of service.ports) {
          if (port.includes("tcp")) {
            const match = tcpPortRegex.exec(port);
            const tcpPort = match[1];
            tcpPorts.push(tcpPort);
          } else if (port.includes("udp")) {
            const match = udpPortRegex.exec(port);
            const updPort = match[1];
            udpPorts.push(updPort);
          }
        }
        service.tcp_ports = tcpPorts.join(", ");
        service.udp_ports = udpPorts.join(", ");
      }
      const servicesAndPorts = firewallStatus.services;
      for (const port of firewallStatus.ports) {
        if (port.includes("tcp")) {
          const match = tcpPortRegex.exec(port);
          const tcpPort = match[1];
          servicesAndPorts.push({
            name: "-",
            tcp_ports: tcpPort,
            udp_ports: "",
          });
        } else if (port.includes("udp")) {
          const match = udpPortRegex.exec(port);
          const updPort = match[1];
          servicesAndPorts.push({
            name: "-",
            tcp_ports: "",
            udp_ports: updPort,
          });
        }
      }
      this.servicesAndPorts = servicesAndPorts;
      this.loading.getFirewallStatus = false;
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../styles/carbon-utils";
</style>
</file>

<file path="core/ui/src/views/Nodes.vue">
<template>
  <cv-grid fullWidth>
    <cv-row>
      <cv-column class="page-title">
        <h2>{{ $t("nodes.title") }}</h2>
      </cv-column>
    </cv-row>
    <cv-row v-if="error.getClusterStatus">
      <cv-column>
        <NsInlineNotification
          kind="error"
          :title="$t('action.get-cluster-status')"
          :description="error.getClusterStatus"
          :showCloseButton="false"
        />
      </cv-column>
    </cv-row>
    <cv-row v-if="nodesOffline.length">
      <cv-column>
        <NsInlineNotification
          kind="error"
          :title="
            $tc('nodes.nodes_offline_c', nodesOffline.length, {
              num: nodesOffline.length,
            })
          "
          :description="
            $tc('nodes.nodes_offline_description_c', nodesOffline.length)
          "
          :showCloseButton="false"
        />
      </cv-column>
    </cv-row>
    <cv-row v-if="error.listNodes">
      <cv-column>
        <NsInlineNotification
          kind="error"
          :title="$t('action.list-nodes')"
          :description="error.listNodes"
          :showCloseButton="false"
        />
      </cv-column>
    </cv-row>
    <cv-row v-if="error.listAlerts">
      <cv-column>
        <NsInlineNotification
          kind="error"
          :title="$t('action.list-alerts')"
          :description="error.listAlerts"
          :showCloseButton="false"
        />
      </cv-column>
    </cv-row>
    <cv-row class="toolbar">
      <cv-column>
        <NsButton
          kind="secondary"
          :icon="Add20"
          @click="q.isShownAddNodeModal = true"
          >{{ $t("nodes.add_node_to_cluster") }}</NsButton
        >
      </cv-column>
    </cv-row>
    <cv-row v-if="stillLoading">
      <cv-column>
        <div
          class="card-grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 3xl:grid-cols-4"
        >
          <cv-tile v-for="index in 2" :key="index" light>
            <cv-skeleton-text
              :paragraph="true"
              :line-count="9"
              heading
            ></cv-skeleton-text>
          </cv-tile>
        </div>
      </cv-column>
    </cv-row>
    <cv-row v-else>
      <cv-column>
        <div
          class="card-grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 3xl:grid-cols-4"
        >
          <template v-for="node in clusterNodes">
            <NodeCard
              v-if="!node.online"
              :key="node.id"
              :nodeId="node.id"
              :nodeLabel="node.ui_name"
              :isLeader="leaderNode && node.id === leaderNode.id"
              light
              loading
              :online="node.online"
            >
              <template #menu>
                <cv-overflow-menu
                  v-if="node.id !== leaderNode.id"
                  :flip-menu="true"
                  tip-position="top"
                  tip-alignment="end"
                  class="top-right-overflow-menu"
                >
                  <cv-overflow-menu-item
                    danger
                    @click="showRemoveNodeModal(node)"
                  >
                    <NsMenuItem
                      :icon="TrashCan20"
                      :label="$t('nodes.remove_from_cluster')"
                    />
                  </cv-overflow-menu-item>
                </cv-overflow-menu>
              </template>
            </NodeCard>
            <NodeCard
              v-else
              :key="node.id + '_'"
              :nodeId="node.id"
              :nodeLabel="node.ui_name"
              :isLeader="leaderNode && node.id === leaderNode.id"
              :role="node.role"
              :leaderLabel="$t('nodes.leader')"
              :workerLabel="$t('nodes.worker')"
              :ns7MigrationLabel="$t('nodes.ns7_migration')"
              :diskUsageLabel="$t('nodes.usage')"
              :online="node.online"
              :fqdn="node.hostname"
              :fqdnLabel="$t('nodes.fqdn')"
              :node_id="node.id"
              :ip_address="node.ip_address"
              :ip_addressLabel="$t('nodes.ip_address')"
              :applications="node.applications"
              :applicationsLabel="$t('nodes.applications')"
              :alertsCount="alertsCountByNode[node.id] || 0"
              :alertsLabel="
                $tc('nodes.alerts', alertsCountByNode[node.id] || 0)
              "
              :class="{ 'node-card--ns7': node.role === 'ns7migration' }"
              light
            >
              <template #menu>
                <cv-overflow-menu
                  v-if="node.role !== 'ns7migration'"
                  :flip-menu="true"
                  tip-position="top"
                  tip-alignment="end"
                  class="top-right-overflow-menu"
                >
                  <cv-overflow-menu-item @click="showSetNodeLabelModal(node)">
                    <NsMenuItem
                      :icon="Edit20"
                      :label="$t('nodes.edit_node_label')"
                    />
                  </cv-overflow-menu-item>
                  <cv-overflow-menu-item @click="showSetNodeFqdnModal(node)">
                    <NsMenuItem :icon="Edit20" :label="$t('nodes.set_fqdn')" />
                  </cv-overflow-menu-item>
                  <cv-overflow-menu-item @click="goToHttpRoutes(node)">
                    <NsMenuItem
                      :icon="ArrowRight20"
                      :label="$t('nodes.go_to_http_routes')"
                    />
                  </cv-overflow-menu-item>
                  <cv-overflow-menu-item @click="goToTlsCertificates(node)">
                    <NsMenuItem
                      :icon="ArrowRight20"
                      :label="$t('nodes.go_to_tls_certificates')"
                    />
                  </cv-overflow-menu-item>
                  <cv-overflow-menu-item @click="goToFirewall(node)">
                    <NsMenuItem
                      :icon="ArrowRight20"
                      :label="$t('nodes.go_to_firewall')"
                    />
                  </cv-overflow-menu-item>
                  <cv-overflow-menu-item
                    v-if="leaderNode && node.id !== leaderNode.id"
                    @click="showPromoteNodeModal(node)"
                  >
                    <NsMenuItem
                      :icon="Recommend20"
                      :label="$t('nodes.promote_to_leader')"
                      ><Recommend20 />
                    </NsMenuItem>
                  </cv-overflow-menu-item>
                  <cv-overflow-menu-item
                    v-if="leaderNode && node.id !== leaderNode.id"
                    danger
                    @click="showRemoveNodeModal(node)"
                  >
                    <NsMenuItem
                      :icon="TrashCan20"
                      :label="$t('nodes.remove_from_cluster')"
                    />
                  </cv-overflow-menu-item>
                </cv-overflow-menu>
              </template>
              <template v-if="node.role !== 'ns7migration'" #content>
                <NsButton
                  kind="ghost"
                  :icon="ArrowRight20"
                  @click="goToNodeDetail(node.id)"
                  >{{ $t("common.see_details") }}</NsButton
                >
              </template>
            </NodeCard>
          </template>
        </div>
      </cv-column>
    </cv-row>
    <NsModal
      size="default"
      :visible="q.isShownAddNodeModal"
      @modal-hidden="q.isShownAddNodeModal = false"
    >
      <template slot="title">{{ $t("nodes.add_node_to_cluster") }}</template>
      <template slot="content">
        <ol class="mg-bottom-md">
          <li>
            {{
              $t("nodes.add_node_to_cluster_step_1", {
                product: this.$root.config.PRODUCT_NAME,
              })
            }}
          </li>
          <li>{{ $t("nodes.add_node_to_cluster_step_2") }}</li>
          <li>{{ $t("nodes.add_node_to_cluster_step_3") }}</li>
          <li>{{ $t("nodes.add_node_to_cluster_step_4") }}</li>
          <li>{{ $t("nodes.add_node_to_cluster_step_5") }}</li>
          <li>{{ $t("nodes.add_node_to_cluster_step_6") }}</li>
        </ol>
        <cv-skeleton-text
          v-if="loading.getFqdn || !leaderNode"
          :paragraph="true"
          :line-count="5"
          heading
        ></cv-skeleton-text>
        <template v-else>
          <span class="join-code">{{ $t("common.join_code") }}</span>
          <NsCodeSnippet
            :copyTooltip="$t('common.copy_to_clipboard')"
            :copy-feedback="$t('common.copied_to_clipboard')"
            :feedback-aria-label="$t('common.copied_to_clipboard')"
            :wrap-text="true"
            :moreText="$t('common.show_more')"
            :lessText="$t('common.show_less')"
            light
            expanded
            hideExpandButton
            >{{ joinCode }}</NsCodeSnippet
          >
        </template>
      </template>
      <template slot="secondary-button">{{ $t("common.close") }}</template>
    </NsModal>
    <NsModal
      size="default"
      :visible="isShownSetNodeLabelModal"
      @modal-hidden="hideSetNodeLabelModal"
      @primary-click="setNodeLabel"
    >
      <template slot="title">{{ $t("nodes.edit_node_label") }}</template>
      <template slot="content">
        <template v-if="currentNode">
          <cv-form @submit.prevent="setNodeLabel">
            <cv-text-input
              :label="
                $t('nodes.node_label') + ' (' + $t('common.optional') + ')'
              "
              v-model.trim="newNodeLabel"
              :placeholder="$t('common.no_label')"
              :helper-text="$t('nodes.node_label_tooltip')"
              maxlength="24"
              ref="newNodeLabel"
            >
            </cv-text-input>
            <div v-if="error.setNodeLabel">
              <NsInlineNotification
                kind="error"
                :title="$t('action.set-name')"
                :description="error.setNodeLabel"
                :showCloseButton="false"
              />
            </div>
          </cv-form>
        </template>
      </template>
      <template slot="secondary-button">{{ $t("common.cancel") }}</template>
      <template slot="primary-button">{{ $t("common.save") }}</template>
    </NsModal>
    <RemoveNodeModal
      :isShown="isShownRemoveNodeModal"
      :node="nodeToRemove"
      @hide="hideRemoveNodeModal"
      @nodeRemoved="retrieveData"
    />
    <PromoteNodeModal
      :isShown="isShownPromoteNodeModal"
      :node="nodeToPromote"
      @hide="hidePromoteNodeModal"
      @nodePromoted="onNodePromoted"
    />
    <NewLeaderModal
      :isShown="isShownNewLeaderModal"
      :endpointAddress="newLeaderEndpointAddress"
      @hide="hideNewLeaderModal"
    />
    <SetFqdnModal
      :isShown="isShownSetFqdnModal"
      :node="currentNode"
      @hide="hideSetFqdnModal"
    />
  </cv-grid>
</template>
⋮----
<h2>{{ $t("nodes.title") }}</h2>
⋮----
>{{ $t("nodes.add_node_to_cluster") }}</NsButton
⋮----
<template v-for="node in clusterNodes">
            <NodeCard
              v-if="!node.online"
              :key="node.id"
              :nodeId="node.id"
              :nodeLabel="node.ui_name"
              :isLeader="leaderNode && node.id === leaderNode.id"
              light
              loading
              :online="node.online"
            >
              <template #menu>
                <cv-overflow-menu
                  v-if="node.id !== leaderNode.id"
                  :flip-menu="true"
                  tip-position="top"
                  tip-alignment="end"
                  class="top-right-overflow-menu"
                >
                  <cv-overflow-menu-item
                    danger
                    @click="showRemoveNodeModal(node)"
                  >
                    <NsMenuItem
                      :icon="TrashCan20"
                      :label="$t('nodes.remove_from_cluster')"
                    />
                  </cv-overflow-menu-item>
                </cv-overflow-menu>
              </template>
            </NodeCard>
            <NodeCard
              v-else
              :key="node.id + '_'"
              :nodeId="node.id"
              :nodeLabel="node.ui_name"
              :isLeader="leaderNode && node.id === leaderNode.id"
              :role="node.role"
              :leaderLabel="$t('nodes.leader')"
              :workerLabel="$t('nodes.worker')"
              :ns7MigrationLabel="$t('nodes.ns7_migration')"
              :diskUsageLabel="$t('nodes.usage')"
              :online="node.online"
              :fqdn="node.hostname"
              :fqdnLabel="$t('nodes.fqdn')"
              :node_id="node.id"
              :ip_address="node.ip_address"
              :ip_addressLabel="$t('nodes.ip_address')"
              :applications="node.applications"
              :applicationsLabel="$t('nodes.applications')"
              :alertsCount="alertsCountByNode[node.id] || 0"
              :alertsLabel="
                $tc('nodes.alerts', alertsCountByNode[node.id] || 0)
              "
              :class="{ 'node-card--ns7': node.role === 'ns7migration' }"
              light
            >
              <template #menu>
                <cv-overflow-menu
                  v-if="node.role !== 'ns7migration'"
                  :flip-menu="true"
                  tip-position="top"
                  tip-alignment="end"
                  class="top-right-overflow-menu"
                >
                  <cv-overflow-menu-item @click="showSetNodeLabelModal(node)">
                    <NsMenuItem
                      :icon="Edit20"
                      :label="$t('nodes.edit_node_label')"
                    />
                  </cv-overflow-menu-item>
                  <cv-overflow-menu-item @click="showSetNodeFqdnModal(node)">
                    <NsMenuItem :icon="Edit20" :label="$t('nodes.set_fqdn')" />
                  </cv-overflow-menu-item>
                  <cv-overflow-menu-item @click="goToHttpRoutes(node)">
                    <NsMenuItem
                      :icon="ArrowRight20"
                      :label="$t('nodes.go_to_http_routes')"
                    />
                  </cv-overflow-menu-item>
                  <cv-overflow-menu-item @click="goToTlsCertificates(node)">
                    <NsMenuItem
                      :icon="ArrowRight20"
                      :label="$t('nodes.go_to_tls_certificates')"
                    />
                  </cv-overflow-menu-item>
                  <cv-overflow-menu-item @click="goToFirewall(node)">
                    <NsMenuItem
                      :icon="ArrowRight20"
                      :label="$t('nodes.go_to_firewall')"
                    />
                  </cv-overflow-menu-item>
                  <cv-overflow-menu-item
                    v-if="leaderNode && node.id !== leaderNode.id"
                    @click="showPromoteNodeModal(node)"
                  >
                    <NsMenuItem
                      :icon="Recommend20"
                      :label="$t('nodes.promote_to_leader')"
                      ><Recommend20 />
                    </NsMenuItem>
                  </cv-overflow-menu-item>
                  <cv-overflow-menu-item
                    v-if="leaderNode && node.id !== leaderNode.id"
                    danger
                    @click="showRemoveNodeModal(node)"
                  >
                    <NsMenuItem
                      :icon="TrashCan20"
                      :label="$t('nodes.remove_from_cluster')"
                    />
                  </cv-overflow-menu-item>
                </cv-overflow-menu>
              </template>
              <template v-if="node.role !== 'ns7migration'" #content>
                <NsButton
                  kind="ghost"
                  :icon="ArrowRight20"
                  @click="goToNodeDetail(node.id)"
                  >{{ $t("common.see_details") }}</NsButton
                >
              </template>
            </NodeCard>
          </template>
⋮----
<template #menu>
                <cv-overflow-menu
                  v-if="node.id !== leaderNode.id"
                  :flip-menu="true"
                  tip-position="top"
                  tip-alignment="end"
                  class="top-right-overflow-menu"
                >
                  <cv-overflow-menu-item
                    danger
                    @click="showRemoveNodeModal(node)"
                  >
                    <NsMenuItem
                      :icon="TrashCan20"
                      :label="$t('nodes.remove_from_cluster')"
                    />
                  </cv-overflow-menu-item>
                </cv-overflow-menu>
              </template>
⋮----
<template #menu>
                <cv-overflow-menu
                  v-if="node.role !== 'ns7migration'"
                  :flip-menu="true"
                  tip-position="top"
                  tip-alignment="end"
                  class="top-right-overflow-menu"
                >
                  <cv-overflow-menu-item @click="showSetNodeLabelModal(node)">
                    <NsMenuItem
                      :icon="Edit20"
                      :label="$t('nodes.edit_node_label')"
                    />
                  </cv-overflow-menu-item>
                  <cv-overflow-menu-item @click="showSetNodeFqdnModal(node)">
                    <NsMenuItem :icon="Edit20" :label="$t('nodes.set_fqdn')" />
                  </cv-overflow-menu-item>
                  <cv-overflow-menu-item @click="goToHttpRoutes(node)">
                    <NsMenuItem
                      :icon="ArrowRight20"
                      :label="$t('nodes.go_to_http_routes')"
                    />
                  </cv-overflow-menu-item>
                  <cv-overflow-menu-item @click="goToTlsCertificates(node)">
                    <NsMenuItem
                      :icon="ArrowRight20"
                      :label="$t('nodes.go_to_tls_certificates')"
                    />
                  </cv-overflow-menu-item>
                  <cv-overflow-menu-item @click="goToFirewall(node)">
                    <NsMenuItem
                      :icon="ArrowRight20"
                      :label="$t('nodes.go_to_firewall')"
                    />
                  </cv-overflow-menu-item>
                  <cv-overflow-menu-item
                    v-if="leaderNode && node.id !== leaderNode.id"
                    @click="showPromoteNodeModal(node)"
                  >
                    <NsMenuItem
                      :icon="Recommend20"
                      :label="$t('nodes.promote_to_leader')"
                      ><Recommend20 />
                    </NsMenuItem>
                  </cv-overflow-menu-item>
                  <cv-overflow-menu-item
                    v-if="leaderNode && node.id !== leaderNode.id"
                    danger
                    @click="showRemoveNodeModal(node)"
                  >
                    <NsMenuItem
                      :icon="TrashCan20"
                      :label="$t('nodes.remove_from_cluster')"
                    />
                  </cv-overflow-menu-item>
                </cv-overflow-menu>
              </template>
<template v-if="node.role !== 'ns7migration'" #content>
                <NsButton
                  kind="ghost"
                  :icon="ArrowRight20"
                  @click="goToNodeDetail(node.id)"
                  >{{ $t("common.see_details") }}</NsButton
                >
              </template>
⋮----
>{{ $t("common.see_details") }}</NsButton
⋮----
<template slot="title">{{ $t("nodes.add_node_to_cluster") }}</template>
<template slot="content">
        <ol class="mg-bottom-md">
          <li>
            {{
              $t("nodes.add_node_to_cluster_step_1", {
                product: this.$root.config.PRODUCT_NAME,
              })
            }}
          </li>
          <li>{{ $t("nodes.add_node_to_cluster_step_2") }}</li>
          <li>{{ $t("nodes.add_node_to_cluster_step_3") }}</li>
          <li>{{ $t("nodes.add_node_to_cluster_step_4") }}</li>
          <li>{{ $t("nodes.add_node_to_cluster_step_5") }}</li>
          <li>{{ $t("nodes.add_node_to_cluster_step_6") }}</li>
        </ol>
        <cv-skeleton-text
          v-if="loading.getFqdn || !leaderNode"
          :paragraph="true"
          :line-count="5"
          heading
        ></cv-skeleton-text>
        <template v-else>
          <span class="join-code">{{ $t("common.join_code") }}</span>
          <NsCodeSnippet
            :copyTooltip="$t('common.copy_to_clipboard')"
            :copy-feedback="$t('common.copied_to_clipboard')"
            :feedback-aria-label="$t('common.copied_to_clipboard')"
            :wrap-text="true"
            :moreText="$t('common.show_more')"
            :lessText="$t('common.show_less')"
            light
            expanded
            hideExpandButton
            >{{ joinCode }}</NsCodeSnippet
          >
        </template>
      </template>
⋮----
{{
              $t("nodes.add_node_to_cluster_step_1", {
                product: this.$root.config.PRODUCT_NAME,
              })
            }}
⋮----
<li>{{ $t("nodes.add_node_to_cluster_step_2") }}</li>
<li>{{ $t("nodes.add_node_to_cluster_step_3") }}</li>
<li>{{ $t("nodes.add_node_to_cluster_step_4") }}</li>
<li>{{ $t("nodes.add_node_to_cluster_step_5") }}</li>
<li>{{ $t("nodes.add_node_to_cluster_step_6") }}</li>
⋮----
<template v-else>
          <span class="join-code">{{ $t("common.join_code") }}</span>
          <NsCodeSnippet
            :copyTooltip="$t('common.copy_to_clipboard')"
            :copy-feedback="$t('common.copied_to_clipboard')"
            :feedback-aria-label="$t('common.copied_to_clipboard')"
            :wrap-text="true"
            :moreText="$t('common.show_more')"
            :lessText="$t('common.show_less')"
            light
            expanded
            hideExpandButton
            >{{ joinCode }}</NsCodeSnippet
          >
        </template>
⋮----
<span class="join-code">{{ $t("common.join_code") }}</span>
⋮----
>{{ joinCode }}</NsCodeSnippet
⋮----
<template slot="secondary-button">{{ $t("common.close") }}</template>
⋮----
<template slot="title">{{ $t("nodes.edit_node_label") }}</template>
<template slot="content">
        <template v-if="currentNode">
          <cv-form @submit.prevent="setNodeLabel">
            <cv-text-input
              :label="
                $t('nodes.node_label') + ' (' + $t('common.optional') + ')'
              "
              v-model.trim="newNodeLabel"
              :placeholder="$t('common.no_label')"
              :helper-text="$t('nodes.node_label_tooltip')"
              maxlength="24"
              ref="newNodeLabel"
            >
            </cv-text-input>
            <div v-if="error.setNodeLabel">
              <NsInlineNotification
                kind="error"
                :title="$t('action.set-name')"
                :description="error.setNodeLabel"
                :showCloseButton="false"
              />
            </div>
          </cv-form>
        </template>
      </template>
⋮----
<template v-if="currentNode">
          <cv-form @submit.prevent="setNodeLabel">
            <cv-text-input
              :label="
                $t('nodes.node_label') + ' (' + $t('common.optional') + ')'
              "
              v-model.trim="newNodeLabel"
              :placeholder="$t('common.no_label')"
              :helper-text="$t('nodes.node_label_tooltip')"
              maxlength="24"
              ref="newNodeLabel"
            >
            </cv-text-input>
            <div v-if="error.setNodeLabel">
              <NsInlineNotification
                kind="error"
                :title="$t('action.set-name')"
                :description="error.setNodeLabel"
                :showCloseButton="false"
              />
            </div>
          </cv-form>
        </template>
⋮----
<template slot="secondary-button">{{ $t("common.cancel") }}</template>
<template slot="primary-button">{{ $t("common.save") }}</template>
⋮----
<script>
import {
  QueryParamService,
  UtilService,
  TaskService,
  IconService,
  PageTitleService,
} from "@nethserver/ns8-ui-lib";
import to from "await-to-js";
import { mapState, mapActions } from "vuex";
import NodeCard from "@/components/nodes/NodeCard";
import RemoveNodeModal from "@/components/nodes/RemoveNodeModal";
import PromoteNodeModal from "@/components/nodes/PromoteNodeModal";
import NewLeaderModal from "@/components/nodes/NewLeaderModal";
import SetFqdnModal from "@/components/nodes/SetFqdnModal";
import Recommend20 from "@carbon/icons-vue/es/recommend/20";
export default {
  name: "Nodes",
  components: {
    NodeCard,
    RemoveNodeModal,
    PromoteNodeModal,
    NewLeaderModal,
    SetFqdnModal,
    Recommend20,
  },
  mixins: [
    TaskService,
    UtilService,
    IconService,
    QueryParamService,
    PageTitleService,
  ],
  pageTitle() {
    return this.$t("nodes.title");
  },
  data() {
    return {
      REFRESH_DATA_TIME_INTERVAL: 30000,
      q: {
        isShownAddNodeModal: false,
      },
      Recommend20,
      joinCode: "",
      nodes: [],
      clusterNodes: [],
      refreshDataInterval: null,
      currentNode: null,
      newNodeLabel: "",
      isShownSetNodeLabelModal: false,
      isShownRemoveNodeModal: false,
      nodeToRemove: null,
      isShownPromoteNodeModal: false,
      nodeToPromote: null,
      isShownNewLeaderModal: false,
      newLeaderEndpointAddress: "",
      isShownSetFqdnModal: false,
      alertsCountByNode: {},
      loading: {
        getClusterStatus: true,
        setNodeLabel: false,
        getFqdn: false,
        listAlerts: true,
        listNodes: true,
      },
      error: {
        getClusterStatus: "",
        setNodeLabel: "",
        getFqdn: "",
        listNodes: "",
        listAlerts: "",
      },
    };
  },
  computed: {
    ...mapState(["leaderListenPort"]),
    leaderNode: function () {
      if (!this.nodes) {
        return null;
      }
      return this.nodes.find((node) => node.local);
    },
    nodesOffline() {
      return this.nodes.filter((n) => n.online == false);
    },
    stillLoading() {
      return (
        this.loading.getClusterStatus ||
        this.loading.listAlerts ||
        this.loading.listNodes
      );
    },
  },
  watch: {
    "q.isShownAddNodeModal": function () {
      if (this.q.isShownAddNodeModal && this.leaderNode) {
        this.getLeaderFqdn();
      }
    },
    leaderNode: function (newLeaderNode, oldLeaderNode) {
      if (
        newLeaderNode &&
        this.q.isShownAddNodeModal &&
        newLeaderNode.id != oldLeaderNode?.id
      ) {
        this.getLeaderFqdn();
      }
    },
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.watchQueryData(vm);
      vm.queryParamsToDataForCore(vm, to.query);
    });
  },
  beforeRouteUpdate(to, from, next) {
    this.queryParamsToDataForCore(this, to.query);
    next();
  },
  created() {
    this.retrieveData();
    this.refreshDataInterval = setInterval(
      this.retrieveData,
      this.REFRESH_DATA_TIME_INTERVAL
    );
  },
  beforeDestroy() {
    clearInterval(this.refreshDataInterval);
  },
  methods: {
    ...mapActions(["setClusterNodesInStore"]),
    retrieveData() {
      this.listAlerts();
      this.getClusterStatus();
    },
    async getLeaderFqdn() {
      this.error.getFqdn = "";
      this.loading.getFqdn = true;
      const taskAction = "get-fqdn";
      const eventId = this.getUuid();
      this.$root.$once(`${taskAction}-aborted-${eventId}`, this.getFqdnAborted);
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.getFqdnCompleted
      );
      const res = await to(
        this.createNodeTask(this.leaderNode.id, {
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.getFqdn = this.getErrorMessage(err);
        this.loading.getFqdn = false;
        return;
      }
    },
    getFqdnCompleted(taskContext, taskResult) {
      const fqdn = `${taskResult.output.hostname}.${taskResult.output.domain}`;
      const loginInfo = this.getFromStorage("loginInfo");
      if (loginInfo && loginInfo.token) {
        const endpoint = window.location.protocol + "//" + fqdn;
        this.joinCode = btoa(endpoint + "|" + loginInfo.token);
      }
      this.loading.getFqdn = false;
    },
    getFqdnAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.loading.getFqdn = false;
    },
    async getClusterStatus() {
      this.error.getClusterStatus = "";
      const taskAction = "get-cluster-status";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.getClusterStatusAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.getClusterStatusCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.getClusterStatus = this.getErrorMessage(err);
        return;
      }
    },
    getClusterStatusAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.getClusterStatus = this.$t("error.generic_error");
      this.loading.getClusterStatus = false;
    },
    getClusterStatusCompleted(taskContext, taskResult) {
      const clusterStatus = taskResult.output;
      this.nodes = clusterStatus.nodes.sort(this.sortByProperty("id"));
      this.setClusterNodesInStore(this.nodes);
      this.loading.getClusterStatus = false;
      this.listNodes();
    },
    async listNodes() {
      this.error.listNodes = "";
      const taskAction = "list-nodes";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.listNodesAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.listNodesCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.listNodes = this.getErrorMessage(err);
        return;
      }
    },
    listNodesAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.listNodes = this.$t("error.generic_error");
      this.loading.listNodes = false;
    },
    listNodesCompleted(taskContext, taskResult) {
      const nodesData = taskResult.output.nodes;
      const onlineById = Object.fromEntries(
        (this.nodes || []).map((node) => [node.id, node.online === true])
      );
      const transformedNodes = nodesData.map((node) => {
        const online =
          node.role === "ns7migration"
            ? true
            : onlineById[node.node_id] === true;
        return {
          id: node.node_id,
          hostname: node.fqdn || "",
          ui_name: node.ui_name || "",
          role: node.role || "worker",
          online,
          ip_address: node.main_ip || "",
          applications: node.app_count || 0,
        };
      });
      this.clusterNodes = transformedNodes.sort(this.sortByProperty("id"));
      this.loading.listNodes = false;
    },
    async listAlerts() {
      this.error.listAlerts = "";
      const taskAction = "list-alerts";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.listAlertsAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.listAlertsCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.listAlerts = this.getErrorMessage(err);
        return;
      }
    },
    listAlertsAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.listAlerts = this.$t("error.generic_error");
      this.loading.listAlerts = false;
    },
    listAlertsCompleted(taskContext, taskResult) {
      const alerts = taskResult.output.alerts;
      const alertsCountByNode = {};
      alerts.forEach((alert) => {
        if (alert.node_id in alertsCountByNode) {
          alertsCountByNode[alert.node_id] += 1;
        } else {
          alertsCountByNode[alert.node_id] = 1;
        }
      });
      this.alertsCountByNode = alertsCountByNode;
      this.loading.listAlerts = false;
    },
    goToNodeDetail(nodeId) {
      this.$router.push({
        name: "NodeDetail",
        params: { nodeId },
      });
    },
    goToFirewall(node) {
      this.$router.push({
        name: "NodeFirewall",
        params: { nodeId: node.id },
      });
    },
    showSetNodeLabelModal(node) {
      this.currentNode = node;
      this.newNodeLabel = node.ui_name;
      this.isShownSetNodeLabelModal = true;
      setTimeout(() => {
        this.focusElement("newNodeLabel");
      }, 300);
    },
    showSetNodeFqdnModal(node) {
      this.currentNode = node;
      this.isShownSetFqdnModal = true;
    },
    hideSetNodeLabelModal() {
      this.isShownSetNodeLabelModal = false;
    },
    async setNodeLabel() {
      this.error.setNodeLabel = "";
      this.loading.setNodeLabel = true;
      const taskAction = "set-name";
      this.$root.$once(taskAction + "-completed", this.setNodeLabelCompleted);
      const res = await to(
        this.createNodeTask(this.currentNode.id, {
          action: taskAction,
          data: {
            name: this.newNodeLabel,
          },
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.setNodeLabel = this.getErrorMessage(err);
        this.loading.setNodeLabel = false;
        return;
      }
    },
    setNodeLabelCompleted() {
      this.loading.setNodeLabel = false;
      this.hideSetNodeLabelModal();
      this.getClusterStatus();
    },
    goToHttpRoutes(node) {
      this.$router.push({
        path: "/settings/http-routes",
        query: { selectedNodeId: node.id },
      });
    },
    goToTlsCertificates(node) {
      this.$router.push({
        path: "/settings/tls-certificates",
        query: { selectedNodeId: node.id },
      });
    },
    goToApplications(node) {
      this.$router.push({
        path: "/applications",
        query: { selectedNodeId: node.id },
      });
    },
    showPromoteNodeModal(node) {
      this.nodeToPromote = node;
      this.isShownPromoteNodeModal = true;
    },
    hidePromoteNodeModal() {
      this.isShownPromoteNodeModal = false;
    },
    showNewLeaderModal() {
      this.isShownNewLeaderModal = true;
    },
    hideNewLeaderModal() {
      this.isShownNewLeaderModal = false;
    },
    hideSetFqdnModal() {
      this.isShownSetFqdnModal = false;
    },
    onNodePromoted(newLeaderEndpointAddress) {
      this.newLeaderEndpointAddress = newLeaderEndpointAddress;
      this.showNewLeaderModal();
    },
    showRemoveNodeModal(node) {
      this.nodeToRemove = node;
      this.isShownRemoveNodeModal = true;
    },
    hideRemoveNodeModal() {
      this.isShownRemoveNodeModal = false;
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../styles/carbon-utils";
ol {
  list-style-type: decimal;
  padding-left: $spacing-05;
}
.join-code {
  font-weight: bold;
}
</style>
</file>

<file path="core/ui/src/views/SoftwareCenter.vue">
<template>
  <div>
    <cv-grid fullWidth>
      <cv-row>
        <cv-column :md="4" :xlg="10" class="page-title">
          <h2>
            {{ $t("software_center.title") }}
          </h2>
        </cv-column>
        <cv-column :md="4" :xlg="6">
          <div class="page-toolbar">
            <NsButton
              kind="secondary"
              size="field"
              :icon="Restart20"
              @click="cleanRepositoriesCache()"
              :disabled="loading.cleanRepositoriesCache"
              :loading="loading.cleanRepositoriesCache"
              class="page-toolbar-item"
              >{{
                $t("software_center.reload_software_repositories")
              }}</NsButton
            >
            <NsIconMenu
              :flipMenu="true"
              tipPosition="top"
              tipAlignment="end"
              class="page-toolbar-item"
            >
              <cv-overflow-menu-item
                v-if="subscriptionIsActive"
                @click="toggleAutomaticUpdates()"
              >
                <NsMenuItem
                  :icon="applyUpdatesIsActive ? PauseOutline20 : PlayOutline20"
                  :label="
                    applyUpdatesIsActive
                      ? $t('software_center.disable_automatic_updates')
                      : $t('software_center.enable_automatic_updates')
                  "
                />
              </cv-overflow-menu-item>
              <cv-overflow-menu-item @click="showSoftwareCenterCoreApps()">
                <NsMenuItem
                  :icon="ArrowRight20"
                  :label="$t('software_center.go_to_core_applications')"
                />
              </cv-overflow-menu-item>
              <cv-overflow-menu-item
                @click="goToSettingsSoftwareRepositories()"
              >
                <NsMenuItem
                  :icon="ArrowRight20"
                  :label="$t('software_center.go_to_software_repositories')"
                />
              </cv-overflow-menu-item>
            </NsIconMenu>
          </div>
        </cv-column>
      </cv-row>
      <cv-row v-if="error.listModules">
        <cv-column>
          <NsInlineNotification
            kind="error"
            :title="$t('action.list-modules')"
            :description="error.listModules"
            :showCloseButton="false"
          />
        </cv-column>
      </cv-row>
      <cv-row v-if="error.listCoreModules">
        <cv-column>
          <NsInlineNotification
            kind="error"
            :title="$t('action.list-core-modules')"
            :description="error.listCoreModules"
            :showCloseButton="false"
          />
        </cv-column>
      </cv-row>
      <cv-row v-if="error.cleanRepositoriesCache">
        <cv-column>
          <NsInlineNotification
            kind="error"
            :title="$t('action.clean-repositories-cache')"
            :description="error.cleanRepositoriesCache"
            :showCloseButton="false"
          />
        </cv-column>
      </cv-row>
      <cv-row v-if="subscriptionIsActive && !applyUpdatesIsActive">
        <cv-column>
          <NsInlineNotification
            kind="warning"
            :title="$t('software_center.automatic_updates_disabled_title')"
            :description="
              $t('software_center.automatic_updates_disabled_description')
            "
            :actionLabel="$t('software_center.enable_automatic_updates')"
            @action="toggleAutomaticUpdates"
            :showCloseButton="false"
          />
        </cv-column>
      </cv-row>
      <cv-row v-if="q.view !== 'updates'">
        <cv-column
          v-if="
            (isCoreUpdateAvailable || appUpdates.length) &&
            !loading.listCoreModules
          "
        >
          <NsInlineNotification
            kind="warning"
            :title="$t('software_center.software_updates')"
            :description="updatesNotificationDescription"
            :actionLabel="$t('software_center.go_to_updates')"
            @action="goToUpdates"
            :showCloseButton="false"
          />
        </cv-column>
      </cv-row>
      <cv-row v-if="error.updateCore">
        <cv-column>
          <NsInlineNotification
            kind="error"
            :title="$t('action.update-core')"
            :description="error.updateCore"
            :showCloseButton="false"
          />
        </cv-column>
      </cv-row>
      <cv-row v-if="testingRepositories.length">
        <cv-column>
          <NsInlineNotification
            kind="warning"
            :title="$t('software_center.testing_warning_title')"
            :description="
              $tc(
                'software_center.testing_warning_description',
                testingRepositories.length,
                { repos: testingRepositories.join(', ') }
              )
            "
            :showCloseButton="false"
          />
        </cv-column>
      </cv-row>
      <cv-row v-if="updatesAreDisabledForMigration">
        <cv-column>
          <NsInlineNotification
            kind="info"
            :title="$t('software_center.updates_disabled_ns7_migration_title')"
            :description="
              $t('software_center.updates_disabled_ns7_migration_description')
            "
            :showCloseButton="false"
          />
        </cv-column>
      </cv-row>
      <div>
        <cv-search
          :label="$t('software_center.search_placeholder')"
          :placeholder="$t('software_center.search_placeholder')"
          size="xl"
          :clear-aria-label="$t('common.clear_search')"
          v-model="q.search"
          v-debounce="searchApp"
          class="app-search"
          :light="true"
        >
        </cv-search>
        <cv-content-switcher
          class="switcher"
          @selected="contentSwitcherSelected"
        >
          <cv-content-switcher-button
            owner-id="all"
            :selected="csbAllSelected"
            :disabled="loading.listModules || loading.listCoreModules"
            >{{ $t("software_center.all") }}</cv-content-switcher-button
          >
          <cv-content-switcher-button
            owner-id="installed"
            :selected="csbInstalledSelected"
            :disabled="loading.listModules || loading.listCoreModules"
            >{{ $t("software_center.installed") }}</cv-content-switcher-button
          >
          <cv-content-switcher-button
            owner-id="updates"
            :selected="csbUpdatesSelected"
            :disabled="loading.listModules || loading.listCoreModules"
            >{{ $t("software_center.updates") }}</cv-content-switcher-button
          >
        </cv-content-switcher>
        <section v-if="['all', 'installed', 'updates'].includes(q.view)">
          <div v-if="csbAllSelected">
            <cv-tile v-if="!modules.length && !loading.listModules" light>
              <NsEmptyState
                :title="$t('software_center.no_apps')"
                key="all-empty-state"
              />
            </cv-tile>
            <AppList
              v-else
              :apps="modules"
              :skeleton="loading.listModules || loading.listCoreModules"
              tab="all"
              @install="openInstallModal"
              key="all-app-list"
              :light="true"
            />
          </div>
          <div v-if="csbInstalledSelected">
            <cv-tile
              v-if="!installedModules.length && !loading.listModules"
              light
            >
              <NsEmptyState
                :title="$t('software_center.no_apps')"
                key="installed-empty-state"
              />
            </cv-tile>
            <AppList
              v-else
              :apps="installedModules"
              :skeleton="loading.listModules || loading.listCoreModules"
              tab="installed"
              @install="openInstallModal"
              key="installed-app-list"
              :light="true"
            />
          </div>
          <div v-if="csbUpdatesSelected">
            <NsInlineNotification
              v-if="error.updateModules"
              kind="error"
              :title="$t('action.update-modules')"
              :description="error.updateModules"
              :showCloseButton="false"
            />
            <NsInlineNotification
              v-if="updateAllAppsTimeout"
              kind="info"
              :title="
                $tc(
                  'software_center.n_instances_will_be_updated_c',
                  numInstancesToUpdate,
                  {
                    num: numInstancesToUpdate,
                  }
                )
              "
              :actionLabel="$t('common.cancel')"
              @action="cancelUpdateAllApps"
              :showCloseButton="false"
              :timer="UPDATE_DELAY"
            />
            <template v-if="isCoreUpdateAvailable && !loadingUpdates">
              <h4 class="mg-bottom-lg">
                {{ $t("software_center.core_update") }}
              </h4>
              <p class="title-description mg-bottom-lg">
                {{ $t("software_center.core_update_description") }}
              </p>
              <AppList
                :apps="[coreApp]"
                :skeleton="false"
                tab="updates"
                key="core-update"
                :light="true"
              />
            </template>
            <template v-if="appUpdates.length && !loadingUpdates">
              <h4 class="mg-bottom-lg">
                {{ $t("software_center.applications_update") }}
              </h4>
              <p
                v-if="subscriptionIsActive && applyUpdatesIsActive"
                class="title-description mg-bottom-lg"
              >
                {{ $t("software_center.applications_update_description") }}
              </p>
              <div v-if="!updateAllAppsTimeout" class="toolbar">
                <NsButton
                  kind="primary"
                  :icon="Upgrade20"
                  @click="willUpdateAllApps()"
                  :disabled="isUpdateInProgress"
                  >{{ $t("software_center.update_all_apps") }}</NsButton
                >
              </div>
              <AppList
                :apps="appUpdates"
                :skeleton="false"
                tab="updates"
                @install="openInstallModal"
                key="updates-app-list"
                :light="true"
              />
            </template>
            <AppList
              v-if="loadingUpdates"
              :apps="[]"
              :skeleton="true"
              tab="updates"
              key="updates-skeleton"
              :light="true"
            />
            <cv-tile
              v-if="
                !appUpdates.length &&
                !isCoreUpdateAvailable &&
                !loadingUpdates &&
                !error.listModules &&
                !error.listCoreModules
              "
              kind="standard"
              :light="true"
            >
              <NsEmptyState
                :title="$t('software_center.cluster_up_to_date')"
                :animationData="RocketLottie"
                animationTitle="rocket"
                :loop="1"
                key="updates-empty-state"
              >
                <template #description>
                  <p>{{ $t("software_center.no_updates_available") }}</p>
                </template>
              </NsEmptyState>
            </cv-tile>
          </div>
        </section>
        <div v-if="q.view === 'search'">
          <h6 class="search-results-title">
            {{ $t("software_center.search_results") }}
          </h6>
          <cv-tile
            v-if="!searchResults.length && !loading.listModules"
            kind="standard"
            :light="true"
          >
            <NsEmptyState
              :title="$t('software_center.no_app_found')"
              :animationData="GhostLottie"
              animationTitle="ghost"
              :loop="1"
              key="search-empty-state"
            >
              <template #description>
                {{ $t("software_center.no_app_found_description") }}
              </template>
            </NsEmptyState>
          </cv-tile>
          <AppList
            v-else
            :apps="searchResults"
            :skeleton="loading.listModules || loading.listCoreModules"
            tab="search"
            @install="openInstallModal"
            key="search-app-list"
            :light="true"
          />
        </div>
      </div>
    </cv-grid>
    <InstallAppModal
      :isShown="isShownInstallModal"
      :app="appToInstall"
      @close="isShownInstallModal = false"
      @installationCompleted="listModules"
    />
    <AutomaticUpdatesModal
      :visible="isShownAutomaticUpdatesModal"
      :enable="!applyUpdatesIsActive"
      @hide="isShownAutomaticUpdatesModal = false"
      @completed="onAutomaticUpdatesChanged"
    />
  </div>
</template>
⋮----
{{ $t("software_center.title") }}
⋮----
>{{
                $t("software_center.reload_software_repositories")
              }}</NsButton
⋮----
>{{ $t("software_center.all") }}</cv-content-switcher-button
⋮----
>{{ $t("software_center.installed") }}</cv-content-switcher-button
⋮----
>{{ $t("software_center.updates") }}</cv-content-switcher-button
⋮----
<template v-if="isCoreUpdateAvailable && !loadingUpdates">
              <h4 class="mg-bottom-lg">
                {{ $t("software_center.core_update") }}
              </h4>
              <p class="title-description mg-bottom-lg">
                {{ $t("software_center.core_update_description") }}
              </p>
              <AppList
                :apps="[coreApp]"
                :skeleton="false"
                tab="updates"
                key="core-update"
                :light="true"
              />
            </template>
⋮----
{{ $t("software_center.core_update") }}
⋮----
{{ $t("software_center.core_update_description") }}
⋮----
<template v-if="appUpdates.length && !loadingUpdates">
              <h4 class="mg-bottom-lg">
                {{ $t("software_center.applications_update") }}
              </h4>
              <p
                v-if="subscriptionIsActive && applyUpdatesIsActive"
                class="title-description mg-bottom-lg"
              >
                {{ $t("software_center.applications_update_description") }}
              </p>
              <div v-if="!updateAllAppsTimeout" class="toolbar">
                <NsButton
                  kind="primary"
                  :icon="Upgrade20"
                  @click="willUpdateAllApps()"
                  :disabled="isUpdateInProgress"
                  >{{ $t("software_center.update_all_apps") }}</NsButton
                >
              </div>
              <AppList
                :apps="appUpdates"
                :skeleton="false"
                tab="updates"
                @install="openInstallModal"
                key="updates-app-list"
                :light="true"
              />
            </template>
⋮----
{{ $t("software_center.applications_update") }}
⋮----
{{ $t("software_center.applications_update_description") }}
⋮----
>{{ $t("software_center.update_all_apps") }}</NsButton
⋮----
<template #description>
                  <p>{{ $t("software_center.no_updates_available") }}</p>
                </template>
⋮----
<p>{{ $t("software_center.no_updates_available") }}</p>
⋮----
{{ $t("software_center.search_results") }}
⋮----
<template #description>
                {{ $t("software_center.no_app_found_description") }}
              </template>
⋮----
{{ $t("software_center.no_app_found_description") }}
⋮----
<script>
import AppList from "@/components/software-center/AppList";
import to from "await-to-js";
import InstallAppModal from "@/components/software-center/InstallAppModal";
import AutomaticUpdatesModal from "@/components/software-center/AutomaticUpdatesModal";
import PauseOutline20 from "@carbon/icons-vue/es/pause--outline/20";
import PlayOutline20 from "@carbon/icons-vue/es/play--outline/20";
import {
  QueryParamService,
  UtilService,
  TaskService,
  IconService,
  LottieService,
  PageTitleService,
} from "@nethserver/ns8-ui-lib";
import { mapState, mapActions } from "vuex";
export default {
  name: "SoftwareCenter",
  components: {
    AppList,
    InstallAppModal,
    AutomaticUpdatesModal,
  },
  mixins: [
    IconService,
    QueryParamService,
    UtilService,
    TaskService,
    LottieService,
    PageTitleService,
  ],
  pageTitle() {
    return this.$t("software_center.title");
  },
  data() {
    return {
      UPDATE_DELAY: 10000,
      q: {
        search: "",
        view: "all",
      },
      minCharsForSearch: 1,
      maxResults: 50,
      searchFields: ["name", "description", "categories"],
      searchResults: [],
      modules: [],
      appUpdates: [],
      coreModules: [],
      repositories: [],
      updateAllAppsTimeout: 0,
      updateCoreTimeout: 0,
      isShownInstallModal: false,
      appToInstall: null,
      isCoreUpdateAvailable: false,
      coreApp: null,
      applyUpdatesIsActive: false,
      subscriptionIsActive: false,
      isShownAutomaticUpdatesModal: false,
      PauseOutline20,
      PlayOutline20,
      loading: {
        listModules: true,
        cleanRepositoriesCache: false,
        listCoreModules: true,
      },
      error: {
        listModules: "",
        cleanRepositoriesCache: "",
        listCoreModules: "",
        updateCore: "",
        updateModules: "",
      },
    };
  },
  computed: {
    ...mapState(["isUpdateInProgress"]),
    csbAllSelected() {
      return this.q.view === "all";
    },
    csbInstalledSelected() {
      return this.q.view === "installed";
    },
    csbUpdatesSelected() {
      return this.q.view === "updates";
    },
    loadingUpdates() {
      return this.loading.listModules || this.loading.listCoreModules;
    },
    updatesNotificationDescription() {
      if (this.isCoreUpdateAvailable && this.appUpdates.length) {
        return this.$tc(
          "software_center.core_and_app_updates_available",
          this.appUpdates.length,
          { numUpdates: this.appUpdates.length }
        );
      }
      if (this.isCoreUpdateAvailable) {
        return this.$t("software_center.core_updates_available_description");
      }
      return this.$tc(
        "software_center.you_have_updates",
        this.appUpdates.length,
        { numUpdates: this.appUpdates.length }
      );
    },
    installedModules() {
      return this.modules.filter((app) => {
        return app.installed.length;
      });
    },
    numInstancesToUpdate() {
      let numInstancesToUpdate = 0;
      for (const appToUpdate of this.appUpdates) {
        const instancesToUpdate = appToUpdate.updates.filter(
          (update) => update.update
        );
        numInstancesToUpdate += instancesToUpdate.length;
      }
      return numInstancesToUpdate;
    },
    testingRepositories() {
      return this.repositories
        .filter((repository) => repository.testing)
        .map((repository) => repository.name);
    },
    updatesAreDisabledForMigration() {
      return this.modules.some(
        (m) => m["disabled_updates_reason"] == "ns7_migration"
      );
    },
  },
  watch: {
    modules() {
      if (this.q.view === "search" && this.q.search) {
        this.searchApp(this.q.search);
      }
    },
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.watchQueryData(vm);
      vm.queryParamsToDataForCore(vm, to.query);
    });
  },
  beforeRouteUpdate(to, from, next) {
    this.queryParamsToDataForCore(this, to.query);
    next();
  },
  created() {
    this.listModules();
    this.listRepositories();
  },
  methods: {
    ...mapActions(["setUpdateInProgressInStore"]),
    async listModules() {
      this.loading.listModules = true;
      this.error.listModules = "";
      const taskAction = "list-modules";
      this.$root.$once(taskAction + "-completed", this.listModulesCompleted);
      this.$root.$once(taskAction + "-aborted", this.listModulesAborted);
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.listModules = this.getErrorMessage(err);
        this.loading.listModules = false;
        return;
      }
    },
    listModulesAborted(taskResult) {
      console.error("list-modules aborted", taskResult);
      this.loading.listModules = false;
      this.loading.listCoreModules = false;
      this.error.listModules = this.$t("error.generic_error");
    },
    async listRepositories() {
      const taskAction = "list-repositories";
      this.$root.$once(
        taskAction + "-completed",
        this.listRepositoriesCompleted
      );
      await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            isNotificationHidden: true,
          },
        })
      );
    },
    listRepositoriesCompleted(taskContext, taskResult) {
      this.repositories = taskResult.output;
    },
    listModulesCompleted(taskContext, taskResult) {
      this.loading.listModules = false;
      let modules = taskResult.output;
      modules.sort(this.sortByProperty("name"));
      let appUpdates = [];
      for (const module of modules) {
        const hasStableUpdate = module.updates.some((update) => update.update);
        if (hasStableUpdate) {
          appUpdates.push(module);
        }
        module.installed.sort(this.sortModuleInstances());
      }
      this.appUpdates = appUpdates;
      this.modules = modules;
      if (modules.length) {
        this.applyUpdatesIsActive = !!modules[0].apply_updates_is_active;
        this.subscriptionIsActive = !!modules[0].subscription_is_active;
      }
      this.listCoreModules();
    },
    async listCoreModules() {
      this.error.listCoreModules = "";
      this.loading.listCoreModules = true;
      const taskAction = "list-core-modules";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.listCoreModulesAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.listCoreModulesCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.listCoreModules = this.getErrorMessage(err);
        this.loading.listCoreModules = false;
        return;
      }
    },
    listCoreModulesAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.listCoreModules = this.$t("error.generic_error");
      this.loading.listCoreModules = false;
    },
    listCoreModulesCompleted(taskContext, taskResult) {
      const coreModules = taskResult.output;
      let isCoreUpdateAvailable = false;
      this.coreApp = {
        id: "core",
        name: this.$t("software_center.core_app_name", {
          productName: this.$root.config.PRODUCT_NAME,
        }),
        description: {
          en: this.$t("software_center.core_app_description", {
            productName: this.$root.config.PRODUCT_NAME,
          }),
        },
        installed: coreModules,
      };
      for (const coreApp of coreModules) {
        for (const coreInstance of coreApp.instances) {
          if (coreInstance.update) {
            isCoreUpdateAvailable = true;
          }
        }
      }
      if (isCoreUpdateAvailable) {
        this.isCoreUpdateAvailable = true;
      } else {
        this.isCoreUpdateAvailable = false;
      }
      this.coreModules = coreModules;
      this.loading.listCoreModules = false;
    },
    searchApp(query) {
      const cleanRegex = /[^a-zA-Z0-9]/g;
      const queryText = query.replace(cleanRegex, "");
      // empty search
      if (queryText.length == 0) {
        this.q.view = "all";
        return;
      }
      if (queryText.length < this.minCharsForSearch) {
        this.searchResults = this.modules;
        return;
      }
      this.q.view = "search";
      this.searchResults = this.modules.filter((app) => {
        return this.searchFields.some((searchField) => {
          if (app[searchField]) {
            if (searchField === "description") {
              const langCode = this.$root.$i18n.locale;
              let appDescription = app.description[langCode];
              if (!appDescription) {
                appDescription = app.description.en;
              }
              return new RegExp(queryText, "i").test(
                appDescription.replace(cleanRegex, "")
              );
            } else if (searchField === "categories") {
              return app.categories.some((category) => {
                return new RegExp(queryText, "i").test(
                  category.replace(cleanRegex, "")
                );
              });
            } else {
              // standard string search field
              return new RegExp(queryText, "i").test(
                app[searchField].replace(cleanRegex, "")
              );
            }
          } else {
            return false;
          }
        });
      }, this);
      if (this.searchResults.length) {
        // limit maximum number of apps
        if (this.searchResults.length > this.maxResults) {
          this.searchResults = this.searchResults.slice(0, this.maxResults);
        }
      }
    },
    contentSwitcherSelected(value) {
      this.q.search = "";
      this.q.view = value;
    },
    goToUpdates() {
      this.$router.replace("/software-center?view=updates");
    },
    goToSettingsSoftwareRepositories() {
      this.$router.push("/settings/software-repository");
    },
    willUpdateAllApps() {
      this.error.updateModules = "";
      this.updateAllAppsTimeout = setTimeout(() => {
        this.updateModules();
        this.updateAllAppsTimeout = 0;
      }, this.UPDATE_DELAY);
    },
    cancelUpdateAllApps() {
      clearTimeout(this.updateAllAppsTimeout);
      this.updateAllAppsTimeout = 0;
    },
    async updateModules() {
      this.error.updateModules = "";
      this.setUpdateInProgressInStore(true);
      const taskAction = "update-modules";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.updateModulesAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.updateModulesCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {},
          extra: {
            title: this.$t("software_center.update_all_apps"),
            description: this.$tc(
              "software_center.updating_n_instances_c",
              this.numInstancesToUpdate,
              {
                num: this.numInstancesToUpdate,
              }
            ),
            eventId,
            numInstances: this.numInstancesToUpdate,
            completion: {
              i18nString: "software_center.num_instances_updated",
              extraTextParams: ["numInstances"],
            },
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.updateModules = this.getErrorMessage(err);
        this.setUpdateInProgressInStore(false);
        return;
      }
    },
    updateModulesAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.setUpdateInProgressInStore(false);
    },
    updateModulesCompleted() {
      this.setUpdateInProgressInStore(false);
      this.listModules();
    },
    openInstallModal(app) {
      this.appToInstall = app;
      this.isShownInstallModal = true;
    },
    async cleanRepositoriesCache() {
      this.loading.cleanRepositoriesCache = true;
      this.error.cleanRepositoriesCache = "";
      const taskAction = "clean-repositories-cache";
      this.$root.$off(taskAction + "-aborted");
      this.$root.$once(
        taskAction + "-aborted",
        this.cleanRepositoriesCacheAborted
      );
      this.$root.$off(taskAction + "-completed");
      this.$root.$once(
        taskAction + "-completed",
        this.cleanRepositoriesCacheCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.loading.cleanRepositoriesCache = false;
        this.error.cleanRepositoriesCache = this.getErrorMessage(err);
        return;
      }
    },
    cleanRepositoriesCacheAborted(taskResult, taskContext) {
      this.loading.cleanRepositoriesCache = false;
      console.error(`${taskContext.action} aborted`, taskResult);
    },
    cleanRepositoriesCacheCompleted() {
      this.loading.cleanRepositoriesCache = false;
      this.listModules();
    },
    showSoftwareCenterCoreApps() {
      this.$router.push("/software-center/core-apps");
    },
    toggleAutomaticUpdates() {
      this.isShownAutomaticUpdatesModal = true;
    },
    onAutomaticUpdatesChanged(enable) {
      this.applyUpdatesIsActive = enable;
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../styles/carbon-utils";
.app-search {
  margin-bottom: $spacing-07;
}
.switcher {
  margin-bottom: $spacing-05;
}
.search-results-title {
  margin-top: $spacing-07;
  margin-bottom: $spacing-03;
}
</style>
</file>

<file path="core/ui/src/views/SoftwareCenterAppInstances.vue">
<template>
  <div>
    <cv-grid fullWidth>
      <cv-row>
        <cv-column>
          <cv-breadcrumb
            aria-label="breadcrumb"
            :no-trailing-slash="true"
            class="breadcrumb"
          >
            <cv-breadcrumb-item>
              <cv-link to="/software-center">{{
                $t("software_center.title")
              }}</cv-link>
            </cv-breadcrumb-item>
            <cv-breadcrumb-item>
              <span>{{ appName }}</span>
            </cv-breadcrumb-item>
          </cv-breadcrumb>
        </cv-column>
      </cv-row>
      <cv-row>
        <cv-column class="subpage-title">
          <h3>
            {{ $t("software_center.app_instances", { app: this.appName }) }}
          </h3>
        </cv-column>
      </cv-row>
      <cv-row v-if="error.listModules">
        <cv-column>
          <NsInlineNotification
            kind="error"
            :title="$t('action.list-modules')"
            :description="error.listModules"
            :showCloseButton="false"
          />
        </cv-column>
      </cv-row>
      <cv-row v-if="error.addFavorite">
        <cv-column>
          <NsInlineNotification
            kind="error"
            :title="$t('action.add-favorite')"
            :description="error.addFavorite"
            :showCloseButton="false"
          />
        </cv-column>
      </cv-row>
      <cv-row v-if="error.removeFavorite">
        <cv-column>
          <NsInlineNotification
            kind="error"
            :title="$t('action.remove-favorite')"
            :description="error.removeFavorite"
            :showCloseButton="false"
          />
        </cv-column>
      </cv-row>
      <cv-row v-if="error.updateModule">
        <cv-column>
          <NsInlineNotification
            kind="error"
            :title="$t('action.update-module')"
            :description="error.updateModule"
            :showCloseButton="false"
          />
        </cv-column>
      </cv-row>
      <cv-row v-if="updateInstancesTimeout">
        <cv-column>
          <NsInlineNotification
            kind="info"
            :title="
              $t('software_center.instances_update_will_start_in_a_moment')
            "
            :actionLabel="$t('common.cancel')"
            @action="cancelUpdateInstances"
            :showCloseButton="false"
            :timer="UPDATE_DELAY"
          />
        </cv-column>
      </cv-row>
      <cv-row v-if="app" class="toolbar">
        <cv-column>
          <NsButton
            v-if="isStableUpdateAvailableForAnyInstance()"
            kind="primary"
            :icon="Upgrade20"
            :disabled="isUpdateInProgress"
            @click="willUpdateAllInstances()"
            class="mg-right-sm"
            >{{ $t("software_center.update_all_instances") }}
          </NsButton>
          <div
            v-if="app.installed && app.installed.length"
            class="inline-flex items-center"
          >
            <NsButton
              kind="secondary"
              :icon="Download20"
              :disabled="!app.versions.length"
              @click="installInstance()"
              >{{ $t("software_center.install_new_instance") }}
            </NsButton>
            <cv-interactive-tooltip
              v-if="app.no_version_reason && app.no_version_reason.message"
              alignment="center"
              direction="bottom"
              class="info mg-left-sm"
            >
              <template slot="trigger">
                <Information16 />
              </template>
              <template slot="content">
                {{
                  $t(
                    `software_center.no_version_reason.${app.no_version_reason.message}`,
                    app.no_version_reason.params
                  )
                }}
              </template>
            </cv-interactive-tooltip>
          </div>
        </cv-column>
      </cv-row>
      <cv-row>
        <template v-if="loading.modules">
          <cv-column>
            <div
              class="card-grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 3xl:grid-cols-4"
            >
              <cv-tile v-for="index in 2" :key="index" light>
                <cv-skeleton-text
                  :paragraph="true"
                  :line-count="7"
                  heading
                ></cv-skeleton-text>
              </cv-tile>
            </div>
          </cv-column>
        </template>
        <cv-column v-else-if="!app.installed.length">
          <NsEmptyState :title="$t('software_center.no_instance_installed')">
            <template #description>
              <div class="inline-flex items-center">
                <NsButton
                  kind="primary"
                  :icon="Download20"
                  :disabled="!app.versions.length"
                  @click="installInstance()"
                  >{{ $t("software_center.install_new_instance") }}
                </NsButton>
                <cv-interactive-tooltip
                  v-if="app.no_version_reason && app.no_version_reason.message"
                  alignment="center"
                  direction="bottom"
                  class="info mg-left-sm"
                >
                  <template slot="trigger">
                    <Information16 />
                  </template>
                  <template slot="content">
                    {{
                      $t(
                        `software_center.no_version_reason.${app.no_version_reason.message}`,
                        app.no_version_reason.params
                      )
                    }}
                  </template>
                </cv-interactive-tooltip>
              </div>
            </template>
          </NsEmptyState>
        </cv-column>
        <cv-column v-else>
          <div
            class="card-grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 3xl:grid-cols-4"
          >
            <NsInfoCard
              v-for="(instance, index) in app.installed"
              :key="index"
              light
              :title="instance.ui_name ? instance.ui_name : instance.id"
              :icon="Application32"
              :class="{
                'highlight-me':
                  isElementHighlighted && elementToHighlight == instance.id,
              }"
            >
              <template #menu>
                <cv-overflow-menu
                  :flip-menu="true"
                  tip-position="top"
                  tip-alignment="end"
                  class="top-right-overflow-menu"
                  :data-test-id="index == 0 ? 'first' : ''"
                >
                  <cv-overflow-menu-item
                    primary-focus
                    v-if="isStableUpdateAvailable(app, instance)"
                    @click="openInstance(instance)"
                  >
                    <NsMenuItem
                      :icon="Application20"
                      :label="$t('software_center.open_app')"
                    />
                  </cv-overflow-menu-item>
                  <cv-overflow-menu-item
                    v-if="isStableUpdateAvailable(app, instance)"
                    :disabled="isUpdateInProgress"
                    @click="updateInstance(instance, false)"
                  >
                    <NsMenuItem
                      :icon="Upgrade20"
                      :label="
                        $t(
                          isTestingUpdateAvailable(app, instance)
                            ? 'software_center.update_to_stable_version'
                            : 'software_center.update'
                        )
                      "
                    />
                  </cv-overflow-menu-item>
                  <cv-overflow-menu-item
                    v-if="isTestingUpdateAvailable(app, instance)"
                    :disabled="isUpdateInProgress"
                    @click="updateInstance(instance, true)"
                  >
                    <NsMenuItem
                      :icon="Upgrade20"
                      :label="$t('software_center.update_to_testing_version')"
                    />
                  </cv-overflow-menu-item>
                  <cv-overflow-menu-item
                    v-if="!favoriteApps.includes(instance.id)"
                    @click="addFavorite(instance)"
                  >
                    <NsMenuItem
                      :icon="Star20"
                      :label="$t('software_center.add_to_favorites')"
                    />
                  </cv-overflow-menu-item>
                  <cv-overflow-menu-item
                    v-if="favoriteApps.includes(instance.id)"
                    @click="removeFavorite(instance)"
                  >
                    <NsMenuItem
                      :icon="Star20"
                      :label="$t('software_center.remove_from_favorites')"
                    />
                  </cv-overflow-menu-item>
                  <cv-overflow-menu-item
                    @click="showSetInstanceLabelModal(instance)"
                  >
                    <NsMenuItem
                      :icon="Edit20"
                      :label="$t('software_center.edit_instance_label')"
                    />
                  </cv-overflow-menu-item>
                  <cv-overflow-menu-item
                    @click="showRestartModuleModal(instance)"
                  >
                    <NsMenuItem
                      :icon="Restart20"
                      :label="$t('software_center.restart_instance')"
                    />
                  </cv-overflow-menu-item>
                  <cv-overflow-menu-item
                    v-if="isAutomaticUpdatesToggleShown(instance)"
                    @click="toggleInstanceAutomaticUpdates(instance)"
                  >
                    <NsMenuItem
                      :icon="
                        instance.automatic_updates
                          ? PauseOutline20
                          : PlayOutline20
                      "
                      :label="
                        instance.automatic_updates
                          ? $t('software_center.disable_automatic_updates')
                          : $t('software_center.enable_automatic_updates')
                      "
                    />
                  </cv-overflow-menu-item>
                  <cv-overflow-menu-item
                    @click="showCloneAppModal(instance)"
                    :data-test-id="index == 0 ? 'first-clone' : ''"
                  >
                    <NsMenuItem
                      :icon="Copy20"
                      :label="$t('software_center.clone')"
                    />
                  </cv-overflow-menu-item>
                  <cv-overflow-menu-item
                    @click="showMoveAppModal(instance)"
                    :disabled="clusterNodes.length < 2"
                  >
                    <NsMenuItem
                      :icon="ArrowRight20"
                      :label="$t('software_center.move')"
                    />
                  </cv-overflow-menu-item>
                  <NsMenuDivider />
                  <cv-overflow-menu-item
                    danger
                    @click="showUninstallModal(app, instance)"
                    :data-test-id="index == 0 ? 'first-uninstall' : ''"
                  >
                    <NsMenuItem
                      :icon="TrashCan20"
                      :label="$t('software_center.uninstall')"
                    />
                  </cv-overflow-menu-item>
                </cv-overflow-menu>
              </template>
              <template #content>
                <div class="instance-card-content">
                  <div v-if="instance.ui_name" class="row">
                    {{ instance.id }}
                  </div>
                  <div class="row icon-and-text">
                    <NsSvg :svg="Chip20" class="icon" />
                    <span v-if="instance.node_ui_name">{{
                      instance.node_ui_name
                    }}</span>
                    <span v-else
                      >{{ $t("common.node") }} {{ instance.node }}</span
                    >
                  </div>
                  <div class="row">
                    <span
                      >{{ $t("common.version") }} {{ instance.version }}</span
                    >
                  </div>
                  <div
                    v-if="isStableUpdateAvailable(app, instance)"
                    class="row"
                  >
                    {{
                      $t("software_center.version_version_available", {
                        version: stableUpdateVersion(app, instance),
                      })
                    }}
                  </div>
                  <div v-if="isUpdatesDisabledShown(instance)" class="row">
                    <cv-tag
                      kind="high-contrast"
                      :label="$t('software_center.updates_disabled')"
                    />
                  </div>
                  <div
                    v-if="
                      app.docs.relnotes_url &&
                      isStableUpdateAvailable(app, instance)
                    "
                    class="row"
                  >
                    <cv-link
                      class="row icon-and-text"
                      :href="app.docs.relnotes_url"
                      target="_blank"
                    >
                      <NsButton kind="ghost" :icon="Launch20">
                        {{ $t("common.release_notes") }}
                      </NsButton>
                    </cv-link>
                  </div>
                  <div class="row actions">
                    <template v-if="isStableUpdateAvailable(app, instance)">
                      <NsButton
                        kind="secondary"
                        :icon="Upgrade20"
                        @click="updateInstance(instance, false)"
                        :disabled="isUpdateInProgress"
                        >{{ $t("software_center.update") }}</NsButton
                      >
                    </template>
                    <template v-else>
                      <NsButton
                        kind="ghost"
                        :icon="Application20"
                        @click="openInstance(instance)"
                        >{{ $t("software_center.open_app") }}</NsButton
                      >
                    </template>
                  </div>
                </div>
              </template>
            </NsInfoCard>
          </div>
        </cv-column>
      </cv-row>
    </cv-grid>
    <InstallAppModal
      :isShown="isShownInstallModal"
      :app="app"
      @close="isShownInstallModal = false"
      @installationCompleted="onInstallationCompleted"
    />
    <UpdateAppModal
      :isShown="isShownUpdateModal"
      :app="app"
      :instance="instanceToUpdate"
      :isUpdatingToTestingVersion="isUpdatingToTestingVersion"
      @hide="isShownUpdateModal = false"
      @updateCompleted="onUpdateCompleted"
    />
    <AutomaticUpdatesModal
      :visible="isShownAutomaticUpdatesModal"
      :enable="enableAutomaticUpdatesForInstance"
      :instance="instanceToToggleAutomaticUpdates"
      @hide="isShownAutomaticUpdatesModal = false"
      @completed="onInstanceAutomaticUpdatesChanged"
    />
    <RestartModuleModal
      :visible="isShowRestartModuleModal"
      :instanceToRestart="instanceToRestart"
      @hide="hideRestartModuleModal"
    />
    <NsDangerDeleteModal
      :isShown="isShownUninstallModal"
      :name="instanceToUninstall ? instanceToUninstall.id : ''"
      :title="
        $t('software_center.app_uninstallation', {
          app: instanceToUninstallLabel,
        })
      "
      :warning="$t('common.please_read_carefully')"
      :description="
        $t('software_center.uninstall_app', {
          name: instanceToUninstallLabel,
        })
      "
      :typeToConfirm="
        $t('common.type_to_confirm', {
          name: instanceToUninstall ? instanceToUninstall.id : '',
        })
      "
      :isErrorShown="!!error.removeModule"
      :errorTitle="$t('action.remove-module')"
      :errorDescription="error.removeModule"
      @hide="isShownUninstallModal = false"
      @confirmDelete="uninstallInstance"
    />
    <SetInstanceLabelModal
      :visible="isShownEditInstanceLabel"
      :currentInstance="currentInstance"
      :newInstanceLabel="newInstanceLabel"
      @hide="hideSetInstanceLabelModal"
      @setInstanceLabelCompleted="listModules"
    />
    <CloneOrMoveAppModal
      :isShown="cloneOrMove.isModalShown"
      :isClone="cloneOrMove.isClone"
      :instanceId="cloneOrMove.instanceId"
      :instanceUiName="cloneOrMove.instanceUiName"
      :installationNode="cloneOrMove.installationNode"
      :app="app"
      @hide="cloneOrMove.isModalShown = false"
      @cloneOrMoveCompleted="onCloneOrMoveCompleted"
    />
  </div>
</template>
⋮----
<cv-link to="/software-center">{{
                $t("software_center.title")
              }}</cv-link>
⋮----
<span>{{ appName }}</span>
⋮----
{{ $t("software_center.app_instances", { app: this.appName }) }}
⋮----
>{{ $t("software_center.update_all_instances") }}
⋮----
>{{ $t("software_center.install_new_instance") }}
⋮----
<template slot="trigger">
                <Information16 />
              </template>
<template slot="content">
                {{
                  $t(
                    `software_center.no_version_reason.${app.no_version_reason.message}`,
                    app.no_version_reason.params
                  )
                }}
              </template>
⋮----
{{
                  $t(
                    `software_center.no_version_reason.${app.no_version_reason.message}`,
                    app.no_version_reason.params
                  )
                }}
⋮----
<template v-if="loading.modules">
          <cv-column>
            <div
              class="card-grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 3xl:grid-cols-4"
            >
              <cv-tile v-for="index in 2" :key="index" light>
                <cv-skeleton-text
                  :paragraph="true"
                  :line-count="7"
                  heading
                ></cv-skeleton-text>
              </cv-tile>
            </div>
          </cv-column>
        </template>
⋮----
<template #description>
              <div class="inline-flex items-center">
                <NsButton
                  kind="primary"
                  :icon="Download20"
                  :disabled="!app.versions.length"
                  @click="installInstance()"
                  >{{ $t("software_center.install_new_instance") }}
                </NsButton>
                <cv-interactive-tooltip
                  v-if="app.no_version_reason && app.no_version_reason.message"
                  alignment="center"
                  direction="bottom"
                  class="info mg-left-sm"
                >
                  <template slot="trigger">
                    <Information16 />
                  </template>
                  <template slot="content">
                    {{
                      $t(
                        `software_center.no_version_reason.${app.no_version_reason.message}`,
                        app.no_version_reason.params
                      )
                    }}
                  </template>
                </cv-interactive-tooltip>
              </div>
            </template>
⋮----
>{{ $t("software_center.install_new_instance") }}
⋮----
<template slot="trigger">
                    <Information16 />
                  </template>
<template slot="content">
                    {{
                      $t(
                        `software_center.no_version_reason.${app.no_version_reason.message}`,
                        app.no_version_reason.params
                      )
                    }}
                  </template>
⋮----
{{
                      $t(
                        `software_center.no_version_reason.${app.no_version_reason.message}`,
                        app.no_version_reason.params
                      )
                    }}
⋮----
<template #menu>
                <cv-overflow-menu
                  :flip-menu="true"
                  tip-position="top"
                  tip-alignment="end"
                  class="top-right-overflow-menu"
                  :data-test-id="index == 0 ? 'first' : ''"
                >
                  <cv-overflow-menu-item
                    primary-focus
                    v-if="isStableUpdateAvailable(app, instance)"
                    @click="openInstance(instance)"
                  >
                    <NsMenuItem
                      :icon="Application20"
                      :label="$t('software_center.open_app')"
                    />
                  </cv-overflow-menu-item>
                  <cv-overflow-menu-item
                    v-if="isStableUpdateAvailable(app, instance)"
                    :disabled="isUpdateInProgress"
                    @click="updateInstance(instance, false)"
                  >
                    <NsMenuItem
                      :icon="Upgrade20"
                      :label="
                        $t(
                          isTestingUpdateAvailable(app, instance)
                            ? 'software_center.update_to_stable_version'
                            : 'software_center.update'
                        )
                      "
                    />
                  </cv-overflow-menu-item>
                  <cv-overflow-menu-item
                    v-if="isTestingUpdateAvailable(app, instance)"
                    :disabled="isUpdateInProgress"
                    @click="updateInstance(instance, true)"
                  >
                    <NsMenuItem
                      :icon="Upgrade20"
                      :label="$t('software_center.update_to_testing_version')"
                    />
                  </cv-overflow-menu-item>
                  <cv-overflow-menu-item
                    v-if="!favoriteApps.includes(instance.id)"
                    @click="addFavorite(instance)"
                  >
                    <NsMenuItem
                      :icon="Star20"
                      :label="$t('software_center.add_to_favorites')"
                    />
                  </cv-overflow-menu-item>
                  <cv-overflow-menu-item
                    v-if="favoriteApps.includes(instance.id)"
                    @click="removeFavorite(instance)"
                  >
                    <NsMenuItem
                      :icon="Star20"
                      :label="$t('software_center.remove_from_favorites')"
                    />
                  </cv-overflow-menu-item>
                  <cv-overflow-menu-item
                    @click="showSetInstanceLabelModal(instance)"
                  >
                    <NsMenuItem
                      :icon="Edit20"
                      :label="$t('software_center.edit_instance_label')"
                    />
                  </cv-overflow-menu-item>
                  <cv-overflow-menu-item
                    @click="showRestartModuleModal(instance)"
                  >
                    <NsMenuItem
                      :icon="Restart20"
                      :label="$t('software_center.restart_instance')"
                    />
                  </cv-overflow-menu-item>
                  <cv-overflow-menu-item
                    v-if="isAutomaticUpdatesToggleShown(instance)"
                    @click="toggleInstanceAutomaticUpdates(instance)"
                  >
                    <NsMenuItem
                      :icon="
                        instance.automatic_updates
                          ? PauseOutline20
                          : PlayOutline20
                      "
                      :label="
                        instance.automatic_updates
                          ? $t('software_center.disable_automatic_updates')
                          : $t('software_center.enable_automatic_updates')
                      "
                    />
                  </cv-overflow-menu-item>
                  <cv-overflow-menu-item
                    @click="showCloneAppModal(instance)"
                    :data-test-id="index == 0 ? 'first-clone' : ''"
                  >
                    <NsMenuItem
                      :icon="Copy20"
                      :label="$t('software_center.clone')"
                    />
                  </cv-overflow-menu-item>
                  <cv-overflow-menu-item
                    @click="showMoveAppModal(instance)"
                    :disabled="clusterNodes.length < 2"
                  >
                    <NsMenuItem
                      :icon="ArrowRight20"
                      :label="$t('software_center.move')"
                    />
                  </cv-overflow-menu-item>
                  <NsMenuDivider />
                  <cv-overflow-menu-item
                    danger
                    @click="showUninstallModal(app, instance)"
                    :data-test-id="index == 0 ? 'first-uninstall' : ''"
                  >
                    <NsMenuItem
                      :icon="TrashCan20"
                      :label="$t('software_center.uninstall')"
                    />
                  </cv-overflow-menu-item>
                </cv-overflow-menu>
              </template>
<template #content>
                <div class="instance-card-content">
                  <div v-if="instance.ui_name" class="row">
                    {{ instance.id }}
                  </div>
                  <div class="row icon-and-text">
                    <NsSvg :svg="Chip20" class="icon" />
                    <span v-if="instance.node_ui_name">{{
                      instance.node_ui_name
                    }}</span>
                    <span v-else
                      >{{ $t("common.node") }} {{ instance.node }}</span
                    >
                  </div>
                  <div class="row">
                    <span
                      >{{ $t("common.version") }} {{ instance.version }}</span
                    >
                  </div>
                  <div
                    v-if="isStableUpdateAvailable(app, instance)"
                    class="row"
                  >
                    {{
                      $t("software_center.version_version_available", {
                        version: stableUpdateVersion(app, instance),
                      })
                    }}
                  </div>
                  <div v-if="isUpdatesDisabledShown(instance)" class="row">
                    <cv-tag
                      kind="high-contrast"
                      :label="$t('software_center.updates_disabled')"
                    />
                  </div>
                  <div
                    v-if="
                      app.docs.relnotes_url &&
                      isStableUpdateAvailable(app, instance)
                    "
                    class="row"
                  >
                    <cv-link
                      class="row icon-and-text"
                      :href="app.docs.relnotes_url"
                      target="_blank"
                    >
                      <NsButton kind="ghost" :icon="Launch20">
                        {{ $t("common.release_notes") }}
                      </NsButton>
                    </cv-link>
                  </div>
                  <div class="row actions">
                    <template v-if="isStableUpdateAvailable(app, instance)">
                      <NsButton
                        kind="secondary"
                        :icon="Upgrade20"
                        @click="updateInstance(instance, false)"
                        :disabled="isUpdateInProgress"
                        >{{ $t("software_center.update") }}</NsButton
                      >
                    </template>
                    <template v-else>
                      <NsButton
                        kind="ghost"
                        :icon="Application20"
                        @click="openInstance(instance)"
                        >{{ $t("software_center.open_app") }}</NsButton
                      >
                    </template>
                  </div>
                </div>
              </template>
⋮----
{{ instance.id }}
⋮----
<span v-if="instance.node_ui_name">{{
                      instance.node_ui_name
                    }}</span>
⋮----
>{{ $t("common.node") }} {{ instance.node }}</span
⋮----
>{{ $t("common.version") }} {{ instance.version }}</span
⋮----
{{
                      $t("software_center.version_version_available", {
                        version: stableUpdateVersion(app, instance),
                      })
                    }}
⋮----
{{ $t("common.release_notes") }}
⋮----
<template v-if="isStableUpdateAvailable(app, instance)">
                      <NsButton
                        kind="secondary"
                        :icon="Upgrade20"
                        @click="updateInstance(instance, false)"
                        :disabled="isUpdateInProgress"
                        >{{ $t("software_center.update") }}</NsButton
                      >
                    </template>
⋮----
>{{ $t("software_center.update") }}</NsButton
⋮----
<template v-else>
                      <NsButton
                        kind="ghost"
                        :icon="Application20"
                        @click="openInstance(instance)"
                        >{{ $t("software_center.open_app") }}</NsButton
                      >
                    </template>
⋮----
>{{ $t("software_center.open_app") }}</NsButton
⋮----
<script>
import to from "await-to-js";
import InstallAppModal from "../components/software-center/InstallAppModal";
import {
  QueryParamService,
  UtilService,
  TaskService,
  IconService,
  PageTitleService,
} from "@nethserver/ns8-ui-lib";
import { mapState, mapActions } from "vuex";
import CloneOrMoveAppModal from "@/components/software-center/CloneOrMoveAppModal";
import UpdateAppModal from "../components/software-center/UpdateAppModal";
import SetInstanceLabelModal from "@/components/software-center/SetInstanceLabelModal.vue";
import RestartModuleModal from "@/components/software-center/RestartModuleModal.vue";
import Information16 from "@carbon/icons-vue/es/information/16";
import PauseOutline20 from "@carbon/icons-vue/es/pause--outline/20";
import PlayOutline20 from "@carbon/icons-vue/es/play--outline/20";
import AutomaticUpdatesModal from "@/components/software-center/AutomaticUpdatesModal";
export default {
  name: "SoftwareCenterAppInstances",
  components: {
    InstallAppModal,
    CloneOrMoveAppModal,
    UpdateAppModal,
    Information16,
    SetInstanceLabelModal,
    RestartModuleModal,
    AutomaticUpdatesModal,
  },
  mixins: [
    TaskService,
    UtilService,
    IconService,
    QueryParamService,
    PageTitleService,
  ],
  pageTitle() {
    return this.$t("software_center.app_instances_no_name");
  },
  data() {
    return {
      UPDATE_DELAY: 10000,
      appName: "",
      app: null,
      PauseOutline20,
      PlayOutline20,
      subscriptionIsActive: false,
      applyUpdatesIsActive: false,
      isShownAutomaticUpdatesModal: false,
      instanceToToggleAutomaticUpdates: null,
      isShownInstallModal: false,
      isShownEditInstanceLabel: false,
      isShownUninstallModal: false,
      isShowRestartModuleModal: false,
      appToUninstall: null,
      instanceToUninstall: null,
      instanceToRestart: null,
      currentInstance: null,
      newInstanceLabel: "",
      elementToHighlight: "",
      isElementHighlighted: false,
      isShownUpdateModal: false,
      instanceToUpdate: null,
      updateInstancesTimeout: 0,
      isUpdatingToTestingVersion: false,
      cloneOrMove: {
        isModalShown: false,
        isClone: true,
        instanceId: "",
        instanceUiName: "",
        installationNode: 0,
      },
      loading: {
        modules: true,
        updateModule: false,
      },
      error: {
        listModules: "",
        removeModule: "",
        addFavorite: "",
        removeFavorite: "",
        setNodeLabel: "",
        updateModule: "",
      },
    };
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.watchQueryData(vm);
      vm.queryParamsToDataForCore(vm, to.query);
    });
  },
  beforeRouteUpdate(to, from, next) {
    this.queryParamsToDataForCore(this, to.query);
    next();
  },
  created() {
    this.appName = this.$route.params.appName;
    this.listModules();
  },
  computed: {
    ...mapState(["favoriteApps", "clusterNodes", "isUpdateInProgress"]),
    instanceToUninstallLabel() {
      if (!this.instanceToUninstall) {
        return "";
      }
      return this.instanceToUninstall.ui_name
        ? `${this.instanceToUninstall.ui_name} (${this.instanceToUninstall.id})`
        : this.instanceToUninstall.id;
    },
    updatableInstancesIds() {
      if (this.app) {
        return this.app.updates.map((instance) => instance.id);
      }
      return [];
    },
    // gates both the menu entry and the tag
    isAutomaticUpdatesOptOutAvailable() {
      return this.subscriptionIsActive && this.applyUpdatesIsActive;
    },
    enableAutomaticUpdatesForInstance() {
      const instance = this.instanceToToggleAutomaticUpdates;
      return instance ? instance.automatic_updates === false : false;
    },
  },
  methods: {
    ...mapActions(["setAppDrawerShownInStore", "setUpdateInProgressInStore"]),
    async listModules() {
      this.loading.modules = true;
      this.error.listModules = "";
      const taskAction = "list-modules";
      this.$root.$once(taskAction + "-completed", this.listModulesCompleted);
      this.$root.$once(taskAction + "-aborted", this.listModulesAborted);
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.loading.modules = false;
        this.error.listModules = this.getErrorMessage(err);
        return;
      }
    },
    listModulesAborted(taskResult) {
      console.error("list-modules aborted", taskResult);
      this.loading.modules = false;
      this.error.listModules = this.$t("error.generic_error");
    },
    isUpdatesDisabledShown(instance) {
      return (
        this.isAutomaticUpdatesOptOutAvailable &&
        instance.automatic_updates === false
      );
    },
    isAutomaticUpdatesToggleShown(instance) {
      return (
        this.isAutomaticUpdatesOptOutAvailable &&
        (this.app.certification_level >= 5 ||
          instance.automatic_updates === false)
      );
    },
    toggleInstanceAutomaticUpdates(instance) {
      this.instanceToToggleAutomaticUpdates = instance;
      this.isShownAutomaticUpdatesModal = true;
    },
    onInstanceAutomaticUpdatesChanged(enable) {
      if (this.instanceToToggleAutomaticUpdates) {
        this.instanceToToggleAutomaticUpdates.automatic_updates = enable;
      }
    },
    listModulesCompleted(taskContext, taskResult) {
      this.loading.modules = false;
      let modules = taskResult.output;
      let app = modules.find((module) => module.name === this.appName);
      if (app) {
        app.installed.sort(this.sortModuleInstances());
        this.app = app;
      }
      if (modules.length) {
        this.subscriptionIsActive = !!modules[0].subscription_is_active;
        this.applyUpdatesIsActive = !!modules[0].apply_updates_is_active;
      }
      if (this.elementToHighlight) {
        this.isElementHighlighted = true;
        setTimeout(() => {
          this.isElementHighlighted = false;
          this.elementToHighlight = "";
        }, 5000);
      }
    },
    isStableUpdateAvailable(app, instance) {
      return (
        app.updates &&
        app.updates.find((update) => {
          return update.id === instance.id && update.update;
        })
      );
    },
    isStableUpdateAvailableForAnyInstance() {
      if (this.app && this.app.updates) {
        return this.app.updates.some((update) => update.update);
      }
      return false;
    },
    stableUpdateVersion(app, instance) {
      if (app.updates.length) {
        const updateFound = app.updates.find((update) => {
          return update.id === instance.id && update.update;
        });
        if (updateFound) {
          return updateFound.update;
        } else {
          return "latest";
        }
      }
    },
    isTestingUpdateAvailable(app, instance) {
      return (
        app.updates &&
        app.updates.find((update) => {
          return update.id === instance.id && update.testing_update;
        })
      );
    },
    openInstance(instance) {
      this.$router.push(`/apps/${instance.id}`);
    },
    updateInstance(instance, isUpdatingToTestingVersion) {
      this.instanceToUpdate = instance;
      this.isUpdatingToTestingVersion = isUpdatingToTestingVersion;
      this.isShownUpdateModal = true;
    },
    addFavoriteCompleted() {
      this.$root.$emit("reloadAppDrawer");
      this.setAppDrawerShownInStore(true);
    },
    addFavoriteAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.addFavorite = this.$t("error.generic_error");
    },
    async addFavorite(app) {
      this.error.addFavorite = "";
      const taskAction = "add-favorite";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.addFavoriteAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.addFavoriteCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {
            instance: app.id,
          },
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.addFavorite = this.getErrorMessage(err);
        this.$root.$off(
          `${taskAction}-completed-${eventId}`,
          this.addFavoriteCompleted
        );
        this.$root.$off(
          `${taskAction}-aborted-${eventId}`,
          this.addFavoriteAborted
        );
        return;
      }
    },
    removeFavoriteCompleted() {
      this.$root.$emit("reloadAppDrawer");
      this.setAppDrawerShownInStore(true);
    },
    removeFavoriteAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.removeFavorite = this.$t("error.generic_error");
    },
    async removeFavorite(app) {
      this.error.removeFavorite = "";
      const taskAction = "remove-favorite";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.removeFavoriteAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.removeFavoriteCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {
            instance: app.id,
          },
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.removeFavorite = this.getErrorMessage(err);
        this.$root.$off(
          `${taskAction}-completed-${eventId}`,
          this.removeFavoriteCompleted
        );
        this.$root.$off(
          `${taskAction}-aborted-${eventId}`,
          this.removeFavoriteAborted
        );
        return;
      }
    },
    showUninstallModal(app, instance) {
      this.appToUninstall = app;
      this.instanceToUninstall = instance;
      this.error.removeModule = "";
      this.isShownUninstallModal = true;
    },
    async uninstallInstance() {
      this.error.removeModule = "";
      const taskAction = "remove-module";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.removeModuleAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.removeModuleCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {
            module_id: this.instanceToUninstall.id,
            preserve_data: false,
          },
          extra: {
            title: this.$t("software_center.instance_uninstallation", {
              instance: this.instanceToUninstall.ui_name
                ? this.instanceToUninstall.ui_name
                : this.instanceToUninstall.id,
            }),
            description: this.$t("software_center.uninstalling"),
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.removeModule = this.getErrorMessage(err);
        return;
      }
      this.isShownUninstallModal = false;
    },
    removeModuleAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.removeModule = this.$t("error.generic_error");
    },
    removeModuleCompleted() {
      this.listModules();
      this.$root.$emit("reloadAppDrawer");
    },
    showRestartModuleModal(instance) {
      this.instanceToRestart = instance;
      this.isShowRestartModuleModal = true;
    },
    hideRestartModuleModal() {
      this.isShowRestartModuleModal = false;
    },
    installInstance() {
      this.isShownInstallModal = true;
    },
    showSetInstanceLabelModal(instance) {
      this.currentInstance = instance;
      this.newInstanceLabel = instance.ui_name;
      this.isShownEditInstanceLabel = true;
    },
    hideSetInstanceLabelModal() {
      this.isShownEditInstanceLabel = false;
    },
    showCloneAppModal(instance) {
      this.cloneOrMove.isClone = true;
      this.cloneOrMove.instanceId = instance.id;
      this.cloneOrMove.instanceUiName = instance.ui_name;
      this.cloneOrMove.installationNode = parseInt(instance.node);
      this.cloneOrMove.isModalShown = true;
    },
    showMoveAppModal(instance) {
      this.cloneOrMove.isClone = false;
      this.cloneOrMove.instanceId = instance.id;
      this.cloneOrMove.instanceUiName = instance.ui_name;
      this.cloneOrMove.installationNode = parseInt(instance.node);
      this.cloneOrMove.isModalShown = true;
    },
    onCloneOrMoveCompleted(newModuleId) {
      this.elementToHighlight = newModuleId;
      this.listModules();
    },
    onInstallationCompleted(newModuleId) {
      this.elementToHighlight = newModuleId;
      this.listModules();
    },
    onUpdateCompleted() {
      this.listModules();
    },
    willUpdateAllInstances() {
      this.updateInstancesTimeout = setTimeout(() => {
        this.updateAllInstances();
        this.updateInstancesTimeout = 0;
      }, this.UPDATE_DELAY);
    },
    async updateAllInstances() {
      this.error.updateModule = "";
      this.setUpdateInProgressInStore(true);
      const taskAction = "update-modules";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.updateModuleAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.updateModuleCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {
            instances: this.updatableInstancesIds,
          },
          extra: {
            title: this.$t("software_center.update_app_instances", {
              app: this.app.name,
            }),
            description: this.$tc(
              "software_center.updating_n_instances_c",
              this.updatableInstancesIds.length,
              {
                num: this.updatableInstancesIds.length,
              }
            ),
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.updateModule = this.getErrorMessage(err);
        this.setUpdateInProgressInStore(false);
        return;
      }
    },
    updateModuleAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.setUpdateInProgressInStore(false);
    },
    updateModuleCompleted() {
      this.setUpdateInProgressInStore(false);
      this.listModules();
    },
    cancelUpdateInstances() {
      clearTimeout(this.updateInstancesTimeout);
      this.updateInstancesTimeout = 0;
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../styles/carbon-utils";
.instance-card-content .row {
  margin-bottom: $spacing-05;
  text-align: center;
}
.instance-card-content .row:last-child {
  margin-bottom: 0;
}
.actions {
  margin-top: $spacing-06;
}
</style>
</file>

<file path="core/ui/src/views/SoftwareCenterCoreApps.vue">
<template>
  <div>
    <cv-grid fullWidth>
      <cv-row>
        <cv-column :md="4" :xlg="10">
          <cv-breadcrumb
            aria-label="breadcrumb"
            :no-trailing-slash="true"
            class="breadcrumb"
          >
            <cv-breadcrumb-item>
              <cv-link to="/software-center">{{
                $t("software_center.title")
              }}</cv-link>
            </cv-breadcrumb-item>
            <cv-breadcrumb-item>
              <span>{{ $t("software_center.core_apps") }}</span>
            </cv-breadcrumb-item>
          </cv-breadcrumb>
        </cv-column>
      </cv-row>
      <cv-row>
        <cv-column class="subpage-title">
          <h2>{{ $t("software_center.core_apps") }}</h2>
        </cv-column>
      </cv-row>
      <cv-row>
        <cv-column>
          <NsInlineNotification
            v-if="isCoreUpdatable"
            kind="warning"
            :title="$t('software_center.core_app_update_available')"
            :description="
              $t('software_center.core_app_update_available_description')
            "
            :showCloseButton="false"
          />
        </cv-column>
      </cv-row>
      <cv-tile light>
        <cv-row>
          <cv-column>
            <NsButton
              class="mg-bottom-md"
              v-if="isCoreUpdatable"
              kind="primary"
              :icon="Upgrade20"
              :disabled="updateCoreTimeout || isUpdateInProgress"
              :loading="isUpdateInProgress"
              @click="onWillUpdateCore"
              >{{ $t("software_center.update_core") }}
            </NsButton>
            <div class="mg-bottom-md">
              {{
                $t("software_center.core_app_table_description", {
                  productName: $root.config.PRODUCT_NAME,
                })
              }}
            </div>
            <NsDataTable
              :allRows="coreInstances"
              :columns="i18nTableColumns"
              :rawColumns="tableColumns"
              :sortable="true"
              :overflow-menu="false"
              :isLoading="loading.listCoreModules"
              :skeletonRows="5"
              isSearchable
              :searchPlaceholder="$t('software_center.search_core_apps')"
              :searchClearLabel="$t('common.clear_search')"
              :noSearchResultsLabel="$t('common.no_search_results')"
              :noSearchResultsDescription="
                $t('common.no_search_results_description')
              "
              :itemsPerPageLabel="$t('pagination.items_per_page')"
              :rangeOfTotalItemsLabel="$t('pagination.range_of_total_items')"
              :ofTotalPagesLabel="$t('pagination.of_total_pages')"
              :backwardText="$t('pagination.previous_page')"
              :forwardText="$t('pagination.next_page')"
              :pageNumberLabel="$t('pagination.page_number')"
              @updatePage="tablePage = $event"
            >
              <template slot="data">
                <cv-data-table-row
                  v-for="(row, rowIndex) in tablePage"
                  :key="`${rowIndex}`"
                  :value="`${rowIndex}`"
                >
                  <cv-data-table-cell>
                    <a @click="showAppInfo(row)">{{
                      row.id
                    }}</a></cv-data-table-cell
                  >
                  <cv-data-table-cell>{{ row.node_id }}</cv-data-table-cell>
                  <cv-data-table-cell>{{ row.version }}</cv-data-table-cell>
                  <cv-data-table-cell v-if="isCoreUpdatable">
                    {{ row.update || "-" }}
                    <cv-link
                      v-if="row.docs && row.docs.relnotes_url && row.update"
                      :href="row.docs.relnotes_url"
                      target="_blank"
                    >
                      <NsButton kind="ghost" :icon="Launch20">
                        {{ $t("common.release_notes") }}
                      </NsButton></cv-link
                    >
                  </cv-data-table-cell>
                </cv-data-table-row>
              </template>
            </NsDataTable>
          </cv-column>
        </cv-row>
      </cv-tile>
    </cv-grid>
    <AppInfoModal
      :app="appInfo.app"
      :isShown="appInfo.isShown"
      @close="onClose"
    />
  </div>
</template>
⋮----
<cv-link to="/software-center">{{
                $t("software_center.title")
              }}</cv-link>
⋮----
<span>{{ $t("software_center.core_apps") }}</span>
⋮----
<h2>{{ $t("software_center.core_apps") }}</h2>
⋮----
>{{ $t("software_center.update_core") }}
⋮----
{{
                $t("software_center.core_app_table_description", {
                  productName: $root.config.PRODUCT_NAME,
                })
              }}
⋮----
<template slot="data">
                <cv-data-table-row
                  v-for="(row, rowIndex) in tablePage"
                  :key="`${rowIndex}`"
                  :value="`${rowIndex}`"
                >
                  <cv-data-table-cell>
                    <a @click="showAppInfo(row)">{{
                      row.id
                    }}</a></cv-data-table-cell
                  >
                  <cv-data-table-cell>{{ row.node_id }}</cv-data-table-cell>
                  <cv-data-table-cell>{{ row.version }}</cv-data-table-cell>
                  <cv-data-table-cell v-if="isCoreUpdatable">
                    {{ row.update || "-" }}
                    <cv-link
                      v-if="row.docs && row.docs.relnotes_url && row.update"
                      :href="row.docs.relnotes_url"
                      target="_blank"
                    >
                      <NsButton kind="ghost" :icon="Launch20">
                        {{ $t("common.release_notes") }}
                      </NsButton></cv-link
                    >
                  </cv-data-table-cell>
                </cv-data-table-row>
              </template>
⋮----
<a @click="showAppInfo(row)">{{
                      row.id
                    }}</a></cv-data-table-cell
⋮----
<cv-data-table-cell>{{ row.node_id }}</cv-data-table-cell>
<cv-data-table-cell>{{ row.version }}</cv-data-table-cell>
⋮----
{{ row.update || "-" }}
⋮----
{{ $t("common.release_notes") }}
⋮----
<script>
import {
  QueryParamService,
  UtilService,
  TaskService,
  IconService,
  LottieService,
  PageTitleService,
} from "@nethserver/ns8-ui-lib";
import { mapState, mapActions } from "vuex";
import to from "await-to-js";
import AppInfoModal from "@/components/software-center/AppInfoModal";
export default {
  name: "SoftwareCenterCoreApps",
  components: { AppInfoModal },
  mixins: [
    IconService,
    QueryParamService,
    UtilService,
    TaskService,
    LottieService,
    PageTitleService,
  ],
  pageTitle() {
    return this.$t("settings_sw_repositories.title");
  },
  data() {
    return {
      tablePage: [],
      tableColumns: [],
      updateCoreTimeout: 0,
      coreApp: null,
      appInfo: {
        isShown: false,
        app: null,
      },
      loading: {
        cleanRepositoriesCache: false,
        listCoreModules: true,
      },
      error: {
        cleanRepositoriesCache: "",
        listCoreModules: "",
        updateCore: "",
        updateModules: "",
      },
    };
  },
  computed: {
    ...mapState(["isUpdateInProgress", "clusterNodes"]),
    nodeIds() {
      return this.clusterNodes.map((node) => node.id);
    },
    isCoreUpdatable() {
      if (this.coreApp) {
        for (const coreApp of this.coreApp.installed) {
          for (const instance of coreApp.instances) {
            if (instance.update) {
              return true;
            }
          }
        }
      }
      return false;
    },
    coreInstances() {
      if (this.coreApp) {
        const coreInstances = [];
        for (const coreApp of this.coreApp.installed) {
          coreInstances.push(...coreApp.instances);
        }
        coreInstances.sort(this.sortByProperty("id"));
        return coreInstances;
      }
      return [];
    },
    i18nTableColumns() {
      return this.tableColumns.map((column) => {
        return this.$t("software_center." + column);
      });
    },
  },
  watch: {
    coreApp: function () {
      this.updateTableData();
    },
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.watchQueryData(vm);
      vm.queryParamsToDataForCore(vm, to.query);
    });
  },
  beforeRouteUpdate(to, from, next) {
    this.queryParamsToDataForCore(this, to.query);
    next();
  },
  created() {
    this.listCoreModules();
    this.updateTableData();
  },
  methods: {
    ...mapActions(["setUpdateInProgressInStore"]),
    onClose() {
      const context = this;
      setTimeout(() => {
        context.appInfo.isShown = false;
      }, 250);
    },
    showAppInfo(app) {
      this.appInfo.isShown = true;
      this.appInfo.app = app;
    },
    updateTableData() {
      this.tableColumns = this.isCoreUpdatable
        ? ["id", "node_id", "version", "update"]
        : ["id", "node_id", "version"];
    },
    async listCoreModules() {
      this.error.listCoreModules = "";
      this.loading.listCoreModules = true;
      const taskAction = "list-core-modules";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.listCoreModulesAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.listCoreModulesCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.listCoreModules = this.getErrorMessage(err);
        this.loading.listCoreModules = false;
        return;
      }
    },
    listCoreModulesAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.listCoreModules = this.$t("error.generic_error");
      this.loading.listCoreModules = false;
    },
    listCoreModulesCompleted(taskContext, taskResult) {
      let coreModules = taskResult.output;
      coreModules = coreModules.map((coreApp) => {
        coreApp.instances = coreApp.instances.map((instance) => {
          instance.node_id = this.getNodeLabel({
            id: instance.node_id,
            ui_name: instance.node_ui_name,
          });
          return instance;
        });
        return coreApp;
      });
      let isCoreUpdateAvailable = false;
      this.coreApp = {
        id: "core",
        name: this.$t("software_center.core_app_name", {
          productName: this.$root.config.PRODUCT_NAME,
        }),
        description: {
          en: this.$t("software_center.core_app_description", {
            productName: this.$root.config.PRODUCT_NAME,
          }),
        },
        installed: coreModules,
      };
      for (const coreApp of coreModules) {
        for (const coreInstance of coreApp.instances) {
          if (coreInstance.update) {
            isCoreUpdateAvailable = true;
            break;
          }
        }
      }
      if (isCoreUpdateAvailable) {
        this.isCoreUpdateAvailable = true;
      } else {
        this.isCoreUpdateAvailable = false;
      }
      this.coreModules = coreModules;
      this.loading.listCoreModules = false;
    },
    onWillUpdateCore() {
      const notification = {
        id: "updateCore",
        title: this.$t("software_center.core_update_will_start_in_a_moment"),
        type: "info",
        toastTimeout: this.DELETE_DELAY,
        actionLabel: this.$t("common.cancel"),
        action: {
          type: "callback",
          callback: this.cancelDeleteAddress,
        },
      };
      this.createNotificationForApp(notification);
      this.updateCoreTimeout = setTimeout(() => {
        this.deleteNotificationForApp("updateCore");
        this.updateCoreTimeout = 0;
        this.updateCore();
      }, this.DELETE_DELAY);
    },
    cancelDeleteAddress() {
      clearTimeout(this.updateCoreTimeout);
      this.deleteNotificationForApp("updateCore");
      this.updateCoreTimeout = 0;
    },
    async updateCore() {
      this.error.updateCore = "";
      this.setUpdateInProgressInStore(true);
      const taskAction = "update-core";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.updateCoreAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.updateCoreCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          data: {
            nodes: this.nodeIds,
          },
          extra: {
            title: this.$t("software_center.update_core"),
            description: this.$t("common.processing"),
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.updateCore = this.getErrorMessage(err);
        this.setUpdateInProgressInStore(false);
        return;
      }
    },
    updateCoreAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.setUpdateInProgressInStore(false);
    },
    updateCoreCompleted() {
      setTimeout(() => {
        this.setUpdateInProgressInStore(false);
        this.listCoreModules();
      }, 5000);
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../styles/carbon-utils";
</style>
</file>

<file path="core/ui/src/views/SystemLogs.vue">
<template>
  <cv-grid fullWidth class="system-logs">
    <cv-row>
      <cv-column class="page-title">
        <h2>{{ $t("system_logs.title") }}</h2>
      </cv-column>
    </cv-row>
    <cv-row>
      <cv-column>
        <div class="page-toolbar">
          <NsButton
            kind="secondary"
            size="field"
            :icon="Add20"
            @click="addSearch()"
            :disabled="searches.length > 1"
            class="page-toolbar-item add-search"
            >{{ $t("system_logs.add_search") }}</NsButton
          >
          <NsButton
            kind="ghost"
            size="field"
            :icon="filtersShown ? RowCollapse20 : RowExpand20"
            @click="toggleFilters()"
            class="page-toolbar-item"
            >{{
              filtersShown
                ? $t("system_logs.collapse_filters")
                : $t("system_logs.expand_filters")
            }}</NsButton
          >
          <NsButton
            kind="ghost"
            size="field"
            :icon="verticalLayout ? Row20 : Column20"
            :disabled="searches.length < 2"
            @click="toggleLayout()"
            class="page-toolbar-item toggle-layout"
            >{{
              verticalLayout
                ? $t("system_logs.horizontal_layout")
                : $t("system_logs.vertical_layout")
            }}</NsButton
          >
        </div>
      </cv-column>
    </cv-row>
    <cv-row class="landscape-warning">
      <cv-column>
        <NsInlineNotification
          kind="warning"
          :title="$t('common.use_landscape_mode')"
          :description="$t('common.use_landscape_mode_description')"
        />
      </cv-column>
    </cv-row>
    <cv-row v-if="error.listInstalledModules">
      <cv-column>
        <NsInlineNotification
          kind="error"
          :title="$t('action.list-installed-modules')"
          :description="error.listInstalledModules"
          :showCloseButton="false"
        />
      </cv-column>
    </cv-row>
    <cv-row v-if="error.listCoreModules">
      <cv-column>
        <NsInlineNotification
          kind="error"
          :title="$t('action.list-core-modules')"
          :description="error.listCoreModules"
          :showCloseButton="false"
        />
      </cv-column>
    </cv-row>
    <cv-row v-if="error.listNodes">
      <cv-column>
        <NsInlineNotification
          kind="error"
          :title="$t('action.list-nodes')"
          :description="error.listNodes"
          :showCloseButton="false"
        />
      </cv-column>
    </cv-row>
    <cv-row>
      <cv-column
        v-for="(searchId, index) in searches"
        :key="searchId"
        :md="verticalLayout ? 4 : 8"
      >
        <LogSearch
          :searchId="searchId"
          :nodes="internalNodes"
          :apps="apps"
          :lokiInstances="lokiInstances"
          :nodesInfo="nodesInfo"
          :loadingApps="loading.listInstalledModules"
          :loadingLoki="loading.lokiInstances"
          :verticalLayout="verticalLayout"
          :numSearches="searches.length"
          :mainSearch="index == 0"
          :searchQuery="q.searchQuery"
          :context="q.context"
          :selectedNodeId="q.selectedNodeId"
          :selectedAppId="q.selectedAppId"
          :selectedLokiId="q.selectedLokiId"
          :followLogs="q.followLogs"
          :regexp="q.regexp"
          :filtersShown="filtersShown"
          :maxLines="q.maxLines"
          :startDate="q.startDate"
          :startTime="q.startTime"
          :endDate="q.endDate"
          :endTime="q.endTime"
          :startSearchCommand="startSearchCommand"
          :closeAriaLabel="$t('common.close')"
          @close="closeSearch"
          @searchStarted="onSearchStarted"
          @updateSearchQuery="onUpdateSearchQuery"
          @updateContext="onUpdateContext"
          @updateSelectedNodeId="onUpdateSelectedNodeId"
          @updateSelectedAppId="onUpdateSelectedAppId"
          @updateFollowLogs="onUpdateFollowLogs"
          @updateRegexp="onUpdateRegexp"
          @updateMaxLines="onUpdateMaxLines"
          @updateStartDate="onUpdateStartDate"
          @updateStartTime="onUpdateStartTime"
          @updateEndDate="onUpdateEndDate"
          @updateEndTime="onUpdateEndTime"
          @updateTimezone="onUpdateTimezone"
          :light="true"
          :ref="'search-' + searchId"
          :timezone="q.timezone"
        />
      </cv-column>
    </cv-row>
  </cv-grid>
</template>
⋮----
<h2>{{ $t("system_logs.title") }}</h2>
⋮----
>{{ $t("system_logs.add_search") }}</NsButton
⋮----
>{{
              filtersShown
                ? $t("system_logs.collapse_filters")
                : $t("system_logs.expand_filters")
            }}</NsButton
⋮----
>{{
              verticalLayout
                ? $t("system_logs.horizontal_layout")
                : $t("system_logs.vertical_layout")
            }}</NsButton
⋮----
<script>
import to from "await-to-js";
import {
  UtilService,
  IconService,
  TaskService,
  QueryParamService,
  DateTimeService,
  PageTitleService,
} from "@nethserver/ns8-ui-lib";
import { v4 as uuidv4 } from "uuid";
import LogSearch from "@/components/system-logs/LogSearch.vue";
import { mapState } from "vuex";
export default {
  name: "SystemLogs",
  components: { LogSearch },
  mixins: [
    IconService,
    UtilService,
    TaskService,
    QueryParamService,
    DateTimeService,
    PageTitleService,
  ],
  pageTitle() {
    return this.$t("system_logs.title");
  },
  data() {
    return {
      q: {
        searchQuery: "",
        context: "cluster",
        selectedNodeId: "",
        selectedAppId: "",
        selectedLokiId: "",
        followLogs: false,
        regexp: false,
        maxLines: "500",
        startDate: "",
        startTime: "",
        endDate: "",
        endTime: "",
        autoStartSearch: false,
        timezone: "local",
      },
      internalNodes: [],
      apps: [],
      lokiInstances: [],
      coreVersions: {},
      nodeFqdns: {},
      clusterInfoRequested: false,
      searches: [],
      verticalLayout: false,
      filtersShown: true,
      startSearchCommand: 0,
      loading: {
        listInstalledModules: false,
        lokiInstances: false,
      },
      error: {
        listInstalledModules: "",
        lokiInstances: "",
        listCoreModules: "",
        listNodes: "",
      },
    };
  },
  computed: {
    ...mapState(["clusterNodes"]),
    nodesInfo() {
      return [...this.clusterNodes]
        .sort((a, b) => a.id - b.id)
        .map((node) => {
          const nodeId = node.id.toString();
          return {
            id: nodeId,
            uiName: node.ui_name || "",
            fqdn: this.nodeFqdns[nodeId] || "",
            coreVersion: this.coreVersions[nodeId] || "",
          };
        });
    },
  },
  watch: {
    clusterNodes: function () {
      if (this.clusterNodes.length) {
        this.initNodes();
      }
    },
    apps: function () {
      if (this.apps.length && this.q.autoStartSearch) {
        this.$nextTick(() => {
          this.startSearchCommand++;
        });
      }
    },
    lokiInstances: function () {
      if (this.lokiInstances.length && this.q.autoStartSearch) {
        this.$nextTick(() => {
          this.startSearchCommand++;
        });
      }
    },
  },
  created() {
    this.initTimeFilters();
    this.initNodes();
    this.listInstalledModules();
    this.getClusterLokiInstances();
    this.addSearch();
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.watchQueryData(vm);
      vm.queryParamsToDataForCore(vm, to.query);
    });
  },
  beforeRouteUpdate(to, from, next) {
    this.queryParamsToDataForCore(this, to.query);
    next();
  },
  methods: {
    initTimeFilters() {
      this.q.startDate = this.formatDate(
        this.subDays(new Date(), 1),
        "yyyy-MM-dd"
      );
      this.q.endDate = this.formatDate(new Date(), "yyyy-MM-dd");
    },
    addSearch() {
      const searchId = uuidv4();
      this.searches.push(searchId);
      this.$nextTick(() => {
        const el = this.$refs["search-" + searchId][0].$el;
        this.scrollToElement(el);
      });
    },
    initNodes() {
      let nodes = [];
      for (let node of this.clusterNodes) {
        nodes.push({
          name: node.id.toString(),
          label: node.ui_name
            ? node.ui_name + " (" + this.$t("common.node") + " " + node.id + ")"
            : this.$t("common.node") + " " + node.id,
          value: node.id.toString(),
        });
      }
      nodes.sort(this.sortByProperty("label"));
      this.internalNodes = nodes;
    },
    async listInstalledModules() {
      this.loading.listInstalledModules = true;
      const taskAction = "list-installed-modules";
      this.$root.$off(taskAction + "-aborted");
      this.$root.$once(
        taskAction + "-aborted",
        this.listInstalledModulesAborted
      );
      this.$root.$once(
        taskAction + "-completed",
        this.listInstalledModulesCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.listInstalledModules = this.getErrorMessage(err);
        return;
      }
    },
    listInstalledModulesAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.listInstalledModules = this.$t("error.generic_error");
      this.loading.listInstalledModules = false;
    },
    listInstalledModulesCompleted(taskContext, taskResult) {
      let apps = [];
      for (let instanceList of Object.values(taskResult.output)) {
        for (let instance of instanceList) {
          apps.push({
            name: instance.id,
            label:
              (instance.ui_name
                ? instance.ui_name + " (" + instance.id + ")"
                : instance.id) +
              " - " +
              (instance.node_ui_name
                ? instance.node_ui_name
                : this.$t("common.node") + " " + instance.node),
            value: instance.id,
            uiName: instance.ui_name || "",
            version: instance.version,
            node: String(instance.node),
          });
        }
      }
      apps.sort(this.sortByProperty("label"));
      this.apps = apps;
      this.loading.listInstalledModules = false;
    },
    onSearchStarted() {
      if (this.clusterInfoRequested) {
        return;
      }
      this.clusterInfoRequested = true;
      this.listCoreModules();
      this.listNodes();
    },
    async listCoreModules() {
      this.error.listCoreModules = "";
      const taskAction = "list-core-modules";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.listCoreModulesAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.listCoreModulesCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.listCoreModules = this.getErrorMessage(err);
      }
    },
    listCoreModulesAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.listCoreModules = this.$t("error.generic_error");
    },
    listCoreModulesCompleted(taskContext, taskResult) {
      const core = taskResult.output.find((module) => module.name == "core");
      if (!core || !core.instances.length) {
        return;
      }
      const coreVersions = {};
      for (const instance of core.instances) {
        coreVersions[String(instance.node_id)] = instance.version;
      }
      this.coreVersions = coreVersions;
    },
    async listNodes() {
      this.error.listNodes = "";
      const taskAction = "list-nodes";
      const eventId = this.getUuid();
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.listNodesAborted
      );
      this.$root.$once(
        `${taskAction}-completed-${eventId}`,
        this.listNodesCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.listNodes = this.getErrorMessage(err);
      }
    },
    listNodesAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.listNodes = this.$t("error.generic_error");
    },
    listNodesCompleted(taskContext, taskResult) {
      const nodeFqdns = {};
      for (const node of taskResult.output.nodes) {
        nodeFqdns[String(node.node_id)] = node.fqdn || "";
      }
      this.nodeFqdns = nodeFqdns;
    },
    async getClusterLokiInstances() {
      this.loading.lokiInstances = true;
      this.error.getClusterLokiInstances = "";
      const taskAction = "list-loki-instances";
      this.$root.$once(
        taskAction + "-aborted",
        this.getClusterLokiInstancesAborted
      );
      this.$root.$once(
        taskAction + "-completed",
        this.getClusterLokiInstancesCompleted
      );
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            isNotificationHidden: true,
          },
        })
      );
      const err = res[0];
      if (err) {
        console.error(`error creating task ${taskAction}`, err);
        this.error.getClusterLokiInstances = this.getErrorMessage(err);
        return;
      }
    },
    getClusterLokiInstancesAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
      this.error.lokiInstances = this.$t("error.generic_error");
      this.loading.lokiInstances = false;
    },
    getClusterLokiInstancesCompleted(taskContext, taskResult) {
      const lokiOutput = taskResult.output.instances.filter(
        (instance) => !instance.offline
      );
      let lokiInstances = [];
      for (let instance of lokiOutput) {
        let currentInstance = "";
        if (instance.active) {
          currentInstance =
            " (" + this.$t("system_logs.current_instance") + ")";
        }
        lokiInstances.push({
          name: instance.instance_id,
          label: instance.instance_label
            ? instance.instance_label +
              " - " +
              instance.instance_id +
              currentInstance
            : instance.instance_id + currentInstance,
          value: instance.instance_id,
          active: instance.active,
        });
      }
      this.lokiInstances = lokiInstances;
      this.q.selectedLokiId = lokiOutput.find(
        (instance) => instance.active === true
      ).instance_id;
      this.loading.lokiInstances = false;
    },
    toggleLayout() {
      this.verticalLayout = !this.verticalLayout;
    },
    toggleFilters() {
      this.filtersShown = !this.filtersShown;
    },
    closeSearch(searchId) {
      this.searches = this.searches.filter((s) => s !== searchId);
      this.verticalLayout = false;
      this.$root.$off(`logsStart-${this.searchId}`);
    },
    onUpdateSearchQuery(searchQuery) {
      this.q.searchQuery = searchQuery;
    },
    onUpdateContext(context) {
      this.q.context = context;
    },
    onUpdateSelectedNodeId(selectedNodeId) {
      this.q.selectedNodeId = selectedNodeId;
    },
    onUpdateSelectedAppId(selectedAppId) {
      this.q.selectedAppId = selectedAppId;
    },
    onUpdateFollowLogs(followLogs) {
      this.q.followLogs = followLogs;
    },
    onUpdateRegexp(regexp) {
      this.q.regexp = regexp;
    },
    onUpdateMaxLines(maxLines) {
      this.q.maxLines = maxLines;
    },
    onUpdateStartDate(startDate) {
      this.q.startDate = startDate;
    },
    onUpdateEndDate(endDate) {
      this.q.endDate = endDate;
    },
    onUpdateStartTime(startTime) {
      this.q.startTime = startTime;
    },
    onUpdateEndTime(endTime) {
      this.q.endTime = endTime;
    },
    onUpdateTimezone(timezone) {
      this.q.timezone = timezone;
    },
  },
};
</script>
⋮----
<style scoped lang="scss">
@import "../styles/carbon-utils";
.add-search {
  margin-right: auto;
}
.page-title {
  margin-bottom: 0;
}
.page-toolbar-item {
  margin-top: $spacing-05;
}
@media (max-width: $breakpoint-x-large) {
  .toggle-layout {
    display: none;
  }
}
</style>
</file>

<file path="core/ui/src/App.vue">
<template>
  <div id="core">
    <ShellHeader v-if="loggedUser && isClusterInitialized" />
    <SideMenu v-if="loggedUser && isClusterInitialized" />
    <MobileSideMenu v-if="loggedUser && isClusterInitialized" />
    <cv-content id="main-content">
      <router-view v-if="isLoaded" />
      <cv-loading :active="!isLoaded" :overlay="true"></cv-loading>
      <TaskErrorModal @hide="hideTaskErrorModal" />
    </cv-content>
  </div>
</template>
⋮----
<script>
import ShellHeader from "@/components/shell/ShellHeader";
import SideMenu from "@/components/shell/SideMenu";
import MobileSideMenu from "@/components/shell/MobileSideMenu";
import axios from "axios";
import WebSocketService from "@/mixins/websocket";
import { mapState, mapActions } from "vuex";
import to from "await-to-js";
import LoginService from "@/mixins/login";
import TaskErrorModal from "@/components/error/TaskErrorModal";
import NotificationService from "@/mixins/notification";
import {
  UtilService,
  TaskService,
  StorageService,
} from "@nethserver/ns8-ui-lib";
export default {
  name: "App",
  components: {
    ShellHeader,
    SideMenu,
    MobileSideMenu,
    TaskErrorModal,
  },
  mixins: [
    StorageService,
    WebSocketService,
    LoginService,
    TaskService,
    NotificationService,
    UtilService,
  ],
  data() {
    return {
      isMaster: true,
      isLoaded: false,
      welcomeMsg: [
        " _   _        _    _       _____                                  ___ ",
        "| \\ | |      | |  | |     / ____|                                / _ \\",
        "|  \\| |  ___ | |_ | |__  | (___    ___  _ __ __   __ ___  _ __  | (_) ",
        "| . ` | / _ \\| __|| '_ \\  \\___ \\  / _ \\| '__|\\ \\ / // _ \\| '__|  > _ <",
        "| |\\  ||  __/| |_ | | | | ____) ||  __/| |    \\ V /|  __/| |    | (_) ",
        "|_| \\_| \\___| \\__||_| |_||_____/  \\___||_|     \\_/  \\___||_|     \\___/",
        "                                                                      ",
        "                                                                      ",
      ].join("\n"),
    };
  },
  computed: {
    ...mapState(["loggedUser", "isClusterInitialized"]),
  },
  created() {
    // print message on console
    console.log("%c" + this.welcomeMsg, "background: #0090de; color: white;");
    // register to events
    this.$root.$on("login", this.initWebSocket);
    this.$root.$on("logout", this.logout);
    this.$root.$on("createErrorNotification", this.createErrorNotification);
    this.$root.$on("createNotificationForApp", this.createNotificationForApp);
    this.$root.$on("deleteNotificationForApp", this.deleteNotificationForApp);
    this.$root.$on(
      "configureKeyboardShortcuts",
      this.configureKeyboardShortcuts
    );
    this.$root.$on("clusterInitialized", this.onClusterInitialized);
    this.$root.$on("websocketConnected", this.onWebsocketConnected);
    this.$root.$on("websocketDisconnected", this.onWebsocketDisconnected);
    this.$root.$on("websocketError", this.onWebsocketError);
    this.$root.$on("websocketAuthError", this.onWebsocketAuthError);
    this.configureAxiosInterceptors();
    this.configureEventListeners();
    // check login
    const loginInfo = this.getFromStorage("loginInfo");
    if (loginInfo?.username) {
      this.setLoggedUserInStore(loginInfo.username);
      // verify token with WS authentication
      this.initWebSocket();
    } else {
      this.isLoaded = true;
    }
  },
  beforeDestroy() {
    this.closeWebSocket();
    window.removeEventListener("blur", this.clickOutsideDrawers);
    window.removeEventListener(
      "keydown",
      this.configureKeyboardShortcutsListener
    );
    // remove all event listeners
    this.$root.$off();
  },
  methods: {
    ...mapActions([
      "setLoggedUserInStore",
      "setClusterInitializedInStore",
      "setMobileSideMenuShownInStore",
      "setNotificationDrawerShownInStore",
      "setAppDrawerShownInStore",
      "toggleSearchExpandedInStore",
      "toggleAppDrawerShownInStore",
      "setLeaderListenPortInStore",
      "setWebsocketConnectedInStore",
      "setClusterLabelInStore",
      "setClusterNodesInStore",
      "hideTaskErrorInStore",
      "setLogoutInfoInStore",
    ]),
    configureKeyboardShortcuts(window) {
      window.addEventListener(
        "keydown",
        this.configureKeyboardShortcutsListener,
        false
      );
    },
    configureKeyboardShortcutsListener(e) {
      if (e.ctrlKey && e.shiftKey && e.code === "KeyA") {
        this.toggleAppDrawerShownInStore();
        // disable default behavior of shortcut
        e.preventDefault();
      } else if (e.ctrlKey && e.shiftKey && e.code === "KeyF") {
        this.toggleSearchExpandedInStore();
        // disable default behavior of shortcut
        e.preventDefault();
      } else if (e.ctrlKey && e.shiftKey && e.code === "KeyS") {
        this.$router.push("/status");
        this.setMobileSideMenuShownInStore(false);
        // disable default behavior of shortcut
        e.preventDefault();
      }
    },
    configureEventListeners() {
      // needed to detect click outside mobile side menu, app drawer and
      // notification drawer when the user is on an external app
      window.addEventListener("blur", this.clickOutsideDrawers);
      // global shortcuts
      this.configureKeyboardShortcuts(window);
    },
    clickOutsideDrawers() {
      if (document.activeElement.id == "app-frame") {
        // close side menu and drawers
        this.setMobileSideMenuShownInStore(false);
        this.setNotificationDrawerShownInStore(false);
        this.setAppDrawerShownInStore(false);
      }
    },
    configureClusterInitializationRedirect() {
      // if cluster has not been initialized, redirect to /init
      this.$router.beforeEach(async (to, from, next) => {
        if (this.isClusterInitialized) {
          if (to.path === "/init") {
            // cannot navigate to initialization page if cluster is already initialized
            return false;
          } else {
            next();
          }
        } else {
          // cluster not initialized
          if (to.path === "/init") {
            next();
          } else {
            // redirect: only /init is allowed
            next("/init?page=welcome");
          }
        }
      });
    },
    configureAxiosInterceptors() {
      const context = this;
      // response interceptor
      axios.interceptors.response.use(
        function (response) {
          return response;
        },
        function (error) {
          console.error(error);
          // print specific error message, if available
          if (error.response?.data?.message) {
            console.error(error.response.data.message);
          }
          // logout if 401 response code is intercepted
          if (error.response?.status == 401) {
            console.warn("Axios interceptor detected 401, logout");
            let sessionExpiredTitle = "";
            let sessionExpiredDescription = "";
            if (error.response?.data?.message === "Token is expired") {
              sessionExpiredTitle = context.$t("login.session_expired_title");
              sessionExpiredDescription = context.$t(
                "login.session_expired_description"
              );
            }
            context.$root.$emit(
              "logout",
              sessionExpiredTitle,
              sessionExpiredDescription
            );
          }
          return Promise.reject(error);
        }
      );
    },
    async logout(logoutInfoTitle, logoutInfoDescription) {
      // invoke logout API
      const res = await to(this.executeLogout());
      const logoutError = res[0];
      if (logoutError) {
        console.error(logoutError);
        return;
      }
      // update logout info in store
      const logoutInfo = {
        title: logoutInfoTitle || "",
        description: logoutInfoDescription || "",
      };
      this.setLogoutInfoInStore(logoutInfo);
      this.deleteFromStorage("loginInfo");
      this.setLoggedUserInStore("");
      this.closeWebSocket();
      this.isLoaded = true;
      // redirect to login page
      if (this.$route.name !== "Login") {
        this.$router.push("/login");
      }
      // hide websocket reconnection notification
      if (this.$options.sockets.notification) {
        this.hideNotification(this.$options.sockets.notification.id);
        this.$options.sockets.notification = null;
      }
    },
    async retrieveClusterStatus(initial) {
      const taskAction = "get-cluster-status";
      const eventId = this.getUuid();
      const completedCallback = initial
        ? this.getInitialClusterStatusCompleted
        : this.getClusterStatusCompleted;
      // register to task error
      this.$root.$once(
        `${taskAction}-aborted-${eventId}`,
        this.getClusterStatusAborted
      );
      // register to task completion
      this.$root.$once(`${taskAction}-completed-${eventId}`, completedCallback);
      const res = await to(
        this.createClusterTask({
          action: taskAction,
          extra: {
            title: this.$t("action." + taskAction),
            isNotificationHidden: true,
            eventId,
          },
        })
      );
      const err = res[0];
      if (err) {
        // check if node is a worker
        if (
          err.response?.status == 403 &&
          err.response.data?.data != "" // should return the leader HTTP host address
        ) {
          this.isMaster = false;
          // redirect to worker page
          this.$router.replace(
            "/init?page=redirect&endpoint=" + err.response.data.data
          );
          this.isLoaded = true;
        } else {
          this.createErrorNotification(
            err,
            this.$t("task.cannot_create_task", { action: taskAction })
          );
          this.isLoaded = true;
          return;
        }
      }
    },
    getClusterStatusAborted(taskResult, taskContext) {
      console.error(`${taskContext.action} aborted`, taskResult);
    },
    onClusterInitialized() {
      this.setClusterInitializedInStore(true);
      this.retrieveClusterStatus(false);
    },
    getInitialClusterStatusCompleted(taskContext, taskResult) {
      if (this.isMaster) {
        const clusterStatus = taskResult.output;
        const isClusterInitialized = clusterStatus.initialized;
        this.setClusterInitializedInStore(isClusterInitialized);
        this.setLeaderListenPortAndNodesInStore(clusterStatus);
        if (this.isClusterInitialized) {
          this.onClusterInitialized();
          this.isLoaded = true;
        } else {
          if (this.$route.name !== "InitializeCluster") {
            this.$router.replace("/init?page=welcome");
          }
          this.isLoaded = true;
        }
        this.configureClusterInitializationRedirect();
        this.setClusterLabelInStore(clusterStatus.ui_name);
      }
    },
    getClusterStatusCompleted(taskContext, taskResult) {
      if (this.isMaster) {
        const clusterStatus = taskResult.output;
        this.setLeaderListenPortAndNodesInStore(clusterStatus);
      }
    },
    setLeaderListenPortAndNodesInStore(clusterStatus) {
      if (clusterStatus.nodes.length) {
        const leaderNode = clusterStatus.nodes.find((el) => el.local);
        const leaderListenPort = leaderNode.vpn.listen_port;
        this.setLeaderListenPortInStore(leaderListenPort);
        const nodes = clusterStatus.nodes.sort(this.sortByProperty("id"));
        this.setClusterNodesInStore(nodes);
      }
    },
    onWebsocketConnected() {
      this.setWebsocketConnectedInStore(true);
      this.retrieveClusterStatus(true);
      if (this.$options.sockets.notification) {
        this.hideNotification(this.$options.sockets.notification.id);
        const notification = {
          title: this.$t("websocket.websocket_connected"),
          description: this.$t("websocket.websocket_connected_description"),
          type: "success",
          toastTimeout: 5000,
          actionLabel: null,
          action: null,
        };
        this.$options.sockets.notification = null;
        this.createNotification(notification);
      }
    },
    onWebsocketError(error) {
      console.error("WebsocketError", error);
    },
    onWebsocketAuthError(error) {
      console.error("WebsocketAuthError", error);
      const sessionExpiredTitle = this.$t("login.session_expired_title");
      const sessionExpiredDescription = this.$t(
        "login.session_expired_description"
      );
      this.logout(sessionExpiredTitle, sessionExpiredDescription);
    },
    onWebsocketDisconnected(event) {
      console.warn("Websocket disconnected", event);
      this.setWebsocketConnectedInStore(false);
      if (this.loggedUser && !this.$options.sockets.notification) {
        const notification = {
          title: this.$t("websocket.websocket_disconnected"),
          description: this.$t("websocket.websocket_disconnected_description"),
          type: "warning",
          toastTimeout: 0,
          actionLabel: this.$t("websocket.reload"),
          action: {
            type: "callback",
            callback: () => {
              location.reload();
            },
          },
        };
        this.$options.sockets.notification = notification;
        this.createNotification(notification);
      }
      setTimeout(() => {
        if (this.loggedUser) {
          console.warn("Retrying websocket connection...");
          this.initWebSocket();
        }
      }, 10000);
    },
    createErrorNotification(err, message) {
      const notification = {
        title: message,
        description: this.getErrorMessage(err),
        type: "error",
      };
      this.createNotification(notification);
    },
    createNotificationForApp(notification) {
      this.createNotification(notification);
    },
    deleteNotificationForApp(notification) {
      this.deleteNotification(notification);
    },
    hideTaskErrorModal() {
      this.hideTaskErrorInStore();
    },
  },
};
</script>
⋮----
<style lang="scss">
@import "./styles/core";
</style>
</file>

<file path="core/ui/src/main.js">
async function loadI18n()
⋮----
render: (h)
</file>

<file path="core/ui/.eslintrc.js">

</file>

<file path="core/ui/.yarnrc.yml">
yarnPath: .yarn/releases/yarn-3.8.7.cjs
nodeLinker: node-modules
</file>

<file path="core/ui/babel.config.js">

</file>

<file path="core/ui/Containerfile">
FROM node:24-bookworm-slim
# renovate: datasource=npm packageName=corepack
ARG COREPACK_VERSION=0.36.0
RUN npm install -g corepack@${COREPACK_VERSION} \
    && corepack enable
WORKDIR /app
ENV NODE_OPTIONS=--openssl-legacy-provider
EXPOSE 8080
ENTRYPOINT ["./container-entrypoint.sh"]
</file>

<file path="core/ui/package.json">
{
  "name": "ns8-ui",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint",
    "watch": "vue-cli-service build --watch",
    "format": "prettier --write src/"
  },
  "dependencies": {
    "@carbon/grid": "^10.26.0",
    "@carbon/icons-vue": "^10.37.0",
    "@carbon/themes": "^10.34.0",
    "@carbon/vue": "^2.40.0",
    "@nethserver/ns8-ui-lib": "^2.2.0",
    "await-to-js": "^3.0.0",
    "axios": "^1.20.0",
    "carbon-components": "^10.41.0",
    "core-js": "^3.6.5",
    "d3": "^7.1.1",
    "lodash": "^4.17.21",
    "lottie-web-vue": "^1.2.0",
    "mark.js": "^8.11.1",
    "papaparse": "^5.5.3",
    "qrcode.vue": "^1.7.0",
    "uuid": "^10.0.0",
    "vue": "^2.7.0",
    "vue-axios": "^3.2.4",
    "vue-clipboard2": "^0.3.3",
    "vue-date-fns": "^2.0.1",
    "vue-debounce": "^3.0.0",
    "vue-gallery": "^2.0.1",
    "vue-i18n": "^8.24.4",
    "vue-infinite-loading": "^2.4.5",
    "vue-native-websocket": "^2.0.14",
    "vue-router": "^3.2.0",
    "vue-text-highlight": "^2.0.10",
    "vue-toastification": "^1.7.11",
    "vue2-timepicker": "^1.1.6",
    "vuex": "^3.4.0"
  },
  "devDependencies": {
    "@babel/core": "^7.14.3",
    "@babel/eslint-parser": "^7.11.0",
    "@vue/cli-plugin-babel": "~4.5.18",
    "@vue/cli-plugin-eslint": "~4.5.18",
    "@vue/cli-plugin-router": "~4.5.18",
    "@vue/cli-plugin-vuex": "~4.5.18",
    "@vue/cli-service": "~4.5.18",
    "@vue/eslint-config-prettier": "^6.0.0",
    "babel-loader": "^8.2.2",
    "css-loader": "^5.2.6",
    "eslint": "^6.7.2",
    "eslint-plugin-prettier": "^3.3.1",
    "eslint-plugin-vue": "^6.2.2",
    "prettier": "^2.2.1",
    "sass": "^1.34.1",
    "sass-loader": "^10.1.1",
    "style-loader": "^2.0.0",
    "vue-loader": "^15.10.0"
  },
  "packageManager": "yarn@3.8.7"
}
</file>

<file path="core/ui/README.md">
# NethServer 8 UI

NethServer 8 UI implements the user interface of the core. It is a web application developed with [VueJs](https://vuejs.org/) and based on [Carbon Design System](https://www.carbondesignsystem.com/).

You can find more information about NethServer 8 UI in the [Developer manual](https://nethserver.github.io/ns8-core/ui/#user-interface).

## Development

To develop NethServer 8 Core UI please refer to [this section of the Developer manual](https://nethserver.github.io/ns8-core/ui/core/#core-ui-development).
</file>

<file path="core/ui/vue.config.js">
chainWebpack: (config) =>
</file>

<file path="docs/core/agents.md">
---
layout: default
title: Agents
nav_order: 3
parent: Core
---

# Agents

Agents are daemons that listens to Redis queues and execute tasks inside the system.

* TOC
{:toc}

## Agent types

The core `cluster` and `node` agent, and every module instance run their
own `agent` process. The process is started by the `agent.service` Systemd
user unit and the `agent@.service` Systemd system template unit provided
by the core.

Systemd units for agents are:

- `agent@cluster.service` running as root. Its
  actions are defined in `/var/lib/nethserver/cluster/actions`

- `agent@node.service` running as root. Its actions
  are defined in `/var/lib/nethserver/node/actions`

- `agent.service` running as non-privileged Unix user
  for each rootless module instance. See the "Additional modules" section
  below for more details

See also the [Agent documentation](https://github.com/NethServer/ns8-core/blob/main/core/agent/README.md).

## Tasks processing

Agents wait for tasks on a Redis list. Only the `cluster` agent and the
`api-server` are allowed to push a new task for an arbitrary module agent. The
task contain two main attributes: the action name (`action`), and the
action input (`data`).

The following Redis command run the `list-actions` action on the cluster agent:

    LPUSH cluster/tasks '{"id":"1a4a3965-d8d2-4c22-99d5-e17e6a5db36b","action":"list-actions","data":{}}'

Read the action output:

    GET task/cluster/1a4a3965-d8d2-4c22-99d5-e17e6a5db36b/output

The action output is a string in JSON format.

```json
[
  "list-actions",
  "destroy-module",
  "add-module",
  "add-user",
  "remove-module",
  "remove-repository",
  "update-routes",
  "alter-user",
  "grant-actions",
  "remove-user",
  "add-repository",
  "get-module-info",
  "join-cluster",
  "list-installed-modules",
  "list-updates",
  "revoke-actions",
  "create-module",
  "get-status",
  "add-node",
  "alter-repository",
  "create-cluster",
  "list-modules",
  "list-repositories"
]
```

Read the collected stderr data from the action steps:

    GET task/cluster/1a4a3965-d8d2-4c22-99d5-e17e6a5db36b/error

Read the originally submitted task payload:

    GET task/cluster/1a4a3965-d8d2-4c22-99d5-e17e6a5db36b/context

Read the action exit code:

    GET task/cluster/1a4a3965-d8d2-4c22-99d5-e17e6a5db36b/exit_code

The above keys are transient. After a few hours they are evicted. This
command return the remaining key TTL (Time To Live), in seconds.

    TTL task/cluster/1a4a3965-d8d2-4c22-99d5-e17e6a5db36b/error

While the action is running, some messages are sent through the progress
channel. It is possible to get them by subscribing the channel.

    SUBSCRIBE progress/cluster/task/1a4a3965-d8d2-4c22-99d5-e17e6a5db36b

## Tasks submission

The Python package `agent.tasks` implements the task processing, handling
communication errors and re-connection/retrying logic at every stage, like:

- Task submission
- Task progress tracking
- Task response parsing
- Task cancellation when the TERM signal is received

Example:

```python
import agent.tasks
print(agent.tasks.run(agent_id='cluster', action='list-actions', endpoint='redis://cluster-leader'))
```

Note the `endpoint=` argument: it uses the `redis://` protocol, that
requires `cluster` privileges to work.

As said above, only the `cluster` agent and `api-server` are allowed to
LPUSH new tasks in Redis. Module agents must submit tasks for other agents
as HTTP requests, through the `api-server`.

> **Note:** the API server only accepts agent credentials (`cluster`,
> `node/*`, `module/*`) from the loopback or cluster VPN network.
> Therefore `agent.tasks` works correctly only when called from an action
> step running on a cluster node (not from an external host).

Basically this can be done in two steps:

1. obtain a JWT token with the module Redis credentials
2. send the task request

The Python module `agent.tasks` implements the two steps internally.

It has a few assumptions, that are always satisfied by an action step environment:

* It obtain the module credentials from the environment from `REDIS_USER`
  and `REDIS_PASSWORD`
* It stores the JWT token in the current working directory (the file is
  `./apitoken.cache`)

This is an example call, note that the `agent_id` is obtained from the
environment.

```python
import agent.tasks, os
print(agent.tasks.run(agent_id=os.environ['AGENT_ID'], action='list-actions'))
```

The above call fails, because agents are not generally authorized to run
`list-actions`. However, just for this example, it is possible to override
the Redis credentials received from the environment.

```python
import agent.tasks, os
os.environ['REDIS_USER'] = 'admin'
os.environ['REDIS_PASSWORD'] = 'Nethesis,1234'
print(agent.tasks.run(agent_id=os.environ['AGENT_ID'], action='list-actions'))
```

The next section explains how to authorize agents to run actions through
roles assignment, and typical error messages if they are not properly set
up.

## Roles and authorizations

In normal conditions module actions must be assigned to `roles`, and roles
must be granted to agents and users. Symptoms of misconfigured roles and
authorizations are `api-server` log lines like

    [AUTH] error retrieving user authorizations: redis: nil

The task execution typically fails with a 403 error. Sometimes the UI
displays an "Authorization error" or "Permission error" notification.

In Redis, a SET defines the actions assigned to a role. If default
assignments are not enough the set can be modified by the module during
the `create-module` action.  A set element represent an exact action name
or an action name pattern, expressed in [glob-pattern
syntax](https://pkg.go.dev/path/filepath#Match) (e.g. `get-*`).

The core defines two builtin roles on every module, every node and on
the cluster:

- `owner` can run any action (`*`)
- `reader` can run actions matching `list-*`, `get-*`, `show-*` and
  `read-*`

A read-only action needs no extra role. Give it one of these prefixes
and any agent or user with the `reader` role can run it. Another module
requests it like any other role, for example
`org.nethserver.authorizations = mariadb@any:reader`. For this reason
actions with these prefixes must never return passwords or other
secrets.

The following Bash command in the `create-module` action allows agents
with the `actionsreader` role to run `list-actions` on `AGENT_ID` (e.g.
`module/mymod1`).

```sh
redis-exec SADD "${AGENT_ID}/roles/actionsreader" "list-actions"
```

Same as above, but to allow also any other action with name prefix `list-`:

```sh
redis-exec SADD "${AGENT_ID}/roles/actionsreader" "list-*"
```

Now it is possible to grant the role `actionsreader` on `module/mymod1` to
another agent (e.g. `module/authmod2`). This is the corresponding Redis command:

    HSET roles/module/authmod2 module/mymod1 actionsreader

Granted permissions are stored in Redis HASH keys with `roles/`
prefix. For example the `roles/admin` key stores the granted permissions
for the `admin` user, you can inspect it with this Redis
command:

    HGETALL roles/admin

It works the same for a module. A module key is for example
`roles/module/traefik1`:

    HGETALL roles/module/traefik1

If the module instance needs to run its own actions, extend the builtin
role `selfadm`. A basic role definition is set up by the builtin step
`10selfadm_role`. It adds `configure-module` to the `selfadm` role during
the module instance creation. If this is undesirable, override the builtin
step.

For instance add the following command in a Bash step of
`configure-module`:

```sh
redis-exec SADD "${AGENT_ID}/roles/selfadm" "get-configuration"
```

Roles are always granted by the `cluster` agent.  Users with the `owner`
role on `cluster` (cluster administrators) can use the following cluster
actions to manage users and their roles:

- `add-user`
- `remove-user`
- `grant-actions`
- `revoke-actions`

Those actions are implemented with the `cluster.grants` Python module.

A module can require additional roles to other modules when it is
instantiated. Set the label `org.nethserver.authorizations` of the module
image to a space separated list of values. Each value describes what is
the required role and what are the modules. The value syntax is `{agent
selector}:{role}`. For instance

    org.nethserver.authorizations = mymod@node:actionsreader funmod@cluster:rolex coolmod@any:roley

If the installed module is `authmod2`, the above label is interpreted in
the following way:

1. grant `authmod2` role `actionsreader` on the _default instance_ of
   module `mymod` running on the same node (`@node` suffix). The first
   instance of `mymod` installed on the node of `authmod2` is usually the
   default one.

2. grant `authmod2` role `rolex` on the _default instance_ of `funmod` at
   cluster level (`@cluster` suffix). That means the first instance of `funmod`
   installed in the cluster on any node.

3. grant `authmod2` role `roley` on any existing instance of module `coolmod`.

To request more than one role on the same agent, write the agent selector
once and separate the roles with a comma, without spaces. For instance

    org.nethserver.authorizations = node:fwadm,portsadm

If the agent selector is repeated (no matter its `@suffix` qualifier), the initial values are ignored and the last value is assigned. For example, a label like `node:fwadm node:portsadm`, is equal to `node:portsadm`.

Other possible *agent selector* values:

- `self` - selects the module itself. Note that the module instance is
  implicitly granted the role `selfadm` on itself.
- `cluster` - selects the cluster agent
- `node` - selects the node agent where the module is running

Depending on the running node ID the value resolves to an agent ID. The above rules
are implemented in Python by the `agent.resolve_agent_id()` function

```python
import agent, os
print(agent.resolve_agent_id('traefik@node', node_id=os.getenv('NODE_ID', 1)))
```

The `node_id` argument is optional.
</file>

<file path="docs/core/api_server.md">
---
layout: default
title: API server
nav_order: 4
parent: Core
---

# API server

The API server is a daemon implemented using [Go](https://golang.org) and
listens on TCP port `9311`.

This component is used to send command from UI to Redis, using HTTP Rest API and Redis Pub/Sub protocol.

* TOC
{:toc}

## API Paths

APIs are documented using a [swagger.json file](https://raw.githubusercontent.com/NethServer/ns8-core/swagdoc/swagger.json).
To browse all existing APIs, use the [Swagger UI](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/NethServer/ns8-core/swagdoc/swagger.json).

API flow:
- authenticate the user using the `login` API
- extract the JWT token from the login API response
- use the token to execute all next API calls

Authentication:
```bash
curl -X 'POST' \
  'http://localhost:9311/api/login' \
  -H 'accept: application/json' \
  -H 'Content-Type: application/json' \
  -d '{"username": "admin", "password": "Nethesis,12345"}' | jq
```

Response, note the JWT token saved inside the `token` field:
```json
{
  "code": 200,
  "expire": "2022-02-01T13:54:50Z",
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY3Rpb25zIjpbXSwiZXhwIjoxNjQzNzIzNjkwLCJpZCI6ImFkbWluIiwib3JpZ19pYXQiOjE2NDMxMTg4OTAsInJvbGUiOiIifQ.BzzmleO6ln40DQUZr4FUyFTFEle6PkK-ar-vqwXJ5uo"
}
```

Use the obtained JWT `token` to list configured nodes:
```bash
curl -X 'GET' \
  'http://localhost:9311/api/nodes' \
  -H 'accept: application/json' \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY3Rpb25zIjpbXSwiZXhwIjoxNjQzNzIzNjkwLCJpZCI6ImFkbWluIiwib3JpZ19pYXQiOjE2NDMxMTg4OTAsInJvbGUiOiIifQ.BzzmleO6ln40DQUZr4FUyFTFEle6PkK-ar-vqwXJ5uo"
```

Response:
```json
{
  "code": 200,
  "data": {
    "list": [
      "1"
    ],
    "queue": "node/*"
  },
  "message": "success"
}
```

You can also use the shortcut command called `api-cli`.
Usage example:
```
# api-cli list-actions
node/1/get-node-status
...
```

## Network access control

The API server enforces source-IP restrictions at login time and on every
authenticated request.

### Agent credentials

Credentials belonging to the internal agents — `cluster`, `node/*`, and
`module/*` — are **always** restricted to the loopback addresses
(`127.0.0.1`, `::1`) and the cluster VPN network (stored in the Redis key
`cluster/network`).  Login attempts from any other source IP are rejected
with HTTP 401, and requests carrying a JWT obtained with agent credentials
are rejected with HTTP 403 when the source IP is outside those networks.
This rule is unconditional and cannot be changed per-user.

### User accounts

Regular user accounts (e.g. `admin`) can optionally be given an
`allowed_networks` restriction through the `cluster/add-user` and
`cluster/alter-user` actions.  When the list is non-empty, login attempts
from IPs that do not match any entry are rejected with HTTP 401, and
requests carrying a JWT are rejected with HTTP 403.  An empty
`allowed_networks` list means no IP restriction.

## Audit log

Every request made to the server, using its APIs or WebSocket, is logged inside an audit db.
The audit db is store in a file using a SQLite database schema. Each record is composed by:
- `ID`: the unique id of the record, autoincrement
- `User`: the name of the user that made the specific action
- `Action`: the name of the action made by the user
- `Data`: the payload of the action (if present)
- `Timestamp`: the time when the specific action is executed

Audit database is saved inside `AUDIT_FILE` variable, default path is `/var/lib/nethserver/api-server/audit.db`.

The audit logs can be access using the `audit` API or directly from command line.
Example:
```
sqlite3 /var/lib/nethserver/api-server/audit.db "SELECT * FROM audit LIMIT 10;" ".exit"
```

## api-cli

You can also use the shortcut command called api-cli. Usage example:
```
# api-cli login
username: admin
password:
```

If authentication is successful the `login` subcommand stores a JWT token in `$XDG_RUNTIME_DIR/.api-cli.cache`. With such token the `run` subcommand sends API calls to `api-server`. To destroy the token run
```
api-cli logout
```

If the token is missing `api-cli` tries to talk directly with Redis. In any case to run an action use the `run` subcommand, e.g.:
```
api-cli run list-actions
```

Shell auto-complete is available. It is possible to type `TAB` key to automatically complete the action name:
```
api-cli run <TAB><TAB>
```
</file>

<file path="docs/core/backup_restore.md">
---
layout: default
title: Backup and Restore
nav_order: 10
parent: Core
---

# Backup and Restore

NS8 core provides a backup and restore infrastructure for applications,
and a procedure tailored for single node cluster disaster recovery.

* TOC
{:toc}

## Core architecture

- A backup **destination** is a remote filesystem accessible with Rclone,
  where backup data is saved. It's a cluster object persisted in Redis,
  under the restricted `private/nodes/*` key space: only nodes can read
  its contents. Secrets and configurations are stored in Rclone-format in
  the HASH key `private/nodes/backup_destination/rclone_conf`, indexed by
  destination ID. Other HASH keys are `cluster/backup_repository/<destination
  ID>`, with public backup destination attributes, and the HASH key
  `private/agents/backup_destination/restic_password`, indexed by
  destination ID: it contains the encryption password of all Restic
  repositories in the backup destination, shared among the applications
  that use it.

- A **backup** is the relation between a periodic schedule of the
  backup, a backup destination, and a set of applications to backup. It
  also has auxiliary attributes, like the backup snapshot retention. It's
  a cluster object persisted in Redis in HASH keys in the form
  `cluster/backup/<backup ID>`. The backup ID is generated from a
  sequence: `cluster/backup_sequence`.

- Every cluster node manages a pool of Systemd timers with the
  `backup-timers.service` unit, to start the backups at the scheduled
  times. The node `run-backup` helper command iterates over the configured
  applications and executes their `module-backup` procedure, by `runagent`
  impersonation. The `run-backup` command also updates the backup status
  of every application in Redis key `node/<node ID>/backup_status/<backup
  ID>`, and writes an overall backup status into
  `/var/lib/nethserver/node/state/node_exporter/backup<backup ID>.prom`
  files. That file holds the last known verdict of the backup, and is read
  by the `node_exporter` textfile collector. It is stored on a persistent
  path, so the metric survives a node reboot and keeps feeding any alert
  based on it until the next scheduled run overwrites it. It also uploads
  `.json` files with backup repositories metadata. When executed on the
  leader node, uploads a copy of the encrypted cluster backup.

- Every cluster node runs a `rclone-gateway` service, an authenticated
  HTTP proxy server. Access is granted to nodes and cluster applications
  providing their Redis credentials (environment variables `REDIS_USER`,
  `REDIS_PASSWORD`). The HTTP proxy server is a frontend to two internal
  `rclone serve` backends: `webdav` and `rest`. Nodes can access both,
  whilst applications can access a restricted set of operations of the
  Restic Rest server, and only on the data they own. Application backup
  jobs (Restic) access their repository through the REST endpoint. See
  also the [module backup documentation]({{site.baseurl}}/modules/backup_restore).

## Inspect the rclone-gateway configuration

Cluster actions never return saved passwords. To see the full rclone
remote configuration run this command:

    podman exec rclone-gateway rclone config show

As an alternative, run

    runagent -m node cat rclone/rclone.conf

Some rclone remotes, like `smb`, do not accept a clear-text password in
the configuration file. In those cases decrypt the password with a command
like this:

    podman exec rclone-gateway rclone reveal <secret>

## Rclone interactive sessions

To manually operate on backup destination contents get an interactive
shell in the `rclone-gateway` container and execute `rclone` commands.
This is an example session that lists a remote's contents.

    [root@rl1]# podman exec -ti rclone-gateway ash -l
    rl1:/$ rclone config show
    [prints rclone configuration]
    rl1:/$ rclone lsd --max-depth=3 dac5d576-ed62-5c4b-b028-c5e97022b27b:
    [prints up to three levels of directories in the backup destination]

This command copies a file in the remote backup destination into the local
`rclone-webdav` Podman volume, where `/srv/repo` is mounted:

    rl1:/$ rclone copy dac5d576-ed62-5c4b-b028-c5e97022b27b:ns8-davidep/cluster-backup-0c0aae59-2b1a-4a69-aa89-a460141e1572.json.gz.gpg /srv/repo/


## Execute a backup

Before executing a backup, you must create a backup repository.
The flow to execute a backup will be something like:
- create a backup repository and retrieve its UUID
- retrieve the UUID of the repository
- configure a backup using the repository as target
- retrieve the backup ID
- execute the backup

1. Create the repository:

       api-cli run add-backup-repository --data '{"name":"BackBlaze repo1","url":"b2:backupns8","parameters":{"b2_account_id":"xxxxxxxxxxxxxxxxxxxxxxxxx","b2_account_key":"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"},"provider":"backblaze","password":"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}'

2. The output will be something like, please note the `id` field:

       {"password": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "id": "48ce000a-79b7-5fe6-8558-177fd70c27b4"}

3. Create a new daily backup named `mybackup` with a retention of 3
   snapshots (3 days) which includes `dokuwiki1` and `dnsmasq1` instances:

       api-cli run add-backup --data '{"repository":"48ce000a-79b7-5fe6-8558-177fd70c27b4","schedule":"daily","retention":3,"instances":["dokuwiki1","dnsmasq1"],"enabled":true, "name":"mybackup"}'


4. The output will the id of the backup, e.g. `1`

5. Run the backup with id `1`:

       runagent -m node run-backup --backup 1

To remove the backup use:

    api-cli run remove-backup --data '{"id":1}'


To remove the backup repository:

    api-cli run remove-backup-repository --data '{"id":"c7a9cfea-303c-5104-8ab7-39ac9f9842bd"}'

## Execute a restore

Before executing a restore, the backup repository should already be configured.

Restore latest snapshot of the `dokuwiki1` module on node `1` from
repository `48ce000a-79b7-5fe6-8558-177fd70c27b4`:

    api-cli run cluster/restore-module --data '{"node":1, "repository":"48ce000a-79b7-5fe6-8558-177fd70c27b4", "path":"dokuwiki/3792c7db-9450-4bd3-84a3-034cd0087839","snapshot":""}'

## Cluster configuration backup

The `run-backup` command on the leader node automatically uploads an
encrypted copy of the cluster backup to each backup destination,
alongside the application backups.

The `cluster/download-cluster-backup` API returns a random URL path where an encrypted
archive is available for download.

    curl -O http://127.0.0.1:9311/backup/$(api-cli run cluster/download-cluster-backup | jq -r .path)

If the previous command is successful a file `dump.json.gz.gpg` is created
in the current directory.

The file with `.gpg` extension is encrypted with the password saved inside `/var/lib/nethserver/cluster/state/backup/passphrase`.
To decrypt it run a command like this:

    echo <passphrase> | \
        gpg --batch -d --passphrase-file /dev/stdin --pinentry-mode loopback -o dump.json.gz dump.json.gz.gpg

The restore procedure can be started from the UI of a new NS8
installation: upload the file and specify the password from the UI.

## The `restic-wrapper` command

The Restic binary is not provided by the Linux distribution. Instead, NS8
runs Restic within a core container, preparing environment variables with
values read from the Redis DB and properly mounting the application Podman
volumes.

The `restic-wrapper` command is designed to manually run Restic from the
command line. It can help to restore individual files and directories, or
run maintenance commands on remote Restic repositories.

The command can be invoked from any agent environment. Print its inline
help with this command:

    runagent restic-wrapper --help

Some options require a module backup ID, or backup destination UUID. Use
the `--show` option to list them. For example:

    runagent -m mail1 restic-wrapper --show

Example of output:

    Destinations:
    - dac5d576-ed63-5c4b-b028-c5e97022b27b OVH S3 destination (s3:s3.de.io.cloud.ovh.net/ns8-backups)
    - 14030a59-a4e6-57cc-b8ea-cd5f97fe44c8 BackBlaze repo1 (b2:ns8-backups)
    Scheduled backups:
    - 1 Backup to BackBlaze repo1, destination UUID 14030a59-a4e6-57cc-b8ea-cd5f97fe44c8
</file>

<file path="docs/core/clone_module.md">
---
layout: default
title: Cloning a module
nav_order: 10
parent: Core
---

# Cloning a module

A (source) module instance can be cloned by the `cluster/clone-module`
action. This action creates a new module instance (destination) that is
equivalent to the source one.

For example to create a clone of instance `dokuwiki1` on node 1, run

    api-cli run clone-module --data '{"module":"dokuwiki1","replace":false,"node":1}'

The `replace` boolean specifies if the source instance should be removed when
`clone-module` completes with success.

- With `"replace":false` the cloning action makes a copy of the source
  instance. The destination instance differs only for its MODULE_UUID.
- With `"replace":true` the cloning action copies also the MODULE_UUID
  value in the destination instance. Finally it removes the source instance.

The cluster `node` where the destination instance runs can be the same of
the source instance. Generally there should be no limitation on running
multiple module instances on the same node. In some cases the services
provided by the instance might require exclusive access to a particular
system resource, as binding a fixed TCP port number. In this case, avoid
to bind the fixed port number in the action `create-module`, otherwise
cloning becomes impossible.

In a nutshell, `cluster/clone-module`:

- Creates a new module instance for the destination using
  `cluster/add-module`
- Starts two parallel subtasks:
  - `transfer-state` on the source instance
  - `clone-module` on the destination instance
- The destination instance copies the MODULE_UUID of the source, if
  `replace` is true
- When both subtasks are succesfully completed and if `replace` is true,
  the source instance is removed with `cluster/remove-module`

Modules can implement additional steps for the  `transfer-state` and
`clone-module` to correctly support module cloning. The core provides a
partial implementation of those actions that is explained in the following
sections.

## Implementation of `transfer-state`

The core implementation of the `transfer-state` action runs a Rsync client
process that transfers the contents of the module volumes and the
AGENT_STATE_DIR (`state/`) directory to the destination instance. The
action input is like:

```json
{
    "replace": true,
    "credentials": ["dokuwiki1", "s3cr3t"],
    "address": "10.5.4.3",
    "port": 20021
}
```

Any step that runs after `05waitserver` can assume the Rsync server
process is ready to receive data.  The action implementation perform the
transfer in two similar steps to ensure data integrity. 

At steps `10sendpayload` and `50sendstate` all volumes are transferred to
the destination with a `rsync` client that runs in a privileged Podman
container. This container mounts all module volumes to correctly map
numeric UID/GIDs.

The step `10sendpayload` transfers data for the first time, thus it is
expected to be slower.

The step `50sendstate` stops the services, quickly transfers the latest
differences. If the transfer is successful the Rsync client sends a
"terminate" signal to the server. Then the step starts again the services
if the `replace` flag is false.

Additional notes:

* some files are never transfered by the core steps. Hardcoded
  high-priority exclude rules skip the following entries:
  - `state/agent.env`
  - `state/environment`
  - `state/apitoken.cache`

* some additional files with `.clone-module` extension are created and
  transfered. See `clone-module` for details.

* the automatic service stop-and-start logic works for rootless modules
  only. Rootfull modules must implement their steps to stop then start
  each service provided by the module.

* implementation of rootless stop-and-start logic is based on the Systemd
  `transfer-state.target` unit. To exclude a service from the
  stop-and-start cycle, add it to that target.

* it is possible to add a Rsync filter to select what files/dirs are
  transferred: just drop a `etc/state-filter-rules.rsync` under the
  AGENT_INSTALL_DIR. See `man 1 rsync` for the file syntax.

## Implementation of `clone-module`

The core implementation of the `clone-module` step runs a Rsync server
that receives volume and `state/` directory contents.

The action input could be:

```json
{
    "credentials": ["dokuwiki1", "s3cr3t"],
    "port": 20027,
    "volumes": [
        "dokuwiki-data"
    ],
    "replace": false
}
```

At step `05create_volumes` the `volumes` input array is used to re-create
the same set of volumes of the source module, if they are not already
created by `create-module`.

Then `rsyncd` server runs at step `10recvstate`. This server blocks the
step until the "terminate" signal is received from the client, or the task
itself is canceled.

If the state data transfer is successful this step merges the contents of
`environment.clone-module` (source module environment) with the
destination module `environment`. It also preserves the source variable
MODULE_UUID, if the `replace` flag is `true`.

Consider that even if the `state/` directory and all Podman volumes are
copied and merged properly by the core action steps, a module often needs
to invoke actions of other modules, too. For example, it might need to set
up an HTTP route, add a hostname to the TLS certificate or publish some
information in Redis. To implement this, further steps by the module can
self-invoke an action like `configure-module`, or symlink some step of it
directly under the `clone-module/` action directory.

Finally, the `90finalize` step enables and starts the **service and timer
Systemd units** as they are in the source module.
</file>

<file path="docs/core/container_metrics.md">
---
layout: default
title: Container metrics
nav_order: 18
parent: Core
---

# Container metrics

NS8 exposes per-container CPU, memory, PIDs, block I/O and network metrics
on each node's existing `node_exporter` endpoint. The metrics are produced
by `refresh-container-metrics.service`, a collector that runs on every
node, writes a Prometheus text file into `node_exporter`'s textfile
collector directory every 60 seconds, and is bound to the lifecycle of
`node_exporter.service` itself. No new port is opened and no new scrape
job is needed: the series appear on the node's `/metrics` endpoint like
any other `node_exporter` metric and are collected into the `metrics`
module's Prometheus on the leader node with the rest of the cluster's
metrics.

The collector reads cgroup v2 accounting files directly, instead of
querying the systemd unit that started the container. NS8 starts
containers with `podman run --detach --cgroups=no-conmon`, so the
systemd unit's own cgroup only accounts for the `conmon` supervisor
process, not the container payload (on a test node: 770 KB reported by
the unit vs. 165 MB in the container's real `libpod-<CID>.scope`
cgroup). The collector reads that scope cgroup instead.

## Metrics

Counters:

| Metric | Labels | Meaning |
|---|---|---|
| `ns8_container_cpu_seconds_total` | `module`, `container`, `mode="user\|system"` | Container CPU time spent, in seconds |
| `ns8_container_blkio_bytes_total` | `module`, `container`, `device`, `op="read\|write"` | Container block I/O transferred, in bytes |
| `ns8_container_blkio_ops_total` | `module`, `container`, `device`, `op="read\|write"` | Container block I/O operations |
| `ns8_container_network_receive_bytes_total` | `module`, `container`, `device` | Container bytes received |
| `ns8_container_network_transmit_bytes_total` | `module`, `container`, `device` | Container bytes transmitted |
| `ns8_container_network_receive_packets_total` | `module`, `container`, `device` | Container packets received |
| `ns8_container_network_transmit_packets_total` | `module`, `container`, `device` | Container packets transmitted |
| `ns8_container_oom_kills_total` | `module`, `container` | Processes killed by the container OOM killer |

Gauges:

| Metric | Labels | Meaning |
|---|---|---|
| `ns8_container_memory_usage_bytes` | `module`, `container` | Container memory usage |
| `ns8_container_memory_peak_bytes` | `module`, `container` | Container peak memory usage |
| `ns8_container_memory_limit_bytes` | `module`, `container` | Container memory limit |
| `ns8_container_memory_swap_bytes` | `module`, `container` | Container swap usage |
| `ns8_container_memory_anon_bytes` | `module`, `container` | Container anonymous memory |
| `ns8_container_memory_file_bytes` | `module`, `container` | Container page cache memory |
| `ns8_container_pids` | `module`, `container` | Processes running in the container |
| `ns8_container_pids_limit` | `module`, `container` | Container process limit |
| `ns8_container_start_time_seconds` | `module`, `container` | Container creation time |
| `ns8_container_info` | `module`, `container`, `id`, `image`, `unit`, `rootless` | Container metadata, always `1` |
| `ns8_container_collector_duration_seconds` | none | Duration of the last container metrics collection |
| `ns8_container_collector_skipped_containers` | none | Containers that could not be collected in the last collection |
| `ns8_container_collector_last_success_timestamp_seconds` | none | Unix timestamp of the last successful collection |

## Labels

`container` is the container name, and `module` is the id of the module
that owns it. Core containers that are not part of an installed module,
such as `redis`, `promtail`, `node_exporter` and `rclone-gateway`, are
reported with `module="core"`.

A container whose owner cannot be determined is reported with
`module="unknown"` instead. That happens while a container is exiting,
when one was started outside a service unit (`podman run` by hand), or
when a rootless container belongs to a local account that is not a
module. Module users are recognised by the agent state file
`~/.config/state/agent.env` (the same test `runagent` uses), not by
owning a container storage directory — any account that has ever run
rootless podman has one of those too. `module="unknown"` is kept
separate from `module="core"` so a failed attribution is never mistaken
for a core container.

Modules that run their containers in a pod also report the pod's infra
container, named `<pod>-infra`. It is a real container with its own
cgroup, and it is attributed to the module that owns the pod.

`ns8_container_start_time_seconds` is podman's own creation timestamp
for the container. NS8 units start their containers with `--replace`, so
a container is recreated on every restart and its creation time is also
its start time. The cgroup directory mtime is used only as a fallback,
when the index carries no timestamp — it's weaker, since a cgroup's
mtime also advances whenever a child cgroup appears or goes away.

The container id (truncated to 12 characters) appears only on
`ns8_container_info`, not on every series: a container gets a new id on
each restart, so putting it everywhere would churn the label set and
break `rate()` across restarts. Use the stable `container` name to
select or aggregate a container across restarts.

## Block I/O

`ns8_container_blkio_bytes_total` and `ns8_container_blkio_ops_total`
depend on the `io` cgroup controller being delegated to the container's
cgroup. Rootfull containers, which run under `machine.slice`, already
have the `io` controller delegated, so block I/O is reported
immediately.

Rootless modules run under `user@<uid>.service`, which by default
delegates only `memory` and `pids`. The core update that ships this
feature installs a drop-in,
`/etc/systemd/system/user@.service.d/50-ns8-delegate.conf`, that adds
`io` gives disk stats access to rootless modules.

The drop-in applies to every local user manager on the node, not only
NethServer module users — a `user@.service.d` drop-in can't be scoped
to particular user ids. Root's own manager is the exception, masked by
an empty `/etc/systemd/system/user@0.service.d/50-ns8-delegate.conf`.

## Network

`ns8_container_network_*` is reported once per network namespace, not
once per container.

Every container in a pod shares the pod's network namespace, so they
all read the same interface counters. To avoid multiplying the pod's
traffic by its container count in a `sum by (module)`, it's reported
once, with `container` set to `<pod>-infra` (podman's name for the
pod's infra container). Other pod members carry no
`ns8_container_network_*` series. Group by `module`, or select
`<pod>-infra`, to get a pod's traffic.

Beyond that, the family is reported only for a container that has its
own network namespace. Most NS8 containers run with `--network=host`
and share the node's namespace instead, so their traffic shows up in
the node's own `node_network_*` metrics, not here.

Loopback (`lo`) is excluded: it's the container talking to itself, not
real traffic in or out, and on a test node it was 98% of all bytes
received — large enough to hide everything else. When a container's
network family is absent from `ns8_container_network_*`, that means
"not applicable", not "zero traffic".

More generally, the collector omits a metric rather than reporting it as
zero whenever the value could not be measured, for example when a
cgroup file is missing. Prometheus treats an absent series and a zero
series differently, and reporting zero would assert a measurement that
was never actually taken.

## Example query

Top 5 modules by CPU usage over the last 5 minutes:

```
topk(5, sum by (module) (rate(ns8_container_cpu_seconds_total[5m])))
```
</file>

<file path="docs/core/database.md">
---
layout: default
title: Database
nav_order: 2
parent: Core
---

# Database

The Redis database runs as a Podman rootfull container, bound to TCP port 6379.

* TOC
{:toc}

Redis is not used only as a database:
  * it exchanges messages among agents and the API server
  * it helps modules to discover information about the core and other modules
  * it provides a signaling bus based on its PUB/SUB feature
  * it stores (a copy of) the system and modules configuration
  * it is an authentication backend for the management UI and the agents

Get the Redis service status:

    systemctl status redis

If any change occurs in the Redis database, it is persisted on the disk
within 5 seconds. The following command prints the database path:

    podman volume inspect redis-data | jq -r .[].Mountpoint

Redis provides blocking *pop* operations on lists. The BRPOP command is
used by agents to wait on a queue for incoming tasks. Task queues keys
look like `module/{module_id}/tasks`.

Redis provides PUB/SUB operations on *channels*. Channels are used to
implement the observer pattern, for instance in the following situations:

1. An agent wants to notify the UI about the progress of a running task.
   The channel name in this case looks like
   `progress/module/{module_id}/task/{uuid}`.

2. An agent wants to communicate to other agents that a particular event
   occurred (e.g. a TLS certificate was automatically renewed). The
   channel name in this case could be like
   `module/{module_id}/event/{event_name}`

## Access

Access Redis with one of the following commands:

    redis-cli PING

* The `redis-cli` command is faster when invoked by the root user, because
  it runs a command in the existing `redis` rootfull container. For
  non-root users a temporary container is created and destroyed.

* The `redis-cli` command attempts to connect with the higher available
  Redis privileges, by reading `agent.env` files.

A Python-based helper script, `redis-exec` is available and it better
suits Bash action scripts as it does not start any container. This client
is synchronous as it waits for the server response:

    runagent redis-exec PING

Note that the `runagent` wrapper is needed because `redis-exec` is
designed to run inside an "agent environment".

An alternative, synchronous invocation relies on the `nc` command,
provided by the `nmap-ncat` RPM (good for development environments):

    nc 127.0.0.1 6379 <<EOF
    PING
    EOF

For completeness here is a pure Bash invocation that does not wait the
server response:

    cat >/dev/tcp/127.0.0.1/6379 <<EOF
    PING
    EOF

## Roles

In a NS8 cluster the leader node runs Redis with *master* role. All
**write operations** must be executed on the leader instance. Worker nodes run
Redis with *replica* role, so they allow only **read operations**.

Changes are propagated from the leader instance to the worker instances.
The following command on the leader node describes the replication status:

    redis-cli ROLE

Example of the command output:

    1) "master"
    2) (integer) 57693
    3) 1) 1) "10.5.4.2"
          2) "6379"
          3) "57693"

The same command in a worker node has a different output. Note that the
deprecated term _slave_ may still used by the Redis protocol to describe
the replica role:

    1) "slave"
    2) "10.5.4.1"
    3) (integer) 6379
    4) "connected"
    5) (integer) 57721

Refer to the Redis official documentation for the exact meaning of the
command output.

The above command identifies the Redis leader instance by IP address and
port number. To know the leader node ID number run this command instead

    redis-cli HGET cluster/environment NODE_ID

To get back the IP address of an arbitrary node, given its node ID, e.g. 3:

    redis-cli HGET node/3/vpn ip_address

## Schema

Redis is a key/value database. Some key naming rules are enforced because
access rights are based on key name patterns. Both admin UI users and
agents have their own Redis credentials for authentication and
authorization.

Some key rule examples:

* `cluster/environment`, `node/{node_id}/environment` The key type is
  HASH. It stores a copy of environment variables of respectively the
  cluster agent running on the leader node, and the agent environment of
  *node_id*.

* `module/{module_id}/environment` The key type is HASH. It stores
  a copy of environment variables of the module *module_id*.

* `node/{node_id}/vpn` The key type is HASH. It stores the cluster VPN
  configuration applied by the node agent *node_id*

* `cluster/node_sequence` The key value is an integer. As the name
  suggests it is used to generate a node ID, when a new node is added to
  the cluster.

Next sections describe the value stored for each **database key**. Key names
follow this notation:

- `/` logical key namespace separator
- `{var}` (curly braces with name) placeholder for any string value
- ` ` (single space) hash field separator

A similar pattern is used also for channel names of
[events]({{site.baseurl}}/core/events).

### cluster/

Key prefix for the cluster agent key namespace. Keys with this prefix are
publicly accessible. As many keys has this prefix, see also the next
subsections for more information.

|key|type|description|
|---|----|-----------|
|cluster/network                        |CIDR       |WireGuard VPN network, default: `10.5.4.0/24` |
|cluster/default_instance/{image}       |STRING     |a module ID for the given image ID |
|cluster/node_sequence                  |INTEGER    |generate node IDs, default: `0` |
|cluster/module_sequence/{image}        |INTEGER    |module sequence to generate instances of image ID, default: `0` |
|cluster/module_uuid                    |HASH       |Maps module_id to module UUID for service discovery and backup authorization. Clone/restore may create temporary UUID duplicates. |
|cluster/module_node                    |HASH       |The module-node association, used for roles assignment|
|cluster/module_domains                 |HASH       |Store relation of modules with user domains. Hash key is MODULE_ID, hash value is a list of domains separated by spaces, e.g. `mydom1.tld mydom2.tld mydom3.tld`|
|cluster/authorizations/{agent_id}      |SET        |Authorization labels persistence, to enforce labels on future modules|
|cluster/roles/{role}                   |SET        |glob patterns matching the actions that {role} can run. {role} is one of "owner", "reader"...|
|cluster/environment                    |HASH       |Cluster environment variables|
|cluster/environment NODE_ID            |INTEGER    |The node ID of the leader node |
|cluster/ui_name                        |STRING     |UI label for the cluster|
|cluster/uuid                           |STRING     |Generated UUID that identifies the cluster|
|cluster/anon_seed                      |STRING     |A random seed for stable facts pseudonymization |
|cluster/override/modules               |HASH       |Maps (image name) => (image URL), overriding the standard image name/URL resolution function |
|cluster/subscription                   |HASH       |[Subscription]({{site.baseurl}}/core/subscription) attributes in key/value pairs|
|cluster/apply_updates                  |HASH       |[Scheduled updates]({{site.baseurl}}/core/updates) attributes in key/value pairs|
|cluster/module_automatic_update        |HASH       |Per-instance [automatic updates]({{site.baseurl}}/core/updates) policy. Hash key is MODULE_ID, hash value is `1` (enabled, default) or `0` (disabled).|
|cluster/tcp_ports_demand               |HASH       |Max TCP ports a module can request. Hash key is MODULE_ID, hash value is the max TCP ports.|
|cluster/udp_ports_demand               |HASH       |Max UDP ports a module can request. Hash key is MODULE_ID, hash value is the max UDP ports.|
|cluster/password_warning/{domain}      |HASH       |Password warning settings for a user domain|
|cluster/password_warning/templates|HASH     |Password warning templates, the hash contains 2 keys: "<domain>_custom_template_content" and "<domain>_custom_mail_subject|

#### cluster/smarthost

This is not a key prefix, it is a key of type HASH by itself and contains
setting storage for [SMTP smarthost]({{site.baseurl}}/core/smarthost).

|key|type|description|
|---|----|-----------|
|cluster/smarthost                      |HASH   |Settings and credentials of a SMTP smarthost provider|
|cluster/smarthost port                 |INTEGER|Public TCP port of the smtp server|
|cluster/smarthost enabled              |0\|1   |(0 disabled, 1 enabled) enable the smarthost provider|
|cluster/smarthost tls                  |0\|1   |(0 disabled, 1 enabled) enable STARTTLS|
|cluster/smarthost tls_verify           |0\|1   |(0 disabled, 1 enabled) verify if the certificate is valid and if the hostname is associated to the certificate|
|cluster/smarthost username             |STRING |username for smtp credentials|
|cluster/smarthost password             |STRING |password for smtp credentials|

#### cluster/repository/

Setting storage for [Software repositories]({{site.baseurl}}/core/software_repositories).

|key|type|description|
|---|----|-----------|
|cluster/repository/{repo}              |HASH   |A software {repo}|
|cluster/repository/{repo} url          |STRING |HTTPS URL of repository|
|cluster/repository/{repo} status       |0\|1   |(0 disabled, 1 enabled)|
|cluster/repository/{repo} testing      |0\|1   |(0 disabled, 1 enabled)|
|cluster/repository_cache/{repo}        |HASH   |Cache of remote repo metadata, with a TTL|
|cluster/repository_cache/{repo} data   |STRING |It contains a JSON string from repodata.json|
|cluster/repository_cache/{repo} updates|STRING |Most recent modification date and time of remote repodata.json|

#### cluster/backup_repository/

Each backup repository is identified with a UUID-based key of type HASH,
under the key prefix `cluster/backup_repository/`.

|key|type|description|
|---|----|-----------|
|cluster/backup_repository/{repo}                       |HASH   |A backup repository UUID|
|cluster/backup_repository/{repo} url                   |STRING |Restic URL of repository, eg. `b2:<bucket>`, `s3:s3.amazonaws.com/<bucket>`|
|cluster/backup_repository/{repo} password              |STRING |Restic encrypt password|
|cluster/backup_repository/{repo} name                  |STRING |Custom repository name|
|cluster/backup_repository/{repo} provider              |STRING |Provider name, can be: `backblaze`, `aws`|
|cluster/backup_repository/{repo} b2_account_id         |STRING |Backblaze B2 account ID, present only if provider is `backblaze`|
|cluster/backup_repository/{repo} b2_account_key        |STRING |Backblaze B2 account KEY, present only if provider is `backblaze`|
|cluster/backup_repository/{repo} aws_access_key_id     |STRING |AWS S3 access key, present only if provider is `aws`|
|cluster/backup_repository/{repo} aws_secret_access_key |STRING |AWS S3 secret key, present only if provider is `aws`|
|cluster/backup_repository/{repo} aws_access_key_id     |STRING |AWS S3 region, present only if provider is `aws`|

#### cluster/backup/

The attribute of a backup schedule are stored in an HASH key under the
`cluster/backup/` key prefix.

|key|type|description|
|---|----|-----------|
|cluster/backup/{id}                       |HASH    |A backup repository numeric ID|
|cluster/backup/{id} name                  |STRING  |Backup name|
|cluster/backup/{id} enabled               |0\|1    |(0 disabled, 1 enabled)|
|cluster/backup/{id} repository            |STRING  |UUID of backup_repository|
|cluster/backup/{id} retention             |INTEGER |Number of snapshots to keep|
|cluster/backup/{id} schedule              |STRING  |Schedule time using `onCalendar` systemd syntax|
|cluster/backup/{id} schedule_hint         |STRING  |Schedule in JSON format for the UI|
|cluster/backup/{id} instances             |STRING  |Space-separated list of module IDs|
|cluster/backup/{id} uinstances            |STRING  |Space-separated list of UUIDs used to rebuild the `instances` field reference after module restoration|

#### cluster/user_domain/

Settings storage for external user domains, LDAP databases not hosted by
the cluster.

|key|type|description|
|---|----|-----------|
|cluster/user_domain/ldap/{domain}/conf                 |HASH   |An external LDAP domain|
|cluster/user_domain/ldap/{domain}/conf schema          |STRING |It can be `ad` or `rfc2307`|
|cluster/user_domain/ldap/{domain}/conf bind_dn         |STRING |LDAP bind DN|
|cluster/user_domain/ldap/{domain}/conf bind_password   |STRING |LDAP bind password|
|cluster/user_domain/ldap/{domain}/conf base_dn         |STRING |LDAP base DN|
|cluster/user_domain/ldap/{domain}/conf tls             |STRING |Can be `on` or `off`|
|cluster/user_domain/ldap/{domain}/conf tls_verify      |STRING |Can be `on` or `off`|
|cluster/user_domain/ldap/{domain}/providers            |LIST   |List of domain provider hosts|
|cluster/user_domain/ldap/{domain}/ui_names             |HASH   |UI labels for domain providers. The key is the provider name, eg `ldap.ns.test:389` => `mylabel`|

#### cluster/counters_cache/

Store the counters of users and groups for each user domain.

|key|type|description|
|---|----|-----------|
|cluster/counters_cache/users/{domain}                  |INT    |Cached number of users in the domain, updated by list APIs|
|cluster/counters_cache/groups/{domain}                 |INT    |Cached number of groups in the domain, updated by list APIs|

### node/

Keys with this key prefix are publicly readable. Each node agent has write
access to its keys under `node/{id}/`, where `{id}` is the integer identifier
of the node (e.g. `node/1/...`).

|key|type|description|
|---|----|-----------|
|node/{id}/vpn                      |HASH||
|node/{id}/vpn ip_address           |STRING     |IP address in cluster/network|
|node/{id}/vpn public_key           |STRING     |Public WireGuard VPN key|
|node/{id}/vpn destinations         |STRING     |List of IP addresses routed through the VPN|
|node/{id}/vpn endpoint             |STRING     |Public IP or host name of the VPN endpoint with :port suffix|
|node/{id}/flags                    |SET        |Flags to mark a node. Supported flags: `nomodules`, the node can't run any module|
|node/{id}/roles/{role}             |SET        |glob patterns matching the actions that {role} can run. {role} is one of "owner", "reader"...|
|node/{id}/tcp_ports_sequence       |INTEGER    |Lower boundary for the next TCP_PORTS_RANGE allocation, default: `20000`|
|node/{id}/udp_ports_sequence       |INTEGER    |Lower boundary for the next UDP_PORTS_RANGE allocation, default: `20000`|
|node/{id}/default_instance/{image} |STRING     |A module ID for the given image ID|
|node/{id}/environment              |HASH       |Node environment variables|
|node/{id}/ui_name                  |STRING     |UI label for the node|
|node/{id}/backup_status/{bkid}     |HASH       |Backup status information with Restic output for each module |


### module/

Keys with this key prefix are publicly readable. Each node agent has write
access to its keys under `module/{id}/`, where `{id}` is the module
 instance identifier (e.g. `module/openldap1/...`).

|key|type|description|
|---|----|-----------|
|module/{id}/environment            |HASH|
|module/{id}/roles/{role}           |SET        |glob patterns matching the actions that {role} can run. {role} is one of "owner", "reader"...|
|module/{id}/flags                  |SET        |Images flags copied from `org.nethserver.flags` image label|
|module/{id}/srv/{transport}/{service} | HASH   |Service discovery information for other modules. See [Service providers]({{site.baseurl}}/modules/service_providers) |

### task/

Keys with this prefix hold sensitive information about a task execution.
The `{agent_id}` identifies the agent that can read/write the keys. For
instance `cluster`, `node/2`, `module/traefik1`...

|key|type|description|
|---|----|-----------|
|task/{agent_id}/context    |STRING  |JSON representation of a task|
|task/{agent_id}/error      |STRING  |stderr data generated by the action execution|
|task/{agent_id}/output     |STRING  |task output, JSON-encoded|
|task/{agent_id}/exit_code  |INTEGER |action exit code|

### user/

|key|type|description|
|---|----|-----------|
|user/{username}                |HASH||
|user/{username} display_name   |STRING|Name and surname|
|user/{username} email          |STRING|Mail address|


### roles/

Each user (or agent) can assume at most one role when it interacts with
another agent. This relation is stored in Redis in a key of type HASH. A
key of the hash is the agent identifier and the corresponding value is the
name of the role.

|key|type|description|
|---|----|-----------|
|roles/{username}             |HASH   ||
|roles/{username} {agent_id}  |STRING |Name of the role - {agent_id} is for instance `module/mail1`, `cluster`...|

### module/traefikX/

Each node runs a Traefik module instance. TLS certificates are stored under its module key prefix.

|key|type|description|
|---|----|-----------|
|module/traefik{X}/certificate/{name}       |HASH|  |
|module/traefik{X}/certificate/{name} key   |STRING |Base64 key of a x509 certificate|
|module/traefik{X}/certificate/{name} cert  |STRING |Base64 x509 certificate|

### AGENT_ID/tasks

Each [agent]({{site.baseurl}}/core/agents) runs a wait loop to run tasks
assigned to it. It waits on a task queue implemented with a Redis LIST key
with the form `{AGENT_ID}/tasks`.

|key|type|description|
|---|----|-----------|
|cluster/tasks                      |LIST      |Task items are JSON encoded objects|
|node/{id}/tasks                    |LIST      |Task items are JSON encoded objects|
|module/{id}/tasks                  |LIST      |Task items are JSON encoded objects|

An element of the task queue is a JSON-encoded string representing an
object with the following basic attributes:

|attribute|type|description|
|---|----|-----------|
|id        |string |UUID generated by the API server |
|action    |string |e.g. `list-users`, `install`, `create-domain`...|
|data      |any    |any JSON type (object, list...)|

For instance

```json
{
  "id": "66b73f7a-8998-4262-a784-36639fc4b2c1",
  "action": "list-actions",
  "data": ["cancel-task", "list-actions"]
}
```

### private/agents/

Access to keys under the `private/agents/` prefix is restricted to cluster
agent (read + write) and other authenticated agents (read-only).

|key|type|description|
|---|----|-----------|
|private/agents/backup_destination/restic_password | HASH | Maps a backup destination ID to its restic password |


### private/nodes/

Access to keys under the `private/nodes/` prefix is restricted to cluster
agent (read + write) and node agents (read-only).

|key|type|description|
|---|----|-----------|
|private/nodes/backup_destination/rclone_conf | HASH | Maps a backup destination ID to its raw rclone configuration, that typically contains secret credentials |
|private/nodes/restore_uuid | HASH | Maps a destination module UUID to a source module UUID. During module restoration the destination module must read the source module backup repository and this map establish the required trust between them, which is enforced by rclone-gateway.|
</file>

<file path="docs/core/events.md">
---
layout: default
title: Events
nav_order: 8
parent: Core
---

# Events

Events are messages published on specific Redis channels. Modules must
subscribe to the channel they want to be notified from. Usually channel
address is under a module name, something like
`module/<module_id>/event/<event_name>`.

Events should respect the following rules:
- use past tense inside the name, like `ldap-provider-changed`,
  `user-domain-changed`, `module-added`...
- accept a parameter in JSON format
- the parameter should contain minimal required info about the event
- optionally, the parameter can contain extra data which can ease the event usage

Well known events:
- `user-domain-changed`: the user domain has become available, has been
  removed, or its configuration has changed. The JSON parameter format is
  `{"node_id":INT,"domain":STRING,"domains":LIST[STRING]}`. Note: the `domain` attribute is deprecated but still included for backward compatibility. The `node_id` attribute is not
  present for external domains. `domains` is a list of domain names.
- `ldap-provider-changed`: an external LDAP account provider was removed
  or added to a user-domain. The JSON parameter format is
  `{"domain":STRING,"key":STRING}`.
- `module-domain-changed`: the relation between modules and user domains
  has been changed. The JSON parameter format is `{"domains":[DOMAIN1,
  DOMAIN2 ...], "modules":[MODULE_ID1, MODULE_ID2...]}` and reflects the
  domains and modules affected by the latest change.
- `backup-schedule-changed`: some backup schedules were changed, JSON parameter
  format is `{"backup_ids": LIST[STRING]}`.
- `backup-status-changed`: the HASH key containing backup status was
  updated. JSON parameter format is
  `{"node_id":INT, "module_id":STRING, "backup_id":INT}`

## Cluster events

Events fired by the `cluster` agent (i.e. channel is `cluster/event/<event name>`):
- `module-added`: the event is fired at the end of the add-module process to inform other modules that a new module has been installed on the cluster
- `module-removed`: the event is fired at the end of the remove-module process to inform other modules that a module has been removed on the cluster
- `leader-changed`: a node was promoted to leader. The `node_id` attribute
  indicates the new leader, and `endpoint` its public Wireguard VPN endpoint address
- `backup-destination-changed`: a backup destination was
  added/altered/removed. JSON parameter format is
  `{"destination_ids": LIST[STRING]}`.

## Node events

Events fired by the `node` agent (i.e. channel is `node/<node id>/event/<event name>`):
- `fqdn-changed`: the node FQDN has changed. The `hostname` and `domain` attribute describe the new FQDN, while the `node` attribute contains the node ID that originated the event

## Signaling events

To signal an event, just [PUBLISH](https://redis.io/commands/PUBLISH) a message to the channel.
All events take a JSON object as a parameter.

Example:
```
redis-cli PUBLISH module/traefik1/event/test '{"field": "value"}'
```

## Handling events

Events are handled like actions by the `agent` service.

Modules can define their event handlers under a dedicated directory:
`${AGENT_INSTALL_DIR}/events/`. The handler directory contains one or more
step scripts that must be executable files. For instance:

- **rootfull module**: `/var/lib/nethserver/mymodule/events/some-event-happened/10handler`.
- **rootless module**: `/home/mymodule/.config/events/some-event-happened/10handler`

Like actions, the event payload can be read by the step scripts from the
standard input file descriptor.

The event handlers receive two additional environment variables:

- `AGENT_EVENT_SOURCE` the agent ID that originated the event
- `AGENT_EVENT_NAME` the name of the event (it is the name same of the
  directory where of the event handler)

Lines sent to standard error and standard output are relayed to the system
log.

Similarly to actions, if an handler step exit code is non-zero, the
handler execution is aborted. Subsequent steps are not executed and an
error message is sent to the log.
</file>

<file path="docs/core/filesystem.md">
---
layout: default
title: Filesystem
nav_order: 1
parent: Core
---

# Filesystem locations

The core executable scripts and binaries are installed under
`/usr/local/bin` and `/usr/local/sbin`.

* The `agent` and `api-server` commands are implemented in
  [Go](https://golang.org/).
* Python scripts run within a special environment known as "agent environment".
  It is installed inside `/usr/local/agent/pyenv`.

Most NS8 core files reside in `/etc/nethserver`,
`/var/lib/nethserver/` and `/usr/local/agent/`. 

See `/var/lib/nethserver/node/state/coreimage.lst` for a complete list.

Rootless modules are totally contained inside UNIX user home directory, like `/home/trafeik1`.
Rootfull modules are homed under `/var/lib/nethserver/samba1`.

## Custom base path for home directories

NS8 core uses the common `/home` path for users' home directories, but you
can configure a different path if it is a device mount point. Follow these
steps to configure a node's agent for this purpose:

1. Create the alternative base path:

       mkdir -m 0755 /home1

2. Mount the device on the new path:

       mount /dev/some /home1

   To make the mount persistent, either edit `/etc/fstab` or create a
   systemd `.mount` unit. Ensure the device is correctly mounted after a
   system reboot.

3. Configure the node agent to use `/home1` as base directory for new
   modules:

       runagent -m node configure-home-basedir --set /home1

From now on, new module instances will use `/home1` as their base
directory. Existing modules are not affected and will retain their current
home directory.

The `configure-home-basedir` command modifies SELinux configuration. Run
the following command to inspect the current customizations:

    semanage fcontext -l -C

Refer to the `semanage-fcontext` man page for additional SELinux-related
information.
</file>

<file path="docs/core/firewall.md">
---
layout: default
title: Firewall
nav_order: 13
parent: Core
---

# Firewall

* TOC
{:toc}

NS8 has a basic built-in firewall based on firewalld.

The firewall has 2 zones:
- trusted: it includes containers and wireguard interface
- public: everything else

Default policies:
- SSH port is always open
- all blocked packets are logged

Please note that rootfull containers with port mapping (DNAT) or private
networking are *not supported*.

## Node Firewall Management

The following Python functions allow you to manage the node's firewall configuration. To use any of these functions, your module must be granted the `fwadm` role for the target node; otherwise, a permission error will be returned.

### Authorization

To permit direct connections from the public zone to a service provided by
a module, the module itself must modify the node firewall configuration.

The node firewall is configured with a simple _fwadm_ API. A module must
be authorized to use it, by adding `node:fwadm` to the module image label
`org.nethserver.authorizations`. For instance, set

       org.nethserver.authorizations=node:fwadm

If the label already has a `node:` value, append the role to it with a
comma, for example `node:fwadm,portsadm`. See [Roles and
authorizations](../agents/#roles-and-authorizations).

### Managing Public Services

The `agent` Python package provides functions to add and remove public services by opening specific ports in the firewall.

#### Adding Public Services

In `create-module`:

```python
import os
import agent
# Raise an exception if add_public_service() returns False
agent.assert_exp(agent.add_public_service(os.environ['MODULE_ID'], ["9010/tcp", "9011/tcp"]), "Firewall service configuration has failed")
```

Function `agent.add_public_service()` can be later invoked with additional
ports, for example during an application update that implements a new
public service. The given port list is _added_ to the existing one. For example:

```python
import os
import agent

agent.add_public_service(os.environ['MODULE_ID'], ["9012/tcp"])
```

If you want to completely replace the port list, set `replace_ports=True`,
for example:

```python
import os
import agent

agent.add_public_service(os.environ['MODULE_ID'], ["9010/tcp","9012/tcp"], replace_ports=True)
```

#### Removing Public Services

In `destroy-module`:

```python
import os
import agent
# Ignore errors on service cleanup
agent.remove_public_service(os.environ['MODULE_ID'])
```

### Managing Rich Rules

For more advanced firewall configurations, you can use rich rules to define complex firewall rules including port forwarding, source address filtering, and more.

#### Adding Rich Rules

Use the `add_rich_rules()` function to apply firewall rich rules on the node:

```python
import agent

rules = [
    'rule family=ipv4 forward-port port=5060 protocol=udp to-port=5060 to-addr=192.168.1.100',
    'rule family=ipv4 source address=10.1.2.3 port port=22 protocol=tcp accept'
]
result = agent.add_rich_rules(rules)
if not result:
    print("Failed to add rich rules")
```

Each element in the `rules` list should be a complete rich-rule string as accepted by firewall-cmd's `--add-rich-rule` option.

#### Removing Rich Rules

Use the `remove_rich_rules()` function to remove firewall rich rules from the node:

```python
import agent

rules = [
    'rule family=ipv4 forward-port port=5060 protocol=udp to-port=5060 to-addr=192.168.1.100'
]
result = agent.remove_rich_rules(rules)
if not result:
    print("Failed to remove rich rules")
```

The rule strings used for removal should match exactly the format stored by firewalld: use `list_rich_rules()` (below) to retrieve them. Refer to the function docstrings and firewalld documentation for the complete rich rule syntax.

#### Listing Rich Rules

Use the `list_rich_rules()` function to retrieve the rich rules currently
configured on the node:

```python
import agent

for rule in agent.list_rich_rules():
    print(rule)
```

The rules are read from the firewalld permanent configuration. Note that
firewalld normalizes the rule syntax when storing it, so the returned strings
may differ from the ones passed to `add_rich_rules()`; do not rely on an exact
string match to correlate them.

If the node cannot be reached the function returns an empty list and logs a
warning, so it never interrupts the calling action. Callers that reconcile a
desired rule set against the current one should pass `raise_on_error=True`
instead, since an empty list is otherwise indistinguishable from "no rules
configured":

```python
try:
    rules = agent.list_rich_rules(raise_on_error=True)
except Exception as e:
    print(f"Failed to list rich rules: {e}")
```
</file>

<file path="docs/core/index.md">
---
layout: default
title: Core
nav_order: 4
has_children: true
---

# Core: implementation details

Before reading this chapter, make sure to take a look at [Design & Architecture]({{site.baseurl}}/design).

NS8 relies on default Linux distribution configurations as much as possible.
</file>

<file path="docs/core/logs.md">
---
layout: default
title: Logs
nav_order: 9
parent: Core
---

# Logs

Almost everything is logged inside the system journal.
Recent logs are available using `journalctl` and services can be inspected using `systemctl` command.

As root use `journalctl` to see messages from agents, rootfull and rootless modules.
As rootless UNIX user (eg. `traefik1`), use `journalctl --user` to see messages only from systemd user session.

By default a Loki instance is installed inside the leader node, it
collects the logs from all cluster nodes. A rootfull Promtail container
runs as a node service on all nodes, including the leader one. It sends
all logs to the Loki server.

Logs of nodes, modules and the whole cluster can be read from the Logs
page, or with the `api-server-logs` command. The following command prints
the last lines of log produced by module `traefik1` and waits for further
lines, like a `tail -f`:

    api-server-logs logs -e module -n traefik1

See `api-server-logs -h` for more command invocation styles.

It is also possible to query the logs of all nodes and modules with the
`logcli` command.

Get the list of existing node identifiers:

    # logcli labels node_id -q
    1
    2

Get the list of modules:

    # logcli labels module_id -q
    ldapproxy1
    loki1
    traefik1

Example log search for module `ldapproxy1`:

<!-- {% raw %} -->

    # logcli query -q --no-labels '{module_id="ldapproxy1"} | json | line_format "{{.MESSAGE}}"'

<!-- {% endraw %} -->

The string wrapped by `''` is the log query. It is expressed in
[LogQL](https://grafana.com/docs/loki/latest/logql/log_queries/).

## Forwarding

On an active Loki instance, it is possible to enable two forwarding services. 
When forwarders are active and the leader node changes, they are automatically migrated to the new leader node.

By default, these forwarders are disabled.

### Syslog server

This service can be enabled either from the cluster admin interface or through the API using the following examples:
```
# api-cli run module/loki1/set-syslog-forwarder --data '{"active": true, "address": "127.0.0.1", "port": "514", "protocol": "udp", "format": "rfc3164", "start_time": "2024-01-01T00:00:00.00Z", "filter": "security"}'
```

**Configuration parameters**
- **active**: Boolean to enable or disable the forwarder (e.g., `true` or `false`).
- **address**: The IP address of the Syslog server.
- **port**: The port on which the Syslog server listens.
- **protocol**: Protocol to use (e.g., `udp` or `tcp`).
- **format**: Log format (e.g., `rfc3164` or `rfc5424`).
- **start_time**: The time from which logs should be forwarded. (`ISO 8601`)
- **filter**: The filter to apply to the logs. The only available filters are `"security"` and `""` (all logs).

It can be also stopped through API:
```
# api-cli run module/loki1/set-syslog-forwarder --data '{"active": false}'
```

### Cloud Log Manager

Cloud Log Manager forwarder is available only with a subscription, and if the subscription expires or is removed, the forwarder is automatically stopped.

Similarly, this service can be enabled from the cluster admin interface or through the API with examples like the following:
```
# api-cli run module/loki1/set-clm-forwarder --data '{"active": true, "address": "https://nar.nethesis.it", "tenant": "example", "start_time": "2024-07-12T00:00:00.000000Z"}'
```

**Configuration parameters**
- **active**: Boolean to enable or disable the forwarder (e.g., `true` or `false`).
- **address**: The URL of the Cloud Log Manager.
- **tenant**: The tenant identifier.
- **start_time**: The time from which logs should be forwarded. (`ISO 8601`)
- **filter**: The filter to apply to the logs. The only available filters are `"security"` and `""` (all logs). By default, the `security` filter is applied and the parameter is optional.

It can be also stopped through API:
```
# api-cli run module/loki1/set-clm-forwarder --data '{"active": false}'
```

When Loki is installed, it generates a unique identifier that is used on the [Cloud Log Manager](https://naradmin.nethesis.it/).
You can find this identifier on Cloud Log Manager settings panel or using the following command:
```
# redis-cli hget module/$(redis-cli --raw get cluster/default_instance/loki)/environment CLOUD_LOG_MANAGER_HOSTNAME
```

### Troubleshooting

- Check the status of forwarders using loki agent:
```
runagent -m loki1
systemctl --user status *forwarder.service
```

See also:
- [Grafana Loki](https://grafana.com/oss/loki/)
- [Promtail](https://grafana.com/docs/loki/latest/clients/promtail/)
- [ns8-loki](https://github.com/NethServer/ns8-loki) module repository
</file>

<file path="docs/core/metrics.md">
---
layout: default
title: Metrics and alerting
nav_order: 16
parent: Core
---

# Metrics and alerting

The core provides a module named `metrics` that collects metrics from the nodes
and sends alerts to the Nethesis portal. The module is installed by the
`create-cluster` action.

The module includes the following services:

- [Prometheus](https://prometheus.io/)
- [Alertmanager](https://prometheus.io/docs/alerting/alertmanager/)
- [Grafana](https://grafana.com/)
- [alert-proxy](alert-proxy/README.md)

Key points:

- Single instance running on the leader node
- Monitors all cluster nodes automatically
- Removed if the leader node becomes a worker
- Prometheus: port 9091
- Alertmanager: port 9093
- alert-proxy: port 9095
- Grafana: port 3000 (disabled by default, enabled with Traefik route)

Configuration:

- Prometheus and Alertmanager configurations are recreated on Prometheus restart
- Module restarts on node addition/removal
- alert-proxy restarts on subscription change to send alerts to Nethesis portals

If a subscription is enabled, alerts are sent to Nethesis portals by default.

Please refer to the module [README](https://github.com/NethServer/ns8-metrics) for details on alert configuration and customization.
</file>

<file path="docs/core/phone_home.md">
---
layout: default
title: Phone Home
nav_order: 15
parent: Core
---

# Phone Home

We're committed to being more aware of our products, how they are used and how they behave in different conditions and hardware.

To do so, we actually need to expand how the Phone Home worked in NS6-NS7 by adding additional telemetry to be sent and processed for analysis.

Starting from NS8, the Phone Home will be activated by default, to disable  this behaviour, simply disable the `phonehome.timer` on leader node of the cluster:

```bash
systemctl disable phonehome.timer
```

To find what data is sent, you can run:
```bash
runagent print-phonehome | jq
```
</file>

<file path="docs/core/port_allocation.md">
---
layout: default
title: Port allocation
nav_order: 17
parent: Core
---

# Port allocation

The `ports_manager` library handles the low-level port allocation storage.
It registers and stores UDP and TCP port information in a SQLite database
for the local node within the cluster.

The SQLite database file, `ports.sqlite`, is stored in the node's `state/`
directory. To inspect its contents, use the following command:

    podman run -i --rm --volume /var/lib/nethserver/node/state/ports.sqlite:/srv/ports.sqlite:z alpine ash -c 'apk add sqlite ; sqlite3 /srv/ports.sqlite' <<<"SELECT *, 'tcp' FROM TCP_PORTS UNION SELECT *, 'udp' FROM UDP_PORTS;"

For more information, refer to [Port
allocation](../../modules/port_allocation) under the Modules section.


## Importing the Library

To use the `ports_manager` library, you need to import it into your Python script as follows:

```python
import node.ports_manager
```

## Available Functions

### `allocate_ports`

This function allows you to allocate a specific number of ports for a given module and protocol.

- **Parameters**:
  - `required_ports` (*int*): The number of ports required.
  - `module_name` (*str*): The name of the module requesting the ports.
  - `protocol` (*str*): The protocol for which the ports are required (e.g. "tcp" or "udp").

- **Return** a tuple (start_port, end_port) if allocation is successful, `None` otherwise.

- **Usage Example**:

```python
allocated_ports = node.ports_manager.allocate_ports(5, "my_module", "tcp")
print(f"my_module ports allocated: {allocated_ports}")
```

### `deallocate_ports`

This function allows you to deallocate all ports previously assigned to a specific module for a given protocol.

- **Parameters**:
  - `module_name` (*str*): The name of the module for which ports should be deallocated.
  - `protocol` (*str*): The protocol for which the ports were allocated (e.g., "tcp" or "udp").

- **Return** a tuple (start_port, end_port) if deallocation is successful, `None` otherwise.

- **Usage Example**:

```python
deallocated_ports = node.ports_manager.deallocate_ports("my_module", "udp")
print(f"my_module ports deallocated: {deallocated_ports}")
```

## Additional Notes

- Ensure to handle exceptions that may be raised during the allocation or deallocation of ports.
- Ports allocated will remain reserved for the specified module until they are explicitly deallocated.
- When using the `allocate_ports` function, if the module already has allocated ports, they will first be deallocated and then reallocated.
</file>

<file path="docs/core/proxy_certificates.md">
---
layout: default
title: Proxy and certificates
nav_order: 5
parent: Core
---

# Proxy and certificates

Traefik is the HTTP proxy server used to access HTTP and HTTPS services,
and it also manages TLS certificates of the local cluster node. See
[Traefik
README](https://github.com/NethServer/ns8-traefik/blob/main/README.md) for
more information.

When a TLS certificate is uploaded from the cluster-admin UI, or it was
requested with ACME protocols and obtained from Let's Encrypt, the Traefik
module notifies the `certificate-changed` event, with a JSON message that
contains the following fields:

- `node_id` (integer): the node id where the Traefik instance is running,
- `module_id` (string): the ID of Traefik itself,
- `names` (array): list of DNS names (also wildcard patterns) that are
  affected by the changed certificate.

Example:
```json
{
    "node_id": 2,
    "module_id": "traefik2",
    "names": ["*.example.org", "www.example.com"]
}
```

The event is published in the Redis channel
`module/traefik<X>/event/certificate-changed`.

Applications that listen for this event can obtain the certificate and its
private key by calling the `get-certificate` action on the module that
generated the event.

For more information, refer to [TLS certificates](../../modules/certificates/)
under the Modules section.
</file>

<file path="docs/core/smarthost.md">
---
layout: default
title: SMTP smarthost
nav_order: 14
parent: Core
---

# SMTP smarthost

Settings and credentials for a SMTP smarthost provider are stored inside Redis, 
a module can discover it by using a Python library. The cluster won't send the 
email for you, the module will do it if it has been designed to send emails. 

Python example code:

```python
#!/usr/bin/env python3

import sys
import json
import agent


smtp = agent.get_smarthost_settings(agent.redis_connect())
if smtp['enabled'] == True:
    pass
json.dump(smtp, fp=sys.stdout)
```

output example:
```json
{"port": 587, "host": "", "username": "", "password": "", "enabled": false, "encrypt_smtp": "starttls", "tls_verify": true}
```

- encrypt_smtp: select the SMTP encryption method (`none`, `starttls`, `tls`)
- tls_verify: verify if the certificate is valid and if the hostname is associated to the certificate (true/false)
- username: it might be empty if the smtp server does not require an user authentication

The module can handle smarthost setup changes by defining an event
handler. Create an executable script with path
`${AGENT_INSTALL_DIR}/events/smarthost-changed/10handler` and run
any command from it. For instance:

```shell
mycommand && systemctl --user reload mymodule.service
```

## Send mail from modules

All agents have access to `ns8-sendmail`, a Python script that reads the SMTP smarthost configuration and sends an email. The script reads the email content from the standard input and sends it to the recipient addresses specified as one or more trailing arguments.

Example of invocation from a module environment:
```shell
echo "Hello, world!" | ns8-sendmail -s "My test mail" -f "no-reply@nethserver.org" user@test.org
```

If a SMTP smarthost is not configured, the script will return an error message and exit with a non-zero status code.

The script will try to parse the message body as a MIME message. If the message body is not a valid MIME message, the script will send the message as a plain text email.
</file>

<file path="docs/core/software_repositories.md">
---
layout: default
title: Software repositories
nav_order: 7
parent: Core
---

# Software repositories

In NS8, applications are available from remote application indexes known as "repositories."

## Cluster configuration

During installation, two repositories are configured:

- `default` (enabled)
- `nethforge` (disabled)

Key points:

- You can configure additional repositories in an NS8 cluster.
- Each repository can be in either an **enabled** or **disabled** state.
- The list of available modules in NS8 is generated by merging data from
  all enabled repositories.
- If two repositories contain modules with the same name, the module from
  the repository with higher priority is used, and others are ignored.
- Repository priority is determined by the alphabetical order of
  repository names, with names later in the alphabet (e.g., "Z") having
  higher priority than those earlier (e.g., "A").
- If a repository has the **testing** flag enabled, pre-releases are
  treated as stable and are included in application update calculations.
- Scheduled updates of a cluster with an active subscription ignore the
  repository configuration, and read only the `subscription` repository
  with the `managed` view. See [updates schedule]({{site.baseurl}}/core/updates#updates-schedule).

Repository configurations are stored in a Redis HASH with the key prefix
`cluster/repository/`. For example, to view the configuration of the
`default` repository, run:

```bash
redis-cli HGETALL cluster/repository/default
```

To enable the testing flag (for QA purposes only), use the following command:

```bash
redis-cli HSET cluster/repository/default testing 1
```

Note: If the testing flag is manually enabled, it will be reset to `0`
after the next core update.

Repository metadata is downloaded and cached in Redis for 3600 seconds. To
clear an existing repository cache, run:

```bash
redis-cli del cluster/repository_cache/<repository_name>
```

## Create a repository

An NS8 repository must contain a file named `repodata.json`, which
describes the content of the repository. Its format is detailed in
[repodata-schema.json](https://github.com/NethServer/ns8-core/blob/main/core/imageroot/var/lib/nethserver/cluster/repodata-schema.json).

Examples of existing repositories include:

- [Default](https://github.com/NethServer/ns8-repomd/), which lists core
  modules and applications with Nethesis Subscription support.

- [NethForge](https://github.com/NethServer/ns8-nethforge/), which
  contains applications with [Community
  certification](../../modules/certification).

To create a personal repository, you can copy the scripts from NethForge
that generate `repodata.json`. The `createrepo.sh` command analyzes a
directory passed as a parameter. If no path is given, it walks through the
current working directory.

Each module that needs to be published inside the repository should have a
directory named after the module itself. The directory should contain:

- A file named `metadata.json`: this contains all module metadata such as
  the name and the URL of the image in the registry. It uses the same
  format as the [UI metadata.json](../../modules/metadata).
- A file named `logo.png`: a PNG file with dimensions of 256x256 pixels.
- A directory named `screenshots`: it can contain one or more images, each
  in PNG format, with a resolution of 1024x768 pixels.

For each directory found, `createrepo.sh` uses the directory name to query
the remote image registry with
[skopeo](https://github.com/containers/skopeo) and retrieve image tags. If
the tags are valid [semantic versions](https://semver.org/), they are
added to the list of available module versions.

See the [dokuwiki
directory](https://github.com/NethServer/ns8-nethforge/tree/main/dokuwiki)
for an example of a complete module metadata directory.

The resulting `repodata.json` and the application directories can then be
uploaded to a public website.
</file>

<file path="docs/core/subscription.md">
---
layout: default
title: Subscription
nav_order: 16
parent: Core
---

# Subscription

The core provides builtin features to subscribe both free and paid support services.

The Redis HASH key `cluster/subscription` holds the attributes of the subscription.

- `provider` The subscription provider identifier. Possible values: `nsent`, `nscom`
- `system_id` System subscription identifier (see [Credential formats](#credential-formats))
- `auth_token` Authentication token for subscription APIs (see [Credential formats](#credential-formats))
- `collect_url` (`nsent` only) Base URL of the *my* collect API the cluster sends heartbeat, inventory
  and backup to, e.g. `https://my.nethesis.it/collect/api/systems`. It is set only when the cluster
  holds **native** *my* credentials; while it is set, `migrate-to-my` does nothing
- `migrated_at` (`nsent` only) RFC3339 UTC timestamp of the credential rotation. Set only when a legacy
  cluster is migrated, not on a fresh native registration
- `legacy_system_id`, `legacy_auth_token` (`nsent` only) The pre-migration credential pair, preserved for
  audit / rollback when `migrate-to-my` rotates a legacy cluster to native *my* credentials
- `dartagnan_url` (`nscom` only) Community subscription API base URL (default `https://my.nethserver.com/api`)
- `vpn_cert_cn` X509 Common Name for server certificate validation
- `vpn_peer_host` (default "sos.nethesis.it")
- `vpn_peer_port` (default "1194")
- `support_user` User name added to cluster-admin when a support session
  is started on the leader node. Password is set to a random UUID value.
  The account is removed when the support session is stopped

When a cluster has the Redis HASH key `cluster/subscription` some Systemd
services and timers are started and enabled at boot. The unit
`check-subscription.service` starts at boot and keep all the other unit
status aligned with the Redis key value.  This is a list of the services
managed by `check-subscription`:

- `send-inventory` (leader only) Run at night, send the cluster inventory to the provider
- `send-heartbeat` (leader only) Run every 10 minutes to signal the cluster liveness
- `send-backup` (leader only) Run at night, send the cluster encrypted backup to the provider
- `apply-updates` (leader only) Run at night, apply core, modules and OS
  updates according to configuration in Redis key `cluster/apply_updates`.
  See also [core updates]({{site.baseurl}}/core/updates)

The subscription status and running services are checked when:
- the node boots
- the node joins the cluster
- the cluster is restored from a cluster backup file
- the cluster subscription is enabled or disabled
- the cluster leader node changes

## Credential formats

The format of `system_id` and `auth_token` depends on the provider:

- **`nsent` (Nethesis Enterprise, new `my`)** — the customer pastes the full *my* token, of the form
  `my_<public>.<secret>`, which is stored as `auth_token`. `set-subscription` posts it to the *my*
  `POST /systems/register` API, which validates it and returns the `system_key`, stored as `system_id`,
  of the form `NETH-XXXX-XXXX-XXXX-XXXX-XXXX-XXXX-XXXX-XXXX` (`NETH-` followed by eight 4-hex-digit
  groups). A `system_id` is **one-shot**: once registered on *my* it cannot be re-registered, and a new
  registration attempt is rejected with HTTP `409` (`system_already_subscribed`).
- **`nscom` (Community)** — `auth_token` is the community token; `system_id` is the machine UUID returned
  by dartagnan (`my.nethserver.com/api/machine/info`).
- **Legacy `nsent` (before migration)** — clusters registered on the old `my.nethesis.it` used a UUID
  `system_id` and a hex `auth_token`. During the transition to the new *my*, `migrate-to-my` rotates the
  pair to native `NETH-…` / `my_…` credentials, stores `collect_url` and `migrated_at`, and preserves
  the old pair under `legacy_system_id` / `legacy_auth_token`.

## Migration to the new my

`migrate-to-my` runs once, at the end of the core update. Until it succeeds, a legacy `nsent` cluster
does not send heartbeat, inventory and backup to *my*.

If it fails, the Subscription page shows a *Complete migration* button. It runs the
`migrate-subscription` cluster action, which fails if the cluster is still not migrated:

    api-cli run migrate-subscription

Or run the script again as `root` on the leader node:

    runagent -m cluster migrate-to-my

Check the result in the journal:

    journalctl -t migrate-to-my

On success, `collect_url` and `migrated_at` are set:

    redis-cli hgetall cluster/subscription

The command is safe to run more than once: it does nothing if the cluster is already migrated, is not
`nsent`, or is not subscribed.

## APIs

Cluster:

- `get-subscription`
- `set-subscription`

Node:

- `get-support-session`
- `start-support-session`
- `stop-support-session`

## Events

- `subscription-changed`

## Remote support

Support sessions are started/stopped by each cluster node separately. Relevant node actions are

- `start-support-session`
- `stop-support-session`

For example, it is possible to start/stop a support session for any node
of the cluster. Run on the leader node this command:

    api-cli run node/7/start-support-session

The action prints the session ID, required to ask support:

    {"session_id": "811630de-67f4-5b6d-8b2f-7cc01f592b1b"}

As alternative, log in on the node and start manually the support service
with this command:

    systemctl start support
    systemctl status support

When a node support session is started

- support SSH key is added to the node `/root/.ssh/authorized_keys` file
  with an `expiry-time=` attribute. Only connections from the node itself
  are allowed with that key.
- support credentials are enabled for cluster-admin access. The user name
  is defined in Redis. Type `HGET cluster/subscription support_user` to
  see its value, by default it is `nethsupport`. The password is set to
  the support session ID value.  `nethsupport` can connect from localhost
  and a restricted set of IP addresses, coded in the
  `support-clusteradminctl` command.
- an OpenVPN tunnel is established with the support server, allowing
  connections to sshd and cluster-admin. The support server address and
  port can be overridden in the Redis `cluster/subscription` key

When the support session is terminated

- the OpenVPN tunnel is closed
- cluster-admin access is removed
- SSH key is removed

The support session is automatically terminated after 24 hours. To avoid
automatic termination and allow it to run up to the maximum allowed
duration of 7 days, execute this command on the relevant node:

    systemctl stop support-expire.timer

After 7 days the session is terminated unconditionally.

Inspect the node session expiry with the `get-support-session` action. For
example:

    api-cli run node/7/get-support-session

## OpenVPN support client

The Systemd unit `support.service` controls an OpenVPN client running in a
container, within a separate network namespace where the TUN device is
created.  This network namespace is configured with `nft` to forward some
TCP ports from the VPN tunnel to services of the node. For example

- Forward VPN ports 981 to 127.0.0.1:22
- Forward VPN ports 22, 9090, 80 and 443 to the respective port on 127.0.0.1

See `nft.conf` for the port forwarding rules.

## Inventory format

The inventory format is compatible with NS7 inventory and merges data
collected on the leader node with data collected by calls to the
`get-facts` action of each module instance.

If a module implements the `get-facts` action, its output is merged in the
inventory data, no matter the node hosting it.

This is an excerpt of `get-facts` data merged with user and group counters
for the LDAP domain `ad.example.org`:

```json
{
  "cluster_module_domain_table": [
    {
      "active_users": 65,
      "domain_id": "ad.example.org",
      "instance_of": "mail",
      "module_id": "mail8",
      "node_id": 5,
      "total_groups": 31,
      "total_users": 86
    },
    {
      "active_users": 65,
      "domain_id": "ad.example.org",
      "instance_of": "ejabberd",
      "module_id": "ejabberd1",
      "node_id": 5,
      "total_groups": 31,
      "total_users": 86
    },
    {
      "active_users": 41,
      "domain_id": "ad.example.org",
      "instance_of": "nextcloud",
      "module_id": "nextcloud1",
      "node_id": 1,
      "total_groups": 31,
      "total_users": 92
    },
    {
      "active_users": 65,
      "domain_id": "ad.example.org",
      "instance_of": "webtop",
      "module_id": "webtop7",
      "node_id": 5,
      "total_groups": 31,
      "total_users": 86
    },
    {
      "active_users": 0,
      "domain_id": null,
      "instance_of": "mattermost",
      "module_id": "mattermost1",
      "node_id": 1,
      "total_groups": null,
      "total_users": 116
    }
  ],
  "cluster_user_domains_table": [
    {
      "active_users": 65,
      "domain_id": "ad.example.org",
      "ejabberd_count": 1,
      "mail_count": 1,
      "nextcloud_count": 1,
      "total_groups": 31,
      "total_users": 86,
      "webtop_count": 1
    }
  ]
}
```

Notes:

- The Mattermost instance `mattermost1` is not bound to the LDAP domain,
  users are stored into the module database. Its `get-facts` action
  returns `active_users` and `total_users` counters with data stored
  inside its database.
- The Nextcloud instance `nextcloud1` implements `get-facts`. Its output
  overrides the `active_users` and `total_users` counters inherited from
  the `ad.example.org` user domain.
- Instances `mail8`, `ejabberd1` and `webtop7` inherit counters from
  domain `ad.example.org`
</file>

<file path="docs/core/testing.md">
---
layout: default
title: Testing suite
nav_order: 11
parent: Core
---

# Testing suite

* TOC
{:toc}

## Requisites

The tests have been created using [Robot Framework](https://robotframework.org/) and the execution happens inside a Podman container. The only dependency required
in the host system is [Podman](https://podman.io/getting-started/installation).

## Tests structure

All tests are in the `tests` directory of NS8 core, in the root of the `tests` directory the file `pythonreq.txt`
specifies the dependencies required and each sub-directory contains a test suite with the related tests.

The test suite and the related tests are executed in alphabetical order, the `__init__.robot` can be used for the suite
initialization. More details in the [Robot Framework documentation](https://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#files-and-directories).

```
core/tests/
├── 00_<test_suite>
│   ├── 00_<test>.robot
│   ├── 10_<test>.robot
│   ├── 20_<test>.robot
│   ├── ...
│   ├── ...
│   └── __init__.robot
├── 01_<test_suite>
│   ├── 00_<test>.robot
│   ├── 10_<test>.robot
│   ├── 20_<test>.robot
│   ├── ...
│   ├── ...
│   └── __init__.robot
├── ...
│   ├── ...
│   ├── ...
│   └── __init__.robot
├── pythonreq.txt
└── __init__.robot
```

## Tests execution

NS8 core uses Robot Framework for integration testing. Tests run inside a Podman container against a machine of your choice using the `run-ns8-tests` script. The standard tooling is provided by the [ns8-github-actions](https://github.com/NethServer/ns8-github-actions) repository.

### Requirements

- [Podman](https://podman.io/) available in `PATH`
- An SSH private key with access to the target NS8 leader node

### Installation

Download the script, make it executable, and place it in your `PATH`:

```bash
curl -o /tmp/run-ns8-tests \
  https://raw.githubusercontent.com/NethServer/ns8-github-actions/refs/heads/v1/scripts/test-module.sh
install -m 0755 -Z /tmp/run-ns8-tests ~/.local/bin
```

### Usage

Enter the core directory, then run tests:

```bash
cd /path/to/ns8-core/core
run-ns8-tests <LEADER_NODE> [robot_options...]
```

| Argument | Description |
|---|---|
| `<LEADER_NODE>` | Hostname or IP of the NS8 leader node |
| `[robot_options...]` | Extra arguments forwarded to the `robot` command (e.g. `--include`, `--exclude`) |

### Environment variables

| Variable | Default | Description |
|---|---|---|
| `SSH_KEYFILE` | `~/.ssh/id_ecdsa` | SSH private key to use for cluster connection |
| `RUN_UI_TESTS` | _(unset)_ | Set to `true` to enable UI/browser test cases |
| `COREMODULES` | _(unset)_ | Space-separated or comma-separated list of core modules to install during cluster setup |

### Test tags

Test cases can be marked with [Robot Framework tags](https://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#tagging-test-cases) to include or exclude tests during execution:

- `backend` — All tests in `10__cluster_sanity` suite
- `ui` — UI test cases (excluded by default, enable with `RUN_UI_TESTS=true`)
- `install` — Tests related to NS8 installation and cluster creation
- `uninstall` — Tests related to NS8 removal
- `unstable` — Tests automatically skipped on failure

To skip installation and uninstallation tests (useful for testing an already-installed cluster):

```bash
run-ns8-tests <LEADER_NODE> --exclude install --exclude uninstall
```

To enable UI tests:

```bash
RUN_UI_TESTS=true run-ns8-tests <LEADER_NODE>
```

### Examples

Basic run (substitute with your leader node hostname):

```bash
run-ns8-tests rl1.leader.cluster0.test.nethserver.org
```

Using a custom SSH key:

```bash
SSH_KEYFILE=~/.ssh/id_ecdsa run-ns8-tests rl1.leader.cluster0.test.nethserver.org
```

With UI tests enabled:

```bash
RUN_UI_TESTS=true run-ns8-tests rl1.leader.cluster0.test.nethserver.org
```

With specific core modules:

```bash
COREMODULES="ghcr.io/nethserver/core:latest ghcr.io/nethserver/traefik:feat-7544" run-ns8-tests rl1.leader.cluster0.test.nethserver.org
```

Skipping installation and uninstallation tests:

```bash
run-ns8-tests rl1.leader.cluster0.test.nethserver.org --exclude install --exclude uninstall
```

## Testing environment

A Terraform configuration is available in the [`ns8-terraform-infra`](https://github.com/NethServer/ns8-terraform-infra) repository to provision a clean infrastructure for test execution.

### Setup

1. Clone the repository and follow its setup instructions
2. [Export the generated SSH keys](https://github.com/NethServer/ns8-terraform-infra#default-ssh-keys-pair)
3. Set `SSH_KEYFILE` to point to the generated key

### Usage

Running tests with the Terraform-generated key:

```bash
SSH_KEYFILE=../../ns8-terraform-infra/key run-ns8-tests <LEADER_NODE>
```

Accessing nodes with the generated key:

```bash
ssh -i ../../ns8-terraform-infra/key <leader_node>
```

### Example

For a domain named `test.nethserver.org` running on Rocky Linux 9 in the `cluster0` workspace:

```bash
SSH_KEYFILE=../../ns8-terraform-infra/key run-ns8-tests rl1.leader.cluster0.test.nethserver.org
```
</file>

<file path="docs/core/tun.md">
---
layout: default
title: TUN devices
nav_order: 13
parent: Core
---

# TUN devices

NS8 can manage TUN devices and pass them to rootless containers.

## Configuration

Each node is responsible for its own TUN devices.
The node is configured with a simple _tunadm_ API. A module must
be authorized to use it, by adding `node:tunadm` to the module image label
`org.nethserver.authorizations`. For instance, set

       org.nethserver.authorizations=node:tunadm

If the label already has a `node:` value, append the role to it with a
comma, for example `node:tunadm,portsadm`. See [Roles and
authorizations](../agents/#roles-and-authorizations).

Please note that for backward compatibility with core 3.16 the _tunadm_
authorization includes also the [_fwadm_](../firewall) one.

Then the module actions must use the `agent`
Python package to add/remove the tun device needed by the
module.

In `create-module`:

```python
import os
import agent
agent.assert_exp(agent.add_tun("tun1", "192.168.1.1/24"))
```

In `destroy-module`:

```python
import os
import agent
agent.assert_exp(agent.remove_tun("tun1"))
```
</file>

<file path="docs/core/updates.md">
---
layout: default
title: Updates
nav_order: 12
parent: Core
---

# Updates

A system running NS8 has many components to keep up-to-date:

- the underlying operating system (OS)
- the NS8 core and its container images
- core modules
- application modules

Updates can be applied on schedule or by request.

## Core updates

The core update changes both the core images and the core modules. In the
first stage cluster nodes update the core components. In the second stage
the leader node launches the update of individual core modules.

### First stage

The first stage applies enhancements and bug fixes for the `core` image.
The core image contains: agents, UI, additional core images and common
actions.

To execute the core update from the command line, run on the leader node:

    update-core ghcr.io/nethserver/core:MAJ.MIN.PATCH

- `MAJ.MIN.PATCH` is a Semver-compliant version tag of a stable core
  release; a symbolic branch name (e.g. `feat-8000`) can be used for
  feature development instead

By default every node in the cluster is updated, keeping core versions
aligned. Updating only a subset of nodes is a development edge case and is
discouraged in production clusters; use `--nodes` to override the default:

    update-core ghcr.io/nethserver/core:MAJ.MIN.PATCH --nodes NODEID1 NODEID2

If the given `core_url` is already present in the local Podman storage, no
remote download occurs and the local image is used instead. Pass `--force`
to always pull and reinstall it, ignoring the Semver tag check:

    update-core ghcr.io/nethserver/core:MAJ.MIN.PATCH --force

By default the command prints only the action output; on failure it also
prints the error. Pass `--verbose` to print the error even on success:

    update-core ghcr.io/nethserver/core:MAJ.MIN.PATCH --verbose

The same action can also be invoked directly with `api-cli`, e.g. to script
around it:

    api-cli run update-core --data '{"core_url":"ghcr.io/nethserver/core:MAJ.MIN.PATCH","nodes":[NODEID1, NODEID2]}'

The cluster agent running on the leader node forwards the core-update
request to selected nodes. Updating a subset of nodes is discouraged in
production clusters; keep core versions aligned on all cluster nodes.

Each node agent compares the image tag of the `core_url` parameter with
core image version installed on the node. One of the following cases
applies:

- Both tags are valid Semver tags: the image is installed only if
  `core_url` is greater than the installed one.

- One or both tags are invalid Semver tags: `core_url` is pulled only
  if not already present in Podman storage and the update continues

- The `force:true` flag is passed: `core_url` is pulled and update runs
  ignoring the Semver tag check.

When `core_url` is downloaded, additional images listed in the `core`
image label `org.nethserver.images` are downloaded as well.

After all downloads are successful, the `core` image is installed,
replacing the previous one.

- Files and empty directories that are no longer used by the new image are
  removed

- Image ID and digest are stored in the node environment

Then the node agent runs executable scripts under
`/var/lib/nethserver/node/update-core.d/`. Execution order is
alphabetical. If a script has non-zero exit code, a warning is printed and
execution continues with the next script. Scripts added to this directory
can be called multiple times, so they must be designed consequently.

If the update fails on some node, the whole process is aborted by the
leader node at this point.

### Second stage

If every node completes the first stage successfully, the leader node
starts the second stage.

The cluster agent on the leader node runs executable scripts under
`/var/lib/nethserver/cluster/update-core-pre-modules.d/`, as described for
the previous stage. Scripts are obtained from the newly installed core
image.

Then the cluster agent searches installed core modules. For example, it
runs the update-module action for any instance of:

- ldapproxy
- traefik
- samba, openldap (account providers)
- loki

See [module updates]({{site.baseurl}}/modules/updates) for more info about
the module update procedure, that is applied also to core modules.

Finally, the cluster agent runs the scripts under
`/var/lib/nethserver/cluster/update-core-post-modules.d/`, as described in
the previous stage. Scripts are obtained from the newly installed core
image.

The exit code of the `update-core` action is non-zero if any core module
has failed its update.

## Operating system updates

If the OS has the `dnf` command (e.g. Rocky Linux), the node `update-os`
action can download and install the distribution updates. If the `dnf`
command is missing OS update is skipped.

If a subscription is active, DNF repositories are accessed with HTTP Basic
authentication.

## Module updates

Application/module updates are controlled by the `cluster/update-modules` action
and described in [module updates]({{site.baseurl}}/modules/updates).

## Updates schedule

The Systemd `apply-updates.timer` and the corresponding cluster helper
`apply-updates` control the updates schedule. This timer can be enabled
only in the leader node.

If the system has a subscription, scheduled updates are enabled by
default.

Scheduled updates run the `update-core` and `update-modules` actions
with the `managed` repository view, a conservative update policy decided
by the repository server. If the cluster has a subscription, the
available core and module versions come only from the `subscription`
repository (`https://subscription.nethserver.com/distfeed/`), regardless
of the `cluster/repository/*` keys: modules from other repositories,
like `nethforge` or custom ones, are never updated by schedule. Manual
updates, for example from the UI, still use the enabled repositories.

The timer status is controlled by the
[subscription]({{site.baseurl}}/modules/subscription) logic, and reflects
the Redis HASH key `cluster/apply_updates`. This is the list of the HASH
key/values:

- `is_active` controls the status of the Systemd `apply-updates.timer`
  unit. `1` for enabled, otherwise disabled

The `cluster/apply_updates is_active` value is set automatically when a
subscription is activated or terminated. It can also be changed directly
with the `set-automatic-updates` cluster action:

    api-cli run set-automatic-updates --data '{"apply_updates_is_active": false}'

Changing `is_active` does not immediately start or stop the
`apply-updates.timer` unit: the `set-automatic-updates` action also runs
the `check-subscription` node helper, which reads the current value and
aligns the timer status accordingly.

### Per-instance automatic updates policy

Each module instance can opt out of automatic updates independently of
the cluster-wide `is_active` switch. The policy is stored in the Redis
HASH `cluster/module_automatic_update`, keyed by module instance ID, with
value `1` (enabled, the default when the key is missing) or `0`
(disabled).

The policy is set with the same `set-automatic-updates` action:

    api-cli run set-automatic-updates --data '{"instances": {"dokuwiki1": false}}'

When the `apply-updates` timer runs `update-modules`, instances whose
policy is `0` are skipped and the exclusion is logged. Manually-triggered
updates (e.g. from the UI or `api-cli run update-modules`) always ignore
this policy and apply to every instance.
</file>

<file path="docs/core/user_domains.md">
---
layout: default
title: User domains
nav_order: 6
parent: Core
---

# User domains

Users and groups are stored in an LDAP database, served by one **account
provider module**. Multiple modules can work together to serve the same
LDAP database as replicas of it. An LDAP database represents an account
**domain**.

A NS8 cluster can host multiple account domains from different
implementations. It is possible to configure and connect external LDAP
services, too. Supported LDAP schema are

1. `ad` - Active Directory
2. `rfc2307`

## LDAP service discovery

A module can discover the list of available account domains with the
`agent.ldapproxy` Python module. The following command dumps a list of
parameters required to connect with an LDAP database on cluster node 1.

    runagent python3 -magent.ldapproxy

Returned TCP endpoints are local (`host` is `127.0.0.1`) and do not
require TLS. The port number depends on the LDAP domain.

Those ports are held by the [Ldapproxy
module](https://github.com/NethServer/ns8-core/blob/main/ldapproxy/README.md).
It is a L4 proxy that relays the TCP connection to an LDAP backend server,
enabling TLS and handling backend failures as needed.

If the LDAP client module runs in a Podman container with a
`private` network, add the following arguments to the `podman run`
command:

    --network=slirp4netns:allow_host_loopback=true

Then replace `127.0.0.1` with the special `10.0.2.2` IP address, that is
translated by Podman back to the loopback device, 127.0.0.1 on the root
network namespace.

Python code example:

```python
from agent.ldapproxy import Ldapproxy
lp = Ldapproxy()
domains = lp.get_domains_list()
print(domains)
domain = lp.get_domain("mydomain")
print(domain)
```

The module can handle the user domain configuration changes by defining an
event handler. Create an executable script with path
`${AGENT_INSTALL_DIR}/events/user-domain-changed/10handler`. For instance:

```shell
mydomain="ad.example.org"

# Check if $mydomain is in the list of changed domains
if jq -e --arg d "$mydomain" '.domains | index($d)' >/dev/null; then
    systemctl --user reload mymodule.service
fi
```

## List users and groups

Once LDAP connection parameters are retrieved with the `agent.ldapproxy`
Python package, it is easy to get user and group listings with the
`agent.ldapclient` package.

This is an excerpt from the `cluster/list-domain-groups` API implementation:

```python
from agent.ldapproxy import Ldapproxy
from agent.ldapclient import Ldapclient

domparams = Ldapproxy().get_domain('mydom.test')
groups = Ldapclient.factory(**domparams).list_groups()
```

For complete examples see the API implementation of

- `cluster/list-domain-groups`
- `cluster/list-domain-users`
- `cluster/get-domain-user`
- `cluster/get-domain-group`

## Hidden users and groups

Some users and/or groups can be hidden to UI and other applications.

Applications might need to build LDAP search filters to configure user and
groups. The `Ldapproxy` library provides some methods that return filter
strings that honor the user and group lists used by the core. For example:

```python
from agent.ldapproxy import Ldapproxy
lp = Ldapproxy()
users_filter = lp.get_ldap_users_search_filter_clause("mydomain")
print(users_filter)
groups_filter = lp.get_ldap_groups_search_filter_clause("mydomain")
print(groups_filter)
```

## Bind modules and account domains

If a module wants to use an account domain it must be granted API
permissions. Add the `accountconsumer` role to the
`org.nethserver.authorizations` label of the module image. For instance
set

    org.nethserver.authorizations=cluster:accountconsumer

The module can now execute a bind procedure, so the core is aware of
existing relations between modules and account domains. When such
relations are formally established the core can

- limit/grant access to LDAP resources
- show the relations in the web user interfaces

For example, a module that uses one domain at a time can unbind the old
domain and bind the new one with a script like this:

```python
import agent

ldap_user_domain = "dept1.example.org"

# Bind the new domain, overriding previous values (unbind)
agent.bind_user_domains([ldap_user_domain])
```

At any time, retrieve the list of domains currently bound:

```python
import agent
rdb = agent.redis_connect(use_replica=True)
domlist = agent.get_bound_domain_list(rdb)
```

When the module or the domain is removed from the cluster, the relation
cleanup occurs automatically.

If the module wants to be notified of any change to the relation between
modules and user domains it can subscribe the `module-domain-changed`
event. For instance, this is the payload of such event:

```json
{
    "modules": ["mymodule1"],
    "domains": ["mydomain.test"]
}
```

The event payload contains a list of module and domains that were affected
by the relation change. Modules and domains can be either added or
removed: they are listed to ease the implementation of event handlers in
both account provider and account client modules.

For instance, the following Python excerpt checks if the module domain was
changed:

```python
event = json.load(sys.stdin)
if not os.environ["LDAP_USER_DOMAIN"] in event["domains"]:
    sys.exit(0) # nothing to do if our domain is among affected domains

# Handle the event by some means, for example
# - rewrite some config file
# - reload some service running in a container
```

## Single sign-on

A module can delegate user authentication to an OpenID Connect (OIDC)
provider module. The core does not implement one: it relies on the
minimal interface described here, and the
[ns8-idp](https://github.com/NethServer/ns8-idp) module (Keycloak) is its
reference implementation.

An OIDC provider serves a realm for each user domain, named after the
domain, with the users and groups of its LDAP database. A module gets an
OIDC client in the realm of a user domain it is bound to. The
`preferred_username` claim of its tokens is the user name in the user
domain, so the module can match OIDC logins with existing accounts.

### OIDC provider discovery

A provider publishes the `module/{MODULE_ID}/srv/http/oidc`
[service key]({{site.baseurl}}/modules/service_providers) and raises the
`service-oidc-changed` event when it changes. The key fields are:

- `host`: the public host name of the provider
- `issuer_url_prefix`: the OIDC issuer of a user domain is this prefix
  followed by the domain name, for example
  `https://sso.example.org/realms/dp.example.org`

The event payload carries the key fields, so listeners can tell whether
the change concerns them, besides the key name and the provider module:

```json
{
    "host": "sso.example.org",
    "issuer_url_prefix": "https://sso.example.org/realms/",
    "key": "module/idp1/srv/http/oidc",
    "module_id": "idp1",
    "module_uuid": "8d257122-0a7f-49c7-a620-08961a68cfa0"
}
```

Endpoints and keys of the issuer are found with the standard OIDC
discovery document, `{issuer}/.well-known/openid-configuration`. To list
the providers:

```python
import agent
rdb = agent.redis_connect(use_replica=True)
providers = agent.list_service_providers(rdb, 'oidc', 'http')
```

### OIDC client registration

A provider implements the `register-client` action, granted by its
`clientadm` role. The client module declares it in its authorizations
label, for example

    org.nethserver.authorizations=idp@any:clientadm

The client module binds the user domain first, then calls the action of
the chosen provider:

```python
import agent
response = agent.tasks.run(agent_id="module/idp1", action="register-client", data={
    "domain": "dp.example.org",
    "redirect_uris": ["https://cloud.example.org/apps/user_oidc/code"],
    "post_logout_redirect_uris": ["https://cloud.example.org/"],
})
agent.assert_exp(response["exit_code"] == 0)
# {"client_id": "nextcloud1", "client_secret": "...", "realm": "dp.example.org",
#  "issuer": "https://sso.example.org/realms/dp.example.org"}
```

The provider must:

- name the client after the calling module ID; an explicit `module_id`
  input attribute is accepted only from tasks without a calling user,
  like those of the cluster agent or `api-cli`
- reject a domain not bound to the calling module
- create the realm if missing, and bind itself to the user domain
- update an existing client and return its current secret; the
  `rotate_secret` flag generates a new one
- keep the enabled state of an existing client: a client disabled by an
  administrator stays disabled when its module registers it again
- delete the client when its module is removed or unbound from the
  domain

Other input attributes:

- `redirect_uris`: without redirect URIs, the client can only
  authenticate its own requests, for example the token introspection of
  a mail server
- `post_logout_redirect_uris`: the module should pass the exact URI its
  application uses at logout. If the attribute is missing, the provider
  allows any URI of the origins of the redirect URIs, like
  `https://cloud.example.org/*`
- `web_origins`: the allowed CORS origins
- `audience`: client IDs added to the token audience. For example a
  webmail client adds the mail module client, because the mail server
  accepts only tokens that list it

Validation errors have the `field` and `error` attributes of the
standard action validation output. The `error` values are
`module_id_required`, `module_id_not_allowed`, `caller_not_a_module` and
`domain_not_bound_to_module`. See also the [register-client input
schema](https://github.com/NethServer/ns8-idp/blob/main/imageroot/actions/register-client/validate-input.json).

A provider can restrict a realm to logins through a federated identity
provider, like Microsoft Entra ID. Such a realm refuses LDAP passwords,
but a module that shows its own login form still accepts them: in that
case the module should offer exclusive SSO, sending its users straight
to the provider, and document an emergency login path for when the
provider is down. Protocols outside the browser, like IMAP and WebDAV,
keep using LDAP passwords.

## Import/Export users APIs

Samba and OpenLDAP core modules implement a uniform API to massively
import and export users.  To use that API modules must be authorized:

    org.nethserver.authorizations=samba@any:domadm openldap@any:domadm

With `domadm` role, a client module can invoke the following actions and
user-portal handlers:

- `export-users`
- `import-users`

This is an example CSV file with 9 fields, that can be used to feed `import-users` input:

    dolores.slughorn3,Dolores Slughorn,Magic!123,dolores.slughorn3@hogwarts.example,aurors|hufflepuff|quidditch,true,false,true
    cedric.macmillan4,Cedric Macmillan,Magic!123,cedric.macmillan4@hogwarts.example,hufflepuff|ministry|quidditch,false,true,false
    pansy.dumbledore5,Pansy Dumbledore,Magic!123,pansy.dumbledore5@hogwarts.example,gryffindor|ravenclaw,true,false,false

Run this Bash command to import the CSV (non-existing groups are created on the fly):

    cat file.csv | jq -R -s '
        split("\n")
        | map(select(length>0))
        | map(split(","))
        | {
            skip_existing: false,
            records:
                map({
                user: .[0],
                display_name: .[1],
                password: .[2],
                locked: (.[5] | test("(?i)^(1|true|yes)$")),
                groups: (.[4] | split("|") | map(ascii_downcase)),
                mail: .[3],
                must_change_password: (.[6] | test("(?i)^(1|true|yes)$")),
                no_password_expiration: (.[7] | test("(?i)^(1|true|yes)$"))
                })
            }
        ' | api-cli run module/samba1/import-users --data -

Actions/handlers for single users and groups are also authorized with role `domadm`:

- `add-user`
- `add-group`
- `alter-user`
- `alter-group`
- `remove-user`
- `remove-group`
- `list-users`
- `list-groups`


## Password expiration warning

The node leader can send email notifications to users when their password
is about to expire.
The notification is available only for internal user domains.

This features has 2 requirements:

- password aging must be enabled on the user domain provider
- the cluster must be configured to send mail notifications using an internal or external [SMTP server](smarthost.md)

A timer named `password-warning.service` runs daily on all nodes to check for expiring passwords, but it actually
sends the email only on the leader node.

Configuration is saved inside Redis so it is available to all nodes:
- `cluster/password_warning/<domain>`
- `cluster/password_warning/templates`

See [database schema](database.md) for details.

### User destination mail address

The `notify-password-warning` script obtains the destination address
from the LDAP `mail` attribute of each user entry in OpenLDAP or Samba
LDAP DB. The attribute is editable from cluster-admin UI and backend actions.

For user entries without `mail` LDAP attribute, the script checks the
existence of a Mail application with a configured mail domain named after
the user domain. If such mail domain exists in the cluster, the destination
address is set to `<user>@<user_domain>`.

- If that Mail application is also the one configured as [SMTP server for
  notifications](smarthost.md), the submission is internal and
  `user_domain` does not need to be resolvable via a public DNS MX record.
- Otherwise, delivery to `user_domain` follows conventional SMTP rules and
  does require a public DNS MX record.

For example user `john` of user domain `ad.example.org` has no address in
the `mail` LDAP attribute. A Mail application with matching domain
`ad.example.org` is searched. If one is found the notification is sent to
`john@ad.example.org`.

If neither the `mail` LDAP attribute is set nor a Mail application is bound
to the user domain, no notification is sent.

To check for expiring passwords and immediately send notifications, run the following command on the leader node:

```bash
systemctl start password-warning.service
```

### Default templates

Default templates are stored inside `/etc/nethserver/password_warning` directory.
Available templates:

- `default_en.tmpl`: English mail template
- `default_it.tmpl`: Italian mail template
- `default_en.sbj`: English mail subject
- `default_it.sbj`: Italian mail subject

### Configure password warning

The configuration can be done using the cluster web interface.
If you want to configure it from command line, see the `cluster/set-password-warning` API.

The API takes the following parameters:

- `domain`: the domain name
- `notification`: enable or disable the notification
- `days`: the number of days before the password expiration
- `mail_from`: the email address of the sender
- `mail_template_name`: the name of the template to use, it could be `default_en`, `default_it` or `custom`. If set to custom, you must provide also `mail_template_content` and `mail_subject`.
- `mail_template_content`: the content of the template, must be base64 encoded
- `mail_subject`: the subject of the email in plain text. 

### Using a Custom Template

Field `mail_template_content` and `mail_subject` use [Python string template](https://docs.python.org/3/library/string.html#template-strings).
The string representation can contain the following placeholders: `$user`, `$name`, `$domain`, `$days`, `$portal_url`.

1. Create a file named `custom.txt` with your custom content:
    ```
    Dear $user ($name) of domain $domain.
    Your password is going to expire in $days days.
    Change it here: $portal_url
    ```
2. Use the custom template:
    ```bash
    api-cli run cluster/set-password-warning --data '{"domain": "leader.cluster0.gs.nethserver.net", "notification": true, "days": 1000, "mail_from": "no-reply@nethserver.org", "mail_template_name": "custom", "mail_template_content": "'$(cat custom.txt | base64 -w0)'", "mail_subject": "my expiration"}'
    ```
</file>

<file path="docs/core/validation.md">
---
layout: default
title: Validation framework
nav_order: 4
parent: Core
---

# Validation framework

All [agent actions]({{site.baseurl}}/core/agents) inherit a validation system.
Each agent action can include some validation steps using JSON schema or create
custom validation steps.

* TOC
{:toc}

## JSON schema

Basic validation of input and output can be enforced using [JSON
Schema](https://json-schema.org/).

To validate the input just drop a `validate-input.json` file inside the
action directory, to validate the output just create a
`validate-output.json` file.

As general rule, schema files are loaded from special paths:
- `${AGENT_INSTALL_DIR}/validator-definitions.json`: this is always picked
  up by the agent from all actions. It can contain the common data format
  definitions
- `${AGENT_INSTALL_DIR}/actions/<action-name>/validate-input.json`: schema
  applied to validate the input data
- `${AGENT_INSTALL_DIR}/actions/<action-name>/validate-output.json`:
  schema applied to validate the output data

## Custom validation

The JSON schema can perform formal validation of input and output parameters.
Semantic validation, like searching for duplicates or check if a network host is reachable,
should be implemented inside custom scripts.

Additional validation logic can be implemented in an early step script
like `01validation`. If the validation fails, the step must execute the
[set-status](#set-status) command and return a non-zero exit code.

It is recommended to write custom scripts using Python, but any executable script inside
the action directory would do the job.

### Progress handling

Validations steps will block the task progress to 0 inside the UI.
After the validation has passed, the task will be set as running and the progress will be
tracked by the user interface.

When writing Python-based validation scripts, use this snippet:
```python
agent.set_weight(os.path.basename(__file__), 0) # Validation step, no task progress at all
```
</file>

<file path="docs/core/volume_metrics.md">
---
layout: default
title: Volume metrics
nav_order: 19
parent: Core
---

# Volume metrics

NS8 exposes per-volume and per-module disk usage on each node's existing
`node_exporter` endpoint. The metrics are produced by
`refresh-volume-metrics.service`, a collector that runs on every node,
writing a Prometheus text file into `node_exporter`'s textfile collector
directory once a day, triggered by `refresh-volume-metrics.timer`. Like
the [container metrics](container_metrics.md), the series appear on the
node's `/metrics` endpoint and are collected into the `metrics`
module's Prometheus on the leader node, with no new port and no new
scrape job.

The collector walks the directory trees, because there's nothing
cheaper to read: podman volumes are plain directories, and the root
filesystem is mounted `noquota`, so a size can only be obtained by
visiting every inode. That walk is expensive on a node holding mail or
file shares, which is why it runs as its own unit on a slow schedule
instead of another pass inside `refresh-container-metrics.service` — a
slow walk never delays the container samples, and a failure in one
collector doesn't take the other down. The unit also runs with
`Nice=10` and `IOSchedulingClass=idle`, so a monitoring pass never
makes a busy server feel slow.

Sizes are the space actually occupied on disk, `st_blocks * 512`, not
the apparent file size, and a hardlinked file is charged once per
module. Both match `du -s -B1`; `ns8_volume_files` matches
`du -s --inodes`.

The image-store walk stays on one filesystem, like `du -x` (compare
against `du -sx -B1`). It skips a running rootfull container's union
view, mounted inside the store at `overlay/<layer>/merged` — counting
it would re-count the whole container rootfs on top of the layers it's
built from, and hardlink dedupe doesn't catch it since lower-layer
files have a link count of one. The volume and state walks do cross
filesystems, so a volume backed by its own mount is still measured.

## Metrics

All gauges:

| Metric | Labels | Meaning |
|---|---|---|
| `ns8_volume_size_bytes` | `module`, `volume` | Volume disk usage |
| `ns8_volume_files` | `module`, `volume` | Filesystem objects in the volume, directories included |
| `ns8_module_volumes_bytes` | `module` | Named volume disk usage of the module |
| `ns8_module_images_bytes` | `module` | Container image store disk usage |
| `ns8_module_state_bytes` | `module` | Module state and configuration disk usage |
| `ns8_module_total_bytes` | `module` | Module disk usage, volumes and images included |
| `ns8_volume_collector_duration_seconds` | none | Duration of the last volume metrics collection |
| `ns8_volume_collector_skipped_modules` | none | Modules that could not be collected in the last collection |
| `ns8_volume_collector_last_success_timestamp_seconds` | none | Unix timestamp of the last successful collection |

## Buckets

Each module is walked once, and the result is split into three
non-overlapping buckets, reported per module by
`ns8_module_volumes_bytes`, `ns8_module_images_bytes` and
`ns8_module_state_bytes`. `ns8_module_total_bytes` is their sum, emitted
because adding three families up in PromQL is awkward.

`ns8_module_volumes_bytes` is the same figure as
`sum by (module) (ns8_volume_size_bytes)`, kept as its own series so
that a per-module view needs no aggregation.

Hardlink accounting is per module: each module's buckets share one set
of visited inodes, so a file with several names inside one module is
charged once, and two modules that share a hardlinked file are each
charged for it. Summing `ns8_module_total_bytes` across modules can
therefore exceed the space actually occupied, which is the same
behaviour as running `du -s` on each module separately.

| Bucket | Rootless module | Rootfull module |
|---|---|---|
| volumes | `~/.local/share/containers/storage/volumes/<volume>` | `/var/lib/containers/storage/volumes/<volume>` |
| images | `~/.local/share/containers/storage`, volumes excluded | `/var/lib/containers/storage`, volumes excluded |
| state | the home directory, container storage excluded | `/var/lib/nethserver/<module>` |

A rootless module is any local user whose home holds the agent state
file `.config/state/agent.env` (the same test `runagent` uses), not
just any owner of a `.local/share/containers/storage` directory —
an administrator who has ever run rootless podman owns one of those
too. This test also keeps a module counted while all its containers
are stopped, unlike a discovery based on running cgroups.

A rootfull module is a `/var/lib/nethserver/<name><number>` directory.
The core's own directories -- `cluster`, `node`, `api-server` -- carry
no trailing digits, so the shape alone tells them apart. Those three are
not modules, but their contents are real disk usage: they are summed
into `ns8_module_state_bytes{module="core"}`.

## Rootfull attribution

Rootfull modules share a single storage root, which constrains what can
be attributed to whom.

The image store is one overlay tree with shared layers, so no rootfull
module can be charged for its own part of it. It is reported once, as
`ns8_module_images_bytes{module="core"}`, rather than split by a guess.
Rootfull modules therefore have no `ns8_module_images_bytes` series of
their own, and their `ns8_module_total_bytes` covers their volumes and
state only.

Rootfull volumes are attributed by name, longest match first:
`crowdsec1-data` belongs to `crowdsec1`. Podman's volume-to-container
link lives only in its own database, unreadable without libpod, so the
name is the only durable clue available. A volume matching no module
(`redis-data`, `rclone-cache`) belongs to a core container and is
reported with `module="core"`, same as the container metrics.

The core's own directories are not modules, so `core` has no
`ns8_module_state_bytes` series: its total is the shared image store
plus the volumes of the core containers.

Volume names are unique per module, not per node: `openldap1` and
`samba1` both own a volume named `data`. Always select on both labels.

## Missing values

As with the container metrics, the collector omits a metric rather than
reporting it as zero whenever a value could not be measured. Prometheus
treats an absent series and a zero series differently, and reporting
zero would assert a measurement that was never taken. A zero in
`ns8_volume_size_bytes` is a real measurement: an empty volume whose
directory fits inside its inode occupies no blocks at all.

If one of a module's trees can't be walked, that bucket is left out and
the module is counted once in `ns8_volume_collector_skipped_modules`.
The module's other buckets are still reported — this gauge is what
tells a partial pass from a complete one, since an absent
`ns8_module_state_bytes` alone could just mean the module has no state
tree. A pass that fails outright leaves the previous file in place, so
metrics go stale rather than disappearing; check
`ns8_volume_collector_last_success_timestamp_seconds` to tell the two
cases apart.

Also pay attention to the following:
- `ns8_volume_collector_skipped_modules` above zero means the last pass
could not measure something
the journal of `refresh-volume-metrics.service`.
- `ns8_volume_collector_duration_seconds` approaching a day is the other
signal worth watching
</file>

<file path="docs/core/vpn.md">
---
layout: default
title: VPN
nav_order: 8
parent: Core
---

# VPN

Each node is connected to the leader using
[WireGuard](https://www.wireguard.com/) in a star network topology, where
the leader node is the hub of the VPN links so it is connected to any
other node.

The VPN has its own network, the default is `10.5.4.0/24` and it listens
on UDP port 55820. Make sure this address is not already used inside your
existing network and the UDP port 55820 is open on your firewall. You can
change the VPN network during cluster initialization.

## Promote a worker to leader

Changing the cluster leader implies all VPN connections must be
reconfigured to point to the new VPN hub. The future leader node must
provide a VPN endpoint that is reachable by any other node. For this
reason, **be prepared in advance** to deal with a leader failure by
providing a reachable endpoint address on one or more worker nodes!

For instance if node with ID `3` has a public and static IP address
`1.2.3.4` log on the leader node and run the following command:

    redis-cli HSET node/3/vpn endpoint 1.2.3.4:55820

A DNS host name can be set too, if there is one available:

    redis-cli HSET node/3/vpn endpoint node3.example.com:55820

When the promotion time comes and depending on the old leader node state,
an automatic or manual procedure executes the new leader promotion.

- If the old leader node is alive, it can notify the cluster nodes to do
  the switch automatically to the new leader

- If the old leader node is dead, a manual change is needed on every node.

### Alive leader

Assuming `3` is the node ID of the new leader,

1. log on to the old leader node,

1. run the `promote-node` action:

       api-cli run promote-node --data '{"node_id":3, "endpoint_address":"node3.example.com", "endpoint_port":55820}'

In a few seconds the change is propagated to all nodes and the old leader
becomes a worker.

The endpoint address is validated with a HTTPS request. We expect that
cluster-admin is running on the endpoint. If this check passes, but VPN
connection fails for any reason, apply the "Dead leader" procedure
described in the next section.

### Dead leader

Assuming `3` is the node ID of the new leader, for each worker node

1. log on to the worker node
1. run the following command for each of them:

       switch-leader --node 3 --endpoint node3.example.com:55820

The order of the nodes is not important but it is wise to start with the
new leader node.

## Wireguerd configuration

The VPN is configured in every node to use the interface `wg0` and listens
on UDP port 55820. To inspect the VPN status run

    wg show wg0

Example:
```
[root@cs1 ~]# wg show wg0
interface: wg0
  public key: 4fYZdrhcdjQo3cyvLIJC1TaFR8G6KRT7hZgZNPRoGzo=
  private key: (hidden)
  listening port: 55820

peer: 3Ft+OeV/fdRXnWKcyD8e+emsMxzQGZ1grWqR+/FCoEc=
  endpoint: 178.128.169.93:55820
  allowed ips: 10.5.4.2/32
  latest handshake: 1 minute, 28 seconds ago
  transfer: 96.23 MiB received, 50.01 MiB sent
  persistent keepalive: every 25 seconds

peer: nvu810d2Q3LGUwJNmJawXj7u16+JUukgreQo4NCcACc=
  endpoint: 104.248.130.240:55820
  allowed ips: 10.5.4.3/32
  latest handshake: 1 minute, 34 seconds ago
  transfer: 12.14 MiB received, 13.57 MiB sent
  persistent keepalive: every 25 seconds
```

Configuration file is saved inside `/etc/wireguard/wg0.conf`, public and private keys are saved inside `/etc/nethserver/wg0.{pub,key}`.

The configuration file is initialized by `create-cluster` and `join-node`
actions. Local modification to the configuration file can be merged into
the runtime state with the following command:

    systemctl reload wg-quick@wg0

Runtime changes can be persisted to the configuration file with the
following command:

    wg-quick save wg0

The `apply-vpn-routes` command is the handler of the "vpn-changed" and
"leader-changed" events. It is also executed at system startup, after
Redis is synchronized with the leader node (or is the cluster leader by
itself). The command:

* reads VPN and IP routing settings from Redis
* applies changes to runtime WireGuard and IP routing configuration, to
  reflect the configuration from Redis
* invokes `wg-quick save wg0` to overwrite the `wg0.conf` configuration
  file
</file>

<file path="docs/modules/agent.md">
---
layout: default
title: Agent
nav_order: 80
parent: Modules
---

# Module agent

* TOC
{:toc}

## Base actions

Agent task processing is defined by actions. An `action` is a directory
containing one ore more executable scripts called `steps`. See [the agent
README](https://github.com/NethServer/ns8-core/blob/main/core/agent/README.md#agent)
for the complete story.

The core provides a set of base actions defined in
`/usr/local/agent/actions` and inherited by module agents.

- `create-module`: executed upon installation, it automatically downloads the module image and all images
  listed inside `org.nethserver.images` label.
- `destroy-module`: executed on module removal; modules can add here
  scripts to clean up configuration, like Traefik routes, Firewalld,
  system-wide Systemd units...
- `get-status`: used by the UI, it returns the current module status, like the node where the application is running, used images and volumes, systemd units status.
  This action works correctly only for rootless modules.
- `list-service-providers`: Look up provider information for a given
  service name and other filtering criteria. See also [Service
  providers]({{site.baseurl}}/modules/service_providers)

Every agent has also a builtin `list-actions` action. This command lists the
actions provided by the agent of `module/traefik1`:

    api-cli run --agent module/traefik1 list-actions | jq

As a convention, all modules with a UI should also implement the following actions:

- `configure-module`: it validates the user input and applies the
  configuration, see [Dokuwiki
  example](https://github.com/NethServer/ns8-dokuwiki/tree/main/imageroot/actions/configure-module)
- `get-configuration`: it should return current configuration, the output
  should be equal or similar to configure-module input, see [Dokuwiki
  example](https://github.com/NethServer/ns8-dokuwiki/tree/main/imageroot/actions/get-configuration)


## Agent environment

Environment variables are copied to Redis at `module/<module_id>/environment`.

Each action has access to environment variables. They are:
1. initialized by `add-module`
2. changed by the agent at run time
3. inherited from the agent environment

Main environment variables are:
- `MODULE_ID`: the ID of the instance, i.e. `myapp1`
- `NODE_ID`: the node ID where the action is running, i.e. `1`
- `<name>_IMAGE`: see [Image download](#image-download)
- `TCP_PORT`, `TCP_PORTS`, `TCP_PORTS_RANGE`: see [Port allocation](#port-allocation)
- `UDP_PORT`, `UDP_PORTS`, `UDP_PORTS_RANGE`: see [Port allocation](#port-allocation)

Other available variables:
- `AGENT_COMFD`: the file descriptor to talk to the agent via [action commands](#action-commands)
- `AGENT_TASK_ID`: the unique ID of current task, i.e. `c0b8b976-9444-42d5-a40b-142a6a483a84`
- `AGENT_TASK_ACTION`: the name of executed action, i.e.: `create-module`
- `AGENT_TASK_USER`: the name of the user that created the action, if available. For example, `admin`
- `AGENT_INSTALL_DIR`
- `AGENT_STATE_DIR`
- `AGENT_ID`
- `IMAGE_ID`
- `IMAGE_URL`
- `IMAGE_DIGEST`
- `IMAGE_REPODIGEST`

Environment variables added by the `add-module` and defined at run time are
saved inside `/home/<module_id>/.config/state/environment`, e.g.
`/home/myapp1/.config/state/environment`.

To run a command within an agent environment, use the `runagent` wrapper. For instance
this command prints the agent environment of the rootfull module `modrootfull1`.

    runagent -m modrootfull1 env


## Agent commands

During the action execution, action steps can talk to the agent using a
simple protocol. For instance, it is possible to set/unset environment
variables that are persisted under the `AGENT_STATE_DIR`.

See all [available action commands](https://github.com/NethServer/ns8-core/blob/main/core/agent/README.md#action-commands).

The protocol is implemented by the Python `agent` package.

Python example:
```python
import agent

agent.set_weight('05longstep', 2)
```

## Validation

See [validation framework]({{site.baseurl}}/core/validation).
</file>

<file path="docs/modules/backup_restore.md">
---
layout: default
title: Backup and Restore
nav_order: 60
parent: Modules
---

# Backup and Restore

* TOC
{:toc}

## General concepts

The module backup engine is [Restic](https://restic.net/) which runs
inside a container (see `RESTIC_IMAGE` in `/etc/nethserver/core.env`).

A module backup is saved under a reserved Restic repository inside one or
more *backup destinations*. A module has no direct access to destinations
and their secret configuration: it must access them through the local node
`rclone-gateway` HTTP proxy service, providing the module's Redis
credentials. The URL to access its Restic repository has this form:

    http://127.0.0.1:4694/<destination ID>/<app type>/<module UUID>

The URL path has three levels:

1. The destination ID, in UUID syntax.
2. The application type, the module ID without the trailing number, e.g. `traefik`.
3. The module UUID

## Entry points

The `module-backup` command is provided by NS8 core and is executed with
module's privileges to backup the module.

The module itself can implement two commands: `module-dump-state` and
`module-cleanup-state` to prepare/cleanup the data that has to be included
in the backup.

The module `state/environment` file is always included inside the backup,
as it is required by the cluster during restoration
(`cluster/restore-module` action).

The restore is implemented using the module `restore-module` action. The
core provides a basic implementation, and the module can extend it to
implement specific restore steps. The basic `10restore` step actually runs
the Restic restore procedure in a temporary container and extracts the
backup data to the `state/` directory and to Podman named volumes.

## Include and exclude files

Whenever possible, containers should use volumes to avoid UID/GID
namespace mappings and SELinux issues during backup an restore.

Includes can be added to the `state-include.conf` file saved inside `AGENT_INSTALL_DIR/etc/`.

In the [source tree](modules/images/#source-tree), the file should be
placed under `<module>/imageroot/etc/state-include.conf`. On installed
modules, the file will appear on different paths:

- rootless containers, eg. `dokuwiki1`, full path will be
  `/home/dokuwiki1/.config/etc/state-include.conf`

- rootfull containers, eg. `dnsmasq1`,  full path will be
  `/var/lib/nethserver/dnsmasq1/etc/state-include.conf`

Lines are interpreted as path patterns. Only patterns referring to volumes
and the agent `state/` directory are considered.

Lines starting with `state/` refer to `AGENT_STATE_DIR` contents. Eg. to
include `mykey.dump` under the `AGENT_STATE_DIR` add

    state/mykey.dump

Lines starting with `volumes/` will be mapped to a volume name. Eg. to
include the whole `dokuwiki-data` volume add

    volumes/dokuwiki-data

Internally, volumes will be mapped as:

- `<volume_name>` (1-1) for rootless containers; eg. for module
  `dokuwiki1`, line prefix `volumes/dokuwiki-data` maps to volume name
  `dokuwiki-data`

- `<module_id>-<volume_name>` for rootfull containers; eg. for module
  `dnsmasq1`, line prefix `volumes/ data` maps to volume name `dnsmasq1-data`

Volumes listed in `state-include.conf` are automatically mounted (and
created if necessary) by the basic `10restore` step of the
`restore-module` action.

Excludes can be added to `state-exclude.conf` file saved inside the `AGENT_INSTALL_DIR`.

For a complete explanation of the patterns, like wildcard characters, see
the official Restic documentation to
[include](https://restic.readthedocs.io/en/stable/040_backup.html#including-files)
and
[exclude](https://restic.readthedocs.io/en/stable/040_backup.html#excluding-files)
files. Note that include and exclude patterns have a slight different
syntax.

## Save Redis keys

To save a Redis key, you should:

- dump the key inside the `module-dump-state` command
- include the dump inside the backup

Given a module named `mymodule`, create the file
`mymodule/imageroot/bin/module-dump-state` inside the module source tree:

    #!/bin/bash
    redis-dump module/mymodule1/mykey > mykey.dump


Make sure also `module-dump-state` is executable:

    chmod a+x mymodule/imageroot/bin/module-dump-state


Then, add the key dump path to `mymodule/imageroot/etc/state-include.conf`:

    state/mykey.dump


## Cleanup state

As best practice, the dump should be removed when the backup has completed.

Given a module named `mymodule`, create the file `mymodule/imageroot/bin/module-cleanup-state` inside the module source tree:

    #!/bin/bash
    rm -f mykey.dump

Make sure also `module-cleanup-state` is executable:

    chmod a+x mymodule/imageroot/bin/module-cleanup-state


## Restore Redis keys

To restore a Redis key, you should add a step inside the `restore-module` action, after index 10.

Given a module named `mymodule`, create a file named `mymodule/imageroot/actions/restore-module/20loadkey` inside the module source tree:

    #!/bin/bash
    redis-restore mymodule1/mykey < mykey.dump
</file>

<file path="docs/modules/certificates.md">
---

layout: default
title: TLS certificates
nav_order: 80
parent: Modules

---

TLS certificates
================

X.509 certificates for TLS are managed by the Traefik instance running on
the local node. For more details, see
[Proxy and certificates](../../core/proxy_certificates) in the core
documentation.

Web applications
----------------

Web applications should not handle TLS certificates directly, as the
Traefik HTTP proxy listens on TCP port 443 for HTTPS requests. HTTP
backends must be configured only for plaintext HTTP connections.

If the module needs to set up a hostname-based HTTP route, it is
possible to instruct Traefik to obtain a TLS certificate for it in a
single action.

```python
agent.set_route({
    'instance': os.environ['MODULE_ID'],
    'url': f'http://127.0.0.1:{os.environ["TCP_PORT"]}',
    'host': host_fqdn,
    'lets_encrypt': True, # request certificate for host_fqdn
    'http2https': True, # redirect http:// URL scheme to https://
})
```

Note that `instance` must be a unique route identifier. If the module uses
multiple HTTP routes, use MODULE_ID as prefix or suffix to distinguish
them (e.g. `mymodule1-ui`, `mymodule1-api`, ...). When the module is
removed HTTP route instances matching `mymodule1` are automatically
removed.

Let's Encrypt remote validation may fail for many reasons. The default
`set_route` behavior is to abort the caller process on any error, echoing
the output and error of the Traefik's `set-route` action. This is obtained
with the following implicit input arguments:

- `lets_encrypt_check: True`
- `lets_encrypt_cleanup: True`

If this is not desired, set argument `error_passthrough=False`, and the
full action result dictionary is returned.


TLS for other applications
--------------------------

Applications that require `.pem`, `.key`, `.crt`, or similar files for
their configuration must be granted Traefik's `fulladm` role to run
privileged actions. Add the following authorization request to your app's
image labels:

     org.nethserver.authorizations = traefik@node:fulladm

This is the general application workflow to request and obtain the
certificate and its private key.

1. A certificate request for Let's Encrypt is issued using the
   `set-certificate` action.

2. The application listens for the `certificate-changed` event. This
   event is triggered when the TLS certificate
   - is uploaded with cluster-admin UI,
   - is obtained/renewed from Let's Encrypt.

3. Upon receiving a `certificate-changed` event, invoke the `get-certificate`
   action to obtain the PEM-encoded key and certificate.

For example, to issue a Let's Encrypt certificate request for
`SERVICE_FQDN` run:

```python
agent.set_certificate({
    "fqdn": myname,
    "lets_encrypt": True, # optional, default True
})
```

Let's Encrypt remote validation may fail for many reasons. The default
`set_certificate` behavior is to abort the caller process if an error
occurs, echoing the output and error of the Traefik's `set-certificate`
action. If this is not desired, set argument `error_passthrough=False`,
and the full action result dictionary is returned to the caller.

To handle the event, create an executable script under
`$AGENT_INSTALL_DIR/events/certificate-changed`. The event handler:

1. Checks if the event is relevant to the running service.
2. Restarts the service.

The following Python code implements these steps using the `agent`
library and the `get-certificate` command:

```python
import agent
import json
import sys
event = json.load(sys.stdin)
myname = os.environ["SERVICE_FQDN"]

if not agent.certificate_event_matches(event, myname):
    sys.exit(0) # ignore event if not relevant

agent.run_helper('systemctl', '--user', 'try-restart', 'myservice')
```

It is recommended to run `get-certificate` before the service starts or is
fully restarted from the handler, to ensure the correct certificate is
used by the service. There can be different ways to achieve this behavior,
but it is recommended to define a separate Systemd unit, to avoid repeated
`get-certificate` invocations if the service enters a crash-loop.

This is an example of `get-certificate.service` definition that also
generates a PEM file with both private key and the complete certificate
chain:

```ini
[Unit]
Description=Get TLS certificate from Traefik

[Service]
Type=oneshot
EnvironmentFile=%S/state/environment
WorkingDirectory=%S/state
SyslogIdentifier=%N
ExecStart=-mkdir -vp tls-certs
ExecStart=-runagent get-certificate --cert-file=tls-certs/server.pem --key-file=tls-certs/server.key $POSTFIX_HOSTNAME
ExecStart=-bash -c 'cd tls-certs ; umask 177 ; cat server.key server.pem > fullchain.pem ; touch -r server.pem fullchain.pem'
```

Add the following lines to `myservice.service` Systemd unit, to run
`get-certificate.service` before the service is started or restarted:

```ini
[Unit]
# ...existing lines
Wants=get-certificate.service
After=get-certificate.service
```

To avoid a full service restart when the certificate changes, the
`myservice.service` unit can provide a reload operation. In this case,
modify the `certificate-changed` event handler as follows.

1. Checks if the event is relevant to the running service.
2. Obtains the certificate and its private key for the service FQDN.
3. If the certificate was changed, reloads the running service.

```python
import agent
import json
import sys
event = json.load(sys.stdin)
myname = os.environ["SERVICE_FQDN"]

if not agent.certificate_event_matches(event, myname):
    sys.exit(0) # ignore event if not relevant

# Obtain the changed certificate and its private key
get_proc = agent.run_helper('get-certificate', '--cert-file=service.pem', '--key-file=service.key', myname)

# Reload the running service if the certificate differs
if get_proc.returncode == 0:
    agent.run_helper('systemctl', '--user', 'reload', 'myservice')
```
</file>

<file path="docs/modules/certification.md">
---
layout: default
title: Community Certification
nav_order: 134
parent: Modules
---

# Application Community Certification

* TOC
{:toc}

## From ideas to applications

Before creating an application for NethServer 8, consider if it's really
necessary. Sometimes, a simple documentation page is sufficient and
requires much less effort. When trying out new ideas, make sure to
document every step and comment in a [community discussion under the
Feature category](http://community.nethserver.org/c/feature).

If the idea gains traction, then it's time to think about a new
application. When creating one, ensure the following requirements are met:

- The application and its components must respect user data privacy and
  integrity. Although this may seem obvious, it's crucial for everyone to
  be aware of any special data treatments performed by the application,
  especially if it relies on third-party cloud services. This allows users
  to evaluate whether those treatments comply with their country's laws
  and personal privacy standards.

- If your application relies on third-party work, make sure it complies
  with their license.

- Create a personal repository on GitHub, for example by starting with the
  [ns8-kickstart
  template](https://github.com/new?template_name=ns8-kickstart&template_owner=NethServer).
  The [How to](../new_module) page provides a brief introduction about
  applications (or modules) development.

- Add a license and copyright notice in the `COPYING` or `LICENSE` file.
  GPL v3+ is highly recommended to ensure your work is distributed and
  used under that license.

- Announce the new application on the [community.nethserver.org
  App](http://community.nethserver.org/c/app) category.

- If desired, submit a pull request for the [NethForge repository
  metadata](https://github.com/NethServer/ns8-nethforge/) to have the
  application listed on the Software Center page. Be sure to include a
  link to the community announcement. If you prefer to setup a personal
  application repository, look at the [Software
  repositories](../../core/software_repositories/) page.

Before being included in NethForge, applications must pass a review
process. The review process leading to inclusion in NethForge is described
in the next section.

## Certification process

The Community Certification ensures that an application is functional,
secure, maintained, and provides sufficient information about the
developer and the software it relies on.

Submitting a pull request (PR) for the [NethForge repository
metadata](https://github.com/NethServer/ns8-nethforge/) starts the
Community certification process for the application.

After approval, at any time, the application can be removed from NethForge
by the NethForge repository maintainers. For example, this can happen if
the current version is no longer maintained and/or has significant security
issues, or if its behavior is deemed malicious.

Here follow some tips that may help to quickly complete the certification
process.

### 1. Metadata and license

0. The PR for NethForge must contain a directory and files as described in
   [Create a
   repository](../../core/software_repositories#create-a-repository).

0. Similarly, fill the [metadata.json](../metadata/) file of the app UI
   with the required information. Provide details for reporting bugs, such
   as a link to the app's bug tracker (you can link to
   `https://github.com/NethServer/dev/issues`), the developer's email, and
   any other relevant contact information.

0. Additionally, in the `metadata.json`, consider linking a document via
   `terms_url` that clarifies any data treatment or application behavior
   the user should be aware of. This is particularly important if the
   application handles sensitive data or must conform to data privacy
   laws. During the certification process, we will pay close attention to
   compliance with EU laws and regulations.

0. Administrator documentation. This is the documentation for the
   administrator who must configure the applications for the final users.
   A public web page link must be provided in the PR description. You can
   decide to write the documentation on your preferred web site or to
   directly create a new [NS8 Admin's
   Manual](https://github.com/NethServer/ns8-docs/) page with a PR. In
   both cases the metadata.json documentation URL will point to the latter
   with an application summary available from there.

0. Integrate the `README.md` file in the code repository with
   documentation for developers and the support team. A detailed
   description of container volumes, environment variables, and special
   maintenance or customization procedures is very important. If something
   is still missing, document it for instance under a "Roadmap",
   "Limitations", "TODO" section. Provide also a link to your Community
   profile to contact you.

0. The application and its parts must have no licensing conflicts.
   Licenses must permit unlimited distribution of the application.

### 2. Platform compliancy

0. The implementation of platform-defined behaviors, where present, must work
   correctly. Pay attention to:

    - Application Creation and Removal
    - Clone and Move
    - Backup and Restore
    - Change of cluster Email notification settings
    - HTTP routes management
    - TLS certificates management
    - Bind to one or more User Domains
    - Node firewall management
    - Node ports allocation

0. Applications must avoid requiring root privileges (rootfull) and should
   operate with the minimum necessary authorizations. Exceptions may be
   requested but must be justified and approved on a case-by-case basis.

0. The UI code respects Internationalization (i18n) and [NS8 Weblate
   project](https://hosted.weblate.org/projects/ns8/) has a component for
   your app Localization (l10n). The app translation license must be
   compatible with the Weblate Libre Hosted plan. For this purpose, if
   your app license is not compliant, choose a translation license from
   [choosealicense.com](https://choosealicense.com/).

### 3. Application updates

Application updates must obey the same rules of the core, described in the
[Development process](../../development_process#update-rules).
</file>

<file path="docs/modules/code_snippets.md">
---
layout: default
title: Code snippets
nav_order: 140
parent: Modules
---

# Code snippets

Some code examples to ease the life of module developers

## Hostname FQDN

Retrieve the fully qualified domain name of the server by using the `agent` Python library. In case of exception the function outputs the default FQDN `myserver.example.org`.

Python example code:

```python
import agent

fqdn = agent.get_hostname()
print(fqdn)
```

output example:
```
foo.domain.com
```

## Port validation

Check if the TCP port is already used by a service. Exit with an error if the port is used.

```python
import sys
import agent

port=80
if agent.tcp_port_in_use(port):
    sys.exit(1)
```


## Web route validation

Check if HTTP routes are handled by Traefik. The function issues an HTTP request to 127.0.0.1 port 80, setting the `Host` header in the HTTP request and/or the URL path. Any HTTP non-404 response assumes the HTTP route exists.

### Test if a domain-based route is used (domain.com)
```python
import sys
import agent

hostname = 'foo.com'
if agent.http_route_in_use(domain=hostname):
    sys.exit(2)
```

### Test if a path-based route is used (/path)
```python
import sys
import agent
path ='/path' # path fragment of the URL to check
if agent.http_route_in_use(domain=none, path=path):
    sys.exit(2)
```

## Atomic file write

Write a file so that readers never see partial contents, even if the
process crashes or the system loses power during the write. The
`agent.safe_open()` context manager writes to a temporary file in the
same directory as the target, flushes it to disk, then atomically
replaces the target and syncs the directory.

```python
import agent

with agent.safe_open("myapp.conf", "w") as fo:
    fo.write("key=value\n")
```

- Only write modes, like `w` or `wb`, are supported; read and append
  modes raise `ValueError`. The `encoding` argument applies to text
  modes.
- If the target file exists, its permission bits are copied to the new
  file. Otherwise the new file is created with mode `0666` minus the
  process umask.
- If the `with` block raises an exception, the target file is left
  untouched and the temporary file is removed.

The agent library itself uses `safe_open()` to write the `environment`
file in `agent.set_env()` and `agent.write_envfile()`. The core uses it
also to generate the HAProxy configuration of the rclone backup gateway
(`rclonegwctl`).

`safe_open()` does not serialize concurrent writers: the last one wins.
For read-modify-write cycles, wrap the whole cycle with the
`agent.exclusive_file_lock()` context manager, as `agent.set_env()`
does:

```python
import agent

with agent.exclusive_file_lock("myapp.conf"):
    with open("myapp.conf") as fi:
        data = fi.read()
    with agent.safe_open("myapp.conf", "w") as fo:
        fo.write(data + "other=value\n")
```

The lock is an advisory `flock()` on a hidden `.<filename>.lock` file in
the same directory, so it is effective only among processes that use
the same function.

## Extra python libraries

If the module requires extra Python libraries, you can install them inside the `create-module` action.

Here's an example of a `create-module` action step named `20initialize`:

```bash
#!/bin/bash

pip install bcrypt==4.1.2
```

You can then use the imported `bcrypt` library in all your action steps. A similar script can be added under `update-module.d/`.
</file>

<file path="docs/modules/database.md">
---
layout: default
title: Database
nav_order: 90
parent: Modules
---

# Database access

Everyone can access the Redis database with read-only privileges. The
Redis user `default` (password is not important) can be used for this
purpose.

To get write access a module must provide the Redis credentials stored in
its `agent.env` file. The complete path is `~/.config/state/agent.env`.
Write access is restricted to Redis keys and channels with prefix
`module/{module_id}/*`. The same credentials allow broad read access, also
on `private/agents/*` namespace.

The above rules are already implemented by the Python `agent` module.

Access Redis in read-only:
```python
import agent

rdb = agent.redis_connect(privileged=False)
somehash = rdb.hgetall('cluster/somehash')
```

Access Redis in read-write mode:
```python
import agent

rdb = agent.redis_connect(privileged=True)
rdb.hset('module/myapp1/myhash', mapping={'myvar': 'myvalue'})
```

If Redis connection is required at service boot time, prefer connecting to
the local replica. This avoids issues if the leader node is unreachable.
```python
import agent

rdb = agent.redis_connect(use_replica=True)
cluster_network = rdb.get('cluster/network')
```

Any additional keyword argument supported by the installed Redis Python
library's `redis.Redis()` constructor can be passed to
`agent.redis_connect()`. These arguments are forwarded to the Redis client and
can configure options such as socket timeouts, retries, TLS, database selection,
and response decoding.

```python
rdb = agent.redis_connect(
    use_replica=True,
    socket_timeout=10,
    socket_connect_timeout=5,
)
```

`decode_responses` is one of these additional arguments. Redis responses are
decoded from UTF-8 to strings by default. Consumers that need to validate or
process each Redis bulk string independently can request the original bytes:

```python
import agent

raw_rdb = agent.redis_connect(
    use_replica=True,
    decode_responses=False,
)
for key in raw_rdb.scan_iter('cluster/*'):
    raw_hash = raw_rdb.hgetall(key)
    # key, raw_hash field names, and raw_hash values are bytes
```
</file>

<file path="docs/modules/images.md">
---
layout: default
title: Images
nav_order: 30
parent: Modules
---

# Images

* TOC
{:toc}

## General

NS8 modules are distributed as packages that are implemented as Podman
container images. A package is pulled from a remote software repository,
implemented by a registry service, like [GitHub
Packages](https://ghcr.io). Each package can be seen much like a *tar
archive*.

When installing a rootless module, the corresponding image is extracted
inside the home of the module Unix user, i.e. `/home/<module_id>`.
Rootfull modules are extracted under `/var/lib/nethserver/<module_id>`.

In both cases the module UI is extracted to
`/var/lib/nethserver/cluster/ui/apps/<module_id>`.

## Source tree

The sources repository of a module can be structured as follow:

- `imageroot/`: it contains module scripts and configuration. Everything inside this directory is copied under the module installation directory. Common subdirs include:
  * `systemd/user`: where Systemd units are stored.
  * `actions/`: each subdirectory implements an *action*.
  * `bin/`: it contains additional binaries for the module. It is added to PATH in the agent environment.
  * `etc/`: to store additional configuration for Backup and Restore
  * `pypkg/`: path for module Python packages, added to `PYTHONPATH`
- `ui/`: it contains all UI source code of the module
- `build-images.sh`: a script to manually build one or more images of the module and push them inside the image registry.
- `README.md`: a [Markdown](https://guides.github.com/features/mastering-markdown/) file describing the module purpose and implementation

## Image labels

Module images can use a list of well-known labels to configure the system:

- `org.nethserver.tcp-ports-demand`: see [Port allocation](../port_allocation)
- `org.nethserver.images`: see [Service images](#service-images)
- `org.nethserver.rootfull`: can be `0` or `1`, if set to `0` the module will run podman in rootless mode,
  if set to `1` the module will run podman in rootfull mode. See [Rootless vs Rootfull](../rootless_rootfull)
- `org.nethserver.authorizations`: authorize the module to run actions of other modules. For instance `traefik@node:routeadm` allows setting routes on the Traefik instance of the module node.
  Request the narrowest scope: prefer `@node` over `@any`, unless the module really needs to drive instances on other nodes.
  See [Roles and authorizations]({{site.baseurl}}/core/agents/#roles-and-authorizations).
- `org.nethserver.flags`: a space-separated list of well-known flags. Currently available flags are:
  - `core_module`: if present, it marks a module as core
  - `account_provider`: if present, it marks a module as an account provider
  - `no_data_backup`: if present, the modules will need no data backup
  - `rootless`: if present, the module is rootless (calculated from `org.nethserver.rootfull` label)
  - `rootfull`: if present, the module is rootfull (calculated from `org.nethserver.rootfull` label)
- `org.nethserver.max-per-node`: maximum number of module instances installed on the same node
- `org.nethserver.min-from`: the image can be used to install a new
  application instance, or to update an existing instance provided it has
  a version greater than or equal to the label value. E.g. if the image
  label `org.nethserver.min-from` has value `2.0.0`, an existing instance
  with version `1.3.0` cannot be updated with it.
- `org.nethserver.min-core`: the image can be used to install a new
  application instance, or update an existing one, if the core version is
  greater than or equal to the label value. E.g. if the image label
  `org.nethserver.min-core` has value `2.7.0` it cannot be installed if
  the leader node running core has version `2.6.2`.
- `org.nethserver.volumes`: space-separated list of named volumes. When
  the node provides additional disks, the Sysadmin is prompted to assign
  these volumes one of them. See [Volumes](../volumes).

Labels are set by `build-images.sh`, when the images are built.

## Service images

Most modules run software from additional Podman images. The
`org.nethserver.images` takes a space-separated list of image URLs that
will be automatically downloaded by the `create-module` base action.

Information about the downloaded images are stored in the agent
environment, so they can be referenced in unit `.service` files and action
scripts.

Environment variables names are set as follow:
- one variable for each image
- variable name is the uppercase value of the image name
- symbols are mapped to `_` (underscore)
- if the image name begins with a digit, a `I` is prepended
- `_IMAGE` suffix is appended

Examples:
- `docker.io/library/mysql:10.3-alpine` becomes `MYSQL_IMAGE=docker.io/library/mysql:10.3-alpine`
- `quay.io/prometheus/node-exporter:v1.5.0` becomes `NODE_EXPORTER_IMAGE=quay.io/prometheus/node-exporter:v1.5.0`
- `docker.io/2fauth/2fauth:5.2.0` becomes `I2FAUTH_IMAGE=docker.io/2fauth/2fauth:5.2.0`

## Registry mirrors

NethServer keeps a copy of some public images on its own registry,
`ghcr.io/nethserver`. Nodes are configured to pull images hosted on
`docker.io` and `quay.io` from this mirror first: if the image is
missing there, or the mirror cannot be reached, it is pulled from the
original registry. Image references in `org.nethserver.images` and in
the agent environment do not change: always use the original registry
URL.

The mirror was introduced to work around Docker Hub pull rate limits.
Docker Hub counts anonymous pulls by IPv6 /64 prefix, so many servers
sharing the same prefix, like VPSs of a cloud provider, reach the
limit quickly and image downloads fail during module installation and
updates (see [NethServer/dev#7160](https://github.com/NethServer/dev/issues/7160)).
The same mechanism was later extended to `quay.io` images (see
[NethServer/dev#8231](https://github.com/NethServer/dev/issues/8231)).

The mirror is made of two parts:

- **Node configuration**: the core installs
  `/etc/containers/registries.conf.d/800-nethserver.conf`, which
  declares `ghcr.io/nethserver/docker.io` and
  `ghcr.io/nethserver/quay.io` as mirrors of the respective registries.
  The configuration applies to Podman, Buildah and Skopeo.

- **Image copy**: the
  [ns8-repomd](https://github.com/NethServer/ns8-repomd) workflow runs
  `syncmirrors.sh` every time it publishes the default repository
  metadata. The script reads the `org.nethserver.images` label of every
  module version and copies each missing `docker.io` and `quay.io`
  image to the mirror, for example
  `quay.io/prometheus/prometheus:v3.13.2` becomes
  `ghcr.io/nethserver/quay.io/prometheus/prometheus:v3.13.2`. Short
  Docker Hub names are expanded, so `docker.io/redis:7` is copied as
  `ghcr.io/nethserver/docker.io/library/redis:7`.

Only images of modules published in the default repository are
mirrored. Images of other repositories, like NethForge, and images
from other registries are always pulled from their original location.
</file>

<file path="docs/modules/index.md">
---
layout: default
title: Modules
nav_order: 5
has_children: true
---

# Modules: implementation details

A module is an NS8 application which is usually composed by a backend and
a frontend.

Every time a module instance is added to the cluster, the new instance
is named as the module itself followed by a progressive number
starting from 1. Given a module named `myapp`, instances will be named
`myapp1`, `myapp2`, etc. This uniquely identifies the instance inside the cluster.

Modules can be managed using these commands:

- `add-module [--force] <module> <node_id>`: install a module on the given node with ID `node_id`; search for `module` inside enabled repositories and install
  latest available version. If `module` is a image registry URL, just install the module straight from it; this method can be used to install
  customized images. Like the Software Center, the command refuses a node that is not eligible, for example because of
  the `org.nethserver.max-per-node` or `org.nethserver.min-core` image labels; `--force` skips this check.
- `remove-module [--no-preserve] <module>`: remove an installed module; if `--no-preserve` is given, erase also all module data
</file>

<file path="docs/modules/metadata.md">
---
layout: default
title: Metadata
nav_order: 32
parent: Modules
---

# Metadata

Local metadata are used to display information inside the *About* page.
Metadata are composed by:

- a JSON file named `metadata.json`, saved inside `imageroot/ui/public/metadata.json`
- a PNG image for the logo named `module_default_logo.png`, saved inside `imageroot/ui/src/assets/module_default_logo.png`

## metadata.json

The JSON format is very similar to the 
[repository metadata](https://github.com/NethServer/ns8-core/blob/main/core/imageroot/var/lib/nethserver/cluster/repodata-schema.json),
without `id`, `logo` and `versions` fields.

Example of `metadata.json`:
```json
{
  "name": "Kickstart",
  "upstream_name": "Kickstart 12",
  "description": {
    "en": "My kickstart module"
  },
  "categories": ["somecategory"],
  "authors": [
    {
      "name": "Name Surname",
      "email": "author@yourmail.org"
    }
  ],
  "docs": {
    "terms_url": "https://docs.kickstart.com/terms/",
    "documentation_url": "https://docs.kickstart.com/",
    "bug_url": "https://github.com/NethServer/dev",
    "code_url": "https://github.com/author/ns8-kickstart",
    "relnotes_url": "https://github.com/author/ns8-kickstart/releases"
  },
  "source": "ghcr.io/nethserver/kickstart"
}
```

The `categories` field contains a list of string. Each string is a category that should describe the application usage scenario.
It could be something like `database` or `collaboration`. Always use lower case strings without spaces.

The list of available categories is available in this [translation.json
source
file](https://github.com/NethServer/ns8-core/blob/main/core/ui/public/i18n/en/translation.json),
under the `app_categories` object. Change proposals to the category list can be
discussed on the community forum, as explained in [development process](../../development_process/).

The `docs` object has the following optional keys:
- The `terms_url` is a link to a web page with important information (e.g. legal/privacy notices, license). It is displayed before installing the application.
- The `relnotes_url` is a link to a web page with the application release notes (changes, improvements, and fixes included in each release).

## Logo

The logo must be a PNG image and its size should be at least of 128x128 pixels.
</file>

<file path="docs/modules/metrics.md">
---
layout: default
title: Metrics
nav_order: 105
parent: Modules
---

# Metrics

A module can publish Prometheus metrics with a command that prints them.
No HTTP server and no open port are needed: the node serves them through
`node_exporter`, which the `metrics` module already scrapes.

Use it for values the module already knows, like the number of app active
users. A module that runs its own Prometheus exporter publishes it as
a target instead, with the `metrics-target-changed` event. See the
[ns8-metrics README](https://github.com/NethServer/ns8-metrics#provisioning-prometheus).

## The export-metrics command

Add an executable `imageroot/bin/export-metrics` to the module. Every 5
minutes the node runs it as:

```text
runagent -m <module_id> export-metrics
```

Example in Python, with the `prometheus_client` library included in
the core:

```python
#!/usr/bin/env python3

import os
import sys
import agent
import prometheus_client as prom

rdb = agent.redis_connect()
# A value the module keeps up to date, here in its own Redis key
users = rdb.hget(f"module/{os.environ['MODULE_ID']}/stats", "active_users") or 0

# Drop the <name>_created series of counters: it changes on every run
prom.disable_created_metrics()
registry = prom.CollectorRegistry()
active_users = prom.Gauge(
    "myapp_active_users",
    "Users active in the last 24 hours",
    registry=registry,
)
active_users.set(users)
sys.stdout.buffer.write(prom.generate_latest(registry))
```

Commands in other languages can print the text format directly, or use
the official client library of the language.

The node adds a `module` label to every sample:

```text
myapp_active_users{module="mail1"} 42
```

## Rules

| Topic | Rule |
|---|---|
| Output | Valid [Prometheus text format](https://prometheus.io/docs/instrumenting/exposition_formats/#text-based-format) on stdout, without timestamps. The node does not check it: review it with the module code. |
| Speed | Must finish within 30 seconds. Read values that are already there, for example in Redis. Compute expensive values in the module's own jobs. |
| Names | Prefix metric names with the application name, like `nethvoice_`. Never use `node_`, `ns8_`, `go_` or `process_`. |
| Labels | The node adds `module="<module_id>"`. Output that sets `module` or `module_id` is rejected. |
| Errors | Log to stderr. The node copies each line to its journal, prefixed with the module ID. |

## Failures

If the command fails, times out, or sets a reserved label:

- the node keeps the last output of the module;
- the error is logged:

  ```text
  journalctl -u refresh-module-metrics.service
  ```

The 30 seconds start when the command starts. When they expire, the node
sends `SIGKILL` to the process group of the command, which includes its
child processes. There is no `SIGTERM` first, so the command cannot
catch the signal or run cleanup code. Its stdout and stderr are
discarded. Do not leave state that needs cleanup: for example, write
files to a temporary name and rename them when they are complete.

If the output is not valid, `node_exporter` skips it. The other modules
are not affected. It logs the error and sets the node-wide
`node_textfile_scrape_error` gauge to `1`:

```text
journalctl -u node_exporter.service
```

When the command is removed, its metrics are removed at the next run.

## Alerts

A module ships its own alert rules in the Redis hash
`module/<module_id>/metrics_alert_rules`, one field per rule set. After
each change it emits the `metrics-alert-rules-changed` event, and
Prometheus reloads its rules without a restart. See
"metrics-alert-rules-changed event" in the
[ns8-metrics README](https://github.com/NethServer/ns8-metrics#metrics-alert-rules-changed-event).

- Prometheus copies the `module` label to `module_id`, the label module
  alert rules are scoped by. See "Per-module node series" in the
  [ns8-metrics README](https://github.com/NethServer/ns8-metrics#per-module-node-series).
- Module rules get the `module_id` matcher of their own module
  automatically.
- Give each rule a `severity` label, `warning` or `critical`, and the
  `summary_en`, `summary_it`, `description_en` and `description_it`
  annotations.
- Rules of a removed module are deleted automatically.
- The core defines no alert on module metrics.

Example: more active users than the license allows, in `license.yml`:

```yaml
alert: MyappTooManyUsers
expr: myapp_active_users > 100
for: 1h
labels:
  severity: warning
annotations:
  summary_en: Too many active users
  summary_it: Troppi utenti attivi
  description_en: Active users exceed the license limit
  description_it: Gli utenti attivi superano il limite della licenza
```

Publish it for `mail1`:

```text
redis-cli -x HSET module/mail1/metrics_alert_rules license < license.yml
redis-cli PUBLISH module/mail1/event/metrics-alert-rules-changed '{}'
```

## Collector

- Command: `refresh-module-metrics`, run by the node agent.
- Schedule: every 5 minutes, by `refresh-module-metrics.timer`.
  `node_exporter.service` wants the timer.
- Modules found as in the [volume
  metrics]({{site.baseurl}}/core/volume_metrics):
  - rootless: a user whose home holds `.config/state/agent.env`;
  - rootfull: a `/var/lib/nethserver/<name><number>` directory.
- Runs `export-metrics` only when `<install dir>/bin/export-metrics`
  exists and is executable. Up to 4 modules run at the same time, in
  random order, each after a random delay of up to 5 seconds.
- Output: `/var/lib/nethserver/node/state/node_exporter/module-<module_id>.prom`,
  one file per module, so invalid output does not hide the others.
  Written atomically, only when it changes.

Run it at once, without waiting for the timer:

```text
runagent -m node refresh-module-metrics
```

If another run is in progress, the command fails at once.
</file>

<file path="docs/modules/network.md">
---
layout: default
title: Network
nav_order: 70
parent: Modules
---

# Network

The [system firewall]({{site.baseurl}}/core/firewall) has two active
zones:

* `public` -- every network interface is added to it; limited TCP/UDP
  ports are allowed from the public zone.
* `trusted` -- cluster VPN network; any connection is allowed from the
  trusted zone.

As a general rule, any module which doesn't require a well-known port,
should request a random port using `org.nethserver.tcp-ports-demand`
and `org.nethserver.udp-ports-demand` labels.

The following example creates a private network namespace and starts a TCP
proxy to connect port 8080 inside the container from `${TCP_PORT}` or `${UDP_PORT}`:

    /usr/bin/podman run ... --publish ${TCP_PORT}:8080 ...

Web applications are usually configured as backends for the local Traefik
HTTP proxy. They can bind only the loopback IP address:

    /usr/bin/podman run ... --publish 127.0.0.1:${TCP_PORT}:8080 ...

The next example does not use any TCP proxy and is more performant. It
requires to configure the listening service in the container to use
directly TCP port `${TCP_PORT}`. The container shares the network
namespace with host machine:

    /usr/bin/podman run ... --network=host ...

Modules using a well-known port, can bind any IP address for that port.
For instance:

    /usr/bin/podman run ... --publish 25:25

Such modules must be properly authorized to open the well-known port in
the system firewall. See [system
firewall]({{site.baseurl}}/core/firewall#configuration) for details.
</file>

<file path="docs/modules/new_module.md">
---
layout: default
title: New module tutorial
nav_order: 120
parent: Modules
---

# How to create a rootless module

This document will guide you, a developer, on how to create a new rootless module.
The module will be a simple NethServer package containing an HTTP echo server.

Before moving further, please take a look to [how NethServer is designed]({{site.baseurl}}/design).
See also [core]({{site.baseurl}}/core) and [modules]({{site.baseurl}}/modules).

* TOC
{:toc}

## Step 0: requirements

This tutorial will use some GitHub features to simplify the module setup
process. While you do not strictly need a GitHub account to develop a
module, you will need one if you want to follow this guide step-by-step.

Before proceeding, please [log in to GitHub](https://github.com/login) or
[create a new account](https://github.com/signup).

On your machine you will also need [GIT](https://git-scm.com/) and a text editor.

## Step 1: clone the kickstart repository

To develop a new module access the [ns8-kickstart](https://github.com/NethServer/ns8-kickstart) GitHub
repository and click on [`Use this template`](https://github.com/NethServer/ns8-kickstart/generate) to
generate a new repository.

1. Name your repo with `ns8-` prefix (e.g. `ns8-mymodule`). 
   Do not end your module name with a number, like ~~`ns8-baaad2`~~!

1. Clone the repository and follow the instructions inside the README

## Step 2: edit the code

It's now time to modify the code and implement your module.

Start easy and just edit the `README.md` file, by replacing this section with your module
description.

If you just want to see your package built and published go to [Step 3](#step-3-commit-and-push).
Otherwise, read about the module structure [below](#module-structure).

### Module structure

Each module is distributed using a container image.

A module is usually composed by the following main parts:
- `imageroot` directory, contains all scripts to configure the module
- `ui` directory, contains all user interface files
- `build-images.sh`, a script to manually build one or more images of the module and eventually push them inside the image registry
- `README.md` describes module implementation and usage

The module is something like an RPM or DEB file: it contains the configuration of the application that will run inside NS8.
During the installation process the system will download the real application (eg. Wordpress, Samba) and configure it
using the [actions]({{site.baseurl}}/modules/agent/) from the module.

#### imageroot

The `imageroot` directory will be extracted to the system during the module install.
It contains 2 main paths:

- `actions` contains all actions for the module agent, the directory will be copied to `/home/mymodule1/.config/actions/`
- `systemd/user/` contains all systemd `.service` files, the directory will be copied to `/home/mymodule1/.config/systemd/user/`

Usually, a module contains also a `configure-module` action to gather user input and configure the module accordingly.
The `configure-module` action should:

- validate user input
- set environment variables and eventually expand the configuration
- enable and start the systemd unit(s)
- setup Traefik proxy routes, if needed

Make sure that all parameters used by `configure-module` are saved inside the environment.
Such parameters could than be retrieved by a `get-configuration` action, used to display the configuration inside the UI.

#### build-images.sh

The script creates an empty container image and publish it to the registry on user request.

The main parts to look for are:
- `repobase`: the URL of the remote image registry
- `reponame`: the name of the module
- [labels]({{site.baseurl}}/modules/images/#image-labels) for basic module setup

#### User Interface

No matter on which node the module will run, the web user interface will be automatically imported inside the leader node
and it will be available from the admin URL `https://your.server.fqdn/cluster-admin`.

See how to [setup and develop the UI]({{site.baseurl}}/ui/modules#modules-user-interface).

Also make sure to edit [`imageroot/ui/public/metadata.json`]({{site.baseurl}}/modules/metadata) and replace the logo at `imageroot/ui/src/assets/module_default_logo.png`.

## Step 3: commit and push

Commit your local changes, than push it to GitHub repository.

After the push, GitHub will build the module as a container image and publish it to GitHub registry.
The module will be available under your namespace like `https://github.com/myuser/ns8-mymodule/pkgs/container/mymodule`.
Published image will contain the name of the branch, or tag, as version like `mymodule:main`, `mymodule:1.0.0`.
The `latest` version will always point to the latest build from the main branch, like `mymodule:latest`.

Another workflow will also build the API documentation from JSON schema and publish the result inside the `apidoc-mybranch`
branch where `mybranch` is the current pushed git branch or tag. Default is `apidoc-main`.

You're ready to [install the module](#step-4-try-the-module), unless you want to know more about [how to manually build and publish](#manual-builds)
your module image.

### Manual builds

You can build your modules locally using any distribution which supports `podman` and `buildah`.
To build the image, just execute `bash build-images.sh` script.

Before pushing images to the registry, you must configure the authentication.
Create a [GitHub Personal Access Token (PAT)](https://docs.github.com/en/github/authenticating-to-github/creating-a-personal-access-token)
for the **ghcr.io** registry (for read-only access `read:packages private` scope should be enough) then run the following command, specifying
your GitHub user name and providing the generated PAT as password:
```
buildah login ghcr.io
```

The `build-images.sh` script will output the command to push the images to
the registry. Example:
```
buildah push ghcr.io/myuser/mymodule docker://ghcr.io/myuser/mymodule:latest
```

If the package should be available inside the [NethServer software repository](#step-5-publish-to-ns8-software-repository), make sure to specify a valid [semantic version](https://semver.org/) as tag.

## Step 4: try the module

If you didn't it already, it's now time to [install NS8]({{site.baseurl}}/quickstart).

You are going an SSH connection to the cluster leader to follow below steps.

First, we have to tell the cluster leader to instantiate a new module. The node agent will
create a new Unix user that runs the rootless module and schedule the `create-module`
action to start soon.

Just install the module straight from the image registry, without using NethServer package repository:
```
add-module ghcr.io/myuser/mymodule:latest 1
```

In case of error, see `journalctl`.

You can now access the module configuration at `https://your.server.fqdn/cluster-admin` or navigate directly
to the application at `https://your.server.fqdn/mymodule`.

Repeat steps from 2 to 4 until you're module is ready for prime time!

## Step 5: publish to an NS8 software repository

This step is optional. First, ensure the image is properly tagged in your
container image registry. The tag must adhere to our [Semver syntax
subset](../../development_process#module-version-numbering-rules).

- Refer to [Software repositories](../../core/software_repositories/) to
  understand how an application is listed in the NS8 Software Center and
  how to set up a personal application repository.

- To publish the application in NethForge, refer to the [Certification
  process](../certification).
</file>

<file path="docs/modules/port_allocation.md">
---
layout: default
title: Port allocation
nav_order: 50
parent: Modules
---

# Port allocation

Many web application modules need a TCP or UDP port to run a backend exposed by Traefik.
Such modules can set the `org.nethserver.tcp-ports-demand` and `org.nethserver.udp-ports-demand` which takes an integer number as value.
Example:
```
org.nethserver.tcp-ports-demand=1
org.nethserver.udp-ports-demand=1
```

The randomly-allocated TCP port number will be available inside the `TCP_PORT` environment variable and it will be
available to all step scripts and inside systemd units.
The available environment variables will be:
- `TCP_PORT`, `UDP_PORT`: it is always present and it contains always the first port, i.e. `20001`
- `TCP_PORTS_RANGE`, `UDP_PORTS_RANGE`: only if value is greater than 1, it contains the list of ports in range format,
  i.e `20001-20002`
- `TCP_PORTS`, `UDP_PORTS`: only if value is greater than 1 and less or equal than 8, it contains a comma separated list of
  ports like, i.e. `20001,20002,20003`

Currently, allocated ports are saved in an SQLite database file managed by the local node agent.

## Authorizations

The module requires an additional role to manage port allocation, which is
assigned by setting the `org.nethserver.authorizations` label on the
module image, as shown in the following example:

    org.nethserver.authorizations = node:portsadm

The following additional label values can be used to mix port allocations
with other existing node-related roles:

- `org.nethserver.authorizations = node:fwadm,portsadm`
- `org.nethserver.authorizations = node:tunadm,portsadm`

The module will be granted execution permissions for the following actions
on the local node:
- `allocate-ports`
- `deallocate-ports`

These actions can be carried out using the agent library without making
direct node API calls, as explained in the next section.

## Agent library

The Python `agent` library provides a convenient interface for managing port allocation and deallocation, based on the node actions `allocate_ports` and `deallocate_ports`.

This interface dynamically allocate and deallocate ports based on the
module's needs without requiring direct interaction with the node's APIs.

It is optional to specify the `module_id` when calling the port allocation or deallocation functions. By default, if the `module_id` is not provided, the function will automatically use the value of the `MODULE_ID` environment variable. This simplifies the function calls in common scenarios, ensuring the correct module name is used without manual input. However, if needed, you can still explicitly pass the `module_id`.
Note that only the cluster agent can modify the port allocations of other modules.

### Allocate ports

Imagine an application module that initially requires only one TCP port. Later, a new feature is added, and it needs four TCP ports to handle more connections.

If ports are already allocated for this module, the previous allocation will be deallocated, and the new requested range of ports will be allocated. Here’s how this can be done:

```python
import agent

# Allocate 4 TCP ports for the module that is calling the function
allocated_ports = agent.allocate_ports(4, "tcp")
```
or
```python
import agent

# Allocate 4 UDP ports for "my_module" module
allocated_ports = agent.allocate_ports(4, "udp", "my_module")
```

If you want to preserve the previously allocated ports and add a new range of ports, you can use the `keep_existing` parameter:

```python
import agent

# Allocate 4 more TCP ports for the module that is calling the function
allocated_ports = agent.allocate_ports(4, "tcp", keep_existing=True)
```

### Deallocate ports

If the module no longer needs the allocated ports, such as when a feature is removed or disabled, the ports can be easily deallocated:

```python
import agent

# Deallocate TCP ports for the module that is calling the function
deallocated_port_ranges = agent.deallocate_ports("tcp")
```
or
```python
import agent

# Deallocate UDP ports for the "my_module" module
deallocated_port_ranges = agent.deallocate_ports("udp", "my_module")
```
By deallocating the ports, the module frees up the resources, allowing other modules to use those ports.

For more information about the low-level implementation of port allocation, see [Port allocation](../../core/port_allocation) in the core documentation.
</file>

<file path="docs/modules/rootless_rootfull.md">
---
layout: default
title: Rootless vs Rootfull
nav_order: 20
parent: Modules
---

# Rootless vs Rootfull

In the Podman world, non-privileged users can run containers on their own:
those are the so-called *rootless* containers.  In NethServer 8, we borrow
the same word from Podman and use it in the context of modules, together
with its opposite, *rootfull*.

To inspect a rootless module start Bash with the `runagent` command to
properly initialize the Systemd runtime environment. For instance, to
check if Traefik is running:

    runagent -m traefik1
    # A Bash prompt from traefik1's session appears
    systemctl --user status traefik
    # Systemctl prints its output

If you type the above commands in the same line, `runagent` executes
`systemctl` without forking an interactive Bash shell:

    runagent -m traefik1 systemctl --user status traefik
    # Systemctl prints its output from traefik1's session

Let's see the differences of rootless modules vs rootfull modules.

## Unix user

The main difference between *rootless* and *rootfull* modules, as
suggested by the adjective, is the Unix user running the module processes
and its system privileges.

**Rootfull**: module containers run as `root` (EUID 0).

**Rootless**: module containers run as a normal Unix user. The Unix user account is
created by the node agent when the module instance is added. It has
session lingering enabled: it automatically starts a persistent Systemd
user manager instance at system boot.

To check if a module is rootless or not, in Python write:

```python
import os
if os.geteuid() == 0:
    print('ROOTFULL')
else:
    print('ROOTLESS')
```

Same thing, in Bash:

```bash
if [[ $EUID == 0 ]]; then
    echo ROOTFULL
else
    echo ROOTLESS
fi
```

As alternative print the effective user ID with

    id -u

To protect against system configuration errors, starting with Core 3.20,
Unix users created for rootless modules are assigned the `/sbin/nologin`
shell by default. To upgrade existing modules to the new shell policy, run
a command like this:

```bash
runagent -l | xargs -l -t -r -- usermod -s /sbin/nologin
```

Note that the above command may raise harmless errors for `cluster`,
`node` and other rootfull module names, which have no corresponding Unix
user.

An interactive shell is not required by NS8 rootless modules. However, if
you need to enable `/bin/bash` for any reason (for example, to log in as
the module user and transfer files with `ssh+rsync`), execute:

```bash
usermod -s /bin/bash myapp1
```

If the new default policy is too strict, customize the shell assigned to
new modules by `add-module` action. Run this command on each cluster node:

```bash
runagent -m node python3 -c 'import agent ; agent.set_env("LOGIN_SHELL", "/bin/bash")'
```

The above command sets the custom shell executable path in the node's
`LOGIN_SHELL` agent environment.


## Filesystem paths

The two types of modules have a similar filesystem structure. Rootless
modules are installed to `/home/<module_id>/.config`, whilst rootfull are
installed to `/var/lib/nethserver/<module_id>`.

## Systemd units

Rootless modules also have Systemd user units installed under
`~/.config/systemd/user`. Recall that some system-wide user units are
installed by the core under `/etc/systemd/user`. When running the
`systemctl` command, add the `--user` flag. Eg.

    systemctl --user status traefik

Rootfull modules share the system-wide Systemd directories. Their units
are installed under `/etc/systemd/system`. As they share the same
directory, unit files must be named as `<module_id>` or they must use the
`<module_id>-` prefix to avoid naming clashes with other instances of the
same module. Eg:

    cat /etc/systemd/system/samba1.service
    systemctl start samba1

## Volumes

Rootfull modules share the same Podman volumes namspace. As consequence,
rootfull modules must use the `<module_id>-` prefix for their volume names
to avoid volume naming clashes. Eg.

    samba1-data
    samba1-config

Rootless modules can use any volume name because the Podman volume
namespace is private for the module.

This command prints out the filesystem path where Podman stores volumes
data:

{% raw %}
    podman system info --format='{{.Store.VolumePath}}'
{% endraw %}
</file>

<file path="docs/modules/service_providers.md">
---
layout: default
title: Service providers
nav_order: 100
parent: Modules
---

# Service providers

A module can become the provider of some kind of service for other modules
running in the same cluster. To ease the service discovery, information
about how to reach the service and any other application parameter must be
written in the Redis database as explained in the next sections.

## `srv` keys

A module can own one or more `srv` Redis keys. Each one identifies a
service endpoint on a given transport protocol. For instance

    module/mail1/srv/tcp/imap
    module/mail1/dovecot/srv/http/openmetrics
    module/mail1/rspamd/srv/http/openmetrics

The generic key pattern is

    module/{MODULE_ID}[/{OPTIONAL_QUALIFIER}]/srv/{TRANSPORT}/{SERVICE_NAME}

Each key must be of type HASH. The hash content depends on the service
requirements, typically the `host` and IP `port` entries are set.

## Raising events

The service provider **should raise** one or more distinct events whenever
the information in its `srv` keys is changed. The event name and payload
must be documented by the service provider. A common convention for the
event name is:

    service-{SERVICE_NAME}-changed

The event payload is a JSON-encoded string representing an object. The
object can contain the needed attributes to identify the source of the event.
They are necessary to event listeners to identify the event
source and retrieve further information as needed, an example payload can be:

```json
{
    "key": "module/mail1/srv/tcp/imap",
    "module_uuid": "8d257122-0a7f-49c7-a620-08961a68cfa0",
    "module_id": "mail1"
}
```

# Service discovery

Service consumers can look up a given service name with the
`agent.list_service_providers()` function, or the corresponding
`list-service-providers` base module action.

For instance, to find IMAP servers on node 1:

    api-cli run module/mail1/list-service-providers --data '{"service":"imap", "transport":"tcp", "filter":{"node":"1"}}' | jq

Yields

```json
[
  {
    "port": "143",
    "host": "10.5.4.1",
    "node": "1",
    "user_domain": "dp.nethserver.net",
    "module_uuid": "8d257122-0a7f-49c7-a620-08961a68cfa0",
    "module_id": "mail1",
    "transport": "tcp",
    "ui_name": null
  }
]
```

The input JSON object attributes are:

- `service` (mandatory): look up this service name
- `transport` (optional): look up records with the given transport, or any
  transport if the attribute is missing
- `filter`: an object where each entry represents an additional filter
  condition. Only services matching all the given conditions are returned.
  The actual attributes depend on the record structure: service providers
  must document which attributes they define. The `list-service-providers`
  base implementation in any case, provides at least the following
  attributes for convenience:
    - `module_id` copy of `HGET module/{id}/environment MODULE_ID`
    - `module_uuid` copy of `HGET module/{id}/environment MODULE_UUID`
    - `ui_name`, copy of `GET module/{id}/ui_name`)
    - `transport`, copy of `transport` of the Redis key name
    - `module_seq`, the module sequential number parsed from `module_id`
      (e.g. `mail1` has sequence `1`)
- `sortby` (optional): sorting rule applied to the results. One of:
    - `node_proximity` (default): services on the local node first, then on
      the leader node, then on other worker nodes; `module_seq` is used as
      a stable secondary key
    - `module_seq_asc`: order by increasing module sequence number (e.g.
      `mail1` before `mail2`)
    - `module_seq_desc`: order by decreasing module sequence number

The following Python code snippet invokes `agent.list_service_providers()`
to discover an IMAP server. It connects to the local Redis replica, so it
works even if the leader is temporarly unreachable: this makes the service
startup more robust.

```python
import agent
rdb = agent.redis_connect(use_replica=True) # connect the local Redis replica
print(agent.list_service_providers(rdb, 'imap', 'tcp'))
```

By default, results are sorted by node proximity to the caller (local node
first, leader node second, other worker nodes third). Pass `sortby` to
select a different rule, e.g. to order candidates by module sequence
number:

```python
print(agent.list_service_providers(rdb, 'imap', 'tcp', sortby='module_seq_desc'))
```
</file>

<file path="docs/modules/systemd_units.md">
---
layout: default
title: Systemd units
nav_order: 60
parent: Modules
---

# Systemd units

A module should have at least one Systemd unit to keep the service running.
The Systemd unit should:
- enable the service on boot
- start and stop podman processes
- ensure restart at least on failure

The Systemd unit can:
- change the working directory to ease finding additional files: `WorkingDirectory=%S/state`
- execute ancillary commands in `Exec*` steps with the `runagent` helper: `ExecStartPre=/usr/local/bin/runagent expand-templates`
- import and use additional environment variables: `EnvironmentFile=%S/state/environment`

When `EnvironmentFile=%S/state/environment` is used in Systemd service
units, remember that the file syntax is not designed to be compatible with
Systemd. Values are stored as raw values, i.e. special characters are not
escaped or quoted:

1. Limit the use of this technique to variables with controlled values, e.g. `IMAGE_URL`.
2. Avoid storing and reading arbitrary strings, like randomly generated
   tokens, and values coming from the user's input.

See [Dokuwiki
unit](https://github.com/NethServer/ns8-dokuwiki/blob/main/imageroot/systemd/user/dokuwiki.service)
as an example.
</file>

<file path="docs/modules/testing.md">
---
layout: default
title: Testing
nav_order: 110
parent: Modules
---

# Testing

NS8 modules use [Robot Framework](https://robotframework.org/) for integration
testing. Tests live in the `tests/` directory of each module repository and run
against a live NS8 cluster. The standard tooling is provided by the
[ns8-github-actions](https://github.com/NethServer/ns8-github-actions) repository,
which includes reusable CI/CD workflows and the `run-ns8-tests` script described
below.

The `run-ns8-tests` script runs any NS8 module's `tests/` directory with
Robot Framework inside a Podman container, directly from your workstation
against a live NS8 cluster. The venv is cached in a named volume so repeated
runs are fast.

* TOC
{:toc}

## Requirements

- [Podman](https://podman.io/) available in `PATH`
- An SSH private key with access to the target NS8 leader node

## Installation

Download the script, make it executable, and place it in your `PATH`:

```bash
curl -o /tmp/run-ns8-tests \
  https://raw.githubusercontent.com/NethServer/ns8-github-actions/refs/heads/v1/scripts/test-module.sh
install -m 0755 -Z /tmp/run-ns8-tests ~/.local/bin
```

## Usage

Enter the NS8 module directory and run the script:

```bash
cd /path/to/ns8-<module>
run-ns8-tests <LEADER_NODE> <IMAGE_URL> [robot options...]
```

| Argument | Description |
|---|---|
| `LEADER_NODE` | Hostname or IP of the NS8 leader node |
| `IMAGE_URL` | Container image URL for the module under test |
| `[robot options...]` | Any extra arguments forwarded to the `robot` command |

## Environment variables

| Variable | Default | Description |
|---|---|---|
| `SSH_KEYFILE` | `~/.ssh/id_ecdsa` | Path to the SSH private key |
| `RUN_UI_TESTS` | _(unset)_ | Set to `true` to enable UI/browser tests |

## Examples

Basic run:

```bash
cd ~/git/ns8-mail
run-ns8-tests rl1.leader.cluster0.test.org ghcr.io/nethserver/mail:bug-6977
```

Using a custom SSH key:

```bash
cd ~/git/ns8-mail
SSH_KEYFILE=~/.ssh/id_ecdsa run-ns8-tests rl1.leader.cluster0.test.org ghcr.io/nethserver/mail:bug-6977
```

With UI tests enabled:

```bash
cd ~/git/ns8-nextcloud
RUN_UI_TESTS=true run-ns8-tests rl1.leader.cluster0.test.org ghcr.io/nethserver/nextcloud:latest
```

With UI tests and a custom SSH key:

```bash
cd ~/git/ns8-nextcloud
SSH_KEYFILE=~/.ssh/id_ecdsa RUN_UI_TESTS=true run-ns8-tests rl1.leader.cluster0.test.org ghcr.io/nethserver/nextcloud:latest
```

Passing extra Robot Framework options (e.g. run a single test suite):

```bash
cd ~/git/ns8-mail
run-ns8-tests rl1.leader.cluster0.test.org ghcr.io/nethserver/mail:latest --suite "Sending mail"
```

Run only tests with a specific tag:

```bash
cd ~/git/ns8-mail
run-ns8-tests rl1.leader.cluster0.test.org ghcr.io/nethserver/mail:latest --include smoke
```

Run a single test by name:

```bash
cd ~/git/ns8-mail
run-ns8-tests rl1.leader.cluster0.test.org ghcr.io/nethserver/mail:latest --test "Send an email"
```

## How it works

- When `RUN_UI_TESTS=true`, the script uses the [Microsoft Playwright](https://playwright.dev/)
  container image and the `robotframework-browser` library.
- Otherwise, a lightweight `python:3.11-alpine` image is used.
- The Python venv is stored in a named volume (`rftest-cache` or `rftest-cache-ui`).
  It is invalidated automatically when the requirements file checksum changes.
- Robot Framework variables passed to all tests:
  - `NODE_ADDR` — the leader node address
  - `IMAGE_URL` — the module image URL
  - `SSH_KEYFILE` — path to the SSH key inside the container (`/tmp/idssh`)
  - `RUN_UI_TESTS` — whether UI tests are active
- Tests tagged `unstable` are skipped on failure (`--skiponfailure unstable`).
- UI tests must be tagged `ui`; they are excluded automatically when
  `RUN_UI_TESTS` is not `true`.
</file>

<file path="docs/modules/updates.md">
---
layout: default
title: Updates
nav_order: 82
parent: Modules
---

## Module updates

The core action `update-module` is the entry point of a module instance
update. It can run the update on multiple instances of the same module at
the same time.

The core then invokes the module `update-module` action. Each module
instance is responsible for updating itself. The core already provides an
extendable implementation of the `update-module` action for the module
agent. The base implementation

- pulls the module image and additional service images
- extracts and installs the module _imageroot_ under the `${AGENT_INSTALL_DIR}`
- runs `systemctl --user daemon-reload`, to refresh Systemd with new unit definitions
- updates the environment variables, keeping track of `PREV_*` values
- runs update scripts installed with the new image, under
  `${AGENT_INSTALL_DIR}/update-module.d/`
- removes stale container images

Modules can provide update scripts to handle upgrade paths like restarting
services and database schema migrations. Executable scripts can be placed
inside `imageroot/update-module.d` which will be then extracted to
`${AGENT_INSTALL_DIR}/update-module.d`. Scripts execution occurs in
alphabetical order. If a script aborts with an exit code, a warning is
printed. Example of a script that restarts a Systemd service,
`imageroot/update-module.d/20restart`:

    #!/bin/bash
    systemctl --user try-restart mymodule.service

Make sure the `20restart` is executable, otherwise it is ignored.

Update scripts and module backups are mutually exclusive. If a backup of
the module instance is running, the update waits for its completion. If
the backup is still running after one hour, the update is aborted
before any change, and can be retried later. A backup scheduled while
the scripts are running is retried later.

Custom steps added to the module `update-module` action do not take part
in this mutual exclusion and can run while a backup is in progress: put
any service restart or data migration in `update-module.d` scripts
instead.

To update an instance from command line, use:

    update-module ghcr.io/nethserver/mymodule:1.0.0 mymodule1

Multiple instances of the same module can be updated together:

    update-module ghcr.io/nethserver/mymodule:1.0.0 mymodule1 mymodule2

If the given `module_url` is already present in the local Podman storage,
no remote download occurs and the local image is used instead. During
development this might be unwanted and to work around this behavior
pass `--force`:

    update-module ghcr.io/nethserver/mymodule:1.0.0 mymodule1 --force

The `update-module` command refuses to update an instance with an image of
a different module (e.g. updating `nextcloud1` with a `mattermost` image),
even with `--force`. This check is enforced by the CLI only: it can be
bypassed by invoking the `cluster/update-module` action directly, e.g. via
`api-cli` (see below).

The same action can also be invoked directly with `api-cli`, e.g. to script
around it:

    api-cli run update-module --data '{"module_url":"ghcr.io/nethserver/mymodule:1.0.0","instances":["mymodule1"],"force":true}'
</file>

<file path="docs/modules/volumes.md">
---
layout: default
title: Volumes
nav_order: 30
parent: Modules
---

# Volumes

To enable data persistence and to obtain better performance, application
data must reside in Podman volumes. A volume, passed via `podman run
--volume` parameter can be of these types:

- Local directory, bind-mounted into the container filesystem.
- Single local file, copied into the container filesystem when podman run
  is invoked.
- Podman named volume.

The following example shows how multiple volumes can be defined for a
service in the Systemd `dovecot.service` unit:

```text
[Service]
...
ExecStart=/usr/bin/podman run \
    ...
    --volume=dovecot-data:/var/lib/vmail \
    --volume=./tls-certs:/etc/ssl/dovecot:z \
    --volume=dovecot-dict:/var/lib/dovecot/dict:z \
    --volume=dovecot-lmtp:/var/lib/umail:z \
    --volume=dovecot-custom:/etc/dovecot/local.conf.d:z \
    ${MAIL_DOVECOT_IMAGE}
```

The above `podman run` arguments define:

* Four named volumes: `dovecot-data`, `dovecot-dict`, `dovecot-lmtp`, and
  `dovecot-custom`. Named volumes are typically used to store application
  data persistently. In some cases, they are shared between containers—for
  example, to enable communication through a Unix-domain socket.

* One bind-mounted directory: `./tls-certs`. This directory, located under
  the current working directory when `podman run` is invoked, is
  bind-mounted to the container’s `/etc/ssl/dovecot`. This approach is
  often used to pass configuration files—or TLS certificates, in this
  case—to the container. A third option, single-file volumes, is described
  in the Podman documentation.

Note the `:z` flag, present in some volume definitions: it configures the
SELinux volume label in "shared" mode (type `container_file_t`), which is
the recommended choice for rootless containers. Since the label is
recursively checked when the container is started, the volume
`dovecot-data` that may contain many files is exempted to avoid long
startup times. If you copy files from external sources into a volume,
ensure the label type is `container_file_t` to avoid file access errors.
Refer to `podman run` man page for differences between volume flags.

Inspect Podman named volumes with:

    podman volume ls

## Suggest volume assignment to additional disks

When an application is created in NS8, or when a service is started for
the first time, named volumes are created under a Podman predefined
directory. You can check its path with:

    {% raw %}podman system info --format='{{.Store.VolumePath}}'{% endraw %}

The path depends on whether the command is executed by root (for rootful
modules) or by a normal user (for rootless modules).

The default path resides under the root filesystem. It is possible to mark
one or more application volumes to be presented for optional assignment to
additional disks, present in the NS8 installation node.

The `org.nethserver.volumes` [image label](../images/#image-labels) is managed by the
application developer. Define this application label like:

     org.nethserver.volumes = dovecot-data

When the Mail application is installed in a NS8 cluster, this label
triggers an UI modal window asking the Sysadmin where to store its data,
provided the destination node has an additional disk already configured.
If not, the volume is created in the default disk.

The label value syntax is a list of words separated by spaces. Each word
must correspond to a named volume. List only the volumes you consider
suitable for additional disks. 

Assume that additional disks are **slower than the root disk**, but have
**bigger size**.

## Configure volume assignments for a node

The system administrator can configure a NS8 node to assign specific
application volumes to custom base directories. These assignments are
stored in `/etc/nethserver/volumes.conf` and evaluated during module
creation.

Assignments defined in `volumes.conf` can extend beyond the volume names
declared by the app developer with the `org.nethserver.volumes` image
label explained in the previous section. However, settings collected from
the UI take precedence over those in `volumes.conf`.

The `volumes.conf` file uses a Windows-INI–like format, where section names
correspond to applications and key-value pairs define named volume
assignments with their system mount points. It can be edited manually with
a text editor or managed through the `volumectl` command.

This is a brief list of `volumectl` invocations for different scenarios.

1. List available base directories (filesystem mountpoints). For each
   directory the mounted disk label, size and used space are printed.

       # volumectl list-base-paths
       /srv/disk00 (MYDISK) size=2.0G used=46.6M

2. Assign base path for `dovecot-data` volume of `mail` applications.

       # volumectl add-volume dovecot-data --target /mnt/disk00 --for mail
       Added volume target for [mail]: dovecot-data → /mnt/disk00

3. Similar to the previous example, but limits the assignment only to the
   next Nextcloud installation.

       # volumectl add-volume nextcloud-app-data --target /mnt/disk01 --for nextcloud --next-only
       Added volume target for [nextcloud4]: nextcloud-app-data → /mnt/disk01
       # volumectl add-volume nextcloud-app-data --target /mnt/disk00 --for nextcloud
       Added volume target for [nextcloud]: nextcloud-app-data → /mnt/disk00

4. Remove an existing volume assignment.

       # volumectl remove-volume nextcloud-app-data --for nextcloud
       (command has no output on success)

Look at `/etc/nethserver/volumes.conf` to check the current settings:

       cat /etc/nethserver/volumes.conf

Output example:

```text
[mail]
dovecot-data = /mnt/disk00

[nextcloud4]
nextcloud-app-data = /mnt/disk01

[nextcloud]
nextcloud-app-data = /mnt/disk00
```

This configuration file example shows how specific volume targets apply to
different applications. It will store `nextcloud-app-data` data
volume of `nextcloud4` application under `/mnt/disk01`, whilst data of
other Nextcloud applications will reside under `/mnt/disk00`.

## Move a volume of an installed application

Assignments in `volumes.conf` are evaluated only when a volume is
created. To move the data of an existing volume to another disk, use
`volumectl move-volume`. It works only with rootless applications.

The move has two steps, to keep the application downtime short:

1. Sync. Copy the volume data to the target base path, while the
   application is running. The first copy can take a long time: run it
   as many times as needed, each run copies only the changes since the
   previous one.

       # volumectl move-volume dovecot-data --for mail1 --target /mnt/disk00 --sync

2. Finalize. Stop the application, copy the last changes, recreate the
   volume at the new location and start the application again. Run it
   right after a sync, so the last copy is short.

       # volumectl move-volume dovecot-data --for mail1 --target /mnt/disk00

The target is one of the base paths printed by `volumectl
list-base-paths`, or the mountpoint of the default disk (for example
`/`) to move the volume back to it. Data is copied preserving numeric
ownership, permissions, ACLs, extended attributes (including SELinux
labels), hard links and sparse files. Both steps check the target has
enough free space.

During the finalize step the whole user session of the application is
stopped: all its services, timers and its agent. If the agent is running
a task, the command refuses to stop it. Retry later, or add `--force` to
stop the agent anyway: the running task is interrupted and never
returns a result to its caller.

If finalize fails, or it is interrupted with Ctrl-C, the original volume
is restored and the application is started again. When finalize
completes, the old data is removed in background by a transient Systemd
unit, `volumectl-trash-*`. Its name is printed by the command, to check
its progress with `journalctl -u`.

Until finalize runs, the original volume is untouched. To cancel a move,
remove the copied data from the target base path, for example:

    rm -rf /mnt/disk00/mail1/dovecot-data

When the target is the default disk, the copy is under the application
home directory, for example `/home/mail1/.local/share/volumectl-staging/dovecot-data`.
</file>

<file path="docs/ui/core.md">
---
layout: default
title: Core UI
nav_order: 2
parent: User Interface
---

# Core User Interface

* TOC
{:toc}

## Components

Core UI includes the following components:

- Login page
- Shell
  - Side menu
  - Top header
  - Global search
  - Notification drawer
  - App launcher
- Cluster status page
- Software center
- Cluster logs (auditing)
- Cluster settings

Source code of core UI is provided [here](https://github.com/NethServer/ns8-core/tree/main/core/ui).

The reusable components of the [UI library](../library) can be explored and tested in its [Storybook](https://nethserver.github.io/ns8-ui-lib/).

Application routing is implemented with [Vue Router](https://router.vuejs.org/). See `core/ui/src/router/index.js`

Core UI uses [Vuex](https://vuex.vuejs.org/) to handle the global state of the application. See `core/ui/src/store/index.js`.

Source code of core UI is provided here: [https://github.com/NethServer/ns8-core/tree/main/core/ui](https://github.com/NethServer/ns8-core/tree/main/core/ui)

## Shortcuts

The core and the applications can add quickly accessible actions called shortcuts.
Shortcuts will be available from the search bar inside the UI.
Examples of shortcuts could be something like "Add a user" or "Show application X logs".

Shortcuts are described inside a `shortcuts.json` file which must be inside the `ui` path:

- core: `/var/lib/nethserver/cluster/ui/shortcuts.json`
- applications: `/var/lib/nethserver/cluster/ui/apps/<app>/shortcuts.json`

A `shorcuts.json` must always contain the following fields:

- `name`: the action name
- `description`: a text which describes the action
- `tags`: a list of tags to ease the research
- `path`: the UI path to open when the shortcut has been selected. The path **must** be relative.

The `list-shortcuts` API will read all `shortcuts.json` files and combine them on a single array and it will generate absolute UI paths.

## Tasks and notifications

Core and modules can submit tasks to the cluster, to a node or to a module.
NS8 provides automatic toast notifications for task creation, progress, completion and abortion; task events are sent from API server to UI through web-socket.
Validation errors can be intercepted as well, in order to highlight invalid input fields or do something after validation is successful (e.g. close a modal).

To execute a task silently and prevent automatic notifications on task events, set the following attribute in task object:

```
extra.isNotificationHidden: true
```

Tasks that only read data should always be silent.

## Error notifications

Errors are notified to the user using inline notifications (`NsInlineNotification` component) or toast notifications (`NsToastNotification` component). Use inline notifications whenever possible, showing the error message in the exact place of the UI where the error occurred. Use toast notifications when there is no proper place to display the error (e.g. background or long running tasks).

## Query string parameters

You can sync the state of some components inside page URL. This is useful in the following cases:

- You share the URL you are visiting with someone (they will see the same UI state)
- You want to link to a specific point and state of the web app, so that you can browse to a page and prefill some input fields, or open a modal automatically. Global shortcuts rely on this feature

Do not use query parameters for data that is not under user control, e.g. data retrieved by the backend.

Modules must use query parameters for their internal navigation, using view data `q.page`.

## Core UI development

Follow the steps below to prepare the development environment for coding NS8 core UI:

- Install NethServer 8 on a development machine
- Create a copy of `core/ui/public/config/config.development.js.sample` and rename your copy to `config.development.js`:
- Edit `config.development.js` by configuring `API_ENDPOINT` and `WS_ENDPOINT` with the IP address of your NethServer 8 leader node
- Disable CORS check. Connect to the leader node and execute:

```
echo GIN_MODE=debug >> /etc/nethserver/api-server.env; systemctl restart api-server
```

You can develop NS8 UI inside a container (recommended) or on your workstation. 
The first time, you have to accept the self signed certificate of the server in a new tab 
of your browser: `https://<IP_address>/cluster-admin/api/login`

### Develop NS8 UI inside a container

You have two options:

- Build and start a Podman container, or
- Use VS Code Dev Containers

#### Build and start a Podman container

Build the container defined by `Containerfile`:

```
cd core/ui

podman build -t ns8-core-dev .
```

Start development server (`--network=host` is required for hot-reload):

```
podman run -ti -v $(pwd):/app:Z --network=host --name ns8-core --replace ns8-core-dev serve
```

Compiles and minifies for production:

```
podman run -ti -v $(pwd):/app:Z --name ns8-core --replace ns8-core-dev build
```

Remember to [prepare your development environment](#core-ui-development) before start coding.

#### Use VS Code Dev Containers

- Install Visual Studio Code extension [Dev Containers](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers) (beware: this procedure may not work on [VSCodium](https://vscodium.com/))
- Dev Containers uses Docker by default but you can configure it to use Podman: go to `File > Preferences > Settings`, search `dev containers docker path` and type `podman` as `Docker path`
- Open `ns8-core` directory (the repository root) in VS Code, if you haven't already
- Open Command Palette (`CTRL+SHIFT+P`) and type `Reopen in Container`
- Open VS Code integrated terminal: `View > Terminal`
- Change directory to `core/ui`
- Enter one of the following commands:
  - `yarn install`: project setup, needed only the first time
  - `yarn serve`: start development server with hot-reload
  - `yarn build`: compiles and minifies for production

Container configuration is contained inside `.devcontainer/devcontainer.json`.

Remember to [prepare your development environment](#core-ui-development) before start coding.

### Develop NS8 UI on your workstation

Developing NS8 UI inside a container is the recommended way, but if you want to do it on your workstation:

- Install development tools:
  - Node.js and npm
  - Yarn
- Run a web server on your workstation (hot reloading enabled):
  - `cd core/ui`
  - `yarn install`: project setup, needed only the first time
  - `yarn serve`: start development server with hot-reload
  - `yarn build`: compiles and minifies for production

Remember to [prepare your development environment](#core-ui-development) before start coding.
</file>

<file path="docs/ui/index.md">
---
layout: default
title: User Interface
nav_order: 6
has_children: true
---

# User Interface

NS8 user interface is a web application developed with [VueJs](https://vuejs.org/) and based on [Carbon Design System](https://www.carbondesignsystem.com/).

NS8 UI can be accessed at `https://leader_node/cluster-admin/`. Default username is `admin` and default password is `Nethesis,1234`.

The web application source is composed by multiple VueJs projects:
- Core UI
- A distinct UI project for every module (e.g. Dokuwiki)
- A UI library that includes a set of reusable UI components and functions (VueJs mixins) used by core and modules UI

Source code of core UI is provided here: [https://github.com/NethServer/ns8-core/tree/main/core/ui](https://github.com/NethServer/ns8-core/tree/main/core/ui)

## UI design

[Carbon grid system](https://www.carbondesignsystem.com/guidelines/2x-grid/implementation/) promotes responsive design. A simple way to develop a responsive layout is to organize content by placing [tiles](https://www.carbondesignsystem.com/components/tile/usage) inside grid columns, using:

- Carbon `CvTile` component
- UI library `NsTile`
- UI library `Ns*Card` components (e.g. `NsInfoCard`, `NsStatusCard`, ...)
</file>

<file path="docs/ui/library.md">
---
layout: default
title: UI library
nav_order: 3
parent: User Interface
---

# UI library

Since core and modules UI share multiple components and features, these facilities have been aggregated into NPM package [@nethserver/ns8-ui-lib](https://www.npmjs.com/package/@nethserver/ns8-ui-lib).
The reusable UI components included in the library are easily recognizable since their name starts with `Ns` prefix, e.g. `NsButton`, `NsInlineNotification`.
The library also includes a set of VueJs mixins used by core and modules to access utility functions and perform common tasks.

Source code of UI library is provided [here](https://github.com/NethServer/ns8-ui-lib).

The library components can be explored and tested in the [UI library Storybook](https://nethserver.github.io/ns8-ui-lib/), published for each library release.

## UI library development

You can develop NS8 UI library inside a container (recommended) or on your workstation.

### Develop NS8 UI library inside a container

You have two options:

- [Build and start a Podman container](#build-and-start-a-podman-container), or
- [Use VS Code Dev Containers](#use-vs-code-dev-containers)

#### Build and start a Podman container

Run the following commands from the `ns8-ui-lib` directory (the repository root), using the official Node.js container image.

Project setup:

```
podman run -ti -v $(pwd):/app:Z -w /app -e NODE_OPTIONS=--openssl-legacy-provider --name ns8-ui-lib --replace docker.io/library/node:lts npm install
```

Compile and minify for production:

```
podman run -ti -v $(pwd):/app:Z -w /app -e NODE_OPTIONS=--openssl-legacy-provider --name ns8-ui-lib --replace docker.io/library/node:lts npm run build
```

Create a tarball:
```
podman run -ti -v $(pwd):/app:Z -w /app -e NODE_OPTIONS=--openssl-legacy-provider --name ns8-ui-lib --replace docker.io/library/node:lts npm run build-pack
```

Start Storybook (`--network=host` is required for hot-reload), then open http://localhost:6006:

```
podman run -ti -v $(pwd):/app:Z -w /app -e NODE_OPTIONS=--openssl-legacy-provider --network=host --name ns8-ui-lib --replace docker.io/library/node:lts npm run storybook
```

Start the playground, a local app to quickly test components (`--network=host` is required for hot-reload), then open http://localhost:8080:

```
podman run -ti -v $(pwd):/app:Z -w /app -e NODE_OPTIONS=--openssl-legacy-provider --network=host --name ns8-ui-lib --replace docker.io/library/node:lts npm run playground
```

Edit `playground/App.vue` for your tests, but do not commit your changes.
Tarball generation is useful for testing a development or testing version of NS8 UI library. To import the generated tarball into another Node project (e.g. `ns8-core` or a NS8 module), see [Import development or testing version](#import-development-or-testing-version).

#### Use VS Code Dev Containers

- Install Visual Studio Code extension [Dev Containers](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers) (beware: this procedure may not work on [VSCodium](https://vscodium.com/))
- Dev Containers uses Docker by default but you can configure it to use Podman: go to `File > Preferences > Settings`, search `dev containers docker path` and type `podman` as `Docker path`
- Open `ns8-ui-lib` directory (the repository root) in VS Code, if you haven't already
- Open Command Palette (`CTRL+SHIFT+P`) and type `Reopen in Container`
- Open VS Code integrated terminal: `View > Terminal`
- Enter one of the following commands:
  - `npm install`: project setup, needed only the first time
  - `npm run build`: compile and minify for production
  - `npm run build-pack`: create a tarball
  - `NODE_OPTIONS=--openssl-legacy-provider npm run storybook`: start Storybook with hot-reload
  - `NODE_OPTIONS=--openssl-legacy-provider npm run playground`: start the playground with hot-reload (edit `playground/App.vue` for your tests, but do not commit your changes)

Tarball generation is useful for testing a development or pre-release version of ns8-ui-lib. To import the generated tarball into another Node project (e.g. `ns8-core` or a NS8 module), see [Import development or testing version](#import-development-or-testing-version).

Dev container configuration is contained inside `.devcontainer/devcontainer.json`.

### Develop NS8 UI library on your workstation

Developing NS8 UI library inside a container is the recommended way, but if you want to do it on your workstation:

- Install Node.js and npm
- `npm install`: project setup, needed only the first time
- `npm run build`: compile and minify for production
- `npm run build-pack`: create a tarball
- `NODE_OPTIONS=--openssl-legacy-provider npm run storybook`: start Storybook with hot-reload
- `NODE_OPTIONS=--openssl-legacy-provider npm run playground`: start the playground with hot-reload (edit `playground/App.vue` for your tests, but do not commit your changes)

Tarball generation is useful for testing a development or pre-release version of ns8-ui-lib. To import the generated tarball into another Node project (e.g. `ns8-core` or a NS8 module), see [Import development or testing version](#import-development-or-testing-version).

## Release a new version

Releasing a new version of `ns8-ui-lib` involves publishing a new NPM package version, creating a GitHub tag and generating a GitHub release. Note that the release command should be executed on your workstation, as your public SSH key is required to push the new tag to GitHub.

Run one of the following commands, depending on the type of version bump. The command will trigger a GitHub action named "Publish to NPM and create release", which will handle the actual release of the new version.

Release a patch version:

```
npm run publish:patch
```

Release a minor version:

```
npm run publish:minor
```

Release a major version:

```
npm run publish:major
```

## Import NS8 UI library components

### Import latest version

To import the latest version of NS8 UI library:

```
yarn add @nethserver/ns8-ui-lib
```

### Import development or testing version

To import a development or testing version of `ns8-ui-lib` from a tarball (generated with `npm run build-pack`) into another Node project (e.g. `ns8-core` or a NS8 module):

```
cd other/node/project
yarn add /path/to/ns8-ui-lib/nethserver-ns8-ui-lib-x.y.z.tgz
```

### Import library components and mixins

To globally include NS8 components, edit `main.js` of the project importing the library:

```js
// main.js

import ns8Lib from "@nethserver/ns8-ui-lib";
Vue.use(ns8Lib);
```

To import a specific mixin inside a component (e.g. `TaskService` mixin) of the project importing the library:

```js
// ComponentName.vue

import { TaskService } from "@nethserver/ns8-ui-lib";

export default {
  name: "ComponentName",
  mixins: [TaskService],
  ...
}
```
</file>

<file path="docs/ui/modules.md">
---
layout: default
title: Modules UI
nav_order: 4
parent: User Interface
---

# Modules User Interface

* TOC
{:toc}

## Guidelines

Users can open modules UI from the App drawer or using Global search.

Every NS8 module follows the same UI guidelines in order to provide a uniform user experience. Almost every module has at least these standard pages:

- Status
- Settings
- About

Status page is the landing page of the module, it should provide a dashboard displaying the current status of the module, including instance name, installation node and information about module systemd services.

Settings page should contain a form to set and review module configuration.

About page should provide module meta-information such as documentation URL, source code and author information.

NS8 modules make use of UI library components and functions, e.g. by including the shared `NsButton` component in a module form, or requesting the execution of a cluster task.

The UI of a module lives inside an &lt;iframe&gt; of core UI (see `core/ui/src/views/Applications.vue`). It has a reference to core VueJs instance, named `ns8Core`, used to:

- Events management (e.g. register to task completion)
- Access to core API URL and other core configurations
- Access to core i18n strings

Modules use [Vue Router](https://router.vuejs.org/) to implement page routing and [Vuex](https://vuex.vuejs.org/) to handle global state.

## Module UI development

- Install NethServer 8 on a development machine
- Creating a new NS8 module? Start from [NS8 kickstart](https://github.com/NethServer/ns8-kickstart)
- Install the module on your development machine
- Replace `MODULE` with the actual module name, e.g. `mail1` in the following steps
- You can develop NS8 modules UI inside a container (recommended) or on your workstation.

### Develop NS8 modules UI inside a container

You have two options:

- Build and start a Podman container, or
- Use VS Code Dev Containers

#### Build and start a Podman container

- Build the container defined by `Containerfile`:

```
cd ui

podman build -t ns8-MODULE-dev .
```

- Compile sources and watch for changes:

```
podman run -ti -v $(pwd):/app:Z --name ns8-MODULE --replace ns8-MODULE-dev watch
```

- [Sync module sources to your NS8 development machine](#sync-module-sources-to-ns8-development-machine)

#### Use VS Code Dev Containers

- Install Visual Studio Code extension [Dev Containers](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers) (beware: this procedure may not work on [VSCodium](https://vscodium.com/))
- Dev Containers uses Docker by default but you can configure it to use Podman: go to `File > Preferences > Settings`, search `dev containers docker path` and type `podman` as `Docker path`
- Open `ns8-MODULE` directory (the repository root) in VS Code, if you haven't already
- Open Command Palette (`CTRL+SHIFT+P`) and type `Reopen in Container`
- Open VS Code integrated terminal: `View > Terminal`
- Change directory to `ui`
- Enter the following commands:
  - `yarn install`: project setup, needed only the first time
  - `yarn watch`: compile sources and watch for changes
- [Sync module sources to your NS8 development machine](#sync-module-sources-to-ns8-development-machine)

Container configuration is contained inside `.devcontainer/devcontainer.json`.

### Develop NS8 modules UI on your workstation

Developing NS8 modules UI inside a container is the recommended way, but if you want to do it on your workstation:

- Install Node.js and npm
- Change directory to `ui`
- `NODE_OPTIONS=--openssl-legacy-provider yarn install`: project setup, needed only the first time
- `NODE_OPTIONS=--openssl-legacy-provider yarn watch`: compile sources and watch for changes
- [Sync module sources to your NS8 development machine](#sync-module-sources-to-ns8-development-machine)

### Sync module sources to NS8 development machine

To sync module sources from your workstation to your NS8 development machine:

- Enter the following commands on your workstation (outside any container):

```
cd PATH_TO_MODULE/ui

watch -n 1 rsync -avz --delete dist/* root@YOUR_NS8_MACHINE:/var/lib/nethserver/cluster/ui/apps/MODULE/
```

- Open your browser at `https://YOUR_NS8_MACHINE/cluster-admin/#/apps/MODULE`
- Edit module sources
- Reload browser page to see your changes (disable browser cache if needed)
</file>

<file path="docs/ui/translation.md">
---
layout: default
title: Localization
nav_order: 5
parent: User Interface
---

## Localization

The user interface is translated with [Weblate](https://hosted.weblate.org/projects/ns8/).

Every time a ns8 repository is updated, Github will notify Weblate.
When new translations are avaialable, Weblate will create a new pull request on the target repository.

To setup the translation process:

1. add [GitHub Weblate app](https://docs.weblate.org/en/latest/admin/continuous.html#github-setup) to your repository
2. add your repository to [hosted.weblate.org](https://hosted.weblate.org) or ask a NethServer developer to add it to ns8 Weblate project

You can automate the step 2 by using the following `weblate-add` script.

```bash
set -e
name=$1

curl \
    --fail \
    --data-binary '{
        "branch": "main",
        "file_format": "json-nested",
        "filemask": "ui/public/i18n/*/translation.json",
        "name": "'$name'",
        "slug": "'$name'",
        "repo": "https://github.com/NethServer/ns8-'$name'.git",
        "template": "ui/public/i18n/en/translation.json",
        "new_base": "",
        "vcs": "github",
        "license": "GPL-3.0-or-later"
    }' \
    -H "Content-Type: application/json" \
    -H "Authorization: Token $TOKEN" \
    https://hosted.weblate.org/api/projects/ns8/components/

curl \
    --fail \
    -d '{"language_code": "it"}' \
    -H "Content-Type: application/json" \
    -H "Authorization: Token $TOKEN" \
    https://hosted.weblate.org/api/components/ns8/$name/translations/
```

Usage example, where `TOKEN` is your Weblate token:
```
TOKEN=xxxxxxxxxxxx bash weblate-add nextcloud
```
</file>

<file path="docs/_config.yml">
title: NS8 dev manual
description: NS8 - Developer manual
remote_theme: pmarsceill/just-the-docs
baseurl: /ns8-core
permalink: pretty
exclude: [vendor]
admin_manual: https://docs.nethserver.org/projects/ns8
search_enabled: true
search_tokenizer_separator: /[\s/]+/
heading_anchors: true
aux_links:
  "NS8 on GitHub":
    - "//github.com/nethserver/ns8-core"
  "NethServer developer handbook":
    - "https://handbook.nethserver.org"
footer_content: ""
# Footer "Edit this page on GitHub" link text
gh_edit_link: true
gh_edit_link_text: "Edit this page on GitHub."
gh_edit_repository: "https://github.com/NethServer/ns8-core"
gh_edit_branch: "master"
gh_edit_source: docs
gh_edit_view_mode: "tree"
color_scheme: nil
plugins:
  - jekyll-seo-tag
compress_html:
  clippings: all
  comments: all
  endings: all
  startings: []
  blanklines: false
  profile: false
</file>

<file path="docs/api.md">
---
layout: default
title: API
nav_order: 7
---

## API doc generation

If an action has JSON schema validators, the schema file is converted to
Markdown format and published in the `apidoc` branch. Browse it at

[API doc tree](https://github.com/NethServer/ns8-core/tree/apidoc)

Pull requests are assigned a dedicated branch. If the PR source branch is
`newfeature` the resulting documentation branch is `apidoc-newfeature`.
The branch lives as long as the PR is merged, or closed.
</file>

<file path="docs/build_system.md">
---
layout: default
title: Build system and SBOM
nav_order: 10
---

# Build system

* TOC
{:toc}

## Manual builds

Every module, including the core, can be built locally or automatically using GitHub Actions.
Each repository usually has a file named `build-images.sh` that can be used to build the module images.

When executed on a local machines, it requires the `podman` or `buildah` command line tools installed.
To build the images, execute the `build-images.sh` script.

Once the images are built, they are available on the local machine and can be used for testing.
To list the images, use the `podman images` command.
The images can be pushed to the image registry using the `podman push` command.

The same script is used by the GitHub Actions workflow to build the images and push them to the image registry.
When executed inside the GitHub Actions environment, the script outputs the image names that are
automatically pushed to `ghcr.io` image registry.

## Automatic builds

Every time a commit is pushed to the repository, a new build can
be automatically started.

Each module, including the core, should use the standard GitHub Actions workflow name `publish-branch.yml` available inside the
[ns8-github-actions](https://github.com/NethServer/ns8-github-actions/) repository.

To enable automatic builds, create a YAML file named `publish-images.yaml` inside `.github/workflows/` directory,
like `.github/workflows/publish-image.yaml`.

Copy this content into the file:

```yaml
name: "Publish images"

on:
  push:
  workflow_dispatch:

permissions:
  packages: write

jobs:
  publish-images:
    if: github.run_number > 1
    uses: NethServer/ns8-github-actions/.github/workflows/publish-branch.yml@v1
```

## SBOM generation

A SBOM (Software Bill of Materials) is a complete list of all software parts that make up a product.
See the developer handbook [security](https://handbook.nethserver.org/security/) for more information.

SBOM are part of the build process and must be generated when a new stable version of the core or a module is released.
It can be created using the `scan-with-trivy.yml` action available in the [ns8-github-actions](https://github.com/NethServer/ns8-github-actions/) repository.

The workflow provides flexibility with configurable inputs, enabling targeted
scanning of specific components (`ui`, `imageroot`) or container images. It
supports key actions such as vulnerability detection, updating the GitHub
Dependency Graph, and generating CycloneDX SBOMs, which are uploaded as
artifacts or attached to GitHub releases when applicable.

See the [release process](../development_process#release-process/) page for more information on how to create a release.

**Inputs:**

1. **`images`**: A JSON array representing the list of container
   images to scan.
2. **`scan_module_ui`**: A boolean flag to enable/disable scanning of the module UI
   (default: `true`).
3. **`scan_module_imageroot`**: A boolean flag to enable/disable scanning of
   the module imageroot (default: `true`).
4. **`generate_sbom`**: A boolean flag to enable/disable SBOM generation
   (default: `true`).
5. **`update_dependencies_graph`**: A boolean flag to enable/disable the
   updating of the GitHub Dependency Graph (default: `true`).
6. **`vulnerability_scan`**: A boolean flag to enable/disable vulnerability
   scanning (default: `true`).
7. **`severity`**: A comma-separated string of severity levels to include in
   the scan results (default: `"UNKNOWN,LOW,MEDIUM,HIGH,CRITICAL"`).

**Outputs:**

1. **Vulnerability Scan Results**:
   - Format: SARIF
   - Location: Uploaded to the GitHub Security tab.

2. **SBOM Files**:
   - Format: CycloneDX (JSON), named with the format `module.cdx.json`.
   - Location:
     - Uploaded as artifacts to the workflow run.
     - Optionally attached to GitHub releases if a tag triggers the workflow.

3. **Dependency Graph Updates**:
   - Format: Github Dependency Graph
   - Dependency data is pushed to the GitHub Dependency Graph to provide a view
     of current dependencies.

### Usage

The workflow can be used in two ways for running Trivy security scans. It can
be simply included as a job into the existing "Publish images" workflow, where
it runs after other jobs finish up. Or it can be set up as a separate workflow
that automatically triggers when image publishing is complete. 

Both approaches are effective - the first keeps everything together in one
pipeline, while the second allows for independent management of security
scanning separate from the main build process. 

However, one disadvantage of the second method is that the workflow will always
appear as executed in the GitHub Actions list after the publish workflow, even
when the scan is not actually performed. This can create misleading entries in
the workflow history compared to the integrated approach.

In both methods the job runs if the output from the `module` job indicates that
the release is either `stable` or `latest`, or if the workflow was manually
triggered (`workflow_dispatch`). It passes two parameters to this workflow: the
images to be scanned, which are outputs from the `module` job, and the severity
levels to be reported.

#### Generate SBOM from build `Publish images` workflow (recommended)

Call the `scan-with-trivy.yml` action as a job inside the `Publish images` workflow.

If the `Publish images` workflow is already present in the repository, make sure to:

- update the permissions section to include the necessary write permissions
- add the `module` job to the workflow, data collected from this job is used in the `trivy` job
- add the `trivy` job to the workflow

{% raw %}
```yaml
name: "Publish images"

on:
  push:
  workflow_dispatch:

permissions:
  packages: write
  actions: read
  contents: write
  security-events: write

jobs:
  publish-images:
    if: github.run_number > 1
    uses: NethServer/ns8-github-actions/.github/workflows/publish-branch.yml@v1
  module:
    needs: publish-images
    uses: NethServer/ns8-github-actions/.github/workflows/module-info.yml@v1
  trivy:
    needs: module
    if: ${{ needs.module.outputs.release == 'stable' || needs.module.outputs.release == 'latest' || github.event_name == 'workflow_dispatch' }}
    uses: NethServer/ns8-github-actions/.github/workflows/scan-with-trivy.yml@v1
    with:
      images: ${{ needs.module.outputs.images }}
```
{% endraw %}

Remember to commit and push the changes to the repository.

#### Generate SBOM using a dedicated workflow

Inside the `.github/workflows` directory, create a new YAML file, `analyze-module.yml`.
Copy and paste the YAML configuration into the `analyze-module.yml` file:

{% raw %}
```yaml
name: Analyze module

on:
  workflow_dispatch:
  workflow_run:
    workflows: ["Publish images"]
    types:
      - completed

permissions:
  packages: write
  actions: read
  contents: write
  security-events: write

jobs:
  module:
    if: ${{ github.event.workflow_run.conclusion == 'success' || github.event.workflow_run.conclusion == '' }}
    uses: NethServer/ns8-github-actions/.github/workflows/module-info.yml@v1
  trivy:
    needs: module
    if: ${{ needs.module.outputs.release == 'stable' || needs.module.outputs.release == 'latest' || github.event_name == 'workflow_dispatch' }}
    uses: NethServer/ns8-github-actions/.github/workflows/scan-with-trivy.yml@v1
    with:
      images: ${{ needs.module.outputs.images }}
      severity: "HIGH,CRITICAL"
```
{% endraw %}

Remember to commit and push the changes to the repository.
</file>

<file path="docs/design.md">
---
layout: default
title: Design & Architecture
nav_order: 4
---

# Design & Architecture

* TOC
{:toc}

## Goals

The design of NethServer 8 (NS8) should fulfill these goals:

- solve sysadmin daily problems, like:
  - no-brain software installation
  - migrate software to another machine
  - easy and effective data backup and restore
  - prepare a machine in a lab, deploy at customer's office
- limit upstream dependency, increase upstream independence
- NS 7 migration (better, upgrade) path
- centralized management portal, installable on premise and as SaaS service

## Assumptions

While Kubernetes is great for managing applications inside big clusters, NS8 is designed
for small and medium business, with limited resources.

Assumptions:

- containers are the new standard
- built for cheap hardware or entry-level Virtual Private Server (VPS)
- few nodes: 1 node mostly, 2 or 3 nodes sometimes
- nodes can be on different geographical areas and the network could have poor latency

## Glossary

NS8 is composed by many parts, let's explain the main terminology.

- *Node*: a physical or virtual installation of NS8, it can be a *leader*, *worker* or both for all-in-one installations
- *Cluster*: a set of one or more nodes
- *Leader*: the node which executes the control logic and has read-write access to the configuration.
- *Worker*: a node which execute one or more modules, it has read-only access to the configuration. A leader node can be  a worker too.
- *Core*: set of fundamental software which is usually installed on all cluster nodes
- *Module*: additional software that can be installed on one or more cluster nodes, like Mail server, Nextcloud, Webtop.
- *Instance*: a running instance of a module with a specific configuration. Each instance runs inside an isolated environment and constituted by one or more Podman containers.
- *Application*: speaking in UI terms, it corresponds to one or more instances.

## Design choices

(almost) Everything runs inside a container.

Design goals:

- store the configuration on a reliable cluster-ready database: one read-write Redis master node for the whole cluster, multiple read-only replica nodes
- use TLS terminator whenever possible to simplify module configuration
- the configuration should be readable for any module inside the system, sensitive data (like passwords) should be store encrypted
- security as first class citizen: rootless container modules with SELinux / AppArmor, rootfull allowed too

List of things considered almost stable, with or without an existing prototype implementation:

- Systemd & Podman foundations
- Unix users for rootless modules
- WireGuard VPN among nodes
- Account providers:
  - Samba AD and OpenLDAP account providers (both are LDAP)
  - Remote LDAP account provider
  - No Unix accounts for domain users
- Cluster agent, Node agent, Module agents
- Events and Actions
- Container Registry as software repository for everything
- Authenticated Redis access for write operations
- Public Redis read only access
- Edge proxies with TLS termination
- Centralized certificate management
- FHS compliant
- API server
- UI structure

### Operating System (OS) requirements

NS8 should run on a OS with the following features:

- small footprint, x86_64 (and aarch64)
- systemd to keeps things running
- podman ≥ 2.2
- support WireGuard VPN
- cgroups v2
- firewalld to manage ports for the public network

### Users

As design choice, NS8 will use two different user bases for the core and the applications.

The core, including the administrator UI, will authenticate only against Redis.
Each module instance will use local Unix accounts.

Applications will be able to access users from the same account provider available on NS7:
- local and remote OpenLDAP
- local and remote AD

Account providers will be accessible using a LDAP proxy.
Each module instance can eventually select a different account provider.

## Components

The system is composed by two main components:
- core
- modules

### Core

The core purpose is managing the applications, providing the basics for their entire life cycle (install, upgrade, reconfigure, uninstall...).
It runs the following components:

- Redis [database and message bus](core/database.md)
- Node, cluster and module [agents](core/agents.md) written in Golang
- Traefik as [edge proxy](core/proxy_certificates.md), for TLS termination and centralized certificates management
- [LDAP proxy](core/user_domains.md), a rootless module listening on 127.0.0.1. It helps other
  modules to connect to account provider LDAP servers, with a clear text connection for local containers
- LDAP local account provider: [Samba DC](https://github.com/NethServer/ns8-core/blob/main/samba/README.md), OpenLDAP (not implemented yet)
- [VPN](core/vpn.md), each node is connected to the leader using WireGuard in a star network topology
- [API server](core/api_server.md), it handles authentication and authorization for UI and cli requests, it also audits executed tasks
- [UI](ui/index.md), it allows configuration of the cluster and applications


### Modules

The core instantiates a set of *modules*. Each module instance runs an
application (e.g. Webtop, Nextcloud) or it can be just a part of it (e.g.
Ldapproxy OpenLDAP and Samba are parts/components of User domains).

In any case a module instance is made of one or more Podman rootless containers.
In exceptional cases a module can run rootfull containers (i.e node_exporter, Crowdsec).

See [Modules architecture](modules/index.md) for more info.
</file>

<file path="docs/development_process.md">
---
layout: default
title: Development process
nav_order: 3
---

# Development process

The NethServer project follows a shared development process. See
[NethServer developer handbook](https://handbook.nethserver.org/) for a
detailed guide on **how to contribute to NethServer** and how we keep
track of the work with GitHub Project and Issues.

The following section describes the release process of NS8 core
and application images.

## NS8 release process

The release process is fully automated with a [GitHub Actions
workflow][^gha]. The workflow is triggered when a [Semver tag][^semver] is pushed
to the git repository.

[^gha]: https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-syntax
[^semver]: https://handbook.nethserver.org/version_numbering/#version-numbering-rules

An action runner starts and executes the main release procedure as defined
by a .yml file under ``.github/workflows/`` directory:

- `publish-images.yml`, for application images,
- `core.yml`, for core images.

In both cases the repository build script (e.g. `build-images.sh`) is
executed by the action runner and resulting Podman container images are
uploaded to the `ghcr.io` image registry.

There may be other conditional workflows that follow. For example:

- If the Semver tag is _stable_, the `ns8-core` repository also builds and
  uploads .qcow and .vmdk images to DigitalOcean Spaces.
- If the stable tag corresponds to a GitHub release, SBOM signatures are
  produced and attached to the release.

The repository GitHub release page is referenced by NS8 Software Center UI
to provide a human-readable summary of changes (changelog). Hence **a
GitHub release must be created**, with the same name as the Semver tag.

Since SBOM signatures and the release changelog are mandatory, the
following section explains how to simultaneously create the repository tag
with a GitHub release.

### Stable release with `gh release` command

As pre-requisite, install `gh`, the official [GitHub CLI][^ghcli] command,
to trigger the release process from a terminal.

[^ghcli]: https://cli.github.com/

#### 1. Last release number

Find the last release number, to use as base to inspect the pending
changes on the `main` branch and generate the changelog.

    ⬢ [davidep@toolbx ns8-core]$ gh release list -L 3
    TITLE   TYPE    TAG NAME  PUBLISHED
    3.17.1  Latest  3.17.1    about 6 days ago
    3.17.0          3.17.0    about 21 days ago
    3.16.1          3.16.1    about 24 days ago

For example, latest is `3.17.1`.

#### 2. Inspect pending changes

The goal of this step is to ensure that all pending changes have gone
through the QA review process.

Switch to `main` branch and pull latest changes.

    git checkout main
    git pull origin main

Review the pending changes changelog:

    git log
    git diff --stat 3.17.1
    git diff 3.17.1

Commits often contain a reference to pull requests. Reference to the
related issue is reported in the PR description.

#### 3. Find related issues

Find in the issue tracker the items with
[VERIFIED][^vrfy] label.
Filter by project, e.g. `NethServer`, `NethVoice` or by milestone.

[^vrfy]: https://github.com/NethServer/dev/issues?q=is%3Aissue%20state%3Aopen%20label%3Averified

If there are still non-verified commits, for example commits that belong
to issues in development or QA stage, **the release process must be stopped**.

#### 4. Check documentation

If a related issue requires a documentation update, make sure the
documentation changes are ready for publication in [ns8-docs
repository][^ns8docs].

[^ns8docs]: https://github.com/NethServer/ns8-docs

#### 5. Check translations

If there are pending UI changes, make sure related strings are ready for
translation on [NS8 Weblate project][^weblate].

[^weblate]: https://hosted.weblate.org/projects/ns8/#components

Check also if a pull request from Weblate is ready, and merge it.

#### 6. Create the release

Choose the [release version number][^semver], incrementing the latest
version major, minor, or patch number.  For example `3.17.1 -> 3.18.0` is
a minor increment.

Create the release and git tag on GitHub in a single command:

    gh release create 3.18.0 --generate-notes --notes-start-tag 3.17.1

Note that if you run `gh` on a git local repository, the working tree
state does not matter.  The command creates the tag on the last commit of
the main repository branch. Use ``--target`` to select an alternative
commit, e.g.:

    gh release create 3.18.0 --generate-notes --notes-start-tag 3.17.1 --target COMMIT-SHA

Then, you can sync the remote tag with the local repository using the
following command:

    git fetch --tags

#### 7. Publish documentation

To publish a documentation PR found at step 4, just merge it.

#### 8. Verification checks

1. The GitHub release has the list of closed PRs (changelog)
1. The SBOM artifacts were attached to the release
1. The container images were pushed to GitHub Packages (ghcr.io)
1. For ns8-core only, the VM pre-built images were uploaded to
   DigitalOcean Spaces
1. Documentation was published
1. Translation repository is not locked
1. Related issues were closed with a link to the GitHub release

## Testing releases

Testing releases occur when code changes are merged with the `main`
branch, to start a testing (QA) process.

Choose the [release version number][^semver], incrementing the latest
stable version major, minor, or patch number. For example, `3.17.1 ->
3.17.2` is a patch increment for a bug fix. The latest release is visible
in the GitHub repository page.

Then append a pre-release suffix, like `-testing.1`, or `-dev.1`:

    3.17.2-testing.1

Create the testing tag on the last commit of your working tree:

    git tag 3.17.2-testing.1

Push the tag to trigger the testing build:

    git push origin 3.17.2-testing.1

For testing releases, you can also use
[ns8-release-module](https://github.com/NethServer/gh-ns8-release-module/).

It is a [GitHub CLI](https://cli.github.com/) extension that automates the
creation and management and it's quite useful when creating testing
releases.

See the full documentation inside the
[README](https://github.com/NethServer/gh-ns8-release-module/blob/main/Readme.md).

## Create a release from GitHub

> **Warning**: always prefer the GitHub CLI to create a release.

In case you forgot to create a release using the GitHub CLI, you can create it manually.
First, make sure the tag is created in the repository and pushed to the remote. Then:

1. Navigate to the GitHub UI:
    - Go to the repository's "Releases" section.
    - Click on "Draft a new release" to start the process.

2. Add a changelog:
    - Provide a detailed changelog for the release.
    - Optionally, use the automatic changelog generation button if available.

3. Attach the SBOM file:
    - For stable releases, attach the Software Bill of Materials (SBOM) file to the release by respecting conventions describe in the [SBOM generation](https://handbook.nethserver.org/security/#sbom-software-bill-of-materials) page.
    You can find the SBOM files as artifacts of the GitHub Actions workflow.

## NethVoice release procedure addendum

The following procedure is used by the NethVoice project. It relies on the
`gh ns8-release-module` extension from
[NethServer/gh-ns8-release-module](https://github.com/NethServer/gh-ns8-release-module).

Before using the extension, install it if needed:

```bash
gh extension install NethServer/gh-ns8-release-module
```

1. Run the pre-release checks to verify that all linked issues are in the
   `verified` state:

       gh ns8-release-module check

2. Create the GitHub release and tag, automatically linking closed issues to
   the release notes:

       gh ns8-release-module create --release-name <version> --with-linked-issues

3. Open the newly created GitHub release and review or edit the generated
   release message to ensure it is accurate and complete.

4. If the release includes changes from external components that are not
   tracked as NS8 module repositories, append their current `HEAD` commit
   references to the release notes. This step is temporary and currently
   applies to `nethesis/nethcti-server`. Use the following helper script to
   retrieve the commit SHAs and format them for inclusion:

   ```bash
   #!/bin/bash

   declare -A repositories=(
       ["nethesis/nethcti-server"]="ns8"
   )

   get_last_commit_sha() {
       repo=$1
       branch=$2
       last_commit_sha=$(gh api repos/"$repo"/commits/"$branch" --jq '.sha')
       echo -n "* https://github.com/$repo/commit/$last_commit_sha"
   }

   if ! command -v gh &> /dev/null; then
       echo "GitHub CLI (gh) is not installed. Please install it first."
       exit 1
   fi

   echo "### External components \`HEAD\`"
   for repo in "${!repositories[@]}"; do
       branch=${repositories[$repo]}
       get_last_commit_sha "$repo" "$branch"
       echo
   done
   ```

   Copy the script output and paste it into the release notes.

5. Remove intermediate testing releases that were created during
   the QA cycle:

       gh ns8-release-module clean --release-name <version>

6. Post a comment on each linked issue to notify that the issue
   has been included in the release:

       gh ns8-release-module comment --release-name <version>

7. Notify the `~nethvoice` channel that the release has been
   published.
</file>

<file path="docs/Gemfile">
# frozen_string_literal: true

source "https://rubygems.org"

git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }

# gem "rails"
gem "jekyll"
gem "github-pages", group: :jekyll_plugins

gem "webrick", "~> 1.7"
</file>

<file path="docs/index.md">
---
layout: default
title: Home
nav_order: 1
---

# NethServer 8 developer manual

NethServer 8 (NS8), is the evolution of NethServer 7 (NS7).
NethServer 8 is designed for small offices and medium enterprises. It's simple, secure and flexible.

## Target audience

This manual is intended for developers interested in NethServer internals.
By reading it, you will learn how to extend, enhance, and debug the
NethServer platform.

## Get involved

The NethServer project welcomes anyone who would like to become involved in the project. This is a brief list of things to do (in a sparse order):

* Writing documentation
* Bug reporting, bug triaging, QA testing
* Translating the web interface
* Developing / coding in Perl, PHP, Python, Bash

## Explore

Give it a try and follow the [quickstart](quickstart.md)!
Look at [core internals](core), [modules architecture](modules) or the [UI implementation](ui).

External links:
- [Administrator manual]({{site.admin_manual}})
- [Project roadmap](https://github.com/orgs/NethServer/projects/8)
- [API documentation](https://github.com/NethServer/ns8-core/tree/apidoc)

Do you need help? Ask the [community](https://community.nethserver.org/)
</file>

<file path="docs/license.md">
---
layout: default
title: License
nav_order: 10
---

# License

NethServer 8 is released under the [GNU General Public License v3.0](https://github.com/NethServer/ns8-core/blob/main/LICENSE) license.

Code files should contain an header with valid [SPDX](https://spdx.dev/ids/) ID and a copyright statement.

Example for `sh`, `bash`, `python` and `Makefile` files:
```
#
# Copyright (C) 2023 Nethesis S.r.l.
# SPDX-License-Identifier: GPL-3.0-or-later
#
```

Extra packages could be released under a different license.
</file>

<file path="docs/quickstart.md">
---
layout: default
title: Quickstart
nav_order: 2
---

# Installation & first steps

* TOC
{:toc}

See the [Administrator manual]({{site.admin_manual}}) for system requirements and installation instructions.

## Core: install custom images

Developers may prefer to run `install.sh` with one or more images from a
development branch or alternative registries.

    curl https://raw.githubusercontent.com/NethServer/ns8-core/main/core/install.sh > install.sh 
    bash install.sh ghcr.io/nethserver/core:latest ghcr.io/nethserver/traefik:mybranch

See also [module override](#module-override).

The install script also accepts the following environment variables:
- `TESTING`: This flag allows you to override the testing setting within
  the `default` repository. It can be set to `0` (disabled) or `1`
  (enabled), with a default value of `0`. Note that this flag will
  automatically reset to `0` after the next core update.
- `REPMOD`: override `default` software repository URL, it could be something like `https://mycustomrrepo.server.test/repomd`
- `ADMIN_PASSWORD`: override default admin password

## Applications: install from CLI

Applications can be installed directly from the user interface.

If you prefer the command line, use the `add-module` command:
```
add-module <module> <node_id>
```
The  above command will try to install the latest stable version of the module.

Example to install Dokuwiki on node 1:
```
add-module dokuwiki 1
```

You can also install an image which is not still available inside the repository by using
its URL.

Example to install Dokuwiki directly from the image registry:
```
add-module ghcr.io/nethserver/dokuwiki:mydev 1
```

If the given image is already present in the local Podman storage, no
remote download occurs and the local image is used instead. During
development this might be unwanted and to work around this behavior
execute the following command in every cluster node, before `add-module`:

    podman rmi ghcr.io/nethserver/dokuwiki:mydev

Like the Software Center, `add-module` refuses a node that is not eligible,
using the image labels from the repository, not from the custom image. Use
`--force` to skip this check:

    add-module --force ghcr.io/nethserver/crowdsec:mydev 1

Many applications need a configuration step after install, for more info, 
please refer to [Administrator manual]({{site.admin_manual}}).

### Module override

Sometimes you may need to install a specific tag for a module even from the UI.
As an example, this can be usefull to override the image used by a
user domain provider.

Command to override the Samba module:
```
redis-cli hset cluster/override/modules samba ghcr.io/nethserver/samba:rootless
```

You can now provision the user domain directly from the web interface.
</file>

<file path="docs/README.md">
# Build the documentation

The documentation is built using Github pages on each commit to the main branch.

## Build locally

Tested on Fedora 36 and Ubuntu 22.04.
Install the dependencies make sure to install ruby >= 3.0.

- Fedora:
    ```
    dnf module install ruby
    dnf install gcc g++
    ```

- Ubuntu:
    ```
    apt install build-essential ruby-full
    ```

Install jekyll and all dependencies:
```
bundle config set --local path '.bundle/vendor'
bundle install
```

Build and serve the site locally:
```
bundle exec jekyll serve
```
</file>

<file path="AGENTS.md">
# ns8-core

This is production-grade project with thousands of installations. Breaking
changes are not allowed.

## Architecture

NethServer 8 is a container-based Linux platform orchestrated via Redis. This
repository contains the **core** — cluster/node management, API server, agent
framework, and admin UI. External application modules live in separate
`ns8-<app>` repositories.

### Components

| Path | Language | Purpose |
|------|----------|---------|
| `core/agent/` | Go | Agent daemon — reads tasks from Redis, handles events, executes actions, on behalf of some system component (cluster, node, application) |
| `core/api-server/` | Go | Gin-based REST API with JWT auth, WebSocket, SQLite audit log |
| `core/api-moduled/` | Go | Generic HTTP API for individual modules (JWT, JSON Schema validation) |
| `core/ui/` | Vue 2 + JS | Admin web UI — Carbon Design System, Vuex, Vue Router, WebSocket |
| `core/imageroot/` | Python 3 / Bash | Action scripts and the Python `agent` package (at `usr/local/agent/pypkg/agent/`), for action and event handler implementation |
| `core/support/` | Shell | Remote support session via OpenVPN |
| `core/restic/`, `core/rsync/` | Shell | Backup and replication container wrappers |
| `core/tests/` | Robot Framework | Integration tests (cluster sanity, UI) |
| `docs/` | Markdown (Jekyll) | Developer manual at nethserver.github.io/ns8-core |

### How actions work

Actions are the primary unit of work. They live under
`core/imageroot/var/lib/nethserver/{cluster,node}/actions/<action-name>/` and
consist of numbered step scripts (`00validate_input`, `50update`, etc.) executed
sequentially by the Go agent. Each action directory may include
`validate-input.json` and `validate-output.json` for JSON Schema validation.

Python action scripts follow this pattern:

```python
#!/usr/bin/env python3
import json, sys, agent, agent.tasks

request = json.load(sys.stdin)
rdb = agent.redis_connect(privileged=True)
# ... business logic ...
json.dump(result, sys.stdout)
```

Key `agent` module APIs: `redis_connect()`, `set_env()`, `read_envfile()`,
`set_progress()`, `run_helper()`, `agent.tasks.run()`, `agent.tasks.runp()`.

### UI task/event model

The Vue UI communicates via WebSocket. Components invoke server-side actions
through `TaskService` mixin methods (e.g., `createModuleTaskForApp`). Each task
gets a unique `eventId` (via `getUuid()`) to avoid event handler collisions.
Progress updates arrive over the WebSocket and flow through the notification
mixin into the Vuex store.

## Build

Container images are built with **buildah** (not Docker):

```bash
cd core && bash build-image.sh
```

Go binaries are compiled with `CGO_ENABLED=0` (agent, api-moduled) or
`CGO_ENABLED=1 -static` (api-server, for SQLite). There are no Makefiles; the
build script is the source of truth.

For local Go development:

```bash
cd core/agent && go build .
cd core/api-server && go build api-server.go
```

UI development:

```bash
cd core/ui
yarn install
yarn serve          # dev server
yarn build          # production build
```

## Lint

For UI/Frontend:

```bash
cd core/ui && yarn lint
```

For Backend:

Bash scripts should pass `shellcheck`.

## Test

**Go agent tests** (runs in containers via podman):

```bash
cd core/agent && bash test-agent.sh
```

**Integration tests** (Robot Framework, requires a live node):

```bash
cd core
run-ns8-tests <LEADER_NODE> [robot_options...]
```

Robot Framework tests are in `core/tests/` with numbered directories
(`10__cluster_sanity/`) and shared `keywords.resource`. The
`run-ns8-tests` helper is provided by the `ns8-github-actions` repository;
you also need Podman in `PATH` and an SSH private key that can access the
target leader node.

## Conventions

- **Action script numbering**: By convention, `00` = validation, `50` = main
  logic, `60+` = post-processing, but intermediate numbers (e.g. `01`, `05`,
  `10`, `20`, `30`) are commonly used. Each step is a separate executable
  (Python 3 or Bash).
- **JSON Schema validation**: Actions define `validate-input.json` /
  `validate-output.json` for automatic request/response validation. Whenever
  an action's input or output attributes change, update the matching schema
  file in the same commit/PR.
- **Redis as state store**: All persistent state is in Redis, not on the
  filesystem. Actions use `agent.redis_connect()` to read/write state.
- **UI design system**: Carbon Design System (`@carbon/vue`). Use Carbon
  components, not custom HTML widgets.
- **UI mixins**: Cross-cutting concerns (WebSocket, notifications, login,
  2FA, audit, node) are Vue mixins in `core/ui/src/mixins/`. Task-related
  services (`TaskService`, `UtilService`, etc.) come from the external
  `@nethserver/ns8-ui-lib` package.
- **Event ID pattern**: Always generate a unique `eventId` per task creation to
  prevent event handler collisions:
  ```js
  const eventId = this.getUuid();
  // use `${taskAction}-completed-${eventId}` for event names
  ```
- **Go modules**: `core/agent`, `core/api-server`, and `core/api-moduled` are
  independent Go modules with separate `go.mod` files. Use `go fmt` before
  commits.
- **Translations**: Managed via Weblate at
  `https://hosted.weblate.org/projects/ns8/`. Do not manually edit translation
  files.
- **`/etc/hosts` handling**: The `set-fqdn` action comments out lines
  containing the old hostname (prefixed with `# commented by set-fqdn #`)
  and appends a new `127.0.1.1` entry for the new hostname.
- **Entrypoint startup waits**: For container entrypoints, a simple readiness
  loop is acceptable when the outer service startup is supervised by Systemd.
  In exceptional failure cases, prefer relying on the Systemd start timeout
  instead of adding extra in-script liveness handling, as long as the
  externally visible service (for example, HAProxy) is not started before the
  dependency is ready.
- **Branch names**: never use "/" in branch names. Use only chars allowed
  by container registry tags, like "-" and alphanumeric chars. This is a
  requirement for container image uploads.
- **Commits**: Use conventional commit style. Short title line, 50 chars max.
  Wrap body text at 72. Append a footer line `Assisted-by: AGENT_NAME:MODEL_VERSION`.
</file>

<file path="CONTRIBUTING">
Contributions (ideas, code, hugs...) to NethServer are welcome!

NethServer users and developers meet here

https://community.nethserver.org/

The development process is detailed here

https://nethserver.github.io/ns8-core/development_process/
</file>

<file path="LICENSE">
GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU General Public License is a free, copyleft license for
software and other kinds of works.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.  We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors.  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights.  Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received.  You must make sure that they, too, receive
or can get the source code.  And you must show them these terms so they
know their rights.

  Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.

  For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software.  For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.

  Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so.  This is fundamentally incompatible with the aim of
protecting users' freedom to change the software.  The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable.  Therefore, we
have designed this version of the GPL to prohibit the practice for those
products.  If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.

  Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary.  To prevent this, the GPL assures that
patents cannot be used to render the program non-free.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Use with the GNU Affero General Public License.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:

    <program>  Copyright (C) <year>  <name of author>
    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.

  The GNU General Public License does not permit incorporating your program
into proprietary programs.  If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library.  If this is what you want to do, use the GNU Lesser General
Public License instead of this License.  But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
</file>

<file path="README.md">
# NethServer 8 Core

This repository contains the NethServer 8 Core source code, the developer
documentation, CI/CD automation, and the installation procedure.

* Find more information in the [Developer
  manual](https://nethserver.github.io/ns8-core/)

* Quick link to [API
  docs](https://github.com/NethServer/ns8-core/tree/apidoc)

* Translate the UI with
  [Weblate](https://hosted.weblate.org/projects/ns8/)

Useful links

- [Website](https://www.nethserver.org)
- [Project roadmap](https://github.com/orgs/NethServer/projects/8)
- [Admin's manual](https://docs.nethserver.org/projects/ns8)
</file>

<file path="renovate.json">
{
  "$schema": "https://docs.renovatebot.com/renovate-schema.json",
  "extends": [
    "local>NethServer/.github:ns8-automerge"
  ],
  "enabledManagers": [
    "npm",
    "github-actions",
    "gomod",
    "custom.regex"
  ],
  "packageRules": [
    {
      "description": "Suppress PRs for major and minor updates of the images and tools of the build and test scripts",
      "matchManagers": ["custom.regex"],
      "matchDatasources": ["docker", "github-tags"],
      "matchUpdateTypes": ["major", "minor"],
      "enabled": false
    }
  ],
  "customManagers": [
    {
      "customType": "regex",
      "fileMatch": [
        "build-image.sh"
      ],
      "matchStrings": [
        "https://github\\.com/(?<depName>.+?)/releases/download/(?<currentValue>.+?)/logcli-linux-amd64\\.zip"
      ],
      "datasourceTemplate": "github-tags"
    },
    {
      "customType": "regex",
      "description": "Keep the Redis and Go images of the test suites aligned with the ones of build-image.sh: same depName, same Renovate PR",
      "fileMatch": [
        "(^|/)test-[^/]+\\.sh$"
      ],
      "matchStrings": [
        "docker\\.io/library/(?<depName>redis|golang):(?<currentValue>[-0-9a-zA-Z_.]+)"
      ],
      "datasourceTemplate": "docker"
    }
  ]
}
</file>

</files>
