diff --git a/.env b/.env index be5a3cf..ec13af4 100644 --- a/.env +++ b/.env @@ -6,6 +6,7 @@ # DATABASE_URL="sqlserver://3team.devgrr.kr:1433;database=onsitesurvey;user=sa;password=1q2w3e4r!;encrypt=true;trustServerCertificate=true;" DATABASE_URL="sqlserver://3team.devgrr.kr:1433;database=onsitesurvey;user=sa;password=1q2w3e4r!;encrypt=true;trustServerCertificate=true;" +# DATABASE_URL="mysql://root:root@localhost:3306/onsitesurvey" # SESSION_PASSWORD="QWERASDFZXCV1234567890REWQFDSAVCXZ" SESSION_PASSWORD="This application is for mobile field research" \ No newline at end of file diff --git a/next.config.ts b/next.config.ts index 1a3917a..bc718b5 100644 --- a/next.config.ts +++ b/next.config.ts @@ -12,10 +12,10 @@ const nextConfig: NextConfig = { source: '/api/user/login', destination: `${process.env.NEXT_PUBLIC_QSP_API_URL}/api/user/login`, }, - { - source: '/api/:path*', - destination: `${process.env.NEXT_PUBLIC_API_URL}/api/:path*`, - }, + // { + // source: '/api/:path*', + // destination: `${process.env.NEXT_PUBLIC_API_URL}/api/:path*`, + // }, ] }, } diff --git a/package.json b/package.json index d00c56c..519fd8a 100644 --- a/package.json +++ b/package.json @@ -14,6 +14,7 @@ "@tanstack/react-query-devtools": "^5.71.0", "axios": "^1.8.4", "iron-session": "^8.0.4", + "lucide": "^0.503.0", "mssql": "^11.0.1", "next": "15.2.4", "react": "^19.0.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 74c7972..b1875d7 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -23,6 +23,9 @@ importers: iron-session: specifier: ^8.0.4 version: 8.0.4 + lucide: + specifier: ^0.503.0 + version: 0.503.0 mssql: specifier: ^11.0.1 version: 11.0.1 @@ -1109,6 +1112,9 @@ packages: lodash.once@4.1.1: resolution: {integrity: sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==} + lucide@0.503.0: + resolution: {integrity: sha512-ZAVlxBU4dbSUAVidb2eT0fH3bTtKCj7M2aZNAVsFOrcnazvYJFu6I8OxFE+Fmx5XNf22Cw4Ln3NBHfBxNfoFOw==} + math-intrinsics@1.1.0: resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==} engines: {node: '>= 0.4'} @@ -2340,6 +2346,8 @@ snapshots: lodash.once@4.1.1: {} + lucide@0.503.0: {} + math-intrinsics@1.1.0: {} micromatch@4.0.8: diff --git a/public/assets/images/common/btn_arr_up.svg b/public/assets/images/common/btn_arr_up.svg new file mode 100644 index 0000000..b90389f --- /dev/null +++ b/public/assets/images/common/btn_arr_up.svg @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/src/app/api/survey-sale/[id]/route.ts b/src/app/api/survey-sale/[id]/route.ts deleted file mode 100644 index 04ccf2d..0000000 --- a/src/app/api/survey-sale/[id]/route.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { NextResponse } from 'next/server' - -// export async function POST(request: Request, { params }: { params: { id: string } }) { -// const body = await request.json() -// const { id } = params - -// // @ts-ignore -// const survey = await prisma.SD_SERVEY_SALES_BASIC_INFO.update({ -// where: { id: Number(id) }, -// data: { -// detail_info: { -// create: body, -// }, -// }, -// }) -// return NextResponse.json({ message: 'Survey detail created successfully' }) -// } - -// export async function GET(request: Request, { params }: { params: { id: string } }) { -// const { id } = params -// // @ts-ignore -// const survey = await prisma.SD_SERVEY_SALES_BASIC_INFO.findUnique({ -// where: { id: Number(id) }, -// include: { -// detail_info: true, -// }, -// }) -// return NextResponse.json(survey) -// } - -// export async function PUT(request: Request, { params }: { params: { id: string } }) { -// const { id } = params -// const body = await request.json() -// // @ts-ignore -// const survey = await prisma.SD_SERVEY_SALES_BASIC_INFO.update({ -// where: { id: Number(id) }, -// data: { -// ...body, -// detail_info: { -// update: body.detail_info, -// }, -// }, -// }) -// return NextResponse.json(survey) -// } - -// export async function DELETE(request: Request, { params }: { params: { id: string; detail_id: string } }) { -// const { id, detail_id } = params -// if (detail_id) { -// // @ts-ignore -// const survey = await prisma.SD_SERVEY_SALES_DETAIL_INFO.delete({ -// where: { id: Number(detail_id) }, -// }) -// } else { -// // @ts-ignore -// const survey = await prisma.SD_SERVEY_SALES_BASIC_INFO.delete({ -// where: { id: Number(id) }, -// }) -// } -// return NextResponse.json({ message: 'Survey deleted successfully' }) -// } - -// export async function PATCH(request: Request, { params }: { params: { id: string } }) { -// const { id } = params -// // @ts-ignore -// const survey = await prisma.SD_SERVEY_SALES_BASIC_INFO.update({ -// where: { id: Number(id) }, -// data: { -// submission_status: true, -// }, -// }) -// return NextResponse.json({ message: 'Survey confirmed successfully' }) -// } diff --git a/src/app/api/survey-sale/route.ts b/src/app/api/survey-sale/route.ts deleted file mode 100644 index 064c686..0000000 --- a/src/app/api/survey-sale/route.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { NextResponse } from 'next/server' -import { prisma } from '@/libs/prisma' - -export async function POST(request: Request) { - const body = await request.json() - // @ts-ignore - const res = await prisma.SD_SERVEY_SALES_BASIC_INFO.create({ - data: body, - }) - return NextResponse.json(res) -} - -export async function GET() { - try { - // @ts-ignore - const res = await prisma.SD_SERVEY_SALES_BASIC_INFO.findMany() - return NextResponse.json(res) - } catch (error) { - console.error(error) - } -} - -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' }) -} diff --git a/src/app/api/survey-sales/[id]/route.ts b/src/app/api/survey-sales/[id]/route.ts new file mode 100644 index 0000000..3da5981 --- /dev/null +++ b/src/app/api/survey-sales/[id]/route.ts @@ -0,0 +1,139 @@ +import { NextResponse } from 'next/server' +import { prisma } from '@/libs/prisma' + +export async function GET(request: Request, context: { params: { id: string } }) { + try { + const { id } = await context.params + // @ts-ignore + const survey = await prisma.SD_SURVEY_SALES_BASIC_INFO.findUnique({ + where: { ID: Number(id) }, + include: { + DETAIL_INFO: true, + }, + }) + return NextResponse.json(survey) + } catch (error) { + console.error('Error fetching survey:', error) + return NextResponse.json({ error: 'Failed to fetch survey' }, { status: 500 }) + } +} + +export async function PUT(request: Request, context: { params: { id: string } }) { + try { + const { id } = await context.params + const body = await request.json() + console.log('body:: ', body) + + // DETAIL_INFO를 분리 + const { DETAIL_INFO, ...basicInfo } = body + + // @ts-ignore + const survey = await prisma.SD_SURVEY_SALES_BASIC_INFO.update({ + where: { ID: Number(id) }, + data: { + ...basicInfo, + UPT_DT: new Date(), + DETAIL_INFO: DETAIL_INFO + ? { + upsert: { + create: DETAIL_INFO, + update: DETAIL_INFO, + }, + } + : undefined, + }, + include: { + DETAIL_INFO: true, + }, + }) + return NextResponse.json(survey) + } catch (error) { + console.error('Error updating survey:', error) + return NextResponse.json({ error: 'Failed to update survey' }, { status: 500 }) + } +} + +export async function DELETE(request: Request, context: { params: { id: string } }) { + try { + const { id } = await context.params + + await prisma.$transaction(async (tx) => { + // @ts-ignore + const detailData = await tx.SD_SURVEY_SALES_BASIC_INFO.findUnique({ + where: { ID: Number(id) }, + select: { + DETAIL_INFO: true, + }, + }) + + if (detailData?.DETAIL_INFO?.ID) { + // @ts-ignore + await tx.SD_SURVEY_SALES_DETAIL_INFO.delete({ + where: { ID: Number(detailData.DETAIL_INFO.ID) }, + }) + } + + // @ts-ignore + await tx.SD_SURVEY_SALES_BASIC_INFO.delete({ + where: { ID: Number(id) }, + }) + }) + + return NextResponse.json({ message: 'Survey deleted successfully' }) + } catch (error) { + console.error('Error deleting survey:', error) + return NextResponse.json({ error: 'Failed to delete survey' }, { status: 500 }) + } +} + +export async function PATCH(request: Request, context: { params: { id: string } }) { + try { + const { id } = await context.params + const body = await request.json() + + if (body.submit) { + // @ts-ignore + const survey = await prisma.SD_SURVEY_SALES_BASIC_INFO.update({ + where: { ID: Number(id) }, + data: { + SUBMISSION_STATUS: true, + SUBMISSION_DATE: new Date(), + }, + }) + return NextResponse.json({ message: 'Survey confirmed successfully' }) + } else { + // @ts-ignore + const hasDetails = await prisma.SD_SURVEY_SALES_DETAIL_INFO.findUnique({ + where: { BASIC_INFO_ID: Number(id) }, + }) + + if (hasDetails) { + //@ts-ignore + const result = await prisma.SD_SURVEY_SALES_BASIC_INFO.update({ + where: { ID: Number(id) }, + data: { + UPT_DT: new Date(), + DETAIL_INFO: { + update: body.DETAIL_INFO, + }, + }, + }) + return NextResponse.json(result) + } else { + // @ts-ignore + const survey = await prisma.SD_SURVEY_SALES_BASIC_INFO.update({ + where: { ID: Number(id) }, + data: { + DETAIL_INFO: { + create: body.DETAIL_INFO, + }, + }, + }) + return NextResponse.json({ message: 'Survey detail created successfully' }) + } + } + } catch (error) { + console.error('Error updating survey:', error) + return NextResponse.json({ error: 'Failed to update survey' }, { status: 500 }) + } +} diff --git a/src/app/api/survey-sales/route.ts b/src/app/api/survey-sales/route.ts new file mode 100644 index 0000000..a2df29d --- /dev/null +++ b/src/app/api/survey-sales/route.ts @@ -0,0 +1,241 @@ +import { NextResponse } from 'next/server' +import { prisma } from '@/libs/prisma' + +/** + * 검색 파라미터 + */ +type SearchParams = { + keyword?: string | null // 검색어 + searchOption?: string | null // 검색 옵션 (select 옵션) + isMySurvey?: string | null // 내가 작성한 매물 + sort?: string | null // 정렬 방식 + offset?: string | null + role?: string | null // 회원권한한 + store?: string | null // 판매점ID + builderNo?: string | null // 시공ID +} + +type WhereCondition = { + AND: any[] + OR?: any[] + [key: string]: any +} + +// 검색 가능한 필드 옵션 +const SEARCH_OPTIONS = [ + 'BUILDING_NAME', // 건물명 + 'REPRESENTATIVE', // 담당자 + 'STORE', // 판매점 + 'CONSTRUCTION_POINT', // 시공점 + 'CUSTOMER_NAME', // 고객명 + 'POST_CODE', // 우편번호 + 'ADDRESS', // 주소 + 'ADDRESS_DETAIL', // 상세주소 +] as const + +// 페이지당 항목 수 +const ITEMS_PER_PAGE = 10 + +/** + * 키워드 검색 조건 생성 함수 + * @param keyword 검색 키워드 + * @param searchOption 검색 옵션 + * @returns 검색 조건 객체 + */ +const createKeywordSearchCondition = (keyword: string, searchOption: string): WhereCondition => { + const where: WhereCondition = { AND: [] } + + if (searchOption === 'all') { + // 모든 필드 검색 시 OR 조건 사용 + where.OR = [] + + // ID가 숫자인 경우 ID 검색 조건 추가 + if (keyword.match(/^\d+$/) || !isNaN(Number(keyword))) { + where.OR.push({ + ID: { equals: Number(keyword) }, + }) + } + + where.OR.push( + ...SEARCH_OPTIONS.map((field) => ({ + [field]: { contains: keyword }, + })), + ) + } else if (SEARCH_OPTIONS.includes(searchOption.toUpperCase() as any)) { + // 특정 필드 검색 + where[searchOption.toUpperCase()] = { contains: keyword } + } else if (searchOption === 'id') { + // ID 검색 (숫자 변환 필요) + const number = Number(keyword) + if (!isNaN(number)) { + where.ID = { equals: number } + } else { + // 유효하지 않은 ID 검색 시 빈 결과 반환 + where.ID = { equals: null } + } + } + return where +} + +/** + * 회원 역할별 검색 조건 생성 함수 + * @param params 검색 파라미터 + * @returns 검색 조건 객체 + */ +const createMemberRoleCondition = (params: SearchParams): WhereCondition => { + const where: WhereCondition = { AND: [] } + + switch (params.role) { + case 'Admin': // 1차점 + // 같은 판매점에서 작성된 매물 + 2차점에서 제출받은 매물 + where.OR = [ + { + AND: [{ STORE: { equals: params.store } }], + }, + { + AND: [{ STORE: { startsWith: params.store } }, { SUBMISSION_STATUS: { equals: true } }], + }, + ] + break + + case 'Admin_Sub': // 2차점 + where.OR = [ + { + AND: [ + { STORE: { equals: params.store } }, + { + OR: [{ CONSTRUCTION_POINT: { equals: null } }, { CONSTRUCTION_POINT: { equals: '' } }], + }, + ], + }, + { + AND: [ + { STORE: { equals: params.store } }, + { CONSTRUCTION_POINT: { not: null } }, + { CONSTRUCTION_POINT: { not: '' } }, + { SUBMISSION_STATUS: { equals: true } }, + ], + }, + ] + break + + case 'Builder': // 2차점 시공권한 + case 'Partner': // Partner + // 같은 시공ID에서 작성된 매물 + where.AND?.push({ + CONSTRUCTION_POINT: { equals: params.builderNo }, + }) + break + + case 'T01': + case 'User': + // 모든 매물 조회 가능 (추가 조건 없음) + break + } + + return where +} + +/** + * GET 핸들러 - 설문 목록 조회 + */ +export async function GET(request: Request) { + try { + // URL 파라미터 파싱 + const { searchParams } = new URL(request.url) + const params: SearchParams = { + keyword: searchParams.get('keyword'), + searchOption: searchParams.get('searchOption'), + isMySurvey: searchParams.get('isMySurvey'), + sort: searchParams.get('sort'), + offset: searchParams.get('offset'), + role: searchParams.get('role'), + store: searchParams.get('store'), + builderNo: searchParams.get('builderNo'), + } + + // 검색 조건 구성 + const where: WhereCondition = { AND: [] } + + // 내가 작성한 매물 조건 적용 + if (params.isMySurvey) { + where.AND.push({ REPRESENTATIVE: params.isMySurvey }) + } + + // 키워드 검색 조건 적용 + if (params.keyword && params.searchOption) { + where.AND.push(createKeywordSearchCondition(params.keyword, params.searchOption)) + } + + // 회원 유형 조건 적용 + const roleCondition = createMemberRoleCondition(params) + if (Object.keys(roleCondition).length > 0) { + where.AND.push(roleCondition) + } + + // 페이지네이션 데이터 조회 + //@ts-ignore + const surveys = await prisma.SD_SURVEY_SALES_BASIC_INFO.findMany({ + where, + orderBy: params.sort === 'created' ? { REG_DT: 'desc' } : { UPT_DT: 'desc' }, + skip: Number(params.offset), + take: ITEMS_PER_PAGE, + }) + // 전체 개수만 조회 + //@ts-ignore + const count = await prisma.SD_SURVEY_SALES_BASIC_INFO.count({ where }) + return NextResponse.json({ data: { data: surveys, count: count } }) + } catch (error) { + console.error(error) + return NextResponse.json({ error: 'Fail Read Survey' }, { status: 500 }) + } +} + +/** + * PUT 핸들러 - 상세 정보 추가 + */ +export async function PUT(request: Request) { + try { + const body = await request.json() + + // 상세 정보 생성을 위한 데이터 구성 + const detailInfo = { + ...body.detail_info, + BASIC_INFO_ID: body.id, + } + + // 상세 정보 생성 + //@ts-ignore + await prisma.SD_SURVEY_SALES_DETAIL_INFO.create({ + data: detailInfo, + }) + + return NextResponse.json({ + message: 'Success Update Survey', + }) + } catch (error) { + console.error(error) + return NextResponse.json({ error: 'Fail Update Survey' }, { status: 500 }) + } +} + +export async function POST(request: Request) { + try { + const body = await request.json() + const { DETAIL_INFO, ...basicInfo } = body + // 기본 정보 생성 + //@ts-ignore + const result = await prisma.SD_SURVEY_SALES_BASIC_INFO.create({ + data: { + ...basicInfo, + DETAIL_INFO: { + create: DETAIL_INFO, + }, + }, + }) + return NextResponse.json(result) + } catch (error) { + console.error(error) + return NextResponse.json({ error: 'Fail Create Survey' }, { status: 500 }) + } +} diff --git a/src/app/layout.tsx b/src/app/layout.tsx index 093dbec..7ba05b0 100644 --- a/src/app/layout.tsx +++ b/src/app/layout.tsx @@ -22,7 +22,7 @@ interface RootLayoutProps { header: ReactNode footer: ReactNode floatBtn: ReactNode -} +}6 export default async function RootLayout({ children, header, footer, floatBtn }: RootLayoutProps): Promise { const cookieStore = await cookies() @@ -33,7 +33,7 @@ export default async function RootLayout({ children, header, footer, floatBtn }: return ( - + {header} diff --git a/src/app/survey-sale/[id]/page.tsx b/src/app/survey-sale/[id]/page.tsx index bc48257..ac22151 100644 --- a/src/app/survey-sale/[id]/page.tsx +++ b/src/app/survey-sale/[id]/page.tsx @@ -1,29 +1,10 @@ import DataTable from '@/components/survey-sale/detail/DataTable' -import DetailForm from '@/components/survey-sale/detail/DetailForm' -import { SurveyBasicInfo } from '@/types/Survey' export default function page() { - const surveyInfo: SurveyBasicInfo = { - ID: 1, - REPRESENTATIVE: 'HG', - STORE: 'HWJ(T01)', - CONSTRUCTION_POINT: '施工点名表示', - INVESTIGATION_DATE: '2021-01-01', - BUILDING_NAME: 'ビル名表示', - CUSTOMER_NAME: '顧客名表示', - POST_CODE: '1234567890', - ADDRESS: '東京都千代田区永田町1-7-1', - ADDRESS_DETAIL: '永田町ビル101号室', - SUBMISSION_STATUS: true, - SUBMISSION_DATE: '2021-01-01', - DETAIL_INFO: null, - REG_DT: new Date(), - UPT_DT: new Date(), - } return ( <> - + {/* */} > ) } diff --git a/src/app/survey-sale/basic-info/page.tsx b/src/app/survey-sale/basic-info/page.tsx deleted file mode 100644 index 20cbeb8..0000000 --- a/src/app/survey-sale/basic-info/page.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import BasicForm from '@/components/survey-sale/detail/BasicForm' - -export default function page() { - return ( - <> - - > - ) -} diff --git a/src/app/survey-sale/page.tsx b/src/app/survey-sale/page.tsx index fc6e6a3..f7692b4 100644 --- a/src/app/survey-sale/page.tsx +++ b/src/app/survey-sale/page.tsx @@ -1,10 +1,8 @@ import ListTable from '@/components/survey-sale/list/ListTable' -import SearchForm from '@/components/survey-sale/list/SearchForm' export default function page() { return ( <> - > ) diff --git a/src/app/survey-sale/regist/page.tsx b/src/app/survey-sale/regist/page.tsx new file mode 100644 index 0000000..0dec827 --- /dev/null +++ b/src/app/survey-sale/regist/page.tsx @@ -0,0 +1,9 @@ +import RegistForm from '@/components/survey-sale/detail/RegistForm' + +export default function RegistPage() { + return ( + <> + + > + ) +} diff --git a/src/app/survey-sale/roof-info/page.tsx b/src/app/survey-sale/roof-info/page.tsx deleted file mode 100644 index 2bdfea5..0000000 --- a/src/app/survey-sale/roof-info/page.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import RoofInfoForm from '@/components/survey-sale/detail/RoofInfoForm' - -export default function page() { - return ( - <> - - > - ) -} diff --git a/src/components/LoadMoreButton.tsx b/src/components/LoadMoreButton.tsx new file mode 100644 index 0000000..219b064 --- /dev/null +++ b/src/components/LoadMoreButton.tsx @@ -0,0 +1,21 @@ +'use client' + +interface LoadMoreButtonProps { + hasMore: boolean + onLoadMore: () => void +} + +export default function LoadMoreButton({ hasMore, onLoadMore }: LoadMoreButtonProps) { + return ( + <> + {hasMore ? ( + + もっと見る + + + ) : ( + <>> + )} + > + ) +} diff --git a/src/components/inquiry/ListForm.tsx b/src/components/inquiry/ListForm.tsx index 0b6ff3f..14f38bb 100644 --- a/src/components/inquiry/ListForm.tsx +++ b/src/components/inquiry/ListForm.tsx @@ -1,10 +1,13 @@ 'use client' +import { useRouter } from 'next/navigation' + export default function ListForm() { + const router = useRouter() return ( <> - + router.push('/inquiry/regist')}> お問い合わせ diff --git a/src/components/inquiry/ListTable.tsx b/src/components/inquiry/ListTable.tsx index 95911a6..d65fa85 100644 --- a/src/components/inquiry/ListTable.tsx +++ b/src/components/inquiry/ListTable.tsx @@ -1,5 +1,52 @@ 'use client' + +import { use, useEffect, useState } from 'react' +import LoadMoreButton from '../LoadMoreButton' + +const inquiryDummy = [ + { id: 1, category: '屋根', title: '屋根材適合性確認依頼', date: '2025.04.02', status: 'completed' }, + { id: 2, category: '外壁', title: '外壁仕上げ材確認', date: '2025.04.03', status: 'completed' }, + { id: 3, category: '設備', title: '換気システム図面確認', date: '2025.04.04', status: 'completed' }, + { id: 4, category: '基礎', title: '基礎配筋検査依頼', date: '2025.04.05', status: 'completed' }, + { id: 5, category: '内装', title: 'クロス仕様確認', date: '2025.04.06', status: 'waiting' }, + { id: 6, category: '構造', title: '耐震壁位置変更申請', date: '2025.04.07', status: 'completed' }, + { id: 7, category: '屋根', title: '雨樋取付方法確認', date: '2025.04.08', status: 'completed' }, + { id: 8, category: '外構', title: 'フェンス高さ変更相談', date: '2025.04.09', status: 'completed' }, + { id: 9, category: '設備', title: '給湯器設置位置確認', date: '2025.04.10', status: 'completed' }, + { id: 10, category: '外壁', title: 'タイル割付案確認依頼', date: '2025.04.11', status: 'waiting' }, + { id: 11, category: '内装', title: '照明配置図面確認', date: '2025.04.12', status: 'completed' }, + { id: 12, category: '構造', title: '梁補強案確認', date: '2025.04.13', status: 'completed' }, + { id: 13, category: '基礎', title: '杭長設計確認依頼', date: '2025.04.14', status: 'completed' }, + { id: 14, category: '屋根', title: '断熱材施工方法確認', date: '2025.04.15', status: 'completed' }, + { id: 15, category: '外構', title: '駐車場勾配図確認', date: '2025.04.16', status: 'completed' }, +] + +const badgeStyle = [ + { + id: 'completed', + label: '回答完了', + color: 'blue', + }, + { + id: 'waiting', + label: '回答待ち', + color: 'orange', + }, +] export default function ListTable() { + const [offset, setOffset] = useState(0) + const [hasMore, setHasMore] = useState(true) + + const inquiryList = inquiryDummy.slice(0, offset + 10) + + useEffect(() => { + if (inquiryDummy.length > offset + 10) { + setHasMore(true) + } else { + setHasMore(false) + } + }, [inquiryList]) + return ( <> @@ -13,10 +60,8 @@ export default function ListTable() { 全体 - 全体 - 全体 - 全体 - 全体 + 回答待ち + 回答完了 @@ -80,9 +125,7 @@ export default function ListTable() { - - もっと見る - + setOffset(offset + 10)} /> diff --git a/src/components/popup/ZipCodePopup.tsx b/src/components/popup/ZipCodePopup.tsx index 45dd486..4923833 100644 --- a/src/components/popup/ZipCodePopup.tsx +++ b/src/components/popup/ZipCodePopup.tsx @@ -1,18 +1,56 @@ 'use client' +import { useServey } from '@/hooks/useSurvey' +import { useAddressStore } from '@/store/addressStore' import { usePopupController } from '@/store/popupController' import { useState } from 'react' +type Address = { + address1: string + address2: string + address3: string + kana1: string + kana2: string + kana3: string + prefcode: string + zipcode: string +} + export default function ZipCodePopup() { const [searchValue, setSearchValue] = useState('') //search 데이터 유무 + const [selected, setSelected] = useState('') + const { setAddressData } = useAddressStore() + const { getZipCode } = useServey() + const [addressInfo, setAddressInfo] = useState([]) //search 데이터 value 추가 + + const popupController = usePopupController() + + const handleApply = () => { + console.log(addressInfo?.[0]) + setAddressData({ + post_code: addressInfo?.[0]?.zipcode || '', + address: addressInfo?.[0]?.address1 || '', + address_detail: addressInfo?.[0]?.address2 + ' ' + addressInfo?.[0]?.address3 || '', + }) + popupController.setZipCodePopup(false) + } + const handleChange = (e: React.ChangeEvent) => { setSearchValue(e.target.value) } - const popupController = usePopupController() - + const handleSearch = () => { + const addressData = getZipCode(searchValue) + addressData.then((address) => { + if (address) { + setAddressInfo(address) + } else { + setAddressInfo([]) + } + }) + } return ( <> @@ -33,10 +71,10 @@ export default function ZipCodePopup() { - + {/*input에 데이터 있으면 삭제버튼 보임 */} {searchValue && setSearchValue('')}>} - + @@ -50,31 +88,23 @@ export default function ZipCodePopup() { - - 東京都 - 浜松 - 浜松町 - - - 東京都 - 浜松 - 浜松町 - - - 東京都 - 浜松 - 浜松町 - + {addressInfo?.map((item, index) => ( + setSelected(item.zipcode)}> + {item.address1} + {item.address2} + {item.address3} + + ))} - + 住所の適用 - + popupController.setZipCodePopup(false)}> 閉じる diff --git a/src/components/survey-sale/common/NavTab.tsx b/src/components/survey-sale/common/NavTab.tsx index 8029afd..ffa6ea7 100644 --- a/src/components/survey-sale/common/NavTab.tsx +++ b/src/components/survey-sale/common/NavTab.tsx @@ -1,31 +1,74 @@ 'use client' import { useSurveySaleTabState } from '@/store/surveySaleTabState' -import { usePathname, useRouter } from 'next/navigation' +import { usePathname, useRouter, useSearchParams, useParams } from 'next/navigation' import { useEffect } from 'react' export default function NavTab() { const router = useRouter() const pathname = usePathname() - if (pathname === '/survey-sale') { - return null - } + const searchParams = useSearchParams() + const id = searchParams.get('id') + const isTemp = searchParams.get('isTemp') - const { basicInfoSelected, roofInfoSelected, reset } = useSurveySaleTabState() + const params = useParams() + const detailId = params.id + + const { basicInfoSelected, roofInfoSelected, reset, setBasicInfoSelected, setRoofInfoSelected } = useSurveySaleTabState() useEffect(() => { return () => { reset() } - }, []) + }, [reset]) + + if (pathname === '/survey-sale') { + return null + } + + const scrollSection = (section: string) => { + const sectionElement = document.getElementById(section) + if (sectionElement) { + sectionElement.scrollIntoView({ behavior: 'smooth' }) + } + } const handleBasicInfoClick = () => { - router.push('/survey-sale/basic-info') + // if (id) { + // router.push(`/survey-sale/basic-info?id=${id}`) + // return + // } + if (detailId) { + router.push(`/survey-sale/${detailId}`) + return + } + scrollSection('basic-form-section') + + setBasicInfoSelected() } const handleRoofInfoClick = () => { - router.push('/survey-sale/roof-info') + // if (id) { + // if (isTemp === 'true') { + // alert('基本情報が一時保存された状態です。') + // return + // } + // router.push(`/survey-sale/roof-info?id=${id}`) + // return + // } + if (detailId) { + router.push(`/survey-sale/${detailId}?tab=roof-info`) + return + } + if (pathname === '/survey-sale/basic-info') { + alert('基本情報を先に保存してください。') + return null + } + // if (pathname === '/survey-sale/regist') { + scrollSection('roof-form-section') + // } + setRoofInfoSelected() } return ( diff --git a/src/components/survey-sale/detail/BasicForm.tsx b/src/components/survey-sale/detail/BasicForm.tsx index 5b7fb31..716930e 100644 --- a/src/components/survey-sale/detail/BasicForm.tsx +++ b/src/components/survey-sale/detail/BasicForm.tsx @@ -2,15 +2,11 @@ import { useEffect, useState } from 'react' import { useSurveySaleTabState } from '@/store/surveySaleTabState' -import { SurveyBasicInfo } from '@/types/Survey' +import { SurveyBasicRequest } from '@/types/Survey' import { Mode } from 'fs' -export default function BasicForm(props: { - surveyInfo: Partial - setSurveyInfo: (surveyInfo: Partial) => void - mode: Mode -}) { - const { surveyInfo, setSurveyInfo, mode } = props +export default function BasicForm(props: { basicInfo: SurveyBasicRequest; setBasicInfo: (basicInfo: SurveyBasicRequest) => void; mode: Mode }) { + const { basicInfo, setBasicInfo, mode } = props const { setBasicInfoSelected } = useSurveySaleTabState() const [isFlip, setIsFlip] = useState(true) @@ -36,8 +32,8 @@ export default function BasicForm(props: { type="text" className="input-frame" readOnly={mode === 'READ'} - value={surveyInfo?.REPRESENTATIVE} - onChange={(e) => setSurveyInfo({ ...surveyInfo, REPRESENTATIVE: e.target.value })} + value={basicInfo?.representative ?? ''} + onChange={(e) => setBasicInfo({ ...basicInfo, representative: e.target.value })} /> @@ -46,8 +42,8 @@ export default function BasicForm(props: { type="text" className="input-frame" readOnly={mode === 'READ'} - value={surveyInfo?.BUILDING_NAME ?? ''} - onChange={(e) => setSurveyInfo({ ...surveyInfo, BUILDING_NAME: e.target.value })} + value={basicInfo?.store ?? ''} + onChange={(e) => setBasicInfo({ ...basicInfo, store: e.target.value })} /> @@ -56,8 +52,8 @@ export default function BasicForm(props: { type="text" className="input-frame" readOnly={mode === 'READ'} - value={surveyInfo?.CONSTRUCTION_POINT ?? ''} - onChange={(e) => setSurveyInfo({ ...surveyInfo, CONSTRUCTION_POINT: e.target.value })} + value={basicInfo?.constructionPoint ?? ''} + onChange={(e) => setBasicInfo({ ...basicInfo, constructionPoint: e.target.value })} /> @@ -71,38 +67,35 @@ export default function BasicForm(props: { - + ) : ( - + )} {/* 건물명 */} 建物名 - + {/* 고객명 */} 建物名 - + 郵便番号/都道府県 {/* 우편번호 */} - + {/* 도도부현 */} - + {/* 주소 */} - - - 郵便番号 @@ -112,7 +105,7 @@ export default function BasicForm(props: { 市区町村名, 以後の住所 - + diff --git a/src/components/survey-sale/detail/ButtonForm.tsx b/src/components/survey-sale/detail/ButtonForm.tsx index 84b4b4c..4b2b9fa 100644 --- a/src/components/survey-sale/detail/ButtonForm.tsx +++ b/src/components/survey-sale/detail/ButtonForm.tsx @@ -1,6 +1,6 @@ -import { Mode } from '@/types/Survey' +import { Mode, SurveyBasicRequest, SurveyDetailRequest } from '@/types/Survey' -export default function ButtonForm(props: { mode: Mode; setMode: (mode: Mode) => void }) { +export default function ButtonForm(props: { mode: Mode; setMode: (mode: Mode) => void; data: { basic: SurveyBasicRequest; roof: SurveyDetailRequest } }) { const { mode, setMode } = props return ( <> diff --git a/src/components/survey-sale/detail/DataTable.tsx b/src/components/survey-sale/detail/DataTable.tsx index b47c092..1d06e2e 100644 --- a/src/components/survey-sale/detail/DataTable.tsx +++ b/src/components/survey-sale/detail/DataTable.tsx @@ -1,6 +1,36 @@ 'use client' +import { useServey } from '@/hooks/useSurvey' +import { useParams, useSearchParams } from 'next/navigation' +import { useEffect, useState } from 'react' +import DetailForm from './DetailForm' +import { SurveyBasicInfo } from '@/types/Survey' + export default function DataTable() { + const params = useParams() + const id = params.id + + const searchParams = useSearchParams() + const isTemp = searchParams.get('isTemporary') + + const { surveyDetail, isLoadingSurveyDetail } = useServey(Number(id)) + const [isTemporary, setIsTemporary] = useState(isTemp === 'true') + + const { validateSurveyDetail } = useServey(Number(id)) + + useEffect(() => { + if (surveyDetail?.detailInfo) { + const validate = validateSurveyDetail(surveyDetail.detailInfo) + if (validate.trim() !== '') { + setIsTemporary(false) + } + } + }, [surveyDetail]) + + if (isLoadingSurveyDetail) { + return Loading... + } + return ( <> @@ -12,19 +42,35 @@ export default function DataTable() { 登録番号 - 0000000020 + {isTemporary ? ( + + 仮保存 + + ) : ( + {surveyDetail?.id} + )} 登録日 - 2025.04.11 + {surveyDetail?.regDt ? new Date(surveyDetail.regDt).toLocaleString() : ''} 更新日時 - 2025.04.11 15:06:29 + {surveyDetail?.uptDt ? new Date(surveyDetail.uptDt).toLocaleString() : ''} 提出可否 - 2025.04.12 10:00:00 (INTERPLUG –販売店) + + {surveyDetail?.submissionStatus && surveyDetail?.submissionDate ? ( + <> + {/* TODO: 제출한 판매점 ID 추가 필요 */} + {new Date(surveyDetail.submissionDate).toLocaleString()} + {surveyDetail.store} + > + ) : ( + '-' + )} + ダウンロード @@ -37,6 +83,7 @@ export default function DataTable() { + > ) } diff --git a/src/components/survey-sale/detail/DetailForm.tsx b/src/components/survey-sale/detail/DetailForm.tsx index 6e5fc24..387bb4f 100644 --- a/src/components/survey-sale/detail/DetailForm.tsx +++ b/src/components/survey-sale/detail/DetailForm.tsx @@ -1,52 +1,92 @@ 'use client' -import { Mode, SurveyBasicInfo } from '@/types/Survey' +import { Mode, SurveyBasicInfo, SurveyBasicRequest, SurveyDetailRequest } from '@/types/Survey' import { useEffect, useState } from 'react' import ButtonForm from './ButtonForm' import BasicForm from './BasicForm' import RoofForm from './RoofForm' +const roofInfoForm: SurveyDetailRequest = { + contractCapacity: null, + retailCompany: null, + supplementaryFacilities: null, + supplementaryFacilitiesEtc: null, + installationSystem: null, + installationSystemEtc: null, + constructionYear: null, + constructionYearEtc: null, + roofMaterial: null, + roofMaterialEtc: null, + roofShape: null, + roofShapeEtc: null, + roofSlope: null, + houseStructure: '1', + houseStructureEtc: null, + rafterMaterial: '1', + rafterMaterialEtc: null, + rafterSize: null, + rafterSizeEtc: null, + rafterPitch: null, + rafterPitchEtc: null, + rafterDirection: '1', + openFieldPlateKind: null, + openFieldPlateKindEtc: null, + openFieldPlateThickness: null, + leakTrace: false, + waterproofMaterial: null, + waterproofMaterialEtc: null, + insulationPresence: '1', + insulationPresenceEtc: null, + structureOrder: null, + structureOrderEtc: null, + installationAvailability: null, + installationAvailabilityEtc: null, + memo: null, +} + +const basicInfoForm: SurveyBasicRequest = { + representative: '', + store: null, + constructionPoint: null, + investigationDate: new Date().toLocaleDateString('en-CA'), + buildingName: null, + customerName: null, + postCode: null, + address: null, + addressDetail: null, + submissionStatus: false, + submissionDate: null, +} export default function DetailForm(props: { surveyInfo?: SurveyBasicInfo; mode?: Mode }) { - const [surveyInfo, setSurveyInfo] = useState>( - props.surveyInfo ?? { - REPRESENTATIVE: '', - CONSTRUCTION_POINT: '', - STORE: '', - INVESTIGATION_DATE: '', - BUILDING_NAME: '', - CUSTOMER_NAME: '', - POST_CODE: '', - ADDRESS: '', - ADDRESS_DETAIL: '', - SUBMISSION_STATUS: true, - SUBMISSION_DATE: '2021-01-01', - DETAIL_INFO: null, - REG_DT: new Date(), - UPT_DT: new Date(), - }, - ) - const [roofValue, setRoofValue] = useState(false) const [mode, setMode] = useState(props.mode ?? 'CREATE') - const basicInfoProps = { surveyInfo, setSurveyInfo, mode } - const roofInfoProps = { surveyInfo, mode } - const buttonFormProps = { mode, setMode } + const [basicInfoData, setBasicInfoData] = useState(basicInfoForm) + const [roofInfoData, setRoofInfoData] = useState(roofInfoForm) useEffect(() => { - // setMode(props.surveyInfo ? 'EDIT' : 'CREATE') - }, [props.surveyInfo]) + if (props.surveyInfo && (mode === 'EDIT' || mode === 'READ')) { + const { id, uptDt, regDt, detailInfo, ...rest } = props.surveyInfo + setBasicInfoData(rest) + if (detailInfo) { + const { id, uptDt, regDt, basicInfoId, ...rest } = detailInfo + setRoofInfoData(rest) + } + } + }, [props.surveyInfo, mode]) - useEffect(() => { - console.log(surveyInfo) - }, [surveyInfo]) + const data = { + basic: basicInfoData, + roof: roofInfoData, + } + + const buttonFormProps = { mode, setMode, data } return ( <> - {mode} {/* 기본정보 */} - + {/* 전기/지붕정보 */} - + > diff --git a/src/components/survey-sale/detail/RegistForm.tsx b/src/components/survey-sale/detail/RegistForm.tsx new file mode 100644 index 0000000..4377713 --- /dev/null +++ b/src/components/survey-sale/detail/RegistForm.tsx @@ -0,0 +1,29 @@ +import { Mode } from '@/types/Survey' +import { useSearchParams } from 'next/navigation' +import DetailForm from './DetailForm' +import { useServey } from '@/hooks/useSurvey' +import { useEffect, useState } from 'react' +import { SurveyBasicInfo } from '@/types/Survey' +import { useSessionStore } from '@/store/session' + +export default function RegistForm() { + const searchParams = useSearchParams() + const id = searchParams.get('id') + + const { surveyDetail } = useServey(Number(id)) + const { session } = useSessionStore() + + const [mode, setMode] = useState('CREATE') + + useEffect(() => { + if (id) { + setMode('EDIT') + } + }, [id]) + + return ( + <> + + > + ) +} diff --git a/src/components/survey-sale/detail/RoofForm.tsx b/src/components/survey-sale/detail/RoofForm.tsx index 878fbf2..794bf21 100644 --- a/src/components/survey-sale/detail/RoofForm.tsx +++ b/src/components/survey-sale/detail/RoofForm.tsx @@ -1,8 +1,217 @@ import { useState } from 'react' -import { Mode, SurveyBasicInfo } from '@/types/Survey' +import { Mode, SurveyDetailInfo, SurveyDetailRequest } from '@/types/Survey' -export default function RoofForm(props: { surveyInfo: Partial; mode: Mode }) { - const { surveyInfo, mode } = props +type RadioEtcKeys = 'houseStructure' | 'rafterMaterial' | 'waterproofMaterial' | 'insulationPresence' | 'rafterDirection' | 'leakTrace' +type SelectBoxKeys = + | 'installationSystem' + | 'constructionYear' + | 'roofShape' + | 'rafterPitch' + | 'rafterSize' + | 'openFieldPlateKind' + | 'structureOrder' + | 'installationAvailability' + +export const supplementary_facilities = [ + { id: 1, name: 'エコキュート' }, //에코큐트 + { id: 2, name: 'エネパーム' }, //에네팜 + { id: 3, name: '蓄電池システム' }, //축전지시스템 + { id: 4, name: '太陽光発電' }, //태양광발전 +] + +export const roof_material = [ + { id: 1, name: 'スレート' }, //슬레이트 + { id: 2, name: 'アスファルトシングル' }, //아스팔트 싱글 + { id: 3, name: '瓦' }, //기와 + { id: 4, name: '金属屋根' }, //금속지붕 +] + +export const selectBoxOptions: Record = { + installationSystem: [ + { + id: 1, + name: '太陽光発電', //태양광발전 + }, + { + id: 2, + name: 'ハイブリッド蓄電システム', //하이브리드축전지시스템 + }, + { + id: 3, + name: '蓄電池システム', //축전지시스템 + }, + ], + constructionYear: [ + { + id: 1, + name: '新築', //신축 + }, + { + id: 2, + name: '既築', //기존 + }, + ], + roofShape: [ + { + id: 1, + name: '切妻', //박공지붕 + }, + { + id: 2, + name: '寄棟', //기동 + }, + { + id: 3, + name: '片流れ', //한쪽흐름 + }, + ], + rafterSize: [ + { + id: 1, + name: '幅35mm以上×高さ48mm以上', + }, + { + id: 2, + name: '幅36mm以上×高さ46mm以上', + }, + { + id: 3, + name: '幅37mm以上×高さ43mm以上', + }, + { + id: 4, + name: '幅38mm以上×高さ40mm以上', + }, + ], + rafterPitch: [ + { + id: 1, + name: '455mm以下', + }, + { + id: 2, + name: '500mm以下', + }, + { + id: 3, + name: '606mm以下', + }, + ], + openFieldPlateKind: [ + { + id: 1, + name: '構造用合板', //구조용합판 + }, + { + id: 2, + name: 'OSB', //OSB + }, + { + id: 3, + name: 'パーティクルボード', //파티클보드 + }, + { + id: 4, + name: '小幅板', //소판 + }, + ], + structureOrder: [ + { + id: 1, + name: '屋根材', //지붕재 + }, + { + id: 2, + name: '防水材', //방수재 + }, + { + id: 3, + name: '屋根の基礎', //지붕의기초 + }, + { + id: 4, + name: '垂木', //서까래 + }, + ], + installationAvailability: [ + { + id: 1, + name: '確認済み', //확인완료 + }, + { + id: 2, + name: '未確認', //미확인 + }, + ], +} + +export const radioEtcData: Record = { + houseStructure: [ + { + id: 1, + label: '木製', + }, + ], + rafterMaterial: [ + { + id: 1, + label: '木製', + }, + { + id: 2, + label: '強制', + }, + ], + waterproofMaterial: [ + { + id: 1, + label: 'アスファルト屋根940(22kg以上)', + }, + ], + insulationPresence: [ + { + id: 1, + label: 'なし', + }, + { + id: 2, + label: 'あり', + }, + ], + rafterDirection: [ + { + id: 1, + label: '垂直垂木', + }, + { + id: 2, + label: '水平垂木', + }, + ], + leakTrace: [ + { + id: 1, + label: 'あり', + }, + { + id: 2, + label: 'なし', + }, + ], +} + +export default function RoofForm(props: { + roofInfo: SurveyDetailRequest | SurveyDetailInfo + setRoofInfo: (roofInfo: SurveyDetailRequest) => void + mode: Mode +}) { + const makeNumArr = (value: string) => { + return value + .split(',') + .map((v) => v.trim()) + .filter((v) => v.length > 0) + } + const { roofInfo, setRoofInfo, mode } = props const [isFlip, setIsFlip] = useState(true) return ( @@ -21,7 +230,7 @@ export default function RoofForm(props: { surveyInfo: Partial; {/* 전기 계약 용량 */} 電気契約容量 - + {mode === 'READ' && } {mode !== 'READ' && ( @@ -39,7 +248,7 @@ export default function RoofForm(props: { surveyInfo: Partial; {/* 전기 소매 회사사 */} 電気小売会社 - + {/* 전기 부대 설비 */} @@ -47,34 +256,33 @@ export default function RoofForm(props: { surveyInfo: Partial; 電気袋設備※複数選択可能 - + {/* エコキュート - + */} + {supplementary_facilities.map((item) => ( + + + {item.name} + + ))} - - エネパーム - - - - 蓄電池システム - - - - 太陽光発電 - - - - その他 (直接入力) + + その他 (直接入力) - + {/* 설치 희망 시스템 */} - 設置希望システム + {/* 設置希望システム {mode === 'READ' && ( @@ -90,7 +298,9 @@ export default function RoofForm(props: { surveyInfo: Partial; 太陽光発電 - )} + )} */} + 設置希望システム + @@ -102,7 +312,7 @@ export default function RoofForm(props: { surveyInfo: Partial; {/* 건축 연수 */} 建築研修 - {mode === 'READ' && } + {/* {mode === 'READ' && } {mode !== 'READ' && ( 新築 @@ -111,12 +321,13 @@ export default function RoofForm(props: { surveyInfo: Partial; 新築 新築 - )} + )} */} + - + {/* 年 - + */} {/* 지붕재 */} @@ -124,36 +335,26 @@ export default function RoofForm(props: { surveyInfo: Partial; 屋根材※最大2個まで選択可能 + {roof_material.map((item) => ( + + + {item.name} + + ))} - - スレート - - - - アスファルトシングル - - - - 瓦 - - - - 金属屋根 - - - - その他 (直接入力) + + その他 (直接入力) - + {/* 지붕 모양 */} 建築研修 - {mode === 'READ' && } + {/* {mode === 'READ' && } {mode !== 'READ' && ( 太陽光発電 @@ -162,7 +363,8 @@ export default function RoofForm(props: { surveyInfo: Partial; 太陽光発電 太陽光発電 - )} + )} */} + @@ -172,207 +374,84 @@ export default function RoofForm(props: { surveyInfo: Partial; {/* 지붕 경사도도 */} 屋根の斜面 - + 寸 {/* 주택구조조 */} 住宅構造 - - - 木製 - - - - その他 (直接入力) - - - - + {/* 서까래 재질 */} 垂木材質 - - - - 木製 - - - - 強制 - - - - その他 (直接入力) - - - - - + {/* 서까래 크기 */} 垂木サイズ - {mode === 'READ' && } - {mode !== 'READ' && ( - - 幅35mm以上×高さ48mm以上 - 幅35mm以上×高さ48mm以上 - 幅35mm以上×高さ48mm以上 - 幅35mm以上×高さ48mm以上 - 幅35mm以上×高さ48mm以上 - - )} - - - + {/* 서까래 피치 */} 垂木サイズ - {mode === 'READ' && } - {mode !== 'READ' && ( - - 455mm以下 - 455mm以下 - 455mm以下 - 455mm以下 - 455mm以下 - - )} - - - + {/* 서까래 방향 */} 垂木の方向 - - - 垂直垂木 - - - - 水平垂木 - + {/* 노지판 종류류 */} 路地板の種類 - {mode === 'READ' && } - {mode !== 'READ' && ( - - 構造用合板 - 構造用合板 - 構造用合板 - 構造用合板 - 構造用合板 - - )} - - - + + {/* 노지판 두께 */} 路地板厚※小幅板を選択した場合, 厚さ. 小幅板間の間隔寸法を記載 - + mm - {/* 서까래 방향 */} - 垂木の方向 + {/* 누수 흔적 */} + 水漏れの痕跡 - - - あり - - - - なし - + - {/* 주택 구조 */} - 住宅構造 - - - アスファルト屋根940(22kg以上) - - - - その他 (直接入力) - - - - + {/* 방수재 종류 */} + 防水材の種類 + {/* 단열재 유무 */} 断熱材の有無 - - - あり - - - - - - - なし - + {/* 지붕 구조의 순서 */} - 路地板の種類 - - {mode === 'READ' && } - {mode !== 'READ' && ( - - 材/防水材/屋根基礎/垂木 - 材/防水材/屋根基礎/垂木 - 材/防水材/屋根基礎/垂木 - 材/防水材/屋根基礎/垂木 - 材/防水材/屋根基礎/垂木 - - )} - - - - + 屋根構造の順序 + {/* 지붕 제품명 설치 가능 여부 확인 */} 屋根製品名 設置可否確認 - - {mode === 'READ' && } - {mode !== 'READ' && ( - - 確認済み - 確認済み - 確認済み - 確認済み - 確認済み - - )} - - - - + {/* 메모 */} @@ -382,8 +461,8 @@ export default function RoofForm(props: { surveyInfo: Partial; className="textarea-form" name="" id="" - defaultValue={'漏れの兆候があるため、正確な点検が必要です.'} placeholder="TextArea Filed" + value={roofInfo?.memo ?? ''} readOnly={mode === 'READ'} > @@ -394,3 +473,56 @@ export default function RoofForm(props: { surveyInfo: Partial; ) } + +const SelectedBox = ({ column, detailInfoData }: { column: string; detailInfoData: SurveyDetailInfo }) => { + const selectedId = detailInfoData?.[column as keyof SurveyDetailInfo] + const etcValue = detailInfoData?.[`${column}Etc` as keyof SurveyDetailInfo] + + return ( + <> + + - + その他 (直接入力) + {selectBoxOptions[column as keyof typeof selectBoxOptions][Number(selectedId)]?.name} + + {etcValue && } + > + ) +} + +const RadioSelected = ({ column, detailInfoData }: { column: string; detailInfoData: SurveyDetailInfo | null }) => { + let selectedId = detailInfoData?.[column as keyof SurveyDetailInfo] + if (column === 'leakTrace') { + selectedId = Number(selectedId) + if (!selectedId) selectedId = 2 + } + + let etcValue = null + if (column !== 'rafterDirection') { + etcValue = detailInfoData?.[`${column}Etc` as keyof SurveyDetailInfo] + } + const etcChecked = etcValue !== null && etcValue !== undefined && etcValue !== '' + + // console.log('column: selectedId', column, selectedId) + return ( + <> + {radioEtcData[column as keyof typeof radioEtcData].map((item) => ( + + + {item.label} + + ))} + {column !== 'rafterDirection' && column !== 'leakTrace' && column !== 'insulationPresence' && ( + + + その他 (直接入力) + + )} + {etcChecked && ( + + + + )} + > + ) +} diff --git a/src/components/survey-sale/detail/RoofInfoForm.tsx b/src/components/survey-sale/detail/RoofInfoForm.tsx deleted file mode 100644 index e8850ca..0000000 --- a/src/components/survey-sale/detail/RoofInfoForm.tsx +++ /dev/null @@ -1,370 +0,0 @@ -'use client' - -import { useEffect } from 'react' -import { useSurveySaleTabState } from '@/store/surveySaleTabState' - -export default function RoofInfoForm() { - const { setRoofInfoSelected } = useSurveySaleTabState() - - useEffect(() => { - setRoofInfoSelected() - }, []) - - return ( - <> - - 電気関係 - - - 電気契約容量 - - - - - - kVA - kVA - kVA - kVA - kVA - - - - - 電気小売会社 - - - - - 電気袋設備※複数選択可能 - - - - - エコキュート - - - - エネパーム - - - - 蓄電池システム - - - - 太陽光発電 - - - - その他 (直接入力) - - - - - - - - 設置希望システム - - - 太陽光発電 - 太陽光発電 - 太陽光発電 - 太陽光発電 - 太陽光発電 - - - - - - - - - - - 屋根関係 - - - 建築研修 - - - 新築 - 新築 - 新築 - 新築 - 新築 - - - - - 年 - - - - - 屋根材※最大2個まで選択可能 - - - - - スレート - - - - アスファルトシングル - - - - 瓦 - - - - 金属屋根 - - - - その他 (直接入力) - - - - - - - - 建築研修 - - - 太陽光発電 - 太陽光発電 - 太陽光発電 - 太陽光発電 - 太陽光発電 - - - - - - - - 屋根の斜面 - - - 寸 - - - - 住宅構造 - - - 木製 - - - - その他 (直接入力) - - - - - - - 垂木材質 - - - - 木製 - - - - 強制 - - - - その他 (直接入力) - - - - - - - - 垂木サイズ - - - 幅35mm以上×高さ48mm以上 - 幅35mm以上×高さ48mm以上 - 幅35mm以上×高さ48mm以上 - 幅35mm以上×高さ48mm以上 - 幅35mm以上×高さ48mm以上 - - - - - - - - 垂木サイズ - - - 455mm以下 - 455mm以下 - 455mm以下 - 455mm以下 - 455mm以下 - - - - - - - - 垂木の方向 - - - - 垂直垂木 - - - - 水平垂木 - - - - - 路地板の種類 - - - 構造用合板 - 構造用合板 - 構造用合板 - 構造用合板 - 構造用合板 - - - - - - - - - 路地板厚※小幅板を選択した場合, 厚さ. 小幅板間の間隔寸法を記載 - - - - mm - - - - 垂木の方向 - - - - あり - - - - なし - - - - - 住宅構造 - - - アスファルト屋根940(22kg以上) - - - - その他 (直接入力) - - - - - - - 断熱材の有無 - - - あり - - - - - - - なし - - - - 路地板の種類 - - - 材/防水材/屋根基礎/垂木 - 材/防水材/屋根基礎/垂木 - 材/防水材/屋根基礎/垂木 - 材/防水材/屋根基礎/垂木 - 材/防水材/屋根基礎/垂木 - - - - - - - - 屋根製品名 設置可否確認 - - - 確認済み - 確認済み - 確認済み - 確認済み - 確認済み - - - - - - - - メモ - - - 確認済み - 確認済み - 確認済み - 確認済み - 確認済み - - - - - - - - - - - 一時保存 - - - - - 保存 - - - - - リスト - - - - - > - ) -} diff --git a/src/components/survey-sale/list/ListTable.tsx b/src/components/survey-sale/list/ListTable.tsx index 6d15b1e..b1ac703 100644 --- a/src/components/survey-sale/list/ListTable.tsx +++ b/src/components/survey-sale/list/ListTable.tsx @@ -1,33 +1,82 @@ 'use client' +import LoadMoreButton from '@/components/LoadMoreButton' +import { useServey } from '@/hooks/useSurvey' +import { useEffect, useState } from 'react' +import { useRouter } from 'next/navigation' +import SearchForm from './SearchForm' +import { useSurveyFilterStore } from '@/store/surveyFilterStore' +import { useSessionStore } from '@/store/session' +import { SurveyBasicInfo } from '@/types/Survey' + export default function ListTable() { + const router = useRouter() + const { surveyList, isLoadingSurveyList } = useServey() + const { offset, setOffset } = useSurveyFilterStore() + + const [heldSurveyList, setHeldSurveyList] = useState([]) + const [hasMore, setHasMore] = useState(false) + + const { session } = useSessionStore() + + useEffect(() => { + if (!session.isLoggedIn || !('data' in surveyList)) return + if ('count' in surveyList && surveyList.count > 0) { + if (offset > 0) { + setHeldSurveyList((prev) => [...prev, ...surveyList.data]) + } else { + setHeldSurveyList(surveyList.data) + } + setHasMore(surveyList.count > offset + 10) + } else { + setHeldSurveyList([]) + setHasMore(false) + } + }, [surveyList, offset, session]) + + const handleDetailClick = (id: number) => { + router.push(`/survey-sale/${id}`) + } + + const handleItemsInit = () => { + setHeldSurveyList([]) + setOffset(0) + } + + // TODO: 로딩 처리 필요 + return ( <> - - - {Array.from({ length: 4 }).map((_, idx) => ( - - - - 0000000021 - 2025.04.22 + + {heldSurveyList.length > 0 ? ( + + + {heldSurveyList.map((survey) => ( + handleDetailClick(survey.id)}> + + + {survey.id} + {survey.investigationDate} + + {survey.buildingName} + {survey.customerName} + + {survey.representative} + {new Date(survey.uptDt).toLocaleString()} + - Hanwha Building - Gil dong - - Hong Gildong - 2025.04.22 10:00:21 - - - - ))} - - - - もっと見る - + + ))} + + + setOffset(offset + 10)} /> + - + ) : ( + + 作成された物件はありません。 + + )} > ) } diff --git a/src/components/survey-sale/list/SearchForm.tsx b/src/components/survey-sale/list/SearchForm.tsx index 5763dbf..327a85c 100644 --- a/src/components/survey-sale/list/SearchForm.tsx +++ b/src/components/survey-sale/list/SearchForm.tsx @@ -1,41 +1,104 @@ 'use client' -export default function SearchForm() { +import { SEARCH_OPTIONS, SEARCH_OPTIONS_ENUM, SEARCH_OPTIONS_PARTNERS, useSurveyFilterStore } from '@/store/surveyFilterStore' +import { useRouter } from 'next/navigation' +import { useState } from 'react' + +export default function SearchForm({ memberRole, userId }: { memberRole: string; userId: string }) { + const router = useRouter() + const { setSearchOption, setSort, setIsMySurvey, setKeyword, isMySurvey, keyword, searchOption, sort } = useSurveyFilterStore() + const [searchKeyword, setSearchKeyword] = useState(keyword) + const [option, setOption] = useState(searchOption) + + const handleSearch = () => { + if (option !== 'id' && searchKeyword.trim().length < 2) { + alert('2文字以上入力してください') + return + } + setKeyword(searchKeyword) + setSearchOption(option) + // onItemsInit() + } + const searchOptions = memberRole === 'Partner' ? SEARCH_OPTIONS_PARTNERS : SEARCH_OPTIONS + return ( - + router.push('/survey-sale/regist')}> 新規売買登録 - - 全体 - 全体 - 全体 - 全体 - 全体 + { + if (e.target.value === 'all') { + setKeyword('') + setSearchKeyword('') + // onItemsInit() + setSearchOption('all') + setOption('all') + } else { + setOption(e.target.value as SEARCH_OPTIONS_ENUM) + } + }} + > + {searchOptions.map((option) => ( + + {option.label} + + ))} - - + { + setSearchKeyword(e.target.value) + }} + onKeyDown={(e) => { + if (e.key === 'Enter') { + handleSearch() + } + }} + /> + - + { + setIsMySurvey(isMySurvey === userId ? null : userId) + // onItemsInit() + }} + /> 私が書いた物件 - - 最近の登録日 - 最近の登録日 - 最近の登録日 - 最近の登録日 - 最近の登録日 + { + setSort(e.target.value as 'created' | 'updated') + // onItemsInit() + }} + > + 最近の登録日 + 最新の更新日 diff --git a/src/components/ui/Main.tsx b/src/components/ui/Main.tsx index 9931293..01cdbf0 100644 --- a/src/components/ui/Main.tsx +++ b/src/components/ui/Main.tsx @@ -1,7 +1,6 @@ 'use client' import { useRouter } from 'next/navigation' - export default function Main() { const router = useRouter() diff --git a/src/hooks/useSurvey.ts b/src/hooks/useSurvey.ts new file mode 100644 index 0000000..d07cddf --- /dev/null +++ b/src/hooks/useSurvey.ts @@ -0,0 +1,232 @@ +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import type { SurveyBasicInfo, SurveyDetailInfo, SurveyDetailRequest, SurveyDetailCoverRequest, SurveyRegistRequest } from '@/types/Survey' +import { axiosInstance } from '@/libs/axios' +import { useSurveyFilterStore } from '@/store/surveyFilterStore' +import { queryStringFormatter } from '@/utils/common-utils' +import { useSessionStore } from '@/store/session' +import { useMemo } from 'react' +import { AxiosResponse } from 'axios' + +const requiredFields = [ + { + field: 'installationSystem', + name: '設置希望システム', + }, + { + field: 'constructionYear', + name: '建築年数', + }, + { + field: 'rafterSize', + name: '垂木サイズ', + }, + { + field: 'rafterPitch', + name: '垂木傾斜', + }, + { + field: 'waterproofMaterial', + name: '防水材', + }, + { + field: 'insulationPresence', + name: '断熱材有無', + }, + { + field: 'structureOrder', + name: '屋根構造の順序', + }, +] + +interface ZipCodeResponse { + status: number + message: string | null + results: ZipCode[] | null +} + +type ZipCode = { + zipcode: string + prefcode: string + address1: string + address2: string + address3: string + kana1: string + kana2: string + kana3: string +} + +export function useServey(id?: number): { + surveyList: { data: SurveyBasicInfo[]; count: number } | {} + surveyDetail: SurveyBasicInfo | null + isLoadingSurveyList: boolean + isLoadingSurveyDetail: boolean + isCreatingSurvey: boolean + isUpdatingSurvey: boolean + isDeletingSurvey: boolean + createSurvey: (survey: SurveyRegistRequest) => Promise + createSurveyDetail: (params: { surveyId: number; surveyDetail: SurveyDetailCoverRequest }) => void + updateSurvey: (survey: SurveyRegistRequest) => void + deleteSurvey: () => Promise + submitSurvey: () => void + validateSurveyDetail: (surveyDetail: SurveyDetailRequest) => string + getZipCode: (zipCode: string) => Promise + refetchSurveyList: () => void +} { + const queryClient = useQueryClient() + const { keyword, searchOption, isMySurvey, sort, offset } = useSurveyFilterStore() + const { session } = useSessionStore() + + const { + data, + isLoading: isLoadingSurveyList, + refetch: refetchSurveyList, + } = useQuery({ + queryKey: ['survey', 'list', keyword, searchOption, isMySurvey, sort, offset, session?.storeNm, session?.builderNo, session?.role], + queryFn: async () => { + const resp = await axiosInstance(null).get<{ data: SurveyBasicInfo[]; count: number }>('/api/survey-sales', { + params: { + keyword, + searchOption, + isMySurvey, + sort, + offset, + store: session?.storeNm, + builderNo: session?.builderNo, + role: session?.role, + }, + }) + return resp.data + }, + enabled: session?.isLoggedIn, + }) + const surveyData = useMemo(() => { + if (!data) return {} + return { + data: data.data, + count: data.count, + } + }, [data]) + + const { data: surveyDetail, isLoading: isLoadingSurveyDetail } = useQuery({ + queryKey: ['survey', id], + queryFn: async () => { + if (id === undefined) throw new Error('id is required') + if (id === null) return null + const resp = await axiosInstance(null).get(`/api/survey-sales/${id}`) + return resp.data + }, + enabled: id !== undefined, + }) + + const { mutateAsync: createSurvey, isPending: isCreatingSurvey } = useMutation({ + mutationFn: async (survey: SurveyRegistRequest) => { + const resp = await axiosInstance(null).post('/api/survey-sales', survey) + return resp.data.id ?? 0 + }, + onSuccess: (data) => { + queryClient.invalidateQueries({ queryKey: ['survey', 'list'] }) + queryClient.invalidateQueries({ queryKey: ['survey', id] }) + return data + }, + }) + + const { mutate: updateSurvey, isPending: isUpdatingSurvey } = useMutation({ + mutationFn: async (survey: SurveyRegistRequest) => { + if (id === undefined) throw new Error('id is required') + const resp = await axiosInstance(null).put(`/api/survey-sales/${id}`, survey) + return resp.data + }, + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: ['survey', id] }) + queryClient.invalidateQueries({ queryKey: ['survey', 'list'] }) + }, + }) + + const { mutateAsync: deleteSurvey, isPending: isDeletingSurvey } = useMutation({ + mutationFn: async () => { + if (id === null) throw new Error('id is required') + const resp = await axiosInstance(null).delete(`/api/survey-sales/${id}`) + return resp.data + }, + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: ['survey', 'list'] }) + queryClient.invalidateQueries({ queryKey: ['survey', id] }) + }, + }) + + const { mutateAsync: createSurveyDetail } = useMutation({ + mutationFn: async ({ surveyId, surveyDetail }: { surveyId: number; surveyDetail: SurveyDetailCoverRequest }) => { + const resp = await axiosInstance(null).patch(`/api/survey-sales/${surveyId}`, surveyDetail) + return resp.data + }, + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: ['survey', 'list'] }) + queryClient.invalidateQueries({ queryKey: ['survey', id] }) + }, + }) + + const { mutateAsync: submitSurvey } = useMutation({ + mutationFn: async () => { + if (id === undefined) throw new Error('id is required') + const resp = await axiosInstance(null).patch(`/api/survey-sales/${id}`, { + submit: true, + }) + return resp.data + }, + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: ['survey', 'list'] }) + queryClient.invalidateQueries({ queryKey: ['survey', id] }) + }, + }) + + const validateSurveyDetail = (surveyDetail: SurveyDetailRequest) => { + const etcFields = ['installationSystem', 'constructionYear', 'rafterSize', 'rafterPitch', 'waterproofMaterial', 'structureOrder'] as const + + const emptyField = requiredFields.find((field) => { + if (etcFields.includes(field.field as (typeof etcFields)[number])) { + return ( + surveyDetail[field.field as keyof SurveyDetailRequest] === null && surveyDetail[`${field.field}_ETC` as keyof SurveyDetailRequest] === '' + ) + } else { + return surveyDetail[field.field as keyof SurveyDetailRequest] === null + } + }) + + const contractCapacity = surveyDetail.contractCapacity + if (contractCapacity && contractCapacity.trim() !== '' && contractCapacity.split(' ')?.length === 1) { + return 'contractCapacityUnit' + } + + return emptyField?.name || '' + } + + const getZipCode = async (zipCode: string): Promise => { + try { + const { data } = await axiosInstance(null).get( + `https://zipcloud.ibsnet.co.jp/api/search?${queryStringFormatter({ zipcode: zipCode.trim() })}`, + ) + return data.results + } catch (e) { + console.error('Failed to fetch zipcode data:', e) + throw new Error('Failed to fetch zipcode data') + } + } + + return { + surveyList: surveyData, + surveyDetail: surveyDetail as SurveyBasicInfo | null, + isLoadingSurveyList, + isLoadingSurveyDetail, + isCreatingSurvey, + isUpdatingSurvey, + isDeletingSurvey, + createSurvey, + updateSurvey, + deleteSurvey, + createSurveyDetail, + submitSurvey, + validateSurveyDetail, + getZipCode, + refetchSurveyList, + } +} diff --git a/src/libs/axios.ts b/src/libs/axios.ts index 8718318..d973f9d 100644 --- a/src/libs/axios.ts +++ b/src/libs/axios.ts @@ -21,7 +21,10 @@ export const axiosInstance = (url: string | null | undefined) => { ) instance.interceptors.response.use( - (response) => transferResponse(response), + (response) => { + response.data = transferResponse(response) + return response + }, (error) => { // 에러 처리 로직 return Promise.reject(error) @@ -52,7 +55,7 @@ export const axiosInstance = (url: string | null | undefined) => { // ) // response데이터가 array, object에 따라 분기하여 키 변환 -const transferResponse = (response: any) => { +export const transferResponse = (response: any) => { if (!response.data) return response.data // 배열인 경우 각 객체의 키를 변환 @@ -80,7 +83,11 @@ const transformObjectKeys = (obj: any): any => { return obj } -// snake case to camel case -const snakeToCamel = (str: string): string => { - return str.replace(/([-_][a-z])/g, (group) => group.toUpperCase().replace('-', '').replace('_', '')) + +export const camelToSnake = (str: string): string => { + return str.replace(/([A-Z])/g, (group) => `_${group.toLowerCase()}`) +} + +const snakeToCamel = (str: string): string => { + return str.toLowerCase().replace(/([-_][a-z])/g, (group) => group.toUpperCase().replace('-', '').replace('_', '')) } diff --git a/src/store/addressStore.ts b/src/store/addressStore.ts new file mode 100644 index 0000000..2e40890 --- /dev/null +++ b/src/store/addressStore.ts @@ -0,0 +1,19 @@ +import { create } from 'zustand' + +type AddressData = { + post_code: string + address: string + address_detail: string +} + +interface AddressState { + addressData: AddressData | null + setAddressData: (address: AddressData) => void + resetAddressData: () => void +} + +export const useAddressStore = create((set) => ({ + addressData: null, + setAddressData: (address) => set({ addressData: address }), + resetAddressData: () => set({ addressData: null }), +})) diff --git a/src/store/inquiryFilterStore.ts b/src/store/inquiryFilterStore.ts new file mode 100644 index 0000000..0960c85 --- /dev/null +++ b/src/store/inquiryFilterStore.ts @@ -0,0 +1,41 @@ +import { create } from 'zustand' + +export const FILTER_OPTIONS = [ + { + id: 'all', + label: '全体', + }, + { + id: 'completed', + label: '回答完了', + }, + { + id: 'waiting', + label: '回答待ち', + }, +] +export type FILTER_OPTIONS_ENUM = (typeof FILTER_OPTIONS)[number]['id'] + +type InquiryFilterState = { + keyword: string + filter: FILTER_OPTIONS_ENUM + isMySurvey: string | null + offset: number + setKeyword: (keyword: string) => void + setFilter: (filter: FILTER_OPTIONS_ENUM) => void + setIsMySurvey: (isMySurvey: string | null) => void + setOffset: (offset: number) => void + reset: () => void +} + +export const useInquiryFilterStore = create((set) => ({ + keyword: '', + filter: 'all', + isMySurvey: null, + offset: 0, + setKeyword: (keyword) => set({ keyword }), + setFilter: (filter) => set({ filter }), + setIsMySurvey: (isMySurvey) => set({ isMySurvey }), + setOffset: (offset) => set({ offset }), + reset: () => set({ keyword: '', filter: 'all', isMySurvey: null, offset: 0 }), +})) diff --git a/src/store/surveyFilterStore.ts b/src/store/surveyFilterStore.ts new file mode 100644 index 0000000..95514e8 --- /dev/null +++ b/src/store/surveyFilterStore.ts @@ -0,0 +1,87 @@ +import { create } from 'zustand' + +export const SEARCH_OPTIONS = [ + { + id: 'all', + label: '全体', + }, + { + id: 'id', + label: '登録番号', + }, + { + id: 'building_name', + label: '建物名', + }, + { + id: 'representative', + label: '作成者', + }, + { + id: 'store', + label: '販売店名', + }, + // { + // id: 'store_id', + // label: '販売店ID', + // }, + { + id: 'construction_point', + label: '施工店名', + }, + // { + // id: 'construction_id', + // label: '施工店ID', + // }, +] + +export const SEARCH_OPTIONS_PARTNERS = [ + { + id: 'all', + label: '全体', + }, + { + id: 'id', + label: '登録番号', + }, + { + id: 'building_name', + label: '建物名', + }, + { + id: 'representative', + label: '作成者', + }, +] + +export type SEARCH_OPTIONS_ENUM = (typeof SEARCH_OPTIONS)[number]['id'] +export type SEARCH_OPTIONS_PARTNERS_ENUM = (typeof SEARCH_OPTIONS_PARTNERS)[number]['id'] +export type SORT_OPTIONS_ENUM = 'created' | 'updated' + +type SurveyFilterState = { + keyword: string + searchOption: SEARCH_OPTIONS_ENUM | SEARCH_OPTIONS_PARTNERS_ENUM + isMySurvey: string | null + sort: SORT_OPTIONS_ENUM + offset: number + setKeyword: (keyword: string) => void + setSearchOption: (searchOption: SEARCH_OPTIONS_ENUM | SEARCH_OPTIONS_PARTNERS_ENUM) => void + setIsMySurvey: (isMySurvey: string | null) => void + setSort: (sort: SORT_OPTIONS_ENUM) => void + setOffset: (offset: number) => void + reset: () => void +} + +export const useSurveyFilterStore = create((set) => ({ + keyword: '', + searchOption: 'all', + isMySurvey: null, + sort: 'created', + offset: 0, + setKeyword: (keyword: string) => set({ keyword }), + setSearchOption: (searchOption: SEARCH_OPTIONS_ENUM | SEARCH_OPTIONS_PARTNERS_ENUM) => set({ searchOption }), + setIsMySurvey: (isMySurvey: string | null) => set({ isMySurvey }), + setSort: (sort: SORT_OPTIONS_ENUM) => set({ sort }), + setOffset: (offset: number) => set({ offset }), + reset: () => set({ keyword: '', searchOption: 'all', isMySurvey: null, sort: 'created', offset: 0 }), +})) diff --git a/src/styles/base/_button.scss b/src/styles/base/_button.scss index c6d11ad..b4d61a4 100644 --- a/src/styles/base/_button.scss +++ b/src/styles/base/_button.scss @@ -49,6 +49,14 @@ background-size: cover; margin-left: 12px; } + .btn-arr-up{ + display: block; + width: 10px; + height: 6px; + background: url(/assets/images/common/btn_arr_up.svg)no-repeat center; + background-size: cover; + margin-left: 12px; + } .btn-edit{ display: block; width: 10px; diff --git a/src/types/Auth.ts b/src/types/Auth.ts index 8dc21cb..61a3880 100644 --- a/src/types/Auth.ts +++ b/src/types/Auth.ts @@ -10,11 +10,11 @@ export interface SessionData { storeNm: null userId: null category: null - userNm: null - userNmKana: null + userNm: null | string + userNmKana: null | string telNo: null fax: null - email: null + email: null | string lastEditUser: null storeGubun: null pwCurr: null diff --git a/src/types/Survey.ts b/src/types/Survey.ts index 83d2ec1..36e7aa5 100644 --- a/src/types/Survey.ts +++ b/src/types/Survey.ts @@ -1,132 +1,132 @@ -export type SurveyBasicInfo = { - ID: number - REPRESENTATIVE: string - STORE: string | null - CONSTRUCTION_POINT: string | null - INVESTIGATION_DATE: string | null - BUILDING_NAME: string | null - CUSTOMER_NAME: string | null - POST_CODE: string | null - ADDRESS: string | null - ADDRESS_DETAIL: string | null - SUBMISSION_STATUS: boolean - SUBMISSION_DATE: string | null - DETAIL_INFO: SurveyDetailInfo | null - REG_DT: Date - UPT_DT: Date -} - -export type SurveyDetailInfo = { - ID: number - BASIC_INFO_ID: number - CONTRACT_CAPACITY: string | null - RETAIL_COMPANY: string | null - SUPPLEMENTARY_FACILITIES: string | null // number 배열 - SUPPLEMENTARY_FACILITIES_ETC: string | null - INSTALLATION_SYSTEM: string | null - INSTALLATION_SYSTEM_ETC: string | null - CONSTRUCTION_YEAR: string | null - CONSTRUCTION_YEAR_ETC: string | null - ROOF_MATERIAL: string | null // number 배열 - ROOF_MATERIAL_ETC: string | null - ROOF_SHAPE: string | null - ROOF_SHAPE_ETC: string | null - ROOF_SLOPE: string | null - HOUSE_STRUCTURE: string | null - HOUSE_STRUCTURE_ETC: string | null - RAFTER_MATERIAL: string | null - RAFTER_MATERIAL_ETC: string | null - RAFTER_SIZE: string | null - RAFTER_SIZE_ETC: string | null - RAFTER_PITCH: string | null - RAFTER_PITCH_ETC: string | null - RAFTER_DIRECTION: string | null - OPEN_FIELD_PLATE_KIND: string | null - OPEN_FIELD_PLATE_KIND_ETC: string | null - OPEN_FIELD_PLATE_THICKNESS: string | null - LEAK_TRACE: boolean | null - WATERPROOF_MATERIAL: string | null - WATERPROOF_MATERIAL_ETC: string | null - INSULATION_PRESENCE: string | null - INSULATION_PRESENCE_ETC: string | null - STRUCTURE_ORDER: string | null - STRUCTURE_ORDER_ETC: string | null - INSTALLATION_AVAILABILITY: string | null - INSTALLATION_AVAILABILITY_ETC: string | null - MEMO: string | null - REG_DT: Date - UPT_DT: Date -} - -export type SurveyBasicRequest = { - REPRESENTATIVE: string - STORE: string | null - CONSTRUCTION_POINT: string | null - INVESTIGATION_DATE: string | null - BUILDING_NAME: string | null - CUSTOMER_NAME: string | null - POST_CODE: string | null - ADDRESS: string | null - ADDRESS_DETAIL: string | null - SUBMISSION_STATUS: boolean - SUBMISSION_DATE: string | null -} - -export type SurveyDetailRequest = { - CONTRACT_CAPACITY: string | null - RETAIL_COMPANY: string | null - SUPPLEMENTARY_FACILITIES: string | null // number 배열 - SUPPLEMENTARY_FACILITIES_ETC: string | null - INSTALLATION_SYSTEM: string | null - INSTALLATION_SYSTEM_ETC: string | null - CONSTRUCTION_YEAR: string | null - CONSTRUCTION_YEAR_ETC: string | null - ROOF_MATERIAL: string | null // number 배열 - ROOF_MATERIAL_ETC: string | null - ROOF_SHAPE: string | null - ROOF_SHAPE_ETC: string | null - ROOF_SLOPE: string | null - HOUSE_STRUCTURE: string | null - HOUSE_STRUCTURE_ETC: string | null - RAFTER_MATERIAL: string | null - RAFTER_MATERIAL_ETC: string | null - RAFTER_SIZE: string | null - RAFTER_SIZE_ETC: string | null - RAFTER_PITCH: string | null - RAFTER_PITCH_ETC: string | null - RAFTER_DIRECTION: string | null - OPEN_FIELD_PLATE_KIND: string | null - OPEN_FIELD_PLATE_KIND_ETC: string | null - OPEN_FIELD_PLATE_THICKNESS: string | null - LEAK_TRACE: boolean | null - WATERPROOF_MATERIAL: string | null - WATERPROOF_MATERIAL_ETC: string | null - INSULATION_PRESENCE: string | null - INSULATION_PRESENCE_ETC: string | null - STRUCTURE_ORDER: string | null - STRUCTURE_ORDER_ETC: string | null - INSTALLATION_AVAILABILITY: string | null - INSTALLATION_AVAILABILITY_ETC: string | null - MEMO: string | null -} - -export type SurveyDetailCoverRequest = { - DETAIL_INFO: SurveyDetailRequest -} - -export type SurveyRegistRequest = { - REPRESENTATIVE: string - STORE: string | null - CONSTRUCTION_POINT: string | null - INVESTIGATION_DATE: string | null - BUILDING_NAME: string | null - CUSTOMER_NAME: string | null - POST_CODE: string | null - ADDRESS: string | null - ADDRESS_DETAIL: string | null - SUBMISSION_STATUS: boolean - SUBMISSION_DATE: string | null - DETAIL_INFO: SurveyDetailRequest | null -} - -export type Mode = 'CREATE' | 'EDIT' | 'READ' | 'TEMP' // 등록 | 수정 | 상세 | 임시저장 +export type SurveyBasicInfo = { + id: number + representative: string + store: string | null + constructionPoint: string | null + investigationDate: string | null + buildingName: string | null + customerName: string | null + postCode: string | null + address: string | null + addressDetail: string | null + submissionStatus: boolean + submissionDate: string | null + detailInfo: SurveyDetailInfo | null + regDt: Date + uptDt: Date +} + +export type SurveyDetailInfo = { + id: number + basicInfoId: number + contractCapacity: string | null + retailCompany: string | null + supplementaryFacilities: string | null // number 배열 + supplementaryFacilitiesEtc: string | null + installationSystem: string | null + installationSystemEtc: string | null + constructionYear: string | null + constructionYearEtc: string | null + roofMaterial: string | null // number 배열 + roofMaterialEtc: string | null + roofShape: string | null + roofShapeEtc: string | null + roofSlope: string | null + houseStructure: string | null + houseStructureEtc: string | null + rafterMaterial: string | null + rafterMaterialEtc: string | null + rafterSize: string | null + rafterSizeEtc: string | null + rafterPitch: string | null + rafterPitchEtc: string | null + rafterDirection: string | null + openFieldPlateKind: string | null + openFieldPlateKindEtc: string | null + openFieldPlateThickness: string | null + leakTrace: boolean | null + waterproofMaterial: string | null + waterproofMaterialEtc: string | null + insulationPresence: string | null + insulationPresenceEtc: string | null + structureOrder: string | null + structureOrderEtc: string | null + installationAvailability: string | null + installationAvailabilityEtc: string | null + memo: string | null + regDt: Date + uptDt: Date +} + +export type SurveyBasicRequest = { + representative: string + store: string | null + constructionPoint: string | null + investigationDate: string | null + buildingName: string | null + customerName: string | null + postCode: string | null + address: string | null + addressDetail: string | null + submissionStatus: boolean + submissionDate: string | null +} + +export type SurveyDetailRequest = { + contractCapacity: string | null + retailCompany: string | null + supplementaryFacilities: string | null // number 배열 + supplementaryFacilitiesEtc: string | null + installationSystem: string | null + installationSystemEtc: string | null + constructionYear: string | null + constructionYearEtc: string | null + roofMaterial: string | null // number 배열 + roofMaterialEtc: string | null + roofShape: string | null + roofShapeEtc: string | null + roofSlope: string | null + houseStructure: string | null + houseStructureEtc: string | null + rafterMaterial: string | null + rafterMaterialEtc: string | null + rafterSize: string | null + rafterSizeEtc: string | null + rafterPitch: string | null + rafterPitchEtc: string | null + rafterDirection: string | null + openFieldPlateKind: string | null + openFieldPlateKindEtc: string | null + openFieldPlateThickness: string | null + leakTrace: boolean | null + waterproofMaterial: string | null + waterproofMaterialEtc: string | null + insulationPresence: string | null + insulationPresenceEtc: string | null + structureOrder: string | null + structureOrderEtc: string | null + installationAvailability: string | null + installationAvailabilityEtc: string | null + memo: string | null +} + +export type SurveyDetailCoverRequest = { + detailInfo: SurveyDetailRequest +} + +export type SurveyRegistRequest = { + representative: string + store: string | null + constructionPoint: string | null + investigationDate: string | null + buildingName: string | null + customerName: string | null + postCode: string | null + address: string | null + addressDetail: string | null + submissionStatus: boolean + submissionDate: string | null + detailInfo: SurveyDetailRequest | null +} + +export type Mode = 'CREATE' | 'EDIT' | 'READ' | 'TEMP' // 등록 | 수정 | 상세 | 임시저장 diff --git a/src/utils/common-utils.js b/src/utils/common-utils.js new file mode 100644 index 0000000..0a1265f --- /dev/null +++ b/src/utils/common-utils.js @@ -0,0 +1,187 @@ +/** + * Check if an object is not empty. + * @param {Object} obj - The object to check. + * @returns {boolean} - Returns true if the object is not empty, false otherwise. + */ +export const isObjectNotEmpty = (obj) => { + if (!obj) { + return false + } + return Object.keys(obj).length > 0 +} + +export const isNotEmptyArray = (array) => { + return Array.isArray(array) && array.length +} + +export const isEmptyArray = (array) => { + return !isNotEmptyArray(array) +} + +/** + * ex) const params = {page:10, searchDvsnCd: 20} + * @param {*} params + * @returns page=10&searchDvsnCd=20 + */ +export const queryStringFormatter = (params = {}) => { + const queries = [] + Object.keys(params).forEach((parameterKey) => { + const parameterValue = params[parameterKey] + + if (parameterValue === undefined || parameterValue === null) { + return + } + + // string trim + if (typeof parameterValue === 'string' && !parameterValue.trim()) { + return + } + + // array to query string + if (Array.isArray(parameterValue)) { + // primitive type + if (parameterValue.every((v) => typeof v === 'number' || typeof v === 'string')) { + queries.push(`${encodeURIComponent(parameterKey)}=${parameterValue.map((v) => encodeURIComponent(v)).join(',')}`) + return + } + // reference type + if (parameterValue.every((v) => typeof v === 'object' && v !== null)) { + parameterValue.map((pv, i) => { + return Object.keys(pv).forEach((valueKey) => { + queries.push(`${encodeURIComponent(`${parameterKey}[${i}].${valueKey}`)}=${encodeURIComponent(pv[valueKey])}`) + }) + }) + return + } + } + // 나머지 + queries.push(`${encodeURIComponent(parameterKey)}=${encodeURIComponent(parameterValue)}`) + }) + return queries.join('&') +} + +// 43000 --> 43,000 +export const convertNumberToPriceDecimal = (value) => { + if (value) return Number(value).toLocaleString() + else if (value === 0) return 0 + else return '' +} + +// 43000.458 --> 43,000.46 +export const convertNumberToPriceDecimalToFixed = (value, fixed) => { + if (value) return Number(value).toLocaleString(undefined, { minimumFractionDigits: fixed, maximumFractionDigits: fixed }) + else if (value === 0) return 0 + else return '' +} + +// 전화번호, FAX 번호 숫자 or '-'만 입력 체크 +export const inputTelNumberCheck = (e) => { + const input = e.target + if (/^[\d-]*$/g.test(input.value)) { + input.value = input.value + } else { + input.value = input.value.replace(/[^\d-]/g, '') + } +} + +// 숫자만 입력 체크 +export const inputNumberCheck = (e) => { + const input = e.target + if (/^[\d]*$/g.test(input.value)) { + input.value = input.value + } else { + input.value = input.value.replace(/[^\d]/g, '') + } +} + +// 값이 숫자인지 확인 +export const numberCheck = (value) => { + return !isNaN(value) +} + +/** + * 파이프함수 정의 + * @param {...any} fns 순수함수들 + * @returns + */ +export const pipe = + (...fns) => + (x) => + fns.reduce((v, f) => f(v), x) + +/** + * 캔버스 각도에 따른 흐름 방향 계산 + * @param {number} canvasAngle + * @returns {object} 흐름 방향 객체 + */ +export const calculateFlowDirection = (canvasAngle) => { + return { + down: -canvasAngle, + up: 180 - canvasAngle, + left: 90 - canvasAngle < 180 ? 90 - canvasAngle : 90 - canvasAngle - 360, + right: -90 - canvasAngle < -180 ? -90 - canvasAngle + 360 : -90 - canvasAngle, + } +} + +/** + * 자바스크립트 객체로 쿼리스트링 생성 + * @param {javascript object} o 쿼리스트링 생성할 객체 + * @returns {string} 쿼리스트링 + */ +export const getQueryString = (o) => { + const queryString = Object.keys(o) + .map((key) => `${key}=${o[key] ?? ''}`) + .join('&') + return `?${queryString}` +} + +export const unescapeString = (str) => { + const regex = /&(amp|lt|gt|quot|#39);/g + const chars = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + ''': "'", + } + + /* + 1. 한번 변환은 {" 로 변환됨 : 에러 발생 => while 변경 + 2. 변환할 내용이 없으면 리턴값이 undefined + + if (regex.test(str)) { + return str.replace(regex, (matched) => chars[matched] || matched) + } + */ + + while (regex.test(str)) { + str = str.replace(regex, (matched) => chars[matched] || matched); + } + return str +} + +export const isNullOrUndefined = (value) => { + return value === null || value === undefined +} + +export const isEqualObjects = (obj1, obj2) => { + const keys1 = Object.keys(obj1) + const keys2 = Object.keys(obj2) + + if (keys1.length !== keys2.length) return false + + for (let key of keys1) { + const val1 = obj1[key] + const val2 = obj2[key] + const areObjects = isObject(val1) && isObject(val2) + + if (areObjects && !deepEqual(val1, val2)) return false + if (!areObjects && val1 !== val2) return false + } + + return true +} + +function isObject(value) { + return value !== null && typeof value === 'object' +}
作成された物件はありません。