Compare commits

...

73 Commits

Author SHA1 Message Date
7a6b9cbf92 feat: 지붕재 적합성 조회 데이터 포멧 변경 및 조회 로직 수정 2025-05-20 13:51:49 +09:00
57d6202d5c Merge branch 'dev' of https://git.hanasys.jp/qcast3/onsitesurvey into feature/suitable 2025-05-19 13:55:08 +09:00
2e66ff5782 Merge pull request 'feature/survey' (#38) from feature/survey into dev
Reviewed-on: #38
2025-05-19 13:51:57 +09:00
eb1f6b23e7 refactor: Update Survey components and API routes for improved data handling and structure 2025-05-19 13:47:57 +09:00
8ae0f62c81 Merge branch 'dev' of https://git.hanasys.jp/qcast3/onsitesurvey into feature/suitable 2025-05-19 13:46:21 +09:00
ab86e16bc9 fix: Add indexes to MS_SUITABLE_DETAIL and MS_SUITABLE_MAIN models in Prisma schema for improved query performance 2025-05-19 13:45:06 +09:00
09f280644f Merge branch 'dev' of https://git.hanasys.jp/qcast3/onsitesurvey into feature/survey 2025-05-19 08:49:11 +09:00
b02f3e85a7 Merge branch 'dev' of https://git.hanasys.jp/qcast3/onsitesurvey into feature/suitable 2025-05-16 18:31:33 +09:00
8d5d0b6244 fix: Update MS_USR_TRK model in Prisma schema to use uppercase 'DATA' field 2025-05-16 18:29:16 +09:00
9c0440b233 feat: add Survey new Design Component 2025-05-16 18:28:36 +09:00
f53c7410e2 Merge branch 'dev' of https://git.hanasys.jp/qcast3/onsitesurvey into feature/suitable 2025-05-16 17:59:29 +09:00
e207cee460 fix: Correct axios instance reference in response interceptor for error handling 2025-05-16 17:59:25 +09:00
69b08706aa fix: Add response interceptor to axios instance for error handling 2025-05-16 17:58:00 +09:00
5fb1afca39 Merge pull request 'feature/pdf-tracking' (#37) from feature/pdf-tracking into dev
Reviewed-on: #37
2025-05-16 17:46:47 +09:00
nalpari
3d9cd1d992 fix: Update PDF download options to A4 format and portrait orientation 2025-05-16 17:46:02 +09:00
4e8fd462cf feat: add MS_USR_TRK model to Prisma schema, update axios instance with request interceptor, and enhance Footer component with PDF link 2025-05-16 16:56:38 +09:00
398fffb6db Merge branch 'dev' of https://git.hanasys.jp/qcast3/onsitesurvey into feature/survey 2025-05-16 16:01:26 +09:00
900e8edcec Merge pull request 'feature/pub' (#36) from feature/pub into dev
Reviewed-on: #36
2025-05-16 15:34:36 +09:00
김민식
e3b755896b [조사매물] 전기.지붕정보, 버튼 폼 추가 2025-05-16 15:33:00 +09:00
김민식
cdae73b95e 🚨chore: Sync Sass
[조사매물] 상세, 수정 퍼블 수정
2025-05-16 15:32:23 +09:00
6bcc466a76 fix: change filtering survey 2025-05-16 14:58:15 +09:00
c653df0ce7 fix: change address input to can change 2025-05-16 11:06:41 +09:00
6b62dfc1f2 Merge branch 'dev' of https://git.hanasys.jp/qcast3/onsitesurvey into feature/survey 2025-05-16 11:03:18 +09:00
2159bef4e0 Merge branch 'dev' of https://git.hanasys.jp/qcast3/onsitesurvey into feature/suitable 2025-05-15 18:33:59 +09:00
21c0a7a3a0 Merge pull request 'feat: scrollTop 기능 추가' (#35) from feature/float-button into dev
Reviewed-on: #35
2025-05-15 18:31:30 +09:00
Daseul Kim
bc3193714a feat: scrollTop 기능 추가 2025-05-15 18:28:31 +09:00
d03c01e3a9 fix: replace img with next/image for optimized loading in MemberInformationPopup 2025-05-15 17:53:14 +09:00
b11cd41ceb fix: delete inquiry test files 2025-05-15 17:19:18 +09:00
c12a010bff fix: delete unused import 2025-05-15 17:10:20 +09:00
ed47d6abf5 Merge branch 'dev' of https://git.hanasys.jp/qcast3/onsitesurvey into feature/survey 2025-05-15 17:02:56 +09:00
d7aca7e214 feat: enhance survey sales API with detailed error handling, improved search parameters, and new registration form component 2025-05-15 16:55:36 +09:00
a227ba7115 Merge branch 'dev' of https://git.hanasys.jp/qcast3/onsitesurvey into feature/survey 2025-05-14 10:00:50 +09:00
47be6a4433 feat: add conditions for read survey list on member type 2025-05-14 09:59:12 +09:00
15e02f60ec Merge branch 'dev' of https://git.hanasys.jp/qcast3/onsitesurvey into feature/survey 2025-05-13 16:46:08 +09:00
1dcb3add79 fix: change Survey's form by Prisma data type changes 2025-05-13 16:45:47 +09:00
cacf351a7c Merge branch 'dev' of https://git.hanasys.jp/qcast3/onsitesurvey into feature/survey 2025-05-13 14:17:24 +09:00
34319dadcd fix: Change the policy to allow Update, Delete, Submit to writer only
- 담당자가 로그인 한 유저 이름과 같을 때 수정, 삭제, 제출 가능하도록 변경
2025-05-12 15:45:37 +09:00
bd89552cc7 Merge branch 'feature/survey' of https://git.hanasys.jp/qcast3/onsitesurvey into feature/survey 2025-05-12 14:47:07 +09:00
김민식
493fd6cb9d common 파일 추가 2025-05-12 14:46:13 +09:00
6bbd1a6174 Merge branch 'feature/survey' of https://git.hanasys.jp/qcast3/onsitesurvey into feature/survey 2025-05-12 14:40:10 +09:00
7173ec2496 feat: implement UserType custom hook for filtering login user type 2025-05-12 14:37:47 +09:00
김민식
c5db65fc4d 우편번호 조회 기능 추가 2025-05-12 14:35:44 +09:00
901b7b1ae8 Merge branch 'dev' of https://git.hanasys.jp/qcast3/onsitesurvey into feature/survey 2025-05-12 11:13:54 +09:00
29488b2412 feat: implement survey list filter by Member Type for temporary
- 로그인 유저 타입 별 조사매물 필터링 임시 구현
- 로그인 유저 타입 구현 이후 변경 예정
2025-05-12 11:11:52 +09:00
da0d77724d fix: correct layout interface and enhance user session management 2025-05-12 10:21:01 +09:00
c06a96bc1b Merge branch 'dev' of https://git.hanasys.jp/qcast3/onsitesurvey into feature/survey 2025-05-09 17:41:41 +09:00
8bc629698a feat: implement SurveyDetail page for roof-information
- 조사매물 지붕정보 상세페이지 구현
2025-05-09 17:41:26 +09:00
34638ff0f0 fix: Change prisma db URL 2025-05-09 15:16:58 +09:00
65483812a6 Merge branch 'dev' of https://git.hanasys.jp/qcast3/onsitesurvey into feature/survey 2025-05-09 15:11:54 +09:00
95d971b198 feat: remove unused survey sale API routes & add address popup at Survey BasicForm 2025-05-09 15:08:55 +09:00
555e6f3b4a Merge branch 'dev' of https://git.hanasys.jp/qcast3/onsitesurvey into feature/survey 2025-05-08 17:02:42 +09:00
2397b7f144 feat: add survey roof-info validation when Create, Update
- 조사 매물 생성, 수정 시 각 컬럼 필수값 validation 추가
- 조사 매물 수정 페이지에서 기타 옵션 선택 시 값 초기화 되도록 구현
2025-05-08 17:01:10 +09:00
dfd5ba419b feat: implement SurveyFilteringOptions to global
- 조사매물 검색 조건 zustand 통해 전역으로 관리하도록 구현
2025-05-08 16:58:14 +09:00
68408eb3c9 Merge branch 'dev' of https://git.hanasys.jp/qcast3/onsitesurvey into feature/survey 2025-05-07 18:09:51 +09:00
115ffb8a74 feat: set SurveyList Filtering
- 조사 매물 목록 페이지 필터링 구현
- 기존 survey-sales 샘플 페이지 모두 삭제
2025-05-07 18:06:10 +09:00
fd27bfe7d0 feat: implement create & update survey roof-information with validate
- 조사 매물 지붕 정보 필수값 적용하여 등록 & 수정 가능하도록 구현
- 조사 매물 상세 & 작성 페이지 Nav 탭 기본 정보 미등록 시 라우팅 안되도록 설정정
2025-05-07 18:05:28 +09:00
daf9f31733 Merge branch 'dev' of https://git.hanasys.jp/qcast3/onsitesurvey into feature/survey 2025-05-07 09:00:35 +09:00
8153dd9d18 fix: solve conflict
- 충돌 해결 및 이전 sample page 주석 처리
2025-05-02 18:13:12 +09:00
ec9f0fa747 Merge branch 'dev' of https://git.hanasys.jp/qcast3/onsitesurvey into feature/survey 2025-05-02 18:10:48 +09:00
8e563c18dc feat: add muticheckbox component for write roof information 2025-05-02 18:06:25 +09:00
c9812d1159 feat: implement survey basic information update function 2025-05-02 18:05:15 +09:00
6777fae68c Merge branch 'dev' of https://git.hanasys.jp/qcast3/onsitesurvey into feature/survey 2025-05-02 15:46:39 +09:00
21fd51753e Merge branch 'dev' of https://git.hanasys.jp/qcast3/onsitesurvey into feature/survey 2025-05-02 15:42:21 +09:00
fc93853601 feat: implement survey-sale's read list & delete function
- 조사 매물 삭제, 리스트 조회 기능 구현
2025-05-02 15:41:37 +09:00
63750844ee Merge branch 'dev' of https://git.hanasys.jp/qcast3/onsitesurvey into feature/survey 2025-05-02 14:16:09 +09:00
ffa72ba9eb fix: Modify react query mutation function
- axiosInstance 함수 정의하지 않고 mutation function에 직접 사용하도록 변경
2025-05-02 11:32:12 +09:00
9185b5cb7a Merge branch 'dev' of https://git.hanasys.jp/qcast3/onsitesurvey into feature/survey 2025-04-30 16:50:21 +09:00
9334773023 fix: prisma db provider 수정정 2025-04-30 16:31:27 +09:00
818ecb724b feat: implement Survey Sale CRUD function
- Survey-sale Create with base information and electronic, roof information
- Survey-sale Update
- Survey-sale Read by filtering
2025-04-30 16:22:08 +09:00
08d99fb4e7 feat: Implement survey-sale, inquiry UI base components
- 조사매물, 1:1 문의 목록 더보기 버튼 구현
- 조사매물, 1:1 문의 목록, 상세 페이지, 작성 페이지 샘플 구현
2025-04-29 11:04:22 +09:00
37a40989dd feat: Add scroll to top button at InquiryList page 2025-04-29 11:04:22 +09:00
ab1e89f5d6 feat: implemnet Inquiry list & detail page's events 2025-04-29 11:04:22 +09:00
a684a3e5be feat: Inquiry sample page 구현
- 문의 목록 페이지
- 문의 작성 페이지
2025-04-29 11:04:22 +09:00
61 changed files with 4758 additions and 1037 deletions

1
.env
View File

@ -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="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="QWERASDFZXCV1234567890REWQFDSAVCXZ"
SESSION_PASSWORD="This application is for mobile field research" SESSION_PASSWORD="This application is for mobile field research"

View File

@ -12,10 +12,10 @@ const nextConfig: NextConfig = {
source: '/api/user/login', source: '/api/user/login',
destination: `${process.env.NEXT_PUBLIC_QSP_API_URL}/api/user/login`, destination: `${process.env.NEXT_PUBLIC_QSP_API_URL}/api/user/login`,
}, },
{ // {
source: '/api/:path*', // source: '/api/:path*',
destination: `${process.env.NEXT_PUBLIC_API_URL}/api/:path*`, // destination: `${process.env.NEXT_PUBLIC_API_URL}/api/:path*`,
}, // },
] ]
}, },
} }

804
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -14,6 +14,7 @@
"@tanstack/react-query-devtools": "^5.71.0", "@tanstack/react-query-devtools": "^5.71.0",
"axios": "^1.8.4", "axios": "^1.8.4",
"iron-session": "^8.0.4", "iron-session": "^8.0.4",
"lucide": "^0.503.0",
"mssql": "^11.0.1", "mssql": "^11.0.1",
"next": "15.2.4", "next": "15.2.4",
"react": "^19.0.0", "react": "^19.0.0",

8
pnpm-lock.yaml generated
View File

@ -23,6 +23,9 @@ importers:
iron-session: iron-session:
specifier: ^8.0.4 specifier: ^8.0.4
version: 8.0.4 version: 8.0.4
lucide:
specifier: ^0.503.0
version: 0.503.0
mssql: mssql:
specifier: ^11.0.1 specifier: ^11.0.1
version: 11.0.1 version: 11.0.1
@ -1109,6 +1112,9 @@ packages:
lodash.once@4.1.1: lodash.once@4.1.1:
resolution: {integrity: sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==} resolution: {integrity: sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==}
lucide@0.503.0:
resolution: {integrity: sha512-ZAVlxBU4dbSUAVidb2eT0fH3bTtKCj7M2aZNAVsFOrcnazvYJFu6I8OxFE+Fmx5XNf22Cw4Ln3NBHfBxNfoFOw==}
math-intrinsics@1.1.0: math-intrinsics@1.1.0:
resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==} resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==}
engines: {node: '>= 0.4'} engines: {node: '>= 0.4'}
@ -2340,6 +2346,8 @@ snapshots:
lodash.once@4.1.1: {} lodash.once@4.1.1: {}
lucide@0.503.0: {}
math-intrinsics@1.1.0: {} math-intrinsics@1.1.0: {}
micromatch@4.0.8: micromatch@4.0.8:

View File

