Compare commits
30 Commits
9b37efc0a1
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| ad80afbfdd | |||
| 9b9c607fd1 | |||
| 166276d19b | |||
| a836645728 | |||
| 3da8608cf1 | |||
| 0714b442be | |||
| db1ce68800 | |||
| 4a159cad71 | |||
| 476c41cf08 | |||
| 13bea66473 | |||
| 47407cdbca | |||
| f9bec78c82 | |||
| 08b94337ad | |||
| 4b65838f0f | |||
| ce3b3c900a | |||
| c01d9c7e40 | |||
| e7dce2f0e9 | |||
| 9cedf085a3 | |||
| 991d6f5257 | |||
| b0443d5950 | |||
| 13765e58d2 | |||
| 8ceb1bb1df | |||
| e2c4881bb7 | |||
| 14d3a3152a | |||
| a033562c4c | |||
| 9e6f57be35 | |||
| 582960cc32 | |||
| 190d2418da | |||
| 5ade939ff9 | |||
| 184f9e8ede |
14
.gitignore
vendored
Normal file
14
.gitignore
vendored
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
__pycache__/
|
||||||
|
*.py[cod]
|
||||||
|
node_modules/
|
||||||
|
dist/
|
||||||
|
.env
|
||||||
|
|
||||||
|
agent/.venv/
|
||||||
|
agent/build/
|
||||||
|
web-client/dist/
|
||||||
|
|
||||||
|
web-server/uploads/
|
||||||
|
docs/*
|
||||||
|
output/
|
||||||
|
tmp/
|
||||||
7
.vscode/settings.json
vendored
Normal file
7
.vscode/settings.json
vendored
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"python.defaultInterpreterPath": "${workspaceFolder}/agent/.venv/Scripts/python.exe",
|
||||||
|
"python.analysis.extraPaths": [
|
||||||
|
"${workspaceFolder}/agent"
|
||||||
|
],
|
||||||
|
"python.terminal.activateEnvironment": true
|
||||||
|
}
|
||||||
139
BUILD_SYSTEM.md
139
BUILD_SYSTEM.md
@@ -1,139 +0,0 @@
|
|||||||
# BUILD_SYSTEM.md
|
|
||||||
|
|
||||||
# Linux Package Installer System
|
|
||||||
|
|
||||||
**Server IP:** 172.20.235.176
|
|
||||||
|
|
||||||
Mục tiêu: xây dựng hệ thống cài đặt, quản lý package `.deb` cho ứng dụng web trên Linux với luồng **Web Server → Web Client → Local Installer Agent → Web Service**.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 1. Thành phần hệ thống
|
|
||||||
|
|
||||||
1. **Web Server** (`server.package.robot`)
|
|
||||||
- Node.js + Express
|
|
||||||
- Chức năng:
|
|
||||||
- Lưu trữ các file `.deb`
|
|
||||||
- Metadata JSON về package: version, dependency, mô tả
|
|
||||||
- API download package
|
|
||||||
- Admin upload package
|
|
||||||
|
|
||||||
2. **Web Client** (`client.package.robot`)
|
|
||||||
- Frontend: React
|
|
||||||
- Backend: Node.js
|
|
||||||
- Chức năng:
|
|
||||||
- Hiển thị danh sách package
|
|
||||||
- Cho người dùng chọn Install / Modify / Update / Remove
|
|
||||||
- Relay lệnh tới Local Installer Agent
|
|
||||||
- Hiển thị tiến trình / status realtime
|
|
||||||
|
|
||||||
3. **Local Installer Agent**
|
|
||||||
- Python
|
|
||||||
- Chạy ngầm trên Linux client
|
|
||||||
- Chức năng:
|
|
||||||
- Tải package từ Web Server
|
|
||||||
- Kiểm tra checksum / chữ ký
|
|
||||||
- Cài / gỡ / update bằng dpkg/apt
|
|
||||||
- Start / restart các service systemd
|
|
||||||
- Báo tiến trình / status về Web Client
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 2. Flow hệ thống
|
|
||||||
|
|
||||||
|
|
||||||
Admin / Developer
|
|
||||||
│ Upload .deb và metadata
|
|
||||||
▼
|
|
||||||
Web Server (172.20.235.176)
|
|
||||||
│ Serve .deb + metadata
|
|
||||||
▼
|
|
||||||
Web Client (React + Node.js)
|
|
||||||
│ Hiển thị package list
|
|
||||||
│ User chọn Install/Modify/Update/Remove
|
|
||||||
▼
|
|
||||||
Local Installer Agent (Python)
|
|
||||||
│ Download .deb từ server
|
|
||||||
│ Verify checksum
|
|
||||||
│ Install / Remove / Update
|
|
||||||
│ Start/Restart systemd service
|
|
||||||
▼
|
|
||||||
Web Service / Package Service
|
|
||||||
│ Chạy sẵn
|
|
||||||
▼
|
|
||||||
User mở browser → truy cập service
|
|
||||||
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 3. Cấu trúc project
|
|
||||||
|
|
||||||
|
|
||||||
project-root/
|
|
||||||
├── server/
|
|
||||||
│ ├── packages/ # .deb files
|
|
||||||
│ ├── metadata/ # JSON metadata
|
|
||||||
│ └── src/ # Node.js + Express
|
|
||||||
│ ├── routes/
|
|
||||||
│ └── controllers/
|
|
||||||
│
|
|
||||||
├── client/
|
|
||||||
│ ├── frontend/ # React UI
|
|
||||||
│ └── backend/ # Node.js relay tới Agent
|
|
||||||
│
|
|
||||||
├── agent/
|
|
||||||
│ ├── bin/ # Python executable / script
|
|
||||||
│ ├── service/ # systemd service file
|
|
||||||
│ └── lib/ # logic install/update/remove/status
|
|
||||||
│
|
|
||||||
└── packages/ # Build các .deb trước khi upload
|
|
||||||
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 4. Metadata JSON mẫu
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"applications": [
|
|
||||||
{
|
|
||||||
"id": "sample-app",
|
|
||||||
"name": "Sample Package",
|
|
||||||
"version": "1.0.0",
|
|
||||||
"packages": [
|
|
||||||
{"id": "sample-core", "required": true, "version": "1.0.0", "file": "sample-core_1.0.0_amd64.deb"},
|
|
||||||
{"id": "sample-web", "required": false, "version": "1.0.0", "file": "sample-web_1.0.0_amd64.deb", "depends": ["sample-core"]},
|
|
||||||
{"id": "sample-api", "required": false, "version": "1.0.0", "file": "sample-api_1.0.0_amd64.deb", "depends": ["sample-core"]}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
5. Flow Install / Modify / Update / Remove
|
|
||||||
User mở Web Client
|
|
||||||
Web Client fetch metadata từ Web Server
|
|
||||||
User chọn package muốn Install/Modify/Update/Remove
|
|
||||||
Web Client gửi JSON request tới Local Installer Agent
|
|
||||||
Local Agent:
|
|
||||||
Download package từ Web Server
|
|
||||||
Verify checksum
|
|
||||||
Install / Remove / Update package
|
|
||||||
Start / Restart systemd service
|
|
||||||
Báo tiến trình / status về Web Client
|
|
||||||
Sau khi cài xong, service chạy sẵn
|
|
||||||
User mở browser → truy cập Web Service
|
|
||||||
6. Công nghệ & ngôn ngữ
|
|
||||||
Thành phần Ngôn ngữ / Framework
|
|
||||||
Web Server Node.js + Express
|
|
||||||
Web Client Frontend React
|
|
||||||
Web Client Backend Node.js
|
|
||||||
Local Installer Agent Python
|
|
||||||
Web Service Tùy ứng dụng
|
|
||||||
7. Quy trình triển khai từ đầu
|
|
||||||
Build package .deb cho ứng dụng web, chia thành các package nhỏ nếu cần.
|
|
||||||
Upload package + metadata lên Web Server.
|
|
||||||
Web Client fetch metadata, hiển thị package list.
|
|
||||||
Cài đặt Local Installer Agent lần đầu trên Linux client.
|
|
||||||
User chọn package → Install / Modify / Update / Remove.
|
|
||||||
Local Installer Agent thực hiện cài/gỡ/update ngầm.
|
|
||||||
Web Service chạy sẵn, người dùng truy cập browser.
|
|
||||||

|
|
||||||
136
agent/README.md
Normal file
136
agent/README.md
Normal file
@@ -0,0 +1,136 @@
|
|||||||
|
# Local Installer Agent
|
||||||
|
|
||||||
|
FastAPI service that runs on each Linux client and listens on `127.0.0.1:5010`.
|
||||||
|
|
||||||
|
It accepts install, update, remove, task, log, installed-app, and service-control requests from `robot.installer`. It stores state in local SQLite and installs trusted `.deb` components downloaded from `robot.package`, Ubuntu APT packages, plus Docker image components from allowed registries when Docker support is enabled.
|
||||||
|
|
||||||
|
## Development
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd agent
|
||||||
|
python3 -m venv .venv
|
||||||
|
source .venv/bin/activate
|
||||||
|
pip install -r requirements.txt
|
||||||
|
uvicorn app.main:app --host 127.0.0.1 --port 5010
|
||||||
|
```
|
||||||
|
|
||||||
|
## Install script URL
|
||||||
|
|
||||||
|
Client machines should keep using the stable installer command:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -fsSL https://robot.package/install-agent.sh | sudo bash
|
||||||
|
```
|
||||||
|
|
||||||
|
The web server resolves `https://robot.package/packages/agent/latest.deb?arch=<dpkg-arch>`
|
||||||
|
to the newest uploaded `local-installer-agent_<version>_<arch>.deb`, so updating the Agent does not require editing the install command.
|
||||||
|
|
||||||
|
Agent packages are uploaded from the web server Admin page at `/agent`. The default storage folder is
|
||||||
|
`web-server/uploads/packages/agent`, and it can be changed with `AGENT_PACKAGE_DIR`.
|
||||||
|
|
||||||
|
## Important API
|
||||||
|
|
||||||
|
```text
|
||||||
|
GET /health
|
||||||
|
GET /system-info
|
||||||
|
GET /apps/installed
|
||||||
|
POST /apps/install
|
||||||
|
POST /apps/update
|
||||||
|
POST /apps/remove
|
||||||
|
GET /tasks/{taskId}
|
||||||
|
GET /tasks/{taskId}/logs
|
||||||
|
GET /tasks/{taskId}/components
|
||||||
|
POST /services/start
|
||||||
|
POST /services/stop
|
||||||
|
POST /services/restart
|
||||||
|
GET /services/{serviceName}/status
|
||||||
|
```
|
||||||
|
|
||||||
|
`POST /apps/install` supports both:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"appId": "robot-suite",
|
||||||
|
"version": "1.0.0"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
and a direct single `.deb` payload:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"appId": "robot-web-app",
|
||||||
|
"appName": "Robot Web App",
|
||||||
|
"packageName": "robot-web-app",
|
||||||
|
"serviceName": "robot-web-app.service",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"downloadUrl": "https://robot.package/packages/robot-web-app_1.0.0_amd64.deb",
|
||||||
|
"checksum": "sha256_hash_here"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
For manifest mode, the Agent fetches:
|
||||||
|
|
||||||
|
```text
|
||||||
|
{ROBOT_PACKAGE_BASE_URL}/api/apps/{appId}/versions/{version}/manifest
|
||||||
|
```
|
||||||
|
|
||||||
|
Docker image components require Docker Engine on the client machine. By default `AUTO_INSTALL_DOCKER=true`, so the agent will install the trusted distro package `docker.io` with `apt-get` when a Docker app is installed and Docker is missing. Set `AUTO_INSTALL_DOCKER=false` if Docker must be provisioned by your own fleet policy. The agent validates `image` against `ALLOWED_DOCKER_REGISTRIES`, then runs a managed container using the manifest fields `containerName`, `restartPolicy`, `ports`, `volumes`, and `env`.
|
||||||
|
|
||||||
|
APT components use a fixed manifest contract and never accept shell commands:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"componentId": "postgresql",
|
||||||
|
"type": "apt",
|
||||||
|
"packageName": "postgresql",
|
||||||
|
"version": "16"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`ALLOWED_APT_PACKAGES=*` allows every syntactically valid APT package name and is the default for newly built Agents. This lets an administrator enter an exact package code on the Web Server without updating each Agent's configuration for every new package.
|
||||||
|
|
||||||
|
To enable this behavior on an already deployed Agent:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo sed -i \
|
||||||
|
's/^ALLOWED_APT_PACKAGES=.*/ALLOWED_APT_PACKAGES=*/' \
|
||||||
|
/etc/local-installer-agent/agent.env
|
||||||
|
sudo systemctl restart local-installer-agent
|
||||||
|
```
|
||||||
|
|
||||||
|
To restore a restricted allowlist, use a comma-separated list without spaces:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ALLOWED_APT_PACKAGES=postgresql,nginx,redis-server,curl
|
||||||
|
```
|
||||||
|
|
||||||
|
Every allowed package must be available from the APT sources configured on the target client. The Agent runs `apt-get update`, but it does not add third-party repositories or signing keys.
|
||||||
|
|
||||||
|
APT packages can execute maintainer scripts as root during installation. Wildcard mode should therefore only be used when the Web Server and package-upload accounts are trusted and access-controlled.
|
||||||
|
|
||||||
|
After installation, the Agent discovers concrete systemd `.service` units shipped by the trusted package and reads their state with a fixed `systemctl show` argv (no shell command is accepted from the manifest or Web Client). The structured result is returned as `serviceCheckStatus` and `serviceChecks` from the task component API and is retained with the installed app for the UI.
|
||||||
|
|
||||||
|
PostgreSQL keeps an additional trusted policy: the Agent enables and starts `postgresql.service`, verifies that it is active, and waits for `pg_isready`. Other discovered package services are checked read-only; they are not blindly enabled or started because packages can ship optional or one-shot units.
|
||||||
|
|
||||||
|
`GET /apps/installed` refreshes the current systemd state for retained service names. For the trusted PostgreSQL policy it also re-runs `pg_isready`, so the UI does not report a healthy meta-service while the database is unavailable.
|
||||||
|
|
||||||
|
Example task component service result:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"serviceCheckStatus": "healthy",
|
||||||
|
"serviceChecks": [
|
||||||
|
{
|
||||||
|
"serviceName": "postgresql.service",
|
||||||
|
"loadState": "loaded",
|
||||||
|
"activeState": "active",
|
||||||
|
"subState": "running",
|
||||||
|
"unitFileState": "enabled",
|
||||||
|
"healthy": true,
|
||||||
|
"readinessStatus": "ready",
|
||||||
|
"checkedAt": "2026-07-20T00:00:00Z"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
2
agent/app/__init__.py
Normal file
2
agent/app/__init__.py
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
"""Local Installer Agent package."""
|
||||||
|
|
||||||
2
agent/app/api/__init__.py
Normal file
2
agent/app/api/__init__.py
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
"""API routers for the Local Installer Agent."""
|
||||||
|
|
||||||
105
agent/app/api/apps.py
Normal file
105
agent/app/api/apps.py
Normal file
@@ -0,0 +1,105 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
from fastapi import APIRouter, BackgroundTasks, HTTPException
|
||||||
|
|
||||||
|
from app.core.command_runner import CommandRunner
|
||||||
|
from app.core.installer import AptInstaller
|
||||||
|
from app.core.service_manager import ServiceManager
|
||||||
|
from app.core.task_runner import TaskRunner
|
||||||
|
from app.models.schemas import InstallRequest, RemoveRequest, UpdateRequest
|
||||||
|
from app.storage.repository import Repository
|
||||||
|
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/apps", tags=["apps"])
|
||||||
|
repository = Repository()
|
||||||
|
task_runner = TaskRunner(repository)
|
||||||
|
|
||||||
|
|
||||||
|
def _task_id(prefix: str) -> str:
|
||||||
|
return f"task_{prefix}_{uuid.uuid4().hex[:12]}"
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/installed")
|
||||||
|
def installed_apps() -> list[dict]:
|
||||||
|
apps = repository.list_installed_apps()
|
||||||
|
command_runner = CommandRunner(repository)
|
||||||
|
service_manager = ServiceManager(command_runner)
|
||||||
|
apt_installer = AptInstaller(command_runner)
|
||||||
|
for app in apps:
|
||||||
|
service_checks: list[dict] = []
|
||||||
|
component_statuses: list[str] = []
|
||||||
|
for component in repository.list_installed_components(app["app_id"]):
|
||||||
|
check_status = component.get("service_check_status", "not-checked")
|
||||||
|
if check_status != "not-checked":
|
||||||
|
component_statuses.append(check_status)
|
||||||
|
for check in component.get("service_checks", []):
|
||||||
|
service_name = str(check.get("serviceName") or "").strip()
|
||||||
|
if not service_name:
|
||||||
|
continue
|
||||||
|
current_check = service_manager.get_service_status(service_name)
|
||||||
|
if current_check.get("status") == "unknown" and current_check.get("errorMessage"):
|
||||||
|
current_check = dict(check)
|
||||||
|
current_check["stale"] = True
|
||||||
|
elif check.get("readinessType") == "postgresql":
|
||||||
|
readiness_status = "ready" if apt_installer.is_postgresql_ready() else "failed"
|
||||||
|
current_check["readinessType"] = "postgresql"
|
||||||
|
current_check["readinessStatus"] = readiness_status
|
||||||
|
current_check["healthy"] = bool(current_check.get("healthy")) and readiness_status == "ready"
|
||||||
|
service_checks.append(
|
||||||
|
{
|
||||||
|
**current_check,
|
||||||
|
"componentId": component["component_id"],
|
||||||
|
"packageName": component.get("package_name"),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
if service_checks and any(not check.get("healthy") for check in service_checks):
|
||||||
|
overall_status = "unhealthy"
|
||||||
|
elif service_checks:
|
||||||
|
overall_status = "healthy"
|
||||||
|
elif "unhealthy" in component_statuses:
|
||||||
|
overall_status = "unhealthy"
|
||||||
|
elif "checking" in component_statuses:
|
||||||
|
overall_status = "checking"
|
||||||
|
elif "healthy" in component_statuses:
|
||||||
|
overall_status = "healthy"
|
||||||
|
elif "not-applicable" in component_statuses:
|
||||||
|
overall_status = "not-applicable"
|
||||||
|
else:
|
||||||
|
overall_status = "not-checked"
|
||||||
|
|
||||||
|
app["serviceCheckStatus"] = overall_status
|
||||||
|
app["serviceChecks"] = service_checks
|
||||||
|
return apps
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/install")
|
||||||
|
def install_app(request: InstallRequest, background_tasks: BackgroundTasks) -> dict[str, str]:
|
||||||
|
if not request.version:
|
||||||
|
raise HTTPException(status_code=400, detail="version is required")
|
||||||
|
task_id = _task_id("install")
|
||||||
|
repository.create_task(task_id, "install", request.app_id, request.app_name)
|
||||||
|
background_tasks.add_task(task_runner.run_install, task_id, request, "install")
|
||||||
|
return {"taskId": task_id, "status": "queued"}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/update")
|
||||||
|
def update_app(request: UpdateRequest, background_tasks: BackgroundTasks) -> dict[str, str]:
|
||||||
|
if not request.version:
|
||||||
|
raise HTTPException(status_code=400, detail="version or targetVersion is required")
|
||||||
|
task_id = _task_id("update")
|
||||||
|
repository.create_task(task_id, "update", request.app_id, request.app_name)
|
||||||
|
background_tasks.add_task(task_runner.run_install, task_id, request, "update")
|
||||||
|
return {"taskId": task_id, "status": "queued"}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/remove")
|
||||||
|
def remove_app(request: RemoveRequest, background_tasks: BackgroundTasks) -> dict[str, str]:
|
||||||
|
if not request.package_name and not repository.list_installed_components(request.app_id):
|
||||||
|
raise HTTPException(status_code=400, detail="packageName is required when app is not tracked locally")
|
||||||
|
task_id = _task_id("remove")
|
||||||
|
repository.create_task(task_id, "remove", request.app_id, request.app_id)
|
||||||
|
background_tasks.add_task(task_runner.run_remove, task_id, request)
|
||||||
|
return {"taskId": task_id, "status": "queued"}
|
||||||
38
agent/app/api/health.py
Normal file
38
agent/app/api/health.py
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import platform
|
||||||
|
import shutil
|
||||||
|
import socket
|
||||||
|
|
||||||
|
from fastapi import APIRouter
|
||||||
|
|
||||||
|
from app.config import settings
|
||||||
|
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/health")
|
||||||
|
def health() -> dict[str, str]:
|
||||||
|
return {
|
||||||
|
"status": "online",
|
||||||
|
"agentVersion": settings.agent_version,
|
||||||
|
"hostname": socket.gethostname(),
|
||||||
|
"os": platform.platform(),
|
||||||
|
"architecture": platform.machine(),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/system-info")
|
||||||
|
def system_info() -> dict[str, str]:
|
||||||
|
disk = shutil.disk_usage("/")
|
||||||
|
memory_total = "unknown"
|
||||||
|
return {
|
||||||
|
"hostname": socket.gethostname(),
|
||||||
|
"os": platform.platform(),
|
||||||
|
"kernel": platform.release(),
|
||||||
|
"architecture": platform.machine(),
|
||||||
|
"diskFree": f"{disk.free // (1024 ** 3)}GB",
|
||||||
|
"memoryTotal": memory_total,
|
||||||
|
}
|
||||||
|
|
||||||
40
agent/app/api/services.py
Normal file
40
agent/app/api/services.py
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from fastapi import APIRouter
|
||||||
|
|
||||||
|
from app.core.command_runner import CommandRunner
|
||||||
|
from app.core.service_manager import ServiceManager
|
||||||
|
from app.models.schemas import ServiceRequest
|
||||||
|
from app.storage.repository import Repository
|
||||||
|
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/services", tags=["services"])
|
||||||
|
|
||||||
|
|
||||||
|
def _manager() -> ServiceManager:
|
||||||
|
return ServiceManager(CommandRunner(Repository()))
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/start")
|
||||||
|
def start_service(request: ServiceRequest) -> dict[str, str]:
|
||||||
|
_manager().start_service(request.service_name)
|
||||||
|
return {"serviceName": request.service_name, "status": "started"}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/stop")
|
||||||
|
def stop_service(request: ServiceRequest) -> dict[str, str]:
|
||||||
|
_manager().stop_service(request.service_name)
|
||||||
|
return {"serviceName": request.service_name, "status": "stopped"}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/restart")
|
||||||
|
def restart_service(request: ServiceRequest) -> dict[str, str]:
|
||||||
|
_manager().restart_service(request.service_name)
|
||||||
|
return {"serviceName": request.service_name, "status": "restarted"}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{service_name}/status")
|
||||||
|
def service_status(service_name: str) -> dict[str, object]:
|
||||||
|
request = ServiceRequest(serviceName=service_name)
|
||||||
|
return _manager().get_service_status(request.service_name)
|
||||||
|
|
||||||
75
agent/app/api/tasks.py
Normal file
75
agent/app/api/tasks.py
Normal file
@@ -0,0 +1,75 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from fastapi import APIRouter, HTTPException
|
||||||
|
|
||||||
|
from app.storage.repository import Repository
|
||||||
|
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/tasks", tags=["tasks"])
|
||||||
|
repository = Repository()
|
||||||
|
|
||||||
|
|
||||||
|
def _task_response(row: dict) -> dict:
|
||||||
|
return {
|
||||||
|
"taskId": row["id"],
|
||||||
|
"type": row["type"],
|
||||||
|
"appId": row["app_id"],
|
||||||
|
"appName": row["app_name"],
|
||||||
|
"status": row["status"],
|
||||||
|
"progress": row["progress"],
|
||||||
|
"currentStep": row["current_step"],
|
||||||
|
"currentComponentId": row["current_component_id"],
|
||||||
|
"errorMessage": row["error_message"],
|
||||||
|
"createdAt": row["created_at"],
|
||||||
|
"startedAt": row["started_at"],
|
||||||
|
"finishedAt": row["finished_at"],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{task_id}")
|
||||||
|
def get_task(task_id: str) -> dict:
|
||||||
|
task = repository.get_task(task_id)
|
||||||
|
if not task:
|
||||||
|
raise HTTPException(status_code=404, detail="Task not found")
|
||||||
|
return _task_response(task)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{task_id}/logs")
|
||||||
|
def get_task_logs(task_id: str) -> dict:
|
||||||
|
if not repository.get_task(task_id):
|
||||||
|
raise HTTPException(status_code=404, detail="Task not found")
|
||||||
|
return {
|
||||||
|
"taskId": task_id,
|
||||||
|
"logs": [
|
||||||
|
{
|
||||||
|
"time": item["timestamp"],
|
||||||
|
"level": item["level"],
|
||||||
|
"message": item["message"],
|
||||||
|
}
|
||||||
|
for item in repository.get_task_logs(task_id)
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{task_id}/components")
|
||||||
|
def get_task_components(task_id: str) -> dict:
|
||||||
|
if not repository.get_task(task_id):
|
||||||
|
raise HTTPException(status_code=404, detail="Task not found")
|
||||||
|
return {
|
||||||
|
"taskId": task_id,
|
||||||
|
"components": [
|
||||||
|
{
|
||||||
|
"componentId": item["component_id"],
|
||||||
|
"type": item["type"],
|
||||||
|
"status": item["status"],
|
||||||
|
"progress": item["progress"],
|
||||||
|
"currentStep": item["current_step"],
|
||||||
|
"errorMessage": item["error_message"],
|
||||||
|
"serviceCheckStatus": item["service_check_status"],
|
||||||
|
"serviceChecks": item["service_checks"],
|
||||||
|
"startedAt": item["started_at"],
|
||||||
|
"finishedAt": item["finished_at"],
|
||||||
|
}
|
||||||
|
for item in repository.get_task_components(task_id)
|
||||||
|
],
|
||||||
|
}
|
||||||
108
agent/app/config.py
Normal file
108
agent/app/config.py
Normal file
@@ -0,0 +1,108 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from functools import lru_cache
|
||||||
|
from pathlib import Path
|
||||||
|
from urllib.parse import urlparse
|
||||||
|
|
||||||
|
|
||||||
|
def _csv(value: str | None, fallback: list[str]) -> list[str]:
|
||||||
|
if not value:
|
||||||
|
return fallback
|
||||||
|
return [item.strip() for item in value.split(",") if item.strip()]
|
||||||
|
|
||||||
|
|
||||||
|
def _csv_with_defaults(value: str | None, defaults: list[str]) -> list[str]:
|
||||||
|
items = _csv(value, [])
|
||||||
|
seen = set(items)
|
||||||
|
for item in defaults:
|
||||||
|
if item not in seen:
|
||||||
|
items.append(item)
|
||||||
|
seen.add(item)
|
||||||
|
return items
|
||||||
|
|
||||||
|
|
||||||
|
def _default_allowed_download_hosts(base_url: str) -> list[str]:
|
||||||
|
parsed = urlparse(base_url)
|
||||||
|
if parsed.hostname:
|
||||||
|
return [parsed.hostname]
|
||||||
|
return ["package.pnkr.cloud"]
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Settings:
|
||||||
|
agent_version: str
|
||||||
|
host: str
|
||||||
|
port: int
|
||||||
|
robot_package_base_url: str
|
||||||
|
allowed_origins: list[str]
|
||||||
|
allowed_download_hosts: list[str]
|
||||||
|
allowed_apt_packages: list[str]
|
||||||
|
allowed_docker_registries: list[str]
|
||||||
|
cache_dir: Path
|
||||||
|
app_dir: Path
|
||||||
|
log_dir: Path
|
||||||
|
db_path: Path
|
||||||
|
allow_remove: bool
|
||||||
|
allow_purge: bool
|
||||||
|
allow_docker: bool
|
||||||
|
allow_docker_compose: bool
|
||||||
|
auto_install_docker: bool
|
||||||
|
command_timeout_seconds: int
|
||||||
|
|
||||||
|
|
||||||
|
def _bool(name: str, default: bool) -> bool:
|
||||||
|
value = os.getenv(name)
|
||||||
|
if value is None:
|
||||||
|
return default
|
||||||
|
return value.strip().lower() in {"1", "true", "yes", "on"}
|
||||||
|
|
||||||
|
|
||||||
|
@lru_cache(maxsize=1)
|
||||||
|
def get_settings() -> Settings:
|
||||||
|
robot_package_base_url = os.getenv("ROBOT_PACKAGE_BASE_URL", "https://package.pnkr.cloud").rstrip("/")
|
||||||
|
return Settings(
|
||||||
|
agent_version=os.getenv("AGENT_VERSION", "1.0.4"),
|
||||||
|
host=os.getenv("AGENT_HOST", "0.0.0.0"),
|
||||||
|
port=int(os.getenv("AGENT_PORT", "5010")),
|
||||||
|
robot_package_base_url=robot_package_base_url,
|
||||||
|
allowed_origins=_csv(
|
||||||
|
os.getenv("ALLOWED_ORIGINS"),
|
||||||
|
[
|
||||||
|
"https://app.pnkr.cloud",
|
||||||
|
"https://package.pnkr.cloud",
|
||||||
|
"http://localhost:3000",
|
||||||
|
"http://127.0.0.1:3000",
|
||||||
|
"http://localhost:5173",
|
||||||
|
"http://127.0.0.1:5173",
|
||||||
|
"http://localhost:8080",
|
||||||
|
"http://127.0.0.1:8080",
|
||||||
|
],
|
||||||
|
),
|
||||||
|
allowed_download_hosts=_csv(
|
||||||
|
os.getenv("ALLOWED_DOWNLOAD_HOSTS"),
|
||||||
|
_default_allowed_download_hosts(robot_package_base_url),
|
||||||
|
),
|
||||||
|
allowed_apt_packages=_csv(
|
||||||
|
os.getenv("ALLOWED_APT_PACKAGES"),
|
||||||
|
["*"],
|
||||||
|
),
|
||||||
|
allowed_docker_registries=_csv_with_defaults(
|
||||||
|
os.getenv("ALLOWED_DOCKER_REGISTRIES"),
|
||||||
|
["registry.robot.package", "docker.io"],
|
||||||
|
),
|
||||||
|
cache_dir=Path(os.getenv("CACHE_DIR", "/var/cache/local-installer-agent/packages")),
|
||||||
|
app_dir=Path(os.getenv("APP_DIR", "/opt/robot-apps")),
|
||||||
|
log_dir=Path(os.getenv("LOG_DIR", "/var/log/local-installer-agent")),
|
||||||
|
db_path=Path(os.getenv("DB_PATH", "/var/lib/local-installer-agent/agent.db")),
|
||||||
|
allow_remove=_bool("ALLOW_REMOVE", True),
|
||||||
|
allow_purge=_bool("ALLOW_PURGE", True),
|
||||||
|
allow_docker=_bool("ALLOW_DOCKER", True),
|
||||||
|
allow_docker_compose=_bool("ALLOW_DOCKER_COMPOSE", False),
|
||||||
|
auto_install_docker=_bool("AUTO_INSTALL_DOCKER", True),
|
||||||
|
command_timeout_seconds=int(os.getenv("COMMAND_TIMEOUT_SECONDS", "900")),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
settings = get_settings()
|
||||||
2
agent/app/core/__init__.py
Normal file
2
agent/app/core/__init__.py
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
"""Core installers and task orchestration."""
|
||||||
|
|
||||||
17
agent/app/core/checksum.py
Normal file
17
agent/app/core/checksum.py
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
def sha256_file(file_path: Path) -> str:
|
||||||
|
digest = hashlib.sha256()
|
||||||
|
with file_path.open("rb") as handle:
|
||||||
|
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
|
||||||
|
digest.update(chunk)
|
||||||
|
return digest.hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def verify_sha256(file_path: Path, expected: str) -> bool:
|
||||||
|
return sha256_file(file_path).lower() == expected.lower()
|
||||||
|
|
||||||
87
agent/app/core/command_runner.py
Normal file
87
agent/app/core/command_runner.py
Normal file
@@ -0,0 +1,87 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import subprocess
|
||||||
|
from collections.abc import Mapping
|
||||||
|
|
||||||
|
from app.config import settings
|
||||||
|
from app.storage.repository import Repository
|
||||||
|
|
||||||
|
|
||||||
|
def _tail_output(label: str, output: str, line_limit: int = 6) -> str:
|
||||||
|
lines = [line.strip() for line in output.splitlines() if line.strip()]
|
||||||
|
if not lines:
|
||||||
|
return ""
|
||||||
|
return f"{label}: {' | '.join(lines[-line_limit:])}"
|
||||||
|
|
||||||
|
|
||||||
|
def _command_output_summary(stdout: str, stderr: str) -> str:
|
||||||
|
parts = [
|
||||||
|
part
|
||||||
|
for part in (
|
||||||
|
_tail_output("stderr", stderr),
|
||||||
|
_tail_output("stdout", stdout),
|
||||||
|
)
|
||||||
|
if part
|
||||||
|
]
|
||||||
|
summary = " ; ".join(parts)
|
||||||
|
return summary[:1600]
|
||||||
|
|
||||||
|
|
||||||
|
class CommandError(RuntimeError):
|
||||||
|
def __init__(self, command: list[str], returncode: int, stdout: str, stderr: str) -> None:
|
||||||
|
message = f"Command failed with exit code {returncode}: {' '.join(command)}"
|
||||||
|
output_summary = _command_output_summary(stdout, stderr)
|
||||||
|
if output_summary:
|
||||||
|
message = f"{message}. Last output: {output_summary}"
|
||||||
|
super().__init__(message)
|
||||||
|
self.command = command
|
||||||
|
self.returncode = returncode
|
||||||
|
self.stdout = stdout
|
||||||
|
self.stderr = stderr
|
||||||
|
|
||||||
|
|
||||||
|
class CommandRunner:
|
||||||
|
def __init__(self, repository: Repository, task_id: str | None = None) -> None:
|
||||||
|
self.repository = repository
|
||||||
|
self.task_id = task_id
|
||||||
|
|
||||||
|
def run(
|
||||||
|
self,
|
||||||
|
command: list[str],
|
||||||
|
timeout: int | None = None,
|
||||||
|
env: Mapping[str, str] | None = None,
|
||||||
|
log_output: bool = True,
|
||||||
|
) -> subprocess.CompletedProcess[str]:
|
||||||
|
if self.task_id:
|
||||||
|
self.repository.add_log(self.task_id, "debug", f"Running command: {' '.join(command)}")
|
||||||
|
|
||||||
|
command_env = os.environ.copy()
|
||||||
|
if env:
|
||||||
|
command_env.update(env)
|
||||||
|
|
||||||
|
try:
|
||||||
|
result = subprocess.run(
|
||||||
|
command,
|
||||||
|
check=False,
|
||||||
|
capture_output=True,
|
||||||
|
env=command_env,
|
||||||
|
stdin=subprocess.DEVNULL,
|
||||||
|
text=True,
|
||||||
|
timeout=timeout or settings.command_timeout_seconds,
|
||||||
|
)
|
||||||
|
except subprocess.TimeoutExpired as error:
|
||||||
|
if self.task_id:
|
||||||
|
self.repository.add_log(self.task_id, "error", f"Command timed out: {' '.join(command)}")
|
||||||
|
raise CommandError(command, 124, error.stdout or "", error.stderr or "") from error
|
||||||
|
|
||||||
|
if self.task_id and log_output:
|
||||||
|
for line in result.stdout.splitlines():
|
||||||
|
self.repository.add_log(self.task_id, "debug", line)
|
||||||
|
for line in result.stderr.splitlines():
|
||||||
|
self.repository.add_log(self.task_id, "warning", line)
|
||||||
|
|
||||||
|
if result.returncode != 0:
|
||||||
|
raise CommandError(command, result.returncode, result.stdout, result.stderr)
|
||||||
|
|
||||||
|
return result
|
||||||
190
agent/app/core/docker_installer.py
Normal file
190
agent/app/core/docker_installer.py
Normal file
@@ -0,0 +1,190 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import shutil
|
||||||
|
|
||||||
|
from app.core.command_runner import CommandError, CommandRunner
|
||||||
|
|
||||||
|
|
||||||
|
DOCKER_REQUIRED_MESSAGE = "Docker runtime is required"
|
||||||
|
|
||||||
|
|
||||||
|
def image_reference(component: dict) -> str:
|
||||||
|
image = component["image"]
|
||||||
|
digest = component.get("digest")
|
||||||
|
tag = component.get("tag")
|
||||||
|
|
||||||
|
if "@" in image:
|
||||||
|
return image
|
||||||
|
if digest:
|
||||||
|
return f"{_image_without_tag(image)}@{digest}"
|
||||||
|
if _image_has_tag(image) or not tag:
|
||||||
|
return image
|
||||||
|
return f"{image}:{tag}"
|
||||||
|
|
||||||
|
|
||||||
|
def _image_has_tag(image: str) -> bool:
|
||||||
|
last_slash = image.rfind("/")
|
||||||
|
last_colon = image.rfind(":")
|
||||||
|
return last_colon > last_slash
|
||||||
|
|
||||||
|
|
||||||
|
def _image_without_tag(image: str) -> str:
|
||||||
|
if not _image_has_tag(image):
|
||||||
|
return image
|
||||||
|
return image[: image.rfind(":")]
|
||||||
|
|
||||||
|
|
||||||
|
class DockerInstaller:
|
||||||
|
def __init__(self, command_runner: CommandRunner) -> None:
|
||||||
|
self.command_runner = command_runner
|
||||||
|
|
||||||
|
def ensure_runtime(self, auto_install: bool = False) -> None:
|
||||||
|
if not shutil.which("docker"):
|
||||||
|
if not auto_install:
|
||||||
|
raise RuntimeError(DOCKER_REQUIRED_MESSAGE)
|
||||||
|
self.install_runtime()
|
||||||
|
|
||||||
|
try:
|
||||||
|
self._verify_runtime()
|
||||||
|
return
|
||||||
|
except CommandError as error:
|
||||||
|
self._log("warning", self._runtime_error_message(error))
|
||||||
|
|
||||||
|
self._start_runtime()
|
||||||
|
try:
|
||||||
|
self._verify_runtime()
|
||||||
|
except CommandError as error:
|
||||||
|
raise RuntimeError(self._runtime_error_message(error)) from error
|
||||||
|
|
||||||
|
def install_runtime(self) -> None:
|
||||||
|
if not shutil.which("apt-get"):
|
||||||
|
raise RuntimeError(
|
||||||
|
f"{DOCKER_REQUIRED_MESSAGE}. Install Docker Engine on this client or disable Docker packages."
|
||||||
|
)
|
||||||
|
|
||||||
|
self._log("info", "Docker runtime not found; installing docker.io")
|
||||||
|
try:
|
||||||
|
self.command_runner.run(["apt-get", "update"], timeout=600)
|
||||||
|
self.command_runner.run(
|
||||||
|
["env", "DEBIAN_FRONTEND=noninteractive", "apt-get", "install", "-y", "docker.io"],
|
||||||
|
timeout=1200,
|
||||||
|
)
|
||||||
|
except CommandError as error:
|
||||||
|
raise RuntimeError(
|
||||||
|
f"{DOCKER_REQUIRED_MESSAGE}: failed to install docker.io with apt-get: "
|
||||||
|
f"{self._command_error_detail(error)}"
|
||||||
|
) from error
|
||||||
|
self._start_runtime()
|
||||||
|
|
||||||
|
def _verify_runtime(self) -> None:
|
||||||
|
self.command_runner.run(["docker", "version", "--format", "{{.Server.Version}}"])
|
||||||
|
|
||||||
|
def _start_runtime(self) -> None:
|
||||||
|
if shutil.which("systemctl"):
|
||||||
|
try:
|
||||||
|
self.command_runner.run(["systemctl", "enable", "--now", "docker"], timeout=120)
|
||||||
|
return
|
||||||
|
except CommandError as error:
|
||||||
|
self._log("warning", f"Could not start Docker with systemctl: {self._command_error_detail(error)}")
|
||||||
|
|
||||||
|
if shutil.which("service"):
|
||||||
|
try:
|
||||||
|
self.command_runner.run(["service", "docker", "start"], timeout=120)
|
||||||
|
except CommandError as error:
|
||||||
|
self._log("warning", f"Could not start Docker service: {self._command_error_detail(error)}")
|
||||||
|
|
||||||
|
def _runtime_error_message(self, error: CommandError) -> str:
|
||||||
|
detail = self._command_error_detail(error)
|
||||||
|
return f"{DOCKER_REQUIRED_MESSAGE}: {detail}" if detail else DOCKER_REQUIRED_MESSAGE
|
||||||
|
|
||||||
|
def _command_error_detail(self, error: CommandError) -> str:
|
||||||
|
output = (error.stderr or error.stdout or "").strip()
|
||||||
|
if not output:
|
||||||
|
return str(error)
|
||||||
|
return output.splitlines()[-1].strip()
|
||||||
|
|
||||||
|
def _log(self, level: str, message: str) -> None:
|
||||||
|
if self.command_runner.task_id:
|
||||||
|
self.command_runner.repository.add_log(self.command_runner.task_id, level, message)
|
||||||
|
|
||||||
|
def pull_image(self, reference: str) -> None:
|
||||||
|
self.command_runner.run(["docker", "pull", reference])
|
||||||
|
|
||||||
|
def recreate_container(self, app_id: str, component: dict) -> None:
|
||||||
|
container_name = component["containerName"]
|
||||||
|
reference = image_reference(component)
|
||||||
|
|
||||||
|
self.remove_container(container_name)
|
||||||
|
|
||||||
|
command = [
|
||||||
|
"docker",
|
||||||
|
"run",
|
||||||
|
"-d",
|
||||||
|
"--name",
|
||||||
|
container_name,
|
||||||
|
"--restart",
|
||||||
|
component.get("restartPolicy", "unless-stopped"),
|
||||||
|
"--label",
|
||||||
|
f"local-installer-agent.app-id={app_id}",
|
||||||
|
"--label",
|
||||||
|
f"local-installer-agent.component-id={component['componentId']}",
|
||||||
|
]
|
||||||
|
|
||||||
|
for name, value in sorted((component.get("env") or {}).items()):
|
||||||
|
command.extend(["-e", f"{name}={value}"])
|
||||||
|
for port in component.get("ports") or []:
|
||||||
|
command.extend(["-p", port])
|
||||||
|
for volume in component.get("volumes") or []:
|
||||||
|
command.extend(["-v", volume])
|
||||||
|
|
||||||
|
command.append(reference)
|
||||||
|
self.command_runner.run(command)
|
||||||
|
|
||||||
|
def remove_container(self, container_name: str, remove_volumes: bool = False) -> None:
|
||||||
|
result = self.command_runner.run([
|
||||||
|
"docker",
|
||||||
|
"ps",
|
||||||
|
"-aq",
|
||||||
|
"--filter",
|
||||||
|
f"name=^/{container_name}$",
|
||||||
|
])
|
||||||
|
if result.stdout.strip():
|
||||||
|
command = ["docker", "rm", "-f"]
|
||||||
|
if remove_volumes:
|
||||||
|
command.append("-v")
|
||||||
|
command.append(container_name)
|
||||||
|
self.command_runner.run(command)
|
||||||
|
|
||||||
|
def remove_labeled_containers(self, app_id: str, component_id: str, remove_volumes: bool = False) -> None:
|
||||||
|
result = self.command_runner.run([
|
||||||
|
"docker",
|
||||||
|
"ps",
|
||||||
|
"-aq",
|
||||||
|
"--filter",
|
||||||
|
f"label=local-installer-agent.app-id={app_id}",
|
||||||
|
"--filter",
|
||||||
|
f"label=local-installer-agent.component-id={component_id}",
|
||||||
|
])
|
||||||
|
container_ids = [line.strip() for line in result.stdout.splitlines() if line.strip()]
|
||||||
|
if not container_ids:
|
||||||
|
return
|
||||||
|
|
||||||
|
command = ["docker", "rm", "-f"]
|
||||||
|
if remove_volumes:
|
||||||
|
command.append("-v")
|
||||||
|
command.extend(container_ids)
|
||||||
|
self.command_runner.run(command)
|
||||||
|
|
||||||
|
def remove_image(self, reference: str) -> None:
|
||||||
|
self.command_runner.run(["docker", "image", "rm", reference])
|
||||||
|
|
||||||
|
def assert_container_running(self, container_name: str) -> None:
|
||||||
|
result = self.command_runner.run([
|
||||||
|
"docker",
|
||||||
|
"inspect",
|
||||||
|
"-f",
|
||||||
|
"{{.State.Running}}",
|
||||||
|
container_name,
|
||||||
|
])
|
||||||
|
if result.stdout.strip().lower() != "true":
|
||||||
|
raise RuntimeError(f"Docker container is not running: {container_name}")
|
||||||
83
agent/app/core/downloader.py
Normal file
83
agent/app/core/downloader.py
Normal file
@@ -0,0 +1,83 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from email.message import Message
|
||||||
|
import re
|
||||||
|
from pathlib import Path
|
||||||
|
from urllib.parse import unquote, urlparse
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
from app.config import settings
|
||||||
|
from app.storage.repository import Repository
|
||||||
|
from app.utils.validators import validate_url_host
|
||||||
|
|
||||||
|
|
||||||
|
SAFE_FILE_RE = re.compile(r"[^a-zA-Z0-9._+-]+")
|
||||||
|
|
||||||
|
|
||||||
|
def _sanitize_file_name(value: str, fallback: str = "package.deb") -> str:
|
||||||
|
name = SAFE_FILE_RE.sub("-", value).strip("-.")
|
||||||
|
return name or fallback
|
||||||
|
|
||||||
|
|
||||||
|
def _safe_url_file_name(url: str) -> str:
|
||||||
|
parsed = urlparse(url)
|
||||||
|
name = Path(unquote(parsed.path)).name or "package.deb"
|
||||||
|
if name == "download":
|
||||||
|
parts = [part for part in parsed.path.split("/") if part]
|
||||||
|
name = "-".join(parts[-3:]) if len(parts) >= 3 else name
|
||||||
|
return _sanitize_file_name(name)
|
||||||
|
|
||||||
|
|
||||||
|
def _content_disposition_file_name(value: str) -> str:
|
||||||
|
if not value:
|
||||||
|
return ""
|
||||||
|
|
||||||
|
message = Message()
|
||||||
|
message["content-disposition"] = value
|
||||||
|
return _sanitize_file_name(message.get_filename() or "", fallback="")
|
||||||
|
|
||||||
|
|
||||||
|
def _response_file_name(url: str, response: httpx.Response) -> str:
|
||||||
|
name = _content_disposition_file_name(response.headers.get("content-disposition", ""))
|
||||||
|
if not name:
|
||||||
|
name = _safe_url_file_name(str(response.url) or url)
|
||||||
|
|
||||||
|
content_type = response.headers.get("content-type", "").split(";", 1)[0].strip().lower()
|
||||||
|
if content_type == "application/vnd.debian.binary-package" and not name.lower().endswith(".deb"):
|
||||||
|
name = f"{name}.deb"
|
||||||
|
|
||||||
|
return name
|
||||||
|
|
||||||
|
|
||||||
|
class Downloader:
|
||||||
|
def __init__(self, repository: Repository, task_id: str) -> None:
|
||||||
|
self.repository = repository
|
||||||
|
self.task_id = task_id
|
||||||
|
|
||||||
|
def download(self, url: str) -> Path:
|
||||||
|
validate_url_host(url, settings.allowed_download_hosts)
|
||||||
|
settings.cache_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
self.repository.add_log(self.task_id, "info", f"Downloading {url}")
|
||||||
|
with httpx.stream("GET", url, follow_redirects=True, timeout=120) as response:
|
||||||
|
response.raise_for_status()
|
||||||
|
self._validate_response(url, response)
|
||||||
|
destination = settings.cache_dir / _response_file_name(url, response)
|
||||||
|
with destination.open("wb") as handle:
|
||||||
|
for chunk in response.iter_bytes():
|
||||||
|
handle.write(chunk)
|
||||||
|
|
||||||
|
self.repository.add_log(self.task_id, "info", f"Downloaded to {destination}")
|
||||||
|
return destination
|
||||||
|
|
||||||
|
def _validate_response(self, requested_url: str, response: httpx.Response) -> None:
|
||||||
|
final_url = str(response.url)
|
||||||
|
validate_url_host(final_url, settings.allowed_download_hosts)
|
||||||
|
|
||||||
|
content_type = response.headers.get("content-type", "").split(";", 1)[0].strip().lower()
|
||||||
|
if content_type in {"text/html", "text/plain"}:
|
||||||
|
raise ValueError(
|
||||||
|
"download did not return a package file "
|
||||||
|
f"(requested {requested_url}, final {final_url}, content-type {content_type or 'unknown'})"
|
||||||
|
)
|
||||||
182
agent/app/core/installer.py
Normal file
182
agent/app/core/installer.py
Normal file
@@ -0,0 +1,182 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import time
|
||||||
|
from pathlib import Path, PurePosixPath
|
||||||
|
|
||||||
|
from app.core.command_runner import CommandError, CommandRunner
|
||||||
|
|
||||||
|
|
||||||
|
APT_DPKG_OPTIONS = [
|
||||||
|
"-o",
|
||||||
|
"Dpkg::Use-Pty=0",
|
||||||
|
"-o",
|
||||||
|
"Dpkg::Options::=--force-confdef",
|
||||||
|
"-o",
|
||||||
|
"Dpkg::Options::=--force-confold",
|
||||||
|
]
|
||||||
|
|
||||||
|
APT_NONINTERACTIVE_ENV = {
|
||||||
|
"DEBIAN_FRONTEND": "noninteractive",
|
||||||
|
"DEBCONF_NONINTERACTIVE_SEEN": "true",
|
||||||
|
"APT_LISTCHANGES_FRONTEND": "none",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_deb_control_output(output: str) -> dict[str, str]:
|
||||||
|
metadata: dict[str, str] = {}
|
||||||
|
|
||||||
|
for line in output.splitlines():
|
||||||
|
key, separator, value = line.partition(":")
|
||||||
|
if not separator:
|
||||||
|
continue
|
||||||
|
|
||||||
|
normalized_key = key.strip().lower()
|
||||||
|
if normalized_key in {"package", "version", "architecture"}:
|
||||||
|
metadata[normalized_key] = value.strip()
|
||||||
|
|
||||||
|
return metadata
|
||||||
|
|
||||||
|
|
||||||
|
class DebInstaller:
|
||||||
|
def __init__(self, command_runner: CommandRunner) -> None:
|
||||||
|
self.command_runner = command_runner
|
||||||
|
|
||||||
|
def get_deb_metadata(self, file_path: Path) -> dict[str, str]:
|
||||||
|
result = self.command_runner.run([
|
||||||
|
"dpkg-deb",
|
||||||
|
"-f",
|
||||||
|
str(file_path),
|
||||||
|
"Package",
|
||||||
|
"Version",
|
||||||
|
"Architecture",
|
||||||
|
])
|
||||||
|
metadata = _parse_deb_control_output(result.stdout)
|
||||||
|
missing_fields = [
|
||||||
|
field
|
||||||
|
for field in ("package", "version", "architecture")
|
||||||
|
if not metadata.get(field)
|
||||||
|
]
|
||||||
|
|
||||||
|
if missing_fields:
|
||||||
|
raise ValueError(
|
||||||
|
"Downloaded .deb is missing metadata fields: "
|
||||||
|
f"{', '.join(missing_fields)}"
|
||||||
|
)
|
||||||
|
|
||||||
|
return metadata
|
||||||
|
|
||||||
|
def install_deb(self, file_path: Path) -> None:
|
||||||
|
self.command_runner.run(
|
||||||
|
[
|
||||||
|
"apt-get",
|
||||||
|
*APT_DPKG_OPTIONS,
|
||||||
|
"install",
|
||||||
|
"--yes",
|
||||||
|
str(file_path),
|
||||||
|
],
|
||||||
|
env=APT_NONINTERACTIVE_ENV,
|
||||||
|
)
|
||||||
|
|
||||||
|
def remove_package(self, package_name: str, purge: bool = False) -> None:
|
||||||
|
action = "purge" if purge else "remove"
|
||||||
|
self.command_runner.run(
|
||||||
|
["apt-get", *APT_DPKG_OPTIONS, action, "--yes", package_name],
|
||||||
|
env=APT_NONINTERACTIVE_ENV,
|
||||||
|
)
|
||||||
|
|
||||||
|
def cleanup_after_remove(self, purge: bool = False) -> None:
|
||||||
|
autoremove_command = ["apt-get", *APT_DPKG_OPTIONS, "autoremove", "--yes"]
|
||||||
|
if purge:
|
||||||
|
autoremove_command.append("--purge")
|
||||||
|
self.command_runner.run(autoremove_command, env=APT_NONINTERACTIVE_ENV)
|
||||||
|
self.command_runner.run(["apt-get", "clean"], env=APT_NONINTERACTIVE_ENV)
|
||||||
|
|
||||||
|
def get_package_version(self, package_name: str) -> str | None:
|
||||||
|
result = self.command_runner.run(["dpkg-query", "-W", "-f=${Version}", package_name])
|
||||||
|
version = result.stdout.strip()
|
||||||
|
return version or None
|
||||||
|
|
||||||
|
def check_package_installed(self, package_name: str) -> bool:
|
||||||
|
try:
|
||||||
|
self.get_package_version(package_name)
|
||||||
|
return True
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
class AptInstaller(DebInstaller):
|
||||||
|
def update_package_index(self) -> None:
|
||||||
|
self.command_runner.run(
|
||||||
|
["apt-get", "update"],
|
||||||
|
timeout=600,
|
||||||
|
env=APT_NONINTERACTIVE_ENV,
|
||||||
|
)
|
||||||
|
|
||||||
|
def install_package(self, package_name: str) -> None:
|
||||||
|
self.command_runner.run(
|
||||||
|
[
|
||||||
|
"apt-get",
|
||||||
|
*APT_DPKG_OPTIONS,
|
||||||
|
"install",
|
||||||
|
"--yes",
|
||||||
|
package_name,
|
||||||
|
],
|
||||||
|
timeout=1200,
|
||||||
|
env=APT_NONINTERACTIVE_ENV,
|
||||||
|
)
|
||||||
|
|
||||||
|
def discover_service_units(self, package_name: str) -> list[str]:
|
||||||
|
"""Return concrete systemd service units shipped by an installed package.
|
||||||
|
|
||||||
|
The package name is already syntax-validated by the manifest validator. It
|
||||||
|
is passed as a single argv item and no shell expansion is performed.
|
||||||
|
Template units are omitted because they cannot be meaningfully checked
|
||||||
|
without an instance name.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
result = self.command_runner.run(
|
||||||
|
["dpkg-query", "-L", package_name],
|
||||||
|
timeout=30,
|
||||||
|
log_output=False,
|
||||||
|
)
|
||||||
|
except CommandError:
|
||||||
|
return []
|
||||||
|
|
||||||
|
service_names: set[str] = set()
|
||||||
|
for raw_path in result.stdout.splitlines():
|
||||||
|
path = raw_path.strip()
|
||||||
|
if not path.endswith(".service"):
|
||||||
|
continue
|
||||||
|
if "/systemd/system/" not in path:
|
||||||
|
continue
|
||||||
|
|
||||||
|
service_name = PurePosixPath(path).name
|
||||||
|
if "@" in service_name:
|
||||||
|
continue
|
||||||
|
service_names.add(service_name)
|
||||||
|
|
||||||
|
return sorted(service_names)
|
||||||
|
|
||||||
|
def wait_for_postgresql(
|
||||||
|
self,
|
||||||
|
attempts: int = 6,
|
||||||
|
delay_seconds: float = 2.0,
|
||||||
|
) -> None:
|
||||||
|
last_error: CommandError | None = None
|
||||||
|
for attempt in range(1, attempts + 1):
|
||||||
|
try:
|
||||||
|
self.command_runner.run(["pg_isready", "--timeout=5"], timeout=10)
|
||||||
|
return
|
||||||
|
except CommandError as error:
|
||||||
|
last_error = error
|
||||||
|
if attempt < attempts:
|
||||||
|
time.sleep(delay_seconds)
|
||||||
|
|
||||||
|
raise RuntimeError("PostgreSQL did not become ready after installation") from last_error
|
||||||
|
|
||||||
|
def is_postgresql_ready(self) -> bool:
|
||||||
|
try:
|
||||||
|
self.command_runner.run(["pg_isready", "--timeout=5"], timeout=10)
|
||||||
|
return True
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
56
agent/app/core/manifest_client.py
Normal file
56
agent/app/core/manifest_client.py
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from urllib.parse import quote
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
from app.config import settings
|
||||||
|
|
||||||
|
|
||||||
|
class ManifestClient:
|
||||||
|
def fetch_manifest(self, app_id: str, version: str) -> dict:
|
||||||
|
app_id_part = quote(app_id, safe="")
|
||||||
|
version_part = quote(version, safe="")
|
||||||
|
url = f"{settings.robot_package_base_url}/api/apps/{app_id_part}/versions/{version_part}/manifest"
|
||||||
|
response = httpx.get(url, follow_redirects=True, timeout=30)
|
||||||
|
if response.is_error:
|
||||||
|
raise RuntimeError(_format_manifest_error(response))
|
||||||
|
return response.json()
|
||||||
|
|
||||||
|
|
||||||
|
def _format_manifest_error(response: httpx.Response) -> str:
|
||||||
|
base_message = f"Manifest request failed with HTTP {response.status_code}: {response.url}"
|
||||||
|
|
||||||
|
try:
|
||||||
|
payload = response.json()
|
||||||
|
except ValueError:
|
||||||
|
detail = response.text.strip()
|
||||||
|
return f"{base_message}. {detail}" if detail else base_message
|
||||||
|
|
||||||
|
if not isinstance(payload, dict):
|
||||||
|
return base_message
|
||||||
|
|
||||||
|
message_parts = []
|
||||||
|
error = str(payload.get("error") or "").strip()
|
||||||
|
detail = str(payload.get("detail") or "").strip()
|
||||||
|
|
||||||
|
if error:
|
||||||
|
message_parts.append(error)
|
||||||
|
if detail:
|
||||||
|
message_parts.append(detail)
|
||||||
|
|
||||||
|
missing_files = payload.get("missingPackageFiles")
|
||||||
|
if isinstance(missing_files, list) and missing_files:
|
||||||
|
descriptions = []
|
||||||
|
for item in missing_files:
|
||||||
|
if not isinstance(item, dict):
|
||||||
|
continue
|
||||||
|
|
||||||
|
package_name = str(item.get("packageName") or item.get("componentId") or "package").strip()
|
||||||
|
version = str(item.get("version") or "").strip()
|
||||||
|
descriptions.append(f"{package_name} {version}".strip())
|
||||||
|
|
||||||
|
if descriptions:
|
||||||
|
message_parts.append(f"Missing package files: {', '.join(descriptions)}")
|
||||||
|
|
||||||
|
return f"{base_message}. {' '.join(message_parts)}" if message_parts else base_message
|
||||||
39
agent/app/core/manifest_validator.py
Normal file
39
agent/app/core/manifest_validator.py
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from app.config import settings
|
||||||
|
from app.models.schemas import AptComponent, AppManifest, DebComponent, DockerComponent
|
||||||
|
from app.utils.validators import validate_docker_registry, validate_url_host
|
||||||
|
|
||||||
|
|
||||||
|
class ManifestValidator:
|
||||||
|
def validate(self, payload: dict) -> dict:
|
||||||
|
manifest = AppManifest.model_validate(payload).model_dump(by_alias=True)
|
||||||
|
components = []
|
||||||
|
for raw_component in manifest["components"]:
|
||||||
|
component_type = raw_component.get("type")
|
||||||
|
if component_type == "deb":
|
||||||
|
component = DebComponent.model_validate(raw_component).model_dump(by_alias=True)
|
||||||
|
validate_url_host(component["downloadUrl"], settings.allowed_download_hosts)
|
||||||
|
components.append(component)
|
||||||
|
elif component_type == "apt":
|
||||||
|
component = AptComponent.model_validate(raw_component).model_dump(by_alias=True)
|
||||||
|
allowed_packages = set(settings.allowed_apt_packages)
|
||||||
|
if "*" not in allowed_packages and component["packageName"] not in allowed_packages:
|
||||||
|
raise ValueError(
|
||||||
|
f"APT package is not allowed: {component['packageName']}"
|
||||||
|
)
|
||||||
|
components.append(component)
|
||||||
|
elif component_type == "docker":
|
||||||
|
if not settings.allow_docker:
|
||||||
|
raise ValueError("Docker components are not enabled on this Agent")
|
||||||
|
component = DockerComponent.model_validate(raw_component).model_dump(by_alias=True)
|
||||||
|
validate_docker_registry(component["image"], settings.allowed_docker_registries)
|
||||||
|
components.append(component)
|
||||||
|
elif component_type == "docker_compose":
|
||||||
|
if not settings.allow_docker_compose:
|
||||||
|
raise ValueError("Docker Compose components are not enabled on this Agent")
|
||||||
|
raise ValueError("Docker Compose components are not implemented on this Agent")
|
||||||
|
else:
|
||||||
|
raise ValueError(f"Unsupported component type: {component_type}")
|
||||||
|
manifest["components"] = sorted(components, key=lambda item: item.get("installOrder", 10))
|
||||||
|
return manifest
|
||||||
93
agent/app/core/service_manager.py
Normal file
93
agent/app/core/service_manager.py
Normal file
@@ -0,0 +1,93 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
from app.core.command_runner import CommandError
|
||||||
|
from app.core.command_runner import CommandRunner
|
||||||
|
|
||||||
|
|
||||||
|
class ServiceManager:
|
||||||
|
def __init__(self, command_runner: CommandRunner) -> None:
|
||||||
|
self.command_runner = command_runner
|
||||||
|
|
||||||
|
def enable_service(self, service_name: str) -> None:
|
||||||
|
self.command_runner.run(["systemctl", "enable", service_name])
|
||||||
|
|
||||||
|
def disable_service(self, service_name: str) -> None:
|
||||||
|
self.command_runner.run(["systemctl", "disable", service_name])
|
||||||
|
|
||||||
|
def start_service(self, service_name: str) -> None:
|
||||||
|
self.command_runner.run(["systemctl", "start", service_name])
|
||||||
|
|
||||||
|
def stop_service(self, service_name: str) -> None:
|
||||||
|
self.command_runner.run(["systemctl", "stop", service_name])
|
||||||
|
|
||||||
|
def restart_service(self, service_name: str) -> None:
|
||||||
|
self.command_runner.run(["systemctl", "restart", service_name])
|
||||||
|
|
||||||
|
def reset_failed(self, service_name: str) -> None:
|
||||||
|
self.command_runner.run(["systemctl", "reset-failed", service_name])
|
||||||
|
|
||||||
|
def assert_service_active(self, service_name: str) -> None:
|
||||||
|
result = self.command_runner.run(["systemctl", "is-active", service_name])
|
||||||
|
if result.stdout.strip() != "active":
|
||||||
|
raise RuntimeError(f"Service is not active: {service_name}")
|
||||||
|
|
||||||
|
def get_service_status(self, service_name: str) -> dict[str, object]:
|
||||||
|
command = [
|
||||||
|
"systemctl",
|
||||||
|
"show",
|
||||||
|
service_name,
|
||||||
|
"--no-pager",
|
||||||
|
"--property=LoadState",
|
||||||
|
"--property=ActiveState",
|
||||||
|
"--property=SubState",
|
||||||
|
"--property=UnitFileState",
|
||||||
|
]
|
||||||
|
error_message: str | None = None
|
||||||
|
try:
|
||||||
|
output = self.command_runner.run(command, timeout=5).stdout
|
||||||
|
except CommandError as error:
|
||||||
|
output = error.stdout
|
||||||
|
error_message = str(error)
|
||||||
|
except Exception as error:
|
||||||
|
output = ""
|
||||||
|
error_message = str(error)
|
||||||
|
|
||||||
|
properties = self._parse_properties(output)
|
||||||
|
load_state = properties.get("LoadState", "unknown") or "unknown"
|
||||||
|
active_state = properties.get("ActiveState", "unknown") or "unknown"
|
||||||
|
sub_state = properties.get("SubState", "unknown") or "unknown"
|
||||||
|
unit_file_state = properties.get("UnitFileState", "unknown") or "unknown"
|
||||||
|
active = load_state == "loaded" and active_state == "active"
|
||||||
|
enabled = unit_file_state in {"enabled", "enabled-runtime"}
|
||||||
|
|
||||||
|
if load_state == "not-found":
|
||||||
|
status = "not-found"
|
||||||
|
elif active_state != "unknown":
|
||||||
|
status = active_state
|
||||||
|
else:
|
||||||
|
status = "unknown"
|
||||||
|
|
||||||
|
return {
|
||||||
|
"serviceName": service_name,
|
||||||
|
"loadState": load_state,
|
||||||
|
"activeState": active_state,
|
||||||
|
"subState": sub_state,
|
||||||
|
"unitFileState": unit_file_state,
|
||||||
|
"active": active,
|
||||||
|
"enabled": enabled,
|
||||||
|
"healthy": active,
|
||||||
|
"status": status,
|
||||||
|
"checkedAt": datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z"),
|
||||||
|
"errorMessage": error_message,
|
||||||
|
}
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _parse_properties(output: str) -> dict[str, str]:
|
||||||
|
properties: dict[str, str] = {}
|
||||||
|
for line in output.splitlines():
|
||||||
|
key, separator, value = line.partition("=")
|
||||||
|
if separator and key:
|
||||||
|
properties[key.strip()] = value.strip()
|
||||||
|
return properties
|
||||||
591
agent/app/core/task_runner.py
Normal file
591
agent/app/core/task_runner.py
Normal file
@@ -0,0 +1,591 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import os
|
||||||
|
import traceback
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from app.config import settings
|
||||||
|
from app.core.checksum import sha256_file
|
||||||
|
from app.core.command_runner import CommandRunner
|
||||||
|
from app.core.downloader import Downloader
|
||||||
|
from app.core.docker_installer import DockerInstaller, image_reference
|
||||||
|
from app.core.installer import AptInstaller, DebInstaller
|
||||||
|
from app.core.manifest_client import ManifestClient
|
||||||
|
from app.core.manifest_validator import ManifestValidator
|
||||||
|
from app.core.service_manager import ServiceManager
|
||||||
|
from app.models.schemas import InstallRequest, RemoveRequest, UpdateRequest
|
||||||
|
from app.storage.repository import Repository, utc_now
|
||||||
|
|
||||||
|
|
||||||
|
APT_SERVICE_POLICIES: dict[str, dict[str, Any]] = {
|
||||||
|
"postgresql": {
|
||||||
|
"managedServices": ["postgresql.service"],
|
||||||
|
"readiness": "postgresql",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class InstalledComponentVerificationError(RuntimeError):
|
||||||
|
"""The package changed on disk, but its required runtime verification failed."""
|
||||||
|
|
||||||
|
|
||||||
|
class TaskRunner:
|
||||||
|
def __init__(self, repository: Repository) -> None:
|
||||||
|
self.repository = repository
|
||||||
|
self.manifest_client = ManifestClient()
|
||||||
|
self.manifest_validator = ManifestValidator()
|
||||||
|
|
||||||
|
def run_install(self, task_id: str, request: InstallRequest | UpdateRequest, task_type: str = "install") -> None:
|
||||||
|
manifest: dict[str, Any] | None = None
|
||||||
|
try:
|
||||||
|
self._mark_started(task_id, f"starting {task_type}")
|
||||||
|
self._require_root_if_available()
|
||||||
|
manifest = self._resolve_manifest(request)
|
||||||
|
self.repository.add_log(task_id, "info", f"Installing {manifest['appId']} {manifest['version']}")
|
||||||
|
self._install_manifest(task_id, manifest)
|
||||||
|
manifest_hash = hashlib.sha256(
|
||||||
|
self.repository.export_manifest_hash(manifest).encode("utf-8")
|
||||||
|
).hexdigest()
|
||||||
|
self.repository.upsert_installed_app(
|
||||||
|
manifest["appId"],
|
||||||
|
manifest["appName"],
|
||||||
|
manifest["version"],
|
||||||
|
manifest_hash,
|
||||||
|
manifest.get("openUrl"),
|
||||||
|
)
|
||||||
|
self.repository.update_task(
|
||||||
|
task_id,
|
||||||
|
status="success",
|
||||||
|
progress=100,
|
||||||
|
current_step="completed",
|
||||||
|
finished_at=utc_now(),
|
||||||
|
)
|
||||||
|
self.repository.add_log(task_id, "info", f"Task {task_id} completed")
|
||||||
|
except InstalledComponentVerificationError as error:
|
||||||
|
self._track_attention_install(task_id, manifest)
|
||||||
|
self._fail_task(task_id, error)
|
||||||
|
except Exception as error:
|
||||||
|
self._fail_task(task_id, error)
|
||||||
|
|
||||||
|
def run_remove(self, task_id: str, request: RemoveRequest) -> None:
|
||||||
|
try:
|
||||||
|
if not settings.allow_remove:
|
||||||
|
raise ValueError("Remove is disabled on this Agent")
|
||||||
|
self._mark_started(task_id, "starting remove")
|
||||||
|
self._require_root_if_available()
|
||||||
|
effective_purge = request.purge and settings.allow_purge
|
||||||
|
if request.purge and not effective_purge:
|
||||||
|
self.repository.add_log(
|
||||||
|
task_id,
|
||||||
|
"warning",
|
||||||
|
"Purge cleanup was requested but ALLOW_PURGE is disabled; falling back to remove cleanup",
|
||||||
|
)
|
||||||
|
|
||||||
|
components = self.repository.list_installed_components(request.app_id)
|
||||||
|
if not components and request.package_name:
|
||||||
|
components = [
|
||||||
|
{
|
||||||
|
"component_id": request.package_name,
|
||||||
|
"type": "deb",
|
||||||
|
"install_order": 10,
|
||||||
|
"package_name": request.package_name,
|
||||||
|
"service_name": request.service_name,
|
||||||
|
}
|
||||||
|
]
|
||||||
|
if not components:
|
||||||
|
raise ValueError("No installed components found for this app")
|
||||||
|
|
||||||
|
command_runner = CommandRunner(self.repository, task_id)
|
||||||
|
installer = DebInstaller(command_runner)
|
||||||
|
services = ServiceManager(command_runner)
|
||||||
|
|
||||||
|
ordered = sorted(components, key=lambda item: item["install_order"], reverse=True)
|
||||||
|
total = len(ordered)
|
||||||
|
removed_apt_package = False
|
||||||
|
for index, component in enumerate(ordered, start=1):
|
||||||
|
progress = int((index - 1) / total * 80) + 10
|
||||||
|
component_id = component["component_id"]
|
||||||
|
self.repository.update_task(
|
||||||
|
task_id,
|
||||||
|
progress=progress,
|
||||||
|
current_step=f"removing {component_id}",
|
||||||
|
current_component_id=component_id,
|
||||||
|
)
|
||||||
|
service_name = component.get("service_name")
|
||||||
|
if service_name:
|
||||||
|
self.repository.add_log(task_id, "info", f"Stopping service {service_name}")
|
||||||
|
self._best_effort(task_id, f"stop service {service_name}", lambda: services.stop_service(service_name))
|
||||||
|
self._best_effort(task_id, f"disable service {service_name}", lambda: services.disable_service(service_name))
|
||||||
|
|
||||||
|
package_name = component.get("package_name")
|
||||||
|
if component["type"] in {"deb", "apt"} and package_name:
|
||||||
|
self.repository.add_log(task_id, "info", f"Removing package {package_name}")
|
||||||
|
installer.remove_package(package_name, purge=effective_purge)
|
||||||
|
if component["type"] == "deb":
|
||||||
|
self._clean_cached_package_files(task_id, package_name, component_id)
|
||||||
|
if service_name:
|
||||||
|
self._best_effort(task_id, f"reset failed state for {service_name}", lambda: services.reset_failed(service_name))
|
||||||
|
removed_apt_package = True
|
||||||
|
elif component["type"] == "docker":
|
||||||
|
container_name = component.get("container_name") or component_id
|
||||||
|
self.repository.add_log(task_id, "info", f"Removing Docker container {container_name}")
|
||||||
|
docker_installer = DockerInstaller(command_runner)
|
||||||
|
docker_installer.ensure_runtime(auto_install=settings.auto_install_docker)
|
||||||
|
docker_installer.remove_labeled_containers(
|
||||||
|
request.app_id,
|
||||||
|
component_id,
|
||||||
|
remove_volumes=effective_purge,
|
||||||
|
)
|
||||||
|
docker_installer.remove_container(container_name, remove_volumes=effective_purge)
|
||||||
|
image = component.get("docker_image") or component.get("image")
|
||||||
|
if effective_purge and image:
|
||||||
|
self._best_effort(task_id, f"remove Docker image {image}", lambda: docker_installer.remove_image(image))
|
||||||
|
else:
|
||||||
|
raise ValueError(f"Unsupported installed component type: {component['type']}")
|
||||||
|
|
||||||
|
if removed_apt_package:
|
||||||
|
self.repository.update_task(task_id, progress=92, current_step="cleaning package leftovers")
|
||||||
|
self._best_effort(
|
||||||
|
task_id,
|
||||||
|
"clean unused packages and apt cache",
|
||||||
|
lambda: installer.cleanup_after_remove(purge=effective_purge),
|
||||||
|
)
|
||||||
|
|
||||||
|
self.repository.delete_installed_app(request.app_id)
|
||||||
|
self.repository.update_task(
|
||||||
|
task_id,
|
||||||
|
status="success",
|
||||||
|
progress=100,
|
||||||
|
current_step="completed",
|
||||||
|
finished_at=utc_now(),
|
||||||
|
)
|
||||||
|
except Exception as error:
|
||||||
|
self._fail_task(task_id, error)
|
||||||
|
|
||||||
|
def _resolve_manifest(self, request: InstallRequest | UpdateRequest) -> dict[str, Any]:
|
||||||
|
if request.download_url:
|
||||||
|
digest = request.sha256 or request.checksum
|
||||||
|
return self.manifest_validator.validate(
|
||||||
|
{
|
||||||
|
"schemaVersion": "1.0",
|
||||||
|
"appId": request.app_id,
|
||||||
|
"appName": request.app_name or request.app_id,
|
||||||
|
"version": request.version,
|
||||||
|
"architecture": "amd64",
|
||||||
|
"components": [
|
||||||
|
{
|
||||||
|
"componentId": request.package_name,
|
||||||
|
"type": "deb",
|
||||||
|
"installOrder": 10,
|
||||||
|
"required": True,
|
||||||
|
"packageName": request.package_name,
|
||||||
|
"version": request.version,
|
||||||
|
"downloadUrl": request.download_url,
|
||||||
|
"sha256": digest,
|
||||||
|
"serviceName": request.service_name,
|
||||||
|
}
|
||||||
|
],
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
payload = self.manifest_client.fetch_manifest(request.app_id, request.version)
|
||||||
|
return self.manifest_validator.validate(payload)
|
||||||
|
|
||||||
|
def _install_manifest(self, task_id: str, manifest: dict[str, Any]) -> None:
|
||||||
|
components = manifest["components"]
|
||||||
|
for component in components:
|
||||||
|
self.repository.create_task_component(
|
||||||
|
task_id,
|
||||||
|
manifest["appId"],
|
||||||
|
component["componentId"],
|
||||||
|
component["type"],
|
||||||
|
component.get("installOrder", 10),
|
||||||
|
)
|
||||||
|
|
||||||
|
total = len(components)
|
||||||
|
if total == 0:
|
||||||
|
raise ValueError("Manifest has no installable components")
|
||||||
|
|
||||||
|
for index, component in enumerate(components, start=1):
|
||||||
|
base_progress = int((index - 1) / total * 80) + 10
|
||||||
|
component_id = component["componentId"]
|
||||||
|
self.repository.update_task(
|
||||||
|
task_id,
|
||||||
|
progress=base_progress,
|
||||||
|
current_step=f"installing {component_id}",
|
||||||
|
current_component_id=component_id,
|
||||||
|
)
|
||||||
|
self.repository.update_task_component(
|
||||||
|
task_id,
|
||||||
|
component_id,
|
||||||
|
status="running",
|
||||||
|
progress=5,
|
||||||
|
current_step="preparing",
|
||||||
|
started_at=utc_now(),
|
||||||
|
)
|
||||||
|
|
||||||
|
if component["type"] == "deb":
|
||||||
|
self._install_deb_component(task_id, manifest["appId"], component)
|
||||||
|
elif component["type"] == "apt":
|
||||||
|
self._install_apt_component(task_id, manifest["appId"], component)
|
||||||
|
elif component["type"] == "docker":
|
||||||
|
self._install_docker_component(task_id, manifest["appId"], component)
|
||||||
|
else:
|
||||||
|
raise ValueError(f"Unsupported component type: {component['type']}")
|
||||||
|
|
||||||
|
self.repository.update_task_component(
|
||||||
|
task_id,
|
||||||
|
component_id,
|
||||||
|
status="success",
|
||||||
|
progress=100,
|
||||||
|
current_step="completed",
|
||||||
|
finished_at=utc_now(),
|
||||||
|
)
|
||||||
|
|
||||||
|
def _install_deb_component(self, task_id: str, app_id: str, component: dict[str, Any]) -> None:
|
||||||
|
component_id = component["componentId"]
|
||||||
|
downloader = Downloader(self.repository, task_id)
|
||||||
|
command_runner = CommandRunner(self.repository, task_id)
|
||||||
|
installer = DebInstaller(command_runner)
|
||||||
|
services = ServiceManager(command_runner)
|
||||||
|
|
||||||
|
self.repository.update_task_component(task_id, component_id, progress=10, current_step="downloading")
|
||||||
|
package_path = downloader.download(component["downloadUrl"])
|
||||||
|
self.repository.update_task_component(task_id, component_id, progress=35, current_step="verifying checksum")
|
||||||
|
actual_sha256 = sha256_file(package_path)
|
||||||
|
expected_sha256 = component["sha256"].lower()
|
||||||
|
if actual_sha256.lower() != expected_sha256:
|
||||||
|
raise ValueError(
|
||||||
|
f"Checksum mismatch for {component_id}: expected {expected_sha256}, got {actual_sha256}"
|
||||||
|
)
|
||||||
|
self.repository.add_log(task_id, "info", f"Checksum verified for {component_id}")
|
||||||
|
|
||||||
|
self.repository.update_task_component(task_id, component_id, progress=50, current_step="validating package metadata")
|
||||||
|
deb_metadata = installer.get_deb_metadata(package_path)
|
||||||
|
expected_package_name = component["packageName"]
|
||||||
|
actual_package_name = deb_metadata["package"]
|
||||||
|
if actual_package_name != expected_package_name:
|
||||||
|
raise ValueError(
|
||||||
|
f"Package metadata mismatch for {component_id}: manifest packageName is "
|
||||||
|
f"{expected_package_name}, but .deb Package is {actual_package_name}. "
|
||||||
|
f"Create or update the package in the web server with Package code {actual_package_name}."
|
||||||
|
)
|
||||||
|
|
||||||
|
expected_version = component.get("version") or ""
|
||||||
|
actual_version = deb_metadata["version"]
|
||||||
|
if expected_version and actual_version != expected_version:
|
||||||
|
raise ValueError(
|
||||||
|
f"Package metadata mismatch for {component_id}: manifest version is "
|
||||||
|
f"{expected_version}, but .deb Version is {actual_version}."
|
||||||
|
)
|
||||||
|
|
||||||
|
self.repository.add_log(
|
||||||
|
task_id,
|
||||||
|
"info",
|
||||||
|
f"Package metadata verified for {actual_package_name} {actual_version}",
|
||||||
|
)
|
||||||
|
|
||||||
|
self.repository.update_task_component(task_id, component_id, progress=60, current_step="installing package")
|
||||||
|
installer.install_deb(package_path)
|
||||||
|
|
||||||
|
self.repository.update_task_component(task_id, component_id, progress=75, current_step="verifying package")
|
||||||
|
installed_version = installer.get_package_version(component["packageName"])
|
||||||
|
self.repository.add_log(
|
||||||
|
task_id,
|
||||||
|
"info",
|
||||||
|
f"Package {component['packageName']} installed with version {installed_version}",
|
||||||
|
)
|
||||||
|
|
||||||
|
service_name = component.get("serviceName")
|
||||||
|
if service_name:
|
||||||
|
self.repository.update_task_component(task_id, component_id, progress=90, current_step="starting service")
|
||||||
|
services.enable_service(service_name)
|
||||||
|
services.start_service(service_name)
|
||||||
|
|
||||||
|
self.repository.upsert_installed_component(app_id, component)
|
||||||
|
|
||||||
|
def _install_apt_component(self, task_id: str, app_id: str, component: dict[str, Any]) -> None:
|
||||||
|
component_id = component["componentId"]
|
||||||
|
package_name = component["packageName"]
|
||||||
|
command_runner = CommandRunner(self.repository, task_id)
|
||||||
|
installer = AptInstaller(command_runner)
|
||||||
|
services = ServiceManager(command_runner)
|
||||||
|
|
||||||
|
self.repository.update_task_component(
|
||||||
|
task_id,
|
||||||
|
component_id,
|
||||||
|
progress=10,
|
||||||
|
current_step="refreshing APT package index",
|
||||||
|
)
|
||||||
|
self.repository.add_log(task_id, "info", "Refreshing APT package index")
|
||||||
|
installer.update_package_index()
|
||||||
|
|
||||||
|
self.repository.update_task_component(
|
||||||
|
task_id,
|
||||||
|
component_id,
|
||||||
|
progress=35,
|
||||||
|
current_step=f"installing APT package {package_name}",
|
||||||
|
)
|
||||||
|
self.repository.add_log(task_id, "info", f"Installing trusted APT package {package_name}")
|
||||||
|
installer.install_package(package_name)
|
||||||
|
|
||||||
|
self.repository.update_task_component(
|
||||||
|
task_id,
|
||||||
|
component_id,
|
||||||
|
progress=70,
|
||||||
|
current_step="verifying installed package",
|
||||||
|
)
|
||||||
|
installed_version = installer.get_package_version(package_name)
|
||||||
|
if not installed_version:
|
||||||
|
raise RuntimeError(f"APT package was not installed: {package_name}")
|
||||||
|
self.repository.add_log(
|
||||||
|
task_id,
|
||||||
|
"info",
|
||||||
|
f"APT package {package_name} installed with version {installed_version}",
|
||||||
|
)
|
||||||
|
|
||||||
|
installed_component = dict(component)
|
||||||
|
installed_component["version"] = installed_version
|
||||||
|
|
||||||
|
policy = APT_SERVICE_POLICIES.get(package_name, {})
|
||||||
|
managed_services = list(policy.get("managedServices", []))
|
||||||
|
discovered_services = installer.discover_service_units(package_name)
|
||||||
|
service_names = list(dict.fromkeys([*managed_services, *discovered_services]))
|
||||||
|
|
||||||
|
self.repository.update_task_component(
|
||||||
|
task_id,
|
||||||
|
component_id,
|
||||||
|
progress=80,
|
||||||
|
current_step="checking package services",
|
||||||
|
service_check_status="checking",
|
||||||
|
service_checks=[],
|
||||||
|
)
|
||||||
|
|
||||||
|
verification_errors: list[str] = []
|
||||||
|
if managed_services:
|
||||||
|
self.repository.update_task_component(
|
||||||
|
task_id,
|
||||||
|
component_id,
|
||||||
|
progress=85,
|
||||||
|
current_step="starting managed package services",
|
||||||
|
)
|
||||||
|
for service_name in managed_services:
|
||||||
|
try:
|
||||||
|
services.enable_service(service_name)
|
||||||
|
services.start_service(service_name)
|
||||||
|
except Exception as error:
|
||||||
|
verification_errors.append(f"Could not start {service_name}: {error}")
|
||||||
|
|
||||||
|
readiness_status: str | None = None
|
||||||
|
if policy.get("readiness") == "postgresql":
|
||||||
|
self.repository.update_task_component(
|
||||||
|
task_id,
|
||||||
|
component_id,
|
||||||
|
progress=90,
|
||||||
|
current_step="checking PostgreSQL readiness",
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
installer.wait_for_postgresql()
|
||||||
|
readiness_status = "ready"
|
||||||
|
except Exception as error:
|
||||||
|
readiness_status = "failed"
|
||||||
|
verification_errors.append(f"PostgreSQL is not accepting connections: {error}")
|
||||||
|
|
||||||
|
service_checks: list[dict[str, Any]] = []
|
||||||
|
self.repository.update_task_component(
|
||||||
|
task_id,
|
||||||
|
component_id,
|
||||||
|
progress=95,
|
||||||
|
current_step="reading service status",
|
||||||
|
)
|
||||||
|
for service_name in service_names:
|
||||||
|
check = services.get_service_status(service_name)
|
||||||
|
if service_name in managed_services and readiness_status is not None:
|
||||||
|
check["readinessType"] = str(policy["readiness"])
|
||||||
|
check["readinessStatus"] = readiness_status
|
||||||
|
check["healthy"] = bool(check.get("healthy")) and readiness_status == "ready"
|
||||||
|
service_checks.append(check)
|
||||||
|
|
||||||
|
if check.get("healthy"):
|
||||||
|
self.repository.add_log(
|
||||||
|
task_id,
|
||||||
|
"info",
|
||||||
|
f"Service {service_name} is active ({check.get('subState', 'unknown')})",
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
self.repository.add_log(
|
||||||
|
task_id,
|
||||||
|
"warning",
|
||||||
|
f"Service {service_name} is not healthy "
|
||||||
|
f"(load={check.get('loadState', 'unknown')}, "
|
||||||
|
f"active={check.get('activeState', 'unknown')}, "
|
||||||
|
f"sub={check.get('subState', 'unknown')})",
|
||||||
|
)
|
||||||
|
|
||||||
|
if not service_names:
|
||||||
|
service_check_status = "not-applicable"
|
||||||
|
self.repository.add_log(
|
||||||
|
task_id,
|
||||||
|
"info",
|
||||||
|
f"APT package {package_name} does not expose a concrete systemd service unit",
|
||||||
|
)
|
||||||
|
elif all(bool(check.get("healthy")) for check in service_checks):
|
||||||
|
service_check_status = "healthy"
|
||||||
|
else:
|
||||||
|
service_check_status = "unhealthy"
|
||||||
|
|
||||||
|
self.repository.update_task_component(
|
||||||
|
task_id,
|
||||||
|
component_id,
|
||||||
|
progress=98,
|
||||||
|
current_step="service checks completed",
|
||||||
|
service_check_status=service_check_status,
|
||||||
|
service_checks=service_checks,
|
||||||
|
)
|
||||||
|
installed_component["serviceCheckStatus"] = service_check_status
|
||||||
|
installed_component["serviceChecks"] = service_checks
|
||||||
|
if managed_services:
|
||||||
|
installed_component["serviceName"] = managed_services[0]
|
||||||
|
self.repository.upsert_installed_component(app_id, installed_component)
|
||||||
|
|
||||||
|
unhealthy_managed_services = [
|
||||||
|
str(check.get("serviceName"))
|
||||||
|
for check in service_checks
|
||||||
|
if check.get("serviceName") in managed_services and not check.get("healthy")
|
||||||
|
]
|
||||||
|
if unhealthy_managed_services:
|
||||||
|
verification_errors.append(
|
||||||
|
f"Required service is not healthy: {', '.join(unhealthy_managed_services)}"
|
||||||
|
)
|
||||||
|
if verification_errors:
|
||||||
|
raise InstalledComponentVerificationError(
|
||||||
|
"; ".join(dict.fromkeys(verification_errors))
|
||||||
|
)
|
||||||
|
|
||||||
|
def _install_docker_component(self, task_id: str, app_id: str, component: dict[str, Any]) -> None:
|
||||||
|
component_id = component["componentId"]
|
||||||
|
container_name = component["containerName"]
|
||||||
|
reference = image_reference(component)
|
||||||
|
command_runner = CommandRunner(self.repository, task_id)
|
||||||
|
installer = DockerInstaller(command_runner)
|
||||||
|
|
||||||
|
self.repository.update_task_component(task_id, component_id, progress=15, current_step="checking Docker runtime")
|
||||||
|
installer.ensure_runtime(auto_install=settings.auto_install_docker)
|
||||||
|
|
||||||
|
self.repository.update_task_component(task_id, component_id, progress=35, current_step="pulling image")
|
||||||
|
self.repository.add_log(task_id, "info", f"Pulling Docker image {reference}")
|
||||||
|
installer.pull_image(reference)
|
||||||
|
|
||||||
|
self.repository.update_task_component(task_id, component_id, progress=70, current_step="recreating container")
|
||||||
|
self.repository.add_log(task_id, "info", f"Recreating Docker container {container_name}")
|
||||||
|
installer.recreate_container(app_id, component)
|
||||||
|
|
||||||
|
self.repository.update_task_component(task_id, component_id, progress=90, current_step="verifying container")
|
||||||
|
installer.assert_container_running(container_name)
|
||||||
|
self.repository.add_log(task_id, "info", f"Docker container {container_name} is running")
|
||||||
|
|
||||||
|
installed_component = dict(component)
|
||||||
|
installed_component["image"] = reference
|
||||||
|
self.repository.upsert_installed_component(app_id, installed_component)
|
||||||
|
|
||||||
|
def _mark_started(self, task_id: str, step: str) -> None:
|
||||||
|
self.repository.update_task(
|
||||||
|
task_id,
|
||||||
|
status="running",
|
||||||
|
progress=5,
|
||||||
|
current_step=step,
|
||||||
|
started_at=utc_now(),
|
||||||
|
)
|
||||||
|
self.repository.add_log(task_id, "info", step)
|
||||||
|
|
||||||
|
def _fail_task(self, task_id: str, error: Exception) -> None:
|
||||||
|
task = self.repository.get_task(task_id)
|
||||||
|
component_id = task.get("current_component_id") if task else None
|
||||||
|
finished_at = utc_now()
|
||||||
|
if component_id:
|
||||||
|
self.repository.update_task_component(
|
||||||
|
task_id,
|
||||||
|
component_id,
|
||||||
|
status="failed",
|
||||||
|
current_step="failed",
|
||||||
|
error_message=str(error),
|
||||||
|
finished_at=finished_at,
|
||||||
|
)
|
||||||
|
self.repository.update_task(
|
||||||
|
task_id,
|
||||||
|
status="failed",
|
||||||
|
current_step="failed",
|
||||||
|
error_message=str(error),
|
||||||
|
finished_at=finished_at,
|
||||||
|
)
|
||||||
|
self.repository.add_log(task_id, "error", str(error))
|
||||||
|
self.repository.add_log(task_id, "debug", traceback.format_exc())
|
||||||
|
|
||||||
|
def _require_root_if_available(self) -> None:
|
||||||
|
geteuid = getattr(os, "geteuid", None)
|
||||||
|
if callable(geteuid) and geteuid() != 0:
|
||||||
|
raise PermissionError("Agent must run as root to call apt and systemctl")
|
||||||
|
|
||||||
|
def _best_effort(self, task_id: str, action: str, callback: Any) -> None:
|
||||||
|
try:
|
||||||
|
callback()
|
||||||
|
except Exception as error:
|
||||||
|
self.repository.add_log(task_id, "warning", f"Could not {action}: {error}")
|
||||||
|
|
||||||
|
def _track_attention_install(self, task_id: str, manifest: dict[str, Any] | None) -> None:
|
||||||
|
if not manifest:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
manifest_hash = hashlib.sha256(
|
||||||
|
self.repository.export_manifest_hash(manifest).encode("utf-8")
|
||||||
|
).hexdigest()
|
||||||
|
self.repository.upsert_installed_app(
|
||||||
|
manifest["appId"],
|
||||||
|
manifest["appName"],
|
||||||
|
manifest["version"],
|
||||||
|
manifest_hash,
|
||||||
|
manifest.get("openUrl"),
|
||||||
|
status="attention",
|
||||||
|
)
|
||||||
|
self.repository.add_log(
|
||||||
|
task_id,
|
||||||
|
"warning",
|
||||||
|
"The package was installed but its service needs attention; it remains available for status and removal",
|
||||||
|
)
|
||||||
|
except Exception as tracking_error:
|
||||||
|
self.repository.add_log(
|
||||||
|
task_id,
|
||||||
|
"warning",
|
||||||
|
f"Could not persist installed package attention state: {tracking_error}",
|
||||||
|
)
|
||||||
|
|
||||||
|
def _clean_cached_package_files(self, task_id: str, *identifiers: str | None) -> None:
|
||||||
|
cache_dir = settings.cache_dir
|
||||||
|
if not cache_dir.exists() or not cache_dir.is_dir():
|
||||||
|
return
|
||||||
|
|
||||||
|
patterns: list[str] = []
|
||||||
|
seen_patterns: set[str] = set()
|
||||||
|
for identifier in identifiers:
|
||||||
|
name = (identifier or "").strip()
|
||||||
|
if not name:
|
||||||
|
continue
|
||||||
|
for pattern in (f"{name}.deb", f"{name}_*.deb"):
|
||||||
|
if pattern not in seen_patterns:
|
||||||
|
patterns.append(pattern)
|
||||||
|
seen_patterns.add(pattern)
|
||||||
|
|
||||||
|
removed_files: set[str] = set()
|
||||||
|
for pattern in patterns:
|
||||||
|
for file_path in cache_dir.glob(pattern):
|
||||||
|
if not file_path.is_file():
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
file_path.unlink()
|
||||||
|
removed_files.add(str(file_path))
|
||||||
|
except Exception as error:
|
||||||
|
self.repository.add_log(task_id, "warning", f"Could not remove cached package {file_path}: {error}")
|
||||||
|
|
||||||
|
for file_path in sorted(removed_files):
|
||||||
|
self.repository.add_log(task_id, "info", f"Removed cached package {file_path}")
|
||||||
37
agent/app/main.py
Normal file
37
agent/app/main.py
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from contextlib import asynccontextmanager
|
||||||
|
|
||||||
|
from fastapi import FastAPI
|
||||||
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
|
|
||||||
|
from app.api import apps, health, services, tasks
|
||||||
|
from app.config import settings
|
||||||
|
from app.storage.database import initialize_database
|
||||||
|
|
||||||
|
|
||||||
|
@asynccontextmanager
|
||||||
|
async def lifespan(app: FastAPI):
|
||||||
|
initialize_database()
|
||||||
|
yield
|
||||||
|
|
||||||
|
|
||||||
|
app = FastAPI(
|
||||||
|
title="Local Installer Agent",
|
||||||
|
version=settings.agent_version,
|
||||||
|
lifespan=lifespan,
|
||||||
|
)
|
||||||
|
|
||||||
|
app.add_middleware(
|
||||||
|
CORSMiddleware,
|
||||||
|
allow_origins=settings.allowed_origins,
|
||||||
|
allow_credentials=True,
|
||||||
|
allow_methods=["*"],
|
||||||
|
allow_headers=["*"],
|
||||||
|
)
|
||||||
|
|
||||||
|
app.include_router(health.router)
|
||||||
|
app.include_router(apps.router)
|
||||||
|
app.include_router(tasks.router)
|
||||||
|
app.include_router(services.router)
|
||||||
|
|
||||||
2
agent/app/models/__init__.py
Normal file
2
agent/app/models/__init__.py
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
"""Pydantic models for API contracts."""
|
||||||
|
|
||||||
292
agent/app/models/schemas.py
Normal file
292
agent/app/models/schemas.py
Normal file
@@ -0,0 +1,292 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any, Literal
|
||||||
|
|
||||||
|
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
||||||
|
|
||||||
|
from app.utils.validators import (
|
||||||
|
validate_app_id,
|
||||||
|
validate_container_name,
|
||||||
|
validate_docker_digest,
|
||||||
|
validate_docker_image,
|
||||||
|
validate_docker_tag,
|
||||||
|
validate_env_name,
|
||||||
|
validate_package_name,
|
||||||
|
validate_port_mapping,
|
||||||
|
validate_restart_policy,
|
||||||
|
validate_service_name,
|
||||||
|
validate_sha256,
|
||||||
|
validate_volume_mapping,
|
||||||
|
validate_version,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
TaskType = Literal["install", "update", "remove"]
|
||||||
|
TaskStatus = Literal["queued", "running", "success", "failed", "cancelled"]
|
||||||
|
ComponentType = Literal["deb", "apt", "docker", "docker_compose"]
|
||||||
|
|
||||||
|
|
||||||
|
class CamelModel(BaseModel):
|
||||||
|
model_config = ConfigDict(populate_by_name=True, extra="forbid")
|
||||||
|
|
||||||
|
|
||||||
|
class HealthResponse(CamelModel):
|
||||||
|
status: str
|
||||||
|
agent_version: str = Field(alias="agentVersion")
|
||||||
|
hostname: str
|
||||||
|
os: str
|
||||||
|
architecture: str
|
||||||
|
|
||||||
|
|
||||||
|
class SystemInfoResponse(CamelModel):
|
||||||
|
hostname: str
|
||||||
|
os: str
|
||||||
|
kernel: str
|
||||||
|
architecture: str
|
||||||
|
disk_free: str = Field(alias="diskFree")
|
||||||
|
memory_total: str = Field(alias="memoryTotal")
|
||||||
|
|
||||||
|
|
||||||
|
class InstallRequest(CamelModel):
|
||||||
|
app_id: str = Field(alias="appId")
|
||||||
|
version: str | None = None
|
||||||
|
app_name: str | None = Field(default=None, alias="appName")
|
||||||
|
package_name: str | None = Field(default=None, alias="packageName")
|
||||||
|
service_name: str | None = Field(default=None, alias="serviceName")
|
||||||
|
download_url: str | None = Field(default=None, alias="downloadUrl")
|
||||||
|
checksum: str | None = None
|
||||||
|
sha256: str | None = None
|
||||||
|
|
||||||
|
@field_validator("app_id")
|
||||||
|
@classmethod
|
||||||
|
def _app_id(cls, value: str) -> str:
|
||||||
|
return validate_app_id(value)
|
||||||
|
|
||||||
|
@field_validator("version")
|
||||||
|
@classmethod
|
||||||
|
def _version(cls, value: str | None) -> str | None:
|
||||||
|
return validate_version(value) if value else None
|
||||||
|
|
||||||
|
@field_validator("package_name")
|
||||||
|
@classmethod
|
||||||
|
def _package_name(cls, value: str | None) -> str | None:
|
||||||
|
return validate_package_name(value) if value else None
|
||||||
|
|
||||||
|
@field_validator("service_name")
|
||||||
|
@classmethod
|
||||||
|
def _service_name(cls, value: str | None) -> str | None:
|
||||||
|
return validate_service_name(value)
|
||||||
|
|
||||||
|
@model_validator(mode="after")
|
||||||
|
def _direct_package_fields(self) -> "InstallRequest":
|
||||||
|
digest = self.sha256 or self.checksum
|
||||||
|
if digest:
|
||||||
|
normalized = validate_sha256(digest)
|
||||||
|
self.sha256 = normalized
|
||||||
|
self.checksum = normalized
|
||||||
|
|
||||||
|
has_direct_package = any([self.download_url, self.package_name, self.checksum, self.sha256])
|
||||||
|
if has_direct_package and not all([self.download_url, self.package_name, self.checksum or self.sha256]):
|
||||||
|
raise ValueError("direct install requires packageName, downloadUrl, and checksum/sha256")
|
||||||
|
return self
|
||||||
|
|
||||||
|
|
||||||
|
class UpdateRequest(InstallRequest):
|
||||||
|
current_version: str | None = Field(default=None, alias="currentVersion")
|
||||||
|
target_version: str | None = Field(default=None, alias="targetVersion")
|
||||||
|
|
||||||
|
@model_validator(mode="after")
|
||||||
|
def _normalize_target(self) -> "UpdateRequest":
|
||||||
|
if self.target_version:
|
||||||
|
self.target_version = validate_version(self.target_version)
|
||||||
|
self.version = self.target_version
|
||||||
|
return self
|
||||||
|
|
||||||
|
|
||||||
|
class RemoveRequest(CamelModel):
|
||||||
|
app_id: str = Field(alias="appId")
|
||||||
|
package_name: str | None = Field(default=None, alias="packageName")
|
||||||
|
service_name: str | None = Field(default=None, alias="serviceName")
|
||||||
|
purge: bool = False
|
||||||
|
|
||||||
|
@field_validator("app_id")
|
||||||
|
@classmethod
|
||||||
|
def _app_id(cls, value: str) -> str:
|
||||||
|
return validate_app_id(value)
|
||||||
|
|
||||||
|
@field_validator("package_name")
|
||||||
|
@classmethod
|
||||||
|
def _package_name(cls, value: str | None) -> str | None:
|
||||||
|
return validate_package_name(value) if value else None
|
||||||
|
|
||||||
|
@field_validator("service_name")
|
||||||
|
@classmethod
|
||||||
|
def _service_name(cls, value: str | None) -> str | None:
|
||||||
|
return validate_service_name(value)
|
||||||
|
|
||||||
|
|
||||||
|
class ServiceRequest(CamelModel):
|
||||||
|
service_name: str = Field(alias="serviceName")
|
||||||
|
|
||||||
|
@field_validator("service_name")
|
||||||
|
@classmethod
|
||||||
|
def _service_name(cls, value: str) -> str:
|
||||||
|
return validate_service_name(value) or value
|
||||||
|
|
||||||
|
|
||||||
|
class TaskQueuedResponse(CamelModel):
|
||||||
|
task_id: str = Field(alias="taskId")
|
||||||
|
status: str
|
||||||
|
|
||||||
|
|
||||||
|
class DebComponent(CamelModel):
|
||||||
|
component_id: str = Field(alias="componentId")
|
||||||
|
type: Literal["deb"] = "deb"
|
||||||
|
install_order: int = Field(default=10, alias="installOrder")
|
||||||
|
required: bool = True
|
||||||
|
package_name: str = Field(alias="packageName")
|
||||||
|
version: str
|
||||||
|
download_url: str = Field(alias="downloadUrl")
|
||||||
|
sha256: str
|
||||||
|
service_name: str | None = Field(default=None, alias="serviceName")
|
||||||
|
|
||||||
|
@field_validator("component_id")
|
||||||
|
@classmethod
|
||||||
|
def _component_id(cls, value: str) -> str:
|
||||||
|
return validate_app_id(value)
|
||||||
|
|
||||||
|
@field_validator("package_name")
|
||||||
|
@classmethod
|
||||||
|
def _package_name(cls, value: str) -> str:
|
||||||
|
return validate_package_name(value)
|
||||||
|
|
||||||
|
@field_validator("version")
|
||||||
|
@classmethod
|
||||||
|
def _version(cls, value: str) -> str:
|
||||||
|
return validate_version(value)
|
||||||
|
|
||||||
|
@field_validator("sha256")
|
||||||
|
@classmethod
|
||||||
|
def _sha256(cls, value: str) -> str:
|
||||||
|
return validate_sha256(value)
|
||||||
|
|
||||||
|
@field_validator("service_name")
|
||||||
|
@classmethod
|
||||||
|
def _service_name(cls, value: str | None) -> str | None:
|
||||||
|
return validate_service_name(value)
|
||||||
|
|
||||||
|
|
||||||
|
class AptComponent(CamelModel):
|
||||||
|
component_id: str = Field(alias="componentId")
|
||||||
|
type: Literal["apt"] = "apt"
|
||||||
|
install_order: int = Field(default=10, alias="installOrder")
|
||||||
|
required: bool = True
|
||||||
|
package_name: str = Field(alias="packageName")
|
||||||
|
version: str | None = None
|
||||||
|
|
||||||
|
@field_validator("component_id")
|
||||||
|
@classmethod
|
||||||
|
def _component_id(cls, value: str) -> str:
|
||||||
|
return validate_app_id(value)
|
||||||
|
|
||||||
|
@field_validator("package_name")
|
||||||
|
@classmethod
|
||||||
|
def _package_name(cls, value: str) -> str:
|
||||||
|
return validate_package_name(value)
|
||||||
|
|
||||||
|
@field_validator("version")
|
||||||
|
@classmethod
|
||||||
|
def _version(cls, value: str | None) -> str | None:
|
||||||
|
return validate_version(value) if value else None
|
||||||
|
|
||||||
|
|
||||||
|
class DockerComponent(CamelModel):
|
||||||
|
component_id: str = Field(alias="componentId")
|
||||||
|
type: Literal["docker"] = "docker"
|
||||||
|
install_order: int = Field(default=10, alias="installOrder")
|
||||||
|
required: bool = True
|
||||||
|
image: str
|
||||||
|
tag: str | None = None
|
||||||
|
digest: str | None = None
|
||||||
|
container_name: str | None = Field(default=None, alias="containerName")
|
||||||
|
restart_policy: str = Field(default="unless-stopped", alias="restartPolicy")
|
||||||
|
ports: list[str] = Field(default_factory=list)
|
||||||
|
volumes: list[str] = Field(default_factory=list)
|
||||||
|
env: dict[str, str] = Field(default_factory=dict)
|
||||||
|
|
||||||
|
@field_validator("component_id")
|
||||||
|
@classmethod
|
||||||
|
def _component_id(cls, value: str) -> str:
|
||||||
|
return validate_app_id(value)
|
||||||
|
|
||||||
|
@field_validator("image")
|
||||||
|
@classmethod
|
||||||
|
def _image(cls, value: str) -> str:
|
||||||
|
return validate_docker_image(value)
|
||||||
|
|
||||||
|
@field_validator("tag")
|
||||||
|
@classmethod
|
||||||
|
def _tag(cls, value: str | None) -> str | None:
|
||||||
|
return validate_docker_tag(value)
|
||||||
|
|
||||||
|
@field_validator("digest")
|
||||||
|
@classmethod
|
||||||
|
def _digest(cls, value: str | None) -> str | None:
|
||||||
|
return validate_docker_digest(value)
|
||||||
|
|
||||||
|
@field_validator("restart_policy")
|
||||||
|
@classmethod
|
||||||
|
def _restart_policy(cls, value: str | None) -> str:
|
||||||
|
return validate_restart_policy(value)
|
||||||
|
|
||||||
|
@field_validator("ports")
|
||||||
|
@classmethod
|
||||||
|
def _ports(cls, values: list[str]) -> list[str]:
|
||||||
|
return [validate_port_mapping(value) for value in values]
|
||||||
|
|
||||||
|
@field_validator("volumes")
|
||||||
|
@classmethod
|
||||||
|
def _volumes(cls, values: list[str]) -> list[str]:
|
||||||
|
return [validate_volume_mapping(value) for value in values]
|
||||||
|
|
||||||
|
@field_validator("env")
|
||||||
|
@classmethod
|
||||||
|
def _env(cls, values: dict[str, Any]) -> dict[str, str]:
|
||||||
|
normalized: dict[str, str] = {}
|
||||||
|
for key, value in values.items():
|
||||||
|
normalized[validate_env_name(str(key))] = str(value)
|
||||||
|
return normalized
|
||||||
|
|
||||||
|
@model_validator(mode="after")
|
||||||
|
def _container_name(self) -> "DockerComponent":
|
||||||
|
self.container_name = validate_container_name(self.container_name or self.component_id)
|
||||||
|
return self
|
||||||
|
|
||||||
|
|
||||||
|
class RawComponent(CamelModel):
|
||||||
|
component_id: str = Field(alias="componentId")
|
||||||
|
type: ComponentType
|
||||||
|
install_order: int = Field(default=10, alias="installOrder")
|
||||||
|
required: bool = True
|
||||||
|
payload: dict[str, Any] = Field(default_factory=dict)
|
||||||
|
|
||||||
|
|
||||||
|
class AppManifest(CamelModel):
|
||||||
|
schema_version: str = Field(default="1.0", alias="schemaVersion")
|
||||||
|
app_id: str = Field(alias="appId")
|
||||||
|
app_name: str = Field(alias="appName")
|
||||||
|
version: str
|
||||||
|
open_url: str | None = Field(default=None, alias="openUrl")
|
||||||
|
architecture: str = "amd64"
|
||||||
|
components: list[dict[str, Any]]
|
||||||
|
signature: str | None = None
|
||||||
|
|
||||||
|
@field_validator("app_id")
|
||||||
|
@classmethod
|
||||||
|
def _app_id(cls, value: str) -> str:
|
||||||
|
return validate_app_id(value)
|
||||||
|
|
||||||
|
@field_validator("version")
|
||||||
|
@classmethod
|
||||||
|
def _version(cls, value: str) -> str:
|
||||||
|
return validate_version(value)
|
||||||
2
agent/app/storage/__init__.py
Normal file
2
agent/app/storage/__init__.py
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
"""SQLite storage layer."""
|
||||||
|
|
||||||
140
agent/app/storage/database.py
Normal file
140
agent/app/storage/database.py
Normal file
@@ -0,0 +1,140 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sqlite3
|
||||||
|
from collections.abc import Iterator
|
||||||
|
from contextlib import contextmanager
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from app.config import settings
|
||||||
|
|
||||||
|
|
||||||
|
SCHEMA = """
|
||||||
|
PRAGMA journal_mode = WAL;
|
||||||
|
PRAGMA foreign_keys = ON;
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS tasks (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
type TEXT NOT NULL,
|
||||||
|
app_id TEXT,
|
||||||
|
app_name TEXT,
|
||||||
|
status TEXT NOT NULL,
|
||||||
|
progress INTEGER DEFAULT 0,
|
||||||
|
current_step TEXT,
|
||||||
|
current_component_id TEXT,
|
||||||
|
error_message TEXT,
|
||||||
|
created_at TEXT NOT NULL,
|
||||||
|
started_at TEXT,
|
||||||
|
finished_at TEXT
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS task_logs (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
task_id TEXT NOT NULL,
|
||||||
|
timestamp TEXT NOT NULL,
|
||||||
|
level TEXT NOT NULL,
|
||||||
|
message TEXT NOT NULL,
|
||||||
|
FOREIGN KEY (task_id) REFERENCES tasks(id) ON DELETE CASCADE
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS installed_apps (
|
||||||
|
app_id TEXT PRIMARY KEY,
|
||||||
|
app_name TEXT NOT NULL,
|
||||||
|
version TEXT NOT NULL,
|
||||||
|
open_url TEXT,
|
||||||
|
manifest_hash TEXT,
|
||||||
|
status TEXT NOT NULL,
|
||||||
|
installed_at TEXT NOT NULL,
|
||||||
|
updated_at TEXT NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS installed_components (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
app_id TEXT NOT NULL,
|
||||||
|
component_id TEXT NOT NULL,
|
||||||
|
type TEXT NOT NULL,
|
||||||
|
install_order INTEGER NOT NULL,
|
||||||
|
status TEXT NOT NULL,
|
||||||
|
package_name TEXT,
|
||||||
|
package_version TEXT,
|
||||||
|
service_name TEXT,
|
||||||
|
service_check_status TEXT DEFAULT 'not-checked',
|
||||||
|
service_checks_json TEXT,
|
||||||
|
docker_image TEXT,
|
||||||
|
docker_digest TEXT,
|
||||||
|
container_name TEXT,
|
||||||
|
compose_project_name TEXT,
|
||||||
|
installed_at TEXT NOT NULL,
|
||||||
|
updated_at TEXT NOT NULL,
|
||||||
|
UNIQUE(app_id, component_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS task_components (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
task_id TEXT NOT NULL,
|
||||||
|
app_id TEXT NOT NULL,
|
||||||
|
component_id TEXT NOT NULL,
|
||||||
|
type TEXT NOT NULL,
|
||||||
|
install_order INTEGER NOT NULL,
|
||||||
|
status TEXT NOT NULL,
|
||||||
|
progress INTEGER DEFAULT 0,
|
||||||
|
current_step TEXT,
|
||||||
|
error_message TEXT,
|
||||||
|
service_check_status TEXT DEFAULT 'not-checked',
|
||||||
|
service_checks_json TEXT,
|
||||||
|
started_at TEXT,
|
||||||
|
finished_at TEXT,
|
||||||
|
FOREIGN KEY (task_id) REFERENCES tasks(id) ON DELETE CASCADE
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS agent_config (
|
||||||
|
key TEXT PRIMARY KEY,
|
||||||
|
value TEXT NOT NULL
|
||||||
|
);
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def _ensure_column(connection: sqlite3.Connection, table: str, column: str, definition: str) -> None:
|
||||||
|
columns = {
|
||||||
|
row["name"]
|
||||||
|
for row in connection.execute(f"PRAGMA table_info({table})").fetchall()
|
||||||
|
}
|
||||||
|
if column not in columns:
|
||||||
|
connection.execute(f"ALTER TABLE {table} ADD COLUMN {column} {definition}")
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def get_connection() -> Iterator[sqlite3.Connection]:
|
||||||
|
connection = sqlite3.connect(settings.db_path, timeout=30)
|
||||||
|
connection.row_factory = sqlite3.Row
|
||||||
|
try:
|
||||||
|
yield connection
|
||||||
|
connection.commit()
|
||||||
|
except Exception:
|
||||||
|
connection.rollback()
|
||||||
|
raise
|
||||||
|
finally:
|
||||||
|
connection.close()
|
||||||
|
|
||||||
|
|
||||||
|
def initialize_database() -> None:
|
||||||
|
db_path = Path(settings.db_path)
|
||||||
|
db_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
settings.cache_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
settings.log_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
with get_connection() as connection:
|
||||||
|
connection.executescript(SCHEMA)
|
||||||
|
_ensure_column(connection, "installed_apps", "open_url", "TEXT")
|
||||||
|
_ensure_column(
|
||||||
|
connection,
|
||||||
|
"installed_components",
|
||||||
|
"service_check_status",
|
||||||
|
"TEXT DEFAULT 'not-checked'",
|
||||||
|
)
|
||||||
|
_ensure_column(connection, "installed_components", "service_checks_json", "TEXT")
|
||||||
|
_ensure_column(
|
||||||
|
connection,
|
||||||
|
"task_components",
|
||||||
|
"service_check_status",
|
||||||
|
"TEXT DEFAULT 'not-checked'",
|
||||||
|
)
|
||||||
|
_ensure_column(connection, "task_components", "service_checks_json", "TEXT")
|
||||||
293
agent/app/storage/repository.py
Normal file
293
agent/app/storage/repository.py
Normal file
@@ -0,0 +1,293 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from app.storage.database import get_connection
|
||||||
|
|
||||||
|
|
||||||
|
def utc_now() -> str:
|
||||||
|
return datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z")
|
||||||
|
|
||||||
|
|
||||||
|
def row_to_dict(row: Any) -> dict[str, Any] | None:
|
||||||
|
if row is None:
|
||||||
|
return None
|
||||||
|
return dict(row)
|
||||||
|
|
||||||
|
|
||||||
|
def _encode_service_checks(value: list[dict[str, Any]]) -> str:
|
||||||
|
return json.dumps(value, ensure_ascii=False, separators=(",", ":"))
|
||||||
|
|
||||||
|
|
||||||
|
def _decode_service_checks(value: Any) -> list[dict[str, Any]]:
|
||||||
|
if not value:
|
||||||
|
return []
|
||||||
|
try:
|
||||||
|
decoded = json.loads(str(value))
|
||||||
|
except (TypeError, ValueError, json.JSONDecodeError):
|
||||||
|
return []
|
||||||
|
if not isinstance(decoded, list):
|
||||||
|
return []
|
||||||
|
return [item for item in decoded if isinstance(item, dict)]
|
||||||
|
|
||||||
|
|
||||||
|
def _component_row(row: Any) -> dict[str, Any]:
|
||||||
|
item = dict(row)
|
||||||
|
item["service_checks"] = _decode_service_checks(item.pop("service_checks_json", None))
|
||||||
|
item["service_check_status"] = item.get("service_check_status") or "not-checked"
|
||||||
|
return item
|
||||||
|
|
||||||
|
|
||||||
|
class Repository:
|
||||||
|
def create_task(self, task_id: str, task_type: str, app_id: str, app_name: str | None) -> None:
|
||||||
|
now = utc_now()
|
||||||
|
with get_connection() as connection:
|
||||||
|
connection.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO tasks (id, type, app_id, app_name, status, progress, current_step, created_at)
|
||||||
|
VALUES (?, ?, ?, ?, 'queued', 0, 'queued', ?)
|
||||||
|
""",
|
||||||
|
(task_id, task_type, app_id, app_name, now),
|
||||||
|
)
|
||||||
|
connection.execute(
|
||||||
|
"INSERT INTO task_logs (task_id, timestamp, level, message) VALUES (?, ?, 'info', ?)",
|
||||||
|
(task_id, now, f"Task {task_id} queued"),
|
||||||
|
)
|
||||||
|
|
||||||
|
def update_task(
|
||||||
|
self,
|
||||||
|
task_id: str,
|
||||||
|
*,
|
||||||
|
status: str | None = None,
|
||||||
|
progress: int | None = None,
|
||||||
|
current_step: str | None = None,
|
||||||
|
current_component_id: str | None = None,
|
||||||
|
error_message: str | None = None,
|
||||||
|
started_at: str | None = None,
|
||||||
|
finished_at: str | None = None,
|
||||||
|
) -> None:
|
||||||
|
fields: list[str] = []
|
||||||
|
values: list[Any] = []
|
||||||
|
for key, value in {
|
||||||
|
"status": status,
|
||||||
|
"progress": progress,
|
||||||
|
"current_step": current_step,
|
||||||
|
"current_component_id": current_component_id,
|
||||||
|
"error_message": error_message,
|
||||||
|
"started_at": started_at,
|
||||||
|
"finished_at": finished_at,
|
||||||
|
}.items():
|
||||||
|
if value is not None:
|
||||||
|
fields.append(f"{key} = ?")
|
||||||
|
values.append(value)
|
||||||
|
if not fields:
|
||||||
|
return
|
||||||
|
values.append(task_id)
|
||||||
|
with get_connection() as connection:
|
||||||
|
connection.execute(f"UPDATE tasks SET {', '.join(fields)} WHERE id = ?", values)
|
||||||
|
|
||||||
|
def add_log(self, task_id: str, level: str, message: str) -> None:
|
||||||
|
with get_connection() as connection:
|
||||||
|
connection.execute(
|
||||||
|
"INSERT INTO task_logs (task_id, timestamp, level, message) VALUES (?, ?, ?, ?)",
|
||||||
|
(task_id, utc_now(), level, message),
|
||||||
|
)
|
||||||
|
|
||||||
|
def get_task(self, task_id: str) -> dict[str, Any] | None:
|
||||||
|
with get_connection() as connection:
|
||||||
|
row = connection.execute("SELECT * FROM tasks WHERE id = ?", (task_id,)).fetchone()
|
||||||
|
return row_to_dict(row)
|
||||||
|
|
||||||
|
def get_task_logs(self, task_id: str) -> list[dict[str, Any]]:
|
||||||
|
with get_connection() as connection:
|
||||||
|
rows = connection.execute(
|
||||||
|
"""
|
||||||
|
SELECT timestamp, level, message
|
||||||
|
FROM task_logs
|
||||||
|
WHERE task_id = ?
|
||||||
|
ORDER BY id ASC
|
||||||
|
""",
|
||||||
|
(task_id,),
|
||||||
|
).fetchall()
|
||||||
|
return [dict(row) for row in rows]
|
||||||
|
|
||||||
|
def create_task_component(
|
||||||
|
self,
|
||||||
|
task_id: str,
|
||||||
|
app_id: str,
|
||||||
|
component_id: str,
|
||||||
|
component_type: str,
|
||||||
|
install_order: int,
|
||||||
|
) -> None:
|
||||||
|
with get_connection() as connection:
|
||||||
|
connection.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO task_components (
|
||||||
|
task_id, app_id, component_id, type, install_order, status, progress, current_step
|
||||||
|
)
|
||||||
|
VALUES (?, ?, ?, ?, ?, 'queued', 0, 'queued')
|
||||||
|
""",
|
||||||
|
(task_id, app_id, component_id, component_type, install_order),
|
||||||
|
)
|
||||||
|
|
||||||
|
def update_task_component(
|
||||||
|
self,
|
||||||
|
task_id: str,
|
||||||
|
component_id: str,
|
||||||
|
*,
|
||||||
|
status: str | None = None,
|
||||||
|
progress: int | None = None,
|
||||||
|
current_step: str | None = None,
|
||||||
|
error_message: str | None = None,
|
||||||
|
service_check_status: str | None = None,
|
||||||
|
service_checks: list[dict[str, Any]] | None = None,
|
||||||
|
started_at: str | None = None,
|
||||||
|
finished_at: str | None = None,
|
||||||
|
) -> None:
|
||||||
|
fields: list[str] = []
|
||||||
|
values: list[Any] = []
|
||||||
|
for key, value in {
|
||||||
|
"status": status,
|
||||||
|
"progress": progress,
|
||||||
|
"current_step": current_step,
|
||||||
|
"error_message": error_message,
|
||||||
|
"service_check_status": service_check_status,
|
||||||
|
"service_checks_json": (
|
||||||
|
_encode_service_checks(service_checks)
|
||||||
|
if service_checks is not None
|
||||||
|
else None
|
||||||
|
),
|
||||||
|
"started_at": started_at,
|
||||||
|
"finished_at": finished_at,
|
||||||
|
}.items():
|
||||||
|
if value is not None:
|
||||||
|
fields.append(f"{key} = ?")
|
||||||
|
values.append(value)
|
||||||
|
if not fields:
|
||||||
|
return
|
||||||
|
values.extend([task_id, component_id])
|
||||||
|
with get_connection() as connection:
|
||||||
|
connection.execute(
|
||||||
|
f"UPDATE task_components SET {', '.join(fields)} WHERE task_id = ? AND component_id = ?",
|
||||||
|
values,
|
||||||
|
)
|
||||||
|
|
||||||
|
def get_task_components(self, task_id: str) -> list[dict[str, Any]]:
|
||||||
|
with get_connection() as connection:
|
||||||
|
rows = connection.execute(
|
||||||
|
"""
|
||||||
|
SELECT component_id, type, status, progress, current_step, error_message,
|
||||||
|
service_check_status, service_checks_json, started_at, finished_at
|
||||||
|
FROM task_components
|
||||||
|
WHERE task_id = ?
|
||||||
|
ORDER BY install_order ASC, id ASC
|
||||||
|
""",
|
||||||
|
(task_id,),
|
||||||
|
).fetchall()
|
||||||
|
return [_component_row(row) for row in rows]
|
||||||
|
|
||||||
|
def list_installed_apps(self) -> list[dict[str, Any]]:
|
||||||
|
with get_connection() as connection:
|
||||||
|
rows = connection.execute(
|
||||||
|
"""
|
||||||
|
SELECT app_id, app_name, version, open_url, manifest_hash, status, installed_at, updated_at
|
||||||
|
FROM installed_apps
|
||||||
|
ORDER BY app_name ASC
|
||||||
|
"""
|
||||||
|
).fetchall()
|
||||||
|
return [dict(row) for row in rows]
|
||||||
|
|
||||||
|
def upsert_installed_app(
|
||||||
|
self,
|
||||||
|
app_id: str,
|
||||||
|
app_name: str,
|
||||||
|
version: str,
|
||||||
|
manifest_hash: str | None,
|
||||||
|
open_url: str | None = None,
|
||||||
|
status: str = "installed",
|
||||||
|
) -> None:
|
||||||
|
now = utc_now()
|
||||||
|
with get_connection() as connection:
|
||||||
|
connection.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO installed_apps (app_id, app_name, version, open_url, manifest_hash, status, installed_at, updated_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
ON CONFLICT(app_id) DO UPDATE SET
|
||||||
|
app_name = excluded.app_name,
|
||||||
|
version = excluded.version,
|
||||||
|
open_url = excluded.open_url,
|
||||||
|
manifest_hash = excluded.manifest_hash,
|
||||||
|
status = excluded.status,
|
||||||
|
updated_at = excluded.updated_at
|
||||||
|
""",
|
||||||
|
(app_id, app_name, version, open_url, manifest_hash, status, now, now),
|
||||||
|
)
|
||||||
|
|
||||||
|
def delete_installed_app(self, app_id: str) -> None:
|
||||||
|
with get_connection() as connection:
|
||||||
|
connection.execute("DELETE FROM installed_components WHERE app_id = ?", (app_id,))
|
||||||
|
connection.execute("DELETE FROM installed_apps WHERE app_id = ?", (app_id,))
|
||||||
|
|
||||||
|
def upsert_installed_component(self, app_id: str, component: dict[str, Any]) -> None:
|
||||||
|
now = utc_now()
|
||||||
|
with get_connection() as connection:
|
||||||
|
connection.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO installed_components (
|
||||||
|
app_id, component_id, type, install_order, status, package_name, package_version,
|
||||||
|
service_name, service_check_status, service_checks_json,
|
||||||
|
docker_image, docker_digest, container_name, compose_project_name,
|
||||||
|
installed_at, updated_at
|
||||||
|
)
|
||||||
|
VALUES (?, ?, ?, ?, 'installed', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
ON CONFLICT(app_id, component_id) DO UPDATE SET
|
||||||
|
type = excluded.type,
|
||||||
|
install_order = excluded.install_order,
|
||||||
|
status = excluded.status,
|
||||||
|
package_name = excluded.package_name,
|
||||||
|
package_version = excluded.package_version,
|
||||||
|
service_name = excluded.service_name,
|
||||||
|
service_check_status = excluded.service_check_status,
|
||||||
|
service_checks_json = excluded.service_checks_json,
|
||||||
|
docker_image = excluded.docker_image,
|
||||||
|
docker_digest = excluded.docker_digest,
|
||||||
|
container_name = excluded.container_name,
|
||||||
|
compose_project_name = excluded.compose_project_name,
|
||||||
|
updated_at = excluded.updated_at
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
app_id,
|
||||||
|
component["componentId"],
|
||||||
|
component["type"],
|
||||||
|
component.get("installOrder", 10),
|
||||||
|
component.get("packageName"),
|
||||||
|
component.get("version"),
|
||||||
|
component.get("serviceName"),
|
||||||
|
component.get("serviceCheckStatus", "not-checked"),
|
||||||
|
_encode_service_checks(component.get("serviceChecks", [])),
|
||||||
|
component.get("image"),
|
||||||
|
component.get("digest"),
|
||||||
|
component.get("containerName"),
|
||||||
|
component.get("projectName"),
|
||||||
|
now,
|
||||||
|
now,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
def list_installed_components(self, app_id: str) -> list[dict[str, Any]]:
|
||||||
|
with get_connection() as connection:
|
||||||
|
rows = connection.execute(
|
||||||
|
"""
|
||||||
|
SELECT *
|
||||||
|
FROM installed_components
|
||||||
|
WHERE app_id = ?
|
||||||
|
ORDER BY install_order ASC, id ASC
|
||||||
|
""",
|
||||||
|
(app_id,),
|
||||||
|
).fetchall()
|
||||||
|
return [_component_row(row) for row in rows]
|
||||||
|
|
||||||
|
def export_manifest_hash(self, manifest: dict[str, Any]) -> str:
|
||||||
|
return json.dumps(manifest, sort_keys=True, separators=(",", ":"))
|
||||||
2
agent/app/utils/__init__.py
Normal file
2
agent/app/utils/__init__.py
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
"""Utility helpers."""
|
||||||
|
|
||||||
137
agent/app/utils/validators.py
Normal file
137
agent/app/utils/validators.py
Normal file
@@ -0,0 +1,137 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
from urllib.parse import urlparse
|
||||||
|
|
||||||
|
|
||||||
|
APP_ID_RE = re.compile(r"^[a-zA-Z0-9._+-]+$")
|
||||||
|
PACKAGE_NAME_RE = re.compile(r"^[a-zA-Z0-9._+-]+$")
|
||||||
|
SERVICE_NAME_RE = re.compile(r"^[a-zA-Z0-9._@+-]+\.service$")
|
||||||
|
VERSION_RE = re.compile(r"^[a-zA-Z0-9._:+~=-]+$")
|
||||||
|
SHA256_RE = re.compile(r"^[0-9a-fA-F]{64}$")
|
||||||
|
DOCKER_DIGEST_RE = re.compile(r"^sha256:[0-9a-fA-F]{64}$")
|
||||||
|
DOCKER_REF_RE = re.compile(r"^[a-z0-9][a-z0-9._:/@+-]{0,254}$")
|
||||||
|
DOCKER_TAG_RE = re.compile(r"^[a-zA-Z0-9_][a-zA-Z0-9_.-]{0,127}$")
|
||||||
|
CONTAINER_NAME_RE = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,127}$")
|
||||||
|
ENV_NAME_RE = re.compile(r"^[a-zA-Z_][a-zA-Z0-9_]*$")
|
||||||
|
PORT_MAPPING_RE = re.compile(r"^[a-zA-Z0-9_.:-]+(?:/(?:tcp|udp|sctp))?$")
|
||||||
|
VOLUME_MAPPING_RE = re.compile(r"^[^\s:]+:[^\s:]+(?::(?:ro|rw))?$")
|
||||||
|
|
||||||
|
|
||||||
|
def validate_app_id(value: str) -> str:
|
||||||
|
if not value or not APP_ID_RE.fullmatch(value):
|
||||||
|
raise ValueError("appId contains invalid characters")
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def validate_package_name(value: str) -> str:
|
||||||
|
if not value or not PACKAGE_NAME_RE.fullmatch(value):
|
||||||
|
raise ValueError("packageName contains invalid characters")
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def validate_service_name(value: str | None) -> str | None:
|
||||||
|
if value is None or value == "":
|
||||||
|
return None
|
||||||
|
if not SERVICE_NAME_RE.fullmatch(value):
|
||||||
|
raise ValueError("serviceName must be a systemd .service name")
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def validate_version(value: str) -> str:
|
||||||
|
if not value or not VERSION_RE.fullmatch(value):
|
||||||
|
raise ValueError("version contains invalid characters")
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def validate_sha256(value: str) -> str:
|
||||||
|
if not value or not SHA256_RE.fullmatch(value):
|
||||||
|
raise ValueError("sha256/checksum must be a 64 character hex digest")
|
||||||
|
return value.lower()
|
||||||
|
|
||||||
|
|
||||||
|
def validate_url_host(url: str, allowed_hosts: list[str]) -> str:
|
||||||
|
parsed = urlparse(url)
|
||||||
|
if parsed.scheme not in {"http", "https"}:
|
||||||
|
raise ValueError("download URL must use http or https")
|
||||||
|
if not parsed.hostname:
|
||||||
|
raise ValueError("download URL is missing a host")
|
||||||
|
if parsed.hostname not in set(allowed_hosts):
|
||||||
|
raise ValueError(f"download host is not allowed: {parsed.hostname}")
|
||||||
|
return url
|
||||||
|
|
||||||
|
|
||||||
|
def validate_docker_image(value: str) -> str:
|
||||||
|
image = value.strip()
|
||||||
|
if not image or not DOCKER_REF_RE.fullmatch(image):
|
||||||
|
raise ValueError("docker image contains invalid characters")
|
||||||
|
if "//" in image or image.endswith(("/", ":", "@")):
|
||||||
|
raise ValueError("docker image reference is malformed")
|
||||||
|
return image
|
||||||
|
|
||||||
|
|
||||||
|
def validate_docker_tag(value: str | None) -> str | None:
|
||||||
|
if value is None or value == "":
|
||||||
|
return None
|
||||||
|
tag = value.strip()
|
||||||
|
if not DOCKER_TAG_RE.fullmatch(tag):
|
||||||
|
raise ValueError("docker tag contains invalid characters")
|
||||||
|
return tag
|
||||||
|
|
||||||
|
|
||||||
|
def validate_docker_digest(value: str | None) -> str | None:
|
||||||
|
if value is None or value == "":
|
||||||
|
return None
|
||||||
|
digest = value.strip()
|
||||||
|
if not DOCKER_DIGEST_RE.fullmatch(digest):
|
||||||
|
raise ValueError("docker digest must be sha256:<64 hex characters>")
|
||||||
|
return digest.lower()
|
||||||
|
|
||||||
|
|
||||||
|
def validate_docker_registry(image: str, allowed_registries: list[str]) -> str:
|
||||||
|
reference = image.split("@", 1)[0]
|
||||||
|
parts = reference.split("/", 1)
|
||||||
|
first_part = parts[0]
|
||||||
|
has_explicit_registry = len(parts) > 1 and (
|
||||||
|
"." in first_part or ":" in first_part or first_part == "localhost"
|
||||||
|
)
|
||||||
|
registry = first_part if has_explicit_registry else "docker.io"
|
||||||
|
allowed = {item.strip() for item in allowed_registries if item.strip()}
|
||||||
|
if "*" not in allowed and registry not in allowed:
|
||||||
|
raise ValueError(f"docker registry is not allowed: {registry}")
|
||||||
|
return image
|
||||||
|
|
||||||
|
|
||||||
|
def validate_container_name(value: str) -> str:
|
||||||
|
name = value.strip()
|
||||||
|
if not name or not CONTAINER_NAME_RE.fullmatch(name):
|
||||||
|
raise ValueError("containerName contains invalid characters")
|
||||||
|
return name
|
||||||
|
|
||||||
|
|
||||||
|
def validate_restart_policy(value: str | None) -> str:
|
||||||
|
policy = (value or "unless-stopped").strip()
|
||||||
|
if policy not in {"no", "always", "unless-stopped", "on-failure"}:
|
||||||
|
raise ValueError("restartPolicy must be one of: no, always, unless-stopped, on-failure")
|
||||||
|
return policy
|
||||||
|
|
||||||
|
|
||||||
|
def validate_port_mapping(value: str) -> str:
|
||||||
|
mapping = value.strip()
|
||||||
|
if not mapping or not PORT_MAPPING_RE.fullmatch(mapping):
|
||||||
|
raise ValueError("docker port mapping contains invalid characters")
|
||||||
|
return mapping
|
||||||
|
|
||||||
|
|
||||||
|
def validate_volume_mapping(value: str) -> str:
|
||||||
|
mapping = value.strip()
|
||||||
|
if not mapping or not VOLUME_MAPPING_RE.fullmatch(mapping):
|
||||||
|
raise ValueError("docker volume mapping must be hostPath:containerPath[:ro|rw]")
|
||||||
|
return mapping
|
||||||
|
|
||||||
|
|
||||||
|
def validate_env_name(value: str) -> str:
|
||||||
|
name = value.strip()
|
||||||
|
if not ENV_NAME_RE.fullmatch(name):
|
||||||
|
raise ValueError("docker env names may contain only letters, numbers, and underscore")
|
||||||
|
return name
|
||||||
10
agent/packaging/DEBIAN/control
Normal file
10
agent/packaging/DEBIAN/control
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
Package: local-installer-agent
|
||||||
|
Version: 1.0.4
|
||||||
|
Section: utils
|
||||||
|
Priority: optional
|
||||||
|
Architecture: amd64
|
||||||
|
Maintainer: Robot Team <admin@robot.package>
|
||||||
|
Depends: python3, python3-venv, python3-pip, curl
|
||||||
|
Description: Local Installer Agent for robot.installer
|
||||||
|
A local background service that installs, updates, and removes trusted .deb,
|
||||||
|
APT repository packages, and Docker apps on the user's Linux machine.
|
||||||
57
agent/packaging/DEBIAN/postinst
Normal file
57
agent/packaging/DEBIAN/postinst
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
set -e
|
||||||
|
|
||||||
|
mkdir -p /var/lib/local-installer-agent
|
||||||
|
mkdir -p /var/log/local-installer-agent
|
||||||
|
mkdir -p /var/cache/local-installer-agent/packages
|
||||||
|
mkdir -p /etc/local-installer-agent
|
||||||
|
|
||||||
|
AGENT_ENV="/etc/local-installer-agent/agent.env"
|
||||||
|
touch "$AGENT_ENV"
|
||||||
|
|
||||||
|
set_agent_env() {
|
||||||
|
KEY="$1"
|
||||||
|
VALUE="$2"
|
||||||
|
|
||||||
|
if grep -q "^$KEY=" "$AGENT_ENV"; then
|
||||||
|
sed -i "s|^$KEY=.*|$KEY=$VALUE|" "$AGENT_ENV"
|
||||||
|
else
|
||||||
|
echo "$KEY=$VALUE" >> "$AGENT_ENV"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
append_csv_env() {
|
||||||
|
KEY="$1"
|
||||||
|
VALUE="$2"
|
||||||
|
|
||||||
|
CURRENT="$(grep "^$KEY=" "$AGENT_ENV" | tail -n 1 | cut -d= -f2- || true)"
|
||||||
|
if [ -z "$CURRENT" ]; then
|
||||||
|
set_agent_env "$KEY" "$VALUE"
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
|
||||||
|
case ",$CURRENT," in
|
||||||
|
*",$VALUE,"*) ;;
|
||||||
|
*) set_agent_env "$KEY" "$CURRENT,$VALUE" ;;
|
||||||
|
esac
|
||||||
|
}
|
||||||
|
|
||||||
|
set_agent_env ALLOW_DOCKER true
|
||||||
|
set_agent_env ALLOW_PURGE true
|
||||||
|
set_agent_env AUTO_INSTALL_DOCKER true
|
||||||
|
append_csv_env ALLOWED_DOCKER_REGISTRIES docker.io
|
||||||
|
|
||||||
|
cd /opt/local-installer-agent
|
||||||
|
|
||||||
|
if [ ! -d "venv" ]; then
|
||||||
|
python3 -m venv venv
|
||||||
|
fi
|
||||||
|
|
||||||
|
./venv/bin/pip install --upgrade pip
|
||||||
|
./venv/bin/pip install -r requirements.txt
|
||||||
|
|
||||||
|
systemctl daemon-reload
|
||||||
|
systemctl enable local-installer-agent
|
||||||
|
systemctl restart local-installer-agent
|
||||||
|
|
||||||
|
exit 0
|
||||||
6
agent/packaging/DEBIAN/postrm
Normal file
6
agent/packaging/DEBIAN/postrm
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
set -e
|
||||||
|
|
||||||
|
systemctl daemon-reload
|
||||||
|
|
||||||
|
exit 0
|
||||||
8
agent/packaging/DEBIAN/prerm
Normal file
8
agent/packaging/DEBIAN/prerm
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
set -e
|
||||||
|
|
||||||
|
if systemctl is-active --quiet local-installer-agent; then
|
||||||
|
systemctl stop local-installer-agent
|
||||||
|
fi
|
||||||
|
|
||||||
|
exit 0
|
||||||
13
agent/packaging/systemd/local-installer-agent.service
Normal file
13
agent/packaging/systemd/local-installer-agent.service
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=Local Installer Agent
|
||||||
|
After=network.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
WorkingDirectory=/opt/local-installer-agent
|
||||||
|
ExecStart=/opt/local-installer-agent/venv/bin/python -m uvicorn app.main:app --host ${AGENT_HOST} --port ${AGENT_PORT}
|
||||||
|
Restart=always
|
||||||
|
User=root
|
||||||
|
EnvironmentFile=/etc/local-installer-agent/agent.env
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
4
agent/requirements.txt
Normal file
4
agent/requirements.txt
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
fastapi>=0.115,<1.0
|
||||||
|
uvicorn[standard]>=0.30,<1.0
|
||||||
|
pydantic>=2,<3
|
||||||
|
httpx>=0.27,<1.0
|
||||||
94
agent/scripts/build-deb.sh
Normal file
94
agent/scripts/build-deb.sh
Normal file
@@ -0,0 +1,94 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
VERSION="${VERSION:-1.0.4}"
|
||||||
|
ARCH="${ARCH:-amd64}"
|
||||||
|
AGENT_HOST="${AGENT_HOST:-0.0.0.0}"
|
||||||
|
AGENT_PORT="${AGENT_PORT:-5010}"
|
||||||
|
ALLOWED_APT_PACKAGES="${ALLOWED_APT_PACKAGES:-*}"
|
||||||
|
DEB_COMPRESSION="${DEB_COMPRESSION:-gzip}"
|
||||||
|
PKG_NAME="local-installer-agent"
|
||||||
|
BUILD_ROOT="${BUILD_ROOT:-build}"
|
||||||
|
BUILD_DIR="${BUILD_ROOT}/${PKG_NAME}_${VERSION}_${ARCH}"
|
||||||
|
OUTPUT_PACKAGE="${BUILD_DIR}.deb"
|
||||||
|
|
||||||
|
if [[ ! "$VERSION" =~ ^[a-zA-Z0-9][a-zA-Z0-9._:+~=-]*$ ]]; then
|
||||||
|
echo "Invalid VERSION: ${VERSION}" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ ! "$ARCH" =~ ^[a-z0-9][a-z0-9._-]*$ ]]; then
|
||||||
|
echo "Invalid ARCH: ${ARCH}" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ "$ALLOWED_APT_PACKAGES" != "*" && ! "$ALLOWED_APT_PACKAGES" =~ ^[a-zA-Z0-9._+-]+(,[a-zA-Z0-9._+-]+)*$ ]]; then
|
||||||
|
echo "Invalid ALLOWED_APT_PACKAGES: ${ALLOWED_APT_PACKAGES}" >&2
|
||||||
|
echo "Use * for any valid APT package or a comma-separated list without spaces." >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
rm -rf "${BUILD_DIR}"
|
||||||
|
rm -f "${OUTPUT_PACKAGE}"
|
||||||
|
|
||||||
|
mkdir -p "${BUILD_DIR}/opt/local-installer-agent"
|
||||||
|
mkdir -p "${BUILD_DIR}/etc/local-installer-agent"
|
||||||
|
mkdir -p "${BUILD_DIR}/etc/systemd/system"
|
||||||
|
mkdir -p "${BUILD_DIR}/DEBIAN"
|
||||||
|
|
||||||
|
cp -r app "${BUILD_DIR}/opt/local-installer-agent/"
|
||||||
|
cp requirements.txt "${BUILD_DIR}/opt/local-installer-agent/"
|
||||||
|
|
||||||
|
find "${BUILD_DIR}/opt/local-installer-agent/app" \
|
||||||
|
\( -type d -name "__pycache__" -o -type f \( -name "*.pyc" -o -name "*.pyo" \) \) \
|
||||||
|
-exec rm -rf {} +
|
||||||
|
|
||||||
|
cp packaging/systemd/local-installer-agent.service \
|
||||||
|
"${BUILD_DIR}/etc/systemd/system/local-installer-agent.service"
|
||||||
|
|
||||||
|
cp packaging/DEBIAN/control "${BUILD_DIR}/DEBIAN/control"
|
||||||
|
cp packaging/DEBIAN/postinst "${BUILD_DIR}/DEBIAN/postinst"
|
||||||
|
cp packaging/DEBIAN/prerm "${BUILD_DIR}/DEBIAN/prerm"
|
||||||
|
cp packaging/DEBIAN/postrm "${BUILD_DIR}/DEBIAN/postrm"
|
||||||
|
|
||||||
|
sed -i \
|
||||||
|
-e "s/^Version:.*/Version: ${VERSION}/" \
|
||||||
|
-e "s/^Architecture:.*/Architecture: ${ARCH}/" \
|
||||||
|
"${BUILD_DIR}/DEBIAN/control"
|
||||||
|
|
||||||
|
chmod 755 "${BUILD_DIR}/DEBIAN/postinst"
|
||||||
|
chmod 755 "${BUILD_DIR}/DEBIAN/prerm"
|
||||||
|
chmod 755 "${BUILD_DIR}/DEBIAN/postrm"
|
||||||
|
chmod 755 "${BUILD_DIR}/DEBIAN"
|
||||||
|
|
||||||
|
cat > "${BUILD_DIR}/etc/local-installer-agent/agent.env" <<EOF
|
||||||
|
AGENT_VERSION=${VERSION}
|
||||||
|
AGENT_HOST=${AGENT_HOST}
|
||||||
|
AGENT_PORT=${AGENT_PORT}
|
||||||
|
ROBOT_PACKAGE_BASE_URL=https://package.pnkr.cloud
|
||||||
|
ALLOWED_ORIGINS=https://app.pnkr.cloud,https://package.pnkr.cloud,http://localhost:3000,http://127.0.0.1:3000,http://localhost:5173,http://127.0.0.1:5173,http://localhost:8080,http://127.0.0.1:8080
|
||||||
|
ALLOWED_DOWNLOAD_HOSTS=package.pnkr.cloud
|
||||||
|
ALLOWED_APT_PACKAGES=${ALLOWED_APT_PACKAGES}
|
||||||
|
ALLOWED_DOCKER_REGISTRIES=registry.robot.package,docker.io
|
||||||
|
CACHE_DIR=/var/cache/local-installer-agent/packages
|
||||||
|
APP_DIR=/opt/robot-apps
|
||||||
|
LOG_DIR=/var/log/local-installer-agent
|
||||||
|
DB_PATH=/var/lib/local-installer-agent/agent.db
|
||||||
|
ALLOW_REMOVE=true
|
||||||
|
ALLOW_PURGE=true
|
||||||
|
ALLOW_DOCKER=true
|
||||||
|
ALLOW_DOCKER_COMPOSE=false
|
||||||
|
AUTO_INSTALL_DOCKER=true
|
||||||
|
EOF
|
||||||
|
|
||||||
|
dpkg-deb -Z"${DEB_COMPRESSION}" --root-owner-group --build "${BUILD_DIR}"
|
||||||
|
|
||||||
|
echo "Built package:"
|
||||||
|
echo "${OUTPUT_PACKAGE}"
|
||||||
|
|
||||||
|
if [ -n "${PUBLISH_DIR:-}" ]; then
|
||||||
|
mkdir -p "${PUBLISH_DIR}"
|
||||||
|
cp "${OUTPUT_PACKAGE}" "${PUBLISH_DIR}/"
|
||||||
|
echo "Published package:"
|
||||||
|
echo "${PUBLISH_DIR}/$(basename "${OUTPUT_PACKAGE}")"
|
||||||
|
fi
|
||||||
23
agent/scripts/install-agent.sh
Normal file
23
agent/scripts/install-agent.sh
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
AGENT_BASE_URL="${AGENT_BASE_URL:-https://robot.package}"
|
||||||
|
ARCH="${ARCH:-$(dpkg --print-architecture)}"
|
||||||
|
AGENT_URL="${AGENT_URL:-${AGENT_BASE_URL%/}/packages/agent/latest.deb?arch=${ARCH}}"
|
||||||
|
TMP_DEB="/tmp/local-installer-agent.deb"
|
||||||
|
|
||||||
|
echo "Downloading Local Installer Agent..."
|
||||||
|
curl -fL "$AGENT_URL" -o "$TMP_DEB"
|
||||||
|
|
||||||
|
echo "Installing Local Installer Agent..."
|
||||||
|
apt install -y "$TMP_DEB"
|
||||||
|
|
||||||
|
echo "Starting Local Installer Agent..."
|
||||||
|
systemctl enable local-installer-agent
|
||||||
|
systemctl restart local-installer-agent
|
||||||
|
|
||||||
|
echo "Checking Agent..."
|
||||||
|
curl -fsSL http://127.0.0.1:5010/health
|
||||||
|
|
||||||
|
echo ""
|
||||||
|
echo "Local Installer Agent installed successfully."
|
||||||
488
agent/tests/test_apt_components.py
Normal file
488
agent/tests/test_apt_components.py
Normal file
@@ -0,0 +1,488 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import subprocess
|
||||||
|
import unittest
|
||||||
|
from types import SimpleNamespace
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
from app.core.command_runner import CommandError
|
||||||
|
from app.core.installer import APT_NONINTERACTIVE_ENV, AptInstaller
|
||||||
|
from app.core.manifest_validator import ManifestValidator
|
||||||
|
from app.core.service_manager import ServiceManager
|
||||||
|
from app.core.task_runner import InstalledComponentVerificationError, TaskRunner
|
||||||
|
|
||||||
|
|
||||||
|
def apt_manifest(component: dict | None = None) -> dict:
|
||||||
|
return {
|
||||||
|
"schemaVersion": "1.0",
|
||||||
|
"appId": "postgresql",
|
||||||
|
"appName": "PostgreSQL",
|
||||||
|
"version": "16",
|
||||||
|
"components": [
|
||||||
|
component
|
||||||
|
or {
|
||||||
|
"componentId": "postgresql",
|
||||||
|
"type": "apt",
|
||||||
|
"packageName": "postgresql",
|
||||||
|
"version": "16",
|
||||||
|
}
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class FakeCommandRunner:
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self.calls: list[tuple[list[str], int | None, dict[str, str] | None]] = []
|
||||||
|
|
||||||
|
def run(
|
||||||
|
self,
|
||||||
|
command: list[str],
|
||||||
|
timeout: int | None = None,
|
||||||
|
env: dict[str, str] | None = None,
|
||||||
|
log_output: bool = True,
|
||||||
|
) -> subprocess.CompletedProcess[str]:
|
||||||
|
self.calls.append((command, timeout, env))
|
||||||
|
return subprocess.CompletedProcess(command, 0, stdout="accepting connections\n", stderr="")
|
||||||
|
|
||||||
|
|
||||||
|
class AptManifestTests(unittest.TestCase):
|
||||||
|
def test_wildcard_accepts_any_valid_apt_package_name(self) -> None:
|
||||||
|
validator_settings = SimpleNamespace(allowed_apt_packages=["*"])
|
||||||
|
with patch("app.core.manifest_validator.settings", validator_settings):
|
||||||
|
manifest = ManifestValidator().validate(
|
||||||
|
apt_manifest(
|
||||||
|
{
|
||||||
|
"componentId": "nginx-extras",
|
||||||
|
"type": "apt",
|
||||||
|
"packageName": "nginx-extras",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(manifest["components"][0]["packageName"], "nginx-extras")
|
||||||
|
|
||||||
|
def test_postgresql_is_accepted_when_allowlisted(self) -> None:
|
||||||
|
validator_settings = SimpleNamespace(allowed_apt_packages=["postgresql"])
|
||||||
|
with patch("app.core.manifest_validator.settings", validator_settings):
|
||||||
|
manifest = ManifestValidator().validate(apt_manifest())
|
||||||
|
|
||||||
|
self.assertEqual(manifest["components"][0]["type"], "apt")
|
||||||
|
self.assertEqual(manifest["components"][0]["packageName"], "postgresql")
|
||||||
|
|
||||||
|
def test_any_package_in_a_multi_package_allowlist_is_accepted(self) -> None:
|
||||||
|
validator_settings = SimpleNamespace(
|
||||||
|
allowed_apt_packages=["postgresql", "nginx", "redis-server"]
|
||||||
|
)
|
||||||
|
with patch("app.core.manifest_validator.settings", validator_settings):
|
||||||
|
manifest = ManifestValidator().validate(
|
||||||
|
apt_manifest(
|
||||||
|
{
|
||||||
|
"componentId": "redis-server",
|
||||||
|
"type": "apt",
|
||||||
|
"packageName": "redis-server",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(manifest["components"][0]["packageName"], "redis-server")
|
||||||
|
|
||||||
|
def test_non_allowlisted_package_is_rejected(self) -> None:
|
||||||
|
validator_settings = SimpleNamespace(allowed_apt_packages=["postgresql"])
|
||||||
|
with patch("app.core.manifest_validator.settings", validator_settings):
|
||||||
|
with self.assertRaisesRegex(ValueError, "APT package is not allowed"):
|
||||||
|
ManifestValidator().validate(
|
||||||
|
apt_manifest(
|
||||||
|
{
|
||||||
|
"componentId": "curl",
|
||||||
|
"type": "apt",
|
||||||
|
"packageName": "curl",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_manifest_cannot_supply_a_shell_command(self) -> None:
|
||||||
|
validator_settings = SimpleNamespace(allowed_apt_packages=["postgresql"])
|
||||||
|
with patch("app.core.manifest_validator.settings", validator_settings):
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
ManifestValidator().validate(
|
||||||
|
apt_manifest(
|
||||||
|
{
|
||||||
|
"componentId": "postgresql",
|
||||||
|
"type": "apt",
|
||||||
|
"packageName": "postgresql",
|
||||||
|
"command": "rm -rf /",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class AptInstallerTests(unittest.TestCase):
|
||||||
|
def test_apt_commands_are_fixed_argument_lists(self) -> None:
|
||||||
|
runner = FakeCommandRunner()
|
||||||
|
installer = AptInstaller(runner)
|
||||||
|
|
||||||
|
installer.update_package_index()
|
||||||
|
installer.install_package("postgresql")
|
||||||
|
installer.wait_for_postgresql(attempts=1, delay_seconds=0)
|
||||||
|
self.assertTrue(installer.is_postgresql_ready())
|
||||||
|
|
||||||
|
self.assertEqual(runner.calls[0][0], ["apt-get", "update"])
|
||||||
|
self.assertEqual(
|
||||||
|
runner.calls[1][0],
|
||||||
|
[
|
||||||
|
"apt-get",
|
||||||
|
"-o",
|
||||||
|
"Dpkg::Use-Pty=0",
|
||||||
|
"-o",
|
||||||
|
"Dpkg::Options::=--force-confdef",
|
||||||
|
"-o",
|
||||||
|
"Dpkg::Options::=--force-confold",
|
||||||
|
"install",
|
||||||
|
"--yes",
|
||||||
|
"postgresql",
|
||||||
|
],
|
||||||
|
)
|
||||||
|
self.assertEqual(runner.calls[1][2], APT_NONINTERACTIVE_ENV)
|
||||||
|
self.assertEqual(runner.calls[2][0], ["pg_isready", "--timeout=5"])
|
||||||
|
self.assertEqual(runner.calls[3][0], ["pg_isready", "--timeout=5"])
|
||||||
|
|
||||||
|
def test_discovers_concrete_service_units_without_shell_commands(self) -> None:
|
||||||
|
class PackageFileRunner(FakeCommandRunner):
|
||||||
|
def run(
|
||||||
|
self,
|
||||||
|
command: list[str],
|
||||||
|
timeout: int | None = None,
|
||||||
|
env: dict[str, str] | None = None,
|
||||||
|
log_output: bool = True,
|
||||||
|
) -> subprocess.CompletedProcess[str]:
|
||||||
|
self.calls.append((command, timeout, env))
|
||||||
|
return subprocess.CompletedProcess(
|
||||||
|
command,
|
||||||
|
0,
|
||||||
|
stdout=(
|
||||||
|
"/usr/lib/systemd/system/example.service\n"
|
||||||
|
"/lib/systemd/system/example-worker.service\n"
|
||||||
|
"/lib/systemd/system/example@.service\n"
|
||||||
|
"/usr/share/doc/example/README\n"
|
||||||
|
),
|
||||||
|
stderr="",
|
||||||
|
)
|
||||||
|
|
||||||
|
runner = PackageFileRunner()
|
||||||
|
services = AptInstaller(runner).discover_service_units("example")
|
||||||
|
|
||||||
|
self.assertEqual(services, ["example-worker.service", "example.service"])
|
||||||
|
self.assertEqual(runner.calls[0][0], ["dpkg-query", "-L", "example"])
|
||||||
|
|
||||||
|
|
||||||
|
class ServiceManagerTests(unittest.TestCase):
|
||||||
|
def test_reports_full_active_service_state(self) -> None:
|
||||||
|
class StatusRunner:
|
||||||
|
def run(self, command: list[str], timeout: int | None = None) -> subprocess.CompletedProcess[str]:
|
||||||
|
return subprocess.CompletedProcess(
|
||||||
|
command,
|
||||||
|
0,
|
||||||
|
stdout=(
|
||||||
|
"LoadState=loaded\n"
|
||||||
|
"ActiveState=active\n"
|
||||||
|
"SubState=running\n"
|
||||||
|
"UnitFileState=enabled\n"
|
||||||
|
),
|
||||||
|
stderr="",
|
||||||
|
)
|
||||||
|
|
||||||
|
status = ServiceManager(StatusRunner()).get_service_status("example.service")
|
||||||
|
|
||||||
|
self.assertTrue(status["active"])
|
||||||
|
self.assertTrue(status["enabled"])
|
||||||
|
self.assertTrue(status["healthy"])
|
||||||
|
self.assertEqual(status["status"], "active")
|
||||||
|
self.assertEqual(status["subState"], "running")
|
||||||
|
|
||||||
|
def test_preserves_inactive_state_from_nonzero_systemctl_result(self) -> None:
|
||||||
|
class InactiveRunner:
|
||||||
|
def run(self, command: list[str], timeout: int | None = None) -> subprocess.CompletedProcess[str]:
|
||||||
|
stdout = (
|
||||||
|
"LoadState=loaded\n"
|
||||||
|
"ActiveState=inactive\n"
|
||||||
|
"SubState=dead\n"
|
||||||
|
"UnitFileState=disabled\n"
|
||||||
|
)
|
||||||
|
raise CommandError(command, 3, stdout, "")
|
||||||
|
|
||||||
|
status = ServiceManager(InactiveRunner()).get_service_status("example.service")
|
||||||
|
|
||||||
|
self.assertFalse(status["active"])
|
||||||
|
self.assertFalse(status["healthy"])
|
||||||
|
self.assertEqual(status["activeState"], "inactive")
|
||||||
|
self.assertEqual(status["unitFileState"], "disabled")
|
||||||
|
|
||||||
|
|
||||||
|
class FakeRepository:
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self.component_updates: list[dict] = []
|
||||||
|
self.logs: list[tuple[str, str]] = []
|
||||||
|
self.installed_component: dict | None = None
|
||||||
|
|
||||||
|
def update_task_component(self, task_id: str, component_id: str, **fields: object) -> None:
|
||||||
|
self.component_updates.append(dict(fields))
|
||||||
|
|
||||||
|
def add_log(self, task_id: str, level: str, message: str) -> None:
|
||||||
|
self.logs.append((level, message))
|
||||||
|
|
||||||
|
def upsert_installed_component(self, app_id: str, component: dict) -> None:
|
||||||
|
self.installed_component = component
|
||||||
|
|
||||||
|
|
||||||
|
class FakeRunRepository:
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self.task = {"current_component_id": "postgresql"}
|
||||||
|
self.task_updates: list[dict] = []
|
||||||
|
self.logs: list[tuple[str, str]] = []
|
||||||
|
self.installed_app_updates: list[dict] = []
|
||||||
|
|
||||||
|
def update_task(self, task_id: str, **fields: object) -> None:
|
||||||
|
self.task_updates.append(dict(fields))
|
||||||
|
|
||||||
|
def update_task_component(self, task_id: str, component_id: str, **fields: object) -> None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
def add_log(self, task_id: str, level: str, message: str) -> None:
|
||||||
|
self.logs.append((level, message))
|
||||||
|
|
||||||
|
def get_task(self, task_id: str) -> dict:
|
||||||
|
return self.task
|
||||||
|
|
||||||
|
def export_manifest_hash(self, manifest: dict) -> str:
|
||||||
|
return "manifest"
|
||||||
|
|
||||||
|
def upsert_installed_app(
|
||||||
|
self,
|
||||||
|
app_id: str,
|
||||||
|
app_name: str,
|
||||||
|
version: str,
|
||||||
|
manifest_hash: str,
|
||||||
|
open_url: str | None,
|
||||||
|
status: str = "installed",
|
||||||
|
) -> None:
|
||||||
|
self.installed_app_updates.append(
|
||||||
|
{"app_id": app_id, "version": version, "status": status}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class FakeAptInstaller:
|
||||||
|
actions: list[str] = []
|
||||||
|
|
||||||
|
def __init__(self, command_runner: object) -> None:
|
||||||
|
self.command_runner = command_runner
|
||||||
|
|
||||||
|
def update_package_index(self) -> None:
|
||||||
|
self.actions.append("update")
|
||||||
|
|
||||||
|
def install_package(self, package_name: str) -> None:
|
||||||
|
self.actions.append(f"install:{package_name}")
|
||||||
|
|
||||||
|
def get_package_version(self, package_name: str) -> str:
|
||||||
|
self.actions.append(f"version:{package_name}")
|
||||||
|
return "16+257build1"
|
||||||
|
|
||||||
|
def wait_for_postgresql(self) -> None:
|
||||||
|
self.actions.append("pg_isready")
|
||||||
|
|
||||||
|
def discover_service_units(self, package_name: str) -> list[str]:
|
||||||
|
self.actions.append(f"discover:{package_name}")
|
||||||
|
return []
|
||||||
|
|
||||||
|
|
||||||
|
class FakeServiceManager:
|
||||||
|
actions: list[str] = []
|
||||||
|
|
||||||
|
def __init__(self, command_runner: object) -> None:
|
||||||
|
self.command_runner = command_runner
|
||||||
|
|
||||||
|
def enable_service(self, service_name: str) -> None:
|
||||||
|
self.actions.append(f"enable:{service_name}")
|
||||||
|
|
||||||
|
def start_service(self, service_name: str) -> None:
|
||||||
|
self.actions.append(f"start:{service_name}")
|
||||||
|
|
||||||
|
def assert_service_active(self, service_name: str) -> None:
|
||||||
|
self.actions.append(f"active:{service_name}")
|
||||||
|
|
||||||
|
def get_service_status(self, service_name: str) -> dict[str, object]:
|
||||||
|
self.actions.append(f"status:{service_name}")
|
||||||
|
return {
|
||||||
|
"serviceName": service_name,
|
||||||
|
"loadState": "loaded",
|
||||||
|
"activeState": "active",
|
||||||
|
"subState": "running",
|
||||||
|
"unitFileState": "enabled",
|
||||||
|
"active": True,
|
||||||
|
"enabled": True,
|
||||||
|
"healthy": True,
|
||||||
|
"status": "active",
|
||||||
|
"checkedAt": "2026-07-20T00:00:00Z",
|
||||||
|
"errorMessage": None,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class AptTaskRunnerTests(unittest.TestCase):
|
||||||
|
def test_only_post_install_verification_failure_marks_app_attention(self) -> None:
|
||||||
|
manifest = apt_manifest()
|
||||||
|
repository = FakeRunRepository()
|
||||||
|
runner = TaskRunner(repository)
|
||||||
|
|
||||||
|
with (
|
||||||
|
patch.object(runner, "_require_root_if_available"),
|
||||||
|
patch.object(runner, "_resolve_manifest", return_value=manifest),
|
||||||
|
patch.object(
|
||||||
|
runner,
|
||||||
|
"_install_manifest",
|
||||||
|
side_effect=InstalledComponentVerificationError("service unhealthy"),
|
||||||
|
),
|
||||||
|
):
|
||||||
|
runner.run_install("task-attention", SimpleNamespace(), "install")
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
repository.installed_app_updates,
|
||||||
|
[{"app_id": "postgresql", "version": "16", "status": "attention"}],
|
||||||
|
)
|
||||||
|
self.assertEqual(repository.task_updates[-1]["status"], "failed")
|
||||||
|
|
||||||
|
def test_early_install_failure_does_not_overwrite_installed_app_version(self) -> None:
|
||||||
|
manifest = apt_manifest()
|
||||||
|
repository = FakeRunRepository()
|
||||||
|
runner = TaskRunner(repository)
|
||||||
|
|
||||||
|
with (
|
||||||
|
patch.object(runner, "_require_root_if_available"),
|
||||||
|
patch.object(runner, "_resolve_manifest", return_value=manifest),
|
||||||
|
patch.object(runner, "_install_manifest", side_effect=RuntimeError("apt update failed")),
|
||||||
|
):
|
||||||
|
runner.run_install("task-early-failure", SimpleNamespace(), "update")
|
||||||
|
|
||||||
|
self.assertEqual(repository.installed_app_updates, [])
|
||||||
|
self.assertEqual(repository.task_updates[-1]["status"], "failed")
|
||||||
|
|
||||||
|
def test_postgresql_install_verifies_service_and_readiness(self) -> None:
|
||||||
|
repository = FakeRepository()
|
||||||
|
FakeAptInstaller.actions = []
|
||||||
|
FakeServiceManager.actions = []
|
||||||
|
|
||||||
|
with (
|
||||||
|
patch("app.core.task_runner.CommandRunner", return_value=object()),
|
||||||
|
patch("app.core.task_runner.AptInstaller", FakeAptInstaller),
|
||||||
|
patch("app.core.task_runner.ServiceManager", FakeServiceManager),
|
||||||
|
):
|
||||||
|
TaskRunner(repository)._install_apt_component(
|
||||||
|
"task-1",
|
||||||
|
"postgresql-app",
|
||||||
|
{
|
||||||
|
"componentId": "postgresql",
|
||||||
|
"type": "apt",
|
||||||
|
"packageName": "postgresql",
|
||||||
|
"version": "16",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
FakeAptInstaller.actions,
|
||||||
|
[
|
||||||
|
"update",
|
||||||
|
"install:postgresql",
|
||||||
|
"version:postgresql",
|
||||||
|
"discover:postgresql",
|
||||||
|
"pg_isready",
|
||||||
|
],
|
||||||
|
)
|
||||||
|
self.assertEqual(
|
||||||
|
FakeServiceManager.actions,
|
||||||
|
[
|
||||||
|
"enable:postgresql.service",
|
||||||
|
"start:postgresql.service",
|
||||||
|
"status:postgresql.service",
|
||||||
|
],
|
||||||
|
)
|
||||||
|
self.assertEqual(repository.installed_component["version"], "16+257build1")
|
||||||
|
self.assertEqual(repository.installed_component["serviceName"], "postgresql.service")
|
||||||
|
self.assertEqual(repository.installed_component["serviceCheckStatus"], "healthy")
|
||||||
|
self.assertEqual(repository.installed_component["serviceChecks"][0]["readinessType"], "postgresql")
|
||||||
|
self.assertEqual(repository.installed_component["serviceChecks"][0]["readinessStatus"], "ready")
|
||||||
|
self.assertEqual(repository.component_updates[-1]["service_check_status"], "healthy")
|
||||||
|
self.assertEqual(repository.component_updates[-1]["current_step"], "service checks completed")
|
||||||
|
|
||||||
|
def test_generic_apt_service_is_checked_but_not_started_automatically(self) -> None:
|
||||||
|
class GenericAptInstaller(FakeAptInstaller):
|
||||||
|
def discover_service_units(self, package_name: str) -> list[str]:
|
||||||
|
self.actions.append(f"discover:{package_name}")
|
||||||
|
return ["example.service"]
|
||||||
|
|
||||||
|
class InactiveServiceManager(FakeServiceManager):
|
||||||
|
def get_service_status(self, service_name: str) -> dict[str, object]:
|
||||||
|
self.actions.append(f"status:{service_name}")
|
||||||
|
return {
|
||||||
|
"serviceName": service_name,
|
||||||
|
"loadState": "loaded",
|
||||||
|
"activeState": "inactive",
|
||||||
|
"subState": "dead",
|
||||||
|
"unitFileState": "disabled",
|
||||||
|
"active": False,
|
||||||
|
"enabled": False,
|
||||||
|
"healthy": False,
|
||||||
|
"status": "inactive",
|
||||||
|
"checkedAt": "2026-07-20T00:00:00Z",
|
||||||
|
"errorMessage": None,
|
||||||
|
}
|
||||||
|
|
||||||
|
repository = FakeRepository()
|
||||||
|
FakeAptInstaller.actions = []
|
||||||
|
FakeServiceManager.actions = []
|
||||||
|
|
||||||
|
with (
|
||||||
|
patch("app.core.task_runner.CommandRunner", return_value=object()),
|
||||||
|
patch("app.core.task_runner.AptInstaller", GenericAptInstaller),
|
||||||
|
patch("app.core.task_runner.ServiceManager", InactiveServiceManager),
|
||||||
|
):
|
||||||
|
TaskRunner(repository)._install_apt_component(
|
||||||
|
"task-2",
|
||||||
|
"example-app",
|
||||||
|
{
|
||||||
|
"componentId": "example",
|
||||||
|
"type": "apt",
|
||||||
|
"packageName": "example",
|
||||||
|
"version": "1",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertNotIn("start:example.service", FakeServiceManager.actions)
|
||||||
|
self.assertNotIn("enable:example.service", FakeServiceManager.actions)
|
||||||
|
self.assertIn("status:example.service", FakeServiceManager.actions)
|
||||||
|
self.assertEqual(repository.installed_component["serviceCheckStatus"], "unhealthy")
|
||||||
|
|
||||||
|
def test_apt_package_without_service_is_marked_not_applicable(self) -> None:
|
||||||
|
repository = FakeRepository()
|
||||||
|
FakeAptInstaller.actions = []
|
||||||
|
FakeServiceManager.actions = []
|
||||||
|
|
||||||
|
with (
|
||||||
|
patch("app.core.task_runner.CommandRunner", return_value=object()),
|
||||||
|
patch("app.core.task_runner.AptInstaller", FakeAptInstaller),
|
||||||
|
patch("app.core.task_runner.ServiceManager", FakeServiceManager),
|
||||||
|
):
|
||||||
|
TaskRunner(repository)._install_apt_component(
|
||||||
|
"task-3",
|
||||||
|
"utility-app",
|
||||||
|
{
|
||||||
|
"componentId": "utility",
|
||||||
|
"type": "apt",
|
||||||
|
"packageName": "utility",
|
||||||
|
"version": "1",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(repository.installed_component["serviceCheckStatus"], "not-applicable")
|
||||||
|
self.assertEqual(repository.installed_component["serviceChecks"], [])
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
194
agent/tests/test_service_check_persistence.py
Normal file
194
agent/tests/test_service_check_persistence.py
Normal file
@@ -0,0 +1,194 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sqlite3
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from contextlib import closing
|
||||||
|
from pathlib import Path
|
||||||
|
from types import SimpleNamespace
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
from app.api import apps as apps_api
|
||||||
|
from app.api import tasks as tasks_api
|
||||||
|
from app.storage.database import initialize_database
|
||||||
|
from app.storage.repository import Repository
|
||||||
|
|
||||||
|
|
||||||
|
SERVICE_CHECK = {
|
||||||
|
"serviceName": "postgresql.service",
|
||||||
|
"loadState": "loaded",
|
||||||
|
"activeState": "active",
|
||||||
|
"subState": "running",
|
||||||
|
"unitFileState": "enabled",
|
||||||
|
"active": True,
|
||||||
|
"enabled": True,
|
||||||
|
"healthy": True,
|
||||||
|
"status": "active",
|
||||||
|
"readinessStatus": "ready",
|
||||||
|
"checkedAt": "2026-07-20T00:00:00Z",
|
||||||
|
"errorMessage": None,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class ServiceCheckPersistenceTests(unittest.TestCase):
|
||||||
|
def setUp(self) -> None:
|
||||||
|
self.temp_dir = tempfile.TemporaryDirectory()
|
||||||
|
root = Path(self.temp_dir.name)
|
||||||
|
fake_settings = SimpleNamespace(
|
||||||
|
db_path=root / "agent.db",
|
||||||
|
cache_dir=root / "cache",
|
||||||
|
log_dir=root / "logs",
|
||||||
|
)
|
||||||
|
self.settings_patch = patch("app.storage.database.settings", fake_settings)
|
||||||
|
self.settings_patch.start()
|
||||||
|
initialize_database()
|
||||||
|
self.db_path = fake_settings.db_path
|
||||||
|
self.repository = Repository()
|
||||||
|
|
||||||
|
def tearDown(self) -> None:
|
||||||
|
self.settings_patch.stop()
|
||||||
|
self.temp_dir.cleanup()
|
||||||
|
|
||||||
|
def test_task_component_api_round_trips_structured_service_checks(self) -> None:
|
||||||
|
self.repository.create_task("task-1", "install", "postgresql", "PostgreSQL")
|
||||||
|
self.repository.create_task_component("task-1", "postgresql", "postgresql", "apt", 10)
|
||||||
|
self.repository.update_task_component(
|
||||||
|
"task-1",
|
||||||
|
"postgresql",
|
||||||
|
service_check_status="healthy",
|
||||||
|
service_checks=[SERVICE_CHECK],
|
||||||
|
)
|
||||||
|
|
||||||
|
with patch.object(tasks_api, "repository", self.repository):
|
||||||
|
response = tasks_api.get_task_components("task-1")
|
||||||
|
|
||||||
|
component = response["components"][0]
|
||||||
|
self.assertEqual(component["serviceCheckStatus"], "healthy")
|
||||||
|
self.assertEqual(component["serviceChecks"], [SERVICE_CHECK])
|
||||||
|
|
||||||
|
def test_initialize_database_migrates_existing_component_tables(self) -> None:
|
||||||
|
with closing(sqlite3.connect(self.db_path)) as connection:
|
||||||
|
connection.execute("DROP TABLE task_components")
|
||||||
|
connection.execute("DROP TABLE installed_components")
|
||||||
|
connection.executescript(
|
||||||
|
"""
|
||||||
|
CREATE TABLE installed_components (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
app_id TEXT NOT NULL,
|
||||||
|
component_id TEXT NOT NULL,
|
||||||
|
type TEXT NOT NULL,
|
||||||
|
install_order INTEGER NOT NULL,
|
||||||
|
status TEXT NOT NULL,
|
||||||
|
package_name TEXT,
|
||||||
|
package_version TEXT,
|
||||||
|
service_name TEXT,
|
||||||
|
docker_image TEXT,
|
||||||
|
docker_digest TEXT,
|
||||||
|
container_name TEXT,
|
||||||
|
compose_project_name TEXT,
|
||||||
|
installed_at TEXT NOT NULL,
|
||||||
|
updated_at TEXT NOT NULL,
|
||||||
|
UNIQUE(app_id, component_id)
|
||||||
|
);
|
||||||
|
CREATE TABLE task_components (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
task_id TEXT NOT NULL,
|
||||||
|
app_id TEXT NOT NULL,
|
||||||
|
component_id TEXT NOT NULL,
|
||||||
|
type TEXT NOT NULL,
|
||||||
|
install_order INTEGER NOT NULL,
|
||||||
|
status TEXT NOT NULL,
|
||||||
|
progress INTEGER DEFAULT 0,
|
||||||
|
current_step TEXT,
|
||||||
|
error_message TEXT,
|
||||||
|
started_at TEXT,
|
||||||
|
finished_at TEXT
|
||||||
|
);
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
connection.commit()
|
||||||
|
|
||||||
|
initialize_database()
|
||||||
|
|
||||||
|
with closing(sqlite3.connect(self.db_path)) as connection:
|
||||||
|
installed_columns = {
|
||||||
|
row[1] for row in connection.execute("PRAGMA table_info(installed_components)")
|
||||||
|
}
|
||||||
|
task_columns = {
|
||||||
|
row[1] for row in connection.execute("PRAGMA table_info(task_components)")
|
||||||
|
}
|
||||||
|
self.assertTrue({"service_check_status", "service_checks_json"} <= installed_columns)
|
||||||
|
self.assertTrue({"service_check_status", "service_checks_json"} <= task_columns)
|
||||||
|
|
||||||
|
def test_installed_apps_include_persisted_service_health(self) -> None:
|
||||||
|
self.repository.upsert_installed_app(
|
||||||
|
"postgresql",
|
||||||
|
"PostgreSQL",
|
||||||
|
"16",
|
||||||
|
"manifest-hash",
|
||||||
|
)
|
||||||
|
self.repository.upsert_installed_component(
|
||||||
|
"postgresql",
|
||||||
|
{
|
||||||
|
"componentId": "postgresql",
|
||||||
|
"type": "apt",
|
||||||
|
"packageName": "postgresql",
|
||||||
|
"version": "16+257build1",
|
||||||
|
"serviceName": "postgresql.service",
|
||||||
|
"serviceCheckStatus": "healthy",
|
||||||
|
"serviceChecks": [SERVICE_CHECK],
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
manager = SimpleNamespace(get_service_status=lambda _name: dict(SERVICE_CHECK))
|
||||||
|
with (
|
||||||
|
patch.object(apps_api, "repository", self.repository),
|
||||||
|
patch.object(apps_api, "ServiceManager", return_value=manager),
|
||||||
|
):
|
||||||
|
response = apps_api.installed_apps()
|
||||||
|
|
||||||
|
self.assertEqual(response[0]["serviceCheckStatus"], "healthy")
|
||||||
|
self.assertEqual(response[0]["serviceChecks"][0]["serviceName"], "postgresql.service")
|
||||||
|
self.assertEqual(response[0]["serviceChecks"][0]["componentId"], "postgresql")
|
||||||
|
|
||||||
|
def test_installed_apps_refresh_postgresql_readiness(self) -> None:
|
||||||
|
stored_check = {
|
||||||
|
**SERVICE_CHECK,
|
||||||
|
"readinessType": "postgresql",
|
||||||
|
"readinessStatus": "ready",
|
||||||
|
}
|
||||||
|
self.repository.upsert_installed_app(
|
||||||
|
"postgresql",
|
||||||
|
"PostgreSQL",
|
||||||
|
"16",
|
||||||
|
"manifest-hash",
|
||||||
|
)
|
||||||
|
self.repository.upsert_installed_component(
|
||||||
|
"postgresql",
|
||||||
|
{
|
||||||
|
"componentId": "postgresql",
|
||||||
|
"type": "apt",
|
||||||
|
"packageName": "postgresql",
|
||||||
|
"version": "16+257build1",
|
||||||
|
"serviceName": "postgresql.service",
|
||||||
|
"serviceCheckStatus": "healthy",
|
||||||
|
"serviceChecks": [stored_check],
|
||||||
|
},
|
||||||
|
)
|
||||||
|
service_manager = SimpleNamespace(get_service_status=lambda _name: dict(SERVICE_CHECK))
|
||||||
|
apt_installer = SimpleNamespace(is_postgresql_ready=lambda: False)
|
||||||
|
|
||||||
|
with (
|
||||||
|
patch.object(apps_api, "repository", self.repository),
|
||||||
|
patch.object(apps_api, "ServiceManager", return_value=service_manager),
|
||||||
|
patch.object(apps_api, "AptInstaller", return_value=apt_installer),
|
||||||
|
):
|
||||||
|
response = apps_api.installed_apps()
|
||||||
|
|
||||||
|
self.assertEqual(response[0]["serviceCheckStatus"], "unhealthy")
|
||||||
|
self.assertEqual(response[0]["serviceChecks"][0]["readinessStatus"], "failed")
|
||||||
|
self.assertFalse(response[0]["serviceChecks"][0]["healthy"])
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
BIN
database.png
Normal file
BIN
database.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 1.3 MiB |
770
design-language.md
Normal file
770
design-language.md
Normal file
@@ -0,0 +1,770 @@
|
|||||||
|
---
|
||||||
|
type: foundation-layer
|
||||||
|
layer: design-language
|
||||||
|
status: draft
|
||||||
|
version: 0.4
|
||||||
|
phase: icon-subphase
|
||||||
|
last-bump: 2026-06-01
|
||||||
|
source-priority:
|
||||||
|
- foundation-4-layer
|
||||||
|
- research-method-d
|
||||||
|
- em-propose
|
||||||
|
tags:
|
||||||
|
- brand
|
||||||
|
- design-language
|
||||||
|
- foundation
|
||||||
|
---
|
||||||
|
|
||||||
|
> [!WARNING] **[DRAFT — chưa ratify, KHÔNG adopt cho production deliverable]**
|
||||||
|
> File này đang xây (Phase 1-3 xong, còn Phase 4-5). Status sẽ chuyển `ratified` khi Phase 5 close + audit cycle pass. Trong khi đang xây: tham khảo OK, KHÔNG dùng làm authority binding cho output Samsung/Nichirin/ODM.
|
||||||
|
|
||||||
|
# Design Language Phenikaa-X v0.4
|
||||||
|
|
||||||
|
> [!NOTE] **Errata mới nhất: v0.4.4 (2026-06-10)** — xem [Lịch sử phiên bản](#lịch-sử-phiên-bản). Nhãn H1 + frontmatter giữ `v0.4` theo chính sách errata-no-bump; patch level thực ở Lịch sử.
|
||||||
|
|
||||||
|
Hệ quy chiếu thiết kế universal cross-surface (Office/Web/HMI/Physical). Layer 1 = nguyên tắc + token + bố cục cơ bản, vendor-agnostic. Layer 2 (Implementation per platform) defer team dev tự build.
|
||||||
|
|
||||||
|
## 1. Nguyên tắc nền tảng
|
||||||
|
|
||||||
|
> [!NOTE] Thuật ngữ đoạn dưới: **token** = đơn vị thiết kế nguyên tử dùng lại được (màu, cỡ chữ, khoảng cách...) định nghĩa một lần, áp dụng mọi nơi · **thứ bậc thị giác** = cách bố cục dẫn mắt người đọc theo mức độ quan trọng · **WCAG 2.2 AA** = chuẩn quốc tế về khả năng tiếp cận nội dung số.
|
||||||
|
|
||||||
|
Năm nguyên tắc định hình mọi quyết định thiết kế Phenikaa-X trên mọi bề mặt (tài liệu, web, giao diện máy, biển hiệu). Ba nguyên tắc đầu truy nguyên giá trị cốt lõi của tổ chức — giữ bản sắc. Hai nguyên tắc sau bảo đảm phạm vi dùng chung của Layer 1. Mỗi nguyên tắc gồm: định nghĩa + cách áp dụng + nguồn.
|
||||||
|
|
||||||
|
### 1.1 Minh bạch
|
||||||
|
|
||||||
|
Thiết kế nói thật. Thông tin quan trọng hiện rõ, không trang trí gây nhiễu, thứ bậc thị giác phản ánh đúng mức độ quan trọng của nội dung.
|
||||||
|
|
||||||
|
**Áp dụng:** Dashboard cycle-time → số liệu chính nổi bật, bỏ trang trí thừa trong biểu đồ. Báo cáo FAT → kết quả đạt/không-đạt rõ, không màu mè che dữ liệu. Slide → một thông điệp chính mỗi trang.
|
||||||
|
|
||||||
|
**Nguồn:** `identity-from-raw.md` §11.2 (Trung thực và minh bạch)
|
||||||
|
|
||||||
|
### 1.2 Rõ ràng
|
||||||
|
|
||||||
|
Mỗi yếu tố thiết kế phải có mục đích. Ưu tiên đọc-hiểu nhanh, súc tích, đúng trọng tâm — không thêm yếu tố không phục vụ thông điệp.
|
||||||
|
|
||||||
|
**Áp dụng:** Proposal → tiêu đề phân cấp rõ, đoạn ngắn. Bảng số liệu → chỉ giữ cột thật cần. Loại bỏ chi tiết trang trí không mang nghĩa.
|
||||||
|
|
||||||
|
**Nguồn:** `applied-from-raw.md` §1 (giọng viết: rõ ràng + súc tích + đúng trọng tâm) + `[fact]` Fluent 2 "Coherent" + Carbon clarity — [Fluent 2 design principles](https://fluent2.microsoft.design/design-principles)
|
||||||
|
|
||||||
|
### 1.3 Trách nhiệm
|
||||||
|
|
||||||
|
Thiết kế nhất quán, chuẩn mực, đáng tin qua mọi sản phẩm. Cùng một token (màu, font, khoảng cách) áp dụng nhất quán — người nhận nhận ra "đây là Phenikaa-X" trước cả khi thấy logo.
|
||||||
|
|
||||||
|
**Áp dụng:** Mọi output dùng chung bảng màu + thang chữ + thang khoảng cách. Không tùy biến tự phát mỗi tài liệu.
|
||||||
|
|
||||||
|
**Nguồn:** `identity-from-raw.md` §11.3 (Trách nhiệm cam kết đến cùng) + §13 (6 Hexagon văn hóa — Kỷ luật hexagon #2) + `[fact]` Carbon "builds consistency" — [Carbon — what is Carbon](https://carbondesignsystem.com/all-about-carbon/what-is-carbon/)
|
||||||
|
|
||||||
|
### 1.4 Có thể truy cập
|
||||||
|
|
||||||
|
Thiết kế cho mọi người dùng, không loại trừ ai. Tuân chuẩn WCAG 2.2 AA: đủ tương phản màu, cỡ chữ đọc được, không chỉ dựa vào màu để truyền thông tin.
|
||||||
|
|
||||||
|
**Áp dụng:** Cặp màu chữ trên nền đạt tỷ lệ tương phản ≥ 4.5:1 (chữ thường). Trạng thái phân biệt thêm bằng icon hoặc chữ, không chỉ bằng màu. Chữ thân bài không nhỏ hơn ngưỡng đọc được.
|
||||||
|
|
||||||
|
**Nguồn:** `identity-from-raw.md` §11.7 (Tôn trọng và trao quyền) + `[fact]` Carbon "Carbon is inclusive" — [Carbon — what is Carbon](https://carbondesignsystem.com/all-about-carbon/what-is-carbon/)
|
||||||
|
|
||||||
|
### 1.5 Đồng bộ đa nền tảng
|
||||||
|
|
||||||
|
Một hệ token chung phục vụ mọi bề mặt: tài liệu Office, web, giao diện máy (HMI), biển hiệu vật lý. Layer 1 định nghĩa token độc lập nền tảng; Layer 2 (team dev) ánh xạ sang định dạng từng nền tảng.
|
||||||
|
|
||||||
|
**Áp dụng:** Màu, font, khoảng cách định nghĩa một lần ở Layer 1 → xuất sang `.thmx` (Office), biến CSS (web), theme giao diện máy. Không định nghĩa lại token riêng cho mỗi nền tảng.
|
||||||
|
|
||||||
|
**Nguồn:** `[fact]` Fluent 2 token "common language" đồng bộ đa nền tảng — [Fluent 2 design tokens](https://fluent2.microsoft.design/design-tokens) + phạm vi Layer 1 (xem `spec-design-language-stream.md`)
|
||||||
|
|
||||||
|
## 2. Token
|
||||||
|
|
||||||
|
### 2.1 Color
|
||||||
|
|
||||||
|
> [!NOTE] Thuật ngữ: **token** = đơn vị màu định nghĩa một lần dùng mọi nơi · **scale/thang** = các bậc đậm-nhạt của một màu · **semantic alias** = tên theo công dụng (vd `text.primary`) trỏ tới một bậc màu cụ thể · **tỷ lệ tương phản** = chỉ số WCAG đo độ đọc được của chữ trên nền.
|
||||||
|
|
||||||
|
Hệ màu canonical Layer 1 — nguồn duy nhất cho mọi bề mặt. Mô hình 3 tầng (kế thừa concept tốt từ prior art cycle-time, sửa màu + chuẩn scope):
|
||||||
|
|
||||||
|
| Tầng | Trách nhiệm | Sống ở đâu |
|
||||||
|
|---|---|---|
|
||||||
|
| **L1 — token universal** | Brand scale + neutral + semantic + theme alias (file này) | `design-language.md` §2.1 |
|
||||||
|
| **L2 — platform** | Ánh xạ token sang `.thmx`/CSS/HMI theme + bộ data-viz dashboard | Team dev / `40-knowledge/cycle-time-dashboard/` |
|
||||||
|
| **L3 — project** | Override white-label ODM/khách | `30-projects/<proj>/.../dashboard-config` |
|
||||||
|
|
||||||
|
Thang xanh + cam **neo trên màu chính thức Tập đoàn** (Trang 18-19 guideline). Neutral + semantic **thiết kế mới** (palette Tập đoàn không có xám/semantic) — hài hoà brand, đạt WCAG.
|
||||||
|
|
||||||
|
#### 2.1.1 Brand color
|
||||||
|
|
||||||
|
**Thang Xanh** (neo Deep Blue chủ đạo + Dark Blue Phenikaa-X):
|
||||||
|
|
||||||
|
| Token | Hex | Nguồn | Vai trò |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `blue-50` | `#EAEDF5` | tint mới | Nền hover/selected (light) |
|
||||||
|
| `blue-100` | `#C5CCE0` | tint mới | Nền nhấn nhẹ |
|
||||||
|
| `blue-200` | `#8C9AC4` | tint mới | Link/accent trên nền tối |
|
||||||
|
| `blue-300` | `#6E7CA8` | tint mới | UI lớn trên nền tối |
|
||||||
|
| `blue-500` | `#223771` | **official Deep Blue** | **Chủ đạo** — heading, link, nút chính |
|
||||||
|
| `blue-700` | `#1A2A57` | shade mới | Nhấn đậm |
|
||||||
|
| `blue-900` | `#1e2243` | **official Dark Blue** | Đậm nhất — footer, nền dark mode |
|
||||||
|
|
||||||
|
> Màu xanh official ngả cyan của Tập đoàn (`#03428E`, `#004E96`, `#00599D` — Trang 18) giữ làm **xanh accent đặc biệt** (sự kiện, đồ hoạ môi trường). Không đưa vào thang chính vì hue lệch sang cyan.
|
||||||
|
|
||||||
|
**Thang Cam** (4 bậc official + tint/shade):
|
||||||
|
|
||||||
|
| Token | Hex | Nguồn | Vai trò |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `orange-100` | `#FCD9C4` | tint mới | Nền cảnh báo nhẹ |
|
||||||
|
| `orange-200` | `#F7941E` | **official** cam nhạt | Accent sáng (nền tối) |
|
||||||
|
| `orange-300` | `#F58220` | **official** | Accent |
|
||||||
|
| `orange-400` | `#F37021` | **official** | Accent đậm |
|
||||||
|
| `orange-500` | `#f26522` | **official Sun Orange** | **Accent chủ đạo** — highlight, CTA |
|
||||||
|
| `orange-700` | `#C44E14` | shade mới | Nhấn đậm |
|
||||||
|
|
||||||
|
#### 2.1.2 Neutral (thiết kế mới — xám ngả xanh hài hoà brand)
|
||||||
|
|
||||||
|
| Token | Hex | Vai trò chính |
|
||||||
|
|---|---|---|
|
||||||
|
| `neutral-0` | `#FFFFFF` | Nền cơ sở (light) |
|
||||||
|
| `neutral-50` | `#F7F8FB` | Nền nâng nhẹ |
|
||||||
|
| `neutral-100` | `#EEEDF6` | = Brilliant White brand tint |
|
||||||
|
| `neutral-200` | `#DDDFEA` | Nền phân vùng |
|
||||||
|
| `neutral-300` | `#C5C8D8` | Viền trang trí (divider) |
|
||||||
|
| `neutral-400` | `#9FA3B8` | Icon phụ, disabled |
|
||||||
|
| `neutral-450` | `#8C90A8` | **Viền thiết yếu** (ô input — đạt 3:1) |
|
||||||
|
| `neutral-500` | `#757A91` | Chữ cấp 3 (caption, large) |
|
||||||
|
| `neutral-550` | `#6A6F88` | Viền thiết yếu dark mode (= `border.strong` dark) |
|
||||||
|
| `neutral-600` | `#565B70` | Chữ phụ (đạt AA) |
|
||||||
|
| `neutral-700` | `#3C4054` | Viền thiết yếu (dark mode area) |
|
||||||
|
| `neutral-800` | `#272A3A` | Nền thẻ (dark) |
|
||||||
|
| `neutral-900` | `#161824` | Chữ chính (light) · nền cơ sở (dark) |
|
||||||
|
|
||||||
|
#### 2.1.3 Semantic (thiết kế mới — căn theo IEC 60204-1 + ISO 3864)
|
||||||
|
|
||||||
|
Màu trạng thái tuân quy ước an toàn công nghiệp (xanh lá = an toàn/chạy, đỏ = dừng/cấm, vàng = cảnh báo, xanh dương = thông tin) để không mâu thuẫn HMI/biển báo. Mỗi màu có biến thể light + dark.
|
||||||
|
|
||||||
|
| Token | Light | Dark | Ý nghĩa |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `success` | `#2E7D32` | `#66BB6A` | An toàn / đạt / chạy |
|
||||||
|
| `warning` | `#9A5B00` | `#FFB74D` | Cảnh báo / cần để ý |
|
||||||
|
| `error` | `#C62828` | `#EF9A9A` | Lỗi / dừng / vượt ngưỡng |
|
||||||
|
| `info` | `#1565C0` | `#90CAF9` | Thông tin / bắt buộc |
|
||||||
|
|
||||||
|
> Quy tắc: trạng thái KHÔNG chỉ phân biệt bằng màu — luôn kèm icon/chữ (per WCAG 1.4.1 + color-blindness, research D §5.3).
|
||||||
|
|
||||||
|
**Biến thể `error.text-sm`** (v0.2 — chỉ cho chữ/nhãn đỏ cỡ nhỏ, KHÔNG phải status mới):
|
||||||
|
|
||||||
|
| Token | Light | Dark | Dùng cho |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `error.text-sm` | `#A4262C` | `#F2B8B5` | Chữ/số đỏ cỡ nhỏ (9–14px) **trên nền sáng** — đỏ trầm chống nhoè viền do tán sắc |
|
||||||
|
|
||||||
|
> **Khi nào cần `error.text-sm`:** đỏ no `error` `#C62828` chỉ **nhoè viền** khi HỘI ĐỦ — **cỡ nhỏ (9–14px) + nét mảnh + bão hoà cao + trên nền sáng/trắng**; nguyên nhân là **tán sắc ngang của mắt (TCA — chromatic aberration)**: bước sóng đỏ lấy nét lệch so với bước sóng khác nên viền nhoè, rõ nhất trên nền trắng `[fact]`. → dùng `error.text-sm` trong đúng điều kiện đó. **KHÔNG cần** đỏ trầm khi thiếu một điều kiện: chữ lớn/đậm · fill/pill/icon/khối đặc (mép nhoè không đáng kể so với diện tích) · **nền tối** — tán sắc gần như **không thấy trên nền đen** `[fact]`, nên dark-mode giữ đỏ sáng `#F2B8B5` (không cần trầm). Đây là biến thể công dụng, KHÔNG đổi nghĩa `error`.
|
||||||
|
|
||||||
|
**Biến thể `warning.icon`** (v0.4 — chỉ cho icon/tiêu đề cảnh báo CỠ LỚN, KHÔNG phải status mới):
|
||||||
|
|
||||||
|
| Token | Light | Dark | Dùng cho |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `warning.icon` | `#CB6119` | `#FFB74D` (= `warning` dark) | Icon + tiêu đề callout cảnh báo cỡ lớn (≥18px / ≥14px đậm) — cam ISO tươi hợp hue an toàn |
|
||||||
|
|
||||||
|
> Ngược chiều `error.text-sm`: `warning` `#9A5B00` cố tình **trầm** để chữ/nhãn cỡ nhỏ vẫn đạt AA 4.5:1. Nhưng icon + tiêu đề callout **cỡ lớn** chỉ cần ngưỡng 3:1 (WCAG 1.4.11 / 1.4.3 large) → dùng cam ISO tươi `#CB6119` (3.99:1 / white · 3.76:1 / `neutral-50` — `[fact]` công thức W3C) cho hợp hue cảnh báo ANSI/ISO + đẹp hơn nâu trầm. Nền tối: `warning` dark `#FFB74D` đã đủ sáng, không cần biến thể. Đây là biến thể công dụng, KHÔNG đổi nghĩa `warning`.
|
||||||
|
|
||||||
|
**Biến thể `caution.fill`** (v0.4.4 — nền vàng callout mức "Thận trọng" ANSI Y2 / ISO 3864 signal yellow, KHÔNG phải status mới):
|
||||||
|
|
||||||
|
| Token | Light | Dark | Dùng cho |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `caution.fill` | `#F9A900` | `#FFB74D` (= `warning` dark) | Nền callout "Thận trọng" (mức nhẹ hơn "Cảnh báo") — **buộc chữ đen `neutral-900`** |
|
||||||
|
|
||||||
|
> Phân biệt 3 cấp cảnh báo (theo ANSI Z535 / ISO 3864): **đỏ `error`** = Nguy hiểm/Cấm · **cam `warning.icon` `#CB6119`** = Cảnh báo (W2, icon/tiêu đề cỡ lớn) · **vàng `caution.fill` `#F9A900`** = Thận trọng (Y2, nền callout). Vàng `#F9A900` quá sáng → chữ trắng **FAIL** (1.96:1 — `[fact]` công thức W3C), nên **buộc chữ đen `neutral-900`** (8.99:1 AAA). Khoá ở `research-status-colors-office.md` §6 (D202, owner ratify S56). Đây là biến thể công dụng nền, KHÔNG đổi nghĩa `warning`.
|
||||||
|
|
||||||
|
#### 2.1.4 Theme alias (light + dark mode)
|
||||||
|
|
||||||
|
Tên theo công dụng — đây là lớp mà output thật tham chiếu, KHÔNG hardcode hex.
|
||||||
|
|
||||||
|
| Alias | Light → token | Dark → token |
|
||||||
|
|---|---|---|
|
||||||
|
| `surface.base` | `neutral-0` | `neutral-900` |
|
||||||
|
| `surface.raised` | `neutral-50` | `neutral-800` |
|
||||||
|
| `surface.brand-tint` | `neutral-100` | `blue-900` |
|
||||||
|
| `text.primary` | `neutral-900` | `neutral-100` |
|
||||||
|
| `text.secondary` | `neutral-600` | `neutral-400` |
|
||||||
|
| `text.tertiary` | `neutral-500` | `neutral-500` |
|
||||||
|
| `border.subtle` | `neutral-300` | `neutral-700` |
|
||||||
|
| `border.strong` | `neutral-450` | `neutral-550` |
|
||||||
|
| `brand.primary` | `blue-500` | `blue-200` |
|
||||||
|
| `brand.accent` | `orange-500` | `orange-300` |
|
||||||
|
| `link` | `blue-500` | `blue-200` |
|
||||||
|
|
||||||
|
#### 2.1.5 AMR body paint + decal (bề mặt vật lý)
|
||||||
|
|
||||||
|
| Token | Spec | Khớp brand | Trạng thái |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `paint.body.primary` | **RAL 5011 Steel Blue** | ≈ Deep Blue `#223771` | `[inference]` cần mẫu RAL vật lý chốt |
|
||||||
|
| `paint.body.accent` | **RAL 2008 Bright Red Orange** | ≈ Sun Orange `#f26522` | `[inference]` cần mẫu RAL vật lý chốt |
|
||||||
|
| `paint.body.dark` | **RAL 5022 Night Blue** | ≈ Dark Blue `#1e2243` | `[inference]` cần mẫu RAL vật lý chốt |
|
||||||
|
| `paint.body.light` | **RAL 9003 Signal White** | ≈ Brilliant White `#eeedf6` | `[inference]` cần mẫu RAL vật lý chốt |
|
||||||
|
| `decal.logo` | Pantone Solid Coated | logo decal trên thân AMR | GAP — chưa có Pantone official (defer M2.5) |
|
||||||
|
|
||||||
|
> 4 màu sơn khớp đủ 4 màu chính thức Phenikaa-X (Deep Blue + Sun Orange + Dark Blue + Brilliant White, per `visual-from-raw.md` §11).
|
||||||
|
|
||||||
|
> Màu nền thân robot (xám máy móc nền — vd RAL 7035) là quyết định product-spec per model, không khoá ở Layer 1.
|
||||||
|
|
||||||
|
#### 2.1.6 WCAG 2.2 AA verify (tính bằng `[fact]` công thức relative luminance W3C)
|
||||||
|
|
||||||
|
| Cặp | Tỷ lệ | Kết quả |
|
||||||
|
|---|---|---|
|
||||||
|
| text.primary / surface.base (light) | 17.6:1 | AAA |
|
||||||
|
| text.secondary `neutral-600` / white | 6.7:1 | AA |
|
||||||
|
| brand.primary `blue-500` / white | 11.3:1 | AAA |
|
||||||
|
| chữ trắng / nền `blue-500` | 11.3:1 | AAA |
|
||||||
|
| **chữ trắng / nền `orange-500`** | **3.15:1** | FAIL body · **PASS chữ lớn** (≥3:1) — xem quy tắc phân tầng |
|
||||||
|
| chữ tối `neutral-900` / `orange-500` | 5.6:1 | AA mọi cỡ ✅ |
|
||||||
|
| border.strong `neutral-450` / white | 3.15:1 | AA non-text |
|
||||||
|
| success/warning/error/info / white | ≥5.1 / 5.4 / 5.6 / 5.8 | AA |
|
||||||
|
| text.primary `neutral-100` / surface.base (dark) | 15.2:1 | AAA |
|
||||||
|
| link `blue-200` / nền tối | 6.3:1 | AA |
|
||||||
|
| semantic dark variant / nền tối | ≥7.4 | AAA |
|
||||||
|
| `error.text-sm` `#A4262C` / white | 7.26:1 | AAA |
|
||||||
|
| `error.text-sm` `#F2B8B5` / nền tối `#1e2243` | 9.01:1 | AAA |
|
||||||
|
| `warning.icon` `#CB6119` / white | 3.99:1 | AA chữ lớn/icon (≥3:1) · FAIL body |
|
||||||
|
| `warning.icon` `#CB6119` / `neutral-50` | 3.76:1 | AA chữ lớn/icon (≥3:1) |
|
||||||
|
| `caution.fill` `#F9A900` / `neutral-900` (chữ đen) | 8.99:1 | AAA |
|
||||||
|
| `caution.fill` `#F9A900` / white (chữ trắng) | 1.96:1 | FAIL — buộc chữ đen |
|
||||||
|
|
||||||
|
> [!IMPORTANT] **Quy tắc dùng chữ trên nền cam (binding — theo bậc cam × cỡ chữ):**
|
||||||
|
> Tính `[fact]` bằng công thức W3C. Cam càng nhạt, chữ trắng càng fail — KHÔNG áp dụng "chữ lớn trắng OK" cho mọi bậc cam:
|
||||||
|
> | Nền | Chữ trắng | Chữ tối `neutral-900` | Khuyến nghị |
|
||||||
|
> |---|---|---|---|
|
||||||
|
> | `orange-200/300/400` (nhạt) | FAIL (≤2.94:1, kể cả chữ lớn) | AA mọi cỡ (6.0–7.7) | **Luôn chữ tối** |
|
||||||
|
> | `orange-500` Sun Orange | chữ lớn OK (3.15:1), body FAIL | AA mọi cỡ (5.6) | Logo + chữ lớn/CTA = trắng; body = tối |
|
||||||
|
> | `orange-700` (đậm) | AA mọi cỡ (4.72) | chỉ chữ lớn (3.74) | Trắng OK mọi cỡ |
|
||||||
|
>
|
||||||
|
> **Hệ quả thực tế:** nút cam **light mode** (`brand.accent`=orange-500) CTA lớn → trắng OK, nút nhỏ → tối. Nút cam **dark mode** (`brand.accent`=orange-300, nhạt) → **luôn chữ tối**. Logo/wordmark: trắng luôn được (logotype miễn trừ WCAG `[fact]`).
|
||||||
|
>
|
||||||
|
> **Quy tắc khác:**
|
||||||
|
> 1. **30% rule** (truyền thông): ấn phẩm marketing ≥30% diện tích màu chủ đạo (Deep Blue/Sun Orange) — per `research-method-d-standard.md` §5.1 (quy tắc 60-30-10).
|
||||||
|
> 2. Trạng thái kèm icon/chữ, không chỉ màu (WCAG 1.4.1).
|
||||||
|
|
||||||
|
> [!NOTE] **Hai thước đo tương phản (dual-metric):** Bảng trên tính bằng **WCAG 2.x** (chuẩn pháp lý hiện hành). WCAG 2.x có lỗi đã ghi nhận với màu cam ("orange problem") — chấm chữ trắng/cam ~3:1 fail dù thực tế đọc rõ. **APCA** (thuật toán cảm nhận thị giác, sẽ vào WCAG 3) phản ánh chính xác hơn. Quy tắc phân tầng cam ở trên dựa trên cả hai. Test harness `50-plans/phenikaa-x-design-system/color-test-harness.html` tính song song WCAG + APCA + mô phỏng mù màu.
|
||||||
|
|
||||||
|
**Nguồn:** `visual-from-raw.md` §11 (4 màu chính + parent 8 tone) + parent guideline Trang 18-19 (crop `color-palette-aux.jpg` 400 DPI verified) + `research-method-d-standard.md` §5.2 (WCAG 2.2) + §9.1 (RAL/Pantone AMR) + `[fact]` [W3C WCAG 2.2](https://www.w3.org/TR/WCAG22/) · [WCAG 1.4.3 logotype exemption](https://www.w3.org/WAI/WCAG21/Understanding/contrast-minimum.html) · [APCA contrast](https://git.apcacontrast.com/documentation/APCAeasyIntro.html) · [Carbon color tokens](https://carbondesignsystem.com/elements/color/tokens/) · RAL `[inference]` [RALcolorchart](https://www.ralcolorchart.com/ral-classic)
|
||||||
|
|
||||||
|
#### 2.1.7 Data-viz — 4 họ màu theo ý đồ
|
||||||
|
|
||||||
|
> [!NOTE] Thuật ngữ: **categorical** = màu phân loại nhóm rời rạc · **sequential** = thang 1 màu cho độ lớn · **diverging** = 2 màu quanh mốc giữa · **ΔE** = chỉ số khoảng cách 2 màu (CIEDE2000; >15 phân biệt rõ, 10–15 ổn, <10 dễ lẫn).
|
||||||
|
|
||||||
|
Màu data-viz chọn theo **ý đồ truyền đạt**, KHÔNG phải 1 bộ cố định (`[fact]` Few "Show Me the Numbers" + Knaflic "Storytelling with Data": màu = ý đồ, phần lớn biểu đồ chỉ cần 1–2 màu). Bốn họ:
|
||||||
|
|
||||||
|
| Họ | Dùng khi | Alias |
|
||||||
|
|---|---|---|
|
||||||
|
| **Categorical** | Phân loại series rời rạc (≤6) | `dataviz.cat-1…6` |
|
||||||
|
| **Sequential** | Độ lớn 1 chiều (mật độ, throughput) | `dataviz.seq-50…900` |
|
||||||
|
| **Diverging** | Lệch quanh mốc (sai số ±, trên/dưới target) | `dataviz.diverge-neg/mid/pos` |
|
||||||
|
| **Status** | Ngưỡng an toàn | đã khoá §2.1.3 |
|
||||||
|
|
||||||
|
> Categorical **cố tình chừa hue xanh-lá/đỏ/vàng** — để dành cho status. Đây là quyết định đo được (khoảng cách tới màu status ΔE 20.1, không đụng nghĩa "đạt/cảnh báo/lỗi"), không phải sở thích.
|
||||||
|
>
|
||||||
|
> **Khi nào dùng họ nào + luật status-override** (lúc data vượt ngưỡng an toàn → đổi sang màu status): xem `_foundation/patterns/pattern-dashboard.md` §2.
|
||||||
|
|
||||||
|
##### 2.1.7.1 Categorical
|
||||||
|
|
||||||
|
Bộ **4 màu** (`cat-1…4`) = dùng nhiều nhất (~90% biểu đồ). Thêm `cat-5, cat-6` chỉ khi buộc 5–6 series. Trên 6 series → đổi **small-multiples** (chia nhiều biểu đồ nhỏ), KHÔNG thêm màu thứ 7 (`[fact]` Cleveland-McGill: màu là kênh tri giác kém chính xác nhất).
|
||||||
|
|
||||||
|
| Token | Light | Dark |
|
||||||
|
|---|---|---|
|
||||||
|
| `dataviz.cat-1` | `#223771` | `#7AA2F7` |
|
||||||
|
| `dataviz.cat-2` | `#f26522` | `#F7941E` |
|
||||||
|
| `dataviz.cat-3` | `#8E6CF0` | `#B79CF5` |
|
||||||
|
| `dataviz.cat-4` | `#22A0A8` | `#56C7D6` |
|
||||||
|
| `dataviz.cat-5` *(chỉ khi cần 5–6)* | `#3E89C0` | `#4FB0DD` |
|
||||||
|
| `dataviz.cat-6` *(chỉ khi cần 5–6)* | `#B05CA0` | `#E07BB0` |
|
||||||
|
|
||||||
|
##### 2.1.7.2 Sequential
|
||||||
|
|
||||||
|
Thang đơn sắc (single-hue) xanh thương hiệu, **độ sáng đều cảm nhận** — dựng bằng OKLab (cố định hue 266° của Deep Blue + chroma ~0.10, chia độ sáng đều), **neo cứng 2 đầu** vào màu chính thức Tập đoàn. Thay thang mượn v0.2 (trả "nợ" perceptual-uniform).
|
||||||
|
|
||||||
|
| Token | Hex | L (OKLab) | Vai trò |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `dataviz.seq-50` | `#ECF2FF` | 0.960 | mật độ thấp nhất (sáng nhất) |
|
||||||
|
| `dataviz.seq-100` | `#C3D5FF` | 0.873 | |
|
||||||
|
| `dataviz.seq-200` | `#9CB8FA` | 0.786 | |
|
||||||
|
| `dataviz.seq-300` | `#819DDD` | 0.700 | |
|
||||||
|
| `dataviz.seq-400` | `#6882C1` | 0.613 | |
|
||||||
|
| `dataviz.seq-500` | `#5068A5` | 0.526 | |
|
||||||
|
| `dataviz.seq-600` | `#394F8A` | 0.440 | |
|
||||||
|
| `dataviz.seq-700` | `#23376F` | 0.353 | ≈ **Deep Blue official** `#223771` |
|
||||||
|
| `dataviz.seq-900` | `#1e2243` | 0.267 | mật độ cao nhất = **Dark Blue official** (neo cứng) |
|
||||||
|
|
||||||
|
> **Bước độ sáng** mọi bậc ~**0.087** (đều — không nhảy vọt, không dồn cục; đo bằng `50-plans/phenikaa-x-design-system/` script OKLab). Số hiệu token là *nhãn quy ước* (bỏ `800` để giữ `seq-900` neo Dark Blue ở đáy) — bước *độ sáng* vẫn đều bất kể nhãn.
|
||||||
|
>
|
||||||
|
> **Dark mode:** đảo nhạt↔đậm theo nền — `seq-900` thành đầu nhạt, `seq-50` thành đầu đậm (giữ cơ chế v0.2). `[inference]` verify khi render thật.
|
||||||
|
|
||||||
|
##### 2.1.7.3 Diverging
|
||||||
|
|
||||||
|
Hai màu brand quanh mốc trung tính (không đỏ/xanh-lá → không đụng status). Cân độ sáng 2 cánh để không tạo bất đối xứng giả.
|
||||||
|
|
||||||
|
| Token | Light | Dark |
|
||||||
|
|---|---|---|
|
||||||
|
| `dataviz.diverge-neg` (cánh âm) | `#5B9BD0` | `#6FAEDD` |
|
||||||
|
| `dataviz.diverge-mid` (mốc 0) | `#EEEDF6` | `#2C3158` |
|
||||||
|
| `dataviz.diverge-pos` (cánh dương) | `#F58220` | `#F7941E` |
|
||||||
|
|
||||||
|
> Giá trị `[inference]` — 2 cánh cân độ sáng ~L*62–70; owner verify khi xem render thật.
|
||||||
|
|
||||||
|
> [!NOTE] **Bằng chứng + rủi ro tồn dư** (đo bằng `50-plans/phenikaa-x-design-system/palette_eval.py`): Categorical sáng ΔE phân biệt 28.8 (4 màu) / 17.8 (6 màu), khoảng cách status 20.1 ✅. Categorical tối 15.0 (4 màu) / 11.9 (6 màu) — **khoảng cách status 9.6 ⚠️** (`cat-2` cam gần warning-dark): dark mode ưu tiên 4 màu + status luôn kèm icon để không lẫn.
|
||||||
|
|
||||||
|
**Nguồn:** `spec-pattern-dashboard.md` (quyết định D135–D138 + bằng chứng) + `spec-phase-3.md` (sequential brand-anchored D147) + `research-method-d-standard.md` §7.3 (Cleveland-McGill `[fact]`) + `[fact]` Few "Show Me the Numbers" + Knaflic "Storytelling with Data" + OKLab (Ottosson 2020) + [ColorBrewer](https://colorbrewer2.org) + [viridis](https://bids.github.io/colormap/) + `palette_eval.py` / `seq_anchor.py` (số đo CIEDE2000 + OKLab L + WCAG W3C).
|
||||||
|
|
||||||
|
### 2.2 Typography
|
||||||
|
|
||||||
|
> [!NOTE] Thuật ngữ: **type scale** = bộ cỡ chữ chuẩn (tiêu đề → chữ thường → chú thích) · **vai trò (role)** = tên theo công dụng (Body, Heading...) thay vì cỡ cụ thể · **độ cao dòng (line-height)** = khoảng cách giữa 2 dòng · **px** = đơn vị màn hình, **pt** = đơn vị Word/in (1pt ≈ 1.33px).
|
||||||
|
|
||||||
|
#### 2.2.1 Font family
|
||||||
|
|
||||||
|
- **Body + Heading:** **Montserrat** — Phenikaa-X UNIQUE retain (owner ratify S12, sub-brand style), per `visual-from-raw.md` §12. Montserrat có bộ ký tự tiếng Việt đầy đủ (Google Fonts Vietnamese subset) `[fact]`.
|
||||||
|
- **Độ đậm dùng:** Regular 400 · Medium 500 · SemiBold 600 · Bold 700.
|
||||||
|
- **Fallback:** `system-ui, -apple-system, "Segoe UI", sans-serif` (khi Montserrat chưa load).
|
||||||
|
- Lưu ý: font trong **logo** ≠ font body (logo có style riêng, per `visual-from-raw.md` §2 Logo).
|
||||||
|
- **UTM Avo** là font của tập đoàn Phenikaa Group — chỉ là tham chiếu, **KHÔNG dùng** cho Phenikaa-X (owner ratify S12, sub-brand giữ style riêng, per `visual-from-raw.md` §16.1 #2).
|
||||||
|
|
||||||
|
> [!NOTE] **Ngoại lệ phạm vi — văn bản hành chính gửi cơ quan nhà nước**
|
||||||
|
> Montserrat áp dụng cho **mọi output do Phenikaa-X kiểm soát** (proposal, slide, brochure, HMI, web, tài liệu kỹ thuật). **Ngoại lệ:** văn bản hành chính gửi cơ quan nhà nước (công văn, tờ trình, hồ sơ thầu dự án nhà nước) → dùng **Times New Roman cỡ 13–14**, mã Unicode TCVN 6909:2001, theo Nghị định 30/2020/NĐ-CP `[fact]`.
|
||||||
|
>
|
||||||
|
> Đây là **format pháp lý bên ngoài, brand không override** — cùng nguyên tắc với màu an toàn IEC 60204-1 / ISO 3864 (đỏ–vàng dừng khẩn không được đổi sang xanh brand).
|
||||||
|
>
|
||||||
|
> Phenikaa-X là công ty cổ phần tư nhân → **không thuộc đối tượng bắt buộc** của Nghị định 30 (đối tượng = cơ quan/tổ chức nhà nước + doanh nghiệp nhà nước) `[fact]`. Nhưng **nên tuân theo** khi tài liệu vào quy trình văn thư nhà nước, để bên nhận chấp nhận `[inference]`.
|
||||||
|
|
||||||
|
#### 2.2.2 Type scale (Major Third 1.25 — neo Body theo thực tế Word 11pt)
|
||||||
|
|
||||||
|
Thang theo tỷ lệ 1.25 (Bringhurst `[fact]`). Body neo **11pt** (cỡ Word A4 đang dùng) → Web 16px. 2 cột đơn vị cho 2 môi trường:
|
||||||
|
|
||||||
|
| Vai trò | Web/HMI (px) | Word/In (pt) | Độ đậm | Line-height | Dùng cho |
|
||||||
|
|---|---|---|---|---|---|
|
||||||
|
| Display | 39 | 28 | Bold 700 | 1.1× | Bìa, tiêu đề slide lớn |
|
||||||
|
| Heading 1 | 31 | 22 | Bold 700 | 1.15× | Tiêu đề chính tài liệu |
|
||||||
|
| Heading 2 | 25 | 18 | SemiBold 600 | 1.2× | Tiêu đề mục |
|
||||||
|
| Heading 3 | 20 | 14 | SemiBold 600 | 1.3× | Tiêu đề mục con |
|
||||||
|
| Heading 4 | 18 | 12 | Bold 700 | 1.3× | Tiêu đề phụ (hơi lớn hơn body) |
|
||||||
|
| Heading 5 | 16 | 11 | SemiBold 600 | 1.4× | Tiêu đề ngang cỡ body, nhạt hơn H4 (weight phân biệt) |
|
||||||
|
| Heading 6 | 16 | 11 | SemiBold 600 · CHỮ HOA | 1.4× | Tiêu đề nhỏ nhất (phân biệt bằng chữ hoa) |
|
||||||
|
| **Body** | 16 | **11** | Regular 400 | **1.5×** | Chữ thường (đoạn văn) |
|
||||||
|
| Label | 13 | 9 | Medium 500 | 1.5× | Chú thích, nhãn KPI, trục biểu đồ |
|
||||||
|
|
||||||
|
> Web hơi lớn hơn In (16px ≈ 12pt vs 11pt) — bình thường: màn hình đọc xa hơn giấy. Cùng vai trò Body, mỗi môi trường neo cỡ phù hợp.
|
||||||
|
>
|
||||||
|
> **6 tầng heading** (map thẳng Word Heading 1-6 / HTML h1-h6). H1-H3 phân biệt bằng **cỡ**; H4-H6 cụm gần body, phân biệt bằng **độ đậm + chữ hoa** (mắt không phân biệt rõ 6 cỡ chữ khác nhau). Thang H4-H6: **H4 Bold 700 → H5 SemiBold 600 → H6 SemiBold 600 + CHỮ HOA** (mỗi cấp đổi đúng 1 tín hiệu so với cấp trên; KHÔNG in nghiêng — bảo toàn dấu tiếng Việt ở cỡ nhỏ + sống sót khi in đen trắng). `[fact]` Word built-in cũng dùng italic ở cấp sâu; brand chọn weight+caps thay italic vì 2 lý do trên.
|
||||||
|
>
|
||||||
|
> **Cỡ theo thiết bị KHÔNG khoá ở L1:** L1 định *tỷ lệ* (1.25) + *vai trò* + cỡ tham chiếu; co giãn responsive theo màn hình (web/HMI/in) là việc **L2** per platform. L1 = hệ, không phải cỡ chết per device.
|
||||||
|
>
|
||||||
|
> **Cột "Line-height" = giá trị web/CSS.** Setting Word-native (Single / Multiple) KHÁC — Word "Multiple N" = N × line-unit font (Montserrat 1.219×), không phải N × cỡ chữ. Xem §2.2.4 bảng ánh xạ Office (body Word = Multiple 1.15, heading lớn = Single).
|
||||||
|
|
||||||
|
#### 2.2.3 Role × surface mapping (áp dụng đa nền tảng)
|
||||||
|
|
||||||
|
| Vai trò | Office (Word/Excel) | Web (Dashboard) | HMI (màn hình máy) | In ấn |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| Display | (hiếm dùng) | hero/h1 trang | tiêu đề splash | tiêu đề poster |
|
||||||
|
| Heading 1-6 | h1-h6 tài liệu | h1-h6 dashboard | tiêu đề màn hình | tiêu đề mục/tiểu mục |
|
||||||
|
| Body | đoạn văn (11pt) | nhãn dữ liệu, đoạn | chữ nút, giá trị | đoạn văn |
|
||||||
|
| Label | caption | nhãn KPI, nhãn trục | chỉ báo | chú thích chân |
|
||||||
|
|
||||||
|
#### 2.2.4 Line-height tiếng Việt + ánh xạ Office-native
|
||||||
|
|
||||||
|
**An toàn dấu chồng đến từ CHẾ ĐỘ cách dòng, KHÔNG từ một bội số.** `[fact]` (M1.7 §4.1 + Microsoft Support f25ed208): mọi chế độ tự nới (Single / Multiple / At least / Double) đều nới đủ chứa dấu chồng tiếng Việt (ầ ẫ ễ ộ ỡ ữ); **CHỈ "Exactly"** (cách dòng cứng) cắt đỉnh dấu. → Quy tắc an toàn = **dùng chế độ auto, tránh "Exactly"** (nếu buộc Exactly: ≥ ~1.25× cỡ chữ + render-test). Ngay cả Word "Single" (Montserrat = 1.219×) đã an toàn dấu — **"1.5×" KHÔNG phải sàn an toàn**, nó là mục tiêu đọc thoải mái cho web.
|
||||||
|
|
||||||
|
**Mục tiêu đọc thoải mái (tách khỏi an toàn dấu):**
|
||||||
|
- Body: vùng dễ đọc **120-145%** `[fact]` (Butterick). Web/HMI dùng 1.5× (màn hình đọc xa); Office body khác — xem ánh xạ dưới.
|
||||||
|
- Heading: chặt hơn body (chữ to cần ít leading).
|
||||||
|
|
||||||
|
**Ánh xạ Office-native — Word "Multiple N" ≠ CSS N** `[fact]` (M1.7 §1): Word nhân N với *line-unit của font*, mà Montserrat line-unit = **1.219×** (do cờ OpenType USE_TYPO_METRICS), KHÔNG phải 1.0. Hệ quả cho `.dotx`:
|
||||||
|
|
||||||
|
| Vai trò | Web/CSS (pitch) | Word (Montserrat) | Pitch thực |
|
||||||
|
|---|---|---|---|
|
||||||
|
| Body | line-height 1.5 | **Multiple 1.15** | 1.40× |
|
||||||
|
| Heading lớn (Title / H1-H4) | 1.1-1.3 | **Single** | 1.219× |
|
||||||
|
| Heading nhỏ (H5/H6 = cỡ body) | 1.4 | **Multiple 1.15** | 1.40× |
|
||||||
|
|
||||||
|
> Web giữ 1.5× (không đổi); Office body = 1.40× (Multiple 1.15). **CẤM Word "1.5 lines" cho body** (= 1.829× Montserrat, quá rộng — đây là bug S44). Nguồn: `50-plans/phenikaa-x-office-templates/research-office-typography.md` §1-§2 (đo OS/2 + ECMA-376) + owner ratify S45.
|
||||||
|
|
||||||
|
`[fact]` Latin body 1.4-1.5 (Bringhurst). `[inference]` Buffer riêng cho tiếng Việt KHÔNG cần khi dùng chế độ auto (engine tự nới) — chỉ cần tránh "Exactly" (`research-method-d-standard.md` §4.2).
|
||||||
|
|
||||||
|
#### 2.2.5 Quy tắc dùng (binding)
|
||||||
|
|
||||||
|
1. Heading + body **cùng family Montserrat** (an toàn, per `research-method-d-standard.md` §4.3). KHÔNG trộn 2 font sans khác nhau.
|
||||||
|
2. Phân cấp bằng **cỡ + độ đậm**, không bằng màu đơn thuần.
|
||||||
|
3. Viết hoa chữ đầu câu tiêu đề; KHÔNG drop-shadow/viền chữ (per `visual-from-raw.md` §13).
|
||||||
|
|
||||||
|
**Nguồn:** `visual-from-raw.md` §12 (Montserrat) + §13 (headline Bold 1.1× / body Regular 1.3×, owner ratify) + `research-method-d-standard.md` §4.1 (modular scale Bringhurst `[fact]`) + §4.2 (VN line-height) + §4.3 (font pairing Hoefler `[fact]`) + thực tế owner Word 11pt body. Endorsed ref: Carbon Productive + Fluent 2 ramp `[fact]`. (Material 3 de-based per `research-record-phase-1.md` §P1.2 — KHÔNG dùng.)
|
||||||
|
|
||||||
|
### 2.3 Spacing — lưới 8px
|
||||||
|
|
||||||
|
> [!NOTE] Thuật ngữ: **lưới 8px (8px grid)** = mọi khoảng cách là bội số của 8 · **token** = tên biến cho 1 giá trị · **macro whitespace** = khoảng nghỉ giữa các khối lớn · **micro whitespace** = khe hẹp bên trong 1 thành phần.
|
||||||
|
|
||||||
|
Đơn vị gốc = **8px**. Bước nửa 4px cho phép trong khe hẹp của component. 2 cột đơn vị (Web/HMI px · Office xấp xỉ pt, 1pt ≈ 1.33px):
|
||||||
|
|
||||||
|
| Token | Web/HMI (px) | Office (≈pt) | Dùng cho |
|
||||||
|
|-------|------|------|----------|
|
||||||
|
| `space.0` | 0 | 0 | Không cách |
|
||||||
|
| `space.xxs` | 4 | 3 | Khe hẹp trong component (icon↔nhãn, padding chip) — nửa bước |
|
||||||
|
| `space.xs` | 8 | 6 | Padding nhỏ, gap giữa 2 item liền kề |
|
||||||
|
| `space.sm` | 12 | 9 | Gap trong nhóm field |
|
||||||
|
| `space.md` | 16 | 12 | Padding thẻ mặc định, gap giữa đoạn |
|
||||||
|
| `space.lg` | 24 | 18 | Gap giữa nhóm / section nhỏ |
|
||||||
|
| `space.xl` | 32 | 24 | Padding trang, gap giữa section lớn |
|
||||||
|
| `space.2xl` | 48 | 36 | Khoảng nghỉ lớn (hero, page block) |
|
||||||
|
| `space.3xl` | 64 | 48 | Tách biệt khối chính (landing, dashboard sheet) |
|
||||||
|
|
||||||
|
**Quy tắc (binding):**
|
||||||
|
1. Mọi margin/padding/gap = bội số **8px** (ngoại lệ duy nhất: `space.xxs` 4px cho khe component).
|
||||||
|
2. Macro whitespace (giữa section) ≥ 2× micro whitespace (trong component) — bảo toàn phân cấp thị giác.
|
||||||
|
3. Macro spacing co theo breakpoint (web/HMI); Word/print KHÔNG co (trang vật lý cố định).
|
||||||
|
|
||||||
|
**Nguồn:** `research-method-d-standard.md` §6.2 (chọn lưới 8pt cross-deliverable) + 8pt baseline Material/Fluent `[fact]`.
|
||||||
|
|
||||||
|
> [!NOTE] **Office-native:** "Lưới 8px" trong Word = **lưới 6pt** (8px × 0.75 = 6pt; 1pt = 20 twip). Cột "Office ≈pt" ở bảng trên đã đúng đơn vị (8→6, 16→12, 24→18…) — convert sạch, không cần tính lại. `[fact]` (M1.7 §5.1).
|
||||||
|
|
||||||
|
#### 2.3.1 Núm 1 — Mật độ (density), 3 mức
|
||||||
|
|
||||||
|
> [!NOTE] Thuật ngữ: **density mode** = mức nén bố cục. **comfortable/compact** = tên chuẩn ngành.
|
||||||
|
|
||||||
|
Cùng thang gốc, đổi *bậc* dùng cho padding/gap component (KHÔNG thêm token — chỉ preset chọn bậc). Giá trị gán per mức = `[inference]` (snap lưới 8px, verify reality-test khi dựng template):
|
||||||
|
|
||||||
|
| Mức | Dùng cho | Padding thẻ | Gap nhóm |
|
||||||
|
|---|---|---|---|
|
||||||
|
| **Thoáng** (comfortable) | Tài liệu đọc kỹ, ít dữ liệu (Manual, training, proposal) | `space.lg` 24px | `space.md` 16px |
|
||||||
|
| **Vừa** (default) | Mặc định cân bằng (FAT/SAT, slide) | `space.md` 16px | `space.sm` 12px |
|
||||||
|
| **Dày** (compact) | Bảng dữ liệu đặc (Datasheet, BOM, data-table) | `space.xs` 8px | `space.xxs` 4px |
|
||||||
|
|
||||||
|
> **Nguồn `[fact]`:** Material Design 3 (default/comfortable/compact) + Cloudscape (comfortable/compact data table).
|
||||||
|
|
||||||
|
#### 2.3.2 Núm 2 — Kích thước màn hình (responsive)
|
||||||
|
|
||||||
|
> [!NOTE] Thuật ngữ: **responsive** = bố cục tự điều chỉnh theo bề rộng màn hình. **macro/micro whitespace** = khoảng nghỉ giữa khối lớn / khe trong 1 component.
|
||||||
|
|
||||||
|
Spacing **macro** (giữa khối lớn) co 1 bậc khi màn hẹp dần; **micro** (trong component) giữ nguyên:
|
||||||
|
|
||||||
|
| Breakpoint (§3.4) | Gutter/gap macro |
|
||||||
|
|---|---|
|
||||||
|
| `desktop` >1024px | `space.xl` 32px |
|
||||||
|
| `tablet` 640-1024px | `space.lg` 24px |
|
||||||
|
| `mobile`/HMI nhỏ <640px | `space.md` 16px |
|
||||||
|
|
||||||
|
> **Nguồn `[fact]`:** Utopia (fluid spacing). **CHỈ áp web/HMI** (màn co giãn). **Word/print KHÔNG co** (trang A4 cố định — xem §2.3.3). L1 định *quy tắc*; *cách* co (clamp, gộp cột) = **L2** team dev (per §3.4).
|
||||||
|
|
||||||
|
#### 2.3.3 Núm 3 — Môi trường (Word pt cố định vs web/HMI px co giãn)
|
||||||
|
|
||||||
|
Word đo spacing dọc bằng "space before/after paragraph" + "line spacing" (paragraph model), KHÔNG bằng box padding như web:
|
||||||
|
|
||||||
|
| Môi trường | Đơn vị | Co giãn (núm 2)? | Token |
|
||||||
|
|---|---|:---:|---|
|
||||||
|
| Web / Dashboard | px | ✅ | `space.*` (px) |
|
||||||
|
| HMI | px | ✅ | `space.*` (px) |
|
||||||
|
| Word / In ấn | pt | ❌ (A4 cố định) | `space.*` (cột pt) **+ token Word-native** |
|
||||||
|
|
||||||
|
**Token Word-native:**
|
||||||
|
|
||||||
|
| Token | Giá trị | Vai trò | Nguồn |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `space.word.para-gap` | 6pt (= `space.xs` Office) | Khoảng sau mỗi đoạn (space after paragraph) | `[fact]` Word default 8pt / business 6-12pt → snap 6pt `[inference]` |
|
||||||
|
| `space.word.section-gap` | 12pt (= `space.md`) | Khoảng trước heading mục | `[inference]` neo lưới + nhịp dọc §2.3.4 |
|
||||||
|
| `space.word.line` | Multiple 1.15 (1.40× Montserrat) | Giãn dòng body | `[fact]` §2.2.4 ánh xạ Office — Word "Multiple 1.15", KHÔNG "1.5 lines" |
|
||||||
|
|
||||||
|
> Density (núm 1) áp Word qua các token này: thoáng = section 18pt/para 9pt · vừa = 12/6 · dày = 9/3 `[inference]` (verify template Phase 4).
|
||||||
|
|
||||||
|
#### 2.3.4 Nhịp dọc (vertical rhythm) + ngoại lệ nhà nước
|
||||||
|
|
||||||
|
**Nhịp dọc:** gap giữa section gắn line-height body — 2 tầng độc lập (KHÔNG hạ cấp nguồn research-grade):
|
||||||
|
- **Sàn cứng (binding):** macro ≥ **2×** micro (ngưỡng tối thiểu giữ phân cấp). `[inference]`
|
||||||
|
- **Mục tiêu khuyến nghị:** macro = **4-8×** micro `[fact]` NNGroup — áp density mặc định/thoáng.
|
||||||
|
- **Ngoại lệ compact:** density Dày tiệm cận sàn 2× — precedent Material 3 compact `[fact]` (owner ratify S36).
|
||||||
|
|
||||||
|
**Ngoại lệ văn bản hành chính nhà nước** (cùng nhóm "format pháp lý bên ngoài, brand KHÔNG override" với font Times New Roman §2.2.1): công văn/tờ trình/hồ sơ thầu nhà nước → theo **NĐ 30/2020/NĐ-CP** `[fact]`: font Times New Roman, mã TCVN 6909:2001, cỡ 13-14, lề trên/dưới 20-25mm/trái 30-35mm/phải 15-20mm, số trang giữa chân trang. **NĐ 30 KHÔNG quy định giãn dòng** `[fact]` — "1.5 dòng" là thông lệ kế thừa từ TT 01/2011/TT-BNV (**đã hết hiệu lực 15/6/2020**), không ràng buộc pháp lý hiện hành. Phenikaa-X (cổ phần tư nhân) không thuộc đối tượng bắt buộc `[fact]`, nên tuân khi tài liệu vào quy trình văn thư nhà nước `[inference]`. (M1.7 §4.2)
|
||||||
|
|
||||||
|
### 2.4 Elevation + shadow — 3 mức tối giản
|
||||||
|
|
||||||
|
Phenikaa-X **nghiêng phẳng**: logo + chữ **CẤM** đổ bóng (per `visual-from-raw.md` §13 + don't #6). Elevation chỉ áp dụng cho **bề mặt UI** (thẻ, popup), KHÔNG cho logo/chữ. Bản in (print) = luôn phẳng (giấy không có lớp).
|
||||||
|
|
||||||
|
| Token | Mức | Shadow (CSS) | Dùng cho |
|
||||||
|
|-------|-----|--------------|----------|
|
||||||
|
| `elevation.0` | Phẳng | `none` | Mặc định · nền · print · HMI phẳng |
|
||||||
|
| `elevation.1` | Nổi nhẹ | `0 1px 3px rgba(22,24,36,.12)` | Thẻ, KPI tile, panel |
|
||||||
|
| `elevation.2` | Lớp phủ | `0 4px 12px rgba(22,24,36,.18)` | Modal, dropdown, tooltip, popover |
|
||||||
|
|
||||||
|
> [!NOTE] **Dark mode:** shadow gần như vô hình trên nền tối → dùng **viền 1px `neutral-700`** thay shadow để tách lớp (pattern Fluent dark) `[inference]`.
|
||||||
|
|
||||||
|
**Nguồn:** Fluent depth = shadow-only, KHÔNG tint overlay (khác Material 3 — đã de-base `research-record-phase-1.md` §P1.2) `[fact]`; nghiêng phẳng của brand `visual-from-raw.md` §13.
|
||||||
|
|
||||||
|
### 2.5 Border + radius
|
||||||
|
|
||||||
|
#### Border (viền)
|
||||||
|
|
||||||
|
| Token | px | Dùng cho |
|
||||||
|
|-------|----|----|
|
||||||
|
| `border.0` | 0 | Không viền — **ưu tiên** (nguyên tắc closure: gợi khối bằng nền + khoảng trắng, không cần viền đầy) |
|
||||||
|
| `border.1` | 1px | Mặc định: field, ô bảng, divider |
|
||||||
|
| `border.2` | 2px | Nhấn: trạng thái active |
|
||||||
|
| `border.accent` | 4px (1 cạnh) | Dải nhấn 1 bên (KPI tile mép trái) — gợi container mà không cần viền 4 cạnh |
|
||||||
|
| `border.focus` | 2px (offset 2px) | Vòng focus bàn phím — màu `blue-500` (light) / `blue-200` (dark), tương phản ≥3:1 với nền kề (WCAG 2.2 §2.4.13) `[fact]` |
|
||||||
|
|
||||||
|
**Quy tắc:** tránh viền đầy 4 cạnh dư thừa (anti-pattern "chartjunk"). Ưu tiên khoảng trắng + nền phân tách.
|
||||||
|
|
||||||
|
#### Radius (bo góc)
|
||||||
|
|
||||||
|
| Token | px | Dùng cho |
|
||||||
|
|-------|----|----|
|
||||||
|
| `radius.none` | 0 | Mặc định công nghiệp/HMI — thẩm mỹ AMR sắc cạnh |
|
||||||
|
| `radius.sm` | 2 | Bo nhẹ: chip, badge, input |
|
||||||
|
| `radius.md` | 4 | Thẻ, panel (Office/dashboard) |
|
||||||
|
| `radius.lg` | 8 | Modal, dialog lớn |
|
||||||
|
|
||||||
|
> [!NOTE] **Bo góc tùy bề mặt (L2 quyết định cuối):** HMI/biển công nghiệp nghiêng `radius.none` (sắc cạnh, kỹ thuật); tài liệu Office/dashboard nghiêng `radius.md` 4px (thẻ mềm, thân thiện). L1 cung cấp thang; L2 chọn mặc định theo từng nền tảng.
|
||||||
|
>
|
||||||
|
> **Office-native:** trong Word chỉ **shape / text-box** bo góc được (qua `a:prstGeom roundRect`); **đoạn văn thường + ô bảng KHÔNG bo** (= `radius.none`). Radius chỉ áp cho KPI tile/khối đồ hoạ, không áp body/table. `[fact]` (M1.7 §5.3).
|
||||||
|
|
||||||
|
**Quy tắc tương tác (hover/active/disabled):** chỉ định nghĩa **token nền** ở đây (`border.focus`); ma trận trạng thái đầy đủ per-component thuộc **L2** (platform implementation). Consensus viền mặc định 1px (Carbon/Material/Fluent) `[fact]`.
|
||||||
|
|
||||||
|
### 2.6 Bộ icon
|
||||||
|
|
||||||
|
> [!NOTE] Thuật ngữ: **bộ icon (icon set)** = một thư viện icon thiết kế đồng bộ một phong cách · **Regular** = kiểu viền rỗng (nét vẽ đường viền) · **Filled** = kiểu tô đặc (khối đặc) — đây là tên Fluent dùng · **currentColor** = SVG kế thừa màu chữ của phần tử cha (đổi màu qua token, không sửa file) · **tương phản non-text** = chỉ số WCAG đo độ rõ của đồ hoạ mang nghĩa (icon, viền) trên nền.
|
||||||
|
|
||||||
|
Bộ icon canonical Layer 1 = **Fluent UI System Icons** (Microsoft, giấy phép MIT) — nguồn icon duy nhất cho mọi bề mặt. Chọn vì: phong cách hình học bo nhẹ thân thiện (cùng gia đình Fluent 2 — chuẩn chính của hệ, `research-record-phase-1.md §P1.2`) · có sẵn **đầy đủ cả Regular + Filled** nên không phải trộn thư viện · gói NuGet chính chủ Microsoft hợp stack dev (MudBlazor) · bên bảo trì bền vững. Tên icon cụ thể (`bot-24-regular`, `warning-24-filled`...) là **L2** — không khoá ở đây (xem §4 cơ chế áp dụng).
|
||||||
|
|
||||||
|
**Thang cỡ icon** — neo thẳng cột pt vai trò type scale §2.2 (cùng *neo per-môi-trường*, KHÔNG theo tỷ lệ ÷1.33 cứng của spacing §2.3):
|
||||||
|
|
||||||
|
| Token | Web/HMI (px) | Office (pt) | Khớp vai trò §2.2 | Dùng cho |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| `icon.sm` | 16 | 11 | Body | Inline cạnh chữ body · nhãn · chip |
|
||||||
|
| `icon.md` | 20 | 14 | Heading 3 | **Mặc định UI** — nút, menu, KPI tile |
|
||||||
|
| `icon.lg` | 24 | 18 | ≈ Heading 2 (25px) | Tiêu đề · mục tiêu chạm (touch) · HMI nhìn xa |
|
||||||
|
|
||||||
|
> Icon **inline** (chèn giữa dòng chữ) lấy cỡ bằng chữ kế bên, không cố định bậc. Cỡ theo thiết bị co giãn = **L2** (giống §2.2 type scale).
|
||||||
|
|
||||||
|
**Quy tắc (binding) — 6 luật cốt lõi:**
|
||||||
|
|
||||||
|
1. **Một nguồn duy nhất** — mọi icon từ Fluent UI System Icons, KHÔNG trộn bộ khác.
|
||||||
|
2. **Hai kiểu, chọn theo tình huống** (KHÔNG khoá mặc định cứng): **Regular** (viền rỗng) cho icon thường/phẳng · **Filled** (tô đặc) cho nhấn mạnh / trạng thái active / HMI nhìn xa / nơi cần lắp êm vào MudBlazor. Trong cùng một ngữ cảnh, giữ một kiểu nhất quán.
|
||||||
|
3. **Cỡ icon** theo thang trên, neo thẳng cột pt vai trò §2.2 (icon.sm=Body 11pt · icon.md=H3 14pt · icon.lg≈H2 18pt) — KHÔNG dùng tỷ lệ ÷1.33 của spacing.
|
||||||
|
4. **Màu icon = token**, KHÔNG hardcode hex: dùng `text.*` / `brand.*` / semantic theo ngữ cảnh; icon phụ (trang trí, ít quan trọng) = `neutral-400`. SVG dùng `currentColor` để kế thừa.
|
||||||
|
5. **Icon mang chức năng/trạng thái luôn kèm nhãn** (chữ hoặc tooltip) — theo WCAG 1.4.1 (use of color); kế thừa §2.1.3 (semantic, file này) + nguyên tắc "không chỉ dựa vào màu" §1.4. Khe icon↔nhãn = `space.xxs` 4px.
|
||||||
|
6. **Tương phản non-text ≥ 3:1** cho icon mang nghĩa (WCAG 2.2 §1.4.11). Icon trang trí thuần (không mang thông tin) miễn trừ.
|
||||||
|
|
||||||
|
> Lưu ý DRY: 6 luật **tái dùng** token đã có (theme alias §2.1.4 + type scale §2.2 + `space.xxs` §2.3 + luật WCAG §1.4 / §2.1.3) — chỉ thêm họ token cỡ icon. Danh sách "khái niệm → tên icon Fluent" là tài liệu tra cứu riêng (L2), dựng khi deliverable thật cần (D125 kích hoạt theo thực tế).
|
||||||
|
|
||||||
|
**Nguồn:** `spec-icon-subphase.md` (D150-D154 — chọn Fluent + 6 luật, owner ratify S37) + `research-method-d-amr-hmi-web.md` §3.5 (rubric Q10 icon-set-consistent) + `research-method-d-standard.md` §5.2 (WCAG non-text 3:1) + `[fact]` [Fluent UI System Icons (GitHub, MIT)](https://github.com/microsoft/fluentui-system-icons) · [WCAG 2.2 §1.4.11 non-text contrast](https://www.w3.org/WAI/WCAG22/Understanding/non-text-contrast.html) · [WCAG 1.4.1 use of color](https://www.w3.org/WAI/WCAG22/Understanding/use-of-color.html).
|
||||||
|
|
||||||
|
## 3. Bố cục cơ bản
|
||||||
|
|
||||||
|
> Bố cục L1 đứng trên **3 trụ nghiên cứu**: (1) nguyên tắc tri giác Gestalt, (2) phân cấp thị giác, (3) hệ lưới — đều có nguồn học thuật. KHÔNG dựa trên bản phác ý tưởng in ấn (xem §3.3 cảnh báo).
|
||||||
|
|
||||||
|
### 3.1 Nguyên tắc bố cục — Gestalt + phân cấp thị giác
|
||||||
|
|
||||||
|
> [!NOTE] Thuật ngữ: **Gestalt** = nhóm nguyên tắc tâm lý mô tả cách não gom element rời thành nhóm · **phân cấp thị giác (visual hierarchy)** = thứ tự mắt nhìn element.
|
||||||
|
|
||||||
|
**Gestalt — não nhóm element thế nào** `[fact]` (Wertheimer 1923):
|
||||||
|
|
||||||
|
| Nguyên tắc | Nghĩa | Áp dụng bố cục Phenikaa-X |
|
||||||
|
|-----------|-------|----------------------------|
|
||||||
|
| Gần gũi (proximity) | Element gần nhau = cùng nhóm | Gom cụm KPI bằng khoảng cách (token §2.3), không cần viền |
|
||||||
|
| Tương tự (similarity) | Cùng màu/shape/size = cùng loại | Series chart cùng màu = cùng nhóm đọc |
|
||||||
|
| Đóng kín (closure) | Não tự khép hình thiếu | Dải nhấn `border.accent` 4px gợi khối — không cần viền 4 cạnh |
|
||||||
|
| Hình–nền (figure-ground) | Element nổi trên nền | Khối `blue-500` + chữ trắng = tương phản rõ |
|
||||||
|
|
||||||
|
**Phân cấp thị giác — mắt đọc theo đường nào** `[fact]` (Nielsen Norman Group):
|
||||||
|
- **F-pattern** — dashboard, báo cáo, trang nhiều chữ (quét trái→phải dòng trên → xuống → dọc lề trái).
|
||||||
|
- **Z-pattern** — slide bìa, proposal, marketing ít chữ (4 góc). `[unverified]` bằng chứng yếu hơn F — coi là guideline.
|
||||||
|
- **Phân cấp bằng:** cỡ (tiêu đề/thân ≥ 2.5×) + tương phản màu + khoảng cách. KHÔNG phân cấp bằng màu đơn thuần.
|
||||||
|
|
||||||
|
**Nguồn:** `research-method-d-standard.md` §2 (Gestalt, Wertheimer 1923 `[fact]`) + §3 (F/Z-pattern, NNGroup `[fact]`).
|
||||||
|
|
||||||
|
### 3.2 Hệ lưới — chọn loại theo ngữ cảnh + lưới 12 cột
|
||||||
|
|
||||||
|
> [!NOTE] Thuật ngữ: **cột (column)** = dải dọc chia bố cục · **gutter** = khe giữa 2 cột.
|
||||||
|
|
||||||
|
**Chọn loại lưới theo ngữ cảnh** `[fact]` (Müller-Brockmann 1981):
|
||||||
|
|
||||||
|
| Loại lưới | Dùng cho |
|
||||||
|
|-----------|----------|
|
||||||
|
| Manuscript (1 cột) | Tài liệu văn xuôi: proposal, báo cáo thân bài |
|
||||||
|
| Column (nhiều cột) | Slide, newsletter, brochure |
|
||||||
|
| Modular (lưới 2D) | Dashboard, gallery thẻ, web card |
|
||||||
|
| Hierarchical (bất quy tắc) | Hero section, trang điều hướng (wayfinding) |
|
||||||
|
|
||||||
|
**Lưới số mặc định cho digital = 12 cột** (chia hết 2/3/4/6 → 2 nửa, 3 phần ba, 4 phần tư). Gutter neo token §2.3:
|
||||||
|
|
||||||
|
| Thuộc tính | Giá trị |
|
||||||
|
|------------|---------|
|
||||||
|
| Số cột | 12 (Fluent + Material `[fact]`) |
|
||||||
|
| Gutter desktop | `space.lg` 24px |
|
||||||
|
| Gutter mobile/HMI | `space.md` 16px |
|
||||||
|
| Bề rộng nội dung tối đa | ~1200px (tránh dòng quá dài) |
|
||||||
|
|
||||||
|
**Ví dụ:** 3 ô KPI = 4+4+4 cột · nội dung 8 cột + sidebar 4 cột · 2 nửa = 6+6.
|
||||||
|
|
||||||
|
**Nguồn:** Müller-Brockmann grid taxonomy `[fact]` + Fluent/Material 12-col `[fact]` (KHÔNG dùng Carbon 16-col — Fluent chuẩn chính `research-record-phase-1.md` §P1.2).
|
||||||
|
|
||||||
|
### 3.3 Khối bố cục (layout primitives) — digital
|
||||||
|
|
||||||
|
4–6 khối **composable** (ghép lồng nhau), mỗi khối tự co giãn theo nội dung. Mọi khoảng cách neo token §2.3 (DRY):
|
||||||
|
|
||||||
|
| Primitive | Vai trò | Khoảng cách |
|
||||||
|
|-----------|---------|-------------|
|
||||||
|
| **Container** | Khung giới hạn bề rộng + padding ngoài | `space.xl` 32px (desktop) |
|
||||||
|
| **Stack** | Xếp dọc, đều khoảng cách | gap = token §2.3 |
|
||||||
|
| **Inline** | Xếp ngang, tự xuống dòng (nút, chip, tag) | gap = `space.sm`/`space.md` |
|
||||||
|
| **Grid** | Lưới 2D (thẻ dashboard, gallery) | gap = gutter §3.2 |
|
||||||
|
|
||||||
|
**Nguồn:** composable layout primitives = chuẩn ngành `[fact]` ([Every Layout](https://every-layout.dev/rudiments/composition/) · [Atlassian primitives](https://atlassian.design/components/primitives/overview)).
|
||||||
|
|
||||||
|
> [!WARNING] **Bản in KHÔNG phải nguồn L1.** `applied-from-raw.md` §2 ("5 khối bố cục") là **bản phác ý tưởng in ấn trích từ guideline tập đoàn** (dùng motif 2:5 + font UTM Avo — cả hai Phenikaa-X KHÔNG dùng), ngôn ngữ "gợi ý / có thể". Đây là **điểm khởi đầu cho template in ở Phase 2**, KHÔNG phải primitive L1 ràng buộc. Khi Phase 2 dựng template in → re-research + chuyển motif sang LiDAR + font sang Montserrat, owner ratify.
|
||||||
|
|
||||||
|
### 3.4 Breakpoint — điểm tham chiếu (hành vi co giãn → L2)
|
||||||
|
|
||||||
|
> [!IMPORTANT] L1 chỉ định nghĩa **bộ điểm tham chiếu** (từ vựng chung). **Hành vi co giãn thật** (cột nào gộp, font scale theo màn hình) thuộc **L2** — nhất quán quyết định §2.2 "kích thước theo thiết bị = L2".
|
||||||
|
|
||||||
|
| Tên | Bề rộng màn hình | Ngữ cảnh |
|
||||||
|
|-----|------------------|----------|
|
||||||
|
| `mobile` | < 640px | Điện thoại, HMI nhỏ |
|
||||||
|
| `tablet` | 640–1024px | Tablet, HMI tầm trung |
|
||||||
|
| `desktop` | > 1024px | PC, dashboard lớn |
|
||||||
|
|
||||||
|
**Quy tắc:** L1 cấp 3 mốc làm vocabulary chung; L1 KHÔNG quy định "mobile lưới 12 thành mấy cột" — việc đó L2 (per nền tảng). `[inference]`
|
||||||
|
|
||||||
|
## 4. Cơ chế áp dụng
|
||||||
|
|
||||||
|
2 cơ chế kết hợp, phủ ~80% trường hợp dùng (theo spec §8.7, quyết định D130):
|
||||||
|
|
||||||
|
### 4.1 Cơ chế 1 — Tự nạp thụ động (passive)
|
||||||
|
|
||||||
|
`@_foundation/design-language.md` đã thêm vào `70-company/CLAUDE.md` (cùng kiểu với `@index.md`).
|
||||||
|
|
||||||
|
- **Kích hoạt:** Claude tự nạp tài liệu này khi làm việc trong `70-company/`.
|
||||||
|
- **Phạm vi:** output thương hiệu trong 70-company (asset logo, template thương hiệu, rà soát governance).
|
||||||
|
- **Chi phí:** ~744 dòng nạp mỗi phiên làm việc trong 70-company (đã tăng ~1.7× so với ~430 dòng Phase 1 sau khi thêm §2.1.7 data-viz + §2.3.1-4 spacing + §2.6 icon + các errata) — vẫn chấp nhận được, nhưng là yếu tố cân nhắc cho §4.3 (vault rule paths-glob) nếu tiếp tục phình.
|
||||||
|
|
||||||
|
### 4.2 Cơ chế 2 — Skill gọi tay (active)
|
||||||
|
|
||||||
|
Skill `phenikaa-x-design-apply` đặt tại `.claude/skills/phenikaa-x-design-apply/SKILL.md`.
|
||||||
|
|
||||||
|
- **Kích hoạt:** anh gõ `/phenikaa-x-design-apply` khi dựng deliverable mới.
|
||||||
|
- **Đầu ra:** thiết kế đã áp dụng + bảng tự kiểm 5 câu + trích nguồn quy tắc.
|
||||||
|
- **Phạm vi:** Dashboard, báo cáo FAT, slide, email, brochure (mọi nơi ngoài 70-company).
|
||||||
|
|
||||||
|
### 4.3 Vault rule paths-glob — HOÃN
|
||||||
|
|
||||||
|
Theo D125 "kích hoạt theo thực tế": chỉ thêm vault rule nếu Phase 5 pilot cho thấy anh quên gõ skill nhiều lần.
|
||||||
|
|
||||||
|
## 5. Cross-references
|
||||||
|
|
||||||
|
### Nguồn căn cứ (per spec §6.1)
|
||||||
|
|
||||||
|
Foundation 4 tầng (đã ratify):
|
||||||
|
- `visual-from-raw.md` — spec màu / typography / logo / motif
|
||||||
|
- `identity-from-raw.md` — 6 giá trị cốt lõi (truy nguyên nguyên tắc)
|
||||||
|
- `applied-from-raw.md` — giọng viết (truy nguyên nguyên tắc §1)
|
||||||
|
- `governance-from-raw.md` — 5 giá trị vận hành (dùng cho phạm vi rà soát governance §4; chưa cite ở §1-§3, reserved Phase 2+)
|
||||||
|
|
||||||
|
Nghiên cứu method D (ship S19):
|
||||||
|
- `50-plans/phenikaa-x-design-system/research-method-d-standard.md` — chuẩn ngành (Gestalt, grid taxonomy, lưới 8pt)
|
||||||
|
- `50-plans/phenikaa-x-design-system/research-method-d-community.md` — Carbon / Material 3 / Fluent 2 / Atlassian / Salesforce
|
||||||
|
- `50-plans/phenikaa-x-design-system/research-method-d-amr-hmi-web.md` — đặc thù AMR / HMI / Web
|
||||||
|
- `50-plans/phenikaa-x-design-system/research-method-d-rubric.md` — rubric kiểm Q1-Q5
|
||||||
|
|
||||||
|
### Nguồn spec
|
||||||
|
|
||||||
|
- `50-plans/phenikaa-x-design-system/spec-design-language-stream.md` — spec brainstorm ratify 2026-05-31
|
||||||
|
- `50-plans/phenikaa-x-design-system/plan.md` — plan stream 5 Phase
|
||||||
|
- `50-plans/phenikaa-x-design-system/research-record-phase-1.md` — nhật ký audit Phase 1
|
||||||
|
|
||||||
|
### Cơ chế áp dụng
|
||||||
|
|
||||||
|
- `70-company/CLAUDE.md` — `@_foundation/design-language.md` tự nạp thụ động
|
||||||
|
- `.claude/skills/phenikaa-x-design-apply/SKILL.md` — gọi tay chủ động
|
||||||
|
|
||||||
|
## Lịch sử phiên bản
|
||||||
|
|
||||||
|
### v0.4.4 (2026-06-10) — Errata: hấp thụ token Caution + dọn nhất quán (audit workflow S59)
|
||||||
|
|
||||||
|
**Thêm (errata additive — KHÔNG đổi token cũ):**
|
||||||
|
- §2.1.2 — thêm bậc `neutral-550` `#6A6F88` (giữa `neutral-500` và `neutral-600`); `border.strong` dark nay trỏ token này thay vì hardcode hex `#6A6F88` — khôi phục nguyên tắc §2.1.4 "alias trỏ token, KHÔNG hardcode hex".
|
||||||
|
- §2.1.3 — thêm biến thể `caution.fill` `#F9A900` (nền vàng callout "Thận trọng" ANSI Y2 / ISO 3864 signal yellow), buộc chữ đen `neutral-900`. Đối xứng tiền lệ `warning.icon` (v0.4.2): trước chỉ nhắc trong changelog prose, nay thành token chính thức §2.1.3 + WCAG §2.1.6.
|
||||||
|
- §2.1.6 — thêm 2 dòng WCAG cho `caution.fill` (8.99:1 / `neutral-900` AAA · 1.96:1 / white FAIL → buộc chữ đen).
|
||||||
|
|
||||||
|
**Sửa (errata — số liệu lỗi thời, KHÔNG đổi token):**
|
||||||
|
- §2.1.6 — đồng bộ cặp chữ trắng / `orange-500` + `border.strong` `neutral-450` / white: bảng ghi `3.2:1` → `3.15:1` (giá trị thực công thức W3C; làm tròn lên 3.2 che mức sát ngưỡng 3:1, đã khớp callout phân tầng cam vốn ghi 3.15).
|
||||||
|
- §4.1 — "~430 dòng" → "~744 dòng" (số dòng thực sau Phase 2/3 + icon + errata; chi phí auto-load eager tăng ~1.7×).
|
||||||
|
|
||||||
|
**Nguồn:** workflow kiểm chứng độc lập 8 chiều (S59 2026-06-10 — 10/21 phát hiện qua phản biện được xác nhận) + `research-status-colors-office.md` §6 (#F9A900 = 8.99:1 / chữ đen, D202) + `[fact]` công thức relative luminance W3C (tự tính lại #F9A900 + neutral-550) + owner ratify S59 2026-06-10. Nhãn H1/frontmatter giữ `v0.4` theo chính sách errata-no-bump; thêm dòng trỏ dưới H1.
|
||||||
|
|
||||||
|
### v0.4.3 (2026-06-10) — Errata: sửa thuật ngữ + điều kiện `error.text-sm`
|
||||||
|
|
||||||
|
**Sửa (errata — KHÔNG đổi token/giá trị màu; KHÔNG bump frontmatter, đúng tiền lệ v0.4.1/v0.4.2):**
|
||||||
|
- §2.1.3 — thuật ngữ nguyên nhân nhoè đỏ nhỏ: **"chromostereopsis" → "tán sắc ngang (TCA — chromatic aberration)"**. Chromostereopsis là ảo giác chiều sâu đỏ/xanh (cần màu đối nghịch kế bên), KHÔNG phải cơ chế nhoè chữ đỏ trên nền sáng. Đồng bộ `research-status-colors-office.md` §3 (đã ghi TCA từ S56).
|
||||||
|
- §2.1.3 — làm rõ **điều kiện cần `error.text-sm`**: chỉ khi HỘI ĐỦ cỡ nhỏ + nét mảnh + bão hoà cao + nền sáng; nêu rõ **nền tối gần như không bị** (tán sắc không thấy trên nền đen) → dark-mode giữ đỏ sáng, không cần trầm.
|
||||||
|
|
||||||
|
**Nguồn:** `[fact]` [UXmatters — color theory digital displays](https://www.uxmatters.com/mt/archives/2007/01/applying-color-theory-to-digital-displays.php) · [MIT 6.813 Reading 16 Color](https://web.mit.edu/6.813/www/sp16/classes/16-color/) · [W3C WCAG3 visual contrast of text](https://www.w3.org/WAI/GL/WCAG3/2021/how-tos/visual-contrast-of-text/) (đỏ/xanh tán sắc, nhoè bão hoà rõ nhất nền trắng — không thấy nền đen) + `research-status-colors-office.md` §3 + owner ratify S58 2026-06-10.
|
||||||
|
|
||||||
|
### v0.4.2 (2026-06-08) — Errata: token `warning.icon` cho callout office
|
||||||
|
|
||||||
|
**Thêm (errata additive — KHÔNG đổi token cũ):**
|
||||||
|
- §2.1.3 — thêm biến thể `warning.icon` `#CB6119` (cam ISO, cho icon + tiêu đề callout cảnh báo cỡ lớn); giữ `warning #9A5B00` cho chữ/nhãn nhỏ. Đối xứng tiền lệ `error`/`error.text-sm`.
|
||||||
|
- §2.1.6 — thêm 2 dòng WCAG cho `warning.icon` (3.99:1 / white · 3.76:1 / `neutral-50` — đạt ngưỡng 3:1 chữ lớn/icon, `[fact]` công thức W3C).
|
||||||
|
|
||||||
|
**Nguồn:** `50-plans/phenikaa-x-office-templates/research-status-colors-office.md` (§6 quyết định cuối + owner ratify S56 2026-06-08). Callout office dùng `warning.icon` cho Cảnh báo; Thận trọng dùng nền vàng `#F9A900` + chữ đen (Y2 ANSI).
|
||||||
|
|
||||||
|
### v0.4.1 (2026-06-04) — Errata typography Office-native (M1.7)
|
||||||
|
|
||||||
|
**Sửa (errata — KHÔNG đổi token, chỉ làm rõ Office mapping + sửa cite pháp lý):**
|
||||||
|
- §2.2.4 — viết lại: an toàn dấu chồng VN đến từ **chế độ auto** (tránh "Exactly"), KHÔNG từ bội số 1.5×; thêm bảng **ánh xạ Office** (Word "Multiple N" ≠ CSS N vì Montserrat line-unit = 1.219×, cờ USE_TYPO_METRICS). Body Word = **Multiple 1.15** (1.40×); heading lớn = **Single** (1.219×).
|
||||||
|
- §2.2.2 — note cột line-height = giá trị web/CSS; Word-native xem §2.2.4.
|
||||||
|
- §2.3 — note "lưới 8px" Office = lưới 6pt (cột pt đã đúng).
|
||||||
|
- §2.3.3 — `space.word.line` 1.5 → Multiple 1.15; bỏ cite TT 01/2011 sai.
|
||||||
|
- §2.3.4 — **NĐ 30 KHÔNG quy định giãn dòng**; "1.5 dòng" kế thừa TT 01/2011 (**đã hết hiệu lực 15/6/2020**).
|
||||||
|
- §2.5 — note radius: Word chỉ shape/text-box bo được, body+bảng KHÔNG bo.
|
||||||
|
|
||||||
|
**Nguồn:** `50-plans/phenikaa-x-office-templates/research-office-typography.md` (M1.7 — đo OS/2 binary + ECMA-376 + NĐ30 Phụ lục I) + owner ratify S45 2026-06-04.
|
||||||
|
|
||||||
|
### v0.4 (2026-06-01) — Sub-phase icon: chọn bộ icon Fluent + 6 luật cốt lõi
|
||||||
|
|
||||||
|
**Ship (additive — Minor bump, KHÔNG đụng token cũ):**
|
||||||
|
- §2.6 mới — Bộ icon canonical = **Fluent UI System Icons** (Microsoft, MIT). Thêm thang cỡ `icon.sm/md/lg` (16/20/24px) + 6 luật cốt lõi (một nguồn · 2 kiểu Regular/Filled theo tình huống · cỡ neo type scale · màu = token · icon kèm nhãn WCAG 1.4.1 · non-text ≥3:1). Tái dùng token sẵn có, không tạo token màu/spacing mới.
|
||||||
|
|
||||||
|
**Defer reality-activated:** icon AMR đặc thù (AMR/AGV/LiDAR/dock/mission) · bảng tra "khái niệm → tên Fluent" (L2) · luật nâng cao (keyline grid, ma trận state).
|
||||||
|
|
||||||
|
**Reconcile nhãn version:** icon ship trước Phase 4 → icon nhận **v0.4**; Phase 4 (Pattern FAT report) rebase **v0.5** khi ship (per `spec-icon-subphase.md` §4 + reviewer S37 MAJOR-1). Đã sync `plan.md` Phase 4 (v0.4→v0.5).
|
||||||
|
|
||||||
|
**Quyết định nguồn:** `50-plans/phenikaa-x-design-system/spec-icon-subphase.md` D150-D154 (brainstorm S37 + owner ratify Fluent + kiểu theo tình huống).
|
||||||
|
|
||||||
|
### v0.3 (2026-06-01) — Phase 3: thang màu sequential đều cảm nhận + mô hình spacing 3 núm
|
||||||
|
|
||||||
|
**Ship (additive — Minor bump):**
|
||||||
|
- §2.1.7.2 — Sequential ĐỔI từ "mượn thang brand" → brand-anchored đơn sắc đều L (OKLab), neo cứng `seq-700`≈Deep Blue + `seq-900`=Dark Blue. Trả "nợ" perceptual-uniform v0.2.
|
||||||
|
- §2.3 — Thêm mô hình spacing "1 thang gốc + 3 núm" (§2.3.1 density 3 mức · §2.3.2 responsive · §2.3.3 môi trường + token `space.word.*` · §2.3.4 nhịp dọc + ngoại lệ nhà nước). Bảng `space.0…3xl` GIỮ nguyên.
|
||||||
|
|
||||||
|
**Tách Phase sau (D146):** icon set → sub-phase riêng (thẩm mỹ risk cao, cần phiên tập trung).
|
||||||
|
|
||||||
|
**Quyết định nguồn:** `50-plans/phenikaa-x-design-system/spec-phase-3.md` D146-D149 (reviewer-clean iter1 + owner ratify S36).
|
||||||
|
|
||||||
|
### v0.2 (2026-06-01) — Phase 2: bảng màu data-viz + chữ đỏ nhỏ
|
||||||
|
|
||||||
|
**Ship (additive — Minor bump, KHÔNG đổi token v0.1 nào):**
|
||||||
|
- §2.1.7 mới — Data-viz 4 họ màu (categorical 4/6 + sequential + diverging) + alias `dataviz.*`
|
||||||
|
- §2.1.3 thêm biến thể `error.text-sm` (chữ đỏ nhỏ chống rung viền) — không đổi nghĩa `error`
|
||||||
|
- §2.1.6 thêm 2 dòng WCAG cho `error.text-sm` (7.26:1 sáng / 9.01:1 tối — AAA)
|
||||||
|
|
||||||
|
**Hoãn Phase 3 (v0.3):**
|
||||||
|
- Sequential perceptual-uniform (thang đều cảm nhận) (→ shipped v0.3)
|
||||||
|
- Spacing formal scale (→ shipped v0.3, mô hình 3 núm)
|
||||||
|
- Icon set (→ tách sub-phase riêng per D146)
|
||||||
|
|
||||||
|
**Quyết định nguồn:** `50-plans/phenikaa-x-design-system/spec-pattern-dashboard.md` D134–D142 (reviewer agent duyệt 2 vòng) + `palette_eval.py` (số đo khách quan).
|
||||||
|
|
||||||
|
### v0.1 (2026-05-31) — Phase 1 bản nháp đầu
|
||||||
|
|
||||||
|
**Ship:**
|
||||||
|
- §1 Nguyên tắc nền tảng — 5 nguyên tắc (3 truy nguyên giá trị cốt lõi + 2 bảo đảm phạm vi Layer 1)
|
||||||
|
- §2 Token — màu (thang sắc độ + alias semantic + verify WCAG) / chữ (thang cỡ + role mapping + verify dấu tiếng Việt) / spacing lưới 8px / elevation 3 mức / border + radius
|
||||||
|
- §3 Bố cục — lưới 12 cột + 4 khối bố cục (Container/Stack/Inline/Grid) + 4 breakpoint
|
||||||
|
- §4 Cơ chế áp dụng — @file thụ động 70-company + skill gọi tay
|
||||||
|
|
||||||
|
**Hoãn Phase 2+:**
|
||||||
|
- Component (mảnh Lego)
|
||||||
|
- Pattern Dashboard (Phase 2)
|
||||||
|
- Data viz (Phase 3)
|
||||||
|
- Pattern báo cáo FAT (Phase 4)
|
||||||
|
|
||||||
|
**Cờ bất định thẩm mỹ (rà lại Phase 5 audit):**
|
||||||
|
1. §1 cách đặt tên nguyên tắc — chờ feedback pilot
|
||||||
|
2. §2.1 số bậc thang sắc độ — rà lại theo cycle-time S24
|
||||||
|
3. §2.2 cặp trọng lượng font — chờ feedback pilot
|
||||||
|
4. §2.4 thẩm mỹ elevation — chờ feedback pilot
|
||||||
|
5. §3.3 cách đặt tên khối bố cục — quy ước chủ quan
|
||||||
BIN
image-1.png
BIN
image-1.png
Binary file not shown.
|
Before Width: | Height: | Size: 1.5 MiB |
11
web-client/.dockerignore
Normal file
11
web-client/.dockerignore
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
node_modules
|
||||||
|
dist
|
||||||
|
.env
|
||||||
|
*.log
|
||||||
|
npm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
|
pnpm-debug.log*
|
||||||
|
.DS_Store
|
||||||
|
Dockerfile
|
||||||
|
.dockerignore
|
||||||
11
web-client/.env.example
Normal file
11
web-client/.env.example
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
# Leave empty in local dev to use Vite proxy: /api -> PACKAGE_PROXY_TARGET.
|
||||||
|
WEB_CLIENT_IMAGE_REPOSITORY=toiiiiday/robot-installer-web-client
|
||||||
|
WEB_CLIENT_CONTAINER_NAME=robot-installer-web-client
|
||||||
|
WEB_CLIENT_PORT=8080
|
||||||
|
IMAGE_TAG=1.0.0
|
||||||
|
DOCKER_NETWORK=robot-installer-net
|
||||||
|
PACKAGE_PROXY_TARGET=http://robot-installer-web-server:3000
|
||||||
|
|
||||||
|
VITE_PACKAGE_BASE_URL=https://package.pnkr.cloud
|
||||||
|
VITE_AGENT_BASE_URL=http://127.0.0.1:5010
|
||||||
|
VITE_APP_OPEN_URL=http://127.0.0.1
|
||||||
29
web-client/Dockerfile
Normal file
29
web-client/Dockerfile
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
FROM node:22-alpine AS build
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
COPY package*.json ./
|
||||||
|
RUN npm ci
|
||||||
|
|
||||||
|
COPY . .
|
||||||
|
|
||||||
|
ARG VITE_PACKAGE_BASE_URL=
|
||||||
|
ARG VITE_AGENT_BASE_URL=http://127.0.0.1:5010
|
||||||
|
ARG VITE_APP_OPEN_URL=http://127.0.0.1
|
||||||
|
|
||||||
|
RUN VITE_PACKAGE_BASE_URL="${VITE_PACKAGE_BASE_URL}" \
|
||||||
|
VITE_AGENT_BASE_URL="${VITE_AGENT_BASE_URL}" \
|
||||||
|
VITE_APP_OPEN_URL="${VITE_APP_OPEN_URL}" \
|
||||||
|
npm run build
|
||||||
|
|
||||||
|
FROM nginx:1.27-alpine AS runtime
|
||||||
|
|
||||||
|
ENV PACKAGE_PROXY_TARGET=http://web-server:3000
|
||||||
|
|
||||||
|
COPY --from=build /app/dist /usr/share/nginx/html
|
||||||
|
COPY nginx.conf.template /etc/nginx/templates/default.conf.template
|
||||||
|
|
||||||
|
EXPOSE 80
|
||||||
|
|
||||||
|
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
|
||||||
|
CMD wget -qO- http://127.0.0.1/ >/dev/null || exit 1
|
||||||
42
web-client/README.md
Normal file
42
web-client/README.md
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
# Robot Installer Web Client
|
||||||
|
|
||||||
|
Web Client public cho user cài, cập nhật và gỡ app thông qua Local Installer Agent.
|
||||||
|
|
||||||
|
## Chạy local
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm install
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
Mặc định khi chạy dev, client gọi package server qua Vite proxy:
|
||||||
|
|
||||||
|
```text
|
||||||
|
robot.package API: http://localhost:5173/api -> http://localhost:3000/api
|
||||||
|
Local Agent: http://127.0.0.1:5010
|
||||||
|
```
|
||||||
|
|
||||||
|
Có thể đổi trong UI hoặc qua `.env`:
|
||||||
|
|
||||||
|
```env
|
||||||
|
VITE_PACKAGE_BASE_URL=
|
||||||
|
VITE_AGENT_BASE_URL=http://127.0.0.1:5010
|
||||||
|
VITE_APP_OPEN_URL=http://127.0.0.1
|
||||||
|
PACKAGE_PROXY_TARGET=http://localhost:3000
|
||||||
|
```
|
||||||
|
|
||||||
|
Khi deploy `robot.installer` thật, đặt `VITE_PACKAGE_BASE_URL=https://robot.package` để browser gọi thẳng package server.
|
||||||
|
|
||||||
|
## Test thật
|
||||||
|
|
||||||
|
1. Chạy `web-server` tại `http://localhost:3000`.
|
||||||
|
2. Chạy hoặc cài Local Installer Agent tại `http://127.0.0.1:5010`.
|
||||||
|
3. Khi test local, Agent nên có:
|
||||||
|
|
||||||
|
```env
|
||||||
|
ROBOT_PACKAGE_BASE_URL=http://localhost:3000
|
||||||
|
ALLOWED_ORIGINS=http://localhost:5173,http://localhost:4173
|
||||||
|
ALLOWED_DOWNLOAD_HOSTS=localhost,127.0.0.1
|
||||||
|
```
|
||||||
|
|
||||||
|
4. Mở Web Client, bấm `Retry`, chọn app đã `Released`, rồi bấm `Install`.
|
||||||
22
web-client/docker-compose.yml
Normal file
22
web-client/docker-compose.yml
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
services:
|
||||||
|
web-client:
|
||||||
|
image: ${WEB_CLIENT_IMAGE_REPOSITORY:-robot-installer-web-client}:${IMAGE_TAG:-local}
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
args:
|
||||||
|
VITE_PACKAGE_BASE_URL: ${VITE_PACKAGE_BASE_URL:-}
|
||||||
|
VITE_AGENT_BASE_URL: ${VITE_AGENT_BASE_URL:-http://127.0.0.1:5010}
|
||||||
|
VITE_APP_OPEN_URL: ${VITE_APP_OPEN_URL:-http://127.0.0.1}
|
||||||
|
container_name: ${WEB_CLIENT_CONTAINER_NAME:-robot-installer-web-client}
|
||||||
|
environment:
|
||||||
|
PACKAGE_PROXY_TARGET: ${PACKAGE_PROXY_TARGET:-http://robot-installer-web-server:3000}
|
||||||
|
ports:
|
||||||
|
- "${WEB_CLIENT_PORT:-8080}:80"
|
||||||
|
networks:
|
||||||
|
- robot-installer
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
networks:
|
||||||
|
robot-installer:
|
||||||
|
name: ${DOCKER_NETWORK:-robot-installer-net}
|
||||||
|
external: true
|
||||||
BIN
web-client/image/logo_PNKX.png
Normal file
BIN
web-client/image/logo_PNKX.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 126 KiB |
14
web-client/index.html
Normal file
14
web-client/index.html
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="vi">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<meta name="color-scheme" content="light" />
|
||||||
|
<link rel="icon" type="image/png" href="/image/logo_PNKX.png" />
|
||||||
|
<title>Robot Installer</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="root"></div>
|
||||||
|
<script type="module" src="/src/main.jsx"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
63
web-client/nginx.conf.template
Normal file
63
web-client/nginx.conf.template
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
server_name _;
|
||||||
|
|
||||||
|
root /usr/share/nginx/html;
|
||||||
|
index index.html;
|
||||||
|
|
||||||
|
client_max_body_size 1024m;
|
||||||
|
|
||||||
|
location = /api {
|
||||||
|
proxy_pass ${PACKAGE_PROXY_TARGET};
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Host $http_host;
|
||||||
|
proxy_set_header X-Forwarded-Host $http_host;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
proxy_set_header X-Forwarded-Port $server_port;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
}
|
||||||
|
|
||||||
|
location ^~ /api/ {
|
||||||
|
proxy_pass ${PACKAGE_PROXY_TARGET};
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Host $http_host;
|
||||||
|
proxy_set_header X-Forwarded-Host $http_host;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
proxy_set_header X-Forwarded-Port $server_port;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
}
|
||||||
|
|
||||||
|
location = /install-agent.sh {
|
||||||
|
proxy_pass ${PACKAGE_PROXY_TARGET};
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Host $http_host;
|
||||||
|
proxy_set_header X-Forwarded-Host $http_host;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
proxy_set_header X-Forwarded-Port $server_port;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
}
|
||||||
|
|
||||||
|
location ^~ /uploads/ {
|
||||||
|
proxy_pass ${PACKAGE_PROXY_TARGET};
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Host $http_host;
|
||||||
|
proxy_set_header X-Forwarded-Host $http_host;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
proxy_set_header X-Forwarded-Port $server_port;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
}
|
||||||
|
|
||||||
|
location ^~ /packages/ {
|
||||||
|
proxy_pass ${PACKAGE_PROXY_TARGET};
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Host $http_host;
|
||||||
|
proxy_set_header X-Forwarded-Host $http_host;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
proxy_set_header X-Forwarded-Port $server_port;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
}
|
||||||
|
|
||||||
|
location / {
|
||||||
|
try_files $uri $uri/ /index.html;
|
||||||
|
}
|
||||||
|
}
|
||||||
1807
web-client/package-lock.json
generated
Normal file
1807
web-client/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
20
web-client/package.json
Normal file
20
web-client/package.json
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
{
|
||||||
|
"name": "robot-installer-web-client",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"private": true,
|
||||||
|
"type": "module",
|
||||||
|
"description": "Public web client for installing Robot applications through the Local Installer Agent.",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite",
|
||||||
|
"build": "vite build",
|
||||||
|
"preview": "vite preview"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@fluentui/react-icons": "^2.0.333",
|
||||||
|
"@fontsource-variable/montserrat": "^5.3.0",
|
||||||
|
"@vitejs/plugin-react": "^5.0.0",
|
||||||
|
"react": "^19.0.0",
|
||||||
|
"react-dom": "^19.0.0",
|
||||||
|
"vite": "^7.3.5"
|
||||||
|
}
|
||||||
|
}
|
||||||
1569
web-client/src/main.jsx
Normal file
1569
web-client/src/main.jsx
Normal file
File diff suppressed because it is too large
Load Diff
376
web-client/src/services/api.js
Normal file
376
web-client/src/services/api.js
Normal file
@@ -0,0 +1,376 @@
|
|||||||
|
export const DEFAULT_PACKAGE_BASE_URL = normalizeUrl(
|
||||||
|
import.meta.env.VITE_PACKAGE_BASE_URL || window.location.origin
|
||||||
|
);
|
||||||
|
export const DEFAULT_AGENT_BASE_URL = normalizeUrl(
|
||||||
|
import.meta.env.VITE_AGENT_BASE_URL || 'http://127.0.0.1:5010'
|
||||||
|
);
|
||||||
|
export const DEFAULT_APP_OPEN_URL = normalizeUrl(
|
||||||
|
import.meta.env.VITE_APP_OPEN_URL || 'http://127.0.0.1'
|
||||||
|
);
|
||||||
|
|
||||||
|
export function normalizeUrl(value) {
|
||||||
|
const text = String(value || '').trim();
|
||||||
|
return text.replace(/\/+$/, '');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function joinUrl(baseUrl, path) {
|
||||||
|
const normalizedBaseUrl = normalizeUrl(baseUrl);
|
||||||
|
const normalizedPath = String(path || '').startsWith('/') ? path : `/${path || ''}`;
|
||||||
|
return `${normalizedBaseUrl}${normalizedPath}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeOpenUrl(value) {
|
||||||
|
const text = normalizeUrl(value);
|
||||||
|
if (!text) return '';
|
||||||
|
|
||||||
|
try {
|
||||||
|
const parsed = new URL(text);
|
||||||
|
return parsed.protocol === 'http:' || parsed.protocol === 'https:' ? text : '';
|
||||||
|
} catch {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getAppOpenUrl(app) {
|
||||||
|
return normalizeOpenUrl(
|
||||||
|
app?.openUrl
|
||||||
|
|| app?.open_url
|
||||||
|
|| app?.webUrl
|
||||||
|
|| app?.web_url
|
||||||
|
|| app?.homepageUrl
|
||||||
|
|| app?.homepage_url
|
||||||
|
|| app?.homepage
|
||||||
|
) || normalizeOpenUrl(DEFAULT_APP_OPEN_URL);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function requestJson(baseUrl, path, options = {}) {
|
||||||
|
const {
|
||||||
|
timeoutMs = 8000,
|
||||||
|
body,
|
||||||
|
headers,
|
||||||
|
...fetchOptions
|
||||||
|
} = options;
|
||||||
|
const url = joinUrl(baseUrl, path);
|
||||||
|
const controller = new AbortController();
|
||||||
|
const timeout = window.setTimeout(() => controller.abort(), timeoutMs);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(url, {
|
||||||
|
...fetchOptions,
|
||||||
|
headers: {
|
||||||
|
Accept: 'application/json',
|
||||||
|
...(body ? { 'Content-Type': 'application/json' } : {}),
|
||||||
|
...headers
|
||||||
|
},
|
||||||
|
body: body ? JSON.stringify(body) : undefined,
|
||||||
|
signal: controller.signal
|
||||||
|
});
|
||||||
|
|
||||||
|
const text = await response.text();
|
||||||
|
let payload = null;
|
||||||
|
if (text) {
|
||||||
|
try {
|
||||||
|
payload = JSON.parse(text);
|
||||||
|
} catch {
|
||||||
|
payload = text;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`${response.status} ${formatErrorDetail(payload || response.statusText)}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return payload;
|
||||||
|
} catch (error) {
|
||||||
|
if (error?.name === 'AbortError') {
|
||||||
|
throw new Error(`Request timeout: ${url}`);
|
||||||
|
}
|
||||||
|
if (error instanceof TypeError) {
|
||||||
|
throw new Error(`Cannot fetch ${url}. Check endpoint reachability and CORS for this Web Client origin.`);
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
} finally {
|
||||||
|
window.clearTimeout(timeout);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatErrorDetail(detail) {
|
||||||
|
if (Array.isArray(detail)) {
|
||||||
|
return detail.map(formatErrorDetail).filter(Boolean).join('; ');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (detail && typeof detail === 'object') {
|
||||||
|
const location = Array.isArray(detail.loc) ? detail.loc.join('.') : '';
|
||||||
|
const messageParts = [
|
||||||
|
detail.msg,
|
||||||
|
detail.message,
|
||||||
|
detail.error,
|
||||||
|
detail.detail
|
||||||
|
]
|
||||||
|
.map((item) => String(item || '').trim())
|
||||||
|
.filter(Boolean);
|
||||||
|
|
||||||
|
if (Array.isArray(detail.missingPackageFiles) && detail.missingPackageFiles.length > 0) {
|
||||||
|
const missingFiles = detail.missingPackageFiles
|
||||||
|
.map(formatMissingPackageFile)
|
||||||
|
.filter(Boolean)
|
||||||
|
.join('; ');
|
||||||
|
|
||||||
|
if (missingFiles) {
|
||||||
|
messageParts.push(`Missing package files: ${missingFiles}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const message = [...new Set(messageParts)].join('. ');
|
||||||
|
|
||||||
|
if (message) {
|
||||||
|
return location ? `${location}: ${message}` : String(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
return JSON.stringify(detail);
|
||||||
|
} catch {
|
||||||
|
return String(detail);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return String(detail || 'Request failed');
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatMissingPackageFile(item) {
|
||||||
|
if (!item || typeof item !== 'object') return String(item || '').trim();
|
||||||
|
|
||||||
|
const packageName = String(item.packageName || item.componentId || 'package').trim();
|
||||||
|
const version = String(item.version || '').trim();
|
||||||
|
const downloadUrl = String(item.downloadUrl || '').trim();
|
||||||
|
const label = [packageName, version].filter(Boolean).join(' ');
|
||||||
|
|
||||||
|
return downloadUrl ? `${label} (${downloadUrl})` : label;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchPackageApps(packageBaseUrl) {
|
||||||
|
const payload = await requestJson(packageBaseUrl, '/api/apps', { timeoutMs: 10000 });
|
||||||
|
return Array.isArray(payload?.apps) ? payload.apps.map(normalizePackageApp) : [];
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchLatestAgentPackage(packageBaseUrl, arch = 'amd64') {
|
||||||
|
const query = arch ? `?arch=${encodeURIComponent(arch)}` : '';
|
||||||
|
return normalizeLatestAgentPackage(
|
||||||
|
await requestJson(packageBaseUrl, `/api/agent/latest${query}`, { timeoutMs: 7000 })
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchApplicationDetail(packageBaseUrl, appId) {
|
||||||
|
return requestJson(packageBaseUrl, `/api/apps/${encodeURIComponent(appId)}`, { timeoutMs: 10000 });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchApplicationManifest(packageBaseUrl, appId, version) {
|
||||||
|
return requestJson(
|
||||||
|
packageBaseUrl,
|
||||||
|
`/api/apps/${encodeURIComponent(appId)}/versions/${encodeURIComponent(version)}/manifest`,
|
||||||
|
{ timeoutMs: 10000 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchAgentHealth(agentBaseUrl) {
|
||||||
|
return requestJson(agentBaseUrl, '/health', { timeoutMs: 2800 });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchAgentSystemInfo(agentBaseUrl) {
|
||||||
|
return requestJson(agentBaseUrl, '/system-info', { timeoutMs: 5000 });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchInstalledApps(agentBaseUrl) {
|
||||||
|
const payload = await requestJson(agentBaseUrl, '/apps/installed', { timeoutMs: 20000 });
|
||||||
|
return Array.isArray(payload) ? payload.map(normalizeInstalledApp) : [];
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function queueInstall(agentBaseUrl, app) {
|
||||||
|
return requestJson(agentBaseUrl, '/apps/install', {
|
||||||
|
method: 'POST',
|
||||||
|
timeoutMs: 10000,
|
||||||
|
body: {
|
||||||
|
appId: app.appId,
|
||||||
|
appName: app.appName,
|
||||||
|
version: app.version
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function queueUpdate(agentBaseUrl, app, installedApp) {
|
||||||
|
return requestJson(agentBaseUrl, '/apps/update', {
|
||||||
|
method: 'POST',
|
||||||
|
timeoutMs: 10000,
|
||||||
|
body: {
|
||||||
|
appId: app.appId,
|
||||||
|
appName: app.appName,
|
||||||
|
currentVersion: installedApp?.version || '',
|
||||||
|
targetVersion: app.version
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function queueRemove(agentBaseUrl, app) {
|
||||||
|
return requestJson(agentBaseUrl, '/apps/remove', {
|
||||||
|
method: 'POST',
|
||||||
|
timeoutMs: 10000,
|
||||||
|
body: {
|
||||||
|
appId: app.appId,
|
||||||
|
purge: true
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchTaskStatus(agentBaseUrl, taskId) {
|
||||||
|
return normalizeTask(await requestJson(agentBaseUrl, `/tasks/${encodeURIComponent(taskId)}`, { timeoutMs: 7000 }));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchTaskLogs(agentBaseUrl, taskId) {
|
||||||
|
const payload = await requestJson(agentBaseUrl, `/tasks/${encodeURIComponent(taskId)}/logs`, { timeoutMs: 7000 });
|
||||||
|
return Array.isArray(payload?.logs) ? payload.logs.map(normalizeLog) : [];
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchTaskComponents(agentBaseUrl, taskId) {
|
||||||
|
const payload = await requestJson(agentBaseUrl, `/tasks/${encodeURIComponent(taskId)}/components`, { timeoutMs: 7000 });
|
||||||
|
return Array.isArray(payload?.components) ? payload.components.map(normalizeComponent) : [];
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizePackageApp(app) {
|
||||||
|
return {
|
||||||
|
appId: String(app.appId || app.app_id || app.id || '').trim(),
|
||||||
|
appCode: String(app.appCode || app.app_code || app.code || app.appId || app.app_id || '').trim(),
|
||||||
|
appName: String(app.appName || app.app_name || app.name || '').trim(),
|
||||||
|
version: String(app.version || '').trim(),
|
||||||
|
status: String(app.status || 'Released').trim(),
|
||||||
|
packageCount: Number(app.packageCount || app.package_count || 0),
|
||||||
|
openUrl: normalizeOpenUrl(
|
||||||
|
app.openUrl
|
||||||
|
|| app.open_url
|
||||||
|
|| app.webUrl
|
||||||
|
|| app.web_url
|
||||||
|
|| app.homepageUrl
|
||||||
|
|| app.homepage_url
|
||||||
|
|| app.homepage
|
||||||
|
)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeInstalledApp(app) {
|
||||||
|
const serviceChecks = normalizeServiceChecks(app.serviceChecks || app.service_checks);
|
||||||
|
return {
|
||||||
|
appId: String(app.appId || app.app_id || '').trim(),
|
||||||
|
appName: String(app.appName || app.app_name || '').trim(),
|
||||||
|
version: String(app.installedVersion || app.version || app.package_version || '').trim(),
|
||||||
|
status: String(app.status || 'installed').trim(),
|
||||||
|
installedAt: app.installedAt || app.installed_at || '',
|
||||||
|
updatedAt: app.updatedAt || app.updated_at || '',
|
||||||
|
serviceCheckStatus: String(
|
||||||
|
app.serviceCheckStatus
|
||||||
|
|| app.service_check_status
|
||||||
|
|| deriveServiceCheckStatus(serviceChecks)
|
||||||
|
).trim(),
|
||||||
|
serviceChecks,
|
||||||
|
openUrl: normalizeOpenUrl(
|
||||||
|
app.openUrl
|
||||||
|
|| app.open_url
|
||||||
|
|| app.webUrl
|
||||||
|
|| app.web_url
|
||||||
|
|| app.homepageUrl
|
||||||
|
|| app.homepage_url
|
||||||
|
|| app.homepage
|
||||||
|
)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeLatestAgentPackage(agentPackage) {
|
||||||
|
return {
|
||||||
|
version: String(agentPackage?.version || '').trim(),
|
||||||
|
arch: String(agentPackage?.arch || '').trim(),
|
||||||
|
fileName: String(agentPackage?.fileName || agentPackage?.file_name || '').trim(),
|
||||||
|
sizeLabel: String(agentPackage?.sizeLabel || agentPackage?.size_label || '').trim(),
|
||||||
|
downloadUrl: String(agentPackage?.downloadUrl || agentPackage?.download_url || '').trim(),
|
||||||
|
installCommand: String(agentPackage?.installCommand || agentPackage?.install_command || '').trim()
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeTask(task) {
|
||||||
|
return {
|
||||||
|
taskId: task.taskId || task.task_id,
|
||||||
|
type: task.type,
|
||||||
|
appId: task.appId || task.app_id,
|
||||||
|
appName: task.appName || task.app_name,
|
||||||
|
status: task.status,
|
||||||
|
progress: Number(task.progress || 0),
|
||||||
|
currentStep: task.currentStep || task.current_step,
|
||||||
|
currentComponentId: task.currentComponentId || task.current_component_id,
|
||||||
|
errorMessage: task.errorMessage || task.error_message,
|
||||||
|
createdAt: task.createdAt || task.created_at,
|
||||||
|
startedAt: task.startedAt || task.started_at,
|
||||||
|
finishedAt: task.finishedAt || task.finished_at
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeLog(log) {
|
||||||
|
return {
|
||||||
|
time: log.time || log.timestamp || '',
|
||||||
|
level: log.level || 'info',
|
||||||
|
message: log.message || ''
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeComponent(component) {
|
||||||
|
const serviceChecks = normalizeServiceChecks(component.serviceChecks || component.service_checks);
|
||||||
|
return {
|
||||||
|
componentId: component.componentId || component.component_id,
|
||||||
|
type: component.type,
|
||||||
|
status: component.status,
|
||||||
|
progress: Number(component.progress || 0),
|
||||||
|
currentStep: component.currentStep || component.current_step,
|
||||||
|
errorMessage: component.errorMessage || component.error_message,
|
||||||
|
serviceCheckStatus: String(
|
||||||
|
component.serviceCheckStatus
|
||||||
|
|| component.service_check_status
|
||||||
|
|| deriveServiceCheckStatus(serviceChecks)
|
||||||
|
).trim(),
|
||||||
|
serviceChecks,
|
||||||
|
startedAt: component.startedAt || component.started_at,
|
||||||
|
finishedAt: component.finishedAt || component.finished_at
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeServiceChecks(value) {
|
||||||
|
return Array.isArray(value) ? value.map(normalizeServiceCheck).filter((item) => item.serviceName) : [];
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeServiceCheck(check) {
|
||||||
|
const activeState = String(check?.activeState || check?.active_state || check?.status || 'unknown').trim();
|
||||||
|
const active = typeof check?.active === 'boolean' ? check.active : activeState === 'active';
|
||||||
|
const readinessStatus = String(check?.readinessStatus || check?.readiness_status || '').trim();
|
||||||
|
const healthy = typeof check?.healthy === 'boolean'
|
||||||
|
? check.healthy
|
||||||
|
: active && (!readinessStatus || readinessStatus === 'ready');
|
||||||
|
|
||||||
|
return {
|
||||||
|
serviceName: String(check?.serviceName || check?.service_name || '').trim(),
|
||||||
|
componentId: String(check?.componentId || check?.component_id || '').trim(),
|
||||||
|
packageName: String(check?.packageName || check?.package_name || '').trim(),
|
||||||
|
loadState: String(check?.loadState || check?.load_state || 'unknown').trim(),
|
||||||
|
activeState,
|
||||||
|
subState: String(check?.subState || check?.sub_state || 'unknown').trim(),
|
||||||
|
unitFileState: String(check?.unitFileState || check?.unit_file_state || 'unknown').trim(),
|
||||||
|
readinessType: String(check?.readinessType || check?.readiness_type || '').trim(),
|
||||||
|
readinessStatus,
|
||||||
|
status: String(check?.status || activeState || 'unknown').trim(),
|
||||||
|
active,
|
||||||
|
enabled: Boolean(check?.enabled),
|
||||||
|
healthy,
|
||||||
|
stale: Boolean(check?.stale),
|
||||||
|
checkedAt: check?.checkedAt || check?.checked_at || '',
|
||||||
|
errorMessage: check?.errorMessage || check?.error_message || ''
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function deriveServiceCheckStatus(serviceChecks) {
|
||||||
|
if (!serviceChecks.length) return 'not-checked';
|
||||||
|
return serviceChecks.every((check) => check.healthy) ? 'healthy' : 'unhealthy';
|
||||||
|
}
|
||||||
1821
web-client/src/styles.css
Normal file
1821
web-client/src/styles.css
Normal file
File diff suppressed because it is too large
Load Diff
36
web-client/vite.config.js
Normal file
36
web-client/vite.config.js
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
import { defineConfig } from 'vite';
|
||||||
|
import react from '@vitejs/plugin-react';
|
||||||
|
|
||||||
|
const packageProxyTarget = process.env.PACKAGE_PROXY_TARGET
|
||||||
|
|| process.env.VITE_PACKAGE_BASE_URL
|
||||||
|
|| 'http://localhost:3000';
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [react()],
|
||||||
|
server: {
|
||||||
|
port: 5173,
|
||||||
|
strictPort: false,
|
||||||
|
proxy: {
|
||||||
|
'/api': {
|
||||||
|
target: packageProxyTarget,
|
||||||
|
changeOrigin: true
|
||||||
|
},
|
||||||
|
'/install-agent.sh': {
|
||||||
|
target: packageProxyTarget,
|
||||||
|
changeOrigin: true
|
||||||
|
},
|
||||||
|
'/uploads': {
|
||||||
|
target: packageProxyTarget,
|
||||||
|
changeOrigin: true
|
||||||
|
},
|
||||||
|
'/packages': {
|
||||||
|
target: packageProxyTarget,
|
||||||
|
changeOrigin: true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
preview: {
|
||||||
|
port: 4173,
|
||||||
|
strictPort: false
|
||||||
|
}
|
||||||
|
});
|
||||||
11
web-server/.dockerignore
Normal file
11
web-server/.dockerignore
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
node_modules
|
||||||
|
uploads
|
||||||
|
.env
|
||||||
|
*.log
|
||||||
|
npm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
|
pnpm-debug.log*
|
||||||
|
.DS_Store
|
||||||
|
Dockerfile
|
||||||
|
.dockerignore
|
||||||
35
web-server/.env.example
Normal file
35
web-server/.env.example
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
PORT=3000
|
||||||
|
WEB_SERVER_IMAGE_REPOSITORY=toiiiiday/robot-installer-web-server
|
||||||
|
WEB_SERVER_CONTAINER_NAME=robot-installer-web-server
|
||||||
|
WEB_SERVER_PORT=3005
|
||||||
|
IMAGE_TAG=1.0.0
|
||||||
|
DOCKER_NETWORK=robot-installer-net
|
||||||
|
WEB_SERVER_UPLOADS_DIR=./uploads
|
||||||
|
MAX_UPLOAD_BYTES=1073741824
|
||||||
|
AGENT_MAX_UPLOAD_BYTES=1073741824
|
||||||
|
DOCUMENT_MAX_UPLOAD_BYTES=52428800
|
||||||
|
DOCUMENT_MAX_CONTENT_BYTES=2097152
|
||||||
|
DOCUMENT_MAX_CONTENT_CHARS=500000
|
||||||
|
SQLSERVER_HOST=172.20.235.176
|
||||||
|
SQLSERVER_PORT=1433
|
||||||
|
SQLSERVER_DATABASE=RobotInstaller
|
||||||
|
SQLSERVER_USER=sa
|
||||||
|
SQLSERVER_PASSWORD=change_me
|
||||||
|
SQLSERVER_ENCRYPT=false
|
||||||
|
SQLSERVER_TRUST_SERVER_CERTIFICATE=true
|
||||||
|
SQLSERVER_USE_UTC=true
|
||||||
|
AUTH_SECRET=change_this_to_a_long_random_value
|
||||||
|
SESSION_MAX_AGE_MS=28800000
|
||||||
|
SESSION_COOKIE_SECURE=true
|
||||||
|
EMAIL_CONFIRMATION_EXPIRES_MS=86400000
|
||||||
|
APP_BASE_URL=https://package.pnkr.cloud
|
||||||
|
APP_SHOW_ERROR_DETAILS=false
|
||||||
|
WEB_CLIENT_ORIGINS=https://app.pnkr.cloud,http://localhost:8080,http://localhost:5173,http://localhost:4173,http://localhost:3000,http://127.0.0.1:3000
|
||||||
|
|
||||||
|
# Mail chính dùng để gửi email xác nhận tới các tài khoản đăng ký
|
||||||
|
SMTP_HOST=smtp.gmail.com
|
||||||
|
SMTP_PORT=587
|
||||||
|
SMTP_SECURE=false
|
||||||
|
SMTP_USER=main_sender_email@gmail.com
|
||||||
|
SMTP_PASSWORD=main_sender_app_password
|
||||||
|
MAIL_FROM="Robot Installer <main_sender_email@gmail.com>"
|
||||||
9
web-server/.gitignore
vendored
Normal file
9
web-server/.gitignore
vendored
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
node_modules/
|
||||||
|
.env
|
||||||
|
uploads/
|
||||||
|
npm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
|
pnpm-debug.log*
|
||||||
|
*.log
|
||||||
|
.DS_Store
|
||||||
31
web-server/Dockerfile
Normal file
31
web-server/Dockerfile
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
FROM node:22-alpine AS dependencies
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
COPY package*.json ./
|
||||||
|
RUN npm ci --omit=dev
|
||||||
|
|
||||||
|
FROM node:22-alpine AS runtime
|
||||||
|
|
||||||
|
ENV NODE_ENV=production
|
||||||
|
ENV PORT=3000
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
RUN apk add --no-cache bzip2 dpkg su-exec xz zstd
|
||||||
|
|
||||||
|
COPY --from=dependencies /app/node_modules ./node_modules
|
||||||
|
COPY . .
|
||||||
|
COPY docker-entrypoint.sh ./docker-entrypoint.sh
|
||||||
|
|
||||||
|
RUN mkdir -p uploads/packages/agent uploads/documents \
|
||||||
|
&& chown -R node:node uploads \
|
||||||
|
&& chmod +x docker-entrypoint.sh
|
||||||
|
|
||||||
|
EXPOSE 3000
|
||||||
|
|
||||||
|
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
|
||||||
|
CMD node -e "fetch('http://127.0.0.1:' + (process.env.PORT || 3000) + '/healthz').then((response) => process.exit(response.ok ? 0 : 1)).catch(() => process.exit(1))"
|
||||||
|
|
||||||
|
ENTRYPOINT ["./docker-entrypoint.sh"]
|
||||||
|
CMD ["npm", "start"]
|
||||||
11
web-server/database/01_create_database.sql
Normal file
11
web-server/database/01_create_database.sql
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
IF DB_ID(N'RobotInstaller') IS NULL
|
||||||
|
BEGIN
|
||||||
|
CREATE DATABASE [RobotInstaller];
|
||||||
|
END;
|
||||||
|
GO
|
||||||
|
|
||||||
|
USE [RobotInstaller];
|
||||||
|
GO
|
||||||
|
|
||||||
|
PRINT N'Database RobotInstaller is ready.';
|
||||||
|
GO
|
||||||
331
web-server/database/02_schema.sql
Normal file
331
web-server/database/02_schema.sql
Normal file
@@ -0,0 +1,331 @@
|
|||||||
|
USE [RobotInstaller];
|
||||||
|
GO
|
||||||
|
|
||||||
|
SET ANSI_NULLS ON;
|
||||||
|
SET QUOTED_IDENTIFIER ON;
|
||||||
|
GO
|
||||||
|
|
||||||
|
IF OBJECT_ID(N'dbo.ApplicationPackages', N'U') IS NOT NULL
|
||||||
|
OR OBJECT_ID(N'dbo.PackageVersions', N'U') IS NOT NULL
|
||||||
|
OR OBJECT_ID(N'dbo.Applications', N'U') IS NOT NULL
|
||||||
|
OR OBJECT_ID(N'dbo.Packages', N'U') IS NOT NULL
|
||||||
|
OR OBJECT_ID(N'dbo.Documents', N'U') IS NOT NULL
|
||||||
|
OR OBJECT_ID(N'dbo.EmailConfirmationTokens', N'U') IS NOT NULL
|
||||||
|
OR OBJECT_ID(N'dbo.Users', N'U') IS NOT NULL
|
||||||
|
BEGIN
|
||||||
|
THROW 50001, 'Schema tables already exist. Review, drop, or migrate existing tables before running 02_schema.sql.', 1;
|
||||||
|
END;
|
||||||
|
GO
|
||||||
|
|
||||||
|
CREATE TABLE dbo.Users
|
||||||
|
(
|
||||||
|
Id UNIQUEIDENTIFIER NOT NULL
|
||||||
|
CONSTRAINT PK_Users PRIMARY KEY CLUSTERED
|
||||||
|
CONSTRAINT DF_Users_Id DEFAULT NEWSEQUENTIALID(),
|
||||||
|
Username NVARCHAR(100) NOT NULL,
|
||||||
|
Email NVARCHAR(255) NOT NULL,
|
||||||
|
PasswordHash NVARCHAR(500) NOT NULL,
|
||||||
|
FullName NVARCHAR(200) NULL,
|
||||||
|
Role NVARCHAR(50) NOT NULL
|
||||||
|
CONSTRAINT DF_Users_Role DEFAULT N'User',
|
||||||
|
IsActive BIT NOT NULL
|
||||||
|
CONSTRAINT DF_Users_IsActive DEFAULT 1,
|
||||||
|
CreatedAt DATETIME2(3) NOT NULL
|
||||||
|
CONSTRAINT DF_Users_CreatedAt DEFAULT SYSUTCDATETIME(),
|
||||||
|
UpdatedAt DATETIME2(3) NULL,
|
||||||
|
CONSTRAINT CK_Users_Role CHECK (Role IN (N'Admin', N'User')),
|
||||||
|
CONSTRAINT CK_Users_Username_NotBlank CHECK (LEN(LTRIM(RTRIM(Username))) > 0),
|
||||||
|
CONSTRAINT CK_Users_Email_NotBlank CHECK (LEN(LTRIM(RTRIM(Email))) > 0)
|
||||||
|
);
|
||||||
|
GO
|
||||||
|
|
||||||
|
CREATE TABLE dbo.EmailConfirmationTokens
|
||||||
|
(
|
||||||
|
Id UNIQUEIDENTIFIER NOT NULL
|
||||||
|
CONSTRAINT PK_EmailConfirmationTokens PRIMARY KEY CLUSTERED
|
||||||
|
CONSTRAINT DF_EmailConfirmationTokens_Id DEFAULT NEWSEQUENTIALID(),
|
||||||
|
UserId UNIQUEIDENTIFIER NOT NULL,
|
||||||
|
TokenHash CHAR(64) NOT NULL,
|
||||||
|
ExpiresAt DATETIME2(3) NOT NULL,
|
||||||
|
ConfirmedAt DATETIME2(3) NULL,
|
||||||
|
CreatedAt DATETIME2(3) NOT NULL
|
||||||
|
CONSTRAINT DF_EmailConfirmationTokens_CreatedAt DEFAULT SYSUTCDATETIME(),
|
||||||
|
CONSTRAINT FK_EmailConfirmationTokens_User
|
||||||
|
FOREIGN KEY (UserId) REFERENCES dbo.Users(Id) ON DELETE CASCADE
|
||||||
|
);
|
||||||
|
GO
|
||||||
|
|
||||||
|
CREATE TABLE dbo.Documents
|
||||||
|
(
|
||||||
|
Id UNIQUEIDENTIFIER NOT NULL
|
||||||
|
CONSTRAINT PK_Documents PRIMARY KEY CLUSTERED
|
||||||
|
CONSTRAINT DF_Documents_Id DEFAULT NEWSEQUENTIALID(),
|
||||||
|
Title NVARCHAR(200) NOT NULL,
|
||||||
|
Category NVARCHAR(50) NOT NULL
|
||||||
|
CONSTRAINT DF_Documents_Category DEFAULT N'other',
|
||||||
|
Summary NVARCHAR(1000) NULL,
|
||||||
|
Content NVARCHAR(MAX) NULL,
|
||||||
|
FilePath NVARCHAR(1000) NULL,
|
||||||
|
OriginalFileName NVARCHAR(260) NULL,
|
||||||
|
MimeType NVARCHAR(200) NULL,
|
||||||
|
FileSizeBytes BIGINT NULL,
|
||||||
|
CreatedByUserId UNIQUEIDENTIFIER NOT NULL,
|
||||||
|
CreatedAt DATETIME2(3) NOT NULL
|
||||||
|
CONSTRAINT DF_Documents_CreatedAt DEFAULT SYSUTCDATETIME(),
|
||||||
|
UpdatedAt DATETIME2(3) NULL,
|
||||||
|
CONSTRAINT FK_Documents_CreatedByUser
|
||||||
|
FOREIGN KEY (CreatedByUserId) REFERENCES dbo.Users(Id),
|
||||||
|
CONSTRAINT CK_Documents_Title_NotBlank CHECK (LEN(LTRIM(RTRIM(Title))) > 0),
|
||||||
|
CONSTRAINT CK_Documents_Category CHECK (
|
||||||
|
Category IN (N'introduction', N'guide', N'user-guide', N'technical', N'policy', N'other')
|
||||||
|
),
|
||||||
|
CONSTRAINT CK_Documents_FileSizeBytes CHECK (FileSizeBytes IS NULL OR FileSizeBytes >= 0),
|
||||||
|
CONSTRAINT CK_Documents_HasReadableContent CHECK (
|
||||||
|
NULLIF(LTRIM(RTRIM(Content)), N'') IS NOT NULL OR FilePath IS NOT NULL
|
||||||
|
)
|
||||||
|
);
|
||||||
|
GO
|
||||||
|
|
||||||
|
CREATE TABLE dbo.Packages
|
||||||
|
(
|
||||||
|
Id UNIQUEIDENTIFIER NOT NULL
|
||||||
|
CONSTRAINT PK_Packages PRIMARY KEY CLUSTERED
|
||||||
|
CONSTRAINT DF_Packages_Id DEFAULT NEWSEQUENTIALID(),
|
||||||
|
PackageCode NVARCHAR(100) NOT NULL,
|
||||||
|
PackageName NVARCHAR(200) NOT NULL,
|
||||||
|
PackageType NVARCHAR(20) NOT NULL,
|
||||||
|
Description NVARCHAR(MAX) NULL,
|
||||||
|
CreatedByUserId UNIQUEIDENTIFIER NOT NULL,
|
||||||
|
CreatedAt DATETIME2(3) NOT NULL
|
||||||
|
CONSTRAINT DF_Packages_CreatedAt DEFAULT SYSUTCDATETIME(),
|
||||||
|
UpdatedAt DATETIME2(3) NULL,
|
||||||
|
IsActive BIT NOT NULL
|
||||||
|
CONSTRAINT DF_Packages_IsActive DEFAULT 1,
|
||||||
|
CONSTRAINT FK_Packages_CreatedByUser
|
||||||
|
FOREIGN KEY (CreatedByUserId) REFERENCES dbo.Users(Id),
|
||||||
|
CONSTRAINT CK_Packages_PackageType CHECK (PackageType IN (N'deb', N'apt', N'docker')),
|
||||||
|
CONSTRAINT CK_Packages_PackageCode_NotBlank CHECK (LEN(LTRIM(RTRIM(PackageCode))) > 0),
|
||||||
|
CONSTRAINT CK_Packages_PackageName_NotBlank CHECK (LEN(LTRIM(RTRIM(PackageName))) > 0)
|
||||||
|
);
|
||||||
|
GO
|
||||||
|
|
||||||
|
CREATE TABLE dbo.PackageVersions
|
||||||
|
(
|
||||||
|
Id UNIQUEIDENTIFIER NOT NULL
|
||||||
|
CONSTRAINT PK_PackageVersions PRIMARY KEY CLUSTERED
|
||||||
|
CONSTRAINT DF_PackageVersions_Id DEFAULT NEWSEQUENTIALID(),
|
||||||
|
PackageId UNIQUEIDENTIFIER NOT NULL,
|
||||||
|
Version NVARCHAR(50) NOT NULL,
|
||||||
|
FilePath NVARCHAR(1000) NULL,
|
||||||
|
DockerImage NVARCHAR(500) NULL,
|
||||||
|
FileChecksumSha256 CHAR(64) NULL,
|
||||||
|
FileSizeBytes BIGINT NULL,
|
||||||
|
ChangeLog NVARCHAR(MAX) NULL,
|
||||||
|
ReleaseDate DATETIME2(3) NOT NULL
|
||||||
|
CONSTRAINT DF_PackageVersions_ReleaseDate DEFAULT SYSUTCDATETIME(),
|
||||||
|
UploadedAt DATETIME2(3) NOT NULL
|
||||||
|
CONSTRAINT DF_PackageVersions_UploadedAt DEFAULT SYSUTCDATETIME(),
|
||||||
|
IsLatest BIT NOT NULL
|
||||||
|
CONSTRAINT DF_PackageVersions_IsLatest DEFAULT 0,
|
||||||
|
IsDeprecated BIT NOT NULL
|
||||||
|
CONSTRAINT DF_PackageVersions_IsDeprecated DEFAULT 0,
|
||||||
|
CONSTRAINT FK_PackageVersions_Package
|
||||||
|
FOREIGN KEY (PackageId) REFERENCES dbo.Packages(Id) ON DELETE CASCADE,
|
||||||
|
CONSTRAINT CK_PackageVersions_Version_NotBlank CHECK (LEN(LTRIM(RTRIM(Version))) > 0),
|
||||||
|
CONSTRAINT CK_PackageVersions_FileSizeBytes CHECK (FileSizeBytes IS NULL OR FileSizeBytes >= 0),
|
||||||
|
CONSTRAINT CK_PackageVersions_FileChecksumSha256 CHECK (
|
||||||
|
FileChecksumSha256 IS NULL
|
||||||
|
OR FileChecksumSha256 NOT LIKE '%[^0-9A-Fa-f]%'
|
||||||
|
)
|
||||||
|
);
|
||||||
|
GO
|
||||||
|
|
||||||
|
CREATE TABLE dbo.Applications
|
||||||
|
(
|
||||||
|
Id UNIQUEIDENTIFIER NOT NULL
|
||||||
|
CONSTRAINT PK_Applications PRIMARY KEY CLUSTERED
|
||||||
|
CONSTRAINT DF_Applications_Id DEFAULT NEWSEQUENTIALID(),
|
||||||
|
AppCode NVARCHAR(100) NOT NULL,
|
||||||
|
AppName NVARCHAR(200) NOT NULL,
|
||||||
|
AppVersion NVARCHAR(50) NOT NULL
|
||||||
|
CONSTRAINT DF_Applications_AppVersion DEFAULT N'1.0.0',
|
||||||
|
Description NVARCHAR(MAX) NULL,
|
||||||
|
CreatedByUserId UNIQUEIDENTIFIER NOT NULL,
|
||||||
|
CreatedAt DATETIME2(3) NOT NULL
|
||||||
|
CONSTRAINT DF_Applications_CreatedAt DEFAULT SYSUTCDATETIME(),
|
||||||
|
UpdatedAt DATETIME2(3) NULL,
|
||||||
|
Status NVARCHAR(50) NOT NULL
|
||||||
|
CONSTRAINT DF_Applications_Status DEFAULT N'Draft',
|
||||||
|
Notes NVARCHAR(500) NULL,
|
||||||
|
OpenUrl NVARCHAR(500) NULL,
|
||||||
|
CONSTRAINT FK_Applications_CreatedByUser
|
||||||
|
FOREIGN KEY (CreatedByUserId) REFERENCES dbo.Users(Id),
|
||||||
|
CONSTRAINT CK_Applications_Status CHECK (Status IN (N'Draft', N'Released', N'Archived')),
|
||||||
|
CONSTRAINT CK_Applications_AppCode_NotBlank CHECK (LEN(LTRIM(RTRIM(AppCode))) > 0),
|
||||||
|
CONSTRAINT CK_Applications_AppName_NotBlank CHECK (LEN(LTRIM(RTRIM(AppName))) > 0),
|
||||||
|
CONSTRAINT CK_Applications_AppVersion_NotBlank CHECK (LEN(LTRIM(RTRIM(AppVersion))) > 0)
|
||||||
|
);
|
||||||
|
GO
|
||||||
|
|
||||||
|
CREATE TABLE dbo.ApplicationPackages
|
||||||
|
(
|
||||||
|
Id UNIQUEIDENTIFIER NOT NULL
|
||||||
|
CONSTRAINT PK_ApplicationPackages PRIMARY KEY CLUSTERED
|
||||||
|
CONSTRAINT DF_ApplicationPackages_Id DEFAULT NEWSEQUENTIALID(),
|
||||||
|
ApplicationId UNIQUEIDENTIFIER NOT NULL,
|
||||||
|
PackageId UNIQUEIDENTIFIER NOT NULL,
|
||||||
|
SelectedVersionId UNIQUEIDENTIFIER NULL,
|
||||||
|
AddedAt DATETIME2(3) NOT NULL
|
||||||
|
CONSTRAINT DF_ApplicationPackages_AddedAt DEFAULT SYSUTCDATETIME(),
|
||||||
|
Notes NVARCHAR(500) NULL,
|
||||||
|
CONSTRAINT FK_ApplicationPackages_Application
|
||||||
|
FOREIGN KEY (ApplicationId) REFERENCES dbo.Applications(Id) ON DELETE CASCADE,
|
||||||
|
CONSTRAINT FK_ApplicationPackages_Package
|
||||||
|
FOREIGN KEY (PackageId) REFERENCES dbo.Packages(Id) ON DELETE CASCADE
|
||||||
|
);
|
||||||
|
GO
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX UX_Users_Username ON dbo.Users(Username);
|
||||||
|
CREATE UNIQUE INDEX UX_Users_Email ON dbo.Users(Email);
|
||||||
|
GO
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX UX_EmailConfirmationTokens_TokenHash
|
||||||
|
ON dbo.EmailConfirmationTokens(TokenHash);
|
||||||
|
|
||||||
|
CREATE INDEX IX_EmailConfirmationTokens_UserId
|
||||||
|
ON dbo.EmailConfirmationTokens(UserId);
|
||||||
|
GO
|
||||||
|
|
||||||
|
CREATE INDEX IX_Documents_Category_UpdatedAt
|
||||||
|
ON dbo.Documents(Category, UpdatedAt DESC, CreatedAt DESC);
|
||||||
|
|
||||||
|
CREATE INDEX IX_Documents_CreatedByUserId
|
||||||
|
ON dbo.Documents(CreatedByUserId);
|
||||||
|
GO
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX UX_Packages_PackageCode ON dbo.Packages(PackageCode);
|
||||||
|
CREATE INDEX IX_Packages_CreatedByUserId ON dbo.Packages(CreatedByUserId);
|
||||||
|
CREATE INDEX IX_Packages_PackageType ON dbo.Packages(PackageType);
|
||||||
|
GO
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX UX_PackageVersions_PackageId_Version
|
||||||
|
ON dbo.PackageVersions(PackageId, Version);
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX UX_PackageVersions_Id_PackageId
|
||||||
|
ON dbo.PackageVersions(Id, PackageId);
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX UX_PackageVersions_OneLatestPerPackage
|
||||||
|
ON dbo.PackageVersions(PackageId)
|
||||||
|
WHERE IsLatest = 1;
|
||||||
|
|
||||||
|
CREATE INDEX IX_PackageVersions_PackageId_ReleaseDate
|
||||||
|
ON dbo.PackageVersions(PackageId, ReleaseDate DESC);
|
||||||
|
GO
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX UX_Applications_AppCode
|
||||||
|
ON dbo.Applications(AppCode);
|
||||||
|
|
||||||
|
CREATE INDEX IX_Applications_CreatedByUserId ON dbo.Applications(CreatedByUserId);
|
||||||
|
CREATE INDEX IX_Applications_Status ON dbo.Applications(Status);
|
||||||
|
GO
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX UX_ApplicationPackages_ApplicationId_PackageId
|
||||||
|
ON dbo.ApplicationPackages(ApplicationId, PackageId);
|
||||||
|
|
||||||
|
CREATE INDEX IX_ApplicationPackages_PackageId
|
||||||
|
ON dbo.ApplicationPackages(PackageId);
|
||||||
|
|
||||||
|
CREATE INDEX IX_ApplicationPackages_SelectedVersionId
|
||||||
|
ON dbo.ApplicationPackages(SelectedVersionId);
|
||||||
|
GO
|
||||||
|
|
||||||
|
ALTER TABLE dbo.ApplicationPackages
|
||||||
|
ADD CONSTRAINT FK_ApplicationPackages_SelectedVersionBelongsToPackage
|
||||||
|
FOREIGN KEY (SelectedVersionId, PackageId)
|
||||||
|
REFERENCES dbo.PackageVersions(Id, PackageId);
|
||||||
|
GO
|
||||||
|
|
||||||
|
CREATE OR ALTER PROCEDURE dbo.SetLatestPackageVersion
|
||||||
|
@PackageVersionId UNIQUEIDENTIFIER
|
||||||
|
AS
|
||||||
|
BEGIN
|
||||||
|
SET NOCOUNT ON;
|
||||||
|
SET XACT_ABORT ON;
|
||||||
|
|
||||||
|
DECLARE @PackageId UNIQUEIDENTIFIER;
|
||||||
|
|
||||||
|
SELECT @PackageId = PackageId
|
||||||
|
FROM dbo.PackageVersions
|
||||||
|
WHERE Id = @PackageVersionId;
|
||||||
|
|
||||||
|
IF @PackageId IS NULL
|
||||||
|
BEGIN
|
||||||
|
THROW 50002, 'Package version does not exist.', 1;
|
||||||
|
END;
|
||||||
|
|
||||||
|
BEGIN TRANSACTION;
|
||||||
|
|
||||||
|
UPDATE dbo.PackageVersions
|
||||||
|
SET IsLatest = 0
|
||||||
|
WHERE PackageId = @PackageId;
|
||||||
|
|
||||||
|
UPDATE dbo.PackageVersions
|
||||||
|
SET IsLatest = 1,
|
||||||
|
IsDeprecated = 0
|
||||||
|
WHERE Id = @PackageVersionId;
|
||||||
|
|
||||||
|
COMMIT TRANSACTION;
|
||||||
|
END;
|
||||||
|
GO
|
||||||
|
|
||||||
|
CREATE OR ALTER PROCEDURE dbo.DeletePackageVersion
|
||||||
|
@PackageVersionId UNIQUEIDENTIFIER
|
||||||
|
AS
|
||||||
|
BEGIN
|
||||||
|
SET NOCOUNT ON;
|
||||||
|
SET XACT_ABORT ON;
|
||||||
|
|
||||||
|
DECLARE @PackageId UNIQUEIDENTIFIER;
|
||||||
|
DECLARE @WasLatest BIT;
|
||||||
|
|
||||||
|
SELECT
|
||||||
|
@PackageId = PackageId,
|
||||||
|
@WasLatest = IsLatest
|
||||||
|
FROM dbo.PackageVersions
|
||||||
|
WHERE Id = @PackageVersionId;
|
||||||
|
|
||||||
|
IF @PackageId IS NULL
|
||||||
|
BEGIN
|
||||||
|
THROW 50003, 'Package version does not exist.', 1;
|
||||||
|
END;
|
||||||
|
|
||||||
|
BEGIN TRANSACTION;
|
||||||
|
|
||||||
|
DELETE FROM dbo.ApplicationPackages
|
||||||
|
WHERE SelectedVersionId = @PackageVersionId;
|
||||||
|
|
||||||
|
DELETE FROM dbo.PackageVersions
|
||||||
|
WHERE Id = @PackageVersionId;
|
||||||
|
|
||||||
|
IF @WasLatest = 1
|
||||||
|
BEGIN
|
||||||
|
DECLARE @NextLatestId UNIQUEIDENTIFIER;
|
||||||
|
|
||||||
|
SELECT TOP (1) @NextLatestId = Id
|
||||||
|
FROM dbo.PackageVersions
|
||||||
|
WHERE PackageId = @PackageId
|
||||||
|
AND IsDeprecated = 0
|
||||||
|
ORDER BY ReleaseDate DESC, UploadedAt DESC;
|
||||||
|
|
||||||
|
IF @NextLatestId IS NOT NULL
|
||||||
|
BEGIN
|
||||||
|
EXEC dbo.SetLatestPackageVersion @NextLatestId;
|
||||||
|
END;
|
||||||
|
END;
|
||||||
|
|
||||||
|
COMMIT TRANSACTION;
|
||||||
|
END;
|
||||||
|
GO
|
||||||
|
|
||||||
|
PRINT N'RobotInstaller schema was created successfully.';
|
||||||
|
GO
|
||||||
134
web-server/database/03_views.sql
Normal file
134
web-server/database/03_views.sql
Normal file
@@ -0,0 +1,134 @@
|
|||||||
|
USE [RobotInstaller];
|
||||||
|
GO
|
||||||
|
|
||||||
|
CREATE OR ALTER VIEW dbo.vw_PackageList
|
||||||
|
AS
|
||||||
|
SELECT
|
||||||
|
p.Id,
|
||||||
|
p.PackageCode,
|
||||||
|
p.PackageName,
|
||||||
|
p.PackageType,
|
||||||
|
p.Description,
|
||||||
|
p.IsActive,
|
||||||
|
p.CreatedAt,
|
||||||
|
p.UpdatedAt,
|
||||||
|
p.CreatedByUserId,
|
||||||
|
u.Username AS CreatedByUsername,
|
||||||
|
latest.Id AS LatestVersionId,
|
||||||
|
latest.Version AS LatestVersion,
|
||||||
|
latest.ReleaseDate AS LatestReleaseDate,
|
||||||
|
latest.FilePath AS LatestFilePath,
|
||||||
|
latest.DockerImage AS LatestDockerImage,
|
||||||
|
version_count.VersionCount
|
||||||
|
FROM dbo.Packages AS p
|
||||||
|
INNER JOIN dbo.Users AS u
|
||||||
|
ON u.Id = p.CreatedByUserId
|
||||||
|
OUTER APPLY
|
||||||
|
(
|
||||||
|
SELECT TOP (1)
|
||||||
|
pv.Id,
|
||||||
|
pv.Version,
|
||||||
|
pv.ReleaseDate,
|
||||||
|
pv.FilePath,
|
||||||
|
pv.DockerImage
|
||||||
|
FROM dbo.PackageVersions AS pv
|
||||||
|
WHERE pv.PackageId = p.Id
|
||||||
|
ORDER BY pv.IsLatest DESC, pv.ReleaseDate DESC, pv.UploadedAt DESC
|
||||||
|
) AS latest
|
||||||
|
OUTER APPLY
|
||||||
|
(
|
||||||
|
SELECT COUNT_BIG(*) AS VersionCount
|
||||||
|
FROM dbo.PackageVersions AS pv
|
||||||
|
WHERE pv.PackageId = p.Id
|
||||||
|
) AS version_count;
|
||||||
|
GO
|
||||||
|
|
||||||
|
CREATE OR ALTER VIEW dbo.vw_PackageVersionList
|
||||||
|
AS
|
||||||
|
SELECT
|
||||||
|
pv.Id,
|
||||||
|
pv.PackageId,
|
||||||
|
p.PackageCode,
|
||||||
|
p.PackageName,
|
||||||
|
p.PackageType,
|
||||||
|
pv.Version,
|
||||||
|
pv.FilePath,
|
||||||
|
pv.DockerImage,
|
||||||
|
pv.FileChecksumSha256,
|
||||||
|
pv.FileSizeBytes,
|
||||||
|
pv.ChangeLog,
|
||||||
|
pv.ReleaseDate,
|
||||||
|
pv.UploadedAt,
|
||||||
|
pv.IsLatest,
|
||||||
|
pv.IsDeprecated
|
||||||
|
FROM dbo.PackageVersions AS pv
|
||||||
|
INNER JOIN dbo.Packages AS p
|
||||||
|
ON p.Id = pv.PackageId;
|
||||||
|
GO
|
||||||
|
|
||||||
|
CREATE OR ALTER VIEW dbo.vw_ApplicationList
|
||||||
|
AS
|
||||||
|
SELECT
|
||||||
|
a.Id,
|
||||||
|
a.AppCode,
|
||||||
|
a.AppName,
|
||||||
|
a.AppVersion,
|
||||||
|
a.Description,
|
||||||
|
a.Status,
|
||||||
|
a.Notes,
|
||||||
|
a.OpenUrl,
|
||||||
|
a.CreatedAt,
|
||||||
|
a.UpdatedAt,
|
||||||
|
a.CreatedByUserId,
|
||||||
|
u.Username AS CreatedByUsername,
|
||||||
|
COUNT_BIG(ap.Id) AS PackageCount
|
||||||
|
FROM dbo.Applications AS a
|
||||||
|
INNER JOIN dbo.Users AS u
|
||||||
|
ON u.Id = a.CreatedByUserId
|
||||||
|
LEFT JOIN dbo.ApplicationPackages AS ap
|
||||||
|
ON ap.ApplicationId = a.Id
|
||||||
|
GROUP BY
|
||||||
|
a.Id,
|
||||||
|
a.AppCode,
|
||||||
|
a.AppName,
|
||||||
|
a.AppVersion,
|
||||||
|
a.Description,
|
||||||
|
a.Status,
|
||||||
|
a.Notes,
|
||||||
|
a.OpenUrl,
|
||||||
|
a.CreatedAt,
|
||||||
|
a.UpdatedAt,
|
||||||
|
a.CreatedByUserId,
|
||||||
|
u.Username;
|
||||||
|
GO
|
||||||
|
|
||||||
|
CREATE OR ALTER VIEW dbo.vw_ApplicationPackageDetails
|
||||||
|
AS
|
||||||
|
SELECT
|
||||||
|
ap.Id,
|
||||||
|
ap.ApplicationId,
|
||||||
|
a.AppCode,
|
||||||
|
a.AppName,
|
||||||
|
a.AppVersion,
|
||||||
|
a.OpenUrl AS AppOpenUrl,
|
||||||
|
ap.PackageId,
|
||||||
|
p.PackageCode,
|
||||||
|
p.PackageName,
|
||||||
|
p.PackageType,
|
||||||
|
ap.SelectedVersionId,
|
||||||
|
pv.Version AS SelectedVersion,
|
||||||
|
pv.FilePath,
|
||||||
|
pv.DockerImage,
|
||||||
|
ap.AddedAt,
|
||||||
|
ap.Notes
|
||||||
|
FROM dbo.ApplicationPackages AS ap
|
||||||
|
INNER JOIN dbo.Applications AS a
|
||||||
|
ON a.Id = ap.ApplicationId
|
||||||
|
INNER JOIN dbo.Packages AS p
|
||||||
|
ON p.Id = ap.PackageId
|
||||||
|
LEFT JOIN dbo.PackageVersions AS pv
|
||||||
|
ON pv.Id = ap.SelectedVersionId;
|
||||||
|
GO
|
||||||
|
|
||||||
|
PRINT N'RobotInstaller views were created successfully.';
|
||||||
|
GO
|
||||||
73
web-server/database/04_notifications.sql
Normal file
73
web-server/database/04_notifications.sql
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
USE [RobotInstaller];
|
||||||
|
GO
|
||||||
|
|
||||||
|
SET ANSI_NULLS ON;
|
||||||
|
SET QUOTED_IDENTIFIER ON;
|
||||||
|
GO
|
||||||
|
|
||||||
|
-- Additive/idempotent migration. Safe to run more than once.
|
||||||
|
IF OBJECT_ID(N'dbo.Notifications', N'U') IS NULL
|
||||||
|
BEGIN
|
||||||
|
CREATE TABLE dbo.Notifications
|
||||||
|
(
|
||||||
|
Id UNIQUEIDENTIFIER NOT NULL
|
||||||
|
CONSTRAINT PK_Notifications PRIMARY KEY CLUSTERED
|
||||||
|
CONSTRAINT DF_Notifications_Id DEFAULT NEWSEQUENTIALID(),
|
||||||
|
RecipientUserId UNIQUEIDENTIFIER NOT NULL,
|
||||||
|
ActorUserId UNIQUEIDENTIFIER NULL,
|
||||||
|
ActorName NVARCHAR(200) NULL,
|
||||||
|
BroadcastId UNIQUEIDENTIFIER NULL,
|
||||||
|
EventType NVARCHAR(100) NOT NULL,
|
||||||
|
Severity NVARCHAR(20) NOT NULL
|
||||||
|
CONSTRAINT DF_Notifications_Severity DEFAULT N'info',
|
||||||
|
Title NVARCHAR(200) NOT NULL,
|
||||||
|
Message NVARCHAR(1000) NOT NULL,
|
||||||
|
EntityType NVARCHAR(50) NULL,
|
||||||
|
EntityId NVARCHAR(100) NULL,
|
||||||
|
ActionUrl NVARCHAR(1000) NULL,
|
||||||
|
ReadAt DATETIME2(3) NULL,
|
||||||
|
CreatedAt DATETIME2(3) NOT NULL
|
||||||
|
CONSTRAINT DF_Notifications_CreatedAt DEFAULT SYSUTCDATETIME(),
|
||||||
|
ExpiresAt DATETIME2(3) NULL,
|
||||||
|
CONSTRAINT FK_Notifications_RecipientUser
|
||||||
|
FOREIGN KEY (RecipientUserId) REFERENCES dbo.Users(Id) ON DELETE CASCADE,
|
||||||
|
CONSTRAINT CK_Notifications_Severity
|
||||||
|
CHECK (Severity IN (N'info', N'success', N'warning', N'error')),
|
||||||
|
CONSTRAINT CK_Notifications_EventType_NotBlank
|
||||||
|
CHECK (LEN(LTRIM(RTRIM(EventType))) > 0),
|
||||||
|
CONSTRAINT CK_Notifications_Title_NotBlank
|
||||||
|
CHECK (LEN(LTRIM(RTRIM(Title))) > 0),
|
||||||
|
CONSTRAINT CK_Notifications_Message_NotBlank
|
||||||
|
CHECK (LEN(LTRIM(RTRIM(Message))) > 0)
|
||||||
|
);
|
||||||
|
END;
|
||||||
|
GO
|
||||||
|
|
||||||
|
IF NOT EXISTS (
|
||||||
|
SELECT 1
|
||||||
|
FROM sys.indexes
|
||||||
|
WHERE object_id = OBJECT_ID(N'dbo.Notifications')
|
||||||
|
AND name = N'IX_Notifications_Recipient_Read_Created'
|
||||||
|
)
|
||||||
|
BEGIN
|
||||||
|
CREATE INDEX IX_Notifications_Recipient_Read_Created
|
||||||
|
ON dbo.Notifications(RecipientUserId, ReadAt, CreatedAt DESC)
|
||||||
|
INCLUDE (Severity, Title, ActionUrl, ExpiresAt);
|
||||||
|
END;
|
||||||
|
GO
|
||||||
|
|
||||||
|
IF NOT EXISTS (
|
||||||
|
SELECT 1
|
||||||
|
FROM sys.indexes
|
||||||
|
WHERE object_id = OBJECT_ID(N'dbo.Notifications')
|
||||||
|
AND name = N'IX_Notifications_BroadcastId'
|
||||||
|
)
|
||||||
|
BEGIN
|
||||||
|
CREATE INDEX IX_Notifications_BroadcastId
|
||||||
|
ON dbo.Notifications(BroadcastId)
|
||||||
|
WHERE BroadcastId IS NOT NULL;
|
||||||
|
END;
|
||||||
|
GO
|
||||||
|
|
||||||
|
PRINT N'RobotInstaller notification schema is ready.';
|
||||||
|
GO
|
||||||
67
web-server/database/05_documents.sql
Normal file
67
web-server/database/05_documents.sql
Normal file
@@ -0,0 +1,67 @@
|
|||||||
|
USE [RobotInstaller];
|
||||||
|
GO
|
||||||
|
|
||||||
|
SET ANSI_NULLS ON;
|
||||||
|
SET QUOTED_IDENTIFIER ON;
|
||||||
|
GO
|
||||||
|
|
||||||
|
IF OBJECT_ID(N'dbo.Documents', N'U') IS NULL
|
||||||
|
BEGIN
|
||||||
|
CREATE TABLE dbo.Documents
|
||||||
|
(
|
||||||
|
Id UNIQUEIDENTIFIER NOT NULL
|
||||||
|
CONSTRAINT PK_Documents PRIMARY KEY CLUSTERED
|
||||||
|
CONSTRAINT DF_Documents_Id DEFAULT NEWSEQUENTIALID(),
|
||||||
|
Title NVARCHAR(200) NOT NULL,
|
||||||
|
Category NVARCHAR(50) NOT NULL
|
||||||
|
CONSTRAINT DF_Documents_Category DEFAULT N'other',
|
||||||
|
Summary NVARCHAR(1000) NULL,
|
||||||
|
Content NVARCHAR(MAX) NULL,
|
||||||
|
FilePath NVARCHAR(1000) NULL,
|
||||||
|
OriginalFileName NVARCHAR(260) NULL,
|
||||||
|
MimeType NVARCHAR(200) NULL,
|
||||||
|
FileSizeBytes BIGINT NULL,
|
||||||
|
CreatedByUserId UNIQUEIDENTIFIER NOT NULL,
|
||||||
|
CreatedAt DATETIME2(3) NOT NULL
|
||||||
|
CONSTRAINT DF_Documents_CreatedAt DEFAULT SYSUTCDATETIME(),
|
||||||
|
UpdatedAt DATETIME2(3) NULL,
|
||||||
|
CONSTRAINT FK_Documents_CreatedByUser
|
||||||
|
FOREIGN KEY (CreatedByUserId) REFERENCES dbo.Users(Id),
|
||||||
|
CONSTRAINT CK_Documents_Title_NotBlank CHECK (LEN(LTRIM(RTRIM(Title))) > 0),
|
||||||
|
CONSTRAINT CK_Documents_Category CHECK (
|
||||||
|
Category IN (N'introduction', N'guide', N'user-guide', N'technical', N'policy', N'other')
|
||||||
|
),
|
||||||
|
CONSTRAINT CK_Documents_FileSizeBytes CHECK (FileSizeBytes IS NULL OR FileSizeBytes >= 0),
|
||||||
|
CONSTRAINT CK_Documents_HasReadableContent CHECK (
|
||||||
|
NULLIF(LTRIM(RTRIM(Content)), N'') IS NOT NULL OR FilePath IS NOT NULL
|
||||||
|
)
|
||||||
|
);
|
||||||
|
END;
|
||||||
|
GO
|
||||||
|
|
||||||
|
IF NOT EXISTS (
|
||||||
|
SELECT 1
|
||||||
|
FROM sys.indexes
|
||||||
|
WHERE name = N'IX_Documents_Category_UpdatedAt'
|
||||||
|
AND object_id = OBJECT_ID(N'dbo.Documents')
|
||||||
|
)
|
||||||
|
BEGIN
|
||||||
|
CREATE INDEX IX_Documents_Category_UpdatedAt
|
||||||
|
ON dbo.Documents(Category, UpdatedAt DESC, CreatedAt DESC);
|
||||||
|
END;
|
||||||
|
GO
|
||||||
|
|
||||||
|
IF NOT EXISTS (
|
||||||
|
SELECT 1
|
||||||
|
FROM sys.indexes
|
||||||
|
WHERE name = N'IX_Documents_CreatedByUserId'
|
||||||
|
AND object_id = OBJECT_ID(N'dbo.Documents')
|
||||||
|
)
|
||||||
|
BEGIN
|
||||||
|
CREATE INDEX IX_Documents_CreatedByUserId
|
||||||
|
ON dbo.Documents(CreatedByUserId);
|
||||||
|
END;
|
||||||
|
GO
|
||||||
|
|
||||||
|
PRINT N'RobotInstaller documents schema is ready.';
|
||||||
|
GO
|
||||||
99
web-server/database/README.md
Normal file
99
web-server/database/README.md
Normal file
@@ -0,0 +1,99 @@
|
|||||||
|
# RobotInstaller database
|
||||||
|
|
||||||
|
Thiết kế này bám theo `database.md` và sơ đồ database hiện có, sau đó bổ sung vài cột cần cho web server:
|
||||||
|
|
||||||
|
- `PackageType`: phân biệt package `.deb` và `docker`.
|
||||||
|
- `AppVersion`: version hiện tại của app đóng gói.
|
||||||
|
- metadata artifact: `DockerImage`, `FileChecksumSha256`, `FileSizeBytes`, `UploadedAt`.
|
||||||
|
- `Role`, `IsActive` cho tài khoản đăng nhập web.
|
||||||
|
|
||||||
|
## Database
|
||||||
|
|
||||||
|
Tên database được chọn: `RobotInstaller`
|
||||||
|
|
||||||
|
Server:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
172.20.235.176
|
||||||
|
```
|
||||||
|
|
||||||
|
Không lưu mật khẩu thật vào file cấu hình. Khi chạy local, tạo file `.env` từ `web-server/.env.example` rồi điền mật khẩu thật.
|
||||||
|
|
||||||
|
## Cấu trúc chính
|
||||||
|
|
||||||
|
| Bảng | Vai trò |
|
||||||
|
| --- | --- |
|
||||||
|
| `dbo.Users` | Người dùng web server |
|
||||||
|
| `dbo.Packages` | Danh mục package |
|
||||||
|
| `dbo.PackageVersions` | Các version của từng package |
|
||||||
|
| `dbo.Applications` | App được đóng gói từ nhiều package |
|
||||||
|
| `dbo.ApplicationPackages` | Liên kết app-package, có thể chọn version cụ thể |
|
||||||
|
| `dbo.Documents` | Nội dung tài liệu và metadata file đính kèm |
|
||||||
|
| `dbo.Notifications` | Thông báo riêng cho từng user và thông báo hệ thống do Admin đăng |
|
||||||
|
|
||||||
|
## Ràng buộc quan trọng
|
||||||
|
|
||||||
|
- `Users.Username`, `Users.Email` là duy nhất.
|
||||||
|
- `Packages.PackageCode` là duy nhất.
|
||||||
|
- `Applications.AppCode` là duy nhất.
|
||||||
|
- Mỗi package không được trùng `Version`.
|
||||||
|
- Mỗi app chỉ chứa một dòng cho mỗi package.
|
||||||
|
- Mỗi package chỉ có tối đa một `IsLatest = 1`.
|
||||||
|
- `ApplicationPackages.SelectedVersionId` bắt buộc thuộc đúng `PackageId` trên cùng dòng.
|
||||||
|
|
||||||
|
## View cho API
|
||||||
|
|
||||||
|
| View | Dùng cho màn hình |
|
||||||
|
| --- | --- |
|
||||||
|
| `dbo.vw_PackageList` | Danh sách package kèm latest version |
|
||||||
|
| `dbo.vw_PackageVersionList` | Chi tiết version của package |
|
||||||
|
| `dbo.vw_ApplicationList` | Danh sách app kèm số package |
|
||||||
|
| `dbo.vw_ApplicationPackageDetails` | Chi tiết package/version trong app |
|
||||||
|
|
||||||
|
## Stored procedure
|
||||||
|
|
||||||
|
| Procedure | Mục đích |
|
||||||
|
| --- | --- |
|
||||||
|
| `dbo.SetLatestPackageVersion` | Đặt một version là latest và tự clear latest cũ |
|
||||||
|
| `dbo.DeletePackageVersion` | Xóa version và các liên kết app đang dùng version đó |
|
||||||
|
|
||||||
|
## Triển khai bằng sqlcmd
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
$env:SQLCMDPASSWORD = '<mat-khau-sa>'
|
||||||
|
|
||||||
|
sqlcmd -S 172.20.235.176 -U sa -b -i .\database\01_create_database.sql
|
||||||
|
sqlcmd -S 172.20.235.176 -U sa -d RobotInstaller -b -i .\database\02_schema.sql
|
||||||
|
sqlcmd -S 172.20.235.176 -U sa -d RobotInstaller -b -i .\database\03_views.sql
|
||||||
|
sqlcmd -S 172.20.235.176 -U sa -d RobotInstaller -b -i .\database\04_notifications.sql
|
||||||
|
sqlcmd -S 172.20.235.176 -U sa -d RobotInstaller -b -i .\database\05_documents.sql
|
||||||
|
```
|
||||||
|
|
||||||
|
Chạy các lệnh trên từ thư mục `web-server`.
|
||||||
|
|
||||||
|
Khi dùng `sqlcmd` để seed/test dữ liệu, thêm `-I` hoặc bật `SET QUOTED_IDENTIFIER ON` vì schema có filtered index cho ràng buộc một latest version trên mỗi package.
|
||||||
|
|
||||||
|
`04_notifications.sql` và `05_documents.sql` là các migration chỉ bổ sung bảng/index và có thể chạy lặp lại. Với database đang hoạt động, chỉ chạy các migration còn thiếu; không chạy lại `02_schema.sql` vì script schema gốc chủ động dừng khi phát hiện bảng đã tồn tại. Web server cũng tự bảo đảm bảng `Documents` tồn tại khi chức năng tài liệu được truy cập.
|
||||||
|
|
||||||
|
## Luồng dữ liệu đề xuất
|
||||||
|
|
||||||
|
1. Upload package mới:
|
||||||
|
- nếu package chưa tồn tại, insert vào `Packages`;
|
||||||
|
- insert version vào `PackageVersions`;
|
||||||
|
- gọi `dbo.SetLatestPackageVersion @PackageVersionId`.
|
||||||
|
|
||||||
|
2. Update package:
|
||||||
|
- insert thêm một dòng mới vào `PackageVersions`;
|
||||||
|
- gọi `dbo.SetLatestPackageVersion @PackageVersionId`.
|
||||||
|
|
||||||
|
3. Tạo app:
|
||||||
|
- insert vào `Applications`;
|
||||||
|
- insert các package được chọn vào `ApplicationPackages`;
|
||||||
|
- nếu user chọn version cụ thể, điền `SelectedVersionId`.
|
||||||
|
|
||||||
|
4. Xóa package:
|
||||||
|
- xóa dòng trong `Packages`;
|
||||||
|
- database tự cascade sang `PackageVersions` và `ApplicationPackages`.
|
||||||
|
|
||||||
|
5. Xóa version:
|
||||||
|
- gọi `dbo.DeletePackageVersion @PackageVersionId` để xóa cả liên kết app đang dùng version đó.
|
||||||
26
web-server/docker-compose.yml
Normal file
26
web-server/docker-compose.yml
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
services:
|
||||||
|
web-server:
|
||||||
|
image: ${WEB_SERVER_IMAGE_REPOSITORY:-robot-installer-web-server}:${IMAGE_TAG:-local}
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
container_name: ${WEB_SERVER_CONTAINER_NAME:-robot-installer-web-server}
|
||||||
|
env_file:
|
||||||
|
- ./.env
|
||||||
|
environment:
|
||||||
|
NODE_ENV: production
|
||||||
|
PORT: 3000
|
||||||
|
APP_BASE_URL: ${APP_BASE_URL:-http://localhost:8080}
|
||||||
|
SESSION_COOKIE_SECURE: ${SESSION_COOKIE_SECURE:-false}
|
||||||
|
WEB_CLIENT_ORIGINS: ${WEB_CLIENT_ORIGINS:-http://localhost:8080,http://localhost:5173,http://localhost:4173,http://localhost:3000,http://127.0.0.1:3000}
|
||||||
|
ports:
|
||||||
|
- "${WEB_SERVER_PORT:-3000}:3000"
|
||||||
|
volumes:
|
||||||
|
- ${WEB_SERVER_UPLOADS_DIR:-./uploads}:/app/uploads
|
||||||
|
networks:
|
||||||
|
- robot-installer
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
networks:
|
||||||
|
robot-installer:
|
||||||
|
name: ${DOCKER_NETWORK:-robot-installer-net}
|
||||||
|
external: true
|
||||||
7
web-server/docker-entrypoint.sh
Normal file
7
web-server/docker-entrypoint.sh
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -e
|
||||||
|
|
||||||
|
mkdir -p /app/uploads/packages/agent /app/uploads/documents
|
||||||
|
chown -R node:node /app/uploads
|
||||||
|
|
||||||
|
exec su-exec node "$@"
|
||||||
BIN
web-server/image/logo_PNKX.png
Normal file
BIN
web-server/image/logo_PNKX.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 126 KiB |
1965
web-server/package-lock.json
generated
Normal file
1965
web-server/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
22
web-server/package.json
Normal file
22
web-server/package.json
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
{
|
||||||
|
"name": "robot-installer-web-server",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"private": true,
|
||||||
|
"description": "Robot Installer package management web server UI",
|
||||||
|
"main": "server.js",
|
||||||
|
"scripts": {
|
||||||
|
"start": "node server.js",
|
||||||
|
"dev": "node server.js"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@fluentui/svg-icons": "^1.1.333",
|
||||||
|
"@fontsource-variable/montserrat": "^5.3.0",
|
||||||
|
"dotenv": "^17.4.2",
|
||||||
|
"ejs": "^3.1.10",
|
||||||
|
"express": "^4.19.2",
|
||||||
|
"mssql": "^12.5.4",
|
||||||
|
"multer": "^2.2.0",
|
||||||
|
"nodemailer": "^9.0.3",
|
||||||
|
"notiflix": "^3.2.8"
|
||||||
|
}
|
||||||
|
}
|
||||||
2356
web-server/public/css/styles.css
Normal file
2356
web-server/public/css/styles.css
Normal file
File diff suppressed because it is too large
Load Diff
1117
web-server/public/js/app.js
Normal file
1117
web-server/public/js/app.js
Normal file
File diff suppressed because it is too large
Load Diff
2934
web-server/server.js
Normal file
2934
web-server/server.js
Normal file
File diff suppressed because it is too large
Load Diff
50
web-server/src/db.js
Normal file
50
web-server/src/db.js
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
const sql = require('mssql');
|
||||||
|
|
||||||
|
let poolPromise;
|
||||||
|
|
||||||
|
function boolFromEnv(value, fallback) {
|
||||||
|
if (value === undefined || value === null || value === '') return fallback;
|
||||||
|
return ['1', 'true', 'yes'].includes(String(value).toLowerCase());
|
||||||
|
}
|
||||||
|
|
||||||
|
function getConfig() {
|
||||||
|
return {
|
||||||
|
server: process.env.SQLSERVER_HOST || 'localhost',
|
||||||
|
port: Number(process.env.SQLSERVER_PORT || 1433),
|
||||||
|
database: process.env.SQLSERVER_DATABASE || 'RobotInstaller',
|
||||||
|
user: process.env.SQLSERVER_USER,
|
||||||
|
password: process.env.SQLSERVER_PASSWORD,
|
||||||
|
options: {
|
||||||
|
encrypt: boolFromEnv(process.env.SQLSERVER_ENCRYPT, false),
|
||||||
|
trustServerCertificate: boolFromEnv(process.env.SQLSERVER_TRUST_SERVER_CERTIFICATE, true),
|
||||||
|
useUTC: boolFromEnv(process.env.SQLSERVER_USE_UTC, true)
|
||||||
|
},
|
||||||
|
pool: {
|
||||||
|
max: 10,
|
||||||
|
min: 0,
|
||||||
|
idleTimeoutMillis: 30000
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getPool() {
|
||||||
|
if (!poolPromise) {
|
||||||
|
poolPromise = sql.connect(getConfig());
|
||||||
|
}
|
||||||
|
|
||||||
|
return poolPromise;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function closePool() {
|
||||||
|
if (!poolPromise) return;
|
||||||
|
|
||||||
|
const pool = await poolPromise;
|
||||||
|
await pool.close();
|
||||||
|
poolPromise = undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
sql,
|
||||||
|
getPool,
|
||||||
|
closePool
|
||||||
|
};
|
||||||
23
web-server/src/document-file-name.js
Normal file
23
web-server/src/document-file-name.js
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
function normalizeDocumentFileName(value) {
|
||||||
|
const fileName = String(value || '');
|
||||||
|
if (!fileName || !/[\u00C2-\u00C5\u00E1\u00E2]/.test(fileName)) return fileName;
|
||||||
|
|
||||||
|
const codePoints = Array.from(fileName, (character) => character.codePointAt(0));
|
||||||
|
if (codePoints.some((codePoint) => codePoint > 0xff)) return fileName;
|
||||||
|
|
||||||
|
const legacyBytes = Buffer.from(codePoints);
|
||||||
|
const decodedName = legacyBytes.toString('utf8');
|
||||||
|
|
||||||
|
if (
|
||||||
|
decodedName.includes('\uFFFD')
|
||||||
|
|| !Buffer.from(decodedName, 'utf8').equals(legacyBytes)
|
||||||
|
) {
|
||||||
|
return fileName;
|
||||||
|
}
|
||||||
|
|
||||||
|
return decodedName;
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
normalizeDocumentFileName
|
||||||
|
};
|
||||||
100
web-server/src/mailer.js
Normal file
100
web-server/src/mailer.js
Normal file
@@ -0,0 +1,100 @@
|
|||||||
|
const nodemailer = require('nodemailer');
|
||||||
|
|
||||||
|
let transporter;
|
||||||
|
|
||||||
|
function boolFromEnv(value, fallback) {
|
||||||
|
if (value === undefined || value === null || value === '') return fallback;
|
||||||
|
return ['1', 'true', 'yes'].includes(String(value).toLowerCase());
|
||||||
|
}
|
||||||
|
|
||||||
|
function isConfigured() {
|
||||||
|
return Boolean(process.env.SMTP_HOST && process.env.SMTP_USER);
|
||||||
|
}
|
||||||
|
|
||||||
|
function escapeHtml(value) {
|
||||||
|
return String(value || '')
|
||||||
|
.replace(/&/g, '&')
|
||||||
|
.replace(/</g, '<')
|
||||||
|
.replace(/>/g, '>')
|
||||||
|
.replace(/"/g, '"')
|
||||||
|
.replace(/'/g, ''');
|
||||||
|
}
|
||||||
|
|
||||||
|
function getSenderAddress() {
|
||||||
|
return process.env.MAIL_FROM || process.env.SMTP_USER;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getTransporter() {
|
||||||
|
if (!isConfigured()) return null;
|
||||||
|
|
||||||
|
if (!transporter) {
|
||||||
|
const port = Number(process.env.SMTP_PORT || 587);
|
||||||
|
|
||||||
|
transporter = nodemailer.createTransport({
|
||||||
|
host: process.env.SMTP_HOST,
|
||||||
|
port,
|
||||||
|
secure: boolFromEnv(process.env.SMTP_SECURE, port === 465),
|
||||||
|
auth: {
|
||||||
|
user: process.env.SMTP_USER,
|
||||||
|
pass: process.env.SMTP_PASSWORD || ''
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return transporter;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function sendConfirmationEmail({ to, name, confirmUrl }) {
|
||||||
|
const mailTransporter = getTransporter();
|
||||||
|
const safeName = escapeHtml(name || to);
|
||||||
|
const safeConfirmUrl = escapeHtml(confirmUrl);
|
||||||
|
|
||||||
|
if (process.env.NODE_ENV !== 'production') {
|
||||||
|
console.info(`Email confirmation link for ${to}: ${confirmUrl}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!mailTransporter) {
|
||||||
|
console.warn(`SMTP is not configured. Email confirmation link for ${to}: ${confirmUrl}`);
|
||||||
|
return { sent: false, reason: 'SMTP_NOT_CONFIGURED' };
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await mailTransporter.sendMail({
|
||||||
|
from: getSenderAddress(),
|
||||||
|
to,
|
||||||
|
subject: 'Xác nhận tài khoản Robot Installer',
|
||||||
|
text: [
|
||||||
|
`Xin chào ${name || to},`,
|
||||||
|
'',
|
||||||
|
'Bạn vừa đăng ký tài khoản hoặc cập nhật email Robot Installer.',
|
||||||
|
`Bấm link sau để xác nhận email và kích hoạt tài khoản: ${confirmUrl}`,
|
||||||
|
'',
|
||||||
|
'Nếu bạn không thực hiện đăng ký này, hãy bỏ qua email.'
|
||||||
|
].join('\n'),
|
||||||
|
html: `
|
||||||
|
<div style="font-family: Arial, sans-serif; color: #172033; line-height: 1.5;">
|
||||||
|
<h2 style="margin: 0 0 12px;">Xác nhận tài khoản Robot Installer</h2>
|
||||||
|
<p>Xin chào ${safeName},</p>
|
||||||
|
<p>Bạn vừa đăng ký tài khoản hoặc cập nhật email Robot Installer. Bấm nút bên dưới để xác nhận email và kích hoạt tài khoản.</p>
|
||||||
|
<p>
|
||||||
|
<a href="${safeConfirmUrl}" style="background: #3755c3; border-radius: 8px; color: #ffffff; display: inline-block; font-weight: 700; padding: 10px 14px; text-decoration: none;">
|
||||||
|
Xác nhận email
|
||||||
|
</a>
|
||||||
|
</p>
|
||||||
|
<p style="color: #566166; font-size: 13px;">Nếu nút không mở được, copy link này vào trình duyệt:<br>${safeConfirmUrl}</p>
|
||||||
|
</div>
|
||||||
|
`
|
||||||
|
});
|
||||||
|
|
||||||
|
console.info('Confirmation email sent:', {
|
||||||
|
to,
|
||||||
|
messageId: result.messageId,
|
||||||
|
accepted: result.accepted,
|
||||||
|
rejected: result.rejected
|
||||||
|
});
|
||||||
|
|
||||||
|
return { sent: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
sendConfirmationEmail
|
||||||
|
};
|
||||||
137
web-server/src/mock-data.js
Normal file
137
web-server/src/mock-data.js
Normal file
@@ -0,0 +1,137 @@
|
|||||||
|
const packages = [
|
||||||
|
{
|
||||||
|
id: 'navigation-stack',
|
||||||
|
code: 'NAV-STACK',
|
||||||
|
name: 'Navigation Stack',
|
||||||
|
type: 'deb',
|
||||||
|
latestVersion: '2.4.1',
|
||||||
|
latestReleaseDate: '2026-05-17',
|
||||||
|
status: 'Active',
|
||||||
|
owner: 'Dũng Tào',
|
||||||
|
description: 'Core navigation package for robot route planning and localization.',
|
||||||
|
artifact: '/packages/navigation-stack_2.4.1_amd64.deb',
|
||||||
|
versions: [
|
||||||
|
{ version: '2.4.1', releaseDate: '2026-05-17', uploadedBy: 'Dũng Tào', status: 'Latest', size: '84.2 MB', changeLog: 'Improve recovery flow and map alignment.' },
|
||||||
|
{ version: '2.4.0', releaseDate: '2026-05-10', uploadedBy: 'Dũng Tào', status: 'Stable', size: '83.8 MB', changeLog: 'Add obstacle avoidance tuning profile.' },
|
||||||
|
{ version: '2.3.8', releaseDate: '2026-04-28', uploadedBy: 'QA Robot', status: 'Deprecated', size: '81.6 MB', changeLog: 'Legacy build kept for rollback.' }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'fleet-agent',
|
||||||
|
code: 'FLEET-AGENT',
|
||||||
|
name: 'Fleet Agent',
|
||||||
|
type: 'docker',
|
||||||
|
latestVersion: '1.9.0',
|
||||||
|
latestReleaseDate: '2026-05-16',
|
||||||
|
status: 'Active',
|
||||||
|
owner: 'Minh Anh',
|
||||||
|
description: 'Docker service that connects robot clients to Fleet Manager.',
|
||||||
|
artifact: 'registry.local/robot/fleet-agent:1.9.0',
|
||||||
|
versions: [
|
||||||
|
{ version: '1.9.0', releaseDate: '2026-05-16', uploadedBy: 'Minh Anh', status: 'Latest', size: '412 MB', changeLog: 'Add heartbeat metrics and websocket retry.' },
|
||||||
|
{ version: '1.8.2', releaseDate: '2026-05-01', uploadedBy: 'Minh Anh', status: 'Stable', size: '405 MB', changeLog: 'Fix token renewal after sleep.' }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'map-sync',
|
||||||
|
code: 'MAP-SYNC',
|
||||||
|
name: 'Map Sync Service',
|
||||||
|
type: 'docker',
|
||||||
|
latestVersion: '3.1.2',
|
||||||
|
latestReleaseDate: '2026-05-12',
|
||||||
|
status: 'Active',
|
||||||
|
owner: 'Hải Nam',
|
||||||
|
description: 'Synchronizes robot map revisions between web server and edge clients.',
|
||||||
|
artifact: 'registry.local/robot/map-sync:3.1.2',
|
||||||
|
versions: [
|
||||||
|
{ version: '3.1.2', releaseDate: '2026-05-12', uploadedBy: 'Hải Nam', status: 'Latest', size: '268 MB', changeLog: 'Compress map snapshot before upload.' },
|
||||||
|
{ version: '3.0.5', releaseDate: '2026-04-22', uploadedBy: 'Hải Nam', status: 'Stable', size: '251 MB', changeLog: 'Improve checksum validation.' }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'ui-kiosk',
|
||||||
|
code: 'UI-KIOSK',
|
||||||
|
name: 'Robot Kiosk UI',
|
||||||
|
type: 'deb',
|
||||||
|
latestVersion: '0.8.6',
|
||||||
|
latestReleaseDate: '2026-05-08',
|
||||||
|
status: 'Testing',
|
||||||
|
owner: 'Linh Phạm',
|
||||||
|
description: 'Touch-screen UI package for robot kiosk mode.',
|
||||||
|
artifact: '/packages/robot-kiosk-ui_0.8.6_amd64.deb',
|
||||||
|
versions: [
|
||||||
|
{ version: '0.8.6', releaseDate: '2026-05-08', uploadedBy: 'Linh Phạm', status: 'Latest', size: '62.4 MB', changeLog: 'Refine operator handoff screens.' },
|
||||||
|
{ version: '0.8.3', releaseDate: '2026-04-19', uploadedBy: 'Linh Phạm', status: 'Deprecated', size: '59.9 MB', changeLog: 'Initial kiosk dashboard.' }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
];
|
||||||
|
|
||||||
|
const applications = [
|
||||||
|
{
|
||||||
|
id: 'warehouse-basic',
|
||||||
|
code: 'APP-WH-BASIC',
|
||||||
|
name: 'Warehouse Basic',
|
||||||
|
version: '1.2.0',
|
||||||
|
status: 'Released',
|
||||||
|
createdAt: '2026-05-18',
|
||||||
|
createdBy: 'Dũng Tào',
|
||||||
|
notes: 'Base package set for warehouse robots.',
|
||||||
|
packages: [
|
||||||
|
{ code: 'NAV-STACK', name: 'Navigation Stack', type: 'deb', selectedVersion: '2.4.1' },
|
||||||
|
{ code: 'FLEET-AGENT', name: 'Fleet Agent', type: 'docker', selectedVersion: '1.9.0' },
|
||||||
|
{ code: 'MAP-SYNC', name: 'Map Sync Service', type: 'docker', selectedVersion: '3.1.2' }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'kiosk-demo',
|
||||||
|
code: 'APP-KIOSK-DEMO',
|
||||||
|
name: 'Kiosk Demo',
|
||||||
|
version: '0.4.0',
|
||||||
|
status: 'Draft',
|
||||||
|
createdAt: '2026-05-16',
|
||||||
|
createdBy: 'Linh Phạm',
|
||||||
|
notes: 'Demo bundle for touch kiosk testing.',
|
||||||
|
packages: [
|
||||||
|
{ code: 'UI-KIOSK', name: 'Robot Kiosk UI', type: 'deb', selectedVersion: '0.8.6' },
|
||||||
|
{ code: 'NAV-STACK', name: 'Navigation Stack', type: 'deb', selectedVersion: '2.4.0' }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'fleet-edge',
|
||||||
|
code: 'APP-FLEET-EDGE',
|
||||||
|
name: 'Fleet Edge',
|
||||||
|
version: '2.0.1',
|
||||||
|
status: 'Released',
|
||||||
|
createdAt: '2026-05-11',
|
||||||
|
createdBy: 'Minh Anh',
|
||||||
|
notes: 'Fleet manager edge runtime.',
|
||||||
|
packages: [
|
||||||
|
{ code: 'FLEET-AGENT', name: 'Fleet Agent', type: 'docker', selectedVersion: '1.9.0' },
|
||||||
|
{ code: 'MAP-SYNC', name: 'Map Sync Service', type: 'docker', selectedVersion: '3.0.5' }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
];
|
||||||
|
|
||||||
|
const activity = [
|
||||||
|
{ title: 'Upload version 2.4.1', detail: 'Navigation Stack được đặt là latest', time: '09:25', icon: 'upload_file' },
|
||||||
|
{ title: 'Release Warehouse Basic', detail: 'App version 1.2.0 đã sẵn sàng đóng gói', time: 'Hôm qua', icon: 'task_alt' },
|
||||||
|
{ title: 'Update Fleet Agent', detail: 'Thêm heartbeat metrics cho Docker image', time: '16/05', icon: 'sync' }
|
||||||
|
];
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
currentUser: {
|
||||||
|
name: 'Dũng Tào',
|
||||||
|
role: 'Admin',
|
||||||
|
email: 'admin@robotics.local'
|
||||||
|
},
|
||||||
|
packages,
|
||||||
|
applications,
|
||||||
|
activity,
|
||||||
|
stats: {
|
||||||
|
totalPackages: packages.length,
|
||||||
|
activePackages: packages.filter((item) => item.status === 'Active').length,
|
||||||
|
totalVersions: packages.reduce((total, item) => total + item.versions.length, 0),
|
||||||
|
totalApplications: applications.length,
|
||||||
|
releasedApplications: applications.filter((item) => item.status === 'Released').length
|
||||||
|
}
|
||||||
|
};
|
||||||
458
web-server/src/notification-repository.js
Normal file
458
web-server/src/notification-repository.js
Normal file
@@ -0,0 +1,458 @@
|
|||||||
|
const crypto = require('crypto');
|
||||||
|
const { sql, getPool } = require('./db');
|
||||||
|
|
||||||
|
const SCHEMA_CHECK_TTL_MS = 30 * 1000;
|
||||||
|
const ALLOWED_SEVERITIES = new Set(['info', 'success', 'warning', 'error']);
|
||||||
|
let notificationSchemaState = {
|
||||||
|
available: false,
|
||||||
|
checkedAt: 0
|
||||||
|
};
|
||||||
|
|
||||||
|
function normalizeSeverity(value) {
|
||||||
|
const severity = String(value || '').trim().toLowerCase();
|
||||||
|
return ALLOWED_SEVERITIES.has(severity) ? severity : 'info';
|
||||||
|
}
|
||||||
|
|
||||||
|
function toIsoString(value) {
|
||||||
|
if (!value) return null;
|
||||||
|
const date = value instanceof Date ? value : new Date(value);
|
||||||
|
return Number.isNaN(date.getTime()) ? null : date.toISOString();
|
||||||
|
}
|
||||||
|
|
||||||
|
function mapNotificationRow(row) {
|
||||||
|
return {
|
||||||
|
id: String(row.Id),
|
||||||
|
eventType: row.EventType,
|
||||||
|
isSystem: row.EventType === 'system.announcement',
|
||||||
|
severity: normalizeSeverity(row.Severity),
|
||||||
|
title: row.Title,
|
||||||
|
message: row.Message,
|
||||||
|
entityType: row.EntityType || '',
|
||||||
|
entityId: row.EntityId || '',
|
||||||
|
actionUrl: row.ActionUrl || '',
|
||||||
|
actorName: row.ActorName || '',
|
||||||
|
isRead: Boolean(row.ReadAt),
|
||||||
|
readAt: toIsoString(row.ReadAt),
|
||||||
|
createdAt: toIsoString(row.CreatedAt)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function checkNotificationSchema(force = false) {
|
||||||
|
const now = Date.now();
|
||||||
|
if (!force && now - notificationSchemaState.checkedAt < SCHEMA_CHECK_TTL_MS) {
|
||||||
|
return notificationSchemaState.available;
|
||||||
|
}
|
||||||
|
|
||||||
|
const pool = await getPool();
|
||||||
|
const result = await pool.request().query(`
|
||||||
|
SELECT CASE WHEN OBJECT_ID(N'dbo.Notifications', N'U') IS NULL THEN 0 ELSE 1 END AS IsAvailable;
|
||||||
|
`);
|
||||||
|
|
||||||
|
notificationSchemaState = {
|
||||||
|
available: Boolean(result.recordset[0] && result.recordset[0].IsAvailable),
|
||||||
|
checkedAt: now
|
||||||
|
};
|
||||||
|
return notificationSchemaState.available;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function listNotifications(userId, options = {}) {
|
||||||
|
const available = await checkNotificationSchema();
|
||||||
|
if (!available) {
|
||||||
|
return {
|
||||||
|
available: false,
|
||||||
|
notifications: [],
|
||||||
|
unreadCount: 0
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const limit = Math.min(Math.max(Math.trunc(Number(options.limit)) || 20, 1), 50);
|
||||||
|
const unreadOnly = Boolean(options.unreadOnly);
|
||||||
|
const pool = await getPool();
|
||||||
|
const result = await pool.request()
|
||||||
|
.input('RecipientUserId', sql.UniqueIdentifier, userId)
|
||||||
|
.input('Limit', sql.Int, limit)
|
||||||
|
.input('UnreadOnly', sql.Bit, unreadOnly ? 1 : 0)
|
||||||
|
.query(`
|
||||||
|
SELECT COUNT_BIG(*) AS UnreadCount
|
||||||
|
FROM dbo.Notifications
|
||||||
|
WHERE RecipientUserId = @RecipientUserId
|
||||||
|
AND ReadAt IS NULL
|
||||||
|
AND (ExpiresAt IS NULL OR ExpiresAt > SYSUTCDATETIME());
|
||||||
|
|
||||||
|
SELECT TOP (@Limit)
|
||||||
|
Id, EventType, Severity, Title, Message, EntityType, EntityId,
|
||||||
|
ActionUrl, ActorName, ReadAt, CreatedAt
|
||||||
|
FROM dbo.Notifications
|
||||||
|
WHERE RecipientUserId = @RecipientUserId
|
||||||
|
AND (@UnreadOnly = 0 OR ReadAt IS NULL)
|
||||||
|
AND (ExpiresAt IS NULL OR ExpiresAt > SYSUTCDATETIME())
|
||||||
|
ORDER BY CreatedAt DESC, Id DESC;
|
||||||
|
`);
|
||||||
|
|
||||||
|
return {
|
||||||
|
available: true,
|
||||||
|
unreadCount: Number(result.recordsets[0][0].UnreadCount || 0),
|
||||||
|
notifications: result.recordsets[1].map(mapNotificationRow)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getUnreadCount(userId) {
|
||||||
|
const available = await checkNotificationSchema();
|
||||||
|
if (!available) {
|
||||||
|
return { available: false, unreadCount: 0 };
|
||||||
|
}
|
||||||
|
|
||||||
|
const pool = await getPool();
|
||||||
|
const result = await pool.request()
|
||||||
|
.input('RecipientUserId', sql.UniqueIdentifier, userId)
|
||||||
|
.query(`
|
||||||
|
SELECT COUNT_BIG(*) AS UnreadCount
|
||||||
|
FROM dbo.Notifications
|
||||||
|
WHERE RecipientUserId = @RecipientUserId
|
||||||
|
AND ReadAt IS NULL
|
||||||
|
AND (ExpiresAt IS NULL OR ExpiresAt > SYSUTCDATETIME());
|
||||||
|
`);
|
||||||
|
|
||||||
|
return {
|
||||||
|
available: true,
|
||||||
|
unreadCount: Number(result.recordset[0].UnreadCount || 0)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function markNotificationRead(notificationId, userId) {
|
||||||
|
if (!await checkNotificationSchema()) {
|
||||||
|
return { available: false, updated: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
const pool = await getPool();
|
||||||
|
const result = await pool.request()
|
||||||
|
.input('Id', sql.UniqueIdentifier, notificationId)
|
||||||
|
.input('RecipientUserId', sql.UniqueIdentifier, userId)
|
||||||
|
.query(`
|
||||||
|
UPDATE dbo.Notifications
|
||||||
|
SET ReadAt = COALESCE(ReadAt, SYSUTCDATETIME())
|
||||||
|
OUTPUT inserted.Id
|
||||||
|
WHERE Id = @Id
|
||||||
|
AND RecipientUserId = @RecipientUserId;
|
||||||
|
`);
|
||||||
|
|
||||||
|
return {
|
||||||
|
available: true,
|
||||||
|
updated: result.recordset.length > 0
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function markAllNotificationsRead(userId) {
|
||||||
|
if (!await checkNotificationSchema()) {
|
||||||
|
return { available: false, updatedCount: 0 };
|
||||||
|
}
|
||||||
|
|
||||||
|
const pool = await getPool();
|
||||||
|
const result = await pool.request()
|
||||||
|
.input('RecipientUserId', sql.UniqueIdentifier, userId)
|
||||||
|
.query(`
|
||||||
|
UPDATE dbo.Notifications
|
||||||
|
SET ReadAt = SYSUTCDATETIME()
|
||||||
|
OUTPUT inserted.Id
|
||||||
|
WHERE RecipientUserId = @RecipientUserId
|
||||||
|
AND ReadAt IS NULL
|
||||||
|
AND (ExpiresAt IS NULL OR ExpiresAt > SYSUTCDATETIME());
|
||||||
|
`);
|
||||||
|
|
||||||
|
return {
|
||||||
|
available: true,
|
||||||
|
updatedCount: result.recordset.length
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function createSystemBroadcast(input) {
|
||||||
|
if (!await checkNotificationSchema()) {
|
||||||
|
return { available: false, broadcastId: null, recipientCount: 0 };
|
||||||
|
}
|
||||||
|
|
||||||
|
const pool = await getPool();
|
||||||
|
const broadcastId = crypto.randomUUID();
|
||||||
|
const result = await pool.request()
|
||||||
|
.input('ActorUserId', sql.UniqueIdentifier, input.actorUserId)
|
||||||
|
.input('ActorName', sql.NVarChar(200), input.actorName || null)
|
||||||
|
.input('BroadcastId', sql.UniqueIdentifier, broadcastId)
|
||||||
|
.input('Severity', sql.NVarChar(20), normalizeSeverity(input.severity))
|
||||||
|
.input('Title', sql.NVarChar(200), input.title)
|
||||||
|
.input('Message', sql.NVarChar(1000), input.message)
|
||||||
|
.input('ActionUrl', sql.NVarChar(1000), input.actionUrl || null)
|
||||||
|
.query(`
|
||||||
|
INSERT dbo.Notifications (
|
||||||
|
RecipientUserId, ActorUserId, ActorName, BroadcastId, EventType,
|
||||||
|
Severity, Title, Message, EntityType, ActionUrl
|
||||||
|
)
|
||||||
|
SELECT
|
||||||
|
u.Id, @ActorUserId, @ActorName, @BroadcastId, N'system.announcement',
|
||||||
|
@Severity, @Title, @Message, N'system', @ActionUrl
|
||||||
|
FROM dbo.Users AS u
|
||||||
|
WHERE u.IsActive = 1;
|
||||||
|
|
||||||
|
DECLARE @RecipientCount INT = @@ROWCOUNT;
|
||||||
|
SELECT @RecipientCount AS RecipientCount;
|
||||||
|
`);
|
||||||
|
|
||||||
|
return {
|
||||||
|
available: true,
|
||||||
|
broadcastId,
|
||||||
|
recipientCount: Number(result.recordset[0].RecipientCount || 0)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function createNotificationsForUsers(input) {
|
||||||
|
if (!await checkNotificationSchema()) {
|
||||||
|
return { available: false, recipientCount: 0 };
|
||||||
|
}
|
||||||
|
|
||||||
|
const uniqueRecipientIds = Array.from(new Set((input.recipientUserIds || []).filter(Boolean))).slice(0, 1000);
|
||||||
|
if (uniqueRecipientIds.length === 0) {
|
||||||
|
return { available: true, recipientCount: 0 };
|
||||||
|
}
|
||||||
|
|
||||||
|
const pool = await getPool();
|
||||||
|
const request = pool.request()
|
||||||
|
.input('ActorUserId', sql.UniqueIdentifier, input.actorUserId || null)
|
||||||
|
.input('ActorName', sql.NVarChar(200), input.actorName || null)
|
||||||
|
.input('EventType', sql.NVarChar(100), input.eventType)
|
||||||
|
.input('Severity', sql.NVarChar(20), normalizeSeverity(input.severity))
|
||||||
|
.input('Title', sql.NVarChar(200), input.title)
|
||||||
|
.input('Message', sql.NVarChar(1000), input.message)
|
||||||
|
.input('EntityType', sql.NVarChar(50), input.entityType || null)
|
||||||
|
.input('EntityId', sql.NVarChar(100), input.entityId || null)
|
||||||
|
.input('ActionUrl', sql.NVarChar(1000), input.actionUrl || null);
|
||||||
|
const recipientRows = uniqueRecipientIds.map((userId, index) => {
|
||||||
|
const parameterName = `RecipientUserId${index}`;
|
||||||
|
request.input(parameterName, sql.UniqueIdentifier, userId);
|
||||||
|
return `SELECT @${parameterName} AS Id`;
|
||||||
|
}).join('\nUNION ALL\n');
|
||||||
|
|
||||||
|
const result = await request.query(`
|
||||||
|
WITH RequestedRecipients AS (
|
||||||
|
${recipientRows}
|
||||||
|
)
|
||||||
|
INSERT dbo.Notifications (
|
||||||
|
RecipientUserId, ActorUserId, ActorName, EventType, Severity,
|
||||||
|
Title, Message, EntityType, EntityId, ActionUrl
|
||||||
|
)
|
||||||
|
SELECT DISTINCT
|
||||||
|
u.Id, @ActorUserId, @ActorName, @EventType, @Severity,
|
||||||
|
@Title, @Message, @EntityType, @EntityId, @ActionUrl
|
||||||
|
FROM dbo.Users AS u
|
||||||
|
INNER JOIN RequestedRecipients AS requested ON requested.Id = u.Id
|
||||||
|
WHERE u.IsActive = 1
|
||||||
|
AND (@ActorUserId IS NULL OR u.Id <> @ActorUserId);
|
||||||
|
|
||||||
|
DECLARE @RecipientCount INT = @@ROWCOUNT;
|
||||||
|
SELECT @RecipientCount AS RecipientCount;
|
||||||
|
`);
|
||||||
|
|
||||||
|
return {
|
||||||
|
available: true,
|
||||||
|
recipientCount: Number(result.recordset[0].RecipientCount || 0)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getPackageVersionAudience(packageId) {
|
||||||
|
if (!await checkNotificationSchema()) return [];
|
||||||
|
|
||||||
|
const pool = await getPool();
|
||||||
|
const result = await pool.request()
|
||||||
|
.input('PackageId', sql.UniqueIdentifier, packageId)
|
||||||
|
.query(`
|
||||||
|
SELECT DISTINCT a.CreatedByUserId AS UserId
|
||||||
|
FROM dbo.ApplicationPackages AS ap
|
||||||
|
INNER JOIN dbo.Applications AS a ON a.Id = ap.ApplicationId
|
||||||
|
WHERE ap.PackageId = @PackageId;
|
||||||
|
`);
|
||||||
|
|
||||||
|
return result.recordset.map((row) => String(row.UserId));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function notifyPackageVersionAvailable(input) {
|
||||||
|
if (!await checkNotificationSchema()) {
|
||||||
|
return { available: false, recipientCount: 0 };
|
||||||
|
}
|
||||||
|
|
||||||
|
const pool = await getPool();
|
||||||
|
const packageResult = await pool.request()
|
||||||
|
.input('PackageId', sql.UniqueIdentifier, input.packageId)
|
||||||
|
.query(`
|
||||||
|
SELECT TOP (1) Id, PackageCode, PackageName
|
||||||
|
FROM dbo.Packages
|
||||||
|
WHERE Id = @PackageId;
|
||||||
|
`);
|
||||||
|
const packageRow = packageResult.recordset[0];
|
||||||
|
if (!packageRow) {
|
||||||
|
return { available: true, recipientCount: 0 };
|
||||||
|
}
|
||||||
|
|
||||||
|
const recipientUserIds = await getPackageVersionAudience(input.packageId);
|
||||||
|
const isArtifactUpdate = Boolean(input.isArtifactUpdate);
|
||||||
|
return createNotificationsForUsers({
|
||||||
|
recipientUserIds,
|
||||||
|
actorUserId: input.actorUserId,
|
||||||
|
actorName: input.actorName,
|
||||||
|
eventType: isArtifactUpdate ? 'package.version_artifact_updated' : 'package.version_available',
|
||||||
|
severity: 'info',
|
||||||
|
title: isArtifactUpdate
|
||||||
|
? `Artifact ${packageRow.PackageCode} ${input.version} đã được cập nhật`
|
||||||
|
: `Package ${packageRow.PackageCode} có version ${input.version} mới`,
|
||||||
|
message: isArtifactUpdate
|
||||||
|
? 'Artifact của version hiện tại đã được upload lại. Hãy kiểm tra trước khi triển khai tiếp.'
|
||||||
|
: 'Application của bạn đang sử dụng package này. Hãy kiểm tra và chọn version mới khi phù hợp.',
|
||||||
|
entityType: 'package',
|
||||||
|
entityId: String(packageRow.Id),
|
||||||
|
actionUrl: `/packages/${packageRow.Id}`
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getPackageDeletionContext(packageId) {
|
||||||
|
if (!await checkNotificationSchema()) return null;
|
||||||
|
|
||||||
|
const pool = await getPool();
|
||||||
|
const result = await pool.request()
|
||||||
|
.input('PackageId', sql.UniqueIdentifier, packageId)
|
||||||
|
.query(`
|
||||||
|
SELECT TOP (1) Id, PackageCode, PackageName, CreatedByUserId
|
||||||
|
FROM dbo.Packages
|
||||||
|
WHERE Id = @PackageId;
|
||||||
|
|
||||||
|
SELECT DISTINCT recipients.UserId
|
||||||
|
FROM (
|
||||||
|
SELECT a.CreatedByUserId AS UserId
|
||||||
|
FROM dbo.ApplicationPackages AS ap
|
||||||
|
INNER JOIN dbo.Applications AS a ON a.Id = ap.ApplicationId
|
||||||
|
WHERE ap.PackageId = @PackageId
|
||||||
|
UNION
|
||||||
|
SELECT CreatedByUserId FROM dbo.Packages WHERE Id = @PackageId
|
||||||
|
UNION
|
||||||
|
SELECT Id FROM dbo.Users WHERE Role = N'Admin'
|
||||||
|
) AS recipients;
|
||||||
|
`);
|
||||||
|
const packageRow = result.recordsets[0][0];
|
||||||
|
if (!packageRow) return null;
|
||||||
|
|
||||||
|
return {
|
||||||
|
packageId: String(packageRow.Id),
|
||||||
|
packageCode: packageRow.PackageCode,
|
||||||
|
packageName: packageRow.PackageName,
|
||||||
|
recipientUserIds: result.recordsets[1].map((row) => String(row.UserId))
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getPackageVersionDeletionContext(packageVersionId) {
|
||||||
|
if (!await checkNotificationSchema()) return null;
|
||||||
|
|
||||||
|
const pool = await getPool();
|
||||||
|
const result = await pool.request()
|
||||||
|
.input('PackageVersionId', sql.UniqueIdentifier, packageVersionId)
|
||||||
|
.query(`
|
||||||
|
SELECT TOP (1)
|
||||||
|
pv.Id, pv.PackageId, pv.Version, p.PackageCode, p.PackageName, p.CreatedByUserId
|
||||||
|
FROM dbo.PackageVersions AS pv
|
||||||
|
INNER JOIN dbo.Packages AS p ON p.Id = pv.PackageId
|
||||||
|
WHERE pv.Id = @PackageVersionId;
|
||||||
|
|
||||||
|
SELECT DISTINCT recipients.UserId
|
||||||
|
FROM (
|
||||||
|
SELECT a.CreatedByUserId AS UserId
|
||||||
|
FROM dbo.ApplicationPackages AS ap
|
||||||
|
INNER JOIN dbo.Applications AS a ON a.Id = ap.ApplicationId
|
||||||
|
WHERE ap.SelectedVersionId = @PackageVersionId
|
||||||
|
UNION
|
||||||
|
SELECT p.CreatedByUserId
|
||||||
|
FROM dbo.PackageVersions AS pv
|
||||||
|
INNER JOIN dbo.Packages AS p ON p.Id = pv.PackageId
|
||||||
|
WHERE pv.Id = @PackageVersionId
|
||||||
|
UNION
|
||||||
|
SELECT Id FROM dbo.Users WHERE Role = N'Admin'
|
||||||
|
) AS recipients;
|
||||||
|
`);
|
||||||
|
const versionRow = result.recordsets[0][0];
|
||||||
|
if (!versionRow) return null;
|
||||||
|
|
||||||
|
return {
|
||||||
|
packageVersionId: String(versionRow.Id),
|
||||||
|
packageId: String(versionRow.PackageId),
|
||||||
|
packageCode: versionRow.PackageCode,
|
||||||
|
packageName: versionRow.PackageName,
|
||||||
|
version: versionRow.Version,
|
||||||
|
recipientUserIds: result.recordsets[1].map((row) => String(row.UserId))
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getApplicationReleaseContext(applicationId) {
|
||||||
|
if (!await checkNotificationSchema()) return null;
|
||||||
|
|
||||||
|
const pool = await getPool();
|
||||||
|
const result = await pool.request()
|
||||||
|
.input('ApplicationId', sql.UniqueIdentifier, applicationId)
|
||||||
|
.query(`
|
||||||
|
SELECT TOP (1) Id, AppCode, AppName, AppVersion, CreatedByUserId
|
||||||
|
FROM dbo.Applications
|
||||||
|
WHERE Id = @ApplicationId;
|
||||||
|
|
||||||
|
SELECT DISTINCT recipients.UserId
|
||||||
|
FROM (
|
||||||
|
SELECT CreatedByUserId AS UserId
|
||||||
|
FROM dbo.Applications
|
||||||
|
WHERE Id = @ApplicationId
|
||||||
|
UNION
|
||||||
|
SELECT Id FROM dbo.Users WHERE Role = N'Admin'
|
||||||
|
) AS recipients;
|
||||||
|
`);
|
||||||
|
const applicationRow = result.recordsets[0][0];
|
||||||
|
if (!applicationRow) return null;
|
||||||
|
|
||||||
|
return {
|
||||||
|
applicationId: String(applicationRow.Id),
|
||||||
|
appCode: applicationRow.AppCode,
|
||||||
|
appName: applicationRow.AppName,
|
||||||
|
appVersion: applicationRow.AppVersion,
|
||||||
|
recipientUserIds: result.recordsets[1].map((row) => String(row.UserId))
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function notifyApplicationReleased(input) {
|
||||||
|
const context = await getApplicationReleaseContext(input.applicationId);
|
||||||
|
if (!context) {
|
||||||
|
return {
|
||||||
|
available: await checkNotificationSchema(),
|
||||||
|
recipientCount: 0
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return createNotificationsForUsers({
|
||||||
|
recipientUserIds: context.recipientUserIds,
|
||||||
|
actorUserId: input.actorUserId,
|
||||||
|
actorName: input.actorName,
|
||||||
|
eventType: 'application.released',
|
||||||
|
severity: 'success',
|
||||||
|
title: `Application ${context.appCode} đã được release`,
|
||||||
|
message: `Version ${context.appVersion} đã chuyển sang trạng thái Released.`,
|
||||||
|
entityType: 'application',
|
||||||
|
entityId: context.applicationId,
|
||||||
|
actionUrl: `/applications/${context.applicationId}`
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
checkNotificationSchema,
|
||||||
|
createNotificationsForUsers,
|
||||||
|
createSystemBroadcast,
|
||||||
|
getApplicationReleaseContext,
|
||||||
|
getPackageImpact: getPackageDeletionContext,
|
||||||
|
getPackageDeletionContext,
|
||||||
|
getPackageVersionAudience,
|
||||||
|
getPackageVersionImpact: getPackageVersionDeletionContext,
|
||||||
|
getPackageVersionDeletionContext,
|
||||||
|
getUnreadCount,
|
||||||
|
listNotifications,
|
||||||
|
markAllNotificationsRead,
|
||||||
|
markNotificationRead: (userId, notificationId) => markNotificationRead(notificationId, userId),
|
||||||
|
notifyApplicationReleased,
|
||||||
|
notifyPackageVersionAvailable
|
||||||
|
};
|
||||||
1910
web-server/src/repository.js
Normal file
1910
web-server/src/repository.js
Normal file
File diff suppressed because it is too large
Load Diff
157
web-server/views/agent.ejs
Normal file
157
web-server/views/agent.ejs
Normal file
@@ -0,0 +1,157 @@
|
|||||||
|
<%- include('partials/page-start') %>
|
||||||
|
|
||||||
|
<section class="page">
|
||||||
|
<div class="page-header">
|
||||||
|
<div>
|
||||||
|
<h1>Agent</h1>
|
||||||
|
<p>Quản lý Local Installer Agent package dùng cho máy client Linux.</p>
|
||||||
|
</div>
|
||||||
|
<div class="page-actions">
|
||||||
|
<span class="badge badge-primary">Admin</span>
|
||||||
|
<span class="badge badge-info"><%= agentPackages.length %> packages</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="agent-layout">
|
||||||
|
<section class="panel">
|
||||||
|
<div class="panel-header">
|
||||||
|
<div>
|
||||||
|
<h2>Upload / Update</h2>
|
||||||
|
<% if (latestAgentPackage) { %>
|
||||||
|
<p>Latest <%= preferredArch %>: <strong><%= latestAgentPackage.version %></strong></p>
|
||||||
|
<% } else { %>
|
||||||
|
<p>Chưa có Agent package cho <%= preferredArch %>.</p>
|
||||||
|
<% } %>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<form class="agent-upload-form" method="post" action="/agent/packages" enctype="multipart/form-data">
|
||||||
|
<div class="form-grid">
|
||||||
|
<label class="form-field">
|
||||||
|
<span>Version</span>
|
||||||
|
<input type="text" name="version" placeholder="0.1.1" required>
|
||||||
|
</label>
|
||||||
|
<label class="form-field">
|
||||||
|
<span>Architecture</span>
|
||||||
|
<input type="text" name="arch" value="<%= preferredArch %>" required>
|
||||||
|
</label>
|
||||||
|
<div class="form-field full">
|
||||||
|
<span>Agent .deb</span>
|
||||||
|
<div class="file-dropzone" data-file-dropzone>
|
||||||
|
<input class="file-input" type="file" name="agentFile" accept=".deb" required data-file-input>
|
||||||
|
<div class="file-dropzone-content">
|
||||||
|
<span class="material-symbols-outlined">upload_file</span>
|
||||||
|
<strong>Chọn file Agent package</strong>
|
||||||
|
<small>Server sẽ lưu thành local-installer-agent_<version>_<arch>.deb</small>
|
||||||
|
<button class="btn btn-secondary" type="button" data-file-browse>
|
||||||
|
<span class="material-symbols-outlined">attach_file</span>
|
||||||
|
Chọn file
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div class="file-preview" data-file-preview hidden>
|
||||||
|
<span class="material-symbols-outlined">draft</span>
|
||||||
|
<div>
|
||||||
|
<strong data-file-name>Chưa chọn file</strong>
|
||||||
|
<small data-file-meta></small>
|
||||||
|
</div>
|
||||||
|
<button class="icon-button subtle" type="button" title="Bỏ file" aria-label="Bỏ file đã chọn" data-file-clear>
|
||||||
|
<span class="material-symbols-outlined">close</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="modal-actions">
|
||||||
|
<button class="btn btn-primary" type="submit">
|
||||||
|
<span class="material-symbols-outlined">upload</span>
|
||||||
|
Upload / Update
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<div class="agent-command-list">
|
||||||
|
<label class="form-field full">
|
||||||
|
<span>Install command</span>
|
||||||
|
<input class="mono" type="text" value="<%= installCommand %>" readonly>
|
||||||
|
</label>
|
||||||
|
<label class="form-field full">
|
||||||
|
<span>Latest package URL</span>
|
||||||
|
<input class="mono" type="text" value="<%= latestAgentUrl %>" readonly>
|
||||||
|
</label>
|
||||||
|
<label class="form-field full">
|
||||||
|
<span>Storage folder</span>
|
||||||
|
<input class="mono" type="text" value="<%= agentPackageDir %>" readonly>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="table-panel wide-panel">
|
||||||
|
<div class="page-filters inline">
|
||||||
|
<label class="filter-field wide">
|
||||||
|
<span>Search</span>
|
||||||
|
<input type="search" placeholder="Tìm theo version, arch, filename..." data-table-search="agentPackagesTable">
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table id="agentPackagesTable" class="data-table agent-table">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Version</th>
|
||||||
|
<th>Arch</th>
|
||||||
|
<th>File</th>
|
||||||
|
<th>Size</th>
|
||||||
|
<th>Uploaded</th>
|
||||||
|
<th>Status</th>
|
||||||
|
<th class="action-col">Actions</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<% if (agentPackages.length === 0) { %>
|
||||||
|
<tr>
|
||||||
|
<td colspan="7" class="table-empty">Chưa có Agent package nào.</td>
|
||||||
|
</tr>
|
||||||
|
<% } %>
|
||||||
|
<% agentPackages.forEach((item) => { %>
|
||||||
|
<tr data-search="<%= `${item.version} ${item.arch} ${item.fileName}`.toLowerCase() %>">
|
||||||
|
<td><strong><%= item.version %></strong></td>
|
||||||
|
<td><span class="badge badge-muted"><%= item.arch %></span></td>
|
||||||
|
<td>
|
||||||
|
<span class="table-title"><%= item.fileName %></span>
|
||||||
|
<span class="table-subtitle"><%= item.downloadPath %></span>
|
||||||
|
</td>
|
||||||
|
<td><%= item.sizeLabel %></td>
|
||||||
|
<td><%= item.uploadedAt %></td>
|
||||||
|
<td>
|
||||||
|
<% if (item.isLatestForArch) { %>
|
||||||
|
<span class="badge badge-success">Latest</span>
|
||||||
|
<% } else { %>
|
||||||
|
<span class="badge badge-muted">Stored</span>
|
||||||
|
<% } %>
|
||||||
|
</td>
|
||||||
|
<td class="action-col">
|
||||||
|
<div class="action-group">
|
||||||
|
<a class="icon-button subtle" href="<%= item.downloadPath %>" title="Download" aria-label="Download <%= item.fileName %>">
|
||||||
|
<span class="material-symbols-outlined">download</span>
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<% }) %>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
<div class="page-pager">
|
||||||
|
<span>Showing 1-<%= agentPackages.length %> of <%= agentPackages.length %></span>
|
||||||
|
<div>
|
||||||
|
<button type="button" disabled>Prev</button>
|
||||||
|
<span>Page 1 / 1</span>
|
||||||
|
<button type="button" disabled>Next</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<%- include('partials/page-end') %>
|
||||||
123
web-server/views/application-detail.ejs
Normal file
123
web-server/views/application-detail.ejs
Normal file
@@ -0,0 +1,123 @@
|
|||||||
|
<%- include('partials/page-start') %>
|
||||||
|
|
||||||
|
<section class="page">
|
||||||
|
<div class="page-header">
|
||||||
|
<div>
|
||||||
|
<div class="breadcrumb"><a href="/applications">Applications</a><span>/</span><span><%= application.code %></span></div>
|
||||||
|
<h1><%= application.name %></h1>
|
||||||
|
<p><%= application.notes %></p>
|
||||||
|
</div>
|
||||||
|
<div class="page-actions">
|
||||||
|
<button
|
||||||
|
class="btn btn-secondary"
|
||||||
|
type="button"
|
||||||
|
data-app-edit
|
||||||
|
data-app-id="<%= application.id %>"
|
||||||
|
data-app-code="<%= application.code %>"
|
||||||
|
data-app-name="<%= application.name %>"
|
||||||
|
data-app-version="<%= application.version %>"
|
||||||
|
data-app-status="<%= application.status %>"
|
||||||
|
data-app-open-url="<%= application.openUrl %>"
|
||||||
|
data-app-notes="<%= application.notes %>"
|
||||||
|
data-app-packages="<%= JSON.stringify(application.packages.map((pkg) => ({ packageId: pkg.packageId, selectedVersionId: pkg.selectedVersionId }))) %>"
|
||||||
|
>
|
||||||
|
<span class="material-symbols-outlined">edit</span>
|
||||||
|
Sửa App
|
||||||
|
</button>
|
||||||
|
<form method="post" action="/applications/<%= application.id %>/release" data-confirm-submit="Chuyển app <%= application.code %> sang Released?">
|
||||||
|
<input type="hidden" name="returnTo" value="<%= currentPath %>">
|
||||||
|
<button class="btn btn-primary" type="submit" <%= application.status === 'Released' ? 'disabled' : '' %>>
|
||||||
|
<span class="material-symbols-outlined">archive</span>
|
||||||
|
Đóng gói
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
<form method="post" action="/applications/<%= application.id %>/delete" data-confirm-submit="Xóa app <%= application.code %> khỏi hệ thống?">
|
||||||
|
<button class="btn btn-danger" type="submit">
|
||||||
|
<span class="material-symbols-outlined">delete</span>
|
||||||
|
Xóa
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="detail-grid">
|
||||||
|
<section class="panel">
|
||||||
|
<div class="panel-header">
|
||||||
|
<div>
|
||||||
|
<h2>Thông tin App</h2>
|
||||||
|
<p>Thông tin dùng ở danh sách và pipeline đóng gói.</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<dl class="detail-list">
|
||||||
|
<div><dt>Code</dt><dd><%= application.code %></dd></div>
|
||||||
|
<div><dt>Version</dt><dd><strong><%= application.version %></strong></dd></div>
|
||||||
|
<div><dt>Package count</dt><dd><%= application.packageCount %></dd></div>
|
||||||
|
<div><dt>Created date</dt><dd><%= application.createdAt %></dd></div>
|
||||||
|
<div><dt>Created by</dt><dd><%= application.createdBy %></dd></div>
|
||||||
|
<div><dt>Open URL</dt><dd class="mono"><%= application.openUrl || '-' %></dd></div>
|
||||||
|
<div><dt>Status</dt><dd><span class="badge <%= helpers.statusClass(application.status) %>"><%= application.status %></span></dd></div>
|
||||||
|
</dl>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel wide-panel">
|
||||||
|
<div class="panel-header">
|
||||||
|
<div>
|
||||||
|
<h2>Package trong App</h2>
|
||||||
|
<p>Mỗi package có thể chọn version cụ thể cho app này.</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="table-wrap compact">
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Package</th>
|
||||||
|
<th>Type</th>
|
||||||
|
<th>Selected version</th>
|
||||||
|
<th class="action-col">Actions</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<% application.packages.forEach((pkg) => { %>
|
||||||
|
<tr>
|
||||||
|
<td>
|
||||||
|
<strong><%= pkg.name %></strong>
|
||||||
|
<span class="table-subtitle"><%= pkg.code %></span>
|
||||||
|
</td>
|
||||||
|
<td><span class="badge <%= helpers.packageTypeClass(pkg.type) %>"><%= helpers.packageTypeLabel(pkg.type) %></span></td>
|
||||||
|
<td><%= pkg.selectedVersion %></td>
|
||||||
|
<td class="action-col">
|
||||||
|
<div class="action-group">
|
||||||
|
<button
|
||||||
|
class="icon-button subtle"
|
||||||
|
type="button"
|
||||||
|
title="Đổi version"
|
||||||
|
data-app-edit
|
||||||
|
data-app-id="<%= application.id %>"
|
||||||
|
data-app-code="<%= application.code %>"
|
||||||
|
data-app-name="<%= application.name %>"
|
||||||
|
data-app-version="<%= application.version %>"
|
||||||
|
data-app-status="<%= application.status %>"
|
||||||
|
data-app-open-url="<%= application.openUrl %>"
|
||||||
|
data-app-notes="<%= application.notes %>"
|
||||||
|
data-app-packages="<%= JSON.stringify(application.packages.map((item) => ({ packageId: item.packageId, selectedVersionId: item.selectedVersionId }))) %>"
|
||||||
|
>
|
||||||
|
<span class="material-symbols-outlined">swap_horiz</span>
|
||||||
|
</button>
|
||||||
|
<form method="post" action="/applications/<%= application.id %>/packages/<%= pkg.packageId %>/delete" data-confirm-submit="Gỡ package <%= pkg.code %> khỏi app?">
|
||||||
|
<button class="icon-button danger" type="submit" title="Gỡ package" aria-label="Gỡ package <%= pkg.name %>">
|
||||||
|
<span class="material-symbols-outlined">link_off</span>
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<% }) %>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<%- include('partials/edit-app-modal') %>
|
||||||
|
<%- include('partials/page-end') %>
|
||||||
115
web-server/views/applications.ejs
Normal file
115
web-server/views/applications.ejs
Normal file
@@ -0,0 +1,115 @@
|
|||||||
|
<%- include('partials/page-start') %>
|
||||||
|
|
||||||
|
<section class="page">
|
||||||
|
<div class="page-header">
|
||||||
|
<div>
|
||||||
|
<h1>Applications</h1>
|
||||||
|
<p>Danh sách app được tạo từ các package đã chọn, kèm version và ghi chú đóng gói.</p>
|
||||||
|
</div>
|
||||||
|
<div class="page-actions">
|
||||||
|
<a class="btn btn-secondary" href="/applications/export.csv">
|
||||||
|
<span class="material-symbols-outlined">download</span>
|
||||||
|
Export
|
||||||
|
</a>
|
||||||
|
<a class="btn btn-primary" href="/builder">
|
||||||
|
<span class="material-symbols-outlined">add</span>
|
||||||
|
Tạo App
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="page-filters">
|
||||||
|
<label class="filter-field">
|
||||||
|
<span>Status</span>
|
||||||
|
<select data-filter-select data-filter-column="status" data-filter-table="applicationsTable">
|
||||||
|
<option value="">Tất cả</option>
|
||||||
|
<option value="Draft">Draft</option>
|
||||||
|
<option value="Released">Released</option>
|
||||||
|
<option value="Archived">Archived</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label class="filter-field wide">
|
||||||
|
<span>Search</span>
|
||||||
|
<input type="search" placeholder="Tìm theo tên app, code, người tạo..." data-table-search="applicationsTable">
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<section class="table-panel">
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table id="applicationsTable" class="data-table">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Application</th>
|
||||||
|
<th>Version</th>
|
||||||
|
<th>Packages</th>
|
||||||
|
<th>Created date</th>
|
||||||
|
<th>Created by</th>
|
||||||
|
<th>Status</th>
|
||||||
|
<th>Notes</th>
|
||||||
|
<th class="action-col">Actions</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<% if (applications.length === 0) { %>
|
||||||
|
<tr>
|
||||||
|
<td colspan="8" class="table-empty">Chưa có app trong database. Tạo app sau khi đã upload package.</td>
|
||||||
|
</tr>
|
||||||
|
<% } %>
|
||||||
|
<% applications.forEach((item) => { %>
|
||||||
|
<tr data-search="<%= `${item.name} ${item.code} ${item.version} ${item.createdBy} ${item.notes}`.toLowerCase() %>" data-status="<%= item.status %>">
|
||||||
|
<td>
|
||||||
|
<a class="table-title" href="/applications/<%= item.id %>"><%= item.name %></a>
|
||||||
|
<span class="table-subtitle"><%= item.code %></span>
|
||||||
|
</td>
|
||||||
|
<td><strong><%= item.version %></strong></td>
|
||||||
|
<td><%= item.packageCount %></td>
|
||||||
|
<td><%= item.createdAt %></td>
|
||||||
|
<td><%= item.createdBy %></td>
|
||||||
|
<td><span class="badge <%= helpers.statusClass(item.status) %>"><%= item.status %></span></td>
|
||||||
|
<td class="notes-cell"><%= item.notes %></td>
|
||||||
|
<td class="action-col">
|
||||||
|
<div class="action-group">
|
||||||
|
<a class="icon-button subtle" href="/applications/<%= item.id %>" title="Xem chi tiết" aria-label="Xem chi tiết <%= item.name %>">
|
||||||
|
<span class="material-symbols-outlined">visibility</span>
|
||||||
|
</a>
|
||||||
|
<button
|
||||||
|
class="icon-button subtle"
|
||||||
|
type="button"
|
||||||
|
title="Sửa app"
|
||||||
|
data-app-edit
|
||||||
|
data-app-id="<%= item.id %>"
|
||||||
|
data-app-code="<%= item.code %>"
|
||||||
|
data-app-name="<%= item.name %>"
|
||||||
|
data-app-version="<%= item.version %>"
|
||||||
|
data-app-status="<%= item.status %>"
|
||||||
|
data-app-open-url="<%= item.openUrl %>"
|
||||||
|
data-app-notes="<%= item.notes %>"
|
||||||
|
data-app-packages="<%= JSON.stringify(item.packages.map((pkg) => ({ packageId: pkg.packageId, selectedVersionId: pkg.selectedVersionId }))) %>"
|
||||||
|
>
|
||||||
|
<span class="material-symbols-outlined">edit</span>
|
||||||
|
</button>
|
||||||
|
<form method="post" action="/applications/<%= item.id %>/delete" data-confirm-submit="Xóa app <%= item.code %>? Thao tác này sẽ xóa thông tin đóng gói của app.">
|
||||||
|
<button class="icon-button danger" type="submit" title="Xóa app" aria-label="Xóa app <%= item.name %>">
|
||||||
|
<span class="material-symbols-outlined">delete</span>
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<% }) %>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
<div class="page-pager">
|
||||||
|
<span>Showing 1-<%= applications.length %> of <%= applications.length %></span>
|
||||||
|
<div>
|
||||||
|
<button type="button" disabled>Prev</button>
|
||||||
|
<span>Page 1 / 1</span>
|
||||||
|
<button type="button" disabled>Next</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<%- include('partials/edit-app-modal') %>
|
||||||
|
<%- include('partials/page-end') %>
|
||||||
95
web-server/views/auth.ejs
Normal file
95
web-server/views/auth.ejs
Normal file
@@ -0,0 +1,95 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="vi">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title><%= title %> | Robot Installer</title>
|
||||||
|
<link rel="stylesheet" href="/vendor/montserrat/index.css">
|
||||||
|
<link rel="stylesheet" href="/vendor/notiflix/notiflix-<%= notiflixVersion %>.min.css">
|
||||||
|
<link rel="stylesheet" href="/css/styles.css">
|
||||||
|
<link rel="icon" type="image/png" href="/image/logo_PNKX.png">
|
||||||
|
</head>
|
||||||
|
<body class="auth-shell" <% if (notice) { %>data-notice-type="<%= notice.type %>" data-notice="<%= notice.message %>"<% } %>>
|
||||||
|
<main class="auth-page">
|
||||||
|
<section class="auth-panel">
|
||||||
|
<div class="auth-brand">
|
||||||
|
<div class="brand-mark">
|
||||||
|
<img class="brand-logo" src="/image/logo_PNKX.png" alt="">
|
||||||
|
</div>
|
||||||
|
<div class="brand-copy">
|
||||||
|
<strong>Robot Installer</strong>
|
||||||
|
<span>User Access</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<% if (mode === 'login') { %>
|
||||||
|
<div class="auth-heading">
|
||||||
|
<h1>Đăng nhập</h1>
|
||||||
|
<p>Truy cập console quản lý package và app.</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<form class="auth-form" method="post" action="/login">
|
||||||
|
<input type="hidden" name="returnTo" value="<%= returnTo %>">
|
||||||
|
<label class="form-field">
|
||||||
|
<span>Username hoặc email</span>
|
||||||
|
<input type="text" name="identifier" autocomplete="username" required autofocus>
|
||||||
|
</label>
|
||||||
|
<label class="form-field">
|
||||||
|
<span>Mật khẩu</span>
|
||||||
|
<input type="password" name="password" autocomplete="current-password" required>
|
||||||
|
</label>
|
||||||
|
<button class="btn btn-primary auth-submit" type="submit">
|
||||||
|
<span class="material-symbols-outlined">login</span>
|
||||||
|
Đăng nhập
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<p class="auth-switch">Chưa có tài khoản? <a href="/register">Đăng ký</a></p>
|
||||||
|
<% } else { %>
|
||||||
|
<div class="auth-heading">
|
||||||
|
<h1>Đăng ký</h1>
|
||||||
|
<p>App sẽ gửi email xác nhận để kích hoạt tài khoản.</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<form class="auth-form" method="post" action="/register" data-register-form>
|
||||||
|
<div class="form-grid">
|
||||||
|
<label class="form-field">
|
||||||
|
<span>Username</span>
|
||||||
|
<input type="text" name="username" value="<%= values.username || '' %>" autocomplete="username" required autofocus data-unique-check="username">
|
||||||
|
<small class="field-feedback" data-unique-feedback="username"></small>
|
||||||
|
</label>
|
||||||
|
<label class="form-field">
|
||||||
|
<span>Họ tên</span>
|
||||||
|
<input type="text" name="fullName" value="<%= values.fullName || '' %>" autocomplete="name">
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<label class="form-field">
|
||||||
|
<span>Email</span>
|
||||||
|
<input type="email" name="email" value="<%= values.email || '' %>" autocomplete="email" required data-unique-check="email">
|
||||||
|
<small class="field-feedback" data-unique-feedback="email"></small>
|
||||||
|
</label>
|
||||||
|
<div class="form-grid">
|
||||||
|
<label class="form-field">
|
||||||
|
<span>Mật khẩu</span>
|
||||||
|
<input type="password" name="password" autocomplete="new-password" minlength="8" required>
|
||||||
|
</label>
|
||||||
|
<label class="form-field">
|
||||||
|
<span>Xác nhận mật khẩu</span>
|
||||||
|
<input type="password" name="confirmPassword" autocomplete="new-password" minlength="8" required>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<button class="btn btn-primary auth-submit" type="submit" data-register-submit>
|
||||||
|
<span class="material-symbols-outlined">person_add</span>
|
||||||
|
Tạo tài khoản
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<p class="auth-switch">Đã có tài khoản? <a href="/login">Đăng nhập</a></p>
|
||||||
|
<% } %>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<script src="/vendor/notiflix/notiflix-<%= notiflixVersion %>.min.js"></script>
|
||||||
|
<script src="/js/app.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
109
web-server/views/builder.ejs
Normal file
109
web-server/views/builder.ejs
Normal file
@@ -0,0 +1,109 @@
|
|||||||
|
<%- include('partials/page-start') %>
|
||||||
|
|
||||||
|
<section class="page">
|
||||||
|
<div class="page-header">
|
||||||
|
<div>
|
||||||
|
<h1>Đóng gói App</h1>
|
||||||
|
<p>Tạo app bằng cách chọn package `.deb` hoặc Docker và gán version cụ thể.</p>
|
||||||
|
</div>
|
||||||
|
<div class="page-actions">
|
||||||
|
<button class="btn btn-secondary" type="submit" form="builderForm" name="status" value="Draft">
|
||||||
|
<span class="material-symbols-outlined">draft</span>
|
||||||
|
Lưu nháp
|
||||||
|
</button>
|
||||||
|
<button class="btn btn-primary" type="submit" form="builderForm">
|
||||||
|
<span class="material-symbols-outlined">save</span>
|
||||||
|
Tạo App
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="builder-layout">
|
||||||
|
<section class="panel">
|
||||||
|
<div class="panel-header">
|
||||||
|
<div>
|
||||||
|
<h2>Thông tin App</h2>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<form id="builderForm" class="form-stack" action="/applications" method="post">
|
||||||
|
<label class="form-field">
|
||||||
|
<span>App code</span>
|
||||||
|
<input type="text" name="appCode" pattern="[A-Za-z0-9._+-]+" title="Only letters, numbers, dot, underscore, plus and hyphen. No spaces." required>
|
||||||
|
</label>
|
||||||
|
<label class="form-field">
|
||||||
|
<span>App version</span>
|
||||||
|
<input type="text" name="appVersion" pattern="[A-Za-z0-9._:+~=-]+" title="Only letters, numbers and . _ : + ~ = - characters." required>
|
||||||
|
</label>
|
||||||
|
<label class="form-field full">
|
||||||
|
<span>App name</span>
|
||||||
|
<input type="text" name="appName" required>
|
||||||
|
</label>
|
||||||
|
<label class="form-field full">
|
||||||
|
<span>Open URL</span>
|
||||||
|
<input type="text" name="openUrl" placeholder="http://127.0.0.1:5000">
|
||||||
|
</label>
|
||||||
|
<label class="form-field full">
|
||||||
|
<span>Notes</span>
|
||||||
|
<textarea name="notes"></textarea>
|
||||||
|
</label>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="table-panel builder-table">
|
||||||
|
<div class="panel-header">
|
||||||
|
<div>
|
||||||
|
<h2>Chọn package</h2>
|
||||||
|
<p>Có thể dùng chung `.deb` và Docker trong một app.</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="page-filters inline">
|
||||||
|
<label class="filter-field wide">
|
||||||
|
<span>Search</span>
|
||||||
|
<input type="search" placeholder="Tìm package..." data-table-search="builderPackagesTable">
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table id="builderPackagesTable" class="data-table">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Use</th>
|
||||||
|
<th>Package</th>
|
||||||
|
<th>Type</th>
|
||||||
|
<th>Version</th>
|
||||||
|
<th>Status</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<% if (packages.length === 0) { %>
|
||||||
|
<tr>
|
||||||
|
<td colspan="5" class="table-empty">Chưa có package để đóng gói. Hãy upload package trước.</td>
|
||||||
|
</tr>
|
||||||
|
<% } %>
|
||||||
|
<% packages.forEach((item, index) => { %>
|
||||||
|
<tr data-search="<%= `${item.name} ${item.code} ${item.latestVersion}`.toLowerCase() %>">
|
||||||
|
<td>
|
||||||
|
<input class="checkbox" form="builderForm" type="checkbox" name="packageIds" value="<%= item.id %>" <%= index < 3 ? 'checked' : '' %> aria-label="Chọn <%= item.name %>">
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<strong><%= item.name %></strong>
|
||||||
|
<span class="table-subtitle"><%= item.code %></span>
|
||||||
|
</td>
|
||||||
|
<td><span class="badge <%= helpers.packageTypeClass(item.type) %>"><%= helpers.packageTypeLabel(item.type) %></span></td>
|
||||||
|
<td>
|
||||||
|
<select class="mini-select" form="builderForm" name="version_<%= item.id %>" aria-label="Version của <%= item.name %>">
|
||||||
|
<% item.versions.forEach((version) => { %>
|
||||||
|
<option value="<%= version.id %>"><%= version.version %></option>
|
||||||
|
<% }) %>
|
||||||
|
</select>
|
||||||
|
</td>
|
||||||
|
<td><span class="badge <%= helpers.statusClass(item.status) %>"><%= item.status %></span></td>
|
||||||
|
</tr>
|
||||||
|
<% }) %>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<%- include('partials/page-end') %>
|
||||||
52
web-server/views/confirm-email-sent.ejs
Normal file
52
web-server/views/confirm-email-sent.ejs
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="vi">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title><%= title %> | Robot Installer</title>
|
||||||
|
<link rel="stylesheet" href="/vendor/montserrat/index.css">
|
||||||
|
<link rel="stylesheet" href="/vendor/notiflix/notiflix-<%= notiflixVersion %>.min.css">
|
||||||
|
<link rel="stylesheet" href="/css/styles.css">
|
||||||
|
<link rel="icon" type="image/png" href="/image/logo_PNKX.png">
|
||||||
|
</head>
|
||||||
|
<body class="auth-shell" <% if (notice) { %>data-notice-type="<%= notice.type %>" data-notice="<%= notice.message %>"<% } %>>
|
||||||
|
<main class="auth-page">
|
||||||
|
<section class="auth-panel">
|
||||||
|
<div class="auth-brand">
|
||||||
|
<div class="brand-mark">
|
||||||
|
<img class="brand-logo" src="/image/logo_PNKX.png" alt="">
|
||||||
|
</div>
|
||||||
|
<div class="brand-copy">
|
||||||
|
<strong>Robot Installer</strong>
|
||||||
|
<span>Email Confirmation</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="auth-confirm-icon">
|
||||||
|
<span class="material-symbols-outlined">mark_email_unread</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="auth-heading">
|
||||||
|
<h1>Kiểm tra email</h1>
|
||||||
|
<p>Chúng tôi đã gửi link xác nhận tới email đăng ký. Tài khoản chỉ được kích hoạt sau khi bạn bấm link confirm.</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<form class="auth-form" method="post" action="/resend-confirmation">
|
||||||
|
<label class="form-field">
|
||||||
|
<span>Email đăng ký</span>
|
||||||
|
<input type="email" name="email" value="<%= email %>" autocomplete="email" required>
|
||||||
|
</label>
|
||||||
|
<button class="btn btn-secondary auth-submit" type="submit">
|
||||||
|
<span class="material-symbols-outlined">forward_to_inbox</span>
|
||||||
|
Gửi lại email xác nhận
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<p class="auth-switch">Đã xác nhận? <a href="/login">Đăng nhập</a></p>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<script src="/vendor/notiflix/notiflix-<%= notiflixVersion %>.min.js"></script>
|
||||||
|
<script src="/js/app.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
122
web-server/views/dashboard.ejs
Normal file
122
web-server/views/dashboard.ejs
Normal file
@@ -0,0 +1,122 @@
|
|||||||
|
<%- include('partials/page-start') %>
|
||||||
|
|
||||||
|
<section class="page">
|
||||||
|
<div class="page-header">
|
||||||
|
<div>
|
||||||
|
<h1>Tổng quan</h1>
|
||||||
|
<p>Theo dõi nhanh package, version mới nhất và các app đang được đóng gói.</p>
|
||||||
|
</div>
|
||||||
|
<div class="page-actions">
|
||||||
|
<button class="btn btn-secondary" type="button" data-modal-open="uploadPackageModal">
|
||||||
|
<span class="material-symbols-outlined">upload_file</span>
|
||||||
|
Upload package
|
||||||
|
</button>
|
||||||
|
<a class="btn btn-primary" href="/builder">
|
||||||
|
<span class="material-symbols-outlined">add_box</span>
|
||||||
|
Tạo App
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="dashboard-stats">
|
||||||
|
<article class="metric-card">
|
||||||
|
<span>Packages</span>
|
||||||
|
<div>
|
||||||
|
<strong><%= stats.totalPackages %></strong>
|
||||||
|
<small><%= stats.activePackages %> active</small>
|
||||||
|
</div>
|
||||||
|
</article>
|
||||||
|
<article class="metric-card">
|
||||||
|
<span>Versions</span>
|
||||||
|
<div>
|
||||||
|
<strong><%= stats.totalVersions %></strong>
|
||||||
|
<small>latest tracking</small>
|
||||||
|
</div>
|
||||||
|
</article>
|
||||||
|
<article class="metric-card">
|
||||||
|
<span>Applications</span>
|
||||||
|
<div>
|
||||||
|
<strong><%= stats.totalApplications %></strong>
|
||||||
|
<small><%= stats.releasedApplications %> released</small>
|
||||||
|
</div>
|
||||||
|
</article>
|
||||||
|
<article class="metric-card">
|
||||||
|
<span>Package types</span>
|
||||||
|
<div>
|
||||||
|
<strong>2</strong>
|
||||||
|
<small>.deb + docker</small>
|
||||||
|
</div>
|
||||||
|
</article>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="dashboard-grid">
|
||||||
|
<section class="panel">
|
||||||
|
<div class="panel-header">
|
||||||
|
<div>
|
||||||
|
<h2>Package mới cập nhật</h2>
|
||||||
|
<p>Hiển thị version mới nhất cho từng package.</p>
|
||||||
|
</div>
|
||||||
|
<a href="/packages" class="text-link">Xem tất cả</a>
|
||||||
|
</div>
|
||||||
|
<div class="table-wrap compact">
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Package</th>
|
||||||
|
<th>Type</th>
|
||||||
|
<th>Latest</th>
|
||||||
|
<th>Status</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<% if (packages.length === 0) { %>
|
||||||
|
<tr>
|
||||||
|
<td colspan="4" class="table-empty">Chưa có package nào. Bấm Upload package để thêm dữ liệu đầu tiên.</td>
|
||||||
|
</tr>
|
||||||
|
<% } %>
|
||||||
|
<% packages.slice(0, 4).forEach((item) => { %>
|
||||||
|
<tr>
|
||||||
|
<td>
|
||||||
|
<a class="table-title" href="/packages/<%= item.id %>"><%= item.name %></a>
|
||||||
|
<span class="table-subtitle"><%= item.code %></span>
|
||||||
|
</td>
|
||||||
|
<td><span class="badge <%= helpers.packageTypeClass(item.type) %>"><%= helpers.packageTypeLabel(item.type) %></span></td>
|
||||||
|
<td><%= item.latestVersion %></td>
|
||||||
|
<td><span class="badge <%= helpers.statusClass(item.status) %>"><%= item.status %></span></td>
|
||||||
|
</tr>
|
||||||
|
<% }) %>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel">
|
||||||
|
<div class="panel-header">
|
||||||
|
<div>
|
||||||
|
<h2>Hoạt động gần đây</h2>
|
||||||
|
<p>Các thay đổi chính trong package/app.</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="activity-list">
|
||||||
|
<% if (activity.length === 0) { %>
|
||||||
|
<div class="table-empty">Chưa có hoạt động upload/update package.</div>
|
||||||
|
<% } %>
|
||||||
|
<% activity.forEach((item) => { %>
|
||||||
|
<div class="activity-item">
|
||||||
|
<div class="activity-icon">
|
||||||
|
<span class="material-symbols-outlined"><%= item.icon %></span>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<strong><%= item.title %></strong>
|
||||||
|
<span><%= item.detail %></span>
|
||||||
|
</div>
|
||||||
|
<time><%= item.time %></time>
|
||||||
|
</div>
|
||||||
|
<% }) %>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<%- include('partials/package-modal') %>
|
||||||
|
<%- include('partials/page-end') %>
|
||||||
161
web-server/views/document-detail.ejs
Normal file
161
web-server/views/document-detail.ejs
Normal file
@@ -0,0 +1,161 @@
|
|||||||
|
<%- include('partials/page-start') %>
|
||||||
|
|
||||||
|
<section class="page document-page">
|
||||||
|
<div class="page-header">
|
||||||
|
<div>
|
||||||
|
<div class="breadcrumb"><a href="/documents">Tài liệu</a><span>/</span><span><%= helpers.documentCategoryLabel(document.category) %></span></div>
|
||||||
|
<h1><%= document.title %></h1>
|
||||||
|
<p><%= document.summary || 'Tài liệu nội bộ Robot Installer.' %></p>
|
||||||
|
</div>
|
||||||
|
<div class="page-actions">
|
||||||
|
<% if (document.filePath) { %>
|
||||||
|
<a class="btn btn-secondary" href="/documents/<%= document.id %>/file?download=1">
|
||||||
|
<span class="material-symbols-outlined">download</span>
|
||||||
|
Tải file
|
||||||
|
</a>
|
||||||
|
<% } %>
|
||||||
|
<button class="btn btn-primary" type="button" data-modal-open="editDocumentModal">
|
||||||
|
<span class="material-symbols-outlined">edit</span>
|
||||||
|
Chỉnh sửa
|
||||||
|
</button>
|
||||||
|
<form method="post" action="/documents/<%= document.id %>/delete" data-confirm-submit="Xóa tài liệu <%= document.title %> và file đính kèm?">
|
||||||
|
<button class="btn btn-danger" type="submit">
|
||||||
|
<span class="material-symbols-outlined">delete</span>
|
||||||
|
Xóa
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="document-detail-grid">
|
||||||
|
<section class="panel document-meta-panel">
|
||||||
|
<div class="panel-header">
|
||||||
|
<div>
|
||||||
|
<h2>Thông tin tài liệu</h2>
|
||||||
|
<p>Thông tin phân loại và tệp lưu trữ.</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<dl class="detail-list">
|
||||||
|
<div><dt>Nhóm</dt><dd><span class="badge badge-info"><%= helpers.documentCategoryLabel(document.category) %></span></dd></div>
|
||||||
|
<div><dt>Người tạo</dt><dd><%= document.createdBy %></dd></div>
|
||||||
|
<div><dt>Ngày tạo</dt><dd><%= document.createdAt %></dd></div>
|
||||||
|
<div><dt>Cập nhật</dt><dd><%= document.updatedAt %></dd></div>
|
||||||
|
<div><dt>File</dt><dd><%= document.originalFileName || 'Không có' %></dd></div>
|
||||||
|
<div><dt>Dung lượng</dt><dd><%= document.fileSize || '-' %></dd></div>
|
||||||
|
</dl>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel document-reader-panel">
|
||||||
|
<div class="panel-header">
|
||||||
|
<div>
|
||||||
|
<h2>Nội dung</h2>
|
||||||
|
<p>Đọc nội dung và xem trước file được trình duyệt hỗ trợ.</p>
|
||||||
|
</div>
|
||||||
|
<% if (document.filePath) { %>
|
||||||
|
<a class="text-link" href="/documents/<%= document.id %>/file" target="_blank" rel="noopener">Mở file</a>
|
||||||
|
<% } %>
|
||||||
|
</div>
|
||||||
|
<div class="document-reader">
|
||||||
|
<% if (document.content) { %>
|
||||||
|
<article class="document-copy"><%= document.content %></article>
|
||||||
|
<% } %>
|
||||||
|
|
||||||
|
<% if (document.filePath && documentPreviewKind) { %>
|
||||||
|
<section class="document-preview-block">
|
||||||
|
<div class="document-section-heading">
|
||||||
|
<span class="material-symbols-outlined">attach_file</span>
|
||||||
|
<strong>Xem trước: <%= document.originalFileName %></strong>
|
||||||
|
</div>
|
||||||
|
<% if (documentPreviewKind === 'image') { %>
|
||||||
|
<img class="document-image-preview" src="/documents/<%= document.id %>/file" alt="<%= document.title %>">
|
||||||
|
<% } else { %>
|
||||||
|
<iframe
|
||||||
|
class="document-file-preview"
|
||||||
|
src="/documents/<%= document.id %>/file"
|
||||||
|
title="Xem trước <%= document.originalFileName %>"
|
||||||
|
<% if (documentPreviewKind === 'text') { %>sandbox<% } %>
|
||||||
|
></iframe>
|
||||||
|
<% } %>
|
||||||
|
</section>
|
||||||
|
<% } else if (document.filePath) { %>
|
||||||
|
<div class="document-attachment-state">
|
||||||
|
<span class="material-symbols-outlined">description</span>
|
||||||
|
<div>
|
||||||
|
<strong><%= document.originalFileName %></strong>
|
||||||
|
<p>Trình duyệt không xem trực tiếp định dạng này. Hãy tải file để mở bằng ứng dụng phù hợp.</p>
|
||||||
|
</div>
|
||||||
|
<a class="btn btn-secondary" href="/documents/<%= document.id %>/file?download=1">Tải file</a>
|
||||||
|
</div>
|
||||||
|
<% } %>
|
||||||
|
|
||||||
|
<% if (!document.content && !document.filePath) { %>
|
||||||
|
<div class="table-empty">Tài liệu chưa có nội dung.</div>
|
||||||
|
<% } %>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<div id="editDocumentModal" class="modal-backdrop" role="dialog" aria-modal="true" aria-labelledby="editDocumentModalTitle">
|
||||||
|
<div class="modal-content wide">
|
||||||
|
<div class="modal-header">
|
||||||
|
<div>
|
||||||
|
<h3 id="editDocumentModalTitle">Chỉnh sửa tài liệu</h3>
|
||||||
|
<p>Cập nhật nội dung hoặc thay thế file đính kèm hiện tại.</p>
|
||||||
|
</div>
|
||||||
|
<button class="icon-button subtle" type="button" data-modal-close aria-label="Đóng">
|
||||||
|
<span class="material-symbols-outlined">close</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<form class="modal-form" method="post" action="/documents/<%= document.id %>/edit" enctype="multipart/form-data">
|
||||||
|
<div class="form-stack">
|
||||||
|
<div class="form-grid">
|
||||||
|
<label class="form-field">
|
||||||
|
<span>Tiêu đề</span>
|
||||||
|
<input type="text" name="title" maxlength="200" required value="<%= document.title %>">
|
||||||
|
</label>
|
||||||
|
<label class="form-field">
|
||||||
|
<span>Nhóm tài liệu</span>
|
||||||
|
<select name="category" required>
|
||||||
|
<% documentCategories.forEach((category) => { %>
|
||||||
|
<option value="<%= category.id %>" <%= document.category === category.id ? 'selected' : '' %>><%= category.label %></option>
|
||||||
|
<% }) %>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<label class="form-field">
|
||||||
|
<span>Mô tả ngắn</span>
|
||||||
|
<textarea name="summary" rows="3" maxlength="1000"><%= document.summary %></textarea>
|
||||||
|
</label>
|
||||||
|
<label class="form-field">
|
||||||
|
<span>Nội dung đọc trực tiếp</span>
|
||||||
|
<textarea name="content" rows="8" maxlength="500000"><%= document.content %></textarea>
|
||||||
|
</label>
|
||||||
|
<label class="form-field">
|
||||||
|
<span>Thay file đính kèm</span>
|
||||||
|
<input
|
||||||
|
type="file"
|
||||||
|
name="documentFile"
|
||||||
|
accept=".pdf,.doc,.docx,.odt,.rtf,.txt,.md,.png,.jpg,.jpeg,.webp,.ppt,.pptx,.xls,.xlsx"
|
||||||
|
>
|
||||||
|
<small>Để trống nếu muốn giữ file hiện tại. File mới sẽ thay thế file cũ.</small>
|
||||||
|
</label>
|
||||||
|
<% if (document.filePath) { %>
|
||||||
|
<label class="document-remove-option">
|
||||||
|
<input type="checkbox" name="removeAttachment" value="1">
|
||||||
|
<span>Xóa file hiện tại: <strong><%= document.originalFileName %></strong></span>
|
||||||
|
</label>
|
||||||
|
<% } %>
|
||||||
|
</div>
|
||||||
|
<div class="modal-actions">
|
||||||
|
<button class="btn btn-secondary" type="button" data-modal-close>Hủy</button>
|
||||||
|
<button class="btn btn-primary" type="submit">
|
||||||
|
<span class="material-symbols-outlined">save</span>
|
||||||
|
Lưu thay đổi
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<%- include('partials/page-end') %>
|
||||||
161
web-server/views/documents.ejs
Normal file
161
web-server/views/documents.ejs
Normal file
@@ -0,0 +1,161 @@
|
|||||||
|
<%- include('partials/page-start') %>
|
||||||
|
|
||||||
|
<section class="page">
|
||||||
|
<div class="page-header">
|
||||||
|
<div>
|
||||||
|
<h1>Tài liệu</h1>
|
||||||
|
<p>Lưu trữ và tra cứu tài liệu giới thiệu, hướng dẫn sử dụng, quy trình và tài liệu kỹ thuật.</p>
|
||||||
|
</div>
|
||||||
|
<div class="page-actions">
|
||||||
|
<button class="btn btn-primary" type="button" data-modal-open="createDocumentModal">
|
||||||
|
<span class="material-symbols-outlined">note_add</span>
|
||||||
|
Thêm tài liệu
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="page-filters">
|
||||||
|
<label class="filter-field">
|
||||||
|
<span>Nhóm tài liệu</span>
|
||||||
|
<select data-filter-select data-filter-column="category" data-filter-table="documentsTable">
|
||||||
|
<option value="">Tất cả</option>
|
||||||
|
<% documentCategories.forEach((category) => { %>
|
||||||
|
<option value="<%= category.id %>"><%= category.label %></option>
|
||||||
|
<% }) %>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label class="filter-field wide">
|
||||||
|
<span>Tìm kiếm</span>
|
||||||
|
<input type="search" placeholder="Tìm theo tiêu đề, mô tả, tác giả..." data-table-search="documentsTable">
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<section class="table-panel">
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table id="documentsTable" class="data-table documents-table">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Tài liệu</th>
|
||||||
|
<th>Nhóm</th>
|
||||||
|
<th>File đính kèm</th>
|
||||||
|
<th>Cập nhật</th>
|
||||||
|
<th>Người tạo</th>
|
||||||
|
<th class="action-col">Thao tác</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<% if (documents.length === 0) { %>
|
||||||
|
<tr>
|
||||||
|
<td colspan="6" class="table-empty">Chưa có tài liệu. Bấm Thêm tài liệu để tạo nội dung đầu tiên.</td>
|
||||||
|
</tr>
|
||||||
|
<% } %>
|
||||||
|
<% documents.forEach((item) => { %>
|
||||||
|
<tr
|
||||||
|
data-search="<%= `${item.title} ${item.summary} ${item.createdBy} ${helpers.documentCategoryLabel(item.category)}`.toLowerCase() %>"
|
||||||
|
data-category="<%= item.category %>"
|
||||||
|
>
|
||||||
|
<td class="document-title-cell">
|
||||||
|
<a class="table-title" href="/documents/<%= item.id %>"><%= item.title %></a>
|
||||||
|
<span class="table-subtitle"><%= item.summary || (item.hasContent ? 'Có nội dung đọc trực tiếp' : 'Tài liệu đính kèm') %></span>
|
||||||
|
</td>
|
||||||
|
<td><span class="badge badge-info"><%= helpers.documentCategoryLabel(item.category) %></span></td>
|
||||||
|
<td>
|
||||||
|
<% if (item.filePath) { %>
|
||||||
|
<span class="document-file-name" title="<%= item.originalFileName %>"><%= item.originalFileName %></span>
|
||||||
|
<span class="table-subtitle"><%= item.fileSize %></span>
|
||||||
|
<% } else { %>
|
||||||
|
<span class="table-subtitle">Không có file</span>
|
||||||
|
<% } %>
|
||||||
|
</td>
|
||||||
|
<td><%= item.updatedAt %></td>
|
||||||
|
<td><%= item.createdBy %></td>
|
||||||
|
<td class="action-col">
|
||||||
|
<div class="action-group">
|
||||||
|
<a class="icon-button subtle" href="/documents/<%= item.id %>" title="Đọc tài liệu" aria-label="Đọc tài liệu <%= item.title %>">
|
||||||
|
<span class="material-symbols-outlined">visibility</span>
|
||||||
|
</a>
|
||||||
|
<% if (item.filePath) { %>
|
||||||
|
<a class="icon-button subtle" href="/documents/<%= item.id %>/file?download=1" title="Tải file" aria-label="Tải file <%= item.title %>">
|
||||||
|
<span class="material-symbols-outlined">download</span>
|
||||||
|
</a>
|
||||||
|
<% } %>
|
||||||
|
<form method="post" action="/documents/<%= item.id %>/delete" data-confirm-submit="Xóa tài liệu <%= item.title %> và file đính kèm?">
|
||||||
|
<button class="icon-button danger" type="submit" title="Xóa tài liệu" aria-label="Xóa tài liệu <%= item.title %>">
|
||||||
|
<span class="material-symbols-outlined">delete</span>
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<% }) %>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
<div class="page-pager">
|
||||||
|
<span>Hiển thị <%= documents.length %> tài liệu</span>
|
||||||
|
<div>
|
||||||
|
<button type="button" disabled>Trước</button>
|
||||||
|
<span>Trang 1 / 1</span>
|
||||||
|
<button type="button" disabled>Sau</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<div id="createDocumentModal" class="modal-backdrop" role="dialog" aria-modal="true" aria-labelledby="createDocumentModalTitle">
|
||||||
|
<div class="modal-content wide">
|
||||||
|
<div class="modal-header">
|
||||||
|
<div>
|
||||||
|
<h3 id="createDocumentModalTitle">Thêm tài liệu</h3>
|
||||||
|
<p>Nhập nội dung để đọc trực tiếp, đính kèm file, hoặc sử dụng cả hai.</p>
|
||||||
|
</div>
|
||||||
|
<button class="icon-button subtle" type="button" data-modal-close aria-label="Đóng">
|
||||||
|
<span class="material-symbols-outlined">close</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<form class="modal-form" method="post" action="/documents" enctype="multipart/form-data">
|
||||||
|
<div class="form-stack">
|
||||||
|
<div class="form-grid">
|
||||||
|
<label class="form-field">
|
||||||
|
<span>Tiêu đề</span>
|
||||||
|
<input type="text" name="title" maxlength="200" required placeholder="Ví dụ: Hướng dẫn cài đặt Robot">
|
||||||
|
</label>
|
||||||
|
<label class="form-field">
|
||||||
|
<span>Nhóm tài liệu</span>
|
||||||
|
<select name="category" required>
|
||||||
|
<% documentCategories.forEach((category) => { %>
|
||||||
|
<option value="<%= category.id %>"><%= category.label %></option>
|
||||||
|
<% }) %>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<label class="form-field">
|
||||||
|
<span>Mô tả ngắn</span>
|
||||||
|
<textarea name="summary" rows="3" maxlength="1000" placeholder="Nội dung chính và đối tượng sử dụng tài liệu này."></textarea>
|
||||||
|
</label>
|
||||||
|
<label class="form-field">
|
||||||
|
<span>Nội dung đọc trực tiếp</span>
|
||||||
|
<textarea name="content" rows="8" maxlength="500000" placeholder="Nhập nội dung hướng dẫn tại đây. Xuống dòng và khoảng trắng sẽ được giữ nguyên khi hiển thị."></textarea>
|
||||||
|
</label>
|
||||||
|
<label class="form-field">
|
||||||
|
<span>File đính kèm</span>
|
||||||
|
<input
|
||||||
|
type="file"
|
||||||
|
name="documentFile"
|
||||||
|
accept=".pdf,.doc,.docx,.odt,.rtf,.txt,.md,.png,.jpg,.jpeg,.webp,.ppt,.pptx,.xls,.xlsx"
|
||||||
|
>
|
||||||
|
<small>Hỗ trợ PDF, Word, OpenDocument, text/Markdown, ảnh, PowerPoint và Excel; tối đa 50 MB mặc định.</small>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<div class="modal-actions">
|
||||||
|
<button class="btn btn-secondary" type="button" data-modal-close>Hủy</button>
|
||||||
|
<button class="btn btn-primary" type="submit">
|
||||||
|
<span class="material-symbols-outlined">save</span>
|
||||||
|
Lưu tài liệu
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<%- include('partials/page-end') %>
|
||||||
18
web-server/views/error.ejs
Normal file
18
web-server/views/error.ejs
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
<%- include('partials/page-start') %>
|
||||||
|
|
||||||
|
<section class="page center-page">
|
||||||
|
<div class="empty-state error-state">
|
||||||
|
<span class="material-symbols-outlined">database_off</span>
|
||||||
|
<h1><%= errorTitle || 'Không thể tải dữ liệu' %></h1>
|
||||||
|
<p><%= errorMessage || 'Web server đang gặp lỗi khi đọc dữ liệu. Kiểm tra log container để xem nguyên nhân chi tiết.' %></p>
|
||||||
|
<% if (errorDetails) { %>
|
||||||
|
<code class="error-detail"><%= errorDetails.code %>: <%= errorDetails.message %></code>
|
||||||
|
<% } %>
|
||||||
|
<a class="btn btn-primary" href="/">
|
||||||
|
<span class="material-symbols-outlined">sync</span>
|
||||||
|
Thử lại
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<%- include('partials/page-end') %>
|
||||||
15
web-server/views/not-found.ejs
Normal file
15
web-server/views/not-found.ejs
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
<%- include('partials/page-start') %>
|
||||||
|
|
||||||
|
<section class="page center-page">
|
||||||
|
<div class="empty-state">
|
||||||
|
<span class="material-symbols-outlined">search_off</span>
|
||||||
|
<h1>Không tìm thấy dữ liệu</h1>
|
||||||
|
<p>Trang hoặc bản ghi bạn mở không tồn tại trong dữ liệu hiện tại.</p>
|
||||||
|
<a class="btn btn-primary" href="/">
|
||||||
|
<span class="material-symbols-outlined">dashboard</span>
|
||||||
|
Về tổng quan
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<%- include('partials/page-end') %>
|
||||||
103
web-server/views/package-detail.ejs
Normal file
103
web-server/views/package-detail.ejs
Normal file
@@ -0,0 +1,103 @@
|
|||||||
|
<%- include('partials/page-start') %>
|
||||||
|
|
||||||
|
<section class="page">
|
||||||
|
<div class="page-header">
|
||||||
|
<div>
|
||||||
|
<div class="breadcrumb"><a href="/packages">Packages</a><span>/</span><span><%= packageItem.code %></span></div>
|
||||||
|
<h1><%= packageItem.name %></h1>
|
||||||
|
<p><%= packageItem.description %></p>
|
||||||
|
</div>
|
||||||
|
<div class="page-actions">
|
||||||
|
<button class="btn btn-secondary" type="button" data-modal-open="updatePackageModal" data-package-update="<%= packageItem.id %>">
|
||||||
|
<span class="material-symbols-outlined">upgrade</span>
|
||||||
|
Update version
|
||||||
|
</button>
|
||||||
|
<form method="post" action="/packages/<%= packageItem.id %>/delete" data-confirm-submit="Xóa package <%= packageItem.code %>? Thao tác này sẽ xóa mọi version và liên kết app liên quan.">
|
||||||
|
<button class="btn btn-danger" type="submit">
|
||||||
|
<span class="material-symbols-outlined">delete</span>
|
||||||
|
Xóa package
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="detail-grid">
|
||||||
|
<section class="panel">
|
||||||
|
<div class="panel-header">
|
||||||
|
<div>
|
||||||
|
<h2>Thông tin package</h2>
|
||||||
|
<p>Metadata chính dùng cho web server và API.</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<dl class="detail-list">
|
||||||
|
<div><dt>Code</dt><dd><%= packageItem.code %></dd></div>
|
||||||
|
<div><dt>Type</dt><dd><span class="badge <%= helpers.packageTypeClass(packageItem.type) %>"><%= helpers.packageTypeLabel(packageItem.type) %></span></dd></div>
|
||||||
|
<div><dt>Latest</dt><dd><strong><%= packageItem.latestVersion %></strong></dd></div>
|
||||||
|
<div><dt>Artifact</dt><dd class="mono"><%= packageItem.artifact %></dd></div>
|
||||||
|
<div><dt>Owner</dt><dd><%= packageItem.owner %></dd></div>
|
||||||
|
<div><dt>Status</dt><dd><span class="badge <%= helpers.statusClass(packageItem.status) %>"><%= packageItem.status %></span></dd></div>
|
||||||
|
</dl>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel wide-panel">
|
||||||
|
<div class="panel-header">
|
||||||
|
<div>
|
||||||
|
<h2>Version history</h2>
|
||||||
|
<p>Mỗi version có ngày upload, changelog và trạng thái.</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="table-wrap compact">
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Version</th>
|
||||||
|
<th>Release date</th>
|
||||||
|
<th>Uploaded by</th>
|
||||||
|
<th>Size</th>
|
||||||
|
<th>Status</th>
|
||||||
|
<th class="action-col">Actions</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<% packageItem.versions.forEach((version) => { %>
|
||||||
|
<tr>
|
||||||
|
<td>
|
||||||
|
<strong><%= version.version %></strong>
|
||||||
|
<span class="table-subtitle"><%= version.changeLog %></span>
|
||||||
|
</td>
|
||||||
|
<td><%= version.releaseDate %></td>
|
||||||
|
<td><%= version.uploadedBy %></td>
|
||||||
|
<td><%= version.size %></td>
|
||||||
|
<td><span class="badge <%= helpers.statusClass(version.status) %>"><%= version.status %></span></td>
|
||||||
|
<td class="action-col">
|
||||||
|
<div class="action-group">
|
||||||
|
<% if (packageItem.type === 'deb' && version.filePath) { %>
|
||||||
|
<a class="icon-button subtle" href="/api/package-versions/<%= version.id %>/download" title="Download package" aria-label="Download package version <%= version.version %>">
|
||||||
|
<span class="material-symbols-outlined">download</span>
|
||||||
|
</a>
|
||||||
|
<% } %>
|
||||||
|
<form method="post" action="/package-versions/<%= version.id %>/latest">
|
||||||
|
<input type="hidden" name="returnTo" value="<%= currentPath %>">
|
||||||
|
<button class="icon-button subtle" type="submit" title="Đặt latest" aria-label="Đặt latest <%= version.version %>" <%= version.status === 'Latest' ? 'disabled' : '' %>>
|
||||||
|
<span class="material-symbols-outlined">stars</span>
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
<form method="post" action="/package-versions/<%= version.id %>/delete" data-confirm-submit="Xóa version <%= version.version %> khỏi package?">
|
||||||
|
<input type="hidden" name="returnTo" value="<%= currentPath %>">
|
||||||
|
<button class="icon-button danger" type="submit" title="Xóa version" aria-label="Xóa version <%= version.version %>">
|
||||||
|
<span class="material-symbols-outlined">delete</span>
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<% }) %>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<%- include('partials/update-package-modal') %>
|
||||||
|
<%- include('partials/page-end') %>
|
||||||
114
web-server/views/packages.ejs
Normal file
114
web-server/views/packages.ejs
Normal file
@@ -0,0 +1,114 @@
|
|||||||
|
<%- include('partials/page-start') %>
|
||||||
|
|
||||||
|
<section class="page">
|
||||||
|
<div class="page-header">
|
||||||
|
<div>
|
||||||
|
<h1>Packages</h1>
|
||||||
|
<p>Quản lý package `.deb`, Docker image, version và trạng thái latest.</p>
|
||||||
|
</div>
|
||||||
|
<div class="page-actions">
|
||||||
|
<a class="btn btn-secondary" href="/packages/export.csv">
|
||||||
|
<span class="material-symbols-outlined">download</span>
|
||||||
|
Export
|
||||||
|
</a>
|
||||||
|
<button class="btn btn-primary" type="button" data-modal-open="uploadPackageModal">
|
||||||
|
<span class="material-symbols-outlined">upload_file</span>
|
||||||
|
Upload package
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="page-filters">
|
||||||
|
<label class="filter-field">
|
||||||
|
<span>Type</span>
|
||||||
|
<select data-filter-select data-filter-column="type" data-filter-table="packagesTable">
|
||||||
|
<option value="">Tất cả</option>
|
||||||
|
<option value="deb">.deb</option>
|
||||||
|
<option value="apt">APT</option>
|
||||||
|
<option value="docker">Docker</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label class="filter-field">
|
||||||
|
<span>Status</span>
|
||||||
|
<select data-filter-select data-filter-column="status" data-filter-table="packagesTable">
|
||||||
|
<option value="">Tất cả</option>
|
||||||
|
<option value="Active">Active</option>
|
||||||
|
<option value="Archived">Archived</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label class="filter-field wide">
|
||||||
|
<span>Search</span>
|
||||||
|
<input type="search" placeholder="Tìm theo tên, code, owner..." data-table-search="packagesTable">
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<section class="table-panel">
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table id="packagesTable" class="data-table">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Package</th>
|
||||||
|
<th>Type</th>
|
||||||
|
<th>Latest version</th>
|
||||||
|
<th>Release date</th>
|
||||||
|
<th>Owner</th>
|
||||||
|
<th>Status</th>
|
||||||
|
<th class="action-col">Actions</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<% if (packages.length === 0) { %>
|
||||||
|
<tr>
|
||||||
|
<td colspan="7" class="table-empty">Chưa có package trong database. Bấm Upload package để tạo package đầu tiên.</td>
|
||||||
|
</tr>
|
||||||
|
<% } %>
|
||||||
|
<% packages.forEach((item) => { %>
|
||||||
|
<tr data-search="<%= `${item.name} ${item.code} ${item.owner} ${item.latestVersion}`.toLowerCase() %>" data-type="<%= item.type %>" data-status="<%= item.status %>">
|
||||||
|
<td>
|
||||||
|
<a class="table-title" href="/packages/<%= item.id %>"><%= item.name %></a>
|
||||||
|
<span class="table-subtitle"><%= item.code %></span>
|
||||||
|
</td>
|
||||||
|
<td><span class="badge <%= helpers.packageTypeClass(item.type) %>"><%= helpers.packageTypeLabel(item.type) %></span></td>
|
||||||
|
<td><strong><%= item.latestVersion %></strong></td>
|
||||||
|
<td><%= item.latestReleaseDate %></td>
|
||||||
|
<td><%= item.owner %></td>
|
||||||
|
<td><span class="badge <%= helpers.statusClass(item.status) %>"><%= item.status %></span></td>
|
||||||
|
<td class="action-col">
|
||||||
|
<div class="action-group">
|
||||||
|
<a class="icon-button subtle" href="/packages/<%= item.id %>" title="Xem chi tiết" aria-label="Xem chi tiết <%= item.name %>">
|
||||||
|
<span class="material-symbols-outlined">visibility</span>
|
||||||
|
</a>
|
||||||
|
<% if (item.type === 'deb' && item.latestVersionId && item.artifact) { %>
|
||||||
|
<a class="icon-button subtle" href="/api/package-versions/<%= item.latestVersionId %>/download" title="Download latest package" aria-label="Download latest package <%= item.name %>">
|
||||||
|
<span class="material-symbols-outlined">download</span>
|
||||||
|
</a>
|
||||||
|
<% } %>
|
||||||
|
<button class="icon-button subtle" type="button" title="Update version" data-modal-open="updatePackageModal" data-package-update="<%= item.id %>">
|
||||||
|
<span class="material-symbols-outlined">upgrade</span>
|
||||||
|
</button>
|
||||||
|
<form method="post" action="/packages/<%= item.id %>/delete" data-confirm-submit="Xóa package <%= item.code %>? Thao tác này sẽ xóa cả version và liên kết app liên quan.">
|
||||||
|
<button class="icon-button danger" type="submit" title="Xóa package" aria-label="Xóa package <%= item.name %>">
|
||||||
|
<span class="material-symbols-outlined">delete</span>
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<% }) %>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
<div class="page-pager">
|
||||||
|
<span>Showing 1-<%= packages.length %> of <%= packages.length %></span>
|
||||||
|
<div>
|
||||||
|
<button type="button" disabled>Prev</button>
|
||||||
|
<span>Page 1 / 1</span>
|
||||||
|
<button type="button" disabled>Next</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<%- include('partials/package-modal') %>
|
||||||
|
<%- include('partials/update-package-modal') %>
|
||||||
|
<%- include('partials/page-end') %>
|
||||||
67
web-server/views/partials/edit-app-modal.ejs
Normal file
67
web-server/views/partials/edit-app-modal.ejs
Normal file
@@ -0,0 +1,67 @@
|
|||||||
|
<div class="modal-backdrop" id="editAppModal" role="dialog" aria-modal="true" aria-labelledby="editAppTitle">
|
||||||
|
<div class="modal-content wide">
|
||||||
|
<div class="modal-header">
|
||||||
|
<h3 id="editAppTitle">Sửa Application</h3>
|
||||||
|
<button class="icon-button subtle" type="button" aria-label="Đóng modal" data-modal-close>
|
||||||
|
<span class="material-symbols-outlined">close</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<form id="editAppForm" class="modal-form" method="post" action="/applications">
|
||||||
|
<input type="hidden" name="returnTo" value="<%= currentPath || '/applications' %>">
|
||||||
|
<div class="form-grid">
|
||||||
|
<label class="form-field">
|
||||||
|
<span>App code</span>
|
||||||
|
<input type="text" name="appCode" pattern="[A-Za-z0-9._+-]+" title="Only letters, numbers, dot, underscore, plus and hyphen. No spaces." required data-edit-app-field="appCode">
|
||||||
|
</label>
|
||||||
|
<label class="form-field">
|
||||||
|
<span>Version</span>
|
||||||
|
<input type="text" name="appVersion" pattern="[A-Za-z0-9._:+~=-]+" title="Only letters, numbers and . _ : + ~ = - characters." required data-edit-app-field="appVersion">
|
||||||
|
</label>
|
||||||
|
<label class="form-field">
|
||||||
|
<span>Status</span>
|
||||||
|
<select name="status" data-edit-app-field="status">
|
||||||
|
<option value="Draft">Draft</option>
|
||||||
|
<option value="Released">Released</option>
|
||||||
|
<option value="Archived">Archived</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label class="form-field full">
|
||||||
|
<span>App name</span>
|
||||||
|
<input type="text" name="appName" required data-edit-app-field="appName">
|
||||||
|
</label>
|
||||||
|
<label class="form-field full">
|
||||||
|
<span>Open URL</span>
|
||||||
|
<input type="text" name="openUrl" placeholder="http://127.0.0.1:5000" data-edit-app-field="openUrl">
|
||||||
|
</label>
|
||||||
|
<label class="form-field full">
|
||||||
|
<span>Notes</span>
|
||||||
|
<textarea name="notes" data-edit-app-field="notes"></textarea>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<div class="modal-mini-table">
|
||||||
|
<% packages.forEach((item) => { %>
|
||||||
|
<label>
|
||||||
|
<input class="checkbox" type="checkbox" name="packageIds" value="<%= item.id %>" data-edit-app-package="<%= item.id %>">
|
||||||
|
<span>
|
||||||
|
<strong><%= item.name %></strong>
|
||||||
|
<small><%= item.code %></small>
|
||||||
|
</span>
|
||||||
|
<select class="mini-select" name="version_<%= item.id %>" data-edit-app-version="<%= item.id %>">
|
||||||
|
<option value="">Latest/default</option>
|
||||||
|
<% item.versions.forEach((version) => { %>
|
||||||
|
<option value="<%= version.id %>"><%= version.version %></option>
|
||||||
|
<% }) %>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<% }) %>
|
||||||
|
</div>
|
||||||
|
<div class="modal-actions">
|
||||||
|
<button class="btn btn-secondary" type="button" data-modal-close>Hủy</button>
|
||||||
|
<button class="btn btn-primary" type="submit">
|
||||||
|
<span class="material-symbols-outlined">save</span>
|
||||||
|
Lưu
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
82
web-server/views/partials/package-modal.ejs
Normal file
82
web-server/views/partials/package-modal.ejs
Normal file
@@ -0,0 +1,82 @@
|
|||||||
|
<div class="modal-backdrop" id="uploadPackageModal" role="dialog" aria-modal="true" aria-labelledby="uploadPackageTitle">
|
||||||
|
<div class="modal-content">
|
||||||
|
<div class="modal-header">
|
||||||
|
<h3 id="uploadPackageTitle">Upload package</h3>
|
||||||
|
<button class="icon-button subtle" type="button" aria-label="Đóng modal" data-modal-close>
|
||||||
|
<span class="material-symbols-outlined">close</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<form class="modal-form" action="/packages" method="post" enctype="multipart/form-data">
|
||||||
|
<div class="form-grid">
|
||||||
|
<label class="form-field">
|
||||||
|
<span>Package code</span>
|
||||||
|
<input type="text" name="packageCode" placeholder="NAV-STACK" pattern="[A-Za-z0-9._+-]+" title="Only letters, numbers, dot, underscore, plus and hyphen. No spaces." required>
|
||||||
|
</label>
|
||||||
|
<label class="form-field">
|
||||||
|
<span>Package type</span>
|
||||||
|
<select name="packageType">
|
||||||
|
<option value="deb">.deb</option>
|
||||||
|
<option value="apt">APT (Ubuntu repository)</option>
|
||||||
|
<option value="docker">Docker</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label class="form-field full">
|
||||||
|
<span>Package name</span>
|
||||||
|
<input type="text" name="packageName" placeholder="Navigation Stack" required>
|
||||||
|
</label>
|
||||||
|
<label class="form-field full">
|
||||||
|
<span>Description</span>
|
||||||
|
<input type="text" name="description" placeholder="Mô tả ngắn về package">
|
||||||
|
</label>
|
||||||
|
<label class="form-field">
|
||||||
|
<span>Version</span>
|
||||||
|
<input type="text" name="version" placeholder="1.0.0" pattern="[A-Za-z0-9._:+~=-]+" title="Only letters, numbers and . _ : + ~ = - characters." required>
|
||||||
|
</label>
|
||||||
|
<label class="form-field">
|
||||||
|
<span>Release date</span>
|
||||||
|
<input type="date" name="releaseDate" value="<%= todayDate %>">
|
||||||
|
</label>
|
||||||
|
<div class="form-field full">
|
||||||
|
<span>Package file</span>
|
||||||
|
<div class="file-dropzone" data-file-dropzone>
|
||||||
|
<input class="file-input" type="file" name="packageFile" accept=".deb,.tar,.tar.gz,.tgz,.zip,.gz" data-file-input>
|
||||||
|
<div class="file-dropzone-content">
|
||||||
|
<span class="material-symbols-outlined">upload_file</span>
|
||||||
|
<strong>Kéo file vào đây hoặc chọn từ máy</strong>
|
||||||
|
<small>Hỗ trợ .deb, .tar, .tgz, .zip cho package hoặc Docker image export</small>
|
||||||
|
<button class="btn btn-secondary" type="button" data-file-browse>
|
||||||
|
<span class="material-symbols-outlined">attach_file</span>
|
||||||
|
Chọn file
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div class="file-preview" data-file-preview hidden>
|
||||||
|
<span class="material-symbols-outlined">draft</span>
|
||||||
|
<div>
|
||||||
|
<strong data-file-name>Chưa chọn file</strong>
|
||||||
|
<small data-file-meta></small>
|
||||||
|
</div>
|
||||||
|
<button class="icon-button subtle" type="button" title="Bỏ file" aria-label="Bỏ file đã chọn" data-file-clear>
|
||||||
|
<span class="material-symbols-outlined">close</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="form-field full">
|
||||||
|
<small>APT packages only store metadata and do not need an uploaded file. Enter the exact package name accepted by <code>apt-get install</code>, for example <code>postgresql</code>, <code>nginx</code>, or <code>redis-server</code>. Agents using <code>ALLOWED_APT_PACKAGES=*</code> accept any valid package code.</small>
|
||||||
|
</div>
|
||||||
|
<label class="form-field full">
|
||||||
|
<span>Docker image/tag</span>
|
||||||
|
<input type="text" name="dockerImage" placeholder="registry.local/robot/fleet-agent:1.9.0">
|
||||||
|
</label>
|
||||||
|
<label class="form-field full">
|
||||||
|
<span>Change log</span>
|
||||||
|
<textarea name="changeLog" placeholder="Ghi chú thay đổi"></textarea>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<div class="modal-actions">
|
||||||
|
<button class="btn btn-secondary" type="button" data-modal-close>Hủy</button>
|
||||||
|
<button class="btn btn-primary" type="submit">Upload</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
111
web-server/views/partials/page-end.ejs
Normal file
111
web-server/views/partials/page-end.ejs
Normal file
@@ -0,0 +1,111 @@
|
|||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<% if (currentUser && currentUser.role === 'User') { %>
|
||||||
|
<div id="profileModal" class="modal-backdrop" role="dialog" aria-modal="true" aria-labelledby="profileModalTitle">
|
||||||
|
<div class="modal-content">
|
||||||
|
<div class="modal-header">
|
||||||
|
<h3 id="profileModalTitle">Thông tin cá nhân</h3>
|
||||||
|
<button class="icon-button subtle" type="button" data-modal-close aria-label="Đóng">
|
||||||
|
<span class="material-symbols-outlined">close</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<form class="modal-form" method="post" action="/profile" data-profile-form>
|
||||||
|
<input type="hidden" name="returnTo" value="<%= currentPath || '/' %>">
|
||||||
|
<div class="profile-summary">
|
||||||
|
<div class="profile-avatar"><%= currentUser.name.charAt(0) %></div>
|
||||||
|
<div>
|
||||||
|
<strong><%= currentUser.name %></strong>
|
||||||
|
<span><%= currentUser.username %></span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="form-stack">
|
||||||
|
<label class="form-field">
|
||||||
|
<span>Fullname</span>
|
||||||
|
<input type="text" name="fullName" value="<%= currentUser.fullName || '' %>" autocomplete="name">
|
||||||
|
</label>
|
||||||
|
<label class="form-field">
|
||||||
|
<span>Email mới</span>
|
||||||
|
<input type="email" name="email" value="<%= currentUser.email || '' %>" autocomplete="email" required data-profile-email>
|
||||||
|
</label>
|
||||||
|
<label class="form-field">
|
||||||
|
<span>Confirm email mới</span>
|
||||||
|
<input type="email" name="confirmEmail" value="<%= currentUser.email || '' %>" autocomplete="email" required data-profile-confirm-email>
|
||||||
|
<small class="field-feedback" data-profile-feedback="email"></small>
|
||||||
|
</label>
|
||||||
|
<label class="form-field">
|
||||||
|
<span>Mật khẩu mới</span>
|
||||||
|
<input type="password" name="newPassword" minlength="8" autocomplete="new-password" data-profile-new-password>
|
||||||
|
</label>
|
||||||
|
<label class="form-field">
|
||||||
|
<span>Xác nhận mật khẩu mới</span>
|
||||||
|
<input type="password" name="confirmPassword" minlength="8" autocomplete="new-password" data-profile-confirm-password>
|
||||||
|
<small class="field-feedback" data-profile-feedback="password"></small>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<div class="modal-actions">
|
||||||
|
<button class="btn btn-secondary" type="button" data-modal-close>Hủy</button>
|
||||||
|
<button class="btn btn-primary" type="submit">
|
||||||
|
<span class="material-symbols-outlined">save</span>
|
||||||
|
Lưu
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<% } %>
|
||||||
|
|
||||||
|
<% if (currentUser && currentUser.role === 'Admin') { %>
|
||||||
|
<div id="systemNotificationModal" class="modal-backdrop" role="dialog" aria-modal="true" aria-labelledby="systemNotificationModalTitle">
|
||||||
|
<div class="modal-content">
|
||||||
|
<div class="modal-header">
|
||||||
|
<div>
|
||||||
|
<h3 id="systemNotificationModalTitle">Đăng thông báo hệ thống</h3>
|
||||||
|
<p>Thông báo sẽ được gửi tới tất cả tài khoản đang hoạt động.</p>
|
||||||
|
</div>
|
||||||
|
<button class="icon-button subtle" type="button" data-modal-close aria-label="Đóng">
|
||||||
|
<span class="material-symbols-outlined">close</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<form class="modal-form" data-system-notification-form>
|
||||||
|
<div class="form-stack">
|
||||||
|
<label class="form-field">
|
||||||
|
<span>Tiêu đề</span>
|
||||||
|
<input type="text" name="title" maxlength="200" required placeholder="Ví dụ: Hệ thống đã cập nhật phiên bản 1.2.0">
|
||||||
|
</label>
|
||||||
|
<label class="form-field">
|
||||||
|
<span>Mức độ</span>
|
||||||
|
<select name="severity" required>
|
||||||
|
<option value="info">Thông tin</option>
|
||||||
|
<option value="success">Cập nhật thành công</option>
|
||||||
|
<option value="warning">Quan trọng / bảo trì</option>
|
||||||
|
<option value="error">Khẩn cấp / sự cố</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label class="form-field">
|
||||||
|
<span>Nội dung</span>
|
||||||
|
<textarea name="message" rows="6" maxlength="1000" required placeholder="Mô tả nội dung cập nhật, ảnh hưởng và việc người dùng cần thực hiện."></textarea>
|
||||||
|
<small>Tối đa 1000 ký tự. Không nhập mật khẩu, token hoặc thông tin nhạy cảm.</small>
|
||||||
|
</label>
|
||||||
|
<label class="form-field">
|
||||||
|
<span>Đường dẫn nội bộ (không bắt buộc)</span>
|
||||||
|
<input type="text" name="actionUrl" maxlength="1000" placeholder="Ví dụ: /applications hoặc /agent">
|
||||||
|
<small>Chỉ chấp nhận đường dẫn trong website bắt đầu bằng dấu /.</small>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<div class="modal-actions">
|
||||||
|
<button class="btn btn-secondary" type="button" data-modal-close>Hủy</button>
|
||||||
|
<button class="btn btn-primary" type="submit" data-system-notification-submit>
|
||||||
|
<span class="material-symbols-outlined">send</span>
|
||||||
|
Gửi cho mọi người
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<% } %>
|
||||||
|
|
||||||
|
<script src="/vendor/notiflix/notiflix-<%= notiflixVersion %>.min.js"></script>
|
||||||
|
<script src="/js/app.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
124
web-server/views/partials/page-start.ejs
Normal file
124
web-server/views/partials/page-start.ejs
Normal file
@@ -0,0 +1,124 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="vi">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title><%= title %> | Robot Installer</title>
|
||||||
|
<link rel="stylesheet" href="/vendor/montserrat/index.css">
|
||||||
|
<link rel="stylesheet" href="/vendor/notiflix/notiflix-<%= notiflixVersion %>.min.css">
|
||||||
|
<link rel="stylesheet" href="/css/styles.css">
|
||||||
|
<link rel="icon" type="image/png" href="/image/logo_PNKX.png">
|
||||||
|
</head>
|
||||||
|
<body class="app-shell" <% if (notice) { %>data-notice-type="<%= notice.type %>" data-notice="<%= notice.message %>"<% } %>>
|
||||||
|
<aside id="appSidebar" class="sidebar" aria-label="Main navigation">
|
||||||
|
<div class="brand-block">
|
||||||
|
<div class="brand-mark">
|
||||||
|
<img class="brand-logo" src="/image/logo_PNKX.png" alt="">
|
||||||
|
</div>
|
||||||
|
<div class="brand-copy">
|
||||||
|
<strong>Robot Installer</strong>
|
||||||
|
<span>Package Console</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<nav class="nav-section" aria-label="Workspace">
|
||||||
|
<span class="nav-label">Workspace</span>
|
||||||
|
<% navItems.forEach((item) => { %>
|
||||||
|
<a href="<%= item.href %>" class="nav-item <%= active === item.id ? 'active' : '' %>">
|
||||||
|
<span class="material-symbols-outlined"><%= item.icon %></span>
|
||||||
|
<span><%= item.label %></span>
|
||||||
|
</a>
|
||||||
|
<% }) %>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<div class="sidebar-copyright">
|
||||||
|
© Copyright 2026 Phenikaa X. All Rights Reserved
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
|
||||||
|
<button id="sidebarBackdrop" type="button" aria-label="Đóng menu"></button>
|
||||||
|
|
||||||
|
<main id="appMain" class="main-shell">
|
||||||
|
<header class="topbar">
|
||||||
|
<div class="topbar-left">
|
||||||
|
<button id="mobileMenuBtn" class="icon-button" type="button" aria-label="Mở menu" aria-expanded="false">
|
||||||
|
<span class="material-symbols-outlined">menu</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="topbar-actions">
|
||||||
|
<button class="icon-button" type="button" title="Đồng bộ dữ liệu" data-refresh-page>
|
||||||
|
<span class="material-symbols-outlined">sync</span>
|
||||||
|
</button>
|
||||||
|
<div class="notification-center" data-notification-center>
|
||||||
|
<button
|
||||||
|
id="notificationButton"
|
||||||
|
class="icon-button notification-button"
|
||||||
|
type="button"
|
||||||
|
title="Thông báo"
|
||||||
|
aria-label="Mở thông báo"
|
||||||
|
aria-controls="notificationPanel"
|
||||||
|
aria-expanded="false"
|
||||||
|
data-notification-toggle
|
||||||
|
>
|
||||||
|
<span class="material-symbols-outlined">notifications</span>
|
||||||
|
<span class="notification-badge" data-notification-badge hidden>0</span>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<section id="notificationPanel" class="notification-panel" aria-label="Thông báo" hidden data-notification-panel>
|
||||||
|
<div class="notification-panel-header">
|
||||||
|
<div>
|
||||||
|
<strong>Thông báo</strong>
|
||||||
|
<span data-notification-summary>Đang tải...</span>
|
||||||
|
</div>
|
||||||
|
<button class="text-button" type="button" data-notification-read-all>Đánh dấu đã đọc</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="notification-tabs" role="tablist" aria-label="Lọc thông báo">
|
||||||
|
<button class="active" type="button" role="tab" aria-selected="true" data-notification-filter="all">Tất cả</button>
|
||||||
|
<button type="button" role="tab" aria-selected="false" data-notification-filter="unread">Chưa đọc</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="notification-list" data-notification-list></div>
|
||||||
|
<div class="notification-empty" data-notification-empty hidden>
|
||||||
|
<span class="material-symbols-outlined">notifications_none</span>
|
||||||
|
<strong>Chưa có thông báo</strong>
|
||||||
|
<span>Các cập nhật quan trọng sẽ xuất hiện tại đây.</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<% if (currentUser.role === 'Admin') { %>
|
||||||
|
<div class="notification-panel-footer">
|
||||||
|
<button class="btn btn-primary" type="button" data-modal-open="systemNotificationModal">
|
||||||
|
<span class="material-symbols-outlined">campaign</span>
|
||||||
|
Đăng thông báo hệ thống
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<% } %>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
<% if (currentUser.role === 'User') { %>
|
||||||
|
<button class="profile-chip profile-chip-button" type="button" title="Cập nhật thông tin cá nhân" aria-label="Cập nhật thông tin cá nhân" data-modal-open="profileModal">
|
||||||
|
<span class="profile-avatar"><%= currentUser.name.charAt(0) %></span>
|
||||||
|
<span class="profile-meta">
|
||||||
|
<strong><%= currentUser.name %></strong>
|
||||||
|
<span><%= currentUser.role %></span>
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
<% } else { %>
|
||||||
|
<div class="profile-chip">
|
||||||
|
<span class="profile-avatar"><%= currentUser.name.charAt(0) %></span>
|
||||||
|
<span class="profile-meta">
|
||||||
|
<strong><%= currentUser.name %></strong>
|
||||||
|
<span><%= currentUser.role %></span>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<% } %>
|
||||||
|
<form class="logout-form" method="post" action="/logout">
|
||||||
|
<button class="icon-button" type="submit" title="Đăng xuất" aria-label="Đăng xuất">
|
||||||
|
<span class="material-symbols-outlined">logout</span>
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<div id="mainContent" class="main-content">
|
||||||
68
web-server/views/partials/update-package-modal.ejs
Normal file
68
web-server/views/partials/update-package-modal.ejs
Normal file
@@ -0,0 +1,68 @@
|
|||||||
|
<div class="modal-backdrop" id="updatePackageModal" role="dialog" aria-modal="true" aria-labelledby="updatePackageTitle">
|
||||||
|
<div class="modal-content">
|
||||||
|
<div class="modal-header">
|
||||||
|
<h3 id="updatePackageTitle">Update package version</h3>
|
||||||
|
<button class="icon-button subtle" type="button" aria-label="Đóng modal" data-modal-close>
|
||||||
|
<span class="material-symbols-outlined">close</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<form class="modal-form" action="/package-versions" method="post" enctype="multipart/form-data">
|
||||||
|
<div class="form-grid">
|
||||||
|
<label class="form-field full">
|
||||||
|
<span>Package</span>
|
||||||
|
<select name="packageId" required>
|
||||||
|
<% packages.forEach((item) => { %>
|
||||||
|
<option value="<%= item.id %>" <%= typeof packageItem !== 'undefined' && packageItem.id === item.id ? 'selected' : '' %>><%= item.code %> - <%= item.name %></option>
|
||||||
|
<% }) %>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label class="form-field">
|
||||||
|
<span>Version</span>
|
||||||
|
<input type="text" name="version" placeholder="2.5.0" pattern="[A-Za-z0-9._:+~=-]+" title="Only letters, numbers and . _ : + ~ = - characters." required>
|
||||||
|
<small>Nhap version moi de them, hoac version da co de re-upload artifact.</small>
|
||||||
|
</label>
|
||||||
|
<label class="form-field">
|
||||||
|
<span>Release date</span>
|
||||||
|
<input type="date" name="releaseDate" value="<%= todayDate %>">
|
||||||
|
</label>
|
||||||
|
<div class="form-field full">
|
||||||
|
<span>Package file</span>
|
||||||
|
<div class="file-dropzone" data-file-dropzone>
|
||||||
|
<input class="file-input" type="file" name="packageFile" accept=".deb,.tar,.tar.gz,.tgz,.zip,.gz" data-file-input>
|
||||||
|
<div class="file-dropzone-content">
|
||||||
|
<span class="material-symbols-outlined">upload_file</span>
|
||||||
|
<strong>Kéo version mới vào đây hoặc chọn file</strong>
|
||||||
|
<small>File .deb hoặc archive Docker export đều dùng được</small>
|
||||||
|
<button class="btn btn-secondary" type="button" data-file-browse>
|
||||||
|
<span class="material-symbols-outlined">attach_file</span>
|
||||||
|
Chọn file
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div class="file-preview" data-file-preview hidden>
|
||||||
|
<span class="material-symbols-outlined">draft</span>
|
||||||
|
<div>
|
||||||
|
<strong data-file-name>Chưa chọn file</strong>
|
||||||
|
<small data-file-meta></small>
|
||||||
|
</div>
|
||||||
|
<button class="icon-button subtle" type="button" title="Bỏ file" aria-label="Bỏ file đã chọn" data-file-clear>
|
||||||
|
<span class="material-symbols-outlined">close</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<label class="form-field full">
|
||||||
|
<span>Docker image/tag</span>
|
||||||
|
<input type="text" name="dockerImage" placeholder="registry.local/robot/fleet-agent:2.0.0">
|
||||||
|
</label>
|
||||||
|
<label class="form-field full">
|
||||||
|
<span>Change log</span>
|
||||||
|
<textarea name="changeLog" placeholder="Mô tả thay đổi trong version này"></textarea>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<div class="modal-actions">
|
||||||
|
<button class="btn btn-secondary" type="button" data-modal-close>Hủy</button>
|
||||||
|
<button class="btn btn-primary" type="submit">Cập nhật</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
277
web-server/views/users.ejs
Normal file
277
web-server/views/users.ejs
Normal file
@@ -0,0 +1,277 @@
|
|||||||
|
<%- include('partials/page-start') %>
|
||||||
|
|
||||||
|
<section class="page">
|
||||||
|
<div class="page-header">
|
||||||
|
<div>
|
||||||
|
<h1>Users</h1>
|
||||||
|
<p>Quản lý tài khoản đăng nhập, quyền Admin/User và trạng thái hoạt động.</p>
|
||||||
|
</div>
|
||||||
|
<div class="page-actions">
|
||||||
|
<span class="badge badge-info"><%= users.length %> users</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="users-layout">
|
||||||
|
<section class="panel">
|
||||||
|
<div class="panel-header">
|
||||||
|
<div>
|
||||||
|
<h2>Tạo user mới</h2>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<form class="user-create-form" method="post" action="/users">
|
||||||
|
<div class="form-stack">
|
||||||
|
<label class="form-field">
|
||||||
|
<span>Username</span>
|
||||||
|
<input type="text" name="username" autocomplete="off" required>
|
||||||
|
</label>
|
||||||
|
<label class="form-field">
|
||||||
|
<span>Họ tên</span>
|
||||||
|
<input type="text" name="fullName" autocomplete="off">
|
||||||
|
</label>
|
||||||
|
<label class="form-field">
|
||||||
|
<span>Email</span>
|
||||||
|
<input type="email" name="email" autocomplete="off" required>
|
||||||
|
</label>
|
||||||
|
<label class="form-field">
|
||||||
|
<span>Role</span>
|
||||||
|
<select name="role">
|
||||||
|
<option value="User">User</option>
|
||||||
|
<option value="Admin">Admin</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label class="form-field full">
|
||||||
|
<span>Mật khẩu tạm</span>
|
||||||
|
<input type="password" name="password" minlength="8" autocomplete="new-password" required>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<div class="modal-actions">
|
||||||
|
<button class="btn btn-primary" type="submit">
|
||||||
|
<span class="material-symbols-outlined">person_add</span>
|
||||||
|
Tạo user
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="table-panel">
|
||||||
|
<div class="page-filters inline">
|
||||||
|
<label class="filter-field">
|
||||||
|
<span>Role</span>
|
||||||
|
<select data-filter-select data-filter-column="role" data-filter-table="usersTable">
|
||||||
|
<option value="">Tất cả</option>
|
||||||
|
<option value="Admin">Admin</option>
|
||||||
|
<option value="User">User</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label class="filter-field">
|
||||||
|
<span>Status</span>
|
||||||
|
<select data-filter-select data-filter-column="status" data-filter-table="usersTable">
|
||||||
|
<option value="">Tất cả</option>
|
||||||
|
<option value="Active">Active</option>
|
||||||
|
<option value="Inactive">Inactive</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label class="filter-field wide">
|
||||||
|
<span>Search</span>
|
||||||
|
<input type="search" placeholder="Tìm theo username, email, họ tên..." data-table-search="usersTable">
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table id="usersTable" class="data-table users-table">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>User</th>
|
||||||
|
<th>Email</th>
|
||||||
|
<th>Role</th>
|
||||||
|
<th>Status</th>
|
||||||
|
<th>Created</th>
|
||||||
|
<th>Owned data</th>
|
||||||
|
<th>Session</th>
|
||||||
|
<th class="action-col">Actions</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<% if (users.length === 0) { %>
|
||||||
|
<tr>
|
||||||
|
<td colspan="8" class="table-empty">Chưa có user nào.</td>
|
||||||
|
</tr>
|
||||||
|
<% } %>
|
||||||
|
<% users.forEach((user) => { %>
|
||||||
|
<tr
|
||||||
|
data-search="<%= `${user.username} ${user.email} ${user.fullName}`.toLowerCase() %>"
|
||||||
|
data-role="<%= user.role %>"
|
||||||
|
data-status="<%= user.status %>"
|
||||||
|
data-user-id="<%= user.id %>"
|
||||||
|
data-user-name="<%= user.name %>"
|
||||||
|
data-user-username="<%= user.username %>"
|
||||||
|
data-user-email="<%= user.email %>"
|
||||||
|
data-user-full-name="<%= user.fullName %>"
|
||||||
|
data-user-role="<%= user.role %>"
|
||||||
|
data-user-status="<%= user.status %>"
|
||||||
|
data-user-active="<%= user.isActive ? 'true' : 'false' %>"
|
||||||
|
data-user-created-at="<%= user.createdAt %>"
|
||||||
|
data-user-updated-at="<%= user.updatedAt %>"
|
||||||
|
data-user-package-count="<%= user.packageCount %>"
|
||||||
|
data-user-application-count="<%= user.applicationCount %>"
|
||||||
|
data-user-document-count="<%= user.documentCount %>"
|
||||||
|
>
|
||||||
|
<td>
|
||||||
|
<span class="table-title"><%= user.name %></span>
|
||||||
|
<span class="table-subtitle"><%= user.username %></span>
|
||||||
|
</td>
|
||||||
|
<td><%= user.email %></td>
|
||||||
|
<td><span class="badge <%= helpers.statusClass(user.role) %>"><%= user.role %></span></td>
|
||||||
|
<td><span class="badge <%= helpers.statusClass(user.status) %>"><%= user.status %></span></td>
|
||||||
|
<td><%= user.createdAt %></td>
|
||||||
|
<td>
|
||||||
|
<span class="table-subtitle"><%= user.packageCount %> packages</span>
|
||||||
|
<span class="table-subtitle"><%= user.applicationCount %> apps</span>
|
||||||
|
<span class="table-subtitle"><%= user.documentCount %> tài liệu</span>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<% if (user.id === currentUser.id) { %>
|
||||||
|
<span class="badge badge-muted">Đang đăng nhập</span>
|
||||||
|
<% } else { %>
|
||||||
|
<span class="table-subtitle">-</span>
|
||||||
|
<% } %>
|
||||||
|
</td>
|
||||||
|
<td class="action-col">
|
||||||
|
<div class="user-actions">
|
||||||
|
<button class="icon-button subtle" type="button" title="Xem user" aria-label="Xem user <%= user.username %>" data-user-view>
|
||||||
|
<span class="material-symbols-outlined">visibility</span>
|
||||||
|
</button>
|
||||||
|
<button class="icon-button subtle" type="button" title="Sửa user" aria-label="Sửa user <%= user.username %>" data-user-edit <%= user.id === currentUser.id ? 'data-current-user="true"' : '' %>>
|
||||||
|
<span class="material-symbols-outlined">edit</span>
|
||||||
|
</button>
|
||||||
|
<% if (user.id !== currentUser.id) { %>
|
||||||
|
<form method="post" action="/users/<%= user.id %>/delete" data-confirm-submit="Xóa user <%= user.username %>? Thao tác này không thể hoàn tác.">
|
||||||
|
<button class="icon-button danger" type="submit" title="Xóa user" aria-label="Xóa user <%= user.username %>">
|
||||||
|
<span class="material-symbols-outlined">delete</span>
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
<% } %>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<% }) %>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
<div class="page-pager">
|
||||||
|
<span>Showing 1-<%= users.length %> of <%= users.length %></span>
|
||||||
|
<div>
|
||||||
|
<button type="button" disabled>Prev</button>
|
||||||
|
<span>Page 1 / 1</span>
|
||||||
|
<button type="button" disabled>Next</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<div id="userDetailModal" class="modal-backdrop" role="dialog" aria-modal="true" aria-labelledby="userDetailTitle">
|
||||||
|
<div class="modal-content">
|
||||||
|
<div class="modal-header">
|
||||||
|
<h3 id="userDetailTitle">Thông tin user</h3>
|
||||||
|
<button class="icon-button subtle" type="button" data-modal-close aria-label="Đóng">
|
||||||
|
<span class="material-symbols-outlined">close</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div class="modal-form">
|
||||||
|
<dl class="detail-list user-detail-list">
|
||||||
|
<div>
|
||||||
|
<dt>Họ tên</dt>
|
||||||
|
<dd data-user-detail="name"></dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt>Username</dt>
|
||||||
|
<dd data-user-detail="username"></dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt>Email</dt>
|
||||||
|
<dd data-user-detail="email"></dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt>Mật khẩu</dt>
|
||||||
|
<dd>Không hiển thị. Có thể đặt lại trong phần Sửa user.</dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt>Role</dt>
|
||||||
|
<dd data-user-detail="role"></dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt>Status</dt>
|
||||||
|
<dd data-user-detail="status"></dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt>Created</dt>
|
||||||
|
<dd data-user-detail="createdAt"></dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt>Updated</dt>
|
||||||
|
<dd data-user-detail="updatedAt"></dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt>Owned data</dt>
|
||||||
|
<dd data-user-detail="ownedData"></dd>
|
||||||
|
</div>
|
||||||
|
</dl>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="editUserModal" class="modal-backdrop" role="dialog" aria-modal="true" aria-labelledby="editUserTitle">
|
||||||
|
<div class="modal-content">
|
||||||
|
<div class="modal-header">
|
||||||
|
<h3 id="editUserTitle">Sửa user</h3>
|
||||||
|
<button class="icon-button subtle" type="button" data-modal-close aria-label="Đóng">
|
||||||
|
<span class="material-symbols-outlined">close</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<form id="editUserForm" class="modal-form" method="post" action="/users">
|
||||||
|
<div class="form-stack">
|
||||||
|
<label class="form-field">
|
||||||
|
<span>Username</span>
|
||||||
|
<input type="text" name="username" required data-edit-user-field="username">
|
||||||
|
</label>
|
||||||
|
<label class="form-field">
|
||||||
|
<span>Họ tên</span>
|
||||||
|
<input type="text" name="fullName" data-edit-user-field="fullName">
|
||||||
|
</label>
|
||||||
|
<label class="form-field">
|
||||||
|
<span>Email</span>
|
||||||
|
<input type="email" name="email" required data-edit-user-field="email">
|
||||||
|
</label>
|
||||||
|
<label class="form-field">
|
||||||
|
<span>Role</span>
|
||||||
|
<select name="role" data-edit-user-field="role">
|
||||||
|
<option value="User">User</option>
|
||||||
|
<option value="Admin">Admin</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label class="form-field">
|
||||||
|
<span>Mật khẩu mới</span>
|
||||||
|
<input type="password" name="newPassword" minlength="8" autocomplete="new-password" data-edit-user-field="newPassword">
|
||||||
|
</label>
|
||||||
|
<label class="form-field">
|
||||||
|
<span>Xác nhận mật khẩu mới</span>
|
||||||
|
<input type="password" name="confirmPassword" minlength="8" autocomplete="new-password" data-edit-user-field="confirmPassword">
|
||||||
|
</label>
|
||||||
|
<label class="inline-checkbox edit-active-toggle">
|
||||||
|
<input class="checkbox" type="checkbox" name="isActive" data-edit-user-field="isActive">
|
||||||
|
Active
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<div class="modal-actions">
|
||||||
|
<button class="btn btn-secondary" type="button" data-modal-close>Hủy</button>
|
||||||
|
<button class="btn btn-primary" type="submit">
|
||||||
|
<span class="material-symbols-outlined">save</span>
|
||||||
|
Lưu
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<%- include('partials/page-end') %>
|
||||||
Reference in New Issue
Block a user