Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[FE][:wrench: FIX]: 프로필 업데이트 구현 및 테스트 + 일기 수정 경로 추가 및 데이터 로딩 테스트 완료 +… #102

Merged
merged 1 commit into from
Aug 7, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/main/frontend/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@ function App() {
<Route path='/diary' element={<DiaryLayout />}>
<Route index element={<Diary />} />
<Route path=':id' element={<Detail />} />
<Route path='write' element={<WriteForm />} />
<Route path='form' element={<WriteForm />} />
<Route path='form/:id' element={<WriteForm />} />
<Route path='graph' element={<Graph />} />
<Route path='recommend' element={<Recommend />} />
<Route path='cart' element={<Cart />} />
Expand Down
15 changes: 14 additions & 1 deletion src/main/frontend/src/apis/diary/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,13 @@ const insertDiary = (formData: FormData) => {
.catch(handleReceiveError);
};

const updateDiary = (formData: FormData) => {
return axios
.put("/api/diary", formData)
.then(handleReceiveData)
.catch(handleReceiveError);
};

const findAllDiary = () => {
return axios
.get("/api/diaries")
Expand All @@ -30,4 +37,10 @@ const deleteDiaryById = (id: string) => {
.catch(handleReceiveError);
};

export { insertDiary, findAllDiary, findDiaryById, deleteDiaryById };
export {
insertDiary,
updateDiary,
findAllDiary,
findDiaryById,
deleteDiaryById,
};
7 changes: 4 additions & 3 deletions src/main/frontend/src/components/molecules/AvatarBox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,12 @@ function AvatarBox() {
new Item("Logout", "/auth/signout", null, isSignin).activateHandler(
async () => {
setItems(items.map((item) => item.changeActive()));
const result = await signout(cookies.token).finally(() => {
await signout(cookies.token).finally(() => {
setIsSignin(false);
dispatch(removeUser());
removeCookie("token");
navigate("/");
});
removeCookie("token");
navigate("/");
},
),
]);
Expand Down
2 changes: 2 additions & 0 deletions src/main/frontend/src/components/organisms/DynamicSection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ function DynamicSection({
width: "100%",
height: "100%",
zIndex: -1,
objectFit: 'cover',
objectPosition: '0 calc(-7rem + 10vh)',
...(main && { filter: "brightness(0.7)" }),
...(background && { backgroundColor: "#fff5f8" }),
}}
Expand Down
24 changes: 18 additions & 6 deletions src/main/frontend/src/components/templates/DetailLayout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ function DetailLayout({ diary, emotion }: { diary: any; emotion: any }) {
navigate("/diary");
};

const handleUpdateDiary = () => {
navigate(`/diary/form/${id}`);
};

return (
<Container maxWidth='lg'>
<UserInfo author={author} regdate={regdate} />
Expand All @@ -61,12 +65,20 @@ function DetailLayout({ diary, emotion }: { diary: any; emotion: any }) {
{title}
</Typography>
{user && user.id === uid && (
<Button
variant='contained'
color='error'
onClick={handleDeleteDiary}>
일기 지우기
</Button>
<Stack direction='row' gap={1}>
<Button
variant='contained'
color='primary'
onClick={handleUpdateDiary}>
일기 수정
</Button>
<Button
variant='contained'
color='error'
onClick={handleDeleteDiary}>
일기 지우기
</Button>
</Stack>
)}
</Stack>
</Stack>
Expand Down
117 changes: 62 additions & 55 deletions src/main/frontend/src/pages/Auth/Profile.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,16 @@ import {
Typography,
} from "@mui/material";
import { useFormik } from "formik";
import { EncryptJWT } from "jose";
import { sha256 } from "js-sha256";
import React, { useContext, useEffect, useState } from "react";
import { useCookies } from "react-cookie";
import * as yup from "yup";
import { checkPassword } from "../../apis/auth";
import { handleReceiveError } from "../../apis/commonTypes";
import { addFaceImage } from "../../apis/faceImage";
import { userUpdate } from "../../apis/user";
import { fileupload } from "../../apis/utils/fileupload";
import TextFieldSet from "../../components/molecules/TextFieldSet";
import { UserContext } from "../../contexts/UserProvider";
import FaceImage from "../../models/FaceImage";
Expand All @@ -26,6 +31,7 @@ import {
passwordValidation,
phoneValidation,
REQUIRED_ERROR,
splitToUnderBar,
} from "../../tools/utils";

const validationSchema = yup.object({
Expand Down Expand Up @@ -60,8 +66,7 @@ const validationSchema = yup.object({
insertTime: yup.number(),
insertDate: yup.string(),
})
.nullable()
.required(REQUIRED_ERROR);
.nullable();
case "string":
return yup.string().required("필수입력");
default:
Expand All @@ -88,8 +93,7 @@ const validationSchema = yup.object({
insertTime: yup.number(),
insertDate: yup.string(),
})
.nullable()
.required(REQUIRED_ERROR);
.nullable();
case "string":
return yup.string().required("필수입력");
default:
Expand Down Expand Up @@ -149,77 +153,77 @@ function Profile() {
onSubmit: (values) => {
console.log(values);

const user = new User();
Object.entries(values).forEach(([column, value]) => {
user.set(column as UserColumn, value);
});
user.set("profileImg", values.profileImg.name);
checkPassword(values.check_password, user.id)
.then((result) => {
if (result) {
const userInfo = new User();
Object.entries(values).forEach(([column, value]) => {
userInfo.set(column as UserColumn, value);
});
userInfo.set("id", user.id);
userInfo.set("profileImg", values.profileImg?.name);

const face = new FaceImage();
face.set("uid", "12345");
face.set("imgPath", values.faceImage.name);
const face = new FaceImage();
const imgSplit = values.faceImage?.name.split(".");
const type = imgSplit.pop();
const name = imgSplit.join();
face.set("uid", user.id);
face.set("imgPath", `${sha256(name)}.${type}`);

setTimeout(() => {
const userFormData = user.makeFormData();
const faceFormData = face.makeFormData();
userUpdate(userFormData);
addFaceImage(faceFormData);
}, 1);
const userFormData = userInfo.makeFormData();
const faceFormData = face.makeFormData();

console.log(userInfo, face, user.id);
console.log(type, name);

fileupload(values.faceImage, user.id, `${sha256(name)}.${type}`);
userUpdate(userFormData);
addFaceImage(faceFormData);
} else {
alert("비밀번호를 다시 확인 해 주세요.");
}
})
.catch(handleReceiveError);
},
});

const [profileImg, setProfileImg] = useState(null);
const [faceImage, setFaceImage] = useState(null);

useEffect(() => {
const { token } = cookies;
if (token) {
// console.log(user, fields);
setFields(
fields.map((field) => ({
...field,
value: user[field.name],
})),
);
}
Object.entries(user).forEach(([key, value]) => {
switch (key) {
case "nickName":
case "email":
case "password":
case "check_password":
case "phone":
formik.values[key] = value as string;
break;
case "profileImg":
case "faceImage":
formik.values[key] = value as object | string;
break;
}
});
setProfileImg("");
setTimeout(() => {
setProfileImg(null);
}, 1);
}, [user]);

// formik 상세화면 배경 이미지 파일 직접 지정
const handleProfileImg = (e: React.FormEvent<HTMLInputElement>) => {
const files = e.currentTarget.files[0];
if (!files) return;
const newFiles = {
name: files.name,
size: files.size,
type: files.type,
lastModified: files.lastModified,
lastModifiedDate: new Date(files.lastModified).toLocaleString("ko", {
year: "numeric",
month: "long",
day: "numeric",
}),
webkitRelativePath: files.webkitRelativePath,
};
formik.values.profileImg = newFiles;
formik.values.profileImg = files;
setProfileImg(files);
};

const handleFaceImage = (e: React.FormEvent<HTMLInputElement>) => {
const files = e.currentTarget.files[0];
if (!files) return;
const newFiles = {
name: files.name,
size: files.size,
type: files.type,
lastModified: files.lastModified,
lastModifiedDate: new Date(files.lastModified).toLocaleString("ko", {
year: "numeric",
month: "long",
day: "numeric",
}),
webkitRelativePath: files.webkitRelativePath,
};
formik.values.faceImage = newFiles;
formik.values.faceImage = files;
setFaceImage(files);
};

Expand Down Expand Up @@ -300,7 +304,10 @@ function Profile() {
<Divider />

{/* text fields */}
<Box component='form' onSubmit={formik.handleSubmit}>
<Box
component='form'
onSubmit={formik.handleSubmit}
encType='multipart/form-data'>
<Stack sx={{ mt: 2, mb: 1 }} spacing={2}>
<TextFieldSet fields={fields} size={"medium"} formik={formik} />

Expand Down
52 changes: 45 additions & 7 deletions src/main/frontend/src/pages/Diary/WriteForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@ import SunEditor from "suneditor-react";
import SunEditorCore from "suneditor/src/lib/core";
import Analyzer from "../../tools/analyzer";
import { useFormik } from "formik";
import { useNavigate } from "react-router-dom";
import { useNavigate, useParams } from "react-router-dom";
import * as yup from "yup";
import axios from "axios";
import { insertDiary } from "../../apis/diary";
import { findDiaryById, insertDiary, updateDiary } from "../../apis/diary";
import Emotions from "../../models/Emotions";
import "suneditor/dist/css/suneditor.min.css";
import Diary from "../../models/Diary";
Expand All @@ -26,12 +26,15 @@ interface FormikProps {
did: string;
}

let temp: any;

function WriteForm() {
const navigate = useNavigate();
const params = useParams();
const [user, dispatch] = useContext(UserContext);
const [cookies, setCookie] = useCookies(["token"]);
const editor = useRef<SunEditorCore>();
const [formData, setFormData] = useState({ title: "" });
const [formData, setFormData] = useState(null);

const formik = useFormik({
initialValues: {
Expand Down Expand Up @@ -63,7 +66,13 @@ function WriteForm() {

const diaryFormData = diary.makeFormData();

const diaryId = await insertDiary(diaryFormData);
if (params.id) {
diaryFormData.append("id", params.id);
}

const diaryId = params.id
? await updateDiary(diaryFormData)
: await insertDiary(diaryFormData);

const emotion = new Emotions();
emotion.getResponseData(
Expand All @@ -73,8 +82,10 @@ function WriteForm() {
emotion.set("did", diaryId);

const emotionFormData = emotion.makeFormData();
console.log(emotion);
insertEmotions(emotionFormData);

if (!params.id) {
insertEmotions(emotionFormData);
}

navigate("/diary");
},
Expand All @@ -90,7 +101,32 @@ function WriteForm() {
}
});
}
}, []);
if (params.id) {
const origin = findDiaryById(params.id);

origin.then((data) => {
temp = data;
Object.entries(data).forEach(([key, value]) => {
switch (key) {
case "title":
case "content":
case "author":
case "uid":
case "did":
formik.values[key] = value as string;
break;
case "isShare":
formik.values[key] = value as boolean;
break;
}
});
setFormData("");
});
}
setTimeout(() => {
setFormData(null);
}, 1);
}, [params]);

const getSunEditorInstance = (sunEditor: SunEditorCore) => {
editor.current = sunEditor;
Expand Down Expand Up @@ -160,6 +196,7 @@ function WriteForm() {
width='100%'
height='300px'
name='content'
setContents={formik.values["content"]}
getSunEditorInstance={getSunEditorInstance}
/>
</Box>
Expand All @@ -181,6 +218,7 @@ function WriteForm() {
</Button>
</Stack>
</Box>
{formData}
</Box>
);
}
Expand Down
Loading