@ -195,6 +195,8 @@ model MS_SUITABLE_DETAIL {
REG_DT DateTime @default(now(), map: "DF__MS_SUITAB__creat__571DF1D5") REG_DT DateTime @default(now(), map: "DF__MS_SUITAB__creat__571DF1D5")
UPT_DT DateTime? UPT_DT DateTime?
MS_SUITABLE_MAIN MS_SUITABLE_MAIN @relation(fields: [MAIN_ID], references: [ID], onUpdate: NoAction, map: "MS_SUITABLE_DETAIL_MS_SUITABLE_MAIN_FK") MS_SUITABLE_MAIN MS_SUITABLE_MAIN @relation(fields: [MAIN_ID], references: [ID], onUpdate: NoAction, map: "MS_SUITABLE_DETAIL_MS_SUITABLE_MAIN_FK")
@@index([MAIN_ID, TRESTLE_MANUFACTURER_PRODUCT_NAME], map: "MS_SUITABLE_DETAIL_MAIN_ID_IDX")
} }
model MS_SUITABLE_MAIN { model MS_SUITABLE_MAIN {
@ -206,4 +208,17 @@ model MS_SUITABLE_MAIN {
REG_DT DateTime @default(now(), map: "DF__MS_SUITAB__creat__5441852A") REG_DT DateTime @default(now(), map: "DF__MS_SUITAB__creat__5441852A")
UPT_DT DateTime? UPT_DT DateTime?
MS_SUITABLE_DETAIL MS_SUITABLE_DETAIL[] MS_SUITABLE_DETAIL MS_SUITABLE_DETAIL[]
@@index([PRODUCT_NAME], map: "MS_SUITABLE_MAIN_PRODUCT_NAME_IDX")
@@index([ROOF_MT_CD, PRODUCT_NAME], map: "MS_SUITABLE_MAIN_ROOF_MT_CD_IDX")
}
/// The underlying table does not contain a valid unique identifier and can therefore currently not be handled by Prisma Client.
model MS_USR_TRK {
ID Int @id @default(autoincrement())
OWNER String @db.VarChar(100)
TYPE String @db.VarChar(50)
URL String? @db.VarChar(200)
REG_DT DateTime @default(now())
DATA String? @db.VarChar(200)
} }

View File

@ -0,0 +1,3 @@
<svg width="10" height="6" viewBox="0 0 10 6" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M1 5L5 1L9 5" stroke="white" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 207 B

View File

@ -1,6 +1,6 @@
import { NextRequest, NextResponse } from 'next/server' import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/libs/prisma' import { prisma } from '@/libs/prisma'
import { SUITABLE_HEAD_CODE } from '@/types/Suitable' import { SUITABLE_HEAD_CODE, type SuitableMain } from '@/types/Suitable'
export async function GET(request: NextRequest) { export async function GET(request: NextRequest) {
try { try {
@ -8,29 +8,24 @@ export async function GET(request: NextRequest) {
const category = searchParams.get('category') const category = searchParams.get('category')
const keyword = searchParams.get('keyword') const keyword = searchParams.get('keyword')
let whereCondition: any = {} let MainWhereCondition: any = {}
const whereCondition: string[] = []
const params: string[] = []
if (category) { if (category) {
whereCondition[SUITABLE_HEAD_CODE.ROOF_MT_CD] = category whereCondition.push(`${SUITABLE_HEAD_CODE.ROOF_MT_CD} = @P1`)
params.push(category)
MainWhereCondition[SUITABLE_HEAD_CODE.ROOF_MT_CD] = category
} }
if (keyword) { if (keyword) {
whereCondition['PRODUCT_NAME'] = { whereCondition.push('PRODUCT_NAME LIKE @P2')
params.push(`%${keyword}%`)
MainWhereCondition['PRODUCT_NAME'] = {
contains: keyword, contains: keyword,
} }
} }
const startTime = performance.now()
console.log(`쿼리 (main table) 시작 시간: ${startTime}ms`)
// // 1 include 사용
// // @ts-ignore
// const suitable = await prisma.MS_SUITABLE_MAIN.findMany({
// where: whereCondition,
// include: {
// MS_SUITABLE_DETAIL: true,
// },
// orderBy: {
// PRODUCT_NAME: 'asc',
// },
// })
// 2 include 안쓰고 따로 쿼리, 쓸거만 골라서 조회
// @ts-ignore // @ts-ignore
const suitable = await prisma.MS_SUITABLE_MAIN.findMany({ const suitable = await prisma.MS_SUITABLE_MAIN.findMany({
select: { select: {
@ -38,31 +33,50 @@ export async function GET(request: NextRequest) {
PRODUCT_NAME: true, PRODUCT_NAME: true,
ROOF_MT_CD: true, ROOF_MT_CD: true,
}, },
where: whereCondition, where: MainWhereCondition,
orderBy: { orderBy: {
PRODUCT_NAME: 'asc', PRODUCT_NAME: 'asc',
}, },
}) })
// @ts-ignore
const suitableDetail = await prisma.MS_SUITABLE_DETAIL.findMany({
select: {
ID: true,
MAIN_ID: true,
TRESTLE_MFPC_CD: true,
TRESTLE_MANUFACTURER_PRODUCT_NAME: true,
MEMO: true,
},
where: whereCondition
? {
MAIN_ID: {
in: suitable.map((suitable: { ID: number }) => suitable.ID),
},
}
: undefined,
orderBy: [{ MAIN_ID: 'asc' }, { TRESTLE_MANUFACTURER_PRODUCT_NAME: 'asc' }],
})
return NextResponse.json({ suitable, suitableDetail }) const endTime = performance.now()
console.log(`쿼리 (main table) 종료 시간: ${endTime - startTime}ms`)
const mainIds: number[] = suitable.map((item: SuitableMain) => item.id)
const startTime2 = performance.now()
console.log(`쿼리 (detail table) 시작 시간: ${startTime2}ms`)
let detailQuery = `
SELECT
msd.main_id
, (
SELECT
msd_json.id
, msd_json.trestle_mfpc_cd
, msd_json.trestle_manufacturer_product_name
, msd_json.memo
FROM ms_suitable_detail msd_json
WHERE msd.main_id = msd_json.main_id
FOR JSON PATH
) AS detail
FROM ms_suitable_detail msd
-- WHERE 1=1
GROUP BY msd.main_id
`
if (whereCondition.length > 0) {
detailQuery = detailQuery.replace('-- WHERE 1=1', `WHERE msd.main_id IN @P1`)
}
// @ts-ignore
const detail = await prisma.$queryRawUnsafe(detailQuery, ...mainIds)
const endTime2 = performance.now()
console.log(`쿼리 (detail table) 종료 시간: ${endTime2 - startTime2}ms`)
const endTime3 = performance.now()
console.log(`쿼리 총 실행 시간: ${endTime3 - startTime}ms`)
return NextResponse.json({ suitable, detail })
} catch (error) { } catch (error) {
console.error('❌ 데이터 조회 중 오류가 발생했습니다:', error) console.error('❌ 데이터 조회 중 오류가 발생했습니다:', error)
return NextResponse.json({ error: '데이터 조회 중 오류가 발생했습니다' }, { status: 500 }) return NextResponse.json({ error: '데이터 조회 중 오류가 발생했습니다' }, { status: 500 })

View File

@ -0,0 +1,71 @@
import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/libs/prisma'
import { SUITABLE_HEAD_CODE, type Suitable } from '@/types/Suitable'
export async function GET(request: NextRequest) {
try {
const searchParams = request.nextUrl.searchParams
const category = searchParams.get('category')
const keyword = searchParams.get('keyword')
const whereCondition: string[] = []
const params: string[] = []
if (category) {
whereCondition.push(`${SUITABLE_HEAD_CODE.ROOF_MT_CD} = @P1`)
params.push(category)
}
if (keyword) {
whereCondition.push('PRODUCT_NAME LIKE @P2')
params.push(`%${keyword}%`)
}
const startTime = performance.now()
console.log(`쿼리 시작 시간: ${startTime}ms`)
let query = `
SELECT
msm.id
, msm.product_name
, msm.manu_ft_cd
, msm.roof_mt_cd
, msm.roof_sh_cd
, details.detail
FROM ms_suitable_main msm
LEFT JOIN (
SELECT
msd.main_id
, (
SELECT
msd_json.id
, msd_json.trestle_mfpc_cd
, msd_json.trestle_manufacturer_product_name
, msd_json.memo
FROM ms_suitable_detail msd_json
WHERE msd.main_id = msd_json.main_id
FOR JSON PATH
) AS detail
FROM ms_suitable_detail msd
GROUP BY msd.main_id
) AS details
ON msm.id = details.main_id
-- AND details.main_id IN (#mainIds)
-- WHERE 1=1
ORDER BY msm.product_name`
// 검색 조건 추가
if (whereCondition.length > 0) {
query = query.replace('-- WHERE 1=1', `WHERE ${whereCondition.join(' AND ')}`)
}
// @ts-ignore
const suitable: Suitable[] = await prisma.$queryRawUnsafe(query, ...params)
const endTime = performance.now()
console.log(`쿼리 실행 시간: ${endTime - startTime}ms`)
return NextResponse.json(suitable)
} catch (error) {
console.error('❌ 데이터 조회 중 오류가 발생했습니다:', error)
return NextResponse.json({ error: '데이터 조회 중 오류가 발생했습니다' }, { status: 500 })
}
}

View File

@ -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' })
// }

View File

@ -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' })
}

View File

@ -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 })
}
}

View File

@ -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 })
}
}

View File

@ -0,0 +1,33 @@
import type { SessionData } from '@/types/Auth'
import { NextResponse } from 'next/server'
import { cookies } from 'next/headers'
import { Prisma } from '@prisma/client'
import { getIronSession } from 'iron-session'
import { sessionOptions } from '@/libs/session'
export const POST = async (request: Request) => {
const { url, data } = await request.json()
const cookieStore = await cookies()
const session = await getIronSession<SessionData>(cookieStore, sessionOptions)
let owner = session.userId
let type = ''
if (url.includes('api')) {
type = 'api'
} else {
type = 'page'
}
// @ts-ignore
const result = await Prisma.MS_USR_TRK.create({
data: {
owner,
type,
url,
data: JSON.stringify(data),
},
})
return NextResponse.json({ message: 'Tracking data received', result })
}

View File

