Files
chpark 4c3ea194a0 권한 그룹 코드 자동 생성 + 대시보드 API URL 환경변수 우선
- RoleFormModal: 권한 코드 입력 필드 제거. 생성 시 ROLE_<base36 timestamp>
  형태로 자동 부여 (시스템 내부 키, UI 비노출). 수정 모드에서도
  authCode 는 기존 값 유지하고 입력 받지 않음.
- dashboard.ts getApiBaseUrl: NEXT_PUBLIC_API_URL 환경변수가 있으면 우선 사용.
  fallback 포트를 8080 → 8090 (compose 외부 노출 포트)으로 정정해
  '데이터를 불러올 수 없습니다 / Failed to fetch' 해결.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 09:07:40 +09:00

238 lines
7.8 KiB
TypeScript

"use client";
import React, { useState, useCallback, useEffect, useMemo } from "react";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
DialogFooter,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { roleAPI, RoleGroup } from "@/lib/api/role";
import { useAuth } from "@/hooks/useAuth";
import { AlertCircle } from "lucide-react";
interface RoleFormModalProps {
isOpen: boolean;
onClose: () => void;
onSuccess?: () => void;
editingRole?: RoleGroup | null;
}
/**
* 권한 그룹 생성/수정 모달
*
* 기능:
* - 권한 그룹 생성 (authName, authCode, companyCode)
* - 권한 그룹 수정 (authName, authCode, status)
* - 유효성 검사
*
* shadcn/ui 표준 모달 디자인 적용
*/
export function RoleFormModal({ isOpen, onClose, onSuccess, editingRole }: RoleFormModalProps) {
const { user: currentUser } = useAuth();
const isEditMode = !!editingRole;
// 폼 데이터
const [formData, setFormData] = useState({
authName: "",
authCode: "",
status: "active",
});
// 상태 관리
const [isLoading, setIsLoading] = useState(false);
const [showAlert, setShowAlert] = useState(false);
const [alertMessage, setAlertMessage] = useState("");
const [alertType, setAlertType] = useState<"success" | "error" | "info">("info");
// 폼 유효성 검사 — 그룹명만 필수 (코드는 자동 생성, UI 비노출)
const isFormValid = useMemo(() => {
return formData.authName.trim() !== "";
}, [formData]);
// 권한 코드 자동 생성기 — ROLE_<base36 timestamp>
// 예: ROLE_K6X9YZA — 충돌 가능성 매우 낮음, 사용자에게는 노출하지 않는 시스템 내부 키
const generateAuthCode = useCallback(() => {
return `ROLE_${Date.now().toString(36).toUpperCase()}`;
}, []);
// 알림 표시
const displayAlert = useCallback((message: string, type: "success" | "error" | "info") => {
setAlertMessage(message);
setAlertType(type);
setShowAlert(true);
setTimeout(() => setShowAlert(false), 3000);
}, []);
// 초기화
useEffect(() => {
if (isOpen) {
if (isEditMode && editingRole) {
// 수정 모드: 기존 데이터 로드
setFormData({
authName: editingRole.authName || "",
authCode: editingRole.authCode || "",
status: editingRole.status || "active",
});
} else {
// 생성 모드: 초기화
setFormData({
authName: "",
authCode: "",
status: "active",
});
}
setShowAlert(false);
}
}, [isOpen, isEditMode, editingRole]);
// 입력 핸들러
const handleInputChange = useCallback((field: string, value: string) => {
setFormData((prev) => ({ ...prev, [field]: value }));
}, []);
// 제출 핸들러
const handleSubmit = useCallback(async () => {
if (!isFormValid) {
displayAlert("모든 필수 항목을 입력해주세요.", "error");
return;
}
setIsLoading(true);
try {
let response;
if (isEditMode && editingRole) {
// 수정 — authCode 는 생성 시 자동 부여된 값을 그대로 유지
response = await roleAPI.update(editingRole.objid, {
authName: formData.authName,
authCode: editingRole.authCode || formData.authCode,
status: formData.status,
});
} else {
// 생성 — 권한 코드는 자동 생성 (사용자 입력 받지 않음)
response = await roleAPI.create({
authName: formData.authName,
authCode: generateAuthCode(),
companyCode: currentUser?.companyCode || "",
});
}
if (response.success) {
displayAlert(isEditMode ? "권한 그룹이 수정되었습니다." : "권한 그룹이 생성되었습니다.", "success");
setTimeout(() => {
onClose();
onSuccess?.();
}, 1500);
} else {
displayAlert(response.message || "작업에 실패했습니다.", "error");
}
} catch (error) {
console.error("권한 그룹 저장 오류:", error);
displayAlert("권한 그룹 저장 중 오류가 발생했습니다.", "error");
} finally {
setIsLoading(false);
}
}, [isFormValid, isEditMode, editingRole, formData, onClose, onSuccess, displayAlert]);
// Enter 키 핸들러
const handleKeyDown = useCallback(
(e: React.KeyboardEvent) => {
if (e.key === "Enter" && isFormValid && !isLoading) {
handleSubmit();
}
},
[isFormValid, isLoading, handleSubmit],
);
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent className="max-w-[95vw] sm:max-w-[500px]">
<DialogHeader>
<DialogTitle className="text-base sm:text-lg">{isEditMode ? "권한 그룹 수정" : "권한 그룹 생성"}</DialogTitle>
</DialogHeader>
<div className="space-y-3 sm:space-y-4">
{/* 권한 그룹명 */}
<div>
<Label htmlFor="authName" className="text-xs sm:text-sm">
<span className="text-destructive">*</span>
</Label>
<Input
id="authName"
value={formData.authName}
onChange={(e) => handleInputChange("authName", e.target.value)}
onKeyDown={handleKeyDown}
placeholder="예: 영업팀 권한"
className="h-8 text-xs sm:h-10 sm:text-sm"
disabled={isLoading}
/>
</div>
{/* 권한 코드는 시스템 내부 키 — 자동 생성, UI 비노출 */}
{/* 상태 (수정 모드에서만 표시) */}
{isEditMode && (
<div>
<Label htmlFor="status" className="text-xs sm:text-sm">
</Label>
<Select value={formData.status} onValueChange={(value) => handleInputChange("status", value)}>
<SelectTrigger className="h-8 text-xs sm:h-10 sm:text-sm">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="active"></SelectItem>
<SelectItem value="inactive"></SelectItem>
</SelectContent>
</Select>
</div>
)}
{/* 알림 메시지 */}
{showAlert && (
<div
className={`rounded-lg border p-3 text-sm ${
alertType === "success"
? "border-green-300 bg-emerald-50 text-emerald-800"
: alertType === "error"
? "border-destructive/50 bg-destructive/10 text-destructive"
: "border-primary/40 bg-primary/10 text-primary"
}`}
>
<div className="flex items-start gap-2">
{alertType === "error" && <AlertCircle className="mt-0.5 h-4 w-4 flex-shrink-0" />}
<span className="text-xs sm:text-sm">{alertMessage}</span>
</div>
</div>
)}
</div>
<DialogFooter className="gap-2 sm:gap-0">
<Button
variant="outline"
onClick={onClose}
disabled={isLoading}
className="h-8 flex-1 text-xs sm:h-10 sm:flex-none sm:text-sm"
>
</Button>
<Button
onClick={handleSubmit}
disabled={isLoading || !isFormValid}
className="h-8 flex-1 text-xs sm:h-10 sm:flex-none sm:text-sm"
>
{isLoading ? "처리중..." : isEditMode ? "수정" : "생성"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}