11'use client' ;
22
3- import React , { useState , useEffect , useRef } from 'react' ;
3+ import React , { useState , useEffect , useRef , useCallback } from 'react' ;
44import Link from 'next/link' ;
55import { useRouter } from 'next/navigation' ;
66import { Button } from '@/components/ui/button' ;
@@ -11,25 +11,64 @@ import Modal from '@/components/Modal';
1111import Cookies from 'js-cookie' ;
1212
1313export default function Page2 ( ) {
14- const { email } = useFormStore ( ) ;
14+ const { id , setTeamId , setMemberIds } = useFormStore ( ) ;
1515 const router = useRouter ( ) ;
16- const [ inputs , setInputs ] = useState < string [ ] > ( ( ) => {
17- const initialInputs = Array ( 5 ) . fill ( '' ) ;
18- if ( email ) {
19- initialInputs [ 0 ] = email ;
20- }
16+ const [ inputs , setInputs ] = useState < Array < { id : string ; displayName : string } > > ( ( ) => {
17+ const initialInputs = Array ( 5 ) . fill ( { id : '' , displayName : '' } ) ;
2118 return initialInputs ;
2219 } ) ;
2320 const [ showModal , setShowModal ] = useState ( false ) ;
2421 const timeoutRef = useRef < NodeJS . Timeout | null > ( null ) ; // Add timeoutRef
2522
23+ const fetchUserById = useCallback ( async ( index : number , userId : string ) => {
24+ if ( ! userId ) return ; // Don't fetch if ID is empty
25+
26+ // Prevent adding self as a team member
27+ if ( index !== 0 && id && Number ( userId ) === Number ( id ) ) { // Check only for other team members, not self
28+ alert ( `자기 자신(${ userId } )을 팀원으로 추가할 수 없습니다.` ) ;
29+ const newInputs = [ ...inputs ] ;
30+ newInputs [ index ] = { id : '' , displayName : '' } ; // Clear the input field
31+ setInputs ( newInputs ) ;
32+ return ;
33+ }
34+
35+ try {
36+ const response = await fetch ( `/api/v1/users/${ userId } ` ) ;
37+ if ( ! response . ok ) {
38+ throw new Error ( `HTTP error! status: ${ response . status } ` ) ;
39+ }
40+ const userData = await response . json ( ) ;
41+ // Assuming the API returns an object with a 'data' field which is the display name
42+ const newInputs = [ ...inputs ] ;
43+ newInputs [ index ] = { id : userId , displayName : userData . data || userId } ; // Store both id and display name
44+ setInputs ( newInputs ) ;
45+ } catch ( error : unknown ) {
46+ let errorMessage = '알 수 없는 오류가 발생했습니다.' ;
47+ if ( error instanceof Error ) {
48+ errorMessage = error . message ;
49+ }
50+ console . error ( `Error fetching user ${ userId } :` , errorMessage ) ;
51+ const newInputs = [ ...inputs ] ;
52+ newInputs [ index ] = { id : userId , displayName : userId } ; // Fallback to just ID if fetch fails
53+ setInputs ( newInputs ) ;
54+ // Optionally, display an error message to the user
55+ }
56+ } , [ id , inputs ] ) ;
57+
2658 useEffect ( ( ) => {
2759 const hasSeenModal = Cookies . get ( 'doNotShowModalPage2' ) ;
2860 if ( ! hasSeenModal ) {
2961 setShowModal ( true ) ;
3062 }
3163 } , [ ] ) ;
3264
65+ // Effect to pre-fill the first input if ID is available
66+ useEffect ( ( ) => {
67+ if ( id && inputs [ 0 ] . id === '' ) { // Only fetch if ID exists and input is empty
68+ fetchUserById ( 0 , id ) ;
69+ }
70+ } , [ id , fetchUserById , inputs ] ) ; // Rerun when id changes
71+
3372 const handleConfirm = ( ) => {
3473 setShowModal ( false ) ;
3574 } ;
@@ -41,7 +80,7 @@ export default function Page2() {
4180
4281 const handleInputChange = ( index : number , value : string ) => {
4382 const newInputs = [ ...inputs ] ;
44- newInputs [ index ] = value ;
83+ newInputs [ index ] = { id : value , displayName : value } ; // Temporarily set display name to ID
4584 setInputs ( newInputs ) ;
4685
4786 // Clear any existing timeout
@@ -55,28 +94,53 @@ export default function Page2() {
5594 } , 3000 ) ;
5695 } ;
5796
58- const fetchUserById = async ( index : number , id : string ) => {
59- if ( ! id ) return ; // Don't fetch if ID is empty
97+ const handleSolveProblem = async ( ) => {
98+ // Step 1: Check if all inputs are filled
99+ const allInputsFilled = inputs . every ( input => input . id !== '' ) ;
100+ if ( ! allInputsFilled ) {
101+ alert ( '모든 팀원 ID를 채워주세요.' ) ;
102+ return ;
103+ }
104+
105+ // Step 2: Construct the JSON body
106+ const myId = id ; // id from useFormStore()
107+ const memberIds = inputs . slice ( 1 ) . map ( input => input . id ) ; // Exclude the first input (my_id)
108+
109+ const requestBody = {
110+ my_id : myId ,
111+ member_ids : memberIds ,
112+ } ;
113+
114+ console . log ( 'Request Body:' , requestBody ) ;
115+
116+ // Step 3: Make the POST request
60117 try {
61- const response = await fetch ( `${ process . env . APP_HOST } /v1/users/${ id } ` ) ;
118+ const response = await fetch ( '/api/v1/teams/create' , {
119+ method : 'POST' ,
120+ headers : {
121+ 'Content-Type' : 'application/json' ,
122+ } ,
123+ body : JSON . stringify ( requestBody ) ,
124+ } ) ;
125+
62126 if ( ! response . ok ) {
63- throw new Error ( `HTTP error! status: ${ response . status } ` ) ;
127+ const errorData = await response . json ( ) ;
128+ throw new Error ( `HTTP error! status: ${ response . status } , message: ${ errorData . detail || response . statusText } ` ) ;
64129 }
65- const userData = await response . json ( ) ;
66- // Assuming the API returns an object with a 'detail' field as per user's confirmation
67- const newInputs = [ ...inputs ] ;
68- newInputs [ index ] = userData . detail || id ; // Use fetched detail, or original ID if not found
69- setInputs ( newInputs ) ;
70- } catch ( error ) {
71- console . error ( `Error fetching user ${ id } :` , error ) ;
72- // Optionally, display an error message to the user
73- }
74- } ;
75130
76- const handleSolveProblem = ( ) => {
77- console . log ( 'Inputs:' , inputs ) ;
78- // You can add logic here to process the inputs before navigating
79- router . push ( '/page3' ) ;
131+ const responseData = await response . json ( ) ;
132+ console . log ( 'Team creation successful:' , responseData ) ;
133+ setTeamId ( responseData . team_id ) ; // Save team_id to store
134+ setMemberIds ( responseData . members_ids ) ; // Save members_ids to store
135+ router . push ( '/page3' ) ; // Navigate to page3 on success
136+ } catch ( error : unknown ) {
137+ console . error ( 'Error creating team:' , error ) ;
138+ let errorMessage = '알 수 없는 오류가 발생했습니다.' ;
139+ if ( error instanceof Error ) {
140+ errorMessage = error . message ;
141+ }
142+ alert ( `팀 생성에 실패했습니다: ${ errorMessage } ` ) ;
143+ }
80144 } ;
81145
82146 return (
@@ -95,7 +159,6 @@ export default function Page2() {
95159 onDoNotShowAgain = { handleDoNotShowAgain }
96160 isOpen = { showModal }
97161 />
98- { email && < p className = "mt-4" > 이메일: < strong > { email } </ strong > </ p > }
99162
100163 < div className = "mt-8 space-y-4" >
101164 { [ ...Array ( 5 ) ] . map ( ( _ , index ) => (
@@ -106,13 +169,13 @@ export default function Page2() {
106169 id = { `team-id-${ index } ` }
107170 type = "id"
108171 placeholder = { `팀원 ${ index + 1 } 의 번호` }
109- value = { inputs [ index ] }
172+ value = { inputs [ index ] . displayName }
110173 onChange = { ( e ) => handleInputChange ( index , e . target . value ) }
111- onBlur = { ( e ) => {
174+ onBlur = { ( ) => {
112175 if ( timeoutRef . current ) {
113176 clearTimeout ( timeoutRef . current ) ; // Clear any pending debounce
114177 }
115- fetchUserById ( index , e . target . value ) ; // Fetch immediately on blur
178+ fetchUserById ( index , inputs [ index ] . id ) ; // Fetch immediately on blur using the stored ID
116179 } }
117180 disabled = { index === 0 }
118181 />
0 commit comments