refactor : change the type of error and warning messages to constant

This commit is contained in:
Dayoung 2025-06-19 15:54:48 +09:00
parent d62caaf857
commit 17003cb74a
17 changed files with 231 additions and 169 deletions

View File

@ -1,7 +1,7 @@
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'
@ -30,7 +30,7 @@ async function downloadFile(request: Request): Promise<NextResponse> {
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}`

View File

@ -1,6 +1,6 @@
import { SessionData } from '@/types/Auth'
import { CommonCode } from '@/types/Inquiry'
import { ERROR_MESSAGES } from '@/utils/common-utils'
import { ERROR_MESSAGE } from '@/hooks/useAlertMsg'
import { HttpStatusCode } from 'axios'
import { ApiError } from 'next/dist/server/api-utils'
@ -16,7 +16,7 @@ export class QnaService {
*/
private handleRouteError(error: any): ApiError {
console.error('❌ API ROUTE ERROR : ', error)
return new ApiError(error.response.status, error.response.data.result.message ?? ERROR_MESSAGES.FETCH_ERROR)
return new ApiError(error.response.status, error.response.data.result.message ?? ERROR_MESSAGE.FETCH_ERROR)
}
/**
* @description try-catch
@ -25,7 +25,7 @@ export class QnaService {
*/
async tryFunction(func: () => Promise<any>, isFile?: boolean): Promise<ApiError | any> {
if (this.session !== undefined && !this.session?.isLoggedIn) {
return new ApiError(HttpStatusCode.Unauthorized, ERROR_MESSAGES.UNAUTHORIZED)
return new ApiError(HttpStatusCode.Unauthorized, ERROR_MESSAGE.UNAUTHORIZED)
}
try {
const response = await func()
@ -44,7 +44,7 @@ export class QnaService {
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_MESSAGES.NOT_FOUND)
return new ApiError(HttpStatusCode.NotFound, ERROR_MESSAGE.NOT_FOUND)
}
return new ApiError(response.result.code, response.result.message)
}

View File

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

View File

@ -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)
}
}
@ -101,9 +101,9 @@ export class SubmissionService {
error instanceof Prisma.PrismaClientValidationError ||
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)
}
/**

View File

@ -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
}
@ -435,9 +436,9 @@ export class SurveySalesService {
error instanceof Prisma.PrismaClientValidationError ||
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)
}
/**

View File

@ -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, 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<File[]>([])
/** 파일 첨부 처리 */
@ -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,

View File

@ -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<HTMLInputElement>) => {

View File

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

View File

@ -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<SubmitFormData>({
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)

View File

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

View File

@ -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<boolean>(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>(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
}
}

View File

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

147
src/hooks/useAlertMsg.ts Normal file
View File

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

View File

@ -1,9 +1,10 @@
import { InquiryList, Inquiry, InquirySaveResponse, CommonCode, INQUIRY_ALERT_MSG } from '@/types/Inquiry'
import { InquiryList, Inquiry, InquirySaveResponse, CommonCode } from '@/types/Inquiry'
import { useAxios } from '@/hooks/useAxios'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useInquiryFilterStore } from '@/store/inquiryFilterStore'
import { useMemo } from 'react'
import { useRouter } from 'next/navigation'
import { useAlertMsg } from '@/hooks/useAlertMsg'
/**
* @description
@ -32,12 +33,12 @@ export function useInquiry(
saveInquiry: (formData: FormData) => Promise<InquirySaveResponse>
downloadFile: (encodeFileNo: number, srcFileNm: string) => Promise<Blob | null>
commonCodeList: CommonCode[]
} {
const queryClient = useQueryClient()
const { inquiryListRequest, offset } = useInquiryFilterStore()
const { axiosInstance } = useAxios()
const router = useRouter()
const { showErrorAlert } = useAlertMsg()
/**
* @description API
*
@ -49,7 +50,7 @@ export function useInquiry(
const errorMsg = error.response?.data.error
console.error('❌ AXIOS INSTANCE ERROR : ', error)
if (errorMsg) {
showInquiryAlert(errorMsg)
showErrorAlert(errorMsg)
}
if (isThrow) {
throw new Error(error)

View File

@ -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<SubmitTargetResponse[] | null>
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 ,
*
@ -116,7 +113,7 @@ export function useSurvey(
const errorMsg = error.response?.data.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<SubmitTargetResponse[] | null> => {
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<SubmitTargetResponse[]>(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,
}
}

View File

@ -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 生成に失敗しました。',
}

View File

@ -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: 'データベース エラーが発生しました。',
}