<!-- Карточка правила: условия кодом с подсветкой, действия с целями,
шаблон и шумодав. -->
<script setup>
import { computed, onMounted, ref } from "vue";
import {
GnBadge,
GnButton,
GnChip,
GnConfirmDialog,
GnIconButton,
GnLoader,
GnPageHeader,
GnStatusCard,
GnSwitch,
} from "gnexus-ui-kit/vue";
import { useToast } from "gnexus-ui-kit/vue";
import { useRoute, useRouter } from "vue-router";
import { api } from "../api.js";
import { fmtTime, jsonSpans } from "../ui.js";
import CodeBlock from "../components/CodeBlock.vue";
const toast = useToast();
const route = useRoute();
const router = useRouter();
const rule = ref(null);
const loading = ref(true);
const error = ref("");
async function load() {
loading.value = true;
error.value = "";
try {
const rules = await api.listRules();
rule.value = rules.find((r) => r.id === Number(route.params.id)) || null;
if (!rule.value) error.value = "Правило не найдено";
} catch (ex) {
error.value = ex.message;
} finally {
loading.value = false;
}
}
async function toggleRule(enabled) {
try {
await api.patchRule(rule.value.id, { enabled });
rule.value = { ...rule.value, enabled };
toast.info(`Правило ${enabled ? "включено" : "выключено"}`);
} catch (ex) {
toast.error(ex.message);
await load();
}
}
const confirmDelete = ref(false);
async function doDelete() {
try {
await api.deleteRule(rule.value.id);
toast.success("Правило удалено");
router.push("/rules");
} catch (ex) {
toast.error(ex.message);
confirmDelete.value = false;
}
}
const CONDITION_KEYS = {
source: "Источник: имя source из реестра",
subjects: "Subject'ы события (любой из)",
actions: "Action'ы события (любой из)",
priority_min: "Минимальный приоритет (low/normal/high/critical)",
payload: "Требования к полям payload (все указанные; значение-список = любой из)",
};
// Условия: ключи с человекочитаемой подписью, значение — код с подсветкой
const conditionRows = computed(() =>
Object.entries(rule.value?.conditions || {}).map(([key, value]) => ({
key,
hint: CONDITION_KEYS[key] || "",
spans: jsonSpans(value),
text: JSON.stringify(value, null, 2),
})),
);
const WEIGHT_TIP =
"Вес определяет порядок применения правил в режиме «первое подошедшее» (ROUTING_MATCH_MODE=first): меньше важнее, срабатывает раньше. В режиме «все» на результат не влияет.";
const THROTTLE_TIP =
"Шумодав: не чаще одной живой доставки в эту цель за N секунд. Подавленное отмечается статусом skipped, critical проходит всегда.";
onMounted(load);
</script>
<template>
<main class="container page">
<GnPageHeader kicker="Synapse · Правило" :title="rule?.name || '…'" subtitle="Условия → действия маршрутизации">
<template #actions>
<GnIconButton icon="ph-arrow-left" label="К списку правил" @click="router.push('/rules')" />
<GnIconButton icon="ph-trash" label="Удалить правило" @click="confirmDelete = true" />
<GnSwitch
v-if="rule"
:model-value="rule.enabled"
@update:model-value="(v) => toggleRule(v)"
/>
</template>
</GnPageHeader>
<GnLoader v-if="loading" />
<GnStatusCard v-else-if="error" variant="error" icon="ph-warning-circle" :text="error" />
<template v-else>
<section class="panel">
<h3 class="panel-title">Параметры</h3>
<dl class="meta">
<div class="meta-row">
<dt>Статус</dt>
<dd>
<GnBadge :variant="rule.enabled ? 'success' : 'secondary'" outline>
{{ rule.enabled ? "включено" : "выключено" }}
</GnBadge>
</dd>
</div>
<div class="meta-row">
<dt>Вес</dt>
<dd>{{ rule.weight }} <span class="mini-hint">{{ WEIGHT_TIP }}</span></dd>
</div>
<div class="meta-row">
<dt>Шумодав</dt>
<dd>
<template v-if="rule.throttle_seconds">
<GnBadge variant="warning" outline>{{ rule.throttle_seconds }} с</GnBadge>
</template>
<template v-else>—</template>
</dd>
</div>
<div class="meta-row">
<dt>Создано</dt>
<dd>{{ fmtTime(rule.created_at) }}</dd>
</div>
</dl>
<p v-if="rule.throttle_seconds" class="channel-hint">
<i class="ph ph-info"></i> {{ THROTTLE_TIP }}
</p>
</section>
<section class="panel">
<h3 class="panel-title">Условия</h3>
<ul class="conditions">
<li v-for="c in conditionRows" :key="c.key" class="condition">
<div class="condition-name">
<code>{{ c.key }}</code>
<span v-if="c.hint" class="condition-hint">{{ c.hint }}</span>
</div>
<CodeBlock :value="c.text" />
</li>
</ul>
</section>
<section class="panel">
<h3 class="panel-title">Шаблон сообщения</h3>
<p v-if="rule.template" class="template-text"><code>{{ rule.template }}</code></p>
<p v-else class="template-text muted">— не задан; у действий может быть свой шаблон</p>
</section>
<section class="panel">
<h3 class="panel-title">Действия</h3>
<ul class="actions-list">
<li v-for="(a, i) in rule.actions" :key="i" class="action-item">
<div class="action-head">
<span class="action-num">{{ i + 1 }}</span>
<GnBadge :variant="a.channel === 'internal_log' ? 'secondary' : 'accent'">
{{ a.channel }}
</GnBadge>
<GnChip v-if="a.target_name" variant="accent">{{ a.target_name }}</GnChip>
<span v-else class="mini-hint">без цели</span>
</div>
<div class="action-body">
<template v-if="a.template">
<span class="mini-hint">шаблон действия:</span>
<code class="tpl">{{ a.template }}</code>
</template>
<template v-else-if="!a.template && !rule.template && a.channel !== 'internal_log'">
<span class="mini-hint">шаблон не задан</span>
</template>
</div>
</li>
</ul>
</section>
</template>
<!-- Удаление правила -->
<GnConfirmDialog
v-model:open="confirmDelete"
title="Удалить правило?"
:message="`Правило «${rule?.name}» будет удалено вместе с действиями. История доставок останется.`"
confirm-variant="danger"
confirm-text="Удалить"
cancel-text="Отмена"
@confirm="doDelete"
/>
</main>
</template>
<style scoped>
.page {
max-width: 1440px;
margin-inline: auto;
padding-block: var(--gn-space-6);
display: flex;
flex-direction: column;
gap: var(--gn-space-4);
}
.panel {
background: var(--gn-surface-panel);
border: 1px solid var(--gn-border-color-muted);
border-radius: 6px;
padding: var(--gn-space-4) var(--gn-space-5);
display: flex;
flex-direction: column;
gap: var(--gn-space-3);
}
.panel-title {
margin: 0;
text-transform: uppercase;
letter-spacing: 0.04em;
font-size: 0.8em;
}
.meta {
margin: 0;
display: grid;
gap: var(--gn-space-2);
}
.meta-row {
display: grid;
grid-template-columns: minmax(120px, 160px) 1fr;
gap: var(--gn-space-3);
align-items: start;
}
.meta-row dt {
color: var(--gn-color-text-medium);
font-size: 0.82em;
text-transform: uppercase;
letter-spacing: 0.04em;
}
.meta-row dd {
margin: 0;
display: flex;
align-items: center;
gap: var(--gn-space-2);
flex-wrap: wrap;
}
.mini-hint {
font-size: 0.8em;
opacity: 0.7;
}
.channel-hint {
margin: 0;
font-size: 0.82em;
opacity: 0.75;
}
.conditions {
margin: 0;
padding: 0;
list-style: none;
display: grid;
gap: var(--gn-space-4);
}
.condition-name {
display: flex;
align-items: baseline;
gap: var(--gn-space-3);
margin-bottom: var(--gn-space-1);
}
.condition-hint {
font-size: 0.82em;
opacity: 0.75;
}
.template-text {
margin: 0;
border-radius: 6px;
padding: var(--gn-space-3) var(--gn-space-4);
background: var(--gn-surface-panel-muted);
overflow-wrap: anywhere;
white-space: pre-wrap;
}
.template-text.muted {
background: none;
}
.actions-list {
margin: 0;
padding: 0;
list-style: none;
display: grid;
gap: var(--gn-space-3);
}
.action-item {
padding: var(--gn-space-3) var(--gn-space-4);
border: 1px solid var(--gn-border-color-muted);
border-radius: 6px;
background: var(--gn-surface-panel-muted);
display: flex;
flex-direction: column;
gap: var(--gn-space-2);
}
.action-head {
display: flex;
align-items: center;
gap: var(--gn-space-3);
flex-wrap: wrap;
}
.action-body {
display: flex;
align-items: baseline;
gap: var(--gn-space-3);
}
.action-num {
opacity: 0.6;
font-size: 0.85em;
}
.tpl {
font-size: 0.85em;
overflow-wrap: anywhere;
}
</style>