@ -22,7 +22,7 @@ interface RootLayoutProps {
header: ReactNode header: ReactNode
footer: ReactNode footer: ReactNode
floatBtn: ReactNode floatBtn: ReactNode
} }6
export default async function RootLayout({ children, header, footer, floatBtn }: RootLayoutProps): Promise<ReactNode> { export default async function RootLayout({ children, header, footer, floatBtn }: RootLayoutProps): Promise<ReactNode> {
const cookieStore = await cookies() const cookieStore = await cookies()
@ -33,7 +33,7 @@ export default async function RootLayout({ children, header, footer, floatBtn }:
return ( return (
<ReactQueryProviders> <ReactQueryProviders>
<EdgeProvider sessionData={sessionData}> <EdgeProvider sessionData={sessionData}>
<html lang="en"> <html lang="ja" suppressHydrationWarning>
<body> <body>
<div className="wrap"> <div className="wrap">
{header} {header}

9
src/app/pdf/page.tsx Normal file
View File

@ -0,0 +1,9 @@
import DownloadPdf from '@/components/DownloadPDF'
export default function page() {
return (
<>
<DownloadPdf />
</>
)
}

View File

@ -0,0 +1,24 @@
import type { ReactNode } from 'react'
interface SuitableLayoutProps {
children: ReactNode
}
export default function layout({ children }: SuitableLayoutProps) {
return (
<>
<div className="container">
<div className="sale-contents">
<div className="border-frame">
<div className="pw-guide">
<div className="pw-guide-txt">使.</div>
<div className="pw-guide-txt">11.</div>
<div className="pw-guide-txt">or屋根材名を直接入力してください.</div>
</div>
</div>
{children}
</div>
</div>
</>
)
}

View File

@ -0,0 +1,9 @@
import SuitableRaw from '@/components/suitable/SuitableRaw'
export default function page() {
return (
<>
<SuitableRaw />
</>
)
}

View File

@ -1,11 +1,10 @@
import DataTable from '@/components/survey-sale/detail/DataTable' import DataTable from '@/components/survey-sale/detail/DataTable'
import DetailForm from '@/components/survey-sale/detail/DetailForm'
export default function page() { export default function page() {
return ( return (
<> <>
<DataTable /> <DataTable />
<DetailForm /> {/* <DetailForm surveyInfo={surveyInfo} mode="READ" /> */}
</> </>
) )
} }

View File

@ -1,9 +0,0 @@
import BasicForm from '@/components/survey-sale/detail/BasicForm'
export default function page() {
return (
<>
<BasicForm />
</>
)
}

View File

@ -9,10 +9,7 @@ export default function layout({ children, navTab }: SurveySaleLayoutProps) {
return ( return (
<> <>
<div className="container"> <div className="container">
<div className="sale-contents"> <div className="sale-contents">{children}</div>
{navTab}
{children}
</div>
</div> </div>
</> </>
) )

View File

@ -1,10 +1,8 @@
import ListTable from '@/components/survey-sale/list/ListTable' import ListTable from '@/components/survey-sale/list/ListTable'
import SearchForm from '@/components/survey-sale/list/SearchForm'
export default function page() { export default function page() {
return ( return (
<> <>
<SearchForm />
<ListTable /> <ListTable />
</> </>
) )

View File

@ -0,0 +1,9 @@
import RegistForm from '@/components/survey-sale/detail/RegistForm'
export default function RegistPage() {
return (
<>
<RegistForm/>
</>
)
}

View File

@ -1,9 +0,0 @@
import RoofInfoForm from '@/components/survey-sale/detail/RoofInfoForm'
export default function page() {
return (
<>
<RoofInfoForm />
</>
)
}

View File

@ -0,0 +1,748 @@
'use client'
import { useRef } from 'react'
import generatePDF, { Margin, Resolution } from 'react-to-pdf'
export default function DownloadPdf() {
const targetRef = useRef<HTMLDivElement>(null)
const handleDownPdf = () => {
const options = {
method: 'open' as const,
resolution: Resolution.HIGH,
page: {
margin: Margin.SMALL,
format: 'A4',
orientation: 'portrait' as const,
},
canvas: {
mimeType: 'image/png' as const,
qualityRatio: 1,
},
overrides: {
pdf: {
compress: true,
},
canvas: {
useCORS: true,
},
},
}
generatePDF(targetRef, options)
// generatePDF(targetRef, { filename: 'page.pdf' })
}
return (
<>
<button onClick={handleDownPdf}>down</button>
<div ref={targetRef} style={{ boxSizing: 'border-box' }}>
<div style={{ margin: '0 auto', padding: 0, maxWidth: '800px' }}>
<div style={{ padding: '20px 20px 50px', borderBottom: '2px solid #2E3A59' }}>
<div style={{ float: 'left', verticalAlign: 'middle', fontSize: '18px', color: '#101010', fontWeight: 600, fontFamily: 'M-Gothic' }}>
HWJ 調1/2
</div>
<div style={{ float: 'right', overflow: 'hidden' }}>
<div style={{ float: 'left', marginRight: '20px' }}>
<p style={{ margin: 0, padding: 0, fontSize: '13px', color: '#101010', fontWeight: 500, fontFamily: 'M-Gothic', textAlign: 'right' }}>
</p>
<p style={{ margin: 0, padding: 0, fontSize: '13px', color: '#FF5656', fontWeight: 400, fontFamily: 'M-Gothic' }}>
Sheet2 No.4Sheet2
</p>
</div>
<div style={{ float: 'right' }}>
<p style={{ margin: 0, padding: 0, fontSize: '13px', color: '#101010', fontWeight: 500, fontFamily: 'M-Gothic' }}></p>
<p style={{ margin: 0, padding: 0, fontSize: '13px', color: '#FF5656', fontWeight: 400, fontFamily: 'M-Gothic' }}>2025.05.09</p>
</div>
</div>
</div>
<div style={{ padding: '24px 20px 12px' }}>
<table
style={{ width: '100%', tableLayout: 'fixed', borderCollapse: 'collapse', fontFamily: 'M-Gothic', WebkitPrintColorAdjust: 'exact' }}
>
<tbody>
<tr>
<th
style={{
padding: '10px',
width: '73px',
border: '1px solid #2E3A59',
backgroundColor: '#F5F6FA',
fontSize: '13px',
fontWeight: 500,
color: '#101010',
textAlign: 'left',
boxSizing: 'border-box',
}}
>
</th>
<td
style={{
padding: '10px',
border: '1px solid #2E3A59',
fontSize: '13px',
fontWeight: 500,
color: '#FF5656',
boxSizing: 'border-box',
}}
>
Sheet2No.1
</td>
</tr>
<tr>
<th
style={{
padding: '10px',
width: '73px',
border: '1px solid #2E3A59',
backgroundColor: '#F5F6FA',
fontSize: '13px',
fontWeight: 500,
color: '#101010',
textAlign: 'left',
boxSizing: 'border-box',
}}
>
</th>
<td
style={{
padding: '10px',
border: '1px solid #2E3A59',
fontSize: '13px',
fontWeight: 500,
color: '#FF5656',
boxSizing: 'border-box',
}}
>
Sheet2No.2
</td>
</tr>
</tbody>
</table>
</div>
<div style={{ padding: '12px 20px 12px' }}>
<div style={{ fontSize: '14px', fontFamily: 'M-Gothic', color: '#101010', fontWeight: 500, marginBottom: '10px' }}></div>
<table
style={{ width: '100%', tableLayout: 'fixed', borderCollapse: 'collapse', fontFamily: 'M-Gothic', WebkitPrintColorAdjust: 'exact' }}
>
<tbody>
<tr>
<th
style={{
padding: '10px',
width: '126px',
border: '1px solid #2E3A59',
backgroundColor: '#F5F6FA',
fontSize: '13px',
fontWeight: 500,
color: '#101010',
textAlign: 'left',
boxSizing: 'border-box',
}}
>
</th>
<td
style={{
padding: '10px',
border: '1px solid #2E3A59',
fontSize: '13px',
fontWeight: 500,
color: '#FF5656',
boxSizing: 'border-box',
}}
>
Sheet2No.1
</td>
<th
style={{
padding: '10px',
width: '126px',
border: '1px solid #2E3A59',
backgroundColor: '#F5F6FA',
fontSize: '13px',
fontWeight: 500,
color: '#101010',
textAlign: 'left',
boxSizing: 'border-box',
}}
>
</th>
<td
style={{
padding: '10px',
border: '1px solid #2E3A59',
fontSize: '13px',
fontWeight: 500,
color: '#FF5656',
boxSizing: 'border-box',
}}
>
Sheet2No.1
</td>
</tr>
<tr>
<th
style={{
padding: '10px',
width: '126px',
border: '1px solid #2E3A59',
backgroundColor: '#F5F6FA',
fontSize: '13px',
fontWeight: 500,
color: '#101010',
textAlign: 'left',
boxSizing: 'border-box',
}}
>
</th>
<td
colSpan={3}
style={{
padding: '10px',
border: '1px solid #2E3A59',
fontSize: '13px',
fontWeight: 500,
color: '#FF5656',
boxSizing: 'border-box',
}}
>
Sheet2No.7 /
</td>
</tr>
<tr>
<th
style={{
padding: '10px',
width: '126px',
border: '1px solid #2E3A59',
backgroundColor: '#F5F6FA',
fontSize: '13px',
fontWeight: 500,
color: '#101010',
textAlign: 'left',
boxSizing: 'border-box',
}}
>
</th>
<td
colSpan={3}
style={{
padding: '10px',
border: '1px solid #2E3A59',
fontSize: '13px',
fontWeight: 500,
color: '#FF5656',
boxSizing: 'border-box',
}}
>
Sheet2No.8 /
</td>
</tr>
</tbody>
</table>
</div>
<div style={{ padding: '12px 20px 12px' }}>
<div style={{ fontSize: '14px', fontFamily: 'M-Gothic', color: '#101010', fontWeight: 500, marginBottom: '10px' }}></div>
<table
style={{ width: '100%', tableLayout: 'fixed', borderCollapse: 'collapse', fontFamily: 'M-Gothic', WebkitPrintColorAdjust: 'exact' }}
>
<tbody>
<tr>
<th
style={{
padding: '10px',
width: '126px',
border: '1px solid #2E3A59',
backgroundColor: '#F5F6FA',
fontSize: '13px',
fontWeight: 500,
color: '#101010',
textAlign: 'left',
boxSizing: 'border-box',
}}
>
</th>
<td
style={{
padding: '10px',
border: '1px solid #2E3A59',
fontSize: '13px',
fontWeight: 500,
color: '#FF5656',
boxSizing: 'border-box',
}}
>
No.9
</td>
<th
style={{
padding: '10px',
width: '126px',
border: '1px solid #2E3A59',
backgroundColor: '#F5F6FA',
fontSize: '13px',
fontWeight: 500,
color: '#101010',
textAlign: 'left',
boxSizing: 'border-box',
}}
>
</th>
<td
style={{
padding: '10px',
border: '1px solid #2E3A59',
fontSize: '13px',
fontWeight: 500,
color: '#FF5656',
boxSizing: 'border-box',
}}
>
No.10
</td>
<th
style={{
padding: '10px',
width: '126px',
border: '1px solid #2E3A59',
backgroundColor: '#F5F6FA',
fontSize: '13px',
fontWeight: 500,
color: '#101010',
textAlign: 'left',
boxSizing: 'border-box',
}}
>
</th>
<td
style={{
padding: '10px',
border: '1px solid #2E3A59',
fontSize: '13px',
fontWeight: 500,
color: '#FF5656',
boxSizing: 'border-box',
}}
>
No.11
</td>
</tr>
<tr>
<th
style={{
padding: '10px',
width: '126px',
border: '1px solid #2E3A59',
backgroundColor: '#F5F6FA',
fontSize: '13px',
fontWeight: 500,
color: '#101010',
textAlign: 'left',
boxSizing: 'border-box',
}}
>
</th>
<td
style={{
padding: '10px',
border: '1px solid #2E3A59',
fontSize: '13px',
fontWeight: 500,
color: '#FF5656',
boxSizing: 'border-box',
}}
>
No.12
</td>
<th
style={{
padding: '10px',
width: '126px',
border: '1px solid #2E3A59',
backgroundColor: '#F5F6FA',
fontSize: '13px',
fontWeight: 500,
color: '#101010',
textAlign: 'left',
boxSizing: 'border-box',
}}
>
</th>
<td
colSpan={3}
style={{
padding: '10px',
border: '1px solid #2E3A59',
fontSize: '13px',
fontWeight: 500,
color: '#FF5656',
boxSizing: 'border-box',
}}
>
No.13
</td>
</tr>
<tr>
<th
style={{
padding: '10px',
width: '126px',
border: '1px solid #2E3A59',
backgroundColor: '#F5F6FA',
fontSize: '13px',
fontWeight: 500,
color: '#101010',
textAlign: 'left',
boxSizing: 'border-box',
}}
>
</th>
<td
style={{
padding: '10px',
border: '1px solid #2E3A59',
fontSize: '13px',
fontWeight: 500,
color: '#FF5656',
boxSizing: 'border-box',
}}
>
No.14
</td>
<th
style={{
padding: '10px',
width: '126px',
border: '1px solid #2E3A59',
backgroundColor: '#F5F6FA',
fontSize: '13px',
fontWeight: 500,
color: '#101010',
textAlign: 'left',
boxSizing: 'border-box',
}}
>
</th>
<td
colSpan={3}
style={{
padding: '10px',
border: '1px solid #2E3A59',
fontSize: '13px',
fontWeight: 500,
color: '#FF5656',
boxSizing: 'border-box',
}}
>
No.15
</td>
</tr>
<tr>
<th
style={{
padding: '10px',
width: '126px',
border: '1px solid #2E3A59',
backgroundColor: '#F5F6FA',
fontSize: '13px',
fontWeight: 500,
color: '#101010',
textAlign: 'left',
boxSizing: 'border-box',
}}
>
</th>
<td
style={{
padding: '10px',
border: '1px solid #2E3A59',
fontSize: '13px',
fontWeight: 500,
color: '#FF5656',
boxSizing: 'border-box',
}}
>
No.16
</td>
<th
style={{
padding: '10px',
width: '126px',
border: '1px solid #2E3A59',
backgroundColor: '#F5F6FA',
fontSize: '13px',
fontWeight: 500,
color: '#101010',
textAlign: 'left',
boxSizing: 'border-box',
}}
>
</th>
<td
colSpan={3}
style={{
padding: '10px',
border: '1px solid #2E3A59',
fontSize: '13px',
fontWeight: 500,
color: '#FF5656',
boxSizing: 'border-box',
}}
>
No.17
</td>
</tr>
<tr>
<th
style={{
padding: '10px',
width: '126px',
border: '1px solid #2E3A59',
backgroundColor: '#F5F6FA',
fontSize: '13px',
fontWeight: 500,
color: '#101010',
textAlign: 'left',
boxSizing: 'border-box',
}}
>
</th>
<td
style={{
padding: '10px',
border: '1px solid #2E3A59',
fontSize: '13px',
fontWeight: 500,
color: '#FF5656',
boxSizing: 'border-box',
}}
>
No.18
</td>
<th
style={{
padding: '10px',
width: '126px',
border: '1px solid #2E3A59',
backgroundColor: '#F5F6FA',
fontSize: '13px',
fontWeight: 500,
color: '#101010',
textAlign: 'left',
boxSizing: 'border-box',
}}
>
</th>
<td
colSpan={3}
style={{
padding: '10px',
border: '1px solid #2E3A59',
fontSize: '13px',
fontWeight: 500,
color: '#FF5656',
boxSizing: 'border-box',
}}
>
No.19
</td>
</tr>
<tr>
<th
style={{
padding: '10px',
width: '126px',
border: '1px solid #2E3A59',
backgroundColor: '#F5F6FA',
fontSize: '13px',
fontWeight: 500,
color: '#101010',
textAlign: 'left',
boxSizing: 'border-box',
}}
>
</th>
<td
colSpan={5}
style={{
padding: '10px',
border: '1px solid #2E3A59',
fontSize: '13px',
fontWeight: 500,
color: '#FF5656',
boxSizing: 'border-box',
}}
>
No.20
</td>
</tr>
<tr>
<th
style={{
padding: '10px',
width: '126px',
border: '1px solid #2E3A59',
backgroundColor: '#F5F6FA',
fontSize: '13px',
fontWeight: 500,
color: '#101010',
textAlign: 'left',
boxSizing: 'border-box',
}}
>
</th>
<td
colSpan={5}
style={{
padding: '10px',
border: '1px solid #2E3A59',
fontSize: '13px',
fontWeight: 500,
color: '#FF5656',
boxSizing: 'border-box',
}}
>
No.21
</td>
</tr>
<tr>
<th
style={{
padding: '10px',
width: '126px',
border: '1px solid #2E3A59',
backgroundColor: '#F5F6FA',
fontSize: '13px',
fontWeight: 500,
color: '#101010',
textAlign: 'left',
boxSizing: 'border-box',
}}
>
</th>
<td
colSpan={5}
style={{
padding: '10px',
border: '1px solid #2E3A59',
fontSize: '13px',
fontWeight: 500,
color: '#FF5656',
boxSizing: 'border-box',
}}
>
No.22
</td>
</tr>
<tr>
<th
style={{
padding: '10px',
width: '126px',
border: '1px solid #2E3A59',
backgroundColor: '#F5F6FA',
fontSize: '13px',
fontWeight: 500,
color: '#101010',
textAlign: 'left',
boxSizing: 'border-box',
}}
>
</th>
<td
colSpan={5}
style={{
padding: '10px',
border: '1px solid #2E3A59',
fontSize: '13px',
fontWeight: 500,
color: '#FF5656',
boxSizing: 'border-box',
}}
>
No.23
</td>
</tr>
</tbody>
</table>
</div>
<div style={{ padding: '12px 20px' }}>
<table
style={{ width: '100%', tableLayout: 'fixed', borderCollapse: 'collapse', fontFamily: 'M-Gothic', WebkitPrintColorAdjust: 'exact' }}
>
<tbody>
<tr>
<th
style={{
padding: '10px',
width: '160px',
border: '1px solid #2E3A59',
backgroundColor: '#F5F6FA',
fontSize: '13px',
fontWeight: 500,
color: '#101010',
textAlign: 'left',
boxSizing: 'border-box',
}}
>
</th>
<td
colSpan={5}
style={{
padding: '10px',
border: '1px solid #2E3A59',
fontSize: '13px',
fontWeight: 500,
color: '#FF5656',
boxSizing: 'border-box',
}}
>
No.23
</td>
</tr>
</tbody>
</table>
</div>
<div style={{ padding: '12px 20px 12px' }}>
<div style={{ fontSize: '14px', fontFamily: 'M-Gothic', color: '#101010', fontWeight: 500, marginBottom: '10px' }}></div>
<div
style={{
boxSizing: 'border-box',
padding: '10px',
fontSize: '13px',
fontWeight: 400,
fontFamily: 'M-Gothic',
color: '#FF5656',
border: '1px solid #2E3A59',
height: '150px',
}}
>
No.25
</div>
</div>
</div>
</div>
</>
)
}

View File

@ -0,0 +1,21 @@
'use client'
interface LoadMoreButtonProps {
hasMore: boolean
onLoadMore: () => void
}
export default function LoadMoreButton({ hasMore, onLoadMore }: LoadMoreButtonProps) {
return (
<>
{hasMore ? (
<button onClick={onLoadMore} className="btn-frame n-blue icon">
<i className="btn-edit"></i>
</button>
) : (
<></>
)}
</>
)
}

View File

@ -1,10 +1,13 @@
'use client' 'use client'
import { useRouter } from 'next/navigation'
export default function ListForm() { export default function ListForm() {
const router = useRouter()
return ( return (
<> <>
<div className="sale-frame"> <div className="sale-frame">
<div className="sale-form-bx"> <div className="sale-form-bx">
<button className="btn-frame n-blue icon"> <button className="btn-frame n-blue icon" onClick={() => router.push('/inquiry/regist')}>
<i className="btn-arr"></i> <i className="btn-arr"></i>
</button> </button>
</div> </div>

View File

@ -1,5 +1,52 @@
'use client' '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() { 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 ( return (
<> <>
<div className="sale-frame"> <div className="sale-frame">
@ -13,10 +60,8 @@ export default function ListTable() {
<div className="filter-select"> <div className="filter-select">
<select className="select-form" name="" id=""> <select className="select-form" name="" id="">
<option value=""></option> <option value=""></option>
<option value=""></option> <option value=""></option>
<option value=""></option> <option value=""></option>
<option value=""></option>
<option value=""></option>
</select> </select>
</div> </div>
</div> </div>
@ -80,9 +125,7 @@ export default function ListTable() {
</li> </li>
</ul> </ul>
<div className="sale-edit-btn"> <div className="sale-edit-btn">
<button className="btn-frame n-blue icon"> <LoadMoreButton hasMore={hasMore} onLoadMore={() => setOffset(offset + 10)} />
<i className="btn-edit"></i>
</button>
</div> </div>
</div> </div>
</div> </div>

View File

@ -3,6 +3,7 @@
import { useRouter } from 'next/navigation' import { useRouter } from 'next/navigation'
import { usePopupController } from '@/store/popupController' import { usePopupController } from '@/store/popupController'
import { useSessionStore } from '@/store/session' import { useSessionStore } from '@/store/session'
import Image from 'next/image'
export default function MemberInformationPopup() { export default function MemberInformationPopup() {
const popupController = usePopupController() const popupController = usePopupController()
@ -22,7 +23,7 @@ export default function MemberInformationPopup() {
<div className="modal-header-inner"> <div className="modal-header-inner">
<div className="modal-name-wrap"> <div className="modal-name-wrap">
<div className="modal-img"> <div className="modal-img">
<img src="/assets/images/layout/modal_header_icon.svg" alt="" /> <Image src="/assets/images/layout/modal_header_icon.svg" width={18} height={20} alt="" />
</div> </div>
<div className="modal-name"></div> <div className="modal-name"></div>
</div> </div>

View File

@ -1,18 +1,56 @@
'use client' 'use client'
import { useServey } from '@/hooks/useSurvey'
import { useAddressStore } from '@/store/addressStore'
import { usePopupController } from '@/store/popupController' import { usePopupController } from '@/store/popupController'
import { useState } from 'react' 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() { export default function ZipCodePopup() {
const [searchValue, setSearchValue] = useState('') //search 데이터 유무 const [searchValue, setSearchValue] = useState('') //search 데이터 유무
const [selected, setSelected] = useState('')
const { setAddressData } = useAddressStore()
const { getZipCode } = useServey()
const [addressInfo, setAddressInfo] = useState<Address[] | null>([])
//search 데이터 value 추가 //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<HTMLInputElement>) => { const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setSearchValue(e.target.value) setSearchValue(e.target.value)
} }
const popupController = usePopupController() const handleSearch = () => {
const addressData = getZipCode(searchValue)
addressData.then((address) => {
if (address) {
setAddressInfo(address)
} else {
setAddressInfo([])
}
})
}
return ( return (
<> <>
<div className="modal-popup"> <div className="modal-popup">
@ -33,10 +71,10 @@ export default function ZipCodePopup() {
<div className="zip-code-search-wrap"> <div className="zip-code-search-wrap">
<div className="zip-code-search-input"> <div className="zip-code-search-input">
<div className="search-input"> <div className="search-input">
<input type="text" className="search-frame" value={searchValue} onChange={handleChange} placeholder="Search" /> <input type="text" className="search-frame" value={searchValue} placeholder="Search" onChange={handleChange} />
{/*input에 데이터 있으면 삭제버튼 보임 */} {/*input에 데이터 있으면 삭제버튼 보임 */}
{searchValue && <button className="del-icon" onClick={() => setSearchValue('')}></button>} {searchValue && <button className="del-icon" onClick={() => setSearchValue('')}></button>}
<button className="search-icon"></button> <button className="search-icon" onClick={handleSearch}></button>
</div> </div>
</div> </div>
<div className="zip-code-table-wrap"> <div className="zip-code-table-wrap">
@ -50,31 +88,23 @@ export default function ZipCodePopup() {
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
<tr> {addressInfo?.map((item, index) => (
<td></td> <tr key={`${item.zipcode}-${index}`} onClick={() => setSelected(item.zipcode)}>
<td></td> <td>{item.address1}</td>
<td></td> <td>{item.address2}</td>
</tr> <td>{item.address3}</td>
<tr> </tr>
<td></td> ))}
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</tbody> </tbody>
</table> </table>
<div className="btn-flex-wrap"> <div className="btn-flex-wrap">
<div className="btn-bx"> <div className="btn-bx">
<button className="btn-frame red icon"> <button className="btn-frame red icon" onClick={handleApply}>
<i className="btn-arr"></i> <i className="btn-arr"></i>
</button> </button>
</div> </div>
<div className="btn-bx"> <div className="btn-bx">
<button className="btn-frame n-blue icon"> <button className="btn-frame n-blue icon" onClick={() => popupController.setZipCodePopup(false)}>
<i className="btn-arr"></i> <i className="btn-arr"></i>
</button> </button>
</div> </div>

View File

@ -48,8 +48,8 @@ export default function Suitable() {
<select className="select-form" name="" id="" value={selectedCategory || ''} onChange={(e) => setSelectedCategory(e.target.value)}> <select className="select-form" name="" id="" value={selectedCategory || ''} onChange={(e) => setSelectedCategory(e.target.value)}>
<option value="">.</option> <option value="">.</option>
{suitableCommCode.get(SUITABLE_HEAD_CODE.ROOF_MT_CD)?.map((category: CommCode, index: number) => ( {suitableCommCode.get(SUITABLE_HEAD_CODE.ROOF_MT_CD)?.map((category: CommCode, index: number) => (
<option key={index} value={category.CODE}> <option key={index} value={category.code}>
{category.CODE_JP} {category.codeJp}
</option> </option>
))} ))}
</select> </select>

View File

@ -1,32 +1,90 @@
'use client' 'use client'
import Image from 'next/image' import Image from 'next/image'
import { useState } from 'react' import { useState, useEffect, useRef, useCallback, useMemo } from 'react'
import SuitableButton from './SuitableButton' import SuitableButton from './SuitableButton'
import SuitableNoData from './SuitableNoData' import SuitableNoData from './SuitableNoData'
import { useSuitable } from '@/hooks/useSuitable' import { useSuitable } from '@/hooks/useSuitable'
import { useSuitableStore } from '@/store/useSuitableStore' import { useSuitableStore } from '@/store/useSuitableStore'
import { SUITABLE_HEAD_CODE, type SuitableMain, type SuitableDetail } from '@/types/Suitable' import { SUITABLE_HEAD_CODE, type SuitableMain, type SuitableDetail } from '@/types/Suitable'
// 한 번에 로드할 아이템 수
const ITEMS_PER_PAGE = 100
export default function SuitableList() { export default function SuitableList() {
const { toCodeName, suitableSearchResults, isSearchLoading, filterSuitableDetail } = useSuitable() const { toCodeName, suitableSearchResults, isSearchLoading, toSuitableDetail } = useSuitable()
const { selectedItems, addSelectedItem, removeSelectedItem } = useSuitableStore() const { selectedItems, addSelectedItem, removeSelectedItem } = useSuitableStore()
const [openItems, setOpenItems] = useState<Set<number>>(new Set()) const [openItems, setOpenItems] = useState<Set<number>>(new Set())
const [visibleItems, setVisibleItems] = useState<SuitableMain[]>([])
const [page, setPage] = useState(1)
const [isLoadingMore, setIsLoadingMore] = useState(false)
const observerTarget = useRef<HTMLDivElement>(null)
const handleItemClick = (itemId: number) => { // 선택된 아이템 확인 함수 메모이제이션
selectedItems.some((selected) => selected === itemId) ? removeSelectedItem(itemId) : addSelectedItem(itemId) const isItemSelected = useCallback(
} (itemId: number) => {
return selectedItems.some((selected) => selected === itemId)
},
[selectedItems],
)
const toggleItemOpen = (itemId: number) => { // 초기 데이터 로드
useEffect(() => {
if (suitableSearchResults) {
const initialItems = suitableSearchResults.suitable.slice(0, ITEMS_PER_PAGE)
setVisibleItems(initialItems)
setPage(1)
}
}, [suitableSearchResults])
// Intersection Observer 설정
useEffect(() => {
const observer = new IntersectionObserver(
(entries) => {
if (entries[0].isIntersecting && suitableSearchResults && !isLoadingMore) {
const nextPage = page + 1
const startIndex = (nextPage - 1) * ITEMS_PER_PAGE
const endIndex = startIndex + ITEMS_PER_PAGE
const nextItems = suitableSearchResults.suitable.slice(startIndex, endIndex)
if (nextItems.length > 0) {
setIsLoadingMore(true)
setVisibleItems((prev) => [...prev, ...nextItems])
setPage(nextPage)
setIsLoadingMore(false)
}
}
},
{
threshold: 0.2,
},
)
if (observerTarget.current) {
observer.observe(observerTarget.current)
}
return () => observer.disconnect()
}, [page, suitableSearchResults, isLoadingMore])
const handleItemClick = useCallback(
(itemId: number) => {
isItemSelected(itemId) ? removeSelectedItem(itemId) : addSelectedItem(itemId)
},
[isItemSelected, addSelectedItem, removeSelectedItem],
)
const toggleItemOpen = useCallback((itemId: number) => {
setOpenItems((prev) => { setOpenItems((prev) => {
const newOpenItems = new Set(prev) const newOpenItems = new Set(prev)
newOpenItems.has(itemId) ? newOpenItems.delete(itemId) : newOpenItems.add(itemId) newOpenItems.has(itemId) ? newOpenItems.delete(itemId) : newOpenItems.add(itemId)
return newOpenItems return newOpenItems
}) })
} }, [])
// TODO: 추후 지붕재 적합성 데이터 CUD 구현 시 ×, ー 데이터 관리 필요 // TODO: 추후 지붕재 적합성 데이터 CUD 구현 시 ×, ー 데이터 관리 필요
const suitableCheck = (value: string) => { const suitableCheck = useCallback((value: string) => {
if (value === '×') { if (value === '×') {
return ( return (
<div className="compliance-icon"> <div className="compliance-icon">
@ -46,52 +104,71 @@ export default function SuitableList() {
</div> </div>
) )
} }
}, [])
// 메모이제이션된 아이템 렌더링
const renderItem = useCallback(
(item: SuitableMain) => {
const isSelected = isItemSelected(item.id)
const isOpen = openItems.has(item.id)
return (
<div className={`compliance-check-bx ${isOpen ? 'act' : ''}`} key={item.id}>
<div className="check-name-wrap">
<div className="check-form-box ">
<input type="checkbox" id={`ch${item.id}`} checked={isSelected} onChange={() => handleItemClick(item.id)} />
<label htmlFor={`ch${item.id}`}>{item.productName}</label>
</div>
<div className="check-name-btn">
<button className="bx-btn" onClick={() => toggleItemOpen(item.id)}></button>
</div>
</div>
<ul className="reference-list check">
{toSuitableDetail(item.id).map((subItem: SuitableDetail) => (
<li className="reference-item" key={subItem.id}>
<div className="check-item-wrap">
<div className="check-form-box light">
<input type="checkbox" id={`ch${subItem.id}`} />
<label htmlFor={`ch${subItem.id}`}>{toCodeName(SUITABLE_HEAD_CODE.TRESTLE_MFPC_CD, subItem.trestleMfpcCd)}</label>
</div>
<div className="compliance-icon-wrap">
{suitableCheck(subItem.trestleManufacturerProductName)}
{subItem.memo && (
<div className="compliance-icon">
<Image src={'/assets/images/sub/compliance_tip_icon.svg'} width={22} height={22} alt=""></Image>
</div>
)}
</div>
</div>
</li>
))}
</ul>
</div>
)
},
[isItemSelected, openItems, handleItemClick, toggleItemOpen, suitableCheck, toCodeName, toSuitableDetail],
)
// 메모이제이션된 아이템 리스트
const renderedItems = useMemo(() => {
return visibleItems.map(renderItem)
}, [visibleItems, renderItem])
if (isSearchLoading) {
return <div>Loading...</div>
}
if (!suitableSearchResults?.suitable.length) {
return <SuitableNoData />
} }
return ( return (
<> <>
{isSearchLoading ? ( {renderedItems}
<div>Loading...</div> <div ref={observerTarget} className="loading-indicator">
) : suitableSearchResults && suitableSearchResults.suitable.length > 0 ? ( {isLoadingMore && <div className="loading-more"> ...</div>}
<> </div>
{suitableSearchResults.suitable.map((item: SuitableMain) => ( <SuitableButton />
<div className={`compliance-check-bx ${openItems.has(item.ID) ? 'act' : ''}`} key={item.ID}>
<div className="check-name-wrap">
<div className="check-form-box ">
<input type="checkbox" id={`ch${item.ID}`} onClick={() => handleItemClick(item.ID)} />
<label htmlFor={`ch${item.ID}`}>{item.PRODUCT_NAME}</label>
</div>
<div className="check-name-btn">
<button className="bx-btn" onClick={() => toggleItemOpen(item.ID)}></button>
</div>
</div>
<ul className="reference-list check">
{filterSuitableDetail(item.ID)?.map((subItem: SuitableDetail) => (
<li className="reference-item" key={subItem.ID}>
<div className="check-item-wrap">
<div className="check-form-box light">
<input type="checkbox" id={`ch${subItem.ID}`} />
<label htmlFor={`ch${subItem.ID}`}>{toCodeName(SUITABLE_HEAD_CODE.TRESTLE_MFPC_CD, subItem.TRESTLE_MFPC_CD)}</label>
</div>
<div className="compliance-icon-wrap">
{suitableCheck(subItem.TRESTLE_MANUFACTURER_PRODUCT_NAME)}
{subItem.MEMO && (
<div className="compliance-icon">
<Image src={'/assets/images/sub/compliance_tip_icon.svg'} width={22} height={22} alt=""></Image>
</div>
)}
</div>
</div>
</li>
))}
</ul>
</div>
))}
<SuitableButton />
</>
) : (
<SuitableNoData />
)}
</> </>
) )
} }

View File

@ -0,0 +1,173 @@
'use client'
import Image from 'next/image'
import { useState, useEffect, useRef, useCallback, useMemo } from 'react'
import SuitableButton from './SuitableButton'
import SuitableNoData from './SuitableNoData'
import { useSuitableRaw, type Suitable } from '@/hooks/useSuitableRaw'
import { useSuitableStore } from '@/store/useSuitableStore'
import { SUITABLE_HEAD_CODE, type SuitableDetail } from '@/types/Suitable'
// 한 번에 로드할 아이템 수
const ITEMS_PER_PAGE = 100
export default function SuitableListRaw() {
const { toCodeName, suitableSearchResults, isSearchLoading, toSuitableDetail } = useSuitableRaw()
const { selectedItems, addSelectedItem, removeSelectedItem } = useSuitableStore()
const [openItems, setOpenItems] = useState<Set<number>>(new Set())
const [visibleItems, setVisibleItems] = useState<Suitable[]>([])
const [page, setPage] = useState(1)
const [isLoadingMore, setIsLoadingMore] = useState(false)
const observerTarget = useRef<HTMLDivElement>(null)
// 선택된 아이템 확인 함수 메모이제이션
const isItemSelected = useCallback(
(itemId: number) => {
return selectedItems.some((selected) => selected === itemId)
},
[selectedItems],
)
// 초기 데이터 로드
useEffect(() => {
if (suitableSearchResults) {
const initialItems = suitableSearchResults.slice(0, ITEMS_PER_PAGE)
setVisibleItems(initialItems)
setPage(1)
}
}, [suitableSearchResults])
// Intersection Observer 설정
useEffect(() => {
const observer = new IntersectionObserver(
(entries) => {
if (entries[0].isIntersecting && suitableSearchResults && !isLoadingMore) {
const nextPage = page + 1
const startIndex = (nextPage - 1) * ITEMS_PER_PAGE
const endIndex = startIndex + ITEMS_PER_PAGE
const nextItems = suitableSearchResults.slice(startIndex, endIndex)
if (nextItems.length > 0) {
setIsLoadingMore(true)
setVisibleItems((prev) => [...prev, ...nextItems])
setPage(nextPage)
setIsLoadingMore(false)
}
}
},
{
threshold: 0.2,
},
)
if (observerTarget.current) {
observer.observe(observerTarget.current)
}
return () => observer.disconnect()
}, [page, suitableSearchResults, isLoadingMore])
const handleItemClick = useCallback(
(itemId: number) => {
isItemSelected(itemId) ? removeSelectedItem(itemId) : addSelectedItem(itemId)
},
[isItemSelected, addSelectedItem, removeSelectedItem],
)
const toggleItemOpen = useCallback((itemId: number) => {
setOpenItems((prev) => {
const newOpenItems = new Set(prev)
newOpenItems.has(itemId) ? newOpenItems.delete(itemId) : newOpenItems.add(itemId)
return newOpenItems
})
}, [])
// TODO: 추후 지붕재 적합성 데이터 CUD 구현 시 ×, ー 데이터 관리 필요
const suitableCheck = useCallback((value: string) => {
if (value === '×') {
return (
<div className="compliance-icon">
<Image src={'/assets/images/sub/compliance_x_icon.svg'} width={22} height={22} alt=""></Image>
</div>
)
} else if (value === 'ー') {
return (
<div className="compliance-icon">
<Image src={'/assets/images/sub/compliance_quest_icon.svg'} width={22} height={22} alt=""></Image>
</div>
)
} else {
return (
<div className="compliance-icon">
<Image src={'/assets/images/sub/compliance_check_icon.svg'} width={22} height={22} alt=""></Image>
</div>
)
}
}, [])
// 메모이제이션된 아이템 렌더링
const renderItem = useCallback(
(item: Suitable) => {
const isSelected = isItemSelected(item.id)
const isOpen = openItems.has(item.id)
return (
<div className={`compliance-check-bx ${isOpen ? 'act' : ''}`} key={item.id}>
<div className="check-name-wrap">
<div className="check-form-box ">
<input type="checkbox" id={`ch${item.id}`} checked={isSelected} onChange={() => handleItemClick(item.id)} />
<label htmlFor={`ch${item.id}`}>{item.productName}</label>
</div>
<div className="check-name-btn">
<button className="bx-btn" onClick={() => toggleItemOpen(item.id)}></button>
</div>
</div>
<ul className="reference-list check">
{toSuitableDetail(item.detail).map((subItem: SuitableDetail) => (
<li className="reference-item" key={subItem.id}>
<div className="check-item-wrap">
<div className="check-form-box light">
<input type="checkbox" id={`ch${subItem.id}`} />
<label htmlFor={`ch${subItem.id}`}>{toCodeName(SUITABLE_HEAD_CODE.TRESTLE_MFPC_CD, subItem.trestleMfpcCd)}</label>
</div>
<div className="compliance-icon-wrap">
{suitableCheck(subItem.trestleManufacturerProductName)}
{subItem.memo && (
<div className="compliance-icon">
<Image src={'/assets/images/sub/compliance_tip_icon.svg'} width={22} height={22} alt=""></Image>
</div>
)}
</div>
</div>
</li>
))}
</ul>
</div>
)
},
[isItemSelected, openItems, handleItemClick, toggleItemOpen, suitableCheck, toCodeName, toSuitableDetail],
)
// 메모이제이션된 아이템 리스트
const renderedItems = useMemo(() => {
return visibleItems.map(renderItem)
}, [visibleItems, renderItem])
if (isSearchLoading) {
return <div>Loading...</div>
}
if (!suitableSearchResults?.length) {
return <SuitableNoData />
}
return (
<>
{renderedItems}
<div ref={observerTarget} className="loading-indicator">
{isLoadingMore && <div className="loading-more"> ...</div>}
</div>
<SuitableButton />
</>
)
}

View File

@ -0,0 +1,118 @@
'use client'
import Image from 'next/image'
import { useEffect, useState } from 'react'
import SuitableListRaw from './SuitableListRaw'
import { useSuitableRaw } from '@/hooks/useSuitableRaw'
import { useSuitableStore } from '@/store/useSuitableStore'
import type { CommCode } from '@/types/CommCode'
import { SUITABLE_HEAD_CODE } from '@/types/Suitable'
export default function SuitableRaw() {
const [reference, setReference] = useState(true)
const { getSuitableCommCode, refetchBySearch } = useSuitableRaw()
const { suitableCommCode, selectedCategory, setSelectedCategory, searchValue, setSearchValue, setIsSearch, clearSelectedItems } = useSuitableStore()
const handleInputSearch = async () => {
if (!searchValue.trim()) {
alert('屋根材の製品名を入力してください。')
return
}
setIsSearch(true)
refetchBySearch()
}
const handleInputClear = () => {
setSearchValue('')
setIsSearch(false)
refetchBySearch()
}
useEffect(() => {
refetchBySearch()
}, [selectedCategory])
useEffect(() => {
getSuitableCommCode()
return () => {
setSelectedCategory('')
setSearchValue('')
clearSelectedItems()
}
}, [])
return (
<div className="border-frame">
<span>1 </span>
<div className="sale-form-bx">
<select className="select-form" name="" id="" value={selectedCategory || ''} onChange={(e) => setSelectedCategory(e.target.value)}>
<option value="">.</option>
{suitableCommCode.get(SUITABLE_HEAD_CODE.ROOF_MT_CD)?.map((category: CommCode, index: number) => (
<option key={index} value={category.code}>
{category.codeJp}
</option>
))}
</select>
</div>
<div className="sale-form-bx">
<div className="search-input">
<input
type="text"
className="search-frame"
placeholder="屋根材 製品名を入力してください."
value={searchValue}
onChange={(e) => setSearchValue(e.target.value)}
/>
{searchValue && <button className="del-icon" onClick={handleInputClear} />}
<button className="search-icon" onClick={handleInputSearch} />
</div>
</div>
<div className="compliance-check-wrap">
<div className={`compliance-check-bx ${reference ? 'act' : ''}`}>
<div className="check-name-wrap">
<div className="check-name"></div>
<div className="check-name-btn">
<button className="bx-btn" onClick={() => setReference(!reference)}></button>
</div>
</div>
<ul className="reference-list">
<li className="reference-item">
<div className="reference-item-bx">
<div className="compliance-icon">
<Image src={'/assets/images/sub/compliance_check_icon.svg'} width={22} height={22} alt=""></Image>
</div>
<span></span>
</div>
</li>
<li className="reference-item">
<div className="reference-item-bx">
<div className="compliance-icon">
<Image src={'/assets/images/sub/compliance_x_icon.svg'} width={22} height={22} alt=""></Image>
</div>
<span></span>
</div>
</li>
<li className="reference-item">
<div className="reference-item-bx">
<div className="compliance-icon">
<Image src={'/assets/images/sub/compliance_quest_icon.svg'} width={22} height={22} alt=""></Image>
</div>
<span></span>
</div>
</li>
<li className="reference-item">
<div className="reference-item-bx">
<div className="compliance-icon">
<Image src={'/assets/images/sub/compliance_tip_icon.svg'} width={22} height={22} alt=""></Image>
</div>
<span></span>
</div>
</li>
</ul>
</div>
<SuitableListRaw />
</div>
</div>
)
}

View File

@ -1,31 +1,74 @@
'use client' 'use client'
import { useSurveySaleTabState } from '@/store/surveySaleTabState' import { useSurveySaleTabState } from '@/store/surveySaleTabState'
import { usePathname, useRouter } from 'next/navigation' import { usePathname, useRouter, useSearchParams, useParams } from 'next/navigation'
import { useEffect } from 'react' import { useEffect } from 'react'
export default function NavTab() { export default function NavTab() {
const router = useRouter() const router = useRouter()
const pathname = usePathname() const pathname = usePathname()
if (pathname === '/survey-sale') { const searchParams = useSearchParams()
return null 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(() => { useEffect(() => {
return () => { return () => {
reset() 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 = () => { 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 = () => { 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 ( return (

View File

@ -1,10 +1,14 @@
'use client' 'use client'
import { useEffect } from 'react' import { useEffect, useState } from 'react'
import { useSurveySaleTabState } from '@/store/surveySaleTabState' import { useSurveySaleTabState } from '@/store/surveySaleTabState'
import { SurveyBasicRequest } from '@/types/Survey'
import { Mode } from 'fs'
export default function BasicForm() { export default function BasicForm(props: { basicInfo: SurveyBasicRequest; setBasicInfo: (basicInfo: SurveyBasicRequest) => void; mode: Mode }) {
const { basicInfo, setBasicInfo, mode } = props
const { setBasicInfoSelected } = useSurveySaleTabState() const { setBasicInfoSelected } = useSurveySaleTabState()
const [isFlip, setIsFlip] = useState<boolean>(true)
useEffect(() => { useEffect(() => {
setBasicInfoSelected() setBasicInfoSelected()
@ -12,84 +16,98 @@ export default function BasicForm() {
return ( return (
<> <>
<div className="sale-frame"> <div className={`sale-detail-toggle-bx ${isFlip ? 'act' : ''}`}>
<div className="data-form-wrap"> <div className="sale-detail-toggle-head" onClick={() => setIsFlip(!isFlip)}>
<div className="data-input-form-bx"> <div className="sale-detail-toggle-name"></div>
<div className="data-input-form-tit"></div> <div className="sale-detail-toggle-btn-wrap">
<input type="text" className="input-frame" defaultValue={'HG'} /> <button className="sale-detail-toggle-btn"></button>
</div>
<div className="data-input-form-bx">
<div className="data-input-form-tit"></div>
<input type="text" className="input-frame" defaultValue={'HWJ(T01)'} />
</div>
<div className="data-input-form-bx">
<div className="data-input-form-tit"></div>
<input type="text" className="input-frame" defaultValue={'施工点名表示'} />
</div> </div>
</div> </div>
</div> <div className="sale-detail-toggle-cont">
<div className="sale-frame">
<div className="data-form-wrap">
<div className="data-input-form-bx">
<div className="data-input-form-tit"></div>
<input
type="text"
className="input-frame"
readOnly={mode === 'READ'}
value={basicInfo?.representative ?? ''}
onChange={(e) => setBasicInfo({ ...basicInfo, representative: e.target.value })}
/>
</div>
<div className="data-input-form-bx">
<div className="data-input-form-tit"></div>
<input
type="text"
className="input-frame"
readOnly={mode === 'READ'}
value={basicInfo?.store ?? ''}
onChange={(e) => setBasicInfo({ ...basicInfo, store: e.target.value })}
/>
</div>
<div className="data-input-form-bx">
<div className="data-input-form-tit"></div>
<input
type="text"
className="input-frame"
readOnly={mode === 'READ'}
value={basicInfo?.constructionPoint ?? ''}
onChange={(e) => setBasicInfo({ ...basicInfo, constructionPoint: e.target.value })}
/>
</div>
</div>
</div>
<div className="sale-frame">
<div className="data-form-wrap">
<div className="data-input-form-bx">
<div className="data-input-form-tit">調</div>
{['CREATE', 'EDIT'].includes(mode as 'CREATE' | 'EDIT') ? (
<div className="date-input">
<button className="date-btn">
<i className="date-icon"></i>
</button>
<input type="date" className="date-frame" readOnly defaultValue={basicInfo?.investigationDate?.toString()} />
</div>
) : (
<input type="date" className="input-frame" disabled defaultValue={basicInfo?.investigationDate?.toString()} />
)}
</div>
<div className="data-input-form-bx">
{/* 건물명 */}
<div className="data-input-form-tit"></div>
<input type="text" className="input-frame" readOnly={mode === 'READ'} defaultValue={basicInfo?.buildingName ?? ''} />
</div>
<div className="data-input-form-bx">
{/* 고객명 */}
<div className="data-input-form-tit"></div>
<input type="text" className="input-frame" readOnly={mode === 'READ'} defaultValue={basicInfo?.customerName ?? ''} />
</div>
<div className="data-input-form-bx">
<div className="data-input-form-tit">便/</div>
<div className="form-flex">
{/* 우편번호 */}
<div className="form-bx">
<input type="text" className="input-frame" readOnly={mode === 'READ'} defaultValue={basicInfo?.postCode ?? ''} disabled />
</div>
{/* 도도부현 */}
<div className="form-bx">
<input type="text" className="input-frame" readOnly={mode === 'READ'} defaultValue={basicInfo?.address ?? ''} disabled />
</div>
</div>
{/* 주소 */}
<div className="form-btn">
<button className="btn-frame n-blue icon">
便<i className="btn-arr"></i>
</button>
</div>
</div>
<div className="sale-frame"> <div className="data-input-form-bx">
<div className="data-form-wrap"> <div className="data-input-form-tit">, </div>
<div className="data-input-form-bx"> <input type="text" className="input-frame" defaultValue={'浜松 浜松町'} readOnly={mode === 'READ'} />
<div className="data-input-form-tit">調</div>
<div className="date-input">
<button className="date-btn">
<i className="date-icon"></i>
</button>
<input type="text" className="date-frame" defaultValue={'2025.04.16'} />
</div>
</div>
<div className="data-input-form-bx">
<div className="data-input-form-tit"></div>
<input type="text" className="input-frame" defaultValue={'ギルドン'} />
</div>
<div className="data-input-form-bx">
<div className="data-input-form-tit"></div>
<input type="text" className="input-frame" defaultValue={'HWJ Building'} />
</div>
<div className="data-input-form-bx">
<div className="data-input-form-tit"></div>
<div className="form-flex">
<div className="form-bx">
<input type="text" className="input-frame" defaultValue={'1050013'} disabled />
</div>
<div className="form-bx">
<select className="select-form" name="" id="">
<option value=""></option>
<option value=""></option>
<option value=""></option>
<option value=""></option>
<option value=""></option>
</select>
</div> </div>
</div> </div>
<div className="form-btn">
<button className="btn-frame n-blue icon">
便<i className="btn-arr"></i>
</button>
</div>
</div>
<div className="data-input-form-bx">
<div className="data-input-form-tit">, </div>
<input type="text" className="input-frame" defaultValue={'浜松 浜松町'} />
</div>
</div>
<div className="btn-flex-wrap">
<div className="btn-bx">
<button className="btn-frame n-blue icon">
<i className="btn-arr"></i>
</button>
</div>
<div className="btn-bx">
<button className="btn-frame red icon">
<i className="btn-arr"></i>
</button>
</div>
<div className="btn-bx">
<button className="btn-frame n-blue icon">
<i className="btn-arr"></i>
</button>
</div> </div>
</div> </div>
</div> </div>

View File

@ -0,0 +1,81 @@
import { Mode, SurveyBasicRequest, SurveyDetailRequest } from '@/types/Survey'
export default function ButtonForm(props: { mode: Mode; setMode: (mode: Mode) => void; data: { basic: SurveyBasicRequest; roof: SurveyDetailRequest } }) {
const { mode, setMode } = props
return (
<>
{mode === 'CREATE' && (
<div className="sale-form-btn-wrap">
<div className="btn-flex-wrap">
<div className="btn-bx">
{/* 임시저장 */}
<button className="btn-frame n-blue icon" onClick={() => setMode('TEMP')}>
<i className="btn-arr"></i>
</button>
</div>
<div className="btn-bx">
{/* 저장 */}
<button className="btn-frame red icon">
<i className="btn-arr"></i>
</button>
</div>
<div className="btn-bx">
{/* 목록 */}
<button className="btn-frame n-blue icon">
<i className="btn-arr"></i>
</button>
</div>
</div>
</div>
)}
{mode === 'TEMP' && (
<div className="sale-form-btn-wrap">
<div className="btn-flex-wrap">
<div className="btn-bx">
{/* 수정 */}
<button className="btn-frame n-blue icon" onClick={() => setMode('EDIT')}>
<i className="btn-arr"></i>
</button>
</div>
<div className="btn-bx">
{/* 삭제 */}
<button className="btn-frame n-blue icon">
<i className="btn-arr"></i>
</button>
</div>
</div>
</div>
)}
{mode === 'EDIT' && (
<div className="sale-form-btn-wrap">
<div className="btn-flex-wrap">
<div className="btn-bx">
{/* 목록 */}
<button className="btn-frame n-blue icon">
<i className="btn-arr"></i>
</button>
</div>
<div className="btn-bx">
{/* 제출 */}
<button className="btn-frame red icon">
<i className="btn-arr"></i>
</button>
</div>
<div className="btn-bx">
{/* 수정 */}
<button className="btn-frame n-blue icon" onClick={() => setMode('EDIT')}>
<i className="btn-arr"></i>
</button>
</div>
<div className="btn-bx">
{/* 삭제 */}
<button className="btn-frame n-blue icon">
<i className="btn-arr"></i>
</button>
</div>
</div>
</div>
)}
</>
)
}

View File

@ -1,9 +1,39 @@
'use client' '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() { 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 <div>Loading...</div>
}
return ( return (
<> <>
<div className="sale-frame"> <div className="sale-data-table-wrap">
<table className="sale-data-table"> <table className="sale-data-table">
<colgroup> <colgroup>
<col style={{ width: '80px' }} /> <col style={{ width: '80px' }} />
@ -12,19 +42,35 @@ export default function DataTable() {
<tbody> <tbody>
<tr> <tr>
<th></th> <th></th>
<td>0000000020</td> {isTemporary ? (
<td>
<span className="text-red-500"></span>
</td>
) : (
<td>{surveyDetail?.id}</td>
)}
</tr> </tr>
<tr> <tr>
<th></th> <th></th>
<td>2025.04.11</td> <td>{surveyDetail?.regDt ? new Date(surveyDetail.regDt).toLocaleString() : ''}</td>
</tr> </tr>
<tr> <tr>
<th></th> <th></th>
<td>2025.04.11 15:06:29</td> <td>{surveyDetail?.uptDt ? new Date(surveyDetail.uptDt).toLocaleString() : ''}</td>
</tr> </tr>
<tr> <tr>
<th></th> <th></th>
<td>2025.04.12 10:00:00 (INTERPLUG )</td> <td>
{surveyDetail?.submissionStatus && surveyDetail?.submissionDate ? (
<>
{/* TODO: 제출한 판매점 ID 추가 필요 */}
<div>{new Date(surveyDetail.submissionDate).toLocaleString()}</div>
<div>{surveyDetail.store}</div>
</>
) : (
'-'
)}
</td>
</tr> </tr>
<tr> <tr>
<th></th> <th></th>
@ -37,6 +83,7 @@ export default function DataTable() {
</tbody> </tbody>
</table> </table>
</div> </div>
<DetailForm surveyInfo={surveyDetail as SurveyBasicInfo} mode="READ" />
</> </>
) )
} }

View File

@ -1,62 +1,93 @@
'use client' 'use client'
export default function DetailForm() { 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 [mode, setMode] = useState<Mode>(props.mode ?? 'CREATE')
const [basicInfoData, setBasicInfoData] = useState<SurveyBasicRequest>(basicInfoForm)
const [roofInfoData, setRoofInfoData] = useState<SurveyDetailRequest>(roofInfoForm)
useEffect(() => {
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])
const data = {
basic: basicInfoData,
roof: roofInfoData,
}
const buttonFormProps = { mode, setMode, data }
return ( return (
<> <>
<div className="sale-frame"> <div className="sale-detail-toggle-wrap">
<div className="data-form-wrap"> {/* 기본정보 */}
<div className="data-input-form-bx"> <BasicForm basicInfo={basicInfoData} setBasicInfo={setBasicInfoData} mode={mode} />
<div className="data-input-form-tit"></div> {/* 전기/지붕정보 */}
<input type="text" className="input-frame" disabled defaultValue={'HG'} /> <RoofForm roofInfo={roofInfoData} setRoofInfo={setRoofInfoData} mode={mode} />
</div> <ButtonForm {...buttonFormProps} />
<div className="data-input-form-bx">
<div className="data-input-form-tit"></div>
<input type="text" className="input-frame" disabled defaultValue={'HWJ(T01)'} />
</div>
<div className="data-input-form-bx">
<div className="data-input-form-tit"></div>
<input type="text" className="input-frame" disabled defaultValue={'施工点名表示'} />
</div>
</div>
</div>
<div className="sale-frame">
<div className="data-form-wrap">
<div className="data-input-form-bx">
<div className="data-input-form-tit">調</div>
<input type="text" className="input-frame" disabled defaultValue={'2025/04/05'} />
</div>
<div className="data-input-form-bx">
<div className="data-input-form-tit"></div>
<input type="text" className="input-frame" disabled defaultValue={'ハンファジャパンビル'} />
</div>
<div className="data-input-form-bx">
<div className="data-input-form-tit"></div>
<input type="text" className="input-frame" disabled defaultValue={'Hong gi'} />
</div>
</div>
<div className="btn-flex-wrap">
<div className="btn-bx">
<button className="btn-frame n-blue icon">
<i className="btn-arr"></i>
</button>
</div>
<div className="btn-bx">
<button className="btn-frame red icon">
<i className="btn-arr"></i>
</button>
</div>
<div className="btn-bx">
<button className="btn-frame n-blue icon">
<i className="btn-arr"></i>
</button>
</div>
<div className="btn-bx">
<button className="btn-frame n-blue icon">
<i className="btn-arr"></i>
</button>
</div>
</div>
</div> </div>
</> </>
) )

View File

@ -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<Mode>('CREATE')
useEffect(() => {
if (id) {
setMode('EDIT')
}
}, [id])
return (
<>
<DetailForm mode={mode} surveyInfo={surveyDetail as SurveyBasicInfo} />
</>
)
}

View File

@ -0,0 +1,528 @@
import { useState } from 'react'
import { Mode, SurveyDetailInfo, SurveyDetailRequest } from '@/types/Survey'
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<SelectBoxKeys, { id: number; name: string }[]> = {
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<RadioEtcKeys, { id: number; label: string }[]> = {
houseStructure: [
{
id: 1,
label: '木製',
},
],
rafterMaterial: [
{
id: 1,
label: '木製',
},
{
id: 2,
label: '強制',
},
],
waterproofMaterial: [
{
id: 1,
label: 'アスファルト屋根94022kg以上',
},
],
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<boolean>(true)
return (
<div className={`sale-detail-toggle-bx ${isFlip ? 'act' : ''}`}>
<div className="sale-detail-toggle-head" onClick={() => setIsFlip(!isFlip)}>
<div className="sale-detail-toggle-name"> / </div>
<div className="sale-detail-toggle-btn-wrap">
<button className="sale-detail-toggle-btn"></button>
</div>
</div>
<div className="sale-detail-toggle-cont">
<div className="sale-frame">
{/* 전기 관계 */}
<div className="sale-roof-title"></div>
<div className="data-form-wrap">
<div className="data-input-form-bx">
{/* 전기 계약 용량 */}
<div className="data-input-form-tit"></div>
<div className="data-input mb5">
<input type="text" className="input-frame" value={roofInfo?.contractCapacity ?? ''} readOnly={mode === 'READ'} />
</div>
{mode === 'READ' && <input type="text" className="input-frame" defaultValue={'10'} readOnly={mode === 'READ'} />}
{mode !== 'READ' && (
<div className="data-input">
<select className="select-form" name="" id="">
<option value="">kVA</option>
<option value="">kVA</option>
<option value="">kVA</option>
<option value="">kVA</option>
<option value="">kVA</option>
</select>
</div>
)}
</div>
<div className="data-input-form-bx">
{/* 전기 소매 회사사 */}
<div className="data-input-form-tit"></div>
<input type="text" className="input-frame" value={roofInfo?.retailCompany ?? ''} readOnly={mode === 'READ'} />
</div>
<div className="data-input-form-bx">
{/* 전기 부대 설비 */}
<div className="data-input-form-tit">
<span></span>
</div>
<div className="data-check-wrap">
{/* <div className="check-form-box">
<input type="checkbox" id="ch01" readOnly={mode === 'READ'} />
<label htmlFor="ch01"></label>
</div> */}
{supplementary_facilities.map((item) => (
<div className="check-form-box" key={item.id}>
<input
type="checkbox"
id={`${item.id}`}
checked={makeNumArr(roofInfo?.supplementaryFacilities ?? '').includes(String(item.id))}
readOnly={mode === 'READ'}
/>
<label htmlFor={`${item.id}`}>{item.name}</label>
</div>
))}
<div className="check-form-box">
<input type="checkbox" id={`supplementaryFacilitiesEtc`} checked={roofInfo?.supplementaryFacilitiesEtc !== null} readOnly />
<label htmlFor={`supplementaryFacilitiesEtc`}> ()</label>
</div>
</div>
<div className="data-input">
<input type="text" className="input-frame" placeholder="-" readOnly value={roofInfo?.supplementaryFacilitiesEtc ?? ''} />
</div>
</div>
<div className="data-input-form-bx">
{/* 설치 희망 시스템 */}
{/* <div className="data-input-form-tit red-f"></div>
{mode === 'READ' && (
<div className="data-input">
<input type="text" className="input-frame" defaultValue={''} disabled />
</div>
)}
{mode !== 'READ' && (
<div className="data-input mb5">
<select className="select-form" name="" id="">
<option value=""></option>
<option value=""></option>
<option value=""></option>
<option value=""></option>
<option value=""></option>
</select>
</div>
)} */}
<div className="data-input-form-tit"></div>
<SelectedBox column="installationSystem" detailInfoData={roofInfo as SurveyDetailInfo} />
</div>
</div>
</div>
<div className="sale-frame">
{/* 지붕 관계 */}
<div className="sale-roof-title"></div>
<div className="data-form-wrap">
<div className="data-input-form-bx">
{/* 건축 연수 */}
<div className="data-input-form-tit red-f"></div>
<div className="data-input mb5">
{/* {mode === 'READ' && <input type="text" className="input-frame" defaultValue={''} disabled />}
{mode !== 'READ' && (
<select className="select-form" name="" id="">
<option value=""></option>
<option value=""></option>
<option value=""></option>
<option value=""></option>
<option value=""></option>
</select>
)} */}
<SelectedBox column="constructionYear" detailInfoData={roofInfo as SurveyDetailInfo} />
</div>
{/* <div className="data-input flex">
<input type="text" className="input-frame" defaultValue={''} disabled />
<span></span>
</div> */}
</div>
<div className="data-input-form-bx">
{/* 지붕재 */}
<div className="data-input-form-tit">
<span>2</span>
</div>
<div className="data-check-wrap">
{roof_material.map((item) => (
<div className="check-form-box" key={item.id}>
<input type="checkbox" id={`${item.id}`} checked={makeNumArr(roofInfo?.roofMaterial ?? '').includes(String(item.id))} readOnly />
<label htmlFor={`${item.id}`}>{item.name}</label>
</div>
))}
<div className="check-form-box">
<input type="checkbox" id={`roofMaterialEtc`} checked={roofInfo?.roofMaterialEtc !== null} readOnly />
<label htmlFor={`roofMaterialEtc`}> ()</label>
</div>
</div>
<div className="data-input">
<input type="text" className="input-frame" placeholder="-" readOnly value={roofInfo?.roofMaterialEtc ?? ''} />
</div>
</div>
<div className="data-input-form-bx">
{/* 지붕 모양 */}
<div className="data-input-form-tit"></div>
<div className="data-input mb5">
{/* {mode === 'READ' && <input type="text" className="input-frame" defaultValue={''} disabled />}
{mode !== 'READ' && (
<select className="select-form" name="" id="">
<option value=""></option>
<option value=""></option>
<option value=""></option>
<option value=""></option>
<option value=""></option>
</select>
)} */}
<SelectedBox column="roofShape" detailInfoData={roofInfo as SurveyDetailInfo} />
</div>
<div className="data-input">
<input type="text" className="input-frame" defaultValue={''} disabled />
</div>
</div>
<div className="data-input-form-bx">
{/* 지붕 경사도도 */}
<div className="data-input-form-tit"></div>
<div className="data-input flex">
<input type="text" className="input-frame" value={roofInfo?.roofSlope ?? ''} readOnly={mode === 'READ'} />
<span></span>
</div>
</div>
<div className="data-input-form-bx">
{/* 주택구조조 */}
<div className="data-input-form-tit"></div>
<RadioSelected column="houseStructure" detailInfoData={roofInfo as SurveyDetailInfo} />
</div>
<div className="data-input-form-bx">
{/* 서까래 재질 */}
<div className="data-input-form-tit"></div>
<RadioSelected column="rafterMaterial" detailInfoData={roofInfo as SurveyDetailInfo} />
</div>
<div className="data-input-form-bx">
{/* 서까래 크기 */}
<div className="data-input-form-tit red-f"></div>
<div className="data-input mb5">
<SelectedBox column="rafterSize" detailInfoData={roofInfo as SurveyDetailInfo} />
</div>
</div>
<div className="data-input-form-bx">
{/* 서까래 피치 */}
<div className="data-input-form-tit red-f"></div>
<div className="data-input mb5">
<SelectedBox column="rafterPitch" detailInfoData={roofInfo as SurveyDetailInfo} />
</div>
</div>
<div className="data-input-form-bx">
{/* 서까래 방향 */}
<div className="data-input-form-tit red-f"></div>
<div className="data-check-wrap mb0">
<RadioSelected column="rafterDirection" detailInfoData={roofInfo as SurveyDetailInfo} />
</div>
</div>
<div className="data-input-form-bx">
{/* 노지판 종류류 */}
<div className="data-input-form-tit"></div>
<div className="data-input mb5">
<SelectedBox column="openFieldPlateKind" detailInfoData={roofInfo as SurveyDetailInfo} />
</div>
</div>
<div className="data-input-form-bx">
{/* 노지판 두께 */}
<div className="data-input-form-tit">
<span>, . </span>
</div>
<div className="data-input flex">
<input type="text" className="input-frame" value={roofInfo?.openFieldPlateThickness ?? ''} readOnly={mode === 'READ'} />
<span>mm</span>
</div>
</div>
<div className="data-input-form-bx">
{/* 누수 흔적 */}
<div className="data-input-form-tit "></div>
<div className="data-check-wrap mb0">
<RadioSelected column="leakTrace" detailInfoData={roofInfo as SurveyDetailInfo} />
</div>
</div>
<div className="data-input-form-bx">
{/* 방수재 종류 */}
<div className="data-input-form-tit red-f"></div>
<RadioSelected column="waterproofMaterial" detailInfoData={roofInfo as SurveyDetailInfo} />
</div>
<div className="data-input-form-bx">
{/* 단열재 유무 */}
<div className="data-input-form-tit red-f"></div>
<RadioSelected column="insulationPresence" detailInfoData={roofInfo as SurveyDetailInfo} />
</div>
<div className="data-input-form-bx">
{/* 지붕 구조의 순서 */}
<div className="data-input-form-tit red-f"></div>
<SelectedBox column="structureOrder" detailInfoData={roofInfo as SurveyDetailInfo} />
</div>
<div className="data-input-form-bx">
{/* 지붕 제품명 설치 가능 여부 확인 */}
<div className="data-input-form-tit"> </div>
<SelectedBox column="installationAvailability" detailInfoData={roofInfo as SurveyDetailInfo} />
</div>
<div className="data-input-form-bx">
{/* 메모 */}
<div className="data-input-form-tit"></div>
<div className="data-input">
<textarea
className="textarea-form"
name=""
id=""
placeholder="TextArea Filed"
value={roofInfo?.memo ?? ''}
readOnly={mode === 'READ'}
></textarea>
</div>
</div>
</div>
</div>
</div>
</div>
)
}
const SelectedBox = ({ column, detailInfoData }: { column: string; detailInfoData: SurveyDetailInfo }) => {
const selectedId = detailInfoData?.[column as keyof SurveyDetailInfo]
const etcValue = detailInfoData?.[`${column}Etc` as keyof SurveyDetailInfo]
return (
<>
<select className="select-form mb10" name={column} id={column} disabled value={selectedId ? 'selected' : etcValue ? 'etc' : ''}>
<option value="">-</option>
<option value="etc"> ()</option>
<option value="selected">{selectBoxOptions[column as keyof typeof selectBoxOptions][Number(selectedId)]?.name}</option>
</select>
{etcValue && <input type="text" className="input-frame" readOnly value={etcValue.toString()} />}
</>
)
}
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) => (
<div className="radio-form-box mb10" key={item.id}>
<input type="radio" name={column} id={`${item.id}`} disabled checked={Number(selectedId) === item.id} />
<label htmlFor={`${item.id}`}>{item.label}</label>
</div>
))}
{column !== 'rafterDirection' && column !== 'leakTrace' && column !== 'insulationPresence' && (
<div className="radio-form-box mb10">
<input type="radio" name={column} id={`${column}Etc`} value="etc" disabled checked={etcChecked} />
<label htmlFor={`${column}Etc`}> ()</label>
</div>
)}
{etcChecked && (
<div className="data-input">
<input type="text" className="input-frame" placeholder="-" readOnly value={etcValue?.toString() ?? ''} />
</div>
)}
</>
)
}

View File

@ -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 (
<>
<div className="sale-frame">
<div className="sale-roof-title"></div>
<div className="data-form-wrap">
<div className="data-input-form-bx">
<div className="data-input-form-tit"></div>
<div className="data-input mb5">
<input type="text" className="input-frame" defaultValue={'10'} />
</div>
<div className="data-input">
<select className="select-form" name="" id="">
<option value="">kVA</option>
<option value="">kVA</option>
<option value="">kVA</option>
<option value="">kVA</option>
<option value="">kVA</option>
</select>
</div>
</div>
<div className="data-input-form-bx">
<div className="data-input-form-tit"></div>
<input type="text" className="input-frame" defaultValue={'HWJ Electric'} />
</div>
<div className="data-input-form-bx">
<div className="data-input-form-tit">
<span></span>
</div>
<div className="data-check-wrap">
<div className="check-form-box">
<input type="checkbox" id="ch01" />
<label htmlFor="ch01"></label>
</div>
<div className="check-form-box">
<input type="checkbox" id="ch02" />
<label htmlFor="ch02"></label>
</div>
<div className="check-form-box">
<input type="checkbox" id="ch03" />
<label htmlFor="ch03"></label>
</div>
<div className="check-form-box">
<input type="checkbox" id="ch04" />
<label htmlFor="ch04"></label>
</div>
<div className="check-form-box">
<input type="checkbox" id="ch05" />
<label htmlFor="ch05"> ()</label>
</div>
</div>
<div className="data-input">
<input type="text" className="input-frame" disabled defaultValue={''} />
</div>
</div>
<div className="data-input-form-bx">
<div className="data-input-form-tit red-f"></div>
<div className="data-input mb5">
<select className="select-form" name="" id="">
<option value=""></option>
<option value=""></option>
<option value=""></option>
<option value=""></option>
<option value=""></option>
</select>
</div>
<div className="data-input">
<input type="text" className="input-frame" defaultValue={''} disabled />
</div>
</div>
</div>
</div>
<div className="sale-frame">
<div className="sale-roof-title"></div>
<div className="data-form-wrap">
<div className="data-input-form-bx">
<div className="data-input-form-tit red-f"></div>
<div className="data-input mb5">
<select className="select-form" name="" id="">
<option value=""></option>
<option value=""></option>
<option value=""></option>
<option value=""></option>
<option value=""></option>
</select>
</div>
<div className="data-input flex">
<input type="text" className="input-frame" defaultValue={''} disabled />
<span></span>
</div>
</div>
<div className="data-input-form-bx">
<div className="data-input-form-tit">
<span>2</span>
</div>
<div className="data-check-wrap">
<div className="check-form-box">
<input type="checkbox" id="ch01" />
<label htmlFor="ch01"></label>
</div>
<div className="check-form-box">
<input type="checkbox" id="ch02" />
<label htmlFor="ch02"></label>
</div>
<div className="check-form-box">
<input type="checkbox" id="ch03" />
<label htmlFor="ch03"></label>
</div>
<div className="check-form-box">
<input type="checkbox" id="ch04" />
<label htmlFor="ch04"></label>
</div>
<div className="check-form-box">
<input type="checkbox" id="ch05" />
<label htmlFor="ch05"> ()</label>
</div>
</div>
<div className="data-input">
<input type="text" className="input-frame" disabled defaultValue={''} />
</div>
</div>
<div className="data-input-form-bx">
<div className="data-input-form-tit"></div>
<div className="data-input mb5">
<select className="select-form" name="" id="">
<option value=""></option>
<option value=""></option>
<option value=""></option>
<option value=""></option>
<option value=""></option>
</select>
</div>
<div className="data-input">
<input type="text" className="input-frame" defaultValue={''} disabled />
</div>
</div>
<div className="data-input-form-bx">
<div className="data-input-form-tit"></div>
<div className="data-input flex">
<input type="text" className="input-frame" defaultValue={'4'} />
<span></span>
</div>
</div>
<div className="data-input-form-bx">
<div className="data-input-form-tit"></div>
<div className="radio-form-box mb10">
<input type="radio" name="radio01" id="ra01" />
<label htmlFor="ra01"></label>
</div>
<div className="radio-form-box mb10">
<input type="radio" name="radio01" id="ra02" />
<label htmlFor="ra02"> ()</label>
</div>
<div className="data-input">
<input type="text" className="input-frame" disabled defaultValue={''} />
</div>
</div>
<div className="data-input-form-bx">
<div className="data-input-form-tit"></div>
<div className="data-check-wrap">
<div className="radio-form-box">
<input type="radio" name="radio02" id="ra03" />
<label htmlFor="ra03"></label>
</div>
<div className="radio-form-box">
<input type="radio" name="radio02" id="ra04" />
<label htmlFor="ra04"></label>
</div>
<div className="radio-form-box">
<input type="radio" name="radio02" id="ra05" />
<label htmlFor="ra05"> ()</label>
</div>
</div>
<div className="data-input">
<input type="text" className="input-frame" disabled defaultValue={''} />
</div>
</div>
<div className="data-input-form-bx">
<div className="data-input-form-tit red-f"></div>
<div className="data-input mb5">
<select className="select-form" name="" id="">
<option value="">35mm以上×48mm以上</option>
<option value="">35mm以上×48mm以上</option>
<option value="">35mm以上×48mm以上</option>
<option value="">35mm以上×48mm以上</option>
<option value="">35mm以上×48mm以上</option>
</select>
</div>
<div className="data-input">
<input type="text" className="input-frame" defaultValue={''} disabled />
</div>
</div>
<div className="data-input-form-bx">
<div className="data-input-form-tit red-f"></div>
<div className="data-input mb5">
<select className="select-form" name="" id="">
<option value="">455mm以下</option>
<option value="">455mm以下</option>
<option value="">455mm以下</option>
<option value="">455mm以下</option>
<option value="">455mm以下</option>
</select>
</div>
<div className="data-input">
<input type="text" className="input-frame" defaultValue={''} disabled />
</div>
</div>
<div className="data-input-form-bx">
<div className="data-input-form-tit red-f"></div>
<div className="data-check-wrap mb0">
<div className="radio-form-box">
<input type="radio" name="radio03" id="ra06" />
<label htmlFor="ra06"></label>
</div>
<div className="radio-form-box">
<input type="radio" name="radio03" id="ra07" />
<label htmlFor="ra07"></label>
</div>
</div>
</div>
<div className="data-input-form-bx">
<div className="data-input-form-tit"></div>
<div className="data-input mb5">
<select className="select-form" name="" id="">
<option value=""></option>
<option value=""></option>
<option value=""></option>
<option value=""></option>
<option value=""></option>
</select>
</div>
<div className="data-input">
<input type="text" className="input-frame" defaultValue={''} disabled />
</div>
</div>
<div className="data-input-form-bx">
<div className="data-input-form-tit">
<span>, . </span>
</div>
<div className="data-input flex">
<input type="text" className="input-frame" defaultValue={'150'} />
<span>mm</span>
</div>
</div>
<div className="data-input-form-bx">
<div className="data-input-form-tit "></div>
<div className="data-check-wrap mb0">
<div className="radio-form-box">
<input type="radio" name="radio04" id="ra08" />
<label htmlFor="ra08"></label>
</div>
<div className="radio-form-box">
<input type="radio" name="radio04" id="ra09" />
<label htmlFor="ra09"></label>
</div>
</div>
</div>
<div className="data-input-form-bx">
<div className="data-input-form-tit red-f"></div>
<div className="radio-form-box mb10">
<input type="radio" name="radio05" id="ra10" />
<label htmlFor="ra10">94022kg以上</label>
</div>
<div className="radio-form-box mb10">
<input type="radio" name="radio05" id="ra11" />
<label htmlFor="ra11"> ()</label>
</div>
<div className="data-input">
<input type="text" className="input-frame" disabled defaultValue={''} />
</div>
</div>
<div className="data-input-form-bx">
<div className="data-input-form-tit red-f"></div>
<div className="radio-form-box mb10">
<input type="radio" name="radio06" id="ra12" />
<label htmlFor="ra12"></label>
</div>
<div className="data-input mb10">
<input type="text" className="input-frame" defaultValue={''} />
</div>
<div className="radio-form-box">
<input type="radio" name="radio06" id="ra13" />
<label htmlFor="ra13"></label>
</div>
</div>
<div className="data-input-form-bx">
<div className="data-input-form-tit red-f"></div>
<div className="data-input mb5">
<select className="select-form" name="" id="">
<option value="">///</option>
<option value="">///</option>
<option value="">///</option>
<option value="">///</option>
<option value="">///</option>
</select>
</div>
<div className="data-input">
<input type="text" className="input-frame" defaultValue={''} disabled />
</div>
</div>
<div className="data-input-form-bx">
<div className="data-input-form-tit"> </div>
<div className="data-input mb5">
<select className="select-form" name="" id="">
<option value=""></option>
<option value=""></option>
<option value=""></option>
<option value=""></option>
<option value=""></option>
</select>
</div>
<div className="data-input">
<input type="text" className="input-frame" defaultValue={'高島'} />
</div>
</div>
<div className="data-input-form-bx">
<div className="data-input-form-tit"></div>
<div className="data-input mb5">
<select className="select-form" name="" id="">
<option value=""></option>
<option value=""></option>
<option value=""></option>
<option value=""></option>
<option value=""></option>
</select>
</div>
<div className="data-input">
<textarea
className="textarea-form"
name=""
id=""
defaultValue={'漏れの兆候があるため、正確な点検が必要です.'}
placeholder="TextArea Filed"
></textarea>
</div>
</div>
</div>
<div className="btn-flex-wrap">
<div className="btn-bx">
<button className="btn-frame n-blue icon">
<i className="btn-arr"></i>
</button>
</div>
<div className="btn-bx">
<button className="btn-frame red icon">
<i className="btn-arr"></i>
</button>
</div>
<div className="btn-bx">
<button className="btn-frame n-blue icon">
<i className="btn-arr"></i>
</button>
</div>
</div>
</div>
</>
)
}

View File

@ -1,33 +1,82 @@
'use client' '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() { export default function ListTable() {
const router = useRouter()
const { surveyList, isLoadingSurveyList } = useServey()
const { offset, setOffset } = useSurveyFilterStore()
const [heldSurveyList, setHeldSurveyList] = useState<SurveyBasicInfo[]>([])
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 ( return (
<> <>
<div className="sale-frame"> <SearchForm memberRole={session?.role ?? ''} userId={session?.userId ?? ''} />
<ul className="sale-list-wrap"> {heldSurveyList.length > 0 ? (
{Array.from({ length: 4 }).map((_, idx) => ( <div className="sale-frame">
<li className="sale-list-item" key={idx}> <ul className="sale-list-wrap">
<div className="sale-item-bx"> {heldSurveyList.map((survey) => (
<div className="sale-item-date-bx"> <li className="sale-list-item cursor-pointer" key={survey.id} onClick={() => handleDetailClick(survey.id)}>
<div className="sale-item-num">0000000021</div> <div className="sale-item-bx">
<div className="sale-item-date">2025.04.22</div> <div className="sale-item-date-bx">
<div className="sale-item-num">{survey.id}</div>
<div className="sale-item-date">{survey.investigationDate}</div>
</div>
<div className="sale-item-tit">{survey.buildingName}</div>
<div className="sale-item-customer">{survey.customerName}</div>
<div className="sale-item-update-bx">
<div className="sale-item-name">{survey.representative}</div>
<div className="sale-item-update">{new Date(survey.uptDt).toLocaleString()}</div>
</div>
</div> </div>
<div className="sale-item-tit">Hanwha Building</div> </li>
<div className="sale-item-customer">Gil dong</div> ))}
<div className="sale-item-update-bx"> </ul>
<div className="sale-item-name">Hong Gildong</div> <div className="sale-edit-btn">
<div className="sale-item-update">2025.04.22 10:00:21</div> <LoadMoreButton hasMore={hasMore} onLoadMore={() => setOffset(offset + 10)} />
</div> </div>
</div>
</li>
))}
</ul>
<div className="sale-edit-btn">
<button className="btn-frame n-blue icon">
<i className="btn-edit"></i>
</button>
</div> </div>
</div> ) : (
<div>
<p></p>
</div>
)}
</> </>
) )
} }

View File

@ -1,41 +1,104 @@
'use client' '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 ( return (
<div className="sale-frame"> <div className="sale-frame">
<div className="sale-form-bx"> <div className="sale-form-bx">
<button className="btn-frame n-blue icon"> <button className="btn-frame n-blue icon" onClick={() => router.push('/survey-sale/regist')}>
<i className="btn-arr"></i> <i className="btn-arr"></i>
</button> </button>
</div> </div>
<div className="sale-form-bx"> <div className="sale-form-bx">
<select className="select-form" name="" id=""> <select
<option value=""></option> className="select-form"
<option value=""></option> name="search-option"
<option value=""></option> id="search-option"
<option value=""></option> value={option}
<option value=""></option> onChange={(e) => {
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 key={option.id} value={option.id}>
{option.label}
</option>
))}
</select> </select>
</div> </div>
<div className="sale-form-bx"> <div className="sale-form-bx">
<div className="search-input"> <div className="search-input">
<input type="text" className="search-frame" placeholder="タイトルを入力してください. (2文字以上)" /> <input
<button className="search-icon"></button> type="text"
className="search-frame"
value={searchKeyword}
placeholder="タイトルを入力してください. (2文字以上)"
onChange={(e) => {
setSearchKeyword(e.target.value)
}}
onKeyDown={(e) => {
if (e.key === 'Enter') {
handleSearch()
}
}}
/>
<button className="search-icon" onClick={handleSearch}></button>
</div> </div>
</div> </div>
<div className="sale-form-bx"> <div className="sale-form-bx">
<div className="check-form-box"> <div className="check-form-box">
<input type="checkbox" id="ch01" /> <input
type="checkbox"
id="ch01"
checked={isMySurvey === userId}
onChange={() => {
setIsMySurvey(isMySurvey === userId ? null : userId)
// onItemsInit()
}}
/>
<label htmlFor="ch01"></label> <label htmlFor="ch01"></label>
</div> </div>
</div> </div>
<div className="sale-form-bx"> <div className="sale-form-bx">
<select className="select-form" name="" id=""> <select
<option value=""></option> className="select-form"
<option value=""></option> name="sort-option"
<option value=""></option> id="sort-option"
<option value=""></option> value={sort}
<option value=""></option> onChange={(e) => {
setSort(e.target.value as 'created' | 'updated')
// onItemsInit()
}}
>
<option value="created"></option>
<option value="updated"></option>
</select> </select>
</div> </div>
</div> </div>

View File

@ -1,7 +1,6 @@
'use client' 'use client'
import { useRouter } from 'next/navigation' import { useRouter } from 'next/navigation'
export default function Main() { export default function Main() {
const router = useRouter() const router = useRouter()

View File

@ -5,9 +5,16 @@ import { usePathname } from 'next/navigation'
export default function FloatBtn() { export default function FloatBtn() {
const pathname = usePathname() const pathname = usePathname()
const scrollToTop = () => {
window.scrollTo({
top: 0,
behavior: 'smooth',
})
}
if (pathname === '/login' || pathname === '/') { if (pathname === '/login' || pathname === '/') {
return null return null
} }
return <button className="top-btn"></button> return <button className="top-btn" onClick={scrollToTop}></button>
} }

View File

@ -1,8 +1,17 @@
'use client'
import Link from 'next/link'
export default function Footer() { export default function Footer() {
return ( return (
<> <>
<footer> <footer>
<div className="footer-inner">COPYRIGHT©2025 Hanwha Japan All Rights Reserved</div> <div className="footer-inner">
COPYRIGHT©2025 Hanwha Japan All Rights Reserved{' '}
<span>
<Link href="/pdf">PDF</Link>
</span>
</div>
</footer> </footer>
</> </>
) )

View File

@ -1,23 +1,20 @@
import { useQuery } from '@tanstack/react-query' import { useQuery } from '@tanstack/react-query'
import { axiosInstance } from '@/libs/axios' import { axiosInstance, transformObjectKeys } from '@/libs/axios'
import { useSuitableStore } from '@/store/useSuitableStore' import { useSuitableStore } from '@/store/useSuitableStore'
import { useCommCode } from './useCommCode' import { useCommCode } from './useCommCode'
import { SUITABLE_HEAD_CODE, type SuitableData, type SuitableMain, type SuitableDetail } from '@/types/Suitable' import { SUITABLE_HEAD_CODE, type SuitableDetailGroup, type SuitableMain, type Suitable, type SuitableDetail } from '@/types/Suitable'
export function useSuitable() { export function useSuitable() {
const { getCommCode } = useCommCode() const { getCommCode } = useCommCode()
const { selectedCategory, searchValue, suitableCommCode, setSuitableCommCode, isSearch } = useSuitableStore() const { selectedCategory, searchValue, suitableCommCode, setSuitableCommCode, isSearch } = useSuitableStore()
const getSuitables = async (): Promise<SuitableData> => { const getSuitables = async (): Promise<Suitable> => {
try { try {
const response = await axiosInstance(null).get<SuitableData>('/api/suitable/list') const response = await axiosInstance(null).get<Suitable>('/api/suitable/list')
return response.data return response.data
} catch (error) { } catch (error) {
console.error('지붕재 데이터 로드 실패:', error) console.error('지붕재 데이터 로드 실패:', error)
return { return { suitable: [], detail: [] }
suitable: [],
suitableDetail: [],
}
} }
} }
@ -42,10 +39,27 @@ export function useSuitable() {
const toCodeName = (headCode: string, code: string): string => { const toCodeName = (headCode: string, code: string): string => {
const commCode = suitableCommCode.get(headCode) const commCode = suitableCommCode.get(headCode)
return commCode?.find((item) => item.CODE === code)?.CODE_JP || '' return commCode?.find((item) => item.code === code)?.codeJp || ''
} }
const { data: suitableList, isLoading: isInitialLoading } = useQuery<SuitableData>({ const toSuitableDetail = (mainId: number): SuitableDetail[] => {
try {
const suitableDetailString = suitableList?.detail.find((item) => item.mainId === mainId)?.detail
if (!suitableDetailString) {
return []
}
const suitableDetailArray = transformObjectKeys(JSON.parse(suitableDetailString)) as SuitableDetail[]
if (!Array.isArray(suitableDetailArray)) {
throw new Error('suitableDetailArray is not an array')
}
return suitableDetailArray
} catch (error) {
console.error('지붕재 데이터 파싱 실패:', error)
return []
}
}
const { data: suitableList, isLoading: isInitialLoading } = useQuery<Suitable>({
queryKey: ['suitables', 'list'], queryKey: ['suitables', 'list'],
queryFn: async () => await getSuitables(), queryFn: async () => await getSuitables(),
staleTime: 1000 * 60 * 10, // 10분 staleTime: 1000 * 60 * 10, // 10분
@ -56,25 +70,23 @@ export function useSuitable() {
data: suitableSearchResults, data: suitableSearchResults,
refetch: refetchBySearch, refetch: refetchBySearch,
isLoading: isSearchLoading, isLoading: isSearchLoading,
} = useQuery<SuitableData>({ } = useQuery<Suitable>({
queryKey: ['suitables', 'search', selectedCategory, searchValue], queryKey: ['suitables', 'search', selectedCategory, isSearch],
queryFn: async () => { queryFn: async () => {
if (!isSearch && !selectedCategory) { if (!isSearch && !selectedCategory) {
return suitableList ?? (await getSuitables()) // 검색 상태가 아니면 초기 데이터 반환 임시처리 // 검색 상태가 아니면 초기 데이터 반환 임시처리
return isInitialLoading ? await getSuitables() : suitableList ?? { suitable: [], detail: [] }
} else { } else {
const suitable = suitableList?.suitable.filter((item: SuitableMain) => { const filteredSuitable = suitableList?.suitable.filter((item: SuitableMain) => {
const categoryMatch = !selectedCategory || item.ROOF_MT_CD === selectedCategory const categoryMatch = !selectedCategory || item.roofMtCd === selectedCategory
const searchMatch = !searchValue || item.PRODUCT_NAME.includes(searchValue) const searchMatch = !searchValue || item.productName.includes(searchValue)
return categoryMatch && searchMatch return categoryMatch && searchMatch
}) }) ?? []
const mainIds = suitable?.map((item: SuitableMain) => item.ID) const mainIds = filteredSuitable.map((item: SuitableMain) => item.id)
const suitableDetail = suitableList?.suitableDetail.filter((item: SuitableDetail) => { const filteredDetail = suitableList?.detail.filter((item: SuitableDetailGroup) => {
return mainIds?.includes(item.MAIN_ID) return mainIds.includes(item.mainId)
}) }) ?? []
return { return { suitable: filteredSuitable, detail: filteredDetail }
suitable: suitable ?? [],
suitableDetail: suitableDetail ?? [],
}
} }
}, },
staleTime: 1000 * 60 * 10, staleTime: 1000 * 60 * 10,
@ -82,26 +94,14 @@ export function useSuitable() {
enabled: true, enabled: true,
}) })
const filterSuitableDetail = (mainId: number): SuitableDetail[] | undefined => {
const result: SuitableDetail[] = []
for (const subItem of suitableSearchResults?.suitableDetail ?? []) {
if (subItem.MAIN_ID > mainId) break
if (subItem.MAIN_ID === mainId) {
result.push(subItem)
}
}
return result
}
return { return {
getSuitables, getSuitables,
getSuitableCommCode, getSuitableCommCode,
toCodeName, toCodeName,
toSuitableDetail,
suitableList, suitableList,
isInitialLoading,
suitableSearchResults, suitableSearchResults,
refetchBySearch, refetchBySearch,
isSearchLoading, isSearchLoading,
filterSuitableDetail,
} }
} }

109
src/hooks/useSuitableRaw.ts Normal file
View File

@ -0,0 +1,109 @@
import { useQuery } from '@tanstack/react-query'
import { axiosInstance, transformObjectKeys } from '@/libs/axios'
import { useSuitableStore } from '@/store/useSuitableStore'
import { useCommCode } from './useCommCode'
import { SUITABLE_HEAD_CODE, type SuitableDetail } from '@/types/Suitable'
export type Suitable = {
id: number
productName: string
manuFtCd: string
roofMtCd: string
roofShCd: string
detail: string
}
export function useSuitableRaw() {
const { getCommCode } = useCommCode()
const { selectedCategory, searchValue, suitableCommCode, setSuitableCommCode, isSearch } = useSuitableStore()
const getSuitables = async (): Promise<Suitable[]> => {
try {
const response = await axiosInstance(null).get<Suitable[]>('/api/suitable/list/test')
return response.data
} catch (error) {
console.error('지붕재 데이터 로드 실패:', error)
return []
}
}
// const updateSearchResults = async (selectedCategory: string | undefined, searchValue: string | undefined): Promise<SuitableData[]> => {
// try {
// const response = await axiosInstance(null).get<SuitableData[]>('/api/suitable/list', { params: { selectedCategory, searchValue } })
// return response.data
// } catch (error) {
// console.error('지붕재 데이터 검색 실패:', error)
// return []
// }
// }
const getSuitableCommCode = () => {
const headCodes = Object.values(SUITABLE_HEAD_CODE) as SUITABLE_HEAD_CODE[]
for (const code of headCodes) {
getCommCode(code).then((res) => {
setSuitableCommCode(code, res)
})
}
}
const toCodeName = (headCode: string, code: string): string => {
const commCode = suitableCommCode.get(headCode)
return commCode?.find((item) => item.code === code)?.codeJp || ''
}
const toSuitableDetail = (suitableDetailString: string): SuitableDetail[] => {
try {
const suitableDetailArray = transformObjectKeys(JSON.parse(suitableDetailString)) as SuitableDetail[]
if (!Array.isArray(suitableDetailArray)) {
throw new Error('suitableDetailArray is not an array')
}
return suitableDetailArray
} catch (error) {
console.error('지붕재 데이터 파싱 실패:', error)
return []
}
}
const { data: suitableList, isLoading: isInitialLoading } = useQuery<Suitable[]>({
queryKey: ['suitables', 'list'],
queryFn: async () => await getSuitables(),
staleTime: 1000 * 60 * 10, // 10분
gcTime: 1000 * 60 * 10, // 10분
})
const {
data: suitableSearchResults,
refetch: refetchBySearch,
isLoading: isSearchLoading,
// } = useQuery<SuitableData>({
} = useQuery<Suitable[]>({
queryKey: ['suitables', 'search', selectedCategory, isSearch],
queryFn: async () => {
if (!isSearch && !selectedCategory) {
return isInitialLoading ? await getSuitables() : suitableList ?? [] // 검색 상태가 아니면 초기 데이터 반환 임시처리
} else {
return (
suitableList?.filter((item: Suitable) => {
const categoryMatch = !selectedCategory || item.roofMtCd === selectedCategory
const searchMatch = !searchValue || item.productName.includes(searchValue)
return categoryMatch && searchMatch
}) ?? []
)
}
},
staleTime: 1000 * 60 * 10,
gcTime: 1000 * 60 * 10,
enabled: true,
})
return {
getSuitables,
getSuitableCommCode,
toCodeName,
toSuitableDetail,
suitableList,
suitableSearchResults,
refetchBySearch,
isSearchLoading,
}
}

232
src/hooks/useSurvey.ts Normal file
View File

@ -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<number>
createSurveyDetail: (params: { surveyId: number; surveyDetail: SurveyDetailCoverRequest }) => void
updateSurvey: (survey: SurveyRegistRequest) => void
deleteSurvey: () => Promise<boolean>
submitSurvey: () => void
validateSurveyDetail: (surveyDetail: SurveyDetailRequest) => string
getZipCode: (zipCode: string) => Promise<ZipCode[] | null>
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<SurveyBasicInfo>(`/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<SurveyBasicInfo>('/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<SurveyRegistRequest>(`/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<boolean>(`/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<SurveyDetailInfo>(`/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<boolean>(`/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<ZipCode[] | null> => {
try {
const { data } = await axiosInstance(null).get<ZipCodeResponse>(
`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,
}
}

View File

@ -1,38 +1,61 @@
import axios from 'axios' import axios from 'axios'
import { tracking } from './tracking'
export const axiosInstance = (url: string | null | undefined) => { export const axiosInstance = (url: string | null | undefined) => {
const baseURL = url || process.env.NEXT_PUBLIC_API_URL const baseURL = url || process.env.NEXT_PUBLIC_API_URL
const instance = axios.create({
return axios.create({
baseURL, baseURL,
headers: { headers: {
Accept: 'application/json', Accept: 'application/json',
}, },
}) })
instance.interceptors.request.use(
(config) => {
console.log('🚀 ~ config:', config)
return config
},
(error) => {
return Promise.reject(error)
},
)
instance.interceptors.response.use(
(response) => {
response.data = transferResponse(response)
return response
},
(error) => {
// 에러 처리 로직
return Promise.reject(error)
},
)
return instance
} }
// Request interceptor // Request interceptor
axios.interceptors.request.use( // axios.interceptors.request.use(
(config) => { // (config) => {
// 여기에 토큰 추가 등의 공통 로직을 넣을 수 있습니다 // // 여기에 토큰 추가 등의 공통 로직을 넣을 수 있습니다
return config // return config
}, // },
(error) => { // (error) => {
return Promise.reject(error) // return Promise.reject(error)
}, // },
) // )
// Response interceptor // Response interceptor
axios.interceptors.response.use( // axios.interceptors.response.use(
(response) => transferResponse(response), // (response) => transferResponse(response),
(error) => { // (error) => {
// 에러 처리 로직 // // 에러 처리 로직
return Promise.reject(error) // return Promise.reject(error)
}, // },
) // )
// response데이터가 array, object에 따라 분기하여 키 변환 // response데이터가 array, object에 따라 분기하여 키 변환
const transferResponse = (response: any) => { export const transferResponse = (response: any) => {
if (!response.data) return response.data if (!response.data) return response.data
// 배열인 경우 각 객체의 키를 변환 // 배열인 경우 각 객체의 키를 변환
@ -45,7 +68,7 @@ const transferResponse = (response: any) => {
} }
// camel case object 반환 // camel case object 반환
const transformObjectKeys = (obj: any): any => { export const transformObjectKeys = (obj: any): any => {
if (Array.isArray(obj)) { if (Array.isArray(obj)) {
return obj.map(transformObjectKeys) return obj.map(transformObjectKeys)
} }
@ -60,7 +83,11 @@ const transformObjectKeys = (obj: any): any => {
return obj return obj
} }
// snake case to camel case
const snakeToCamel = (str: string): string => { export const camelToSnake = (str: string): string => {
return str.replace(/([-_][a-z])/g, (group) => group.toUpperCase().replace('-', '').replace('_', '')) 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('_', ''))
} }

10
src/libs/tracking.ts Normal file
View File

@ -0,0 +1,10 @@
import { axiosInstance } from './axios'
export const tracking = async (params: { url: string; data: string }) => {
const { url, data } = params
const result = await axiosInstance(null).post('/api/tracking', {
url,
data,
})
console.log('🚀 ~ result ~ result:', result)
}

19
src/store/addressStore.ts Normal file
View File

@ -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<AddressState>((set) => ({
addressData: null,
setAddressData: (address) => set({ addressData: address }),
resetAddressData: () => set({ addressData: null }),
}))

View File

@ -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<InquiryFilterState>((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 }),
}))

View File

@ -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<SurveyFilterState>((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 }),
}))

View File

@ -49,6 +49,14 @@
background-size: cover; background-size: cover;
margin-left: 12px; 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{ .btn-edit{
display: block; display: block;
width: 10px; width: 10px;

View File

@ -10,11 +10,11 @@ export interface SessionData {
storeNm: null storeNm: null
userId: null userId: null
category: null category: null
userNm: null userNm: null | string
userNmKana: null userNmKana: null | string
telNo: null telNo: null
fax: null fax: null
email: null email: null | string
lastEditUser: null lastEditUser: null
storeGubun: null storeGubun: null
pwCurr: null pwCurr: null

View File

@ -1,5 +1,5 @@
export type CommCode = { export type CommCode = {
HEAD_CD: string headCd: string
CODE: string code: string
CODE_JP: string codeJp: string
} }

View File

@ -9,32 +9,36 @@ export enum SUITABLE_HEAD_CODE {
TRESTLE_MFPC_CD = 'TRESTLE_MFPC_CD', TRESTLE_MFPC_CD = 'TRESTLE_MFPC_CD',
} }
export type SuitableIncludeDetail = {
ID: number
PRODUCT_NAME: string
MANU_FT_CD: string
ROOF_MT_CD: string
ROOF_SH_CD: string
MS_SUITABLE_DETAIL: SuitableDetail[]
}
export type SuitableData = {
suitable: SuitableMain[]
suitableDetail: SuitableDetail[]
}
export type SuitableMain = { export type SuitableMain = {
ID: number id: number
PRODUCT_NAME: string productName: string
MANU_FT_CD: string manuFtCd: string
ROOF_MT_CD: string roofMtCd: string
ROOF_SH_CD: string roofShCd: string
} }
export type SuitableDetail = { export type SuitableDetail = {
ID: number id: number
MAIN_ID: number mainId: number
TRESTLE_MFPC_CD: string trestleMfpcCd: string
TRESTLE_MANUFACTURER_PRODUCT_NAME: string trestleManufacturerProductName: string
MEMO: string memo: string
}
// export type Suitable = {
// id: number
// productName: string
// manuFtCd: string
// roofMtCd: string
// roofShCd: string
// detail: string
// }
export type SuitableDetailGroup = {
mainId: number
detail: string
}
export type Suitable = {
suitable: SuitableMain[]
detail: SuitableDetailGroup[]
} }

View File

@ -1,132 +1,132 @@
import { SEARCH_OPTIONS_ENUM, SEARCH_OPTIONS_PARTNERS_ENUM, SORT_OPTIONS_ENUM } from '@/store/surveyFilterStore'
export type SurveyBasicInfo = { export type SurveyBasicInfo = {
ID: number id: number
REPRESENTATIVE: string representative: string
STORE: string | null store: string | null
CONSTRUCTION_POINT: string | null constructionPoint: string | null
INVESTIGATION_DATE: string | null investigationDate: string | null
BUILDING_NAME: string | null buildingName: string | null
CUSTOMER_NAME: string | null customerName: string | null
POST_CODE: string | null postCode: string | null
ADDRESS: string | null address: string | null
ADDRESS_DETAIL: string | null addressDetail: string | null
SUBMISSION_STATUS: boolean submissionStatus: boolean
SUBMISSION_DATE: string | null submissionDate: string | null
DETAIL_INFO: SurveyDetailInfo | null detailInfo: SurveyDetailInfo | null
REG_DT: Date regDt: Date
UPT_DT: Date uptDt: Date
} }
export type SurveyDetailInfo = { export type SurveyDetailInfo = {
ID: number id: number
BASIC_INFO_ID: number basicInfoId: number
CONTRACT_CAPACITY: string | null contractCapacity: string | null
RETAIL_COMPANY: string | null retailCompany: string | null
SUPPLEMENTARY_FACILITIES: string | null // number 배열 supplementaryFacilities: string | null // number 배열
SUPPLEMENTARY_FACILITIES_ETC: string | null supplementaryFacilitiesEtc: string | null
INSTALLATION_SYSTEM: string | null installationSystem: string | null
INSTALLATION_SYSTEM_ETC: string | null installationSystemEtc: string | null
CONSTRUCTION_YEAR: string | null constructionYear: string | null
CONSTRUCTION_YEAR_ETC: string | null constructionYearEtc: string | null
ROOF_MATERIAL: string | null // number 배열 roofMaterial: string | null // number 배열
ROOF_MATERIAL_ETC: string | null roofMaterialEtc: string | null
ROOF_SHAPE: string | null roofShape: string | null
ROOF_SHAPE_ETC: string | null roofShapeEtc: string | null
ROOF_SLOPE: string | null roofSlope: string | null
HOUSE_STRUCTURE: string | null houseStructure: string | null
HOUSE_STRUCTURE_ETC: string | null houseStructureEtc: string | null
RAFTER_MATERIAL: string | null rafterMaterial: string | null
RAFTER_MATERIAL_ETC: string | null rafterMaterialEtc: string | null
RAFTER_SIZE: string | null rafterSize: string | null
RAFTER_SIZE_ETC: string | null rafterSizeEtc: string | null
RAFTER_PITCH: string | null rafterPitch: string | null
RAFTER_PITCH_ETC: string | null rafterPitchEtc: string | null
RAFTER_DIRECTION: string | null rafterDirection: string | null
OPEN_FIELD_PLATE_KIND: string | null openFieldPlateKind: string | null
OPEN_FIELD_PLATE_KIND_ETC: string | null openFieldPlateKindEtc: string | null
OPEN_FIELD_PLATE_THICKNESS: string | null openFieldPlateThickness: string | null
LEAK_TRACE: boolean | null leakTrace: boolean | null
WATERPROOF_MATERIAL: string | null waterproofMaterial: string | null
WATERPROOF_MATERIAL_ETC: string | null waterproofMaterialEtc: string | null
INSULATION_PRESENCE: string | null insulationPresence: string | null
INSULATION_PRESENCE_ETC: string | null insulationPresenceEtc: string | null
STRUCTURE_ORDER: string | null structureOrder: string | null
STRUCTURE_ORDER_ETC: string | null structureOrderEtc: string | null
INSTALLATION_AVAILABILITY: string | null installationAvailability: string | null
INSTALLATION_AVAILABILITY_ETC: string | null installationAvailabilityEtc: string | null
MEMO: string | null memo: string | null
REG_DT: Date regDt: Date
UPT_DT: Date uptDt: Date
} }
export type SurveyBasicRequest = { export type SurveyBasicRequest = {
REPRESENTATIVE: string representative: string
STORE: string | null store: string | null
CONSTRUCTION_POINT: string | null constructionPoint: string | null
INVESTIGATION_DATE: string | null investigationDate: string | null
BUILDING_NAME: string | null buildingName: string | null
CUSTOMER_NAME: string | null customerName: string | null
POST_CODE: string | null postCode: string | null
ADDRESS: string | null address: string | null
ADDRESS_DETAIL: string | null addressDetail: string | null
SUBMISSION_STATUS: boolean submissionStatus: boolean
SUBMISSION_DATE: string | null submissionDate: string | null
} }
export type SurveyDetailRequest = { export type SurveyDetailRequest = {
CONTRACT_CAPACITY: string | null contractCapacity: string | null
RETAIL_COMPANY: string | null retailCompany: string | null
SUPPLEMENTARY_FACILITIES: string | null // number 배열 supplementaryFacilities: string | null // number 배열
SUPPLEMENTARY_FACILITIES_ETC: string | null supplementaryFacilitiesEtc: string | null
INSTALLATION_SYSTEM: string | null installationSystem: string | null
INSTALLATION_SYSTEM_ETC: string | null installationSystemEtc: string | null
CONSTRUCTION_YEAR: string | null constructionYear: string | null
CONSTRUCTION_YEAR_ETC: string | null constructionYearEtc: string | null
ROOF_MATERIAL: string | null // number 배열 roofMaterial: string | null // number 배열
ROOF_MATERIAL_ETC: string | null roofMaterialEtc: string | null
ROOF_SHAPE: string | null roofShape: string | null
ROOF_SHAPE_ETC: string | null roofShapeEtc: string | null
ROOF_SLOPE: string | null roofSlope: string | null
HOUSE_STRUCTURE: string | null houseStructure: string | null
HOUSE_STRUCTURE_ETC: string | null houseStructureEtc: string | null
RAFTER_MATERIAL: string | null rafterMaterial: string | null
RAFTER_MATERIAL_ETC: string | null rafterMaterialEtc: string | null
RAFTER_SIZE: string | null rafterSize: string | null
RAFTER_SIZE_ETC: string | null rafterSizeEtc: string | null
RAFTER_PITCH: string | null rafterPitch: string | null
RAFTER_PITCH_ETC: string | null rafterPitchEtc: string | null
RAFTER_DIRECTION: string | null rafterDirection: string | null
OPEN_FIELD_PLATE_KIND: string | null openFieldPlateKind: string | null
OPEN_FIELD_PLATE_KIND_ETC: string | null openFieldPlateKindEtc: string | null
OPEN_FIELD_PLATE_THICKNESS: string | null openFieldPlateThickness: string | null
LEAK_TRACE: boolean | null leakTrace: boolean | null
WATERPROOF_MATERIAL: string | null waterproofMaterial: string | null
WATERPROOF_MATERIAL_ETC: string | null waterproofMaterialEtc: string | null
INSULATION_PRESENCE: string | null insulationPresence: string | null
INSULATION_PRESENCE_ETC: string | null insulationPresenceEtc: string | null
STRUCTURE_ORDER: string | null structureOrder: string | null
STRUCTURE_ORDER_ETC: string | null structureOrderEtc: string | null
INSTALLATION_AVAILABILITY: string | null installationAvailability: string | null
INSTALLATION_AVAILABILITY_ETC: string | null installationAvailabilityEtc: string | null
MEMO: string | null memo: string | null
} }
export type SurveyDetailCoverRequest = { export type SurveyDetailCoverRequest = {
DETAIL_INFO: SurveyDetailRequest detailInfo: SurveyDetailRequest
} }
export type SurveyRegistRequest = { export type SurveyRegistRequest = {
REPRESENTATIVE: string representative: string
STORE: string | null store: string | null
CONSTRUCTION_POINT: string | null constructionPoint: string | null
INVESTIGATION_DATE: string | null investigationDate: string | null
BUILDING_NAME: string | null buildingName: string | null
CUSTOMER_NAME: string | null customerName: string | null
POST_CODE: string | null postCode: string | null
ADDRESS: string | null address: string | null
ADDRESS_DETAIL: string | null addressDetail: string | null
SUBMISSION_STATUS: boolean submissionStatus: boolean
SUBMISSION_DATE: string | null submissionDate: string | null
DETAIL_INFO: SurveyDetailRequest | null detailInfo: SurveyDetailRequest | null
} }
export type Mode = 'CREATE' | 'EDIT' | 'READ' | 'TEMP' // 등록 | 수정 | 상세 | 임시저장

187
src/utils/common-utils.js Normal file
View File

@ -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 = {
'&amp;': '&',
'&lt;': '<',
'&gt;': '>',
'&quot;': '"',
'&#39;': "'",
}
/*
1. 한번 변환은 {&quot; 변환됨 : 에러 발생 => 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'
}