Files
studio-admin-fe/src/pages/applications/AppManagementPage.tsx
T
chyoo 9625752a81
ci/woodpecker/push/woodpecker Pipeline was successful
track requesters for builds releases deployments and migrations
2026-07-10 10:42:56 +09:00

2109 lines
103 KiB
TypeScript

import { useEffect, useState, type MouseEvent } from 'react';
import { Database, Pencil, Play, Plus, RotateCcw, Settings2, Square, Trash2, UserCog } from 'lucide-react';
import { Badge, Button, Card, CardHeader, Modal } from '../../components/ui';
import { useToast } from '../../components/toast';
import { PageTitle } from '../../layout/AppLayout';
import { apiBaseUrl, apiFetch, authHeaders } from '../../lib/api';
import { filterAppsByCurrentAdmin, grantAppPermissionToCurrentAdmin, isOwnerAdmin, setAdminAppPermissions } from '../../lib/admin-app-permissions';
import { runtimeStatusDotClass, statusDotToneClass } from '../../lib/status-dot';
import { cn } from '../../lib/utils';
import { getStoredSelectedAppId, setStoredSelectedAppId } from '../../lib/selected-app';
import type { ApiApp, ApiAppComponent, BuildEnvVariable, RuntimePersistentVolumeClaim, RuntimeResource } from '../../types/runtime';
import { LoadingModal } from '../operations/operation-utils';
import { loadAdmins, updateAdminAppPermissions, type AdminAccount } from '../operations/operations-api';
type ComponentPortForm = {
name: string;
port: string;
targetPort: string;
nodePort: string;
protocol: string;
};
type BuildEnvVariableForm = {
id?: string;
key: string;
value: string;
isSecret: boolean;
};
const emptyComponentPort = (): ComponentPortForm => ({
name: '',
port: '',
targetPort: '',
nodePort: '',
protocol: 'TCP'
});
const emptyBuildEnvVariable = (): BuildEnvVariableForm => ({
key: '',
value: '',
isSecret: false
});
function useMinimumLoading(loading: boolean, minimumMs = 500) {
const [visible, setVisible] = useState(loading);
useEffect(() => {
if (loading) {
setVisible(true);
return;
}
const timer = window.setTimeout(() => setVisible(false), minimumMs);
return () => window.clearTimeout(timer);
}, [loading, minimumMs]);
return visible;
}
function isPageAgentClick(event: MouseEvent<HTMLElement>) {
return !event.nativeEvent.isTrusted;
}
function blockPageAgentDestructiveClick(event: MouseEvent<HTMLElement>) {
if (!isPageAgentClick(event)) return false;
event.preventDefault();
event.stopPropagation();
return true;
}
function getTone(status: string) {
if (['활성', '완료', '게시됨', '실행 중', '배포됨', 'ACTIVE', 'READY'].includes(status)) return 'green';
if (['주의', '예약됨', '대기', '준비중', '카나리'].includes(status)) return 'amber';
if (['잠김', '실패', '오프라인', '비활성'].includes(status)) return 'red';
if (['진행중', '동기화'].includes(status)) return 'blue';
return 'neutral';
}
function formatStatus(status?: string | null, launcherLinked?: boolean) {
if (status === 'DISABLED' || status === 'INACTIVE') return '비활성';
if (launcherLinked) return '활성';
const statusMap: Record<string, string> = {
ACTIVE: '활성',
READY: '준비됨',
ERROR: '오류'
};
return status ? statusMap[status] ?? status : '-';
}
function AppAdminAvatar({ admin }: { admin: AdminAccount }) {
const [failed, setFailed] = useState(false);
const initial = (admin.name || admin.email || '?').trim().charAt(0).toUpperCase() || '?';
if (admin.avatarUrl && !failed) {
return (
<img
src={admin.avatarUrl}
alt=""
className="size-8 shrink-0 rounded-full border border-border bg-muted object-cover"
onError={() => setFailed(true)}
/>
);
}
return (
<span className="inline-flex size-8 shrink-0 items-center justify-center rounded-full border border-border bg-muted text-xs font-semibold text-muted-foreground">
{initial}
</span>
);
}
function loadApps() {
return apiFetch(`${apiBaseUrl}/apps`, { headers: authHeaders() })
.then((response) => {
if (!response.ok) {
throw new Error('Apps request failed');
}
return response.json() as Promise<ApiApp[]>;
})
.then(filterAppsByCurrentAdmin);
}
function loadRuntimeResources(namespace: string) {
return apiFetch(`${apiBaseUrl}/apps/runtime-namespaces/${encodeURIComponent(namespace)}/resources`, { headers: authHeaders() })
.then((response) => {
if (!response.ok) throw new Error('Runtime resources request failed');
return response.json() as Promise<{ resources: RuntimeResource[] }>;
});
}
function controlRuntimeWorkload(namespace: string, kind: string, name: string, action: 'restart' | 'start' | 'stop') {
const apiKind = kind === 'Deployment' ? 'deployment' : kind === 'StatefulSet' ? 'statefulset' : kind === 'DaemonSet' ? 'daemonset' : '';
if (!apiKind) return Promise.reject(new Error('지원하지 않는 워크로드 유형입니다.'));
const path = action === 'restart'
? `/runtime/workloads/${encodeURIComponent(namespace)}/${encodeURIComponent(apiKind)}/${encodeURIComponent(name)}/restart`
: `/runtime/workloads/${encodeURIComponent(namespace)}/${encodeURIComponent(apiKind)}/${encodeURIComponent(name)}/scale`;
return apiFetch(`${apiBaseUrl}${path}`, {
method: 'POST',
headers: authHeaders({ 'Content-Type': 'application/json' }),
body: action === 'restart' ? undefined : JSON.stringify({ replicas: action === 'start' ? 1 : 0 })
}).then((response) => {
if (!response.ok) throw new Error('워크로드 제어 요청이 실패했습니다.');
return response.json().catch(() => null);
});
}
function deleteRuntimeWorkload(namespace: string, kind: string, name: string, deleteService: boolean) {
const apiKind = kind === 'Deployment' ? 'deployment' : kind === 'StatefulSet' ? 'statefulset' : kind === 'DaemonSet' ? 'daemonset' : '';
if (!apiKind) return Promise.reject(new Error('지원하지 않는 워크로드 유형입니다.'));
const query = deleteService ? '?deleteService=true' : '';
return apiFetch(`${apiBaseUrl}/runtime/workloads/${encodeURIComponent(namespace)}/${encodeURIComponent(apiKind)}/${encodeURIComponent(name)}${query}`, {
method: 'DELETE',
headers: authHeaders()
}).then(async (response) => {
if (!response.ok) {
const body = await response.json().catch(() => null);
const message = Array.isArray(body?.message) ? body.message.join(', ') : body?.message;
throw new Error(message || '워크로드 삭제 요청이 실패했습니다.');
}
return response.json().catch(() => null);
});
}
function loadWorkloadPersistentVolumeClaims(namespace: string, kind: string, name: string) {
const apiKind = kind === 'StatefulSet' ? 'statefulset' : '';
if (!apiKind) return Promise.reject(new Error('StatefulSet 데이터 볼륨만 조회할 수 있습니다.'));
return apiFetch(`${apiBaseUrl}/runtime/workloads/${encodeURIComponent(namespace)}/${encodeURIComponent(apiKind)}/${encodeURIComponent(name)}/pvcs`, {
headers: authHeaders()
}).then(async (response) => {
if (!response.ok) {
const body = await response.json().catch(() => null);
const message = Array.isArray(body?.message) ? body.message.join(', ') : body?.message;
throw new Error(message || '데이터 볼륨 조회 요청이 실패했습니다.');
}
return response.json() as Promise<{ claims: RuntimePersistentVolumeClaim[] }>;
});
}
function deleteWorkloadPersistentVolumeClaim(namespace: string, kind: string, name: string, claimName: string) {
const apiKind = kind === 'StatefulSet' ? 'statefulset' : '';
if (!apiKind) return Promise.reject(new Error('StatefulSet 데이터 볼륨만 삭제할 수 있습니다.'));
return apiFetch(`${apiBaseUrl}/runtime/workloads/${encodeURIComponent(namespace)}/${encodeURIComponent(apiKind)}/${encodeURIComponent(name)}/pvcs/${encodeURIComponent(claimName)}`, {
method: 'DELETE',
headers: authHeaders()
}).then(async (response) => {
if (!response.ok) {
const body = await response.json().catch(() => null);
const message = Array.isArray(body?.message) ? body.message.join(', ') : body?.message;
throw new Error(message || '데이터 볼륨 삭제 요청이 실패했습니다.');
}
return response.json().catch(() => null);
});
}
function loadComponentBuildEnv(componentId: string) {
return apiFetch(`${apiBaseUrl}/apps/components/${encodeURIComponent(componentId)}/build-env`, {
headers: authHeaders()
}).then(async (response) => {
if (!response.ok) {
const body = await response.json().catch(() => null);
const message = Array.isArray(body?.message) ? body.message.join(', ') : body?.message;
throw new Error(message || '빌드 환경변수 조회 요청이 실패했습니다.');
}
return response.json() as Promise<{ variables: BuildEnvVariable[] }>;
});
}
function saveComponentBuildEnv(componentId: string, variables: BuildEnvVariableForm[]) {
return apiFetch(`${apiBaseUrl}/apps/components/${encodeURIComponent(componentId)}/build-env`, {
method: 'PUT',
headers: authHeaders({ 'Content-Type': 'application/json' }),
body: JSON.stringify({
variables: variables
.map((variable) => ({
key: variable.key.trim(),
value: variable.value,
isSecret: variable.isSecret
}))
.filter((variable) => variable.key)
})
}).then(async (response) => {
if (!response.ok) {
const body = await response.json().catch(() => null);
const message = Array.isArray(body?.message) ? body.message.join(', ') : body?.message;
throw new Error(message || '빌드 환경변수 저장 요청이 실패했습니다.');
}
return response.json() as Promise<{ variables: BuildEnvVariable[] }>;
});
}
function isRunningResource(resource: RuntimeResource) {
if (!['Pod', 'Deployment', 'StatefulSet', 'DaemonSet'].includes(resource.kind)) return false;
return ['Running', 'Pending', 'ContainerCreating'].includes(resource.status) || !resource.ready.endsWith('/0');
}
function isWorkloadResource(resource: RuntimeResource) {
return ['Deployment', 'StatefulSet', 'DaemonSet'].includes(resource.kind);
}
function isStoppedResource(resource: RuntimeResource) {
return resource.ready.endsWith('/0');
}
function runtimeStatusLabel(resource: RuntimeResource, stopped: boolean) {
if (stopped) return '중지됨';
if (resource.status === 'Running') return '실행 중';
if (resource.status === 'Pending' || resource.status === 'ContainerCreating') return '준비 중';
if (['Error', 'CrashLoopBackOff', 'ImagePullBackOff', 'Failed'].includes(resource.status)) return '오류';
return resource.status || '-';
}
function runtimeStatusTone(resource: RuntimeResource, stopped: boolean): 'neutral' | 'green' | 'amber' | 'red' | 'blue' {
if (stopped) return 'neutral';
if (resource.status === 'Running') return 'green';
if (resource.status === 'Pending' || resource.status === 'ContainerCreating') return 'amber';
if (['Error', 'CrashLoopBackOff', 'ImagePullBackOff', 'Failed'].includes(resource.status)) return 'red';
return 'blue';
}
function isComponentRunning(component: ApiAppComponent, resources: RuntimeResource[]) {
const name = component.name.toLowerCase();
return resources.some((resource) => {
const resourceName = resource.name.toLowerCase();
return isRunningResource(resource) && (resourceName === name || resourceName.startsWith(`${name}-`));
});
}
function componentPortForms(component: ApiAppComponent): ComponentPortForm[] {
if (component.ports?.length) {
return component.ports.map((port) => ({
name: port.name ?? '',
port: port.port ? String(port.port) : '',
targetPort: port.targetPort ? String(port.targetPort) : '',
nodePort: port.nodePort ? String(port.nodePort) : '',
protocol: port.protocol ?? 'TCP'
}));
}
if (component.port) {
return [{
name: 'http',
port: String(component.port),
targetPort: String(component.targetPort ?? component.port),
nodePort: '',
protocol: 'TCP'
}];
}
return [emptyComponentPort()];
}
function formatComponentPorts(component: ApiAppComponent) {
const ports = componentPortForms(component).filter((port) => port.port);
if (ports.length === 0) return '-';
return ports.map((port) => {
const nodePort = port.nodePort ? ` / node ${port.nodePort}` : '';
return `${port.name || 'port'} ${port.port}:${port.targetPort || port.port}${nodePort}`;
}).join(', ');
}
function appKeyFromName(name: string) {
return name
.toLowerCase()
.trim()
.replace(/\s+/g, '-')
.replace(/[^a-z0-9-]/g, '')
.replace(/-+/g, '-')
.replace(/^-|-$/g, '');
}
export function AppManagementPage() {
const { toast } = useToast();
const [apiApps, setApiApps] = useState<ApiApp[]>([]);
const [isAppsLoading, setIsAppsLoading] = useState(true);
const appsLoadingVisible = useMinimumLoading(isAppsLoading);
const [selectedAppId, setSelectedAppId] = useState(() => getStoredSelectedAppId());
const [isCreateAppOpen, setIsCreateAppOpen] = useState(false);
const [newAppKey, setNewAppKey] = useState('');
const [newAppName, setNewAppName] = useState('');
const [newAppNamespace, setNewAppNamespace] = useState('');
const [newAppDescription, setNewAppDescription] = useState('');
const [appCreateStatus, setAppCreateStatus] = useState<'idle' | 'saving' | 'error'>('idle');
const [isComponentOpen, setIsComponentOpen] = useState(false);
const [componentName, setComponentName] = useState('');
const [componentType, setComponentType] = useState('CONTAINER');
const [componentImageSource, setComponentImageSource] = useState('SOURCE');
const [componentExternalImage, setComponentExternalImage] = useState('');
const [componentWorkloadType, setComponentWorkloadType] = useState('Deployment');
const [componentReplicas, setComponentReplicas] = useState('1');
const [componentServiceType, setComponentServiceType] = useState('ClusterIP');
const [componentStorageEnabled, setComponentStorageEnabled] = useState(false);
const [componentStorageSize, setComponentStorageSize] = useState('');
const [componentStorageMountPath, setComponentStorageMountPath] = useState('');
const [componentStorageRetain, setComponentStorageRetain] = useState(true);
const [componentRepo, setComponentRepo] = useState('');
const [componentBranch, setComponentBranch] = useState('develop');
const [componentPort, setComponentPort] = useState('');
const [componentTargetPort, setComponentTargetPort] = useState('');
const [componentPorts, setComponentPorts] = useState<ComponentPortForm[]>([emptyComponentPort()]);
const [componentSaveStatus, setComponentSaveStatus] = useState<'idle' | 'saving' | 'error'>('idle');
const [editingComponent, setEditingComponent] = useState<ApiAppComponent | null>(null);
const [buildEnvComponent, setBuildEnvComponent] = useState<ApiAppComponent | null>(null);
const [buildEnvVariables, setBuildEnvVariables] = useState<BuildEnvVariableForm[]>([emptyBuildEnvVariable()]);
const [buildEnvStatus, setBuildEnvStatus] = useState<'idle' | 'loading' | 'saving' | 'error'>('idle');
const [deletingApp, setDeletingApp] = useState<ApiApp | null>(null);
const [appDeleteStatus, setAppDeleteStatus] = useState<'idle' | 'deleting' | 'error'>('idle');
const [appDeleteOptions, setAppDeleteOptions] = useState({
unlinkSources: true,
deleteRuntimeSettings: true,
scaleDownWorkloads: true,
deleteKubernetesResources: false,
deletePersistentVolumes: false
});
const [isAppAdminsOpen, setIsAppAdminsOpen] = useState(false);
const [appAdmins, setAppAdmins] = useState<AdminAccount[]>([]);
const [appAdminPermissions, setAppAdminPermissions] = useState<Record<string, string[]>>({});
const [appAdminsLoading, setAppAdminsLoading] = useState(false);
const [appAdminSavingId, setAppAdminSavingId] = useState('');
const [appAdminSearch, setAppAdminSearch] = useState('');
const [appAdminConfirm, setAppAdminConfirm] = useState<{ admin: AdminAccount; allowed: boolean } | null>(null);
const [deletingComponent, setDeletingComponent] = useState<ApiAppComponent | null>(null);
const [runtimeResources, setRuntimeResources] = useState<RuntimeResource[]>([]);
const [workloadActionKey, setWorkloadActionKey] = useState('');
const [deletingWorkload, setDeletingWorkload] = useState<RuntimeResource | null>(null);
const [deleteServiceWithWorkload, setDeleteServiceWithWorkload] = useState(false);
const [deletingVolumeWorkload, setDeletingVolumeWorkload] = useState<RuntimeResource | null>(null);
const [volumeClaims, setVolumeClaims] = useState<RuntimePersistentVolumeClaim[]>([]);
const [selectedVolumeClaimName, setSelectedVolumeClaimName] = useState('');
const [volumeDeleteConfirmText, setVolumeDeleteConfirmText] = useState('');
const [volumeDeleteBackupChecked, setVolumeDeleteBackupChecked] = useState(false);
const [volumeDeleteStatus, setVolumeDeleteStatus] = useState<'idle' | 'loading' | 'deleting' | 'error'>('idle');
const selectedApp = apiApps.find((app) => app.id === selectedAppId) ?? apiApps[0];
const totalComponents = selectedApp?.components?.length ?? 0;
const linkedComponents = selectedApp?.components?.filter((component) => component.repository).length ?? 0;
const workloads = runtimeResources.filter(isWorkloadResource);
const selectedVolumeClaim = volumeClaims.find((claim) => claim.name === selectedVolumeClaimName);
const volumeDeleteConfirmPhrase = selectedVolumeClaimName ? `${selectedVolumeClaimName} 삭제` : '';
const selectedAppAuthorizedAdmins = selectedApp
? appAdmins.filter((admin) => isOwnerAdmin(admin) || (appAdminPermissions[admin.id] ?? admin.appPermissions ?? []).includes(selectedApp.id))
: [];
const appAdminAddOptions = selectedApp
? appAdmins.filter((admin) => (
admin.isActive
&& !isOwnerAdmin(admin)
&& !(appAdminPermissions[admin.id] ?? admin.appPermissions ?? []).includes(selectedApp.id)
))
: [];
const appAdminSearchKeyword = appAdminSearch.trim().toLowerCase();
const appAdminSearchResults = appAdminSearchKeyword.length >= 2
? appAdminAddOptions.filter((admin) => `${admin.name} ${admin.email} ${admin.role}`.toLowerCase().includes(appAdminSearchKeyword)).slice(0, 8)
: [];
const canDeleteVolume = Boolean(
deletingVolumeWorkload &&
selectedVolumeClaimName &&
volumeDeleteBackupChecked &&
volumeDeleteConfirmText.trim() === volumeDeleteConfirmPhrase &&
volumeDeleteStatus !== 'loading' &&
volumeDeleteStatus !== 'deleting'
);
useEffect(() => {
setIsAppsLoading(true);
loadApps()
.then((apps) => {
setApiApps(apps);
setSelectedAppId((current) => {
const storedAppId = getStoredSelectedAppId();
const preferredAppId = storedAppId || current;
const nextAppId = apps.some((app) => app.id === preferredAppId) ? preferredAppId : apps[0]?.id || '';
if (nextAppId) setStoredSelectedAppId(nextAppId);
return nextAppId;
});
setIsAppsLoading(false);
})
.catch(() => {
setApiApps([]);
setIsAppsLoading(false);
});
}, []);
const selectApp = (appId: string) => {
setSelectedAppId(appId);
setStoredSelectedAppId(appId);
};
useEffect(() => {
if (!selectedApp?.namespace) {
setRuntimeResources([]);
return;
}
let mounted = true;
loadRuntimeResources(selectedApp.namespace)
.then((result) => {
if (mounted) setRuntimeResources(result.resources ?? []);
})
.catch(() => {
if (mounted) setRuntimeResources([]);
});
return () => {
mounted = false;
};
}, [selectedApp?.namespace]);
const refreshRuntimeResources = () => {
if (!selectedApp?.namespace) {
setRuntimeResources([]);
return Promise.resolve();
}
return loadRuntimeResources(selectedApp.namespace)
.then((result) => setRuntimeResources(result.resources ?? []))
.catch(() => setRuntimeResources([]));
};
const runWorkloadAction = (resource: RuntimeResource, action: 'restart' | 'start' | 'stop') => {
if (!selectedApp?.namespace) return;
const actionKey = `${action}-${resource.kind}-${resource.name}`;
setWorkloadActionKey(actionKey);
controlRuntimeWorkload(selectedApp.namespace, resource.kind, resource.name, action)
.then(() => {
toast({
type: 'success',
title: action === 'restart' ? '워크로드 재시작' : action === 'start' ? '워크로드 시작' : '워크로드 중지',
message: `${resource.name} 작업을 요청했습니다.`
});
return refreshRuntimeResources();
})
.catch((error: Error) => {
toast({ type: 'error', title: '워크로드 제어 실패', message: error.message });
})
.finally(() => setWorkloadActionKey(''));
};
const requestDeleteWorkload = (resource: RuntimeResource) => {
setDeletingWorkload(resource);
setDeleteServiceWithWorkload(false);
};
const confirmDeleteWorkload = () => {
if (!selectedApp?.namespace || !deletingWorkload) return;
const actionKey = `delete-${deletingWorkload.kind}-${deletingWorkload.name}`;
setWorkloadActionKey(actionKey);
deleteRuntimeWorkload(selectedApp.namespace, deletingWorkload.kind, deletingWorkload.name, deleteServiceWithWorkload)
.then(() => {
toast({
type: 'success',
title: '워크로드 삭제',
message: `${deletingWorkload.name} 삭제를 요청했습니다.`
});
setDeletingWorkload(null);
return refreshRuntimeResources();
})
.catch((error: Error) => {
toast({ type: 'error', title: '워크로드 삭제 실패', message: error.message });
})
.finally(() => setWorkloadActionKey(''));
};
const requestDeleteVolume = (resource: RuntimeResource) => {
if (!selectedApp?.namespace) return;
if (resource.kind !== 'StatefulSet') {
toast({ type: 'error', title: '데이터 볼륨 삭제 불가', message: 'StatefulSet 워크로드만 데이터 볼륨을 삭제할 수 있습니다.' });
return;
}
if (!isStoppedResource(resource)) {
toast({ type: 'warning', title: '워크로드 중지 필요', message: '데이터 볼륨 삭제 전 DB 워크로드를 먼저 중지하세요.' });
return;
}
setDeletingVolumeWorkload(resource);
setVolumeClaims([]);
setSelectedVolumeClaimName('');
setVolumeDeleteConfirmText('');
setVolumeDeleteBackupChecked(false);
setVolumeDeleteStatus('loading');
loadWorkloadPersistentVolumeClaims(selectedApp.namespace, resource.kind, resource.name)
.then((result) => {
const claims = result.claims ?? [];
setVolumeClaims(claims);
setSelectedVolumeClaimName(claims[0]?.name ?? '');
setVolumeDeleteStatus('idle');
})
.catch((error: Error) => {
setVolumeDeleteStatus('error');
toast({ type: 'error', title: '데이터 볼륨 조회 실패', message: error.message });
});
};
const closeVolumeDeleteModal = () => {
setDeletingVolumeWorkload(null);
setVolumeClaims([]);
setSelectedVolumeClaimName('');
setVolumeDeleteConfirmText('');
setVolumeDeleteBackupChecked(false);
setVolumeDeleteStatus('idle');
};
const confirmDeleteVolume = () => {
if (!selectedApp?.namespace || !deletingVolumeWorkload || !selectedVolumeClaimName) return;
setVolumeDeleteStatus('deleting');
deleteWorkloadPersistentVolumeClaim(
selectedApp.namespace,
deletingVolumeWorkload.kind,
deletingVolumeWorkload.name,
selectedVolumeClaimName
)
.then(() => {
toast({
type: 'success',
title: '데이터 볼륨 삭제',
message: `${selectedVolumeClaimName} 삭제를 요청했습니다.`
});
closeVolumeDeleteModal();
return refreshRuntimeResources();
})
.catch((error: Error) => {
setVolumeDeleteStatus('error');
toast({ type: 'error', title: '데이터 볼륨 삭제 실패', message: error.message });
});
};
const changeNewAppName = (name: string) => {
const appKey = appKeyFromName(name);
setNewAppName(name);
setNewAppKey(appKey);
setNewAppNamespace(appKey ? `stdo-${appKey}` : '');
};
const createApp = () => {
if (!newAppKey.trim() || !newAppName.trim()) return;
const namespace = newAppNamespace.trim();
setAppCreateStatus('saving');
apiFetch(`${apiBaseUrl}/apps`, {
method: 'POST',
headers: authHeaders({ 'Content-Type': 'application/json' }),
body: JSON.stringify({
key: newAppKey,
name: newAppName,
namespace: namespace || undefined,
description: newAppDescription || undefined
})
})
.then((response) => {
if (!response.ok) throw new Error('App create failed');
return response.json();
})
.then((result) => {
if (!namespace) return result;
return apiFetch(`${apiBaseUrl}/apps/runtime-namespaces`, {
method: 'POST',
headers: authHeaders({ 'Content-Type': 'application/json' }),
body: JSON.stringify({ namespace })
})
.then(async (response) => {
if (!response.ok) {
const body = await response.json().catch(() => null);
const message = Array.isArray(body?.message) ? body.message.join(', ') : body?.message;
throw new Error(message || '네임스페이스 create failed');
}
return response.json();
})
.then((namespaceResult) => {
toast({
type: 'success',
title: '네임스페이스 생성/확인',
message: namespaceResult.created ? `${namespaceResult.namespace} 네임스페이스를 생성했습니다.` : `${namespaceResult.namespace} 네임스페이스가 이미 있습니다.`
});
return result;
})
.catch((namespaceError: Error) => {
toast({
type: 'warning',
title: '앱 등록 완료 / 네임스페이스 생성 실패',
message: namespaceError.message
});
return result;
});
})
.then((result) => {
if (result?.app?.id) grantAppPermissionToCurrentAdmin(result.app.id);
return loadApps();
})
.then((apps) => {
setApiApps(apps);
setNewAppKey('');
setNewAppName('');
setNewAppNamespace('');
setNewAppDescription('');
setAppCreateStatus('idle');
setIsCreateAppOpen(false);
toast({ type: 'success', title: '앱 등록', message: '앱 그룹이 등록되었습니다.' });
})
.catch(() => {
setAppCreateStatus('error');
toast({ type: 'error', title: '앱 등록 실패', message: '중복 Key 또는 백엔드 상태를 확인하세요.' });
});
};
const getBuildTargetForType = (type: string) => {
if (componentImageSource === 'EXTERNAL') return '외부 이미지';
if (componentImageSource === 'DATABASE') return 'DB 이미지';
const targets: Record<string, string> = {
ELECTRON: 'AppImage',
CONTAINER: 'container-image',
STATIC_WEB: 'web-image',
DATABASE: 'database',
MIGRATION: 'prisma/migrations'
};
return targets[type] ?? 'container-image';
};
const isSourceBuildComponent = componentImageSource === 'SOURCE';
const isStorageWorkload = componentWorkloadType === 'StatefulSet' || componentType === 'DATABASE';
const componentPayload = () => {
const normalizedPorts = componentPorts
.map((item) => ({
name: item.name.trim() || undefined,
port: item.port ? Number(item.port) : undefined,
targetPort: item.targetPort ? Number(item.targetPort) : item.port ? Number(item.port) : undefined,
nodePort: componentServiceType === 'NodePort' && item.nodePort ? Number(item.nodePort) : undefined,
protocol: item.protocol || 'TCP'
}))
.filter((item) => item.port);
const primaryPort = normalizedPorts[0];
return {
name: componentName.trim(),
type: componentType,
imageSource: componentImageSource,
externalImage: componentImageSource !== 'SOURCE' ? componentExternalImage.trim() || undefined : undefined,
workloadType: componentWorkloadType,
replicas: componentReplicas ? Number(componentReplicas) : undefined,
serviceType: componentServiceType,
storageEnabled: componentStorageEnabled,
storageSize: componentStorageEnabled ? componentStorageSize.trim() || undefined : undefined,
storageMountPath: componentStorageEnabled ? componentStorageMountPath.trim() || undefined : undefined,
storageRetain: componentStorageRetain,
repository: isSourceBuildComponent ? componentRepo || undefined : undefined,
branch: isSourceBuildComponent ? componentBranch || undefined : undefined,
buildTarget: getBuildTargetForType(componentType),
port: primaryPort?.port ?? (componentPort ? Number(componentPort) : undefined),
targetPort: primaryPort?.targetPort ?? (componentTargetPort ? Number(componentTargetPort) : componentPort ? Number(componentPort) : undefined),
ports: normalizedPorts.length ? normalizedPorts : undefined
};
};
const createComponent = () => {
if (!selectedApp?.id || !componentName.trim()) return;
setComponentSaveStatus('saving');
apiFetch(`${apiBaseUrl}/apps/${selectedApp.id}/components`, {
method: 'POST',
headers: authHeaders({ 'Content-Type': 'application/json' }),
body: JSON.stringify(componentPayload())
})
.then((response) => {
if (!response.ok) throw new Error('Component create failed');
return response.json();
})
.then(() => loadApps())
.then((apps) => {
setApiApps(apps);
setComponentName('');
setComponentType('CONTAINER');
setComponentImageSource('SOURCE');
setComponentExternalImage('');
setComponentWorkloadType('Deployment');
setComponentReplicas('1');
setComponentServiceType('ClusterIP');
setComponentStorageEnabled(false);
setComponentStorageSize('');
setComponentStorageMountPath('');
setComponentStorageRetain(true);
setComponentRepo('');
setComponentBranch('develop');
setComponentPort('');
setComponentTargetPort('');
setComponentPorts([emptyComponentPort()]);
setComponentSaveStatus('idle');
setIsComponentOpen(false);
toast({ type: 'success', title: '구성요소 추가', message: '앱 구성요소가 추가되었습니다.' });
})
.catch(() => {
setComponentSaveStatus('error');
toast({ type: 'error', title: '구성요소 추가 실패', message: '입력값 또는 백엔드 상태를 확인하세요.' });
});
};
const openEditComponent = (component: ApiAppComponent) => {
setEditingComponent(component);
setComponentName(component.name);
setComponentType(component.type);
setComponentImageSource(component.imageSource ?? (component.type === 'DATABASE' ? 'DATABASE' : 'SOURCE'));
setComponentExternalImage(component.externalImage ?? '');
setComponentWorkloadType(component.workloadType ?? (component.type === 'DATABASE' ? 'StatefulSet' : 'Deployment'));
setComponentReplicas(component.replicas ? String(component.replicas) : '1');
setComponentServiceType(component.serviceType ?? 'ClusterIP');
setComponentStorageEnabled(Boolean(component.storageEnabled));
setComponentStorageSize(component.storageSize ?? '');
setComponentStorageMountPath(component.storageMountPath ?? '');
setComponentStorageRetain(component.storageRetain ?? true);
setComponentRepo(component.repository ?? '');
setComponentBranch(component.branch ?? 'develop');
setComponentPort(component.port ? String(component.port) : '');
setComponentTargetPort(component.targetPort ? String(component.targetPort) : '');
setComponentPorts(componentPortForms(component));
setComponentSaveStatus('idle');
setIsComponentOpen(true);
};
const closeComponentModal = () => {
setIsComponentOpen(false);
setEditingComponent(null);
setComponentName('');
setComponentType('CONTAINER');
setComponentImageSource('SOURCE');
setComponentExternalImage('');
setComponentWorkloadType('Deployment');
setComponentReplicas('1');
setComponentServiceType('ClusterIP');
setComponentStorageEnabled(false);
setComponentStorageSize('');
setComponentStorageMountPath('');
setComponentStorageRetain(true);
setComponentRepo('');
setComponentBranch('develop');
setComponentPort('');
setComponentTargetPort('');
setComponentPorts([emptyComponentPort()]);
setComponentSaveStatus('idle');
};
const updateComponent = () => {
if (!editingComponent || !componentName.trim()) return;
setComponentSaveStatus('saving');
apiFetch(`${apiBaseUrl}/apps/components/${editingComponent.id}`, {
method: 'PATCH',
headers: authHeaders({ 'Content-Type': 'application/json' }),
body: JSON.stringify(componentPayload())
})
.then((response) => {
if (!response.ok) throw new Error('Component update failed');
return response.json();
})
.then(() => loadApps())
.then((apps) => {
setApiApps(apps);
closeComponentModal();
toast({ type: 'success', title: '구성요소 수정', message: '앱 구성요소가 수정되었습니다.' });
})
.catch(() => {
setComponentSaveStatus('error');
toast({ type: 'error', title: '구성요소 수정 실패', message: '입력값 또는 백엔드 API 상태를 확인하세요.' });
});
};
const openBuildEnvModal = (component: ApiAppComponent) => {
setBuildEnvComponent(component);
setBuildEnvStatus('loading');
const fallbackVariables = component.buildVariables?.length
? component.buildVariables.map((variable) => ({
id: variable.id,
key: variable.key,
value: variable.value,
isSecret: variable.isSecret
}))
: [emptyBuildEnvVariable()];
setBuildEnvVariables(fallbackVariables);
loadComponentBuildEnv(component.id)
.then(({ variables }) => {
setBuildEnvVariables(variables.length
? variables.map((variable) => ({
id: variable.id,
key: variable.key,
value: variable.value,
isSecret: variable.isSecret
}))
: [emptyBuildEnvVariable()]);
setBuildEnvStatus('idle');
})
.catch((error: Error) => {
setBuildEnvStatus('error');
toast({ type: 'error', title: '빌드 환경변수 조회 실패', message: error.message });
});
};
const closeBuildEnvModal = () => {
setBuildEnvComponent(null);
setBuildEnvVariables([emptyBuildEnvVariable()]);
setBuildEnvStatus('idle');
};
const saveBuildEnv = () => {
if (!buildEnvComponent) return;
setBuildEnvStatus('saving');
saveComponentBuildEnv(buildEnvComponent.id, buildEnvVariables)
.then(({ variables }) => {
setApiApps((current) => current.map((app) => ({
...app,
components: app.components?.map((component) => component.id === buildEnvComponent.id
? { ...component, buildVariables: variables }
: component)
})));
toast({ type: 'success', title: '빌드 환경변수 저장', message: '구성요소 빌드 환경변수를 저장했습니다.' });
closeBuildEnvModal();
})
.catch((error: Error) => {
setBuildEnvStatus('error');
toast({ type: 'error', title: '빌드 환경변수 저장 실패', message: error.message });
});
};
const deleteComponent = () => {
if (!deletingComponent) return;
apiFetch(`${apiBaseUrl}/apps/components/${deletingComponent.id}`, { method: 'DELETE', headers: authHeaders() })
.then((response) => {
if (!response.ok) throw new Error('Component delete failed');
return response.json().catch(() => null);
})
.then(() => loadApps())
.then((apps) => {
setApiApps(apps);
setDeletingComponent(null);
toast({ type: 'success', title: '구성요소 삭제', message: '앱 구성요소가 삭제되었습니다.' });
})
.catch(() => {
toast({ type: 'error', title: '구성요소 삭제 실패', message: '참조 이력 또는 백엔드 API 상태를 확인하세요.' });
});
};
const deleteApp = () => {
if (!deletingApp) return;
setAppDeleteStatus('deleting');
apiFetch(`${apiBaseUrl}/apps/${deletingApp.id}/decommission`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...authHeaders()
},
body: JSON.stringify(appDeleteOptions)
})
.then((response) => {
if (!response.ok) throw new Error('App delete failed');
return response.json().catch(() => null);
})
.then(() => loadApps())
.then((apps) => {
setApiApps(apps);
setDeletingApp(null);
setAppDeleteStatus('idle');
setSelectedAppId((current) => {
if (current !== deletingApp.id) return current;
const nextAppId = apps[0]?.id ?? '';
setStoredSelectedAppId(nextAppId);
return nextAppId;
});
toast({ type: 'success', title: '앱 삭제', message: '앱 그룹이 삭제되었습니다.' });
})
.catch(() => {
setAppDeleteStatus('error');
toast({ type: 'error', title: '앱 삭제 실패', message: '참조 이력 또는 백엔드 API 상태를 확인하세요.' });
});
};
const updateAppDeleteOption = (key: keyof typeof appDeleteOptions, value: boolean) => {
setAppDeleteOptions((current) => ({
...current,
[key]: value,
...(key === 'deleteKubernetesResources' && !value ? { deletePersistentVolumes: false } : {})
}));
};
const openAppAdmins = () => {
if (!selectedApp) return;
setIsAppAdminsOpen(true);
setAppAdminsLoading(true);
setAppAdminSearch('');
loadAdmins()
.then((admins) => {
setAppAdmins(admins);
setAppAdminPermissions(Object.fromEntries(admins.map((admin) => [admin.id, admin.appPermissions ?? []])));
})
.catch((error: Error) => {
setAppAdmins([]);
setAppAdminPermissions({});
toast({ type: 'error', title: '관리자 조회 실패', message: error.message });
})
.finally(() => setAppAdminsLoading(false));
};
const requestAppAdminAccess = (admin: AdminAccount, allowed: boolean) => {
if (isOwnerAdmin(admin) || appAdminSavingId) return;
setAppAdminConfirm({ admin, allowed });
};
const setAppAdminAccess = (admin: AdminAccount, allowed: boolean) => {
if (!selectedApp || isOwnerAdmin(admin) || appAdminSavingId) return;
const currentAppIds = appAdminPermissions[admin.id] ?? admin.appPermissions ?? [];
const nextAppIds = allowed
? [...new Set([...currentAppIds, selectedApp.id])]
: currentAppIds.filter((appId) => appId !== selectedApp.id);
setAppAdminSavingId(admin.id);
updateAdminAppPermissions(admin.id, nextAppIds)
.then((result) => {
const savedAppIds = result.appIds ?? nextAppIds;
setAppAdminPermissions((current) => ({ ...current, [admin.id]: savedAppIds }));
setAppAdmins((current) => current.map((item) => item.id === admin.id ? { ...item, appPermissions: savedAppIds } : item));
setAdminAppPermissions(admin, savedAppIds);
setAppAdminSearch('');
setAppAdminConfirm(null);
toast({
type: 'success',
title: allowed ? '관리자 추가' : '관리자 해제',
message: `${admin.name} 관리자 권한이 저장되었습니다.`
});
})
.catch((error: Error) => {
toast({ type: 'error', title: '앱 관리자 저장 실패', message: error.message });
})
.finally(() => setAppAdminSavingId(''));
};
return (
<>
<PageTitle
eyebrow="어플리케이션"
title="앱 관리"
description="런처에 등록할 앱을 제품 단위로 관리하고, 앱을 구성하는 실행 요소와 운영 리소스를 하나의 묶음으로 운영합니다."
actions={
<div className="flex items-center gap-2">
<Button variant="outline" className="h-8 px-3 text-[13px]" disabled={!selectedApp} onClick={openAppAdmins}>
<UserCog className="size-4" />관리자
</Button>
<Button className="h-8 px-3 text-[13px]" onClick={() => setIsCreateAppOpen(true)}>
<Plus className="size-4" />앱 등록
</Button>
</div>
}
/>
<div className="space-y-4">
<Card className="min-w-0 overflow-hidden">
<CardHeader title="등록된 앱 그룹" description="앱 그룹을 먼저 등록한 뒤 구성요소와 저장소를 연결합니다." />
<div className="max-h-[320px] overflow-x-auto overflow-y-auto">
<table className="w-full min-w-[760px] text-left text-sm">
<thead className="sticky top-0 z-10 border-b border-border bg-card text-xs text-muted-foreground">
<tr>
<th className="px-5 py-3 font-medium">Key</th>
<th className="px-5 py-3 font-medium">앱 이름</th>
<th className="px-5 py-3 font-medium">네임스페이스</th>
<th className="px-5 py-3 font-medium">구성요소</th>
<th className="px-5 py-3 font-medium">상태</th>
<th className="w-20 px-5 py-3 text-right font-medium">관리</th>
</tr>
</thead>
<tbody className="divide-y divide-border">
{!isAppsLoading && apiApps.length === 0 ? (
<tr>
<td colSpan={6} className="px-5 py-6 text-center text-muted-foreground">등록된 앱 그룹이 없습니다.</td>
</tr>
) : (
apiApps.map((app) => (
<tr
key={app.id}
className={cn(
'cursor-pointer transition-colors hover:bg-muted/20',
selectedApp?.id === app.id && 'bg-primary/20 shadow-[inset_4px_0_0_var(--color-primary)] hover:bg-primary/25'
)}
onClick={() => selectApp(app.id)}
>
<td className="px-5 py-3 font-semibold">{app.key}</td>
<td className="px-5 py-3">{app.name}</td>
<td className="px-5 py-3 text-muted-foreground">{app.namespace || '-'}</td>
<td className="px-5 py-3">{app.components?.length ?? 0}</td>
<td className="px-5 py-3">
<Badge tone={getTone(formatStatus(app.status, app.launcherLinked))}>{formatStatus(app.status, app.launcherLinked)}</Badge>
</td>
<td className="px-5 py-3">
<div className="flex justify-end">
<Button
variant="outline"
className="size-8 border-rose-500/50 px-0 text-rose-300 hover:border-rose-400 hover:bg-rose-500/10 hover:text-rose-200"
title="삭제"
aria-label="삭제"
onClick={(event) => {
if (blockPageAgentDestructiveClick(event)) return;
event.stopPropagation();
setAppDeleteStatus('idle');
setAppDeleteOptions({
unlinkSources: true,
deleteRuntimeSettings: true,
scaleDownWorkloads: true,
deleteKubernetesResources: false,
deletePersistentVolumes: false
});
setDeletingApp(app);
}}
>
<Trash2 className="size-4" />
</Button>
</div>
</td>
</tr>
))
)}
</tbody>
</table>
</div>
</Card>
{selectedApp ? (
<div className="min-w-0 space-y-4">
<Card className="min-w-0 overflow-hidden">
<CardHeader
title={`${selectedApp.name} 구성 요약`}
description="앱 실행과 운영에 필요한 구성요소와 배포 리소스 요약입니다."
/>
<div className="grid gap-4 p-5 md:grid-cols-4">
{[
['네임스페이스', selectedApp.namespace],
['연결 소스', `${linkedComponents}개`],
['구성요소', `${totalComponents}개`],
['상태', formatStatus(selectedApp.status, selectedApp.launcherLinked)]
].map(([label, value]) => (
<div key={label} className="rounded-md border border-border bg-muted/20 p-4">
<p className="text-xs text-muted-foreground">{label}</p>
<p className="mt-2 truncate text-sm font-semibold">{value}</p>
</div>
))}
</div>
<div className="px-5 pb-5">
<div className="grid gap-4 text-sm md:grid-cols-2">
<div className="rounded-md border border-border bg-muted/20 p-4">
<p className="text-xs text-muted-foreground">Key</p>
<p className="mt-2 truncate font-semibold">{selectedApp.key}</p>
</div>
<div className="rounded-md border border-border bg-muted/20 p-4">
<p className="text-xs text-muted-foreground">설명</p>
<p className="mt-2 truncate font-semibold text-muted-foreground">{selectedApp.description || '-'}</p>
</div>
</div>
</div>
</Card>
<Card>
<CardHeader
title="앱 구성요소"
description="앱을 구성하는 실행 요소와 관련 리소스를 관리합니다."
action={
<Button className="h-8 px-3 text-[13px]" disabled={!selectedApp} onClick={() => setIsComponentOpen(true)}>
<Plus className="size-4" />
추가
</Button>
}
/>
<div className="max-h-[430px] overflow-x-auto overflow-y-auto">
<table className="w-full min-w-[980px] text-left text-sm">
<thead className="border-b border-border text-xs text-muted-foreground">
<tr>
<th className="px-5 py-3 font-medium">구성요소</th>
<th className="px-5 py-3 font-medium">역할</th>
<th className="px-5 py-3 font-medium">유형</th>
<th className="px-5 py-3 font-medium">워크로드</th>
<th className="px-5 py-3 font-medium">포트</th>
<th className="px-5 py-3 font-medium">소스</th>
<th className="w-24 px-5 py-3 text-right font-medium">관리</th>
</tr>
</thead>
<tbody className="divide-y divide-border">
{!isAppsLoading && (selectedApp.components ?? []).map((component) => {
const running = isComponentRunning(component, runtimeResources);
const imageSourceLabel = component.imageSource === 'EXTERNAL' ? '외부 이미지' : component.imageSource === 'DATABASE' ? 'DB 이미지' : '소스 빌드';
return (
<tr key={component.name} className="hover:bg-muted/20">
<td className="px-5 py-3 font-medium">
<span className="inline-flex items-center gap-2">
<span className={cn('size-2.5 shrink-0 rounded-full', running ? statusDotToneClass('green') : component.repository ? statusDotToneClass('blue') : statusDotToneClass('neutral'))} />
{component.name}
</span>
</td>
<td className="px-5 py-3 text-muted-foreground">{imageSourceLabel}</td>
<td className="px-5 py-3">{component.type}</td>
<td className="px-5 py-3 text-muted-foreground">
{component.workloadType ?? '-'}
</td>
<td className="max-w-[220px] px-5 py-3 text-muted-foreground">
<span className="block truncate">{formatComponentPorts(component)}</span>
</td>
<td className="px-5 py-3 text-muted-foreground">{component.repository || (component.imageSource === 'EXTERNAL' ? '외부 이미지' : '미연결')}</td>
<td className="px-5 py-3">
<div className="grid grid-cols-[2rem_2rem_2rem] justify-end gap-2">
<Button variant="outline" className="size-8 px-0" title="수정" aria-label="수정" onClick={() => openEditComponent(component)}>
<Pencil className="size-4" />
</Button>
<Button variant="outline" className="size-8 px-0" title="빌드 환경변수" aria-label="빌드 환경변수" onClick={() => openBuildEnvModal(component)}>
<Settings2 className="size-4" />
</Button>
{!running ? (
<Button
variant="outline"
className="size-8 border-rose-500/50 px-0 text-rose-300 hover:border-rose-400 hover:bg-rose-500/10 hover:text-rose-200"
title="삭제"
aria-label="삭제"
onClick={(event) => {
if (blockPageAgentDestructiveClick(event)) return;
setDeletingComponent(component);
}}
>
<Trash2 className="size-4" />
</Button>
) : <span aria-hidden="true" />}
</div>
</td>
</tr>
);
})}
{!isAppsLoading && (selectedApp.components ?? []).length === 0 ? (
<tr>
<td colSpan={7} className="px-5 py-6 text-center text-muted-foreground">등록된 구성요소가 없습니다.</td>
</tr>
) : null}
</tbody>
</table>
</div>
</Card>
<Card className="min-w-0 overflow-hidden">
<CardHeader
title="워크로드 제어"
description="현재 실행 중인 리소스 상태를 확인하고 필요한 작업을 실행합니다."
action={<span className="text-xs text-muted-foreground">총 {workloads.length}개</span>}
/>
<div className="max-h-[360px] overflow-x-auto overflow-y-auto">
<table className="w-full min-w-[980px] text-left text-sm">
<thead className="sticky top-0 z-10 border-b border-border bg-card text-xs text-muted-foreground">
<tr>
<th className="px-5 py-3 font-medium">이름</th>
<th className="px-5 py-3 font-medium">유형</th>
<th className="px-5 py-3 font-medium">준비 상태</th>
<th className="px-5 py-3 font-medium">이미지/상세</th>
<th className="w-52 px-5 py-3 text-right font-medium">작업</th>
</tr>
</thead>
<tbody className="divide-y divide-border">
{!isAppsLoading && workloads.length === 0 ? (
<tr>
<td colSpan={5} className="px-5 py-12 text-center text-muted-foreground">제어할 워크로드가 없습니다.</td>
</tr>
) : null}
{workloads.map((resource) => {
const stopped = isStoppedResource(resource);
const actionBase = `${resource.kind}-${resource.name}`;
const pending = workloadActionKey.endsWith(actionBase);
return (
<tr key={actionBase} className="hover:bg-muted/20">
<td className="px-5 py-3">
<span className="inline-flex items-center gap-2">
<span className={cn('block size-2.5 shrink-0 rounded-full', stopped ? statusDotToneClass('neutral') : runtimeStatusDotClass(resource.status))} />
<span className="text-sm text-foreground">{resource.name}</span>
</span>
</td>
<td className="px-5 py-3 text-foreground">{resource.kind}</td>
<td className="px-5 py-3">{resource.ready}</td>
<td className="max-w-[420px] px-5 py-3">
<span className="block truncate font-mono text-xs text-muted-foreground">{resource.detail || '-'}</span>
</td>
<td className="px-5 py-3">
<div className="flex justify-end gap-2">
<Button
variant="outline"
className="size-8 px-0"
title="재시작"
aria-label={`${resource.name} 재시작`}
disabled={pending || stopped}
onClick={() => runWorkloadAction(resource, 'restart')}
>
<RotateCcw className={workloadActionKey === `restart-${actionBase}` ? 'size-4 animate-spin' : 'size-4'} />
</Button>
<Button
variant={stopped ? 'default' : 'outline'}
className="size-8 px-0"
title={stopped ? '시작' : '중지'}
aria-label={`${resource.name} ${stopped ? '시작' : '중지'}`}
disabled={pending}
onClick={() => runWorkloadAction(resource, stopped ? 'start' : 'stop')}
>
{stopped ? <Play className="size-4" /> : <Square className="size-3.5" />}
</Button>
<Button
variant="outline"
className="size-8 border-rose-500/50 px-0 text-rose-300 hover:border-rose-400 hover:bg-rose-500/10 hover:text-rose-200"
title="삭제"
aria-label={`${resource.name} 삭제`}
disabled={pending}
onClick={(event) => {
if (blockPageAgentDestructiveClick(event)) return;
requestDeleteWorkload(resource);
}}
>
<Trash2 className="size-4" />
</Button>
{resource.kind === 'StatefulSet' ? (
<Button
variant="outline"
className="size-8 border-amber-500/50 px-0 text-amber-300 hover:border-amber-400 hover:bg-amber-500/10 hover:text-amber-200"
title={stopped ? '데이터 볼륨 삭제' : '중지 후 데이터 볼륨 삭제 가능'}
aria-label={`${resource.name} 데이터 볼륨 삭제`}
disabled={pending || !stopped}
onClick={(event) => {
if (blockPageAgentDestructiveClick(event)) return;
requestDeleteVolume(resource);
}}
>
<Database className="size-4" />
</Button>
) : null}
</div>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
</Card>
</div>
) : !isAppsLoading ? (
<Card className="px-5 py-8 text-center text-sm text-muted-foreground">
등록된 앱을 선택해주세요.
</Card>
) : null}
</div>
{isAppAdminsOpen ? (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-background/55 px-4 backdrop-blur-[2px]">
<div className="flex max-h-[86vh] w-full max-w-2xl flex-col rounded-lg border border-border bg-card shadow-xl">
<div className="border-b border-border px-5 py-3">
<h2 className="text-sm font-semibold">관리자</h2>
<p className="mt-1 text-xs text-muted-foreground">
{selectedApp?.name ?? '-'} · {selectedApp?.key ?? '-'} 앱에 접근할 수 있는 관리자입니다.
</p>
</div>
<div className="min-h-0 space-y-4 overflow-y-auto px-5 py-5">
<div className="rounded-md border border-border p-3">
<p className="text-xs font-medium text-muted-foreground">관리자 추가</p>
<input
className="mt-2 h-9 w-full rounded-md border border-input bg-background px-3 text-sm text-foreground outline-none placeholder:text-muted-foreground focus:ring-2 focus:ring-ring"
value={appAdminSearch}
onChange={(event) => setAppAdminSearch(event.target.value)}
placeholder="이름 또는 이메일 입력"
disabled={appAdminsLoading || appAdminAddOptions.length === 0 || Boolean(appAdminSavingId)}
/>
{appAdminSearchKeyword.length >= 2 ? (
<div className="mt-2 overflow-hidden rounded-md border border-border">
{appAdminSearchResults.length === 0 ? (
<div className="px-3 py-4 text-center text-sm text-muted-foreground">검색 결과가 없습니다.</div>
) : (
appAdminSearchResults.map((admin) => (
<div
key={admin.id}
className="flex w-full items-center justify-between gap-3 border-b border-border px-3 py-2 text-left last:border-b-0 hover:bg-muted/20"
>
<span className="flex min-w-0 items-center gap-3">
<AppAdminAvatar admin={admin} />
<span className="min-w-0">
<span className="block truncate text-sm font-semibold text-foreground">{admin.name}</span>
<span className="mt-0.5 block truncate text-xs text-muted-foreground">{admin.email}</span>
</span>
</span>
<div className="flex shrink-0 items-center gap-2">
<Badge tone="blue">{admin.role}</Badge>
<Button
variant="outline"
className="h-7 px-2 text-xs"
disabled={Boolean(appAdminSavingId)}
onClick={() => requestAppAdminAccess(admin, true)}
>
선택
</Button>
</div>
</div>
))
)}
</div>
) : null}
</div>
<div className="overflow-hidden rounded-md border border-border">
{appAdminsLoading ? (
<div className="px-4 py-10 text-center text-sm text-muted-foreground">관리자 목록을 불러오는 중입니다.</div>
) : selectedAppAuthorizedAdmins.length === 0 ? (
<div className="px-4 py-10 text-center text-sm text-muted-foreground">권한이 있는 관리자가 없습니다.</div>
) : (
selectedAppAuthorizedAdmins.map((admin) => {
const owner = isOwnerAdmin(admin);
const saving = appAdminSavingId === admin.id;
return (
<div key={admin.id} className="flex items-center justify-between gap-4 border-b border-border px-4 py-3 last:border-b-0 hover:bg-muted/20">
<div className="flex min-w-0 items-center gap-3">
<AppAdminAvatar admin={admin} />
<div className="min-w-0">
<div className="flex flex-wrap items-center gap-2">
<p className="truncate text-sm font-semibold text-foreground">{admin.name}</p>
<Badge tone={owner ? 'green' : 'blue'}>{owner ? '오너' : '관리자'}</Badge>
{!admin.isActive ? <Badge tone="red">비활성</Badge> : null}
</div>
<p className="mt-1 truncate text-xs text-muted-foreground">{admin.email}</p>
</div>
</div>
{owner ? (
<span className="shrink-0 text-xs text-muted-foreground">전체 앱 접근</span>
) : (
<Button
variant="outline"
className="h-8 shrink-0 border-rose-500/50 px-3 text-[13px] text-rose-300 hover:border-rose-400 hover:bg-rose-500/10 hover:text-rose-200"
disabled={saving || Boolean(appAdminSavingId)}
onClick={() => requestAppAdminAccess(admin, false)}
>
{saving ? '저장 중' : '해제'}
</Button>
)}
</div>
);
})
)}
</div>
</div>
<div className="flex justify-end gap-2 border-t border-border px-5 py-3">
<Button variant="outline" onClick={() => setIsAppAdminsOpen(false)} disabled={Boolean(appAdminSavingId)}>
닫기
</Button>
</div>
</div>
</div>
) : null}
<Modal
open={Boolean(appAdminConfirm)}
title={appAdminConfirm?.allowed ? '관리자 권한 추가' : '관리자 권한 해제'}
onClose={() => {
if (!appAdminSavingId) setAppAdminConfirm(null);
}}
footer={
<>
<Button variant="outline" disabled={Boolean(appAdminSavingId)} onClick={() => setAppAdminConfirm(null)}>취소</Button>
<Button
className={appAdminConfirm?.allowed ? undefined : 'border border-rose-500/40 bg-rose-500/15 text-rose-200 hover:bg-rose-500/25'}
disabled={!appAdminConfirm || Boolean(appAdminSavingId)}
onClick={() => appAdminConfirm && setAppAdminAccess(appAdminConfirm.admin, appAdminConfirm.allowed)}
>
{appAdminSavingId ? '저장 중' : appAdminConfirm?.allowed ? '추가' : '해제'}
</Button>
</>
}
>
<div className="space-y-4">
<div className="rounded-md border border-border bg-muted/20 px-4 py-3">
<p className="text-sm font-semibold text-foreground">{appAdminConfirm?.admin.name ?? '-'}</p>
<p className="mt-1 text-xs text-muted-foreground">{appAdminConfirm?.admin.email ?? '-'}</p>
</div>
<p className="text-sm leading-6 text-muted-foreground">
{appAdminConfirm?.allowed
? `${selectedApp?.name ?? '-'} 앱 접근 권한을 추가합니다.`
: `${selectedApp?.name ?? '-'} 앱 접근 권한을 해제합니다.`}
</p>
</div>
</Modal>
{isCreateAppOpen ? (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-background/55 px-4 backdrop-blur-[2px]">
<div className="w-full max-w-lg rounded-lg border border-border bg-card shadow-xl">
<div className="border-b border-border px-5 py-3">
<h2 className="text-sm font-semibold">앱 등록</h2>
</div>
<div className="space-y-4 px-5 py-5">
<label className="block">
<span className="text-xs font-medium text-muted-foreground">앱 이름 <b className="text-foreground">*</b></span>
<input value={newAppName} onChange={(event) => changeNewAppName(event.target.value)} className="mt-2 h-9 w-full rounded-md border border-border bg-background px-3 text-sm outline-none focus:border-primary" />
</label>
<label className="block">
<span className="text-xs font-medium text-muted-foreground">앱 Key</span>
<input value={newAppKey} readOnly className="mt-2 h-9 w-full rounded-md border border-border bg-muted/40 px-3 font-mono text-sm text-muted-foreground outline-none" />
</label>
<label className="block">
<span className="text-xs font-medium text-muted-foreground">네임스페이스</span>
<input value={newAppNamespace} readOnly className="mt-2 h-9 w-full rounded-md border border-border bg-muted/40 px-3 font-mono text-sm text-muted-foreground outline-none" />
</label>
<label className="block">
<span className="text-xs font-medium text-muted-foreground">설명</span>
<textarea value={newAppDescription} onChange={(event) => setNewAppDescription(event.target.value)} className="mt-2 min-h-20 w-full rounded-md border border-border bg-background px-3 py-2 text-sm outline-none focus:border-primary" />
</label>
{appCreateStatus === 'error' ? <p className="text-xs text-rose-300">앱 등록에 실패했습니다. 중복 Key 또는 백엔드 상태를 확인하세요.</p> : null}
</div>
<div className="flex justify-end gap-2 border-t border-border px-5 py-3">
<Button variant="ghost" onClick={() => setIsCreateAppOpen(false)}>취소</Button>
<Button onClick={createApp} disabled={!newAppKey.trim() || !newAppName.trim() || appCreateStatus === 'saving'}>{appCreateStatus === 'saving' ? '등록 중' : '등록'}</Button>
</div>
</div>
</div>
) : null}
{isComponentOpen ? (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-background/55 px-4 backdrop-blur-[2px]">
<div className="flex max-h-[88vh] w-full max-w-2xl flex-col rounded-lg border border-border bg-card shadow-xl">
<div className="border-b border-border px-5 py-3">
<h2 className="text-sm font-semibold">{editingComponent ? '앱 구성요소 수정' : '앱 구성요소 추가'}</h2>
</div>
<div className="min-h-0 space-y-4 overflow-y-auto px-5 py-5">
<label className="block">
<span className="text-xs font-medium text-muted-foreground">앱 그룹</span>
<input
value={selectedApp?.name ?? ''}
readOnly
className="mt-2 h-9 w-full rounded-md border border-border bg-muted/40 px-3 text-sm text-muted-foreground outline-none"
/>
</label>
<label className="block">
<span className="text-xs font-medium text-muted-foreground">구성요소명 <b className="text-foreground">*</b></span>
<input value={componentName} onChange={(event) => setComponentName(event.target.value)} className="mt-2 h-9 w-full rounded-md border border-border bg-background px-3 text-sm outline-none focus:border-primary" />
</label>
<label className="block">
<span className="text-xs font-medium text-muted-foreground">유형 <b className="text-foreground">*</b></span>
<select
value={componentType}
onChange={(event) => {
const nextType = event.target.value;
setComponentType(nextType);
if (nextType === 'DATABASE') {
setComponentImageSource('DATABASE');
setComponentWorkloadType('StatefulSet');
setComponentStorageEnabled(true);
setComponentStorageSize((prev) => prev || '10Gi');
setComponentStorageMountPath((prev) => prev || '/var/lib/postgresql/data');
} else if (nextType === 'MIGRATION') {
setComponentWorkloadType('Job');
}
}}
className="mt-2 h-9 w-full rounded-md border border-border bg-background px-3 text-sm outline-none focus:border-primary"
>
<option value="ELECTRON">ELECTRON</option>
<option value="CONTAINER">CONTAINER</option>
<option value="STATIC_WEB">STATIC_WEB</option>
<option value="DATABASE">DATABASE</option>
<option value="MIGRATION">MIGRATION</option>
</select>
</label>
<div className="grid gap-3 sm:grid-cols-2">
<label className="block">
<span className="text-xs font-medium text-muted-foreground">이미지 소스 <b className="text-foreground">*</b></span>
<select
value={componentImageSource}
onChange={(event) => {
const nextSource = event.target.value;
setComponentImageSource(nextSource);
if (nextSource === 'EXTERNAL') {
setComponentWorkloadType((prev) => prev === 'Job' ? 'Deployment' : prev);
}
if (nextSource === 'DATABASE') {
setComponentType('DATABASE');
setComponentWorkloadType('StatefulSet');
setComponentStorageEnabled(true);
setComponentStorageSize((prev) => prev || '10Gi');
}
}}
className="mt-2 h-9 w-full rounded-md border border-border bg-background px-3 text-sm outline-none focus:border-primary"
>
<option value="SOURCE">소스 빌드</option>
<option value="EXTERNAL">외부 이미지</option>
<option value="DATABASE">DB 이미지</option>
</select>
</label>
<label className="block">
<span className="text-xs font-medium text-muted-foreground">워크로드 <b className="text-foreground">*</b></span>
<select
value={componentWorkloadType}
onChange={(event) => {
const nextType = event.target.value;
setComponentWorkloadType(nextType);
if (nextType === 'StatefulSet') setComponentStorageEnabled(true);
}}
className="mt-2 h-9 w-full rounded-md border border-border bg-background px-3 text-sm outline-none focus:border-primary"
>
<option value="Deployment">Deployment</option>
<option value="StatefulSet">StatefulSet</option>
<option value="Job">Job</option>
</select>
</label>
</div>
{componentImageSource === 'SOURCE' ? (
<>
<label className="block">
<span className="text-xs font-medium text-muted-foreground">Repository</span>
<input
value={componentRepo}
onChange={(event) => setComponentRepo(event.target.value)}
className="mt-2 h-9 w-full rounded-md border border-border bg-background px-3 text-sm outline-none focus:border-primary"
/>
</label>
<label className="block">
<span className="text-xs font-medium text-muted-foreground">기본 브랜치</span>
<select
value={componentBranch}
onChange={(event) => setComponentBranch(event.target.value)}
className="mt-2 h-9 w-full rounded-md border border-border bg-background px-3 text-sm outline-none focus:border-primary"
>
<option value="develop">develop</option>
<option value="release">release</option>
<option value="main">main</option>
</select>
</label>
</>
) : (
<label className="block">
<span className="text-xs font-medium text-muted-foreground">이미지명 <b className="text-foreground">*</b></span>
<input
value={componentExternalImage}
onChange={(event) => setComponentExternalImage(event.target.value)}
className="mt-2 h-9 w-full rounded-md border border-border bg-background px-3 font-mono text-sm outline-none focus:border-primary"
placeholder={componentImageSource === 'DATABASE' ? 'postgres:17' : 'gitea/gitea:1.22.6'}
/>
</label>
)}
<label className="block">
<span className="text-xs font-medium text-muted-foreground">빌드 대상</span>
<input
value={getBuildTargetForType(componentType)}
readOnly
className="mt-2 h-9 w-full rounded-md border border-border bg-muted/40 px-3 text-sm text-muted-foreground outline-none"
/>
</label>
<div className="rounded-md border border-border bg-muted/10 p-4">
<div className="flex items-center justify-between gap-3">
<span className="text-xs font-medium text-muted-foreground">포트</span>
<Button
type="button"
variant="outline"
className="h-7 px-2 text-xs"
onClick={() => setComponentPorts((prev) => [...prev, emptyComponentPort()])}
>
<Plus className="size-3.5" />
추가
</Button>
</div>
<div className="mt-3 space-y-2">
{componentPorts.map((item, index) => (
<div
key={index}
className={cn(
'grid min-w-0 gap-2',
componentServiceType === 'NodePort'
? 'sm:grid-cols-[minmax(0,1fr)_minmax(0,0.8fr)_minmax(0,0.8fr)_minmax(0,0.8fr)_minmax(0,0.65fr)_2.5rem]'
: 'sm:grid-cols-[minmax(0,1fr)_minmax(0,0.85fr)_minmax(0,0.85fr)_minmax(0,0.7fr)_2.5rem]'
)}
>
<input
value={item.name}
onChange={(event) => setComponentPorts((prev) => prev.map((port, portIndex) => portIndex === index ? { ...port, name: event.target.value } : port))}
className="h-9 min-w-0 rounded-md border border-border bg-background px-3 text-sm outline-none focus:border-primary"
placeholder={index === 0 ? 'http' : 'ssh'}
/>
<input
type="number"
min="1"
value={item.port}
onChange={(event) => setComponentPorts((prev) => prev.map((port, portIndex) => portIndex === index ? { ...port, port: event.target.value, targetPort: port.targetPort || event.target.value } : port))}
className="h-9 min-w-0 rounded-md border border-border bg-background px-3 text-sm outline-none focus:border-primary"
placeholder="서비스 포트"
/>
<input
type="number"
min="1"
value={item.targetPort}
onChange={(event) => setComponentPorts((prev) => prev.map((port, portIndex) => portIndex === index ? { ...port, targetPort: event.target.value } : port))}
className="h-9 min-w-0 rounded-md border border-border bg-background px-3 text-sm outline-none focus:border-primary"
placeholder="컨테이너 포트"
/>
{componentServiceType === 'NodePort' ? (
<input
type="number"
min="30000"
max="32767"
value={item.nodePort}
onChange={(event) => setComponentPorts((prev) => prev.map((port, portIndex) => portIndex === index ? { ...port, nodePort: event.target.value } : port))}
className="h-9 min-w-0 rounded-md border border-border bg-background px-3 text-sm outline-none focus:border-primary"
placeholder="노드 포트"
/>
) : null}
<select
value={item.protocol}
onChange={(event) => setComponentPorts((prev) => prev.map((port, portIndex) => portIndex === index ? { ...port, protocol: event.target.value } : port))}
className="h-9 min-w-0 rounded-md border border-border bg-background px-2 text-sm outline-none focus:border-primary"
>
<option value="TCP">TCP</option>
<option value="UDP">UDP</option>
</select>
<Button
type="button"
variant="ghost"
className="size-9 justify-self-end px-0 text-rose-300"
disabled={componentPorts.length === 1}
onClick={(event) => {
if (blockPageAgentDestructiveClick(event)) return;
setComponentPorts((prev) => prev.filter((_, portIndex) => portIndex !== index));
}}
title="포트 삭제"
aria-label="포트 삭제"
>
<Trash2 className="size-4" />
</Button>
</div>
))}
</div>
</div>
<div className="grid gap-3 sm:grid-cols-2">
<label className="block">
<span className="text-xs font-medium text-muted-foreground">복제 수</span>
<input
type="number"
min="0"
value={componentReplicas}
onChange={(event) => setComponentReplicas(event.target.value)}
className="mt-2 h-9 w-full rounded-md border border-border bg-background px-3 text-sm outline-none focus:border-primary"
/>
</label>
<label className="block">
<span className="text-xs font-medium text-muted-foreground">서비스 타입</span>
<select
value={componentServiceType}
onChange={(event) => setComponentServiceType(event.target.value)}
className="mt-2 h-9 w-full rounded-md border border-border bg-background px-3 text-sm outline-none focus:border-primary"
>
<option value="ClusterIP">ClusterIP</option>
<option value="NodePort">NodePort</option>
<option value="LoadBalancer">LoadBalancer</option>
</select>
</label>
</div>
<div className="rounded-md border border-border bg-muted/10 p-4">
<label className="flex items-center gap-2 text-xs font-medium text-muted-foreground">
<input
type="checkbox"
className="size-4 accent-primary"
checked={componentStorageEnabled}
onChange={(event) => setComponentStorageEnabled(event.target.checked)}
/>
스토리지 사용
</label>
{componentStorageEnabled ? (
<div className="mt-4 grid gap-3 sm:grid-cols-2">
<label className="block">
<span className="text-xs font-medium text-muted-foreground">용량</span>
<input
value={componentStorageSize}
onChange={(event) => setComponentStorageSize(event.target.value)}
className="mt-2 h-9 w-full rounded-md border border-border bg-background px-3 text-sm outline-none focus:border-primary"
placeholder="10Gi"
/>
</label>
<label className="block">
<span className="text-xs font-medium text-muted-foreground">마운트 경로</span>
<input
value={componentStorageMountPath}
onChange={(event) => setComponentStorageMountPath(event.target.value)}
className="mt-2 h-9 w-full rounded-md border border-border bg-background px-3 font-mono text-sm outline-none focus:border-primary"
placeholder={isStorageWorkload ? '/data' : '/app/data'}
/>
</label>
<label className="flex items-center gap-2 text-xs font-medium text-muted-foreground sm:col-span-2">
<input
type="checkbox"
className="size-4 accent-primary"
checked={componentStorageRetain}
onChange={(event) => setComponentStorageRetain(event.target.checked)}
/>
워크로드 삭제 시 데이터 보존
</label>
</div>
) : null}
</div>
{componentSaveStatus === 'error' ? <p className="text-xs text-rose-300">구성요소 저장에 실패했습니다.</p> : null}
</div>
<div className="flex justify-end gap-2 border-t border-border px-5 py-3">
<Button variant="ghost" onClick={closeComponentModal}>취소</Button>
<Button
onClick={editingComponent ? updateComponent : createComponent}
disabled={!selectedApp || !componentName.trim() || (componentImageSource !== 'SOURCE' && !componentExternalImage.trim()) || componentSaveStatus === 'saving'}
>
{componentSaveStatus === 'saving' ? '저장 중' : '저장'}
</Button>
</div>
</div>
</div>
) : null}
{buildEnvComponent ? (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-background/55 px-4 backdrop-blur-[2px]">
<div className="flex max-h-[86vh] w-full max-w-3xl flex-col rounded-lg border border-border bg-card shadow-xl">
<div className="flex items-center gap-2 border-b border-border px-5 py-3">
<Settings2 className="size-4 text-primary" />
<div>
<h2 className="text-sm font-semibold">빌드 환경변수</h2>
<p className="mt-1 text-xs text-muted-foreground">{buildEnvComponent.name}</p>
</div>
</div>
<div className="min-h-0 flex-1 overflow-y-auto px-5 py-5">
{buildEnvStatus === 'loading' ? (
<div className="rounded-md border border-border bg-background/60 px-4 py-6 text-center text-sm text-muted-foreground">
환경변수를 불러오는 중입니다.
</div>
) : (
<div className="space-y-3">
<div className="grid gap-2 text-xs font-medium text-muted-foreground sm:grid-cols-[minmax(0,1fr)_minmax(0,1.5fr)_5.5rem_2.5rem]">
<span>키</span>
<span>값</span>
<span>비밀값</span>
<span />
</div>
{buildEnvVariables.map((variable, index) => (
<div key={variable.id ?? index} className="grid min-w-0 gap-2 sm:grid-cols-[minmax(0,1fr)_minmax(0,1.5fr)_5.5rem_2.5rem]">
<input
value={variable.key}
onChange={(event) => setBuildEnvVariables((prev) => prev.map((item, itemIndex) => itemIndex === index ? { ...item, key: event.target.value } : item))}
className="h-9 min-w-0 rounded-md border border-border bg-background px-3 font-mono text-sm outline-none focus:border-primary"
placeholder="VITE_API_BASE_URL"
/>
<input
value={variable.value}
onChange={(event) => setBuildEnvVariables((prev) => prev.map((item, itemIndex) => itemIndex === index ? { ...item, value: event.target.value } : item))}
className="h-9 min-w-0 rounded-md border border-border bg-background px-3 font-mono text-sm outline-none focus:border-primary"
placeholder="https://workspace-api.autonomystudio.net/api"
/>
<label className="flex h-9 items-center gap-2 rounded-md border border-border bg-background px-3 text-xs text-muted-foreground">
<input
type="checkbox"
className="size-4 accent-primary"
checked={variable.isSecret}
onChange={(event) => setBuildEnvVariables((prev) => prev.map((item, itemIndex) => itemIndex === index ? { ...item, isSecret: event.target.checked } : item))}
/>
사용
</label>
<Button
type="button"
variant="ghost"
className="size-9 justify-self-end px-0 text-rose-300"
disabled={buildEnvVariables.length === 1}
onClick={(event) => {
if (blockPageAgentDestructiveClick(event)) return;
setBuildEnvVariables((prev) => prev.filter((_, itemIndex) => itemIndex !== index));
}}
title="환경변수 삭제"
aria-label="환경변수 삭제"
>
<Trash2 className="size-4" />
</Button>
</div>
))}
<Button
type="button"
variant="outline"
className="h-8 px-3 text-xs"
onClick={() => setBuildEnvVariables((prev) => [...prev, emptyBuildEnvVariable()])}
>
<Plus className="size-3.5" />
추가
</Button>
</div>
)}
{buildEnvStatus === 'error' ? <p className="mt-4 text-xs text-rose-300">빌드 환경변수 처리에 실패했습니다.</p> : null}
</div>
<div className="flex justify-end gap-2 border-t border-border px-5 py-3">
<Button variant="ghost" onClick={closeBuildEnvModal}>취소</Button>
<Button onClick={saveBuildEnv} disabled={buildEnvStatus === 'loading' || buildEnvStatus === 'saving'}>
{buildEnvStatus === 'saving' ? '저장 중' : '저장'}
</Button>
</div>
</div>
</div>
) : null}
{deletingComponent ? (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-background/55 px-4 backdrop-blur-[2px]">
<div className="w-full max-w-md rounded-lg border border-border bg-card shadow-xl">
<div className="border-b border-border px-5 py-3">
<h2 className="text-sm font-semibold">구성요소 삭제</h2>
</div>
<div className="px-5 py-5 text-sm text-muted-foreground">
<span className="font-semibold text-foreground">{deletingComponent.name}</span> 구성요소를 삭제합니다. 빌드/릴리즈 이력이 연결되어 있으면 실패할 수 있습니다.
</div>
<div className="flex justify-end gap-2 border-t border-border px-5 py-3">
<Button variant="ghost" onClick={() => setDeletingComponent(null)}>취소</Button>
<Button
variant="secondary"
onClick={(event) => {
if (blockPageAgentDestructiveClick(event)) return;
deleteComponent();
}}
>
삭제
</Button>
</div>
</div>
</div>
) : null}
{deletingApp ? (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-background/55 px-4 backdrop-blur-[2px]">
<div className="w-full max-w-xl rounded-lg border border-border bg-card shadow-xl">
<div className="flex items-center gap-2 border-b border-border px-5 py-3">
<Trash2 className="size-4 text-rose-300" />
<h2 className="text-sm font-semibold">앱 폐기</h2>
</div>
<div className="space-y-4 px-5 py-6 text-sm">
<p className="text-muted-foreground">
<span className="font-semibold text-foreground">{deletingApp.name}</span> 앱을 목록에서 삭제하고 선택한 운영 리소스를 정리합니다.
</p>
<div className="space-y-2 rounded-md border border-border bg-muted/20 p-3">
{[
['unlinkSources', '저장소 연결 정보 삭제'],
['deleteRuntimeSettings', '실행 설정 삭제'],
['scaleDownWorkloads', 'Kubernetes 워크로드 중지'],
['deleteKubernetesResources', 'Kubernetes 리소스 삭제'],
['deletePersistentVolumes', 'PVC/데이터 볼륨 삭제']
].map(([key, label]) => {
const optionKey = key as keyof typeof appDeleteOptions;
const disabled = optionKey === 'deletePersistentVolumes' && !appDeleteOptions.deleteKubernetesResources;
return (
<label key={key} className={cn('flex items-center gap-2 text-sm', disabled && 'opacity-50')}>
<input
type="checkbox"
checked={appDeleteOptions[optionKey]}
disabled={disabled}
onChange={(event) => updateAppDeleteOption(optionKey, event.target.checked)}
className="size-4 accent-primary"
/>
{label}
</label>
);
})}
</div>
<div className="rounded-md border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-xs leading-5 text-amber-200">
PVC/데이터 볼륨 삭제는 되돌릴 수 없습니다. DB 데이터 백업을 확인한 경우에만 선택하세요.
</div>
{appDeleteStatus === 'error' ? (
<p className="text-xs text-rose-300">앱 폐기에 실패했습니다. 백엔드 로그와 Kubernetes 권한을 확인하세요.</p>
) : null}
</div>
<div className="flex justify-end gap-2 border-t border-border px-5 py-3">
<Button variant="ghost" onClick={() => setDeletingApp(null)} disabled={appDeleteStatus === 'deleting'}>취소</Button>
<Button
variant="outline"
className="border-rose-500/50 text-rose-300 hover:border-rose-400 hover:bg-rose-500/10 hover:text-rose-200"
onClick={(event) => {
if (blockPageAgentDestructiveClick(event)) return;
deleteApp();
}}
disabled={appDeleteStatus === 'deleting'}
>
{appDeleteStatus === 'deleting' ? '폐기 중' : '폐기'}
</Button>
</div>
</div>
</div>
) : null}
{deletingWorkload ? (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-background/55 px-4 backdrop-blur-[2px]">
<div className="w-full max-w-lg rounded-lg border border-border bg-card shadow-xl">
<div className="border-b border-border px-5 py-3">
<h2 className="text-sm font-semibold">워크로드 삭제</h2>
</div>
<div className="space-y-4 px-5 py-5 text-sm">
<p className="text-muted-foreground">
워크로드를 삭제합니다. 앱 구성요소는 남아 있으며, 필요하면 삭제 완료 후 앱 구성요소에서 별도로 삭제하세요.
</p>
<div className="rounded-md border border-border bg-background/70 p-4">
<div className="grid gap-3 text-xs md:grid-cols-2">
<div>
<p className="text-muted-foreground">대상</p>
<p className="mt-1 font-mono text-foreground">{deletingWorkload.name}</p>
</div>
<div>
<p className="text-muted-foreground">유형</p>
<p className="mt-1 text-foreground">{deletingWorkload.kind}</p>
</div>
<div>
<p className="text-muted-foreground">네임스페이스</p>
<p className="mt-1 font-mono text-foreground">{selectedApp?.namespace || '-'}</p>
</div>
<div>
<p className="text-muted-foreground">준비 상태</p>
<p className="mt-1 text-foreground">{deletingWorkload.ready}</p>
</div>
</div>
</div>
<label className="flex items-center gap-2 text-sm text-muted-foreground">
<input
type="checkbox"
className="size-4 accent-primary"
checked={deleteServiceWithWorkload}
onChange={(event) => setDeleteServiceWithWorkload(event.target.checked)}
/>
관련 Service도 함께 삭제
</label>
<div className="rounded-md border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-xs leading-5 text-amber-200">
ConfigMap/Secret은 삭제하지 않습니다. StatefulSet의 PVC도 기본 삭제하지 않으므로 DB 데이터는 별도 백업 확인 후 처리하세요.
</div>
</div>
<div className="flex justify-end gap-2 border-t border-border px-5 py-3">
<Button variant="ghost" onClick={() => setDeletingWorkload(null)}>취소</Button>
<Button
variant="outline"
className="border-rose-500/50 text-rose-300 hover:border-rose-400 hover:bg-rose-500/10 hover:text-rose-200"
disabled={workloadActionKey === `delete-${deletingWorkload.kind}-${deletingWorkload.name}`}
onClick={(event) => {
if (blockPageAgentDestructiveClick(event)) return;
confirmDeleteWorkload();
}}
>
삭제
</Button>
</div>
</div>
</div>
) : null}
{deletingVolumeWorkload ? (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-background/55 px-4 backdrop-blur-[2px]">
<div className="w-full max-w-xl rounded-lg border border-border bg-card shadow-xl">
<div className="flex items-center gap-2 border-b border-border px-5 py-3">
<Trash2 className="size-4 text-rose-300" />
<h2 className="text-sm font-semibold">데이터 볼륨 삭제</h2>
</div>
<div className="space-y-4 px-5 py-5 text-sm">
<p className="text-muted-foreground">
선택한 DB 워크로드의 PVC를 삭제합니다. 이 작업은 저장된 데이터 삭제로 이어지며 되돌릴 수 없습니다.
</p>
<div className="rounded-md border border-border bg-background/70 p-4">
<div className="grid gap-3 text-xs md:grid-cols-2">
<div>
<p className="text-muted-foreground">워크로드</p>
<p className="mt-1 font-mono text-foreground">{deletingVolumeWorkload.name}</p>
</div>
<div>
<p className="text-muted-foreground">네임스페이스</p>
<p className="mt-1 font-mono text-foreground">{selectedApp?.namespace || '-'}</p>
</div>
<div>
<p className="text-muted-foreground">상태</p>
<p className="mt-1 text-foreground">{runtimeStatusLabel(deletingVolumeWorkload, isStoppedResource(deletingVolumeWorkload))}</p>
</div>
<div>
<p className="text-muted-foreground">준비 상태</p>
<p className="mt-1 text-foreground">{deletingVolumeWorkload.ready}</p>
</div>
</div>
</div>
<label className="block">
<span className="text-xs font-medium text-muted-foreground">삭제할 데이터 볼륨</span>
<select
className="mt-2 h-9 w-full rounded-md border border-input bg-background px-3 text-sm text-foreground outline-none focus:ring-2 focus:ring-ring"
value={selectedVolumeClaimName}
disabled={volumeDeleteStatus === 'loading' || volumeClaims.length === 0}
onChange={(event) => {
setSelectedVolumeClaimName(event.target.value);
setVolumeDeleteConfirmText('');
}}
>
{volumeDeleteStatus === 'loading' ? <option value="">조회 중</option> : null}
{volumeClaims.length === 0 && volumeDeleteStatus !== 'loading' ? <option value="">연결된 PVC 없음</option> : null}
{volumeClaims.map((claim) => (
<option key={claim.name} value={claim.name}>{claim.name}</option>
))}
</select>
</label>
{selectedVolumeClaim ? (
<div className="rounded-md border border-border bg-background/70 p-4">
<div className="grid gap-3 text-xs md:grid-cols-2">
<div>
<p className="text-muted-foreground">용량</p>
<p className="mt-1 text-foreground">{selectedVolumeClaim.capacity || '-'}</p>
</div>
<div>
<p className="text-muted-foreground">상태</p>
<p className="mt-1 text-foreground">{selectedVolumeClaim.status || '-'}</p>
</div>
<div>
<p className="text-muted-foreground">스토리지 클래스</p>
<p className="mt-1 text-foreground">{selectedVolumeClaim.storageClass || '-'}</p>
</div>
<div>
<p className="text-muted-foreground">접근 모드</p>
<p className="mt-1 text-foreground">{selectedVolumeClaim.accessModes?.join(', ') || '-'}</p>
</div>
</div>
</div>
) : null}
<label className="flex items-center gap-2 rounded-md border border-border bg-muted/20 px-3 py-2 text-sm text-muted-foreground">
<input
type="checkbox"
className="size-4 accent-primary"
checked={volumeDeleteBackupChecked}
onChange={(event) => setVolumeDeleteBackupChecked(event.target.checked)}
/>
백업 여부를 확인했습니다.
</label>
<label className="block">
<span className="text-xs font-medium text-muted-foreground">
확인 문구 입력: <b className="font-mono text-foreground">{volumeDeleteConfirmPhrase || '-'}</b>
</span>
<input
className="mt-2 h-9 w-full rounded-md border border-input bg-background px-3 text-sm text-foreground outline-none placeholder:text-muted-foreground focus:ring-2 focus:ring-ring"
value={volumeDeleteConfirmText}
onChange={(event) => setVolumeDeleteConfirmText(event.target.value)}
placeholder={volumeDeleteConfirmPhrase || '삭제할 PVC를 선택하세요'}
/>
</label>
<div className="rounded-md border border-rose-500/30 bg-rose-500/10 px-3 py-2 text-xs leading-5 text-rose-200">
PVC를 삭제하면 해당 DB 데이터가 삭제됩니다. 워크로드가 다시 시작되면 빈 볼륨으로 생성될 수 있습니다.
</div>
</div>
<div className="flex justify-end gap-2 border-t border-border px-5 py-3">
<Button variant="ghost" onClick={closeVolumeDeleteModal}>취소</Button>
<Button
variant="outline"
className="border-rose-500/50 text-rose-300 hover:border-rose-400 hover:bg-rose-500/10 hover:text-rose-200"
disabled={!canDeleteVolume}
onClick={(event) => {
if (blockPageAgentDestructiveClick(event)) return;
confirmDeleteVolume();
}}
>
{volumeDeleteStatus === 'deleting' ? '삭제 중' : '삭제'}
</Button>
</div>
</div>
</div>
) : null}
<LoadingModal open={appsLoadingVisible} />
</>
);
}