Skip to content

Commit

Permalink
Merge pull request #31 from flowerseok/feature/socialshare
Browse files Browse the repository at this point in the history
[feat] 카카오공유하기 추가
  • Loading branch information
oooppq authored Feb 1, 2024
2 parents 62490b5 + b080a14 commit 0d5a5f9
Show file tree
Hide file tree
Showing 10 changed files with 113 additions and 121 deletions.
92 changes: 40 additions & 52 deletions app/find-taste/result/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import UserStyle from '@/components/matchingtest/UserStyle';
import Similar from '@/components/matchingtest/Similar';
import ResultNav from '@/components/matchingtest/ResultNav';
import Link from 'next/link';
import { useState } from 'react';
import { useState, useEffect } from 'react';
import ResultModal from '@/components/matchingtest/ResultModal';

interface ResultPageProps {
Expand All @@ -28,70 +28,58 @@ interface Fragrance {
}

const Page = ({ searchParams }: ResultPageProps) => {
const parseAndStoreData = (params: { [key: string]: any }) => {
const Families: Family[] = [];
const Fragrance: Fragrance[] = [];
const familySet = new Set();
const fragranceSet = new Set();
const addFamilyData = (index: string) => {
const familyKorName = params[`familyKorName[${index}]`] || '';
const familyEngName = params[`familyEngName[${index}]`] || '';
const summary = params[`summary[${index}]`] || '';
const icon = params[`icon[${index}]`] || '';
const keyword = params[`keyword[${index}]`] || [];
const [families, setFamilies] = useState<Family[]>([]);
const [fragrances, setFragrances] = useState<Fragrance[]>([]);

if (familyKorName && !familySet.has(familyKorName)) {
familySet.add(familyKorName);
Families.push({ familyKorName, familyEngName, summary, icon, keyword });
}
};

const addFragranceData = (index: string) => {
const fragranceId = params[`fragranceId[${index}]`] || '';
if (!fragranceSet.has(fragranceId)) {
fragranceSet.add(fragranceId);
Fragrance.push({
fragranceId,
fragranceName: params[`fragranceName[${index}]`] || '',
brandName: params[`brandName[${index}]`] || '',
familyName: params[`familyName[${index}]`] || '',
thumbnail: params[`thumbnail[${index}]`] || '',
});
}
};

Object.keys(params).forEach((key) => {
const match = key.match(/\[(\d+)\]/);
if (match) {
const index = match[1];
if (key.startsWith('family')) {
addFamilyData(index);
} else if (key.startsWith('fragrance')) {
addFragranceData(index);
}
const styles = {
style1: searchParams.vibe ? searchParams.vibe[0] : '',
style2: searchParams.vibe ? searchParams.vibe[1] : '',
};
const payload = {
concentration: searchParams.persistence,
season: searchParams.season,
mainFamily: searchParams.main,
scent: searchParams.individuality,
style: searchParams.vibe,
};
const datafetch = async () => {
try {
const res = await fetch('/api/extract', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ payload }),
});

if (!res.ok) {
throw new Error(`Failed to send request: ${res.status}`);
}
});

return { Families, Fragrance };
const responseData = await res.json();
setFamilies(responseData.families);
setFragrances(responseData.fragrances);
} catch (error) {
// eslint-disable-next-line no-console
console.error('Error fetching data:', error);
}
};

const { Families, Fragrance } = parseAndStoreData(searchParams);

const style = {
style1: searchParams.style1,
style2: searchParams.style2,
};
useEffect(() => {
datafetch();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

const [isModalOpen, setModalOpen] = useState(false);

const handleShareClick = () => {
setModalOpen(true);
};

return (
<div>
<ResultNav />
<UserStyle families={Families} />
<Similar fragrance={Fragrance} style={style} />
<UserStyle families={families} />
<Similar fragrance={fragrances} style={styles} />
<div className="flex flex-row mt-[79px] justify-center mx-4 gap-x-[11px] pb-[28px]">
<button
type="button"
Expand Down
73 changes: 11 additions & 62 deletions app/find-taste/test/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,22 +11,6 @@ import SwiperHeader from '@/components/matchingtest/SwiperHeader';
import Loading from '@/components/matchingtest/Loading';
import { useRouter } from 'next/navigation';

interface Family {
familyKorName: string;
familyEngName: string;
summary: string;
icon: string;
keyword: string[];
}

interface Fragrance {
fragranceId: number;
fragranceName: string;
brandName: string;
familyName: string;
thumbnail: string;
}

interface SelectionsState {
persistence: string[];
season: string[];
Expand Down Expand Up @@ -56,56 +40,21 @@ const Page = () => {
setSelections((prev) => ({ ...prev, [category]: selection }));
};

const handleSubmit = async () => {
const payload = {
concentration: selections.persistence,
season: selections.season,
mainFamily: selections.main,
scent: selections.individuality,
style: selections.vibe,
};

try {
const res = await fetch(`/api/extract`, {
method: 'POST',
body: JSON.stringify({ payload }),
});
// handleSumbit 수정

if (!res.ok) {
throw new Error(`Failed to send request: ${res.status}`);
const handleSubmit = () => {
Object.entries(selections).forEach(([key, value]) => {
if (Array.isArray(value)) {
value.forEach((val) => queryParams.append(`${key}`, val));
} else {
queryParams.append(`${key}`, value);
}
});

const responseData = await res.json();

responseData.families.forEach((family: Family, familyIndex: number) => {
Object.entries(family).forEach(([key, value]) => {
if (Array.isArray(value)) {
value.forEach((val) =>
queryParams.append(`${key}[${familyIndex}]`, val),
);
} else {
queryParams.append(`${key}[${familyIndex}]`, value);
}
});
});
responseData.fragrances.forEach(
(fragrance: Fragrance, fragranceIndex: number) => {
Object.entries(fragrance).forEach(([key, value]) => {
queryParams.append(`${key}[${fragranceIndex}]`, value.toString());
});
},
);

queryParams.append(`style1`, selections.vibe[0]);
queryParams.append(`style2`, selections.vibe[1]);
// window.location.replace(`/loading/?${queryParams}`);
setQueryString(queryParams.toString());
setIsLoading(true);
} catch (error) {
// eslint-disable-next-line no-console
console.error('Error sending data:', error);
}
setQueryString(queryParams.toString());
setIsLoading(true);
};

const slides = [
{
name: 'persistence',
Expand Down
8 changes: 8 additions & 0 deletions app/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import localFont from 'next/font/local';
import type { Metadata } from 'next';
import './globals.css';
import KakaoScript from '@/components/matchingtest/KakaoScript';

export const metadata: Metadata = {
title: '어코드 | 프레그런스 큐레이션 플랫폼',
Expand All @@ -12,6 +13,12 @@ export const metadata: Metadata = {
},
};

declare global {
interface Window {
Kakao: any;
}
}

const myFont = localFont({
src: './fonts/PretendardVariable.woff2',
style: 'normal',
Expand All @@ -27,6 +34,7 @@ export default function RootLayout({
return (
<html lang="en" className={myFont.className}>
<body>{children}</body>
<KakaoScript />
</html>
);
}
19 changes: 19 additions & 0 deletions components/matchingtest/KakaoScript.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
'use client';

import Script from 'next/script';

function KakaoScript() {
const onLoad = () => {
window.Kakao.init(process.env.NEXT_PUBLIC_KAKAO_API_KEY);
};

return (
<Script
src="https://developers.kakao.com/sdk/js/kakao.js"
async
onLoad={onLoad}
/>
);
}

export default KakaoScript;
33 changes: 27 additions & 6 deletions components/matchingtest/ResultModal.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React, { useState, useEffect } from 'react';

import { LinkLogo, Klogo } from '@/public/images';
import { LinkLogo, KakaoShare } from '@/public/images';
import Image from 'next/image';

interface ResultModalProps {
onClose: () => void;
Expand Down Expand Up @@ -66,6 +66,25 @@ const ResultModal = ({ onClose }: ResultModalProps) => {
copyToClipboardFallback(window.location.href);
}
};
const Currentlocation = window.location.search;

const kakaoShare = () => {
if (window.Kakao) {
const kakao = window.Kakao;
const appKey = process.env.NEXT_PUBLIC_KAKAO_APP_KEY;
const templateId = 103731;
if (!kakao.isInitialized()) {
kakao.init(appKey);
}
kakao.Share.sendCustom({
templateId,
templateArgs: {
btnTitle: '테스트하러가기',
id: Currentlocation,
},
});
}
};
return (
<div
className="fixed inset-0 bg-black bg-opacity-50 flex justify-center items-center z-50"
Expand All @@ -88,10 +107,12 @@ const ResultModal = ({ onClose }: ResultModalProps) => {
<div className="h1 text-center mb-4">공유하기</div>
<div className="flex flex-row justify-center gap-x-10 h2">
<div className="flex flex-col">
<div className="mb-2">
<Klogo />
</div>
<div>카카오톡</div>
<button type="button" onClick={() => kakaoShare()}>
<div className="mb-2">
<Image src={KakaoShare} alt="공유하기" />
</div>
<div>카카오톡</div>
</button>
</div>
<div
className="flex flex-col"
Expand Down
4 changes: 4 additions & 0 deletions components/matchingtest/UserStyle.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
GreenGray,
EarthyGray,
FruityGray,
FougereGray,
} from '@/public/images';
import Image from 'next/image';

Expand Down Expand Up @@ -62,6 +63,9 @@ const UserStyle = ({ families }: UserStyleProps) => {
case 'FRUITY':
imageSrc = FruityGray;
break;
case 'FOUGERE':
imageSrc = FougereGray;
break;
default:
}

Expand Down
Binary file added public/images/Fougere-gray.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified public/images/Fruity-gray.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added public/images/KakaoShare.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
5 changes: 4 additions & 1 deletion public/images/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,4 +101,7 @@ export { default as AldehydeGray} from './Aldehyde-gray.png';
export { default as AromaticGray} from './Aromatic-gray.png';
export { default as LeatherGray} from './Leather-gray.png';
export { default as SpicyGray} from './Spicy-gray.png';
export { default as FruityGray} from './Fruity-gray.png';
export { default as FruityGray} from './Fruity-gray.png';
export { default as FougereGray} from './Fougere-gray.png';

export {default as KakaoShare} from './KakaoShare.png';

0 comments on commit 0d5a5f9

Please sign in to comment.