Merge branch 'backup' into feature/survey
This commit is contained in:
commit
69a60de914
@ -7,31 +7,10 @@ const nextConfig: NextConfig = {
|
||||
includePaths: [path.join(__dirname, './src/styles')],
|
||||
},
|
||||
async rewrites() {
|
||||
return [
|
||||
{
|
||||
source: '/:path*',
|
||||
destination: `${process.env.NEXT_PUBLIC_API_URL}/:path*`,
|
||||
},
|
||||
]
|
||||
},
|
||||
async headers() {
|
||||
return [
|
||||
{
|
||||
source: '/api/:path*',
|
||||
headers: [
|
||||
{
|
||||
key: 'Access-Control-Allow-Origin',
|
||||
value: '*',
|
||||
},
|
||||
{
|
||||
key: 'Access-Control-Allow-Methods',
|
||||
value: 'GET, POST, PUT, DELETE, OPTIONS',
|
||||
},
|
||||
{
|
||||
key: 'Access-Control-Allow-Headers',
|
||||
value: 'Content-Type, Authorization',
|
||||
},
|
||||
],
|
||||
destination: `${process.env.NEXT_PUBLIC_API_URL}/api/:path*`,
|
||||
},
|
||||
]
|
||||
},
|
||||
|
||||
@ -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
|
||||
},
|
||||
|
||||
|
||||
@ -120,4 +120,8 @@ export const surveySalesApi = {
|
||||
throw error
|
||||
}
|
||||
},
|
||||
update: async (data: SurveySalesBasicInfo): Promise<SurveySalesBasicInfo> => {
|
||||
const response = await axiosInstance.put<SurveySalesBasicInfo>(`/api/survey-sales`, data)
|
||||
return response.data
|
||||
},
|
||||
}
|
||||
|
||||
16
src/app/api/suitable/category/route.ts
Normal file
16
src/app/api/suitable/category/route.ts
Normal 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)
|
||||
}
|
||||
@ -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)
|
||||
|
||||
@ -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 })
|
||||
}
|
||||
}
|
||||
|
||||
@ -19,3 +19,25 @@ export async function GET() {
|
||||
console.error(error)
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(request: Request) {
|
||||
// @ts-ignore
|
||||
const res = await prisma.SD_SERVEY_SALES_BASIC_INFO.findMany({
|
||||
include: {
|
||||
detail_info: true,
|
||||
},
|
||||
})
|
||||
return NextResponse.json(res)
|
||||
}
|
||||
|
||||
export async function PUT(request: Request) {
|
||||
const body = await request.json()
|
||||
console.log('🚀 ~ PUT ~ body:', body)
|
||||
const detailInfo = { ...body.detail_info, basic_info_id: body.id }
|
||||
console.log('🚀 ~ PUT ~ detailInfo:', detailInfo)
|
||||
// @ts-ignore
|
||||
const res = await prisma.SD_SERVEY_SALES_DETAIL_INFO.create({
|
||||
data: detailInfo,
|
||||
})
|
||||
return NextResponse.json({ message: 'Survey sales updated successfully' })
|
||||
}
|
||||
|
||||
@ -2,6 +2,7 @@ import SuitableDetails from '@/components/SuitableDetails'
|
||||
|
||||
export default async function page({ params }: { params: Promise<{ slug: string }> }) {
|
||||
const { slug } = await params
|
||||
console.log('🚀 ~ page ~ slug:', slug)
|
||||
return (
|
||||
<>
|
||||
<h1>Suitable Details</h1>
|
||||
|
||||
@ -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>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@ -2,19 +2,70 @@
|
||||
|
||||
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({
|
||||
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>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
116
src/components/SuitablePdf.tsx
Normal file
116
src/components/SuitablePdf.tsx
Normal 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>
|
||||
)
|
||||
}
|
||||
@ -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>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@ -1,9 +1,12 @@
|
||||
'use client'
|
||||
|
||||
import { surveySalesApi, SurveySalesBasicInfo } from '@/api/surveySales'
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { surveySalesApi, SurveySalesBasicInfo, SurveySalesDetailInfo } from '@/api/surveySales'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { useState } from 'react'
|
||||
|
||||
export default function SurveySales() {
|
||||
const [isSearch, setIsSearch] = useState(false)
|
||||
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const {
|
||||
@ -34,6 +37,68 @@ export default function SurveySales() {
|
||||
createSurveySales(data)
|
||||
}
|
||||
|
||||
const { data, error: errorList } = useQuery({
|
||||
queryKey: ['survey-sales', 'list'],
|
||||
queryFn: surveySalesApi.getList,
|
||||
enabled: isSearch,
|
||||
})
|
||||
|
||||
const { mutate: updateSurveySales } = useMutation({
|
||||
mutationFn: surveySalesApi.update,
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['survey-sales', 'list'] })
|
||||
},
|
||||
})
|
||||
|
||||
const handleUpdateSurveySales = () => {
|
||||
const detailData: SurveySalesDetailInfo = {
|
||||
contract_capacity: '1100',
|
||||
retail_company: 'test company',
|
||||
supplementary_facilities: 1,
|
||||
supplementary_facilities_etc: '',
|
||||
installation_system: 3,
|
||||
installation_system_etc: '',
|
||||
construction_year: 4,
|
||||
construction_year_etc: '',
|
||||
roof_material: 1,
|
||||
roof_material_etc: '',
|
||||
roof_shape: 2,
|
||||
roof_shape_etc: '',
|
||||
roof_slope: '4.5',
|
||||
house_structure: 1,
|
||||
house_structure_etc: '',
|
||||
rafter_material: 5,
|
||||
rafter_material_etc: 'test message',
|
||||
rafter_size: 3,
|
||||
rafter_size_etc: '',
|
||||
rafter_pitch: 2,
|
||||
rafter_pitch_etc: '',
|
||||
rafter_direction: 3,
|
||||
open_field_plate_kind: 3,
|
||||
open_field_plate_kind_etc: '',
|
||||
open_field_plate_thickness: '',
|
||||
leak_trace: false,
|
||||
waterproof_material: 2,
|
||||
waterproof_material_etc: '',
|
||||
insulation_presence: 3,
|
||||
insulation_presence_etc: '',
|
||||
structure_order: 2,
|
||||
structure_order_etc: '',
|
||||
installation_availability: 1,
|
||||
installation_availability_etc: '',
|
||||
memo: 'test memo',
|
||||
}
|
||||
|
||||
if (!data) return
|
||||
|
||||
const surveySalesData: SurveySalesBasicInfo = {
|
||||
...data[0],
|
||||
detail_info: { ...detailData },
|
||||
}
|
||||
|
||||
updateSurveySales(surveySalesData)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex items-center justify-center">
|
||||
@ -41,13 +106,22 @@ export default function SurveySales() {
|
||||
<button className="bg-blue-500 text-white px-4 py-2 rounded-md" onClick={handleSurveySales}>
|
||||
신규 등록
|
||||
</button>
|
||||
<button className="bg-blue-500 text-white px-4 py-2 rounded-md">조회</button>
|
||||
<button className="bg-blue-500 text-white px-4 py-2 rounded-md" onClick={() => setIsSearch(true)}>
|
||||
조회
|
||||
</button>
|
||||
<button className="bg-blue-500 text-white px-4 py-2 rounded-md" onClick={handleUpdateSurveySales}>
|
||||
수정 (detail info add)
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{/* <div className="bg-orange-100 border-l-4 border-orange-500 text-orange-700 p-4 m-4" role="alert">
|
||||
<p className="font-bold">Be Warned</p>
|
||||
<p>기본 데이터 세팅 되어있습니다.</p>
|
||||
</div> */}
|
||||
<div>
|
||||
{errorList && <div>Error: {errorList.message}</div>}
|
||||
{data && data.map((item) => <div key={item.id}>{JSON.stringify(item)}</div>)}
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
30
src/hooks/useSuitable.ts
Normal file
30
src/hooks/useSuitable.ts
Normal 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 }
|
||||
}
|
||||
68
src/store/useSuitableStore.ts
Normal file
68
src/store/useSuitableStore.ts
Normal 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 []
|
||||
// }
|
||||
// }
|
||||
Loading…
x
Reference in New Issue
Block a user