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

회비 API 연동 #53

Merged
merged 3 commits into from
Feb 15, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
73 changes: 73 additions & 0 deletions apps/member/src/api/membershipFee.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { API_BASE_URL, END_POINT } from '@constants/api';
import { PaginationType } from '@type/api';
import type { MembershipFeeType } from '@type/membershipFee';
import { createCommonPagination, createPath, getAccessToken } from '@utils/api';
import { server } from './server';

interface postMembershipFeeArgs {
body: MembershipFeeType;
multipartFile?: FormData;
}

export const postMembershipFee = async ({
body,
multipartFile,
}: postMembershipFeeArgs) => {
const accessToken = getAccessToken();
let membershipFeeData;

if (multipartFile) {
const storagePeriod = 7;
const url = createPath(API_BASE_URL, END_POINT.UPLOADEDFILE_MEMBERSHIP_FEE);
const addUrl = `${url}?storagePeriod=${storagePeriod}`;
const { data: imageData } = await fetch(addUrl, {
method: 'POST',
headers: {
Authorization: `Bearer ${accessToken}`,
},
body: multipartFile,
})
.then((response) => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.catch((e) => console.error(e));
console.log('이미지 저장 완료');

membershipFeeData = {
...body,
imageUrl: imageData[0],
};
} else {
membershipFeeData = body;
}

const { data } = await fetch(
createPath(API_BASE_URL, END_POINT.MEMBERSHIP_FEE),
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${accessToken}`,
},
body: JSON.stringify(membershipFeeData),
},
).then((response) => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
});

return data;
};

export const getMembershipFee = async (page: number, size: number) => {
const params = { page, size };
const { data } = await server.get<PaginationType<MembershipFeeType>>({
url: createCommonPagination(END_POINT.MEMBERSHIP_FEE, params),
});
return data;
};
36 changes: 36 additions & 0 deletions apps/member/src/api/uploadedFile.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { END_POINT } from '@constants/api';
import { createCommonPagination, getAccessToken } from '@utils/api';

interface postUploadedFileMembershipFeeArgs {
storagePeriod: number;
multipartFile: string;
}

export const postUploadedFileMembershipFee = async ({
storagePeriod,
multipartFile,
}: postUploadedFileMembershipFeeArgs) => {
const accessToken = getAccessToken();
const params = { storagePeriod };
const url = createCommonPagination(
END_POINT.UPLOADEDFILE_MEMBERSHIP_FEE,
params,
);

const { data } = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${accessToken}`,
},
body: JSON.stringify(multipartFile),
}).then((response) => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
});
console.log('image stored');

return data;
};
93 changes: 52 additions & 41 deletions apps/member/src/components/support/RequestForm/RequestForm.tsx
Original file line number Diff line number Diff line change
@@ -1,85 +1,96 @@
import { Button } from '@clab/design-system';
import { ChangeEvent, useState } from 'react';
import { ChangeEvent, useRef, useState } from 'react';

import { Input } from '@clab/design-system';
import Section from '@components/common/Section/Section';

interface InputProps {
name: string;
cost: string;
purpose: string;
url: string;
}
import { useMembershipFeeMutation } from '@hooks/queries/useMembershipFeeMutation';
import { MembershipFeeType } from '@type/membershipFee';

