Skip to content

Commit

Permalink
Merge pull request #171 from Dindb-dong/feat/118/uploadFiles
Browse files Browse the repository at this point in the history
#118: fix: uploadFiles(but have one error), refactor: InfoPage, add: MarketType
  • Loading branch information
kimheonningg authored Jan 5, 2025
2 parents 05b5e60 + ce60723 commit 4066acf
Show file tree
Hide file tree
Showing 14 changed files with 269 additions and 116 deletions.
2 changes: 1 addition & 1 deletion src/common/FileBox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ const SelectView = styled.View`
margin-bottom: 5px;
`;

const FileBox = ({ data, setData, max }: FileBoxProps) => {
const FileBox = ({ data = [], setData, max }: FileBoxProps) => {
const handleFileDelete = (index: number) => {
const newData = data.filter((v, i) => i !== index);
setData?.(newData);
Expand Down
4 changes: 2 additions & 2 deletions src/common/Footer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ const Footer = () => {
<BottomButton
value={'주문서 보내기'}
pressed={pressed}
onPress={() => {}}
style={{ width: '95%' }}
onPress={() => { }}
style={{ width: '90%' }}
/>
</FooterContainer>
</View>
Expand Down
2 changes: 1 addition & 1 deletion src/components/Auth/Reformer/CareerModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -379,7 +379,7 @@ export default function CareerModal({
</Caption11M>
</View>
<FileBox
data={form.field[index].file}
data={form.field[index]?.file || []} // `undefined`이면 빈 배열로 전달
setData={r => {
handleContentChange(r, 'file');
}}
Expand Down
62 changes: 40 additions & 22 deletions src/components/Auth/Reformer/ReformFormCareer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -114,12 +114,12 @@ export default function ReformCareer({ fix, form, setForm }: ReformProps) {
// `form`이 초기화되었는지 확인하는 useEffect
useEffect(() => {
// form이 완전히 초기화되었는지 확인
if (!isFormInitialized && form.link && form.region) {
memorizedForm.current = { ...form }; // 초기 form 상태 저장
if (!isFormInitialized && form.link && form.region && form.field) {
memorizedForm.current = JSON.parse(JSON.stringify(form)); // 깊은 복사로 저장
setIsFormInitialized(true); // 초기화 완료 표시
console.log("Initial form state saved in memorizedForm:", memorizedForm.current);
}
}, [form, isFormInitialized]);
}, [form.picture, isFormInitialized]);

const handleAddCareer = () => { // 빈 필드 생성
const newIndex = form.field.length;
Expand Down Expand Up @@ -183,9 +183,25 @@ export default function ReformCareer({ fix, form, setForm }: ReformProps) {
nickname: updatedForm.nickname,
introduce: updatedForm.introduce,
}
try {
try { // TODO: 마켓 정보도 수정하기: 소개글, 링크, 닉네임 등
const response = await request.put(`/api/user`, params, headers);
if (response && response.status === 200) {
try {
const marketUUID = await getMarketUUID();
const params_ = {
market_name: updatedForm.nickname,
market_address: updatedForm.link,
market_introduce: updatedForm.introduce,
}
const response2 = await request.put(`/api/market/${marketUUID}`, params_, headers)
if (response2 && response2.status === 200) {
console.log('마켓 정보 업데이트 성공: ', updatedForm.nickname, updatedForm.link, updatedForm.introduce);
} else {
console.log('마켓 정보 업데이트 실패 ');
}
} catch (error) {
console.log(error);
}
console.log('닉네임, 소개글 업데이트 완료!');
} else {
console.log('닉네임, 소개글 업데이트 실패:', response)
Expand All @@ -211,7 +227,7 @@ export default function ReformCareer({ fix, form, setForm }: ReformProps) {
);
const hasChanges = JSON.stringify(updatedEducationFields) !== JSON.stringify(initialEducationFields);
const hasAdded = !initialEducationFields || initialEducationFields.length === 0; // 이전에 없었을 때

console.log(JSON.stringify(updatedEducationFields), '///', JSON.stringify(initialEducationFields));
if (hasAdded && hasChanges) { // 새롭게 추가됐을 때
for (const edu of updatedEducationFields) {
const response3 = await request.post(
Expand Down Expand Up @@ -263,7 +279,7 @@ export default function ReformCareer({ fix, form, setForm }: ReformProps) {
console.log("학력 데이터 추가 실패:", response3.status, response3.data);
}
}
console.log("새 학력 데이터 등록 완료");

} catch (error) {
console.error("Error updating education data:", error);
Alert.alert("학력 정보 업데이트 중 오류가 발생했습니다.");
Expand Down Expand Up @@ -589,7 +605,7 @@ export default function ReformCareer({ fix, form, setForm }: ReformProps) {
try {
const response = await request.put(`/api/user/reformer`, params, headers);
if (response && response.status === 200) {
console.log('지역, 업데이트 성공:', response.data);
console.log('지역, 링크 업데이트 성공:', updatedForm.link, updatedForm.region);
navigation.goBack();
} else {
Alert.alert('지역, 링크 업데이트 실패');
Expand Down Expand Up @@ -745,7 +761,6 @@ export default function ReformCareer({ fix, form, setForm }: ReformProps) {
.map((data) => uploadFiles(data.type, data)); // 필터링된 데이터로 uploadFiles 호출

await Promise.all(uploadPromises);
console.log('모든 파일 업로드 완료');
if (fix) { // 수정하러 들어왔을 경우
Alert.alert(
"프로필 수정이 완료되었습니다.",
Expand Down Expand Up @@ -793,7 +808,7 @@ export default function ReformCareer({ fix, form, setForm }: ReformProps) {
const uuidKey = `${engType}_uuid`; // 각 타입에 따른 UUID 키 생성
// data.file 배열 처리
data.file.forEach((file: any) => {
formData.append('document', {
formData.append('proof_document', {
uri: file.uri, // 파일의 URI
type: file.type || 'application/pdf',
name: file.name || 'document.pdf', // 파일 이름
Expand Down Expand Up @@ -872,7 +887,7 @@ export default function ReformCareer({ fix, form, setForm }: ReformProps) {
return { ...prev, picture: profileImage }
})
} else {
console.log('Failed to fetch user data:', response);
console.log('유저 프로필 이미지 패치 실패:', response);
}
} catch (error) {
console.error('Error fetching user data:', error);
Expand All @@ -890,6 +905,9 @@ export default function ReformCareer({ fix, form, setForm }: ReformProps) {
setForm(prev => {
return { ...prev, introduce: response.data.introduce }
})
console.log('자기소개 패치:', response.data.introduce)
} else {
console.log('자기소개 패치 실패:', response);
}
} catch (err) {
console.error(err);
Expand All @@ -902,11 +920,10 @@ export default function ReformCareer({ fix, form, setForm }: ReformProps) {
Authorization: `Bearer ${accessToken}`
};
try { // 링크, 지역
console.log('리폼러 데이터 가져오기');
const response = await request.get(`/api/user/reformer`, {}, headers);
if (response && response.status === 200) {
const data = response.data;
console.log('테스트', data);
console.log('패치한 리폼러 데이터:', data);
// 각 항목을 form.field 형식에 맞게 변환하여 추가
const newFields: any[] = [];
// 학력 데이터 추가
Expand Down Expand Up @@ -1038,16 +1055,17 @@ export default function ReformCareer({ fix, form, setForm }: ReformProps) {
onPress={!fix ? handleSubmit : handleFix}
style={{ width: '90%', alignSelf: 'center', marginBottom: 10 }}
/>
{<View>
<BottomButton
value="check"
pressed={false}
onPress={() => {
console.log(form);
}}
style={{ width: '90%', alignSelf: 'center', marginBottom: 10 }}
/>
</View>}
{fix && // TODO: 이거 배포 전에는 삭제하기! (디버깅용)
<View>
<BottomButton
value="check"
pressed={false}
onPress={() => {
console.log(form);
}}
style={{ width: '90%', alignSelf: 'center', marginBottom: 10 }}
/>
</View>}
</View>
{careerIndex >= 0 && (
<CareerModal
Expand Down
103 changes: 78 additions & 25 deletions src/components/Auth/Reformer/ReformerMyPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import {
import { Tabs, MaterialTabBar } from 'react-native-collapsible-tab-view';
import { BLACK } from '../../../styles/GlobalColor.tsx';
import ServicePage from '../../../components/Home/Market/ServicePage';
import InfoPage from '../../../components/Home/Market/InfoPage.tsx';
import InfoPage, { MarketType } from '../../../components/Home/Market/InfoPage.tsx';
import ScrollTopButton from '../../../common/ScrollTopButton.tsx';
import { LoginContext } from '../../../common/Context';
import DetailScreenHeader from '../../../components/Home/components/DetailScreenHeader.tsx';
Expand All @@ -31,6 +31,7 @@ import { CommonActions, useFocusEffect } from '@react-navigation/native';
import { Title20B } from '../../../styles/GlobalText.tsx';
import DeleteModal from '../DeleteModal.tsx';
import { MarketResponseType } from '../../Home/Market/MarketTabView.tsx';
import { AwardsType, CareerType, CertifiType, EducType, FreeType, ReformerResponseType } from '../../../types/UserTypes.ts';

export const ReformerMyPageScreen = ({ navigation, route }: MypageStackProps) => {

Expand Down Expand Up @@ -105,20 +106,47 @@ export const ReformerMyPageScreen = ({ navigation, route }: MypageStackProps) =>
const [activeTab, setActiveTab] = useState('profile');
const scrollRef = useRef<ScrollView | null>(null);
const defaultMarketResponseData: MarketResponseType = {
market_address: '',
market_introduce: '정보 없음',
market_name: '정보 없음',
market_thumbnail: '',
market_address: '', // 링크
market_introduce: '정보 없음', // 자기소개
market_name: '정보 없음', // 닉네임
market_thumbnail: '', // 왜 안 나오지...? 원래없나
market_uuid: '',
};
const defaultReformerResponseData: ReformerResponseType = {
nickname: '', // 닉네임
reformer_link: '', // 자기소개
reformer_area: '', // 활동지역
education: [], // 학력
certification: [], // 자격증
awards: [], // 공모전
career: [], // 경력
freelancer: [] // 외주
}


const [marketData, setMarketData] = useState<MarketResponseType>(
const [marketResponseData, setMarketResponseData] = useState<MarketResponseType>(
defaultMarketResponseData,
);
const [reformerResponseData, setReformerResponseData] = useState<ReformerResponseType>(defaultReformerResponseData,);
const [marketData, setMarketData] = useState<MarketType>({
reformer_link: '', // 링크
market_introduce: '정보 없음', // 자기소개
market_name: '정보 없음', // 닉네임
market_thumbnail: '', // 왜 안 나오지...? 원래없나
market_uuid: '',
reformer_area: '??',
})
const fetchMarketData = (data: Partial<MarketType>) => {

setMarketData((prev) => ({
...prev, // 기존 데이터를 유지
...data, // 새로운 데이터로 업데이트
}));

};

const request = Request();
const { isLogin, setLogin } = useContext(LoginContext);
const [market_uuid, setMarket_uuid] = useState<any>('');
const [reformerInfo, setReformerInfo] = useState({
nickname: route.params?.nickname || '',
backgroundphoto:
Expand Down Expand Up @@ -165,14 +193,52 @@ export const ReformerMyPageScreen = ({ navigation, route }: MypageStackProps) =>
backgroundphoto:
'https://image.made-in-china.com/2f0j00efRbSJMtHgqG/Denim-Bag-Youth-Fashion-Casual-Small-Mini-Square-Ladies-Shoulder-Bag-Women-Wash-Bags.webp',
picture: profileImage,
introduce:
introduce:// 근데 이거 안씀
response.data.introduce ||
'나는야 업씨러 이하늘 환경을 사랑하지요 눈누난나',
role: 'reformer',
});
setNickname(response.data.nickname);
const UUID = await getMarketUUID();
setMarket_uuid(UUID);
// setNickname(response.data.nickname);
try { // 본인 마켓 정보 가져오기: 링크, 자기소개, 닉네임, uuid
const response2 = await request.get(`/api/market`, {}, headers);
if (response2 && response2.status === 200) {
const marketResult: MarketResponseType = response2.data;
setMarketResponseData(marketResult);
fetchMarketData({
market_introduce: marketResult.market_introduce,
market_name: marketResult.market_name,
market_thumbnail: marketResult.market_thumbnail || '', // 기본값 유지
market_uuid: marketResult.market_uuid,
});
console.log('마켓 정보 가져오기 성공', response2.data);
try { // reformer 정보 가져오기: 활동지역, 경력사항들
const response3 = await request.get(`/api/user/reformer`, {}, headers);
if (response3 && response3.status === 200) {
const reformerResult: ReformerResponseType = response3.data;
setReformerResponseData(reformerResult);
fetchMarketData({
reformer_link: reformerResult.reformer_link,
reformer_area: reformerResult.reformer_area,
education: reformerResult.education,
certification: reformerResult.certification,
awards: reformerResult.awards,
career: reformerResult.career,
freelancer: reformerResult.freelancer,
});
console.log('리폼러 정보 가져오기 성공 ', response3.data);
console.log('마켓 최종 합산 데이터:', marketData);
} else {
console.log(response3);
}
} catch (error) {
console.log(error);
}
} else {
console.log('마켓 정보 가져오기에 실패했습니다.', response2);
}
} catch (error) {
console.log(error);
}
return response.data;
} else {
console.log('Failed to fetch user data:', response);
Expand Down Expand Up @@ -356,24 +422,11 @@ export const ReformerMyPageScreen = ({ navigation, route }: MypageStackProps) =>
<Tabs.Tab name="프로필" key="profile">
{/* FIXME */}
<InfoPage
marketData={{
market_address: '',
market_introduce: '정보 없음',
market_name: '정보 없음',
market_thumbnail: '',
market_uuid: '',
}}
marketData={marketData}
/>
</Tabs.Tab>
<Tabs.Tab name="서비스" key="service">
<View>

{/*<TouchableOpacity
style={styles.saveButton}
onPress={() => navigation.navigate('TempStorage')}>
<Text style={styles.saveButtonText}>임시저장 (5)</Text>
{/*수정 필요
</TouchableOpacity>*/}
<ServicePage scrollViewRef={scrollRef} navigation={navigation} />
<ScrollTopButton scrollViewRef={scrollRef} />
</View>
Expand Down
30 changes: 20 additions & 10 deletions src/components/Home/Market/DetailBox2.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// DetailBox component without the tab
import { View, Text, StyleSheet } from 'react-native';
import { View, Text, StyleSheet, Image } from 'react-native';
import RenderHTML from 'react-native-render-html';
import { MaterialDetail, ServiceDetailOption } from './Service';

Expand Down Expand Up @@ -51,6 +51,7 @@ const ContentBox = ({ content }: { content: string }) => {
maxWidth: 370,
}}
/>
{/* TODO: 서비스 상세에 있는 사진들 받아오기 */}
</View>
</View>
</View>
Expand Down Expand Up @@ -101,15 +102,24 @@ const OptionBox = ({ list }: { list: ServiceDetailOption[] }) => {
+{option.option_price}
</Text>
</View>
<View
style={{
backgroundColor: '#f1f1f1',
padding: 14,
borderRadius: 8,
}}>
<Text style={TextStyles.optionContentLabel}>
{option.option_content}
</Text>
<View style={{
flexDirection: 'row',
}}>
<View
style={{
backgroundColor: '#f1f1f1',
padding: 14,
borderRadius: 8,
flexGrow: 1,
}}>
<Text style={TextStyles.optionContentLabel}>
{option.option_content}
</Text>
</View>
<Image
style={{ width: 50, height: 50, flexGrow: 0.2 }}
source={{ uri: option.option_photoUri }}
/>
</View>
</View>
);
Expand Down
Loading

0 comments on commit 4066acf

Please sign in to comment.