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

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:
Ho Ngoc Hai
2026-04-19 16:09:44 +07:00
parent 593d1594bd
commit ab26eb4c05
18 changed files with 655 additions and 0 deletions

View File

@@ -10,10 +10,12 @@ import { BanUserHandler } from './application/commands/ban-user/ban-user.handler
import { BulkModerateListingsHandler } from './application/commands/bulk-moderate-listings/bulk-moderate-listings.handler';
import { RejectKycHandler } from './application/commands/reject-kyc/reject-kyc.handler';
import { RejectListingHandler } from './application/commands/reject-listing/reject-listing.handler';
import { UpdateAiSettingsHandler } from './application/commands/update-ai-settings/update-ai-settings.handler';
import { UpdateUserStatusHandler } from './application/commands/update-user-status/update-user-status.handler';
import { AdminAuditListener } from './application/listeners/admin-audit.listener';
import { UserBannedListener } from './application/listeners/user-banned.listener';
import { UserDeactivatedListener } from './application/listeners/user-deactivated.listener';
import { GetAiSettingsHandler } from './application/queries/get-ai-settings/get-ai-settings.handler';
import { GetAuditLogsHandler } from './application/queries/get-audit-logs/get-audit-logs.handler';
import { GetDashboardStatsHandler } from './application/queries/get-dashboard-stats/get-dashboard-stats.handler';
import { GetKycQueueHandler } from './application/queries/get-kyc-queue/get-kyc-queue.handler';
@@ -21,6 +23,7 @@ import { GetModerationQueueHandler } from './application/queries/get-moderation-
import { GetRevenueStatsHandler } from './application/queries/get-revenue-stats/get-revenue-stats.handler';
import { GetUserDetailHandler } from './application/queries/get-user-detail/get-user-detail.handler';
import { GetUsersHandler } from './application/queries/get-users/get-users.handler';
import { SystemSettingsService } from './application/services/system-settings.service';
import { ADMIN_QUERY_REPOSITORY } from './domain/repositories/admin-query.repository';
import { AUDIT_LOG_REPOSITORY } from './domain/repositories/audit-log.repository';
import { PrismaAdminQueryRepository } from './infrastructure/repositories/prisma-admin-query.repository';
@@ -37,6 +40,7 @@ const CommandHandlers = [
ApproveKycHandler,
RejectKycHandler,
BulkModerateListingsHandler,
UpdateAiSettingsHandler,
];
const QueryHandlers = [
@@ -47,6 +51,7 @@ const QueryHandlers = [
GetUserDetailHandler,
GetKycQueueHandler,
GetAuditLogsHandler,
GetAiSettingsHandler,
];
@Module({
@@ -57,6 +62,9 @@ const QueryHandlers = [
{ provide: ADMIN_QUERY_REPOSITORY, useClass: PrismaAdminQueryRepository },
{ provide: AUDIT_LOG_REPOSITORY, useClass: PrismaAuditLogRepository },
// Services
SystemSettingsService,
// CQRS
...CommandHandlers,
...QueryHandlers,
@@ -66,5 +74,6 @@ const QueryHandlers = [
UserDeactivatedListener,
AdminAuditListener,
],
exports: [SystemSettingsService],
})
export class AdminModule {}

View File

@@ -14,3 +14,5 @@ export { RejectKycCommand } from './reject-kyc/reject-kyc.command';
export { RejectKycHandler } from './reject-kyc/reject-kyc.handler';
export { BulkModerateListingsCommand } from './bulk-moderate-listings/bulk-moderate-listings.command';
export { BulkModerateListingsHandler } from './bulk-moderate-listings/bulk-moderate-listings.handler';
export { UpdateAiSettingsCommand } from './update-ai-settings/update-ai-settings.command';
export { UpdateAiSettingsHandler } from './update-ai-settings/update-ai-settings.handler';

View File

@@ -0,0 +1,8 @@
export class UpdateAiSettingsCommand {
constructor(
public readonly adminId: string,
public readonly apiUrl?: string,
public readonly apiKey?: string,
public readonly model?: string,
) {}
}

View File

@@ -0,0 +1,43 @@
import { InternalServerErrorException } from '@nestjs/common';
import { CommandHandler, type ICommandHandler } from '@nestjs/cqrs';
import { DomainException, LoggerService } from '@modules/shared';
import { type AiSettingsDto } from '../../queries/get-ai-settings/get-ai-settings.handler';
import { SystemSettingsService } from '../../services/system-settings.service';
import { UpdateAiSettingsCommand } from './update-ai-settings.command';
@CommandHandler(UpdateAiSettingsCommand)
export class UpdateAiSettingsHandler
implements ICommandHandler<UpdateAiSettingsCommand>
{
constructor(
private readonly systemSettings: SystemSettingsService,
private readonly logger: LoggerService,
) {}
async execute(command: UpdateAiSettingsCommand): Promise<AiSettingsDto> {
try {
const updated = await this.systemSettings.updateAiSettings({
apiUrl: command.apiUrl,
apiKey: command.apiKey,
model: command.model,
updatedBy: command.adminId,
});
return {
apiUrl: updated.apiUrl,
apiKeyMasked: SystemSettingsService.maskApiKey(updated.apiKey),
model: updated.model,
hasApiKey: Boolean(updated.apiKey),
updatedAt: updated.updatedAt ? updated.updatedAt.toISOString() : null,
};
} catch (error) {
if (error instanceof DomainException) throw error;
this.logger.error(
`Failed to update AI settings: ${error instanceof Error ? error.message : String(error)}`,
error instanceof Error ? error.stack : undefined,
'UpdateAiSettingsHandler',
);
throw new InternalServerErrorException('Lỗi khi lưu cài đặt AI');
}
}
}

View File

@@ -0,0 +1,42 @@
import { InternalServerErrorException } from '@nestjs/common';
import { QueryHandler, type IQueryHandler } from '@nestjs/cqrs';
import { DomainException, LoggerService } from '@modules/shared';
import { SystemSettingsService } from '../../services/system-settings.service';
import { GetAiSettingsQuery } from './get-ai-settings.query';
export interface AiSettingsDto {
apiUrl: string;
apiKeyMasked: string | null;
model: string;
hasApiKey: boolean;
updatedAt: string | null;
}
@QueryHandler(GetAiSettingsQuery)
export class GetAiSettingsHandler implements IQueryHandler<GetAiSettingsQuery> {
constructor(
private readonly systemSettings: SystemSettingsService,
private readonly logger: LoggerService,
) {}
async execute(_query: GetAiSettingsQuery): Promise<AiSettingsDto> {
try {
const current = await this.systemSettings.getAiSettings();
return {
apiUrl: current.apiUrl,
apiKeyMasked: SystemSettingsService.maskApiKey(current.apiKey),
model: current.model,
hasApiKey: Boolean(current.apiKey),
updatedAt: current.updatedAt ? current.updatedAt.toISOString() : null,
};
} catch (error) {
if (error instanceof DomainException) throw error;
this.logger.error(
`Failed to get AI settings: ${error instanceof Error ? error.message : String(error)}`,
error instanceof Error ? error.stack : undefined,
'GetAiSettingsHandler',
);
throw new InternalServerErrorException('Lỗi khi đọc cài đặt AI');
}
}
}

View File

@@ -0,0 +1,3 @@
export class GetAiSettingsQuery {
constructor() {}
}

View File

@@ -12,3 +12,5 @@ export { GetKycQueueQuery } from './get-kyc-queue/get-kyc-queue.query';
export { GetKycQueueHandler } from './get-kyc-queue/get-kyc-queue.handler';
export { GetAuditLogsQuery } from './get-audit-logs/get-audit-logs.query';
export { GetAuditLogsHandler } from './get-audit-logs/get-audit-logs.handler';
export { GetAiSettingsQuery } from './get-ai-settings/get-ai-settings.query';
export { GetAiSettingsHandler, type AiSettingsDto } from './get-ai-settings/get-ai-settings.handler';

View File

@@ -0,0 +1,159 @@
import { Injectable } from '@nestjs/common';
import { PrismaService } from '@modules/shared';
/**
* SystemSettings service — read/write the SystemSetting key/value store for
* runtime-configurable platform settings (currently: Claude/Anthropic AI
* credentials).
*
* TODO(hardening): secret values are persisted as plain strings. A future
* iteration should encrypt `isSecret` entries at rest (libsodium / KMS).
*/
export const AI_SETTING_KEYS = {
apiUrl: 'ai.api_url',
apiKey: 'ai.api_key',
model: 'ai.model',
} as const;
export const AI_DEFAULTS = {
apiUrl: 'https://api.anthropic.com/v1',
model: 'claude-opus-4-5',
} as const;
export interface AiSettingsInternal {
apiUrl: string;
apiKey: string | null;
model: string;
updatedAt: Date | null;
}
export interface UpdateAiSettingsInput {
apiUrl?: string;
apiKey?: string; // pass empty string to clear, '__UNCHANGED__' to leave, undefined to leave
model?: string;
updatedBy?: string | null;
}
export const UNCHANGED_SENTINEL = '__UNCHANGED__';
@Injectable()
export class SystemSettingsService {
constructor(private readonly prisma: PrismaService) {}
/**
* Read the current AI settings including the raw (unmasked) API key. Intended
* for backend runtime consumers only — never return the raw key over HTTP.
*/
async getAiSettings(): Promise<AiSettingsInternal> {
const rows = await this.prisma.systemSetting.findMany({
where: {
key: {
in: [AI_SETTING_KEYS.apiUrl, AI_SETTING_KEYS.apiKey, AI_SETTING_KEYS.model],
},
},
});
const byKey = new Map(rows.map((r) => [r.key, r]));
const apiUrlRow = byKey.get(AI_SETTING_KEYS.apiUrl);
const apiKeyRow = byKey.get(AI_SETTING_KEYS.apiKey);
const modelRow = byKey.get(AI_SETTING_KEYS.model);
const latestUpdatedAt = rows.reduce<Date | null>((acc, r) => {
if (!acc || r.updatedAt > acc) return r.updatedAt;
return acc;
}, null);
return {
apiUrl: apiUrlRow?.value || AI_DEFAULTS.apiUrl,
apiKey: apiKeyRow?.value || null,
model: modelRow?.value || AI_DEFAULTS.model,
updatedAt: latestUpdatedAt,
};
}
async updateAiSettings(input: UpdateAiSettingsInput): Promise<AiSettingsInternal> {
const updatedBy = input.updatedBy ?? null;
const ops: Array<Promise<unknown>> = [];
if (input.apiUrl !== undefined) {
ops.push(
this.prisma.systemSetting.upsert({
where: { key: AI_SETTING_KEYS.apiUrl },
create: {
key: AI_SETTING_KEYS.apiUrl,
value: input.apiUrl,
valueType: 'string',
isSecret: false,
updatedBy,
},
update: { value: input.apiUrl, valueType: 'string', isSecret: false, updatedBy },
}),
);
}
if (input.model !== undefined) {
ops.push(
this.prisma.systemSetting.upsert({
where: { key: AI_SETTING_KEYS.model },
create: {
key: AI_SETTING_KEYS.model,
value: input.model,
valueType: 'string',
isSecret: false,
updatedBy,
},
update: { value: input.model, valueType: 'string', isSecret: false, updatedBy },
}),
);
}
// apiKey semantics:
// - undefined → do nothing
// - '__UNCHANGED__' → do nothing (frontend round-trip sentinel)
// - '' (empty) → explicit clear
// - any other string → overwrite
if (input.apiKey !== undefined && input.apiKey !== UNCHANGED_SENTINEL) {
if (input.apiKey === '') {
ops.push(
this.prisma.systemSetting.deleteMany({ where: { key: AI_SETTING_KEYS.apiKey } }),
);
} else {
ops.push(
this.prisma.systemSetting.upsert({
where: { key: AI_SETTING_KEYS.apiKey },
create: {
key: AI_SETTING_KEYS.apiKey,
value: input.apiKey,
valueType: 'secret',
isSecret: true,
updatedBy,
},
update: {
value: input.apiKey,
valueType: 'secret',
isSecret: true,
updatedBy,
},
}),
);
}
}
await Promise.all(ops);
return this.getAiSettings();
}
/**
* Mask an Anthropic API key: keep first 7 chars + `...` + last 4 chars.
* Example: `sk-ant-api03-abc...wxyz` → `sk-ant-...wxyz`.
*/
static maskApiKey(raw: string | null): string | null {
if (!raw) return null;
if (raw.length <= 11) {
// Too short to meaningfully mask — still hide the middle.
return `${raw.slice(0, Math.min(4, raw.length))}...`;
}
return `${raw.slice(0, 7)}...${raw.slice(-4)}`;
}
}

View File

@@ -1,4 +1,5 @@
export { AdminModule } from './admin.module';
export { SystemSettingsService } from './application/services/system-settings.service';
export { ListingApprovedEvent } from './domain/events/listing-approved.event';
export { ListingRejectedEvent } from './domain/events/listing-rejected.event';
export {

View File

@@ -15,8 +15,11 @@ import { AdjustSubscriptionCommand } from '../../application/commands/adjust-sub
import { type AdjustSubscriptionResult } from '../../application/commands/adjust-subscription/adjust-subscription.handler';
import { BanUserCommand } from '../../application/commands/ban-user/ban-user.command';
import { type BanUserResult } from '../../application/commands/ban-user/ban-user.handler';
import { UpdateAiSettingsCommand } from '../../application/commands/update-ai-settings/update-ai-settings.command';
import { UpdateUserStatusCommand } from '../../application/commands/update-user-status/update-user-status.command';
import { type UpdateUserStatusResult } from '../../application/commands/update-user-status/update-user-status.handler';
import { GetAiSettingsQuery } from '../../application/queries/get-ai-settings/get-ai-settings.query';
import { type AiSettingsDto } from '../../application/queries/get-ai-settings/get-ai-settings.handler';
import { GetAuditLogsQuery } from '../../application/queries/get-audit-logs/get-audit-logs.query';
import { GetDashboardStatsQuery } from '../../application/queries/get-dashboard-stats/get-dashboard-stats.query';
import { GetRevenueStatsQuery } from '../../application/queries/get-revenue-stats/get-revenue-stats.query';
@@ -34,6 +37,7 @@ import { BanUserDto } from '../dto/ban-user.dto';
import { GetAuditLogsQueryDto } from '../dto/get-audit-logs-query.dto';
import { GetUsersQueryDto } from '../dto/get-users-query.dto';
import { RevenueStatsDto } from '../dto/revenue-stats.dto';
import { UpdateAiSettingsDto } from '../dto/update-ai-settings.dto';
import { UpdateUserStatusDto } from '../dto/update-user-status.dto';
@ApiTags('admin')
@@ -171,6 +175,31 @@ export class AdminController {
);
}
// ── AI Settings ──
@Get('settings/ai')
@ApiOperation({ summary: 'Get AI provider (Claude) settings' })
@ApiResponse({ status: 200, description: 'AI settings retrieved successfully' })
@ApiResponse({ status: 401, description: 'Unauthorized missing or invalid JWT' })
@ApiResponse({ status: 403, description: 'Forbidden requires ADMIN role' })
async getAiSettings(): Promise<AiSettingsDto> {
return this.queryBus.execute(new GetAiSettingsQuery());
}
@Patch('settings/ai')
@ApiOperation({ summary: 'Update AI provider (Claude) settings' })
@ApiResponse({ status: 200, description: 'AI settings updated successfully' })
@ApiResponse({ status: 401, description: 'Unauthorized missing or invalid JWT' })
@ApiResponse({ status: 403, description: 'Forbidden requires ADMIN role' })
async updateAiSettings(
@Body() dto: UpdateAiSettingsDto,
@CurrentUser() user: JwtPayload,
): Promise<AiSettingsDto> {
return this.commandBus.execute(
new UpdateAiSettingsCommand(user.sub, dto.apiUrl, dto.apiKey, dto.model),
);
}
// ── Audit Logs ──
@Get('audit-logs')

View File

@@ -9,3 +9,4 @@ export { ApproveKycDto } from './approve-kyc.dto';
export { RejectKycDto } from './reject-kyc.dto';
export { BulkModerateDto } from './bulk-moderate.dto';
export { GetAuditLogsQueryDto } from './get-audit-logs-query.dto';
export { UpdateAiSettingsDto } from './update-ai-settings.dto';

View File

@@ -0,0 +1,32 @@
import { ApiPropertyOptional } from '@nestjs/swagger';
import { IsOptional, IsString, MaxLength } from 'class-validator';
export class UpdateAiSettingsDto {
@ApiPropertyOptional({
description: 'Base URL of the Anthropic-compatible API endpoint',
example: 'https://api.anthropic.com/v1',
})
@IsOptional()
@IsString()
@MaxLength(500)
apiUrl?: string;
@ApiPropertyOptional({
description:
'Raw API key. Send empty string to clear, "__UNCHANGED__" to leave untouched, omit to leave untouched.',
example: 'sk-ant-api03-xxxxxxxx',
})
@IsOptional()
@IsString()
@MaxLength(500)
apiKey?: string;
@ApiPropertyOptional({
description: 'Model identifier to use for Claude calls.',
example: 'claude-opus-4-5',
})
@IsOptional()
@IsString()
@MaxLength(120)
model?: string;
}