const RequestForm = () => {
const [input, setInput] = useState<InputProps>({
name: '',
cost: '',
url: '',
purpose: '',
const { membershipFeeMutate } = useMembershipFeeMutation();
const imageUploader = useRef<HTMLInputElement>(null);
const [input, setInput] = useState<MembershipFeeType>({
category: '',
amount: 0,
content: '',
});

const { name, cost, purpose, url } = input;
const { category, amount, content } = input;

const onChangeInputs = (e: ChangeEvent<HTMLInputElement>) => {
setInput((prev) => ({
...prev,
[e.target.name]: e.target.value,
[e.target.name]:
e.target.name === 'amount'
? parseFloat(e.target.value.replace(/,/g, ''))
: e.target.value,
}));
};

const addComma = (cost: string) => {
const returnString = cost
.replace(/,/g, '')
.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
const addComma = (amount: number) => {
if (!amount) return '';
const returnString = String(amount).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
return returnString;
};

const onClickRequest = () => {
if (!name || !cost || !purpose || !cost || !url) {
const onClickRequest = async () => {
if (!category || !amount || !content) {
alert('필수 입력 사항을 확인해주세요');
} else {
alert('검토 후 안내드리겠습니다.');
console.log(imageUploader.current?.files);
if (imageUploader.current?.files?.length) {
console.log('checked');
const files = imageUploader.current?.files[0];
const formData = new FormData();
formData.append('multipartFile', files, encodeURIComponent(files.name));
membershipFeeMutate({ body: input, multipartFile: formData });
console.log('posted');
}
}
setInput({
category: '',
amount: 0,
content: '',
});
};

return (
<Section>
<Section.Header title="신청서" />
<Section.Body className="mt-4 grid gap-2 md:grid-cols-2">
<Input
id="name"
name="name"
label="품명"
placeholder="품명을 작성해주세요"
value={name}
id="category"
name="category"
label="분류"
placeholder="신청 분류를 작성해주세요"
value={category}
onChange={onChangeInputs}
/>
<Input
id="cost"
name="cost"
id="amount"
name="amount"
label="금액"
inputMode="numeric"
placeholder="구매 금액을 작성해주세요"
value={addComma(cost) || cost}
onChange={onChangeInputs}
/>
<Input
id="url"
name="url"
label="URL"
placeholder="구매한 사이트의 URL을 작성해주세요"
value={url}
value={addComma(amount)}
onChange={onChangeInputs}
/>
<Input
id="purpose"
name="purpose"
id="content"
name="content"
label="사유"
placeholder="요청 사유를 작성해주세요"
value={purpose}
value={content}
onChange={onChangeInputs}
/>
<Input
id="membershipFormUploader"
name="membershipFormUploader"
type="file"
label="증빙 자료"
ref={imageUploader}
className="border-none"
/>
</Section.Body>
<Button className="w-full mt-6" onClick={onClickRequest}>
요청하기
Expand Down
2 changes: 2 additions & 0 deletions apps/member/src/constants/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ export const END_POINT = {
COMMENTS: (boardId: number) => `/comments/${boardId}`,
HIRE: (jobPostingId: number) => `/job-postings/${jobPostingId}`,
NEWS: (newsId: number) => `/news/${newsId}`,
MEMBERSHIP_FEE: `/membership-fees`,
UPLOADEDFILE_MEMBERSHIP_FEE: `/files/membership-fee`,
};

export const HTTP_STATUS_CODE = {
Expand Down
2 changes: 2 additions & 0 deletions apps/member/src/constants/key.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,6 @@ export const QUERY_KEY = {
COMMENTS: 'Comments',
HIRE: 'Hire',
NEWS: 'News',
MEMBERSHIP_FEE: 'MembershipFee',
UPLOADEDFILE: 'UploadedFile',
};
10 changes: 10 additions & 0 deletions apps/member/src/hooks/queries/useMembershipFee.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { QUERY_KEY } from '@constants/key';
import { useSuspenseQuery } from '@tanstack/react-query';
import { getMembershipFee } from '@api/membershipFee';

export const useMembershipFee = (page = 0, size = 20) => {
return useSuspenseQuery({
queryKey: [QUERY_KEY.MEMBERSHIP_FEE, page, size],
queryFn: () => getMembershipFee(page, size),
});
};
10 changes: 10 additions & 0 deletions apps/member/src/hooks/queries/useMembershipFeeMutation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { postMembershipFee } from '@api/membershipFee';
import { useMutation } from '@tanstack/react-query';

export const useMembershipFeeMutation = () => {
const membershipFeeMutation = useMutation({
mutationFn: postMembershipFee,
});

return { membershipFeeMutate: membershipFeeMutation.mutate };
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { postUploadedFileMembershipFee } from '@api/uploadedFile';
import { QUERY_KEY } from '@constants/key';
import { useMutation, useQueryClient } from '@tanstack/react-query';

export const useUploadedFileMembershipFeeMutation = () => {
const queryClient = useQueryClient();

const uploadedFileMembershipFeeMutation = useMutation({
mutationFn: postUploadedFileMembershipFee,
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: [QUERY_KEY.UPLOADEDFILE],
});
},
});

return {
uploadedFileMembershipFeeMutate: uploadedFileMembershipFeeMutation.mutate,
};
};
10 changes: 10 additions & 0 deletions apps/member/src/types/membershipFee.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
export interface MembershipFeeType {
id?: number;
memberId?: string;
memberName?: string;
category: string;
amount: number;
content: string;
imageUrl?: string;
createdAt?: string;
}
39 changes: 22 additions & 17 deletions packages/design-system/src/Input/Input.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,31 @@
import React, { ComponentPropsWithRef } from 'react';
import React, { ComponentPropsWithRef, forwardRef } from 'react';
import { twMerge } from 'tailwind-merge';

interface InputProps extends ComponentPropsWithRef<'input'> {
id: string;
label?: string;
}

const Input = ({ label, id, className, ...rest }: InputProps) => {
return (
<div className="flex flex-col">
{label && (
<label htmlFor={id} className="text-xs mb-1 ml-1">
{label}
</label>
)}
<input
id={id}
className={twMerge('border rounded-lg p-2', className)}
{...rest}
/>
</div>
);
};
const Input = forwardRef<HTMLInputElement, InputProps>(
({ label, id, className, ...rest }, ref) => {
return (
<div className="flex flex-col">
{label && (
<label htmlFor={id} className="text-xs mb-1 ml-1">
{label}
</label>
)}
<input
ref={ref}
id={id}
className={twMerge('border rounded-lg p-2', className)}
{...rest}
/>
</div>
);
},
);

Input.displayName = 'Input';

export default Input;