310 lines
11 KiB
TypeScript
310 lines
11 KiB
TypeScript
'use client'
|
|
|
|
import { useEffect, useMemo, useState } from 'react'
|
|
import { KriDialog } from '@/components/common/KriDialog'
|
|
import { Button } from '@/components/ui/button'
|
|
import { Input } from '@/components/ui/input'
|
|
import { Label } from '@/components/ui/label'
|
|
import { useDialog } from '@/hooks/useDialog'
|
|
import type { DialogId } from '@/store/jotai/dialog'
|
|
import { UserInfoSaveRequest } from '@/types/user'
|
|
import KriPassword, { KRI_PW_REGEX } from "@/components/common/KriPassword";
|
|
import {KriSelect, KriSelectItem} from "@/components/common/KriSelect";
|
|
import type { DataVerification } from "@kri/common";
|
|
import {apiError} from "@kri/common/http";
|
|
import {CONTACT_INTERVIEWER_ROLE, FW_TEAM, USER_NAME_REGEX} from "@/const/userConst";
|
|
import {NONE_HTTP_ERROR, UNKNOWN_HTTP_ERROR} from "@kri/common/http";
|
|
import type { CmpnInfo } from "@/types/cmpn";
|
|
import { isExternalManager, isFieldWorkUser } from "@/utils/userRole";
|
|
|
|
// 외주사(EXTERNAL_USER_ROLE_GROUP)와 콜센터/컨택원/면접원(FW_USER_ROLE_GROUP)은 배정 체계가 완전히 달라
|
|
// 서로 넘나드는 권한 수정을 지원하지 않는다. 하나 새로 만들어서 넘기는 게 맞다.
|
|
const isCrossExternalFwRoleChange = (fromRole: number, toRole: number) =>
|
|
(isExternalManager(fromRole) && isFieldWorkUser(toRole)) ||
|
|
(isFieldWorkUser(fromRole) && isExternalManager(toRole))
|
|
|
|
export type UserUpsertDialogProps = {
|
|
/** Jotai로 관리할 다이얼로그 ID */
|
|
dialogId?: DialogId
|
|
|
|
/** 필요한 경우 부모에서 직접 open 제어 */
|
|
open?: boolean
|
|
onOpenChange?: (open: boolean) => void
|
|
|
|
mode?: 'create' | 'edit'
|
|
initialData?: Partial<UserInfoSaveRequest>
|
|
isInternal: boolean
|
|
userCmpn: string
|
|
userCmpnArray: CmpnInfo[]
|
|
userRoleArray: KriSelectItem[]
|
|
onSubmit: (data: UserInfoSaveRequest) => void | Promise<void>
|
|
onCheckDuplicate?: (userId: string) => DataVerification | Promise<DataVerification>
|
|
}
|
|
|
|
const UserUpsertDialog = ({
|
|
dialogId = 'userUpsertDialog',
|
|
open,
|
|
onOpenChange,
|
|
mode = 'create',
|
|
initialData,
|
|
userCmpn,
|
|
userCmpnArray,
|
|
userRoleArray,
|
|
onSubmit,
|
|
onCheckDuplicate,
|
|
}: UserUpsertDialogProps) => {
|
|
const defaultUserInfo:UserInfoSaveRequest = {
|
|
userId: '',
|
|
userPw: '',
|
|
userName: '',
|
|
userCmpn: userCmpn,
|
|
userTeam: '',
|
|
userRole: CONTACT_INTERVIEWER_ROLE,
|
|
memo: '',
|
|
}
|
|
|
|
const { isDialogOpen, showDialog, hideDialog } = useDialog();
|
|
|
|
const [formData, setFormData] = useState<UserInfoSaveRequest>(defaultUserInfo);
|
|
|
|
const [isCheckedDuplicate, setIsCheckedDuplicate] = useState(false);
|
|
const [isSubmitting, setIsSubmitting] = useState(false);
|
|
|
|
// 실제 Dialog에 전달할 open 값
|
|
const resolvedOpen = open ?? isDialogOpen(dialogId);
|
|
|
|
// 부모 콜백과 jotai 상태를 함께 처리
|
|
const handleOpenChange = (nextOpen: boolean) => {
|
|
onOpenChange?.(nextOpen);
|
|
|
|
if (nextOpen) {
|
|
showDialog(dialogId);
|
|
} else {
|
|
hideDialog(dialogId);
|
|
}
|
|
}
|
|
|
|
// initialData / mode / open 변경 시 폼 세팅
|
|
useEffect(() => {
|
|
if (initialData) {
|
|
setFormData(prev => ({
|
|
...prev,
|
|
...initialData,
|
|
}));
|
|
|
|
if (mode === 'edit'){
|
|
setIsCheckedDuplicate(true);
|
|
}
|
|
} else {
|
|
setFormData(defaultUserInfo);
|
|
setIsCheckedDuplicate(false);
|
|
}
|
|
}, [initialData, mode, resolvedOpen])
|
|
|
|
// 수정 모드에서는 최초 권한 기준으로 외주사 ↔ 콜센터/컨택원/면접원 간 이동이 되는 선택지를 아예 뺀다.
|
|
const availableRoleArray = useMemo(() => {
|
|
if (mode === 'create' || initialData?.userRole == null) return userRoleArray
|
|
const initialRole = initialData.userRole
|
|
return userRoleArray.filter((item) => !isCrossExternalFwRoleChange(initialRole, Number(item.value)))
|
|
}, [mode, initialData?.userRole, userRoleArray])
|
|
|
|
const handleInputChange = <K extends keyof UserInfoSaveRequest>(field: K, value: UserInfoSaveRequest[K]) => {
|
|
setFormData(prev => ({
|
|
...prev,
|
|
[field]: value,
|
|
}));
|
|
|
|
if (field === 'userId' && mode === 'create') {
|
|
setIsCheckedDuplicate(false);
|
|
}
|
|
}
|
|
|
|
const handleCheckDuplicate = async () => {
|
|
if (!formData.userId.trim()) {
|
|
alert("아이디를 입력해주세요.");
|
|
return
|
|
}
|
|
|
|
if (onCheckDuplicate) {
|
|
const isDuplicate = await onCheckDuplicate(formData.userId);
|
|
if (!isDuplicate.success) {
|
|
alert(isDuplicate.errMessage);
|
|
setIsCheckedDuplicate(false);
|
|
} else {
|
|
alert("사용 가능한 아이디입니다.");
|
|
setIsCheckedDuplicate(true);
|
|
}
|
|
} else {
|
|
setIsCheckedDuplicate(true);
|
|
}
|
|
}
|
|
|
|
const handleSubmit = async () => {
|
|
if (!formData.userId.trim()) {
|
|
alert("아이디를 입력해주세요.");
|
|
return;
|
|
}
|
|
if (mode === 'create' && !isCheckedDuplicate) {
|
|
alert("아이디 중복체크를 해주세요.");
|
|
return;
|
|
}
|
|
if (!formData.userPw.trim()) {
|
|
alert("비밀번호를 입력해주세요.");
|
|
return;
|
|
}
|
|
if (!KRI_PW_REGEX.test(formData.userPw)) {
|
|
alert("비밀번호는 영문과 숫자를 포함한 8~20자로 입력해주세요.");
|
|
return;
|
|
}
|
|
if (!formData.userName.trim()) {
|
|
alert("이름을 입력해주세요.");
|
|
return;
|
|
}
|
|
if(!USER_NAME_REGEX.test(formData.userName)){
|
|
alert("올바르지 않은 이름입니다.");
|
|
return;
|
|
}
|
|
|
|
setIsSubmitting(true);
|
|
|
|
formData.userTeam = FW_TEAM;
|
|
|
|
try {
|
|
await onSubmit(formData as UserInfoSaveRequest);
|
|
handleOpenChange(false);
|
|
} catch (e) {
|
|
const err = apiError(e, {
|
|
fallbackMessage: "Save failed.",
|
|
});
|
|
console.error(err.status, err.code, err.message);
|
|
if(err.code !== NONE_HTTP_ERROR && err.code !== UNKNOWN_HTTP_ERROR){
|
|
alert(err.message);
|
|
}
|
|
else{
|
|
alert("저장에 실패했습니다.");
|
|
}
|
|
} finally {
|
|
setIsSubmitting(false);
|
|
}
|
|
}
|
|
|
|
return (
|
|
<KriDialog
|
|
open={resolvedOpen}
|
|
onOpenChange={handleOpenChange}
|
|
title={<span className="text-xl">{mode === 'create' ? '계정 등록' : '계정 수정'}</span>}
|
|
description="면접원 계정 정보를 입력해주세요."
|
|
contentClassName="sm:max-w-[500px] text-sm"
|
|
bodyClassName="grid gap-4 py-4"
|
|
footer={
|
|
<>
|
|
<Button
|
|
type="button"
|
|
variant="outline"
|
|
onClick={() => handleOpenChange(false)}
|
|
>
|
|
취소
|
|
</Button>
|
|
<Button
|
|
type="submit"
|
|
onClick={handleSubmit}
|
|
disabled={isSubmitting}
|
|
>
|
|
{mode === 'create' ? "등록" : "수정"}
|
|
</Button>
|
|
</>
|
|
}
|
|
>
|
|
<div className="grid gap-2">
|
|
<Label htmlFor="userId">
|
|
ID<span className="text-red-500 ml-1">*</span>
|
|
</Label>
|
|
<div className="flex gap-2">
|
|
<Input
|
|
id="userId"
|
|
placeholder="Enter ID"
|
|
value={formData.userId}
|
|
onChange={(e) => handleInputChange('userId', e.target.value)}
|
|
disabled={mode === 'edit'}
|
|
/>
|
|
{mode === 'create' && (
|
|
<Button
|
|
variant="outline"
|
|
onClick={handleCheckDuplicate}
|
|
disabled={!formData.userId.trim() || isCheckedDuplicate}
|
|
>
|
|
{isCheckedDuplicate ? "확인완료" : "중복체크"}
|
|
</Button>
|
|
)}
|
|
</div>
|
|
</div>
|
|
<div className="grid gap-2">
|
|
<Label htmlFor="password">
|
|
PW<span className="text-red-500 ml-1">*</span>
|
|
</Label>
|
|
<KriPassword
|
|
id="password"
|
|
label=""
|
|
value={formData.userPw}
|
|
onChange={(v) => handleInputChange('userPw', v)}
|
|
placeholder="Enter password"
|
|
/>
|
|
</div>
|
|
<div className="grid gap-2">
|
|
<Label htmlFor="userName">
|
|
이름<span className="text-red-500 ml-1">*</span>
|
|
</Label>
|
|
<Input
|
|
id="userName"
|
|
placeholder="Enter name"
|
|
value={formData.userName}
|
|
onChange={(e) => handleInputChange('userName', e.target.value)}
|
|
/>
|
|
</div>
|
|
<div className="grid gap-2">
|
|
<Label>계정 권한</Label>
|
|
<KriSelect
|
|
items={availableRoleArray}
|
|
value={String(formData.userRole)}
|
|
getLabel={(item) => item.label}
|
|
getValue={(item) => String(item.value)}
|
|
onChange={(e) => {
|
|
if(mode !== 'create'){
|
|
alert("권한이 변경되면 해당 계정에 배정된 리스트 정보가 초기화됩니다.");
|
|
}
|
|
handleInputChange('userRole', Number(e));
|
|
}}
|
|
useAll={false}
|
|
className="w-full min-w-0 overflow-hidden [&>span]:truncate"
|
|
heightClassName="h-8"
|
|
/>
|
|
</div>
|
|
<div className="grid gap-2">
|
|
<Label>소속 회사</Label>
|
|
<KriSelect
|
|
items={userCmpnArray}
|
|
value={formData.userCmpn}
|
|
getValue={(item) => item.cmpnId}
|
|
getLabel={(item) => item.cmpnAlias || item.cmpnId}
|
|
onChange={(e) => handleInputChange('userCmpn', e)}
|
|
useAll={false}
|
|
disabled={mode !== 'create'}
|
|
className="w-full min-w-0 overflow-hidden [&>span]:truncate"
|
|
heightClassName="h-9"
|
|
/>
|
|
</div>
|
|
<div className="grid gap-2">
|
|
<Label htmlFor="memo">메모</Label>
|
|
<textarea id="memo" className="flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
|
|
rows={3}
|
|
placeholder="Enter memo"
|
|
value={formData.memo}
|
|
onChange={(e) => handleInputChange('memo', e.target.value)}
|
|
/>
|
|
</div>
|
|
</KriDialog>
|
|
)
|
|
}
|
|
|
|
export default UserUpsertDialog
|