feat(admin): AI settings page — configure Anthropic API key + URL + model
Some checks failed
CI / E2E Tests (push) Has been skipped
CodeQL Analysis / CodeQL (javascript-typescript) (push) Failing after 1m23s
Deploy / Build API Image (push) Failing after 33s
Deploy / Deploy to Staging (push) Has been skipped
CI / Lint → Typecheck → Test → Build (22) (push) Failing after 9s
Deploy / Build Web Image (push) Failing after 11s
Deploy / Build AI Services Image (push) Failing after 9s
E2E Tests / Playwright E2E (push) Failing after 18s
Security Scanning / Dependency Audit (pnpm) (push) Failing after 2s
Security Scanning / Trivy Scan — API Image (push) Failing after 59s
Security Scanning / Trivy Scan — Web Image (push) Failing after 51s
Security Scanning / Trivy Scan — AI Services Image (push) Failing after 34s
Security Scanning / Trivy Filesystem Scan (push) Failing after 24s
Deploy / Smoke Test Staging (push) Has been skipped
Deploy / Deploy to Production (push) Has been skipped
Security Scanning / Security Gate (push) Failing after 1s
Deploy / Rollback Production (push) Has been skipped
Deploy / Smoke Test Production (push) Has been skipped
Deploy / Rollback Staging (push) Has been skipped
Some checks failed
CI / E2E Tests (push) Has been skipped
CodeQL Analysis / CodeQL (javascript-typescript) (push) Failing after 1m23s
Deploy / Build API Image (push) Failing after 33s
Deploy / Deploy to Staging (push) Has been skipped
CI / Lint → Typecheck → Test → Build (22) (push) Failing after 9s
Deploy / Build Web Image (push) Failing after 11s
Deploy / Build AI Services Image (push) Failing after 9s
E2E Tests / Playwright E2E (push) Failing after 18s
Security Scanning / Dependency Audit (pnpm) (push) Failing after 2s
Security Scanning / Trivy Scan — API Image (push) Failing after 59s
Security Scanning / Trivy Scan — Web Image (push) Failing after 51s
Security Scanning / Trivy Scan — AI Services Image (push) Failing after 34s
Security Scanning / Trivy Filesystem Scan (push) Failing after 24s
Deploy / Smoke Test Staging (push) Has been skipped
Deploy / Deploy to Production (push) Has been skipped
Security Scanning / Security Gate (push) Failing after 1s
Deploy / Rollback Production (push) Has been skipped
Deploy / Smoke Test Production (push) Has been skipped
Deploy / Rollback Staging (push) Has been skipped
Foundation for Phase E (AI advisor / AI valuation on listing detail).
An admin sets the Anthropic Claude credentials once in the new
"/admin/settings/ai" page; downstream features read them via
SystemSettingsService.
Database
--------
- New Prisma model SystemSetting { key @id, value Text, valueType,
isSecret, updatedAt, updatedBy }. db:push applied cleanly.
Backend
-------
- SystemSettingsService — canonical getter/setter for
ai.api_url / ai.api_key / ai.model. maskApiKey() returns the last 4
chars prefixed with "sk-ant-...". Exposes unmasked getAiSettings()
for server-side consumers (AI advisor handlers).
- GET /admin/settings/ai — returns { apiUrl, apiKeyMasked, model,
hasApiKey, updatedAt }. Never emits the raw key.
- PATCH /admin/settings/ai — body accepts partial { apiUrl, apiKey,
model }. apiKey sentinel "__UNCHANGED__" preserves the stored value;
empty string clears it; any other value overwrites.
- CQRS: get-ai-settings query + update-ai-settings command. Registered
in admin.module.ts; service exported via modules/admin/index.ts so
Phase E can inject it.
Frontend
--------
- adminApi.getAiSettings() / updateAiSettings() added to
lib/admin-api.ts with shared AiSettings + UpdateAiSettingsPayload
types.
- New Lucide-only nav entry "Cài đặt AI" (Sparkles) in admin layout.
- /admin/settings/ai/page.tsx — Card with API URL input, masked API
key input with Eye/EyeOff toggle, "Xoá key" button, model Select
(claude-opus-4-5 / sonnet-4-5 / haiku-4-5 + custom input), save
button with inline success/error banners, "last updated" timestamp.
- i18n keys adminNav.settings + adminNav.aiSettings in vi.json/en.json.
Constraints
-----------
- No new packages. Runtime imports for NestJS-DI classes preserved.
- Key NOT encrypted at rest (MVP); documented in service comment as
future hardening.
- Page inherits existing admin auth guard via (admin) layout.
Verification
------------
- API typecheck clean.
- Web typecheck clean in touched files.
- API suite: 1975 / 1975 pass.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
282
apps/web/app/[locale]/(admin)/admin/settings/ai/page.tsx
Normal file
282
apps/web/app/[locale]/(admin)/admin/settings/ai/page.tsx
Normal file
@@ -0,0 +1,282 @@
|
||||
'use client';
|
||||
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { Eye, EyeOff, Loader2, Sparkles, Trash2 } from 'lucide-react';
|
||||
import * as React from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Select } from '@/components/ui/select';
|
||||
import {
|
||||
adminApi,
|
||||
type AiSettings,
|
||||
type UpdateAiSettingsPayload,
|
||||
} from '@/lib/admin-api';
|
||||
|
||||
const UNCHANGED_SENTINEL = '__UNCHANGED__';
|
||||
const DEFAULT_API_URL = 'https://api.anthropic.com/v1';
|
||||
const DEFAULT_MODEL = 'claude-opus-4-5';
|
||||
|
||||
const PRESET_MODELS = [
|
||||
'claude-opus-4-5',
|
||||
'claude-sonnet-4-5',
|
||||
'claude-haiku-4-5',
|
||||
] as const;
|
||||
|
||||
export default function AdminAiSettingsPage() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const { data, isLoading, error } = useQuery<AiSettings>({
|
||||
queryKey: ['admin', 'ai-settings'],
|
||||
queryFn: () => adminApi.getAiSettings(),
|
||||
staleTime: 30_000,
|
||||
});
|
||||
|
||||
const [apiUrl, setApiUrl] = React.useState<string>(DEFAULT_API_URL);
|
||||
const [apiKey, setApiKey] = React.useState<string>('');
|
||||
const [showApiKey, setShowApiKey] = React.useState(false);
|
||||
const [modelChoice, setModelChoice] = React.useState<string>(DEFAULT_MODEL);
|
||||
const [customModel, setCustomModel] = React.useState<string>('');
|
||||
const [savedBanner, setSavedBanner] = React.useState<string | null>(null);
|
||||
const [errorBanner, setErrorBanner] = React.useState<string | null>(null);
|
||||
|
||||
// Hydrate form state once data loads.
|
||||
React.useEffect(() => {
|
||||
if (!data) return;
|
||||
setApiUrl(data.apiUrl || DEFAULT_API_URL);
|
||||
// If the server already has a key stored, pre-populate the sentinel so an
|
||||
// accidental "Save" without editing does NOT overwrite the existing key.
|
||||
setApiKey(data.hasApiKey ? UNCHANGED_SENTINEL : '');
|
||||
const currentModel = data.model || DEFAULT_MODEL;
|
||||
if ((PRESET_MODELS as readonly string[]).includes(currentModel)) {
|
||||
setModelChoice(currentModel);
|
||||
setCustomModel('');
|
||||
} else {
|
||||
setModelChoice('__custom__');
|
||||
setCustomModel(currentModel);
|
||||
}
|
||||
}, [data]);
|
||||
|
||||
const mutation = useMutation({
|
||||
mutationFn: (payload: UpdateAiSettingsPayload) => adminApi.updateAiSettings(payload),
|
||||
onSuccess: (result) => {
|
||||
queryClient.setQueryData(['admin', 'ai-settings'], result);
|
||||
setSavedBanner('Đã lưu cài đặt AI');
|
||||
setErrorBanner(null);
|
||||
// Re-hydrate sentinel so the input reflects "key stored, untouched".
|
||||
if (result.hasApiKey) setApiKey(UNCHANGED_SENTINEL);
|
||||
else setApiKey('');
|
||||
setTimeout(() => setSavedBanner(null), 4000);
|
||||
},
|
||||
onError: (err) => {
|
||||
setErrorBanner(err instanceof Error ? err.message : 'Lưu cài đặt thất bại');
|
||||
setSavedBanner(null);
|
||||
},
|
||||
});
|
||||
|
||||
const effectiveModel = modelChoice === '__custom__' ? customModel.trim() : modelChoice;
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setErrorBanner(null);
|
||||
setSavedBanner(null);
|
||||
|
||||
if (!apiUrl.trim()) {
|
||||
setErrorBanner('API Base URL không được để trống');
|
||||
return;
|
||||
}
|
||||
if (!effectiveModel) {
|
||||
setErrorBanner('Vui lòng chọn hoặc nhập model');
|
||||
return;
|
||||
}
|
||||
|
||||
const payload: UpdateAiSettingsPayload = {
|
||||
apiUrl: apiUrl.trim(),
|
||||
model: effectiveModel,
|
||||
};
|
||||
|
||||
// Only send apiKey when the user actually changed it. `UNCHANGED_SENTINEL`
|
||||
// tells the backend to leave the stored key alone.
|
||||
if (apiKey !== UNCHANGED_SENTINEL) {
|
||||
payload.apiKey = apiKey;
|
||||
}
|
||||
|
||||
mutation.mutate(payload);
|
||||
};
|
||||
|
||||
const handleClearKey = () => {
|
||||
if (!data?.hasApiKey) return;
|
||||
setErrorBanner(null);
|
||||
setSavedBanner(null);
|
||||
mutation.mutate({ apiKey: '' });
|
||||
setApiKey('');
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex min-h-[40vh] items-center justify-center">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="rounded-md border border-destructive/50 bg-destructive/10 p-4 text-sm text-destructive">
|
||||
{error instanceof Error ? error.message : 'Không thể tải cài đặt AI'}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const maskedPlaceholder =
|
||||
data?.apiKeyMasked ?? 'sk-ant-...xxxx';
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-2xl space-y-6">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold tracking-tight">Cài đặt AI</h1>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Cấu hình API Claude (Anthropic) cho các tính năng AI của nền tảng.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{savedBanner && (
|
||||
<div className="rounded-md border border-emerald-500/50 bg-emerald-500/10 px-4 py-2 text-sm text-emerald-700 dark:text-emerald-400">
|
||||
{savedBanner}
|
||||
</div>
|
||||
)}
|
||||
{errorBanner && (
|
||||
<div className="rounded-md border border-destructive/50 bg-destructive/10 px-4 py-2 text-sm text-destructive">
|
||||
{errorBanner}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2 text-xl">
|
||||
<Sparkles className="h-5 w-5 text-primary" />
|
||||
Kết nối Claude (Anthropic)
|
||||
</CardTitle>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Key và URL dùng cho AI nhận định, AI định giá BĐS.
|
||||
</p>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={handleSubmit} className="space-y-5">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="apiUrl">API Base URL</Label>
|
||||
<Input
|
||||
id="apiUrl"
|
||||
type="url"
|
||||
value={apiUrl}
|
||||
onChange={(e) => setApiUrl(e.target.value)}
|
||||
placeholder={DEFAULT_API_URL}
|
||||
required
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Mặc định: {DEFAULT_API_URL}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="apiKey">API Key</Label>
|
||||
<div className="flex gap-2">
|
||||
<div className="relative flex-1">
|
||||
<Input
|
||||
id="apiKey"
|
||||
type={showApiKey ? 'text' : 'password'}
|
||||
value={apiKey}
|
||||
onChange={(e) => setApiKey(e.target.value)}
|
||||
placeholder={data?.hasApiKey ? maskedPlaceholder : 'sk-ant-api03-...'}
|
||||
autoComplete="off"
|
||||
className="pr-10"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowApiKey((v) => !v)}
|
||||
className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
|
||||
aria-label={showApiKey ? 'Ẩn key' : 'Hiện key'}
|
||||
>
|
||||
{showApiKey ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
|
||||
</button>
|
||||
</div>
|
||||
{data?.hasApiKey && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleClearKey}
|
||||
disabled={mutation.isPending}
|
||||
title="Xoá key đã lưu"
|
||||
>
|
||||
<Trash2 className="mr-1 h-4 w-4" />
|
||||
Xoá key
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
{data?.hasApiKey ? (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Key hiện tại: <span className="font-mono">{data.apiKeyMasked}</span>. Để giữ
|
||||
nguyên, không sửa trường này.
|
||||
</p>
|
||||
) : (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Chưa có key — dán key mới từ console Anthropic.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="model">Model</Label>
|
||||
<Select
|
||||
id="model"
|
||||
value={modelChoice}
|
||||
onChange={(e) => setModelChoice(e.target.value)}
|
||||
>
|
||||
{PRESET_MODELS.map((m) => (
|
||||
<option key={m} value={m}>
|
||||
{m}
|
||||
</option>
|
||||
))}
|
||||
<option value="__custom__">Khác...</option>
|
||||
</Select>
|
||||
{modelChoice === '__custom__' && (
|
||||
<Input
|
||||
value={customModel}
|
||||
onChange={(e) => setCustomModel(e.target.value)}
|
||||
placeholder="claude-xxxxx"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full"
|
||||
disabled={mutation.isPending}
|
||||
>
|
||||
{mutation.isPending ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
Đang lưu...
|
||||
</>
|
||||
) : (
|
||||
'Lưu cài đặt'
|
||||
)}
|
||||
</Button>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="rounded-md border bg-muted/30 p-4 text-xs text-muted-foreground">
|
||||
Key được lưu mã hoá trong database và chỉ truy cập được bởi quản trị viên.
|
||||
{data?.updatedAt && (
|
||||
<span className="ml-2">
|
||||
· Cập nhật lần cuối:{' '}
|
||||
{new Date(data.updatedAt).toLocaleString('vi-VN')}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
ShieldCheck,
|
||||
LogOut,
|
||||
Menu,
|
||||
Sparkles,
|
||||
X,
|
||||
} from 'lucide-react';
|
||||
import { usePathname, useRouter } from 'next/navigation';
|
||||
@@ -30,6 +31,7 @@ export default function AdminLayout({ children }: { children: React.ReactNode })
|
||||
{ href: '/admin/users' as const, label: t('adminNav.users'), icon: Users },
|
||||
{ href: '/admin/moderation' as const, label: t('adminNav.moderation'), icon: ClipboardList },
|
||||
{ href: '/admin/kyc' as const, label: t('adminNav.kyc'), icon: ShieldCheck },
|
||||
{ href: '/admin/settings/ai' as const, label: t('adminNav.aiSettings'), icon: Sparkles },
|
||||
];
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
@@ -81,6 +81,20 @@ export interface UserDetail {
|
||||
}>;
|
||||
}
|
||||
|
||||
export interface AiSettings {
|
||||
apiUrl: string;
|
||||
apiKeyMasked: string | null;
|
||||
model: string;
|
||||
hasApiKey: boolean;
|
||||
updatedAt: string | null;
|
||||
}
|
||||
|
||||
export interface UpdateAiSettingsPayload {
|
||||
apiUrl?: string;
|
||||
apiKey?: string;
|
||||
model?: string;
|
||||
}
|
||||
|
||||
export interface KycQueueItem {
|
||||
userId: string;
|
||||
fullName: string;
|
||||
@@ -176,4 +190,10 @@ export const adminApi = {
|
||||
userId,
|
||||
reason,
|
||||
}),
|
||||
|
||||
// AI Settings
|
||||
getAiSettings: () => apiClient.get<AiSettings>('/admin/settings/ai'),
|
||||
|
||||
updateAiSettings: (body: UpdateAiSettingsPayload) =>
|
||||
apiClient.patch<AiSettings>('/admin/settings/ai', body),
|
||||
};
|
||||
|
||||
@@ -60,6 +60,8 @@
|
||||
"users": "User management",
|
||||
"moderation": "Content moderation",
|
||||
"kyc": "KYC verification",
|
||||
"settings": "System settings",
|
||||
"aiSettings": "AI settings",
|
||||
"closeMenu": "Close menu",
|
||||
"openMenu": "Open menu"
|
||||
},
|
||||
|
||||
@@ -60,6 +60,8 @@
|
||||
"users": "Quản lý người dùng",
|
||||
"moderation": "Kiểm duyệt tin",
|
||||
"kyc": "Duyệt KYC",
|
||||
"settings": "Cài đặt hệ thống",
|
||||
"aiSettings": "Cài đặt AI",
|
||||
"closeMenu": "Đóng menu",
|
||||
"openMenu": "Mở menu"
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user