diff --git a/src/entities/account/model/types.ts b/src/entities/account/model/types.ts index e491ffe..dd6e81e 100644 --- a/src/entities/account/model/types.ts +++ b/src/entities/account/model/types.ts @@ -12,6 +12,8 @@ export enum AccountUserTabKeys { export interface AccountUserTabProps { activeTab: AccountUserTabKeys; tid: string; + mid?: string; + usrid?: string; }; export interface AuthItem { useYn?: boolean; @@ -19,13 +21,16 @@ export interface AuthItem { tid?: string; }; export interface UserManageAuthListProps { - authItems: Array + userItems: Array; + mid: string; }; export interface UserManageAuthItemProps extends AuthItem { - + usrid?: string; + mid?: string; }; export interface UserLoginAuthInfoWrapProps { - tid: string; + mid: string; + usrid: string; }; export interface UserAccountAuthWrapProps { tid: string; @@ -40,4 +45,72 @@ export interface UserAccountAuthPermListProps { }; export interface UserAccountAuthPermItemProps extends PermItem { tid: string; -}; \ No newline at end of file +}; + +export interface VerificationItem { + type: string; + contact: string; +} + +export interface UserCreateRequest { + mid: string; + usrid: string; + password?: string; + loginRange: string; + verifications: Array; +} + +export interface UserCreateResponse { + status: boolean; + error?: { + root: string; + errKey: string; + code: string; + message: string; + timestamp: string; + details: Record; + }; + data?: { + user: { + usrid: string; + mid: string; + gid: string; + aid: string; + pw: string; + authCd: string; + status: string; + regDt: string; + memo: string; + changeDt: string; + failCnt: number; + oldPw1: string; + oldPw2: string; + oldPw3: string; + oldPw4: string; + worker: string; + loginCd: string; + pwWorkIp: string; + pwCheckYn: string; + loginFailDt: string; + loginFailTm: string; + loginFailIp: string; + desaYn: string; + desaAccType: string; + desaAccIp: string; + desaProcType: string; + desaFormat: string; + desaSvcCl: string; + emailAuth1: string; + emailAuth2: string; + emailAuth3: string; + authDt: string; + authTm: string; + userAidGroupYn: string; + userAidGroupId: string; + subNm: string; + subLevel: string; + multiAccessYn: string; + duplicateAccessYn: string; + }; + }; +} \ No newline at end of file diff --git a/src/entities/account/ui/account-user-tab.tsx b/src/entities/account/ui/account-user-tab.tsx index a49e927..8cd9f97 100644 --- a/src/entities/account/ui/account-user-tab.tsx +++ b/src/entities/account/ui/account-user-tab.tsx @@ -7,7 +7,9 @@ import { export const AccountUserTab = ({ activeTab, - tid + tid, + mid, + usrid }: AccountUserTabProps) => { const { navigate } = useNavigate(); @@ -16,14 +18,18 @@ export const AccountUserTab = ({ if(tab === AccountUserTabKeys.LoginAuthInfo){ navigate(PATHS.account.user.loginAuthInfo, { state: { - tid: tid + tid: tid, + mid: mid, + usrid: usrid } }); } else if(tab === AccountUserTabKeys.AccountAuth){ navigate(PATHS.account.user.accountAuth, { state: { - tid: tid + tid: tid, + mid: mid, + usrid: usrid } }); } diff --git a/src/entities/account/ui/user-login-auth-info-wrap.tsx b/src/entities/account/ui/user-login-auth-info-wrap.tsx index 1997d0e..61d2631 100644 --- a/src/entities/account/ui/user-login-auth-info-wrap.tsx +++ b/src/entities/account/ui/user-login-auth-info-wrap.tsx @@ -1,8 +1,268 @@ -import { UserLoginAuthInfoWrapProps } from '../model/types'; +import { UserFindAuthMethodParams, UserAuthMethodData } from '@/entities/user/model/types'; +import { useUserFindAuthMethodMutation } from '@/entities/user/api/use-user-find-authmethod-mutation'; +import { DEFAULT_PAGE_PARAM } from '@/entities/common/model/constant'; +import { useEffect, useState } from 'react'; export const UserLoginAuthInfoWrap = ({ - tid -}: UserLoginAuthInfoWrapProps) => { + mid, + usrid, +}: UserFindAuthMethodParams) => { + const { mutateAsync: userFindAuthMethod } = useUserFindAuthMethodMutation(); + const [pageParam] = useState(DEFAULT_PAGE_PARAM); + const [authMethodData, setAuthMethodData] = useState(); + const [initialData, setInitialData] = useState(); + const [newEmails, setNewEmails] = useState([]); + const [newPhones, setNewPhones] = useState([]); + const [editableEmailIndex, setEditableEmailIndex] = useState(-1); + const [editablePhoneIndex, setEditablePhoneIndex] = useState(-1); + const [readOnlyEmails, setReadOnlyEmails] = useState>(new Set()); + const [readOnlyPhones, setReadOnlyPhones] = useState>(new Set()); + + const handleRemoveExistingEmail = (index: number) => { + if (authMethodData?.emails) { + const updatedEmails = authMethodData.emails.filter((_, i) => i !== index); + setAuthMethodData({ ...authMethodData, emails: updatedEmails }); + } + }; + + const handleRemoveExistingPhone = (index: number) => { + if (authMethodData?.phones) { + const updatedPhones = authMethodData.phones.filter((_, i) => i !== index); + setAuthMethodData({ ...authMethodData, phones: updatedPhones }); + } + }; + + const callUserFindAuthMethod = (mid: string, usrid: string) => { + let params: UserFindAuthMethodParams = { + mid: mid, + usrid: usrid, + page: pageParam + }; + userFindAuthMethod(params).then((rs: any) => { + console.log("User Find Auth Method: ", rs); + // API 응답이 직접 데이터를 반환하는 경우 + if (rs.emails || rs.phones) { + console.log("Setting authMethodData directly from response: ", rs); + setAuthMethodData(rs); + setInitialData(rs); + } + // API 응답이 data 프로퍼티 안에 있는 경우 + else if (rs.data) { + console.log("Setting authMethodData from rs.data: ", rs.data); + setAuthMethodData(rs.data); + setInitialData(rs.data); + } + }); + }; + + useEffect(() => { + if (mid && usrid) { + callUserFindAuthMethod(mid, usrid); + } + }, [mid, usrid]); + + const handleAddEmail = () => { + // 현재 편집 중인 항목을 읽기전용으로 고정 + if (editableEmailIndex >= 0) { + setReadOnlyEmails(prev => new Set([...prev, editableEmailIndex])); + } + + // 새로운 편집 가능한 항목 추가 + setEditableEmailIndex(newEmails.length); + setNewEmails([...newEmails, '']); + }; + + const handleAddPhone = () => { + // 현재 편집 중인 항목을 읽기전용으로 고정 + if (editablePhoneIndex >= 0) { + setReadOnlyPhones(prev => new Set([...prev, editablePhoneIndex])); + } + + // 새로운 편집 가능한 항목 추가 + setEditablePhoneIndex(newPhones.length); + setNewPhones([...newPhones, '']); + }; + + + const handleRemoveNewEmail = (index: number) => { + const updatedEmails = newEmails.filter((_, i) => i !== index); + setNewEmails(updatedEmails); + + // 읽기전용 인덱스들을 업데이트 (삭제된 인덱스보다 큰 인덱스들은 1씩 감소) + const updatedReadOnlyEmails = new Set(); + readOnlyEmails.forEach(readOnlyIndex => { + if (readOnlyIndex < index) { + updatedReadOnlyEmails.add(readOnlyIndex); + } else if (readOnlyIndex > index) { + updatedReadOnlyEmails.add(readOnlyIndex - 1); + } + // readOnlyIndex === index인 경우 제거됨 (Set에 추가하지 않음) + }); + setReadOnlyEmails(updatedReadOnlyEmails); + + // 삭제 후 편집 가능한 인덱스 조정 + if (index === editableEmailIndex) { + // 현재 편집 중인 항목을 삭제한 경우 - 편집 가능한 항목이 없음 + setEditableEmailIndex(-1); + } else if (index < editableEmailIndex) { + // 편집 가능한 항목보다 앞의 항목을 삭제한 경우 + setEditableEmailIndex(editableEmailIndex - 1); + } + }; + + const handleRemoveNewPhone = (index: number) => { + const updatedPhones = newPhones.filter((_, i) => i !== index); + setNewPhones(updatedPhones); + + // 읽기전용 인덱스들을 업데이트 (삭제된 인덱스보다 큰 인덱스들은 1씩 감소) + const updatedReadOnlyPhones = new Set(); + readOnlyPhones.forEach(readOnlyIndex => { + if (readOnlyIndex < index) { + updatedReadOnlyPhones.add(readOnlyIndex); + } else if (readOnlyIndex > index) { + updatedReadOnlyPhones.add(readOnlyIndex - 1); + } + // readOnlyIndex === index인 경우 제거됨 (Set에 추가하지 않음) + }); + setReadOnlyPhones(updatedReadOnlyPhones); + + // 삭제 후 편집 가능한 인덱스 조정 + if (index === editablePhoneIndex) { + // 현재 편집 중인 항목을 삭제한 경우 - 편집 가능한 항목이 없음 + setEditablePhoneIndex(-1); + } else if (index < editablePhoneIndex) { + // 편집 가능한 항목보다 앞의 항목을 삭제한 경우 + setEditablePhoneIndex(editablePhoneIndex - 1); + } + }; + + const handleNewEmailChange = (index: number, value: string) => { + const updated = [...newEmails]; + updated[index] = value; + setNewEmails(updated); + }; + + const handleNewPhoneChange = (index: number, value: string) => { + const updated = [...newPhones]; + updated[index] = value; + setNewPhones(updated); + }; + + // 이메일 형식 검증 + const isValidEmail = (email: string) => { + const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; + return emailRegex.test(email); + }; + + // 전화번호 형식 검증 (010으로 시작하고 총 11자리 숫자) + const isValidPhone = (phone: string) => { + const phoneRegex = /^010\d{8}$/; + return phoneRegex.test(phone); + }; + + // 이메일 추가 버튼 활성화 조건 + const isEmailAddButtonEnabled = () => { + if (newEmails.length === 0) return true; // 처음은 활성화 + + const lastEmailIndex = newEmails.length - 1; + const lastEmail = newEmails[lastEmailIndex]; + + // 마지막 항목이 편집 가능하고, 유효한 형식이며, 중복이 없으면 활성화 + return lastEmailIndex >= editableEmailIndex && + lastEmail && + lastEmail.trim() && + isValidEmail(lastEmail) && + !hasDuplicateEmail(); + }; + + // 전화번호 추가 버튼 활성화 조건 + const isPhoneAddButtonEnabled = () => { + if (newPhones.length === 0) return true; // 처음은 활성화 + + const lastPhoneIndex = newPhones.length - 1; + const lastPhone = newPhones[lastPhoneIndex]; + + // 마지막 항목이 편집 가능하고, 유효한 형식이며, 중복이 없으면 활성화 + return lastPhoneIndex >= editablePhoneIndex && + lastPhone && + lastPhone.trim() && + isValidPhone(lastPhone) && + !hasDuplicatePhone(); + }; + + // 삭제 버튼 활성화 조건 (전체 항목이 1개만 남으면 비활성화) + const isDeleteButtonEnabled = () => { + const totalEmailCount = (authMethodData?.emails?.length || 0) + newEmails.length; + const totalPhoneCount = (authMethodData?.phones?.length || 0) + newPhones.length; + const totalCount = totalEmailCount + totalPhoneCount; + + return totalCount > 1; + }; + + // 중복 이메일 검증 + const hasDuplicateEmail = () => { + const allEmails = [ + ...(authMethodData?.emails?.map(e => e.content) || []), + ...newEmails.filter(e => e.trim()) + ]; + + const uniqueEmails = new Set(allEmails); + return allEmails.length !== uniqueEmails.size; + }; + + // 중복 전화번호 검증 + const hasDuplicatePhone = () => { + const allPhones = [ + ...(authMethodData?.phones?.map(p => p.content) || []), + ...newPhones.filter(p => p.trim()) + ]; + + const uniquePhones = new Set(allPhones); + return allPhones.length !== uniquePhones.size; + }; + + const isSaveButtonEnabled = () => { + // 새로 추가된 이메일 중 값이 있는 것들의 형식 검증 + const validNewEmails = newEmails.filter(e => e.trim()); + const hasInvalidEmail = validNewEmails.some(email => !isValidEmail(email)); + + // 새로 추가된 전화번호 중 값이 있는 것들의 형식 검증 + const validNewPhones = newPhones.filter(p => p.trim()); + const hasInvalidPhone = validNewPhones.some(phone => !isValidPhone(phone)); + + // 형식이 맞지 않는 항목이 있거나 중복이 있으면 비활성화 + if (hasInvalidEmail || hasInvalidPhone || hasDuplicateEmail() || hasDuplicatePhone()) { + return false; + } + + // 현재 이메일과 전화번호가 모두 없으면 비활성화 + const currentEmailCount = (authMethodData?.emails?.length || 0) + validNewEmails.length; + const currentPhoneCount = (authMethodData?.phones?.length || 0) + validNewPhones.length; + + if (currentEmailCount === 0 && currentPhoneCount === 0) { + return false; + } + + // 초기 데이터와 비교하여 변경사항이 있는지 확인 + const initialEmailCount = initialData?.emails?.length || 0; + const initialPhoneCount = initialData?.phones?.length || 0; + const currentApiEmailCount = authMethodData?.emails?.length || 0; + const currentApiPhoneCount = authMethodData?.phones?.length || 0; + + // 삭제가 발생했거나 새로운 항목이 추가된 경우 활성화 + const hasChanges = ( + currentApiEmailCount < initialEmailCount || + currentApiPhoneCount < initialPhoneCount || + validNewEmails.length > 0 || + validNewPhones.length > 0 + ); + + return hasChanges; + }; + + console.log("Rendering with authMethodData: ", authMethodData); + console.log("Emails: ", authMethodData?.emails); + console.log("Phones: ", authMethodData?.phones); return ( <> @@ -11,88 +271,107 @@ export const UserLoginAuthInfoWrap = ({
이메일 주소
-
-
- - -
-
- - -
-
- - -
+ {authMethodData?.emails && authMethodData.emails.length > 0 && authMethodData.emails.map((email, index) => ( +
+ + +
+ ))} + {newEmails.map((email, index) => ( +
+ handleNewEmailChange(index, e.target.value)} + readOnly={readOnlyEmails.has(index) || index !== editableEmailIndex} + /> + +
+ ))}
휴대폰 번호
-
-
- - -
-
- - -
+ {authMethodData?.phones && authMethodData.phones.length > 0 && authMethodData.phones.map((phone, index) => ( +
+ + +
+ ))} + {newPhones.map((phone, index) => ( +
+ handleNewPhoneChange(index, e.target.value)} + readOnly={readOnlyPhones.has(index) || index !== editablePhoneIndex} + /> + +
+ ))}
※ 탭을 변경하면 미저장 내용은 초기화됩니다.
- +
diff --git a/src/entities/account/ui/user-manage-auth-item.tsx b/src/entities/account/ui/user-manage-auth-item.tsx index cb8e0fd..ed1247b 100644 --- a/src/entities/account/ui/user-manage-auth-item.tsx +++ b/src/entities/account/ui/user-manage-auth-item.tsx @@ -3,16 +3,19 @@ import { useNavigate } from '@/shared/lib/hooks/use-navigate'; import { UserManageAuthItemProps } from '../model/types'; export const UserManageAuthItem = ({ - useYn, - authName, - tid + usrid, + tid, + mid, }: UserManageAuthItemProps) => { const { navigate } = useNavigate(); const onClickToNavigation = () => { + // state를 통해 데이터 전달 navigate(PATHS.account.user.loginAuthInfo, { state: { - tid: tid + tid: tid, + mid: mid, + usrid: usrid } }); }; @@ -23,8 +26,8 @@ export const UserManageAuthItem = ({ onClick={ () => onClickToNavigation() } >
- { (!!useYn)? '사용': '미사용' } - { authName } + {/* { (!!useYn)? '사용': '미사용' } */} + { usrid }
diff --git a/src/entities/account/ui/user-manage-auth-list.tsx b/src/entities/account/ui/user-manage-auth-list.tsx index fa59bb7..3ae275d 100644 --- a/src/entities/account/ui/user-manage-auth-list.tsx +++ b/src/entities/account/ui/user-manage-auth-list.tsx @@ -2,18 +2,19 @@ import { UserManageAuthItem } from './user-manage-auth-item'; import { UserManageAuthListProps } from '../model/types'; export const UserManageAuthList = ({ - authItems + userItems, + mid }: UserManageAuthListProps) => { - + const getUserManageAuthItems = () => { let rs = []; - for(let i=0;i ); } diff --git a/src/entities/account/ui/user-manage-wrap.tsx b/src/entities/account/ui/user-manage-wrap.tsx index f6b06ca..d344b24 100644 --- a/src/entities/account/ui/user-manage-wrap.tsx +++ b/src/entities/account/ui/user-manage-wrap.tsx @@ -2,21 +2,29 @@ import { useEffect, useState } from 'react'; import { PATHS } from '@/shared/constants/paths'; import { useNavigate } from '@/shared/lib/hooks/use-navigate'; import { AuthItem } from '../model/types'; +import { DEFAULT_PAGE_PARAM } from '@/entities/common/model/constant'; import { UserManageAuthList } from './user-manage-auth-list'; +import { useUserFindMutation } from '@/entities/user/api/use-user-find-mutation'; +import { UserListItem } from '@/entities/user/model/types'; export const UserManageWrap = () => { const { navigate } = useNavigate(); + const { mutateAsync: userFind } = useUserFindMutation(); + const [userItems, setUserItems] = useState>([]); + const [pageParam, setPageParam] = useState(DEFAULT_PAGE_PARAM); + const [mid, setMid] = useState('nictest00m'); - const [authItems, setAuthItems] = useState>([]); + const midList = [ + { value: 'nictest00m', label: 'nictest00m' }, + { value: 'nictest01m', label: 'nictest01m' }, + { value: 'nictest02m', label: 'nictest02m' }, + ]; - const callAuthList = () => { - setAuthItems([ - {useYn: true, authName: 'test01', tid: 'A12334556'}, - {useYn: true, authName: 'test02', tid: 'A33334556'}, - {useYn: true, authName: 'test03', tid: 'A12345556'}, - {useYn: true, authName: 'test04', tid: 'A12978676'}, - {useYn: false, authName: 'test05', tid: 'A12344444'}, - ]); + const callList = (mid: string) => { + setPageParam(pageParam); + userFind({ mid: mid, page: pageParam }).then((rs) => { + setUserItems(rs.content || []); + }); }; const onClickToNavigation = () => { @@ -24,21 +32,25 @@ export const UserManageWrap = () => { }; useEffect(() => { - callAuthList(); - }, []); + callList(mid); + }, [mid]); + return ( <>
- setMid(e.target.value)}> + {midList.map(item => ( + + ))}
등록 현황
- { (!!authItems && authItems.length > 0) && + { (!!userItems && userItems.length > 0) && }
diff --git a/src/entities/user/api/use-user-create-mutation.ts b/src/entities/user/api/use-user-create-mutation.ts index 90844e5..b3590c3 100644 --- a/src/entities/user/api/use-user-create-mutation.ts +++ b/src/entities/user/api/use-user-create-mutation.ts @@ -1,24 +1,50 @@ import axios from 'axios'; -import { API_URL } from '@/shared/api/urls'; -import { resultify } from '@/shared/lib/resultify'; +import { API_URL_USER } from '@/shared/api/api-url-user'; import { CBDCAxiosError } from '@/shared/@types/error'; -import { +import { UserCreateParams, UserCreateResponse } from '../model/types'; -import { + +interface UserCreateMutationResponse { + status: boolean; + data?: UserCreateResponse; + error?: { + root: string; + errKey: string; + code: string; + message: string; + timestamp: string; + details: Record; + }; +} + +import { useMutation, UseMutationOptions } from '@tanstack/react-query'; -export const userCreate = (params: UserCreateParams) => { - return resultify( - axios.post(API_URL.userCreate(), params), - ); +export const userCreate = async (params: UserCreateParams): Promise => { + try { + const response = await axios.post(API_URL_USER.userCreate(), params); + return { status: true, data: response.data }; + } catch (error: any) { + return { + status: false, + error: { + root: 'USER_CREATE', + errKey: error.response?.data?.errKey || 'UNKNOWN_ERROR', + code: error.response?.status?.toString() || '500', + message: error.response?.data?.message || error.message || 'Unknown error', + timestamp: new Date().toISOString(), + details: error.response?.data?.details || {} + } + }; + } }; -export const useUserCreateMutation = (options?: UseMutationOptions) => { - const mutation = useMutation({ +export const useUserCreateMutation = (options?: UseMutationOptions) => { + const mutation = useMutation({ ...options, mutationFn: (params: UserCreateParams) => userCreate(params), }); diff --git a/src/entities/user/api/use-user-exists-userid-mutation.ts b/src/entities/user/api/use-user-exists-userid-mutation.ts index 2ebd4d3..198093d 100644 --- a/src/entities/user/api/use-user-exists-userid-mutation.ts +++ b/src/entities/user/api/use-user-exists-userid-mutation.ts @@ -1,9 +1,8 @@ import axios from 'axios'; -import { API_URL } from '@/shared/api/urls'; +import { API_URL_USER } from '@/shared/api/api-url-user'; import { resultify } from '@/shared/lib/resultify'; import { CBDCAxiosError } from '@/shared/@types/error'; import { - UserExistsUseridParams, UserExistsUseridResponse } from '../model/types'; import { @@ -11,16 +10,16 @@ import { UseMutationOptions } from '@tanstack/react-query'; -export const userExistsUserid = (params: UserExistsUseridParams) => { +export const userExistsUserid = (usrId: string) => { return resultify( - axios.post(API_URL.userExistsUserid(), params), + axios.post(API_URL_USER.userExistsUserid(usrId)), ); }; -export const useUserExistsUseridMutation = (options?: UseMutationOptions) => { - const mutation = useMutation({ +export const useUserExistsUseridMutation = (options?: UseMutationOptions) => { + const mutation = useMutation({ ...options, - mutationFn: (params: UserExistsUseridParams) => userExistsUserid(params), + mutationFn: (usrId: string) => userExistsUserid(usrId), }); return { diff --git a/src/entities/user/api/use-user-exists-userid-query.ts b/src/entities/user/api/use-user-exists-userid-query.ts new file mode 100644 index 0000000..fd9ff2a --- /dev/null +++ b/src/entities/user/api/use-user-exists-userid-query.ts @@ -0,0 +1,31 @@ +import axios from 'axios'; +import { API_URL_USER } from '@/shared/api/api-url-user'; +import { CBDCAxiosError } from '@/shared/@types/error'; +import { + UserExistsUseridResponse +} from '../model/types'; +import { + useQuery, + UseQueryOptions +} from '@tanstack/react-query'; + +export const userExistsUserid = async (usrid: string) => { + const response = await axios.post(API_URL_USER.userExistsUserid(usrid)); + return response.data; +}; + +export const useUserExistsUseridQuery = ( + usrid: string, + options?: Omit, 'queryKey' | 'queryFn'> +) => { + const query = useQuery({ + queryKey: ['userExistsUserid', usrid], + queryFn: async () => await userExistsUserid(usrid), + enabled: !!usrid && usrid.trim().length > 0, // usrid가 있을 때만 실행 + ...options, + }); + + return { + ...query, + }; +}; \ No newline at end of file diff --git a/src/entities/user/api/use-user-find-authmethod-mutation.ts b/src/entities/user/api/use-user-find-authmethod-mutation.ts new file mode 100644 index 0000000..7a15fe7 --- /dev/null +++ b/src/entities/user/api/use-user-find-authmethod-mutation.ts @@ -0,0 +1,29 @@ +import axios from 'axios'; +import { API_URL_USER } from '@/shared/api/api-url-user'; +import { resultify } from '@/shared/lib/resultify'; +import { CBDCAxiosError } from '@/shared/@types/error'; +import { + UserFindAuthMethodParams, + UserFindAuthMethodResponse +} from '../model/types'; +import { + useMutation, + UseMutationOptions +} from '@tanstack/react-query'; + +export const userFindAuthMethod = (params: UserFindAuthMethodParams) => { + return resultify( + axios.post(API_URL_USER.findAuthMethod(), params), + ); +}; + +export const useUserFindAuthMethodMutation = (options?: UseMutationOptions) => { + const mutation = useMutation({ + ...options, + mutationFn: (params: UserFindAuthMethodParams) => userFindAuthMethod(params), + }); + + return { + ...mutation, + }; +}; diff --git a/src/entities/user/api/use-user-find-mutation.ts b/src/entities/user/api/use-user-find-mutation.ts new file mode 100644 index 0000000..2f17e57 --- /dev/null +++ b/src/entities/user/api/use-user-find-mutation.ts @@ -0,0 +1,29 @@ +import axios from 'axios'; +import { API_URL_USER } from '@/shared/api/api-url-user'; +import { resultify } from '@/shared/lib/resultify'; +import { CBDCAxiosError } from '@/shared/@types/error'; +import { + UserFindParams, + UserFindResponse +} from '../model/types'; +import { + useMutation, + UseMutationOptions +} from '@tanstack/react-query'; + +export const userFind = (params: UserFindParams) => { + return resultify( + axios.post(API_URL_USER.findUser(), params), + ); +}; + +export const useUserFindMutation = (options?: UseMutationOptions) => { + const mutation = useMutation({ + ...options, + mutationFn: (params: UserFindParams) => userFind(params), + }); + + return { + ...mutation, + }; +}; diff --git a/src/entities/user/model/types.ts b/src/entities/user/model/types.ts index 66d3a79..5a1e924 100644 --- a/src/entities/user/model/types.ts +++ b/src/entities/user/model/types.ts @@ -1,3 +1,8 @@ +import { + DefaulResponsePagination, + DefaultRequestPagination +} from '@/entities/common/model/types'; + export interface LoginParams { id: string; password: string; @@ -21,28 +26,60 @@ export interface LoginResponse { available2FAMethod?: Array; requires2FA?: boolean; }; + export interface UserInfo extends LoginResponse { } export interface UserParams { }; + +export interface UserListItem { + usrid: string; + idCl: string; + status: string; +} + +export interface UserFindResponse extends DefaulResponsePagination { + content: Array; +}; + +export interface UserFindParams { + mid: string; + page: DefaultRequestPagination; +}; + export interface UserExistsUseridParams { usrId: string; }; + +export interface UserFindAuthMethodParams { + mid: string; + usrid: string; + page?: DefaultRequestPagination; +}; + +export interface UserFindAuthMethodResponse { + status: boolean; + data: UserAuthMethodData; +}; + export interface UserExistsUseridResponse { exists: boolean; }; + export interface VerificationsItem { type: string; contact: string; }; + export interface UserCreateParams { userId: string; password: string; loginRange: string; verification: Array }; + export interface UserData { usrid: string; mid: string; @@ -85,5 +122,17 @@ export interface UserData { }; export interface UserCreateResponse { user: UserData; -}; +}; +export interface AuthMethodItem { + usrid: string; + systemAdminClassId: string; + authMethodType: string; + sequence: number; + content: string; +} + +export interface UserAuthMethodData { + emails: Array; + phones: Array; +} \ No newline at end of file diff --git a/src/pages/account/user/account-auth-page.tsx b/src/pages/account/user/account-auth-page.tsx index fdfa461..e905ea1 100644 --- a/src/pages/account/user/account-auth-page.tsx +++ b/src/pages/account/user/account-auth-page.tsx @@ -16,7 +16,7 @@ import { export const UserAccountAuthPage = () => { const { navigate } = useNavigate(); const location = useLocation(); - const [tid, setTid] = useState(location?.state.tid); + const { tid, mid, usrid } = location.state || {}; const [activeTab, setActiveTab] = useState(AccountUserTabKeys.AccountAuth); useSetHeaderTitle('사용자 설정'); @@ -34,13 +34,15 @@ export const UserAccountAuthPage = () => { <>
-
- +
diff --git a/src/pages/account/user/add-account-page.tsx b/src/pages/account/user/add-account-page.tsx index 822ad70..643d143 100644 --- a/src/pages/account/user/add-account-page.tsx +++ b/src/pages/account/user/add-account-page.tsx @@ -1,14 +1,331 @@ import { PATHS } from '@/shared/constants/paths'; import { useNavigate } from '@/shared/lib/hooks/use-navigate'; import { HeaderType } from '@/entities/common/model/types'; -import { +import { useSetHeaderTitle, useSetHeaderType, useSetFooterMode, useSetOnBack } from '@/widgets/sub-layout/use-sub-layout'; +import { useState, useEffect, useRef } from 'react'; +import { VerificationItem } from '@/entities/account/model/types'; +import { useUserCreateMutation } from '@/entities/user/api/use-user-create-mutation'; +import { useUserExistsUseridQuery } from '@/entities/user/api/use-user-exists-userid-query'; export const UserAddAccountPage = () => { const { navigate } = useNavigate(); + const { mutateAsync: userCreate, isPending } = useUserCreateMutation(); + + // 폼 상태 관리 + const [formData, setFormData] = useState({ + usrid: '', + password: '', + loginRange: 'MID' + }); + + // 에러 상태 관리 + const [errors, setErrors] = useState({ + usrid: '', + password: '' + }); + + // 사용자 ID 검증을 위한 상태 + const [shouldCheckUsrid, setShouldCheckUsrid] = useState(false); + const [isCheckingUsrid, setIsCheckingUsrid] = useState(false); + const debounceTimeout = useRef(null); + + // 이메일/전화번호 상태 관리 (기본 1개씩 빈 공란 배치) + const [newEmails, setNewEmails] = useState(['']); + const [newPhones, setNewPhones] = useState(['']); + const [editableEmailIndex, setEditableEmailIndex] = useState(0); + const [editablePhoneIndex, setEditablePhoneIndex] = useState(0); + const [readOnlyEmails, setReadOnlyEmails] = useState>(new Set()); + const [readOnlyPhones, setReadOnlyPhones] = useState>(new Set()); + + // 사용자 ID 존재 여부 확인 쿼리 + const { data: userExistsData, isLoading: isUserExistsLoading } = useUserExistsUseridQuery( + shouldCheckUsrid && formData.usrid.trim().length > 0 ? formData.usrid : '', + { + enabled: shouldCheckUsrid && formData.usrid.trim().length > 0, + } + ); + + // Handle user exists query result + useEffect(() => { + if (userExistsData && shouldCheckUsrid) { + setIsCheckingUsrid(false); + if (userExistsData.exists) { + setErrors(prev => ({ ...prev, usrid: '동일한 ID가 이미 존재합니다.' })); + } else { + setErrors(prev => ({ ...prev, usrid: '' })); + } + setShouldCheckUsrid(false); + } + }, [userExistsData, shouldCheckUsrid]); + + // 이메일/전화번호 관리 함수들 (user-login-auth-info-wrap 방식) + const handleAddEmail = () => { + // 현재 편집 중인 항목을 읽기전용으로 고정 + if (editableEmailIndex >= 0) { + setReadOnlyEmails(prev => new Set([...prev, editableEmailIndex])); + } + + // 새로운 편집 가능한 항목 추가 + setEditableEmailIndex(newEmails.length); + setNewEmails([...newEmails, '']); + }; + + const handleAddPhone = () => { + // 현재 편집 중인 항목을 읽기전용으로 고정 + if (editablePhoneIndex >= 0) { + setReadOnlyPhones(prev => new Set([...prev, editablePhoneIndex])); + } + + // 새로운 편집 가능한 항목 추가 + setEditablePhoneIndex(newPhones.length); + setNewPhones([...newPhones, '']); + }; + + const handleRemoveNewEmail = (index: number) => { + const updatedEmails = newEmails.filter((_, i) => i !== index); + setNewEmails(updatedEmails); + + // 읽기전용 인덱스들을 업데이트 + const updatedReadOnlyEmails = new Set(); + readOnlyEmails.forEach(readOnlyIndex => { + if (readOnlyIndex < index) { + updatedReadOnlyEmails.add(readOnlyIndex); + } else if (readOnlyIndex > index) { + updatedReadOnlyEmails.add(readOnlyIndex - 1); + } + }); + setReadOnlyEmails(updatedReadOnlyEmails); + + // 편집 가능한 인덱스 조정 + if (index === editableEmailIndex) { + setEditableEmailIndex(-1); + } else if (index < editableEmailIndex) { + setEditableEmailIndex(editableEmailIndex - 1); + } + }; + + const handleRemoveNewPhone = (index: number) => { + const updatedPhones = newPhones.filter((_, i) => i !== index); + setNewPhones(updatedPhones); + + // 읽기전용 인덱스들을 업데이트 + const updatedReadOnlyPhones = new Set(); + readOnlyPhones.forEach(readOnlyIndex => { + if (readOnlyIndex < index) { + updatedReadOnlyPhones.add(readOnlyIndex); + } else if (readOnlyIndex > index) { + updatedReadOnlyPhones.add(readOnlyIndex - 1); + } + }); + setReadOnlyPhones(updatedReadOnlyPhones); + + // 편집 가능한 인덱스 조정 + if (index === editablePhoneIndex) { + setEditablePhoneIndex(-1); + } else if (index < editablePhoneIndex) { + setEditablePhoneIndex(editablePhoneIndex - 1); + } + }; + + const handleNewEmailChange = (index: number, value: string) => { + const updated = [...newEmails]; + updated[index] = value; + setNewEmails(updated); + }; + + const handleNewPhoneChange = (index: number, value: string) => { + const updated = [...newPhones]; + updated[index] = value; + setNewPhones(updated); + }; + + // 폼 입력 핸들러 + const handleInputChange = (field: string, value: string) => { + setFormData(prev => ({ ...prev, [field]: value })); + + // 사용자 ID의 경우 디바운스 적용하여 자동 검증 + if (field === 'usrid') { + // 기존 타이머 클리어 + if (debounceTimeout.current) { + clearTimeout(debounceTimeout.current); + } + + // 에러 초기화 + setErrors(prev => ({ ...prev, usrid: '' })); + + // 값이 있으면 500ms 후 검증 실행 + if (value.trim().length > 0) { + setIsCheckingUsrid(true); + debounceTimeout.current = setTimeout(() => { + setShouldCheckUsrid(true); + }, 500); + } else { + setIsCheckingUsrid(false); + } + } else { + // 다른 필드는 에러만 초기화 + if (errors[field as keyof typeof errors]) { + setErrors(prev => ({ ...prev, [field]: '' })); + } + } + }; + + // 컴포넌트 언마운트 시 타이머 정리 + useEffect(() => { + return () => { + if (debounceTimeout.current) { + clearTimeout(debounceTimeout.current); + } + }; + }, []); + + // 검증 함수들 + const isValidEmail = (email: string) => { + const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; + return emailRegex.test(email); + }; + + const isValidPhone = (phone: string) => { + const phoneRegex = /^010\d{8}$/; + return phoneRegex.test(phone); + }; + + // 이메일 추가 버튼 활성화 조건 + const isEmailAddButtonEnabled = () => { + if (newEmails.length === 0) return true; + + const lastEmailIndex = newEmails.length - 1; + const lastEmail = newEmails[lastEmailIndex]; + + return lastEmailIndex >= editableEmailIndex && + lastEmail && + lastEmail.trim() && + isValidEmail(lastEmail) && + !hasDuplicateEmail(); + }; + + // 전화번호 추가 버튼 활성화 조건 + const isPhoneAddButtonEnabled = () => { + if (newPhones.length === 0) return true; + + const lastPhoneIndex = newPhones.length - 1; + const lastPhone = newPhones[lastPhoneIndex]; + + return lastPhoneIndex >= editablePhoneIndex && + lastPhone && + lastPhone.trim() && + isValidPhone(lastPhone) && + !hasDuplicatePhone(); + }; + + // 중복 검증 + const hasDuplicateEmail = () => { + const validEmails = newEmails.filter(e => e.trim()); + const uniqueEmails = new Set(validEmails); + return validEmails.length !== uniqueEmails.size; + }; + + const hasDuplicatePhone = () => { + const validPhones = newPhones.filter(p => p.trim()); + const uniquePhones = new Set(validPhones); + return validPhones.length !== uniquePhones.size; + }; + + // 삭제 버튼 활성화 조건 + const isDeleteButtonEnabled = () => { + const totalCount = newEmails.length + newPhones.length; + return totalCount > 1; + }; + + // 폼 검증 + const validateForm = () => { + const newErrors = { usrid: '', password: '' }; + let isValid = true; + + // 사용자 ID 검증 + if (!formData.usrid.trim()) { + newErrors.usrid = 'ID를 입력해 주세요'; + isValid = false; + } + + // 비밀번호 검증 + if (!formData.password.trim()) { + newErrors.password = '비밀번호를 입력해 주세요'; + isValid = false; + } else if (formData.password.length < 8) { + newErrors.password = '8자리 이상 입력해 주세요'; + isValid = false; + } + + // 이메일/전화번호 중 하나는 필수 + const validEmails = newEmails.filter(email => email.trim() && isValidEmail(email)); + const validPhones = newPhones.filter(phone => phone.trim() && isValidPhone(phone)); + + if (validEmails.length === 0 && validPhones.length === 0) { + // 최소 하나의 유효한 연락처가 필요 + isValid = false; + } + + // 중복이 있으면 비활성화 + if (hasDuplicateEmail() || hasDuplicatePhone()) { + isValid = false; + } + + setErrors(newErrors); + return isValid; + }; + + // 저장 핸들러 + const handleSave = async () => { + if (!validateForm()) { + return; + } + + try { + // verifications 배열 생성 + const verifications: VerificationItem[] = []; + + newEmails.forEach(email => { + if (email.trim() && isValidEmail(email)) { + verifications.push({ type: 'EMAIL', contact: email }); + } + }); + + newPhones.forEach(phone => { + if (phone.trim() && isValidPhone(phone)) { + verifications.push({ type: 'PHONE', contact: phone }); + } + }); + + const request = { + userId: formData.usrid, + password: formData.password, + loginRange: formData.loginRange, + verification: verifications + }; + + const response = await userCreate(request); + + if (response.status) { + // 성공 시 사용자 관리 페이지로 이동 + navigate(PATHS.account.user.manage); + } else if (response.error) { + // 에러 처리 + if (response.error.errKey === 'USER_DUPLICATE') { + setErrors(prev => ({ ...prev, usrid: '동일한 ID가 이미 존재합니다.' })); + } else { + // 기타 에러 처리 + console.error('User creation failed:', response.error.message); + } + } + } catch (error) { + console.error('User creation error:', error); + } + }; useSetHeaderTitle('사용자 추가'); useSetHeaderType(HeaderType.LeftArrow); @@ -26,28 +343,54 @@ export const UserAddAccountPage = () => {
사용자ID *
- +
+ handleInputChange('usrid', e.target.value)} + /> + {isCheckingUsrid && ( +
+ 확인 중... +
+ )} +
-
동일한 ID가 이미 존재합니다.
+ {errors.usrid &&
{errors.usrid}
} + {!errors.usrid && formData.usrid && userExistsData && !userExistsData.exists && ( +
사용 가능한 ID입니다.
+ )}
비밀번호 *
- handleInputChange('password', e.target.value)} />
-
(오류 결과 메시지)
+ {errors.password &&
{errors.password}
}
로그인 범위
- handleInputChange('loginRange', e.target.value)} + > + +
@@ -61,55 +404,77 @@ export const UserAddAccountPage = () => {
이메일 주소
-
-
- - -
+ {newEmails.map((email, index) => ( +
+ handleNewEmailChange(index, e.target.value)} + readOnly={readOnlyEmails.has(index) || index !== editableEmailIndex} + /> + +
+ ))}
휴대폰 번호
-
-
- - -
+ {newPhones.map((phone, index) => ( +
+ handleNewPhoneChange(index, e.target.value)} + readOnly={readOnlyPhones.has(index) || index !== editablePhoneIndex} + /> + +
+ ))}
- + type="button" + onClick={handleSave} + disabled={isPending} + > + {isPending ? '저장 중...' : '저장'} +
diff --git a/src/pages/account/user/login-auth-info-page.tsx b/src/pages/account/user/login-auth-info-page.tsx index dc88900..5e376ea 100644 --- a/src/pages/account/user/login-auth-info-page.tsx +++ b/src/pages/account/user/login-auth-info-page.tsx @@ -1,12 +1,12 @@ -import { useEffect, useState } from 'react'; -import { useLocation } from 'react-router'; +import { useState } from 'react'; +import { useLocation } from 'react-router-dom'; import { PATHS } from '@/shared/constants/paths'; import { useNavigate } from '@/shared/lib/hooks/use-navigate'; import { AccountUserTab } from '@/entities/account/ui/account-user-tab'; import { UserLoginAuthInfoWrap } from '@/entities/account/ui/user-login-auth-info-wrap'; import { AccountUserTabKeys } from '@/entities/account/model/types'; import { HeaderType } from '@/entities/common/model/types'; -import { +import { useSetHeaderTitle, useSetHeaderType, useSetFooterMode, @@ -14,9 +14,9 @@ import { } from '@/widgets/sub-layout/use-sub-layout'; export const UserLoginAuthInfoPage = () => { - const { navigate } = useNavigate(); const location = useLocation(); - const [tid, setTid] = useState(location?.state.tid); + const { mid, usrid, tid } = location.state || {}; + const { navigate } = useNavigate(); const [activeTab, setActiveTab] = useState(AccountUserTabKeys.LoginAuthInfo); useSetHeaderTitle('사용자 설정'); @@ -26,21 +26,36 @@ export const UserLoginAuthInfoPage = () => { navigate(PATHS.account.user.manage); }); - useEffect(() => { - console.log('tid : ', tid); - }, []); + // const { mutateAsync: userFindAuthMethod } = useUserFindAuthMethodMutation(); + + // const callUserFindAuthMethod = (mid: string, usrid: string) => { + // let parms: UserFindAuthMethodParams = { + // mid: mid, + // usrid: usrid + // } + // userFindAuthMethod(params).then((rs: UserFindAuthMethodResponse) => { + // console.log("User Find Auth Method: ", rs) + // }); + // } + + // useEffect(() => { + // callUserFindAuthMethod(mid, usrid); + // }, [mid, usrid]); return ( <>
-
- +
diff --git a/src/pages/account/user/menu-auth-page.tsx b/src/pages/account/user/menu-auth-page.tsx index cd0ef0a..1d45858 100644 --- a/src/pages/account/user/menu-auth-page.tsx +++ b/src/pages/account/user/menu-auth-page.tsx @@ -12,31 +12,23 @@ import { export const UserMenuAuthPage = () => { const { navigate } = useNavigate(); - const location = useLocation(); - const [tid, setTid] = useState(location?.state.tid); - const [menuId, setMenuId] = useState(location?.state.menuId); useSetHeaderTitle('사용자 설정'); useSetHeaderType(HeaderType.LeftArrow); useSetFooterMode(true); useSetOnBack(() => { - navigate(PATHS.account.user.accountAuth, { - state: { - tid: tid - } - }); + navigate(PATHS.account.user.accountAuth); }); useEffect(() => { - console.log('tid : ', tid); - console.log('menuId : ', menuId); + }); return ( <>
-
+
메뉴별 사용 권한을 설정해 주세요.
선택한 권한에 따라 기능 이용이 제한됩니다.
diff --git a/src/shared/api/api-url-user.ts b/src/shared/api/api-url-user.ts index f2750f0..572860b 100644 --- a/src/shared/api/api-url-user.ts +++ b/src/shared/api/api-url-user.ts @@ -4,22 +4,40 @@ import { } from './../constants/url'; export const API_URL_USER = { - allUserList: () => { - return `${API_BASE_URL}/api/v1/${API_URL_KEY}/user/all/users`; + userExistsUserid: (usrid: string) => { + return `${API_BASE_URL}/api/v1/${API_URL_KEY}/user/exists/${usrid}`; }, - createUser: () => { + userCreate: () => { + // 사용자 추가 return `${API_BASE_URL}/api/v1/${API_URL_KEY}/user/create`; }, - deleteUser: () => { - return `${API_BASE_URL}/api/v1/${API_URL_KEY}/user/delete`; - }, - updateUser: () => { - return `${API_BASE_URL}/api/v1/${API_URL_KEY}/user/update`; - }, - userDetail: () => { - return `${API_BASE_URL}/api/v1/${API_URL_KEY}/user/detail`; + findUser: () => { + return `${API_BASE_URL}/api/v1/${API_URL_KEY}/user/find`; }, existsUserid: () => { return `${API_BASE_URL}/api/v1/${API_URL_KEY}/user/exists/userid`; }, + deleteUser: () => { + return `${API_BASE_URL}/api/v1/${API_URL_KEY}/user/delete`; + }, + createUser: () => { + return `${API_BASE_URL}/api/v1/${API_URL_KEY}/user/create`; + }, + findAuthMethod: () => { + return `${API_BASE_URL}/api/v1/${API_URL_KEY}/user/tfa/find`; + }, + modifyAuthMethod: () => { + return `${API_BASE_URL}/api/v1/${API_URL_KEY}/user/tfa/modify`; + }, + // allUserList: () => { + // return `${API_BASE_URL}/api/v1/${API_URL_KEY}/user/all/users`; + // }, + + // updateUser: () => { + // return `${API_BASE_URL}/api/v1/${API_URL_KEY}/user/update`; + // }, + // userDetail: () => { + // return `${API_BASE_URL}/api/v1/${API_URL_KEY}/user/detail`; + // }, + } \ No newline at end of file diff --git a/src/shared/ui/assets/css/style.css b/src/shared/ui/assets/css/style.css index cdbf854..53f7e11 100644 --- a/src/shared/ui/assets/css/style.css +++ b/src/shared/ui/assets/css/style.css @@ -4422,6 +4422,18 @@ ul.txn-amount-detail li span:last-child { background: #F5F5F5 url('../images/ico_del_minus.svg') no-repeat center center; } +.icon-btn.check { + width: 36px; + height: 36px; + border-radius: 6px; + background: #F5F5F5 url('../images/ico_alone_check.svg') no-repeat center center; +} + +.button-group { + display: flex; + gap: 8px; +} + .notice-bar { padding: 14px 16px; background: #F4F8FF;