Merge pull request 'feature/suitable' (#5) from feature/suitable into backup

Reviewed-on: #5
This commit is contained in:
seul 2025-04-30 16:24:45 +09:00
commit 681d3942f2
10 changed files with 466 additions and 37 deletions

View File

@ -38,14 +38,31 @@ export interface Suitable {
}
export const suitableApi = {
getList: async (): Promise<Suitable[]> => {
const response = await axiosInstance.get<Suitable[]>('/api/suitable/list')
getList: async (category?: string, keyword?: string): Promise<Suitable[]> => {
let condition: any = {}
if (category) {
condition['category'] = category
}
if (keyword) {
condition['keyword'] = {
contains: keyword,
}
}
console.log('🚀 ~ getList: ~ condition:', condition)
const response = await axiosInstance.get<Suitable[]>('/api/suitable/list', { params: condition })
console.log('🚀 ~ getList: ~ response:', response)
return response.data
},
getCategory: async (): Promise<Suitable[]> => {
const response = await axiosInstance.get<Suitable[]>('/api/suitable/category')
console.log('🚀 ~ getCategory: ~ response:', response)
return response.data
},
getDetails: async (roofMaterial: string): Promise<Suitable[]> => {
const response = await axiosInstance.get<Suitable[]>(`/api/suitable/details?roof-material=${roofMaterial}`)
console.log('🚀 ~ getDetails: ~ response:', response)
return response.data
},

View File

@ -0,0 +1,16 @@
import { NextResponse } from 'next/server'
import { prisma } from '@/libs/prisma'
export async function GET() {
// @ts-ignore
const roofMaterialCategory = await prisma.MS_SUITABLE.findMany({
select: {
roof_material: true,
},
distinct: ['roof_material'],
orderBy: {
roof_material: 'asc',
},
})
return NextResponse.json(roofMaterialCategory)
}

View File

@ -1,4 +1,5 @@
import { NextResponse } from 'next/server'
import { prisma } from '@/libs/prisma'
export async function GET(request: Request) {
const { searchParams } = new URL(request.url)

View File

@ -1,8 +1,35 @@
import { NextResponse } from 'next/server'
import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/libs/prisma'
export async function GET() {
// @ts-ignore
const suitables = await prisma.MS_SUITABLE.findMany()
return NextResponse.json(suitables)
export async function GET(request: NextRequest) {
try {
const searchParams = request.nextUrl.searchParams
const category = searchParams.get('category')
const keyword = searchParams.get('keyword')
let whereCondition: any = {}
if (category) {
whereCondition['roof_material'] = category
}
if (keyword) {
whereCondition['product_name'] = {
contains: keyword,
}
}
console.log('🚀 ~ /api/suitable/list: ~ prisma where condition:', whereCondition)
// @ts-ignore
const suitables = await prisma.MS_SUITABLE.findMany({
where: whereCondition,
orderBy: {
product_name: 'asc',
},
})
return NextResponse.json(suitables)
} catch (error) {
console.error('❌ 데이터 조회 중 오류가 발생했습니다:', error)
return NextResponse.json({ error: '데이터 조회 중 오류가 발생했습니다' }, { status: 500 })
}
}

View File

@ -1,16 +1,33 @@
'use client'
import { suitableApi } from '@/api/suitable'
import { useQuery } from '@tanstack/react-query'
import { useSuitableStore } from '@/store/useSuitableStore'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { useRouter } from 'next/navigation'
import type { Suitable as SuitableType } from '@/api/suitable'
export default function Suitable() {
const router = useRouter()
const { data, error, isPending } = useQuery({
queryKey: ['suitable-list'],
queryFn: suitableApi.getList,
const queryClient = useQueryClient()
const { selectedItems, addSelectedItem, removeSelectedItem } = useSuitableStore()
const handleItemClick = (item: SuitableType) => {
if (!item.id) return // 초기 데이터 import 때문에 Suitable.id가 optional 타입이라서 방어 처리 추가
selectedItems.some((selected) => selected.id === item.id) ? removeSelectedItem(item.id) : addSelectedItem(item)
}
const { data: suitableList, isLoading } = useQuery<SuitableType[]>({
queryKey: ['suitables', 'search'],
queryFn: async () => {
const data = queryClient.getQueryData(['suitables', 'search']) as SuitableType[]
return data ?? []
},
enabled: false,
})
if (isLoading || !suitableList || suitableList.length === 0) {
return <div>Loading...</div>
}
return (
<>
<h1 className="text-4xl font-bold">Suitable</h1>
@ -22,9 +39,31 @@ export default function Suitable() {
>
HOME
</button>
{error && <div>Error: {error.message}</div>}
{isPending && <div>Loading...</div>}
{data && data.map((item) => <div key={item.id}>{item.product_name}</div>)}
<div>
<h2 className="text-lg font-semibold mb-2"> </h2>
{selectedItems.length > 0 ? (
selectedItems.map((item) => (
<div key={item.id} onClick={() => handleItemClick(item)}>
{item.product_name}
</div>
))
) : (
<div> .</div>
)}
</div>
<br />
<div>
<h2 className="text-lg font-semibold mb-2"> </h2>
{suitableList ? (
suitableList.map((item: SuitableType) => (
<div key={item.id} className="p-2 border rounded cursor-pointer hover:bg-gray-100" onClick={() => handleItemClick(item)}>
{item.product_name}
</div>
))
) : (
<div> .</div>
)}
</div>
</>
)
}

View File

@ -1,23 +1,71 @@
'use client'
import { Suitable, suitableApi } from '@/api/suitable'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { suitableApi } from '@/api/suitable'
import { useQuery } from '@tanstack/react-query'
import generatePDF, { usePDF, Options } from 'react-to-pdf'
import PDFContent from './SuitablePdf'
const pdfOptions: Options = {
filename: 'page.pdf',
method: 'save',
page: { format: 'a4', margin: 10 },
overrides: {
pdf: {
compress: true,
},
},
}
export default function SuitableDetails({ roofMaterial }: { roofMaterial: string }) {
console.log('🚀 ~ SuitableDetails ~ roofMaterial:', roofMaterial)
// const { data, error, isPending } = useQuery({
// queryKey: ['suitable-details'],
// queryFn: () => suitableApi.getDetails(roofMaterial),
// staleTime: 0,
// })
const cache = useQueryClient()
const listData = cache.getQueryData(['suitable-list']) as Suitable[]
const data = listData.filter((item) => item.roof_material === roofMaterial)
const { data, isLoading } = useQuery({
queryKey: ['suitable-details'],
queryFn: () => suitableApi.getDetails(roofMaterial),
staleTime: 0,
enabled: !!roofMaterial,
})
const { toPDF, targetRef } = usePDF({ ...pdfOptions, method: 'open' })
if (isLoading) {
return <div>Loading...</div>
}
return (
<>
<h1 className="text-4xl font-bold">Searched Roof Material: {roofMaterial}</h1>
{data && data.map((item) => <div key={item.id}>{item.product_name}</div>)}
<button className="inline-block bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded" onClick={() => toPDF()}>
OPEN PDF
</button>
<button
className="inline-block bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
onClick={() => generatePDF(targetRef, pdfOptions)}
>
SAVE PDF
</button>
{/* <button onClick={handleDownloadPDF}>Download PDF</button> */}
{/* <div ref={targetRef} className="pdf-content"> */}
<div>
<h1 className="text-4xl font-bold">Searched Roof Material: {decodeURIComponent(roofMaterial as string)}</h1>
{data &&
data.map((item) => (
<div key={item.id}>
<br />
<div>product_name: {item.product_name}</div>
<div>manufacturer: {item.manufacturer}</div>
<div>roof_material: {item.roof_material}</div>
<div>shape: {item.shape}</div>
<div>support_roof_tile: {item.support_roof_tile}</div>
<div>support_roof_bracket: {item.support_roof_bracket}</div>
<div>yg_anchor: {item.yg_anchor}</div>
</div>
))}
</div>
{/* <div style={{ display: 'none' }}> */}
<div>
<div ref={targetRef}>
<h1 className="text-4xl font-bold">PDF </h1>
<PDFContent data={data ?? []} />
</div>
</div>
</>
)
}

View File

@ -0,0 +1,116 @@
import { Suitable } from '@/api/suitable'
interface StatusInfo {
statusIcon: string
statusText: string
}
interface FittingItem {
name: string
value: string
memo: string
}
function getStatusInfo(value: string): StatusInfo | null {
const val = value?.trim()?.replace(/ー|/g, '-') || ''
if (['○', ''].includes(val)) {
return {
statusIcon: '✅',
statusText: '設置可',
}
}
if (['×', '✕'].includes(val)) {
return {
statusIcon: '❌',
statusText: '設置不可',
}
}
if (['-', '', 'ー'].includes(val)) {
return {
statusIcon: '❓',
statusText: 'お問い合わせください',
}
}
if (val === '') return null
return {
statusIcon: '✅',
statusText: `${val} で設置可`,
}
}
function getFittingItems(item: Suitable): FittingItem[] {
return [
{ name: '屋根瓦用支持金具', value: item.support_roof_tile, memo: item.support_roof_tile_memo },
{ name: '屋根ブラケット用支持金具', value: item.support_roof_bracket, memo: item.support_roof_bracket_memo },
{ name: 'YGアンカー', value: item.yg_anchor, memo: item.yg_anchor_memo },
{ name: 'RG屋根瓦パーツ', value: item.rg_roof_tile_part, memo: item.rg_roof_tile_part_memo },
{ name: 'DIDOハント支持瓦2', value: item.dido_hunt_support_tile_2, memo: item.dido_hunt_support_tile_2_memo },
{ name: '高島パワーベース', value: item.takashima_power_base, memo: item.takashima_power_base_memo },
{ name: '高島瓦ブラケット', value: item.takashima_tile_bracket, memo: item.takashima_tile_bracket_memo },
{ name: 'スレートブラケット4', value: item.slate_bracket_4, memo: item.slate_bracket_4_memo },
{ name: 'スレートシングルメタルブラケット', value: item.slate_single_metal_bracket, memo: item.slate_single_metal_bracket_memo },
{ name: 'DIDOハントショートラック4', value: item.dido_hunt_short_rack_4, memo: item.dido_hunt_short_rack_4_memo },
{
name: '高島スレートブラケットスレートシングル',
value: item.takashima_slate_bracket_slate_single,
memo: item.takashima_slate_bracket_slate_single_memo,
},
{ name: 'DFメタルブラケット', value: item.df_metal_bracket, memo: item.df_metal_bracket_memo },
{ name: 'スレートメタルブラケット', value: item.slate_metal_bracket, memo: item.slate_metal_bracket_memo },
{ name: '高島スレートブラケットメタル屋根', value: item.takashima_slate_bracket_metal_roof, memo: item.takashima_slate_bracket_metal_roof_memo },
]
}
function FittingItem({ fitting }: { fitting: FittingItem }) {
const statusInfo = getStatusInfo(fitting.value)
if (!statusInfo) return null
return (
<li>
<span>{statusInfo.statusIcon}</span>
<span>
<strong>{fitting.name}</strong>{statusInfo.statusText}
</span>
{fitting.memo && (
<span>
<strong></strong>
{fitting.memo}
</span>
)}
</li>
)
}
export default function PDFContent({ data }: { data: Suitable[] }) {
return (
<div className="pdf-content">
<style jsx global>{`
.pdf-content,
.pdf-content * {
color: black !important;
-webkit-print-color-adjust: exact !important;
print-color-adjust: exact !important;
}
`}</style>
<h1> ()</h1>
{data.map((item) => (
<div key={item.id}>
<br />
<h2>
{item.product_name}{item.manufacturer} / {item.roof_material} / {item.shape}
</h2>
<ul>
{getFittingItems(item).map((fitting, index) => (
<FittingItem key={index} fitting={fitting} />
))}
</ul>
</div>
))}
</div>
)
}

View File

@ -1,21 +1,88 @@
'use client'
import { useState } from 'react'
import { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'
import { useQuery } from '@tanstack/react-query'
import { useSuitable } from '@/hooks/useSuitable'
import Link from 'next/link'
export default function SuitableSearch() {
const router = useRouter()
const [selectedValue, setSelectedValue] = useState('')
const [selectedCategory, setSelectedCategory] = useState<string>('')
const [searchValue, setSearchValue] = useState<string>('')
const { getCategories, getSuitables } = useSuitable()
const { data: categories } = useQuery({
queryKey: ['categories'],
queryFn: getCategories,
staleTime: 1000 * 60 * 60, // 60분
})
const { data: suitableList } = useQuery({
queryKey: ['suitables', 'list'],
queryFn: async () => await getSuitables(),
staleTime: 1000 * 60 * 10, // 10분
gcTime: 1000 * 60 * 10, // 10분
})
const { data: suitableSearch, refetch: refetchBySearch } = useQuery({
queryKey: ['suitables', 'search'],
queryFn: async () => {
// api를 호출하는 검색 방법
// return await updateSearchResults(selectedCategory || undefined, searchValue || undefined)
// useQuery 캐시 데이터를 사용하는 검색 방법
return (
suitableList?.filter((item) => {
const categoryMatch = !selectedCategory || item.roof_material === selectedCategory
const searchMatch = !searchValue || item.product_name.includes(searchValue)
return categoryMatch && searchMatch
}) ?? []
)
},
staleTime: 1000 * 60 * 10,
gcTime: 1000 * 60 * 10,
enabled: false,
})
// 초기 데이터 로딩된 후 검색 결과 없으면 검색 결과 로딩
useEffect(() => {
if (suitableList && (!suitableSearch || suitableSearch.length === 0)) {
refetchBySearch()
}
}, [suitableList, suitableSearch])
// 카테고리 선택 시 검색 결과 로딩
useEffect(() => {
refetchBySearch()
}, [selectedCategory])
const handleSearch = async () => {
if (!searchValue.trim()) {
alert('검색어를 입력하세요.')
return
}
refetchBySearch()
}
return (
<>
<select onChange={(e) => setSelectedValue(e.target.value)}>
<option value=""> </option>
<option value="瓦"></option>
<option value="スレート"></option>
<option value="アスファルトシングル"></option>
</select>
<button onClick={() => router.push(`/suitable/${selectedValue}`)}></button>
<div>
<select value={selectedCategory || ''} onChange={(e) => setSelectedCategory(e.target.value)}>
<option value=""> </option>
{categories?.map((category) => (
<option key={category.roof_material} value={category.roof_material}>
{category.roof_material}
</option>
))}
</select>
<Link href={`/suitable/${selectedCategory}`} className="inline-block bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
</Link>
</div>
<div>
<input type="text" placeholder="검색어를 입력하세요" onChange={(e) => setSearchValue(e.target.value)} />
<button onClick={handleSearch}></button>
</div>
</>
)
}

30
src/hooks/useSuitable.ts Normal file
View File

@ -0,0 +1,30 @@
import { suitableApi } from '@/api/suitable'
export function useSuitable() {
const getCategories = async () => {
try {
return await suitableApi.getCategory()
} catch (error) {
console.error('카테고리 데이터 로드 실패:', error)
return []
}
}
const getSuitables = async () => {
try {
return await suitableApi.getList()
} catch (error) {
console.error('지붕재 데이터 로드 실패:', error)
}
}
const updateSearchResults = async (selectedCategory: string | undefined, searchValue: string | undefined) => {
try {
return await suitableApi.getList(selectedCategory, searchValue)
} catch (error) {
console.error('지붕재 데이터 검색 실패:', error)
}
}
return { getCategories, getSuitables, updateSearchResults }
}

View File

@ -0,0 +1,68 @@
import { create } from 'zustand'
import { Suitable, suitableApi } from '@/api/suitable'
interface SuitableState {
// // 검색 결과 리스트
// searchResults: Suitable[]
// // 초기 데이터 로드
// fetchInitializeData: () => Promise<void>
// // 검색 결과 설정
// setSearchResults: (results: Suitable[]) => void
// // 검색 결과 초기화
// resetSearchResults: () => void
// 선택된 아이템 리스트
selectedItems: Suitable[]
// 선택된 아이템 추가
addSelectedItem: (item: Suitable) => void
// 선택된 아이템 제거
removeSelectedItem: (itemId: number) => void
// 선택된 아이템 모두 제거
clearSelectedItems: () => void
}
export const useSuitableStore = create<SuitableState>((set) => ({
// // 초기 상태
// searchResults: [],
// // 초기 데이터 로드
// fetchInitializeData: async () => {
// const suitables = await fetchInitialSuitablee()
// set({ searchResults: suitables })
// },
// // 검색 결과 설정
// setSearchResults: (results) => set({ searchResults: results }),
// // 검색 결과 초기화
// resetSearchResults: () => set({ searchResults: [] }),
// 초기 상태
selectedItems: [],
// 선택된 아이템 추가 (중복 방지)
addSelectedItem: (item) =>
set((state) => ({
selectedItems: state.selectedItems.some((i) => i.id === item.id) ? state.selectedItems : [...state.selectedItems, item],
})),
// 선택된 아이템 제거
removeSelectedItem: (itemId) =>
set((state) => ({
selectedItems: state.selectedItems.filter((item) => item.id !== itemId),
})),
// 선택된 아이템 모두 제거
clearSelectedItems: () => set({ selectedItems: [] }),
}))
// // 전체 데이터 초기화 함수
// async function fetchInitialSuitablee() {
// try {
// const suitable = await suitableApi.getList()
// return suitable
// } catch (error) {
// console.error('초기 데이터 로드 실패:', error)
// return []
// }
// }