diff --git a/src/app/api/qna/detail/route.ts b/src/app/api/qna/detail/route.ts index d1f8078..77a5ec0 100644 --- a/src/app/api/qna/detail/route.ts +++ b/src/app/api/qna/detail/route.ts @@ -1,27 +1,77 @@ -import { ERROR_MESSAGES, queryStringFormatter } from '@/utils/common-utils' +import { queryStringFormatter } from '@/utils/common-utils' import axios from 'axios' import { NextResponse } from 'next/server' import { loggerWrapper } from '@/libs/api-wrapper' -import { HttpStatusCode } from 'axios' +import { QnaService } from '../service' +import { ApiError } from 'next/dist/server/api-utils' +import { getIronSession } from 'iron-session' +import { SessionData } from '@/types/Auth' +import { sessionOptions } from '@/libs/session' +import { cookies } from 'next/headers' +/** + * @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, + * ... + * "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 { + const cookieStore = await cookies() + const session = await getIronSession(cookieStore, sessionOptions) + + const service = new QnaService(session) const { searchParams } = new URL(request.url) const params = { compCd: searchParams.get('compCd'), qnaNo: searchParams.get('qnoNo'), langCd: searchParams.get('langCd'), - loginId: searchParams.get('loginId'), } - try { - const response = await axios.get(`${process.env.NEXT_PUBLIC_INQUIRY_API_URL}/api/qna/detail?${queryStringFormatter(params)}`) - if (response.status === 200) { - return NextResponse.json(response.data) - } - return NextResponse.json({ error: response.data.result }, { status: response.status }) - } catch (error: any) { - return NextResponse.json({ error: error.response.data.result ?? ERROR_MESSAGES.FETCH_ERROR }, { status: HttpStatusCode.InternalServerError }) + const result = await service.tryFunction(() => + axios.get(`${process.env.NEXT_PUBLIC_INQUIRY_API_URL}/api/qna/detail?loginId=${session.userId}&${queryStringFormatter(params)}`), + ) + if (result instanceof ApiError) { + return NextResponse.json({ error: result.message }, { status: result.statusCode }) } + return NextResponse.json(result.data) } export const GET = loggerWrapper(getQnaDetail) diff --git a/src/app/api/qna/file/route.ts b/src/app/api/qna/file/route.ts index 8d6ea8a..32f7ab3 100644 --- a/src/app/api/qna/file/route.ts +++ b/src/app/api/qna/file/route.ts @@ -1,7 +1,9 @@ import { HttpStatusCode } from 'axios' import { NextResponse } from 'next/server' import { loggerWrapper } from '@/libs/api-wrapper' -import { ERROR_MESSAGES } from '@/utils/common-utils' +import { ERROR_MESSAGE } from '@/hooks/useAlertMsg' +import { QnaService } from '../service' +import { ApiError } from 'next/dist/server/api-utils' /** * @api {GET} /api/qna/file 문의 첨부 파일 다운로드 API @@ -22,36 +24,32 @@ import { ERROR_MESSAGES } from '@/utils/common-utils' * @apiError {Number} 400 잘못된 요청 */ async function downloadFile(request: Request): Promise { + const service = new QnaService() const { searchParams } = new URL(request.url) const encodeFileNo = searchParams.get('encodeFileNo') const srcFileNm = searchParams.get('srcFileNm') || 'downloaded-file' if (!encodeFileNo) { - return NextResponse.json({ error: ERROR_MESSAGES.BAD_REQUEST }, { status: HttpStatusCode.BadRequest }) + return NextResponse.json({ error: ERROR_MESSAGE.BAD_REQUEST }, { status: HttpStatusCode.BadRequest }) } const url = `${process.env.NEXT_PUBLIC_INQUIRY_API_URL}/api/file/downloadFile2?encodeFileNo=${encodeFileNo}` - try { - const resp = await fetch(url) - - if (!resp.ok) { - return NextResponse.json({ error: ERROR_MESSAGES.FETCH_ERROR }, { status: HttpStatusCode.InternalServerError }) - } - - const contentType = resp.headers.get('content-type') || 'application/octet-stream' - const contentDisposition = resp.headers.get('content-disposition') || `attachment; filename="${srcFileNm}"` - - return new NextResponse(resp.body, { - status: 200, - headers: { - 'Content-Type': contentType, - 'Content-Disposition': contentDisposition, - }, - }) - } catch (error: any) { - return NextResponse.json({ error: error.response?.data ?? ERROR_MESSAGES.FETCH_ERROR }, { status: HttpStatusCode.InternalServerError }) + const resp = await service.tryFunction(() => fetch(url), true) + if (resp instanceof ApiError) { + return NextResponse.json({ error: resp.message }, { status: resp.statusCode }) } + + const contentType = resp.headers.get('content-type') || 'application/octet-stream' + const contentDisposition = resp.headers.get('content-disposition') || `attachment; filename="${srcFileNm}"` + + return new NextResponse(resp.body, { + status: 200, + headers: { + 'Content-Type': contentType, + 'Content-Disposition': contentDisposition, + }, + }) } export const GET = loggerWrapper(downloadFile) diff --git a/src/app/api/qna/list/route.ts b/src/app/api/qna/list/route.ts index 7e8807d..243c9e6 100644 --- a/src/app/api/qna/list/route.ts +++ b/src/app/api/qna/list/route.ts @@ -1,41 +1,73 @@ -import axios, { HttpStatusCode } from 'axios' +import axios from 'axios' import { NextResponse } from 'next/server' -import { ERROR_MESSAGES, queryStringFormatter } from '@/utils/common-utils' +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' +import { QnaService } from '../service' +import { ApiError } from 'next/dist/server/api-utils' +/** + * @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 { const cookieStore = await cookies() const session = await getIronSession(cookieStore, sessionOptions) - if (!session.isLoggedIn) { - return NextResponse.json({ error: ERROR_MESSAGES.UNAUTHORIZED }, { status: HttpStatusCode.Unauthorized }) - } + const service = new QnaService(session) const { searchParams } = new URL(request.url) + const params = service.getSearchParams(searchParams) - const params: Record = {} - searchParams.forEach((value, key) => { - const match = key.match(/inquiryListRequest\[(.*)\]/) - if (match) { - params[match[1]] = value - } else { - params[key] = value - } - }) - - try { - const response = await axios.get(`${process.env.NEXT_PUBLIC_INQUIRY_API_URL}/api/qna/list?${queryStringFormatter(params)}`) - if (response.status === 200) { - return NextResponse.json(response.data) - } - return NextResponse.json({ error: response.data.result }, { status: response.status }) - } catch (error: any) { - return NextResponse.json({ error: error.response.data.result ?? ERROR_MESSAGES.FETCH_ERROR }, { status: HttpStatusCode.InternalServerError }) + const result = await service.tryFunction(() => axios.get(`${process.env.NEXT_PUBLIC_INQUIRY_API_URL}/api/qna/list?${queryStringFormatter(params)}`), true) + if (result instanceof ApiError) { + return NextResponse.json({ error: result.message }, { status: result.statusCode }) } + return NextResponse.json(result.data.data) } export const GET = loggerWrapper(getQnaList) diff --git a/src/app/api/qna/route.ts b/src/app/api/qna/route.ts index 2773761..767f9ca 100644 --- a/src/app/api/qna/route.ts +++ b/src/app/api/qna/route.ts @@ -1,22 +1,45 @@ import { NextResponse } from 'next/server' import axios from 'axios' -import { CommonCode } from '@/types/Inquiry' import { loggerWrapper } from '@/libs/api-wrapper' +import { QnaService } from './service' +import { ApiError } from 'next/dist/server/api-utils' -async function getCommonCodeListData(request: Request): Promise { - 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) => { - if (item.headCd === '204200' || item.headCd === '204300' || item.headCd === '204400') { - codeList.push({ - headCd: item.headCd, - code: item.code, - name: item.codeJp, - refChar1: item.refChr1, - }) - } - }) - return NextResponse.json({ data: codeList }) +/** + * @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(): Promise { + const service = new QnaService() + const response = await service.tryFunction(() => axios.get(`${process.env.NEXT_PUBLIC_INQUIRY_API_URL}/api/system/commonCodeListData`)) + if (response instanceof ApiError) { + return NextResponse.json({ error: response.message }, { status: response.statusCode }) + } + const result = service.getInquiryTypeList(response.data.apiCommCdList) + return NextResponse.json({ data: result }) } export const GET = loggerWrapper(getCommonCodeListData) diff --git a/src/app/api/qna/save/route.ts b/src/app/api/qna/save/route.ts index 4575479..d042658 100644 --- a/src/app/api/qna/save/route.ts +++ b/src/app/api/qna/save/route.ts @@ -1,23 +1,51 @@ -import axios, { HttpStatusCode } from 'axios' +import axios from 'axios' import { NextResponse } from 'next/server' import { loggerWrapper } from '@/libs/api-wrapper' -import { ERROR_MESSAGES } from '@/utils/common-utils' +import { QnaService } from '../service' +import { ApiError } from 'next/dist/server/api-utils' +import { getIronSession } from 'iron-session' +import { SessionData } from '@/types/Auth' +import { sessionOptions } from '@/libs/session' +import { cookies } from 'next/headers' +/** + * @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 { + const cookieStore = await cookies() + const session = await getIronSession(cookieStore, sessionOptions) + + const service = new QnaService(session) const formData = await request.formData() - try { - const response = await axios.post(`${process.env.NEXT_PUBLIC_INQUIRY_API_URL}/api/qna/save`, formData, { + const result = await service.tryFunction(() => + axios.post(`${process.env.NEXT_PUBLIC_INQUIRY_API_URL}/api/qna/save`, formData, { headers: { 'Content-Type': 'multipart/form-data', }, - }) - if (response.status === 200) { - return NextResponse.json(response.data) - } - return NextResponse.json({ error: response.data.result }, { status: response.status }) - } catch (error: any) { - return NextResponse.json({ error: error.response.data.result ?? ERROR_MESSAGES.FETCH_ERROR }, { status: HttpStatusCode.InternalServerError }) + }), + ) + if (result instanceof ApiError) { + return NextResponse.json({ error: result.message }, { status: result.statusCode }) } + return NextResponse.json(result.data) } export const POST = loggerWrapper(setQna) diff --git a/src/app/api/qna/service.ts b/src/app/api/qna/service.ts new file mode 100644 index 0000000..56600f3 --- /dev/null +++ b/src/app/api/qna/service.ts @@ -0,0 +1,89 @@ +import { SessionData } from '@/types/Auth' +import { CommonCode } from '@/types/Inquiry' +import { ERROR_MESSAGE } from '@/hooks/useAlertMsg' +import { HttpStatusCode } from 'axios' +import { ApiError } from 'next/dist/server/api-utils' + +export class QnaService { + private session?: SessionData + constructor(session?: SessionData) { + this.session = session + } + /** + * @description API ROUTE 에러 처리 + * @param {any} error 에러 객체 + * @returns {ApiError} 에러 객체 + */ + private handleRouteError(error: any): ApiError { + console.error('❌ API ROUTE ERROR : ', error) + return new ApiError(error.response.status, error.response.data.result.message ?? ERROR_MESSAGE.FETCH_ERROR) + } + /** + * @description 비동기 함수 try-catch 처리 함수 + * @param {() => Promise} func 비동기 함수 + * @returns {Promise} 에러 객체 또는 함수 결과 + */ + async tryFunction(func: () => Promise, isFile?: boolean): Promise { + if (this.session !== undefined && !this.session?.isLoggedIn) { + return new ApiError(HttpStatusCode.Unauthorized, ERROR_MESSAGE.UNAUTHORIZED) + } + try { + const response = await func() + if (isFile) return response + return this.handleResult(response) + } catch (error) { + return this.handleRouteError(error) + } + } + + /** + * @description 함수 결과 처리 함수 + * @param {any} result 함수 결과 + * @returns {ApiError | any} 에러 객체 또는 함수 결과 + */ + private handleResult(response: any): ApiError | any { + if (response.status === HttpStatusCode.Ok) { + if (response.data.data !== null) return response.data + return new ApiError(HttpStatusCode.NotFound, ERROR_MESSAGE.NOT_FOUND) + } + return new ApiError(response.result.code, response.result.message) + } + + /** + * @description 문의 유형 타입 목록 조회 + * @param {string[]} responseList 문의 유형 타입 목록 + * @returns {CommonCode[]} 문의 유형 타입 목록 + */ + getInquiryTypeList(responseList: string[]): CommonCode[] { + const codeList: CommonCode[] = [] + responseList.forEach((item: any) => { + if (item.headCd === '204200' || item.headCd === '204300' || item.headCd === '204400') { + codeList.push({ + headCd: item.headCd, + code: item.code, + name: item.codeJp, + refChar1: item.refChr1, + }) + } + }) + return codeList + } + + /** + * @description 문의 목록 조회 파라미터 처리 + * @param {URLSearchParams} searchParams URLSearchParams 객체 + * @returns {Record} 문의 목록 조회 파라미터 + */ + getSearchParams(searchParams: URLSearchParams): Record { + const params: Record = {} + searchParams.forEach((value, key) => { + const match = key.match(/inquiryListRequest\[(.*)\]/) + if (match) { + params[match[1]] = value + } else { + params[key] = value + } + }) + return params + } +} diff --git a/src/app/api/submission/route.ts b/src/app/api/submission/route.ts index 00b06aa..7d68824 100644 --- a/src/app/api/submission/route.ts +++ b/src/app/api/submission/route.ts @@ -1,9 +1,9 @@ import { NextRequest, NextResponse } from 'next/server' import { SubmissionService } from './service' import { HttpStatusCode } from 'axios' -import { ERROR_MESSAGES } from '@/utils/common-utils' import { loggerWrapper } from '@/libs/api-wrapper' import { ApiError } from 'next/dist/server/api-utils' +import { ERROR_MESSAGE } from '@/hooks/useAlertMsg' /** * @api {GET} /api/submission 제출 대상 조회 @@ -47,7 +47,7 @@ async function getSubmitTargetData(request: NextRequest): Promise const role = searchParams.get('role') if (!storeId || !role) { - return NextResponse.json({ error: ERROR_MESSAGES.BAD_REQUEST }, { status: HttpStatusCode.BadRequest }) + return NextResponse.json({ error: ERROR_MESSAGE.BAD_REQUEST }, { status: HttpStatusCode.BadRequest }) } const submissionService = new SubmissionService(storeId, role) diff --git a/src/app/api/submission/service.ts b/src/app/api/submission/service.ts index 431436c..235abee 100644 --- a/src/app/api/submission/service.ts +++ b/src/app/api/submission/service.ts @@ -1,5 +1,5 @@ import { prisma } from '@/libs/prisma' -import { ERROR_MESSAGES } from '@/utils/common-utils' +import { ERROR_MESSAGE } from '@/hooks/useAlertMsg' import { SubmitTargetResponse } from '@/types/Survey' import { HttpStatusCode } from 'axios' import { ApiError } from 'next/dist/server/api-utils' @@ -17,7 +17,7 @@ export class SubmissionService { constructor(storeId: string, role: string) { this.storeId = storeId this.role = role - } + } /** * @description 제출 대상 조회 @@ -30,7 +30,7 @@ export class SubmissionService { case 'Builder': return this.getSubmissionTargetBuilder() default: - return new ApiError(HttpStatusCode.BadRequest, ERROR_MESSAGES.BAD_REQUEST) + return new ApiError(HttpStatusCode.BadRequest, ERROR_MESSAGE.BAD_REQUEST) } } @@ -99,11 +99,11 @@ export class SubmissionService { error instanceof Prisma.PrismaClientUnknownRequestError || error instanceof Prisma.PrismaClientRustPanicError || error instanceof Prisma.PrismaClientValidationError || - error instanceof Prisma.PrismaClientUnknownRequestError + error instanceof Prisma.PrismaClientKnownRequestError ) { - return new ApiError(HttpStatusCode.InternalServerError, ERROR_MESSAGES.PRISMA_ERROR) + return new ApiError(HttpStatusCode.InternalServerError, ERROR_MESSAGE.PRISMA_ERROR) } - return new ApiError(error.statusCode ?? HttpStatusCode.InternalServerError, error.message ?? ERROR_MESSAGES.FETCH_ERROR) + return new ApiError(error.statusCode ?? HttpStatusCode.InternalServerError, error.message ?? ERROR_MESSAGE.FETCH_ERROR) } /** diff --git a/src/app/api/survey-sales/service.ts b/src/app/api/survey-sales/service.ts index 8b75fb0..a9fa9c3 100644 --- a/src/app/api/survey-sales/service.ts +++ b/src/app/api/survey-sales/service.ts @@ -1,10 +1,11 @@ import { prisma } from '@/libs/prisma' import { SurveyBasicInfo, SurveyRegistRequest, SurveySearchParams } from '@/types/Survey' -import { convertToSnakeCase, ERROR_MESSAGES } from '@/utils/common-utils' +import { convertToSnakeCase } from '@/utils/common-utils' import { Prisma } from '@prisma/client' import type { SessionData } from '@/types/Auth' import { HttpStatusCode } from 'axios' import { ApiError } from 'next/dist/server/api-utils' +import { ERROR_MESSAGE } from '@/hooks/useAlertMsg' type WhereCondition = { AND: any[] @@ -54,15 +55,15 @@ export class SurveySalesService { */ checkSession(): ApiError | null { if (!this.session?.isLoggedIn || this.session?.role === null) { - return new ApiError(HttpStatusCode.Unauthorized, ERROR_MESSAGES.UNAUTHORIZED) + return new ApiError(HttpStatusCode.Unauthorized, ERROR_MESSAGE.UNAUTHORIZED) } if (this.session?.role === 'Builder' || this.session?.role === 'Partner') { if (this.params.builderId === null) { - return new ApiError(HttpStatusCode.Forbidden, ERROR_MESSAGES.NO_PERMISSION) + return new ApiError(HttpStatusCode.Forbidden, ERROR_MESSAGE.FORBIDDEN) } } else { if (this.session?.storeId === null) { - return new ApiError(HttpStatusCode.Forbidden, ERROR_MESSAGES.NO_PERMISSION) + return new ApiError(HttpStatusCode.Forbidden, ERROR_MESSAGE.FORBIDDEN) } } return null @@ -261,11 +262,11 @@ export class SurveySalesService { include: { DETAIL_INFO: true }, }) if (!result) { - return new ApiError(HttpStatusCode.NotFound, ERROR_MESSAGES.NOT_FOUND) + return new ApiError(HttpStatusCode.NotFound, ERROR_MESSAGE.NOT_FOUND) } if (!isPdf) { - if (!this.session?.isLoggedIn) return new ApiError(HttpStatusCode.Unauthorized, ERROR_MESSAGES.UNAUTHORIZED) - if (!this.checkRole(result, this.session as SessionData)) return new ApiError(HttpStatusCode.Forbidden, ERROR_MESSAGES.NO_PERMISSION) + if (!this.session?.isLoggedIn) return new ApiError(HttpStatusCode.Unauthorized, ERROR_MESSAGE.UNAUTHORIZED) + if (!this.checkRole(result, this.session as SessionData)) return new ApiError(HttpStatusCode.Forbidden, ERROR_MESSAGE.FORBIDDEN) } return result } @@ -433,11 +434,11 @@ export class SurveySalesService { error instanceof Prisma.PrismaClientUnknownRequestError || error instanceof Prisma.PrismaClientRustPanicError || error instanceof Prisma.PrismaClientValidationError || - error instanceof Prisma.PrismaClientUnknownRequestError + error instanceof Prisma.PrismaClientKnownRequestError ) { - return new ApiError(HttpStatusCode.InternalServerError, ERROR_MESSAGES.PRISMA_ERROR) + return new ApiError(HttpStatusCode.InternalServerError, ERROR_MESSAGE.PRISMA_ERROR) } - return new ApiError(error.statusCode ?? HttpStatusCode.InternalServerError, error.message ?? ERROR_MESSAGES.FETCH_ERROR) + return new ApiError(error.statusCode ?? HttpStatusCode.InternalServerError, error.message ?? ERROR_MESSAGE.FETCH_ERROR) } /** diff --git a/src/components/inquiry/Detail.tsx b/src/components/inquiry/Detail.tsx index f01ec54..3470c10 100644 --- a/src/components/inquiry/Detail.tsx +++ b/src/components/inquiry/Detail.tsx @@ -9,12 +9,13 @@ export default function Detail() { const params = useParams() const id = params.id - const { inquiryDetail, downloadFile } = useInquiry(Number(id), '5200') - const { commonCodeList } = useInquiry() + const { inquiryDetail, downloadFile, commonCodeList } = useInquiry(Number(id), false) const router = useRouter() const { session } = useSessionStore() + const isBuilderOrPartner = session?.role === 'Builder' || session?.role === 'Partner' + return ( <>
@@ -43,11 +44,11 @@ export default function Detail() { 販売店 - {inquiryDetail?.storeNm} + {isBuilderOrPartner ? '-' : inquiryDetail?.storeNm} E-mail - {inquiryDetail?.regEmail} + {inquiryDetail?.regEmail ? inquiryDetail?.regEmail : '-'} 名前 diff --git a/src/components/inquiry/RegistForm.tsx b/src/components/inquiry/RegistForm.tsx index 7ad869e..21e4e61 100644 --- a/src/components/inquiry/RegistForm.tsx +++ b/src/components/inquiry/RegistForm.tsx @@ -3,11 +3,13 @@ import { useInquiry } from '@/hooks/useInquiry' import { useSessionStore } from '@/store/session' import { InquiryRequest } from '@/types/Inquiry' - import { useEffect, useState } from 'react' import { useRouter } from 'next/navigation' +import { CONFIRM_MESSAGE, SUCCESS_MESSAGE, useAlertMsg, WARNING_MESSAGE } from '@/hooks/useAlertMsg' + export default function RegistForm() { - const { saveInquiry, isSavingInquiry } = useInquiry() + const { saveInquiry, isSavingInquiry, commonCodeList } = useInquiry(undefined, false) + const { showErrorAlert, showSuccessAlert, showConfirm } = useAlertMsg() const { session } = useSessionStore() const router = useRouter() @@ -46,8 +48,6 @@ export default function RegistForm() { } }, [session]) - const { commonCodeList } = useInquiry() - const [attachedFiles, setAttachedFiles] = useState([]) /** 파일 첨부 처리 */ @@ -74,23 +74,23 @@ export default function RegistForm() { const handleSubmit = async () => { const emptyField = requiredFieldNames.find((field) => inquiryRequest[field.id as keyof InquiryRequest] === '') if (emptyField) { - alert(`${emptyField?.name}を入力してください。`) + showErrorAlert(WARNING_MESSAGE.REQUIRED_FIELD_IS_EMPTY, emptyField?.name) focusOnRequiredField(emptyField?.id ?? '') return } const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/ if (!emailRegex.test(inquiryRequest.qstMail)) { - alert('有効なメールアドレスを入力してください。') + showErrorAlert(WARNING_MESSAGE.EMAIL_PREFIX_IS_INVALID) focusOnRequiredField('qstMail') return } if (inquiryRequest.title.length > 100) { - alert('お問い合わせタイトルは100文字以内で入力してください。') + showErrorAlert(WARNING_MESSAGE.TITLE_MAX_LENGTH) focusOnRequiredField('title') return } if (inquiryRequest.contents.length > 2000) { - alert('お問い合わせ内容は2,000文字以内で入力してください。') + showErrorAlert(WARNING_MESSAGE.CONTENTS_MAX_LENGTH) focusOnRequiredField('contents') return } @@ -102,11 +102,11 @@ export default function RegistForm() { Object.entries(inquiryRequest).forEach(([key, value]) => { formData.append(key, value ?? '') }) - window.neoConfirm( - 'お問い合わせを登録しますか? Hanwha Japanの担当者にお問い合わせメールが送信されます。', + showConfirm( + CONFIRM_MESSAGE.SAVE_INQUIRY_CONFIRM, async () => { const res = await saveInquiry(formData) - alert('保存されました。') + showSuccessAlert(SUCCESS_MESSAGE.SAVE_SUCCESS) router.push(`/inquiry/${res.qnaNo}`) }, () => null, diff --git a/src/components/inquiry/list/ListForm.tsx b/src/components/inquiry/list/ListForm.tsx index 878a7e5..94eb8f5 100644 --- a/src/components/inquiry/list/ListForm.tsx +++ b/src/components/inquiry/list/ListForm.tsx @@ -2,10 +2,12 @@ import { useInquiryFilterStore } from '@/store/inquiryFilterStore' import { useRouter } from 'next/navigation' import { useState } from 'react' +import { useAlertMsg, WARNING_MESSAGE } from '@/hooks/useAlertMsg' export default function ListForm() { const router = useRouter() const { inquiryListRequest, setInquiryListRequest, reset, setOffset } = useInquiryFilterStore() + const { showErrorAlert } = useAlertMsg() const [searchKeyword, setSearchKeyword] = useState(inquiryListRequest.schTitle ?? '') const handleSearch = () => { @@ -13,7 +15,7 @@ export default function ListForm() { reset() setInquiryListRequest({ ...inquiryListRequest, schTitle: searchKeyword }) } else { - alert('2文字以上入力してください') + showErrorAlert(WARNING_MESSAGE.KEYWORD_MINIMUM_LENGTH) } } const handleKeyDown = (e: React.KeyboardEvent) => { diff --git a/src/components/inquiry/list/ListTable.tsx b/src/components/inquiry/list/ListTable.tsx index b1359f7..ca7264a 100644 --- a/src/components/inquiry/list/ListTable.tsx +++ b/src/components/inquiry/list/ListTable.tsx @@ -25,7 +25,7 @@ export default function ListTable() { const router = useRouter() const pathname = usePathname() - const { inquiryList, isLoadingInquiryList } = useInquiry() + const { inquiryList, isLoadingInquiryList } = useInquiry(undefined, true) const { inquiryListRequest, setInquiryListRequest, reset, offset, setOffset } = useInquiryFilterStore() const [hasMore, setHasMore] = useState(false) diff --git a/src/components/pdf/SurveySaleDownloadPdf.tsx b/src/components/pdf/SurveySaleDownloadPdf.tsx index 0999906..556abfc 100644 --- a/src/components/pdf/SurveySaleDownloadPdf.tsx +++ b/src/components/pdf/SurveySaleDownloadPdf.tsx @@ -7,14 +7,15 @@ 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' -import { SURVEY_ALERT_MSG } from '@/types/Survey' +import { ERROR_MESSAGE, SUCCESS_MESSAGE, useAlertMsg } from '@/hooks/useAlertMsg' export default function SurveySaleDownloadPdf() { const params = useParams() const id = params.id const router = useRouter() - const { surveyDetail, isLoadingSurveyDetail, showSurveyAlert } = useSurvey(Number(id), true) + const { surveyDetail, isLoadingSurveyDetail } = useSurvey(Number(id), true) + const { showErrorAlert, showSuccessAlert } = useAlertMsg() const { setIsShow } = useSpinnerStore() const { session } = useSessionStore() @@ -61,11 +62,11 @@ export default function SurveySaleDownloadPdf() { } else { router.replace('/') } - showSurveyAlert('PDFの生成が完了しました。 ポップアップウィンドウからダウンロードしてください。') + showSuccessAlert(SUCCESS_MESSAGE.PDF_GENERATION_SUCCESS) }) .catch((error: any) => { console.error('❌ PDF GENERATION ERROR', error) - showSurveyAlert(SURVEY_ALERT_MSG.PDF_GENERATION_ERROR) + showErrorAlert(ERROR_MESSAGE.PDF_GENERATION_ERROR) }) } diff --git a/src/components/popup/SurveySaleSubmitPopup.tsx b/src/components/popup/SurveySaleSubmitPopup.tsx index ca8ced0..0fe861e 100644 --- a/src/components/popup/SurveySaleSubmitPopup.tsx +++ b/src/components/popup/SurveySaleSubmitPopup.tsx @@ -8,6 +8,7 @@ import { useCommCode } from '@/hooks/useCommCode' import { CommCode } from '@/types/CommCode' import { sendEmail } from '@/libs/mailer' import { useSpinnerStore } from '@/store/spinnerStore' +import { CONFIRM_MESSAGE, SUCCESS_MESSAGE, ERROR_MESSAGE, useAlertMsg, WARNING_MESSAGE } from '@/hooks/useAlertMsg' interface SubmitFormData { saleBase: string | null @@ -35,6 +36,7 @@ export default function SurveySaleSubmitPopup() { const { setIsShow } = useSpinnerStore() const { getCommCode } = useCommCode() const { surveyDetail, getSubmitTarget } = useSurvey(Number(routeId)) + const { showErrorAlert, showSuccessAlert, showConfirm } = useAlertMsg() const [submitData, setSubmitData] = useState({ saleBase: null, @@ -109,7 +111,7 @@ export default function SurveySaleSubmitPopup() { for (const field of requiredFields) { if (data[field.id] === '' || data[field.id] === null || data[field.id]?.length === 0) { - alert(`${field.name}は必須入力項目です。`) + showErrorAlert(WARNING_MESSAGE.REQUIRED_FIELD_IS_EMPTY, field.name) const element = document.getElementById(field.id) if (element) { element.focus() @@ -123,7 +125,7 @@ export default function SurveySaleSubmitPopup() { /** 제출 처리 - 데이터 검증 이후 메일 전송 완료되면 데이터 저장 */ const handleSubmit = () => { if (validateData(submitData)) { - window.neoConfirm('送信しますか? 送信後は変更・修正することはできません。', () => { + showConfirm(CONFIRM_MESSAGE.SUBMIT_CONFIRM, () => { setIsShow(true) sendEmail({ to: submitData.receiver, @@ -133,14 +135,14 @@ export default function SurveySaleSubmitPopup() { }) .then(() => { if (!isSubmittingSurvey) { - alert('提出が完了しました。') + showSuccessAlert(SUCCESS_MESSAGE.SUBMIT_SUCCESS) submitSurvey({ targetId: submitData.targetId, targetNm: submitData.targetNm }) popupController.setSurveySaleSubmitPopup(false) } }) .catch((error) => { - console.error('Error sending email:', error) - alert('メール送信に失敗しました。 再度送信してください。') + console.error('❌ SEND EMAIL ERROR : ', error) + showErrorAlert(ERROR_MESSAGE.EMAIL_SEND_ERROR) }) .finally(() => { setIsShow(false) diff --git a/src/components/survey-sale/detail/ButtonForm.tsx b/src/components/survey-sale/detail/ButtonForm.tsx index c731d98..e870a73 100644 --- a/src/components/survey-sale/detail/ButtonForm.tsx +++ b/src/components/survey-sale/detail/ButtonForm.tsx @@ -6,7 +6,7 @@ import { useEffect, useState } from 'react' import { useParams, useRouter } from 'next/navigation' import { requiredFields, useSurvey } from '@/hooks/useSurvey' import { usePopupController } from '@/store/popupController' -import { SURVEY_ALERT_MSG } from '@/types/Survey' +import { CONFIRM_MESSAGE, SUCCESS_MESSAGE, useAlertMsg, WARNING_MESSAGE } from '@/hooks/useAlertMsg' interface ButtonFormProps { mode: Mode @@ -49,7 +49,8 @@ export default function ButtonForm({ mode, setMode, data }: ButtonFormProps) { const isSubmit = data.basic.submissionStatus const { deleteSurvey, updateSurvey, isDeletingSurvey, isUpdatingSurvey } = useSurvey(id) - const { validateSurveyDetail, createSurvey, isCreatingSurvey, showSurveyAlert, showSurveyConfirm } = useSurvey() + const { validateSurveyDetail, createSurvey, isCreatingSurvey } = useSurvey() + const { showErrorAlert, showSuccessAlert, showConfirm } = useAlertMsg() useEffect(() => { if (!session?.isLoggedIn) return @@ -117,7 +118,7 @@ export default function ButtonForm({ mode, setMode, data }: ButtonFormProps) { router.push(`/survey-sale/${savedId}`) } } - showSurveyAlert(SURVEY_ALERT_MSG.TEMP_SAVE_SUCCESS) + showSuccessAlert(SUCCESS_MESSAGE.TEMP_SAVE_SUCCESS) } /** 입력 필드 포커스 처리 */ @@ -130,7 +131,7 @@ export default function ButtonForm({ mode, setMode, data }: ButtonFormProps) { const saveProcess = async (emptyField: string | null, isSubmitProcess?: boolean) => { if (emptyField?.trim() === '') { if (!isSubmitProcess) { - showSurveyConfirm(SURVEY_ALERT_MSG.SAVE_CONFIRM, async () => { + showConfirm(CONFIRM_MESSAGE.SAVE_CONFIRM, async () => { await handleSuccessfulSave(isSubmitProcess) }) } else { @@ -155,7 +156,7 @@ export default function ButtonForm({ mode, setMode, data }: ButtonFormProps) { if (isSubmitProcess) { popupController.setSurveySaleSubmitPopup(true) } else { - showSurveyAlert(SURVEY_ALERT_MSG.SAVE_SUCCESS) + showSuccessAlert(SUCCESS_MESSAGE.SAVE_SUCCESS) } } } else { @@ -165,7 +166,7 @@ export default function ButtonForm({ mode, setMode, data }: ButtonFormProps) { await router.push(`/survey-sale/${savedId}?show=true`) } else { await router.push(`/survey-sale/${savedId}`) - showSurveyAlert(SURVEY_ALERT_MSG.SAVE_SUCCESS) + showSuccessAlert(SUCCESS_MESSAGE.SAVE_SUCCESS) } } } @@ -173,10 +174,10 @@ export default function ButtonForm({ mode, setMode, data }: ButtonFormProps) { /** 필수값 미입력 처리 */ const handleFailedSave = (emptyField: string | null) => { if (emptyField?.includes('Unit')) { - showSurveyAlert(SURVEY_ALERT_MSG.UNIT_REQUIRED) + showErrorAlert(WARNING_MESSAGE.REQUIRED_UNIT_IS_EMPTY) } else { const fieldInfo = requiredFields.find((field) => field.field === emptyField) - showSurveyAlert(SURVEY_ALERT_MSG.REQUIRED_FIELD, fieldInfo?.name || '') + showErrorAlert(WARNING_MESSAGE.REQUIRED_FIELD_IS_EMPTY, fieldInfo?.name || '') } focusInput(emptyField as keyof SurveyDetailInfo) } @@ -184,10 +185,10 @@ export default function ButtonForm({ mode, setMode, data }: ButtonFormProps) { /** 삭제 로직 */ const handleDelete = async () => { if (!Number.isNaN(id)) { - showSurveyConfirm(SURVEY_ALERT_MSG.DELETE_CONFIRM, async () => { + showConfirm(CONFIRM_MESSAGE.DELETE_CONFIRM, async () => { await deleteSurvey() if (!isDeletingSurvey) { - showSurveyAlert(SURVEY_ALERT_MSG.DELETE_SUCCESS) + showSuccessAlert(SUCCESS_MESSAGE.DELETE_SUCCESS) router.push('/survey-sale') } }) @@ -197,16 +198,16 @@ export default function ButtonForm({ mode, setMode, data }: ButtonFormProps) { /** 제출 로직 */ const handleSubmit = async () => { if (data.basic.srlNo?.startsWith('一時保存') && Number.isNaN(id)) { - showSurveyAlert(SURVEY_ALERT_MSG.TEMP_SAVE_SUBMIT_ERROR) + showErrorAlert(WARNING_MESSAGE.TEMP_CANNOT_SUBMIT) return } if (mode === 'READ') { - showSurveyConfirm(SURVEY_ALERT_MSG.SUBMIT_CONFIRM, async () => { + showConfirm(CONFIRM_MESSAGE.SUBMIT_CONFIRM, async () => { popupController.setSurveySaleSubmitPopup(true) }) } else { - showSurveyConfirm(SURVEY_ALERT_MSG.SAVE_AND_SUBMIT_CONFIRM, async () => { + showConfirm(CONFIRM_MESSAGE.SAVE_AND_SUBMIT_CONFIRM, async () => { handleSave(false, true) }) } diff --git a/src/components/survey-sale/detail/RoofForm.tsx b/src/components/survey-sale/detail/RoofForm.tsx index 35d7828..ecffd61 100644 --- a/src/components/survey-sale/detail/RoofForm.tsx +++ b/src/components/survey-sale/detail/RoofForm.tsx @@ -1,7 +1,6 @@ import { useState } from 'react' import type { Mode, SurveyDetailInfo, SurveyDetailRequest } from '@/types/Survey' -import { useSurvey } from '@/hooks/useSurvey' -import { SURVEY_ALERT_MSG } from '@/types/Survey' +import { useAlertMsg, WARNING_MESSAGE } from '@/hooks/useAlertMsg' type RadioEtcKeys = | 'structureOrder' @@ -249,7 +248,7 @@ export default function RoofForm(props: { mode: Mode }) { const { roofInfo, setRoofInfo, mode } = props - const { showSurveyAlert } = useSurvey() + const { showErrorAlert } = useAlertMsg() const [isFlip, setIsFlip] = useState(true) const handleNumberInput = (key: keyof SurveyDetailRequest, value: number | string) => { @@ -257,13 +256,13 @@ export default function RoofForm(props: { if (key === 'roofSlope' || key === 'openFieldPlateThickness') { const stringValue = value.toString() if (stringValue.length > 5) { - showSurveyAlert('保存できるサイズを超えました。') + showErrorAlert(WARNING_MESSAGE.SAVE_SIZE_OVERFLOW) return } if (stringValue.includes('.')) { const decimalPlaces = stringValue.split('.')[1].length if (decimalPlaces > 1) { - showSurveyAlert('小数点以下1桁までしか許されません。') + showErrorAlert(WARNING_MESSAGE.DECIMAL_POINT_CANNOT_EXCEED) return } } @@ -735,7 +734,7 @@ const MultiCheck = ({ roofInfo: SurveyDetailInfo setRoofInfo: (roofInfo: SurveyDetailRequest) => void }) => { - const { showSurveyAlert } = useSurvey() + const { showErrorAlert } = useAlertMsg() const multiCheckData = column === 'supplementaryFacilities' ? supplementaryFacilities : roofMaterial const etcValue = roofInfo?.[`${column}Etc` as keyof SurveyDetailInfo] const [isOtherCheck, setIsOtherCheck] = useState(Boolean(etcValue)) @@ -755,7 +754,7 @@ const MultiCheck = ({ if (isRoofMaterial) { const totalSelected = selectedValues.length + (isOtherSelected || isOtherCheck ? 1 : 0) if (totalSelected >= 2) { - showSurveyAlert(SURVEY_ALERT_MSG.ROOF_MATERIAL_MAX_SELECT_ERROR) + showErrorAlert(WARNING_MESSAGE.ROOF_MATERIAL_MAX_SELECT) return } } @@ -769,7 +768,7 @@ const MultiCheck = ({ if (isRoofMaterial) { const currentSelected = selectedValues.length if (!isOtherCheck && currentSelected >= 2) { - showSurveyAlert(SURVEY_ALERT_MSG.ROOF_MATERIAL_MAX_SELECT_ERROR) + showErrorAlert(WARNING_MESSAGE.ROOF_MATERIAL_MAX_SELECT) return } } diff --git a/src/components/survey-sale/list/SearchForm.tsx b/src/components/survey-sale/list/SearchForm.tsx index 86ad3c0..66bf38e 100644 --- a/src/components/survey-sale/list/SearchForm.tsx +++ b/src/components/survey-sale/list/SearchForm.tsx @@ -3,18 +3,18 @@ import { SEARCH_OPTIONS, SEARCH_OPTIONS_ENUM, SEARCH_OPTIONS_PARTNERS, useSurveyFilterStore } from '@/store/surveyFilterStore' import { useRouter } from 'next/navigation' import { useState } from 'react' -import { useSurvey } from '@/hooks/useSurvey' +import { useAlertMsg, WARNING_MESSAGE } from '@/hooks/useAlertMsg' export default function SearchForm({ memberRole, userId }: { memberRole: string; userId: string }) { const router = useRouter() - const { showSurveyAlert } = useSurvey() - const { setSearchOption, setSort, setIsMySurvey, setKeyword, reset, isMySurvey, keyword, searchOption, sort, setOffset } = useSurveyFilterStore() + const { showErrorAlert } = useAlertMsg() + const { setSearchOption, setSort, setIsMySurvey, setKeyword, isMySurvey, keyword, searchOption, sort, setOffset } = useSurveyFilterStore() const [searchKeyword, setSearchKeyword] = useState(keyword) const [option, setOption] = useState(searchOption) const handleSearch = () => { if (option !== 'id' && searchKeyword.trim().length < 2) { - showSurveyAlert('2文字以上入力してください') + showErrorAlert(WARNING_MESSAGE.KEYWORD_MINIMUM_LENGTH) return } setOffset(0) @@ -64,7 +64,7 @@ export default function SearchForm({ memberRole, userId }: { memberRole: string; placeholder="タイトルを入力してください. (2文字以上)" onChange={(e) => { if (e.target.value.length > 30) { - showSurveyAlert('30文字以内で入力してください') + showErrorAlert(WARNING_MESSAGE.KEYWORD_MAX_LENGTH) return } setSearchKeyword(e.target.value) diff --git a/src/hooks/useAlertMsg.ts b/src/hooks/useAlertMsg.ts new file mode 100644 index 0000000..d0e82b9 --- /dev/null +++ b/src/hooks/useAlertMsg.ts @@ -0,0 +1,147 @@ +/** + * @description 성공 메세지 상수 객체 + */ +export const SUCCESS_MESSAGE = { + /** 저장 성공 - "저장되었습니다." */ + SAVE_SUCCESS: '保存されました。', + + /** 임시 저장 성공 - "임시 저장되었습니다." */ + TEMP_SAVE_SUCCESS: '一時保存されました。', + + /** 삭제 성공 - "삭제되었습니다." */ + DELETE_SUCCESS: '削除されました。', + + /** 제출 성공 - "제출이 완료되었습니다." */ + SUBMIT_SUCCESS: '提出が完了しました。', + + /** 문의 제목 최대값 메세지 - "문의 제목은 100자 이내로 입력하세요." */ + INQUIRY_TITLE_MAX_LENGTH: 'お問い合わせタイトルは100文字以内で入力してください。', + + /** 문의 내용 최대값 메세지 - "문의 내용은 2,000자 이내로 입력하세요." */ + INQUIRY_CONTENTS_MAX_LENGTH: 'お問い合わせ内容は2,000文字以内で入力してください。', + + /** PDF 생성 성공 - "PDF 생성이 완료되었습니다.\n팝업 창에서 다운로드 하세요." */ + PDF_GENERATION_SUCCESS: 'PDFの生成が完了しました。\nポップアップウィンドウからダウンロードしてください。', +} + +/** + * @description 확인 메세지 상수 객체 + */ +export const CONFIRM_MESSAGE = { + /** 제출 확인 - "제출하시겠습니까?" */ + SUBMIT_CONFIRM: '提出しますか?', + + /** 저장 확인 - "저장하시겠습니까?" */ + SAVE_CONFIRM: '保存しますか?', + + /** 삭제 확인 - "삭제하시겠습니까?" */ + DELETE_CONFIRM: '削除しますか?', + + /** 저장 및 제출 확인 - "입력한 정보를 저장하고 보내시겠습니까?" */ + SAVE_AND_SUBMIT_CONFIRM: '記入した情報を保存して送信しますか?', + + /** 문의 저장 확인 메세지 - "문의를 등록 하시겠습니까? 한화재팬 담당자에게 문의 메일이 발송됩니다." */ + SAVE_INQUIRY_CONFIRM: 'お問い合わせを登録しますか? Hanwha Japanの担当者にお問い合わせメールが送信されます。', +} + +export const WARNING_MESSAGE = { + /** 입력 오류 경고 메세지 */ + /** 필수 입력 메세지 - "~ 항목이 비어 있습니다."*/ + REQUIRED_FIELD_IS_EMPTY: '項目が空です。', + + /* 전기계약 용량 단위 입력 메세지 - "전기 계약 용량의 단위를 입력하세요."*/ + REQUIRED_UNIT_IS_EMPTY: '電気契約容量の単位を入力してください。', + + /** 이메일 유효성 에러 - "유효한 이메일 주소를 입력해 주세요." */ + EMAIL_PREFIX_IS_INVALID: '有効なメールアドレスを入力してください。', + + /** 최소값 오류 - "2자 이상 입력하세요" */ + KEYWORD_MINIMUM_LENGTH: '2文字以上入力してください', + + /** 최대값 오류 - "30자 이내로 입력하세요" */ + KEYWORD_MAX_LENGTH: '30文字以内で入力してください', + + /** 제목 최대값 오류 - "100자 이내로 입력하세요" */ + TITLE_MAX_LENGTH: '100文字以内で入力してください', + + /** 내용 최대값 오류 - "2,000자 이내로 입력하세요" */ + CONTENTS_MAX_LENGTH: '2,000文字以内で入力してください', + + /** 소수점 오류 - "소수점 이하 1자리까지만 허용됩니다." */ + DECIMAL_POINT_CANNOT_EXCEED: '小数点以下1桁までしか許されません。', + + /** 숫자 최대값 오류 - "저장할 수 있는 크기를 초과했습니다." */ + SAVE_SIZE_OVERFLOW: '保存できるサイズを超えました。', + + /** 최대 선택 오류 메세지 - "지붕재는 최대 2개까지 선택할 수 있습니다." */ + ROOF_MATERIAL_MAX_SELECT: '屋根材は最大2個まで選択できます。', + + /** 임시 저장 제출 오류 - "임시 저장된 데이터는 제출할 수 없습니다." */ + TEMP_CANNOT_SUBMIT: '一時保存されたデータは提出できません。', +} + +/** + * @description 에러 메세지 상수 객체 + * - 입력 오류 경고 메세지 + * - 결과 실패 메세지 + * - 서버 에러 메세지 + */ +export const ERROR_MESSAGE = { + /** 결과 실패 메세지 */ + /** PDF 생성 오류 - "PDF 생성에 실패했습니다." */ + PDF_GENERATION_ERROR: 'PDF 生成に失敗しました。', + + /** 이메일 전송 오류 - "이메일 전송에 실패했습니다. 다시 시도해주세요." */ + EMAIL_SEND_ERROR: 'メール送信に失敗しました。 再度送信してください。', + + /** 서버 에러 메세지 */ + /** 데이터를 찾을 수 없습니다. - 404 */ + NOT_FOUND: 'データが見つかりません。', + + /** 승인되지 않았습니다. - 401 */ + UNAUTHORIZED: '承認されていません。', + + /** 권한이 없습니다. - 403 */ + FORBIDDEN: '権限がありません。', + + /** 데이터의 조회에 실패했습니다. - 500 */ + FETCH_ERROR: 'データの取得に失敗しました。', + + /** 서버 에러 - "일시적인 오류가 발생했습니다. 계속되는 경우 관리자에게 문의하시기 바랍니다." - 500 */ + SERVER_ERROR: '一時的なエラーが発生しました。 継続的な場合は、管理者に連絡してください。', + + /** 잘못된 요청입니다. - 400 */ + BAD_REQUEST: '間違ったリクエストです。', + + /** 데이터베이스 오류가 발생했습니다. - 500 */ + PRISMA_ERROR: 'データベース エラーが発生しました。', +} + +export function useAlertMsg(): { + showErrorAlert: (message: string, requiredField?: string) => void + showConfirm: (message: string, onConfirm: () => void, onCancel?: () => void) => void + showSuccessAlert: (message: string) => void +} { + const showErrorAlert = (message: string, requiredField?: string) => { + if (message.trim() === '' || message === null || message === undefined) return + if (message.length > 100) { + alert(ERROR_MESSAGE.SERVER_ERROR) + return + } + requiredField ? alert(`${requiredField} ${message}`) : alert(message) + } + + const showConfirm = (message: string, onConfirm: () => void, onCancel?: () => void) => { + window.neoConfirm(message, onConfirm, onCancel) + } + + const showSuccessAlert = (message: string) => { + alert(message) + } + + return { + showErrorAlert, + showConfirm, + showSuccessAlert, + } +} diff --git a/src/hooks/useInquiry.ts b/src/hooks/useInquiry.ts index 707b0e0..3533084 100644 --- a/src/hooks/useInquiry.ts +++ b/src/hooks/useInquiry.ts @@ -3,8 +3,8 @@ import { useAxios } from '@/hooks/useAxios' 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' +import { useAlertMsg } from '@/hooks/useAlertMsg' /** * @description 문의사항 관련 기능을 제공하는 커스텀 훅 @@ -23,7 +23,7 @@ import { useRouter } from 'next/navigation' */ export function useInquiry( qnoNo?: number, - compCd?: string, + isList?: boolean, ): { inquiryList: InquiryList[] isLoadingInquiryList: boolean @@ -36,20 +36,24 @@ export function useInquiry( } { const queryClient = useQueryClient() const { inquiryListRequest, offset } = useInquiryFilterStore() - const { session } = useSessionStore() const { axiosInstance } = useAxios() const router = useRouter() - + const { showErrorAlert } = useAlertMsg() /** * @description API 에러 처리 및 라우팅 * * @param {any} error 에러 객체 * @returns {void} 라우팅 처리 */ - const errorRouter = (error: any) => { + const handleError = (error: any, isThrow?: boolean) => { const status = error.response?.status - if (error.response?.data.error) { - alert(error.response?.data.error) + const errorMsg = error.response?.data.error + console.error('❌ AXIOS INSTANCE ERROR : ', error) + if (errorMsg) { + showErrorAlert(errorMsg) + } + if (isThrow) { + throw new Error(error) } switch (status) { // session 없는 경우 @@ -73,6 +77,25 @@ export function useInquiry( } } + /** + * @description 비동기 함수 try-catch 처리 함수 + * @param {() => Promise} func 비동기 함수 + * @param {boolean} isList 목록 조회 여부 + * @param {boolean} isThrow 에러 던지기 여부 + * @returns {Promise} 함수 결과 또는 빈 데이터 + */ + const tryFunction = async (func: () => Promise, isList?: boolean, isThrow?: boolean): Promise => { + try { + return await func() + } catch (error) { + handleError(error, isThrow) + if (isList) { + return { data: [], count: 0 } + } + return null + } + } + /** * @description 문의사항 목록 조회 * @@ -83,17 +106,20 @@ export function useInquiry( const { data: inquiryList, isLoading: isLoadingInquiryList } = useQuery({ queryKey: ['inquiryList', inquiryListRequest, offset], queryFn: async () => { - try { - const resp = await axiosInstance(null).get<{ data: InquiryList[] }>(`/api/qna/list`, { - params: { inquiryListRequest, startRow: offset, endRow: offset + 9 }, - }) - return resp.data.data - } catch (error: any) { - errorRouter(error) - return [] - } + const isListQuery = true + const shouldThrowError = false + + const resp = await tryFunction( + () => + axiosInstance(null).get<{ data: InquiryList[] }>(`/api/qna/list`, { + params: { inquiryListRequest, startRow: offset, endRow: offset + 9 }, + }), + isListQuery, + shouldThrowError, + ) + return resp.data }, - enabled: !!inquiryListRequest, + enabled: isList, }) /** @@ -119,19 +145,22 @@ export function useInquiry( * @returns {boolean} isLoading - 문의사항 상세 정보 로딩 상태 */ const { data: inquiryDetail, isLoading: isLoadingInquiryDetail } = useQuery({ - queryKey: ['inquiryDetail', qnoNo, compCd, session?.userId], + queryKey: ['inquiryDetail', qnoNo], queryFn: async () => { - try { - const resp = await axiosInstance(null).get<{ data: Inquiry }>(`/api/qna/detail`, { - params: { qnoNo, compCd, langCd: 'JA', loginId: session?.userId ?? '' }, - }) - return resp.data.data - } catch (error: any) { - errorRouter(error) - return null - } + const isListQuery = false + const shouldThrowError = false + + const resp = await tryFunction( + () => + axiosInstance(null).get<{ data: Inquiry }>(`/api/qna/detail`, { + params: { qnoNo, compCd: '5200', langCd: 'JA' }, + }), + isListQuery, + shouldThrowError, + ) + return resp?.data ?? null }, - enabled: qnoNo !== undefined && compCd !== undefined, + enabled: qnoNo !== undefined, }) /** @@ -142,14 +171,21 @@ export function useInquiry( */ const { mutateAsync: saveInquiry, isPending: isSavingInquiry } = useMutation({ mutationFn: async (formData: FormData) => { - const resp = await axiosInstance(null).post<{ data: InquirySaveResponse }>('/api/qna/save', formData) - return resp.data.data + const isListQuery = false + const shouldThrowError = true + + const resp = await tryFunction( + () => axiosInstance(null).post<{ data: InquirySaveResponse }>('/api/qna/save', formData), + isListQuery, + shouldThrowError, + ) + return resp?.data ?? null }, onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['inquiryList'] }) }, onError: (error: any) => { - errorRouter(error) + handleError(error, true) }, }) @@ -161,24 +197,21 @@ export function useInquiry( * @returns {Promise} 다운로드된 파일 데이터 또는 null */ const downloadFile = async (encodeFileNo: number, srcFileNm: string) => { - try { - const resp = await fetch(`/api/qna/file?encodeFileNo=${encodeFileNo}&srcFileNm=${srcFileNm}`) + const isListQuery = false + const shouldThrowError = true - const blob = await resp.blob() - const url = URL.createObjectURL(blob) - const a = document.createElement('a') - a.href = url - a.download = srcFileNm - document.body.appendChild(a) - a.click() - document.body.removeChild(a) - URL.revokeObjectURL(url) + const resp = await tryFunction(() => fetch(`/api/qna/file?encodeFileNo=${encodeFileNo}&srcFileNm=${srcFileNm}`), isListQuery, shouldThrowError) + const blob = await resp.blob() + const url = URL.createObjectURL(blob) + const a = document.createElement('a') + a.href = url + a.download = srcFileNm + document.body.appendChild(a) + a.click() + document.body.removeChild(a) + URL.revokeObjectURL(url) - return blob - } catch (error) { - alert('ファイルのダウンロードに失敗しました') - return null - } + return blob } /** @@ -191,7 +224,10 @@ export function useInquiry( const { data: commonCodeList, isLoading: isLoadingCommonCodeList } = useQuery({ queryKey: ['commonCodeList'], queryFn: async () => { - const resp = await axiosInstance(null).get<{ data: CommonCode[] }>(`/api/qna`) + const isListQuery = false + const shouldThrowError = false + + const resp = await tryFunction(() => axiosInstance(null).get<{ data: CommonCode[] }>(`/api/qna`), isListQuery, shouldThrowError) return resp.data }, staleTime: Infinity, diff --git a/src/hooks/useSurvey.ts b/src/hooks/useSurvey.ts index 98821a1..471d5aa 100644 --- a/src/hooks/useSurvey.ts +++ b/src/hooks/useSurvey.ts @@ -1,4 +1,4 @@ -import { SURVEY_ALERT_MSG, type SubmitTargetResponse, type SurveyBasicInfo, type SurveyDetailRequest, type SurveyRegistRequest } from '@/types/Survey' +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' @@ -6,8 +6,7 @@ import { useSessionStore } from '@/store/session' import { useAxios } from './useAxios' import { queryStringFormatter } from '@/utils/common-utils' import { useRouter } from 'next/navigation' - - +import { ERROR_MESSAGE, useAlertMsg } from './useAlertMsg' export const requiredFields = [ { @@ -95,15 +94,13 @@ export function useSurvey( refetchSurveyList: () => void refetchSurveyDetail: () => void getSubmitTarget: (params: { storeId: string; role: string }) => Promise - showSurveyAlert: (message: (typeof SURVEY_ALERT_MSG)[keyof typeof SURVEY_ALERT_MSG] | string, requiredField?: string) => void - showSurveyConfirm: (message: string, onConfirm: () => void, onCancel?: () => void) => void } { const queryClient = useQueryClient() const { keyword, searchOption, isMySurvey, sort, offset } = useSurveyFilterStore() const { session } = useSessionStore() const { axiosInstance } = useAxios() const router = useRouter() - + const { showErrorAlert } = useAlertMsg() /** * @description 조사 매물 목록, 상세 데이터 조회 에러 처리 * @@ -114,9 +111,9 @@ export function useSurvey( const handleError = (error: any, isThrow?: boolean) => { const status = error.response?.status const errorMsg = error.response?.data.error - console.error('❌ API ERROR : ', error) + console.error('❌ AXIOS INSTANCE ERROR : ', error) if (errorMsg) { - showSurveyAlert(errorMsg) + showErrorAlert(errorMsg) } if (isThrow) { throw new Error(error) @@ -419,55 +416,18 @@ export function useSurvey( const getSubmitTarget = async (params: { storeId: string; role: string }): Promise => { if (!params.storeId) { /** 판매점 ID 없는 경우 */ - showSurveyAlert('販売店IDがありません。') + showErrorAlert(ERROR_MESSAGE.BAD_REQUEST) return null } const endpoint = `/api/submission?storeId=${params.storeId}&role=${params.role}` if (!endpoint) { /** 권한 오류 */ - showSurveyAlert('権限が間違っています。') + showErrorAlert(ERROR_MESSAGE.FORBIDDEN) return null } return await tryFunction(() => axiosInstance(null).get(endpoint), false, true) } - /** - * @description 조사 매물 알림 메시지 출력 - * - * @param {string} message 알림 메시지 - * @param {string} [requiredField] 필수 필드 이름 - */ - const showSurveyAlert = ( - message: (typeof SURVEY_ALERT_MSG)[keyof typeof SURVEY_ALERT_MSG] | string, - requiredField?: (typeof requiredFields)[number]['field'], - ) => { - if (requiredField) { - alert(`${requiredField} ${message}`) - } else { - alert(message) - } - } - - /** - * @description 조사 매물 확인 메시지 출력 - * - * @param {string} message 확인 메시지 - * @param {Function} onConfirm 확인 함수 - * @param {Function} [onCancel] 취소 함수 - */ - const showSurveyConfirm = (message: string, onConfirm: () => void, onCancel?: () => void) => { - if (window.neoConfirm) { - window.neoConfirm(message, onConfirm) - } else { - const confirmed = confirm(message) - if (confirmed) { - onConfirm() - } else if (onCancel) { - onCancel() - } - } - } - return { surveyList: surveyData.data, surveyDetail: surveyDetail as SurveyBasicInfo | null, @@ -486,7 +446,5 @@ export function useSurvey( getSubmitTarget, refetchSurveyList, refetchSurveyDetail, - showSurveyAlert, - showSurveyConfirm, } } diff --git a/src/types/Survey.ts b/src/types/Survey.ts index 3802916..3e10082 100644 --- a/src/types/Survey.ts +++ b/src/types/Survey.ts @@ -322,36 +322,4 @@ export type SurveySearchParams = { storeId?: string | null /** 시공점 ID */ builderId?: string | null -} - - -export const SURVEY_ALERT_MSG = { - /** 기본 메세지 */ - /** 저장 성공 - "저장되었습니다." */ - SAVE_SUCCESS: '保存されました。', - /** 임시 저장 성공 - "임시 저장되었습니다." */ - TEMP_SAVE_SUCCESS: '一時保存されました。', - /** 삭제 성공 - "삭제되었습니다." */ - DELETE_SUCCESS: '削除されました。', - /** 제출 확인 - "제출하시겠습니까?" */ - SUBMIT_CONFIRM: '提出しますか?', - /** 저장 확인 - "저장하시겠습니까?" */ - SAVE_CONFIRM: '保存しますか?', - /** 삭제 확인 - "삭제하시겠습니까?" */ - DELETE_CONFIRM: '削除しますか?', - /** 저장 및 제출 확인 - "입력한 정보를 저장하고 보내시겠습니까?" */ - SAVE_AND_SUBMIT_CONFIRM: '記入した情報を保存して送信しますか?', - /** 임시 저장 제출 오류 - "임시 저장된 데이터는 제출할 수 없습니다." */ - TEMP_SAVE_SUBMIT_ERROR: '一時保存されたデータは提出できません。', - - /** 입력 오류 메세지 */ - /* 전기계약 용량 단위 입력 메세지 - "전기 계약 용량의 단위를 입력하세요."*/ - UNIT_REQUIRED: '電気契約容量の単位を入力してください。', - /** 필수 입력 메세지 - "항목이 비어 있습니다."*/ - REQUIRED_FIELD: '項目が空です。', - /** 최대 선택 오류 메세지 - "지붕재는 최대 2개까지 선택할 수 있습니다." */ - ROOF_MATERIAL_MAX_SELECT_ERROR: '屋根材は最大2個まで選択できます。', - - /** PDF 생성 오류 - "PDF 생성에 실패했습니다." */ - PDF_GENERATION_ERROR: 'PDF 生成に失敗しました。', } \ No newline at end of file diff --git a/src/utils/common-utils.js b/src/utils/common-utils.js index e4eb144..a81373c 100644 --- a/src/utils/common-utils.js +++ b/src/utils/common-utils.js @@ -209,21 +209,3 @@ export const convertToSnakeCase = (obj) => { return obj } - -/** - * @description 조사 매물 조회 에러 메시지 - */ -export const ERROR_MESSAGES = { - /** 데이터를 찾을 수 없습니다. */ - NOT_FOUND: 'データが見つかりません。', - /** 승인되지 않았습니다. */ - UNAUTHORIZED: '承認されていません。', - /** 권한이 없습니다. */ - NO_PERMISSION: '権限がありません。', - /** 데이터의 조회에 실패했습니다. */ - FETCH_ERROR: 'データの取得に失敗しました。', - /** 잘못된 요청입니다. */ - BAD_REQUEST: '間違ったリクエストです。', - /** 데이터베이스 오류가 발생했습니다. */ - PRISMA_ERROR: 'データベース エラーが発生しました。', -}