feat(queries): 完成 M04 查询定义与版本激活
交付不可变查询版本、保存即生效与激活(D26),并带控制台列表筛选排序与试跑预览;补 RLS 下 current_version_no 回填迁移。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
8c0335040f
commit
21cc721fcc
97 files changed
+13354
-153
No files matched your search
@@ -197,7 +197,39 @@ async function mockDatasources(page: Page, rows: Row[] = seedRows()): Promise<Mo
|
||||
}
|
||||
if (parts.length === 1) {
|
||||
if (method === "GET") {
|
||||
return json(200, ok({ items: mock.rows }));
|
||||
const name = (url.searchParams.get("name") || "").trim().toLowerCase();
|
||||
const engine = url.searchParams.get("engine") || "";
|
||||
const enabledParam = url.searchParams.get("enabled");
|
||||
const page = Number(url.searchParams.get("page") || "1");
|
||||
const pageSize = Number(url.searchParams.get("page_size") || "20");
|
||||
const sortBy = url.searchParams.get("sort_by") || "created_at";
|
||||
const sortOrder = url.searchParams.get("sort_order") || "asc";
|
||||
let rows = [...mock.rows];
|
||||
if (name) {
|
||||
rows = rows.filter((item) => item.name.toLowerCase().includes(name));
|
||||
}
|
||||
if (engine) {
|
||||
rows = rows.filter((item) => item.engine === engine);
|
||||
}
|
||||
if (enabledParam === "true") {
|
||||
rows = rows.filter((item) => item.enabled);
|
||||
}
|
||||
if (enabledParam === "false") {
|
||||
rows = rows.filter((item) => !item.enabled);
|
||||
}
|
||||
const dir = sortOrder === "asc" ? 1 : -1;
|
||||
rows.sort((a, b) => {
|
||||
const av = (a as Record<string, unknown>)[sortBy];
|
||||
const bv = (b as Record<string, unknown>)[sortBy];
|
||||
if (av === bv) return 0;
|
||||
if (av == null) return 1;
|
||||
if (bv == null) return -1;
|
||||
return av < bv ? -dir : dir;
|
||||
});
|
||||
const total = rows.length;
|
||||
const start = Math.max(0, (page - 1) * pageSize);
|
||||
const items = rows.slice(start, start + pageSize);
|
||||
return json(200, ok({ items, total, page, page_size: pageSize }));
|
||||
}
|
||||
const created = row({ id: "55555555-5555-4555-8555-555555555555", name: "x" });
|
||||
Object.assign(created, body, { secret_configured: true });
|
||||
@@ -262,11 +294,13 @@ test.describe("datasources console", () => {
|
||||
|
||||
await expect(page.getByTestId("datasource-table")).toBeVisible();
|
||||
const crumb = page.getByTestId("breadcrumb");
|
||||
await expect(crumb).toContainText("Watchman");
|
||||
await expect(crumb).toContainText("预警平台");
|
||||
await expect(crumb).toContainText("数据源");
|
||||
await expect(crumb).not.toContainText("新建");
|
||||
await expect(crumb).not.toContainText("详情");
|
||||
await expect(page.getByTestId("nav-datasources")).toBeVisible();
|
||||
await expect(page.getByTestId("side-logo")).toBeVisible();
|
||||
await expect(page.getByTestId("side-user").getByTestId("shell-welcome")).toBeVisible();
|
||||
|
||||
for (const header of ["名称", "引擎", "主机", "端口", "库名", "用户名", "状态", "最近测试", "操作"]) {
|
||||
await expect(page.locator(".el-table__header").getByText(header, { exact: true })).toBeVisible();
|
||||
@@ -275,6 +309,9 @@ test.describe("datasources console", () => {
|
||||
await expect(page.getByTestId("datasource-table")).toContainText("SQL Server");
|
||||
await expect(page.getByTestId("datasource-table")).toContainText("2026-11-17");
|
||||
await expect(page.getByTestId("datasource-table")).toContainText("尚未测试");
|
||||
await expect(page.getByTestId("datasource-pagination")).toBeVisible();
|
||||
await expect(page.getByTestId("datasource-filter-search")).toBeVisible();
|
||||
await expect(page.getByTestId("datasource-filter-reset")).toBeVisible();
|
||||
|
||||
// 新建 sits above the table, right aligned.
|
||||
const create = await page.getByTestId("datasource-create").boundingBox();
|
||||
|
||||
@@ -0,0 +1,967 @@
|
||||
import { expect, test, type Page, type Route } from "@playwright/test";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const evidenceDir = path.resolve(
|
||||
path.dirname(fileURLToPath(import.meta.url)),
|
||||
"../../../../docs/evidence/M04/ui",
|
||||
);
|
||||
|
||||
// Synthetic data only. The API is mocked; no source database or secret is involved.
|
||||
const SERVER_TEXT = "FATAL: driver said something private";
|
||||
|
||||
type Draft = {
|
||||
sql_template: string;
|
||||
param_schema: Record<string, unknown>[];
|
||||
output_schema: Record<string, unknown>[];
|
||||
allowed_identifiers: string[];
|
||||
timeout_ms: number;
|
||||
max_rows: number;
|
||||
};
|
||||
|
||||
type Def = {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string | null;
|
||||
datasource_id: string;
|
||||
enabled: boolean;
|
||||
current_version_no: number | null;
|
||||
latest_version_no: number | null;
|
||||
latest_published_version_no: number | null;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
current: Draft;
|
||||
};
|
||||
|
||||
type Ver = Draft & {
|
||||
id: string;
|
||||
definition_id: string;
|
||||
version_no: number;
|
||||
published_at: string;
|
||||
published_by: string;
|
||||
};
|
||||
|
||||
const DS_ONE = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
|
||||
const DS_TWO = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb";
|
||||
const DS_OFF = "cccccccc-cccc-4ccc-8ccc-cccccccccccc";
|
||||
const Q_ONE = "11111111-1111-4111-8111-111111111111";
|
||||
const Q_TWO = "22222222-2222-4222-8222-222222222222";
|
||||
const Q_OFF = "33333333-3333-4333-8333-333333333333";
|
||||
const Q_NEW = "55555555-5555-4555-8555-555555555555";
|
||||
|
||||
function datasourceRows() {
|
||||
const base = {
|
||||
description: null,
|
||||
kind: "database",
|
||||
engine: "postgresql",
|
||||
host: "db.example.test",
|
||||
port: 5432,
|
||||
database_name: "process_demo",
|
||||
username: "readonly_demo",
|
||||
secret_configured: true,
|
||||
read_only_intent: true,
|
||||
circuit_state: "closed",
|
||||
circuit_opened_at: null,
|
||||
circuit_open_until: null,
|
||||
circuit_failure_window_seconds: 300,
|
||||
circuit_failure_threshold: 3,
|
||||
circuit_open_cooldown_seconds: 600,
|
||||
last_test_category: null,
|
||||
last_test_at: null,
|
||||
last_test_message: null,
|
||||
created_at: "2026-11-17T01:00:00+00:00",
|
||||
updated_at: "2026-11-17T01:00:00+00:00",
|
||||
};
|
||||
return [
|
||||
{ ...base, id: DS_ONE, name: "产线工艺库", enabled: true },
|
||||
{ ...base, id: DS_TWO, name: "设备台账库", enabled: true },
|
||||
{ ...base, id: DS_OFF, name: "历史归档库", enabled: false },
|
||||
];
|
||||
}
|
||||
|
||||
const SQL_ONE =
|
||||
"SELECT lot_no, temperature, phone\nFROM process_readings\nWHERE line_code = :line_code";
|
||||
|
||||
function draftOne(): Draft {
|
||||
return {
|
||||
sql_template: SQL_ONE,
|
||||
param_schema: [
|
||||
{ name: "line_code", type: "string", required: true },
|
||||
{ name: "min_temp", type: "number", required: false, default: 0 },
|
||||
],
|
||||
output_schema: [
|
||||
{ name: "lot_no", type: "string" },
|
||||
{ name: "temperature", type: "number" },
|
||||
{ name: "phone", type: "string" },
|
||||
],
|
||||
allowed_identifiers: ["process_readings"],
|
||||
timeout_ms: 5000,
|
||||
max_rows: 200,
|
||||
};
|
||||
}
|
||||
|
||||
function def(overrides: Partial<Def> & Pick<Def, "id" | "name">): Def {
|
||||
return {
|
||||
description: "示例(虚构)",
|
||||
datasource_id: DS_ONE,
|
||||
enabled: true,
|
||||
current_version_no: 1,
|
||||
latest_version_no: 1,
|
||||
latest_published_version_no: 1,
|
||||
created_at: "2026-11-17T01:00:00+00:00",
|
||||
updated_at: "2026-11-18T01:40:00+00:00",
|
||||
current: draftOne(),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function seedDefs(): Def[] {
|
||||
return [
|
||||
def({ id: Q_ONE, name: "产线温度采样", current_version_no: 1, latest_version_no: 1 }),
|
||||
def({
|
||||
id: Q_TWO,
|
||||
name: "设备停机记录",
|
||||
datasource_id: DS_TWO,
|
||||
current: {
|
||||
...draftOne(),
|
||||
sql_template: "SELECT 1",
|
||||
param_schema: [],
|
||||
output_schema: [],
|
||||
allowed_identifiers: [],
|
||||
},
|
||||
}),
|
||||
def({ id: Q_OFF, name: "质检不良统计", enabled: false }),
|
||||
];
|
||||
}
|
||||
|
||||
function seedVersions(): Ver[] {
|
||||
return [
|
||||
{
|
||||
...draftOne(),
|
||||
id: "v-1",
|
||||
definition_id: Q_ONE,
|
||||
version_no: 1,
|
||||
published_at: "2026-11-18T01:40:00+00:00",
|
||||
published_by: "admin.demo",
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
function ok(data: unknown): string {
|
||||
return JSON.stringify({ success: true, data, request_id: "pw-q" });
|
||||
}
|
||||
|
||||
function fail(code: number, message: string, details: Record<string, unknown> = {}): string {
|
||||
return JSON.stringify({
|
||||
success: false,
|
||||
error: { code, message, details, retryable: false },
|
||||
request_id: "pw-q",
|
||||
});
|
||||
}
|
||||
|
||||
type Outcome = { status: number; body: string; delayMs: number };
|
||||
|
||||
type Mock = {
|
||||
defs: Def[];
|
||||
versions: Ver[];
|
||||
requests: { method: string; pathname: string; body: unknown }[];
|
||||
preview: Outcome;
|
||||
};
|
||||
|
||||
const SUCCESS_BODY = ok({
|
||||
id: Q_ONE,
|
||||
version_no: 1,
|
||||
source: "current",
|
||||
status: "success",
|
||||
message: "query succeeded",
|
||||
columns: ["lot_no", "temperature", "phone"],
|
||||
rows: [
|
||||
{ lot_no: "LOT-1001", temperature: 71.2, phone: "***" },
|
||||
{ lot_no: "LOT-1002", temperature: 72, phone: null },
|
||||
],
|
||||
row_count: 2,
|
||||
masked_columns: ["phone"],
|
||||
});
|
||||
|
||||
function previewBody(data: Record<string, unknown>): string {
|
||||
return ok({ id: Q_ONE, version_no: 1, source: "current", message: "m", ...data });
|
||||
}
|
||||
|
||||
async function signIn(page: Page, roles: string[]): Promise<void> {
|
||||
await page.route("**/auth/me", async (route) => {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: "application/json",
|
||||
body: ok({ subject: "user-1", display_name: "Worker", roles }),
|
||||
});
|
||||
});
|
||||
await page.route("**/health", async (route) => {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: "application/json",
|
||||
body: ok({ status: "ok", app: "watchman", version: "0.1.0" }),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function summary(row: Def): Omit<Def, "current"> {
|
||||
const { current: _current, ...rest } = row;
|
||||
return rest;
|
||||
}
|
||||
|
||||
function versionSummary(row: Ver) {
|
||||
return {
|
||||
id: row.id,
|
||||
definition_id: row.definition_id,
|
||||
version_no: row.version_no,
|
||||
published_at: row.published_at,
|
||||
published_by: row.published_by,
|
||||
};
|
||||
}
|
||||
|
||||
/** Mocks /queries and the datasource list. Page source files under /src/... never match. */
|
||||
async function mockApi(page: Page, defs: Def[] = seedDefs(), versions: Ver[] = seedVersions()): Promise<Mock> {
|
||||
const mock: Mock = {
|
||||
defs,
|
||||
versions,
|
||||
requests: [],
|
||||
preview: { status: 200, delayMs: 0, body: SUCCESS_BODY },
|
||||
};
|
||||
const sources = datasourceRows();
|
||||
const matcher = (url: URL) =>
|
||||
/^\/datasources$/.test(url.pathname) ||
|
||||
/^\/queries(\/[^/]+(\/(enable|disable|preview|references|versions(\/\d+(\/(preview|activate))?)?))?)?$/.test(
|
||||
url.pathname,
|
||||
);
|
||||
await page.route(matcher, async (route: Route) => {
|
||||
const request = route.request();
|
||||
const url = new URL(request.url());
|
||||
const method = request.method();
|
||||
let body: unknown = null;
|
||||
if (method === "POST" || method === "PATCH") {
|
||||
body = request.postData() ? request.postDataJSON() : null;
|
||||
}
|
||||
mock.requests.push({ method, pathname: url.pathname, body });
|
||||
const json = (status: number, text: string) =>
|
||||
route.fulfill({ status, contentType: "application/json", body: text });
|
||||
const parts = url.pathname.split("/").filter(Boolean);
|
||||
if (parts[0] === "datasources") {
|
||||
const page = Number(url.searchParams.get("page") || "1");
|
||||
const pageSize = Number(url.searchParams.get("page_size") || "20");
|
||||
return json(
|
||||
200,
|
||||
ok({ items: sources, total: sources.length, page, page_size: pageSize }),
|
||||
);
|
||||
}
|
||||
if (parts.length === 1) {
|
||||
if (method === "GET") {
|
||||
const name = (url.searchParams.get("name") || "").trim().toLowerCase();
|
||||
const datasourceId = url.searchParams.get("datasource_id") || "";
|
||||
const enabledParam = url.searchParams.get("enabled");
|
||||
const page = Number(url.searchParams.get("page") || "1");
|
||||
const pageSize = Number(url.searchParams.get("page_size") || "20");
|
||||
const sortBy = url.searchParams.get("sort_by") || "updated_at";
|
||||
const sortOrder = url.searchParams.get("sort_order") || "desc";
|
||||
let rows = mock.defs.map(summary);
|
||||
if (name) {
|
||||
rows = rows.filter((item) => item.name.toLowerCase().includes(name));
|
||||
}
|
||||
if (datasourceId) {
|
||||
rows = rows.filter((item) => item.datasource_id === datasourceId);
|
||||
}
|
||||
if (enabledParam === "true") {
|
||||
rows = rows.filter((item) => item.enabled);
|
||||
}
|
||||
if (enabledParam === "false") {
|
||||
rows = rows.filter((item) => !item.enabled);
|
||||
}
|
||||
const dir = sortOrder === "asc" ? 1 : -1;
|
||||
rows = [...rows].sort((a, b) => {
|
||||
const av = (a as Record<string, unknown>)[sortBy === "datasource_name" ? "datasource_id" : sortBy];
|
||||
const bv = (b as Record<string, unknown>)[sortBy === "datasource_name" ? "datasource_id" : sortBy];
|
||||
if (av === bv) return 0;
|
||||
if (av == null) return 1;
|
||||
if (bv == null) return -1;
|
||||
return av < bv ? -dir : dir;
|
||||
});
|
||||
const total = rows.length;
|
||||
const start = Math.max(0, (page - 1) * pageSize);
|
||||
const items = rows.slice(start, start + pageSize);
|
||||
return json(200, ok({ items, total, page, page_size: pageSize }));
|
||||
}
|
||||
const payload = body as Record<string, unknown>;
|
||||
if (mock.defs.some((item) => item.name === payload.name)) {
|
||||
return json(409, fail(40000, "Query name already exists", { reason: "duplicate_name" }));
|
||||
}
|
||||
const content = {
|
||||
sql_template: String(payload.sql_template),
|
||||
param_schema: payload.param_schema as Record<string, unknown>[],
|
||||
output_schema: payload.output_schema as Record<string, unknown>[],
|
||||
allowed_identifiers: payload.allowed_identifiers as string[],
|
||||
timeout_ms: Number(payload.timeout_ms),
|
||||
max_rows: Number(payload.max_rows),
|
||||
};
|
||||
const created = def({
|
||||
id: Q_NEW,
|
||||
name: String(payload.name),
|
||||
description: (payload.description as string | null) ?? null,
|
||||
datasource_id: String(payload.datasource_id),
|
||||
current: content,
|
||||
current_version_no: 1,
|
||||
latest_version_no: 1,
|
||||
latest_published_version_no: 1,
|
||||
});
|
||||
mock.defs.push(created);
|
||||
mock.versions.push({
|
||||
...content,
|
||||
id: `v-${Q_NEW}-1`,
|
||||
definition_id: Q_NEW,
|
||||
version_no: 1,
|
||||
published_at: "2026-11-18T02:00:00+00:00",
|
||||
published_by: "admin.demo",
|
||||
});
|
||||
return json(200, ok({ ...summary(created), current: created.current }));
|
||||
}
|
||||
const found = mock.defs.find((item) => item.id === parts[1]);
|
||||
if (!found) {
|
||||
return json(404, fail(40000, "Query not found", { reason: "not_found" }));
|
||||
}
|
||||
const full = () => ok({ ...summary(found), current: found.current });
|
||||
const action = parts[2];
|
||||
if (!action) {
|
||||
if (method === "GET") {
|
||||
return json(200, full());
|
||||
}
|
||||
const patch = body as Record<string, unknown>;
|
||||
if (mock.defs.some((item) => item.name === patch.name && item.id !== found.id)) {
|
||||
return json(409, fail(40000, "Query name already exists", { reason: "duplicate_name" }));
|
||||
}
|
||||
if (
|
||||
"sql_template" in patch ||
|
||||
"param_schema" in patch ||
|
||||
"output_schema" in patch ||
|
||||
"timeout_ms" in patch ||
|
||||
"max_rows" in patch
|
||||
) {
|
||||
return json(400, fail(40000, "use save version", { reason: "use_save_version" }));
|
||||
}
|
||||
found.name = String(patch.name ?? found.name);
|
||||
found.description = (patch.description as string | null) ?? null;
|
||||
found.datasource_id = String(patch.datasource_id ?? found.datasource_id);
|
||||
return json(200, full());
|
||||
}
|
||||
if (action === "enable" || action === "disable") {
|
||||
found.enabled = action === "enable";
|
||||
return json(200, full());
|
||||
}
|
||||
if (action === "references") {
|
||||
return json(200, ok({ id: found.id, items: [] }));
|
||||
}
|
||||
const own = mock.versions
|
||||
.filter((item) => item.definition_id === found.id)
|
||||
.sort((a, b) => b.version_no - a.version_no);
|
||||
if (action === "versions" && parts.length === 3) {
|
||||
if (method === "POST") {
|
||||
const payload = body as Record<string, unknown>;
|
||||
const next = (found.latest_version_no ?? 0) + 1;
|
||||
const content = {
|
||||
sql_template: String(payload.sql_template),
|
||||
param_schema: (payload.param_schema as Record<string, unknown>[]) ?? [],
|
||||
output_schema: (payload.output_schema as Record<string, unknown>[]) ?? [],
|
||||
allowed_identifiers: (payload.allowed_identifiers as string[]) ?? [],
|
||||
timeout_ms: Number(payload.timeout_ms ?? 10000),
|
||||
max_rows: Number(payload.max_rows ?? 100),
|
||||
};
|
||||
const version: Ver = {
|
||||
...content,
|
||||
id: `v-${found.id}-${next}`,
|
||||
definition_id: found.id,
|
||||
version_no: next,
|
||||
published_at: "2026-11-18T02:00:00+00:00",
|
||||
published_by: "admin.demo",
|
||||
};
|
||||
mock.versions.push(version);
|
||||
found.current = content;
|
||||
found.current_version_no = next;
|
||||
found.latest_version_no = next;
|
||||
found.latest_published_version_no = next;
|
||||
return json(200, ok(version));
|
||||
}
|
||||
return json(200, ok({ id: found.id, items: own.map(versionSummary) }));
|
||||
}
|
||||
if (action === "versions" && parts.length === 4) {
|
||||
const frozen = own.find((item) => item.version_no === Number(parts[3]));
|
||||
return frozen ? json(200, ok(frozen)) : json(404, fail(40000, "Query version not found", { reason: "not_found" }));
|
||||
}
|
||||
if (action === "versions" && parts[4] === "activate") {
|
||||
const no = Number(parts[3]);
|
||||
const frozen = own.find((item) => item.version_no === no);
|
||||
if (!frozen) {
|
||||
return json(404, fail(40000, "Query version not found", { reason: "not_found" }));
|
||||
}
|
||||
found.current_version_no = no;
|
||||
found.current = {
|
||||
sql_template: frozen.sql_template,
|
||||
param_schema: frozen.param_schema,
|
||||
output_schema: frozen.output_schema,
|
||||
allowed_identifiers: frozen.allowed_identifiers,
|
||||
timeout_ms: frozen.timeout_ms,
|
||||
max_rows: frozen.max_rows,
|
||||
};
|
||||
return json(200, full());
|
||||
}
|
||||
if (action === "preview" || parts[4] === "preview") {
|
||||
if (!found.enabled) {
|
||||
return json(409, fail(40000, "Query is disabled", { reason: "disabled" }));
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, mock.preview.delayMs));
|
||||
return json(mock.preview.status, mock.preview.body);
|
||||
}
|
||||
return json(404, fail(40000, "Not found", { reason: "not_found" }));
|
||||
});
|
||||
return mock;
|
||||
}
|
||||
|
||||
async function pickDatasource(page: Page, name: string): Promise<void> {
|
||||
await page.getByTestId("field-datasource").locator(".el-select__wrapper").click();
|
||||
await page.getByRole("option", { name }).click();
|
||||
}
|
||||
|
||||
async function confirmDialog(page: Page): Promise<void> {
|
||||
await page.locator(".el-message-box__btns .el-button--primary").click();
|
||||
}
|
||||
|
||||
async function fillCreateForm(page: Page, name: string): Promise<void> {
|
||||
await page.getByTestId("field-name").locator("input").fill(name);
|
||||
await pickDatasource(page, "设备台账库");
|
||||
await page.getByTestId("field-sql").locator("textarea").fill("SELECT lot_no FROM {{process_readings}} WHERE line_code = :line_code");
|
||||
await page.getByTestId("param-add").click();
|
||||
await page.getByTestId("param-name").fill("line_code");
|
||||
await page.getByTestId("output-add").click();
|
||||
await page.getByTestId("output-name").fill("lot_no");
|
||||
await page.getByTestId("identifier-input").fill("process_readings");
|
||||
await page.getByTestId("identifier-add").click();
|
||||
}
|
||||
|
||||
test.describe("queries console", () => {
|
||||
test("a viewer and an operator see 无法进入查询 and no request is made", async ({ page }) => {
|
||||
await signIn(page, ["watchman-viewer"]);
|
||||
const mock = await mockApi(page);
|
||||
await page.goto("/#/queries");
|
||||
await expect(page.getByTestId("query-denied")).toContainText("无法进入查询");
|
||||
await expect(page.getByTestId("breadcrumb")).toContainText("查询");
|
||||
await expect(page.getByTestId("query-table")).toHaveCount(0);
|
||||
await expect(page.getByTestId("query-create")).toHaveCount(0);
|
||||
await page.screenshot({ path: path.join(evidenceDir, "query-denied-viewer.png"), fullPage: true });
|
||||
|
||||
// Deep links are gated too, and the breadcrumb stays at the list level.
|
||||
await page.goto(`/#/queries/${Q_ONE}`);
|
||||
await expect(page.getByTestId("query-denied")).toBeVisible();
|
||||
await page.goto("/#/queries/new");
|
||||
await expect(page.getByTestId("query-denied")).toBeVisible();
|
||||
await expect(page.getByTestId("breadcrumb")).not.toContainText("新建");
|
||||
await page.goto(`/#/queries/${Q_ONE}/versions/1`);
|
||||
await expect(page.getByTestId("query-denied")).toBeVisible();
|
||||
await expect(page.getByTestId("breadcrumb")).not.toContainText("版本");
|
||||
expect(mock.requests).toHaveLength(0);
|
||||
|
||||
await page.unroute("**/auth/me");
|
||||
await signIn(page, ["watchman-operator"]);
|
||||
await page.goto("/#/queries");
|
||||
await page.reload();
|
||||
await expect(page.getByTestId("query-denied")).toBeVisible();
|
||||
expect(mock.requests).toHaveLength(0);
|
||||
});
|
||||
|
||||
test("empty list shows the empty state with 新建 above it", async ({ page }) => {
|
||||
await signIn(page, ["watchman-admin"]);
|
||||
await mockApi(page, [], []);
|
||||
await page.goto("/#/queries");
|
||||
await expect(page.getByTestId("query-empty")).toContainText("还没有查询");
|
||||
await expect(page.getByTestId("query-create")).toBeVisible();
|
||||
const create = (await page.getByTestId("query-create").boundingBox())!;
|
||||
const empty = (await page.getByTestId("query-empty").boundingBox())!;
|
||||
expect(create.y + create.height).toBeLessThanOrEqual(empty.y);
|
||||
await page.screenshot({ path: path.join(evidenceDir, "query-empty.png"), fullPage: true });
|
||||
});
|
||||
|
||||
test("admin list: breadcrumb, 新建 above the table, columns, disabled row", async ({ page }) => {
|
||||
await signIn(page, ["watchman-admin"]);
|
||||
await mockApi(page);
|
||||
await page.goto("/#/queries");
|
||||
|
||||
await expect(page.getByTestId("query-table")).toBeVisible();
|
||||
await expect(page.getByTestId("nav-queries")).toBeVisible();
|
||||
const crumb = page.getByTestId("breadcrumb");
|
||||
await expect(crumb).toContainText("预警平台");
|
||||
await expect(crumb).toContainText("查询");
|
||||
await expect(crumb).not.toContainText("新建");
|
||||
await expect(crumb).not.toContainText("详情");
|
||||
// No page title repeated under the breadcrumb.
|
||||
await expect(page.getByRole("heading")).toHaveCount(0);
|
||||
await expect(page.getByTestId("side-logo")).toBeVisible();
|
||||
await expect(page.getByTestId("side-user").getByTestId("shell-welcome")).toBeVisible();
|
||||
await expect(page.getByTestId("side-user").getByTestId("logout")).toBeVisible();
|
||||
|
||||
for (const header of ["名称", "数据源", "状态", "当前版本", "更新时间", "操作"]) {
|
||||
await expect(page.locator(".el-table__header").getByText(header, { exact: true })).toBeVisible();
|
||||
}
|
||||
const table = page.getByTestId("query-table");
|
||||
await expect(table).toContainText("产线温度采样");
|
||||
await expect(table).toContainText("产线工艺库");
|
||||
await expect(table).toContainText("v1");
|
||||
await expect(table).toContainText("2026-11-18");
|
||||
await expect(page.getByTestId(`query-row-${Q_ONE}`).getByTestId("row-switch-version")).toBeVisible();
|
||||
await expect(page.getByTestId("query-pagination")).toBeVisible();
|
||||
|
||||
const create = (await page.getByTestId("query-create").boundingBox())!;
|
||||
const box = (await table.boundingBox())!;
|
||||
expect(create.y + create.height).toBeLessThanOrEqual(box.y);
|
||||
expect(create.x + create.width).toBeGreaterThan(box.x + box.width - 40);
|
||||
await expect(page.getByTestId("query-footer")).toHaveCount(0);
|
||||
|
||||
await expect(page.getByTestId("query-list-toolbar")).toBeVisible();
|
||||
await expect(page.getByTestId("query-filter-name")).toBeVisible();
|
||||
await expect(page.getByTestId("query-filter-datasource")).toBeVisible();
|
||||
await expect(page.getByTestId("query-filter-status")).toBeVisible();
|
||||
await expect(page.getByTestId("query-filter-search")).toBeVisible();
|
||||
await expect(page.getByTestId("query-filter-reset")).toBeVisible();
|
||||
// Draft filters do not apply until 查询 is clicked.
|
||||
await page.getByTestId("query-filter-name").getByRole("textbox").fill("温度");
|
||||
await expect(table).toContainText("质检不良统计");
|
||||
await page.getByTestId("query-filter-search").click();
|
||||
await expect(table).toContainText("产线温度采样");
|
||||
await expect(table).not.toContainText("质检不良统计");
|
||||
await page.getByTestId("query-filter-reset").click();
|
||||
await expect(table).toContainText("质检不良统计");
|
||||
|
||||
// Disabled row: visible, 预览 disabled with a title, 打开 still works.
|
||||
const off = page.getByTestId(`query-row-${Q_OFF}`);
|
||||
await expect(off).toBeVisible();
|
||||
await expect(off.getByTestId("row-preview")).toBeDisabled();
|
||||
await expect(off.getByTestId("row-preview")).toHaveAttribute("title", "已停用,不能预览");
|
||||
await expect(off.getByTestId("row-open")).toBeEnabled();
|
||||
const live = page.getByTestId(`query-row-${Q_ONE}`);
|
||||
await expect(live.getByTestId("row-preview")).toBeEnabled();
|
||||
|
||||
await expect(page.locator("body")).not.toContainText("正式版本进行删除");
|
||||
await expect(page.locator("body")).not.toContainText("原型");
|
||||
await page.screenshot({ path: path.join(evidenceDir, "query-list.png"), fullPage: true });
|
||||
});
|
||||
|
||||
test("create: footer, validation, then save creates v1 and opens the detail", async ({
|
||||
page,
|
||||
}) => {
|
||||
await signIn(page, ["watchman-admin"]);
|
||||
const mock = await mockApi(page);
|
||||
await page.goto("/#/queries");
|
||||
await page.getByTestId("query-create").click();
|
||||
|
||||
const crumb = page.getByTestId("breadcrumb");
|
||||
await expect(crumb).toContainText("新建");
|
||||
await expect(crumb).not.toContainText("详情");
|
||||
await expect(page.getByTestId("basic-sub")).toContainText("新建");
|
||||
await expect(page.getByTestId("versions-create-note")).toBeVisible();
|
||||
|
||||
// Create footer: 返回列表, 保存 live; 试跑预览 disabled until saved. No publish.
|
||||
await expect(page.getByTestId("footer-back")).toHaveText("返回列表");
|
||||
await expect(page.getByTestId("footer-save")).toHaveText("保存");
|
||||
await expect(page.getByTestId("footer-publish")).toHaveCount(0);
|
||||
await expect(page.getByTestId("footer-preview")).toBeDisabled();
|
||||
await expect(page.getByTestId("footer-enable")).toHaveCount(0);
|
||||
await expect(page.getByTestId("footer-disable")).toHaveCount(0);
|
||||
await expect(page.getByTestId("preview-need-save")).toBeVisible();
|
||||
|
||||
// SQL textarea is monospace.
|
||||
const font = await page
|
||||
.getByTestId("field-sql")
|
||||
.locator("textarea")
|
||||
.evaluate((el) => getComputedStyle(el).fontFamily);
|
||||
expect(font.toLowerCase()).toMatch(/mono|consolas/);
|
||||
|
||||
// A blank form does not submit.
|
||||
await page.getByTestId("footer-save").click();
|
||||
for (const field of ["name", "datasource", "sql"]) {
|
||||
await expect(page.getByTestId(`field-${field}`).locator(".el-form-item__error")).toBeVisible();
|
||||
}
|
||||
expect(mock.requests.filter((item) => item.method === "POST")).toHaveLength(0);
|
||||
|
||||
// Undeclared SQL parameter is flagged live; an invalid parameter name and a limit are refused.
|
||||
await page.getByTestId("field-sql").locator("textarea").fill("SELECT 1 WHERE a = :line_code AND b = :since");
|
||||
await expect(page.getByTestId("chip-undeclared")).toHaveCount(2);
|
||||
await expect(page.getByTestId("chip-undeclared").filter({ hasText: ":since 未声明" })).toBeVisible();
|
||||
await page.getByTestId("param-add").click();
|
||||
await page.getByTestId("param-name").fill("1bad");
|
||||
await page.getByTestId("footer-save").click();
|
||||
await expect(page.getByTestId("field-params").locator(".el-form-item__error")).toContainText("参数名不合法");
|
||||
await page.getByTestId("param-name").fill("line_code");
|
||||
await page.getByTestId("field-timeout").locator("input").fill("300001");
|
||||
await page.getByTestId("field-timeout").locator("input").press("Tab");
|
||||
await expect(page.getByTestId("field-timeout").locator(".el-form-item__error")).toContainText("1–300000");
|
||||
await page.getByTestId("field-max-rows").locator("input").fill("0");
|
||||
await page.getByTestId("field-max-rows").locator("input").press("Tab");
|
||||
await expect(page.getByTestId("field-max-rows").locator(".el-form-item__error")).toContainText("1–10000");
|
||||
await page.screenshot({ path: path.join(evidenceDir, "query-create-validation.png"), fullPage: true });
|
||||
expect(mock.requests.filter((item) => item.method === "POST")).toHaveLength(0);
|
||||
|
||||
// Happy path.
|
||||
await page.reload();
|
||||
await fillCreateForm(page, "新建演示查询");
|
||||
await page.getByTestId("field-timeout").locator("input").fill("5000");
|
||||
await page.getByTestId("field-max-rows").locator("input").fill("50");
|
||||
await page.screenshot({ path: path.join(evidenceDir, "query-create.png"), fullPage: true });
|
||||
await page.getByTestId("footer-save").click();
|
||||
|
||||
// Saved: the detail page opens with v1 current and no publish button.
|
||||
await expect(page.getByTestId("breadcrumb")).toContainText("详情");
|
||||
await expect(page.getByTestId("field-name").locator("input")).toHaveValue("新建演示查询");
|
||||
await expect(page.getByTestId("footer-publish")).toHaveCount(0);
|
||||
await expect(page.getByTestId("footer-disable")).toBeVisible();
|
||||
await expect(page.getByTestId("footer-preview")).toBeEnabled();
|
||||
await expect(page.getByTestId("basic-sub")).toContainText("当前生效 v1");
|
||||
|
||||
const post = mock.requests.find((item) => item.method === "POST" && item.pathname === "/queries");
|
||||
expect(post).toBeTruthy();
|
||||
const body = post!.body as Record<string, unknown>;
|
||||
expect(Object.keys(body).sort()).toEqual([
|
||||
"allowed_identifiers",
|
||||
"datasource_id",
|
||||
"description",
|
||||
"max_rows",
|
||||
"name",
|
||||
"output_schema",
|
||||
"param_schema",
|
||||
"sql_template",
|
||||
"timeout_ms",
|
||||
]);
|
||||
expect(body.name).toBe("新建演示查询");
|
||||
expect(body.datasource_id).toBe(DS_TWO);
|
||||
expect(body.param_schema).toEqual([{ name: "line_code", type: "string", required: true }]);
|
||||
expect(body.output_schema).toEqual([{ name: "lot_no", type: "string" }]);
|
||||
expect(body.allowed_identifiers).toEqual(["process_readings"]);
|
||||
expect(body.timeout_ms).toBe(5000);
|
||||
expect(body.max_rows).toBe(50);
|
||||
});
|
||||
|
||||
test("a disabled datasource cannot be picked", async ({ page }) => {
|
||||
await signIn(page, ["watchman-admin"]);
|
||||
await mockApi(page);
|
||||
await page.goto("/#/queries/new");
|
||||
await page.getByTestId("field-datasource").locator(".el-select__wrapper").click();
|
||||
await expect(page.getByRole("option", { name: /历史归档库/ })).toHaveClass(/is-disabled/);
|
||||
await expect(page.getByRole("option", { name: /产线工艺库/ })).not.toHaveClass(/is-disabled/);
|
||||
});
|
||||
|
||||
test("duplicate name shows the API reason on the form", async ({ page }) => {
|
||||
await signIn(page, ["watchman-admin"]);
|
||||
await mockApi(page);
|
||||
await page.goto("/#/queries/new");
|
||||
await fillCreateForm(page, "产线温度采样");
|
||||
await page.getByTestId("footer-save").click();
|
||||
await expect(page.getByTestId("query-save-error")).toContainText("名称已存在");
|
||||
await expect(page.getByTestId("query-save-error")).not.toContainText("Query name already exists");
|
||||
});
|
||||
|
||||
test("detail: footer outside the scroll area, centered, in order; sections present", async ({ page }) => {
|
||||
await page.setViewportSize({ width: 1280, height: 520 });
|
||||
await signIn(page, ["watchman-admin"]);
|
||||
await mockApi(page);
|
||||
await page.goto("/#/queries");
|
||||
await page.getByTestId(`query-row-${Q_ONE}`).getByTestId("row-open").click();
|
||||
|
||||
const crumb = page.getByTestId("breadcrumb");
|
||||
await expect(crumb).toContainText("详情");
|
||||
await expect(crumb).not.toContainText("新建");
|
||||
await expect(page.getByRole("heading", { level: 1 })).toHaveCount(0);
|
||||
await expect(page.getByTestId("field-name").locator("input")).toHaveValue("产线温度采样");
|
||||
await expect(page.getByTestId("basic-sub")).toContainText("当前生效 v1");
|
||||
await expect(page.getByTestId("status-tag")).toHaveText("启用");
|
||||
await expect(page.getByTestId("param-name").first()).toHaveValue("line_code");
|
||||
await expect(page.getByTestId("params-table").locator(".el-table__row").nth(1).getByTestId("param-default")).toHaveValue("0");
|
||||
await expect(page.getByTestId("output-name").nth(1)).toHaveValue("temperature");
|
||||
await expect(page.getByTestId("identifier-tag")).toHaveText("process_readings");
|
||||
await expect(page.getByTestId("field-timeout").locator("input")).toHaveValue("5000");
|
||||
await expect(page.getByTestId("references-empty")).toHaveText("尚无引用");
|
||||
await expect(page.getByTestId("versions-table")).toContainText("v1");
|
||||
await expect(page.getByTestId("versions-table")).toContainText("admin.demo");
|
||||
await expect(page.getByTestId("versions-table")).toContainText("当前生效");
|
||||
|
||||
const footer = page.getByTestId("query-footer");
|
||||
await expect(footer).toBeVisible();
|
||||
await expect(page.getByTestId("query-scroll").getByTestId("query-footer")).toHaveCount(0);
|
||||
const order = ["footer-back", "footer-save", "footer-disable", "footer-preview"];
|
||||
const labels = ["返回列表", "保存", "停用", "试跑预览"];
|
||||
const xs: number[] = [];
|
||||
for (const [index, id] of order.entries()) {
|
||||
await expect(page.getByTestId(id)).toHaveText(labels[index]);
|
||||
xs.push((await page.getByTestId(id).boundingBox())!.x);
|
||||
}
|
||||
expect([...xs].sort((a, b) => a - b)).toEqual(xs);
|
||||
await expect(page.getByTestId("footer-publish")).toHaveCount(0);
|
||||
await expect(page.getByTestId("versions-block").getByRole("button", { name: "发布" })).toHaveCount(0);
|
||||
|
||||
const footerBox = (await footer.boundingBox())!;
|
||||
const first = (await page.getByTestId("footer-back").boundingBox())!;
|
||||
const last = (await page.getByTestId("footer-preview").boundingBox())!;
|
||||
expect(Math.abs((first.x + last.x + last.width) / 2 - (footerBox.x + footerBox.width / 2))).toBeLessThan(6);
|
||||
expect(await page.getByTestId("query-scroll").evaluate((el) => el.scrollHeight > el.clientHeight)).toBe(true);
|
||||
await page.getByTestId("query-scroll").evaluate((el) => el.scrollTo(0, el.scrollHeight));
|
||||
const after = (await footer.boundingBox())!;
|
||||
expect(after.y).toBeCloseTo(footerBox.y, 0);
|
||||
expect(after.y + after.height).toBeLessThanOrEqual(520);
|
||||
await page.getByTestId("query-scroll").evaluate((el) => el.scrollTo(0, 0));
|
||||
await page.screenshot({ path: path.join(evidenceDir, "query-detail.png"), fullPage: true });
|
||||
});
|
||||
|
||||
test("unsaved edits disable the preview until saved; metadata save sends PATCH", async ({ page }) => {
|
||||
await signIn(page, ["watchman-admin"]);
|
||||
const mock = await mockApi(page);
|
||||
await page.goto(`/#/queries/${Q_ONE}`);
|
||||
await expect(page.getByTestId("footer-preview")).toBeEnabled();
|
||||
await expect(page.getByTestId("preview-dirty")).toHaveCount(0);
|
||||
|
||||
await page.getByTestId("field-name").locator("input").fill("产线温度采样(改)");
|
||||
await expect(page.getByTestId("preview-dirty")).toContainText("未保存");
|
||||
await expect(page.getByTestId("footer-preview")).toBeDisabled();
|
||||
await expect(page.getByTestId("footer-preview")).toHaveAttribute("title", /先保存/);
|
||||
|
||||
await page.getByTestId("footer-save").click();
|
||||
await expect(page.getByTestId("preview-dirty")).toHaveCount(0);
|
||||
await expect(page.getByTestId("footer-preview")).toBeEnabled();
|
||||
const patch = mock.requests.find((item) => item.method === "PATCH");
|
||||
expect((patch!.body as Record<string, unknown>).name).toBe("产线温度采样(改)");
|
||||
expect(patch!.pathname).toBe(`/queries/${Q_ONE}`);
|
||||
expect(mock.requests.filter((item) => item.pathname.endsWith("/publish"))).toHaveLength(0);
|
||||
});
|
||||
|
||||
test("saving content creates a new version; version page is read-only and can activate", async ({ page }) => {
|
||||
await signIn(page, ["watchman-admin"]);
|
||||
const mock = await mockApi(page);
|
||||
await page.goto(`/#/queries/${Q_ONE}`);
|
||||
|
||||
await page.getByTestId("field-sql").locator("textarea").fill(`${SQL_ONE}\n-- v2`);
|
||||
await page.getByTestId("footer-save").click();
|
||||
await expect(page.getByTestId("versions-table")).toContainText("v2");
|
||||
await expect(page.getByTestId("basic-sub")).toContainText("当前生效 v2");
|
||||
const saveVersion = mock.requests.find(
|
||||
(item) => item.method === "POST" && item.pathname === `/queries/${Q_ONE}/versions`,
|
||||
);
|
||||
expect(saveVersion).toBeTruthy();
|
||||
expect((saveVersion!.body as Record<string, unknown>).sql_template).toContain("-- v2");
|
||||
expect(mock.requests.filter((item) => item.pathname.endsWith("/publish"))).toHaveLength(0);
|
||||
|
||||
// Open v1: read-only page with activate + back to query.
|
||||
await page.getByTestId("version-open-1").click();
|
||||
const crumb = page.getByTestId("breadcrumb");
|
||||
await expect(crumb).toContainText("详情");
|
||||
await expect(crumb).toContainText("版本 v1");
|
||||
await expect(page.getByTestId("version-number")).toHaveText("v1");
|
||||
await expect(page.getByTestId("version-readonly-tag")).toHaveText("只读");
|
||||
await expect(page.getByTestId("version-sql")).toContainText("FROM process_readings");
|
||||
await expect(page.getByTestId("params-table")).toContainText("line_code");
|
||||
await expect(page.getByTestId("version-limits")).toContainText("5000");
|
||||
await expect(page.getByTestId("version-frozen-note")).toContainText("已冻结");
|
||||
await expect(page.getByTestId("param-name")).toHaveCount(0);
|
||||
await expect(page.getByTestId("field-sql")).toHaveCount(0);
|
||||
await expect(page.getByTestId("footer-save")).toHaveCount(0);
|
||||
await expect(page.getByTestId("footer-publish")).toHaveCount(0);
|
||||
await expect(page.getByTestId("footer-back")).toHaveText("返回列表");
|
||||
await expect(page.getByTestId("footer-query")).toHaveText("返回查询");
|
||||
await expect(page.getByTestId("footer-activate")).toHaveText("激活此版本");
|
||||
await expect(page.getByTestId("footer-preview")).toHaveText("试跑预览");
|
||||
await expect(page.getByTestId("preview-target")).toContainText("版本 v1");
|
||||
await page.screenshot({ path: path.join(evidenceDir, "query-version.png"), fullPage: true });
|
||||
|
||||
await page.getByTestId("footer-activate").click();
|
||||
expect(
|
||||
mock.requests.filter((item) => item.pathname === `/queries/${Q_ONE}/versions/1/activate`),
|
||||
).toHaveLength(1);
|
||||
await page.getByTestId("footer-query").click();
|
||||
await expect(page.getByTestId("field-name")).toBeVisible();
|
||||
await expect(page.getByTestId("breadcrumb")).not.toContainText("版本");
|
||||
await expect(page.getByTestId("basic-sub")).toContainText("当前生效 v1");
|
||||
});
|
||||
|
||||
test("a version preview runs that version", async ({ page }) => {
|
||||
await signIn(page, ["watchman-admin"]);
|
||||
const mock = await mockApi(page);
|
||||
await page.goto(`/#/queries/${Q_ONE}/versions/1`);
|
||||
await page.getByTestId("preview-param-line_code").locator("input").fill("L1");
|
||||
await page.getByTestId("footer-preview").click();
|
||||
await expect(page.getByTestId("preview-result")).toHaveAttribute("data-status", "success");
|
||||
const call = mock.requests.find((item) => item.pathname === `/queries/${Q_ONE}/versions/1/preview`)!;
|
||||
expect(call.body).toEqual({ params: { line_code: "L1", min_temp: 0 } });
|
||||
});
|
||||
|
||||
test("preview: running, success with a masked column, parameter values sent by type", async ({ page }) => {
|
||||
await signIn(page, ["watchman-admin"]);
|
||||
const mock = await mockApi(page);
|
||||
mock.preview.delayMs = 600;
|
||||
await page.goto(`/#/queries/${Q_ONE}`);
|
||||
|
||||
await expect(page.getByTestId("preview-none")).toBeVisible();
|
||||
await expect(page.getByTestId("preview-target")).toContainText("当前版本");
|
||||
// Declared defaults pre-fill the inputs; a value that does not fit the type is not sent.
|
||||
await expect(page.getByTestId("preview-param-min_temp").locator("input")).toHaveValue("0");
|
||||
await page.getByTestId("preview-param-min_temp").locator("input").fill("abc");
|
||||
await page.getByTestId("footer-preview").click();
|
||||
await expect(page.getByTestId("preview-param-min_temp")).toContainText("不符");
|
||||
expect(mock.requests.filter((item) => item.pathname.endsWith("/preview"))).toHaveLength(0);
|
||||
|
||||
await page.getByTestId("preview-param-min_temp").locator("input").fill("1.5");
|
||||
await page.getByTestId("preview-param-line_code").locator("input").fill("L1");
|
||||
await page.getByTestId("footer-preview").click();
|
||||
await expect(page.getByTestId("preview-running")).toContainText("试跑中");
|
||||
await expect(page.getByTestId("footer-preview")).toBeDisabled();
|
||||
const result = page.getByTestId("preview-result");
|
||||
await expect(result).toHaveAttribute("data-status", "success");
|
||||
await expect(page.getByTestId("preview-table")).toContainText("LOT-1001");
|
||||
await expect(page.getByTestId("preview-table")).toContainText("NULL");
|
||||
await expect(page.getByTestId("masked-phone")).toHaveText("脱敏");
|
||||
await expect(page.getByTestId("masked-lot_no")).toHaveCount(0);
|
||||
await expect(page.getByTestId("preview-meta")).toContainText("timeout_ms=5000");
|
||||
await expect(page.getByTestId("preview-meta")).toContainText("产线工艺库");
|
||||
await expect(page.getByTestId("preview-meta")).toContainText("不创建报警");
|
||||
|
||||
const call = mock.requests.find((item) => item.pathname === `/queries/${Q_ONE}/preview`)!;
|
||||
expect(call.body).toEqual({ params: { line_code: "L1", min_temp: 1.5 } });
|
||||
await page.screenshot({ path: path.join(evidenceDir, "query-preview-success.png"), fullPage: true });
|
||||
});
|
||||
|
||||
test("preview: empty, illegal type and every failure kind stay apart", async ({ page }) => {
|
||||
await signIn(page, ["watchman-admin"]);
|
||||
const mock = await mockApi(page);
|
||||
await page.goto(`/#/queries/${Q_ONE}`);
|
||||
const result = page.getByTestId("preview-result");
|
||||
|
||||
mock.preview.body = previewBody({ status: "empty", columns: ["lot_no"], rows: [], row_count: 0, masked_columns: [] });
|
||||
await page.getByTestId("footer-preview").click();
|
||||
await expect(result).toHaveAttribute("data-status", "empty");
|
||||
await expect(result).toContainText("空结果");
|
||||
await expect(result).toContainText("不是失败");
|
||||
await expect(page.getByTestId("preview-table")).toHaveCount(0);
|
||||
await page.screenshot({ path: path.join(evidenceDir, "query-preview-empty.png"), fullPage: true });
|
||||
|
||||
mock.preview.body = previewBody({
|
||||
status: "illegal_type",
|
||||
columns: ["temperature"],
|
||||
details: { fields: [{ field: "temperature", expected: "number", actual: "str", row: 1 }] },
|
||||
});
|
||||
await page.getByTestId("footer-preview").click();
|
||||
await expect(result).toHaveAttribute("data-status", "illegal_type");
|
||||
await expect(result).toContainText("输出类型不匹配");
|
||||
await expect(page.getByTestId("preview-problems")).toContainText("temperature");
|
||||
await expect(page.getByTestId("preview-problems")).toContainText("number");
|
||||
await expect(page.getByTestId("preview-problems")).toContainText("str");
|
||||
await page.screenshot({ path: path.join(evidenceDir, "query-preview-illegal.png"), fullPage: true });
|
||||
|
||||
const kinds: [string, string, boolean][] = [
|
||||
["timeout", "执行超时", false],
|
||||
["unreachable", "连接失败", true],
|
||||
["auth_failed", "认证失败", true],
|
||||
["rejected", "拒绝连接", true],
|
||||
["sql_error", "SQL 执行失败", false],
|
||||
["limit_exceeded", "超出 max_rows", false],
|
||||
["validation", "模板或参数无效", false],
|
||||
];
|
||||
for (const [kind, title, counted] of kinds) {
|
||||
mock.preview.body = previewBody({
|
||||
status: "failure",
|
||||
failure_kind: kind,
|
||||
message: SERVER_TEXT,
|
||||
details: kind === "limit_exceeded" ? { max_rows: 200 } : kind === "validation" ? { reason: "missing_param" } : {},
|
||||
});
|
||||
await page.getByTestId("footer-preview").click();
|
||||
await expect(result).toHaveAttribute("data-status", "failure");
|
||||
await expect(result).toHaveAttribute("data-failure-kind", kind);
|
||||
await expect(result).toContainText(title);
|
||||
await expect(page.getByTestId("preview-failure-note")).toContainText(counted ? "会计入" : "不计入");
|
||||
await expect(page.locator("body")).not.toContainText(SERVER_TEXT);
|
||||
}
|
||||
await expect(result).toContainText("缺少必填参数");
|
||||
await page.screenshot({ path: path.join(evidenceDir, "query-preview-failure.png"), fullPage: true });
|
||||
|
||||
mock.preview.body = previewBody({
|
||||
status: "failure",
|
||||
failure_kind: "circuit_open",
|
||||
details: { reason: "circuit_open", circuit_open_until: "2026-11-18T09:30:00+00:00" },
|
||||
});
|
||||
await page.getByTestId("footer-preview").click();
|
||||
await expect(result).toHaveAttribute("data-status", "circuit_open");
|
||||
await expect(result).toContainText("熔断中");
|
||||
await expect(result).toContainText("2026-11-18");
|
||||
|
||||
mock.preview.body = previewBody({ status: "failure", failure_kind: "disabled", details: { reason: "disabled" } });
|
||||
await page.getByTestId("footer-preview").click();
|
||||
await expect(result).toHaveAttribute("data-status", "disabled");
|
||||
await expect(result).toContainText("数据源已停用");
|
||||
|
||||
mock.preview = { status: 403, delayMs: 0, body: fail(42000, SERVER_TEXT, { permission_node: "x" }) };
|
||||
await page.getByTestId("footer-preview").click();
|
||||
await expect(page.getByTestId("preview-error")).toContainText("权限不足");
|
||||
await expect(page.locator("body")).not.toContainText(SERVER_TEXT);
|
||||
});
|
||||
|
||||
test("disabled query: the button stays clickable and the 409 is explained", async ({ page }) => {
|
||||
await signIn(page, ["watchman-admin"]);
|
||||
const mock = await mockApi(page);
|
||||
await page.goto(`/#/queries/${Q_OFF}`);
|
||||
await expect(page.getByTestId("query-disabled-note")).toBeVisible();
|
||||
await expect(page.getByTestId("footer-enable")).toHaveText("启用");
|
||||
await expect(page.getByTestId("footer-disable")).toHaveCount(0);
|
||||
await expect(page.getByTestId("footer-preview")).toBeEnabled();
|
||||
await page.getByTestId("footer-preview").click();
|
||||
const result = page.getByTestId("preview-result");
|
||||
await expect(result).toHaveAttribute("data-status", "disabled");
|
||||
await expect(result).toContainText("该查询已停用");
|
||||
await expect(page.locator("body")).not.toContainText("Query is disabled");
|
||||
expect(mock.requests.filter((item) => item.pathname.endsWith("/preview"))).toHaveLength(1);
|
||||
await page.screenshot({ path: path.join(evidenceDir, "query-disabled.png"), fullPage: true });
|
||||
});
|
||||
|
||||
test("停用 asks to confirm, 启用 does not; the list follows", async ({ page }) => {
|
||||
await signIn(page, ["watchman-admin"]);
|
||||
const mock = await mockApi(page);
|
||||
await page.goto(`/#/queries/${Q_ONE}`);
|
||||
await page.getByTestId("footer-disable").click();
|
||||
await page.locator(".el-message-box__btns .el-button:not(.el-button--primary)").click();
|
||||
expect(mock.requests.filter((item) => item.pathname.endsWith("/disable"))).toHaveLength(0);
|
||||
|
||||
await page.getByTestId("footer-disable").click();
|
||||
await confirmDialog(page);
|
||||
await expect(page.getByTestId("footer-enable")).toHaveText("启用");
|
||||
await expect(page.getByTestId("query-disabled-note")).toBeVisible();
|
||||
await expect(page.getByTestId("status-tag")).toHaveText("已停用");
|
||||
|
||||
await page.getByTestId("footer-back").click();
|
||||
await expect(page.getByTestId(`query-row-${Q_ONE}`).getByTestId("row-preview")).toBeDisabled();
|
||||
|
||||
await page.getByTestId(`query-row-${Q_ONE}`).getByTestId("row-open").click();
|
||||
await page.getByTestId("footer-enable").click();
|
||||
await expect(page.getByTestId("footer-disable")).toBeVisible();
|
||||
await expect(page.getByTestId("query-disabled-note")).toHaveCount(0);
|
||||
expect(mock.requests.filter((item) => item.pathname.endsWith("/enable"))).toHaveLength(1);
|
||||
});
|
||||
|
||||
test("list 预览 opens the detail at the trial-run panel without running it", async ({ page }) => {
|
||||
await page.setViewportSize({ width: 1280, height: 520 });
|
||||
await signIn(page, ["watchman-admin"]);
|
||||
const mock = await mockApi(page);
|
||||
await page.goto("/#/queries");
|
||||
await page.getByTestId(`query-row-${Q_ONE}`).getByTestId("row-preview").click();
|
||||
await expect(page.getByTestId("preview-card")).toBeInViewport();
|
||||
await expect(page.getByTestId("preview-none")).toBeVisible();
|
||||
expect(mock.requests.filter((item) => item.pathname.endsWith("/preview"))).toHaveLength(0);
|
||||
});
|
||||
|
||||
test("unknown query and version show a not-found message", async ({ page }) => {
|
||||
await signIn(page, ["watchman-admin"]);
|
||||
await mockApi(page);
|
||||
await page.goto("/#/queries/99999999-9999-4999-8999-999999999999");
|
||||
await expect(page.getByTestId("query-load-error")).toContainText("查询不存在");
|
||||
await expect(page.getByTestId("footer-back")).toBeVisible();
|
||||
await expect(page.getByTestId("footer-save")).toHaveCount(0);
|
||||
await page.goto(`/#/queries/${Q_ONE}/versions/9`);
|
||||
await expect(page.getByTestId("query-load-error")).toContainText("版本不存在");
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,9 @@
|
||||
{
|
||||
"appName": "Watchman",
|
||||
"appName": "Alert Platform",
|
||||
"login": {
|
||||
"title": "Sign in to Watchman",
|
||||
"title": "Sign in to Alert Platform",
|
||||
"subtitle": "Use your company account to open the alert platform",
|
||||
"eyebrow": "WATCHMAN · EARLY WARNING",
|
||||
"eyebrow": "ALERT PLATFORM · EARLY WARNING",
|
||||
"heroEm": "visible",
|
||||
"heroBefore": "Make exceptions ",
|
||||
"submitting": "Signing in",
|
||||
@@ -20,7 +20,7 @@
|
||||
"unavailable": "Sign-in is temporarily unavailable. Try again shortly.",
|
||||
"logout": "Sign out",
|
||||
"forbiddenTitle": "No access",
|
||||
"forbiddenBody": "This account is signed in, but it does not have a Watchman view, operate, or admin role.",
|
||||
"forbiddenBody": "This account is signed in, but it does not have an Alert Platform view, operate, or admin role.",
|
||||
"fixture": "Local identity mode. This is not a production sign-in."
|
||||
},
|
||||
"shell": {
|
||||
@@ -36,8 +36,10 @@
|
||||
"nav": {
|
||||
"home": "Overview",
|
||||
"datasources": "Data sources",
|
||||
"queries": "Queries",
|
||||
"create": "New",
|
||||
"detail": "Details"
|
||||
"detail": "Details",
|
||||
"version": "Version v{no}"
|
||||
},
|
||||
"datasource": {
|
||||
"list": {
|
||||
@@ -45,7 +47,15 @@
|
||||
"loading": "Loading data sources",
|
||||
"loadFailed": "Failed to load data sources",
|
||||
"empty": "No data sources yet",
|
||||
"emptyHint": "An administrator can create the first data source."
|
||||
"emptyHint": "An administrator can create the first data source.",
|
||||
"filterName": "Name (contains)",
|
||||
"filterEngine": "Engine",
|
||||
"filterStatus": "Status",
|
||||
"filterSearch": "Search",
|
||||
"filterReset": "Reset",
|
||||
"filterClear": "Clear filters",
|
||||
"filterEmpty": "No data sources match",
|
||||
"filterEmptyHint": "Try another name, engine or status, or reset the filters."
|
||||
},
|
||||
"columns": {
|
||||
"name": "Name",
|
||||
@@ -166,5 +176,281 @@
|
||||
},
|
||||
"saved": "Saved",
|
||||
"disabled": "Disabled"
|
||||
},
|
||||
"query": {
|
||||
"list": {
|
||||
"create": "New",
|
||||
"loadFailed": "Failed to load queries",
|
||||
"empty": "No queries yet",
|
||||
"emptyHint": "An administrator can create the first query: pick a data source, write a parameterized SQL template, and declare its parameters and output contract.",
|
||||
"filterName": "Name (contains)",
|
||||
"filterDatasource": "Data source",
|
||||
"filterStatus": "Status",
|
||||
"filterSearch": "Search",
|
||||
"filterReset": "Reset",
|
||||
"filterClear": "Clear filters",
|
||||
"filterEmpty": "No queries match",
|
||||
"filterEmptyHint": "Try another name, data source or status, or reset the filters."
|
||||
},
|
||||
"columns": {
|
||||
"name": "Name",
|
||||
"datasource": "Data source",
|
||||
"status": "Status",
|
||||
"latestVersion": "Latest version",
|
||||
"currentVersion": "Current version",
|
||||
"updatedAt": "Updated",
|
||||
"actions": "Actions"
|
||||
},
|
||||
"status": {
|
||||
"enabled": "Enabled",
|
||||
"disabled": "Disabled"
|
||||
},
|
||||
"actions": {
|
||||
"open": "Open",
|
||||
"preview": "Preview",
|
||||
"previewDisabledWhy": "Disabled, cannot be previewed",
|
||||
"backToList": "Back to list",
|
||||
"backToDraft": "Back to query",
|
||||
"backToQuery": "Back to query",
|
||||
"save": "Save",
|
||||
"publish": "Publish",
|
||||
"activate": "Activate this version",
|
||||
"switchVersion": "Switch version",
|
||||
"needSave": "Save the draft first",
|
||||
"disable": "Disable",
|
||||
"enable": "Enable",
|
||||
"runPreview": "Run preview",
|
||||
"previewNeedSave": "Save first; preview uses the saved current version",
|
||||
"add": "Add",
|
||||
"remove": "Remove"
|
||||
},
|
||||
"denied": {
|
||||
"title": "Queries are not available",
|
||||
"body": "Only administrators can open the query pages."
|
||||
},
|
||||
"form": {
|
||||
"basic": "Basics",
|
||||
"subNew": "New",
|
||||
"subSaved": "Current {version}",
|
||||
"name": "Name",
|
||||
"namePlaceholder": "Unique within the tenant",
|
||||
"nameTooLong": "At most 128 characters",
|
||||
"datasource": "Data source",
|
||||
"datasourcePlaceholder": "Select a data source",
|
||||
"datasourceOff": "(disabled)",
|
||||
"datasourcesFailed": "Failed to load data sources",
|
||||
"description": "Purpose",
|
||||
"status": "Status",
|
||||
"statusNew": "Enabled by default after creation",
|
||||
"statusHint": "Switch it with {action} in the footer",
|
||||
"sql": "SQL template",
|
||||
"sqlPlaceholder": "SELECT lot_no FROM process_readings WHERE line_code = :line_code",
|
||||
"sqlHint": "Use named parameters such as :line_code. Values are always bound, never spliced into the SQL. Read-only access is guaranteed by the data source account and the executor.",
|
||||
"paramsTitle": "Parameter schema",
|
||||
"paramsHint": "Every :name in the SQL must be declared here. Undeclared parameters are refused when running or publishing.",
|
||||
"outputsTitle": "Output schema",
|
||||
"outputsHint": "The output contract used to check result types: names and types only.",
|
||||
"identifiersTitle": "Allowed identifiers",
|
||||
"identifiersHint": "Table or column names cannot be parameter values. Only names declared here may appear in the template at {example}. Empty means none are allowed.",
|
||||
"limits": "Execution limits",
|
||||
"limitsHint": "Server caps: timeout_ms up to {timeout}, max_rows up to {rows}.",
|
||||
"required": "Required",
|
||||
"invalidRange": "Enter a whole number from {min} to {max}"
|
||||
},
|
||||
"sqlParams": {
|
||||
"none": "No :parameters used in the SQL yet.",
|
||||
"used": "Parameters in the SQL:",
|
||||
"undeclared": ":{name} not declared",
|
||||
"undeclaredTitle": "Not declared in the parameter schema; preview and save will reject it",
|
||||
"unused": "{name} unused",
|
||||
"unusedTitle": "Declared but not used in the SQL"
|
||||
},
|
||||
"params": {
|
||||
"name": "Name",
|
||||
"type": "Type",
|
||||
"required": "Required",
|
||||
"default": "Default",
|
||||
"yes": "Yes",
|
||||
"no": "No",
|
||||
"add": "Add parameter",
|
||||
"empty": "No parameters declared yet.",
|
||||
"namePlaceholder": "For example line_code",
|
||||
"defaultPlaceholder": "Optional",
|
||||
"invalidName": "Invalid parameter name: {name}",
|
||||
"duplicate": "Duplicate parameter name: {name}",
|
||||
"invalidDefault": "Default does not fit the type: {name}"
|
||||
},
|
||||
"outputs": {
|
||||
"name": "Column",
|
||||
"type": "Type",
|
||||
"add": "Add output column",
|
||||
"empty": "No output columns declared yet.",
|
||||
"namePlaceholder": "For example lot_no",
|
||||
"invalidName": "Invalid output column name: {name}",
|
||||
"duplicate": "Duplicate output column name: {name}",
|
||||
"invalidDefault": "Invalid output column: {name}"
|
||||
},
|
||||
"identifiers": {
|
||||
"none": "None (dynamic identifiers are not allowed)",
|
||||
"placeholder": "Type an identifier and press Enter, for example process_readings",
|
||||
"invalid": "An identifier may only contain letters, digits and underscores, and cannot start with a digit: {name}"
|
||||
},
|
||||
"preview": {
|
||||
"title": "Trial run",
|
||||
"target": "Preview target: ",
|
||||
"targetVersion": "Version v{no} (frozen)",
|
||||
"dirtyNote": "You have unsaved changes. Save before running a preview (it uses the saved current version).",
|
||||
"needSaveNote": "Save before running a preview.",
|
||||
"noParams": "This query declares no parameters, so you can run it directly.",
|
||||
"invalidValue": "The value does not fit the parameter type",
|
||||
"unset": "(not set)",
|
||||
"none": "Not run yet. Fill in the parameters and use Run preview in the footer.",
|
||||
"running": "Running",
|
||||
"success": {
|
||||
"title": "Run succeeded",
|
||||
"body": "Returned {count} sample rows and the columns fit the output contract. Columns tagged Masked are covered."
|
||||
},
|
||||
"empty": {
|
||||
"title": "Empty result",
|
||||
"body": "The query ran successfully but no row matched. This is neither a failure nor a type error."
|
||||
},
|
||||
"illegal": {
|
||||
"title": "Output type mismatch",
|
||||
"body": "The query ran, but the returned values do not fit the output contract, so the whole batch is not valid output.",
|
||||
"row": "Row",
|
||||
"field": "Column",
|
||||
"expected": "Contract type",
|
||||
"actual": "Actual type"
|
||||
},
|
||||
"failure": {
|
||||
"timeout": {
|
||||
"title": "Timed out",
|
||||
"body": "No answer within timeout_ms, so the query was stopped. Narrow the time window or adjust the limits and retry."
|
||||
},
|
||||
"unreachable": {
|
||||
"title": "Connection failed",
|
||||
"body": "Could not connect to the data source. Check the data source and the network."
|
||||
},
|
||||
"auth_failed": {
|
||||
"title": "Data source authentication failed",
|
||||
"body": "The data source did not accept the saved account or password. Update it on the data source page."
|
||||
},
|
||||
"rejected": {
|
||||
"title": "Data source refused the connection",
|
||||
"body": "The data source replied but refused the connection, for example because the database does not exist."
|
||||
},
|
||||
"sql_error": {
|
||||
"title": "SQL failed",
|
||||
"body": "The source database rejected the SQL. Check the SQL template."
|
||||
},
|
||||
"limit_exceeded": {
|
||||
"title": "Over max_rows",
|
||||
"body": "More rows than max_rows={max_rows} were returned, so nothing was returned. Narrow the condition or raise max_rows."
|
||||
},
|
||||
"validation": {
|
||||
"title": "Template or parameters invalid",
|
||||
"body": "The template or parameters failed validation, so nothing was sent to the source database."
|
||||
},
|
||||
"engine_readonly_unsupported": {
|
||||
"title": "Preview not available for this engine",
|
||||
"body": "SQL Server has no server-enforced read-only session in this release, so query preview is refused. Use a PostgreSQL or MySQL data source; connection tests still work."
|
||||
},
|
||||
"unknown": {
|
||||
"title": "Run failed",
|
||||
"body": "The query did not complete."
|
||||
},
|
||||
"noteCircuit": "Connection-class failures count toward this data source's circuit breaker.",
|
||||
"noteNoCircuit": "This kind of failure does not count toward the circuit breaker."
|
||||
},
|
||||
"disabled": {
|
||||
"title": "Disabled, not run",
|
||||
"queryBody": "This query is disabled and cannot be run. Use Enable in the footer first.",
|
||||
"sourceBody": "The bound data source is disabled and cannot be run."
|
||||
},
|
||||
"circuit": {
|
||||
"title": "Data source circuit open, not run",
|
||||
"body": "The data source circuit is open, so no query is sent to the source database. Expected to recover after {until}."
|
||||
},
|
||||
"masked": "Masked",
|
||||
"datasource": "Data source {name}",
|
||||
"onlyPreview": "Preview only: no alarm is created, no notification is sent, nothing enters official runs.",
|
||||
"failedUnknown": "The run did not finish. Try again shortly.",
|
||||
"targetCurrent": "Current version (saved content)"
|
||||
},
|
||||
"versions": {
|
||||
"title": "Versions",
|
||||
"hint": "Saving creates a new version and makes it current. Any history version can be activated.",
|
||||
"empty": "No versions yet.",
|
||||
"emptyCreate": "After you save, v1 will appear here.",
|
||||
"version": "Version",
|
||||
"latest": "Latest",
|
||||
"current": "Current",
|
||||
"publishedAt": "Created at",
|
||||
"publishedBy": "By",
|
||||
"unpublished": "No version",
|
||||
"none": "None",
|
||||
"loadFailed": "Failed to load versions",
|
||||
"frozenNote": "Version {version} is frozen and cannot be edited. Fix it on the query page and save a new version; you can still preview or activate here.",
|
||||
"info": "Version info",
|
||||
"readonly": "Read-only",
|
||||
"query": "Query",
|
||||
"activated": "Switched to {version}",
|
||||
"switchTitle": "Switch version · {name}"
|
||||
},
|
||||
"refs": {
|
||||
"title": "References",
|
||||
"empty": "No references yet",
|
||||
"loadFailed": "Failed to load references"
|
||||
},
|
||||
"publishConfirm": {
|
||||
"title": "Publish {version}?",
|
||||
"body": "The saved draft will be frozen as immutable version {version}. It cannot be changed or deleted afterwards; a correction needs a new version.",
|
||||
"ok": "Publish",
|
||||
"cancel": "Cancel"
|
||||
},
|
||||
"disableConfirm": {
|
||||
"title": "Disable query",
|
||||
"body": "A disabled query cannot be previewed. The record and published versions are kept. Disable \"{name}\"?",
|
||||
"ok": "Disable",
|
||||
"cancel": "Cancel"
|
||||
},
|
||||
"disabledNote": "This query is disabled. You can still view and edit the draft, but not run a preview. Use Enable in the footer to restore it.",
|
||||
"notFound": "Query not found",
|
||||
"versionNotFound": "Version not found",
|
||||
"loadFailed": "Failed to load the query",
|
||||
"saveFailed": "The action did not complete. Try again shortly.",
|
||||
"saved": "Draft saved",
|
||||
"savedVersion": "Saved as {version} and set as current",
|
||||
"publishNeedSave": "Save unsaved changes first",
|
||||
"published": "Saved {version}",
|
||||
"enabledDone": "Enabled",
|
||||
"disabledDone": "Disabled",
|
||||
"errors": {
|
||||
"duplicate_name": "This name already exists. Choose another.",
|
||||
"datasource_not_found": "The selected data source does not exist",
|
||||
"datasource_not_database": "Only a database data source can be used",
|
||||
"template_empty": "The SQL template cannot be empty",
|
||||
"param_schema_invalid": "The parameter schema is invalid",
|
||||
"param_default_invalid": "A parameter default does not fit its type",
|
||||
"output_schema_invalid": "The output schema is invalid",
|
||||
"allowed_identifiers_invalid": "The allowed identifiers are invalid",
|
||||
"limit_invalid": "A limit must be a whole number of at least 1",
|
||||
"disabled": "The query is disabled and cannot be run",
|
||||
"version_conflict": "Version number conflict. Refresh and try again.",
|
||||
"not_found": "Record not found",
|
||||
"version_immutable": "A published version cannot be changed",
|
||||
"identifier_invalid": "An identifier in the template is malformed",
|
||||
"identifier_not_allowed": "The template uses an identifier that is not allowed",
|
||||
"identifier_unterminated": "An identifier in the template is not closed",
|
||||
"missing_param": "A required parameter is missing",
|
||||
"multiple_statements": "The template may contain only one statement",
|
||||
"param_type_mismatch": "A parameter value does not fit its type",
|
||||
"params_invalid": "The parameters are malformed",
|
||||
"template_unterminated": "The template has an unclosed quote or comment",
|
||||
"undeclared_param": "The template uses a parameter that is not declared",
|
||||
"unknown_param": "A parameter that is not declared was sent",
|
||||
"unsupported_engine": "This data source engine is not supported yet",
|
||||
"unsupported_datasource": "This data source type is not supported yet"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
{
|
||||
"appName": "Watchman",
|
||||
"appName": "แพลตฟอร์มแจ้งเตือน",
|
||||
"login": {
|
||||
"title": "เข้าสู่ Watchman",
|
||||
"title": "เข้าสู่แพลตฟอร์มแจ้งเตือน",
|
||||
"subtitle": "ใช้บัญชีบริษัทเพื่อเข้าสู่แพลตฟอร์มแจ้งเตือน",
|
||||
"eyebrow": "WATCHMAN · EARLY WARNING",
|
||||
"eyebrow": "แพลตฟอร์มแจ้งเตือน · EARLY WARNING",
|
||||
"heroEm": "เห็นได้",
|
||||
"heroBefore": "ทำให้ความผิดปกติ",
|
||||
"submitting": "กำลังเข้าสู่ระบบ",
|
||||
@@ -20,7 +20,7 @@
|
||||
"unavailable": "บริการเข้าสู่ระบบไม่พร้อมชั่วคราว โปรดลองอีกครั้ง",
|
||||
"logout": "ออกจากระบบ",
|
||||
"forbiddenTitle": "ไม่มีสิทธิ์เข้าใช้",
|
||||
"forbiddenBody": "บัญชีนี้เข้าสู่ระบบแล้ว แต่ไม่มีบทบาทดู ดำเนินการ หรือผู้ดูแลของ Watchman",
|
||||
"forbiddenBody": "บัญชีนี้เข้าสู่ระบบแล้ว แต่ไม่มีบทบาทดู ดำเนินการ หรือผู้ดูแลของแพลตฟอร์มแจ้งเตือน",
|
||||
"fixture": "โหมดตัวตนภายในเครื่อง ไม่ใช่การเข้าสู่ระบบจริง"
|
||||
},
|
||||
"shell": {
|
||||
@@ -36,8 +36,10 @@
|
||||
"nav": {
|
||||
"home": "ภาพรวม",
|
||||
"datasources": "แหล่งข้อมูล",
|
||||
"queries": "คิวรี",
|
||||
"create": "สร้างใหม่",
|
||||
"detail": "รายละเอียด"
|
||||
"detail": "รายละเอียด",
|
||||
"version": "เวอร์ชัน v{no}"
|
||||
},
|
||||
"datasource": {
|
||||
"list": {
|
||||
@@ -45,7 +47,15 @@
|
||||
"loading": "กำลังโหลดแหล่งข้อมูล",
|
||||
"loadFailed": "โหลดแหล่งข้อมูลไม่สำเร็จ",
|
||||
"empty": "ยังไม่มีแหล่งข้อมูล",
|
||||
"emptyHint": "ผู้ดูแลสามารถสร้างแหล่งข้อมูลแรกได้"
|
||||
"emptyHint": "ผู้ดูแลสามารถสร้างแหล่งข้อมูลแรกได้",
|
||||
"filterName": "ชื่อ (ค้นหาบางส่วน)",
|
||||
"filterEngine": "เอนจิน",
|
||||
"filterStatus": "สถานะ",
|
||||
"filterSearch": "ค้นหา",
|
||||
"filterReset": "รีเซ็ต",
|
||||
"filterClear": "ล้างตัวกรอง",
|
||||
"filterEmpty": "ไม่มีแหล่งข้อมูลที่ตรงเงื่อนไข",
|
||||
"filterEmptyHint": "ลองเปลี่ยนชื่อ เอนจิน หรือสถานะ หรือกดรีเซ็ต"
|
||||
},
|
||||
"columns": {
|
||||
"name": "ชื่อ",
|
||||
@@ -166,5 +176,281 @@
|
||||
},
|
||||
"saved": "บันทึกแล้ว",
|
||||
"disabled": "ปิดใช้งานแล้ว"
|
||||
},
|
||||
"query": {
|
||||
"list": {
|
||||
"create": "สร้างใหม่",
|
||||
"loadFailed": "โหลดคิวรีไม่สำเร็จ",
|
||||
"empty": "ยังไม่มีคิวรี",
|
||||
"emptyHint": "ผู้ดูแลสามารถสร้างคิวรีแรกได้ โดยเลือกแหล่งข้อมูล เขียนเทมเพลต SQL แบบมีพารามิเตอร์ และประกาศพารามิเตอร์กับสัญญาเอาต์พุต",
|
||||
"filterName": "ชื่อ (ค้นหาบางส่วน)",
|
||||
"filterDatasource": "แหล่งข้อมูล",
|
||||
"filterStatus": "สถานะ",
|
||||
"filterSearch": "ค้นหา",
|
||||
"filterReset": "รีเซ็ต",
|
||||
"filterClear": "ล้างตัวกรอง",
|
||||
"filterEmpty": "ไม่มีคิวรีที่ตรงเงื่อนไข",
|
||||
"filterEmptyHint": "ลองเปลี่ยนชื่อ แหล่งข้อมูล หรือสถานะ หรือกดรีเซ็ต"
|
||||
},
|
||||
"columns": {
|
||||
"name": "ชื่อ",
|
||||
"datasource": "แหล่งข้อมูล",
|
||||
"status": "สถานะ",
|
||||
"latestVersion": "เวอร์ชันล่าสุด",
|
||||
"currentVersion": "เวอร์ชันปัจจุบัน",
|
||||
"updatedAt": "อัปเดตเมื่อ",
|
||||
"actions": "การดำเนินการ"
|
||||
},
|
||||
"status": {
|
||||
"enabled": "เปิดใช้งาน",
|
||||
"disabled": "ปิดใช้งานแล้ว"
|
||||
},
|
||||
"actions": {
|
||||
"open": "เปิด",
|
||||
"preview": "ตัวอย่าง",
|
||||
"previewDisabledWhy": "ปิดใช้งานแล้ว ดูตัวอย่างไม่ได้",
|
||||
"backToList": "กลับไปที่รายการ",
|
||||
"backToDraft": "กลับไปที่คิวรี",
|
||||
"backToQuery": "กลับไปที่คิวรี",
|
||||
"save": "บันทึก",
|
||||
"publish": "เผยแพร่",
|
||||
"activate": "เปิดใช้เวอร์ชันนี้",
|
||||
"switchVersion": "สลับเวอร์ชัน",
|
||||
"needSave": "บันทึกฉบับร่างก่อน",
|
||||
"disable": "ปิดใช้งาน",
|
||||
"enable": "เปิดใช้งาน",
|
||||
"runPreview": "ทดลองรันตัวอย่าง",
|
||||
"previewNeedSave": "บันทึกก่อน ตัวอย่างใช้เวอร์ชันปัจจุบันที่บันทึกแล้ว",
|
||||
"add": "เพิ่ม",
|
||||
"remove": "ลบ"
|
||||
},
|
||||
"denied": {
|
||||
"title": "ไม่สามารถเข้าถึงคิวรี",
|
||||
"body": "เฉพาะผู้ดูแลเท่านั้นที่เปิดหน้าคิวรีได้"
|
||||
},
|
||||
"form": {
|
||||
"basic": "ข้อมูลพื้นฐาน",
|
||||
"subNew": "สร้างใหม่",
|
||||
"subSaved": "ใช้งานอยู่ {version}",
|
||||
"name": "ชื่อ",
|
||||
"namePlaceholder": "ไม่ซ้ำภายในผู้เช่า",
|
||||
"nameTooLong": "ยาวได้ไม่เกิน 128 ตัวอักษร",
|
||||
"datasource": "แหล่งข้อมูล",
|
||||
"datasourcePlaceholder": "เลือกแหล่งข้อมูล",
|
||||
"datasourceOff": "(ปิดใช้งานแล้ว)",
|
||||
"datasourcesFailed": "โหลดแหล่งข้อมูลไม่สำเร็จ",
|
||||
"description": "วัตถุประสงค์",
|
||||
"status": "สถานะ",
|
||||
"statusNew": "เปิดใช้งานโดยค่าเริ่มต้นหลังสร้าง",
|
||||
"statusHint": "สลับได้ด้วย {action} ที่ส่วนท้ายหน้า",
|
||||
"sql": "เทมเพลต SQL",
|
||||
"sqlPlaceholder": "SELECT lot_no FROM process_readings WHERE line_code = :line_code",
|
||||
"sqlHint": "ใช้พารามิเตอร์แบบมีชื่อ เช่น :line_code ค่าจะถูกผูกเสมอ ไม่ถูกต่อเข้ากับ SQL การอ่านอย่างเดียวรับประกันโดยบัญชีแหล่งข้อมูลและตัวรัน",
|
||||
"paramsTitle": "สคีมาพารามิเตอร์",
|
||||
"paramsHint": ":name ทุกตัวใน SQL ต้องประกาศที่นี่ พารามิเตอร์ที่ไม่ได้ประกาศจะถูกปฏิเสธเมื่อรันหรือเผยแพร่",
|
||||
"outputsTitle": "สคีมาเอาต์พุต",
|
||||
"outputsHint": "สัญญาเอาต์พุตสำหรับตรวจชนิดผลลัพธ์ มีเพียงชื่อและชนิด",
|
||||
"identifiersTitle": "ตัวระบุที่อนุญาต",
|
||||
"identifiersHint": "ชื่อตารางหรือคอลัมน์ใช้เป็นค่าพารามิเตอร์ไม่ได้ เฉพาะชื่อที่ประกาศที่นี่เท่านั้นที่ปรากฏในเทมเพลตที่ตำแหน่ง {example} ได้ ว่างไว้หมายถึงไม่อนุญาต",
|
||||
"limits": "ขีดจำกัดการรัน",
|
||||
"limitsHint": "เซิร์ฟเวอร์จำกัด: timeout_ms ไม่เกิน {timeout}, max_rows ไม่เกิน {rows}",
|
||||
"required": "จำเป็น",
|
||||
"invalidRange": "ต้องเป็นจำนวนเต็มตั้งแต่ {min} ถึง {max}"
|
||||
},
|
||||
"sqlParams": {
|
||||
"none": "ยังไม่มีพารามิเตอร์ :name ใน SQL",
|
||||
"used": "พารามิเตอร์ใน SQL:",
|
||||
"undeclared": ":{name} ยังไม่ได้ประกาศ",
|
||||
"undeclaredTitle": "ยังไม่ได้ประกาศใน parameter schema ตัวอย่างและการบันทึกจะถูกปฏิเสธ",
|
||||
"unused": "{name} ไม่ได้ใช้",
|
||||
"unusedTitle": "ประกาศไว้แต่ไม่ได้ใช้ใน SQL"
|
||||
},
|
||||
"params": {
|
||||
"name": "ชื่อ",
|
||||
"type": "ชนิด",
|
||||
"required": "จำเป็น",
|
||||
"default": "ค่าเริ่มต้น",
|
||||
"yes": "ใช่",
|
||||
"no": "ไม่",
|
||||
"add": "เพิ่มพารามิเตอร์",
|
||||
"empty": "ยังไม่ได้ประกาศพารามิเตอร์",
|
||||
"namePlaceholder": "เช่น line_code",
|
||||
"defaultPlaceholder": "เว้นว่างได้",
|
||||
"invalidName": "ชื่อพารามิเตอร์ไม่ถูกต้อง: {name}",
|
||||
"duplicate": "ชื่อพารามิเตอร์ซ้ำ: {name}",
|
||||
"invalidDefault": "ค่าเริ่มต้นไม่ตรงกับชนิด: {name}"
|
||||
},
|
||||
"outputs": {
|
||||
"name": "คอลัมน์",
|
||||
"type": "ชนิด",
|
||||
"add": "เพิ่มคอลัมน์เอาต์พุต",
|
||||
"empty": "ยังไม่ได้ประกาศคอลัมน์เอาต์พุต",
|
||||
"namePlaceholder": "เช่น lot_no",
|
||||
"invalidName": "ชื่อคอลัมน์เอาต์พุตไม่ถูกต้อง: {name}",
|
||||
"duplicate": "ชื่อคอลัมน์เอาต์พุตซ้ำ: {name}",
|
||||
"invalidDefault": "คอลัมน์เอาต์พุตไม่ถูกต้อง: {name}"
|
||||
},
|
||||
"identifiers": {
|
||||
"none": "ไม่มี (ไม่อนุญาตตัวระบุแบบไดนามิก)",
|
||||
"placeholder": "พิมพ์ตัวระบุแล้วกด Enter เช่น process_readings",
|
||||
"invalid": "ตัวระบุมีได้เฉพาะตัวอักษร ตัวเลข และขีดล่าง และห้ามขึ้นต้นด้วยตัวเลข: {name}"
|
||||
},
|
||||
"preview": {
|
||||
"title": "ทดลองรันตัวอย่าง",
|
||||
"target": "เป้าหมายตัวอย่าง: ",
|
||||
"targetVersion": "เวอร์ชัน v{no} (ล็อกแล้ว)",
|
||||
"dirtyNote": "มีการแก้ไขที่ยังไม่บันทึก บันทึกก่อนรันตัวอย่าง (ใช้เวอร์ชันปัจจุบันที่บันทึกแล้ว)",
|
||||
"needSaveNote": "บันทึกก่อนจึงจะรันตัวอย่างได้",
|
||||
"noParams": "คิวรีนี้ไม่ได้ประกาศพารามิเตอร์ จึงรันได้ทันที",
|
||||
"invalidValue": "ค่าไม่ตรงกับชนิดพารามิเตอร์",
|
||||
"unset": "(ยังไม่ระบุ)",
|
||||
"none": "ยังไม่ได้รัน กรอกพารามิเตอร์แล้วกด ทดลองรันตัวอย่าง ที่ส่วนท้ายหน้า",
|
||||
"running": "กำลังรัน",
|
||||
"success": {
|
||||
"title": "รันสำเร็จ",
|
||||
"body": "ส่งคืน {count} แถวตัวอย่าง และคอลัมน์ตรงตามสัญญาเอาต์พุต คอลัมน์ที่ติดป้ายปกปิดถูกบดบังแล้ว"
|
||||
},
|
||||
"empty": {
|
||||
"title": "ผลลัพธ์ว่าง",
|
||||
"body": "คิวรีรันสำเร็จแต่ไม่มีแถวที่ตรงเงื่อนไข ไม่ใช่ความล้มเหลวและไม่ใช่ข้อผิดพลาดด้านชนิด"
|
||||
},
|
||||
"illegal": {
|
||||
"title": "ชนิดเอาต์พุตไม่ตรง",
|
||||
"body": "คิวรีรันแล้ว แต่ค่าที่ส่งคืนไม่ตรงกับสัญญาเอาต์พุต ผลลัพธ์ทั้งชุดจึงไม่ถือว่าถูกต้อง",
|
||||
"row": "แถว",
|
||||
"field": "คอลัมน์",
|
||||
"expected": "ชนิดตามสัญญา",
|
||||
"actual": "ชนิดจริง"
|
||||
},
|
||||
"failure": {
|
||||
"timeout": {
|
||||
"title": "หมดเวลา",
|
||||
"body": "ไม่มีการตอบกลับภายใน timeout_ms จึงยกเลิกคิวรี ลองลดช่วงเวลาหรือปรับขีดจำกัดแล้วลองใหม่"
|
||||
},
|
||||
"unreachable": {
|
||||
"title": "เชื่อมต่อไม่สำเร็จ",
|
||||
"body": "เชื่อมต่อแหล่งข้อมูลไม่ได้ โปรดตรวจสอบแหล่งข้อมูลและเครือข่าย"
|
||||
},
|
||||
"auth_failed": {
|
||||
"title": "การยืนยันตัวตนกับแหล่งข้อมูลล้มเหลว",
|
||||
"body": "แหล่งข้อมูลไม่ยอมรับบัญชีหรือรหัสผ่านที่บันทึกไว้ โปรดอัปเดตที่หน้าแหล่งข้อมูล"
|
||||
},
|
||||
"rejected": {
|
||||
"title": "แหล่งข้อมูลปฏิเสธการเชื่อมต่อ",
|
||||
"body": "แหล่งข้อมูลตอบกลับแต่ปฏิเสธการเชื่อมต่อ เช่น ไม่มีฐานข้อมูลชื่อนี้"
|
||||
},
|
||||
"sql_error": {
|
||||
"title": "SQL ทำงานล้มเหลว",
|
||||
"body": "ฐานข้อมูลต้นทางปฏิเสธ SQL นี้ โปรดตรวจสอบเทมเพลต SQL"
|
||||
},
|
||||
"limit_exceeded": {
|
||||
"title": "เกิน max_rows",
|
||||
"body": "ส่งคืนแถวมากกว่า max_rows={max_rows} จึงไม่ส่งคืนอะไรเลย ลองจำกัดเงื่อนไขหรือเพิ่ม max_rows"
|
||||
},
|
||||
"validation": {
|
||||
"title": "เทมเพลตหรือพารามิเตอร์ไม่ถูกต้อง",
|
||||
"body": "เทมเพลตหรือพารามิเตอร์ไม่ผ่านการตรวจสอบ จึงไม่ได้ส่งอะไรไปยังฐานข้อมูลต้นทาง"
|
||||
},
|
||||
"engine_readonly_unsupported": {
|
||||
"title": "เอนจินนี้ยังไม่รองรับการทดลองรัน",
|
||||
"body": "SQL Server ยังไม่มีเซสชันแบบบังคับอ่านอย่างเดียวในรุ่นนี้ จึงไม่รันพรีวิวคิวรี โปรดใช้แหล่งข้อมูล PostgreSQL หรือ MySQL ส่วนการทดสอบการเชื่อมต่อยังใช้ได้"
|
||||
},
|
||||
"unknown": {
|
||||
"title": "การรันล้มเหลว",
|
||||
"body": "คิวรีทำงานไม่เสร็จ"
|
||||
},
|
||||
"noteCircuit": "ความล้มเหลวประเภทการเชื่อมต่อจะนับรวมในสถิติเบรกเกอร์ของแหล่งข้อมูลนี้",
|
||||
"noteNoCircuit": "ความล้มเหลวประเภทนี้ไม่นับรวมในสถิติเบรกเกอร์"
|
||||
},
|
||||
"disabled": {
|
||||
"title": "ปิดใช้งานแล้ว ไม่ได้รัน",
|
||||
"queryBody": "คิวรีนี้ปิดใช้งานแล้วจึงรันไม่ได้ โปรดกด เปิดใช้งาน ที่ส่วนท้ายหน้าก่อน",
|
||||
"sourceBody": "แหล่งข้อมูลที่ผูกไว้ปิดใช้งานแล้วจึงรันไม่ได้"
|
||||
},
|
||||
"circuit": {
|
||||
"title": "เบรกเกอร์ของแหล่งข้อมูลเปิดอยู่ ไม่ได้รัน",
|
||||
"body": "เบรกเกอร์ของแหล่งข้อมูลเปิดอยู่ จึงไม่ส่งคิวรีไปยังฐานข้อมูลต้นทาง คาดว่าจะกลับมาหลัง {until}"
|
||||
},
|
||||
"masked": "ปกปิด",
|
||||
"datasource": "แหล่งข้อมูล {name}",
|
||||
"onlyPreview": "ดูตัวอย่างเท่านั้น: ไม่สร้างการแจ้งเตือน ไม่ส่งการแจ้ง และไม่เข้าสู่การรันจริง",
|
||||
"failedUnknown": "การรันไม่เสร็จสิ้น โปรดลองใหม่ภายหลัง",
|
||||
"targetCurrent": "เวอร์ชันปัจจุบัน (เนื้อหาที่บันทึกแล้ว)"
|
||||
},
|
||||
"versions": {
|
||||
"title": "เวอร์ชัน",
|
||||
"hint": "การบันทึกจะสร้างเวอร์ชันใหม่และตั้งเป็นปัจจุบัน สามารถเปิดใช้เวอร์ชันย้อนหลังได้",
|
||||
"empty": "ยังไม่มีเวอร์ชัน",
|
||||
"emptyCreate": "หลังบันทึก v1 จะปรากฏที่นี่",
|
||||
"version": "เวอร์ชัน",
|
||||
"latest": "ล่าสุด",
|
||||
"current": "ใช้งานอยู่",
|
||||
"publishedAt": "สร้างเมื่อ",
|
||||
"publishedBy": "โดย",
|
||||
"unpublished": "ไม่มีเวอร์ชัน",
|
||||
"none": "ไม่มี",
|
||||
"loadFailed": "โหลดรายการเวอร์ชันไม่สำเร็จ",
|
||||
"frozenNote": "เวอร์ชัน {version} ถูกแช่แข็ง แก้ไขที่หน้าคิวรีแล้วบันทึกเป็นเวอร์ชันใหม่ ที่นี่ยังดูตัวอย่างหรือเปิดใช้ได้",
|
||||
"info": "ข้อมูลเวอร์ชัน",
|
||||
"readonly": "อ่านอย่างเดียว",
|
||||
"query": "คิวรี",
|
||||
"activated": "สลับเป็น {version} แล้ว",
|
||||
"switchTitle": "สลับเวอร์ชัน · {name}"
|
||||
},
|
||||
"refs": {
|
||||
"title": "การอ้างอิง",
|
||||
"empty": "ยังไม่มีการอ้างอิง",
|
||||
"loadFailed": "โหลดการอ้างอิงไม่สำเร็จ"
|
||||
},
|
||||
"publishConfirm": {
|
||||
"title": "ยืนยันเผยแพร่ {version}?",
|
||||
"body": "ฉบับร่างที่บันทึกไว้จะถูกล็อกเป็นเวอร์ชัน {version} ที่แก้ไขไม่ได้ หลังเผยแพร่จะแก้ไขหรือลบไม่ได้ หากต้องการแก้ต้องเผยแพร่เวอร์ชันใหม่",
|
||||
"ok": "เผยแพร่",
|
||||
"cancel": "ยกเลิก"
|
||||
},
|
||||
"disableConfirm": {
|
||||
"title": "ปิดใช้งานคิวรี",
|
||||
"body": "คิวรีที่ปิดใช้งานจะดูตัวอย่างไม่ได้ ระเบียนและเวอร์ชันที่เผยแพร่แล้วยังคงอยู่ ปิดใช้งาน \"{name}\" หรือไม่?",
|
||||
"ok": "ปิดใช้งาน",
|
||||
"cancel": "ยกเลิก"
|
||||
},
|
||||
"disabledNote": "คิวรีนี้ปิดใช้งานแล้ว ยังดูและแก้ไขฉบับร่างได้ แต่ทดลองรันตัวอย่างไม่ได้ กด เปิดใช้งาน ที่ส่วนท้ายหน้าเพื่อกู้คืน",
|
||||
"notFound": "ไม่พบคิวรี",
|
||||
"versionNotFound": "ไม่พบเวอร์ชัน",
|
||||
"loadFailed": "โหลดคิวรีไม่สำเร็จ",
|
||||
"saveFailed": "การดำเนินการไม่เสร็จสิ้น โปรดลองใหม่ภายหลัง",
|
||||
"saved": "บันทึกฉบับร่างแล้ว",
|
||||
"savedVersion": "บันทึกเป็น {version} และตั้งเป็นปัจจุบันแล้ว",
|
||||
"publishNeedSave": "มีการแก้ไขที่ยังไม่บันทึก กรุณาบันทึกก่อน",
|
||||
"published": "บันทึก {version} แล้ว",
|
||||
"enabledDone": "เปิดใช้งานแล้ว",
|
||||
"disabledDone": "ปิดใช้งานแล้ว",
|
||||
"errors": {
|
||||
"duplicate_name": "ชื่อนี้มีอยู่แล้ว โปรดใช้ชื่ออื่น",
|
||||
"datasource_not_found": "ไม่พบแหล่งข้อมูลที่เลือก",
|
||||
"datasource_not_database": "ใช้ได้เฉพาะแหล่งข้อมูลประเภทฐานข้อมูล",
|
||||
"template_empty": "เทมเพลต SQL ต้องไม่ว่าง",
|
||||
"param_schema_invalid": "สคีมาพารามิเตอร์ไม่ถูกต้อง",
|
||||
"param_default_invalid": "ค่าเริ่มต้นของพารามิเตอร์ไม่ตรงกับชนิด",
|
||||
"output_schema_invalid": "สคีมาเอาต์พุตไม่ถูกต้อง",
|
||||
"allowed_identifiers_invalid": "ตัวระบุที่อนุญาตไม่ถูกต้อง",
|
||||
"limit_invalid": "ขีดจำกัดต้องเป็นจำนวนเต็มตั้งแต่ 1 ขึ้นไป",
|
||||
"disabled": "คิวรีปิดใช้งานแล้ว รันไม่ได้",
|
||||
"version_conflict": "หมายเลขเวอร์ชันขัดแย้ง โปรดรีเฟรชแล้วลองใหม่",
|
||||
"not_found": "ไม่พบระเบียน",
|
||||
"version_immutable": "เวอร์ชันที่เผยแพร่แล้วแก้ไขไม่ได้",
|
||||
"identifier_invalid": "ตัวระบุในเทมเพลตเขียนไม่ถูกต้อง",
|
||||
"identifier_not_allowed": "เทมเพลตใช้ตัวระบุที่ไม่ได้รับอนุญาต",
|
||||
"identifier_unterminated": "ตัวระบุในเทมเพลตไม่ได้ปิด",
|
||||
"missing_param": "ขาดพารามิเตอร์ที่จำเป็น",
|
||||
"multiple_statements": "เทมเพลตมีได้เพียงหนึ่งคำสั่ง",
|
||||
"param_type_mismatch": "ค่าพารามิเตอร์ไม่ตรงกับชนิด",
|
||||
"params_invalid": "รูปแบบพารามิเตอร์ไม่ถูกต้อง",
|
||||
"template_unterminated": "เทมเพลตมีเครื่องหมายคำพูดหรือคอมเมนต์ที่ไม่ปิด",
|
||||
"undeclared_param": "เทมเพลตใช้พารามิเตอร์ที่ไม่ได้ประกาศ",
|
||||
"unknown_param": "ส่งพารามิเตอร์ที่ไม่ได้ประกาศมา",
|
||||
"unsupported_engine": "ยังไม่รองรับเอนจินของแหล่งข้อมูลนี้",
|
||||
"unsupported_datasource": "ยังไม่รองรับแหล่งข้อมูลประเภทนี้"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
{
|
||||
"appName": "Watchman",
|
||||
"appName": "预警平台",
|
||||
"login": {
|
||||
"title": "登录 Watchman",
|
||||
"title": "登录预警平台",
|
||||
"subtitle": "使用公司账号进入预警平台",
|
||||
"eyebrow": "WATCHMAN · EARLY WARNING",
|
||||
"eyebrow": "预警平台 · EARLY WARNING",
|
||||
"hero": "让异常{em}被看见{/em}",
|
||||
"heroEm": "被看见",
|
||||
"heroBefore": "让异常",
|
||||
@@ -21,7 +21,7 @@
|
||||
"unavailable": "登录服务暂不可用,请稍后再试",
|
||||
"logout": "退出",
|
||||
"forbiddenTitle": "没有访问权限",
|
||||
"forbiddenBody": "当前账号已登录,但没有 Watchman 的查看、处理或管理角色。",
|
||||
"forbiddenBody": "当前账号已登录,但没有预警平台的查看、处理或管理角色。",
|
||||
"fixture": "本地身份模式,不能当作正式登录"
|
||||
},
|
||||
"shell": {
|
||||
@@ -37,8 +37,10 @@
|
||||
"nav": {
|
||||
"home": "概览",
|
||||
"datasources": "数据源",
|
||||
"queries": "查询",
|
||||
"create": "新建",
|
||||
"detail": "详情"
|
||||
"detail": "详情",
|
||||
"version": "版本 v{no}"
|
||||
},
|
||||
"datasource": {
|
||||
"list": {
|
||||
@@ -46,7 +48,15 @@
|
||||
"loading": "数据源加载中",
|
||||
"loadFailed": "数据源加载失败",
|
||||
"empty": "还没有数据源",
|
||||
"emptyHint": "管理者可以新建第一个数据源。"
|
||||
"emptyHint": "管理者可以新建第一个数据源。",
|
||||
"filterName": "名称(模糊)",
|
||||
"filterEngine": "引擎",
|
||||
"filterStatus": "状态",
|
||||
"filterSearch": "查询",
|
||||
"filterReset": "重置",
|
||||
"filterClear": "清除筛选",
|
||||
"filterEmpty": "没有符合条件的数据源",
|
||||
"filterEmptyHint": "试试改名称、引擎或状态,或点重置。"
|
||||
},
|
||||
"columns": {
|
||||
"name": "名称",
|
||||
@@ -167,5 +177,281 @@
|
||||
},
|
||||
"saved": "已保存",
|
||||
"disabled": "已停用"
|
||||
},
|
||||
"query": {
|
||||
"list": {
|
||||
"create": "新建",
|
||||
"loadFailed": "查询加载失败",
|
||||
"empty": "还没有查询",
|
||||
"emptyHint": "管理者可以新建第一个查询定义:选择数据源,写参数化 SQL,声明参数与输出契约。",
|
||||
"filterName": "名称(模糊)",
|
||||
"filterDatasource": "数据源",
|
||||
"filterStatus": "状态",
|
||||
"filterSearch": "查询",
|
||||
"filterReset": "重置",
|
||||
"filterClear": "清除筛选",
|
||||
"filterEmpty": "没有符合条件的查询",
|
||||
"filterEmptyHint": "试试改名称、数据源或状态,或点重置。"
|
||||
},
|
||||
"columns": {
|
||||
"name": "名称",
|
||||
"datasource": "数据源",
|
||||
"status": "状态",
|
||||
"latestVersion": "最新版本",
|
||||
"currentVersion": "当前版本",
|
||||
"updatedAt": "更新时间",
|
||||
"actions": "操作"
|
||||
},
|
||||
"status": {
|
||||
"enabled": "启用",
|
||||
"disabled": "已停用"
|
||||
},
|
||||
"actions": {
|
||||
"open": "打开",
|
||||
"preview": "预览",
|
||||
"previewDisabledWhy": "已停用,不能预览",
|
||||
"backToList": "返回列表",
|
||||
"backToDraft": "返回查询",
|
||||
"backToQuery": "返回查询",
|
||||
"save": "保存",
|
||||
"publish": "发布",
|
||||
"activate": "激活此版本",
|
||||
"switchVersion": "切换版本",
|
||||
"needSave": "请先保存",
|
||||
"disable": "停用",
|
||||
"enable": "启用",
|
||||
"runPreview": "试跑预览",
|
||||
"previewNeedSave": "请先保存,预览使用已保存的当前版本",
|
||||
"add": "添加",
|
||||
"remove": "删除"
|
||||
},
|
||||
"denied": {
|
||||
"title": "无法进入查询",
|
||||
"body": "只有管理者可以进入查询界面。"
|
||||
},
|
||||
"form": {
|
||||
"basic": "基本信息",
|
||||
"subNew": "新建",
|
||||
"subSaved": "当前生效 {version}",
|
||||
"name": "名称",
|
||||
"namePlaceholder": "租户内唯一",
|
||||
"nameTooLong": "名称最多 128 个字符",
|
||||
"datasource": "数据源",
|
||||
"datasourcePlaceholder": "请选择数据源",
|
||||
"datasourceOff": "(已停用)",
|
||||
"datasourcesFailed": "数据源列表加载失败",
|
||||
"description": "用途说明",
|
||||
"status": "状态",
|
||||
"statusNew": "新建后默认启用",
|
||||
"statusHint": "通过页脚「{action}」切换",
|
||||
"sql": "SQL 模板",
|
||||
"sqlPlaceholder": "SELECT lot_no FROM process_readings WHERE line_code = :line_code",
|
||||
"sqlHint": "使用命名参数,例如 :line_code,值一律参数绑定,不拼接进 SQL。是否只读由数据源账户与执行器保证。",
|
||||
"paramsTitle": "参数 schema",
|
||||
"paramsHint": "SQL 中的 :name 必须在此声明,未声明的参数在试跑和保存时会被拒绝。",
|
||||
"outputsTitle": "输出 schema",
|
||||
"outputsHint": "输出契约,用于检查结果类型;只有名称和类型。",
|
||||
"identifiersTitle": "允许的标识符",
|
||||
"identifiersHint": "表或字段名不能当作参数值;只有这里声明的名称才允许出现在模板的 {example} 位置,留空表示不允许。",
|
||||
"limits": "执行限制",
|
||||
"limitsHint": "服务端有上限:timeout_ms 不超过 {timeout},max_rows 不超过 {rows}。",
|
||||
"required": "必填",
|
||||
"invalidRange": "须为 {min}–{max} 的整数"
|
||||
},
|
||||
"sqlParams": {
|
||||
"none": "SQL 中尚未使用 :参数。",
|
||||
"used": "SQL 中的参数:",
|
||||
"undeclared": ":{name} 未声明",
|
||||
"undeclaredTitle": "未在参数 schema 中声明,试跑和保存会被拒绝",
|
||||
"unused": "{name} 未使用",
|
||||
"unusedTitle": "已声明但 SQL 中未使用"
|
||||
},
|
||||
"params": {
|
||||
"name": "参数名",
|
||||
"type": "类型",
|
||||
"required": "必填",
|
||||
"default": "默认值",
|
||||
"yes": "是",
|
||||
"no": "否",
|
||||
"add": "添加参数",
|
||||
"empty": "尚未声明参数。",
|
||||
"namePlaceholder": "例如 line_code",
|
||||
"defaultPlaceholder": "可空",
|
||||
"invalidName": "参数名不合法:{name}",
|
||||
"duplicate": "参数名重复:{name}",
|
||||
"invalidDefault": "默认值与类型不符:{name}"
|
||||
},
|
||||
"outputs": {
|
||||
"name": "字段名",
|
||||
"type": "类型",
|
||||
"add": "添加输出字段",
|
||||
"empty": "尚未声明输出字段。",
|
||||
"namePlaceholder": "例如 lot_no",
|
||||
"invalidName": "输出字段名不合法:{name}",
|
||||
"duplicate": "输出字段名重复:{name}",
|
||||
"invalidDefault": "输出字段不合法:{name}"
|
||||
},
|
||||
"identifiers": {
|
||||
"none": "无(不允许动态标识符)",
|
||||
"placeholder": "输入标识符后按回车,例如 process_readings",
|
||||
"invalid": "标识符只能包含字母、数字和下划线,且不能以数字开头:{name}"
|
||||
},
|
||||
"preview": {
|
||||
"title": "试跑预览",
|
||||
"target": "预览对象:",
|
||||
"targetVersion": "版本 v{no}(已冻结)",
|
||||
"dirtyNote": "当前有未保存修改;请先保存再试跑(预览使用已保存的当前版本)。",
|
||||
"needSaveNote": "保存后才能试跑预览。",
|
||||
"noParams": "该查询没有声明参数,可直接试跑。",
|
||||
"invalidValue": "值与参数类型不符",
|
||||
"unset": "(未填)",
|
||||
"none": "尚未试跑。填写参数后点击页脚「试跑预览」。",
|
||||
"running": "试跑中",
|
||||
"success": {
|
||||
"title": "试跑成功",
|
||||
"body": "返回 {count} 行样例,列符合输出契约。标记「脱敏」的列已被遮盖。"
|
||||
},
|
||||
"empty": {
|
||||
"title": "空结果",
|
||||
"body": "查询已成功执行,但没有符合条件的行。这不是失败,也不是类型错误。"
|
||||
},
|
||||
"illegal": {
|
||||
"title": "输出类型不匹配",
|
||||
"body": "查询已执行,但返回值与输出契约不符,整批结果不视为合法输出。",
|
||||
"row": "行",
|
||||
"field": "字段",
|
||||
"expected": "契约类型",
|
||||
"actual": "实际类型"
|
||||
},
|
||||
"failure": {
|
||||
"timeout": {
|
||||
"title": "执行超时",
|
||||
"body": "超过 timeout_ms 仍未返回,已中止查询。可缩小时间窗或调整限制后重试。"
|
||||
},
|
||||
"unreachable": {
|
||||
"title": "连接失败",
|
||||
"body": "无法连接到数据源。请检查数据源与网络。"
|
||||
},
|
||||
"auth_failed": {
|
||||
"title": "数据源认证失败",
|
||||
"body": "数据源不接受已保存的账号或口令。请到数据源页面更新。"
|
||||
},
|
||||
"rejected": {
|
||||
"title": "数据源拒绝连接",
|
||||
"body": "数据源已响应但拒绝了连接,例如库名不存在。"
|
||||
},
|
||||
"sql_error": {
|
||||
"title": "SQL 执行失败",
|
||||
"body": "源库拒绝了该 SQL。请检查 SQL 模板。"
|
||||
},
|
||||
"limit_exceeded": {
|
||||
"title": "超出 max_rows",
|
||||
"body": "返回行数超过 max_rows={max_rows},整批结果未返回。请缩小条件或调大 max_rows。"
|
||||
},
|
||||
"validation": {
|
||||
"title": "模板或参数无效",
|
||||
"body": "查询模板或参数未通过校验,未向源库发起查询。"
|
||||
},
|
||||
"engine_readonly_unsupported": {
|
||||
"title": "该引擎暂不支持试跑",
|
||||
"body": "SQL Server 尚无服务端强制只读会话,本轮不执行其查询预览。请改用 PostgreSQL 或 MySQL 数据源;连接测试仍可用。"
|
||||
},
|
||||
"unknown": {
|
||||
"title": "试跑失败",
|
||||
"body": "查询没有完成。"
|
||||
},
|
||||
"noteCircuit": "连接类失败会计入该数据源的熔断统计。",
|
||||
"noteNoCircuit": "该类失败不计入熔断统计。"
|
||||
},
|
||||
"disabled": {
|
||||
"title": "已停用,未执行",
|
||||
"queryBody": "该查询已停用,不能试跑。请先在页脚「启用」。",
|
||||
"sourceBody": "所绑定的数据源已停用,不能试跑。"
|
||||
},
|
||||
"circuit": {
|
||||
"title": "数据源熔断中,未执行",
|
||||
"body": "数据源当前熔断,不会向源库发起查询。预计 {until} 后恢复。"
|
||||
},
|
||||
"masked": "脱敏",
|
||||
"datasource": "数据源 {name}",
|
||||
"onlyPreview": "仅预览:不创建报警、不发送通知、不进入正式运行。",
|
||||
"failedUnknown": "试跑未完成,请稍后再试",
|
||||
"targetCurrent": "当前版本(已保存内容)"
|
||||
},
|
||||
"versions": {
|
||||
"title": "版本",
|
||||
"hint": "保存会生成新版本并自动生效;可激活任一历史版本为当前。",
|
||||
"empty": "尚无版本。",
|
||||
"emptyCreate": "保存后会生成 v1,并出现在这里。",
|
||||
"version": "版本",
|
||||
"latest": "最新",
|
||||
"current": "当前生效",
|
||||
"publishedAt": "生成时间",
|
||||
"publishedBy": "操作人",
|
||||
"unpublished": "无版本",
|
||||
"none": "无",
|
||||
"loadFailed": "版本列表加载失败",
|
||||
"frozenNote": "版本 {version} 已冻结,内容不可修改。更正请返回查询修改后保存为新版本;这里仍可试跑预览或激活。",
|
||||
"info": "版本信息",
|
||||
"readonly": "只读",
|
||||
"query": "查询",
|
||||
"activated": "已切换为 {version}",
|
||||
"switchTitle": "切换版本 · {name}"
|
||||
},
|
||||
"refs": {
|
||||
"title": "引用",
|
||||
"empty": "尚无引用",
|
||||
"loadFailed": "引用加载失败"
|
||||
},
|
||||
"publishConfirm": {
|
||||
"title": "确认发布 {version}?",
|
||||
"body": "将把当前已保存的草稿固化为不可变版本 {version}。发布后不能修改或删除,更正需发布新版本。",
|
||||
"ok": "确认发布",
|
||||
"cancel": "取消"
|
||||
},
|
||||
"disableConfirm": {
|
||||
"title": "停用查询",
|
||||
"body": "停用后不能试跑预览,记录与已发布版本仍然保留。确定停用「{name}」吗?",
|
||||
"ok": "停用",
|
||||
"cancel": "取消"
|
||||
},
|
||||
"disabledNote": "该查询已停用。仍可查看与编辑,但不能试跑预览;可在页脚「启用」。",
|
||||
"notFound": "查询不存在",
|
||||
"versionNotFound": "版本不存在",
|
||||
"loadFailed": "查询加载失败",
|
||||
"saveFailed": "操作未完成,请稍后再试",
|
||||
"saved": "已保存",
|
||||
"savedVersion": "已保存为 {version} 并设为当前",
|
||||
"publishNeedSave": "有未保存修改,请先保存",
|
||||
"published": "已保存 {version}",
|
||||
"enabledDone": "已启用",
|
||||
"disabledDone": "已停用",
|
||||
"errors": {
|
||||
"duplicate_name": "名称已存在,请换一个名称",
|
||||
"datasource_not_found": "所选数据源不存在",
|
||||
"datasource_not_database": "只能选择数据库类型的数据源",
|
||||
"template_empty": "SQL 模板不能为空",
|
||||
"param_schema_invalid": "参数 schema 不合法",
|
||||
"param_default_invalid": "参数默认值与类型不符",
|
||||
"output_schema_invalid": "输出 schema 不合法",
|
||||
"allowed_identifiers_invalid": "允许的标识符不合法",
|
||||
"limit_invalid": "执行限制须为不小于 1 的整数",
|
||||
"disabled": "查询已停用,不能试跑",
|
||||
"version_conflict": "版本号冲突,请刷新后重试",
|
||||
"not_found": "记录不存在",
|
||||
"version_immutable": "已发布版本不可修改",
|
||||
"identifier_invalid": "模板中的标识符写法不合法",
|
||||
"identifier_not_allowed": "模板用到了未声明允许的标识符",
|
||||
"identifier_unterminated": "模板中的标识符没有结束",
|
||||
"missing_param": "缺少必填参数",
|
||||
"multiple_statements": "模板只能包含一条语句",
|
||||
"param_type_mismatch": "参数值与类型不符",
|
||||
"params_invalid": "参数格式不合法",
|
||||
"template_unterminated": "模板中有未闭合的引号或注释",
|
||||
"undeclared_param": "模板用到了未声明的参数",
|
||||
"unknown_param": "传入了未声明的参数",
|
||||
"unsupported_engine": "该数据源引擎暂不支持",
|
||||
"unsupported_datasource": "该数据源类型暂不支持"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
{
|
||||
"appName": "Watchman",
|
||||
"appName": "預警平台",
|
||||
"login": {
|
||||
"title": "登入 Watchman",
|
||||
"title": "登入預警平台",
|
||||
"subtitle": "使用公司帳號進入預警平台",
|
||||
"eyebrow": "WATCHMAN · EARLY WARNING",
|
||||
"eyebrow": "預警平台 · EARLY WARNING",
|
||||
"heroEm": "被看見",
|
||||
"heroBefore": "讓異常",
|
||||
"submitting": "登入中",
|
||||
@@ -20,7 +20,7 @@
|
||||
"unavailable": "登入服務暫不可用,請稍後再試",
|
||||
"logout": "登出",
|
||||
"forbiddenTitle": "沒有存取權限",
|
||||
"forbiddenBody": "目前帳號已登入,但沒有 Watchman 的查看、處理或管理角色。",
|
||||
"forbiddenBody": "目前帳號已登入,但沒有預警平台的查看、處理或管理角色。",
|
||||
"fixture": "本地身分模式,不能當作正式登入"
|
||||
},
|
||||
"shell": {
|
||||
@@ -36,8 +36,10 @@
|
||||
"nav": {
|
||||
"home": "概覽",
|
||||
"datasources": "資料來源",
|
||||
"queries": "查詢",
|
||||
"create": "新增",
|
||||
"detail": "詳情"
|
||||
"detail": "詳情",
|
||||
"version": "版本 v{no}"
|
||||
},
|
||||
"datasource": {
|
||||
"list": {
|
||||
@@ -45,7 +47,15 @@
|
||||
"loading": "資料來源載入中",
|
||||
"loadFailed": "資料來源載入失敗",
|
||||
"empty": "還沒有資料來源",
|
||||
"emptyHint": "管理者可以新增第一個資料來源。"
|
||||
"emptyHint": "管理者可以新增第一個資料來源。",
|
||||
"filterName": "名稱(模糊)",
|
||||
"filterEngine": "引擎",
|
||||
"filterStatus": "狀態",
|
||||
"filterSearch": "查詢",
|
||||
"filterReset": "重置",
|
||||
"filterClear": "清除篩選",
|
||||
"filterEmpty": "沒有符合條件的資料來源",
|
||||
"filterEmptyHint": "試試改名稱、引擎或狀態,或點重置。"
|
||||
},
|
||||
"columns": {
|
||||
"name": "名稱",
|
||||
@@ -166,5 +176,281 @@
|
||||
},
|
||||
"saved": "已儲存",
|
||||
"disabled": "已停用"
|
||||
},
|
||||
"query": {
|
||||
"list": {
|
||||
"create": "新建",
|
||||
"loadFailed": "查詢載入失敗",
|
||||
"empty": "還沒有查詢",
|
||||
"emptyHint": "管理者可以新建第一個查詢定義:選擇資料來源,撰寫參數化 SQL,宣告參數與輸出契約。",
|
||||
"filterName": "名稱(模糊)",
|
||||
"filterDatasource": "資料來源",
|
||||
"filterStatus": "狀態",
|
||||
"filterSearch": "查詢",
|
||||
"filterReset": "重置",
|
||||
"filterClear": "清除篩選",
|
||||
"filterEmpty": "沒有符合條件的查詢",
|
||||
"filterEmptyHint": "試試改名稱、資料來源或狀態,或點重置。"
|
||||
},
|
||||
"columns": {
|
||||
"name": "名稱",
|
||||
"datasource": "資料來源",
|
||||
"status": "狀態",
|
||||
"latestVersion": "最新版本",
|
||||
"currentVersion": "目前版本",
|
||||
"updatedAt": "更新時間",
|
||||
"actions": "操作"
|
||||
},
|
||||
"status": {
|
||||
"enabled": "啟用",
|
||||
"disabled": "已停用"
|
||||
},
|
||||
"actions": {
|
||||
"open": "開啟",
|
||||
"preview": "預覽",
|
||||
"previewDisabledWhy": "已停用,不能預覽",
|
||||
"backToList": "返回列表",
|
||||
"backToDraft": "返回查詢",
|
||||
"backToQuery": "返回查詢",
|
||||
"save": "儲存",
|
||||
"publish": "發布",
|
||||
"activate": "啟用此版本",
|
||||
"switchVersion": "切換版本",
|
||||
"needSave": "請先儲存草稿",
|
||||
"disable": "停用",
|
||||
"enable": "啟用",
|
||||
"runPreview": "試跑預覽",
|
||||
"previewNeedSave": "請先儲存,預覽使用已儲存的目前版本",
|
||||
"add": "新增",
|
||||
"remove": "刪除"
|
||||
},
|
||||
"denied": {
|
||||
"title": "無法進入查詢",
|
||||
"body": "只有管理者可以進入查詢介面。"
|
||||
},
|
||||
"form": {
|
||||
"basic": "基本資訊",
|
||||
"subNew": "新建",
|
||||
"subSaved": "目前生效 {version}",
|
||||
"name": "名稱",
|
||||
"namePlaceholder": "租戶內唯一",
|
||||
"nameTooLong": "名稱最多 128 個字元",
|
||||
"datasource": "資料來源",
|
||||
"datasourcePlaceholder": "請選擇資料來源",
|
||||
"datasourceOff": "(已停用)",
|
||||
"datasourcesFailed": "資料來源列表載入失敗",
|
||||
"description": "用途說明",
|
||||
"status": "狀態",
|
||||
"statusNew": "新建後預設啟用",
|
||||
"statusHint": "透過頁尾「{action}」切換",
|
||||
"sql": "SQL 範本",
|
||||
"sqlPlaceholder": "SELECT lot_no FROM process_readings WHERE line_code = :line_code",
|
||||
"sqlHint": "使用具名參數,例如 :line_code,值一律參數綁定,不拼接進 SQL。是否唯讀由資料來源帳戶與執行器保證。",
|
||||
"paramsTitle": "參數 schema",
|
||||
"paramsHint": "SQL 中的 :name 必須在此宣告,未宣告的參數在試跑和發布時會被拒絕。",
|
||||
"outputsTitle": "輸出 schema",
|
||||
"outputsHint": "輸出契約,用於檢查結果型別;只有名稱和型別。",
|
||||
"identifiersTitle": "允許的識別字",
|
||||
"identifiersHint": "表或欄位名不能當作參數值;只有這裡宣告的名稱才允許出現在範本的 {example} 位置,留空表示不允許。",
|
||||
"limits": "執行限制",
|
||||
"limitsHint": "伺服端有上限:timeout_ms 不超過 {timeout},max_rows 不超過 {rows}。",
|
||||
"required": "必填",
|
||||
"invalidRange": "須為 {min}–{max} 的整數"
|
||||
},
|
||||
"sqlParams": {
|
||||
"none": "SQL 中尚未使用 :參數。",
|
||||
"used": "SQL 中的參數:",
|
||||
"undeclared": ":{name} 未宣告",
|
||||
"undeclaredTitle": "未在參數 schema 中宣告,試跑和儲存會被拒絕",
|
||||
"unused": "{name} 未使用",
|
||||
"unusedTitle": "已宣告但 SQL 中未使用"
|
||||
},
|
||||
"params": {
|
||||
"name": "參數名",
|
||||
"type": "型別",
|
||||
"required": "必填",
|
||||
"default": "預設值",
|
||||
"yes": "是",
|
||||
"no": "否",
|
||||
"add": "新增參數",
|
||||
"empty": "尚未宣告參數。",
|
||||
"namePlaceholder": "例如 line_code",
|
||||
"defaultPlaceholder": "可空",
|
||||
"invalidName": "參數名不合法:{name}",
|
||||
"duplicate": "參數名重複:{name}",
|
||||
"invalidDefault": "預設值與型別不符:{name}"
|
||||
},
|
||||
"outputs": {
|
||||
"name": "欄位名",
|
||||
"type": "型別",
|
||||
"add": "新增輸出欄位",
|
||||
"empty": "尚未宣告輸出欄位。",
|
||||
"namePlaceholder": "例如 lot_no",
|
||||
"invalidName": "輸出欄位名不合法:{name}",
|
||||
"duplicate": "輸出欄位名重複:{name}",
|
||||
"invalidDefault": "輸出欄位不合法:{name}"
|
||||
},
|
||||
"identifiers": {
|
||||
"none": "無(不允許動態識別字)",
|
||||
"placeholder": "輸入識別字後按 Enter,例如 process_readings",
|
||||
"invalid": "識別字只能包含英文字母、數字和底線,且不能以數字開頭:{name}"
|
||||
},
|
||||
"preview": {
|
||||
"title": "試跑預覽",
|
||||
"target": "預覽對象:",
|
||||
"targetVersion": "版本 v{no}(已凍結)",
|
||||
"dirtyNote": "目前有未儲存修改;請先儲存再試跑(預覽使用已儲存的目前版本)。",
|
||||
"needSaveNote": "儲存後才能試跑預覽。",
|
||||
"noParams": "該查詢沒有宣告參數,可直接試跑。",
|
||||
"invalidValue": "值與參數型別不符",
|
||||
"unset": "(未填)",
|
||||
"none": "尚未試跑。填寫參數後點擊頁尾「試跑預覽」。",
|
||||
"running": "試跑中",
|
||||
"success": {
|
||||
"title": "試跑成功",
|
||||
"body": "回傳 {count} 列樣本,欄位符合輸出契約。標記「遮罩」的欄位已被遮蓋。"
|
||||
},
|
||||
"empty": {
|
||||
"title": "空結果",
|
||||
"body": "查詢已成功執行,但沒有符合條件的列。這不是失敗,也不是型別錯誤。"
|
||||
},
|
||||
"illegal": {
|
||||
"title": "輸出型別不符",
|
||||
"body": "查詢已執行,但回傳值與輸出契約不符,整批結果不視為合法輸出。",
|
||||
"row": "列",
|
||||
"field": "欄位",
|
||||
"expected": "契約型別",
|
||||
"actual": "實際型別"
|
||||
},
|
||||
"failure": {
|
||||
"timeout": {
|
||||
"title": "執行逾時",
|
||||
"body": "超過 timeout_ms 仍未回應,已中止查詢。可縮小時間窗或調整限制後重試。"
|
||||
},
|
||||
"unreachable": {
|
||||
"title": "連線失敗",
|
||||
"body": "無法連線到資料來源。請檢查資料來源與網路。"
|
||||
},
|
||||
"auth_failed": {
|
||||
"title": "資料來源認證失敗",
|
||||
"body": "資料來源不接受已儲存的帳號或密碼。請到資料來源頁面更新。"
|
||||
},
|
||||
"rejected": {
|
||||
"title": "資料來源拒絕連線",
|
||||
"body": "資料來源已回應但拒絕了連線,例如資料庫名稱不存在。"
|
||||
},
|
||||
"sql_error": {
|
||||
"title": "SQL 執行失敗",
|
||||
"body": "來源資料庫拒絕了該 SQL。請檢查 SQL 範本。"
|
||||
},
|
||||
"limit_exceeded": {
|
||||
"title": "超出 max_rows",
|
||||
"body": "回傳列數超過 max_rows={max_rows},整批結果未回傳。請縮小條件或調大 max_rows。"
|
||||
},
|
||||
"validation": {
|
||||
"title": "範本或參數無效",
|
||||
"body": "查詢範本或參數未通過驗證,未向來源資料庫發起查詢。"
|
||||
},
|
||||
"engine_readonly_unsupported": {
|
||||
"title": "此引擎暫不支援試跑",
|
||||
"body": "SQL Server 尚無服務端強制唯讀工作階段,本輪不執行其查詢預覽。請改用 PostgreSQL 或 MySQL 資料來源;連線測試仍可用。"
|
||||
},
|
||||
"unknown": {
|
||||
"title": "試跑失敗",
|
||||
"body": "查詢沒有完成。"
|
||||
},
|
||||
"noteCircuit": "連線類失敗會計入該資料來源的熔斷統計。",
|
||||
"noteNoCircuit": "此類失敗不計入熔斷統計。"
|
||||
},
|
||||
"disabled": {
|
||||
"title": "已停用,未執行",
|
||||
"queryBody": "該查詢已停用,不能試跑。請先在頁尾「啟用」。",
|
||||
"sourceBody": "所綁定的資料來源已停用,不能試跑。"
|
||||
},
|
||||
"circuit": {
|
||||
"title": "資料來源熔斷中,未執行",
|
||||
"body": "資料來源目前熔斷,不會向來源資料庫發起查詢。預計 {until} 後恢復。"
|
||||
},
|
||||
"masked": "遮罩",
|
||||
"datasource": "資料來源 {name}",
|
||||
"onlyPreview": "僅預覽:不建立警報、不發送通知、不進入正式運行。",
|
||||
"failedUnknown": "試跑未完成,請稍後再試",
|
||||
"targetCurrent": "目前版本(已儲存內容)"
|
||||
},
|
||||
"versions": {
|
||||
"title": "版本",
|
||||
"hint": "儲存會產生新版本並自動生效;可啟用任一歷史版本為目前。",
|
||||
"empty": "尚無版本。",
|
||||
"emptyCreate": "儲存後會產生 v1,並出現在這裡。",
|
||||
"version": "版本",
|
||||
"latest": "最新",
|
||||
"current": "目前生效",
|
||||
"publishedAt": "產生時間",
|
||||
"publishedBy": "操作人",
|
||||
"unpublished": "無版本",
|
||||
"none": "無",
|
||||
"loadFailed": "版本列表載入失敗",
|
||||
"frozenNote": "版本 {version} 已凍結,內容不可修改。更正請返回查詢修改後儲存為新版本;這裡仍可試跑預覽或啟用。",
|
||||
"info": "版本資訊",
|
||||
"readonly": "唯讀",
|
||||
"query": "查詢",
|
||||
"activated": "已切換為 {version}",
|
||||
"switchTitle": "切換版本 · {name}"
|
||||
},
|
||||
"refs": {
|
||||
"title": "引用",
|
||||
"empty": "尚無引用",
|
||||
"loadFailed": "引用載入失敗"
|
||||
},
|
||||
"publishConfirm": {
|
||||
"title": "確認發布 {version}?",
|
||||
"body": "將把目前已儲存的草稿固化為不可變版本 {version}。發布後不能修改或刪除,更正需發布新版本。",
|
||||
"ok": "確認發布",
|
||||
"cancel": "取消"
|
||||
},
|
||||
"disableConfirm": {
|
||||
"title": "停用查詢",
|
||||
"body": "停用後不能試跑預覽,記錄與已發布版本仍然保留。確定停用「{name}」嗎?",
|
||||
"ok": "停用",
|
||||
"cancel": "取消"
|
||||
},
|
||||
"disabledNote": "該查詢已停用。仍可檢視與編輯草稿,但不能試跑預覽;可在頁尾「啟用」。",
|
||||
"notFound": "查詢不存在",
|
||||
"versionNotFound": "版本不存在",
|
||||
"loadFailed": "查詢載入失敗",
|
||||
"saveFailed": "操作未完成,請稍後再試",
|
||||
"saved": "草稿已儲存",
|
||||
"savedVersion": "已儲存為 {version} 並設為目前",
|
||||
"publishNeedSave": "有未儲存修改,請先儲存",
|
||||
"published": "已儲存 {version}",
|
||||
"enabledDone": "已啟用",
|
||||
"disabledDone": "已停用",
|
||||
"errors": {
|
||||
"duplicate_name": "名稱已存在,請換一個名稱",
|
||||
"datasource_not_found": "所選資料來源不存在",
|
||||
"datasource_not_database": "只能選擇資料庫類型的資料來源",
|
||||
"template_empty": "SQL 範本不能為空",
|
||||
"param_schema_invalid": "參數 schema 不合法",
|
||||
"param_default_invalid": "參數預設值與型別不符",
|
||||
"output_schema_invalid": "輸出 schema 不合法",
|
||||
"allowed_identifiers_invalid": "允許的識別字不合法",
|
||||
"limit_invalid": "執行限制須為不小於 1 的整數",
|
||||
"disabled": "查詢已停用,不能試跑",
|
||||
"version_conflict": "版本號衝突,請重新整理後重試",
|
||||
"not_found": "記錄不存在",
|
||||
"version_immutable": "已發布版本不可修改",
|
||||
"identifier_invalid": "範本中的識別字寫法不合法",
|
||||
"identifier_not_allowed": "範本用到了未宣告允許的識別字",
|
||||
"identifier_unterminated": "範本中的識別字沒有結束",
|
||||
"missing_param": "缺少必填參數",
|
||||
"multiple_statements": "範本只能包含一條語句",
|
||||
"param_type_mismatch": "參數值與型別不符",
|
||||
"params_invalid": "參數格式不合法",
|
||||
"template_unterminated": "範本中有未閉合的引號或註解",
|
||||
"undeclared_param": "範本用到了未宣告的參數",
|
||||
"unknown_param": "傳入了未宣告的參數",
|
||||
"unsupported_engine": "該資料來源引擎暫不支援",
|
||||
"unsupported_datasource": "該資料來源類型暫不支援"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,14 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* Signed-in layout: side navigation, a top bar with the breadcrumb, and the routed page.
|
||||
* The routed page owns its own scrolling, so footers can stay outside the scroll area.
|
||||
* Signed-in layout: side navigation with brand + user footer, a top breadcrumb bar, and
|
||||
* the routed page. The routed page owns its own scrolling so footers can stay outside it.
|
||||
*/
|
||||
import { computed } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { RouterLink, RouterView, useRoute } from "vue-router";
|
||||
import { ElBreadcrumb, ElBreadcrumbItem, ElButton } from "element-plus";
|
||||
import { allowsDatasources } from "./session";
|
||||
import logoUrl from "./assets/logo.jpg";
|
||||
import { allowsDatasources, allowsQueries } from "./session";
|
||||
import { useAuthStore } from "./stores/auth";
|
||||
|
||||
defineProps<{ displayName?: string }>();
|
||||
@@ -17,21 +18,38 @@ const { t } = useI18n();
|
||||
const route = useRoute();
|
||||
const auth = useAuthStore();
|
||||
|
||||
const CRUMB_LINKS: Record<string, string> = { datasources: "/datasources" };
|
||||
const CRUMB_LINKS: Record<string, string> = { datasources: "/datasources", queries: "/queries" };
|
||||
|
||||
/** Where a non-final crumb goes. A query's "detail" crumb is the draft page of the same query. */
|
||||
function crumbLink(key: string): string | undefined {
|
||||
if (key === "detail" && route.name === "query-version" && route.params.id) {
|
||||
return `/queries/${encodeURIComponent(String(route.params.id))}`;
|
||||
}
|
||||
return CRUMB_LINKS[key];
|
||||
}
|
||||
|
||||
function crumbLabel(key: string): string {
|
||||
return key === "version"
|
||||
? t("nav.version", { no: String(route.params.versionNo ?? "") })
|
||||
: t(`nav.${key}`);
|
||||
}
|
||||
|
||||
const crumbs = computed(() => {
|
||||
let keys = (route.meta.crumbs as string[] | undefined) ?? [];
|
||||
// Roles that cannot enter datasources see the list level only.
|
||||
// Roles that cannot enter datasources or queries see the list level only.
|
||||
if (route.path.startsWith("/datasources") && !allowsDatasources(auth.user?.roles ?? [])) {
|
||||
keys = ["datasources"];
|
||||
}
|
||||
if (route.path.startsWith("/queries") && !allowsQueries(auth.user?.roles ?? [])) {
|
||||
keys = ["queries"];
|
||||
}
|
||||
const items: { label: string; to?: string }[] = [
|
||||
{ label: t("appName"), to: keys.length > 0 ? "/" : undefined },
|
||||
];
|
||||
keys.forEach((key, index) => {
|
||||
items.push({
|
||||
label: t(`nav.${key}`),
|
||||
to: index < keys.length - 1 ? CRUMB_LINKS[key] : undefined,
|
||||
label: crumbLabel(key),
|
||||
to: index < keys.length - 1 ? crumbLink(key) : undefined,
|
||||
});
|
||||
});
|
||||
return items;
|
||||
@@ -47,11 +65,14 @@ const activeClass = "!bg-[#eef0fb] !font-semibold !text-[var(--color-primary)]";
|
||||
class="flex h-screen bg-[var(--bg-surface-soft)] text-[length:var(--font-size-base)] text-[var(--text-primary)]"
|
||||
>
|
||||
<aside
|
||||
class="w-48 shrink-0 border-r border-[var(--border-subtle)] bg-white px-2.5 py-3.5"
|
||||
class="flex w-48 shrink-0 flex-col border-r border-[var(--border-subtle)] bg-white px-2.5 py-3.5"
|
||||
data-testid="side-nav"
|
||||
>
|
||||
<div class="px-2.5 pb-3.5 text-base font-bold tracking-wide">{{ t("appName") }}</div>
|
||||
<nav class="flex flex-col gap-1">
|
||||
<div class="mb-3.5 flex items-center gap-2 px-2.5" data-testid="side-brand">
|
||||
<img :src="logoUrl" alt="" class="h-7 w-7 shrink-0 object-contain" data-testid="side-logo" />
|
||||
<span class="text-base font-bold tracking-wide">{{ t("appName") }}</span>
|
||||
</div>
|
||||
<nav class="flex flex-1 flex-col gap-1">
|
||||
<RouterLink to="/" :class="linkClass" :exact-active-class="activeClass" data-testid="nav-home">
|
||||
{{ t("nav.home") }}
|
||||
</RouterLink>
|
||||
@@ -63,21 +84,36 @@ const activeClass = "!bg-[#eef0fb] !font-semibold !text-[var(--color-primary)]";
|
||||
>
|
||||
{{ t("nav.datasources") }}
|
||||
</RouterLink>
|
||||
<RouterLink
|
||||
to="/queries"
|
||||
:class="linkClass"
|
||||
:active-class="activeClass"
|
||||
data-testid="nav-queries"
|
||||
>
|
||||
{{ t("nav.queries") }}
|
||||
</RouterLink>
|
||||
</nav>
|
||||
<div
|
||||
class="mt-3 border-t border-[var(--border-subtle)] px-2.5 pt-3"
|
||||
data-testid="side-user"
|
||||
>
|
||||
<div class="mb-2 text-[13px] text-[var(--text-secondary)]" data-testid="shell-welcome">
|
||||
{{ t("shell.welcome", { name: displayName }) }}
|
||||
</div>
|
||||
<ElButton class="w-full" data-testid="logout" @click="emit('logout')">
|
||||
{{ t("login.logout") }}
|
||||
</ElButton>
|
||||
</div>
|
||||
</aside>
|
||||
<div class="flex min-w-0 flex-1 flex-col">
|
||||
<header
|
||||
class="flex h-12 shrink-0 items-center justify-between border-b border-[var(--border-subtle)] bg-white px-5"
|
||||
class="flex h-12 shrink-0 items-center border-b border-[var(--border-subtle)] bg-white px-5"
|
||||
>
|
||||
<ElBreadcrumb separator="/" data-testid="breadcrumb">
|
||||
<ElBreadcrumbItem v-for="item in crumbs" :key="item.label" :to="item.to">
|
||||
{{ item.label }}
|
||||
</ElBreadcrumbItem>
|
||||
</ElBreadcrumb>
|
||||
<div class="flex items-center gap-3">
|
||||
<span data-testid="shell-welcome">{{ t("shell.welcome", { name: displayName }) }}</span>
|
||||
<ElButton data-testid="logout" @click="emit('logout')">{{ t("login.logout") }}</ElButton>
|
||||
</div>
|
||||
</header>
|
||||
<main class="min-h-0 flex-1 overflow-hidden">
|
||||
<RouterView />
|
||||
|
||||
@@ -1,21 +1,26 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* Datasource list. The page button sits above the table, right aligned.
|
||||
* Row actions stay in the row. Disabled rows stay visible, can be enabled again and cannot be
|
||||
* tested; rows with an open circuit cannot be tested until the cooldown ends.
|
||||
* Datasource list. Filters are drafts until 查询; sort and page hit the server. Row actions
|
||||
* stay in the row. Disabled rows stay visible, can be enabled again and cannot be tested;
|
||||
* rows with an open circuit cannot be tested until the cooldown ends.
|
||||
*/
|
||||
import { onMounted, ref } from "vue";
|
||||
import { computed, onMounted, reactive, ref } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { useRouter } from "vue-router";
|
||||
import {
|
||||
ElAlert,
|
||||
ElButton,
|
||||
ElInput,
|
||||
ElMessage,
|
||||
ElMessageBox,
|
||||
ElOption,
|
||||
ElPagination,
|
||||
ElSelect,
|
||||
ElTable,
|
||||
ElTableColumn,
|
||||
vLoading,
|
||||
} from "element-plus";
|
||||
import { LIST_DEFAULT_PAGE_SIZE, LIST_PAGE_SIZES, actionsColumnWidth } from "../tableLayout";
|
||||
import { disableDatasource, enableDatasource, listDatasources } from "./client";
|
||||
import { describeError } from "./errors";
|
||||
import { engineLabel, formatDateTime } from "./format";
|
||||
@@ -25,22 +30,103 @@ const { t, te } = useI18n();
|
||||
const router = useRouter();
|
||||
|
||||
const items = ref<Datasource[]>([]);
|
||||
const total = ref(0);
|
||||
const loading = ref(true);
|
||||
const loadError = ref("");
|
||||
|
||||
const draft = reactive({ name: "", engine: "", status: "" });
|
||||
const applied = reactive({ name: "", engine: "", status: "" });
|
||||
|
||||
const page = ref(1);
|
||||
const pageSize = ref(LIST_DEFAULT_PAGE_SIZE);
|
||||
const sortBy = ref("created_at");
|
||||
const sortOrder = ref<"asc" | "desc">("asc");
|
||||
|
||||
const hasAppliedFilters = computed(
|
||||
() => applied.name.trim() !== "" || applied.engine !== "" || applied.status !== "",
|
||||
);
|
||||
/** Three row actions: edit / test / enable|disable. */
|
||||
const actionsWidth = actionsColumnWidth(3);
|
||||
|
||||
async function load(): Promise<void> {
|
||||
loading.value = true;
|
||||
loadError.value = "";
|
||||
try {
|
||||
items.value = (await listDatasources()).items;
|
||||
const enabled =
|
||||
applied.status === "enabled" ? true : applied.status === "disabled" ? false : undefined;
|
||||
const result = await listDatasources({
|
||||
name: applied.name.trim() || undefined,
|
||||
engine: applied.engine || undefined,
|
||||
enabled,
|
||||
sort_by: sortBy.value,
|
||||
sort_order: sortOrder.value,
|
||||
page: page.value,
|
||||
page_size: pageSize.value,
|
||||
});
|
||||
items.value = result.items;
|
||||
total.value = result.total;
|
||||
} catch (error) {
|
||||
loadError.value = describeError(error, t, te, "datasource.list.loadFailed");
|
||||
items.value = [];
|
||||
total.value = 0;
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Table slots type their rows loosely, so row handlers take the slot row and narrow it here.
|
||||
function applyFilters(): void {
|
||||
applied.name = draft.name;
|
||||
applied.engine = draft.engine;
|
||||
applied.status = draft.status;
|
||||
page.value = 1;
|
||||
void load();
|
||||
}
|
||||
|
||||
function resetFilters(): void {
|
||||
draft.name = "";
|
||||
draft.engine = "";
|
||||
draft.status = "";
|
||||
applied.name = "";
|
||||
applied.engine = "";
|
||||
applied.status = "";
|
||||
page.value = 1;
|
||||
void load();
|
||||
}
|
||||
|
||||
function onSortChange(payload: { prop: string | null; order: string | null }): void {
|
||||
const propMap: Record<string, string> = {
|
||||
name: "name",
|
||||
engine: "engine",
|
||||
host: "host",
|
||||
port: "port",
|
||||
database_name: "database_name",
|
||||
username: "username",
|
||||
status: "enabled",
|
||||
last_test_at: "last_test_at",
|
||||
};
|
||||
const next = payload.prop ? propMap[payload.prop] : undefined;
|
||||
if (!next || !payload.order) {
|
||||
sortBy.value = "created_at";
|
||||
sortOrder.value = "asc";
|
||||
} else {
|
||||
sortBy.value = next;
|
||||
sortOrder.value = payload.order === "ascending" ? "asc" : "desc";
|
||||
}
|
||||
page.value = 1;
|
||||
void load();
|
||||
}
|
||||
|
||||
function onPageChange(next: number): void {
|
||||
page.value = next;
|
||||
void load();
|
||||
}
|
||||
|
||||
function onSizeChange(next: number): void {
|
||||
pageSize.value = next;
|
||||
page.value = 1;
|
||||
void load();
|
||||
}
|
||||
|
||||
function asRow(source: unknown): Datasource {
|
||||
return source as Datasource;
|
||||
}
|
||||
@@ -133,10 +219,44 @@ onMounted(load);
|
||||
|
||||
<template>
|
||||
<div class="h-full overflow-auto p-5" data-testid="datasource-list">
|
||||
<div class="mb-3 flex justify-end">
|
||||
<ElButton type="primary" data-testid="datasource-create" @click="openCreate">
|
||||
{{ t("datasource.list.create") }}
|
||||
<div class="mb-3 flex flex-wrap items-center gap-2" data-testid="datasource-list-toolbar">
|
||||
<div class="w-[200px]" data-testid="datasource-filter-name">
|
||||
<ElInput v-model="draft.name" clearable :placeholder="t('datasource.list.filterName')" />
|
||||
</div>
|
||||
<div class="w-[160px]" data-testid="datasource-filter-engine">
|
||||
<ElSelect
|
||||
v-model="draft.engine"
|
||||
clearable
|
||||
class="w-full"
|
||||
:placeholder="t('datasource.list.filterEngine')"
|
||||
>
|
||||
<ElOption label="PostgreSQL" value="postgresql" />
|
||||
<ElOption label="MySQL" value="mysql" />
|
||||
<ElOption label="SQL Server" value="sqlserver" />
|
||||
</ElSelect>
|
||||
</div>
|
||||
<div class="w-[140px]" data-testid="datasource-filter-status">
|
||||
<ElSelect
|
||||
v-model="draft.status"
|
||||
clearable
|
||||
class="w-full"
|
||||
:placeholder="t('datasource.list.filterStatus')"
|
||||
>
|
||||
<ElOption :label="t('datasource.status.enabled')" value="enabled" />
|
||||
<ElOption :label="t('datasource.status.disabled')" value="disabled" />
|
||||
</ElSelect>
|
||||
</div>
|
||||
<ElButton type="primary" data-testid="datasource-filter-search" @click="applyFilters">
|
||||
{{ t("datasource.list.filterSearch") }}
|
||||
</ElButton>
|
||||
<ElButton data-testid="datasource-filter-reset" @click="resetFilters">
|
||||
{{ t("datasource.list.filterReset") }}
|
||||
</ElButton>
|
||||
<div class="ml-auto">
|
||||
<ElButton type="primary" data-testid="datasource-create" @click="openCreate">
|
||||
{{ t("datasource.list.create") }}
|
||||
</ElButton>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ElAlert
|
||||
@@ -148,83 +268,136 @@ onMounted(load);
|
||||
:closable="false"
|
||||
/>
|
||||
<div
|
||||
v-else-if="!loading && items.length === 0"
|
||||
v-else-if="!loading && total === 0 && !hasAppliedFilters"
|
||||
data-testid="datasource-empty"
|
||||
class="rounded-lg border border-dashed border-[var(--border-default)] bg-white px-5 py-14 text-center"
|
||||
>
|
||||
<h3 class="mb-1.5 text-[15px] font-semibold">{{ t("datasource.list.empty") }}</h3>
|
||||
<p class="text-[var(--text-secondary)]">{{ t("datasource.list.emptyHint") }}</p>
|
||||
</div>
|
||||
<ElTable
|
||||
v-else
|
||||
v-loading="loading"
|
||||
:data="items"
|
||||
data-testid="datasource-table"
|
||||
:row-class-name="rowClass"
|
||||
<div
|
||||
v-else-if="!loading && total === 0 && hasAppliedFilters"
|
||||
data-testid="datasource-filter-empty"
|
||||
class="rounded-lg border border-dashed border-[var(--border-default)] bg-white px-5 py-14 text-center"
|
||||
>
|
||||
<ElTableColumn prop="name" :label="t('datasource.columns.name')" min-width="140" />
|
||||
<ElTableColumn :label="t('datasource.columns.engine')" min-width="110">
|
||||
<template #default="{ row }">{{ engineLabel(row.engine) }}</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn prop="host" :label="t('datasource.columns.host')" min-width="170" />
|
||||
<ElTableColumn prop="port" :label="t('datasource.columns.port')" width="80" />
|
||||
<ElTableColumn prop="database_name" :label="t('datasource.columns.database')" min-width="130" />
|
||||
<ElTableColumn prop="username" :label="t('datasource.columns.username')" min-width="130" />
|
||||
<ElTableColumn :label="t('datasource.columns.status')" min-width="150">
|
||||
<template #default="{ row }">
|
||||
<span class="inline-flex items-center gap-1.5">
|
||||
<span
|
||||
class="h-[7px] w-[7px] rounded-full"
|
||||
:class="row.enabled ? 'bg-[#1a7f37]' : 'bg-[var(--text-muted)]'"
|
||||
/>
|
||||
{{ row.enabled ? t("datasource.status.enabled") : t("datasource.status.disabled") }}
|
||||
<span v-if="row.circuit_state === 'open'" class="text-xs text-[#cf222e]" data-testid="row-circuit-open">
|
||||
{{ t("datasource.status.circuitOpen") }}
|
||||
<h3 class="mb-1.5 text-[15px] font-semibold">{{ t("datasource.list.filterEmpty") }}</h3>
|
||||
<p class="text-[var(--text-secondary)]">{{ t("datasource.list.filterEmptyHint") }}</p>
|
||||
</div>
|
||||
<template v-else>
|
||||
<ElTable
|
||||
v-loading="loading"
|
||||
:data="items"
|
||||
row-key="id"
|
||||
data-testid="datasource-table"
|
||||
:row-class-name="rowClass"
|
||||
@sort-change="onSortChange"
|
||||
>
|
||||
<ElTableColumn prop="name" :label="t('datasource.columns.name')" min-width="140" sortable="custom" />
|
||||
<ElTableColumn prop="engine" :label="t('datasource.columns.engine')" min-width="110" sortable="custom">
|
||||
<template #default="{ row }">{{ engineLabel(row.engine) }}</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn prop="host" :label="t('datasource.columns.host')" min-width="170" sortable="custom" />
|
||||
<ElTableColumn prop="port" :label="t('datasource.columns.port')" width="90" sortable="custom" />
|
||||
<ElTableColumn
|
||||
prop="database_name"
|
||||
:label="t('datasource.columns.database')"
|
||||
min-width="130"
|
||||
sortable="custom"
|
||||
/>
|
||||
<ElTableColumn
|
||||
prop="username"
|
||||
:label="t('datasource.columns.username')"
|
||||
min-width="130"
|
||||
sortable="custom"
|
||||
/>
|
||||
<ElTableColumn prop="status" :label="t('datasource.columns.status')" min-width="150" sortable="custom">
|
||||
<template #default="{ row }">
|
||||
<span class="inline-flex items-center gap-1.5">
|
||||
<span
|
||||
class="h-[7px] w-[7px] rounded-full"
|
||||
:class="row.enabled ? 'bg-[#1a7f37]' : 'bg-[var(--text-muted)]'"
|
||||
/>
|
||||
{{ row.enabled ? t("datasource.status.enabled") : t("datasource.status.disabled") }}
|
||||
<span
|
||||
v-if="row.circuit_state === 'open'"
|
||||
class="text-xs text-[#cf222e]"
|
||||
data-testid="row-circuit-open"
|
||||
>
|
||||
{{ t("datasource.status.circuitOpen") }}
|
||||
</span>
|
||||
</span>
|
||||
</span>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn :label="t('datasource.columns.lastTest')" min-width="190">
|
||||
<template #default="{ row }">
|
||||
<span
|
||||
:class="
|
||||
row.last_test_category === 'success'
|
||||
? 'text-[#1a7f37]'
|
||||
: row.last_test_category
|
||||
? 'text-[#cf222e]'
|
||||
: 'text-[var(--text-muted)]'
|
||||
"
|
||||
>
|
||||
{{ lastTestText(row) }}
|
||||
</span>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn :label="t('datasource.columns.actions')" width="148" fixed="right">
|
||||
<template #default="{ row }">
|
||||
<div class="whitespace-nowrap" :data-testid="`datasource-row-${row.id}`">
|
||||
<ElButton link type="primary" data-testid="row-edit" @click="openDetail(row)">
|
||||
{{ t("datasource.actions.edit") }}
|
||||
</ElButton>
|
||||
<ElButton
|
||||
link
|
||||
type="primary"
|
||||
data-testid="row-test"
|
||||
:disabled="testBlocked(row)"
|
||||
:title="testTitle(row)"
|
||||
@click="openTest(row)"
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn
|
||||
prop="last_test_at"
|
||||
:label="t('datasource.columns.lastTest')"
|
||||
min-width="190"
|
||||
sortable="custom"
|
||||
>
|
||||
<template #default="{ row }">
|
||||
<span
|
||||
:class="
|
||||
row.last_test_category === 'success'
|
||||
? 'text-[#1a7f37]'
|
||||
: row.last_test_category
|
||||
? 'text-[#cf222e]'
|
||||
: 'text-[var(--text-muted)]'
|
||||
"
|
||||
>
|
||||
{{ t("datasource.actions.test") }}
|
||||
</ElButton>
|
||||
<ElButton v-if="row.enabled" link type="danger" data-testid="row-disable" @click="disable(row)">
|
||||
{{ t("datasource.actions.disable") }}
|
||||
</ElButton>
|
||||
<ElButton v-else link type="success" data-testid="row-enable" @click="enable(row)">
|
||||
{{ t("datasource.actions.enable") }}
|
||||
</ElButton>
|
||||
</div>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
</ElTable>
|
||||
{{ lastTestText(row) }}
|
||||
</span>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn
|
||||
:label="t('datasource.columns.actions')"
|
||||
:width="actionsWidth"
|
||||
align="right"
|
||||
fixed="right"
|
||||
>
|
||||
<template #default="{ row }">
|
||||
<div class="whitespace-nowrap" :data-testid="`datasource-row-${row.id}`">
|
||||
<ElButton link type="primary" data-testid="row-edit" @click="openDetail(row)">
|
||||
{{ t("datasource.actions.edit") }}
|
||||
</ElButton>
|
||||
<ElButton
|
||||
link
|
||||
type="primary"
|
||||
data-testid="row-test"
|
||||
:disabled="testBlocked(row)"
|
||||
:title="testTitle(row)"
|
||||
@click="openTest(row)"
|
||||
>
|
||||
{{ t("datasource.actions.test") }}
|
||||
</ElButton>
|
||||
<ElButton
|
||||
v-if="row.enabled"
|
||||
link
|
||||
type="danger"
|
||||
data-testid="row-disable"
|
||||
@click="disable(row)"
|
||||
>
|
||||
{{ t("datasource.actions.disable") }}
|
||||
</ElButton>
|
||||
<ElButton v-else link type="success" data-testid="row-enable" @click="enable(row)">
|
||||
{{ t("datasource.actions.enable") }}
|
||||
</ElButton>
|
||||
</div>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
</ElTable>
|
||||
<div class="mt-3 flex justify-end" data-testid="datasource-pagination">
|
||||
<ElPagination
|
||||
background
|
||||
layout="total, sizes, prev, pager, next"
|
||||
:total="total"
|
||||
:page-size="pageSize"
|
||||
:page-sizes="[...LIST_PAGE_SIZES]"
|
||||
:current-page="page"
|
||||
@current-change="onPageChange"
|
||||
@size-change="onSizeChange"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -6,14 +6,32 @@ import type {
|
||||
ConnectionTestOutcome,
|
||||
Datasource,
|
||||
DatasourceList,
|
||||
DatasourceListParams,
|
||||
DatasourceReferences,
|
||||
DraftTestOutcome,
|
||||
} from "./types";
|
||||
|
||||
const JSON_HEADERS = { "Content-Type": "application/json" };
|
||||
|
||||
export function listDatasources(): Promise<DatasourceList> {
|
||||
return api<DatasourceList>("/datasources");
|
||||
function toQuery(params?: DatasourceListParams): string {
|
||||
if (!params) {
|
||||
return "";
|
||||
}
|
||||
const q = new URLSearchParams();
|
||||
if (params.name) q.set("name", params.name);
|
||||
if (params.engine) q.set("engine", params.engine);
|
||||
if (params.enabled !== undefined) q.set("enabled", String(params.enabled));
|
||||
if (params.sort_by) q.set("sort_by", params.sort_by);
|
||||
if (params.sort_order) q.set("sort_order", params.sort_order);
|
||||
if (params.page !== undefined) q.set("page", String(params.page));
|
||||
if (params.page_size !== undefined) q.set("page_size", String(params.page_size));
|
||||
if (params.usable) q.set("usable", "true");
|
||||
const text = q.toString();
|
||||
return text ? `?${text}` : "";
|
||||
}
|
||||
|
||||
export function listDatasources(params?: DatasourceListParams): Promise<DatasourceList> {
|
||||
return api<DatasourceList>(`/datasources${toQuery(params)}`);
|
||||
}
|
||||
|
||||
export function getDatasource(id: string): Promise<Datasource> {
|
||||
|
||||
@@ -48,7 +48,24 @@ export type Datasource = {
|
||||
updated_at: string | null;
|
||||
};
|
||||
|
||||
export type DatasourceList = { items: Datasource[] };
|
||||
export type DatasourceList = {
|
||||
items: Datasource[];
|
||||
total: number;
|
||||
page: number;
|
||||
page_size: number;
|
||||
};
|
||||
|
||||
/** Console list query params; omit fields the server should ignore. */
|
||||
export type DatasourceListParams = {
|
||||
name?: string;
|
||||
engine?: string;
|
||||
enabled?: boolean;
|
||||
sort_by?: string;
|
||||
sort_order?: "asc" | "desc";
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
usable?: boolean;
|
||||
};
|
||||
|
||||
export type DatasourceReferences = { id: string; items: unknown[] };
|
||||
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* Allowed identifiers: closable tags plus an input (Enter or the add button). Only names the
|
||||
* backend accepts are added. Readonly shows the frozen list without the input.
|
||||
* Boundary: these names are the only ones allowed in the template's `{{name}}` identifier
|
||||
* position; values still go through parameters.
|
||||
*/
|
||||
import { ref } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { ElButton, ElInput, ElTag } from "element-plus";
|
||||
import { isValidIdentifier } from "./validation";
|
||||
|
||||
const props = defineProps<{ modelValue: string[]; readonly?: boolean }>();
|
||||
const emit = defineEmits<{ "update:modelValue": [items: string[]] }>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const input = ref("");
|
||||
const problem = ref("");
|
||||
|
||||
function add(): void {
|
||||
const value = input.value.trim();
|
||||
problem.value = "";
|
||||
if (value === "") {
|
||||
return;
|
||||
}
|
||||
if (!isValidIdentifier(value)) {
|
||||
problem.value = t("query.identifiers.invalid", { name: value });
|
||||
return;
|
||||
}
|
||||
if (!props.modelValue.includes(value)) {
|
||||
emit("update:modelValue", [...props.modelValue, value]);
|
||||
}
|
||||
input.value = "";
|
||||
}
|
||||
|
||||
function remove(name: string): void {
|
||||
emit(
|
||||
"update:modelValue",
|
||||
props.modelValue.filter((item) => item !== name),
|
||||
);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div data-testid="identifiers-block">
|
||||
<div class="flex flex-wrap items-center gap-1.5" data-testid="identifier-tags">
|
||||
<span v-if="modelValue.length === 0" class="text-[var(--text-muted)]">
|
||||
{{ t("query.identifiers.none") }}
|
||||
</span>
|
||||
<ElTag
|
||||
v-for="name in modelValue"
|
||||
:key="name"
|
||||
:closable="!readonly"
|
||||
effect="plain"
|
||||
data-testid="identifier-tag"
|
||||
@close="remove(name)"
|
||||
>
|
||||
{{ name }}
|
||||
</ElTag>
|
||||
</div>
|
||||
<div v-if="!readonly" class="mt-2.5 flex max-w-md gap-2">
|
||||
<ElInput
|
||||
v-model="input"
|
||||
data-testid="identifier-input"
|
||||
:placeholder="t('query.identifiers.placeholder')"
|
||||
@keyup.enter="add"
|
||||
/>
|
||||
<ElButton data-testid="identifier-add" @click="add">{{ t("query.actions.add") }}</ElButton>
|
||||
</div>
|
||||
<p v-if="problem" class="mt-1.5 text-[var(--el-color-danger)]" data-testid="identifier-problem">
|
||||
{{ problem }}
|
||||
</p>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,77 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* Output schema table (the contract used to check result types): editable name and type rows
|
||||
* for the draft, or plain text when `readonly` (a frozen version).
|
||||
*/
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { ElButton, ElInput, ElOption, ElSelect, ElTable, ElTableColumn } from "element-plus";
|
||||
import { newOutputRow } from "./payload";
|
||||
import { OUTPUT_TYPES, type OutputRow } from "./types";
|
||||
|
||||
const props = defineProps<{ modelValue: OutputRow[]; readonly?: boolean }>();
|
||||
const emit = defineEmits<{ "update:modelValue": [rows: OutputRow[]] }>();
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
function add(): void {
|
||||
emit("update:modelValue", [...props.modelValue, newOutputRow()]);
|
||||
}
|
||||
|
||||
function remove(key: number): void {
|
||||
emit(
|
||||
"update:modelValue",
|
||||
props.modelValue.filter((row) => row.key !== key),
|
||||
);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div data-testid="outputs-block">
|
||||
<div v-if="!readonly" class="mb-2 flex justify-end">
|
||||
<ElButton data-testid="output-add" @click="add">{{ t("query.outputs.add") }}</ElButton>
|
||||
</div>
|
||||
<p
|
||||
v-if="modelValue.length === 0"
|
||||
data-testid="outputs-empty"
|
||||
class="rounded-lg border border-dashed border-[var(--border-default)] px-5 py-4 text-center text-[var(--text-secondary)]"
|
||||
>
|
||||
{{ t("query.outputs.empty") }}
|
||||
</p>
|
||||
<ElTable v-else :data="modelValue" row-key="key" data-testid="outputs-table">
|
||||
<ElTableColumn :label="t('query.outputs.name')" min-width="200">
|
||||
<template #default="{ row }">
|
||||
<ElInput
|
||||
v-if="!readonly"
|
||||
v-model="row.name"
|
||||
class="query-mono"
|
||||
data-testid="output-name"
|
||||
:placeholder="t('query.outputs.namePlaceholder')"
|
||||
/>
|
||||
<span v-else class="query-mono">{{ row.name }}</span>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn :label="t('query.outputs.type')" min-width="160">
|
||||
<template #default="{ row }">
|
||||
<ElSelect v-if="!readonly" v-model="row.type" class="w-full" data-testid="output-type">
|
||||
<ElOption v-for="type in OUTPUT_TYPES" :key="type" :label="type" :value="type" />
|
||||
</ElSelect>
|
||||
<span v-else class="query-mono">{{ row.type }}</span>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn v-if="!readonly" :label="t('query.columns.actions')" width="90" align="right">
|
||||
<template #default="{ row }">
|
||||
<ElButton link type="danger" data-testid="output-remove" @click="remove(row.key)">
|
||||
{{ t("query.actions.remove") }}
|
||||
</ElButton>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
</ElTable>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.query-mono,
|
||||
.query-mono :deep(input) {
|
||||
font-family: ui-monospace, SFMono-Regular, Consolas, monospace;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,108 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* Parameter schema table. Editable rows (name, type, required, default) for the draft, or
|
||||
* plain text when `readonly` (a frozen version). Rows are removed in the row; adding sits
|
||||
* above the table. The default is kept as text and converted by type when the body is built.
|
||||
*/
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { ElButton, ElCheckbox, ElInput, ElOption, ElSelect, ElTable, ElTableColumn } from "element-plus";
|
||||
import { newParamRow } from "./payload";
|
||||
import { VALUE_TYPES, type ParamRow } from "./types";
|
||||
|
||||
const props = defineProps<{ modelValue: ParamRow[]; readonly?: boolean }>();
|
||||
const emit = defineEmits<{ "update:modelValue": [rows: ParamRow[]] }>();
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
function add(): void {
|
||||
emit("update:modelValue", [...props.modelValue, newParamRow()]);
|
||||
}
|
||||
|
||||
function remove(key: number): void {
|
||||
emit(
|
||||
"update:modelValue",
|
||||
props.modelValue.filter((row) => row.key !== key),
|
||||
);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div data-testid="params-block">
|
||||
<div v-if="!readonly" class="mb-2 flex justify-end">
|
||||
<ElButton data-testid="param-add" @click="add">{{ t("query.params.add") }}</ElButton>
|
||||
</div>
|
||||
<p
|
||||
v-if="modelValue.length === 0"
|
||||
data-testid="params-empty"
|
||||
class="rounded-lg border border-dashed border-[var(--border-default)] px-5 py-4 text-center text-[var(--text-secondary)]"
|
||||
>
|
||||
{{ t("query.params.empty") }}
|
||||
</p>
|
||||
<ElTable v-else :data="modelValue" row-key="key" data-testid="params-table">
|
||||
<ElTableColumn :label="t('query.params.name')" min-width="170">
|
||||
<template #default="{ row }">
|
||||
<ElInput
|
||||
v-if="!readonly"
|
||||
v-model="row.name"
|
||||
class="query-mono"
|
||||
data-testid="param-name"
|
||||
:placeholder="t('query.params.namePlaceholder')"
|
||||
/>
|
||||
<span v-else class="query-mono">{{ row.name }}</span>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn :label="t('query.params.type')" min-width="130">
|
||||
<template #default="{ row }">
|
||||
<ElSelect v-if="!readonly" v-model="row.type" class="w-full" data-testid="param-type">
|
||||
<ElOption v-for="type in VALUE_TYPES" :key="type" :label="type" :value="type" />
|
||||
</ElSelect>
|
||||
<span v-else class="query-mono">{{ row.type }}</span>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn :label="t('query.params.required')" width="90">
|
||||
<template #default="{ row }">
|
||||
<ElCheckbox v-if="!readonly" v-model="row.required" data-testid="param-required" />
|
||||
<span v-else>{{ row.required ? t("query.params.yes") : t("query.params.no") }}</span>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn :label="t('query.params.default')" min-width="170">
|
||||
<template #default="{ row }">
|
||||
<template v-if="!readonly">
|
||||
<ElSelect
|
||||
v-if="row.type === 'boolean'"
|
||||
v-model="row.defaultText"
|
||||
class="w-full"
|
||||
clearable
|
||||
data-testid="param-default"
|
||||
:placeholder="t('query.params.defaultPlaceholder')"
|
||||
>
|
||||
<ElOption label="true" value="true" />
|
||||
<ElOption label="false" value="false" />
|
||||
</ElSelect>
|
||||
<ElInput
|
||||
v-else
|
||||
v-model="row.defaultText"
|
||||
data-testid="param-default"
|
||||
:placeholder="t('query.params.defaultPlaceholder')"
|
||||
/>
|
||||
</template>
|
||||
<span v-else class="query-mono">{{ row.defaultText === "" ? "—" : row.defaultText }}</span>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn v-if="!readonly" :label="t('query.columns.actions')" width="90" align="right">
|
||||
<template #default="{ row }">
|
||||
<ElButton link type="danger" data-testid="param-remove" @click="remove(row.key)">
|
||||
{{ t("query.actions.remove") }}
|
||||
</ElButton>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
</ElTable>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.query-mono,
|
||||
.query-mono :deep(input) {
|
||||
font-family: ui-monospace, SFMono-Regular, Consolas, monospace;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,276 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* Trial-run panel: parameter inputs plus the outcome of the last run. It only displays; the
|
||||
* page owns the footer button and the request. Outcomes are held in memory for display only.
|
||||
* The five outcomes stay visually and verbally apart: success, empty (not an error), illegal
|
||||
* type (contract mismatch), failure (timeout / connection / SQL kinds) and refused (disabled,
|
||||
* circuit open). Sample values of sensitive-looking columns arrive already masked by the API.
|
||||
*/
|
||||
import { computed } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { ElAlert, ElForm, ElFormItem, ElInput, ElOption, ElSelect, ElTable, ElTableColumn, ElTag } from "element-plus";
|
||||
import { formatCell, formatDateTime } from "./format";
|
||||
import type { PreviewSpec } from "./payload";
|
||||
import { isConnectionKind, type PreviewView } from "./preview";
|
||||
|
||||
const props = defineProps<{
|
||||
specs: PreviewSpec[];
|
||||
modelValue: Record<string, string>;
|
||||
view: PreviewView;
|
||||
/** "current" runs the saved current version; "version" runs a frozen version. */
|
||||
target: "current" | "version" | "draft";
|
||||
versionNo?: number;
|
||||
/** Unsaved edits exist: the run would use the saved current version, so it is blocked. */
|
||||
dirty?: boolean;
|
||||
/** Nothing saved yet (create): there is nothing to run. */
|
||||
needSave?: boolean;
|
||||
limits: { timeout_ms: number; max_rows: number } | null;
|
||||
datasourceName: string;
|
||||
invalid: string[];
|
||||
}>();
|
||||
const emit = defineEmits<{ "update:modelValue": [values: Record<string, string>] }>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
|
||||
const targetLabel = computed(() =>
|
||||
props.target === "version"
|
||||
? t("query.preview.targetVersion", { no: props.versionNo ?? "" })
|
||||
: t("query.preview.targetCurrent"),
|
||||
);
|
||||
|
||||
function setValue(name: string, value: string | undefined): void {
|
||||
emit("update:modelValue", { ...props.modelValue, [name]: value ?? "" });
|
||||
}
|
||||
|
||||
function placeholder(type: string): string {
|
||||
return type === "datetime" ? "YYYY-MM-DD HH:MM:SS" : "";
|
||||
}
|
||||
|
||||
const failureKind = computed(() => {
|
||||
if (props.view.kind !== "failure") {
|
||||
return "";
|
||||
}
|
||||
return te(`query.preview.failure.${props.view.failureKind}.title`) ? props.view.failureKind : "unknown";
|
||||
});
|
||||
|
||||
/** Validation failures carry a stable reason; show its wording when we have one. */
|
||||
const failureDetail = computed(() => {
|
||||
if (props.view.kind !== "failure") {
|
||||
return "";
|
||||
}
|
||||
const reason = props.view.outcome.details?.reason;
|
||||
if (typeof reason === "string" && te(`query.errors.${reason}`)) {
|
||||
return t(`query.errors.${reason}`);
|
||||
}
|
||||
return "";
|
||||
});
|
||||
|
||||
const failureMaxRows = computed(() =>
|
||||
props.view.kind === "failure" ? String(props.view.outcome.details?.max_rows ?? props.limits?.max_rows ?? "") : "",
|
||||
);
|
||||
|
||||
const circuitUntil = computed(() => (props.view.kind === "circuit_open" ? formatDateTime(props.view.until) : ""));
|
||||
|
||||
const maskedColumns = computed(() =>
|
||||
props.view.kind === "success" || props.view.kind === "empty" ? props.view.outcome.masked_columns ?? [] : [],
|
||||
);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section
|
||||
class="mb-4 rounded-lg border border-[var(--border-subtle)] bg-white px-[18px] py-4"
|
||||
data-testid="preview-card"
|
||||
>
|
||||
<h3 class="mb-1 text-[14.5px] font-semibold">{{ t("query.preview.title") }}</h3>
|
||||
<p class="mb-2.5 text-[var(--text-secondary)]">
|
||||
{{ t("query.preview.target") }}<b data-testid="preview-target">{{ targetLabel }}</b>
|
||||
</p>
|
||||
<ElAlert
|
||||
v-if="dirty"
|
||||
class="mb-2.5"
|
||||
type="warning"
|
||||
data-testid="preview-dirty"
|
||||
:title="t('query.preview.dirtyNote')"
|
||||
show-icon
|
||||
:closable="false"
|
||||
/>
|
||||
<ElAlert
|
||||
v-else-if="needSave"
|
||||
class="mb-2.5"
|
||||
type="info"
|
||||
data-testid="preview-need-save"
|
||||
:title="t('query.preview.needSaveNote')"
|
||||
show-icon
|
||||
:closable="false"
|
||||
/>
|
||||
|
||||
<p v-if="specs.length === 0" class="mb-3 text-[var(--text-muted)]" data-testid="preview-no-params">
|
||||
{{ t("query.preview.noParams") }}
|
||||
</p>
|
||||
<ElForm v-else label-position="top" class="max-w-3xl" data-testid="preview-params" @submit.prevent>
|
||||
<div class="grid grid-cols-1 gap-x-5 sm:grid-cols-3">
|
||||
<ElFormItem
|
||||
v-for="spec in specs"
|
||||
:key="spec.name"
|
||||
:label="`${spec.name} · ${spec.type}${spec.required ? ' *' : ''}`"
|
||||
:error="invalid.includes(spec.name) ? t('query.preview.invalidValue') : ''"
|
||||
:data-testid="`preview-param-${spec.name}`"
|
||||
>
|
||||
<ElSelect
|
||||
v-if="spec.type === 'boolean'"
|
||||
:model-value="modelValue[spec.name] ?? ''"
|
||||
class="w-full"
|
||||
clearable
|
||||
:placeholder="t('query.preview.unset')"
|
||||
@update:model-value="setValue(spec.name, $event)"
|
||||
>
|
||||
<ElOption label="true" value="true" />
|
||||
<ElOption label="false" value="false" />
|
||||
</ElSelect>
|
||||
<ElInput
|
||||
v-else
|
||||
:model-value="modelValue[spec.name] ?? ''"
|
||||
:placeholder="placeholder(spec.type)"
|
||||
@update:model-value="setValue(spec.name, $event)"
|
||||
/>
|
||||
</ElFormItem>
|
||||
</div>
|
||||
</ElForm>
|
||||
|
||||
<div data-testid="preview-result" :data-status="view.kind" :data-failure-kind="failureKind">
|
||||
<p
|
||||
v-if="view.kind === 'none'"
|
||||
data-testid="preview-none"
|
||||
class="rounded-lg border border-[var(--border-subtle)] bg-[var(--bg-surface-soft)] px-3 py-2 text-[var(--text-secondary)]"
|
||||
>
|
||||
{{ t("query.preview.none") }}
|
||||
</p>
|
||||
|
||||
<ElAlert
|
||||
v-else-if="view.kind === 'running'"
|
||||
type="info"
|
||||
data-testid="preview-running"
|
||||
:title="t('query.preview.running')"
|
||||
show-icon
|
||||
:closable="false"
|
||||
/>
|
||||
|
||||
<template v-else-if="view.kind === 'success' || view.kind === 'empty'">
|
||||
<ElAlert
|
||||
:type="view.kind === 'success' ? 'success' : 'info'"
|
||||
:title="t(`query.preview.${view.kind}.title`)"
|
||||
:description="
|
||||
view.kind === 'success'
|
||||
? t('query.preview.success.body', { count: view.outcome.row_count })
|
||||
: t('query.preview.empty.body')
|
||||
"
|
||||
show-icon
|
||||
:closable="false"
|
||||
/>
|
||||
<ElTable
|
||||
v-if="view.kind === 'success' && view.outcome.columns.length > 0"
|
||||
class="mt-2.5"
|
||||
:data="view.outcome.rows"
|
||||
data-testid="preview-table"
|
||||
>
|
||||
<ElTableColumn
|
||||
v-for="column in view.outcome.columns"
|
||||
:key="column"
|
||||
:prop="column"
|
||||
min-width="130"
|
||||
>
|
||||
<template #header>
|
||||
{{ column }}
|
||||
<ElTag
|
||||
v-if="maskedColumns.includes(column)"
|
||||
type="warning"
|
||||
effect="light"
|
||||
size="small"
|
||||
:data-testid="`masked-${column}`"
|
||||
>
|
||||
{{ t("query.preview.masked") }}
|
||||
</ElTag>
|
||||
</template>
|
||||
<template #default="{ row }">{{ formatCell(row[column]) }}</template>
|
||||
</ElTableColumn>
|
||||
</ElTable>
|
||||
</template>
|
||||
|
||||
<template v-else-if="view.kind === 'illegal_type'">
|
||||
<ElAlert
|
||||
type="warning"
|
||||
:title="t('query.preview.illegal.title')"
|
||||
:description="t('query.preview.illegal.body')"
|
||||
show-icon
|
||||
:closable="false"
|
||||
/>
|
||||
<ElTable class="mt-2.5" :data="view.outcome.details?.fields ?? []" data-testid="preview-problems">
|
||||
<ElTableColumn :label="t('query.preview.illegal.row')" width="80">
|
||||
<template #default="{ row }">{{ Number(row.row) + 1 }}</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn prop="field" :label="t('query.preview.illegal.field')" min-width="140" />
|
||||
<ElTableColumn prop="expected" :label="t('query.preview.illegal.expected')" min-width="120" />
|
||||
<ElTableColumn prop="actual" :label="t('query.preview.illegal.actual')" min-width="120" />
|
||||
</ElTable>
|
||||
</template>
|
||||
|
||||
<template v-else-if="view.kind === 'failure'">
|
||||
<ElAlert
|
||||
:type="view.failureKind === 'timeout' ? 'warning' : 'error'"
|
||||
:title="t(`query.preview.failure.${failureKind}.title`)"
|
||||
:description="
|
||||
[t(`query.preview.failure.${failureKind}.body`, { max_rows: failureMaxRows }), failureDetail]
|
||||
.filter((text) => text !== '')
|
||||
.join(' ')
|
||||
"
|
||||
show-icon
|
||||
:closable="false"
|
||||
/>
|
||||
<p class="mt-2 text-xs text-[var(--text-secondary)]" data-testid="preview-failure-note">
|
||||
{{
|
||||
isConnectionKind(view.failureKind)
|
||||
? t("query.preview.failure.noteCircuit")
|
||||
: t("query.preview.failure.noteNoCircuit")
|
||||
}}
|
||||
</p>
|
||||
</template>
|
||||
|
||||
<ElAlert
|
||||
v-else-if="view.kind === 'disabled'"
|
||||
type="warning"
|
||||
:title="t('query.preview.disabled.title')"
|
||||
:description="
|
||||
view.scope === 'query' ? t('query.preview.disabled.queryBody') : t('query.preview.disabled.sourceBody')
|
||||
"
|
||||
show-icon
|
||||
:closable="false"
|
||||
/>
|
||||
|
||||
<ElAlert
|
||||
v-else-if="view.kind === 'circuit_open'"
|
||||
type="error"
|
||||
:title="t('query.preview.circuit.title')"
|
||||
:description="t('query.preview.circuit.body', { until: circuitUntil })"
|
||||
show-icon
|
||||
:closable="false"
|
||||
/>
|
||||
|
||||
<ElAlert
|
||||
v-else
|
||||
type="error"
|
||||
data-testid="preview-error"
|
||||
:title="view.text"
|
||||
show-icon
|
||||
:closable="false"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<p class="mt-2 text-xs text-[var(--text-secondary)]" data-testid="preview-meta">
|
||||
<template v-if="limits">
|
||||
timeout_ms={{ limits.timeout_ms }} · max_rows={{ limits.max_rows }} ·
|
||||
{{ t("query.preview.datasource", { name: datasourceName }) }}<br />
|
||||
</template>
|
||||
{{ t("query.preview.onlyPreview") }}
|
||||
</p>
|
||||
</section>
|
||||
</template>
|
||||
@@ -0,0 +1,673 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* Query create and edit page (one form, two modes chosen by the route).
|
||||
* Footer: 返回列表, 保存, 停用/启用, 试跑预览. Save creates v1 on create, or saves a new
|
||||
* immutable version (and activates it) when content changed; metadata-only saves PATCH.
|
||||
* Trial run uses the saved current version; unsaved edits disable 试跑预览.
|
||||
*/
|
||||
import { computed, nextTick, onMounted, reactive, ref } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { useRoute, useRouter } from "vue-router";
|
||||
import {
|
||||
ElAlert,
|
||||
ElButton,
|
||||
ElForm,
|
||||
ElFormItem,
|
||||
ElInput,
|
||||
ElInputNumber,
|
||||
ElMessage,
|
||||
ElMessageBox,
|
||||
ElOption,
|
||||
ElSelect,
|
||||
ElTag,
|
||||
type FormInstance,
|
||||
type FormRules,
|
||||
} from "element-plus";
|
||||
import { listDatasources } from "../datasources/client";
|
||||
import type { Datasource } from "../datasources/types";
|
||||
import {
|
||||
createQuery,
|
||||
disableQuery,
|
||||
enableQuery,
|
||||
getQuery,
|
||||
getReferences,
|
||||
listVersions,
|
||||
previewCurrent,
|
||||
saveQueryVersion,
|
||||
updateQuery,
|
||||
} from "./client";
|
||||
import { describeError, isNotFound } from "./errors";
|
||||
import { versionLabel } from "./format";
|
||||
import IdentifierTags from "./IdentifierTags.vue";
|
||||
import OutputsTable from "./OutputsTable.vue";
|
||||
import ParamsTable from "./ParamsTable.vue";
|
||||
import {
|
||||
buildMetadataPayload,
|
||||
buildPayload,
|
||||
buildPreviewParams,
|
||||
buildVersionContent,
|
||||
emptyForm,
|
||||
formFromRecord,
|
||||
formSnapshot,
|
||||
initialPreviewValues,
|
||||
specsFromSchema,
|
||||
} from "./payload";
|
||||
import PreviewPanel from "./PreviewPanel.vue";
|
||||
import { viewFromError, viewFromOutcome, type PreviewView } from "./preview";
|
||||
import { ROWS_RANGE, TIMEOUT_RANGE, type QueryDetail, type VersionSummary } from "./types";
|
||||
import {
|
||||
firstOutputIssue,
|
||||
firstParamIssue,
|
||||
isFilledText,
|
||||
isIntegerInRange,
|
||||
sqlParamStatus,
|
||||
} from "./validation";
|
||||
import VersionsTable from "./VersionsTable.vue";
|
||||
|
||||
const { t, te } = useI18n();
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
|
||||
/** How a template names an allowed identifier; built in script because the braces clash with the template syntax. */
|
||||
const IDENTIFIER_EXAMPLE = `${"{{"}name${"}}"}`;
|
||||
|
||||
const isCreate = route.name === "query-create";
|
||||
const queryId = isCreate ? "" : String(route.params.id ?? "");
|
||||
|
||||
const formRef = ref<FormInstance>();
|
||||
const previewAnchor = ref<HTMLElement>();
|
||||
const form = reactive(emptyForm());
|
||||
const record = ref<QueryDetail | null>(null);
|
||||
/** Text of the form as last saved (or loaded); a difference means unsaved edits. */
|
||||
const savedSnapshot = ref(formSnapshot(form));
|
||||
const loaded = ref(false);
|
||||
const loadError = ref("");
|
||||
const saving = ref(false);
|
||||
const saveError = ref("");
|
||||
const busy = ref(false);
|
||||
const datasources = ref<Datasource[]>([]);
|
||||
const datasourcesError = ref("");
|
||||
const versions = ref<VersionSummary[]>([]);
|
||||
const versionsError = ref("");
|
||||
const references = ref<{ name?: string; id?: string }[] | null>(null);
|
||||
const referencesError = ref("");
|
||||
const previewView = ref<PreviewView>({ kind: "none" });
|
||||
const previewValues = ref<Record<string, string>>({});
|
||||
const previewInvalid = ref<string[]>([]);
|
||||
|
||||
type Validator = (rule: unknown, value: unknown, callback: (error?: Error) => void) => void;
|
||||
|
||||
const trigger = ["blur", "change"];
|
||||
const requiredText = () => ({
|
||||
validator: ((_rule, value, callback) =>
|
||||
isFilledText(value) ? callback() : callback(new Error(t("query.form.required")))) as Validator,
|
||||
trigger,
|
||||
});
|
||||
const integerIn = (min: number, max: number) => ({
|
||||
validator: ((_rule, value, callback) => {
|
||||
if (value === null || value === undefined || value === "") {
|
||||
return callback(new Error(t("query.form.required")));
|
||||
}
|
||||
return isIntegerInRange(value, min, max)
|
||||
? callback()
|
||||
: callback(new Error(t("query.form.invalidRange", { min, max })));
|
||||
}) as Validator,
|
||||
trigger,
|
||||
});
|
||||
|
||||
const rules = computed<FormRules>(() => ({
|
||||
name: [
|
||||
requiredText(),
|
||||
{
|
||||
max: 128,
|
||||
message: t("query.form.nameTooLong"),
|
||||
trigger,
|
||||
},
|
||||
],
|
||||
datasource_id: [requiredText()],
|
||||
sql_template: [requiredText()],
|
||||
params: [
|
||||
{
|
||||
validator: ((_rule, _value, callback) => {
|
||||
const problem = firstParamIssue(form.params);
|
||||
return problem
|
||||
? callback(new Error(t(`query.params.${problem.issue}`, { name: problem.name })))
|
||||
: callback();
|
||||
}) as Validator,
|
||||
trigger,
|
||||
},
|
||||
],
|
||||
outputs: [
|
||||
{
|
||||
validator: ((_rule, _value, callback) => {
|
||||
const problem = firstOutputIssue(form.outputs);
|
||||
return problem
|
||||
? callback(new Error(t(`query.outputs.${problem.issue}`, { name: problem.name })))
|
||||
: callback();
|
||||
}) as Validator,
|
||||
trigger,
|
||||
},
|
||||
],
|
||||
timeout_ms: [integerIn(TIMEOUT_RANGE.min, TIMEOUT_RANGE.max)],
|
||||
max_rows: [integerIn(ROWS_RANGE.min, ROWS_RANGE.max)],
|
||||
}));
|
||||
|
||||
const databaseSources = computed(() => datasources.value.filter((item) => item.kind === "database"));
|
||||
const recordEnabled = computed(() => record.value?.enabled === true);
|
||||
const dirty = computed(() => !isCreate && record.value !== null && formSnapshot(form) !== savedSnapshot.value);
|
||||
const previewSpecs = computed(() => specsFromSchema(record.value?.current.param_schema ?? []));
|
||||
const previewRunning = computed(() => previewView.value.kind === "running");
|
||||
const sqlStatus = computed(() =>
|
||||
sqlParamStatus(
|
||||
form.sql_template,
|
||||
form.params.map((row) => row.name),
|
||||
),
|
||||
);
|
||||
const sourceName = computed(
|
||||
() => datasources.value.find((item) => item.id === record.value?.datasource_id)?.name ?? "",
|
||||
);
|
||||
const currentLabel = computed(
|
||||
() => versionLabel(record.value?.current_version_no) ?? t("query.versions.none"),
|
||||
);
|
||||
const previewLimits = computed(() =>
|
||||
record.value
|
||||
? { timeout_ms: record.value.current.timeout_ms, max_rows: record.value.current.max_rows }
|
||||
: null,
|
||||
);
|
||||
|
||||
function applyRecord(row: QueryDetail): void {
|
||||
record.value = row;
|
||||
const next = formFromRecord(row);
|
||||
Object.assign(form, next);
|
||||
savedSnapshot.value = formSnapshot(form);
|
||||
previewValues.value = initialPreviewValues(previewSpecs.value, previewValues.value);
|
||||
}
|
||||
|
||||
function backToList(): void {
|
||||
void router.push({ name: "query-list" });
|
||||
}
|
||||
|
||||
function contentChanged(): boolean {
|
||||
if (!record.value) {
|
||||
return true;
|
||||
}
|
||||
const saved = buildVersionContent(formFromRecord(record.value));
|
||||
const next = buildVersionContent(form);
|
||||
return JSON.stringify(saved) !== JSON.stringify(next);
|
||||
}
|
||||
|
||||
function metadataChanged(): boolean {
|
||||
if (!record.value) {
|
||||
return true;
|
||||
}
|
||||
const saved = buildMetadataPayload(formFromRecord(record.value));
|
||||
const next = buildMetadataPayload(form);
|
||||
return JSON.stringify(saved) !== JSON.stringify(next);
|
||||
}
|
||||
|
||||
async function save(): Promise<void> {
|
||||
saveError.value = "";
|
||||
const valid = await formRef.value?.validate().catch(() => false);
|
||||
if (!valid) {
|
||||
return;
|
||||
}
|
||||
saving.value = true;
|
||||
try {
|
||||
if (isCreate) {
|
||||
const created = await createQuery(buildPayload(form));
|
||||
ElMessage.success(t("query.savedVersion", { version: "v1" }));
|
||||
await router.replace({ name: "query-detail", params: { id: created.id } });
|
||||
return;
|
||||
}
|
||||
if (metadataChanged()) {
|
||||
await updateQuery(queryId, buildMetadataPayload(form));
|
||||
}
|
||||
if (contentChanged()) {
|
||||
const version = await saveQueryVersion(queryId, buildVersionContent(form));
|
||||
ElMessage.success(t("query.savedVersion", { version: `v${version.version_no}` }));
|
||||
} else if (metadataChanged()) {
|
||||
ElMessage.success(t("query.saved"));
|
||||
} else {
|
||||
ElMessage.success(t("query.saved"));
|
||||
}
|
||||
applyRecord(await getQuery(queryId));
|
||||
previewView.value = { kind: "none" };
|
||||
previewInvalid.value = [];
|
||||
await refreshVersions();
|
||||
} catch (error) {
|
||||
saveError.value = describeError(error, t, te, "query.saveFailed");
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshVersions(): Promise<void> {
|
||||
versionsError.value = "";
|
||||
try {
|
||||
versions.value = (await listVersions(queryId)).items;
|
||||
} catch (error) {
|
||||
versionsError.value = describeError(error, t, te, "query.versions.loadFailed");
|
||||
}
|
||||
}
|
||||
|
||||
async function onVersionActivated(): Promise<void> {
|
||||
applyRecord(await getQuery(queryId));
|
||||
await refreshVersions();
|
||||
}
|
||||
|
||||
async function enable(): Promise<void> {
|
||||
saveError.value = "";
|
||||
busy.value = true;
|
||||
try {
|
||||
record.value = await enableQuery(queryId);
|
||||
ElMessage.success(t("query.enabledDone"));
|
||||
} catch (error) {
|
||||
saveError.value = describeError(error, t, te, "query.saveFailed");
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function disable(): Promise<void> {
|
||||
if (!record.value) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await ElMessageBox.confirm(
|
||||
t("query.disableConfirm.body", { name: record.value.name }),
|
||||
t("query.disableConfirm.title"),
|
||||
{
|
||||
type: "warning",
|
||||
confirmButtonText: t("query.disableConfirm.ok"),
|
||||
cancelButtonText: t("query.disableConfirm.cancel"),
|
||||
},
|
||||
);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
saveError.value = "";
|
||||
busy.value = true;
|
||||
try {
|
||||
record.value = await disableQuery(queryId);
|
||||
ElMessage.success(t("query.disabledDone"));
|
||||
} catch (error) {
|
||||
saveError.value = describeError(error, t, te, "query.saveFailed");
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function runPreview(): Promise<void> {
|
||||
if (!record.value || dirty.value || previewRunning.value) {
|
||||
return;
|
||||
}
|
||||
const { params, invalid } = buildPreviewParams(previewSpecs.value, previewValues.value);
|
||||
previewInvalid.value = invalid;
|
||||
if (invalid.length > 0) {
|
||||
return;
|
||||
}
|
||||
previewView.value = { kind: "running" };
|
||||
await nextTick();
|
||||
previewAnchor.value?.scrollIntoView?.({ block: "nearest" });
|
||||
try {
|
||||
previewView.value = viewFromOutcome(await previewCurrent(queryId, params));
|
||||
} catch (error) {
|
||||
previewView.value = viewFromError(error, (failure) =>
|
||||
describeError(failure, t, te, "query.preview.failedUnknown"),
|
||||
);
|
||||
}
|
||||
await nextTick();
|
||||
previewAnchor.value?.scrollIntoView?.({ block: "nearest" });
|
||||
}
|
||||
|
||||
async function loadReferences(): Promise<void> {
|
||||
try {
|
||||
references.value = (await getReferences(queryId)).items as { name?: string; id?: string }[];
|
||||
} catch (error) {
|
||||
referencesError.value = describeError(error, t, te, "query.refs.loadFailed");
|
||||
}
|
||||
}
|
||||
|
||||
async function loadDatasources(): Promise<void> {
|
||||
try {
|
||||
datasources.value = (
|
||||
await listDatasources({ page: 1, page_size: 100, sort_by: "name", sort_order: "asc" })
|
||||
).items;
|
||||
} catch (error) {
|
||||
datasourcesError.value = describeError(error, t, te, "query.form.datasourcesFailed");
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
if (isCreate) {
|
||||
await loadDatasources();
|
||||
savedSnapshot.value = formSnapshot(form);
|
||||
loaded.value = true;
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const [row] = await Promise.all([getQuery(queryId), loadDatasources()]);
|
||||
applyRecord(row);
|
||||
loaded.value = true;
|
||||
} catch (error) {
|
||||
loadError.value = isNotFound(error) ? t("query.notFound") : describeError(error, t, te, "query.loadFailed");
|
||||
return;
|
||||
}
|
||||
void refreshVersions();
|
||||
void loadReferences();
|
||||
// The list's 预览 arrives with ?preview=1 and only brings the trial-run panel into view.
|
||||
if (route.query.preview === "1") {
|
||||
await nextTick();
|
||||
previewAnchor.value?.scrollIntoView?.({ block: "start" });
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex h-full min-h-0 flex-col">
|
||||
<div class="min-h-0 flex-1 overflow-y-auto p-5" data-testid="query-scroll">
|
||||
<ElAlert
|
||||
v-if="loadError"
|
||||
type="error"
|
||||
data-testid="query-load-error"
|
||||
:title="loadError"
|
||||
show-icon
|
||||
:closable="false"
|
||||
/>
|
||||
<template v-else-if="loaded">
|
||||
<ElAlert
|
||||
v-if="!isCreate && record && !record.enabled"
|
||||
class="mb-3.5"
|
||||
type="warning"
|
||||
data-testid="query-disabled-note"
|
||||
:title="t('query.disabledNote')"
|
||||
show-icon
|
||||
:closable="false"
|
||||
/>
|
||||
<ElAlert
|
||||
v-if="saveError"
|
||||
class="mb-3.5"
|
||||
type="error"
|
||||
data-testid="query-save-error"
|
||||
:title="saveError"
|
||||
show-icon
|
||||
:closable="false"
|
||||
/>
|
||||
<ElAlert
|
||||
v-if="datasourcesError"
|
||||
class="mb-3.5"
|
||||
type="error"
|
||||
data-testid="query-datasources-error"
|
||||
:title="datasourcesError"
|
||||
show-icon
|
||||
:closable="false"
|
||||
/>
|
||||
|
||||
<ElForm
|
||||
ref="formRef"
|
||||
:model="form"
|
||||
:rules="rules"
|
||||
label-position="top"
|
||||
data-testid="query-form"
|
||||
@submit.prevent
|
||||
>
|
||||
<section class="mb-4 rounded-lg border border-[var(--border-subtle)] bg-white px-[18px] py-4">
|
||||
<h3 class="mb-3 text-[14.5px] font-semibold">
|
||||
{{ t("query.form.basic") }}
|
||||
<span class="ml-2 font-normal text-[var(--text-muted)]" data-testid="basic-sub">
|
||||
{{ isCreate ? t("query.form.subNew") : t("query.form.subSaved", { version: currentLabel }) }}
|
||||
</span>
|
||||
</h3>
|
||||
<div class="grid max-w-3xl grid-cols-1 gap-x-6 sm:grid-cols-2">
|
||||
<ElFormItem :label="t('query.form.name')" prop="name" data-testid="field-name">
|
||||
<ElInput v-model="form.name" :placeholder="t('query.form.namePlaceholder')" />
|
||||
</ElFormItem>
|
||||
<ElFormItem :label="t('query.form.datasource')" prop="datasource_id" data-testid="field-datasource">
|
||||
<ElSelect
|
||||
v-model="form.datasource_id"
|
||||
class="w-full"
|
||||
:placeholder="t('query.form.datasourcePlaceholder')"
|
||||
>
|
||||
<ElOption
|
||||
v-for="source in databaseSources"
|
||||
:key="source.id"
|
||||
:label="source.enabled ? source.name : `${source.name} ${t('query.form.datasourceOff')}`"
|
||||
:value="source.id"
|
||||
:disabled="!source.enabled"
|
||||
/>
|
||||
</ElSelect>
|
||||
</ElFormItem>
|
||||
<ElFormItem
|
||||
:label="t('query.form.description')"
|
||||
prop="description"
|
||||
class="sm:col-span-2"
|
||||
data-testid="field-description"
|
||||
>
|
||||
<ElInput v-model="form.description" type="textarea" :rows="2" />
|
||||
</ElFormItem>
|
||||
<ElFormItem :label="t('query.form.status')" data-testid="field-status">
|
||||
<span v-if="isCreate" class="text-[var(--text-secondary)]">{{ t("query.form.statusNew") }}</span>
|
||||
<span v-else class="inline-flex items-center gap-2">
|
||||
<ElTag :type="recordEnabled ? 'success' : 'info'" effect="light" data-testid="status-tag">
|
||||
{{ recordEnabled ? t("query.status.enabled") : t("query.status.disabled") }}
|
||||
</ElTag>
|
||||
<span class="text-[var(--text-muted)]">
|
||||
{{ t("query.form.statusHint", { action: recordEnabled ? t("query.actions.disable") : t("query.actions.enable") }) }}
|
||||
</span>
|
||||
</span>
|
||||
</ElFormItem>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="mb-4 rounded-lg border border-[var(--border-subtle)] bg-white px-[18px] py-4">
|
||||
<h3 class="mb-3 text-[14.5px] font-semibold">{{ t("query.form.sql") }}</h3>
|
||||
<ElFormItem prop="sql_template" label-width="0" data-testid="field-sql">
|
||||
<ElInput
|
||||
v-model="form.sql_template"
|
||||
class="query-sql"
|
||||
type="textarea"
|
||||
:rows="8"
|
||||
:spellcheck="false"
|
||||
:placeholder="t('query.form.sqlPlaceholder')"
|
||||
/>
|
||||
</ElFormItem>
|
||||
<p class="mb-2 text-xs text-[var(--text-muted)]">{{ t("query.form.sqlHint") }}</p>
|
||||
<div class="flex flex-wrap items-center gap-1.5" data-testid="sql-chips">
|
||||
<span v-if="sqlStatus.used.length === 0 && sqlStatus.unused.length === 0" class="text-[var(--text-muted)]">
|
||||
{{ t("query.sqlParams.none") }}
|
||||
</span>
|
||||
<template v-else>
|
||||
<span class="text-[var(--text-muted)]">{{ t("query.sqlParams.used") }}</span>
|
||||
<ElTag
|
||||
v-for="name in sqlStatus.used"
|
||||
:key="`u-${name}`"
|
||||
:type="sqlStatus.undeclared.includes(name) ? 'danger' : 'success'"
|
||||
effect="light"
|
||||
:data-testid="sqlStatus.undeclared.includes(name) ? 'chip-undeclared' : 'chip-declared'"
|
||||
:title="sqlStatus.undeclared.includes(name) ? t('query.sqlParams.undeclaredTitle') : undefined"
|
||||
>
|
||||
{{ sqlStatus.undeclared.includes(name) ? t("query.sqlParams.undeclared", { name }) : `:${name}` }}
|
||||
</ElTag>
|
||||
<ElTag
|
||||
v-for="name in sqlStatus.unused"
|
||||
:key="`n-${name}`"
|
||||
type="info"
|
||||
effect="light"
|
||||
data-testid="chip-unused"
|
||||
:title="t('query.sqlParams.unusedTitle')"
|
||||
>
|
||||
{{ t("query.sqlParams.unused", { name }) }}
|
||||
</ElTag>
|
||||
</template>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="mb-4 rounded-lg border border-[var(--border-subtle)] bg-white px-[18px] py-4">
|
||||
<h3 class="mb-1 text-[14.5px] font-semibold">{{ t("query.form.paramsTitle") }}</h3>
|
||||
<p class="mb-2.5 text-xs text-[var(--text-muted)]">{{ t("query.form.paramsHint") }}</p>
|
||||
<ElFormItem prop="params" label-width="0" data-testid="field-params">
|
||||
<ParamsTable v-model="form.params" class="w-full" />
|
||||
</ElFormItem>
|
||||
</section>
|
||||
|
||||
<section class="mb-4 rounded-lg border border-[var(--border-subtle)] bg-white px-[18px] py-4">
|
||||
<h3 class="mb-1 text-[14.5px] font-semibold">{{ t("query.form.outputsTitle") }}</h3>
|
||||
<p class="mb-2.5 text-xs text-[var(--text-muted)]">{{ t("query.form.outputsHint") }}</p>
|
||||
<ElFormItem prop="outputs" label-width="0" data-testid="field-outputs">
|
||||
<OutputsTable v-model="form.outputs" class="w-full" />
|
||||
</ElFormItem>
|
||||
</section>
|
||||
|
||||
<section class="mb-4 rounded-lg border border-[var(--border-subtle)] bg-white px-[18px] py-4">
|
||||
<h3 class="mb-1 text-[14.5px] font-semibold">{{ t("query.form.identifiersTitle") }}</h3>
|
||||
<p class="mb-2.5 text-xs text-[var(--text-muted)]">
|
||||
{{ t("query.form.identifiersHint", { example: IDENTIFIER_EXAMPLE }) }}
|
||||
</p>
|
||||
<IdentifierTags v-model="form.identifiers" />
|
||||
</section>
|
||||
|
||||
<section class="mb-4 rounded-lg border border-[var(--border-subtle)] bg-white px-[18px] py-4">
|
||||
<h3 class="mb-3 text-[14.5px] font-semibold">{{ t("query.form.limits") }}</h3>
|
||||
<div class="grid max-w-3xl grid-cols-1 gap-x-6 sm:grid-cols-2">
|
||||
<ElFormItem label="timeout_ms" prop="timeout_ms" data-testid="field-timeout">
|
||||
<ElInputNumber
|
||||
v-model="form.timeout_ms"
|
||||
style="width: 100%"
|
||||
:controls="false"
|
||||
:precision="0"
|
||||
align="left"
|
||||
/>
|
||||
</ElFormItem>
|
||||
<ElFormItem label="max_rows" prop="max_rows" data-testid="field-max-rows">
|
||||
<ElInputNumber
|
||||
v-model="form.max_rows"
|
||||
style="width: 100%"
|
||||
:controls="false"
|
||||
:precision="0"
|
||||
align="left"
|
||||
/>
|
||||
</ElFormItem>
|
||||
</div>
|
||||
<p class="text-xs text-[var(--text-muted)]">
|
||||
{{ t("query.form.limitsHint", { timeout: TIMEOUT_RANGE.max, rows: ROWS_RANGE.max }) }}
|
||||
</p>
|
||||
</section>
|
||||
</ElForm>
|
||||
|
||||
<div ref="previewAnchor">
|
||||
<PreviewPanel
|
||||
v-model="previewValues"
|
||||
:specs="previewSpecs"
|
||||
:view="previewView"
|
||||
target="current"
|
||||
:dirty="dirty"
|
||||
:need-save="isCreate"
|
||||
:limits="previewLimits"
|
||||
:datasource-name="sourceName"
|
||||
:invalid="previewInvalid"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<section class="mb-4 rounded-lg border border-[var(--border-subtle)] bg-white px-[18px] py-4">
|
||||
<h3 class="mb-1 text-[14.5px] font-semibold">{{ t("query.versions.title") }}</h3>
|
||||
<p class="mb-2.5 text-xs text-[var(--text-muted)]">{{ t("query.versions.hint") }}</p>
|
||||
<p
|
||||
v-if="isCreate"
|
||||
data-testid="versions-create-note"
|
||||
class="rounded-lg border border-dashed border-[var(--border-default)] px-5 py-4 text-center text-[var(--text-secondary)]"
|
||||
>
|
||||
{{ t("query.versions.emptyCreate") }}
|
||||
</p>
|
||||
<ElAlert
|
||||
v-else-if="versionsError"
|
||||
type="error"
|
||||
data-testid="versions-error"
|
||||
:title="versionsError"
|
||||
show-icon
|
||||
:closable="false"
|
||||
/>
|
||||
<VersionsTable
|
||||
v-else
|
||||
:definition-id="queryId"
|
||||
:versions="versions"
|
||||
:active-no="record?.current_version_no ?? undefined"
|
||||
@activated="onVersionActivated"
|
||||
/>
|
||||
</section>
|
||||
|
||||
<section
|
||||
class="mb-4 rounded-lg border border-[var(--border-subtle)] bg-white px-[18px] py-4"
|
||||
data-testid="query-references"
|
||||
>
|
||||
<h3 class="mb-3 text-[14.5px] font-semibold">{{ t("query.refs.title") }}</h3>
|
||||
<ElAlert
|
||||
v-if="referencesError"
|
||||
type="error"
|
||||
:title="referencesError"
|
||||
show-icon
|
||||
:closable="false"
|
||||
/>
|
||||
<ul v-else-if="references && references.length > 0" data-testid="references-list">
|
||||
<li v-for="(item, index) in references" :key="item.id ?? index">{{ item.name ?? item.id }}</li>
|
||||
</ul>
|
||||
<p
|
||||
v-else
|
||||
data-testid="references-empty"
|
||||
class="rounded-lg border border-dashed border-[var(--border-default)] px-5 py-4 text-center text-[var(--text-secondary)]"
|
||||
>
|
||||
{{ t("query.refs.empty") }}
|
||||
</p>
|
||||
</section>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<footer
|
||||
data-testid="query-footer"
|
||||
class="flex shrink-0 flex-wrap items-center justify-center gap-2 border-t border-[var(--border-subtle)] bg-white px-5 py-3"
|
||||
>
|
||||
<ElButton data-testid="footer-back" @click="backToList">{{ t("query.actions.backToList") }}</ElButton>
|
||||
<template v-if="loaded && !loadError">
|
||||
<ElButton
|
||||
type="primary"
|
||||
data-testid="footer-save"
|
||||
:loading="saving"
|
||||
:disabled="busy || previewRunning"
|
||||
@click="save"
|
||||
>
|
||||
{{ t("query.actions.save") }}
|
||||
</ElButton>
|
||||
<template v-if="!isCreate">
|
||||
<ElButton
|
||||
v-if="recordEnabled"
|
||||
type="danger"
|
||||
plain
|
||||
data-testid="footer-disable"
|
||||
:disabled="busy || saving"
|
||||
@click="disable"
|
||||
>
|
||||
{{ t("query.actions.disable") }}
|
||||
</ElButton>
|
||||
<ElButton v-else type="success" plain data-testid="footer-enable" :disabled="busy || saving" @click="enable">
|
||||
{{ t("query.actions.enable") }}
|
||||
</ElButton>
|
||||
</template>
|
||||
<ElButton
|
||||
data-testid="footer-preview"
|
||||
:disabled="isCreate || dirty || previewRunning || saving"
|
||||
:title="isCreate || dirty ? t('query.actions.previewNeedSave') : undefined"
|
||||
@click="runPreview"
|
||||
>
|
||||
{{ t("query.actions.runPreview") }}
|
||||
</ElButton>
|
||||
</template>
|
||||
</footer>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.query-sql :deep(textarea) {
|
||||
font-family: ui-monospace, SFMono-Regular, Consolas, monospace;
|
||||
font-size: 12.5px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,32 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* Gate for every query page. Only watchman-admin sees the child routes.
|
||||
* Other signed-in roles get the "cannot enter" panel, and no child page is created,
|
||||
* so no query request is sent for them. The backend enforces the same rule.
|
||||
* Child pages are keyed by URL, so create -> detail and detail -> version reload cleanly.
|
||||
*/
|
||||
import { computed } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { RouterView } from "vue-router";
|
||||
import { allowsQueries } from "../session";
|
||||
import { useAuthStore } from "../stores/auth";
|
||||
|
||||
const { t } = useI18n();
|
||||
const auth = useAuthStore();
|
||||
const allowed = computed(() => allowsQueries(auth.user?.roles ?? []));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<RouterView v-if="allowed" v-slot="{ Component, route }">
|
||||
<component :is="Component" :key="route.fullPath" />
|
||||
</RouterView>
|
||||
<div v-else class="h-full overflow-auto p-5">
|
||||
<div
|
||||
data-testid="query-denied"
|
||||
class="rounded-lg border border-dashed border-[var(--border-default)] bg-white px-5 py-14 text-center"
|
||||
>
|
||||
<h3 class="mb-1.5 text-[15px] font-semibold">{{ t("query.denied.title") }}</h3>
|
||||
<p class="text-[var(--text-secondary)]">{{ t("query.denied.body") }}</p>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,400 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* Query list. Filters are drafts until 查询; sort and page hit the server.
|
||||
* Row actions: 打开 / 切换版本 / 预览 (D26). Disabled rows stay visible; 预览 is disabled
|
||||
* with a title. 预览 opens the detail scrolled to the trial-run panel.
|
||||
*/
|
||||
import { computed, onMounted, reactive, ref } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { useRouter } from "vue-router";
|
||||
import {
|
||||
ElAlert,
|
||||
ElButton,
|
||||
ElDialog,
|
||||
ElInput,
|
||||
ElOption,
|
||||
ElPagination,
|
||||
ElSelect,
|
||||
ElTable,
|
||||
ElTableColumn,
|
||||
ElTag,
|
||||
vLoading,
|
||||
} from "element-plus";
|
||||
import { listDatasources } from "../datasources/client";
|
||||
import type { Datasource } from "../datasources/types";
|
||||
import { LIST_DEFAULT_PAGE_SIZE, LIST_PAGE_SIZES, actionsColumnWidth } from "../tableLayout";
|
||||
import { listQueries, listVersions } from "./client";
|
||||
import { describeError } from "./errors";
|
||||
import { formatDateTime, versionLabel } from "./format";
|
||||
import type { QuerySummary, VersionSummary } from "./types";
|
||||
import VersionsTable from "./VersionsTable.vue";
|
||||
|
||||
const { t, te } = useI18n();
|
||||
const router = useRouter();
|
||||
|
||||
const items = ref<QuerySummary[]>([]);
|
||||
const total = ref(0);
|
||||
const datasources = ref<Datasource[]>([]);
|
||||
const loading = ref(true);
|
||||
const loadError = ref("");
|
||||
|
||||
/** Draft filters edited in the toolbar; applied only on 查询 / 重置. */
|
||||
const draft = reactive({ name: "", datasourceId: "", status: "" });
|
||||
const applied = reactive({ name: "", datasourceId: "", status: "" });
|
||||
|
||||
const page = ref(1);
|
||||
const pageSize = ref(LIST_DEFAULT_PAGE_SIZE);
|
||||
const sortBy = ref("updated_at");
|
||||
const sortOrder = ref<"asc" | "desc">("desc");
|
||||
|
||||
const datasourceNames = computed(() => new Map(datasources.value.map((item) => [item.id, item.name])));
|
||||
const hasAppliedFilters = computed(
|
||||
() =>
|
||||
applied.name.trim() !== "" || applied.datasourceId !== "" || applied.status !== "",
|
||||
);
|
||||
const actionsWidth = actionsColumnWidth(3);
|
||||
const switchOpen = ref(false);
|
||||
const switchRow = ref<QuerySummary | null>(null);
|
||||
const switchVersions = ref<VersionSummary[]>([]);
|
||||
const switchLoading = ref(false);
|
||||
const switchError = ref("");
|
||||
|
||||
async function loadOptions(): Promise<void> {
|
||||
try {
|
||||
// Option lists need a wide page; not the table page size.
|
||||
const sources = await listDatasources({ page: 1, page_size: 100, sort_by: "name", sort_order: "asc" });
|
||||
datasources.value = sources.items;
|
||||
} catch {
|
||||
datasources.value = [];
|
||||
}
|
||||
}
|
||||
|
||||
async function load(): Promise<void> {
|
||||
loading.value = true;
|
||||
loadError.value = "";
|
||||
try {
|
||||
const enabled =
|
||||
applied.status === "enabled" ? true : applied.status === "disabled" ? false : undefined;
|
||||
const result = await listQueries({
|
||||
name: applied.name.trim() || undefined,
|
||||
datasource_id: applied.datasourceId || undefined,
|
||||
enabled,
|
||||
sort_by: sortBy.value,
|
||||
sort_order: sortOrder.value,
|
||||
page: page.value,
|
||||
page_size: pageSize.value,
|
||||
});
|
||||
items.value = result.items;
|
||||
total.value = result.total;
|
||||
} catch (error) {
|
||||
loadError.value = describeError(error, t, te, "query.list.loadFailed");
|
||||
items.value = [];
|
||||
total.value = 0;
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function applyFilters(): void {
|
||||
applied.name = draft.name;
|
||||
applied.datasourceId = draft.datasourceId;
|
||||
applied.status = draft.status;
|
||||
page.value = 1;
|
||||
void load();
|
||||
}
|
||||
|
||||
function resetFilters(): void {
|
||||
draft.name = "";
|
||||
draft.datasourceId = "";
|
||||
draft.status = "";
|
||||
applied.name = "";
|
||||
applied.datasourceId = "";
|
||||
applied.status = "";
|
||||
page.value = 1;
|
||||
void load();
|
||||
}
|
||||
|
||||
function onSortChange(payload: { prop: string | null; order: string | null }): void {
|
||||
const propMap: Record<string, string> = {
|
||||
name: "name",
|
||||
datasource: "datasource_name",
|
||||
status: "enabled",
|
||||
currentVersion: "current_version_no",
|
||||
updated_at: "updated_at",
|
||||
};
|
||||
const next = payload.prop ? propMap[payload.prop] : undefined;
|
||||
if (!next || !payload.order) {
|
||||
sortBy.value = "updated_at";
|
||||
sortOrder.value = "desc";
|
||||
} else {
|
||||
sortBy.value = next;
|
||||
sortOrder.value = payload.order === "ascending" ? "asc" : "desc";
|
||||
}
|
||||
page.value = 1;
|
||||
void load();
|
||||
}
|
||||
|
||||
function onPageChange(next: number): void {
|
||||
page.value = next;
|
||||
void load();
|
||||
}
|
||||
|
||||
function onSizeChange(next: number): void {
|
||||
pageSize.value = next;
|
||||
page.value = 1;
|
||||
void load();
|
||||
}
|
||||
|
||||
function asRow(source: unknown): QuerySummary {
|
||||
return source as QuerySummary;
|
||||
}
|
||||
|
||||
function rowClass({ row }: { row: unknown }): string {
|
||||
return asRow(row).enabled ? "" : "query-row-off";
|
||||
}
|
||||
|
||||
function sourceName(source: unknown): string {
|
||||
const row = asRow(source);
|
||||
return datasourceNames.value.get(row.datasource_id) ?? row.datasource_id;
|
||||
}
|
||||
|
||||
function currentVersion(source: unknown): string {
|
||||
return versionLabel(asRow(source).current_version_no) ?? t("query.versions.none");
|
||||
}
|
||||
|
||||
function openCreate(): void {
|
||||
void router.push({ name: "query-create" });
|
||||
}
|
||||
|
||||
function openDetail(source: unknown): void {
|
||||
void router.push({ name: "query-detail", params: { id: asRow(source).id } });
|
||||
}
|
||||
|
||||
function openPreview(source: unknown): void {
|
||||
void router.push({ name: "query-detail", params: { id: asRow(source).id }, query: { preview: "1" } });
|
||||
}
|
||||
|
||||
async function openSwitch(source: unknown): Promise<void> {
|
||||
const row = asRow(source);
|
||||
switchRow.value = row;
|
||||
switchOpen.value = true;
|
||||
switchLoading.value = true;
|
||||
switchError.value = "";
|
||||
switchVersions.value = [];
|
||||
try {
|
||||
switchVersions.value = (await listVersions(row.id)).items;
|
||||
} catch (error) {
|
||||
switchError.value = describeError(error, t, te, "query.versions.loadFailed");
|
||||
} finally {
|
||||
switchLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function onSwitchActivated(): Promise<void> {
|
||||
switchOpen.value = false;
|
||||
await load();
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await loadOptions();
|
||||
await load();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="h-full overflow-auto p-5" data-testid="query-list">
|
||||
<div class="mb-3 flex flex-wrap items-center gap-2" data-testid="query-list-toolbar">
|
||||
<div class="w-[200px]" data-testid="query-filter-name">
|
||||
<ElInput v-model="draft.name" clearable :placeholder="t('query.list.filterName')" />
|
||||
</div>
|
||||
<div class="w-[200px]" data-testid="query-filter-datasource">
|
||||
<ElSelect
|
||||
v-model="draft.datasourceId"
|
||||
clearable
|
||||
class="w-full"
|
||||
:placeholder="t('query.list.filterDatasource')"
|
||||
>
|
||||
<ElOption
|
||||
v-for="source in datasources"
|
||||
:key="source.id"
|
||||
:label="source.name"
|
||||
:value="source.id"
|
||||
/>
|
||||
</ElSelect>
|
||||
</div>
|
||||
<div class="w-[140px]" data-testid="query-filter-status">
|
||||
<ElSelect
|
||||
v-model="draft.status"
|
||||
clearable
|
||||
class="w-full"
|
||||
:placeholder="t('query.list.filterStatus')"
|
||||
>
|
||||
<ElOption :label="t('query.status.enabled')" value="enabled" />
|
||||
<ElOption :label="t('query.status.disabled')" value="disabled" />
|
||||
</ElSelect>
|
||||
</div>
|
||||
<ElButton type="primary" data-testid="query-filter-search" @click="applyFilters">
|
||||
{{ t("query.list.filterSearch") }}
|
||||
</ElButton>
|
||||
<ElButton data-testid="query-filter-reset" @click="resetFilters">
|
||||
{{ t("query.list.filterReset") }}
|
||||
</ElButton>
|
||||
<div class="ml-auto">
|
||||
<ElButton type="primary" data-testid="query-create" @click="openCreate">
|
||||
{{ t("query.list.create") }}
|
||||
</ElButton>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ElAlert
|
||||
v-if="loadError"
|
||||
type="error"
|
||||
data-testid="query-load-error"
|
||||
:title="loadError"
|
||||
show-icon
|
||||
:closable="false"
|
||||
/>
|
||||
<div
|
||||
v-else-if="!loading && total === 0 && !hasAppliedFilters"
|
||||
data-testid="query-empty"
|
||||
class="rounded-lg border border-dashed border-[var(--border-default)] bg-white px-5 py-14 text-center"
|
||||
>
|
||||
<h3 class="mb-1.5 text-[15px] font-semibold">{{ t("query.list.empty") }}</h3>
|
||||
<p class="text-[var(--text-secondary)]">{{ t("query.list.emptyHint") }}</p>
|
||||
</div>
|
||||
<div
|
||||
v-else-if="!loading && total === 0 && hasAppliedFilters"
|
||||
data-testid="query-filter-empty"
|
||||
class="rounded-lg border border-dashed border-[var(--border-default)] bg-white px-5 py-14 text-center"
|
||||
>
|
||||
<h3 class="mb-1.5 text-[15px] font-semibold">{{ t("query.list.filterEmpty") }}</h3>
|
||||
<p class="text-[var(--text-secondary)]">{{ t("query.list.filterEmptyHint") }}</p>
|
||||
</div>
|
||||
<template v-else>
|
||||
<ElTable
|
||||
v-loading="loading"
|
||||
:data="items"
|
||||
row-key="id"
|
||||
data-testid="query-table"
|
||||
:default-sort="{ prop: 'updated_at', order: 'descending' }"
|
||||
:row-class-name="rowClass"
|
||||
@sort-change="onSortChange"
|
||||
>
|
||||
<ElTableColumn
|
||||
prop="name"
|
||||
:label="t('query.columns.name')"
|
||||
min-width="180"
|
||||
sortable="custom"
|
||||
/>
|
||||
<ElTableColumn
|
||||
prop="datasource"
|
||||
:label="t('query.columns.datasource')"
|
||||
min-width="160"
|
||||
sortable="custom"
|
||||
>
|
||||
<template #default="{ row }">{{ sourceName(row) }}</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn
|
||||
prop="status"
|
||||
:label="t('query.columns.status')"
|
||||
min-width="110"
|
||||
sortable="custom"
|
||||
>
|
||||
<template #default="{ row }">
|
||||
<ElTag :type="row.enabled ? 'success' : 'info'" effect="light" data-testid="row-status">
|
||||
{{ row.enabled ? t("query.status.enabled") : t("query.status.disabled") }}
|
||||
</ElTag>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn
|
||||
prop="currentVersion"
|
||||
:label="t('query.columns.currentVersion')"
|
||||
min-width="120"
|
||||
sortable="custom"
|
||||
>
|
||||
<template #default="{ row }">{{ currentVersion(row) }}</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn
|
||||
prop="updated_at"
|
||||
:label="t('query.columns.updatedAt')"
|
||||
min-width="150"
|
||||
sortable="custom"
|
||||
>
|
||||
<template #default="{ row }">{{ formatDateTime(row.updated_at) }}</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn
|
||||
:label="t('query.columns.actions')"
|
||||
:width="actionsWidth"
|
||||
align="right"
|
||||
fixed="right"
|
||||
>
|
||||
<template #default="{ row }">
|
||||
<div class="whitespace-nowrap" :data-testid="`query-row-${row.id}`">
|
||||
<ElButton link type="primary" data-testid="row-open" @click="openDetail(row)">
|
||||
{{ t("query.actions.open") }}
|
||||
</ElButton>
|
||||
<ElButton link type="primary" data-testid="row-switch-version" @click="openSwitch(row)">
|
||||
{{ t("query.actions.switchVersion") }}
|
||||
</ElButton>
|
||||
<ElButton
|
||||
link
|
||||
type="primary"
|
||||
data-testid="row-preview"
|
||||
:disabled="!row.enabled"
|
||||
:title="row.enabled ? undefined : t('query.actions.previewDisabledWhy')"
|
||||
@click="openPreview(row)"
|
||||
>
|
||||
{{ t("query.actions.preview") }}
|
||||
</ElButton>
|
||||
</div>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
</ElTable>
|
||||
<div class="mt-3 flex justify-end" data-testid="query-pagination">
|
||||
<ElPagination
|
||||
background
|
||||
layout="total, sizes, prev, pager, next"
|
||||
:total="total"
|
||||
:page-size="pageSize"
|
||||
:page-sizes="[...LIST_PAGE_SIZES]"
|
||||
:current-page="page"
|
||||
@current-change="onPageChange"
|
||||
@size-change="onSizeChange"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<ElDialog
|
||||
v-model="switchOpen"
|
||||
align-center
|
||||
append-to-body
|
||||
:close-on-click-modal="false"
|
||||
:title="t('query.versions.switchTitle', { name: switchRow?.name ?? '' })"
|
||||
width="680px"
|
||||
data-testid="query-switch-dialog"
|
||||
>
|
||||
<ElAlert
|
||||
v-if="switchError"
|
||||
type="error"
|
||||
:title="switchError"
|
||||
show-icon
|
||||
:closable="false"
|
||||
/>
|
||||
<div v-else v-loading="switchLoading">
|
||||
<VersionsTable
|
||||
v-if="switchRow"
|
||||
:definition-id="switchRow.id"
|
||||
:versions="switchVersions"
|
||||
:active-no="switchRow.current_version_no ?? undefined"
|
||||
@activated="onSwitchActivated"
|
||||
/>
|
||||
</div>
|
||||
</ElDialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
:deep(.query-row-off td) {
|
||||
color: var(--text-muted);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,279 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* Read-only page of one frozen version. Footer: 返回列表, 返回查询, 激活此版本 (when not
|
||||
* current), 试跑预览. Breadcrumb: 预警平台 / 查询 / 详情 / 版本 vN.
|
||||
*/
|
||||
import { computed, nextTick, onMounted, ref } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { useRoute, useRouter } from "vue-router";
|
||||
import { ElAlert, ElButton, ElDescriptions, ElDescriptionsItem, ElMessage, ElTag } from "element-plus";
|
||||
import { listDatasources } from "../datasources/client";
|
||||
import type { Datasource } from "../datasources/types";
|
||||
import { activateQueryVersion, getQuery, getVersion, listVersions, previewVersion } from "./client";
|
||||
import { describeError, isNotFound } from "./errors";
|
||||
import { formatDateTime } from "./format";
|
||||
import IdentifierTags from "./IdentifierTags.vue";
|
||||
import OutputsTable from "./OutputsTable.vue";
|
||||
import ParamsTable from "./ParamsTable.vue";
|
||||
import { buildPreviewParams, initialPreviewValues, rowsFromContent, specsFromSchema } from "./payload";
|
||||
import PreviewPanel from "./PreviewPanel.vue";
|
||||
import { viewFromError, viewFromOutcome, type PreviewView } from "./preview";
|
||||
import type { OutputRow, ParamRow, QueryDetail, QueryVersion, VersionSummary } from "./types";
|
||||
import VersionsTable from "./VersionsTable.vue";
|
||||
|
||||
const { t, te } = useI18n();
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
|
||||
const queryId = String(route.params.id ?? "");
|
||||
const versionNo = Number(route.params.versionNo);
|
||||
|
||||
const previewAnchor = ref<HTMLElement>();
|
||||
const record = ref<QueryDetail | null>(null);
|
||||
const version = ref<QueryVersion | null>(null);
|
||||
const params = ref<ParamRow[]>([]);
|
||||
const outputs = ref<OutputRow[]>([]);
|
||||
const versions = ref<VersionSummary[]>([]);
|
||||
const datasources = ref<Datasource[]>([]);
|
||||
const loaded = ref(false);
|
||||
const loadError = ref("");
|
||||
const previewView = ref<PreviewView>({ kind: "none" });
|
||||
const previewValues = ref<Record<string, string>>({});
|
||||
const previewInvalid = ref<string[]>([]);
|
||||
|
||||
const previewSpecs = computed(() => specsFromSchema(version.value?.param_schema ?? []));
|
||||
const previewRunning = computed(() => previewView.value.kind === "running");
|
||||
const sourceName = computed(
|
||||
() => datasources.value.find((item) => item.id === record.value?.datasource_id)?.name ?? "",
|
||||
);
|
||||
const isActive = computed(
|
||||
() => version.value !== null && version.value.version_no === record.value?.current_version_no,
|
||||
);
|
||||
const previewLimits = computed(() =>
|
||||
version.value ? { timeout_ms: version.value.timeout_ms, max_rows: version.value.max_rows } : null,
|
||||
);
|
||||
const activating = ref(false);
|
||||
|
||||
function backToList(): void {
|
||||
void router.push({ name: "query-list" });
|
||||
}
|
||||
|
||||
function backToQuery(): void {
|
||||
void router.push({ name: "query-detail", params: { id: queryId } });
|
||||
}
|
||||
|
||||
async function activate(): Promise<void> {
|
||||
if (!version.value || isActive.value || activating.value) {
|
||||
return;
|
||||
}
|
||||
activating.value = true;
|
||||
try {
|
||||
record.value = await activateQueryVersion(queryId, version.value.version_no);
|
||||
ElMessage.success(t("query.versions.activated", { version: `v${version.value.version_no}` }));
|
||||
versions.value = (await listVersions(queryId)).items;
|
||||
} catch (error) {
|
||||
loadError.value = describeError(error, t, te, "query.saveFailed");
|
||||
} finally {
|
||||
activating.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function onActivatedFromTable(): Promise<void> {
|
||||
record.value = await getQuery(queryId);
|
||||
versions.value = (await listVersions(queryId)).items;
|
||||
}
|
||||
|
||||
async function runPreview(): Promise<void> {
|
||||
if (!version.value || previewRunning.value) {
|
||||
return;
|
||||
}
|
||||
const built = buildPreviewParams(previewSpecs.value, previewValues.value);
|
||||
previewInvalid.value = built.invalid;
|
||||
if (built.invalid.length > 0) {
|
||||
return;
|
||||
}
|
||||
previewView.value = { kind: "running" };
|
||||
await nextTick();
|
||||
previewAnchor.value?.scrollIntoView?.({ block: "nearest" });
|
||||
try {
|
||||
previewView.value = viewFromOutcome(await previewVersion(queryId, versionNo, built.params));
|
||||
} catch (error) {
|
||||
previewView.value = viewFromError(error, (failure) =>
|
||||
describeError(failure, t, te, "query.preview.failedUnknown"),
|
||||
);
|
||||
}
|
||||
await nextTick();
|
||||
previewAnchor.value?.scrollIntoView?.({ block: "nearest" });
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
if (!Number.isInteger(versionNo) || versionNo < 1) {
|
||||
loadError.value = t("query.versionNotFound");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const [row, frozen] = await Promise.all([getQuery(queryId), getVersion(queryId, versionNo)]);
|
||||
record.value = row;
|
||||
version.value = frozen;
|
||||
const rows = rowsFromContent(frozen);
|
||||
params.value = rows.params;
|
||||
outputs.value = rows.outputs;
|
||||
previewValues.value = initialPreviewValues(specsFromSchema(frozen.param_schema));
|
||||
loaded.value = true;
|
||||
} catch (error) {
|
||||
loadError.value = isNotFound(error)
|
||||
? t("query.versionNotFound")
|
||||
: describeError(error, t, te, "query.loadFailed");
|
||||
return;
|
||||
}
|
||||
// The list and the names only decorate the page; a failure of either must not hide the version.
|
||||
void listVersions(queryId)
|
||||
.then((result) => {
|
||||
versions.value = result.items;
|
||||
})
|
||||
.catch(() => undefined);
|
||||
void listDatasources({ page: 1, page_size: 100, sort_by: "name", sort_order: "asc" })
|
||||
.then((result) => {
|
||||
datasources.value = result.items;
|
||||
})
|
||||
.catch(() => undefined);
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex h-full min-h-0 flex-col">
|
||||
<div class="min-h-0 flex-1 overflow-y-auto p-5" data-testid="query-scroll">
|
||||
<ElAlert
|
||||
v-if="loadError"
|
||||
type="error"
|
||||
data-testid="query-load-error"
|
||||
:title="loadError"
|
||||
show-icon
|
||||
:closable="false"
|
||||
/>
|
||||
<template v-else-if="loaded && record && version">
|
||||
<ElAlert
|
||||
class="mb-3.5"
|
||||
type="info"
|
||||
data-testid="version-frozen-note"
|
||||
:title="t('query.versions.frozenNote', { version: `v${version.version_no}` })"
|
||||
show-icon
|
||||
:closable="false"
|
||||
/>
|
||||
|
||||
<section class="mb-4 rounded-lg border border-[var(--border-subtle)] bg-white px-[18px] py-4">
|
||||
<h3 class="mb-3 text-[14.5px] font-semibold">
|
||||
{{ t("query.versions.info") }}
|
||||
<ElTag type="info" effect="plain" class="ml-2" data-testid="version-readonly-tag">
|
||||
{{ t("query.versions.readonly") }}
|
||||
</ElTag>
|
||||
</h3>
|
||||
<ElDescriptions :column="2" data-testid="version-info">
|
||||
<ElDescriptionsItem :label="t('query.versions.query')">{{ record.name }}</ElDescriptionsItem>
|
||||
<ElDescriptionsItem :label="t('query.versions.version')">
|
||||
<span data-testid="version-number">v{{ version.version_no }}</span>
|
||||
<ElTag v-if="isActive" type="success" effect="light" class="ml-1.5" data-testid="version-active-tag">
|
||||
{{ t("query.versions.current") }}
|
||||
</ElTag>
|
||||
</ElDescriptionsItem>
|
||||
<ElDescriptionsItem :label="t('query.versions.publishedAt')">
|
||||
{{ formatDateTime(version.published_at) }}
|
||||
</ElDescriptionsItem>
|
||||
<ElDescriptionsItem :label="t('query.versions.publishedBy')">
|
||||
{{ version.published_by ?? "" }}
|
||||
</ElDescriptionsItem>
|
||||
<ElDescriptionsItem :label="t('query.columns.datasource')">{{ sourceName }}</ElDescriptionsItem>
|
||||
</ElDescriptions>
|
||||
</section>
|
||||
|
||||
<section class="mb-4 rounded-lg border border-[var(--border-subtle)] bg-white px-[18px] py-4">
|
||||
<h3 class="mb-3 text-[14.5px] font-semibold">{{ t("query.form.sql") }}</h3>
|
||||
<pre
|
||||
data-testid="version-sql"
|
||||
class="query-sql-frozen overflow-auto whitespace-pre-wrap rounded-md border border-[var(--border-subtle)] bg-[var(--bg-surface-soft)] px-3 py-2.5"
|
||||
>{{ version.sql_template }}</pre
|
||||
>
|
||||
</section>
|
||||
|
||||
<section class="mb-4 rounded-lg border border-[var(--border-subtle)] bg-white px-[18px] py-4">
|
||||
<h3 class="mb-3 text-[14.5px] font-semibold">{{ t("query.form.paramsTitle") }}</h3>
|
||||
<ParamsTable :model-value="params" readonly />
|
||||
</section>
|
||||
|
||||
<section class="mb-4 rounded-lg border border-[var(--border-subtle)] bg-white px-[18px] py-4">
|
||||
<h3 class="mb-3 text-[14.5px] font-semibold">{{ t("query.form.outputsTitle") }}</h3>
|
||||
<OutputsTable :model-value="outputs" readonly />
|
||||
</section>
|
||||
|
||||
<section class="mb-4 rounded-lg border border-[var(--border-subtle)] bg-white px-[18px] py-4">
|
||||
<h3 class="mb-3 text-[14.5px] font-semibold">{{ t("query.form.identifiersTitle") }}</h3>
|
||||
<IdentifierTags :model-value="version.allowed_identifiers" readonly />
|
||||
</section>
|
||||
|
||||
<section class="mb-4 rounded-lg border border-[var(--border-subtle)] bg-white px-[18px] py-4">
|
||||
<h3 class="mb-3 text-[14.5px] font-semibold">{{ t("query.form.limits") }}</h3>
|
||||
<ElDescriptions :column="2" data-testid="version-limits">
|
||||
<ElDescriptionsItem label="timeout_ms">{{ version.timeout_ms }}</ElDescriptionsItem>
|
||||
<ElDescriptionsItem label="max_rows">{{ version.max_rows }}</ElDescriptionsItem>
|
||||
</ElDescriptions>
|
||||
</section>
|
||||
|
||||
<div ref="previewAnchor">
|
||||
<PreviewPanel
|
||||
v-model="previewValues"
|
||||
:specs="previewSpecs"
|
||||
:view="previewView"
|
||||
target="version"
|
||||
:version-no="version.version_no"
|
||||
:limits="previewLimits"
|
||||
:datasource-name="sourceName"
|
||||
:invalid="previewInvalid"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<section class="mb-4 rounded-lg border border-[var(--border-subtle)] bg-white px-[18px] py-4">
|
||||
<h3 class="mb-3 text-[14.5px] font-semibold">{{ t("query.versions.title") }}</h3>
|
||||
<VersionsTable
|
||||
:definition-id="queryId"
|
||||
:versions="versions"
|
||||
:current-no="version.version_no"
|
||||
:active-no="record.current_version_no ?? undefined"
|
||||
@activated="onActivatedFromTable"
|
||||
/>
|
||||
</section>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<footer
|
||||
data-testid="query-footer"
|
||||
class="flex shrink-0 flex-wrap items-center justify-center gap-2 border-t border-[var(--border-subtle)] bg-white px-5 py-3"
|
||||
>
|
||||
<ElButton data-testid="footer-back" @click="backToList">{{ t("query.actions.backToList") }}</ElButton>
|
||||
<template v-if="loaded && !loadError">
|
||||
<ElButton data-testid="footer-query" @click="backToQuery">{{ t("query.actions.backToQuery") }}</ElButton>
|
||||
<ElButton
|
||||
v-if="!isActive"
|
||||
type="primary"
|
||||
plain
|
||||
data-testid="footer-activate"
|
||||
:loading="activating"
|
||||
@click="activate"
|
||||
>
|
||||
{{ t("query.actions.activate") }}
|
||||
</ElButton>
|
||||
<ElButton data-testid="footer-preview" :disabled="previewRunning" @click="runPreview">
|
||||
{{ t("query.actions.runPreview") }}
|
||||
</ElButton>
|
||||
</template>
|
||||
</footer>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.query-sql-frozen {
|
||||
margin: 0;
|
||||
font-family: ui-monospace, SFMono-Regular, Consolas, monospace;
|
||||
font-size: 12.5px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,133 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* Versions of one query, newest first. Opening a row goes to the read-only version page.
|
||||
* Activate sets current_version_no without creating a new version (D26).
|
||||
*/
|
||||
import { ref } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { useRouter } from "vue-router";
|
||||
import { ElButton, ElMessage, ElTable, ElTableColumn, ElTag } from "element-plus";
|
||||
import { activateQueryVersion } from "./client";
|
||||
import { describeError } from "./errors";
|
||||
import { formatDateTime } from "./format";
|
||||
import type { VersionSummary } from "./types";
|
||||
|
||||
const props = defineProps<{
|
||||
definitionId: string;
|
||||
versions: VersionSummary[];
|
||||
/** Currently active version (D26). */
|
||||
activeNo?: number;
|
||||
/** Highlight a row (e.g. the version page's own number). */
|
||||
currentNo?: number;
|
||||
/** When false, hide activate actions (read-only contexts can still show the badge). */
|
||||
allowActivate?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{ activated: [] }>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
const router = useRouter();
|
||||
const activating = ref<number | null>(null);
|
||||
|
||||
function open(source: unknown): void {
|
||||
const row = source as VersionSummary;
|
||||
void router.push({
|
||||
name: "query-version",
|
||||
params: { id: props.definitionId, versionNo: String(row.version_no) },
|
||||
});
|
||||
}
|
||||
|
||||
async function activate(source: unknown): Promise<void> {
|
||||
const row = source as VersionSummary;
|
||||
if (row.version_no === props.activeNo || activating.value !== null) {
|
||||
return;
|
||||
}
|
||||
activating.value = row.version_no;
|
||||
try {
|
||||
await activateQueryVersion(props.definitionId, row.version_no);
|
||||
ElMessage.success(t("query.versions.activated", { version: `v${row.version_no}` }));
|
||||
emit("activated");
|
||||
} catch (error) {
|
||||
ElMessage.error(describeError(error, t, te, "query.saveFailed"));
|
||||
} finally {
|
||||
activating.value = null;
|
||||
}
|
||||
}
|
||||
|
||||
function rowClass({ row }: { row: unknown }): string {
|
||||
const no = (row as VersionSummary).version_no;
|
||||
return no === props.currentNo || no === props.activeNo ? "query-version-current" : "";
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div data-testid="versions-block">
|
||||
<p
|
||||
v-if="versions.length === 0"
|
||||
data-testid="versions-empty"
|
||||
class="rounded-lg border border-dashed border-[var(--border-default)] px-5 py-4 text-center text-[var(--text-secondary)]"
|
||||
>
|
||||
{{ t("query.versions.empty") }}
|
||||
</p>
|
||||
<ElTable
|
||||
v-else
|
||||
:data="versions"
|
||||
row-key="id"
|
||||
data-testid="versions-table"
|
||||
:row-class-name="rowClass"
|
||||
>
|
||||
<ElTableColumn :label="t('query.versions.version')" min-width="140">
|
||||
<template #default="{ row }">
|
||||
<span class="query-mono">v{{ row.version_no }}</span>
|
||||
<ElTag
|
||||
v-if="row.version_no === activeNo"
|
||||
type="success"
|
||||
effect="light"
|
||||
class="ml-1.5"
|
||||
data-testid="version-active-tag"
|
||||
>
|
||||
{{ t("query.versions.current") }}
|
||||
</ElTag>
|
||||
<ElTag
|
||||
v-else-if="versions[0]?.version_no === row.version_no"
|
||||
type="info"
|
||||
effect="light"
|
||||
class="ml-1.5"
|
||||
>
|
||||
{{ t("query.versions.latest") }}
|
||||
</ElTag>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn :label="t('query.versions.publishedAt')" min-width="150">
|
||||
<template #default="{ row }">{{ formatDateTime(row.published_at) }}</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn prop="published_by" :label="t('query.versions.publishedBy')" min-width="130" />
|
||||
<ElTableColumn :label="t('query.columns.actions')" width="168" align="right">
|
||||
<template #default="{ row }">
|
||||
<ElButton link type="primary" :data-testid="`version-open-${row.version_no}`" @click="open(row)">
|
||||
{{ t("query.actions.open") }}
|
||||
</ElButton>
|
||||
<ElButton
|
||||
v-if="allowActivate !== false && row.version_no !== activeNo"
|
||||
link
|
||||
type="primary"
|
||||
:data-testid="`version-activate-${row.version_no}`"
|
||||
:loading="activating === row.version_no"
|
||||
@click="activate(row)"
|
||||
>
|
||||
{{ t("query.actions.activate") }}
|
||||
</ElButton>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
</ElTable>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.query-mono {
|
||||
font-family: ui-monospace, SFMono-Regular, Consolas, monospace;
|
||||
}
|
||||
:deep(.query-version-current td) {
|
||||
background: var(--el-fill-color-lighter);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,103 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("@watchman/api", async () => {
|
||||
const actual = await vi.importActual<typeof import("@watchman/api")>("@watchman/api");
|
||||
return { ...actual, requestJson: vi.fn() };
|
||||
});
|
||||
|
||||
import { requestJson } from "@watchman/api";
|
||||
import {
|
||||
createQuery,
|
||||
disableQuery,
|
||||
enableQuery,
|
||||
getReferences,
|
||||
getVersion,
|
||||
listQueries,
|
||||
listVersions,
|
||||
previewDraft,
|
||||
previewVersion,
|
||||
saveQueryVersion,
|
||||
activateQueryVersion,
|
||||
updateQuery,
|
||||
} from "./client";
|
||||
import { buildPayload, emptyForm } from "./payload";
|
||||
|
||||
const mocked = vi.mocked(requestJson);
|
||||
|
||||
function lastCall(): { url: string; init: RequestInit } {
|
||||
const [url, init] = mocked.mock.calls[mocked.mock.calls.length - 1];
|
||||
return { url: String(url), init: (init ?? {}) as RequestInit };
|
||||
}
|
||||
|
||||
describe("query client", () => {
|
||||
beforeEach(() => {
|
||||
mocked.mockReset();
|
||||
mocked.mockResolvedValue({});
|
||||
});
|
||||
|
||||
it("reads use GET on the /queries routes", async () => {
|
||||
await listQueries();
|
||||
expect(lastCall().url).toBe("/queries");
|
||||
await listQueries({ name: "温度", page: 2, page_size: 10, sort_by: "name", sort_order: "asc" });
|
||||
expect(lastCall().url).toContain("/queries?");
|
||||
expect(lastCall().url).toContain("name=");
|
||||
expect(lastCall().url).toContain("page=2");
|
||||
await listVersions("q 1");
|
||||
expect(lastCall().url).toBe("/queries/q%201/versions");
|
||||
await getVersion("q1", 3);
|
||||
expect(lastCall().url).toBe("/queries/q1/versions/3");
|
||||
await getReferences("q1");
|
||||
expect(lastCall().url).toBe("/queries/q1/references");
|
||||
expect(lastCall().init.method).toBeUndefined();
|
||||
});
|
||||
|
||||
it("create and update send the whole draft as JSON", async () => {
|
||||
const form = { ...emptyForm("ds-1"), name: "n", sql_template: "SELECT 1" };
|
||||
await createQuery(buildPayload(form));
|
||||
expect(lastCall().url).toBe("/queries");
|
||||
expect(lastCall().init.method).toBe("POST");
|
||||
expect(JSON.parse(String(lastCall().init.body)).datasource_id).toBe("ds-1");
|
||||
await updateQuery("q1", buildPayload(form));
|
||||
expect(lastCall().url).toBe("/queries/q1");
|
||||
expect(lastCall().init.method).toBe("PATCH");
|
||||
expect(new Headers(lastCall().init.headers).get("Content-Type")).toBe("application/json");
|
||||
});
|
||||
|
||||
it("enable, disable and activate are body-less POSTs", async () => {
|
||||
await enableQuery("q1");
|
||||
expect(lastCall()).toMatchObject({ url: "/queries/q1/enable", init: { method: "POST" } });
|
||||
await disableQuery("q1");
|
||||
expect(lastCall().url).toBe("/queries/q1/disable");
|
||||
await activateQueryVersion("q1", 2);
|
||||
expect(lastCall().url).toBe("/queries/q1/versions/2/activate");
|
||||
expect(lastCall().init.body).toBeUndefined();
|
||||
});
|
||||
|
||||
it("saveQueryVersion posts content as a new version", async () => {
|
||||
await saveQueryVersion("q1", {
|
||||
sql_template: "SELECT 1",
|
||||
param_schema: [],
|
||||
output_schema: [],
|
||||
allowed_identifiers: [],
|
||||
timeout_ms: 1000,
|
||||
max_rows: 10,
|
||||
});
|
||||
expect(lastCall().url).toBe("/queries/q1/versions");
|
||||
expect(lastCall().init.method).toBe("POST");
|
||||
expect(JSON.parse(String(lastCall().init.body)).sql_template).toBe("SELECT 1");
|
||||
});
|
||||
|
||||
it("previews post only the parameter values", async () => {
|
||||
await previewDraft("q1", { line_code: "L1" });
|
||||
expect(lastCall().url).toBe("/queries/q1/preview");
|
||||
expect(JSON.parse(String(lastCall().init.body))).toEqual({ params: { line_code: "L1" } });
|
||||
await previewVersion("q1", 2, {});
|
||||
expect(lastCall().url).toBe("/queries/q1/versions/2/preview");
|
||||
expect(JSON.parse(String(lastCall().init.body))).toEqual({ params: {} });
|
||||
});
|
||||
|
||||
it("unwraps what requestJson returns", async () => {
|
||||
mocked.mockResolvedValueOnce({ items: [{ id: "q1" }] });
|
||||
expect(await listQueries()).toEqual({ items: [{ id: "q1" }] });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,124 @@
|
||||
/** Calls to the /queries routes. Each one returns the unwrapped envelope data. */
|
||||
|
||||
import { api } from "../api";
|
||||
import type { QueryPayload } from "./payload";
|
||||
import type {
|
||||
PreviewOutcome,
|
||||
QueryDetail,
|
||||
QueryList,
|
||||
QueryListParams,
|
||||
QueryReferences,
|
||||
QueryVersion,
|
||||
VersionList,
|
||||
} from "./types";
|
||||
|
||||
const JSON_HEADERS = { "Content-Type": "application/json" };
|
||||
|
||||
function base(id: string): string {
|
||||
return `/queries/${encodeURIComponent(id)}`;
|
||||
}
|
||||
|
||||
function toQuery(params?: QueryListParams): string {
|
||||
if (!params) {
|
||||
return "";
|
||||
}
|
||||
const q = new URLSearchParams();
|
||||
if (params.name) q.set("name", params.name);
|
||||
if (params.datasource_id) q.set("datasource_id", params.datasource_id);
|
||||
if (params.enabled !== undefined) q.set("enabled", String(params.enabled));
|
||||
if (params.sort_by) q.set("sort_by", params.sort_by);
|
||||
if (params.sort_order) q.set("sort_order", params.sort_order);
|
||||
if (params.page !== undefined) q.set("page", String(params.page));
|
||||
if (params.page_size !== undefined) q.set("page_size", String(params.page_size));
|
||||
const text = q.toString();
|
||||
return text ? `?${text}` : "";
|
||||
}
|
||||
|
||||
export function listQueries(params?: QueryListParams): Promise<QueryList> {
|
||||
return api<QueryList>(`/queries${toQuery(params)}`);
|
||||
}
|
||||
|
||||
export function getQuery(id: string): Promise<QueryDetail> {
|
||||
return api<QueryDetail>(base(id));
|
||||
}
|
||||
|
||||
export function createQuery(payload: QueryPayload): Promise<QueryDetail> {
|
||||
return api<QueryDetail>("/queries", {
|
||||
method: "POST",
|
||||
headers: JSON_HEADERS,
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
}
|
||||
|
||||
/** Metadata-only PATCH (name / description / datasource). */
|
||||
export function updateQuery(
|
||||
id: string,
|
||||
payload: Pick<QueryPayload, "name" | "description" | "datasource_id">,
|
||||
): Promise<QueryDetail> {
|
||||
return api<QueryDetail>(base(id), {
|
||||
method: "PATCH",
|
||||
headers: JSON_HEADERS,
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
}
|
||||
|
||||
export type VersionContent = Omit<QueryPayload, "name" | "description" | "datasource_id">;
|
||||
|
||||
/** Save content as the next immutable version and make it current (D26). */
|
||||
export function saveQueryVersion(id: string, content: VersionContent): Promise<QueryVersion> {
|
||||
return api<QueryVersion>(`${base(id)}/versions`, {
|
||||
method: "POST",
|
||||
headers: JSON_HEADERS,
|
||||
body: JSON.stringify(content),
|
||||
});
|
||||
}
|
||||
|
||||
export function activateQueryVersion(id: string, versionNo: number): Promise<QueryDetail> {
|
||||
return api<QueryDetail>(`${base(id)}/versions/${encodeURIComponent(String(versionNo))}/activate`, {
|
||||
method: "POST",
|
||||
});
|
||||
}
|
||||
|
||||
export function disableQuery(id: string): Promise<QueryDetail> {
|
||||
return api<QueryDetail>(`${base(id)}/disable`, { method: "POST" });
|
||||
}
|
||||
|
||||
export function enableQuery(id: string): Promise<QueryDetail> {
|
||||
return api<QueryDetail>(`${base(id)}/enable`, { method: "POST" });
|
||||
}
|
||||
|
||||
export function listVersions(id: string): Promise<VersionList> {
|
||||
return api<VersionList>(`${base(id)}/versions`);
|
||||
}
|
||||
|
||||
export function getVersion(id: string, versionNo: number): Promise<QueryVersion> {
|
||||
return api<QueryVersion>(`${base(id)}/versions/${encodeURIComponent(String(versionNo))}`);
|
||||
}
|
||||
|
||||
/** Trial-run the current active version. */
|
||||
export function previewCurrent(id: string, params: Record<string, unknown>): Promise<PreviewOutcome> {
|
||||
return api<PreviewOutcome>(`${base(id)}/preview`, {
|
||||
method: "POST",
|
||||
headers: JSON_HEADERS,
|
||||
body: JSON.stringify({ params }),
|
||||
});
|
||||
}
|
||||
|
||||
/** @deprecated use previewCurrent */
|
||||
export const previewDraft = previewCurrent;
|
||||
|
||||
export function previewVersion(
|
||||
id: string,
|
||||
versionNo: number,
|
||||
params: Record<string, unknown>,
|
||||
): Promise<PreviewOutcome> {
|
||||
return api<PreviewOutcome>(`${base(id)}/versions/${encodeURIComponent(String(versionNo))}/preview`, {
|
||||
method: "POST",
|
||||
headers: JSON_HEADERS,
|
||||
body: JSON.stringify({ params }),
|
||||
});
|
||||
}
|
||||
|
||||
export function getReferences(id: string): Promise<QueryReferences> {
|
||||
return api<QueryReferences>(`${base(id)}/references`);
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { BusinessError } from "@watchman/api";
|
||||
import { describeError, isDisabledRejection, isNotFound } from "./errors";
|
||||
import { isConnectionKind, viewFromError, viewFromOutcome } from "./preview";
|
||||
import type { PreviewOutcome } from "./types";
|
||||
|
||||
const MESSAGES: Record<string, string> = {
|
||||
"query.errors.duplicate_name": "名称已存在",
|
||||
"query.errors.disabled": "查询已停用",
|
||||
"codes.40000": "参数错误",
|
||||
"codes.42000": "权限不足",
|
||||
fallback: "未完成",
|
||||
};
|
||||
const t = (key: string) => MESSAGES[key] ?? key;
|
||||
const te = (key: string) => key in MESSAGES;
|
||||
|
||||
function business(
|
||||
code: number,
|
||||
status: number,
|
||||
details: Record<string, unknown> = {},
|
||||
): BusinessError {
|
||||
return new BusinessError({ code, message: "server text must never show", details, status, requestId: "r" });
|
||||
}
|
||||
|
||||
describe("describeError", () => {
|
||||
it("prefers the stable reason", () => {
|
||||
expect(describeError(business(40000, 409, { reason: "duplicate_name" }), t, te, "fallback")).toBe("名称已存在");
|
||||
});
|
||||
|
||||
it("falls back to the numeric code, then to the fallback text", () => {
|
||||
expect(describeError(business(42000, 403), t, te, "fallback")).toBe("权限不足 (42000)");
|
||||
expect(describeError(business(40000, 400, { reason: "unheard_of" }), t, te, "fallback")).toBe("参数错误 (40000)");
|
||||
expect(describeError(business(50000, 500), t, te, "fallback")).toBe("未完成 (50000)");
|
||||
});
|
||||
|
||||
it("uses the fallback for anything that is not an API error", () => {
|
||||
expect(describeError(new TypeError("network"), t, te, "fallback")).toBe("未完成");
|
||||
});
|
||||
|
||||
it("never shows the server message text", () => {
|
||||
expect(describeError(business(40000, 400), t, te, "fallback")).not.toContain("server text");
|
||||
});
|
||||
});
|
||||
|
||||
describe("status checks", () => {
|
||||
it("not found is HTTP 404 (the code stays 40000)", () => {
|
||||
expect(isNotFound(business(40000, 404, { reason: "not_found" }))).toBe(true);
|
||||
expect(isNotFound(business(40000, 400))).toBe(false);
|
||||
expect(isNotFound(new Error("x"))).toBe(false);
|
||||
});
|
||||
|
||||
it("a disabled rejection is HTTP 409 with reason disabled", () => {
|
||||
expect(isDisabledRejection(business(40000, 409, { reason: "disabled" }))).toBe(true);
|
||||
expect(isDisabledRejection(business(40000, 409, { reason: "duplicate_name" }))).toBe(false);
|
||||
expect(isDisabledRejection(business(40000, 400, { reason: "disabled" }))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("preview views", () => {
|
||||
const base = { id: "q1", version_no: 1, source: "current" as const, message: "m" };
|
||||
|
||||
it("keeps success, empty, illegal type and failure apart", () => {
|
||||
const success: PreviewOutcome = {
|
||||
...base,
|
||||
status: "success",
|
||||
columns: ["a"],
|
||||
rows: [{ a: 1 }],
|
||||
row_count: 1,
|
||||
masked_columns: [],
|
||||
};
|
||||
const empty: PreviewOutcome = { ...success, status: "empty", rows: [], row_count: 0 };
|
||||
const illegal: PreviewOutcome = {
|
||||
...base,
|
||||
status: "illegal_type",
|
||||
columns: ["a"],
|
||||
details: { fields: [{ field: "a", expected: "integer", actual: "str", row: 0 }] },
|
||||
};
|
||||
const timeout: PreviewOutcome = { ...base, status: "failure", failure_kind: "timeout", details: {} };
|
||||
expect(viewFromOutcome(success).kind).toBe("success");
|
||||
expect(viewFromOutcome(empty).kind).toBe("empty");
|
||||
expect(viewFromOutcome(illegal).kind).toBe("illegal_type");
|
||||
const failure = viewFromOutcome(timeout);
|
||||
expect(failure.kind).toBe("failure");
|
||||
expect(failure.kind === "failure" && failure.failureKind).toBe("timeout");
|
||||
});
|
||||
|
||||
it("maps a disabled source and an open circuit to their own panels", () => {
|
||||
const disabled: PreviewOutcome = { ...base, status: "failure", failure_kind: "disabled", details: { reason: "disabled" } };
|
||||
expect(viewFromOutcome(disabled)).toEqual({ kind: "disabled", scope: "datasource" });
|
||||
const open: PreviewOutcome = {
|
||||
...base,
|
||||
status: "failure",
|
||||
failure_kind: "circuit_open",
|
||||
details: { circuit_open_until: "2026-11-18T09:30:00+00:00" },
|
||||
};
|
||||
expect(viewFromOutcome(open)).toEqual({ kind: "circuit_open", until: "2026-11-18T09:30:00+00:00" });
|
||||
const noTime: PreviewOutcome = { ...base, status: "failure", failure_kind: "circuit_open", details: {} };
|
||||
expect(viewFromOutcome(noTime)).toEqual({ kind: "circuit_open", until: null });
|
||||
});
|
||||
|
||||
it("a failure without a kind is still shown as a failure", () => {
|
||||
const view = viewFromOutcome({ ...base, status: "failure", failure_kind: null, details: {} });
|
||||
expect(view.kind === "failure" && view.failureKind).toBe("unknown");
|
||||
});
|
||||
|
||||
it("only connection-class kinds count toward the circuit", () => {
|
||||
expect(["unreachable", "auth_failed", "rejected"].every(isConnectionKind)).toBe(true);
|
||||
expect(["timeout", "sql_error", "limit_exceeded", "validation"].some(isConnectionKind)).toBe(false);
|
||||
});
|
||||
|
||||
it("a 409 from the preview route is the disabled panel, other errors are plain text", () => {
|
||||
const describe_ = (error: unknown) => describeError(error, t, te, "fallback");
|
||||
expect(viewFromError(business(40000, 409, { reason: "disabled" }), describe_)).toEqual({
|
||||
kind: "disabled",
|
||||
scope: "query",
|
||||
});
|
||||
expect(viewFromError(business(42000, 403), describe_)).toEqual({ kind: "error", text: "权限不足 (42000)" });
|
||||
expect(viewFromError(new Error("boom"), describe_)).toEqual({ kind: "error", text: "未完成" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
/**
|
||||
* Turns a failed API call into one line for the user. No server message text is shown:
|
||||
* the stable `details.reason` picks the wording, then the numeric code, then a fallback.
|
||||
*/
|
||||
|
||||
import { BusinessError } from "@watchman/api";
|
||||
|
||||
type Translate = (key: string, named?: Record<string, unknown>) => string;
|
||||
type Exists = (key: string) => boolean;
|
||||
|
||||
export function describeError(error: unknown, t: Translate, te: Exists, fallbackKey: string): string {
|
||||
if (!(error instanceof BusinessError)) {
|
||||
return t(fallbackKey);
|
||||
}
|
||||
const reason = error.details.reason;
|
||||
if (typeof reason === "string" && te(`query.errors.${reason}`)) {
|
||||
return t(`query.errors.${reason}`);
|
||||
}
|
||||
if (te(`codes.${error.code}`)) {
|
||||
return `${t(`codes.${error.code}`)} (${error.code})`;
|
||||
}
|
||||
return `${t(fallbackKey)} (${error.code})`;
|
||||
}
|
||||
|
||||
/** True when the API says the thing does not exist (HTTP 404, reason not_found). */
|
||||
export function isNotFound(error: unknown): boolean {
|
||||
return error instanceof BusinessError && error.status === 404;
|
||||
}
|
||||
|
||||
/** True when a preview was refused because the query definition is disabled (HTTP 409). */
|
||||
export function isDisabledRejection(error: unknown): boolean {
|
||||
return error instanceof BusinessError && error.status === 409 && error.details.reason === "disabled";
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
/** Display helpers for query rows and preview samples. */
|
||||
|
||||
function pad(value: number): string {
|
||||
return String(value).padStart(2, "0");
|
||||
}
|
||||
|
||||
/** "2026-11-17 09:12" in the browser's time zone, or an empty string when unset or invalid. */
|
||||
export function formatDateTime(iso: string | null | undefined): string {
|
||||
if (!iso) {
|
||||
return "";
|
||||
}
|
||||
const date = new Date(iso);
|
||||
if (Number.isNaN(date.getTime())) {
|
||||
return "";
|
||||
}
|
||||
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
|
||||
}
|
||||
|
||||
/** One preview cell as text: SQL NULL is shown as NULL, objects as JSON. */
|
||||
export function formatCell(value: unknown): string {
|
||||
if (value === null || value === undefined) {
|
||||
return "NULL";
|
||||
}
|
||||
if (typeof value === "object") {
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
return String(value);
|
||||
}
|
||||
|
||||
/** "v3" for a version number, or null when never published. */
|
||||
export function versionLabel(versionNo: number | null | undefined): string | null {
|
||||
return versionNo === null || versionNo === undefined ? null : `v${versionNo}`;
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import zhCN from "../../locales/zh-CN/common.json";
|
||||
import zhTW from "../../locales/zh-TW/common.json";
|
||||
import en from "../../locales/en/common.json";
|
||||
import th from "../../locales/th/common.json";
|
||||
|
||||
function leafKeys(value: unknown, prefix = ""): string[] {
|
||||
if (value === null || typeof value !== "object") {
|
||||
return [prefix];
|
||||
}
|
||||
return Object.entries(value as Record<string, unknown>).flatMap(([key, child]) =>
|
||||
leafKeys(child, prefix ? `${prefix}.${key}` : key),
|
||||
);
|
||||
}
|
||||
|
||||
function texts(value: unknown): string[] {
|
||||
if (typeof value === "string") {
|
||||
return [value];
|
||||
}
|
||||
if (value && typeof value === "object") {
|
||||
return Object.values(value as Record<string, unknown>).flatMap(texts);
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
describe("query locale keys", () => {
|
||||
const base = leafKeys((zhCN as { query: unknown }).query).sort();
|
||||
|
||||
it.each([
|
||||
["zh-TW", zhTW],
|
||||
["en", en],
|
||||
["th", th],
|
||||
])("%s has the same query keys as zh-CN", (_name, messages) => {
|
||||
expect(leafKeys((messages as { query: unknown }).query).sort()).toEqual(base);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["zh-CN", zhCN],
|
||||
["zh-TW", zhTW],
|
||||
["en", en],
|
||||
["th", th],
|
||||
])("%s has the nav entries and every text is filled", (_name, messages) => {
|
||||
const nav = (messages as { nav: Record<string, string> }).nav;
|
||||
expect(nav.queries).toBeTruthy();
|
||||
expect(nav.version).toContain("{no}");
|
||||
expect(texts((messages as { query: unknown }).query).every((text) => text.trim() !== "")).toBe(true);
|
||||
});
|
||||
|
||||
it("names every backend reason the console can show", () => {
|
||||
for (const reason of [
|
||||
"duplicate_name",
|
||||
"datasource_not_found",
|
||||
"template_empty",
|
||||
"param_schema_invalid",
|
||||
"output_schema_invalid",
|
||||
"limit_invalid",
|
||||
"disabled",
|
||||
"version_conflict",
|
||||
"missing_param",
|
||||
"undeclared_param",
|
||||
]) {
|
||||
expect(leafKeys(zhCN)).toContain(`query.errors.${reason}`);
|
||||
}
|
||||
});
|
||||
|
||||
it("has the page-level messages the pages call by name", () => {
|
||||
for (const key of [
|
||||
"query.saved",
|
||||
"query.savedVersion",
|
||||
"query.saveFailed",
|
||||
"query.loadFailed",
|
||||
"query.notFound",
|
||||
"query.versionNotFound",
|
||||
"query.enabledDone",
|
||||
"query.disabledDone",
|
||||
"query.disabledNote",
|
||||
"query.preview.failedUnknown",
|
||||
"query.preview.targetCurrent",
|
||||
"query.versions.loadFailed",
|
||||
"query.versions.activated",
|
||||
"query.form.datasourcesFailed",
|
||||
]) {
|
||||
expect(leafKeys(zhCN)).toContain(key);
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps the footer wording after removing draft/publish", () => {
|
||||
const query = (zhCN as unknown as { query: { actions: Record<string, string> } }).query;
|
||||
expect(query.actions.backToList).toBe("返回列表");
|
||||
expect(query.actions.save).toBe("保存");
|
||||
expect(query.actions.activate).toBe("激活此版本");
|
||||
expect(query.actions.switchVersion).toBe("切换版本");
|
||||
expect(query.actions.disable).toBe("停用");
|
||||
expect(query.actions.enable).toBe("启用");
|
||||
expect(query.actions.runPreview).toBe("试跑预览");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,160 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
buildPayload,
|
||||
buildPreviewParams,
|
||||
emptyForm,
|
||||
formFromRecord,
|
||||
formSnapshot,
|
||||
initialPreviewValues,
|
||||
newOutputRow,
|
||||
newParamRow,
|
||||
specsFromSchema,
|
||||
} from "./payload";
|
||||
import type { QueryDetail, QueryForm } from "./types";
|
||||
|
||||
function filled(overrides: Partial<QueryForm> = {}): QueryForm {
|
||||
return {
|
||||
...emptyForm("ds-1"),
|
||||
name: " 产线温度采样 ",
|
||||
description: "",
|
||||
sql_template: "SELECT lot_no FROM process_readings WHERE line_code = :line_code\n",
|
||||
params: [
|
||||
{ key: 1, name: "line_code", type: "string", required: true, defaultText: "" },
|
||||
{ key: 2, name: "min_temp", type: "number", required: false, defaultText: "0.5" },
|
||||
{ key: 3, name: "active", type: "boolean", required: false, defaultText: "true" },
|
||||
],
|
||||
outputs: [{ key: 4, name: " lot_no ", type: "string" }],
|
||||
identifiers: ["process_readings", "process_readings"],
|
||||
timeout_ms: 5000,
|
||||
max_rows: 200,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("buildPayload", () => {
|
||||
it("trims text, nulls a blank description and keeps the SQL untouched", () => {
|
||||
const payload = buildPayload(filled());
|
||||
expect(payload.name).toBe("产线温度采样");
|
||||
expect(payload.description).toBeNull();
|
||||
expect(payload.sql_template.endsWith("\n")).toBe(true);
|
||||
expect(payload.datasource_id).toBe("ds-1");
|
||||
});
|
||||
|
||||
it("converts parameter defaults by type and omits blank ones", () => {
|
||||
const { param_schema } = buildPayload(filled());
|
||||
expect(param_schema[0]).toEqual({ name: "line_code", type: "string", required: true });
|
||||
expect("default" in param_schema[0]).toBe(false);
|
||||
expect(param_schema[1]).toEqual({ name: "min_temp", type: "number", required: false, default: 0.5 });
|
||||
expect(param_schema[2].default).toBe(true);
|
||||
});
|
||||
|
||||
it("builds the output schema and dedupes identifiers", () => {
|
||||
const payload = buildPayload(filled());
|
||||
expect(payload.output_schema).toEqual([{ name: "lot_no", type: "string" }]);
|
||||
expect(payload.allowed_identifiers).toEqual(["process_readings"]);
|
||||
expect(payload.timeout_ms).toBe(5000);
|
||||
expect(payload.max_rows).toBe(200);
|
||||
});
|
||||
|
||||
it("carries only draft fields: no tenant, version, publisher or enabled flag", () => {
|
||||
const keys = Object.keys(buildPayload(filled())).sort();
|
||||
expect(keys).toEqual([
|
||||
"allowed_identifiers",
|
||||
"datasource_id",
|
||||
"description",
|
||||
"max_rows",
|
||||
"name",
|
||||
"output_schema",
|
||||
"param_schema",
|
||||
"sql_template",
|
||||
"timeout_ms",
|
||||
]);
|
||||
});
|
||||
|
||||
it("new rows start required for parameters and string typed", () => {
|
||||
expect(newParamRow()).toMatchObject({ name: "", type: "string", required: true, defaultText: "" });
|
||||
expect(newOutputRow()).toMatchObject({ name: "", type: "string" });
|
||||
expect(newParamRow().key).not.toBe(newParamRow().key);
|
||||
});
|
||||
});
|
||||
|
||||
describe("record round trip", () => {
|
||||
const record: QueryDetail = {
|
||||
id: "q-1",
|
||||
name: "产线温度采样",
|
||||
description: null,
|
||||
datasource_id: "ds-1",
|
||||
enabled: true,
|
||||
current_version_no: 2,
|
||||
latest_version_no: 2,
|
||||
latest_published_version_no: 2,
|
||||
created_at: null,
|
||||
updated_at: null,
|
||||
current: {
|
||||
sql_template: "SELECT 1 WHERE a = :a",
|
||||
param_schema: [
|
||||
{ name: "a", type: "integer", required: true, default: 7 },
|
||||
{ name: "b", type: "boolean", required: false, default: false },
|
||||
{ name: "c", type: "datetime", required: false },
|
||||
],
|
||||
output_schema: [{ name: "n", type: "nullish" }],
|
||||
allowed_identifiers: ["t"],
|
||||
timeout_ms: 10000,
|
||||
max_rows: 100,
|
||||
},
|
||||
};
|
||||
|
||||
it("shows stored defaults as text and sends them back unchanged", () => {
|
||||
const form = formFromRecord(record);
|
||||
expect(form.params.map((row) => row.defaultText)).toEqual(["7", "false", ""]);
|
||||
const payload = buildPayload(form);
|
||||
expect(payload.param_schema).toEqual(record.current.param_schema);
|
||||
expect(payload.output_schema).toEqual(record.current.output_schema);
|
||||
expect(payload.description).toBeNull();
|
||||
});
|
||||
|
||||
it("a snapshot of a freshly loaded form equals itself and changes on an edit", () => {
|
||||
const form = formFromRecord(record);
|
||||
const saved = formSnapshot(form);
|
||||
expect(formSnapshot(formFromRecord(record))).toBe(saved);
|
||||
form.sql_template += " ";
|
||||
expect(formSnapshot(form)).not.toBe(saved);
|
||||
});
|
||||
});
|
||||
|
||||
describe("preview params", () => {
|
||||
const specs = specsFromSchema([
|
||||
{ name: "line_code", type: "string", required: true },
|
||||
{ name: "since", type: "datetime", required: false, default: "2026-11-17 00:00:00" },
|
||||
{ name: "limit", type: "integer", required: false },
|
||||
]);
|
||||
|
||||
it("starts from defaults and keeps what the user typed", () => {
|
||||
expect(initialPreviewValues(specs)).toEqual({
|
||||
line_code: "",
|
||||
since: "2026-11-17 00:00:00",
|
||||
limit: "",
|
||||
});
|
||||
expect(initialPreviewValues(specs, { line_code: "L1", gone: "x" })).toEqual({
|
||||
line_code: "L1",
|
||||
since: "2026-11-17 00:00:00",
|
||||
limit: "",
|
||||
});
|
||||
});
|
||||
|
||||
it("omits blank values and converts the rest by type", () => {
|
||||
const result = buildPreviewParams(specs, { line_code: "L1", since: "", limit: "5" });
|
||||
expect(result.params).toEqual({ line_code: "L1", limit: 5 });
|
||||
expect(result.invalid).toEqual([]);
|
||||
});
|
||||
|
||||
it("reports values that do not fit instead of sending them", () => {
|
||||
const result = buildPreviewParams(specs, { line_code: "L1", since: "", limit: "five" });
|
||||
expect(result.invalid).toEqual(["limit"]);
|
||||
expect("limit" in result.params).toBe(false);
|
||||
});
|
||||
|
||||
it("sends nothing for a query without parameters", () => {
|
||||
expect(buildPreviewParams([], {})).toEqual({ params: {}, invalid: [] });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,214 @@
|
||||
/**
|
||||
* Request bodies for create / metadata update / save-version, and form ↔ API mapping.
|
||||
* Boundary: tenant, version pointers, publisher and enabled are never sent.
|
||||
*/
|
||||
|
||||
import {
|
||||
LIMIT_DEFAULTS,
|
||||
type OutputRow,
|
||||
type OutputSchemaItem,
|
||||
type ParamRow,
|
||||
type ParamSchemaItem,
|
||||
type QueryDetail,
|
||||
type QueryDraft,
|
||||
type QueryForm,
|
||||
type QueryVersion,
|
||||
} from "./types";
|
||||
import { isValueTextValid, parseValueText } from "./validation";
|
||||
|
||||
export type QueryPayload = {
|
||||
name: string;
|
||||
description: string | null;
|
||||
datasource_id: string;
|
||||
sql_template: string;
|
||||
param_schema: ParamSchemaItem[];
|
||||
output_schema: OutputSchemaItem[];
|
||||
allowed_identifiers: string[];
|
||||
timeout_ms: number;
|
||||
max_rows: number;
|
||||
};
|
||||
|
||||
let rowCounter = 0;
|
||||
|
||||
export function nextRowKey(): number {
|
||||
rowCounter += 1;
|
||||
return rowCounter;
|
||||
}
|
||||
|
||||
export function newParamRow(): ParamRow {
|
||||
// Required is the backend's default for a parameter.
|
||||
return { key: nextRowKey(), name: "", type: "string", required: true, defaultText: "" };
|
||||
}
|
||||
|
||||
export function newOutputRow(): OutputRow {
|
||||
return { key: nextRowKey(), name: "", type: "string" };
|
||||
}
|
||||
|
||||
export function emptyForm(datasourceId = ""): QueryForm {
|
||||
return {
|
||||
name: "",
|
||||
description: "",
|
||||
datasource_id: datasourceId,
|
||||
sql_template: "",
|
||||
params: [],
|
||||
outputs: [],
|
||||
identifiers: [],
|
||||
timeout_ms: LIMIT_DEFAULTS.timeout_ms,
|
||||
max_rows: LIMIT_DEFAULTS.max_rows,
|
||||
};
|
||||
}
|
||||
|
||||
/** Text shown in the default input for a stored default value. */
|
||||
export function defaultToText(value: unknown): string {
|
||||
if (value === undefined || value === null) {
|
||||
return "";
|
||||
}
|
||||
return typeof value === "string" ? value : String(value);
|
||||
}
|
||||
|
||||
export function paramsToRows(items: ParamSchemaItem[]): ParamRow[] {
|
||||
return items.map((item) => ({
|
||||
key: nextRowKey(),
|
||||
name: item.name,
|
||||
type: item.type,
|
||||
required: item.required !== false,
|
||||
defaultText: defaultToText(item.default),
|
||||
}));
|
||||
}
|
||||
|
||||
export function outputsToRows(items: OutputSchemaItem[]): OutputRow[] {
|
||||
return items.map((item) => ({ key: nextRowKey(), name: item.name, type: item.type }));
|
||||
}
|
||||
|
||||
export function formFromRecord(record: QueryDetail): QueryForm {
|
||||
const current = record.current;
|
||||
return {
|
||||
name: record.name,
|
||||
description: record.description ?? "",
|
||||
datasource_id: record.datasource_id,
|
||||
sql_template: current.sql_template,
|
||||
params: paramsToRows(current.param_schema),
|
||||
outputs: outputsToRows(current.output_schema),
|
||||
identifiers: [...current.allowed_identifiers],
|
||||
timeout_ms: current.timeout_ms,
|
||||
max_rows: current.max_rows,
|
||||
};
|
||||
}
|
||||
|
||||
/** Form-like rows for the frozen content of a version (read-only view). */
|
||||
export function rowsFromContent(content: QueryDraft | QueryVersion): {
|
||||
params: ParamRow[];
|
||||
outputs: OutputRow[];
|
||||
} {
|
||||
return { params: paramsToRows(content.param_schema), outputs: outputsToRows(content.output_schema) };
|
||||
}
|
||||
|
||||
/** A blank default text means "no default" and sends no `default` key. */
|
||||
export function buildParamSchema(rows: ParamRow[]): ParamSchemaItem[] {
|
||||
return rows.map((row) => {
|
||||
const item: ParamSchemaItem = { name: row.name.trim(), type: row.type, required: row.required };
|
||||
if (row.defaultText.trim() !== "") {
|
||||
item.default = parseValueText(row.type, row.defaultText);
|
||||
}
|
||||
return item;
|
||||
});
|
||||
}
|
||||
|
||||
export function buildOutputSchema(rows: OutputRow[]): OutputSchemaItem[] {
|
||||
return rows.map((row) => ({ name: row.name.trim(), type: row.type }));
|
||||
}
|
||||
|
||||
/** Full body for POST /queries (create with v1) and POST .../versions (save content). */
|
||||
export function buildPayload(form: QueryForm): QueryPayload {
|
||||
const description = form.description.trim();
|
||||
return {
|
||||
name: form.name.trim(),
|
||||
description: description === "" ? null : description,
|
||||
datasource_id: form.datasource_id,
|
||||
sql_template: form.sql_template,
|
||||
param_schema: buildParamSchema(form.params),
|
||||
output_schema: buildOutputSchema(form.outputs),
|
||||
allowed_identifiers: [...new Set(form.identifiers)],
|
||||
timeout_ms: Number(form.timeout_ms),
|
||||
max_rows: Number(form.max_rows),
|
||||
};
|
||||
}
|
||||
|
||||
/** Metadata-only PATCH body. */
|
||||
export function buildMetadataPayload(
|
||||
form: QueryForm,
|
||||
): Pick<QueryPayload, "name" | "description" | "datasource_id"> {
|
||||
const description = form.description.trim();
|
||||
return {
|
||||
name: form.name.trim(),
|
||||
description: description === "" ? null : description,
|
||||
datasource_id: form.datasource_id,
|
||||
};
|
||||
}
|
||||
|
||||
/** Content-only body for POST .../versions. */
|
||||
export function buildVersionContent(
|
||||
form: QueryForm,
|
||||
): Omit<QueryPayload, "name" | "description" | "datasource_id"> {
|
||||
const full = buildPayload(form);
|
||||
return {
|
||||
sql_template: full.sql_template,
|
||||
param_schema: full.param_schema,
|
||||
output_schema: full.output_schema,
|
||||
allowed_identifiers: full.allowed_identifiers,
|
||||
timeout_ms: full.timeout_ms,
|
||||
max_rows: full.max_rows,
|
||||
};
|
||||
}
|
||||
|
||||
/** Stable text of the form's saved-relevant content, to tell unsaved edits from saved ones. */
|
||||
export function formSnapshot(form: QueryForm): string {
|
||||
return JSON.stringify(buildPayload(form));
|
||||
}
|
||||
|
||||
export type PreviewSpec = { name: string; type: string; required: boolean; defaultText: string };
|
||||
|
||||
export function specsFromSchema(items: ParamSchemaItem[]): PreviewSpec[] {
|
||||
return items.map((item) => ({
|
||||
name: item.name,
|
||||
type: item.type,
|
||||
required: item.required !== false,
|
||||
defaultText: defaultToText(item.default),
|
||||
}));
|
||||
}
|
||||
|
||||
/** Initial preview inputs: the declared defaults, keeping what the user already typed. */
|
||||
export function initialPreviewValues(
|
||||
specs: PreviewSpec[],
|
||||
previous: Record<string, string> = {},
|
||||
): Record<string, string> {
|
||||
const values: Record<string, string> = {};
|
||||
for (const spec of specs) {
|
||||
values[spec.name] = previous[spec.name] ?? spec.defaultText;
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
/**
|
||||
* Body of the preview calls. Blank inputs are omitted so the server applies the default or
|
||||
* reports the missing parameter. `invalid` lists names whose text does not fit the type.
|
||||
*/
|
||||
export function buildPreviewParams(
|
||||
specs: PreviewSpec[],
|
||||
values: Record<string, string>,
|
||||
): { params: Record<string, unknown>; invalid: string[] } {
|
||||
const params: Record<string, unknown> = {};
|
||||
const invalid: string[] = [];
|
||||
for (const spec of specs) {
|
||||
const text = values[spec.name] ?? "";
|
||||
if (text.trim() === "") {
|
||||
continue;
|
||||
}
|
||||
if (!isValueTextValid(spec.type, text)) {
|
||||
invalid.push(spec.name);
|
||||
continue;
|
||||
}
|
||||
params[spec.name] = parseValueText(spec.type, text);
|
||||
}
|
||||
return { params, invalid };
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* Maps a preview response (or a refused call) to the panel the console shows.
|
||||
* Boundary: pure mapping, no I/O. The outcome is only ever held in memory for display; the
|
||||
* console never stores sample rows. Server message text is not shown, only the status and
|
||||
* failure kind pick the wording.
|
||||
*/
|
||||
|
||||
import type { PreviewFailure, PreviewIllegalType, PreviewOutcome, PreviewRows } from "./types";
|
||||
import { isDisabledRejection } from "./errors";
|
||||
|
||||
export const FAILURE_KINDS = [
|
||||
"timeout",
|
||||
"unreachable",
|
||||
"auth_failed",
|
||||
"rejected",
|
||||
"sql_error",
|
||||
"limit_exceeded",
|
||||
"validation",
|
||||
"engine_readonly_unsupported",
|
||||
] as const;
|
||||
|
||||
export type PreviewView =
|
||||
| { kind: "none" }
|
||||
| { kind: "running" }
|
||||
| { kind: "success"; outcome: PreviewRows }
|
||||
| { kind: "empty"; outcome: PreviewRows }
|
||||
| { kind: "illegal_type"; outcome: PreviewIllegalType }
|
||||
| { kind: "failure"; failureKind: string; outcome: PreviewFailure }
|
||||
/** scope "query": the definition is disabled (HTTP 409); "datasource": its source is disabled. */
|
||||
| { kind: "disabled"; scope: "query" | "datasource" }
|
||||
| { kind: "circuit_open"; until: string | null }
|
||||
| { kind: "error"; text: string };
|
||||
|
||||
/** Connection-class failures count against the datasource circuit (M03); the others do not. */
|
||||
export function isConnectionKind(kind: string): boolean {
|
||||
return kind === "unreachable" || kind === "auth_failed" || kind === "rejected";
|
||||
}
|
||||
|
||||
export function viewFromOutcome(outcome: PreviewOutcome): PreviewView {
|
||||
if (outcome.status === "illegal_type") {
|
||||
return { kind: "illegal_type", outcome };
|
||||
}
|
||||
if (outcome.status !== "failure") {
|
||||
return outcome.status === "success" ? { kind: "success", outcome } : { kind: "empty", outcome };
|
||||
}
|
||||
const kind = outcome.failure_kind ?? "unknown";
|
||||
if (kind === "disabled") {
|
||||
return { kind: "disabled", scope: "datasource" };
|
||||
}
|
||||
if (kind === "circuit_open") {
|
||||
const until = outcome.details?.circuit_open_until;
|
||||
return { kind: "circuit_open", until: typeof until === "string" ? until : null };
|
||||
}
|
||||
return { kind: "failure", failureKind: kind, outcome };
|
||||
}
|
||||
|
||||
/** A refused preview call: 409 disabled gets its own panel; anything else is a plain error. */
|
||||
export function viewFromError(error: unknown, describe: (error: unknown) => string): PreviewView {
|
||||
if (isDisabledRejection(error)) {
|
||||
return { kind: "disabled", scope: "query" };
|
||||
}
|
||||
return { kind: "error", text: describe(error) };
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
/** Query definition shapes returned by /queries, and the form rows the console edits. */
|
||||
|
||||
export const VALUE_TYPES = ["string", "integer", "number", "boolean", "datetime"] as const;
|
||||
export type ValueType = (typeof VALUE_TYPES)[number];
|
||||
|
||||
/** "nullish" is output-only: the column carries no type constraint. */
|
||||
export const OUTPUT_TYPES = [...VALUE_TYPES, "nullish"] as const;
|
||||
export type OutputType = (typeof OUTPUT_TYPES)[number];
|
||||
|
||||
/** Server defaults and caps. A value above a cap is capped by the server; below 1 is refused. */
|
||||
export const LIMIT_DEFAULTS = { timeout_ms: 10000, max_rows: 100 } as const;
|
||||
export const TIMEOUT_RANGE = { min: 1, max: 300000 } as const;
|
||||
export const ROWS_RANGE = { min: 1, max: 10000 } as const;
|
||||
export const MAX_OUTPUT_NAME = 128;
|
||||
|
||||
export type ParamSchemaItem = {
|
||||
name: string;
|
||||
type: ValueType;
|
||||
required: boolean;
|
||||
default?: unknown;
|
||||
};
|
||||
|
||||
export type OutputSchemaItem = { name: string; type: OutputType };
|
||||
|
||||
/** Editable draft content, keyed like the PATCH body. */
|
||||
export type QueryDraft = {
|
||||
sql_template: string;
|
||||
param_schema: ParamSchemaItem[];
|
||||
output_schema: OutputSchemaItem[];
|
||||
allowed_identifiers: string[];
|
||||
timeout_ms: number;
|
||||
max_rows: number;
|
||||
};
|
||||
|
||||
export type QuerySummary = {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string | null;
|
||||
datasource_id: string;
|
||||
enabled: boolean;
|
||||
current_version_no: number | null;
|
||||
latest_version_no: number | null;
|
||||
/** @deprecated alias of latest_version_no */
|
||||
latest_published_version_no?: number | null;
|
||||
created_at: string | null;
|
||||
updated_at: string | null;
|
||||
};
|
||||
|
||||
export type QueryDetail = QuerySummary & { current: QueryDraft };
|
||||
|
||||
export type QueryList = {
|
||||
items: QuerySummary[];
|
||||
total: number;
|
||||
page: number;
|
||||
page_size: number;
|
||||
};
|
||||
|
||||
/** Console list query params; omit fields the server should ignore. */
|
||||
export type QueryListParams = {
|
||||
name?: string;
|
||||
datasource_id?: string;
|
||||
enabled?: boolean;
|
||||
sort_by?: string;
|
||||
sort_order?: "asc" | "desc";
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
};
|
||||
|
||||
export type VersionSummary = {
|
||||
id: string;
|
||||
definition_id: string;
|
||||
version_no: number;
|
||||
published_at: string | null;
|
||||
published_by: string | null;
|
||||
};
|
||||
|
||||
export type QueryVersion = VersionSummary & QueryDraft;
|
||||
|
||||
export type VersionList = { id: string; items: VersionSummary[] };
|
||||
|
||||
export type QueryReferences = { id: string; items: unknown[] };
|
||||
|
||||
export type PreviewFailureKind =
|
||||
| "validation"
|
||||
| "disabled"
|
||||
| "circuit_open"
|
||||
| "timeout"
|
||||
| "unreachable"
|
||||
| "auth_failed"
|
||||
| "rejected"
|
||||
| "limit_exceeded"
|
||||
| "sql_error"
|
||||
| "engine_readonly_unsupported";
|
||||
|
||||
type PreviewBase = {
|
||||
id: string;
|
||||
version_no: number | null;
|
||||
source: "current" | "version" | "draft";
|
||||
message: string;
|
||||
};
|
||||
|
||||
export type PreviewRows = PreviewBase & {
|
||||
status: "success" | "empty";
|
||||
columns: string[];
|
||||
rows: Record<string, unknown>[];
|
||||
row_count: number;
|
||||
masked_columns: string[];
|
||||
};
|
||||
|
||||
export type TypeProblem = { field: string; expected: string; actual: string; row: number };
|
||||
|
||||
export type PreviewIllegalType = PreviewBase & {
|
||||
status: "illegal_type";
|
||||
columns: string[];
|
||||
details: { fields?: TypeProblem[] };
|
||||
};
|
||||
|
||||
export type PreviewFailure = PreviewBase & {
|
||||
status: "failure";
|
||||
failure_kind: PreviewFailureKind | string | null;
|
||||
details: Record<string, unknown>;
|
||||
};
|
||||
|
||||
/** Response of both preview routes. Nothing in it is stored on the server. */
|
||||
export type PreviewOutcome = PreviewRows | PreviewIllegalType | PreviewFailure;
|
||||
|
||||
/** One editable parameter row. `defaultText` is the raw input; the payload converts it by type. */
|
||||
export type ParamRow = {
|
||||
key: number;
|
||||
name: string;
|
||||
type: ValueType;
|
||||
required: boolean;
|
||||
defaultText: string;
|
||||
};
|
||||
|
||||
export type OutputRow = { key: number; name: string; type: OutputType };
|
||||
|
||||
export type QueryForm = {
|
||||
name: string;
|
||||
description: string;
|
||||
datasource_id: string;
|
||||
sql_template: string;
|
||||
params: ParamRow[];
|
||||
outputs: OutputRow[];
|
||||
identifiers: string[];
|
||||
timeout_ms: number | null;
|
||||
max_rows: number | null;
|
||||
};
|
||||
@@ -0,0 +1,139 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { OutputRow, ParamRow } from "./types";
|
||||
import {
|
||||
detectSqlParams,
|
||||
firstOutputIssue,
|
||||
firstParamIssue,
|
||||
isFilledText,
|
||||
isIntegerInRange,
|
||||
isValidIdentifier,
|
||||
isValueTextValid,
|
||||
parseValueText,
|
||||
sqlParamStatus,
|
||||
} from "./validation";
|
||||
|
||||
const param = (overrides: Partial<ParamRow> = {}): ParamRow => ({
|
||||
key: 1,
|
||||
name: "line_code",
|
||||
type: "string",
|
||||
required: true,
|
||||
defaultText: "",
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const output = (overrides: Partial<OutputRow> = {}): OutputRow => ({
|
||||
key: 1,
|
||||
name: "lot_no",
|
||||
type: "string",
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe("basic checks", () => {
|
||||
it("isFilledText needs a visible character", () => {
|
||||
expect(isFilledText("SELECT 1")).toBe(true);
|
||||
expect(isFilledText(" ")).toBe(false);
|
||||
expect(isFilledText(undefined)).toBe(false);
|
||||
});
|
||||
|
||||
it("limits use whole numbers inside the server caps", () => {
|
||||
expect(isIntegerInRange(1, 1, 300000)).toBe(true);
|
||||
expect(isIntegerInRange(300000, 1, 300000)).toBe(true);
|
||||
expect(isIntegerInRange(300001, 1, 300000)).toBe(false);
|
||||
expect(isIntegerInRange(0, 1, 10000)).toBe(false);
|
||||
expect(isIntegerInRange(1.5, 1, 10000)).toBe(false);
|
||||
expect(isIntegerInRange(null, 1, 10000)).toBe(false);
|
||||
});
|
||||
|
||||
it("identifiers follow the backend pattern", () => {
|
||||
expect(isValidIdentifier("process_readings")).toBe(true);
|
||||
expect(isValidIdentifier("_x1")).toBe(true);
|
||||
expect(isValidIdentifier("1abc")).toBe(false);
|
||||
expect(isValidIdentifier("a.b")).toBe(false);
|
||||
expect(isValidIdentifier("a b")).toBe(false);
|
||||
expect(isValidIdentifier("")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("detectSqlParams", () => {
|
||||
it("finds :name markers once each", () => {
|
||||
expect(detectSqlParams("WHERE a = :line_code AND b >= :since AND c = :line_code")).toEqual([
|
||||
"line_code",
|
||||
"since",
|
||||
]);
|
||||
});
|
||||
|
||||
it("skips casts, quoted text and comments", () => {
|
||||
expect(detectSqlParams("SELECT x::int, ':not_this', 'it''s :nor_this' FROM t -- :comment\nWHERE y = :real")).toEqual(["real"]);
|
||||
expect(detectSqlParams("/* :hidden */ SELECT :shown")).toEqual(["shown"]);
|
||||
});
|
||||
|
||||
it("is empty for a template without parameters", () => {
|
||||
expect(detectSqlParams("SELECT 1")).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("sqlParamStatus", () => {
|
||||
it("separates undeclared and unused names", () => {
|
||||
const status = sqlParamStatus("SELECT :a, :b", ["a", " c ", ""]);
|
||||
expect(status.used).toEqual(["a", "b"]);
|
||||
expect(status.undeclared).toEqual(["b"]);
|
||||
expect(status.unused).toEqual(["c"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("value text", () => {
|
||||
it("blank text always fits (no default / not provided)", () => {
|
||||
for (const type of ["string", "integer", "number", "boolean", "datetime"]) {
|
||||
expect(isValueTextValid(type, " ")).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("checks integer, number and boolean text", () => {
|
||||
expect(isValueTextValid("integer", "42")).toBe(true);
|
||||
expect(isValueTextValid("integer", "4.2")).toBe(false);
|
||||
expect(isValueTextValid("integer", "abc")).toBe(false);
|
||||
expect(isValueTextValid("number", "4.2")).toBe(true);
|
||||
expect(isValueTextValid("number", "abc")).toBe(false);
|
||||
expect(isValueTextValid("boolean", "true")).toBe(true);
|
||||
expect(isValueTextValid("boolean", "yes")).toBe(false);
|
||||
expect(isValueTextValid("datetime", "2026-11-17 00:00:00")).toBe(true);
|
||||
});
|
||||
|
||||
it("converts text to JSON values by type", () => {
|
||||
expect(parseValueText("integer", " 7 ")).toBe(7);
|
||||
expect(parseValueText("number", "0.5")).toBe(0.5);
|
||||
expect(parseValueText("boolean", "false")).toBe(false);
|
||||
expect(parseValueText("boolean", "true")).toBe(true);
|
||||
expect(parseValueText("string", " keep spaces ")).toBe(" keep spaces ");
|
||||
expect(parseValueText("datetime", " 2026-11-17 ")).toBe("2026-11-17");
|
||||
});
|
||||
});
|
||||
|
||||
describe("firstParamIssue", () => {
|
||||
it("accepts a clean list", () => {
|
||||
expect(firstParamIssue([param(), param({ key: 2, name: "since", type: "datetime" })])).toBeNull();
|
||||
});
|
||||
|
||||
it("flags a bad name, a duplicate and a default that does not fit", () => {
|
||||
expect(firstParamIssue([param({ name: "1bad" })])).toEqual({ issue: "invalidName", name: "1bad" });
|
||||
expect(firstParamIssue([param({ name: " " })])).toEqual({ issue: "invalidName", name: "" });
|
||||
expect(firstParamIssue([param(), param({ key: 2 })])).toEqual({ issue: "duplicate", name: "line_code" });
|
||||
expect(firstParamIssue([param({ type: "integer", defaultText: "x" })])).toEqual({
|
||||
issue: "invalidDefault",
|
||||
name: "line_code",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("firstOutputIssue", () => {
|
||||
it("accepts a clean list and an empty one", () => {
|
||||
expect(firstOutputIssue([])).toBeNull();
|
||||
expect(firstOutputIssue([output(), output({ key: 2, name: "temperature", type: "number" })])).toBeNull();
|
||||
});
|
||||
|
||||
it("flags blank, too long and duplicate names", () => {
|
||||
expect(firstOutputIssue([output({ name: " " })])).toEqual({ issue: "invalidName", name: "" });
|
||||
expect(firstOutputIssue([output({ name: "x".repeat(129) })])?.issue).toBe("invalidName");
|
||||
expect(firstOutputIssue([output(), output({ key: 2 })])).toEqual({ issue: "duplicate", name: "lot_no" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,123 @@
|
||||
/**
|
||||
* Pure checks behind the query form, so they can be unit tested without a DOM.
|
||||
* Boundary: these mirror the backend's schema rules for early feedback only; the server stays
|
||||
* the authority. SQL is never parsed beyond spotting `:name` markers for a hint.
|
||||
*/
|
||||
|
||||
import { MAX_OUTPUT_NAME, type OutputRow, type ParamRow } from "./types";
|
||||
|
||||
/** Same pattern the backend uses for parameter names and allowed identifiers. */
|
||||
const IDENTIFIER_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
||||
|
||||
export function isFilledText(value: unknown): boolean {
|
||||
return typeof value === "string" && value.trim() !== "";
|
||||
}
|
||||
|
||||
/** A whole number within [min, max]. null, NaN, decimals and strings are rejected. */
|
||||
export function isIntegerInRange(value: unknown, min: number, max: number): boolean {
|
||||
return typeof value === "number" && Number.isInteger(value) && value >= min && value <= max;
|
||||
}
|
||||
|
||||
export function isValidIdentifier(value: string): boolean {
|
||||
return IDENTIFIER_RE.test(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parameter names used in a template as `:name`. Quoted text, comments and `::` casts are
|
||||
* skipped, so this is a hint only (the server prepares the real statement).
|
||||
*/
|
||||
export function detectSqlParams(sql: string): string[] {
|
||||
const text = sql
|
||||
.replace(/\/\*[\s\S]*?\*\//g, " ")
|
||||
.replace(/--[^\n]*/g, " ")
|
||||
.replace(/'(?:[^']|'')*'/g, "''");
|
||||
const found: string[] = [];
|
||||
const pattern = /(^|[^:\w]):([A-Za-z_]\w*)/g;
|
||||
let match = pattern.exec(text);
|
||||
while (match) {
|
||||
if (!found.includes(match[2])) {
|
||||
found.push(match[2]);
|
||||
}
|
||||
match = pattern.exec(text);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
export type SqlParamStatus = { used: string[]; undeclared: string[]; unused: string[] };
|
||||
|
||||
export function sqlParamStatus(sql: string, declared: string[]): SqlParamStatus {
|
||||
const used = detectSqlParams(sql);
|
||||
const names = declared.map((name) => name.trim()).filter((name) => name !== "");
|
||||
return {
|
||||
used,
|
||||
undeclared: used.filter((name) => !names.includes(name)),
|
||||
unused: names.filter((name) => !used.includes(name)),
|
||||
};
|
||||
}
|
||||
|
||||
/** Whether a typed default or preview value text fits the declared type. Blank means "none". */
|
||||
export function isValueTextValid(type: string, text: string): boolean {
|
||||
const value = text.trim();
|
||||
if (value === "") {
|
||||
return true;
|
||||
}
|
||||
if (type === "integer") {
|
||||
return /^[+-]?\d+$/.test(value);
|
||||
}
|
||||
if (type === "number") {
|
||||
return Number.isFinite(Number(value));
|
||||
}
|
||||
if (type === "boolean") {
|
||||
return value === "true" || value === "false";
|
||||
}
|
||||
// string and datetime: any text; the server judges a datetime's format.
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Converts a value text to a JSON value of the declared type. Call only when valid. */
|
||||
export function parseValueText(type: string, text: string): string | number | boolean {
|
||||
if (type === "integer" || type === "number") {
|
||||
return Number(text.trim());
|
||||
}
|
||||
if (type === "boolean") {
|
||||
return text.trim() === "true";
|
||||
}
|
||||
return type === "datetime" ? text.trim() : text;
|
||||
}
|
||||
|
||||
export type RowIssue = "invalidName" | "duplicate" | "invalidDefault";
|
||||
|
||||
/** First problem in the parameter rows, with the offending name, or null. */
|
||||
export function firstParamIssue(rows: ParamRow[]): { issue: RowIssue; name: string } | null {
|
||||
const seen = new Set<string>();
|
||||
for (const row of rows) {
|
||||
const name = row.name.trim();
|
||||
if (!isValidIdentifier(name)) {
|
||||
return { issue: "invalidName", name };
|
||||
}
|
||||
if (seen.has(name)) {
|
||||
return { issue: "duplicate", name };
|
||||
}
|
||||
seen.add(name);
|
||||
if (!isValueTextValid(row.type, row.defaultText)) {
|
||||
return { issue: "invalidDefault", name };
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** First problem in the output rows, with the offending name, or null. */
|
||||
export function firstOutputIssue(rows: OutputRow[]): { issue: RowIssue; name: string } | null {
|
||||
const seen = new Set<string>();
|
||||
for (const row of rows) {
|
||||
const name = row.name.trim();
|
||||
if (name === "" || name.length > MAX_OUTPUT_NAME) {
|
||||
return { issue: "invalidName", name };
|
||||
}
|
||||
if (seen.has(name)) {
|
||||
return { issue: "duplicate", name };
|
||||
}
|
||||
seen.add(name);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Console routes. Hash history keeps every page URL out of the API proxy prefixes
|
||||
* (the datasource API also lives under /datasources).
|
||||
* `meta.crumbs` lists the nav keys after "Watchman" in the breadcrumb.
|
||||
* (the datasource and query APIs also live under /datasources and /queries).
|
||||
* `meta.crumbs` lists the nav keys after the app name crumb in the breadcrumb.
|
||||
*/
|
||||
|
||||
import { createRouter, createWebHashHistory, type RouterHistory } from "vue-router";
|
||||
@@ -9,6 +9,10 @@ import DatasourceEdit from "./datasources/DatasourceEdit.vue";
|
||||
import DatasourceGate from "./datasources/DatasourceGate.vue";
|
||||
import DatasourceList from "./datasources/DatasourceList.vue";
|
||||
import HomeView from "./HomeView.vue";
|
||||
import QueryEdit from "./queries/QueryEdit.vue";
|
||||
import QueryGate from "./queries/QueryGate.vue";
|
||||
import QueryList from "./queries/QueryList.vue";
|
||||
import QueryVersionView from "./queries/QueryVersionView.vue";
|
||||
|
||||
export function createAppRouter(history: RouterHistory = createWebHashHistory()) {
|
||||
return createRouter({
|
||||
@@ -39,6 +43,36 @@ export function createAppRouter(history: RouterHistory = createWebHashHistory())
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
path: "/queries",
|
||||
component: QueryGate,
|
||||
children: [
|
||||
{
|
||||
path: "",
|
||||
name: "query-list",
|
||||
component: QueryList,
|
||||
meta: { crumbs: ["queries"] },
|
||||
},
|
||||
{
|
||||
path: "new",
|
||||
name: "query-create",
|
||||
component: QueryEdit,
|
||||
meta: { crumbs: ["queries", "create"] },
|
||||
},
|
||||
{
|
||||
path: ":id",
|
||||
name: "query-detail",
|
||||
component: QueryEdit,
|
||||
meta: { crumbs: ["queries", "detail"] },
|
||||
},
|
||||
{
|
||||
path: ":id/versions/:versionNo",
|
||||
name: "query-version",
|
||||
component: QueryVersionView,
|
||||
meta: { crumbs: ["queries", "detail", "version"] },
|
||||
},
|
||||
],
|
||||
},
|
||||
{ path: "/:pathMatch(.*)*", redirect: "/" },
|
||||
],
|
||||
});
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import { allowsDatasources, authHeaders, clearSession, loadSession, saveSession } from "./session";
|
||||
import { allowsDatasources, allowsQueries, authHeaders, clearSession, loadSession, saveSession } from "./session";
|
||||
|
||||
describe("session token storage", () => {
|
||||
beforeEach(() => {
|
||||
@@ -31,3 +31,12 @@ describe("datasource access", () => {
|
||||
expect(allowsDatasources([])).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("query access", () => {
|
||||
it("allows only watchman-admin, like datasources", () => {
|
||||
expect(allowsQueries(["watchman-admin"])).toBe(true);
|
||||
expect(allowsQueries(["watchman-operator"])).toBe(false);
|
||||
expect(allowsQueries(["watchman-viewer"])).toBe(false);
|
||||
expect(allowsQueries([])).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -23,6 +23,11 @@ export function allowsDatasources(roles: string[]): boolean {
|
||||
return roles.includes("watchman-admin");
|
||||
}
|
||||
|
||||
/** Only watchman-admin opens the query pages (same rule as datasources). */
|
||||
export function allowsQueries(roles: string[]): boolean {
|
||||
return roles.includes("watchman-admin");
|
||||
}
|
||||
|
||||
export function saveSession(user: SessionUser): void {
|
||||
const next = { ...user };
|
||||
if (next.expires_in && !next.token_expires_at) {
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
/**
|
||||
* Shared console table layout helpers.
|
||||
* Action-column widths are fixed by link-button count (see docs/current/frontend-ui.md).
|
||||
*/
|
||||
|
||||
/** ~48px per link button + 24px padding; keeps the ops column from stretching. */
|
||||
const ACTIONS_WIDTH_BY_COUNT: Record<number, number> = {
|
||||
1: 72,
|
||||
2: 120,
|
||||
3: 168,
|
||||
4: 216,
|
||||
5: 264,
|
||||
};
|
||||
|
||||
export function actionsColumnWidth(buttonCount: number): number {
|
||||
if (buttonCount in ACTIONS_WIDTH_BY_COUNT) {
|
||||
return ACTIONS_WIDTH_BY_COUNT[buttonCount];
|
||||
}
|
||||
return Math.max(72, 24 + buttonCount * 48);
|
||||
}
|
||||
|
||||
export const LIST_PAGE_SIZES = [10, 20, 50] as const;
|
||||
export const LIST_DEFAULT_PAGE_SIZE = 20;
|
||||
@@ -12,6 +12,7 @@ export default defineConfig({
|
||||
"/platform": "http://127.0.0.1:8000",
|
||||
"/auth": "http://127.0.0.1:8000",
|
||||
"/datasources": "http://127.0.0.1:8000",
|
||||
"/queries": "http://127.0.0.1:8000",
|
||||
},
|
||||
},
|
||||
});
|
||||
Reference in new issue
Block a user