File size: 9,851 Bytes
345b8ff
 
 
4dc66a3
 
 
 
345b8ff
 
 
 
 
 
4dc66a3
 
345b8ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4dc66a3
 
 
 
 
 
 
 
 
 
345b8ff
 
 
 
 
 
4dc66a3
 
 
 
 
 
 
 
345b8ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4dc66a3
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
"use client";

import { useCallback, useMemo, useState } from "react";
import Link from "next/link";

import { AdminRulesPanel } from "@/components/admin-rules-panel";
import { Footer } from "@/components/footer";
import { useTenant } from "@/contexts/TenantContext";
import { TenantSelector } from "@/components/tenant-selector";

const BACKEND_BASE_URL = process.env.NEXT_PUBLIC_BACKEND_BASE_URL ?? "http://localhost:8000";

type StatusState = { tone: "info" | "success" | "error"; message: string } | null;

export default function AdminRulesPage() {
  const { tenantId } = useTenant();
  const [rulesInput, setRulesInput] = useState("");
  const [deleteInput, setDeleteInput] = useState("");
  const [rules, setRules] = useState<string[]>([]);
  const [loading, setLoading] = useState(false);
  const [status, setStatus] = useState<StatusState>(null);

  const headers = useMemo(() => {
    if (!tenantId.trim()) return undefined;
    return {
      "Content-Type": "application/json",
      "x-tenant-id": tenantId.trim(),
    };
  }, [tenantId]);

  const requireTenant = useCallback(() => {
    if (!tenantId.trim()) {
      setStatus({ tone: "error", message: "Enter a tenant ID in the navbar first." });
      return false;
    }
    return true;
  }, [tenantId]);

  const handleRefresh = useCallback(async () => {
    if (!requireTenant()) return;
    try {
      setLoading(true);
      setStatus({ tone: "info", message: "Loading rules..." });
      const response = await fetch(`${BACKEND_BASE_URL}/admin/rules`, {
        method: "GET",
        headers,
      });
      if (!response.ok) {
        throw new Error(`Backend error ${response.status}`);
      }
      const data = await response.json();
      setRules(data.rules ?? []);
      setStatus({ tone: "success", message: "Rules synced." });
    } catch (error: any) {
      setStatus({ tone: "error", message: error.message || "Failed to fetch rules" });
    } finally {
      setLoading(false);
    }
  }, [headers, requireTenant]);

  const handleUpload = useCallback(async () => {
    if (!requireTenant()) return;
    const lines = rulesInput
      .split("\n")
      .map((line) => line.trim())
      .filter(Boolean);

    if (!lines.length) {
      setStatus({ tone: "error", message: "Add at least one rule to upload." });
      return;
    }

    try {
      setLoading(true);
      setStatus({ tone: "info", message: "Uploading rules..." });
      const response = await fetch(`${BACKEND_BASE_URL}/admin/rules/bulk`, {
        method: "POST",
        headers,
        body: JSON.stringify({ rules: lines }),
      });
      if (!response.ok) {
        const details = await response.text();
        throw new Error(details || `Backend error ${response.status}`);
      }
      await handleRefresh();
      setRulesInput("");
      setStatus({ tone: "success", message: "Rules uploaded successfully." });
    } catch (error: any) {
      setStatus({ tone: "error", message: error.message || "Failed to upload rules" });
    } finally {
      setLoading(false);
    }
  }, [handleRefresh, headers, requireTenant, rulesInput]);

  const handleDelete = useCallback(async () => {
    if (!requireTenant()) return;
    if (!deleteInput.trim()) {
      setStatus({ tone: "error", message: "Enter the rule text you want to delete." });
      return;
    }

    try {
      setLoading(true);
      setStatus({ tone: "info", message: "Deleting rule..." });
      const response = await fetch(
        `${BACKEND_BASE_URL}/admin/rules/${encodeURIComponent(deleteInput.trim())}`,
        {
          method: "DELETE",
          headers,
        }
      );
      if (!response.ok) {
        const details = await response.text();
        throw new Error(details || `Backend error ${response.status}`);
      }
      await handleRefresh();
      setDeleteInput("");
      setStatus({ tone: "success", message: "Rule deleted." });
    } catch (error: any) {
      setStatus({ tone: "error", message: error.message || "Failed to delete rule" });
    } finally {
      setLoading(false);
    }
  }, [deleteInput, handleRefresh, headers, requireTenant]);

  return (
    <main className="mx-auto flex min-h-screen max-w-5xl flex-col gap-10 px-4 pb-16 pt-12 sm:px-6 lg:px-8">
      <header className="flex flex-col gap-4 rounded-2xl border border-white/10 bg-white/5 px-6 py-6 text-slate-100 shadow-lg shadow-slate-950/40">
        <div className="flex items-center justify-between gap-3">
          <div className="flex items-center gap-3 text-base font-semibold">
            <span className="inline-flex h-10 w-10 items-center justify-center rounded-2xl bg-gradient-to-br from-sky-400 to-cyan-500 text-slate-950">
              IC
            </span>
            IntegraChat · Admin Rule Ingestion
          </div>
          <div className="flex items-center gap-4">
            <TenantSelector />
            <Link href="/" className="text-xs font-semibold uppercase tracking-[0.3em] text-cyan-300 hover:text-white">
              ← Back Home
            </Link>
          </div>
        </div>
        <p className="text-sm text-slate-300">
          Push governance policies, compliance workflows, and red-flag patterns to the backend&apos;s persistent rules
          store using the MCP admin services.
        </p>
      </header>

      <AdminRulesPanel />

      <section className="rounded-3xl border border-white/10 bg-white/5 p-6 shadow-2xl shadow-slate-950/40">
        <div className="flex flex-col gap-6">
          <div className="flex items-center justify-end gap-3">
            <button
              onClick={handleRefresh}
              disabled={loading}
              className="flex-1 rounded-full bg-gradient-to-r from-cyan-400 to-blue-500 px-6 py-3 text-sm font-semibold text-slate-950 shadow-lg shadow-cyan-500/30 disabled:opacity-60"
            >
              Refresh Rules
            </button>
          </div>

          <div className="grid gap-4 lg:grid-cols-2">
            <label className="flex flex-col gap-2 text-sm font-semibold text-slate-200">
              Bulk Upload Rules (one per line)
              <textarea
                value={rulesInput}
                onChange={(e) => setRulesInput(e.target.value)}
                placeholder="Disallow sharing salaries\nBlock deleting production data"
                rows={6}
                className="rounded-2xl border border-white/10 bg-slate-900/50 px-4 py-3 text-base text-white outline-none ring-0 focus:border-cyan-400"
              />
            </label>
            <label className="flex flex-col gap-2 text-sm font-semibold text-slate-200">
              Delete Rule (exact text match)
              <textarea
                value={deleteInput}
                onChange={(e) => setDeleteInput(e.target.value)}
                placeholder="Enter the exact rule text to remove..."
                rows={6}
                className="rounded-2xl border border-white/10 bg-slate-900/50 px-4 py-3 text-base text-white outline-none ring-0 focus:border-cyan-400"
              />
            </label>
          </div>

          <div className="flex flex-wrap gap-3">
            <button
              onClick={handleUpload}
              disabled={loading}
              className="rounded-full bg-gradient-to-r from-emerald-400 to-lime-400 px-6 py-3 text-sm font-semibold text-slate-900 shadow-lg shadow-emerald-500/30 disabled:opacity-60"
            >
              Upload / Append Rules
            </button>
            <button
              onClick={handleDelete}
              disabled={loading}
              className="rounded-full border border-rose-500 px-6 py-3 text-sm font-semibold text-rose-300 transition hover:bg-rose-500/10 disabled:opacity-60"
            >
              Delete Rule
            </button>
          </div>

          {status && (
            <div
              className={`rounded-2xl border px-4 py-3 text-sm ${
                status.tone === "error"
                  ? "border-rose-500/40 bg-rose-500/10 text-rose-200"
                  : status.tone === "success"
                    ? "border-emerald-500/40 bg-emerald-500/10 text-emerald-200"
                    : "border-cyan-500/40 bg-cyan-500/10 text-cyan-200"
              }`}
            >
              {status.message}
            </div>
          )}

          <div className="rounded-2xl border border-white/10 bg-slate-950/40">
            <div className="flex items-center justify-between border-b border-white/5 px-5 py-3 text-xs uppercase tracking-[0.3em] text-slate-400">
              <span>Rule Set</span>
              <span>{rules.length} entries</span>
            </div>
            <div className="overflow-x-auto">
              <table className="w-full text-left text-sm text-slate-200">
                <thead className="bg-white/5 text-xs uppercase tracking-[0.2em] text-slate-400">
                  <tr>
                    <th className="px-4 py-3">#</th>
                    <th className="px-4 py-3">Rule</th>
                  </tr>
                </thead>
                <tbody>
                  {rules.length === 0 && (
                    <tr>
                      <td colSpan={2} className="px-4 py-6 text-center text-slate-500">
                        No rules loaded. Use the refresh button above.
                      </td>
                    </tr>
                  )}
                  {rules.map((rule, idx) => (
                    <tr key={`${rule}-${idx}`} className="border-t border-white/5">
                      <td className="px-4 py-3 text-slate-400">{idx + 1}</td>
                      <td className="px-4 py-3">{rule}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </section>

      <Footer />
    </main>
  );
}