fix: survey update, create, submit logic fix

- 조사매물 수정, 작성, 조회 시 각 컴포넌트에 데이터 적용 안되던 문제 해결
- 조사매물 제출 시 데이터 저장 안되는 문제 해결결
This commit is contained in:
Dayoung 2025-05-20 17:56:09 +09:00
parent d21865ca65
commit 905a309a9c
7 changed files with 140 additions and 127 deletions

View File

@ -23,30 +23,22 @@ export async function PUT(request: NextRequest, { params }: { params: Promise<{
try {
const { id } = await params
const body = await request.json()
const { DETAIL_INFO, ...basicInfo } = body
const { detailInfo, ...basicInfo } = body
console.log('body:: ', body)
// @ts-ignore
const survey = await prisma.SD_SURVEY_SALES_BASIC_INFO.update({
where: { ID: Number(id) },
data: {
...convertToSnakeCase(basicInfo),
UPT_DT: new Date(),
DETAIL_INFO: DETAIL_INFO ? {
upsert: {
create: convertToSnakeCase(DETAIL_INFO),
update: convertToSnakeCase(DETAIL_INFO),
where: {
BASIC_INFO_ID: Number(id)
}
}
} : undefined
DETAIL_INFO: {
update: convertToSnakeCase(detailInfo)
}
},
include: {
DETAIL_INFO: true
}
})
console.log('survey:: ', survey)
return NextResponse.json(survey)
} catch (error) {
console.error('Error updating survey:', error)

View File

@ -236,6 +236,7 @@ export async function POST(request: Request) {
}
}
})
console.log('result:: ', result)
return NextResponse.json(result)
} catch (error) {
console.error(error)

View File

@ -22,8 +22,13 @@ export default function ButtonForm(props: {
const params = useParams()
const routeId = params.id
const [isSubmitProcess, setIsSubmitProcess] = useState(false)
// ------------------------------------------------------------
const [isSubmitProcess, setIsSubmitProcess] = useState(false)
const [saveData, setSaveData] = useState({
...props.data.basic,
detailInfo: props.data.roof,
})
// --------------------------------------------------------------
// 권한
// 제출권한 ㅇ
@ -37,6 +42,10 @@ export default function ButtonForm(props: {
setIsSubmiter(session.storeNm === props.data.basic.store && session.builderNo === props.data.basic.constructionPoint)
setIsWriter(session.userNm === props.data.basic.representative)
}
setSaveData({
...props.data.basic,
detailInfo: props.data.roof,
})
}, [session, props.data])
// ------------------------------------------------------------
@ -45,18 +54,13 @@ export default function ButtonForm(props: {
const id = routeId ? Number(routeId) : Number(idParam)
const { deleteSurvey, submitSurvey, updateSurvey } = useServey(Number(id))
const { validateSurveyDetail, createSurvey } = useServey()
let saveData = {
...props.data.basic,
detailInfo: props.data.roof,
}
const handleSave = (isTemporary: boolean) => {
const handleSave = (isTemporary: boolean, isSubmitProcess?: boolean) => {
const emptyField = validateSurveyDetail(props.data.roof)
console.log('handleSave, emptyField:: ', emptyField)
if (isTemporary) {
tempSaveProcess()
} else {
saveProcess(emptyField)
saveProcess(emptyField, isSubmitProcess ?? false)
}
}
@ -78,30 +82,38 @@ export default function ButtonForm(props: {
}
}
const saveProcess = async (emptyField: string) => {
if (emptyField.trim() === '') {
const saveProcess = async (emptyField: string | null, isSubmitProcess?: boolean) => {
if (emptyField?.trim() === '') {
if (idParam) {
// 수정 페이지에서 작성 후 제출
if (isSubmitProcess) {
saveData = {
const updatedData = {
...saveData,
submissionStatus: true,
submissionDate: new Date().toISOString(),
}
await updateSurvey(updatedData)
router.push(`/survey-sale/${idParam}`)
} else {
await updateSurvey(saveData)
router.push(`/survey-sale/${idParam}`)
}
await updateSurvey(saveData)
router.push(`/survey-sale/${idParam}`)
} else {
const id = await createSurvey(saveData)
if (isSubmitProcess) {
const updatedData = {
...saveData,
submissionStatus: true,
submissionDate: new Date().toISOString(),
}
const id = await createSurvey(updatedData)
submitProcess(id)
return
} else {
const id = await createSurvey(saveData)
router.push(`/survey-sale/${id}`)
}
router.push(`/survey-sale/${id}`)
}
alert('保存されました。')
} else {
if (emptyField.includes('Unit')) {
if (emptyField?.includes('Unit')) {
alert('電気契約容量の単位を入力してください。')
focusInput(emptyField as keyof SurveyDetailInfo)
} else {
@ -124,11 +136,10 @@ export default function ButtonForm(props: {
const handleSubmit = async () => {
window.neoConfirm('提出しますか?', async () => {
setIsSubmitProcess(true)
if (routeId) {
if (Number(routeId)) {
submitProcess()
} else {
handleSave(false)
handleSave(false, true)
}
})
}

View File

@ -81,11 +81,12 @@ export default function DetailForm() {
setRoofInfoData(rest)
}
}
}, [surveyDetail, mode])
}, [surveyDetail])
// console.log('mode:: ', mode)
// console.log('surveyDetail:: ', surveyDetail)
// console.log('roofInfoData:: ', roofInfoData)
// console.log('basicInfoData:: ', basicInfoData)
console.log('roofInfoData:: ', roofInfoData)
const data = {
basic: basicInfoData,

View File

@ -464,17 +464,17 @@ const SelectedBox = ({
}) => {
const selectedId = detailInfoData?.[column as keyof SurveyDetailInfo]
const etcValue = detailInfoData?.[`${column}Etc` as keyof SurveyDetailInfo]
const [isEtcSelected, setIsEtcSelected] = useState<boolean>(Boolean(etcValue))
const [isEtcSelected, setIsEtcSelected] = useState<boolean>(etcValue !== null && etcValue !== undefined && etcValue !== '')
const [etcVal, setEtcVal] = useState<string>(etcValue?.toString() ?? '')
const isSpecialCase = column === 'constructionYear' || column === 'installationAvailability'
const showEtcOption = !isSpecialCase
const handleSelectChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
const value = e.target.value
const isSpecialCase = column === 'constructionYear' || column === 'installationAvailability'
const isEtc = value === 'etc'
const isSpecialEtc = isSpecialCase && value === '2'
const updatedData: typeof detailInfoData = {
const updatedData = {
...detailInfoData,
[column]: isEtc ? null : value,
[`${column}Etc`]: isEtc ? '' : null,
@ -485,14 +485,20 @@ const SelectedBox = ({
}
setIsEtcSelected(isEtc || isSpecialEtc)
if (!isEtc) setEtcVal('')
setRoofInfo(updatedData)
}
const handleEtcInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const value = e.target.value
setEtcVal(value)
setRoofInfo({ ...detailInfoData, [`${column}Etc`]: value })
setRoofInfo({ ...detailInfoData, [`${column}Etc`]: e.target.value })
}
const isInputDisabled = () => {
if (mode === 'READ') return true
if (column === 'installationAvailability') return false
if (column === 'constructionYear') {
return detailInfoData.constructionYear === '1' || detailInfoData.constructionYear === null
}
return !isEtcSelected && !etcValue
}
return (
@ -502,7 +508,7 @@ const SelectedBox = ({
name={column}
id={column}
disabled={mode === 'READ'}
value={selectedId ? Number(selectedId) : etcValue !== null ? 'etc' : ''}
value={selectedId ? Number(selectedId) : etcValue ? 'etc' : ''}
onChange={handleSelectChange}
>
{selectBoxOptions[column as keyof typeof selectBoxOptions].map((item) => (
@ -510,7 +516,7 @@ const SelectedBox = ({
{item.name}
</option>
))}
{column !== 'installationAvailability' && column !== 'constructionYear' && (
{showEtcOption && (
<option key="etc" value="etc">
()
</option>
@ -524,17 +530,9 @@ const SelectedBox = ({
type="text"
className="input-frame"
placeholder="-"
value={etcVal}
value={detailInfoData[`${column}Etc` as keyof SurveyDetailInfo]?.toString() ?? ''}
onChange={handleEtcInputChange}
disabled={
mode === 'READ'
? true
: column === 'installationAvailability'
? false
: column === 'constructionYear'
? detailInfoData.constructionYear === '1' || detailInfoData.constructionYear === null
: !isEtcSelected
}
disabled={isInputDisabled()}
/>
</div>
</>
@ -552,49 +550,52 @@ const RadioSelected = ({
detailInfoData: SurveyDetailInfo
setRoofInfo: (roofInfo: SurveyDetailRequest) => void
}) => {
let selectedId = detailInfoData?.[column as keyof SurveyDetailInfo]
if (column === 'leakTrace') {
selectedId = Number(selectedId)
if (!selectedId) selectedId = 2
}
const etcValue = detailInfoData?.[`${column}Etc` as keyof SurveyDetailInfo]
const [etcChecked, setEtcChecked] = useState<boolean>(Boolean(etcValue))
let etcValue = null
if (column !== 'rafterDirection') {
etcValue = detailInfoData?.[`${column}Etc` as keyof SurveyDetailInfo]
}
const [etcChecked, setEtcChecked] = useState<boolean>(etcValue !== null && etcValue !== undefined && etcValue !== '')
const [etcVal, setEtcVal] = useState<string>(etcValue?.toString() ?? '')
const selectedId = column === 'leakTrace'
? Number(detailInfoData?.[column as keyof SurveyDetailInfo]) || 2
: detailInfoData?.[column as keyof SurveyDetailInfo]
const isSpecialColumn = column === 'rafterDirection' || column === 'leakTrace' || column === 'insulationPresence'
const showEtcOption = !isSpecialColumn
const handleRadioChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const value = e.target.value
if (column === 'leakTrace') {
handleBooleanRadioChange(value)
setRoofInfo({ ...detailInfoData, leakTrace: value === '1' })
return
}
if (value === 'etc') {
setEtcChecked(true)
setRoofInfo({ ...detailInfoData, [column]: null, [`${column}Etc`]: '' })
} else {
if (column === 'insulationPresence' && value === '2') {
setEtcChecked(true)
} else {
setEtcChecked(false)
}
setRoofInfo({ ...detailInfoData, [column]: value, [`${column}Etc`]: null })
return
}
}
const handleBooleanRadioChange = (value: string) => {
if (value === '1') {
setRoofInfo({ ...detailInfoData, leakTrace: true })
} else {
setRoofInfo({ ...detailInfoData, leakTrace: false })
}
const isInsulationPresence = column === 'insulationPresence'
const isRafterDirection = column === 'rafterDirection'
setEtcChecked(isInsulationPresence && value === '2')
setRoofInfo({
...detailInfoData,
[column]: value,
[`${column}Etc`]: isRafterDirection ? detailInfoData[`${column}Etc` as keyof SurveyDetailInfo] : null
})
}
const handleEtcInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const value = e.target.value
setEtcVal(value)
setRoofInfo({ ...detailInfoData, [`${column}Etc`]: value })
setRoofInfo({ ...detailInfoData, [`${column}Etc`]: e.target.value })
}
const isInputDisabled = () => {
if (mode === 'READ') return true
if (column === 'insulationPresence') {
return detailInfoData.insulationPresence !== '2'
}
return !etcChecked && !etcValue
}
return (
@ -613,7 +614,7 @@ const RadioSelected = ({
<label htmlFor={`${column}_${item.id}`}>{item.label}</label>
</div>
))}
{column !== 'rafterDirection' && column !== 'leakTrace' && column !== 'insulationPresence' && (
{showEtcOption && (
<div className="radio-form-box mb10">
<input
type="radio"
@ -621,21 +622,21 @@ const RadioSelected = ({
id={`${column}Etc`}
value="etc"
disabled={mode === 'READ'}
checked={etcChecked}
checked={etcChecked || Boolean(etcValue)}
onChange={handleRadioChange}
/>
<label htmlFor={`${column}Etc`}> ()</label>
</div>
)}
{column !== 'leakTrace' && column !== 'rafterDirection' && (
{showEtcOption && (
<div className="data-input">
<input
type="text"
className="input-frame"
placeholder="-"
value={etcVal}
value={detailInfoData[`${column}Etc` as keyof SurveyDetailInfo]?.toString() ?? ''}
onChange={handleEtcInputChange}
disabled={mode === 'READ' || !etcChecked}
disabled={isInputDisabled()}
/>
</div>
)}
@ -655,51 +656,56 @@ const MultiCheck = ({
setRoofInfo: (roofInfo: SurveyDetailRequest) => void
}) => {
const multiCheckData = column === 'supplementaryFacilities' ? supplementaryFacilities : roofMaterial
const etcValue = roofInfo?.[`${column}Etc` as keyof SurveyDetailInfo]
const [isOtherCheck, setIsOtherCheck] = useState<boolean>(Boolean(etcValue))
const [isOtherCheck, setIsOtherCheck] = useState<boolean>(false)
const [otherValue, setOtherValue] = useState<string>(roofInfo?.[`${column}Etc` as keyof SurveyDetailInfo]?.toString() ?? '')
const isRoofMaterial = column === 'roofMaterial'
const selectedValues = makeNumArr(String(roofInfo[column as keyof SurveyDetailInfo] ?? ''))
const handleCheckbox = (id: number) => {
const value = makeNumArr(String(roofInfo[column as keyof SurveyDetailInfo] ?? ''))
const isOtherSelected = roofInfo?.[`${column}Etc` as keyof SurveyDetailInfo] !== null
const isOtherSelected = Boolean(etcValue)
let newValue: string[]
if (value.includes(String(id))) {
newValue = value.filter((v) => v !== String(id))
} else {
if (column === 'roofMaterial') {
const totalSelected = value.length + (isOtherSelected ? 1 : 0)
if (selectedValues.includes(String(id))) {
newValue = selectedValues.filter((v) => v !== String(id))
} else {
if (isRoofMaterial) {
const totalSelected = selectedValues.length + (isOtherSelected ? 1 : 0)
if (totalSelected >= 2) {
alert('屋根材は最大2個まで選択できます。')
return
}
}
newValue = [...value, String(id)]
newValue = [...selectedValues, String(id)]
}
setRoofInfo({ ...roofInfo, [column]: newValue.join(',') })
}
const handleOtherCheckbox = () => {
if (column === 'roofMaterial') {
const value = makeNumArr(String(roofInfo[column as keyof SurveyDetailInfo] ?? ''))
const currentSelected = value.length
if (isRoofMaterial) {
const currentSelected = selectedValues.length
if (!isOtherCheck && currentSelected >= 2) {
alert('屋根材は最大2個まで選択できます。')
return
}
}
const newIsOtherCheck = !isOtherCheck
setIsOtherCheck(newIsOtherCheck)
setOtherValue('')
setRoofInfo({ ...roofInfo, [`${column}Etc`]: newIsOtherCheck ? '' : null })
// 기타 선택 해제 시 값도 null로 설정
setRoofInfo({
...roofInfo,
[`${column}Etc`]: newIsOtherCheck ? '' : null
})
}
const handleOtherInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const value = e.target.value
setOtherValue(value)
setRoofInfo({ ...roofInfo, [`${column}Etc`]: value })
setRoofInfo({ ...roofInfo, [`${column}Etc`]: e.target.value })
}
const isInputDisabled = () => {
return mode === 'READ' || (!isOtherCheck && !etcValue)
}
return (
@ -710,7 +716,7 @@ const MultiCheck = ({
<input
type="checkbox"
id={`${column}_${item.id}`}
checked={makeNumArr(String(roofInfo[column as keyof SurveyDetailInfo] ?? '')).includes(String(item.id))}
checked={selectedValues.includes(String(item.id))}
disabled={mode === 'READ'}
onChange={() => handleCheckbox(item.id)}
/>
@ -721,7 +727,7 @@ const MultiCheck = ({
<input
type="checkbox"
id={`${column}Etc`}
checked={roofInfo?.[`${column}Etc` as keyof SurveyDetailInfo] !== null}
checked={isOtherCheck || Boolean(etcValue)}
disabled={mode === 'READ'}
onChange={handleOtherCheckbox}
/>
@ -733,9 +739,9 @@ const MultiCheck = ({
type="text"
className="input-frame"
placeholder="-"
value={otherValue}
value={roofInfo[`${column}Etc` as keyof SurveyDetailInfo]?.toString() ?? ''}
onChange={handleOtherInputChange}
disabled={mode === 'READ' || !isOtherCheck}
disabled={isInputDisabled()}
/>
</div>
</>

View File

@ -2,8 +2,8 @@
import LoadMoreButton from '@/components/LoadMoreButton'
import { useServey } from '@/hooks/useSurvey'
import { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'
import { useEffect, useState, useMemo, useRef } from 'react'
import { useRouter, usePathname } from 'next/navigation'
import SearchForm from './SearchForm'
import { useSurveyFilterStore } from '@/store/surveyFilterStore'
import { useSessionStore } from '@/store/session'
@ -11,19 +11,26 @@ import type { SurveyBasicInfo } from '@/types/Survey'
export default function ListTable() {
const router = useRouter()
const pathname = usePathname()
const { surveyList, isLoadingSurveyList } = useServey()
const { offset, setOffset } = useSurveyFilterStore()
const { session } = useSessionStore()
const [heldSurveyList, setHeldSurveyList] = useState<SurveyBasicInfo[]>([])
const [hasMore, setHasMore] = useState(false)
const { session } = useSessionStore()
useEffect(() => {
setOffset(0)
setHeldSurveyList([])
}, [pathname])
useEffect(() => {
if (!session.isLoggedIn || !('data' in surveyList)) return
if ('count' in surveyList && surveyList.count > 0) {
if (offset > 0) {
setHeldSurveyList((prev) => [...prev, ...surveyList.data])
setHeldSurveyList(prev => [...prev, ...surveyList.data])
} else {
setHeldSurveyList(surveyList.data)
}
@ -32,22 +39,17 @@ export default function ListTable() {
setHeldSurveyList([])
setHasMore(false)
}
}, [surveyList, offset, session])
}, [surveyList, offset, session.isLoggedIn])
const handleDetailClick = (id: number) => {
router.push(`/survey-sale/${id}`)
}
const handleItemsInit = () => {
setHeldSurveyList([])
setOffset(0)
}
// TODO: 로딩 처리 필요
return (
<>
<SearchForm memberRole={session?.role ?? ''} userId={session?.userId ?? ''} />
<SearchForm memberRole={session?.role ?? ''} userNm={session?.userNm ?? ''} />
{heldSurveyList.length > 0 ? (
<div className="sale-frame">
<ul className="sale-list-wrap">

View File

@ -4,7 +4,7 @@ import { SEARCH_OPTIONS, SEARCH_OPTIONS_ENUM, SEARCH_OPTIONS_PARTNERS, useSurvey
import { useRouter } from 'next/navigation'
import { useState } from 'react'
export default function SearchForm({ memberRole, userId }: { memberRole: string; userId: string }) {
export default function SearchForm({ memberRole, userNm }: { memberRole: string; userNm: string }) {
const router = useRouter()
const { setSearchOption, setSort, setIsMySurvey, setKeyword, isMySurvey, keyword, searchOption, sort } = useSurveyFilterStore()
const [searchKeyword, setSearchKeyword] = useState(keyword)
@ -75,9 +75,9 @@ export default function SearchForm({ memberRole, userId }: { memberRole: string;
<input
type="checkbox"
id="ch01"
checked={isMySurvey === userId}
checked={isMySurvey === userNm}
onChange={() => {
setIsMySurvey(isMySurvey === userId ? null : userId)
setIsMySurvey(isMySurvey === userNm ? null : userNm)
}}
/>
<label htmlFor="ch01"></label>