Compare commits

...

83 Commits

Author SHA1 Message Date
3d5cb308a8 docs: add description annotation at inquiry API files 2025-06-18 09:19:55 +09:00
de5b6d0c65 Merge branch 'dev' of https://git.hanasys.jp/qcast3/onsitesurvey into feature/inquiry 2025-06-17 18:24:20 +09:00
7cf3ac9a98 Merge pull request 'refactor: 지붕재적합성 에러처리 추가' (#72) from feature/suitable into dev
Reviewed-on: #72
2025-06-17 15:55:22 +09:00
fcf87c153e refactor: 지붕재적합성 에러처리 추가 2025-06-17 15:40:14 +09:00
54cd61c8b2 Merge pull request 'feature/survey' (#71) from feature/survey into dev
Reviewed-on: #71
2025-06-17 13:43:24 +09:00
17d306bb11 fix: change submit data set logic
- 제출 폼 데이터 삽입 안되는 오류 해결
- api error 메세지 설정
- api 응답 객체 변경
2025-06-17 13:20:18 +09:00
870e6ad02d Merge pull request 'feat: api logger 추가' (#69) from feature/log into dev
Reviewed-on: #69
2025-06-17 11:24:40 +09:00
e806358d0e fix: update route at useTitle
- useTitle 헤더 제목, url 변경
- 임시저장 로직 수정
2025-06-17 11:01:03 +09:00
bc73d36588 feat: api logger 실행모드 production 으로 한정 2025-06-17 10:52:16 +09:00
cd28667f3c feat: add route error handling for invalid URL access in DetailForm component 2025-06-16 17:59:03 +09:00
19a11783d6 fix: fix type error 2025-06-16 17:38:34 +09:00
5d5ba2e82a feat: add api logger to survey-sale api 2025-06-16 17:31:47 +09:00
a2e6c2343a Merge branch 'feature/log' of https://git.hanasys.jp/qcast3/onsitesurvey into feature/survey 2025-06-16 17:01:46 +09:00
b783ca92d7 feat: 기 개발된 api에 api logger 적용 2025-06-16 16:49:59 +09:00
c212ed0ad6 fix: api log wrapper 수정 2025-06-16 16:03:38 +09:00
70c5af70f5 Merge branch 'dev' of https://git.hanasys.jp/qcast3/onsitesurvey into feature/survey 2025-06-16 09:20:45 +09:00
ed8c6187d3 feat: api log wrapper 추가 2025-06-13 17:26:34 +09:00
7597700e7b feat: logger 날짜 분리 추가 2025-06-13 16:50:15 +09:00
8fc88f526d Merge branch 'dev' of https://git.hanasys.jp/qcast3/onsitesurvey into feature/log 2025-06-13 16:12:36 +09:00
nalpari
855dedce44 chore: update baseUrl for production environment
- Reverted baseUrl to the production server URL 'https://hanasysfield.jp' and commented out the local server IP address for production configuration.
- Ensured proper environment-specific settings for production deployment.
2025-06-13 14:13:00 +09:00
77895c220d Merge branch 'dev' of https://git.hanasys.jp/qcast3/onsitesurvey into feature/survey 2025-06-13 13:17:46 +09:00
042096c682 refactor: add an error alert conditional 2025-06-13 13:17:37 +09:00
298b563977 Merge branch 'dev' of https://git.hanasys.jp/qcast3/onsitesurvey into feature/log 2025-06-13 13:02:22 +09:00
36a06c226b Merge branch 'dev' of https://git.hanasys.jp/qcast3/onsitesurvey into feature/log 2025-06-13 13:01:28 +09:00
nalpari
96b5e39a58 chore: update baseUrl for production environment
- Commented out the previous production baseUrl and set a new baseUrl to point to the local server IP address for production configuration.
- Ensured consistency in environment-specific configurations.
2025-06-13 12:25:46 +09:00
nalpari
1af57d0965 chore: update API URLs for development and production environments
- Changed NEXT_PUBLIC_API_URL in .env.development and .env.production to point to the new development and production server URLs, respectively.
- Updated baseUrl in config.development.ts and config.production.ts to reflect the new server addresses for consistent environment configuration.
2025-06-12 18:09:08 +09:00
3eb5974414 feat: api logger 적용 2025-06-12 18:05:29 +09:00
a573d7ffb1 feat: api logger 추가 2025-06-12 18:03:24 +09:00
nalpari
420c481b84 chore: configure webpack for production optimization
- Added a webpack configuration to utilize terser-webpack-plugin for minifying JavaScript files in production builds, ensuring no comments are included in the output.
2025-06-12 17:36:45 +09:00
44d7a52790 chore: add production start script
- Introduced a new script in prod.startscript.js to execute the production server using pnpm for streamlined deployment.
2025-06-12 16:07:52 +09:00
99b37e3ac3 chore: update metadata for layout components
- Changed titles and descriptions in layout.tsx files for the main app, inquiry, suitable, and survey-sale sections to reflect the new project name "HANASYS現地調査" and its specific contexts.
2025-06-12 16:07:46 +09:00
f8d1cb54b6 chore: add development start script
- Introduced a new script in dev.startscript.js to execute the development server using pnpm for streamlined local development.
2025-06-12 15:33:28 +09:00
7c724f2430 chore: update development environment API URLs
- Changed NEXT_PUBLIC_API_URL in .env.development and baseUrl in config.development.ts to point to the new local server IP address for development purposes.
2025-06-12 15:20:25 +09:00
38ff8ce65f chore: update production database URL in .env.production
- Changed DATABASE_URL to point to the new SQL Server instance for production environment.
- Maintained existing connection settings for consistency across environments.
2025-06-12 15:06:34 +09:00
74865df3ba Merge remote-tracking branch 'origin/dev' into dev 2025-06-12 14:57:09 +09:00
15114d8da0 chore: update environment configuration for development, localhost, and production
- Added DATABASE_URL, DATABASE_CONNECTION_LIMIT, DATABASE_POOL_MIN, DATABASE_POOL_MAX, and SESSION_PASSWORD to .env, .env.development, .env.localhost, and .env.production files.
- Ensured consistent database connection settings across different environments for improved application performance.
2025-06-12 14:56:57 +09:00
907c92a546 Merge pull request 'feature/survey : 에러 해결' (#68) from feature/survey into dev
Reviewed-on: #68
2025-06-12 14:34:00 +09:00
5893cd6491 fix: fix build error by Specifying the type 2025-06-12 14:31:38 +09:00
0c68949fdd Merge branch 'dev' of https://git.hanasys.jp/qcast3/onsitesurvey into feature/survey 2025-06-12 14:27:31 +09:00
1f3aa2cc04 chore: update Prisma client configuration for improved environment handling and graceful shutdown
- Refactored Prisma client initialization to differentiate between development and production environments.
- Enhanced logging settings based on the environment.
- Implemented graceful shutdown for Prisma client on process termination signals.
2025-06-12 13:40:56 +09:00
cdfe211203 fix: fixed error for popup element
- 수정/작성 제출 시 팝업 올라오지 않는 문제 해결
2025-06-12 09:02:40 +09:00
d36b5c714f chore: db url appName추가, prisma 임시 원복 2025-06-11 17:53:44 +09:00
b97af6338e chore: update database connection settings and enhance Prisma client configuration
- Added connection timeout to DATABASE_URL in .env.
- Introduced DATABASE_CONNECTION_LIMIT, DATABASE_POOL_MIN, and DATABASE_POOL_MAX for connection pooling.
- Enhanced Prisma client initialization with logging and connection pool settings.
- Implemented graceful disconnection on process termination signals.
2025-06-11 17:36:15 +09:00
643895ccb2 chore: remove obsolete data.ts file containing extensive database entries 2025-06-11 10:44:26 +09:00
ada3057d36 fix: update EdgeProvider routing logic to handle session state more effectively 2025-06-11 10:12:46 +09:00
10787e7e60 fix: comment out handlePageEvent in EdgeProvider to prevent unintended page event tracking 2025-06-10 17:41:58 +09:00
d357355641 Merge pull request 'feature/survey' (#67) from feature/survey into dev
Reviewed-on: #67
2025-06-10 17:27:41 +09:00
f51b03cab7 docs: add annotations in SurveySale related Files
- Added detailed descriptions for search parameters and API functionalities in survey-sales routes.
- Improved documentation for inquiry-related hooks and types, enhancing clarity on their usage.
- Refactored comments for better readability and consistency across the codebase.
2025-06-10 17:13:35 +09:00
19ff53ae50 Merge pull request 'fix: 지붕재적합성 detail 데이터 없는 경우 방어처리 추가' (#66) from feature/suitable into dev
Reviewed-on: #66
2025-06-10 16:20:04 +09:00
25cbd92a55 fix: 지붕재적합성 detail 데이터 없는 경우 방어처리 추가 2025-06-10 15:42:38 +09:00
cc90977cd9 Merge branch 'dev' of https://git.hanasys.jp/qcast3/onsitesurvey into feature/survey 2025-06-10 15:32:42 +09:00
7db421c26a refactor: Refactoring code and add error handling
- 조사매물 조회 시 로그인 여부 확인 로직 서버 사이드로 이동
- 에러 핸들링 추가
- 조사매물 수정/작성 페이지 컴포넌트 리팩토링
- 조사매물 작성 후 제출 버튼 클릭 시 node 삽입 오류 해결
2025-06-10 15:32:27 +09:00
7fd1be2cc4 Merge pull request 'docs: 지붕재적합성 description 주석 추가' (#65) from feature/suitable into dev
Reviewed-on: #65
2025-06-10 13:11:38 +09:00
5f15e7360c docs: 지붕재적합성 description 추가 2025-06-10 11:34:53 +09:00
e3e6f10893 docs: 지붕재적합성 hooks description 추가 2025-06-10 11:34:02 +09:00
32329b1cb7 docs: 지붕재적합성 api description 추가 2025-06-09 17:47:15 +09:00
c99649d106 Merge branch 'feature/survey' of https://git.hanasys.jp/qcast3/onsitesurvey into feature/inquiry 2025-06-09 10:39:04 +09:00
d61cd9c64e Merge branch 'dev' of https://git.hanasys.jp/qcast3/onsitesurvey into feature/inquiry 2025-06-09 10:38:22 +09:00
763c9d37cf fix: fix data not loading error when navigating PDF pages without not login
- 로그인 하지 않고 pdf 링크로 이동 시 데이터 로드 되지 않는 문제 해결
- 로그인 하지 않았을 때 pdf 다운로드 이후 메인 페이지로 이동하도록 수정
2025-06-09 10:37:48 +09:00
f4a52f7752 Merge branch 'dev' of https://git.hanasys.jp/qcast3/onsitesurvey into feature/suitable 2025-06-09 10:26:36 +09:00
2aef601670 Merge pull request 'style: 지붕재 적합성 pdf pub 수정' (#64) from feature/suitable-pub into dev
Reviewed-on: #64
2025-06-09 10:21:35 +09:00
fc67b0fde7 Merge branch 'feature/suitable-pub' of https://git.hanasys.jp/qcast3/onsitesurvey into feature/suitable 2025-06-09 09:15:33 +09:00
a0beb8eca3 Merge branch 'dev' of https://git.hanasys.jp/qcast3/onsitesurvey into feature/survey 2025-06-09 09:11:30 +09:00
5cd9eb6ca2 remove: delete unused API files for auth, suitable, surveySales, and user 2025-06-05 18:16:22 +09:00
f7abbdc973 Merge branch 'dev' of https://git.hanasys.jp/qcast3/onsitesurvey into feature/inquiry 2025-06-05 18:07:24 +09:00
8c91bd605c Merge branch 'dev' of https://git.hanasys.jp/qcast3/onsitesurvey into feature/survey 2025-06-05 18:06:11 +09:00
f5022ab423 feat: get submit target store, representative user emails 2025-06-05 18:06:04 +09:00
2ba72f1142 fix: suitablepdf 수정 2025-06-05 18:04:53 +09:00
39056cf35f Merge pull request 'refactor: 구 지붕재 적합성 pdf 제거 및 suitable store 변수명 변경' (#63) from feature/suitable into dev
Reviewed-on: #63
2025-06-05 17:53:57 +09:00
762ce60e13 refactor: suitable store 변수명 변경 selectedCategory -> searchCategory 2025-06-05 17:47:08 +09:00
c62414e619 refactor: 지붕재 상세팝업 데이터 조회 수정
- 구 지붕재 적합성 pdf 페이지와 연계된 내용 제거 및 수정
- crypto-js 라이브러리 제거
2025-06-05 16:45:57 +09:00
a9ef91a430 Merge branch 'feature/submition-target' of https://git.hanasys.jp/qcast3/onsitesurvey into feature/survey 2025-06-05 16:38:02 +09:00
de42153955 chore: change inquiry api url 2025-06-05 16:27:12 +09:00
85344afd43 remove: 구 지붕재 적합성 pdf 페이지 삭제 2025-06-05 16:15:07 +09:00
1db17d6558 style: 지붕재 상세 팝업 하단 버튼 float 처리 2025-06-05 15:34:07 +09:00
a23c4cdfd9 Merge pull request 'fix: fix build error' (#62) from feature/survey into dev
Reviewed-on: #62
2025-06-05 13:49:48 +09:00
5feef03187 Merge pull request 'feat: 지붕재 데이터 조회 시 스피너 로딩처리 추가, 사이드바 지붕재적합성 페이지 이동 연결' (#61) from feature/suitable into dev
Reviewed-on: #61
2025-06-05 13:49:40 +09:00
f06b7cf0ac fix: fix build error 2025-06-05 13:48:20 +09:00
afb67c6b36 Merge branch 'dev' of https://git.hanasys.jp/qcast3/onsitesurvey into feature/suitable 2025-06-05 13:46:08 +09:00
9eea0bcc58 feat: 지붕재 데이터 조회 시 스피너 로딩처리 추가 2025-06-05 13:45:48 +09:00
b368443033 Merge pull request 'feature/inquiry : 파일 다운로드 오류 해결 및 사이드바 라우팅 변경' (#60) from feature/inquiry into dev
Reviewed-on: #60
2025-06-05 13:26:27 +09:00
3ff43475ac feat: 사이드바 지붕재적합성 페이지 이동 연결 2025-06-05 10:41:18 +09:00
69571e86b8 refactor: update Prisma schema to enhance data models
- Added BC_QM_BUILDER, BC_QM_TERMS, BC_QM_USER, IF_PERSON_OFFICE_MAPPING, MS_CUST_AGENCY_STOREID, MS_CUST_H, MS_CUST_PERSON, MS_CUST_STOREID, MS_CUST_STOREID_ADDITNL models to the Prisma schema for improved data structure.
- Reintroduced CONSTRUCTION_POINT_ID and SUBMISSION_TARGET_NM fields in SD_SURVEY_SALES_BASIC_INFO model for consistency and enhanced data representation.
2025-06-02 11:34:25 +09:00
80 changed files with 2983 additions and 78677 deletions

12
.env
View File

@ -1,12 +0,0 @@
# Environment variables declared in this file are automatically made available to Prisma.
# See the documentation for more detail: https://pris.ly/d/prisma-schema#accessing-environment-variables-from-the-schema
# Prisma supports the native connection string format for PostgreSQL, MySQL, SQLite, SQL Server, MongoDB and CockroachDB.
# See the documentation for all the connection string options: https://pris.ly/d/connection-strings
# DATABASE_URL="sqlserver://3team.devgrr.kr:1433;database=onsitesurvey;user=sa;password=1q2w3e4r!;encrypt=true;trustServerCertificate=true;"
DATABASE_URL="sqlserver://3team.devgrr.kr:1433;database=onsitesurvey;user=sa;password=1q2w3e4r!;encrypt=true;trustServerCertificate=true;"
# DATABASE_URL="mysql://root:root@localhost:3306/onsitesurvey"
# SESSION_PASSWORD="QWERASDFZXCV1234567890REWQFDSAVCXZ"
SESSION_PASSWORD="This application is for mobile field research"

View File

@ -1,15 +1,25 @@
NEXT_PUBLIC_RUN_MODE=development
DATABASE_URL="sqlserver://172.16.56.60:14331;database=hanwha_qcells_jp;user=qcells_jp;password=zbtpf2022!;encrypt=true;trustServerCertificate=true;applicationName=OnSiteSurvey"
DATABASE_CONNECTION_LIMIT=10
DATABASE_POOL_MIN=2
DATABASE_POOL_MAX=10
SESSION_PASSWORD="This application is for mobile field research"
# 모바일 디바이스로 로컬 서버 확인하려면 자신 IP 주소로 변경
# 다시 로컬에서 개발할때는 localhost로 변경
#route handler
NEXT_PUBLIC_API_URL=http://localhost:3000
# NEXT_PUBLIC_API_URL=http://172.16.56.60:3000
NEXT_PUBLIC_API_URL=https://dev.hanasysfield.jp
#qsp 로그인 api
NEXT_PUBLIC_QSP_API_URL=http://121.168.9.37:8080
# NEXT_PUBLIC_QSP_API_URL=https://jp-dev.qsalesplatform.com
#1:1문의 api
NEXT_PUBLIC_INQUIRY_API_URL=https://jp-dev.qsalesplatform.com
# NEXT_PUBLIC_INQUIRY_API_URL=https://jp-dev.qsalesplatform.com
NEXT_PUBLIC_INQUIRY_API_URL=http://1.248.227.176:8120
EMAIL_TITLE_PREFIX=(System Test)

View File

@ -1,4 +1,12 @@
NEXT_PUBLIC_RUN_MODE=local
DATABASE_URL="sqlserver://172.16.56.60:14331;database=hanwha_qcells_jp;user=qcells_jp;password=zbtpf2022!;encrypt=true;trustServerCertificate=true;applicationName=OnSiteSurvey"
DATABASE_CONNECTION_LIMIT=10
DATABASE_POOL_MIN=2
DATABASE_POOL_MAX=10
SESSION_PASSWORD="This application is for mobile field research"
# 모바일 디바이스로 로컬 서버 확인하려면 자신 IP 주소로 변경
# 다시 로컬에서 개발할때는 localhost로 변경
#route handler
@ -9,7 +17,8 @@ NEXT_PUBLIC_QSP_API_URL=http://1.248.227.176:8120
# NEXT_PUBLIC_QSP_API_URL=https://jp-dev.qsalesplatform.com
#1:1문의 api
NEXT_PUBLIC_INQUIRY_API_URL=https://jp-dev.qsalesplatform.com
# NEXT_PUBLIC_INQUIRY_API_URL=https://jp-dev.qsalesplatform.com
NEXT_PUBLIC_INQUIRY_API_URL=http://1.248.227.176:8120
EMAIL_TITLE_PREFIX=

View File

@ -1,6 +1,15 @@
NEXT_PUBLIC_RUN_MODE=production
DATABASE_URL="sqlserver://172.16.56.57:14331;database=hanwha_qcells_jp;user=qcells_jp;password=zbtpf2022!;encrypt=true;trustServerCertificate=true;applicationName=OnSiteSurvey"
DATABASE_CONNECTION_LIMIT=10
DATABASE_POOL_MIN=2
DATABASE_POOL_MAX=10
SESSION_PASSWORD="This application is for mobile field research"
#route handler
NEXT_PUBLIC_API_URL=http://localhost:3000
# NEXT_PUBLIC_API_URL=http://localhost:3000
NEXT_PUBLIC_API_URL=https://hanasysfield.jp
#qsp 로그인 api
# NEXT_PUBLIC_QSP_API_URL=http://1.248.227.176:8120

6
.gitignore vendored
View File

@ -45,4 +45,8 @@ next-env.d.ts
bun.lockb
pnpm-lock.yaml
pnpm-workspace.yaml
pnpm-workspace.yaml
# logs
logs/
*.log

View File

@ -18,7 +18,7 @@ Next.js와 TypeScript로 구축된 현장 조사용 모바일 애플리케이션
### 필수 요구사항
- Node.js (LTS 버전)
- Node.js (LTS 버전) 22.16.0 권장
- npm 또는 yarn 또는 pnpm 또는 burn
- Prisma CLI
@ -52,7 +52,9 @@ npm start
## 프로젝트 구조
[프로젝트 구조 Diagram](./diagram/mermaid.md)
[컴포넌트 간 관계 Diagram](./diagram/mermaid.md)
[페이지 컴포넌트 간 관례 Diagram](./diagram/mermaid3.md)
```
├── app/ # Next.js 앱 디렉토리
@ -63,6 +65,12 @@ npm start
└── public/ # 정적 자산
```
## 로그인
[로그인 Sequence Diagram](./diagram/mermaid2.md)
[로그인 컴포넌트 Diagram](./diagram/Login.md)
## 참고
### prisma 연결

2
dev.startscript.js Normal file
View File

@ -0,0 +1,2 @@
var exec = require('child_process').exec
exec('pnpm run start:dev', { windowsHide: true })

View File

@ -6,7 +6,12 @@ const nextConfig: NextConfig = {
sassOptions: {
includePaths: [path.join(__dirname, './src/styles')],
},
serverExternalPackages: ['@react-pdf/renderer'],
serverExternalPackages: ['@react-pdf/renderer', 'pino'],
logging: {
fetches: {
fullUrl: true,
},
},
async rewrites() {
return [
{
@ -19,6 +24,22 @@ const nextConfig: NextConfig = {
// },
]
},
webpack: (config, { dev, isServer }) => {
if (!dev && !isServer) {
config.optimization.minimizer = config.optimization.minimizer || []
config.optimization.minimizer.push(
new (require('terser-webpack-plugin'))({
terserOptions: {
format: {
comments: false,
},
},
extractComments: false,
}),
)
}
return config
},
}
export default nextConfig

579
package-lock.json generated
View File

@ -14,7 +14,6 @@
"@tanstack/react-query-devtools": "^5.71.0",
"@types/nodemailer": "^6.4.17",
"axios": "^1.8.4",
"crypto-js": "^4.2.0",
"env-cmd": "^10.1.0",
"iron-session": "^8.0.4",
"lucide": "^0.503.0",
@ -33,7 +32,6 @@
},
"devDependencies": {
"@tailwindcss/postcss": "^4",
"@types/crypto-js": "^4.2.2",
"@types/mysql": "^2.15.27",
"@types/node": "^20",
"@types/react": "^19",
@ -321,431 +319,6 @@
"tslib": "^2.4.0"
}
},
"node_modules/@esbuild/aix-ppc64": {
"version": "0.25.4",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.4.tgz",
"integrity": "sha512-1VCICWypeQKhVbE9oW/sJaAmjLxhVqacdkvPLEjwlttjfwENRSClS8EjBz0KzRyFSCPDIkuXW34Je/vk7zdB7Q==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"aix"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-arm": {
"version": "0.25.4",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.4.tgz",
"integrity": "sha512-QNdQEps7DfFwE3hXiU4BZeOV68HHzYwGd0Nthhd3uCkkEKK7/R6MTgM0P7H7FAs5pU/DIWsviMmEGxEoxIZ+ZQ==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-arm64": {
"version": "0.25.4",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.4.tgz",
"integrity": "sha512-bBy69pgfhMGtCnwpC/x5QhfxAz/cBgQ9enbtwjf6V9lnPI/hMyT9iWpR1arm0l3kttTr4L0KSLpKmLp/ilKS9A==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-x64": {
"version": "0.25.4",
"resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.4.tgz",
"integrity": "sha512-TVhdVtQIFuVpIIR282btcGC2oGQoSfZfmBdTip2anCaVYcqWlZXGcdcKIUklfX2wj0JklNYgz39OBqh2cqXvcQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/darwin-arm64": {
"version": "0.25.4",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.4.tgz",
"integrity": "sha512-Y1giCfM4nlHDWEfSckMzeWNdQS31BQGs9/rouw6Ub91tkK79aIMTH3q9xHvzH8d0wDru5Ci0kWB8b3up/nl16g==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/darwin-x64": {
"version": "0.25.4",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.4.tgz",
"integrity": "sha512-CJsry8ZGM5VFVeyUYB3cdKpd/H69PYez4eJh1W/t38vzutdjEjtP7hB6eLKBoOdxcAlCtEYHzQ/PJ/oU9I4u0A==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/freebsd-arm64": {
"version": "0.25.4",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.4.tgz",
"integrity": "sha512-yYq+39NlTRzU2XmoPW4l5Ifpl9fqSk0nAJYM/V/WUGPEFfek1epLHJIkTQM6bBs1swApjO5nWgvr843g6TjxuQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/freebsd-x64": {
"version": "0.25.4",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.4.tgz",
"integrity": "sha512-0FgvOJ6UUMflsHSPLzdfDnnBBVoCDtBTVyn/MrWloUNvq/5SFmh13l3dvgRPkDihRxb77Y17MbqbCAa2strMQQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-arm": {
"version": "0.25.4",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.4.tgz",
"integrity": "sha512-kro4c0P85GMfFYqW4TWOpvmF8rFShbWGnrLqlzp4X1TNWjRY3JMYUfDCtOxPKOIY8B0WC8HN51hGP4I4hz4AaQ==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-arm64": {
"version": "0.25.4",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.4.tgz",
"integrity": "sha512-+89UsQTfXdmjIvZS6nUnOOLoXnkUTB9hR5QAeLrQdzOSWZvNSAXAtcRDHWtqAUtAmv7ZM1WPOOeSxDzzzMogiQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ia32": {
"version": "0.25.4",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.4.tgz",
"integrity": "sha512-yTEjoapy8UP3rv8dB0ip3AfMpRbyhSN3+hY8mo/i4QXFeDxmiYbEKp3ZRjBKcOP862Ua4b1PDfwlvbuwY7hIGQ==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-loong64": {
"version": "0.25.4",
"resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.4.tgz",
"integrity": "sha512-NeqqYkrcGzFwi6CGRGNMOjWGGSYOpqwCjS9fvaUlX5s3zwOtn1qwg1s2iE2svBe4Q/YOG1q6875lcAoQK/F4VA==",
"cpu": [
"loong64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-mips64el": {
"version": "0.25.4",
"resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.4.tgz",
"integrity": "sha512-IcvTlF9dtLrfL/M8WgNI/qJYBENP3ekgsHbYUIzEzq5XJzzVEV/fXY9WFPfEEXmu3ck2qJP8LG/p3Q8f7Zc2Xg==",
"cpu": [
"mips64el"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ppc64": {
"version": "0.25.4",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.4.tgz",
"integrity": "sha512-HOy0aLTJTVtoTeGZh4HSXaO6M95qu4k5lJcH4gxv56iaycfz1S8GO/5Jh6X4Y1YiI0h7cRyLi+HixMR+88swag==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-riscv64": {
"version": "0.25.4",
"resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.4.tgz",
"integrity": "sha512-i8JUDAufpz9jOzo4yIShCTcXzS07vEgWzyX3NH2G7LEFVgrLEhjwL3ajFE4fZI3I4ZgiM7JH3GQ7ReObROvSUA==",
"cpu": [
"riscv64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-s390x": {
"version": "0.25.4",
"resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.4.tgz",
"integrity": "sha512-jFnu+6UbLlzIjPQpWCNh5QtrcNfMLjgIavnwPQAfoGx4q17ocOU9MsQ2QVvFxwQoWpZT8DvTLooTvmOQXkO51g==",
"cpu": [
"s390x"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-x64": {
"version": "0.25.4",
"resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.4.tgz",
"integrity": "sha512-6e0cvXwzOnVWJHq+mskP8DNSrKBr1bULBvnFLpc1KY+d+irZSgZ02TGse5FsafKS5jg2e4pbvK6TPXaF/A6+CA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/netbsd-arm64": {
"version": "0.25.4",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.4.tgz",
"integrity": "sha512-vUnkBYxZW4hL/ie91hSqaSNjulOnYXE1VSLusnvHg2u3jewJBz3YzB9+oCw8DABeVqZGg94t9tyZFoHma8gWZQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/netbsd-x64": {
"version": "0.25.4",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.4.tgz",
"integrity": "sha512-XAg8pIQn5CzhOB8odIcAm42QsOfa98SBeKUdo4xa8OvX8LbMZqEtgeWE9P/Wxt7MlG2QqvjGths+nq48TrUiKw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-arm64": {
"version": "0.25.4",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.4.tgz",
"integrity": "sha512-Ct2WcFEANlFDtp1nVAXSNBPDxyU+j7+tId//iHXU2f/lN5AmO4zLyhDcpR5Cz1r08mVxzt3Jpyt4PmXQ1O6+7A==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-x64": {
"version": "0.25.4",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.4.tgz",
"integrity": "sha512-xAGGhyOQ9Otm1Xu8NT1ifGLnA6M3sJxZ6ixylb+vIUVzvvd6GOALpwQrYrtlPouMqd/vSbgehz6HaVk4+7Afhw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/sunos-x64": {
"version": "0.25.4",
"resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.4.tgz",
"integrity": "sha512-Mw+tzy4pp6wZEK0+Lwr76pWLjrtjmJyUB23tHKqEDP74R3q95luY/bXqXZeYl4NYlvwOqoRKlInQialgCKy67Q==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"sunos"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-arm64": {
"version": "0.25.4",
"resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.4.tgz",
"integrity": "sha512-AVUP428VQTSddguz9dO9ngb+E5aScyg7nOeJDrF1HPYu555gmza3bDGMPhmVXL8svDSoqPCsCPjb265yG/kLKQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-ia32": {
"version": "0.25.4",
"resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.4.tgz",
"integrity": "sha512-i1sW+1i+oWvQzSgfRcxxG2k4I9n3O9NRqy8U+uugaT2Dy7kLO9Y7wI72haOahxceMX8hZAzgGou1FhndRldxRg==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-x64": {
"version": "0.25.4",
"resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.4.tgz",
"integrity": "sha512-nOT2vZNw6hJ+z43oP1SPea/G/6AbN6X+bGNhNuq8NtRHy4wsMhw765IKLNmnjek7GvjWBYQ8Q5VBoYTFg9y1UQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@img/sharp-darwin-arm64": {
"version": "0.33.5",
"resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.33.5.tgz",
@ -1575,9 +1148,9 @@
}
},
"node_modules/@prisma/client": {
"version": "6.7.0",
"resolved": "https://registry.npmjs.org/@prisma/client/-/client-6.7.0.tgz",
"integrity": "sha512-+k61zZn1XHjbZul8q6TdQLpuI/cvyfil87zqK2zpreNIXyXtpUv3+H/oM69hcsFcZXaokHJIzPAt5Z8C8eK2QA==",
"version": "6.9.0",
"resolved": "https://registry.npmjs.org/@prisma/client/-/client-6.9.0.tgz",
"integrity": "sha512-Gg7j1hwy3SgF1KHrh0PZsYvAaykeR0PaxusnLXydehS96voYCGt1U5zVR31NIouYc63hWzidcrir1a7AIyCsNQ==",
"hasInstallScript": true,
"license": "Apache-2.0",
"engines": {
@ -1597,64 +1170,63 @@
}
},
"node_modules/@prisma/config": {
"version": "6.7.0",
"resolved": "https://registry.npmjs.org/@prisma/config/-/config-6.7.0.tgz",
"integrity": "sha512-di8QDdvSz7DLUi3OOcCHSwxRNeW7jtGRUD2+Z3SdNE3A+pPiNT8WgUJoUyOwJmUr5t+JA2W15P78C/N+8RXrOA==",
"version": "6.9.0",
"resolved": "https://registry.npmjs.org/@prisma/config/-/config-6.9.0.tgz",
"integrity": "sha512-Wcfk8/lN3WRJd5w4jmNQkUwhUw0eksaU/+BlAJwPQKW10k0h0LC9PD/6TQFmqKVbHQL0vG2z266r0S1MPzzhbA==",
"devOptional": true,
"license": "Apache-2.0",
"dependencies": {
"esbuild": ">=0.12 <1",
"esbuild-register": "3.6.0"
"jiti": "2.4.2"
}
},
"node_modules/@prisma/debug": {
"version": "6.7.0",
"resolved": "https://registry.npmjs.org/@prisma/debug/-/debug-6.7.0.tgz",
"integrity": "sha512-RabHn9emKoYFsv99RLxvfG2GHzWk2ZI1BuVzqYtmMSIcuGboHY5uFt3Q3boOREM9de6z5s3bQoyKeWnq8Fz22w==",
"version": "6.9.0",
"resolved": "https://registry.npmjs.org/@prisma/debug/-/debug-6.9.0.tgz",
"integrity": "sha512-bFeur/qi/Q+Mqk4JdQ3R38upSYPebv5aOyD1RKywVD+rAMLtRkmTFn28ZuTtVOnZHEdtxnNOCH+bPIeSGz1+Fg==",
"devOptional": true,
"license": "Apache-2.0"
},
"node_modules/@prisma/engines": {
"version": "6.7.0",
"resolved": "https://registry.npmjs.org/@prisma/engines/-/engines-6.7.0.tgz",
"integrity": "sha512-3wDMesnOxPrOsq++e5oKV9LmIiEazFTRFZrlULDQ8fxdub5w4NgRBoxtWbvXmj2nJVCnzuz6eFix3OhIqsZ1jw==",
"version": "6.9.0",
"resolved": "https://registry.npmjs.org/@prisma/engines/-/engines-6.9.0.tgz",
"integrity": "sha512-im0X0bwDLA0244CDf8fuvnLuCQcBBdAGgr+ByvGfQY9wWl6EA+kRGwVk8ZIpG65rnlOwtaWIr/ZcEU5pNVvq9g==",
"devOptional": true,
"hasInstallScript": true,
"license": "Apache-2.0",
"dependencies": {
"@prisma/debug": "6.7.0",
"@prisma/engines-version": "6.7.0-36.3cff47a7f5d65c3ea74883f1d736e41d68ce91ed",
"@prisma/fetch-engine": "6.7.0",
"@prisma/get-platform": "6.7.0"
"@prisma/debug": "6.9.0",
"@prisma/engines-version": "6.9.0-10.81e4af48011447c3cc503a190e86995b66d2a28e",
"@prisma/fetch-engine": "6.9.0",
"@prisma/get-platform": "6.9.0"
}
},
"node_modules/@prisma/engines-version": {
"version": "6.7.0-36.3cff47a7f5d65c3ea74883f1d736e41d68ce91ed",
"resolved": "https://registry.npmjs.org/@prisma/engines-version/-/engines-version-6.7.0-36.3cff47a7f5d65c3ea74883f1d736e41d68ce91ed.tgz",
"integrity": "sha512-EvpOFEWf1KkJpDsBCrih0kg3HdHuaCnXmMn7XFPObpFTzagK1N0Q0FMnYPsEhvARfANP5Ok11QyoTIRA2hgJTA==",
"version": "6.9.0-10.81e4af48011447c3cc503a190e86995b66d2a28e",
"resolved": "https://registry.npmjs.org/@prisma/engines-version/-/engines-version-6.9.0-10.81e4af48011447c3cc503a190e86995b66d2a28e.tgz",
"integrity": "sha512-Qp9gMoBHgqhKlrvumZWujmuD7q4DV/gooEyPCLtbkc13EZdSz2RsGUJ5mHb3RJgAbk+dm6XenqG7obJEhXcJ6Q==",
"devOptional": true,
"license": "Apache-2.0"
},
"node_modules/@prisma/fetch-engine": {
"version": "6.7.0",
"resolved": "https://registry.npmjs.org/@prisma/fetch-engine/-/fetch-engine-6.7.0.tgz",
"integrity": "sha512-zLlAGnrkmioPKJR4Yf7NfW3hftcvqeNNEHleMZK9yX7RZSkhmxacAYyfGsCcqRt47jiZ7RKdgE0Wh2fWnm7WsQ==",
"version": "6.9.0",
"resolved": "https://registry.npmjs.org/@prisma/fetch-engine/-/fetch-engine-6.9.0.tgz",
"integrity": "sha512-PMKhJdl4fOdeE3J3NkcWZ+tf3W6rx3ht/rLU8w4SXFRcLhd5+3VcqY4Kslpdm8osca4ej3gTfB3+cSk5pGxgFg==",
"devOptional": true,
"license": "Apache-2.0",
"dependencies": {
"@prisma/debug": "6.7.0",
"@prisma/engines-version": "6.7.0-36.3cff47a7f5d65c3ea74883f1d736e41d68ce91ed",
"@prisma/get-platform": "6.7.0"
"@prisma/debug": "6.9.0",
"@prisma/engines-version": "6.9.0-10.81e4af48011447c3cc503a190e86995b66d2a28e",
"@prisma/get-platform": "6.9.0"
}
},
"node_modules/@prisma/get-platform": {
"version": "6.7.0",
"resolved": "https://registry.npmjs.org/@prisma/get-platform/-/get-platform-6.7.0.tgz",
"integrity": "sha512-i9IH5lO4fQwnMLvQLYNdgVh9TK3PuWBfQd7QLk/YurnAIg+VeADcZDbmhAi4XBBDD+hDif9hrKyASu0hbjwabw==",
"version": "6.9.0",
"resolved": "https://registry.npmjs.org/@prisma/get-platform/-/get-platform-6.9.0.tgz",
"integrity": "sha512-/B4n+5V1LI/1JQcHp+sUpyRT1bBgZVPHbsC4lt4/19Xp4jvNIVcq5KYNtQDk5e/ukTSjo9PZVAxxy9ieFtlpTQ==",
"devOptional": true,
"license": "Apache-2.0",
"dependencies": {
"@prisma/debug": "6.7.0"
"@prisma/debug": "6.9.0"
}
},
"node_modules/@react-pdf/fns": {
@ -2142,13 +1714,6 @@
"integrity": "sha512-7qSgZbincDDDFyRweCIEvZULFAw5iz/DeunhvuxpL31nfntX3P4Yd4HkHBRg9H8CdqY1e5WFN1PZIz/REL9MVQ==",
"license": "MIT"
},
"node_modules/@types/crypto-js": {
"version": "4.2.2",
"resolved": "https://registry.npmjs.org/@types/crypto-js/-/crypto-js-4.2.2.tgz",
"integrity": "sha512-sDOLlVbHhXpAUAL0YHDUUwDZf3iN4Bwi4W6a0W0b+QcAezUbRtH4FVb+9J4h+XFPW7l/gQ9F8qC7P+Ec4k8QVQ==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/mysql": {
"version": "2.15.27",
"resolved": "https://registry.npmjs.org/@types/mysql/-/mysql-2.15.27.tgz",
@ -2875,60 +2440,6 @@
"node": ">= 0.4"
}
},
"node_modules/esbuild": {
"version": "0.25.4",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.4.tgz",
"integrity": "sha512-8pgjLUcUjcgDg+2Q4NYXnPbo/vncAY4UmyaCm0jZevERqCHZIaWwdJHkf8XQtu4AxSKCdvrUbT0XUr1IdZzI8Q==",
"devOptional": true,
"hasInstallScript": true,
"license": "MIT",
"bin": {
"esbuild": "bin/esbuild"
},
"engines": {
"node": ">=18"
},
"optionalDependencies": {
"@esbuild/aix-ppc64": "0.25.4",
"@esbuild/android-arm": "0.25.4",
"@esbuild/android-arm64": "0.25.4",
"@esbuild/android-x64": "0.25.4",
"@esbuild/darwin-arm64": "0.25.4",
"@esbuild/darwin-x64": "0.25.4",
"@esbuild/freebsd-arm64": "0.25.4",
"@esbuild/freebsd-x64": "0.25.4",
"@esbuild/linux-arm": "0.25.4",
"@esbuild/linux-arm64": "0.25.4",
"@esbuild/linux-ia32": "0.25.4",
"@esbuild/linux-loong64": "0.25.4",
"@esbuild/linux-mips64el": "0.25.4",
"@esbuild/linux-ppc64": "0.25.4",
"@esbuild/linux-riscv64": "0.25.4",
"@esbuild/linux-s390x": "0.25.4",
"@esbuild/linux-x64": "0.25.4",
"@esbuild/netbsd-arm64": "0.25.4",
"@esbuild/netbsd-x64": "0.25.4",
"@esbuild/openbsd-arm64": "0.25.4",
"@esbuild/openbsd-x64": "0.25.4",
"@esbuild/sunos-x64": "0.25.4",
"@esbuild/win32-arm64": "0.25.4",
"@esbuild/win32-ia32": "0.25.4",
"@esbuild/win32-x64": "0.25.4"
}
},
"node_modules/esbuild-register": {
"version": "3.6.0",
"resolved": "https://registry.npmjs.org/esbuild-register/-/esbuild-register-3.6.0.tgz",
"integrity": "sha512-H2/S7Pm8a9CL1uhp9OvjwrBh5Pvx0H8qVOxNu8Wed9Y7qv56MPtq+GGM8RJpq6glYJn9Wspr8uw7l55uyinNeg==",
"devOptional": true,
"license": "MIT",
"dependencies": {
"debug": "^4.3.4"
},
"peerDependencies": {
"esbuild": ">=0.12 <1"
}
},
"node_modules/event-target-shim": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz",
@ -3024,21 +2535,6 @@
"node": ">= 6"
}
},
"node_modules/fsevents": {
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
"integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
"node_modules/function-bind": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
@ -3398,7 +2894,7 @@
"version": "2.4.2",
"resolved": "https://registry.npmjs.org/jiti/-/jiti-2.4.2.tgz",
"integrity": "sha512-rg9zJN+G4n2nfJl5MW3BMygZX56zKPNVEYYqq7adpmMh4Jn2QNEwhvQlFy6jPVdcod7txZtKHWnyZiA3a0zP7A==",
"dev": true,
"devOptional": true,
"license": "MIT",
"bin": {
"jiti": "lib/jiti-cli.mjs"
@ -4219,15 +3715,15 @@
"license": "MIT"
},
"node_modules/prisma": {
"version": "6.7.0",
"resolved": "https://registry.npmjs.org/prisma/-/prisma-6.7.0.tgz",
"integrity": "sha512-vArg+4UqnQ13CVhc2WUosemwh6hr6cr6FY2uzDvCIFwH8pu8BXVv38PktoMLVjtX7sbYThxbnZF5YiR8sN2clw==",
"version": "6.9.0",
"resolved": "https://registry.npmjs.org/prisma/-/prisma-6.9.0.tgz",
"integrity": "sha512-resJAwMyZREC/I40LF6FZ6rZTnlrlrYrb63oW37Gq+U+9xHwbyMSPJjKtM7VZf3gTO86t/Oyz+YeSXr3CmAY1Q==",
"devOptional": true,
"hasInstallScript": true,
"license": "Apache-2.0",
"dependencies": {
"@prisma/config": "6.7.0",
"@prisma/engines": "6.7.0"
"@prisma/config": "6.9.0",
"@prisma/engines": "6.9.0"
},
"bin": {
"prisma": "build/index.js"
@ -4235,9 +3731,6 @@
"engines": {
"node": ">=18.18"
},
"optionalDependencies": {
"fsevents": "2.3.3"
},
"peerDependencies": {
"typescript": ">=5.1.0"
},

View File

@ -21,7 +21,6 @@
"@tanstack/react-query-devtools": "^5.71.0",
"@types/nodemailer": "^6.4.17",
"axios": "^1.8.4",
"crypto-js": "^4.2.0",
"env-cmd": "^10.1.0",
"iron-session": "^8.0.4",
"lucide": "^0.503.0",
@ -30,6 +29,7 @@
"next": "15.2.4",
"nodemailer": "^7.0.3",
"pdf-lib": "^1.17.1",
"pino": "^9.7.0",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"react-to-pdf": "^2.0.0",
@ -40,13 +40,13 @@
},
"devDependencies": {
"@tailwindcss/postcss": "^4",
"@types/crypto-js": "^4.2.2",
"@types/mysql": "^2.15.27",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"prisma": "^6.7.0",
"tailwindcss": "^4",
"terser-webpack-plugin": "^5.3.14",
"typescript": "^5"
}
}

View File

@ -13,7 +13,6 @@ model SD_SURVEY_SALES_BASIC_INFO {
REPRESENTATIVE String @db.NVarChar(200)
STORE String? @db.NVarChar(200)
CONSTRUCTION_POINT String? @db.NVarChar(200)
CONSTRUCTION_POINT_ID String? @db.NVarChar(200)
INVESTIGATION_DATE String? @db.NVarChar(10)
BUILDING_NAME String? @db.NVarChar(200)
CUSTOMER_NAME String? @db.NVarChar(200)
@ -23,11 +22,12 @@ model SD_SURVEY_SALES_BASIC_INFO {
SUBMISSION_STATUS Boolean @default(false)
SUBMISSION_DATE DateTime? @db.Date
SUBMISSION_TARGET_ID String? @db.NVarChar(200)
SUBMISSION_TARGET_NM String? @db.NVarChar(200)
REG_DT DateTime @default(now())
UPT_DT DateTime @updatedAt
REPRESENTATIVE_ID String? @db.NVarChar(100)
STORE_ID String? @db.NVarChar(100)
CONSTRUCTION_POINT_ID String? @db.NVarChar(200)
SUBMISSION_TARGET_NM String? @db.NVarChar(200)
DETAIL_INFO SD_SURVEY_SALES_DETAIL_INFO?
}
@ -179,3 +179,304 @@ model MS_USR_TRK {
REG_DT DateTime @default(now())
DATA String? @db.NVarChar(200)
}
model BC_QM_BUILDER {
COMP_CD String @db.NVarChar(4)
BUILDER_NO String @db.NVarChar(50)
AGENCY_STORE_ID String @db.NVarChar(100)
BUILDER_NM String @db.NVarChar(100)
BUILDER_ID String? @db.NVarChar(100)
ZIP_NO String? @db.NVarChar(7)
PRFT_JP String? @db.NVarChar(100)
MNCP_NM String? @db.NVarChar(100)
ADDR_NM String? @db.NVarChar(200)
ADDR_DTL String? @db.NVarChar(200)
RECEIVER_NM String? @db.NVarChar(100)
RECEIVER_CONTACT_NO String? @db.NVarChar(100)
USE_YN String? @db.NVarChar(1)
REG_DT DateTime? @db.DateTime
REG_ID String? @db.NVarChar(50)
UPT_DT DateTime? @db.DateTime
UPT_ID String? @db.NVarChar(50)
BC_QM_USER BC_QM_USER[]
@@id([COMP_CD, BUILDER_NO], map: "PK_BC_QM_BUILDER")
}
model BC_QM_TERMS {
COMP_CD String @db.NVarChar(4)
TERMS_NO Decimal @db.Decimal(18, 0)
VER_NO String @db.NVarChar(3)
VER_SUB_NO String @db.NVarChar(3)
OPERTN_DT DateTime @db.Date
TERMS_CTNT String @db.NVarChar(Max)
DEL_YN String? @db.NVarChar(1)
REG_DT DateTime? @db.DateTime
REG_ID String? @db.NVarChar(50)
UPT_DT DateTime? @db.DateTime
UPT_ID String? @db.NVarChar(50)
BC_QM_USER BC_QM_USER[]
@@id([TERMS_NO, COMP_CD], map: "PK_BC_QM_TERMS")
}
model BC_QM_USER {
COMP_CD String @db.NVarChar(4)
USER_ID String @db.NVarChar(50)
AGENCY_STORE_ID String @db.NVarChar(100)
USER_NM String @db.NVarChar(100)
USER_AUTH_CD String @db.NVarChar(10)
EMAIL String? @db.NVarChar(100)
PSTN_NM String? @db.NVarChar(100)
TEL_NO String? @db.NVarChar(100)
MOBILE_NO String? @db.NVarChar(100)
FAX_NO String? @db.NVarChar(100)
LAST_LOGIN_DT DateTime? @db.DateTime
PWD String @db.NVarChar(100)
PWD_INIT_YN String? @default("N", map: "DF__BC_QM_USE__PWD_I__42E1EEFE") @db.NVarChar(1)
LOGIN_FAIL_CNT Decimal? @default(0, map: "DF__BC_QM_USE__LOGIN__43D61337") @db.Decimal(18, 0)
LAST_LOGIN_FAIL_DT DateTime? @db.DateTime
LAST_PWD_UPT_DT DateTime? @db.DateTime
BUILDER_NO String? @db.NVarChar(50)
ZIP_NO String? @db.NVarChar(7)
PRFT_JP String? @db.NVarChar(100)
MNCP_NM String? @db.NVarChar(100)
ADDR_NM String? @db.NVarChar(200)
TERMS_AGREE_YN String? @default("N", map: "DF__BC_QM_USE__TERMS__44CA3770") @db.NVarChar(1)
TERMS_AGREE_DT DateTime? @db.DateTime
AGREE_TERMS_NO Decimal? @db.Decimal(18, 0)
STAT_CD String? @db.NVarChar(1)
DEL_YN String? @db.NVarChar(1)
REG_DT DateTime? @db.DateTime
REG_ID String? @db.NVarChar(50)
UPT_DT DateTime? @db.DateTime
UPT_ID String? @db.NVarChar(50)
USER_NM_KANA String? @db.NVarChar(50)
BC_QM_BUILDER BC_QM_BUILDER? @relation(fields: [COMP_CD, BUILDER_NO], references: [COMP_CD, BUILDER_NO], onUpdate: NoAction, map: "FK_BC_QM_USER_01")
BC_QM_TERMS BC_QM_TERMS? @relation(fields: [AGREE_TERMS_NO, COMP_CD], references: [TERMS_NO, COMP_CD], onUpdate: NoAction, map: "FK_BC_QM_USER_02")
@@id([COMP_CD, USER_ID], map: "PK_BC_QM_USER")
}
model IF_PERSON_OFFICE_MAPPING {
IF_SEQ Decimal @id(map: "PK_IF_PERSON_OFFICE_MAPPING") @db.Decimal(22, 0)
SEQ Int?
LIFNR String? @db.NVarChar(10)
VKBUR String? @db.NVarChar(4)
IF_DT DateTime? @db.DateTime
IF_STS String? @db.NVarChar(1)
IF_MSG String? @db.NVarChar(200)
}
model MS_CUST_AGENCY_STOREID {
COMP_CD String @db.NVarChar(4)
STORE_ID String @db.NVarChar(100)
AGENCY_STORE_ID String @db.NVarChar(100)
AGENCY_QCAST_NM String? @db.NVarChar(100)
PLAN_REQ_SUBMIT_YN String? @default("N", map: "DF__MS_CUST_A__PLAN___3B40CD36") @db.NVarChar(1)
DEL_YN String? @default("N", map: "DF__MS_CUST_A__DEL_Y__3C34F16F") @db.NVarChar(1)
REG_DT DateTime? @db.DateTime
REG_ID String? @db.NVarChar(50)
UPT_DT DateTime? @db.DateTime
UPT_ID String? @db.NVarChar(50)
EMAIL String? @db.NVarChar(100)
REMARK String? @db.NVarChar(Max)
BDL_TP_CD String? @db.NVarChar(10)
@@id([COMP_CD, AGENCY_STORE_ID], map: "PK_MS_CUST_AGENCY_STOREID")
}
model MS_CUST_H {
COMP_CD String @db.NVarChar(4)
CUST_CD String @db.NVarChar(10)
ACCOUNT_GR String? @db.NVarChar(4)
CUST_NM String? @db.NVarChar(70)
HAUS_NO String? @db.NVarChar(10)
POST_CD String? @db.NVarChar(10)
CITY_CD String? @db.NVarChar(12)
CITY_NM String? @db.NVarChar(40)
COUNTRY_CD String? @db.NVarChar(4)
REGION_CD String? @db.NVarChar(4)
STREET_NM String? @db.NVarChar(60)
STREET_NM2 String? @db.NVarChar(60)
STREET_NM3 String? @db.NVarChar(60)
STREET_NM4 String? @db.NVarChar(60)
STREET_NM5 String? @db.NVarChar(60)
TIME_ZONE String? @db.NVarChar(10)
TRANSP_ZONE String? @db.NVarChar(10)
LANG_CD String? @db.NVarChar(2)
TEL_NO String? @db.NVarChar(30)
TEL_NO_EXT String? @db.NVarChar(10)
MOBILE_NO String? @db.NVarChar(30)
FAX_NO String? @db.NVarChar(30)
FAX_NO_EXT String? @db.NVarChar(10)
EMAIL String? @db.NVarChar(100)
INDUSTRY_CD String? @db.NVarChar(4)
VAT_REG_NO String? @db.NVarChar(20)
LOCAT_NO1 Decimal? @db.Decimal(7, 0)
LOCAT_NO2 Decimal? @db.Decimal(5, 0)
RESI_CD String? @db.NVarChar(4)
UTIL_CD String? @db.NVarChar(4)
MARK_PF String? @db.NVarChar(4)
INVS_CD String? @db.NVarChar(4)
PRMT_CD String? @db.NVarChar(4)
SVC_PR_CD String? @db.NVarChar(4)
ENG_CNSL_CD String? @db.NVarChar(4)
RECON_ACC_CD String? @db.NVarChar(20)
SORT_KEY String? @db.NVarChar(12)
CASH_MGMT_GR String? @db.NVarChar(12)
INTEREST_IND_CD String? @db.NVarChar(12)
TERM_PAY_CD String? @db.NVarChar(12)
PAY_HIST_YN String? @db.NVarChar(2)
DUN_PROC_CD String? @db.NVarChar(4)
DUN_BLOCK_CD String? @db.NVarChar(1)
DUN_LEVEL_CD Decimal? @db.Decimal(1, 0)
POLICY_NO String? @db.NVarChar(20)
INSURED_AMT Decimal? @db.Decimal(13, 3)
VAL_TO_DATE DateTime? @db.Date
DEDUCT_RATE Decimal? @db.Decimal(9, 0)
APPLIED_INSURA Decimal? @db.Decimal(13, 3)
EASY_NO String? @db.NVarChar(20)
APPLY_DATE DateTime? @db.Date
EXPIRE_DATE DateTime? @db.Date
ADD_TXT1 String? @db.NVarChar(400)
ADD_TXT2 String? @db.NVarChar(400)
REF_PS_ID String? @db.NVarChar(20)
CUST_COMP_CD String? @db.NVarChar(4)
CUST_TEXT String? @db.NVarChar(Max)
CUST_GRADE String? @db.NVarChar(2)
INCOME_TAX_NO String? @db.NVarChar(20)
STAT_CD String? @db.NVarChar(2)
REG_DT DateTime? @db.DateTime
REG_ID String? @db.NVarChar(50)
UPT_DT DateTime? @db.DateTime
UPT_ID String? @db.NVarChar(50)
QSP_ACCOUNT_GR String? @db.NVarChar(4)
BDL_TP_CD String? @db.NVarChar(10)
BDL_SUB_TP_CD String? @db.NVarChar(100)
MS_CUST_STOREID MS_CUST_STOREID[]
@@id([COMP_CD, CUST_CD], map: "PK_MS_CUST_H")
}
model MS_CUST_PERSON {
SEQ Decimal @db.Decimal(22, 0)
COMP_CD String @db.NVarChar(4)
CUST_CD String @db.NVarChar(10)
EOS_LOGIN_ID String? @db.NVarChar(100)
EOS_PWD String? @db.NVarChar(100)
NAME String? @db.NVarChar(50)
PSTN_NM String? @db.NVarChar(50)
EMAIL String? @db.NVarChar(100)
TEL_NO String? @db.NVarChar(100)
AUTHORITY String @db.NVarChar(1)
DEL_YN String? @default("N", map: "DF__MS_CUST_P__DEL_Y__339FAB6E") @db.NVarChar(1)
LOGIN_DT DateTime? @db.DateTime
PWD_INIT_YN String? @db.NVarChar(1)
LOGIN_FAIL_CNT Decimal? @db.Decimal(18, 0)
REG_DT DateTime? @db.DateTime
REG_ID String? @db.NVarChar(50)
UPT_DT DateTime? @db.DateTime
UPT_ID String? @db.NVarChar(50)
LOGIN_FAIL_DT DateTime? @db.DateTime
PLAN_REQ_AUTH String? @default("N", map: "DF__MS_CUST_P__PLAN___3493CFA7") @db.NVarChar(1)
PRICE_VIEW_STAT_CD String? @default("S", map: "DF__MS_CUST_P__PRICE__3587F3E0") @db.NVarChar(10)
SD_SUBMIT_YN String? @default("N", map: "DF__MS_CUST_P__SD_SU__367C1819") @db.NVarChar(1)
STORE_ID String? @db.NVarChar(100)
USER_NM_KANA String? @db.NVarChar(50)
FAX String? @db.NVarChar(100)
PLAN_MAIL_RCV_YN String? @default("Y", map: "DF__MS_CUST_P__PLAN___37703C52") @db.NVarChar(1)
SD_MAIL_RCV_YN String? @default("Y", map: "DF__MS_CUST_P__SD_MA__3864608B") @db.NVarChar(1)
@@id([SEQ, COMP_CD, CUST_CD], map: "PK_MS_CUST_PERSON")
}
model MS_CUST_STOREID {
COMP_CD String @db.NVarChar(4)
STORE_ID String @db.NVarChar(100)
CUST_CD String @db.NVarChar(10)
REPRESENTATIVE_STORE_YN String? @db.NVarChar(1)
SP_MODULE_PRICE_SEQ Decimal? @db.Decimal(20, 0)
SP_MODULE_PRICE_EXP_FR_DT DateTime? @db.Date
SP_MODULE_PRICE_EXP_TO_DT DateTime? @db.Date
SP_BOS_PRICE_SEQ Decimal? @db.Decimal(20, 0)
SP_BOS_PRICE_EXP_FR_DT DateTime? @db.Date
SP_BOS_PRICE_EXP_TO_DT DateTime? @db.Date
PKG_PRICE_RANK String? @default("C", map: "DF__MS_CUST_S__PKG_P__29221CFB") @db.NVarChar(3)
SP_PKG_PRICE Decimal? @db.Decimal(13, 1)
SP_PKG_PRICE_EXP_FR_DT DateTime? @db.Date
SP_PKG_PRICE_EXP_TO_DT DateTime? @db.Date
DEL_YN String? @default("N", map: "DF__MS_CUST_S__DEL_Y__2A164134") @db.NVarChar(1)
REG_DT DateTime? @db.DateTime
REG_ID String? @db.NVarChar(50)
UPT_DT DateTime? @db.DateTime
UPT_ID String? @db.NVarChar(50)
MOVE_DT DateTime? @db.DateTime
MOVE_ID String? @db.NVarChar(50)
STORE_QCAST_NM String? @db.NVarChar(100)
PLAN_REQ_AUTH String? @default("N", map: "DF__MS_CUST_S__PLAN___2B0A656D") @db.NVarChar(1)
PKG_EXCEPT_YN String? @default("N", map: "DF__MS_CUST_S__PKG_E__2BFE89A6") @db.NVarChar(1)
MODULE_PRICE_RANK String? @default("C", map: "DF__MS_CUST_S__MODUL__2CF2ADDF") @db.NVarChar(20)
BOS_PRICE_RANK String? @default("A", map: "DF__MS_CUST_S__BOS_P__2DE6D218") @db.NVarChar(20)
PLAN_REQ_SUBMIT_YN String? @default("N", map: "DF__MS_CUST_S__PLAN___2EDAF651") @db.NVarChar(1)
QSP_SUBAL_YN String? @default("N", map: "DF__MS_CUST_S__QSP_S__2FCF1A8A") @db.NVarChar(1)
MS_CUST_H MS_CUST_H @relation(fields: [COMP_CD, CUST_CD], references: [COMP_CD, CUST_CD], onUpdate: NoAction, map: "MS_CUST_STOREID_FK")
@@id([COMP_CD, STORE_ID], map: "PK_MS_CUST_STOREID")
@@index([COMP_CD, CUST_CD], map: "IDX_MS_CUST_STOREID_COMP_CD_01")
}
model MS_CUST_STOREID_ADDITNL {
COMP_CD String @db.NVarChar(20)
STORE_ID String @db.NVarChar(100)
REQ_CUST_CD String? @db.NVarChar(10)
REQ_STORE_QCAST_NM String? @db.NVarChar(100)
STORE_QCAST_NM_KANA String? @db.NVarChar(100)
BIZ_NO String? @db.NVarChar(20)
POST_CD String? @db.NVarChar(10)
ADDR String? @db.NVarChar(255)
TEL_NO String? @db.NVarChar(100)
FAX String? @db.NVarChar(100)
APPR_DT DateTime? @db.DateTime
APPR_ID String? @db.NVarChar(50)
APPR_STAT_CD String? @db.NVarChar(10)
APPR_REMARKS String? @db.NVarChar(300)
REQ_APPR_DT DateTime? @db.DateTime
PAY_TERMS_CD String? @db.NVarChar(10)
FIRST_STORE_ID String? @db.NVarChar(100)
PARENT_STORE_ID String? @db.NVarChar(100)
STORE_LVL Int?
KAM_ID String? @db.NVarChar(50)
QT_COMP_NM String? @db.NVarChar(100)
QT_POST_CD String? @db.NVarChar(10)
QT_ADDR String? @db.NVarChar(255)
QT_TEL_NO String? @db.NVarChar(100)
QT_FAX String? @db.NVarChar(100)
QT_E_MAIL String? @db.NVarChar(100)
ORD_DELI_TARGET String? @db.NVarChar(100)
ORD_DELI_COMP_NM String? @db.NVarChar(100)
ORD_DELI_COMP_USER_NM String? @db.NVarChar(40)
ORD_DELI_TEL_NO String? @db.NVarChar(100)
ORD_DELI_POST_CD String? @db.NVarChar(10)
ORD_DELI_REMARKS String? @db.NVarChar(200)
GUAR_STORE_NM String? @db.NVarChar(100)
GUAR_STORE_POST_CD String? @db.NVarChar(10)
GUAR_STORE_ADDR String? @db.NVarChar(255)
GUAR_TEL_NO String? @db.NVarChar(100)
NORTH_MODULE_YN String? @default("N", map: "DF__MS_CUST_S__NORTH__17036CC0") @db.NVarChar(1)
DEL_YN String? @default("N", map: "DF__MS_CUST_S__DEL_Y__17F790F9") @db.NVarChar(1)
REG_DT DateTime? @db.DateTime
REG_ID String? @db.NVarChar(50)
UPT_DT DateTime? @db.DateTime
UPT_ID String? @db.NVarChar(50)
REQ_MODULE_PRICE_RANK String? @db.NVarChar(20)
REQ_BOS_PRICE_RANK String? @db.NVarChar(20)
REQ_PKG_PRICE_RANK String? @db.NVarChar(3)
REQ_BDL_TP_CD String? @db.NVarChar(10)
REQ_BDL_SUB_TP_CD String? @db.NVarChar(100)
REMARK String? @db.NVarChar(500)
NORTH_MODULE_UPT_DT DateTime? @db.DateTime
NORTH_MODULE_UPT_ID String? @db.NVarChar(50)
@@id([COMP_CD, STORE_ID], map: "PK_MS_CUST_STOREID_ADDITNL")
}

2
prod.startscript.js Normal file
View File

@ -0,0 +1,2 @@
var exec = require('child_process').exec
exec('pnpm run start:prod', { windowsHide: true })

View File

@ -1,22 +0,0 @@
'use server'
import { sessionOptions } from '@/libs/session'
import type { SessionData } from '@/types/Auth'
import { getIronSession } from 'iron-session'
import { cookies } from 'next/headers'
import { redirect } from 'next/navigation'
export const logout = async () => {
const cookieStore = await cookies()
const session = await getIronSession<SessionData>(cookieStore, sessionOptions)
session.destroy()
return redirect('/login')
}
export const getSession = async () => {
const cookieStore = await cookies()
const session = await getIronSession<SessionData>(cookieStore, sessionOptions)
return session
}

View File

@ -1,107 +0,0 @@
import { database } from '@/data'
import { axiosInstance } from '@/libs/axios'
export interface Suitable {
id?: number
product_name: string
manufacturer: string
roof_material: string
shape: string
support_roof_tile: string
support_roof_tile_memo: string
support_roof_bracket: string
support_roof_bracket_memo: string
yg_anchor: string
yg_anchor_memo: string
rg_roof_tile_part: string
rg_roof_tile_part_memo: string
dido_hunt_support_tile_2: string
dido_hunt_support_tile_2_memo: string
takashima_power_base: string
takashima_power_base_memo: string
takashima_tile_bracket: string
takashima_tile_bracket_memo: string
slate_bracket_4: string
slate_bracket_4_memo: string
slate_single_metal_bracket: string
slate_single_metal_bracket_memo: string
dido_hunt_short_rack_4: string
dido_hunt_short_rack_4_memo: string
takashima_slate_bracket_slate_single: string
takashima_slate_bracket_slate_single_memo: string
df_metal_bracket: string
df_metal_bracket_memo: string
slate_metal_bracket: string
slate_metal_bracket_memo: string
takashima_slate_bracket_metal_roof: string
takashima_slate_bracket_metal_roof_memo: string
}
export const suitableApi = {
// getList: async (category?: string, keyword?: string): Promise<Suitable[]> => {
// let condition: any = {}
// if (category) {
// condition['category'] = category
// }
// if (keyword) {
// condition['keyword'] = {
// contains: keyword,
// }
// }
// console.log('🚀 ~ getList: ~ condition:', condition)
// const response = await axiosInstance(null).get<Suitable[]>('/api/suitable/list', { params: condition })
// console.log('🚀 ~ getList: ~ response:', response)
// return response.data
// },
// getCategory: async (): Promise<Suitable[]> => {
// const response = await axiosInstance(null).get<Suitable[]>('/api/suitable/category')
// console.log('🚀 ~ getCategory: ~ response:', response)
// return response.data
// },
// getDetails: async (roofMaterial: string): Promise<Suitable[]> => {
// const response = await axiosInstance(null).get<Suitable[]>(`/api/suitable/details?roof-material=${roofMaterial}`)
// console.log('🚀 ~ getDetails: ~ response:', response)
// return response.data
// },
// create: async () => {
// const suitableData: Suitable[] = []
// database.forEach((item) => {
// suitableData.push({
// product_name: item[0],
// manufacturer: item[1],
// roof_material: item[2],
// shape: item[3],
// support_roof_tile: item[4],
// support_roof_tile_memo: item[5],
// support_roof_bracket: item[6],
// support_roof_bracket_memo: item[7],
// yg_anchor: item[8],
// yg_anchor_memo: item[9],
// rg_roof_tile_part: item[10],
// rg_roof_tile_part_memo: item[11],
// dido_hunt_support_tile_2: item[12],
// dido_hunt_support_tile_2_memo: item[13],
// takashima_power_base: item[14],
// takashima_power_base_memo: item[15],
// takashima_tile_bracket: item[16],
// takashima_tile_bracket_memo: item[17],
// slate_bracket_4: item[18],
// slate_bracket_4_memo: item[19],
// slate_single_metal_bracket: item[20],
// slate_single_metal_bracket_memo: item[21],
// dido_hunt_short_rack_4: item[22],
// dido_hunt_short_rack_4_memo: item[23],
// takashima_slate_bracket_slate_single: item[24],
// takashima_slate_bracket_slate_single_memo: item[25],
// df_metal_bracket: item[26],
// df_metal_bracket_memo: item[27],
// slate_metal_bracket: item[28],
// slate_metal_bracket_memo: item[29],
// takashima_slate_bracket_metal_roof: item[30],
// takashima_slate_bracket_metal_roof_memo: item[31],
// })
// })
// const response = await axiosInstance(null).post<Suitable[]>('/api/suitable', suitableData)
// return response.data
// },
}

View File

@ -1,127 +0,0 @@
import { axiosInstance } from '@/libs/axios'
export interface SurveySalesBasicInfo {
id?: number
representative: string
store: string | null
construction_point: string | null
investigation_date: string | null
building_name: string | null
customer_name: string | null
post_code: string | null
address: string | null
address_detail: string | null
submission_status: boolean
submission_date?: string | null
detail_info?: SurveySalesDetailInfo | null
}
export interface SurveySalesDetailInfo {
id?: number
contract_capacity: string | null
retail_company: string | null
supplementary_facilities: number | null
supplementary_facilities_etc: string | null
installation_system: number | null
installation_system_etc: string | null
construction_year: number | null
construction_year_etc: string | null
roof_material: number | null
roof_material_etc: string | null
roof_shape: number | null
roof_shape_etc: string | null
roof_slope: string | null
house_structure: number | null
house_structure_etc: string | null
rafter_material: number | null
rafter_material_etc: string | null
rafter_size: number | null
rafter_size_etc: string | null
rafter_pitch: number | null
rafter_pitch_etc: string | null
rafter_direction: number | null
open_field_plate_kind: number | null
open_field_plate_kind_etc: string | null
open_field_plate_thickness: string | null
leak_trace: boolean | null
waterproof_material: number | null
waterproof_material_etc: string | null
insulation_presence: number | null
insulation_presence_etc: string | null
structure_order: number | null
structure_order_etc: string | null
installation_availability: number | null
installation_availability_etc: string | null
memo: string | null
}
export const surveySalesApi = {
create: async (data: SurveySalesBasicInfo): Promise<number> => {
try {
const response = await axiosInstance(null).post<SurveySalesBasicInfo>('/api/survey-sales', data)
return response.data.id ?? 0
} catch (error) {
console.error(error)
return 0
}
},
getList: async (): Promise<SurveySalesBasicInfo[] | []> => {
try {
const response = await axiosInstance(null).get<SurveySalesBasicInfo[]>('/api/survey-sales')
return response.data
} catch (error) {
console.error(error)
return []
}
},
getDetail: async (id: number): Promise<SurveySalesBasicInfo | null> => {
try {
const response = await axiosInstance(null).get<SurveySalesBasicInfo>(`/api/survey-sales/${id}`)
return response.data
} catch (error) {
console.error(error)
return null
}
},
update: async (id: number, data: SurveySalesBasicInfo): Promise<SurveySalesBasicInfo | null> => {
try {
const response = await axiosInstance(null).put<SurveySalesBasicInfo>(`/api/survey-sales/${id}`, data)
return response.data
} catch (error) {
console.error(error)
return null
}
},
delete: async (id: number, isDetail: boolean = false): Promise<boolean> => {
try {
await axiosInstance(null).delete(`/api/survey-sales/${id}`, {
params: {
detail_id: isDetail ? id : undefined,
},
})
return true
} catch (error) {
throw error
}
},
createDetail: async (surveyId: number, data: SurveySalesDetailInfo): Promise<boolean> => {
try {
await axiosInstance(null).post<SurveySalesDetailInfo>(`/api/survey-sales/${surveyId}`, data)
return true
} catch (error) {
throw error
}
},
confirm: async (id: number): Promise<boolean> => {
try {
await axiosInstance(null).patch<SurveySalesBasicInfo>(`/api/survey-sales/${id}`)
return true
} catch (error) {
throw error
}
},
// update: async (data: SurveySalesBasicInfo): Promise<SurveySalesBasicInfo> => {
// const response = await axiosInstance.put<SurveySalesBasicInfo>(`/api/survey-sales`, data)
// return response.data
// },
}

View File

@ -1,37 +0,0 @@
import { axiosInstance } from '@/libs/axios'
export interface UserData {
username: string
email: string
password: string
}
export interface User {
id: number
username: string
email: string
created_at: string
updated_at: string
}
export interface LoginData {
username: string
password: string
}
export const userApi = {
create: async (data: UserData): Promise<User> => {
const response = await axiosInstance(null).post<User>('/api/user/create', data)
return response.data
},
getList: async (): Promise<User[]> => {
const response = await axiosInstance(null).get<User[]>('/api/user/list')
return response.data
},
getUser: async (data: LoginData): Promise<User> => {
const response = await axiosInstance(null).post<User>(`/api/user`, data)
return response.data
},
}

View File

@ -1,7 +1,8 @@
import { NextResponse } from 'next/server'
import { loggerWrapper } from '@/libs/api-wrapper'
import { axiosInstance } from '@/libs/axios'
export async function POST(req: Request) {
async function setChgPwd(req: Request): Promise<NextResponse> {
const { loginId, email, pwd, chgPwd } = await req.json()
console.log('🚀 ~ POST ~ loginId:', loginId)
console.log('🚀 ~ POST ~ email:', email)
@ -19,3 +20,5 @@ export async function POST(req: Request) {
return NextResponse.json({ code: 200, data: result.data })
}
export const POST = loggerWrapper(setChgPwd)

View File

@ -1,8 +1,9 @@
import { NextRequest, NextResponse } from 'next/server'
import { loggerWrapper } from '@/libs/api-wrapper'
import { prisma } from '@/libs/prisma'
import type { CommCode } from '@/types/CommCode'
export async function GET(request: NextRequest) {
async function getCommCode(request: NextRequest): Promise<NextResponse> {
try {
const searchParams = request.nextUrl.searchParams
const headCode = searchParams.get('headCode')
@ -20,24 +21,26 @@ export async function GET(request: NextRequest) {
if (!headCd) {
return NextResponse.json({ error: `${headCode}를 찾을 수 없습니다` }, { status: 404 })
}
// @ts-ignore
const roofMaterials: CommCode[] = await prisma.BC_COMM_L.findMany({
where: {
HEAD_CD: headCd.HEAD_CD,
},
select: {
HEAD_CD: true,
CODE: true,
CODE_JP: true,
},
orderBy: {
CODE: 'asc',
},
})
if (headCode === 'SALES_OFFICE_CD') {
return getSaleOffice(headCd.HEAD_CD)
} else {
// @ts-ignore
const roofMaterials: CommCode[] = await prisma.BC_COMM_L.findMany({
where: {
HEAD_CD: headCd.HEAD_CD,
},
select: {
HEAD_CD: true,
CODE: true,
CODE_JP: true,
},
orderBy: {
CODE: 'asc',
},
})
return NextResponse.json(roofMaterials)
}
return NextResponse.json(roofMaterials)
} catch (error) {
console.error('❌ 데이터 조회 중 오류가 발생했습니다:', error)
return NextResponse.json({ error: '데이터 조회 중 오류가 발생했습니다' }, { status: 500 })
@ -60,3 +63,5 @@ const getSaleOffice = async (headCode: string) => {
})
return NextResponse.json(commCodeSaleOffice)
}
export const GET = loggerWrapper(getCommCode)

View File

@ -1,8 +1,62 @@
import { queryStringFormatter } from '@/utils/common-utils'
import axios from 'axios'
import { NextResponse } from 'next/server'
import { loggerWrapper } from '@/libs/api-wrapper'
export async function GET(request: Request) {
/**
* @api {GET} /api/qna/detail API
* @apiName GET /api/qna/detail
* @apiGroup Qna
* @apiDescription API
*
* @apiParam {String} compCd
* @apiParam {String} qnaNo
* @apiParam {String} langCd
* @apiParam {String} loginId ID
*
* @apiExample {curl} Example usage:
* curl -X GET http://localhost:3000/api/qna/detail
*
* @apiSuccessExample {json} Success-Response:
* {
* "data": {
"compCd": "5200",
"qnaNo": 51,
"qstTitle": "Q.CAST TEST",
"qstContents": "Q.CAST TEST CONTENTS",
"regDt": "2025.04.29 16:16:51",
"regId": "X112",
"regNm": "株式会社アイ工務店",
"regEmail": "x112@interplug.co.kr",
"answerYn": "N",
"ansContents": null,
"ansRegDt": null,
"ansRegNm": null,
"ansListFile": null,
"storeId": "X112",
"storeNm": "株式会社アイ工務店",
"regUserNm": "TEST",
"regUserTelNo": "010-1111-1111",
"qnaClsLrgCd": "A01",
"qnaClsMidCd": "B02",
"qnaClsSmlCd": "C05",
"listFile": [
{
"fileNo": 853
"encodeFileNo": 853,
"srcFileNm": "Quotation_4500380_20240808145129.pdf",
"fileCours": "/temp/20250428/"
"fileSize":160982,
"regDt":"2024.08.13"
}
...
],
...
},
* @apiError {Number} 401 ( )
* @apiError {Number} 500
*/
async function getQnaDetail(request: Request): Promise<NextResponse> {
const { searchParams } = new URL(request.url)
const params = {
compCd: searchParams.get('compCd'),
@ -22,3 +76,5 @@ export async function GET(request: Request) {
return NextResponse.json({ error: 'route error' }, { status: 500 })
}
}
export const GET = loggerWrapper(getQnaDetail)

View File

@ -1,5 +1,6 @@
import axios from 'axios'
import { NextResponse } from 'next/server'
import { loggerWrapper } from '@/libs/api-wrapper'
// export async function GET(request: Request) {
// const { searchParams } = new URL(request.url)
@ -38,7 +39,7 @@ import { NextResponse } from 'next/server'
// }
// }
export async function GET(request: Request) {
async function downloadFile(request: Request): Promise<NextResponse> {
const { searchParams } = new URL(request.url)
const encodeFileNo = searchParams.get('encodeFileNo')
const srcFileNm = searchParams.get('srcFileNm') || 'downloaded-file'
@ -71,3 +72,5 @@ export async function GET(request: Request) {
return NextResponse.json({ error: error.response?.data || 'Failed to download file' }, { status: 500 })
}
}
export const GET = loggerWrapper(downloadFile)

View File

@ -1,8 +1,65 @@
import axios from 'axios'
import { NextResponse } from 'next/server'
import { queryStringFormatter } from '@/utils/common-utils'
import { getIronSession } from 'iron-session'
import { cookies } from 'next/headers'
import { loggerWrapper } from '@/libs/api-wrapper'
import { sessionOptions } from '@/libs/session'
import { SessionData } from '@/types/Auth'
/**
* @api {GET} /api/qna/list API
* @apiName GET /api/qna/list
* @apiGroup Qna
* @apiDescription API
*
* @apiParam {String} compCd
* @apiParam {String} langCd
* @apiParam {String} storeId ID
* @apiParam {String} siteTpCd
* @apiParam {String} schTitle
* @apiParam {String} schRegId ID
* @apiParam {String} schFromDt
* @apiParam {String} schToDt
* @apiParam {String} schAnswerYn
* @apiParam {String} loginId ID
*
* @apiExample {curl} Example usage:
* curl -X GET http://localhost:3000/api/qna/list
*
* @apiSuccessExample {json} Success-Response:
* {
* "data": [
{
"totCnt": 1,
"rowNumber": 1,
"compCd": "5200",
"qnaNo": 51,
"qstTitle": "Q.CAST TEST22",
"regDt": "2025.05.12",
"regId": "X112",
"regNm": "株式会社アイ工務店",
"answerYn": "N",
"attachYn": null,
"qnaClsLrgCd": "見積関連",
"qnaClsMidCd": "構造設置可否",
"qnaClsSmlCd": "C05 未定2",
"regUserNm": "Test"
},
...
],
}
* @apiError {Number} 500
* @apiError {Number} 401 ( )
*/
async function getQnaList(request: Request): Promise<NextResponse> {
const cookieStore = await cookies()
const session = await getIronSession<SessionData>(cookieStore, sessionOptions)
if (!session.isLoggedIn) {
return NextResponse.json({ error: 'ログインしていません。' }, { status: 401 })
}
export async function GET(request: Request) {
const { searchParams } = new URL(request.url)
const params: Record<string, string> = {}
@ -26,3 +83,5 @@ export async function GET(request: Request) {
return NextResponse.json({ error: 'route error' }, { status: 500 })
}
}
export const GET = loggerWrapper(getQnaList)

View File

@ -1,8 +1,37 @@
import { NextResponse } from 'next/server'
import axios from 'axios'
import { CommonCode } from '@/types/Inquiry'
import { loggerWrapper } from '@/libs/api-wrapper'
export async function GET() {
/**
* @api {GET} /api/qna API
* @apiName GET /api/qna
* @apiGroup Qna
* @apiDescription API
*
* @apiSuccess {Object} data
* @apiSuccess {String} data.headCd
* @apiSuccess {String} data.code
* @apiSuccess {String} data.codeJp -
* @apiSuccess {String} data.refChr1 -
*
* @apiExample {curl} Example usage:
* curl -X GET http://localhost:3000/api/qna
*
* @apiSuccessExample {json} Success-Response:
* {
* "data": [
* {
* "headCd": "204200",
* "code": "1",
* "codeJp": "1",
* "refChr1": "1"
* }
* ],
* ...
* }
*/
async function getCommonCodeListData(request: Request): Promise<NextResponse> {
const response = await axios.get(`${process.env.NEXT_PUBLIC_INQUIRY_API_URL}/api/system/commonCodeListData`)
const codeList: CommonCode[] = []
response.data.data.apiCommCdList.forEach((item: any) => {
@ -17,3 +46,5 @@ export async function GET() {
})
return NextResponse.json({ data: codeList })
}
export const GET = loggerWrapper(getCommonCodeListData)

View File

@ -1,7 +1,29 @@
import axios from 'axios'
import { NextResponse } from 'next/server'
import { loggerWrapper } from '@/libs/api-wrapper'
export async function POST(request: Request) {
/**
* @api {POST} /api/qna/save API
* @apiName POST /api/qna/save
* @apiGroup Qna
* @apiDescription API
*
* @apiBody {InquiryRequest} inquiryRequest
*
* @apiExample {curl} Example usage:
* curl -X POST http://localhost:3000/api/qna/save
*
* @apiSuccessExample {json} Success-Response:
* {
* "data" : {
* "cnt": 1,
* "qnoNo": 1,
* "mailYn": "Y"
* },
* },
* @apiError {Number} 500
*/
async function setQna(request: Request): Promise<NextResponse> {
const formData = await request.formData()
console.log(formData)
try {
@ -19,3 +41,5 @@ export async function POST(request: Request) {
return NextResponse.json({ error: 'Failed to save qna' }, { status: 500 })
}
}
export const POST = loggerWrapper(setQna)

View File

@ -0,0 +1,39 @@
import { prisma } from '@/libs/prisma'
import { NextRequest, NextResponse } from 'next/server'
import { loggerWrapper } from '@/libs/api-wrapper'
import { SubmitTargetResponse } from '@/types/Survey'
// 2차점이 자신에게 매핑 된 1차 판매점과 관리자 정보 조회
async function getSubMissionAdminSub(request: NextRequest): Promise<NextResponse> {
try {
const { searchParams } = new URL(request.url)
const id = searchParams.get('id')
const query = `
OPEN SYMMETRIC KEY SYMMETRICKEY DECRYPTION BY CERTIFICATE CERTI_QSPJP;
SELECT
MCS.STORE_ID AS targetStoreId
, MCS.STORE_QCAST_NM AS targetStoreNm
, MCP.EOS_LOGIN_ID AS repUserId
, CONVERT(NVARCHAR(100), DecryptByKey(MCP.EMAIL)) AS repUserEmail
, MCP.AUTHORITY AS auth
FROM MS_CUST_STOREID MCS WITH(NOLOCK)
LEFT OUTER JOIN MS_CUST_PERSON MCP WITH(NOLOCK)
ON MCS.COMP_CD = MCP.COMP_CD
AND MCS.STORE_ID = MCP.STORE_ID
AND MCP.DEL_YN = 'N'
WHERE MCS.COMP_CD = '5200'
AND MCS.STORE_ID = (SELECT STORE_ID FROM MS_CUST_AGENCY_STOREID WHERE AGENCY_STORE_ID = '${id}' AND DEL_YN = 'N')
AND MCP.EMAIL IS NOT NULL
AND MCS.DEL_YN = 'N';
CLOSE SYMMETRIC KEY SYMMETRICKEY;
`
const data: SubmitTargetResponse[] = await prisma.$queryRawUnsafe(query)
return NextResponse.json(data)
} catch (error) {
console.error('❌ 데이터 조회 중 오류가 발생했습니다:', error)
return NextResponse.json({ error: 'データの取得に失敗しました。' }, { status: 500 })
}
}
export const GET = loggerWrapper(getSubMissionAdminSub)

View File

@ -0,0 +1,48 @@
import { prisma } from '@/libs/prisma'
import { NextRequest, NextResponse } from 'next/server'
import { loggerWrapper } from '@/libs/api-wrapper'
type SuperPerson = {
storeId: string
salesOfficeCd: string
fromEmail: string
toEmail: string
}
async function getSubmissionAdmin(request: NextRequest): Promise<NextResponse> {
try {
const { searchParams } = new URL(request.url)
const id = searchParams.get('id')
const query = `
OPEN SYMMETRIC KEY SYMMETRICKEY DECRYPTION BY CERTIFICATE CERTI_QSPJP;
SELECT
MCSA.STORE_ID
, BCL.CODE AS SALES_OFFICE_CD
, REF_CHR1 AS FROM_E_MAIL
, REF_CHR2 AS TO_E_MAIL
FROM MS_CUST_STOREID_ADDITNL MCSA WITH(NOLOCK)
LEFT OUTER JOIN IF_PERSON_OFFICE_MAPPING IPOM WITH(NOLOCK)
ON MCSA.KAM_ID = IPOM.LIFNR
AND IF_STS = 'R'
AND VKBUR IS NOT NULL
AND VKBUR != ''
INNER JOIN BC_COMM_L BCL WITH(NOLOCK)
ON BCL.CODE = IPOM.VKBUR
AND BCL.HEAD_CD = '103200'
AND BCL.DEL_YN = 'N'
WHERE MCSA.COMP_CD = '5200'
AND MCSA.STORE_ID = 'A03'
AND MCSA.DEL_YN = 'N'
;
CLOSE SYMMETRIC KEY SYMMETRICKEY;
`
const data: SuperPerson[] = await prisma.$queryRawUnsafe(query)
return NextResponse.json(data)
} catch (error) {
console.error('❌ 데이터 조회 중 오류가 발생했습니다:', error)
return NextResponse.json({ error: 'データの取得に失敗しました。' }, { status: 500 })
}
}
export const GET = loggerWrapper(getSubmissionAdmin)

View File

@ -0,0 +1,41 @@
import { prisma } from '@/libs/prisma'
import { SubmitTargetResponse } from '@/types/Survey'
import { NextRequest, NextResponse } from 'next/server'
import { loggerWrapper } from '@/libs/api-wrapper'
// 2차점의 시공권한 user가 해당 판매점의 관리자 정보 조회
// N == 일반유저, S == 수퍼유저, B == 시공권한유저
async function getSubmissionBuilder(request: NextRequest): Promise<NextResponse> {
try {
const { searchParams } = new URL(request.url)
const id = searchParams.get('id')
const query = `
OPEN SYMMETRIC KEY SYMMETRICKEY DECRYPTION BY CERTIFICATE CERTI_QSPJP;
SELECT
MCAS.AGENCY_STORE_ID AS targetStoreId
, MCAS.AGENCY_QCAST_NM AS targetStoreNm
, BQU.USER_ID AS repUserId
, CONVERT(NVARCHAR(100), DecryptByKey(BQU.EMAIL)) AS repUserEmail
, BQU.USER_AUTH_CD AS auth
FROM MS_CUST_AGENCY_STOREID MCAS WITH(NOLOCK)
LEFT OUTER JOIN BC_QM_USER BQU WITH(NOLOCK)
ON MCAS.COMP_CD = BQU.COMP_CD
AND MCAS.AGENCY_STORE_ID = BQU.AGENCY_STORE_ID
AND MCAS.DEL_YN = 'N'
WHERE MCAS.COMP_CD = '5200'
AND MCAS.AGENCY_STORE_ID = '${id}'
AND BQU.EMAIL IS NOT NULL
AND BQU.USER_AUTH_CD != 'B'
AND MCAS.DEL_YN = 'N';
CLOSE SYMMETRIC KEY SYMMETRICKEY;
`
const data: SubmitTargetResponse[] = await prisma.$queryRawUnsafe(query)
return NextResponse.json(data)
} catch (error) {
console.error('❌ 데이터 조회 중 오류가 발생했습니다:', error)
return NextResponse.json({ error: 'データの取得に失敗しました。' }, { status: 500 })
}
}
export const GET = loggerWrapper(getSubmissionBuilder)

View File

@ -0,0 +1,41 @@
import { prisma } from '@/libs/prisma'
import { NextRequest, NextResponse } from 'next/server'
import { loggerWrapper } from '@/libs/api-wrapper'
type SuperPerson = {
storeId: string
userId: string
eMail: string
}
async function getSubmissionSuper(request: NextRequest): Promise<NextResponse> {
try {
const { searchParams } = new URL(request.url)
const id = searchParams.get('id')
const query = `
OPEN SYMMETRIC KEY SYMMETRICKEY DECRYPTION BY CERTIFICATE CERTI_QSPJP;
SELECT
MCSA.STORE_ID
, BU.USER_ID
, CONVERT(NVARCHAR(100), DecryptByKey(BU.E_MAIL)) AS E_MAIL
FROM MS_CUST_STOREID_ADDITNL MCSA WITH(NOLOCK)
LEFT OUTER JOIN BC_USER bu WITH(NOLOCK)
ON MCSA.COMP_CD = BU.COMP_CD
AND MCSA.KAM_ID = BU.KAM_ID
AND BU.STAT_CD = 'A'
AND BU.DEL_YN = 'N'
WHERE MCSA.COMP_CD = '5200'
AND MCSA.STORE_ID = 'A03'
AND MCSA.DEL_YN = 'N';
CLOSE SYMMETRIC KEY SYMMETRICKEY;
`
const data: SuperPerson[] = await prisma.$queryRawUnsafe(query)
return NextResponse.json(data)
} catch (error) {
console.error('❌ 데이터 조회 중 오류가 발생했습니다:', error);
return NextResponse.json({ error: 'データの取得に失敗しました。' }, { status: 500 });
}
}
export const GET = loggerWrapper(getSubmissionSuper)

View File

@ -1,20 +1,61 @@
import { NextRequest, NextResponse } from 'next/server'
import { HttpStatusCode } from 'axios'
import { loggerWrapper } from '@/libs/api-wrapper'
import { prisma } from '@/libs/prisma'
import { type Suitable } from '@/types/Suitable'
export async function GET(request: NextRequest) {
/**
* @api {get} /api/suitable/list API
* @apiName GetSuitableList
* @apiGroup Suitable
*
* @apiDescription
*
*
* @apiParam {Number} pageNumber
* @apiParam {Number} itemPerPage
* @apiParam {String} [category] (: RMG001)
* @apiParam {String} [keyword]
*
* @apiExample {curl} Example usage:
* curl -X GET \
* -G "pageNumber=1" \
* -G "itemPerPage=10" \
* -G "category=RMG001" \
* -G "keyword=검색키워드" \
* http://localhost:3000/api/suitable/list
*
* @apiSuccess {Array} suitable
* @apiSuccessExample {json} Success-Response:
* [
* {
* "id": 1,
* "product_name": "test",
* "detail_cnt": 1,
* "detail": [
* {
* "id": 1,
* "trestle_mfpc_cd": "test",
* "trestle_manufacturer_product_name": "test",
* "memo": "test"
* }
* ]
* }
* ]
*/
async function getSuitableList(request: NextRequest): Promise<NextResponse> {
try {
const searchParams = request.nextUrl.searchParams
const pageNumber = parseInt(searchParams.get('pageNumber') || '0')
const itemPerPage = parseInt(searchParams.get('itemPerPage') || '0')
if (pageNumber === 0 || itemPerPage === 0) {
return NextResponse.json({ error: '페이지 번호와 페이지당 아이템 수가 필요합니다' }, { status: 400 })
}
const category = searchParams.get('category')
const keyword = searchParams.get('keyword')
/* 파라미터 체크 */
if (pageNumber === 0 || itemPerPage === 0) {
return NextResponse.json({ error: '페이지 번호와 페이지당 아이템 수가 필요합니다' }, { status: HttpStatusCode.BadRequest })
}
let query = `
SELECT
msm.id
@ -48,7 +89,7 @@ export async function GET(request: NextRequest) {
FETCH NEXT @P2 ROWS ONLY;
`
// 검색 조건 설정
/* 검색 조건 설정 */
if (category) {
const roofMtQuery = `
SELECT roof_mt_cd
@ -65,11 +106,16 @@ export async function GET(request: NextRequest) {
const suitable: Suitable[] = await prisma.$queryRawUnsafe(query, pageNumber, itemPerPage)
// console.log(`검색 조건 :::: 카테고리: ${category}, 키워드: ${keyword}`)
return NextResponse.json(suitable)
return NextResponse.json(suitable, {
headers: {
'spinner-state': 'true',
},
status: HttpStatusCode.Ok,
})
} catch (error) {
console.error('❌ 데이터 조회 중 오류가 발생했습니다:', error)
return NextResponse.json({ error: '데이터 조회 중 오류가 발생했습니다' }, { status: 500 })
console.error(`데이터 조회 중 오류가 발생했습니다: ${error}`)
return NextResponse.json({ error: `데이터 조회 중 오류가 발생했습니다: ${error}` }, { status: HttpStatusCode.InternalServerError })
}
}
export const GET = loggerWrapper(getSuitableList)

View File

@ -1,20 +1,44 @@
import React from 'react'
import { NextRequest, NextResponse } from 'next/server'
import { HttpStatusCode } from 'axios'
import { pdf, Document } from '@react-pdf/renderer'
import { PDFDocument } from 'pdf-lib'
import { loggerWrapper } from '@/libs/api-wrapper'
import { prisma } from '@/libs/prisma'
import { type Suitable } from '@/types/Suitable'
import SuitablePdf from '@/components/pdf/SuitablePdf'
export async function POST(request: NextRequest) {
// 파라미터 체크
/**
* @api {post} /api/suitable/pdf PDF API
* @apiName CreateSuitablePdf
* @apiGroup Suitable
*
* @apiDescription
* PDF
*
* @apiBody {FormData} form-data
* @apiBody {String} form-data.ids ID ( )
* @apiBody {String} form-data.detailIds ID ( )
* @apiBody {String} form-data.fileTitle PDF
*
* @apiExample {curl} Example usage:
* curl -X POST \
* -F "ids=1,2,3" \
* -F "detailIds=4,5,6" \
* -F "fileTitle=적합성조사보고서" \
* http://localhost:3000/api/suitable/pdf
*
* @apiSuccess {File} PDF
*/
async function createSuitablePdf(request: NextRequest): Promise<NextResponse> {
const formData = await request.formData()
const ids = formData.get('ids') as string
const detailIds = formData.get('detailIds') as string
const fileTitle = formData.get('fileTitle') as string
/* 파라미터 체크 */
if (ids === '' || detailIds === '' || fileTitle === '') {
return NextResponse.json({ error: '필수 파라미터가 누락되었습니다' }, { status: 400 })
return NextResponse.json({ error: '필수 파라미터가 누락되었습니다' }, { status: HttpStatusCode.BadRequest })
}
try {
@ -59,14 +83,14 @@ export async function POST(request: NextRequest) {
ORDER BY msm.product_name;
`
// 검색 조건 설정
/* 검색 조건 설정 */
query = query.replaceAll(':mainIds', ids)
query = query.replaceAll(':detailIds', detailIds)
// 데이터 조회
/* 데이터 조회 */
const suitable: Suitable[] = await prisma.$queryRawUnsafe(query)
// pdf 생성 : mainId 100개씩 청크로 나누기
/* pdf 생성 : mainId 100개씩 청크로 나누기 */
const CHUNK_SIZE = 100
const pdfBuffers: Uint8Array[] = []
for (let i = 0; i < suitable.length; i += CHUNK_SIZE) {
@ -85,7 +109,7 @@ export async function POST(request: NextRequest) {
pdfBuffers.push(new Uint8Array(arrayBuffer))
}
// 모든 PDF 버퍼 병합
/* 모든 PDF 버퍼 병합 */
const mergedPdfBytes = await mergePdfBuffers(pdfBuffers)
const fileName = `${fileTitle.replace(' ', '_')}.pdf`
@ -98,11 +122,16 @@ export async function POST(request: NextRequest) {
},
})
} catch (error) {
console.error('❌ 데이터 조회 중 오류가 발생했습니다:', error)
return NextResponse.json({ error: '데이터 조회 중 오류가 발생했습니다' }, { status: 500 })
console.error(`데이터 조회 중 오류가 발생했습니다: ${error}`)
return NextResponse.json({ error: `데이터 조회 중 오류가 발생했습니다: ${error}` }, { status: HttpStatusCode.InternalServerError })
}
}
/**
* @description PDF
* @param buffers PDF
* @returns PDF
*/
async function mergePdfBuffers(buffers: Uint8Array[]) {
const mergedPdf = await PDFDocument.create()
@ -115,3 +144,5 @@ async function mergePdfBuffers(buffers: Uint8Array[]) {
const mergedPdfBytes = await mergedPdf.save()
return mergedPdfBytes
}
export const POST = loggerWrapper(createSuitablePdf)

View File

@ -1,7 +1,35 @@
import { NextRequest, NextResponse } from 'next/server'
import { HttpStatusCode } from 'axios'
import { loggerWrapper } from '@/libs/api-wrapper'
import { prisma } from '@/libs/prisma'
export async function GET(request: NextRequest) {
/**
* @api {get} /api/suitable/pick API
* @apiName GetSuitablePick
* @apiGroup Suitable
*
* @apiDescription
* main_id와 detail_id를
*
* @apiParam {String} [category] (: RMG001)
* @apiParam {String} [keyword]
*
* @apiExample {curl} Example usage:
* curl -X GET \
* -G "category=RMG001" \
* -G "keyword=검색키워드" \
* http://localhost:3000/api/suitable/pick
*
* @apiSuccess {Array} suitableIdSet
* @apiSuccessExample {json} Success-Response:
* [
* {
* "id": 1,
* "detail_id": "1,2,3"
* }
* ]
*/
async function getSuitablePick(request: NextRequest): Promise<NextResponse> {
try {
const searchParams = request.nextUrl.searchParams
const category = searchParams.get('category')
@ -26,7 +54,7 @@ export async function GET(request: NextRequest) {
;
`
// 검색 조건 설정
/* 검색 조건 설정 */
if (category) {
const roofMtQuery = `
SELECT roof_mt_cd
@ -45,7 +73,9 @@ export async function GET(request: NextRequest) {
return NextResponse.json(suitableIdSet)
} catch (error) {
console.error('❌ 데이터 조회 중 오류가 발생했습니다:', error)
return NextResponse.json({ error: '데이터 조회 중 오류가 발생했습니다' }, { status: 500 })
console.error(`데이터 조회 중 오류가 발생했습니다: ${error}`)
return NextResponse.json({ error: `데이터 조회 중 오류가 발생했습니다: ${error}` }, { status: HttpStatusCode.InternalServerError })
}
}
export const GET = loggerWrapper(getSuitablePick)

View File

@ -1,15 +1,56 @@
import { NextRequest, NextResponse } from 'next/server'
import { HttpStatusCode } from 'axios'
import { loggerWrapper } from '@/libs/api-wrapper'
import { prisma } from '@/libs/prisma'
import { Suitable } from '@/types/Suitable'
export async function POST(request: NextRequest) {
/**
* @api {post} /api/suitable API
* @apiName GetSuitable
* @apiGroup Suitable
*
* @apiDescription
*
*
* @apiBody {FormData} form-data
* @apiBody {String} form-data.ids ID ( )
* @apiBody {String} [form-data.detailIds] ID ( )
*
* @apiExample {curl} Example usage:
* curl -X POST \
* -F "ids=1,2,3" \
* -F "detailIds=4,5,6" \
* http://localhost:3000/api/suitable
*
* @apiSuccess {Array} suitable
* @apiSuccessExample {json} Success-Response:
* [
* {
* "id": 1,
* "product_name": "test",
* "manu_ft_cd": "test",
* "roof_mt_cd": "test",
* "roof_sh_cd": "test",
* "detail": [
* {
* "id": 1,
* "trestle_mfpc_cd": "MFPC001",
* "trestle_manufacturer_product_name": "test",
* "memo": "test"
* }
* ]
* }
* ]
*/
async function getSuitable(request: NextRequest): Promise<NextResponse> {
try {
const body: Record<string, string> = await request.json()
const ids = body.ids
const detailIds = body.detailIds
const detailIds = body.detailIds || ''
if (ids === '' || detailIds === '') {
return NextResponse.json({ error: '필수 파라미터가 누락되었습니다' }, { status: 400 })
/* 파라미터 체크 */
if (ids === '') {
return NextResponse.json({ error: '필수 파라미터가 누락되었습니다' }, { status: HttpStatusCode.BadRequest })
}
let query = `
@ -32,7 +73,7 @@ export async function POST(request: NextRequest) {
, msd_json.memo
FROM ms_suitable_detail msd_json
WHERE msd.main_id = msd_json.main_id
AND msd_json.id IN (:detailIds)
--detailIds AND msd_json.id IN (:detailIds)
FOR JSON PATH
) AS detail
FROM ms_suitable_detail msd
@ -45,15 +86,20 @@ export async function POST(request: NextRequest) {
ORDER BY msm.product_name;
`
// 검색 조건 설정
/* 검색 조건 설정 */
query = query.replaceAll(':mainIds', ids)
query = query.replaceAll(':detailIds', detailIds)
if (detailIds) {
query = query.replace('--detailIds ', '')
query = query.replace(':detailIds', detailIds)
}
const suitable: Suitable[] = await prisma.$queryRawUnsafe(query)
return NextResponse.json(suitable)
} catch (error) {
console.error('❌ 데이터 조회 중 오류가 발생했습니다:', error)
return NextResponse.json({ error: '데이터 조회 중 오류가 발생했습니다' }, { status: 500 })
console.error(`데이터 조회 중 오류가 발생했습니다: ${error}`)
return NextResponse.json({ error: `데이터 조회 중 오류가 발생했습니다: ${error}` }, { status: HttpStatusCode.InternalServerError })
}
}
export const POST = loggerWrapper(getSuitable)

View File

@ -1,100 +1,172 @@
import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/libs/prisma'
import { convertToSnakeCase } from '@/utils/common-utils'
import { getIronSession } from 'iron-session'
import { sessionOptions } from '@/libs/session'
import { cookies } from 'next/headers'
import type { SessionData } from '@/types/Auth'
import { Prisma } from '@prisma/client'
import { loggerWrapper } from '@/libs/api-wrapper'
interface Survey {
SRL_NO: string
SUBMISSION_STATUS: boolean
SUBMISSION_TARGET_ID: string | null
STORE_ID: string | null
CONSTRUCTION_POINT_ID: string | null
}
/**
* @description
*/
const ERROR_MESSAGES = {
NOT_FOUND: 'データが見つかりません。',
UNAUTHORIZED: 'Unauthorized',
NO_PERMISSION: '該当物件の照会権限がありません。',
FETCH_ERROR: 'データの取得に失敗しました。',
} as const
interface SessionParams {
role: string | null
storeId: string | null
builderId: string | null
isLoggedIn: string | null
}
/**
* @description T01
* @param {any} survey
* @returns {boolean}
*/
const checkT01Role = (survey: any): boolean => survey.SRL_NO !== '一時保存'
const checkT01Role = (survey: Survey): boolean => survey.SRL_NO !== '一時保存'
const checkAdminRole = (survey: Survey, storeId: string | null): boolean => {
/**
* @description Admin (1 )
* @param {any} survey
* @param {string | null} storeId ID
* @returns {boolean}
*/
const checkAdminRole = (survey: any, storeId: string | null): boolean => {
if (!storeId) return false
if (survey.SUBMISSION_STATUS) {
return survey.SUBMISSION_TARGET_ID === storeId || survey.STORE_ID === storeId
}
return survey.STORE_ID === storeId
return survey.SUBMISSION_STATUS ? survey.SUBMISSION_TARGET_ID === storeId || survey.STORE_ID === storeId : survey.STORE_ID === storeId
}
const checkAdminSubRole = (survey: Survey, storeId: string | null): boolean => {
/**
* @description Admin_Sub (2 )
* @param {any} survey
* @param {string | null} storeId ID
* @returns {boolean}
*/
const checkAdminSubRole = (survey: any, storeId: string | null): boolean => {
if (!storeId) return false
if (survey.SUBMISSION_STATUS) {
return survey.SUBMISSION_TARGET_ID === storeId || (survey.STORE_ID === storeId && survey.CONSTRUCTION_POINT_ID === null)
}
return survey.STORE_ID === storeId && survey.CONSTRUCTION_POINT_ID === null
return survey.SUBMISSION_STATUS
? survey.SUBMISSION_TARGET_ID === storeId || (survey.STORE_ID === storeId && !survey.CONSTRUCTION_POINT_ID)
: survey.STORE_ID === storeId && !survey.CONSTRUCTION_POINT_ID
}
const checkPartnerOrBuilderRole = (survey: Survey, builderId: string | null): boolean => {
/**
* @description Partner () Builder (2 )
* @param {any} survey
* @param {string | null} builderId ID
* @returns {boolean}
*/
const checkPartnerOrBuilderRole = (survey: any, builderId: string | null): boolean => {
if (!builderId) return false
return survey.CONSTRUCTION_POINT_ID === builderId
}
const checkRole = (survey: Survey, sessionParams: SessionParams): boolean => {
if (!survey || !sessionParams.role) return false
/**
* @description
* @param {any} survey
* @param {any} session
* @returns {boolean}
*/
const checkRole = (survey: any, session: any): boolean => {
if (!survey || !session.isLoggedIn) return false
switch (sessionParams.role) {
case 'T01':
return checkT01Role(survey)
// T01 이외 1차점
case 'Admin':
return checkAdminRole(survey, sessionParams.storeId)
// 2차점
case 'Admin_Sub':
return checkAdminSubRole(survey, sessionParams.storeId)
// partner
case 'Partner':
// 2차점 시공권한 user
case 'Builder':
return checkPartnerOrBuilderRole(survey, sessionParams.builderId)
default:
return false
const roleChecks = {
T01: () => checkT01Role(survey),
Admin: () => checkAdminRole(survey, session.storeId),
Admin_Sub: () => checkAdminSubRole(survey, session.storeId),
Partner: () => checkPartnerOrBuilderRole(survey, session.builderId),
Builder: () => checkPartnerOrBuilderRole(survey, session.builderId),
}
return roleChecks[session.role as keyof typeof roleChecks]?.() ?? false
}
export async function GET(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
/**
* @description
* @param {number} id ID
* @returns {Promise<any>}
*/
const fetchSurvey = async (id: number) => {
// @ts-ignore
return await prisma.SD_SURVEY_SALES_BASIC_INFO.findFirst({
where: { ID: id },
include: { DETAIL_INFO: true },
})
}
/**
* @api {GET} /api/survey-sales/:id API
* @apiName GET /api/survey-sales/:id
* @apiGroup SurveySales
* @apiDescription API
*
* @apiParam {Number} id PRIMARY KEY ID (required)
* @apiParam {Boolean} isPdf pdf (optional, default: false)
*
* @apiSuccess {Object} SurveySaleBasicInfo
*
* @apiError {Number} 401 ( )
* @apiError {Number} 403
* @apiError {Number} 404
* @apiError {Number} 500
*
* @apiExample {curl} Example usage:
* curl -X GET \
* -G "isPdf=true" \
* http://localhost:3000/api/survey-sales/1
*
* @apiSuccessExample {json} Success-Response:
* {
* "id": 1,
* "srlNo": "1234567890",
* "storeId": "1234567890",
* "detailInfo": {
* "id": 1,
* "trestleMfpcCd": "1234567890",
* "trestleManufacturerProductName": "1234567890",
* "memo": "1234567890"
* ...
* }
* ...
* }
*/
async function getSurveySaleDetail(request: NextRequest): Promise<NextResponse> {
try {
const { id } = await params
const cookieStore = await cookies()
const session = await getIronSession<SessionData>(cookieStore, sessionOptions)
const id = request.nextUrl.pathname.split('/').pop() ?? ''
const { searchParams } = new URL(request.url)
const isPdf = searchParams.get('isPdf') === 'true'
const sessionParams: SessionParams = {
role: searchParams.get('role'),
storeId: searchParams.get('storeId'),
builderId: searchParams.get('builderId'),
isLoggedIn: searchParams.get('isLoggedIn'),
const survey = await fetchSurvey(Number(id))
if (!survey) {
return NextResponse.json({ error: ERROR_MESSAGES.NOT_FOUND }, { status: 404 })
}
// @ts-ignore
const survey = await prisma.SD_SURVEY_SALES_BASIC_INFO.findFirst({
where: {
ID: Number(id),
},
include: {
DETAIL_INFO: true,
},
})
if (checkRole(survey, sessionParams)) {
/** pdf 데이터 요청 여부, 권한 여부 확인 */
if (isPdf || checkRole(survey, session)) {
return NextResponse.json(survey)
} else {
return NextResponse.json({ error: '該当物件の照会権限がありません。' }, { status: 403 })
}
} catch (error: any) {
/** 로그인 여부 확인 */
if (!session?.isLoggedIn || session?.role === null) {
return NextResponse.json({ error: ERROR_MESSAGES.UNAUTHORIZED }, { status: 401 })
}
/** 권한 없음 */
return NextResponse.json({ error: ERROR_MESSAGES.NO_PERMISSION }, { status: 403 })
} catch (error) {
console.error('Error fetching survey:', error)
return NextResponse.json({ error: 'データの取得に失敗しました。' }, { status: 500 })
return NextResponse.json({ error: ERROR_MESSAGES.FETCH_ERROR }, { status: 500 })
}
}
/**
* @description SRL_NO
* @param {string} srlNo SRL_NO
* @param {string} storeId ID
* @param {string} role
* @returns {Promise<string>} SRL_NO
*/
const getNewSrlNo = async (srlNo: string, storeId: string, role: string) => {
const srlRole = role === 'T01' || role === 'Admin' ? 'HO' : role === 'Admin_Sub' || role === 'Builder' ? 'HM' : ''
@ -104,7 +176,7 @@ const getNewSrlNo = async (srlNo: string, storeId: string, role: string) => {
const lastSurvey = await prisma.SD_SURVEY_SALES_BASIC_INFO.findFirst({
where: {
SRL_NO: {
startsWith: srlRole + storeId,
startsWith: srlRole,
},
},
orderBy: {
@ -124,9 +196,42 @@ const getNewSrlNo = async (srlNo: string, storeId: string, role: string) => {
return newSrlNo
}
export async function PUT(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
/**
* @api {PUT} /api/survey-sales/:id API
* @apiName PUT /api/survey-sales/:id
* @apiGroup SurveySales
* @apiDescription API
*
* @apiParam {Number} id PRIMARY KEY ID (required)
* @apiBody {Object} survey (required)
* @apiBody {Boolean} isTemporary (optional, default: false)
* @apiBody {String} storeId ID (optional)
* @apiBody {String} role (optional)
*
* @apiSuccess {Object} SurveySaleBasicInfo
*
* @apiExample {curl} Example usage:
* curl -X PUT \
* -H "Content-Type: application/json" \
* -d '{"survey": {"detailInfo": {"id": 1, "memo": "1234567890", ...}, "srlNo": "1234567890", ...},"storeId": "1234567890", "role": "T01", "isTemporary": false}' \
* http://localhost:3000/api/survey-sales/1
*
* @apiSuccessExample {json} Success-Response:
* {
* "id": 1,
* "srlNo": "1234567890",
* "storeId": "1234567890",
* "detailInfo": {
* "id": 1,
* "memo": "1234567890",
* ...
* }
* ...
* }
* */
async function updateSurveySaleDetail(request: NextRequest): Promise<NextResponse> {
try {
const { id } = await params
const id = request.nextUrl.pathname.split('/').pop() ?? ''
const body = await request.json()
const { detailInfo, ...basicInfo } = body.survey
@ -150,15 +255,33 @@ export async function PUT(request: NextRequest, { params }: { params: Promise<{
return NextResponse.json(survey)
} catch (error) {
console.error('Error updating survey:', error)
return NextResponse.json({ error: 'Failed to update survey' }, { status: 500 })
return NextResponse.json({ error: 'データ保存に失敗しました。' }, { status: 500 })
}
}
export async function DELETE(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
/**
* @api {DELETE} /api/survey-sales/:id API
* @apiName DELETE /api/survey-sales/:id
* @apiGroup SurveySales
* @apiDescription API
*
* @apiParam {Number} id PRIMARY KEY ID (required)
*
* @apiSuccess {String} message
*
* @apiExample {curl} Example usage:
* curl -X DELETE \
* http://localhost:3000/api/survey-sales/1
*
* @apiSuccessExample {json} Success-Response:
* {
* "message": "success"
*/
async function deleteSurveySaleDetail(request: NextRequest): Promise<NextResponse> {
try {
const { id } = await params
const id = request.nextUrl.pathname.split('/').pop() ?? ''
await prisma.$transaction(async (tx) => {
await prisma.$transaction(async (tx: Prisma.TransactionClient) => {
// @ts-ignore
const detailData = await tx.SD_SURVEY_SALES_BASIC_INFO.findUnique({
where: { ID: Number(id) },
@ -180,16 +303,51 @@ export async function DELETE(request: NextRequest, { params }: { params: Promise
})
})
return NextResponse.json({ message: 'Survey deleted successfully' })
return NextResponse.json({ message: 'success' })
} catch (error) {
console.error('Error deleting survey:', error)
return NextResponse.json({ error: 'Failed to delete survey' }, { status: 500 })
return NextResponse.json({ error: 'データ削除に失敗しました。' }, { status: 500 })
}
}
export async function PATCH(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
/**
* @api {PATCH} /api/survey-sales/:id API
* @apiName PATCH /api/survey-sales/:id
* @apiGroup SurveySales
* @apiDescription API
*
* @apiParam {Number} id PRIMARY KEY ID (required)
* @apiBody {String} targetId ID (required)
* @apiBody {String} targetNm (required)
*
* @apiSuccess {String} message
* @apiSuccess {Object} data
*
* @apiExample {curl} Example usage:
* curl -X PATCH \
* -H "Content-Type: application/json" \
* -d '{"targetId": "1234567890", "targetNm": "1234567890"}' \
* http://localhost:3000/api/survey-sales/1
*
* @apiSuccessExample {json} Success-Response:
* {
* "message": "success",
* "data": {
* "id": 1,
* "srlNo": "1234567890",
* "storeId": "1234567890",
* "detailInfo": {
* "id": 1,
* "memo": "1234567890",
* ...
* }
* ...
* }
* }
*/
async function submitSurveySaleDetail(request: NextRequest): Promise<NextResponse> {
try {
const { id } = await params
const id = request.nextUrl.pathname.split('/').pop() ?? ''
const body = await request.json()
// @ts-ignore
const survey = await prisma.SD_SURVEY_SALES_BASIC_INFO.update({
@ -205,6 +363,11 @@ export async function PATCH(request: NextRequest, { params }: { params: Promise<
return NextResponse.json({ message: 'Survey confirmed successfully', data: survey })
} catch (error) {
console.error('Error updating survey:', error)
return NextResponse.json({ error: 'Failed to update survey' }, { status: 500 })
return NextResponse.json({ error: 'データ保存に失敗しました。' }, { status: 500 })
}
}
export const GET = loggerWrapper(getSurveySaleDetail)
export const PUT = loggerWrapper(updateSurveySaleDetail)
export const DELETE = loggerWrapper(deleteSurveySaleDetail)
export const PATCH = loggerWrapper(submitSurveySaleDetail)

View File

@ -1,18 +1,19 @@
import { NextResponse } from 'next/server'
import { prisma } from '@/libs/prisma'
import { convertToSnakeCase } from '@/utils/common-utils'
import { loggerWrapper } from '@/libs/api-wrapper'
/**
*
* @description
*/
type SearchParams = {
keyword?: string | null // 검색어
searchOption?: string | null // 검색 옵션 (select 옵션)
isMySurvey?: string | null // 내가 작성한 매물
sort?: string | null // 정렬 방식
keyword?: string | null
searchOption?: string | null
isMySurvey?: string | null
sort?: string | null
offset?: string | null
role?: string | null // 회원권한한
storeId?: string | null // 판매점ID
builderId?: string | null // 시공ID
role?: string | null
storeId?: string | null
builderId?: string | null
}
type WhereCondition = {
@ -21,35 +22,35 @@ type WhereCondition = {
[key: string]: any
}
// 검색 가능한 필드 옵션
/** 검색 가능한 필드 옵션 */
const SEARCH_OPTIONS = [
'BUILDING_NAME', // 건물명
'REPRESENTATIVE', // 담당자
'STORE', // 판매점명
'STORE_ID', // 판매점ID
'CONSTRUCTION_POINT', // 시공점명
'CONSTRUCTION_POINT_ID', // 시공점ID
'CUSTOMER_NAME', // 고객명
'POST_CODE', // 우편번호
'ADDRESS', // 주소
'ADDRESS_DETAIL', // 상세주소
'SRL_NO', // 등록번호
'BUILDING_NAME',
'REPRESENTATIVE',
'STORE',
'STORE_ID',
'CONSTRUCTION_POINT',
'CONSTRUCTION_POINT_ID',
'CUSTOMER_NAME',
'POST_CODE',
'ADDRESS',
'ADDRESS_DETAIL',
'SRL_NO',
] as const
// 페이지당 항목 수
/** 페이지당 기본 항목 수 */
const ITEMS_PER_PAGE = 10
/**
*
* @param keyword
* @param searchOption
* @returns
* @description
* @param {string} keyword
* @param {string} searchOption
* @returns {WhereCondition}
*/
const createKeywordSearchCondition = (keyword: string, searchOption: string): WhereCondition => {
const where: WhereCondition = { AND: [] }
if (searchOption === 'all') {
// 모든 필드 검색 시 OR 조건 사용
/** 모든 필드 검색 시 OR 조건 사용 */
where.OR = []
where.OR.push(
@ -58,42 +59,38 @@ const createKeywordSearchCondition = (keyword: string, searchOption: string): Wh
})),
)
} else if (SEARCH_OPTIONS.includes(searchOption.toUpperCase() as any)) {
// 특정 필드 검색
/** 특정 필드 검색 */
where[searchOption.toUpperCase()] = { contains: keyword }
}
return where
}
/**
*
* @param params
* @returns
* @description
* @param {SearchParams} params
* @returns {WhereCondition}
*/
const createMemberRoleCondition = (params: SearchParams): WhereCondition => {
const where: WhereCondition = { AND: [] }
switch (params.role) {
case 'Admin': // 1차점
case 'Admin':
where.OR = [
{
// 같은 판매점에서 작성한 제출/제출되지 않은 매물
AND: [{ STORE_ID: { equals: params.storeId } }],
},
{
// MUSUBI (시공권한 X) 가 ORDER 에 제출한 매물
AND: [{ SUBMISSION_TARGET_ID: { equals: params.storeId } }, { SUBMISSION_STATUS: { equals: true } }],
},
]
break
case 'Admin_Sub': // 2차점
case 'Admin_Sub':
where.OR = [
{
// MUSUBI (시공권한 X) 같은 판매점에서 작성한 제출/제출되지 않은 매물
AND: [{ STORE_ID: { equals: params.storeId } }, { CONSTRUCTION_POINT_ID: { equals: params.builderId } }],
},
{
// MUSUBI (시공권한 O) 가 MUSUBI 에 제출한 매물 + PARTNER 가 제출한 매물
AND: [
{ SUBMISSION_TARGET_ID: { equals: params.storeId } },
{ CONSTRUCTION_POINT_ID: { not: null } },
@ -104,9 +101,8 @@ const createMemberRoleCondition = (params: SearchParams): WhereCondition => {
]
break
case 'Builder': // MUSUBI (시공권한 O)
case 'Partner': // PARTNER
// 시공ID 같은 매물
case 'Builder':
case 'Partner':
where.AND?.push({
CONSTRUCTION_POINT_ID: { equals: params.builderId },
})
@ -129,19 +125,77 @@ const createMemberRoleCondition = (params: SearchParams): WhereCondition => {
]
break
case 'User':
// 모든 매물 조회 가능 (추가 조건 없음)
break
}
return where
}
/**
* @description ,
* @param {SearchParams} params
* @returns {NextResponse}
*/
const checkSession = (params: SearchParams) => {
if (params.role === null) {
return NextResponse.json({ data: [], count: 0 })
}
if (params.role === 'Builder' || params.role === 'Partner') {
if (params.builderId === null) {
return NextResponse.json({ data: [], count: 0 })
}
} else {
if (params.storeId === null) {
return NextResponse.json({ data: [], count: 0 })
}
}
return null
}
/**
* GET -
* @api {GET} /api/survey-sales API
* @apiName GET /api/survey-sales
* @apiGroup SurveySales
* @apiDescription API
*
* @apiParam {String} keyword (optional)
* @apiParam {String} searchOption (optional)
* @apiParam {String} isMySurvey (optional)
* @apiParam {String} sort (optional)
* @apiParam {String} offset (optional)
* @apiParam {String} role (optional)
* @apiParam {String} storeId ID (optional)
* @apiParam {String} builderId ID (optional)
*
* @apiSuccess {Object[]} data
* @apiSuccess {Number} data.count
*
* @apiExample {curl} Example usage:
* curl -X GET \
* -G "keyword=test&searchOption=all&isMySurvey=true&sort=created&offset=0&role=Admin&storeId=1234567890&builderId=1234567890" \
* http://localhost:3000/api/survey-sales
*
* @apiSuccessExample {json} Success-Response:
* {
* "data": [
* {
* "id": 1,
* "srlNo": "1234567890",
* "storeId": "1234567890",
* "detailInfo": {
* "id": 1,
* "memo": "1234567890",
* ...
* }
* ...
* }
* ],
* "count": 1
* }
*
*/
export async function GET(request: Request) {
async function getSurveySales(request: Request) {
try {
// URL 파라미터 파싱
/** URL 파라미터 파싱 */
const { searchParams } = new URL(request.url)
const params: SearchParams = {
keyword: searchParams.get('keyword'),
@ -154,25 +208,31 @@ export async function GET(request: Request) {
builderId: searchParams.get('builderId'),
}
// 검색 조건 구성
/** 세션 체크 결과 처리 */
const sessionCheckResult = checkSession(params)
if (sessionCheckResult) {
return sessionCheckResult
}
/** 검색 조건 구성 */
const where: WhereCondition = { AND: [] }
// 내가 작성한 매물 조건 적용
/** 내가 작성한 매물 조건 적용 */
if (params.isMySurvey) {
where.AND.push({ REPRESENTATIVE_ID: 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,
@ -180,30 +240,52 @@ export async function GET(request: Request) {
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 })
return NextResponse.json({ error: 'データ照会に失敗しました。' }, { status: 500 })
}
}
/**
* PUT -
* @api {PUT} /api/survey-sales API
* @apiName PUT /api/survey-sales
* @apiGroup SurveySales
* @apiDescription API
*
* @apiParam {Number} id ID (required)
* @apiBody {Object} detail_info (required)
*
* @apiSuccess {String} message
*
* @apiExample {curl} Example usage:
* curl -X PUT \
* -H "Content-Type: application/json" \
* -d '{"id": 1, "detail_info": {"memo": "1234567890"}}' \
* http://localhost:3000/api/survey-sales
*
* @apiSuccessExample {json} Success-Response:
* {
* "message": "Success Update Survey"
* }
*
* @apiError {Number} 500
*/
export async function PUT(request: Request) {
async function updateSurveySales(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,
@ -218,7 +300,43 @@ export async function PUT(request: Request) {
}
}
export async function POST(request: Request) {
/**
* @api {POST} /api/survey-sales API
* @apiName POST /api/survey-sales
* @apiGroup SurveySales
* @apiDescription API
*
* @apiParam {Object} survey (required)
* @apiParam {String} role (required)
* @apiParam {String} storeId ID (required)
* @returns
*
* @apiSuccess {Object} data
*
* @apiExample {curl} Example usage:
* curl -X POST \
* -H "Content-Type: application/json" \
* -d '{"survey": {"srlNo": "1234567890", "storeId": "1234567890", "role": "T01", "detail_info": {"memo": "1234567890"}}}' \
* http://localhost:3000/api/survey-sales
*
* @apiSuccessExample {json} Success-Response:
* {
* "data": {
* "id": 1,
* "srlNo": "1234567890",
* "storeId": "1234567890",
* "detailInfo": {
* "id": 1,
* "memo": "1234567890",
* ...
* }
* ...
* }
* }
*
* @apiError {Number} 500
*/
async function createSurveySales(request: Request) {
try {
const body = await request.json()
@ -231,8 +349,8 @@ export async function POST(request: Request) {
? ''
: null
// 임시 저장 시 임시저장으로 저장
// 기본 저장 시 (HO/HM) + 판매점ID + yyMMdd + 000 으로 저장
/** 임시 저장 시 임시저장으로 저장 */
/** 기본 저장 시 (HO/HM) + 판매점ID + yyMMdd + 000 으로 저장 */
const baseSrlNo =
body.survey.srlNo ??
role +
@ -253,10 +371,10 @@ export async function POST(request: Request) {
},
})
// 마지막 번호 추출
/** 마지막 번호 추출 */
const lastNumber = lastSurvey ? parseInt(lastSurvey.SRL_NO.slice(-3)) : 0
// 새로운 srlNo 생성 - 임시저장일 경우 '임시저장' 으로 저장
/** 새로운 srlNo 생성 - 임시저장일 경우 '임시저장' 으로 저장 */
const newSrlNo = baseSrlNo.startsWith('一時保存') ? baseSrlNo : baseSrlNo + (lastNumber + 1).toString().padStart(3, '0')
const { detailInfo, ...basicInfo } = body.survey
@ -273,6 +391,10 @@ export async function POST(request: Request) {
return NextResponse.json(result)
} catch (error) {
console.error(error)
return NextResponse.json({ error: 'Fail Create Survey' }, { status: 500 })
return NextResponse.json({ error: 'データ保存に失敗しました。' }, { status: 500 })
}
}
export const GET = loggerWrapper(getSurveySales)
export const PUT = loggerWrapper(updateSurveySales)
export const POST = loggerWrapper(createSurveySales)

View File

@ -1,5 +1,11 @@
import { Metadata } from 'next'
import type { ReactNode } from 'react'
export const metadata: Metadata = {
title: 'HANASYS現地調査:お問い合わせ',
description: 'HANASYS現地調査:お問い合わせ',
}
export default function layout({ children }: { children: ReactNode }) {
return <div className="container">{children}</div>
}

View File

@ -13,8 +13,8 @@ import { sessionOptions } from '@/libs/session'
import '@/styles/style.scss'
export const metadata: Metadata = {
title: 'Create Next App',
description: 'Generated by create next app',
title: 'HANASYS現地調査',
description: 'HANASYS現地調査',
}
interface RootLayoutProps {

View File

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

View File

@ -1,9 +1,15 @@
import { Metadata } from 'next'
import type { ReactNode } from 'react'
interface SuitableLayoutProps {
children: ReactNode
}
export const metadata: Metadata = {
title: 'HANASYS現地調査:屋根材積合成',
description: 'HANASYS現地調査:屋根材積合成',
}
export default function layout({ children }: SuitableLayoutProps) {
return (
<>

View File

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

View File

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

View File

@ -1,11 +1,16 @@
import { Metadata } from 'next'
import type { ReactNode } from 'react'
interface SurveySaleLayoutProps {
children: ReactNode
navTab: ReactNode
}
export default function layout({ children, navTab }: SurveySaleLayoutProps) {
export const metadata: Metadata = {
title: 'HANASYS現地調査:調査物件',
description: 'HANASYS現地調査:調査物件',
}
export default function layout({ children }: SurveySaleLayoutProps) {
return (
<>
<div className="container">

View File

@ -15,6 +15,8 @@ export default function Detail() {
const { session } = useSessionStore()
const isBuilderOrPartner = session?.role === 'Builder' || session?.role === 'Partner'
return (
<>
<div className="inquiry-frame">
@ -43,11 +45,11 @@ export default function Detail() {
</tr>
<tr>
<th></th>
<td>{inquiryDetail?.storeNm}</td>
<td>{isBuilderOrPartner ? '-' : inquiryDetail?.storeNm}</td>
</tr>
<tr>
<th>E-mail</th>
<td>{inquiryDetail?.regEmail}</td>
<td>{inquiryDetail?.regEmail ? inquiryDetail?.regEmail : '-'}</td>
</tr>
<tr>
<th></th>

View File

@ -50,6 +50,7 @@ export default function RegistForm() {
const [attachedFiles, setAttachedFiles] = useState<File[]>([])
/** 파일 첨부 처리 */
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const files = e.target.files
if (files && files.length > 0) {
@ -58,15 +59,18 @@ export default function RegistForm() {
e.target.value = ''
}
/** 파일 삭제 처리 */
const handleRemoveFile = (index: number) => {
setAttachedFiles(attachedFiles.filter((_, i) => i !== index))
}
/** 필수 필드 포커스 처리 */
const focusOnRequiredField = (fieldId: string) => {
const element = document.getElementById(fieldId)
if (element) element.focus()
}
/** 제출 처리 */
const handleSubmit = async () => {
const emptyField = requiredFieldNames.find((field) => inquiryRequest[field.id as keyof InquiryRequest] === '')
if (emptyField) {

View File

@ -57,6 +57,7 @@ export default function ListTable() {
}
}, [session, inquiryList])
/** 내 문의 필터 처리 - 체크 시 자신의 문의 목록만 조회 */
const handleMyInquiry = () => {
setOffset(1)
setInquiryListRequest({
@ -65,6 +66,7 @@ export default function ListTable() {
})
}
/** 답변 여부 필터 처리리 */
const handleFilter = (e: React.ChangeEvent<HTMLSelectElement>) => {
switch (e.target.value) {
case 'N':

View File

@ -1,132 +0,0 @@
'use client'
import { useEffect, useRef, useState } from 'react'
import generatePDF, { Margin, Options, Resolution, usePDF } from 'react-to-pdf'
import { useSuitable } from '@/hooks/useSuitable'
import { useSuitableStore } from '@/store/useSuitableStore'
import { SUITABLE_HEAD_CODE, type Suitable, type SuitableDetail } from '@/types/Suitable'
export default function SuitableDownloadPdf() {
const [fileName, setFileName] = useState<string[]>([])
const [createTime, setCreateTime] = useState('')
const targetRef = useRef<HTMLDivElement>(null)
const { toCodeName, toSuitableDetail, selectedSuitables, isSelectedSuitablesLoading } = useSuitable()
const { selectedCategory, suitableCommCode, selectedItemsSearching, setSelectedItemsSearching } = useSuitableStore()
const handleDownPdf = () => {
const options: Options = {
filename: `${fileName.join('_')}.pdf`,
method: 'open' as const,
resolution: Resolution.HIGH,
page: {
margin: Margin.SMALL,
format: 'A4',
orientation: 'landscape' 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' })
}
const formatDateString = () => {
const now = new Date()
const year = now.getFullYear()
const month = now.getMonth() + 1
const day = now.getDate()
const hours = now.getHours()
const minutes = now.getMinutes()
return `${year}${month}${day}${hours}:${minutes.toString().padStart(2, '0')}`
}
useEffect(() => {
setCreateTime(formatDateString())
setFileName([
`(${suitableCommCode.get(SUITABLE_HEAD_CODE.ROOF_MATL_GRP_CD)?.find((category) => category.code === selectedCategory)?.codeJp})`,
'屋根材適合表',
])
if (!selectedItemsSearching) {
setSelectedItemsSearching(true)
}
}, [])
if (!selectedCategory) return <div> .</div>
if (isSelectedSuitablesLoading) return <div>Loading...</div>
return (
<>
{/* <button onClick={() => handleDownPdf()}>PDFダウンロード</button> */}
<div className="pdf-table-wrap" ref={targetRef}>
<div className="pdf-intro-page">
<div className="pdf-intro-tit-wrap">
<div className="pdf-intro-tit mb20"></div>
<div className="pdf-intro-tit mb20">{fileName.join(' ')}</div>
<div className="pdf-intro-date">{createTime}</div>
</div>
<div className="pdf-intro-cont-wrap">
<p>使</p>
<p></p>
<p></p>
<p></p>
</div>
<div className="pdf-intro-foot-date">{createTime}</div>
</div>
<div className="pdf-table-content">
<div className="pdf-table-grid-wrap">
{selectedSuitables?.map((item: Suitable) => (
<div className="pdf-table-card" key={item.id}>
<div className="pdf-table-tit-wrap">
<span>{item.productName}</span>
<span>{toCodeName(SUITABLE_HEAD_CODE.MANU_FT_CD, item.manuFtCd)}</span>
<span>{toCodeName(SUITABLE_HEAD_CODE.ROOF_MT_CD, item.roofMtCd)}</span>
</div>
<div className="pdf-roof-table">
<table>
<colgroup>
<col width={'18%'} />
<col width={'23%'} />
<col width={'18%'} />
<col />
</colgroup>
<thead>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
{toSuitableDetail(item.detail).map((subItem: SuitableDetail) => (
<tr key={subItem.id}>
<td>{toCodeName(SUITABLE_HEAD_CODE.ROOF_SH_CD, item.roofShCd)}</td>
<td>{toCodeName(SUITABLE_HEAD_CODE.TRESTLE_MFPC_CD, subItem.trestleMfpcCd)}</td>
<td>{subItem.trestleManufacturerProductName}</td>
<td>{subItem.memo}</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
))}
</div>
<div className="pdf-intro-foot-date">{createTime}</div>
</div>
</div>
</>
)
}

View File

@ -10,45 +10,127 @@ Font.register({
const styles = StyleSheet.create({
page: {
padding: 30,
fontSize: 10,
maxWidth: 840,
minWidth: 840,
margin: '0 auto',
padding: 20,
fontFamily: 'NotoSansJP',
},
text: {
introPage: {
height: 550,
padding: '60 20',
},
introTitWrap: {
textAlign: 'center',
marginBottom: 70,
},
introTit: {
fontSize: 18,
fontWeight: 500,
color: '#101010',
fontFamily: 'NotoSansJP',
marginBottom: 20,
},
introDate: {
fontSize: 16,
fontWeight: 400,
color: '#101010',
fontFamily: 'NotoSansJP',
},
introContText: {
fontSize: 13,
fontWeight: 400,
color: '#101010',
fontFamily: 'NotoSansJP',
},
tableGridWrap: {
display: 'flex',
flexWrap: 'wrap',
flexDirection: 'row',
gap: 20
},
tableCard:{
width: '48.7%',
},
tableTitWrap: {
display: 'flex',
flexDirection: 'row',
alignItems: 'center',
marginBottom: 5,
},
tableTit:{
fontSize: 8,
fontWeight: 500,
fontFamily: 'NotoSansJP',
color: '#101010',
},
tableTit01: {
paddingRight: 6,
borderRight: '1px solid #101010'
},
tableTit02: {
padding: '0 6',
borderRight: '1px solid #101010'
},
tableTit03: {
paddingLeft: 6,
},
table: {
display: 'flex',
width: 'auto',
borderStyle: 'solid',
borderWidth: 1,
borderColor: '#000',
width: '100%',
},
tableRow: {
flexDirection: 'row',
},
tableColHeader: {
width: '25%',
borderStyle: 'solid',
borderWidth: 1,
backgroundColor: '#f0f0f0',
padding: 2,
tableCol01: {
width: '18%',
},
tableCol: {
width: '25%',
borderStyle: 'solid',
borderWidth: 1,
padding: 2,
tableCol02: {
width: '23%',
},
tableCol03: {
width: '18%',
},
tableCol04: {
width: '41%',
},
tableTh: {
fontSize: 5,
fontWeight: 500,
color: '#fff',
backgroundColor: '#18B490',
border: '1px solid #18B490',
textAlign: 'center'
},
tableTd: {
display: 'flex',
flexDirection: 'row',
alignItems: 'center',
fontSize: 5,
fontWeight: 300,
color: '#101010',
backgroundColor: '#fff',
border: '1px solid #CBCBCB',
padding: 3,
},
marginL:{
marginLeft: -1,
},
marginT:{
marginTop: -1,
},
footer: {
position: 'absolute',
bottom: 30,
bottom: 5,
left: 30,
right: 30,
},
footerDate: {
fontSize: 10,
fontSize: 7,
textAlign: 'right',
fontFamily: 'NotoSansJP',
fontWeight: 400,
color: '#101010',
},
})
@ -70,52 +152,52 @@ export default function SuitablePdf({ data, fileTitle, firstPage }: { data: Suit
<Page size="A4" orientation="landscape" style={styles.page}>
{/* Intro Section */}
{firstPage && (
<View>
<View>
<Text style={styles.text}></Text>
<Text style={styles.text}>{fileTitle}</Text>
<Text style={styles.text}>{createTime}</Text>
<View style={styles.introPage}>
<View style={styles.introTitWrap}>
<Text style={styles.introTit}></Text>
<Text style={styles.introTit}>{fileTitle}</Text>
<Text style={styles.introDate}>{createTime}</Text>
</View>
<View>
<Text style={styles.text}>使</Text>
<Text style={styles.text}></Text>
<Text style={styles.text}>
<Text style={styles.introContText}>使</Text>
<Text style={styles.introContText}></Text>
<Text style={styles.introContText}>
</Text>
<Text style={styles.text}></Text>
<Text style={styles.introContText}></Text>
</View>
</View>
)}
<View>
<View style={styles.tableGridWrap}>
{/* Cards Section */}
{data?.map((item: Suitable) => (
<View key={item.id}>
<View key={item.id} style={styles.tableCard}>
{/* Table Title */}
<View>
<Text style={styles.text}>{item.productName}</Text>
<Text style={styles.text}>{item.manuFtCd}</Text>
<Text style={styles.text}>{item.roofMtCd}</Text>
<View style={styles.tableTitWrap}>
<Text style={[styles.tableTit, styles.tableTit01]}>{item.productName}</Text>
<Text style={[styles.tableTit, styles.tableTit02]}>{item.manuFtCd}</Text>
<Text style={[styles.tableTit, styles.tableTit03]}>{item.roofMtCd}</Text>
</View>
{/* Table */}
<View style={styles.table}>
{/* Table Header */}
<View style={styles.tableRow}>
<Text style={[styles.tableColHeader, styles.text]}></Text>
<Text style={[styles.tableColHeader, styles.text]}></Text>
<Text style={[styles.tableColHeader, styles.text]}></Text>
<Text style={[styles.tableColHeader, styles.text]}></Text>
<Text style={[styles.tableCol01, styles.tableTh]}></Text>
<Text style={[styles.tableCol02, styles.tableTh , styles.marginL]}></Text>
<Text style={[styles.tableCol03, styles.tableTh, styles.marginL]}></Text>
<Text style={[styles.tableCol04 , styles.tableTh, styles.marginL]}></Text>
</View>
{/* Table Body */}
<View>
{JSON.parse(item.detail)?.map((subItem: SuitableDetail) => (
<View key={subItem.id} style={styles.tableRow}>
<Text style={[styles.tableCol, styles.text]}>{item.roofShCd}</Text>
<Text style={[styles.tableCol, styles.text]}>{subItem.trestleMfpcCd}</Text>
<Text style={[styles.tableCol, styles.text]}>{subItem.trestleManufacturerProductName}</Text>
<Text style={[styles.tableCol, styles.text]}>{subItem.memo}</Text>
<View style={[styles.tableCol01, styles.tableTd, styles.marginT]}><Text>{item.roofShCd}</Text></View>
<View style={[styles.tableCol02, styles.tableTd, styles.marginL, styles.marginT]}><Text>{subItem.trestleMfpcCd}</Text></View>
<View style={[styles.tableCol03, styles.tableTd, styles.marginL, styles.marginT]}><Text>{subItem.trestleManufacturerProductName}</Text></View>
<View style={[styles.tableCol04, styles.tableTd, styles.marginL, styles.marginT]}><Text>{subItem.memo}</Text></View>
</View>
))}
</View>
@ -126,7 +208,7 @@ export default function SuitablePdf({ data, fileTitle, firstPage }: { data: Suit
{/* Footer */}
<View style={styles.footer} fixed>
<Text style={[styles.footerDate, styles.text]}>{createTime}</Text>
<Text style={styles.footerDate}>{createTime}</Text>
</View>
</Page>
)

View File

@ -6,20 +6,28 @@ import { useParams, useRouter } from 'next/navigation'
import { useSurvey } from '@/hooks/useSurvey'
import { radioEtcData, roofMaterial, selectBoxOptions, supplementaryFacilities } from '../survey-sale/detail/RoofForm'
import { useSpinnerStore } from '@/store/spinnerStore'
import { useSessionStore } from '@/store/session'
export default function SurveySaleDownloadPdf() {
const params = useParams()
const id = params.id
const router = useRouter()
const { surveyDetail, isLoadingSurveyDetail } = useSurvey(Number(id))
const { surveyDetail, isLoadingSurveyDetail } = useSurvey(Number(id), true)
const { setIsShow } = useSpinnerStore()
const { session } = useSessionStore()
const targetRef = useRef<HTMLDivElement>(null)
const isGeneratedRef = useRef(false)
/** 페이지 랜더링 이후 PDF 생성 */
useEffect(() => {
if (isLoadingSurveyDetail || !surveyDetail || isGeneratedRef.current) return
if (isLoadingSurveyDetail || isGeneratedRef.current) return
if (surveyDetail === null) {
alert('データが見つかりません。')
router.replace('/')
return
}
isGeneratedRef.current = true
handleDownPdf()
}, [surveyDetail?.id, isLoadingSurveyDetail])
@ -48,11 +56,20 @@ export default function SurveySaleDownloadPdf() {
},
}
generatePDF(targetRef, options).then(() => {
setIsShow(false)
router.replace(`/survey-sale/${id}`)
alert('PDFの生成が完了しました。 ポップアップウィンドウからダウンロードしてください。')
})
/** PDF 생성 이후 세션 여부에 따른 라우팅 처리 */
generatePDF(targetRef, options)
.then(() => {
setIsShow(false)
if (session?.isLoggedIn) {
router.replace(`/survey-sale/${id}`)
} else {
router.replace('/')
}
alert('PDFの生成が完了しました。 ポップアップウィンドウからダウンロードしてください。')
})
.catch((error: any) => {
console.error('error', error)
})
}
return (
@ -60,8 +77,8 @@ export default function SurveySaleDownloadPdf() {
<div
ref={targetRef}
style={{
width: '794px', // A4 너비
minHeight: '1123px', // A4 높이
width: '794px',
minHeight: '1123px',
transform: 'scale(1.0)',
transformOrigin: 'top left',
padding: '20px',

View File

@ -5,17 +5,16 @@ import { useCallback, useEffect, useState } from 'react'
import SuitableDetailPopupButton from './SuitableDetailPopupButton'
import { useSuitable } from '@/hooks/useSuitable'
import { usePopupController } from '@/store/popupController'
import { useSuitableStore } from '@/store/useSuitableStore'
import { SUITABLE_HEAD_CODE, type Suitable, type SuitableDetail } from '@/types/Suitable'
export default function SuitableDetailPopup() {
const popupController = usePopupController()
const { toCodeName, toSuitableDetail, suitableCheckIcon, suitableCheckMemo, selectedSuitables, isSelectedSuitablesLoading } = useSuitable()
const { setSelectedItemsSearching } = useSuitableStore()
const { toCodeName, toSuitableDetail, suitableCheckIcon, suitableCheckMemo, getSelectedSuitables, suitableErrorAlert } = useSuitable()
const [openItems, setOpenItems] = useState<Set<number>>(new Set())
const [selectedSuitables, setSelectedSuitables] = useState<Suitable[]>([])
// 아이템 열기/닫기
/* 아이템 열기/닫기 */
const toggleItemOpen = useCallback((itemId: number) => {
setOpenItems((prev) => {
const newOpenItems = new Set(prev)
@ -25,7 +24,13 @@ export default function SuitableDetailPopup() {
}, [])
useEffect(() => {
setSelectedItemsSearching(true)
getSelectedSuitables()
.then((res) => {
setSelectedSuitables(res)
})
.catch(() => {
suitableErrorAlert()
})
}, [])
return (
@ -45,60 +50,56 @@ export default function SuitableDetailPopup() {
</div>
<div className="modal-body">
<div className="compliance-check-pop-wrap">
{isSelectedSuitablesLoading ? (
<div>Loading...</div>
) : (
selectedSuitables?.map((item: Suitable) => (
<div className={`compliance-check-bx ${openItems.has(item.id) ? 'act' : ''}`} key={item.id}>
<div className="check-name-wrap">
<div className="check-name">{item.productName}</div>
<div className="check-name-btn">
<button className="bx-btn" onClick={() => toggleItemOpen(item.id)}></button>
</div>
</div>
<div className="compliance-check-pop-contents">
<div className="check-pop-data-wrap">
<div className="check-pop-data-tit"> </div>
<div className="check-pop-data-txt">{toCodeName(SUITABLE_HEAD_CODE.MANU_FT_CD, item.manuFtCd)}</div>
</div>
<div className="check-pop-data-wrap">
<div className="check-pop-data-tit"></div>
<div className="check-pop-data-txt">{toCodeName(SUITABLE_HEAD_CODE.ROOF_MT_CD, item.roofMtCd)}</div>
</div>
<div className="check-pop-data-wrap">
<div className="check-pop-data-tit"></div>
<div className="check-pop-data-txt">{toCodeName(SUITABLE_HEAD_CODE.ROOF_SH_CD, item.roofShCd)}</div>
</div>
<div className="check-pop-data-table-wrap">
{toSuitableDetail(item.detail).map((subItem: SuitableDetail) => (
<div className="check-pop-data-table" key={subItem.id}>
<div className="pop-data-table-head">
<div className="pop-data-table-head-name">{toCodeName(SUITABLE_HEAD_CODE.TRESTLE_MFPC_CD, subItem.trestleMfpcCd)}</div>
<div className="pop-data-table-head-icon">
<div className="compliance-icon">
<Image src={suitableCheckIcon(subItem.trestleManufacturerProductName)} width={22} height={22} alt="" />
</div>
{subItem.memo && (
<div className="compliance-icon">
<Image src={'/assets/images/sub/compliance_tip_icon.svg'} width={22} height={22} alt=""></Image>
</div>
)}
</div>
</div>
<div className="pop-data-table-body">{suitableCheckMemo(subItem.trestleManufacturerProductName)}</div>
{subItem.memo && (
<div className="pop-data-table-footer">
<div className="pop-data-table-footer-unit"></div>
<div className="pop-data-table-footer-data">{subItem.memo}</div>
</div>
)}
</div>
))}
</div>
{selectedSuitables?.map((item: Suitable) => (
<div className={`compliance-check-bx ${openItems.has(item.id) ? 'act' : ''}`} key={item.id}>
<div className="check-name-wrap">
<div className="check-name">{item.productName}</div>
<div className="check-name-btn">
<button className="bx-btn" onClick={() => toggleItemOpen(item.id)}></button>
</div>
</div>
))
)}
<div className="compliance-check-pop-contents">
<div className="check-pop-data-wrap">
<div className="check-pop-data-tit"> </div>
<div className="check-pop-data-txt">{toCodeName(SUITABLE_HEAD_CODE.MANU_FT_CD, item.manuFtCd)}</div>
</div>
<div className="check-pop-data-wrap">
<div className="check-pop-data-tit"></div>
<div className="check-pop-data-txt">{toCodeName(SUITABLE_HEAD_CODE.ROOF_MT_CD, item.roofMtCd)}</div>
</div>
<div className="check-pop-data-wrap">
<div className="check-pop-data-tit"></div>
<div className="check-pop-data-txt">{toCodeName(SUITABLE_HEAD_CODE.ROOF_SH_CD, item.roofShCd)}</div>
</div>
<div className="check-pop-data-table-wrap">
{toSuitableDetail(item.detail)?.map((subItem: SuitableDetail) => (
<div className="check-pop-data-table" key={subItem.id}>
<div className="pop-data-table-head">
<div className="pop-data-table-head-name">{toCodeName(SUITABLE_HEAD_CODE.TRESTLE_MFPC_CD, subItem.trestleMfpcCd)}</div>
<div className="pop-data-table-head-icon">
<div className="compliance-icon">
<Image src={suitableCheckIcon(subItem.trestleManufacturerProductName)} width={22} height={22} alt="" />
</div>
{subItem.memo && (
<div className="compliance-icon">
<Image src={'/assets/images/sub/compliance_tip_icon.svg'} width={22} height={22} alt=""></Image>
</div>
)}
</div>
</div>
<div className="pop-data-table-body">{suitableCheckMemo(subItem.trestleManufacturerProductName)}</div>
{subItem.memo && (
<div className="pop-data-table-footer">
<div className="pop-data-table-footer-unit"></div>
<div className="pop-data-table-footer-data">{subItem.memo}</div>
</div>
)}
</div>
))}
</div>
</div>
</div>
))}
</div>
<SuitableDetailPopupButton />
</div>

View File

@ -9,31 +9,35 @@ export default function SuitableDetailPopupButton() {
const popupController = usePopupController()
const { downloadSuitablePdf } = useSuitable()
/* 상세 팝업 닫기 */
const handleClosePopup = () => {
popupController.setSuitableDetailPopup(false)
}
/* 페이지 이동 */
const handleRedirectPage = (path: string) => {
handleClosePopup()
router.push(path)
}
return (
<div className="btn-flex-wrap com">
<div className="btn-bx">
<button className="btn-frame n-blue icon" onClick={handleClosePopup}>
<i className="btn-arr"></i>
</button>
</div>
<div className="btn-bx">
<button className="btn-frame red icon" onClick={downloadSuitablePdf}>
<i className="btn-arr"></i>
</button>
</div>
<div className="btn-bx">
<button className="btn-frame n-blue icon" onClick={() => handleRedirectPage('/inquiry/regist')}>
11<i className="btn-arr"></i>
</button>
<div className="float-btn-wrap">
<div className="btn-flex-wrap com">
<div className="btn-bx">
<button className="btn-frame n-blue icon" onClick={handleClosePopup}>
<i className="btn-arr"></i>
</button>
</div>
<div className="btn-bx">
<button className="btn-frame red icon" onClick={downloadSuitablePdf}>
<i className="btn-arr"></i>
</button>
</div>
<div className="btn-bx">
<button className="btn-frame n-blue icon" onClick={() => handleRedirectPage('/inquiry/regist')}>
11<i className="btn-arr"></i>
</button>
</div>
</div>
</div>
)

View File

@ -15,7 +15,7 @@ interface SubmitFormData {
targetNm: string | null
sender: string
receiver: string[] | string
reference: string | null
reference: string[] | null
title: string
contents: string | null
}
@ -34,7 +34,7 @@ export default function SurveySaleSubmitPopup() {
const { setIsShow } = useSpinnerStore()
const { getCommCode } = useCommCode()
const { surveyDetail } = useSurvey(Number(routeId))
const { surveyDetail, getSubmitTarget } = useSurvey(Number(routeId))
const [submitData, setSubmitData] = useState<SubmitFormData>({
saleBase: null,
@ -48,20 +48,43 @@ export default function SurveySaleSubmitPopup() {
})
const [commCodeList, setCommCodeList] = useState<CommCode[]>([])
/** 제출 타겟 데이터 조회 및 제출 폼 데이터 삽입 */
useEffect(() => {
if (!session?.isLoggedIn || !surveyDetail?.id) return
const baseUpdate = {
sender: session?.email ?? '',
title: '[HANASYS現地調査] 調査物件が提出. (' + surveyDetail?.srlNo + ')',
}
if (session?.role === 'Admin') {
getCommCode('SALES_OFFICE_CD').then((codes) => {
setCommCodeList(codes)
})
setSubmitData((prev) => ({
...prev,
...baseUpdate,
}))
} else if (session?.role === 'Builder' || session?.role === 'Admin_Sub') {
getSubmitTarget({ storeId: surveyDetail?.storeId ?? '', role: session?.role ?? '' }).then((data) => {
if (!data) return
if (data && data.length > 0) {
const updateData: Partial<SubmitFormData> = {
sender: session?.email ?? '',
title: '[HANASYS現地調査] 調査物件が提出. (' + surveyDetail?.srlNo + ')',
targetId: data[0]?.targetStoreId ?? '',
targetNm: data[0]?.targetStoreNm ?? '',
receiver: data.filter((item) => item.auth === 'S').map((item) => item.repUserEmail),
reference: data.filter((item) => item.auth === 'N').map((item) => item.repUserEmail),
saleBase: null,
contents: '',
}
setSubmitData((prev) => ({
...prev,
...updateData,
}))
}
})
}
setSubmitData({
...submitData,
targetId: session?.role === 'Builder' ? surveyDetail?.storeId ?? null : null,
targetNm: session?.role === 'Builder' ? surveyDetail?.store ?? null : null,
sender: session?.email ?? '',
title: '[HANASYS現地調査] 調査物件が提出. (' + surveyDetail?.srlNo + ')',
})
}, [session, surveyDetail])
const FORM_FIELDS: FormField[] = [
@ -80,6 +103,7 @@ export default function SurveySaleSubmitPopup() {
setSubmitData((prev) => ({ ...prev, [field]: value }))
}
/** 필수값 검증 */
const validateData = (data: SubmitFormData): boolean => {
const requiredFields = FORM_FIELDS.filter((field) => field.required)
@ -96,20 +120,21 @@ export default function SurveySaleSubmitPopup() {
return true
}
// TODO: Admin_Sub 계정 매핑된 submit target id 추가!!!! && 메일 테스트트
/** 제출 처리 - 데이터 검증 이후 메일 전송 완료되면 데이터 저장 */
const handleSubmit = () => {
if (validateData(submitData)) {
window.neoConfirm('送信しますか? 送信後は変更・修正することはできません。', () => {
setIsShow(true)
sendEmail({
to: submitData.receiver,
cc: submitData.reference ?? '',
subject: submitData.title,
content: contentsRef.current?.innerHTML ?? '',
})
.then(() => {
if (!isSubmittingSurvey) {
alert('提出が完了しました。')
// submitSurvey({ targetId: submitData.targetId, targetNm: submitData.targetNm })
submitSurvey({ targetId: submitData.targetId, targetNm: submitData.targetNm })
popupController.setSurveySaleSubmitPopup(false)
}
})
@ -118,7 +143,6 @@ export default function SurveySaleSubmitPopup() {
alert('メール送信に失敗しました。 再度送信してください。')
})
.finally(() => {
submitSurvey({ targetId: submitData.targetId, targetNm: submitData.targetNm })
setIsShow(false)
popupController.setSurveySaleSubmitPopup(false)
})
@ -132,6 +156,7 @@ export default function SurveySaleSubmitPopup() {
popupController.setSurveySaleSubmitPopup(false)
}
/** 권한 별 폼 필드 렌더링 */
const renderFormField = (field: FormField) => {
const isReadOnly = false

View File

@ -6,13 +6,19 @@ import { useSuitableStore } from '@/store/useSuitableStore'
export default function SuitableButton() {
const popupController = usePopupController()
const { getSuitableIds, clearSuitableStore, downloadSuitablePdf } = useSuitable()
const { getSuitableIds, clearSuitableStore, downloadSuitablePdf, suitableErrorAlert } = useSuitable()
const { selectedItems, addAllSelectedItem } = useSuitableStore()
/* 데이터 전체 선택 */
const handleSelectAll = async () => {
addAllSelectedItem(await getSuitableIds())
try {
addAllSelectedItem(await getSuitableIds())
} catch (error) {
suitableErrorAlert()
}
}
/* 상세 팝업 열기 */
const handleOpenPopup = () => {
if (selectedItems.size === 0) {
alert('屋根材を選択してください。')
@ -21,6 +27,7 @@ export default function SuitableButton() {
popupController.setSuitableDetailPopup(true)
}
/* pdf 다운로드 */
const handleRedirectPdfDownload = () => {
if (selectedItems.size === 0) {
alert('屋根材を選択してください。')

View File

@ -6,6 +6,7 @@ import SuitableButton from './SuitableButton'
import SuitableNoData from './SuitableNoData'
import { useSuitable } from '@/hooks/useSuitable'
import { useSuitableStore } from '@/store/useSuitableStore'
import { useSpinnerStore } from '@/store/spinnerStore'
import { SUITABLE_HEAD_CODE, type Suitable, type SuitableDetail } from '@/types/Suitable'
export default function SuitableList() {
@ -18,13 +19,15 @@ export default function SuitableList() {
hasNextPage,
isFetchingNextPage,
isLoading,
isError,
suitableCheckIcon,
suitableErrorAlert,
} = useSuitable()
const { selectedItems, addSelectedItem, removeSelectedItem, setSelectedItemsSearching } = useSuitableStore()
const { selectedItems, addSelectedItem, removeSelectedItem } = useSuitableStore()
const [openItems, setOpenItems] = useState<Set<number>>(new Set())
const observerTarget = useRef<HTMLDivElement>(null)
// 선택된 아이템 확인 - 메인 하위 아이템 indeterminate 확인
/* 선택된 아이템 확인 - 메인 하위 아이템 indeterminate 확인 */
const isMainIndeterminate = useMemo(
() => (mainId: number, detailCnt: number) => {
const mainItem = selectedItems.get(mainId)
@ -34,7 +37,7 @@ export default function SuitableList() {
[selectedItems],
)
// 선택된 아이템 확인
/* 선택된 아이템 확인 */
const isItemSelected = useCallback(
(mainId: number, detailId?: number): boolean => {
const mainItem = selectedItems.get(mainId)
@ -45,16 +48,15 @@ export default function SuitableList() {
[selectedItems],
)
// 아이템 클릭
/* 아이템 클릭 */
const handleItemClick = useCallback(
(mainId: number, detailId?: number, detailIds?: Set<number>): void => {
setSelectedItemsSearching(false)
isItemSelected(mainId, detailId) ? removeSelectedItem(mainId, detailId) : addSelectedItem(mainId, detailId, detailIds)
},
[isItemSelected, addSelectedItem, removeSelectedItem],
)
// 아이템 열기/닫기
/* 아이템 열기/닫기 */
const toggleItemOpen = useCallback((itemId: number) => {
setOpenItems((prev) => {
const newOpenItems = new Set(prev)
@ -63,7 +65,7 @@ export default function SuitableList() {
})
}, [])
// 아이템 렌더링
/* 아이템 렌더링 */
const renderItem = useCallback(
(item: Suitable) => {
return (
@ -83,7 +85,7 @@ export default function SuitableList() {
</div>
</div>
<ul className="reference-list check">
{toSuitableDetail(item.detail).map((subItem: SuitableDetail) => (
{toSuitableDetail(item.detail)?.map((subItem: SuitableDetail) => (
<li className="reference-item" key={subItem.id}>
<div className="check-item-wrap">
<div className="check-form-box light">
@ -115,10 +117,10 @@ export default function SuitableList() {
[isItemSelected, openItems, handleItemClick, toggleItemOpen, toCodeName, toSuitableDetail],
)
// 아이템 리스트
/* 조회 데이터 리스트 */
const suitableList = useMemo(() => suitables?.pages.flat() ?? [], [suitables?.pages])
// Intersection Observer 설정
/* Intersection Observer 설정 */
useEffect(() => {
const observer = new IntersectionObserver(
(entries) => {
@ -128,7 +130,7 @@ export default function SuitableList() {
},
{
threshold: 0,
rootMargin: '100px',
rootMargin: `${window.innerHeight * 0.2}px`,
},
)
@ -139,15 +141,23 @@ export default function SuitableList() {
return () => observer.disconnect()
}, [hasNextPage, isFetchingNextPage, fetchNextPage])
if (isLoading) return <div>Loading...</div>
/* 데이터 로딩 상태 처리 */
useEffect(() => {
useSpinnerStore.getState().setIsShow(isLoading || isFetchingNextPage)
}, [isLoading, isFetchingNextPage])
/* 조회 데이터 오류 처리 */
useEffect(() => {
if (isError) suitableErrorAlert()
}, [isError])
/* 조회 데이터 없는 경우 */
if (!suitableList.length) return <SuitableNoData />
return (
<>
{suitableList.map(renderItem)}
<div ref={observerTarget} className="loading-indicator">
{isFetchingNextPage && <div className="loading-more"> ...</div>}
</div>
<div ref={observerTarget} />
<SuitableButton />
</>
)

View File

@ -7,11 +7,12 @@ import type { CommCode } from '@/types/CommCode'
import { SUITABLE_HEAD_CODE } from '@/types/Suitable'
export default function SuitableSearch() {
const [searchValue, setSearchValue] = useState('')
const [searchValue, setSearchValue] = useState<string>('')
const { getSuitableCommCode, clearSuitableStore } = useSuitable()
const { suitableCommCode, selectedCategory, setSelectedCategory, setSearchKeyword } = useSuitableStore()
const { suitableCommCode, searchCategory, setSearchCategory, setSearchKeyword } = useSuitableStore()
/* 키워드 입력 글자 제한 */
const handleInputChange = (value: string) => {
if (Array.from(value).length > 30) {
alert('検索ワードは最大30文字まで入力できます。')
@ -21,6 +22,7 @@ export default function SuitableSearch() {
setSearchValue(value)
}
/* 키워드 검색 */
const handleInputSearch = async () => {
if (!searchValue.trim()) {
alert('屋根材の製品名を入力してください。')
@ -29,6 +31,7 @@ export default function SuitableSearch() {
setSearchKeyword(searchValue)
}
/* 키워드 초기화 */
const handleInputClear = () => {
setSearchValue('')
clearSuitableStore({ items: true, keyword: true })
@ -42,7 +45,7 @@ export default function SuitableSearch() {
return (
<>
<div className="sale-form-bx">
<select className="select-form" name="" id="" value={selectedCategory || ''} onChange={(e) => setSelectedCategory(e.target.value)}>
<select className="select-form" name="" id="" value={searchCategory || ''} onChange={(e) => setSearchCategory(e.target.value)}>
<option value="">.</option>
{suitableCommCode.get(SUITABLE_HEAD_CODE.ROOF_MATL_GRP_CD)?.map((category: CommCode, index: number) => (
<option key={index} value={category.code}>

View File

@ -1,90 +0,0 @@
'use client'
import { useSurveySaleTabState } from '@/store/surveySaleTabState'
import { usePathname, useRouter, useSearchParams, useParams } from 'next/navigation'
import { useEffect } from 'react'
export default function NavTab() {
const router = useRouter()
const pathname = usePathname()
const searchParams = useSearchParams()
const id = searchParams.get('id')
const isTemp = searchParams.get('isTemp')
const params = useParams()
const detailId = params.id
const { basicInfoSelected, roofInfoSelected, reset, setBasicInfoSelected, setRoofInfoSelected } = useSurveySaleTabState()
useEffect(() => {
return () => {
reset()
}
}, [reset])
if (pathname === '/survey-sale') {
return null
}
const scrollSection = (section: string) => {
const sectionElement = document.getElementById(section)
if (sectionElement) {
sectionElement.scrollIntoView({ behavior: 'smooth' })
}
}
const handleBasicInfoClick = () => {
// 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 = () => {
// 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 (
<>
<div className="sale-detail-tab-relative">
<div className="sale-detail-tab-wrap">
<div className="sale-detail-tab-inner">
<button className={`sale-detail-tab ${basicInfoSelected ? 'act' : ''}`} onClick={handleBasicInfoClick}>
</button>
<button className={`sale-detail-tab ${roofInfoSelected ? 'act' : ''}`} onClick={handleRoofInfoClick}>
/
</button>
</div>
</div>
</div>
</>
)
}

View File

@ -1,7 +1,6 @@
'use client'
import { useEffect, useState } from 'react'
import { useSurveySaleTabState } from '@/store/surveySaleTabState'
import type { SurveyBasicRequest } from '@/types/Survey'
import type { Mode } from 'fs'
import { usePopupController } from '@/store/popupController'
@ -16,25 +15,19 @@ interface BasicFormProps {
}
export default function BasicForm({ basicInfo, setBasicInfo, mode, session }: BasicFormProps) {
const { setBasicInfoSelected } = useSurveySaleTabState()
const [isFlip, setIsFlip] = useState<boolean>(true)
const { addressData } = useAddressStore()
const { addressData, resetAddressData } = useAddressStore()
const popupController = usePopupController()
useEffect(() => {
setBasicInfoSelected()
}, [])
// 주소 데이터가 변경될 때만 업데이트
useEffect(() => {
if (!addressData) return
setBasicInfo({
...basicInfo,
postCode: addressData.post_code,
postCode: addressData.post_code.slice(0, 3) + '-' + addressData.post_code.slice(3),
address: addressData.address,
addressDetail: addressData.address_detail,
})
resetAddressData()
}, [addressData])
return (
@ -59,6 +52,7 @@ export default function BasicForm({ basicInfo, setBasicInfo, mode, session }: Ba
onChange={(e) => setBasicInfo({ ...basicInfo, representative: e.target.value })}
/>
</div>
{/* 페이지 모드 별, 권한 별 판매점, 시공점 입력 여부 처리 */}
{mode === 'READ' || session?.role === 'Builder' ? (
<>
{storeInput(basicInfo, setBasicInfo, mode)}
@ -148,6 +142,7 @@ export default function BasicForm({ basicInfo, setBasicInfo, mode, session }: Ba
)
}
/** 판매점 입력 창 */
const storeInput = (basicInfo: SurveyBasicRequest, setBasicInfo: (basicInfo: SurveyBasicRequest) => void, mode: Mode) => {
return (
<div className="data-input-form-bx">
@ -163,6 +158,7 @@ const storeInput = (basicInfo: SurveyBasicRequest, setBasicInfo: (basicInfo: Sur
)
}
/** 시공점 입력 창 */
const builderInput = (basicInfo: SurveyBasicRequest, setBasicInfo: (basicInfo: SurveyBasicRequest) => void, mode: Mode) => {
return (
<div className="data-input-form-bx">

View File

@ -3,7 +3,7 @@
import type { Mode, SurveyBasicRequest, SurveyDetailInfo, SurveyDetailRequest } from '@/types/Survey'
import { useSessionStore } from '@/store/session'
import { useEffect, useState } from 'react'
import { useParams, useRouter, useSearchParams } from 'next/navigation'
import { useParams, useRouter } from 'next/navigation'
import { requiredFields, useSurvey } from '@/hooks/useSurvey'
import { usePopupController } from '@/store/popupController'
@ -29,10 +29,9 @@ interface SaveData extends SurveyBasicRequest {
export default function ButtonForm({ mode, setMode, data }: ButtonFormProps) {
const router = useRouter()
const { session } = useSessionStore()
const searchParams = useSearchParams()
const idParam = searchParams.get('id')
const params = useParams()
const routeId = params.id
const id = Number(params.id)
const popupController = usePopupController()
const [saveData, setSaveData] = useState<SaveData>({
@ -47,7 +46,6 @@ export default function ButtonForm({ mode, setMode, data }: ButtonFormProps) {
})
const isSubmit = data.basic.submissionStatus
const id = Number(routeId) ? Number(routeId) : Number(idParam)
const { deleteSurvey, updateSurvey, isDeletingSurvey, isUpdatingSurvey } = useSurvey(id)
const { validateSurveyDetail, createSurvey, isCreatingSurvey } = useSurvey()
@ -64,14 +62,16 @@ export default function ButtonForm({ mode, setMode, data }: ButtonFormProps) {
})
}, [session, data])
/** 권한 정리 로직 - 작성자(담당자), 제출 권한자, 제출 수신자*/
const calculatePermissions = (session: any, basicData: SurveyBasicRequest): PermissionState => {
const isSubmiter = calculateSubmitPermission(session, basicData)
const isWriter = session.userNm === basicData.representative
const isWriter = session.userId === basicData.representativeId
const isReceiver = session?.storeId === basicData.submissionTargetId
return { isSubmiter, isWriter, isReceiver }
}
/** 제출 권한 체크 */
const calculateSubmitPermission = (session: any, basicData: SurveyBasicRequest): boolean => {
switch (session?.role) {
case 'T01':
@ -87,41 +87,45 @@ export default function ButtonForm({ mode, setMode, data }: ButtonFormProps) {
}
}
/** 저장 로직 */
const handleSave = (isTemporary: boolean, isSubmitProcess: boolean) => {
const emptyField = validateSurveyDetail(data.roof)
const hasEmptyField = emptyField?.trim() !== ''
if (isTemporary) {
hasEmptyField ? tempSaveProcess() : saveProcess(emptyField, false)
tempSaveProcess()
} else {
saveProcess(emptyField, isSubmitProcess)
}
}
/** 임시 저장 로직 */
const tempSaveProcess = async () => {
if (idParam) {
/**route 에 id 가 있는 경우 업데이트, 없는 경우 생성 */
if (!Number.isNaN(id)) {
await updateSurvey({ survey: saveData, isTemporary: true })
if (!isUpdatingSurvey) {
router.push(`/survey-sale/${idParam}`)
setMode('READ')
}
} else {
const updatedData = {
...saveData,
srlNo: '一時保存',
}
const id = await createSurvey(updatedData)
const savedId = await createSurvey(updatedData)
if (!isCreatingSurvey) {
router.push(`/survey-sale/${id}`)
router.push(`/survey-sale/${savedId}`)
}
}
alert('一時保存されました。')
}
/** 입력 필드 포커스 처리 */
const focusInput = (field: keyof SurveyDetailInfo) => {
const input = document.getElementById(field)
input?.focus()
}
/** 저장 로직 */
const saveProcess = async (emptyField: string | null, isSubmitProcess?: boolean) => {
if (emptyField?.trim() === '') {
await handleSuccessfulSave(isSubmitProcess)
@ -130,28 +134,34 @@ export default function ButtonForm({ mode, setMode, data }: ButtonFormProps) {
}
}
/** 저장 성공 로직 */
const handleSuccessfulSave = async (isSubmitProcess?: boolean) => {
if (idParam) {
await updateSurvey({ survey: saveData, isTemporary: false, storeId: session.storeId ?? '' })
/** route 에 id 가 있는 경우 업데이트, 없는 경우 생성 */
if (!Number.isNaN(id)) {
await updateSurvey({
survey: saveData,
isTemporary: false,
storeId: session?.role === 'Partner' ? session?.builderId ?? null : session?.storeId ?? null,
})
if (!isUpdatingSurvey) {
router.push(`/survey-sale/${idParam}`)
setMode('READ')
if (isSubmitProcess) {
popupController.setSurveySaleSubmitPopup(true)
}
}
} else {
const id = await createSurvey(saveData)
if (!isCreatingSurvey) {
router.push(`/survey-sale/${id}`)
/** 제출 로직인 경우 search param 추가 */
const savedId = await createSurvey(saveData)
if (isSubmitProcess) {
await router.push(`/survey-sale/${savedId}?show=true`)
} else {
await router.push(`/survey-sale/${savedId}`)
alert('保存されました。')
}
}
if (isSubmitProcess) {
if (!isCreatingSurvey && !isUpdatingSurvey) {
await popupController.setSurveySaleSubmitPopup(true)
}
} else {
alert('保存されました。')
}
}
/** 필수값 미입력 처리 */
const handleFailedSave = (emptyField: string | null) => {
if (emptyField?.includes('Unit')) {
alert('電気契約容量の単位を入力してください。')
@ -161,8 +171,9 @@ export default function ButtonForm({ mode, setMode, data }: ButtonFormProps) {
focusInput(emptyField as keyof SurveyDetailInfo)
}
/** 삭제 로직 */
const handleDelete = async () => {
if (routeId) {
if (!Number.isNaN(id)) {
window.neoConfirm('削除しますか?', async () => {
await deleteSurvey()
if (!isDeletingSurvey) {
@ -173,13 +184,14 @@ export default function ButtonForm({ mode, setMode, data }: ButtonFormProps) {
}
}
/** 제출 로직 */
const handleSubmit = async () => {
if (data.basic.srlNo?.startsWith('一時保存') && Number(routeId)) {
if (data.basic.srlNo?.startsWith('一時保存') && Number.isNaN(id)) {
alert('一時保存されたデータは提出できません。')
return
}
if (Number(routeId)) {
if (mode === 'READ') {
window.neoConfirm('提出しますか?', async () => {
popupController.setSurveySaleSubmitPopup(true)
})
@ -190,8 +202,10 @@ export default function ButtonForm({ mode, setMode, data }: ButtonFormProps) {
}
}
/** 로그인 여부 체크 */
if (!session?.isLoggedIn) return null
/** 읽기 모드, 제출 된 데이터, 제출 권한자는 리스트 버튼만 표시 */
if (mode === 'READ' && isSubmit && permissions.isSubmiter) {
return (
<div className="sale-form-btn-wrap">
@ -204,19 +218,25 @@ export default function ButtonForm({ mode, setMode, data }: ButtonFormProps) {
return (
<>
{/* 읽기 모드 버튼 처리 */}
{/* 작성자 - 수정, 삭제, 제출(미제출인 매물) 버튼 표시 */}
{/* 제출권한자 - 수정, 제출(미제출인 매물) 버튼 표시 */}
{/* 제출수신자 - 수정, 삭제 버튼 표시 */}
{mode === 'READ' && (
<div className="sale-form-btn-wrap">
<div className="btn-flex-wrap">
<ListButton />
{(permissions.isWriter || permissions.isSubmiter || (permissions.isReceiver && isSubmit)) && (
<EditButton setMode={setMode} id={id.toString()} />
)}
{(permissions.isWriter || permissions.isSubmiter || (permissions.isReceiver && isSubmit)) && <EditButton setMode={setMode} />}
{(permissions.isWriter || (permissions.isReceiver && isSubmit)) && <DeleteButton handleDelete={handleDelete} />}
{!isSubmit && permissions.isSubmiter && <SubmitButton handleSubmit={handleSubmit} />}
</div>
</div>
)}
{/* 수정, 작성 모드 */}
{/* 작성자 - 임시저장, 저장, 제출(미제출인 매물) 버튼 표시 */}
{/* 제출권한자 - 임시저장, 저장, 제출(미제출인 매물) 버튼 표시 */}
{/* 제출수신자 - 임시저장, 저장 버튼 표시 */}
{(mode === 'CREATE' || mode === 'EDIT') && (
<div className="sale-form-btn-wrap">
<div className="btn-flex-wrap">
@ -231,7 +251,7 @@ export default function ButtonForm({ mode, setMode, data }: ButtonFormProps) {
)
}
// Button Components
/** Button Components */
const ListButton = () => {
const router = useRouter()
return (
@ -243,14 +263,12 @@ const ListButton = () => {
)
}
const EditButton = ({ setMode, id }: { setMode: (mode: Mode) => void; id: string }) => {
const router = useRouter()
const EditButton = ({ setMode }: { setMode: (mode: Mode) => void }) => {
return (
<div className="btn-bx">
<button
className="btn-frame n-blue icon"
onClick={() => {
router.push(`/survey-sale/regist?id=${id}`)
setMode('EDIT')
}}
>

View File

@ -1,31 +1,12 @@
'use client'
import { useSurvey } from '@/hooks/useSurvey'
import { useParams, useRouter } from 'next/navigation'
import { useEffect } from 'react'
import DetailForm from './DetailForm'
import { useSessionStore } from '@/store/session'
import { useRouter } from 'next/navigation'
import { SurveyBasicInfo } from '@/types/Survey'
export default function DataTable() {
const params = useParams()
const id = params.id
export default function DataTable({ surveyDetail }: { surveyDetail: SurveyBasicInfo }) {
const router = useRouter()
const { session } = useSessionStore()
useEffect(() => {
if (Number.isNaN(Number(id))) {
alert('間違ったアプローチです。')
window.location.href = '/survey-sale'
}
}, [id])
const { surveyDetail, isLoadingSurveyDetail } = useSurvey(Number(id))
if (isLoadingSurveyDetail) {
return null
}
/** 제출 상태 처리 */
const submitStatus = () => {
const { submissionTargetNm, submissionTargetId } = surveyDetail ?? {}
@ -87,7 +68,7 @@ export default function DataTable() {
<tr>
<th></th>
<td>
<button className="data-down" onClick={() => router.push(`/pdf/survey-sale/${id}`)}>
<button className="data-down" onClick={() => router.push(`/pdf/survey-sale/${surveyDetail.id}`)}>
HWJ現地調査票確認<i className="down-icon"></i>
</button>
</td>
@ -95,7 +76,6 @@ export default function DataTable() {
</tbody>
</table>
</div>
<DetailForm />
</>
)
}

View File

@ -5,9 +5,11 @@ import { useEffect, useState } from 'react'
import ButtonForm from './ButtonForm'
import BasicForm from './BasicForm'
import RoofForm from './RoofForm'
import { useParams, useSearchParams } from 'next/navigation'
import { useParams, useRouter, useSearchParams, usePathname } from 'next/navigation'
import { useSurvey } from '@/hooks/useSurvey'
import { useSessionStore } from '@/store/session'
import DataTable from './DataTable'
import { usePopupController } from '@/store/popupController'
const roofInfoForm: SurveyDetailRequest = {
contractCapacity: null,
@ -68,16 +70,19 @@ const basicInfoForm: SurveyBasicRequest = {
}
export default function DetailForm() {
const idParam = useSearchParams().get('id')
const routeId = useParams().id
const id = useParams().id
const modeset = Number(routeId) ? 'READ' : idParam ? 'EDIT' : 'CREATE'
const id = Number(routeId) ? Number(routeId) : Number(idParam)
const modeset = !Number.isNaN(Number(id)) ? 'READ' : 'CREATE'
const { surveyDetail, isLoadingSurveyDetail, validateSurveyDetail } = useSurvey(Number(id))
const { surveyDetail, isLoadingSurveyDetail } = useSurvey(Number(id))
const { session } = useSessionStore()
const searchParams = useSearchParams()
const popupController = usePopupController()
const router = useRouter()
const pathname = usePathname()
const [mode, setMode] = useState<Mode>(modeset)
const [basicInfoData, setBasicInfoData] = useState<SurveyBasicRequest>(() => ({
...basicInfoForm,
representative: session?.userNm ?? '',
@ -89,7 +94,24 @@ export default function DetailForm() {
}))
const [roofInfoData, setRoofInfoData] = useState<SurveyDetailRequest>(roofInfoForm)
// 세션 데이터가 변경될 때 기본 정보 업데이트
/** route 에러 처리 - 잘못된 URL 접근 시 생성 페이지로 리다이렉트 */
useEffect(() => {
if (modeset === 'CREATE' && pathname !== '/survey-sale/regist') {
router.replace('/survey-sale/regist')
}
return
}, [modeset, id, pathname])
/** 제출 팝업 처리 - createSurvey 이후 popup 처리 시 노드 삽입 오류로 인해 별도 처리 */
useEffect(() => {
const show = searchParams.get('show')
if (show === 'true' && !isLoadingSurveyDetail) {
popupController.setSurveySaleSubmitPopup(true)
router.replace(pathname)
}
}, [searchParams, pathname, isLoadingSurveyDetail])
/** 세션 데이터가 변경될 때 기본 정보 업데이트 */
useEffect(() => {
if (!session?.isLoggedIn) return
setBasicInfoData((prev) => ({
@ -103,10 +125,9 @@ export default function DetailForm() {
}))
}, [session?.isLoggedIn])
// 설문 데이터 로딩 및 업데이트
/** 조사매물 상세 데이터 업데이트 */
useEffect(() => {
if (isLoadingSurveyDetail || !session?.isLoggedIn) return
if (surveyDetail && (mode === 'EDIT' || mode === 'READ')) {
if (!isLoadingSurveyDetail && surveyDetail && (mode === 'EDIT' || mode === 'READ')) {
const { id, uptDt, regDt, detailInfo, ...rest } = surveyDetail
setBasicInfoData((prev) => ({
...prev,
@ -116,12 +137,9 @@ export default function DetailForm() {
if (detailInfo) {
const { id, uptDt, regDt, basicInfoId, ...rest } = detailInfo
setRoofInfoData(rest)
if (validateSurveyDetail(rest).trim() !== '') {
// validation logic here if needed
}
}
}
}, [mode, session?.isLoggedIn, isLoadingSurveyDetail])
}, [mode, isLoadingSurveyDetail, surveyDetail])
const data = {
basic: basicInfoData,
@ -132,6 +150,7 @@ export default function DetailForm() {
return (
<>
{mode === 'READ' && surveyDetail && <DataTable surveyDetail={surveyDetail} />}
<div className="sale-detail-toggle-wrap">
<BasicForm basicInfo={basicInfoData} setBasicInfo={setBasicInfoData} mode={mode} session={session} />
<RoofForm roofInfo={roofInfoData} setRoofInfo={setRoofInfoData} mode={mode} />

View File

@ -19,116 +19,145 @@ type SelectBoxKeys =
| 'installationAvailability'
export const supplementaryFacilities = [
{ id: 1, name: 'エコキュート' }, //에코큐트
{ id: 2, name: 'エネパーム' }, //에네팜
{ id: 3, name: '蓄電池システム' }, //축전지시스템
{ id: 4, name: '太陽光発電' }, //태양광발전
/** 에코큐트 */
{ id: 1, name: 'エコキュート' },
/** 에네팜 */
{ id: 2, name: 'エネパーム' },
/** 축전지시스템 */
{ id: 3, name: '蓄電池システム' },
/** 태양광발전 */
{ id: 4, name: '太陽光発電' },
]
export const roofMaterial = [
{ id: 1, name: 'スレート' }, //슬레이트
{ id: 2, name: 'アスファルトシングル' }, //아스팔트 싱글
{ id: 3, name: '瓦' }, //기와
{ id: 4, name: '金属屋根' }, //금속지붕
/** 슬레이트 */
{ 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: '太陽光発電', //태양광발전
name: '太陽光発電',
},
{
/** 하이브리드축전지시스템 */
id: 2,
name: 'ハイブリッド蓄電システム', //하이브리드축전지시스템
name: 'ハイブリッド蓄電システム',
},
{
/** 축전지시스템 */
id: 3,
name: '蓄電池システム', //축전지시스템
name: '蓄電池システム',
},
],
constructionYear: [
{
/** 신축 */
id: 1,
name: '新築', //신축
name: '新築',
},
{
/** 기축 */
id: 2,
name: '既築', //기존
name: '既築',
},
],
roofShape: [
{
/** 박공지붕 */
id: 1,
name: '切妻', //박공지붕
name: '切妻',
},
{
/** 기동 */
id: 2,
name: '寄棟', //기동
name: '寄棟',
},
{
/** 한쪽흐름 */
id: 3,
name: '片流れ', //한쪽흐름
name: '片流れ',
},
],
rafterSize: [
{
/** 35mm 이상×48mm 이상 */
id: 1,
name: '幅35mm以上×高さ48mm以上',
},
{
/** 36mm 이상×46mm 이상 */
id: 2,
name: '幅36mm以上×高さ46mm以上',
},
{
/** 37mm 이상×43mm 이상 */
id: 3,
name: '幅37mm以上×高さ43mm以上',
},
{
/** 38mm 이상×40mm 이상 */
id: 4,
name: '幅38mm以上×高さ40mm以上',
},
],
rafterPitch: [
{
/** 455mm 이하 */
id: 1,
name: '455mm以下',
},
{
/** 500mm 이하 */
id: 2,
name: '500mm以下',
},
{
/** 606mm 이하 */
id: 3,
name: '606mm以下',
},
],
openFieldPlateKind: [
{
/** 구조용합판 */
id: 1,
name: '構造用合板', //구조용합판
name: '構造用合板',
},
{
/** OSB */
id: 2,
name: 'OSB', //OSB
name: 'OSB',
},
{
/** 파티클보드 */
id: 3,
name: 'パーティクルボード', //파티클보드
name: 'パーティクルボード',
},
{
/** 소판 */
id: 4,
name: '小幅板', //소판
name: '小幅板',
},
],
installationAvailability: [
{
/** 확인완료 */
id: 1,
name: '確認済み', //확인완료
name: '確認済み',
},
{
/** 미확인 */
id: 2,
name: '未確認', //미확인
name: '未確認',
},
],
}
@ -136,58 +165,69 @@ export const selectBoxOptions: Record<SelectBoxKeys, { id: number; name: string
export const radioEtcData: Record<RadioEtcKeys, { id: number; label: string }[]> = {
structureOrder: [
{
/** 지붕재 - 방수재 - 지붕의기초 - 서까래 */
id: 1,
label: '屋根材 > 防水材 > 屋根の基礎 > 垂木', //지붕재 방수재 지붕의기초 서까래
label: '屋根材 > 防水材 > 屋根の基礎 > 垂木',
},
],
houseStructure: [
{
/** 목재 */
id: 1,
label: '木製',
},
],
rafterMaterial: [
{
/** 목재 */
id: 1,
label: '木製',
},
{
/** 강재 */
id: 2,
label: '強制',
},
],
waterproofMaterial: [
{
/** 아스팔트 지붕 940(22kg 이상) */
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: 'なし',
},
@ -210,6 +250,7 @@ export default function RoofForm(props: {
const [isFlip, setIsFlip] = useState<boolean>(true)
const handleNumberInput = (key: keyof SurveyDetailRequest, value: number | string) => {
/** 지붕 경사도, 노지판 두께 처리 - 최대 5자리, 소수점 1자리 처리 */
if (key === 'roofSlope' || key === 'openFieldPlateThickness') {
const stringValue = value.toString()
if (stringValue.length > 5) {
@ -224,6 +265,7 @@ export default function RoofForm(props: {
}
}
}
/** 전기 계약 용량 처리 - 단위 붙여서 저장*/
if (key === 'contractCapacity') {
const remainValue = roofInfo.contractCapacity?.split(' ')[1] ?? roofInfo.contractCapacity
if (Number.isNaN(Number(remainValue))) {
@ -235,6 +277,7 @@ export default function RoofForm(props: {
setRoofInfo({ ...roofInfo, [key]: value.toString() })
}
/** 전기 계약 용량 단위 처리 */
const handleUnitInput = (value: string) => {
const numericValue = roofInfo.contractCapacity?.replace(/[^0-9.]/g, '') || ''
setRoofInfo({
@ -461,6 +504,7 @@ export default function RoofForm(props: {
)
}
/** SelectBox 처리 */
const SelectedBox = ({
mode,
column,
@ -479,6 +523,7 @@ const SelectedBox = ({
const isSpecialCase = column === 'constructionYear' || column === 'installationAvailability'
const showEtcOption = !isSpecialCase
/** SelectBox 값 변경 처리 */
const handleSelectChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
const value = e.target.value
const isEtc = value === 'etc'
@ -498,10 +543,16 @@ const SelectedBox = ({
setRoofInfo(updatedData)
}
/** 기타 입력 처리 */
const handleEtcInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setRoofInfo({ ...detailInfoData, [`${column}Etc`]: e.target.value })
}
/** Input box
* - 모드 : 비활성화
* - 여부 : 기타
* - 연수 : 신축(1)
* */
const isInputDisabled = () => {
if (mode === 'READ') return true
if (column === 'installationAvailability') return false
@ -552,6 +603,7 @@ const SelectedBox = ({
)
}
/** RadioBox 선택 처리 */
const RadioSelected = ({
mode,
column,
@ -572,20 +624,26 @@ const RadioSelected = ({
const isSpecialColumn = column === 'rafterDirection' || column === 'leakTrace' || column === 'insulationPresence'
const showEtcOption = !isSpecialColumn
/** RadioBox 값 변경 처리 */
const handleRadioChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const value = e.target.value
/** 누수 흔적 처리 - boolean 타입이므로 별도 처리 */
if (column === 'leakTrace') {
setRoofInfo({ ...detailInfoData, leakTrace: value === '1' })
return
}
/** 기타 체크 처리 */
if (value === 'etc') {
setEtcChecked(true)
setRoofInfo({ ...detailInfoData, [column]: null, [`${column}Etc`]: '' })
return
}
/** - (1)
* -
* */
const isInsulationPresence = column === 'insulationPresence'
const isRafterDirection = column === 'rafterDirection'
@ -598,10 +656,15 @@ const RadioSelected = ({
})
}
/** 기타 입력 처리 */
const handleEtcInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setRoofInfo({ ...detailInfoData, [`${column}Etc`]: e.target.value })
}
/** Input box
* - 모드 : 비활성화
* - 유무 : 단열재 (1)
* */
const isInputDisabled = () => {
if (mode === 'READ') return true
if (column === 'insulationPresence') {
@ -657,6 +720,7 @@ const RadioSelected = ({
)
}
/** 다중 선택 처리 */
const MultiCheck = ({
mode,
column,
@ -675,6 +739,7 @@ const MultiCheck = ({
const isRoofMaterial = column === 'roofMaterial'
const selectedValues = makeNumArr(String(roofInfo[column as keyof SurveyDetailInfo] ?? ''))
/** 다중 선택 처리 */
const handleCheckbox = (id: number) => {
const isOtherSelected = Boolean(etcValue)
let newValue: string[]
@ -682,6 +747,7 @@ const MultiCheck = ({
if (selectedValues.includes(String(id))) {
newValue = selectedValues.filter((v) => v !== String(id))
} else {
/** 지붕 재료 처리 - 최대 2개 선택 처리 */
if (isRoofMaterial) {
const totalSelected = selectedValues.length + (isOtherSelected || isOtherCheck ? 1 : 0)
if (totalSelected >= 2) {
@ -694,6 +760,7 @@ const MultiCheck = ({
setRoofInfo({ ...roofInfo, [column]: newValue.join(',') })
}
/** 기타 선택 처리 */
const handleOtherCheckbox = () => {
if (isRoofMaterial) {
const currentSelected = selectedValues.length
@ -706,17 +773,19 @@ const MultiCheck = ({
const newIsOtherCheck = !isOtherCheck
setIsOtherCheck(newIsOtherCheck)
// 기타 선택 해제 시 값도 null로 설정
/** 기타 선택 해제 시 값도 null로 설정 */
setRoofInfo({
...roofInfo,
[`${column}Etc`]: newIsOtherCheck ? '' : null,
})
}
/** 기타 입력 처리 */
const handleOtherInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setRoofInfo({ ...roofInfo, [`${column}Etc`]: e.target.value })
}
/** Input box 비활성화 처리 */
const isInputDisabled = () => {
return mode === 'READ' || (!isOtherCheck && !etcValue)
}

View File

@ -27,12 +27,7 @@ export default function ListTable() {
}, [pathname])
useEffect(() => {
if (!session.isLoggedIn || isLoadingSurveyList) return
// if ('status' in surveyList && surveyList.status === 403) {
// alert('権限がありません。')
// router.push('/survey-sale')
// return
// }
if (isLoadingSurveyList) return
if ('count' in surveyList && surveyList.count > 0) {
if (offset > 0) {
setHeldSurveyList((prev) => [...prev, ...surveyList.data])
@ -44,7 +39,7 @@ export default function ListTable() {
setHeldSurveyList([])
setHasMore(false)
}
}, [surveyList, offset, session.isLoggedIn])
}, [surveyList, offset, isLoadingSurveyList])
const handleDetailClick = (id: number) => {
router.push(`/survey-sale/${id}`)

View File

@ -19,6 +19,7 @@ export default function SearchForm({ memberRole, userId }: { memberRole: string;
setKeyword(searchKeyword)
setSearchOption(option)
}
/** 권한 별 검색 옵션 목록 처리 */
const searchOptions = memberRole === 'Partner' ? SEARCH_OPTIONS_PARTNERS : SEARCH_OPTIONS
return (

View File

@ -111,7 +111,7 @@ export default function Header() {
</div>
</SwiperSlide>
<SwiperSlide>
<div className="side-swiper-card">
<div className="side-swiper-card" onClick={() => router.push('/suitable')}>
<div className="side-swiper-icon icon01"></div>
<div className="side-swiper-infor"> </div>
</div>

View File

@ -1,7 +1,8 @@
import getConfigs from '@/config/config.common'
// 환경마다 달라져야 할 변수, 값들을 정의합니다. (여기는 development 환경에 맞는 값을 지정합니다.)
const baseUrl = 'http://1.248.227.176:3000'
// const baseUrl = 'http://172.16.56.60:3000'
const baseUrl = 'https://dev.hanasysfield.jp'
const mode = 'development'
// 환경마다 달라져야 할 값들을 getConfig 함수에 전달합니다.

View File

@ -1,7 +1,8 @@
import getConfigs from '@/config/config.common'
// 환경마다 달라져야 할 변수, 값들을 정의합니다. (여기는 production 환경에 맞는 값을 지정합니다.)
const baseUrl = 'http://localhost.prod:3000'
const baseUrl = 'https://hanasysfield.jp'
// const baseUrl = 'http://172.16.56.55:3000'
const mode = 'production'
// 환경마다 달라져야 할 값들을 getConfig 함수에 전달합니다.

76790
src/data.ts

File diff suppressed because it is too large Load Diff

View File

@ -9,9 +9,10 @@ export function useAxios() {
}
const responseHandler = (response: AxiosResponse) => {
// if (response.headers['spinner-state'] === undefined) {
useSpinnerStore.getState().setIsShow(false)
// }
/* spinner 조작 커스텀이 필요한 경우 api 응답 헤더에 spinner-state: true 추가 */
if (!response.headers['spinner-state']) {
useSpinnerStore.getState().setIsShow(false)
}
response.data = transferResponse(response)
return response
}

View File

@ -9,7 +9,7 @@ export function useCommCode() {
return response.data
} catch (error) {
console.error(`common code (${headCode}) load failed:`, error)
return []
throw error
}
}

View File

@ -4,7 +4,23 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useInquiryFilterStore } from '@/store/inquiryFilterStore'
import { useMemo } from 'react'
import { useSessionStore } from '@/store/session'
import { useRouter } from 'next/navigation'
/**
* @description
*
* @param {number} [qnoNo]
* @param {string} [compCd]
* @returns {Object}
* @returns {InquiryList[]} inquiryList -
* @returns {boolean} isLoadingInquiryList -
* @returns {Inquiry|null} inquiryDetail -
* @returns {boolean} isLoadingInquiryDetail -
* @returns {boolean} isSavingInquiry -
* @returns {Function} saveInquiry -
* @returns {Function} downloadFile -
* @returns {CommonCode[]} commonCodeList -
*/
export function useInquiry(
qnoNo?: number,
compCd?: string,
@ -22,7 +38,48 @@ export function useInquiry(
const { inquiryListRequest, offset } = useInquiryFilterStore()
const { session } = useSessionStore()
const { axiosInstance } = useAxios()
const router = useRouter()
/**
* @description API
*
* @param {any} error
* @returns {void}
*/
const errorRouter = (error: any) => {
const status = error.response?.status
if (error.response?.data.error) {
alert(error.response?.data.error)
}
switch (status) {
// session 없는 경우
case 401:
router.replace('/login')
break
// 조회 권한 없는 경우
case 403:
router.replace('/inquiry/list')
break
// 데이터 DB상 존재하지 않는 경우
case 404:
router.replace('/inquiry/list')
break
// 서버 오류
case 500:
router.back()
break
default:
break
}
}
/**
* @description
*
* @returns {Object}
* @returns {InquiryList[]} data -
* @returns {boolean} isLoading -
*/
const { data: inquiryList, isLoading: isLoadingInquiryList } = useQuery({
queryKey: ['inquiryList', inquiryListRequest, offset],
queryFn: async () => {
@ -32,13 +89,19 @@ export function useInquiry(
})
return resp.data.data
} catch (error: any) {
console.error(error.response.data)
errorRouter(error)
return []
}
},
enabled: !!inquiryListRequest,
})
/**
* @description
*
* @returns {Object}
* @returns {InquiryList[]} inquiryList -
*/
const inquriyListData = useMemo(() => {
if (isLoadingInquiryList) {
return { inquiryList: [] }
@ -48,6 +111,13 @@ export function useInquiry(
}
}, [inquiryList, isLoadingInquiryList])
/**
* @description
*
* @returns {Object}
* @returns {Inquiry|null} data -
* @returns {boolean} isLoading -
*/
const { data: inquiryDetail, isLoading: isLoadingInquiryDetail } = useQuery({
queryKey: ['inquiryDetail', qnoNo, compCd, session?.userId],
queryFn: async () => {
@ -57,13 +127,19 @@ export function useInquiry(
})
return resp.data.data
} catch (error: any) {
console.error(error.response)
errorRouter(error)
return null
}
},
enabled: qnoNo !== undefined && compCd !== undefined,
})
/**
* @description
*
* @param {FormData} formData
* @returns {Promise<InquirySaveResponse>}
*/
const { mutateAsync: saveInquiry, isPending: isSavingInquiry } = useMutation({
mutationFn: async (formData: FormData) => {
const resp = await axiosInstance(null).post<{ data: InquirySaveResponse }>('/api/qna/save', formData)
@ -72,8 +148,18 @@ export function useInquiry(
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['inquiryList'] })
},
onError: (error: any) => {
errorRouter(error)
},
})
/**
* @description
*
* @param {number} encodeFileNo
* @param {string} srcFileNm
* @returns {Promise<Blob|null>} null
*/
const downloadFile = async (encodeFileNo: number, srcFileNm: string) => {
try {
const resp = await fetch(`/api/qna/file?encodeFileNo=${encodeFileNo}&srcFileNm=${srcFileNm}`)
@ -90,12 +176,18 @@ export function useInquiry(
return blob
} catch (error) {
console.error('File download error:', error)
alert('ファイルのダウンロードに失敗しました')
return null
}
}
/**
* @description
*
* @returns {Object}
* @returns {CommonCode[]} data -
* @returns {boolean} isLoading -
*/
const { data: commonCodeList, isLoading: isLoadingCommonCodeList } = useQuery({
queryKey: ['commonCodeList'],
queryFn: async () => {

View File

@ -1,5 +1,4 @@
import { useInfiniteQuery, useQuery } from '@tanstack/react-query'
import { SHA256 } from 'crypto-js'
import { useInfiniteQuery } from '@tanstack/react-query'
import { transformObjectKeys } from '@/libs/axios'
import { useSuitableStore } from '@/store/useSuitableStore'
import { useAxios } from './useAxios'
@ -13,15 +12,24 @@ export function useSuitable() {
itemPerPage,
suitableCommCode,
setSuitableCommCode,
selectedCategory,
clearSelectedCategory,
searchCategory,
clearSearchCategory,
searchKeyword,
clearSearchKeyword,
selectedItems,
clearSelectedItems,
selectedItemsSearching,
} = useSuitableStore()
/**
* @description . API를
*
* @param {Object} param
* @param {number} [param.pageNumber] (기본값: 1)
* @param {string} [param.category]
* @param {string} [param.keyword]
*
* @returns {Promise<Suitable[]>}
*/
const getSuitables = async ({
pageNumber,
category,
@ -42,50 +50,87 @@ export function useSuitable() {
const response = await axiosInstance(null).get<Suitable[]>('/api/suitable/list', { params })
return response.data
} catch (error) {
console.error('지붕재 데이터 로드 실패:', error)
return []
console.error(`지붕재 적합성 데이터 조회 실패: ${error}`)
throw error
}
}
/**
* @description . API를 main_id, detail_id를
*
* @returns {Promise<SuitableIds[]>}
*/
const getSuitableIds = async (): Promise<SuitableIds[]> => {
try {
const params: Record<string, string> = {}
if (selectedCategory) params.category = selectedCategory
if (searchCategory) params.category = searchCategory
if (searchKeyword) params.keyword = searchKeyword
const response = await axiosInstance(null).get<SuitableIds[]>('/api/suitable/pick', { params })
return response.data
} catch (error) {
console.error('지붕재 아이디 로드 실패:', error)
return []
console.error(`지붕재 적합성 데이터 아이디 조회 실패: ${error}`)
throw error
}
}
/**
* @description . API를
*
* @param {string} ids main_id ( )
* @param {string} [detailIds] detail_id ( )
*
* @returns {Promise<Suitable[]>}
*/
const getSuitableDetails = async (ids: string, detailIds?: string): Promise<Suitable[]> => {
try {
const params: Record<string, string> = { ids: ids }
if (detailIds) params.detailIds = detailIds
if (detailIds?.trim()) params.detailIds = detailIds
const response = await axiosInstance(null).post<Suitable[]>('/api/suitable', params)
return response.data
} catch (error) {
console.error('지붕재 상세 데이터 로드 실패:', error)
return []
console.error(`지붕재 적합성 상세 데이터 조회 실패: ${error}`)
throw error
}
}
const getSuitableCommCode = () => {
/**
* @description . API를
*
* @returns {void}
*/
const getSuitableCommCode = (): void => {
const headCodes = Object.values(SUITABLE_HEAD_CODE) as SUITABLE_HEAD_CODE[]
for (const code of headCodes) {
getCommCode(code).then((res) => {
setSuitableCommCode(code, res)
})
getCommCode(code)
.then((res) => {
setSuitableCommCode(code, res)
})
.catch(() => {
suitableErrorAlert()
})
}
}
/**
* @description JP
*
* @param {string} headCode head_code
* @param {string} code code
*
* @returns {string} JP
*/
const toCodeName = (headCode: string, code: string): string => {
const commCode = suitableCommCode.get(headCode)
return commCode?.find((item) => item.code === code)?.codeJp || ''
}
/**
* @description detail string
*
* @param {string} suitableDetailString detail string
*
* @returns {SuitableDetail[]} detail
*/
const toSuitableDetail = (suitableDetailString: string): SuitableDetail[] => {
if (!suitableDetailString) return []
try {
@ -95,36 +140,49 @@ export function useSuitable() {
}
return suitableDetailArray
} catch (error) {
console.error('지붕재 데이터 파싱 실패:', error)
console.error(`지붕재 적합성 detail 데이터 파싱 실패: ${error}`)
return []
}
}
/**
* @description . detail id Set
*
* @param {string} suitableDetailString detail
*
* @returns {Set<number>} detail id
*/
const toSuitableDetailIds = (suitableDetailString: string): Set<number> => {
try {
if (!suitableDetailString) return new Set()
return new Set<number>(JSON.parse(suitableDetailString).map(({ id }: { id: number }) => id))
} catch (error) {
console.error('지붕재 데이터 파싱 실패:', error)
console.error(`지붕재 적합성 detail 데이터 파싱 실패: ${error}`)
return new Set()
}
}
/**
* @description
*
* @returns {Object}
*/
const {
data: suitables,
fetchNextPage,
hasNextPage,
isFetchingNextPage,
isLoading,
// isError,
// error,
isError,
error,
} = useInfiniteQuery<Suitable[]>({
queryKey: ['suitables', 'list', selectedCategory, searchKeyword],
queryKey: ['suitables', 'list', searchCategory, searchKeyword],
queryFn: async (context) => {
const pageParam = context.pageParam as number
if (pageParam === 1) clearSuitableStore({ items: true })
return await getSuitables({
pageNumber: pageParam,
...(selectedCategory && { category: selectedCategory }),
...(searchCategory && { category: searchCategory }),
...(searchKeyword && { keyword: searchKeyword }),
})
},
@ -134,51 +192,34 @@ export function useSuitable() {
initialPageParam: 1,
staleTime: 1000 * 60 * 10,
gcTime: 1000 * 60 * 10,
enabled: selectedCategory !== '' || searchKeyword !== '',
})
const serializeSelectedItems = (): { ids: string; detailIds: string } => {
const ids: string[] = []
const detailIds: string[] = []
for (const [key, value] of selectedItems) {
ids.push(String(key))
for (const id of value) detailIds.push(String(id))
}
return { ids: ids.join(','), detailIds: detailIds.length > 0 ? detailIds.join(',') : '' }
}
const getSelectedItemsHash = (): string => {
const entries = Array.from(selectedItems.entries())
.map(([key, value]) => `${key}:${Array.from(value).sort().join(',')}`)
.sort()
.join('|')
return SHA256(entries).toString()
}
const {
data: selectedSuitables,
isLoading: isSelectedSuitablesLoading,
// refetch: refetchSelectedSuitables,
} = useQuery<Suitable[]>({
queryKey: ['suitables', 'selectedItems', getSelectedItemsHash(), selectedItemsSearching],
queryFn: async () => {
const { ids, detailIds } = serializeSelectedItems()
return await getSuitableDetails(ids, detailIds)
},
staleTime: Infinity,
gcTime: Infinity,
enabled: selectedItemsSearching,
refetchOnMount: false,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
enabled: searchCategory !== '' || searchKeyword !== '',
retry: 1,
retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
})
/**
* @description . , ,
*
* @param {Object} param
* @param {boolean} [param.items]
* @param {boolean} [param.category]
* @param {boolean} [param.keyword]
*
* @returns {void}
*/
const clearSuitableStore = ({ items = false, category = false, keyword = false }: { items?: boolean; category?: boolean; keyword?: boolean }) => {
if (items) clearSelectedItems()
if (category) clearSelectedCategory()
if (category) clearSearchCategory()
if (keyword) clearSearchKeyword()
}
/**
* @description
*
* @param {string} value
*
* @returns {string}
*/
// TODO: 추후 지붕재 적합성 데이터 CUD 구현 시 ×, -, ー 데이터 관리 필요
const suitableCheckIcon = (value: string): string => {
const iconMap: Record<string, string> = {
@ -190,6 +231,13 @@ export function useSuitable() {
return iconMap[value] || iconMap.default
}
/**
* @description
*
* @param {string} value
*
* @returns {string}
*/
// TODO: 추후 지붕재 적합성 데이터 CUD 구현 시 ○, ×, -, ー 데이터 관리 필요
const suitableCheckMemo = (value: string): string => {
if (value === '○') return '設置可'
@ -198,11 +246,47 @@ export function useSuitable() {
return `${value}で設置可`
}
/**
* @description main_id, detail_id를 .
*
* @returns {Object} main_id, detail_id
* @returns {string} main_id ( )
* @returns {string} detail_id ( )
*/
const serializeSelectedItems = (): { ids: string; detailIds: string } => {
const ids: string[] = []
const detailIds: string[] = []
for (const [key, value] of selectedItems) {
ids.push(String(key))
for (const id of value) detailIds.push(String(id))
}
return { ids: ids.join(','), detailIds: detailIds.length > 0 ? detailIds.join(',') : '' }
}
/**
* @description . API를
*
* @returns {Promise<Suitable[]>}
*/
const getSelectedSuitables = async (): Promise<Suitable[]> => {
try {
const { ids, detailIds } = serializeSelectedItems()
return await getSuitableDetails(ids, detailIds)
} catch (error) {
throw error
}
}
/**
* @description pdf . form API를 pdf
*
* @returns {Promise<void>} pdf
*/
const downloadSuitablePdf = async (): Promise<void> => {
try {
const { ids, detailIds } = serializeSelectedItems()
const fileTitle = `(${
suitableCommCode.get(SUITABLE_HEAD_CODE.ROOF_MATL_GRP_CD)?.find((category) => category.code === selectedCategory)?.codeJp
suitableCommCode.get(SUITABLE_HEAD_CODE.ROOF_MATL_GRP_CD)?.find((category) => category.code === searchCategory)?.codeJp
}) `
const form = document.createElement('form')
@ -233,14 +317,22 @@ export function useSuitable() {
form.submit()
document.body.removeChild(form)
} catch (error) {
console.error('지붕재 상세 데이터 pdf 다운로드 실패:', error)
console.error(`지붕재 적합성 상세 데이터 pdf 다운로드 실패: ${error}`)
suitableErrorAlert()
}
}
/**
* @description
*
* @returns {void}
*/
const suitableErrorAlert = (): void => {
alert('一時的なエラーが発生しました。 継続的な場合は、管理者に連絡してください。')
}
return {
getSuitables,
getSuitableIds,
getSuitableDetails,
getSuitableCommCode,
toCodeName,
toSuitableDetail,
@ -250,11 +342,13 @@ export function useSuitable() {
hasNextPage,
isFetchingNextPage,
isLoading,
selectedSuitables,
isSelectedSuitablesLoading,
isError,
error,
getSelectedSuitables,
clearSuitableStore,
suitableCheckIcon,
suitableCheckMemo,
downloadSuitablePdf,
suitableErrorAlert,
}
}

View File

@ -1,5 +1,5 @@
import type { SurveyBasicInfo, SurveyDetailRequest, SurveyRegistRequest } from '@/types/Survey'
import { useMemo, useEffect } from 'react'
import type { SubmitTargetResponse, SurveyBasicInfo, SurveyDetailRequest, SurveyRegistRequest } from '@/types/Survey'
import { useMemo } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useSurveyFilterStore } from '@/store/surveyFilterStore'
import { useSessionStore } from '@/store/session'
@ -54,8 +54,28 @@ type ZipCode = {
kana2: string
kana3: string
}
export function useSurvey(id?: number): {
/**
* @description
*
* @param {number} [id] ID
* @param {boolean} [isPdf] PDF
* @returns {Object}
* @returns {SurveyBasicInfo[]} surveyList -
* @returns {SurveyBasicInfo} surveyDetail -
* @returns {boolean} isLoadingSurveyList -
* @returns {boolean} isLoadingSurveyDetail -
* @returns {boolean} isCreatingSurvey -
* @returns {boolean} isUpdatingSurvey -
* @returns {boolean} isDeletingSurvey -
* @returns {boolean} isSubmittingSurvey -
* @returns {Function} createSurvey -
* @returns {Function} updateSurvey -
* @returns {Function} deleteSurvey -
*/
export function useSurvey(
id?: number,
isPdf?: boolean,
): {
surveyList: { data: SurveyBasicInfo[]; count: number } | {}
surveyDetail: SurveyBasicInfo | null
isLoadingSurveyList: boolean
@ -65,12 +85,14 @@ export function useSurvey(id?: number): {
isDeletingSurvey: boolean
isSubmittingSurvey: boolean
createSurvey: (survey: SurveyRegistRequest) => Promise<number>
updateSurvey: ({ survey, isTemporary, storeId }: { survey: SurveyRegistRequest; isTemporary: boolean; storeId?: string }) => void
updateSurvey: ({ survey, isTemporary, storeId }: { survey: SurveyRegistRequest; isTemporary: boolean; storeId?: string | null }) => void
deleteSurvey: () => Promise<boolean>
submitSurvey: (params: { targetId?: string | null; targetNm?: string | null }) => void
validateSurveyDetail: (surveyDetail: SurveyDetailRequest) => string
getZipCode: (zipCode: string) => Promise<ZipCode[] | null>
refetchSurveyList: () => void
refetchSurveyDetail: () => void
getSubmitTarget: (params: { storeId: string; role: string }) => Promise<SubmitTargetResponse[] | null>
} {
const queryClient = useQueryClient()
const { keyword, searchOption, isMySurvey, sort, offset } = useSurveyFilterStore()
@ -78,33 +100,48 @@ export function useSurvey(id?: number): {
const { axiosInstance } = useAxios()
const router = useRouter()
const checkSession = () => {
if (session?.isLoggedIn) {
switch (session?.role) {
case 'T01':
case 'Admin':
case 'Admin_Sub':
if (session?.storeId === null) {
alert('販売店IDがありません。')
return false
}
return true
case 'Builder':
case 'Partner':
if (session?.builderId === null) {
alert('施工店IDがありません。')
return false
}
return true
default:
alert('権限が間違っています。')
return false
}
/**
* @description ,
*
* @param {any} error
* @returns {void}
*/
const errorRouter = (error: any) => {
const status = error.response?.status
if (error.response?.data.error) {
alert(error.response?.data.error)
}
switch (status) {
/** session 없는 경우 */
case 401:
router.replace('/login')
break
/** 조회 권한 없는 경우 */
case 403:
router.replace('/survey-sale')
break
/** 데이터 DB상 존재하지 않는 경우 */
case 404:
router.replace('/survey-sale')
break
/** 서버 오류 */
case 500:
router.back()
break
default:
break
}
alert('ログインしていません。')
return false
}
/**
* @description
*
* @returns {Object}
* @returns {SurveyBasicInfo[]}
* @returns {number}
* @returns {() => void}
* @returns {boolean}
*/
const {
data: surveyListData,
isLoading: isLoadingSurveyList,
@ -112,26 +149,34 @@ export function useSurvey(id?: number): {
} = useQuery({
queryKey: ['survey', 'list', keyword, searchOption, isMySurvey, sort, offset, session?.storeNm, session?.builderId, session?.role],
queryFn: async () => {
if (!checkSession()) {
router.replace('/')
try {
const resp = await axiosInstance(null).get<{ data: SurveyBasicInfo[]; count: number }>('/api/survey-sales', {
params: {
keyword,
searchOption,
isMySurvey,
sort,
offset,
storeId: session?.storeId,
builderId: session?.builderId,
role: session?.role,
},
})
return resp.data
} catch (error: any) {
errorRouter(error)
return { data: [], count: 0 }
}
const resp = await axiosInstance(null).get<{ data: SurveyBasicInfo[]; count: number }>('/api/survey-sales', {
params: {
keyword,
searchOption,
isMySurvey,
sort,
offset,
storeId: session?.storeId,
builderId: session?.builderId,
role: session?.role,
},
})
return resp.data
},
enabled: session?.isLoggedIn,
})
/**
* @description
*
* @returns {Object}
* @returns {number} count -
* @returns {SurveyBasicInfo[]} data -
*/
const surveyData = useMemo(() => {
if (!surveyListData) return { count: 0, data: [] }
return {
@ -139,51 +184,70 @@ export function useSurvey(id?: number): {
}
}, [surveyListData])
const { data: surveyDetail, isLoading: isLoadingSurveyDetail } = useQuery({
/**
* @description
*
* @returns {Object}
* @returns {SurveyBasicInfo} surveyDetail -
* @returns {boolean} isLoadingSurveyDetail -
* @returns {() => void} refetchSurveyDetail -
*/
const {
data: surveyDetail,
isLoading: isLoadingSurveyDetail,
refetch: refetchSurveyDetail,
} = useQuery({
queryKey: ['survey', id],
queryFn: async () => {
if (!checkSession()) {
router.replace('/survey-sale')
return null
}
if (id === 0 || id === undefined) return null
if (Number.isNaN(id) || id === undefined || id === 0) return null
try {
const resp = await axiosInstance(null).get<SurveyBasicInfo>(`/api/survey-sales/${id}`, {
params: {
role: session?.role,
storeId: session?.storeId,
builderId: session?.builderId,
isLoggedIn: session?.isLoggedIn,
isPdf: isPdf,
},
})
return resp.data
} catch (error: any) {
alert(error.response?.data.error)
router.replace('/survey-sale')
errorRouter(error)
return null
}
},
enabled: id !== 0 && id !== undefined && session?.isLoggedIn,
enabled: id !== 0 && id !== undefined && id !== null,
})
/**
* @description
*
* @param {SurveyRegistRequest} survey
* @returns {Promise<number>} ID
*/
const { mutateAsync: createSurvey, isPending: isCreatingSurvey } = useMutation({
mutationFn: async (survey: SurveyRegistRequest) => {
const resp = await axiosInstance(null).post<SurveyBasicInfo>('/api/survey-sales', {
const resp = await axiosInstance(null).post<{ id: number }>('/api/survey-sales', {
survey: survey,
storeId: session?.storeId ?? null,
storeId: session?.role === 'Partner' ? session?.builderId ?? null : session?.storeId ?? null,
role: session?.role ?? null,
})
return resp.data.id ?? 0
},
onSuccess: (data) => {
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['survey', 'list'] })
queryClient.invalidateQueries({ queryKey: ['survey', id] })
return data
},
})
/**
* @description
*
* @param {Object} params
* @param {SurveyRegistRequest} params.survey
* @param {boolean} params.isTemporary
* @param {string|null} [params.storeId] ID
* @returns {Promise<SurveyRegistRequest>}
* @throws {Error} id가
*/
const { mutate: updateSurvey, isPending: isUpdatingSurvey } = useMutation({
mutationFn: async ({ survey, isTemporary, storeId }: { survey: SurveyRegistRequest; isTemporary: boolean; storeId?: string }) => {
mutationFn: async ({ survey, isTemporary, storeId }: { survey: SurveyRegistRequest; isTemporary: boolean; storeId?: string | null }) => {
if (id === undefined) throw new Error('id is required')
const resp = await axiosInstance(null).put<SurveyRegistRequest>(`/api/survey-sales/${id}`, {
survey: survey,
@ -197,8 +261,21 @@ export function useSurvey(id?: number): {
queryClient.invalidateQueries({ queryKey: ['survey', id] })
queryClient.invalidateQueries({ queryKey: ['survey', 'list'] })
},
onError: (error: any) => {
alert(error.response?.data.error)
},
})
/**
* @description
*
* @returns {Promise<boolean>}
* @throws {Error} id가
*
* @example
*
*
*/
const { mutateAsync: deleteSurvey, isPending: isDeletingSurvey } = useMutation({
mutationFn: async () => {
if (id === null) throw new Error('id is required')
@ -207,10 +284,21 @@ export function useSurvey(id?: number): {
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['survey', 'list'] })
queryClient.invalidateQueries({ queryKey: ['survey', id] })
},
onError: (error: any) => {
alert(error.response?.data.error)
},
})
/**
* @description
*
* @param {Object} params
* @param {string|null} [params.targetId] ID
* @param {string|null} [params.targetNm]
* @returns {Promise<boolean>}
* @throws {Error} id가
*/
const { mutateAsync: submitSurvey, isPending: isSubmittingSurvey } = useMutation({
mutationFn: async ({ targetId, targetNm }: { targetId?: string | null; targetNm?: string | null }) => {
if (!id) throw new Error('id is required')
@ -224,15 +312,22 @@ export function useSurvey(id?: number): {
queryClient.invalidateQueries({ queryKey: ['survey', 'list'] })
queryClient.invalidateQueries({ queryKey: ['survey', id] })
},
onError: (error: any) => {
alert(error.response?.data.error)
},
})
/**
* @description
*
* @param {SurveyDetailRequest} surveyDetail
* @returns {string}
*/
const validateSurveyDetail = (surveyDetail: SurveyDetailRequest) => {
// 상수 정의
const ETC_FIELDS = ['installationSystem', 'rafterSize', 'rafterPitch', 'waterproofMaterial', 'structureOrder'] as const
const SPECIAL_CONDITIONS = ['constructionYear', 'insulationPresence'] as const
// 유틸리티 함수들
const isEmptyValue = (value: any): boolean => {
return value === null || value?.toString().trim() === ''
}
@ -267,18 +362,60 @@ export function useSurvey(id?: number): {
return ''
}
/**
* @description
*
* @param {string} zipCode
* @returns {Promise<ZipCode[]|null>}
* @throws {Error}
*/
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)
} catch (error: any) {
console.error('Failed to fetch zipcode data:', error)
alert(error.response?.data.error)
throw new Error('Failed to fetch zipcode data')
}
}
/**
* @description
*
* @param {Object} params
* @param {string} params.storeId ID
* @param {string} params.role
* @returns {Promise<SubmitTargetResponse[]|null>}
*/
const getSubmitTarget = async (params: { storeId: string; role: string }): Promise<SubmitTargetResponse[] | null> => {
try {
if (!params.storeId) {
alert('販売店IDがありません。')
return null
}
const endpoints = {
Admin_Sub: `/api/submission/admin-sub?id=${params.storeId}`,
Builder: `/api/submission/builder?id=${params.storeId}`,
} as const
const endpoint = endpoints[params.role as keyof typeof endpoints]
if (!endpoint) {
alert('権限が間違っています。')
return null
}
const { data } = await axiosInstance(null).get<SubmitTargetResponse[]>(endpoint)
return data
} catch (error: any) {
alert(error.response?.data.error)
return null
}
}
return {
surveyList: surveyData.data,
surveyDetail: surveyDetail as SurveyBasicInfo | null,
@ -294,6 +431,8 @@ export function useSurvey(id?: number): {
submitSurvey,
validateSurveyDetail,
getZipCode,
getSubmitTarget,
refetchSurveyList,
refetchSurveyDetail,
}
}

View File

@ -1,8 +1,8 @@
export const useTitle = () => {
const getTitle = (pathname: string) => {
// Handle dynamic routes first
if (pathname.startsWith('/survey-sale/') && pathname !== '/survey-sale/basic-info' && pathname !== '/survey-sale/roof-info') {
return '調査物件一覧'
if (pathname.startsWith('/survey-sale/') && pathname !== '/survey-sale/regist') {
return '調査物件詳細'
}
if (pathname.startsWith('/inquiry/') && pathname !== '/inquiry/list' && pathname !== '/inquiry/regist') {
@ -17,10 +17,8 @@ export const useTitle = () => {
return '屋根材適合性の確認'
case '/survey-sale':
return '調査物件一覧'
case '/survey-sale/basic-info':
case '/survey-sale/regist':
return '調査物件登録'
case '/survey-sale/roof-info':
return '調査物件新規登録'
case '/inquiry/list':
return '1:1お問い合わせ'
case '/inquiry/regist':

21
src/libs/api-wrapper.ts Normal file
View File

@ -0,0 +1,21 @@
import { NextRequest, NextResponse } from 'next/server'
import { writeApiLog } from './logger'
export function loggerWrapper(handler: (req: NextRequest) => Promise<NextResponse>): (req: NextRequest) => Promise<NextResponse> {
return async function (req: NextRequest) {
const reqClone = req.clone()
const response = await handler(req)
await writeApiLog(
new NextRequest(req.url, {
method: req.method,
headers: req.headers,
body: reqClone.body ? await reqClone.text() : undefined,
}),
response.status,
)
return response
}
}

95
src/libs/logger.ts Normal file
View File

@ -0,0 +1,95 @@
import { NextRequest } from 'next/server'
import { join } from 'path'
import pino from 'pino'
/* 실행 모드 */
const isProduction = process.env.NODE_ENV === 'production'
/* 로그 데이터 인터페이스 */
interface ApiLogData {
responseStatus: number
method: string
url: string
// headers: { [k: string]: string }
query: { [k: string]: string }
body: string | undefined
}
/* 날짜별 로그 파일 경로 생성 함수 */
const getLogFilePath = (): string => {
const today = new Date().toISOString().split('T')[0] // YYYY-MM-DD 형식
return join(process.cwd(), 'logs', `onsite-survey-${today}.log`)
}
/* 날짜별 로거 생성 클래스 */
class DailyLogger {
private currentDate: string
private logger: pino.Logger
private destination: ReturnType<typeof pino.destination>
constructor() {
this.currentDate = new Date().toISOString().split('T')[0]
this.destination = pino.destination({
dest: getLogFilePath(),
mkdir: true,
sync: false,
})
this.logger = this.createLogger()
/* kill signal 핸들러 등록 */
process.on('SIGTERM', this.handleShutdown.bind(this))
process.on('SIGINT', this.handleShutdown.bind(this))
}
private async handleShutdown(): Promise<void> {
this.destination.flushSync()
this.destination.end()
}
private createLogger(): pino.Logger {
return pino(
{
level: isProduction ? 'info' : 'silent',
timestamp: pino.stdTimeFunctions.isoTime,
},
this.destination,
)
}
public info(obj: any, msg?: string): void {
const today = new Date().toISOString().split('T')[0]
if (today !== this.currentDate) {
/* 기존 destination 종료 */
this.destination.flushSync()
this.destination.end()
/* 새로운 destination 생성 */
this.destination = pino.destination({
dest: getLogFilePath(),
mkdir: true,
sync: false,
})
this.currentDate = today
this.logger = this.createLogger()
}
this.logger.info(obj, msg)
}
}
/* 로거 인스턴스 */
const dailyLogger = new DailyLogger()
/* API 로그 기록 함수 */
export const writeApiLog = async (request: NextRequest, responseStatus: number): Promise<void> => {
const logData: ApiLogData = {
responseStatus: responseStatus,
method: request.method,
url: request.url,
// headers: Object.fromEntries(request.headers),
query: Object.fromEntries(new URL(request.url).searchParams),
body: request.body ? await request.text() : undefined,
}
dailyLogger.info(logData, 'API Request')
}

View File

@ -1,11 +1,43 @@
import { PrismaClient } from '@prisma/client'
declare global {
var prisma: PrismaClient | undefined
// 환경별 설정
const isDevelopment = process.env.NODE_ENV === 'development'
const isProduction = process.env.NODE_ENV === 'production'
const globalForPrisma = globalThis as unknown as {
prisma: PrismaClient | undefined
}
export const prisma = global.prisma || new PrismaClient()
// Prisma Client 설정
export const prisma =
globalForPrisma.prisma ??
new PrismaClient({
log: isDevelopment ? ['query', 'error', 'warn'] : ['error'],
if (process.env.NODE_ENV !== 'production') {
global.prisma = prisma
// 데이터소스 설정
datasources: {
db: {
url: process.env.DATABASE_URL,
},
},
// 에러 포맷팅
errorFormat: isDevelopment ? 'pretty' : 'minimal',
})
// 개발 환경에서만 글로벌 객체에 저장
if (!isProduction) globalForPrisma.prisma = prisma
// Graceful shutdown
const shutdown = async () => {
console.log('🚀 ~ shutdown ~ Shutting down Prisma Client...:')
await prisma.$disconnect()
process.exit(0)
}
process.on('SIGINT', shutdown)
process.on('SIGTERM', shutdown)
process.on('beforeExit', async () => {
console.log('🚀 ~ process.on ~ beforeExit:')
await prisma.$disconnect()
})

View File

@ -36,12 +36,12 @@ export default function EdgeProvider({ children, sessionData }: EdgeProviderProp
*
*
*/
const handlePageEvent = (path: string) => {
tracking({
url: path,
data: '',
})
}
// const handlePageEvent = (path: string) => {
// tracking({
// url: path,
// data: '',
// })
// }
/**
* alert - window.alert
@ -69,17 +69,6 @@ export default function EdgeProvider({ children, sessionData }: EdgeProviderProp
}
useEffect(() => {
if (pathname === '/login') {
if (session?.isLoggedIn) {
router.push('/')
}
}
if (pathname === '/') {
if (!session?.isLoggedIn) {
router.push('/login')
}
}
//alert 함수 변경해서 바인딩
window.alert = function (msg, alertBtn = () => setAlert(false)) {
alertFunc(msg, alertBtn)
@ -94,6 +83,13 @@ export default function EdgeProvider({ children, sessionData }: EdgeProviderProp
alertFunc2(msg, alertBtn2Yes || (() => {}), alertBtn2No || (() => {}))
return false
}
if (sessionData === '') {
router.push('/login')
} else {
if (pathname === '/login') {
router.push('/')
}
}
// 서버 세션이 있으면 zuatand 세션 데이터 갱신
if (sessionData && sessionData !== '') {
setSession({
@ -116,7 +112,7 @@ export default function EdgeProvider({ children, sessionData }: EdgeProviderProp
//사이드바 초기화
reset()
// 페이지 이벤트 트래킹
handlePageEvent(pathname)
// handlePageEvent(pathname)
}, [pathname])
return (

View File

@ -1,6 +1,9 @@
import { InquiryListRequest } from '@/types/Inquiry'
import { create } from 'zustand'
/**
* @description
*/
type InquiryFilterState = {
inquiryListRequest: InquiryListRequest
setInquiryListRequest: (inquiryListRequest: InquiryListRequest) => void
@ -9,6 +12,15 @@ type InquiryFilterState = {
setOffset: (offset: number) => void
}
/**
* @description
*
* @param {InquiryListRequest} inquiryListRequest
* @param {Function} setInquiryListRequest
* @param {Function} reset
* @param {number} offset
* @param {Function} setOffset
*/
export const useInquiryFilterStore = create<InquiryFilterState>((set) => ({
inquiryListRequest: {
compCd: '5200',

View File

@ -1,5 +1,11 @@
import { create } from 'zustand'
/**
* @description
*
* @param {string} id ID
* @param {string} label
*/
export const SEARCH_OPTIONS = [
{
id: 'all',
@ -35,6 +41,12 @@ export const SEARCH_OPTIONS = [
},
]
/**
* @description -
*
* @param {string} id ID
* @param {string} label
*/
export const SEARCH_OPTIONS_PARTNERS = [
{
id: 'all',
@ -54,8 +66,19 @@ export const SEARCH_OPTIONS_PARTNERS = [
},
]
/**
* @description
*/
export type SEARCH_OPTIONS_ENUM = (typeof SEARCH_OPTIONS)[number]['id']
/**
* @description
*/
export type SEARCH_OPTIONS_PARTNERS_ENUM = (typeof SEARCH_OPTIONS_PARTNERS)[number]['id']
/**
* @description
*/
export type SORT_OPTIONS_ENUM = 'created' | 'updated'
type SurveyFilterState = {
@ -72,6 +95,22 @@ type SurveyFilterState = {
reset: () => void
}
/**
* @description
*
* @param {string} keyword
* @param {SEARCH_OPTIONS_ENUM | SEARCH_OPTIONS_PARTNERS_ENUM} searchOption
* @param {string | null} isMySurvey
* @param {SORT_OPTIONS_ENUM} sort
* @param {number} offset
*
* @param {Function} setKeyword
* @param {Function} setSearchOption
* @param {Function} setIsMySurvey
* @param {Function} setSort
* @param {Function} setOffset
* @param {Function} reset
*/
export const useSurveyFilterStore = create<SurveyFilterState>((set) => ({
keyword: '',
searchOption: 'all',

View File

@ -1,26 +0,0 @@
import { create } from 'zustand'
type SurveySaleTabState = {
basicInfoSelected: boolean
roofInfoSelected: boolean
setBasicInfoSelected: () => void
setRoofInfoSelected: () => void
reset: () => void
}
type InitialState = {
basicInfoSelected: boolean
roofInfoSelected: boolean
}
const initialState: InitialState = {
basicInfoSelected: true,
roofInfoSelected: false,
}
export const useSurveySaleTabState = create<SurveySaleTabState>((set) => ({
...initialState,
setBasicInfoSelected: () => set((state) => ({ ...state, basicInfoSelected: true, roofInfoSelected: false })),
setRoofInfoSelected: () => set((state) => ({ ...state, basicInfoSelected: false, roofInfoSelected: true })),
reset: () => set(initialState),
}))

View File

@ -11,43 +11,38 @@ interface SuitableState {
/* 공통코드 설정 */
setSuitableCommCode: (headCode: string, commCode: CommCode[]) => void
/* 선택된 카테고리 */
selectedCategory: string
/* 선택된 카테고리 설정 */
setSelectedCategory: (category: string) => void
/* 선택된 카테고리 초기화 */
clearSelectedCategory: () => void
/* 검색 카테고리 */
searchCategory: string
/* 검색 카테고리 설정 */
setSearchCategory: (category: string) => void
/* 검색 카테고리 초기화 */
clearSearchCategory: () => void
/* 검색 */
/* 검색 키워드 */
searchKeyword: string
/* 검색 설정 */
/* 검색 키워드 설정 */
setSearchKeyword: (value: string) => void
/* 검색 초기화 */
/* 검색 키워드 초기화 */
clearSearchKeyword: () => void
/* 선택된 아이템 리스트 */
selectedItems: Map<number, Set<number>>
/* 선택 아이템 추가 */
addSelectedItem: (mainId: number, detailId?: number, detailIds?: Set<number>) => void
/* 아이템 전체 추가 */
/* 선택 아이템 전체 추가 */
addAllSelectedItem: (suitableIds: SuitableIds[]) => void
/* 선택 아이템 제거 */
/* 선택 아이템 제거 */
removeSelectedItem: (mainId: number, detailId?: number) => void
/* 선택 아이템 모두 제거 */
/* 선택 아이템 모두 제거 */
clearSelectedItems: () => void
/* 선택된 아이템 검색 상태 */
selectedItemsSearching: boolean
/* 선택된 아이템 검색 상태 설정 */
setSelectedItemsSearching: (value: boolean) => void
}
export const useSuitableStore = create<SuitableState>((set) => ({
itemPerPage: 100 as number,
suitableCommCode: new Map() as Map<string, CommCode[]>,
selectedCategory: '' as string,
searchCategory: '' as string,
searchKeyword: '' as string,
selectedItems: new Map() as Map<number, Set<number>>,
selectedItemsSearching: false as boolean,
/* 공통코드 설정 */
setSuitableCommCode: (headCode: string, commCode: CommCode[]) =>
@ -55,20 +50,20 @@ export const useSuitableStore = create<SuitableState>((set) => ({
suitableCommCode: new Map(state.suitableCommCode).set(headCode, commCode),
})),
/* 선택된 카테고리 설정 */
setSelectedCategory: (category: string) => set({ selectedCategory: category }),
/* 선택된 카테고리 초기화 */
clearSelectedCategory: () => set({ selectedCategory: '' }),
/* 검색 카테고리 설정 */
setSearchCategory: (category: string) => set({ searchCategory: category }),
/* 검색 카테고리 초기화 */
clearSearchCategory: () => set({ searchCategory: '' }),
/* 검색 설정 */
/* 검색 키워드 설정 */
setSearchKeyword: (value: string) => set({ searchKeyword: value }),
/* 검색 초기화 */
/* 검색 키워드 초기화 */
clearSearchKeyword: () => set({ searchKeyword: '' }),
/* 선택 아이템 추가 */
/* 선택 아이템 추가 */
addSelectedItem: (mainId: number, detailId?: number, detailIds?: Set<number>) => {
if (detailId) {
// 디테일(하위) 아이템 추가
/* 디테일(하위) 아이템 추가 */
set((state) => {
const detailSet = state.selectedItems.get(mainId) || new Set()
detailSet.add(detailId)
@ -76,7 +71,7 @@ export const useSuitableStore = create<SuitableState>((set) => ({
return { selectedItems: state.selectedItems }
})
} else {
// 메인(상위) 아이템 추가
/* 메인(상위) 아이템 추가 */
set((state) => {
state.selectedItems.set(mainId, detailIds || new Set())
return { selectedItems: state.selectedItems }
@ -84,7 +79,7 @@ export const useSuitableStore = create<SuitableState>((set) => ({
}
},
/* 아이템 전체 추가 */
/* 선택 아이템 전체 추가 */
addAllSelectedItem: (suitableIds: SuitableIds[]) => {
set(() => {
const newSelectedItems = new Map()
@ -95,31 +90,28 @@ export const useSuitableStore = create<SuitableState>((set) => ({
})
},
/* 선택 아이템 제거 */
/* 선택 아이템 제거 */
removeSelectedItem: (mainId: number, detailId?: number) => {
set((state) => {
const newSelectedItems = new Map(state.selectedItems)
if (!detailId) {
// 메인(상위) 아이템 제거
/* 메인(상위) 아이템 제거 */
newSelectedItems.delete(mainId)
return { selectedItems: newSelectedItems }
}
// 디테일(하위) 아이템 제거
/* 디테일(하위) 아이템 제거 */
const detailSet = state.selectedItems.get(mainId) || new Set()
detailSet.delete(detailId)
// 디테일(하위)하위 아이템이 모두 제거되면 메인 아이템도 제거
/* 디테일(하위)하위 아이템이 모두 제거되면 메인 아이템도 제거 */
detailSet.size === 0 ? newSelectedItems.delete(mainId) : newSelectedItems.set(mainId, detailSet)
return { selectedItems: newSelectedItems }
})
},
/* 선택 아이템 모두 제거 */
/* 선택 아이템 모두 제거 */
clearSelectedItems: () => set({ selectedItems: new Map() as Map<number, Set<number>> }),
/* 선택된 아이템 검색 상태 설정 */
setSelectedItemsSearching: (value: boolean) => set({ selectedItemsSearching: value }),
}))

View File

@ -1,94 +1,190 @@
/**
* @description
*/
export type InquiryListRequest = {
compCd: string //company code
langCd: string //language code
storeId: string //store id
siteTpCd: string //site type code (QC: QCast, QR: QRead)
schTitle: string | null //search title
schRegId: string | null //search regId
schFromDt: string | null //search start date
schToDt: string | null //search end date
schAnswerYn: string | null //search answer yn
loginId: string //login id
/* 회사 코드 */
compCd: string
/* 언어 코드 */
langCd: string
/* 판매점 ID */
storeId: string
/* 사이트 유형 코드 */
siteTpCd: string
/* 검색 제목 */
schTitle: string | null
/* 검색 등록자 ID */
schRegId: string | null
/* 검색 시작 일자 */
schFromDt: string | null
/* 검색 종료 일자 */
schToDt: string | null
/* 검색 답변 여부 */
schAnswerYn: string | null
/* 로그인 ID */
loginId: string
}
/**
* @description
*/
export type InquiryList = {
totCnt: number //total count
rowNumber: number //row number
compCd: string //company code
qnaNo: number //qna number
qstTitle: string //title
regDt: string //registration date
regId: string //registration Userid
regNm: string //registration User name
answerYn: string //answer yn - Y / N
attachYn: string | null //attach yn - Y / N
qnaClsLrgCd: string //qna CLS large Code
qnaClsMidCd: string //qna CLS Mid Code
qnaClsSmlCd: string | null //qna CLS Small Code
regUserNm: string //registration User name
/* 총 건수 */
totCnt: number
/* 행 번호 */
rowNumber: number
/* 회사 코드 */
compCd: string
/* 문의 번호 */
qnaNo: number
/* 문의 제목 */
qstTitle: string
/* 문의 등록 일자 */
regDt: string
/* 문의 등록자 이메일 */
regEmail: string
/* 문의 등록자 ID */
regId: string
/* 문의 등록자 이름 */
regNm: string
/* 답변 여부 */
answerYn: string
/* 첨부 여부 */
attachYn: string | null
/* 문의 대분류 코드 */
qnaClsLrgCd: string
/* 문의 중분류 코드 */
qnaClsMidCd: string
/* 문의 소분류 코드 */
qnaClsSmlCd: string | null
/* 문의 등록자 이름 */
regUserNm: string
}
/**
* @description
*/
export type InquiryDetailRequest = {
compCd: string //company code
langCd: string //language code
qnaNo: number //qna number
loginId: string //login id
/* 회사 코드 */
compCd: string
/* 언어 코드 */
langCd: string
/* 문의 번호 */
qnaNo: number
/* 로그인 ID */
loginId: string
}
/**
* @description
*/
export type Inquiry = {
compCd: string //company code
qnaNo: number //qna number
qstTitle: string //title
qstContents: string //content
regDt: string //registration date
regId: string //registration Userid
regNm: string //registration User name
regEmail: string //registration User email
answerYn: string //answer yn - Y / N
ansContents: string | null //answer content
ansRegDt: string | null //answer registration date
ansRegNm: string | null //answer registration User name
storeId: string | null //store id
storeNm: string | null //store name
regUserNm: string //registration User name
regUserTelNo: string | null //registration User tel number
qnaClsLrgCd: string //qna CLS large Code
qnaClsMidCd: string //qna CLS Mid Code
qnaClsSmlCd: string | null //qna CLS Small Code
listFile: listFile[] | null //Question list file
ansListFile: listFile[] | null //Answer list file
/* 회사 코드 */
compCd: string
/* 문의 번호 */
qnaNo: number
/* 문의 제목 */
qstTitle: string
/* 문의 내용 */
qstContents: string
/* 문의 등록 일자 */
regDt: string
/* 문의 등록자 ID */
regId: string
/* 문의 등록자 이름 */
regNm: string
/* 문의 등록자 이메일 */
regEmail: string
/* 답변 여부 */
answerYn: string
/* 답변 내용 */
ansContents: string | null
/* 답변 등록 일자 */
ansRegDt: string | null
/* 답변 등록자 이름 */
ansRegNm: string | null
/* 판매점 ID */
storeId: string | null
/* 판매점 이름 */
storeNm: string | null
/* 문의 등록자 이름 */
regUserNm: string
/* 문의 등록자 전화번호 */
regUserTelNo: string | null
/* 문의 대분류 코드 */
qnaClsLrgCd: string
/* 문의 중분류 코드 */
qnaClsMidCd: string
/* 문의 소분류 코드 */
qnaClsSmlCd: string | null
/* 문의 첨부 파일 */
listFile: listFile[] | null
/* 답변 첨부 파일 */
ansListFile: listFile[] | null
}
/**
* @description
*/
export type listFile = {
fileNo: number //file number
encodeFileNo: string //encode file number
srcFileNm: string //source file name
fileCours: string //file course
fileSize: number //file size(Byte)
regDt: string //registration date
/* 파일 번호 */
fileNo: number
/* 인코딩 파일 번호 */
encodeFileNo: string
/* 소스 파일 이름 */
srcFileNm: string
/* 파일 코스 */
fileCours: string
/* 파일 크기 */
fileSize: number
/* 등록 일자 */
regDt: string
}
/**
* @description
*/
export type InquiryRequest = {
compCd: string //company code
siteTpCd: string //site type code(QC: QCast, QR: QRead)
qnaClsLrgCd: string //qna CLS large Code
qnaClsMidCd: string //qna CLS Mid Code
qnaClsSmlCd: string | null //qna CLS Small Code
title: string //title
contents: string //contents
regId: string //registration Userid
storeId: string //store id
regUserNm: string //registration User name
regUserTelNo: string | null //registration User tel number
qstMail: string //mail
/* 회사 코드 */
compCd: string
/* 사이트 유형 코드 */
siteTpCd: string
/* 문의 대분류 코드 */
qnaClsLrgCd: string
/* 문의 중분류 코드 */
qnaClsMidCd: string
/* 문의 소분류 코드 */
qnaClsSmlCd: string | null
/* 문의 제목 */
title: string
/* 문의 내용 */
contents: string
/* 문의 등록자 ID */
regId: string
/* 판매점 ID */
storeId: string
/* 문의 등록자 이름 */
regUserNm: string
/* 문의 등록자 전화번호 */
regUserTelNo: string | null
/* 문의 이메일 */
qstMail: string
}
/**
* @description
*/
export type InquirySaveResponse = {
cnt: number | null //count
qnaNo: number //qna number
mailYn: string //mail yn - Y / N
/* 건수 */
cnt: number | null
/* 문의 번호 */
qnaNo: number
/* 메일 여부 */
mailYn: string
}
/**
* @description
*/
export type CommonCode = {
headCd: string
code: string

View File

@ -1,148 +1,303 @@
/**
* @description
*/
export type SurveyBasicInfo = {
/* 조사 매물 ID */
id: number
/* 담당자명 */
representative: string
/* 담당자 ID */
representativeId: string | null
/* 판매점명 */
store: string | null
/* 판매점 ID */
storeId: string | null
/* 시공점명 */
constructionPoint: string | null
/* 시공점 ID */
constructionPointId: string | null
/* 조사 일자 */
investigationDate: string | null
/* 건물 이름 */
buildingName: string | null
/* 고객명 */
customerName: string | null
/* 우편번호 */
postCode: string | null
/* 주소 (도도부현) */
address: string | null
/* 상세 주소 */
addressDetail: string | null
/* 제출 상태 */
submissionStatus: boolean
/* 제출 일시 */
submissionDate: string | null
/* 조사 매물 상세 데이터 */
detailInfo: SurveyDetailInfo | null
/* 등록 일시 */
regDt: Date
/* 수정 일시 */
uptDt: Date
/* 제출 대상 판매점 ID */
submissionTargetId: string | null
/* 제출 대상 판매점명 */
submissionTargetNm: string | null
srlNo: string | null //판매점IDyyMMdd000
/* 일련번호 */
srlNo: string | null
}
/**
* @description
*/
export type SurveyDetailInfo = {
/* 조사 매물 상세 ID */
id: number
/* 조사 매물 기본 데이터 ID */
basicInfoId: number
/* 전기계약 용량 */
contractCapacity: string | null
/* 전기 소매 회사 */
retailCompany: string | null
/* 전기 부대 설비 */
supplementaryFacilities: string | null // number 배열
/* 전기 부대 설비 기타 */
supplementaryFacilitiesEtc: string | null
/* 설치 희망 시스템 */
installationSystem: string | null
/* 설치 희망 시스템 기타 */
installationSystemEtc: string | null
/* 건축 년도 */
constructionYear: string | null
/* 건축 년도 기타 */
constructionYearEtc: string | null
roofMaterial: string | null // number 배열
/* 지붕재 - 다중 선택 가능 [number]*/
roofMaterial: string | null
/* 지붕재 기타 */
roofMaterialEtc: string | null
/* 지붕모양 */
roofShape: string | null
/* 지붕모양 기타 */
roofShapeEtc: string | null
/* 지붕 경사 */
roofSlope: string | null
/* 주택 구조 */
houseStructure: string | null
/* 주택 구조 기타 */
houseStructureEtc: string | null
/* 서까래 재질*/
rafterMaterial: string | null
/* 서까래 재질 기타 */
rafterMaterialEtc: string | null
/* 서까래 크기 */
rafterSize: string | null
/* 서까래 크기 기타 */
rafterSizeEtc: string | null
/* 서까래 피치 */
rafterPitch: string | null
/* 서까래 피치 기타 */
rafterPitchEtc: string | null
/* 서까래 방향 */
rafterDirection: string | null
/* 노지판의 종류 */
openFieldPlateKind: string | null
/* 노지판의 종류 기타 */
openFieldPlateKindEtc: string | null
/* 노지판의 두께 */
openFieldPlateThickness: string | null
/* 누수 흔적 */
leakTrace: boolean | null
/* 방수재 종류*/
waterproofMaterial: string | null
/* 방수재 종류 기타 */
waterproofMaterialEtc: string | null
/* 단열재 유무 */
insulationPresence: string | null
/* 단열재 유무 기타 */
insulationPresenceEtc: string | null
/* 지붕 구조의 순서*/
structureOrder: string | null
/* 지붕 구조의 순서 기타 */
structureOrderEtc: string | null
/* 지붕 제품명 설치 가능 여부 확인*/
installationAvailability: string | null
/* 지붕 제품명 설치 가능 여부 확인 기타 */
installationAvailabilityEtc: string | null
/* 메모 */
memo: string | null
/* 등록 일시 */
regDt: Date
/* 수정 일시 */
uptDt: Date
}
/**
* @description
*/
export type SurveyBasicRequest = {
/* 담당자명 */
representative: string
/* 담당자 ID */
representativeId: string | null
/* 판매점명 */
store: string | null
/* 판매점 ID */
storeId: string | null
/* 시공점명 */
constructionPoint: string | null
/* 시공점 ID */
constructionPointId: string | null
/* 조사 일자 */
investigationDate: string | null
/* 건물 이름 */
buildingName: string | null
/* 고객명 */
customerName: string | null
/* 우편번호 */
postCode: string | null
/* 주소 (도도부현) */
address: string | null
/* 상세 주소 */
addressDetail: string | null
/* 제출 상태 */
submissionStatus: boolean
/* 제출 일시 */
submissionDate: string | null
/* 제출 대상 판매점 ID */
submissionTargetId: string | null
/* 제출 대상 판매점명 */
submissionTargetNm: string | null
srlNo: string | null //판매점IDyyMMdd000
/* 일련번호 */
srlNo: string | null
}
/**
* @description
*/
export type SurveyDetailRequest = {
/* 전기계약 용량 */
contractCapacity: string | null
/* 전기 소매 회사 */
retailCompany: string | null
/* 전기 부대 설비 */
supplementaryFacilities: string | null // number 배열
/* 전기 부대 설비 기타 */
supplementaryFacilitiesEtc: string | null
/* 설치 희망 시스템 */
installationSystem: string | null
/* 설치 희망 시스템 기타 */
installationSystemEtc: string | null
/* 건축 년도 */
constructionYear: string | null
/* 건축 년도 기타 */
constructionYearEtc: string | null
roofMaterial: string | null // number 배열
/* 지붕재 - 다중 선택 가능 [number]*/
roofMaterial: string | null
/* 지붕재 기타 */
roofMaterialEtc: string | null
/* 지붕모양 */
roofShape: string | null
/* 지붕모양 기타 */
roofShapeEtc: string | null
/* 지붕 경사 */
roofSlope: string | null
/* 주택 구조 */
houseStructure: string | null
/* 주택 구조 기타 */
houseStructureEtc: string | null
/* 서까래 재질*/
rafterMaterial: string | null
/* 서까래 재질 기타 */
rafterMaterialEtc: string | null
/* 서까래 크기 */
rafterSize: string | null
/* 서까래 크기 기타 */
rafterSizeEtc: string | null
/* 서까래 피치 */
rafterPitch: string | null
/* 서까래 피치 기타 */
rafterPitchEtc: string | null
/* 서까래 방향 */
rafterDirection: string | null
/* 노지판의 종류 */
openFieldPlateKind: string | null
/* 노지판의 종류 기타 */
openFieldPlateKindEtc: string | null
/* 노지판의 두께 */
openFieldPlateThickness: string | null
/* 누수 흔적 */
leakTrace: boolean | null
/* 방수재 종류*/
waterproofMaterial: string | null
/* 방수재 종류 기타 */
waterproofMaterialEtc: string | null
/* 단열재 유무 */
insulationPresence: string | null
/* 단열재 유무 기타 */
insulationPresenceEtc: string | null
/* 지붕 구조의 순서*/
structureOrder: string | null
/* 지붕 구조의 순서 기타 */
structureOrderEtc: string | null
/* 지붕 제품명 설치 가능 여부 확인*/
installationAvailability: string | null
/* 지붕 제품명 설치 가능 여부 확인 기타 */
installationAvailabilityEtc: string | null
/* 메모 */
memo: string | null
}
export type SurveyDetailCoverRequest = {
detailInfo: SurveyDetailRequest
}
/**
* @description
*/
export type SurveyRegistRequest = {
/* 담당자명 */
representative: string
/* 담당자 ID */
representativeId: string | null
/* 판매점명 */
store: string | null
/* 판매점 ID */
storeId: string | null
/* 시공점명 */
constructionPoint: string | null
/* 조사 일자 */
investigationDate: string | null
/* 건물 이름 */
buildingName: string | null
/* 고객명 */
customerName: string | null
/* 우편번호 */
postCode: string | null
/* 주소 (도도부현) */
address: string | null
/* 상세 주소 */
addressDetail: string | null
/* 제출 상태 */
submissionStatus: boolean
/* 제출 일시 */
submissionDate: string | null
/* 조사 매물 상세 데이터 */
detailInfo: SurveyDetailRequest | null
/* 제출 대상 판매점 ID */
submissionTargetId: string | null
srlNo: string | null //판매점IDyyMMdd000
/* 일련번호 */
srlNo: string | null
}
export type Mode = 'CREATE' | 'EDIT' | 'READ' | 'TEMP' // 등록 | 수정 | 상세 | 임시저장
/**
* @description
*/
export type Mode = 'CREATE' | 'EDIT' | 'READ' | 'SUBMIT'
export type SubmitTargetResponse = {
/* 제출 대상 판매점 ID */
targetStoreId: string
/* 제출 대상 판매점명 */
targetStoreNm: string
/* 담당자 ID */
repUserId: string
/* 담당자 이메일 */
repUserEmail: string
/* 권한 */
auth: string
}