Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion src/entities/event/hook/useEventHook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import { useParams } from 'react-router-dom';
import { useUserInfo } from '../../../features/join/hooks/useUserHook';
import { ApiResponse } from '../../../shared/types/api/apiResponse';
import useAuthStore from '../../../app/provider/authStore';
import { AxiosError } from 'axios';
import { EventDeletionResponse } from '../model/event';

export const useEventDetail = () => {
const { id } = useParams();
Expand All @@ -23,9 +25,17 @@ export const useEventDetail = () => {
};

export const useEventDeletion = () => {
return useMutation<ApiResponse<null>, Error, number>({
return useMutation<ApiResponse<null>, AxiosError<EventDeletionResponse>, number>({
mutationFn: async (eventId: number) => {
return await eventDeletion(eventId);
},
onError: error => {
const code = error.response?.data?.code;

if (code === 'EVENT4002') {
const message = error.response?.data?.message || '알 수 없는 오류가 발생했습니다.';
alert(message);
}
},
Comment on lines +32 to +39
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

특정 에러 코드 처리 로직을 검토해주세요.

에러 응답 구조에 대한 안전한 접근과 특정 에러 코드(EVENT4002) 처리가 잘 구현되었습니다. 다만 사용자 경험 측면에서 alert 사용을 토스트나 모달 등의 더 나은 UI 컴포넌트로 대체하는 것을 고려해보세요.

다음 스크립트로 다른 에러 코드들도 처리가 필요한지 확인해보세요:


🏁 Script executed:

#!/bin/bash
# 이벤트 관련 API에서 반환될 수 있는 다른 에러 코드들 검색
rg -A 3 -B 3 "EVENT[0-9]+" --type ts

Length of output: 1054


이벤트 에러 코드 처리 검증 및 UX 개선 제안

  • 코드베이스 전역에서 EVENT[0-9]+ 패턴을 검색한 결과, 대응 로직이 필요한 에러 코드는 현재 EVENT4002 하나뿐입니다.
  • 해당 코드(EVENT4002)는
    • src/entities/event/hook/useEventHook.ts (onError 콜백)
    • src/shared/ui/EventCard.tsx (삭제 불가 경고)
      두 곳에서 일관되게 처리되고 있음을 확인했습니다.
      → 추가 처리해야 할 다른 에러 코드는 없습니다.

다만, 사용자 경험 측면에서

  • alert 호출 대신 토스트(Toast)나 모달(Modal) 같은 비차단 UI 컴포넌트로 교체할 것을 권장드립니다.
🤖 Prompt for AI Agents
In src/entities/event/hook/useEventHook.ts around lines 32 to 39, the onError
callback currently uses alert to notify users of the EVENT4002 error. To improve
user experience, replace the alert call with a non-blocking UI component such as
a toast notification or modal dialog. Implement this by integrating the existing
toast or modal system used in the project, ensuring the error message is
displayed in a user-friendly, non-intrusive manner.

});
};
4 changes: 4 additions & 0 deletions src/entities/event/model/event.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export interface EventDeletionResponse {
code: string;
message: string;
}
17 changes: 13 additions & 4 deletions src/features/host/hook/useHostHook.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import { useMutation } from '@tanstack/react-query';
import { HostCreationRequest, UpdateHostChannelInfoRequest } from '../model/host';
import { HostCreationRequest, HostDeletionResponse, UpdateHostChannelInfoRequest } from '../model/host';
import { ApiResponse } from '../../../shared/types/api/apiResponse';
import { createHost, deleteHost, updateHostInfo } from '../api/host';
import { AxiosError } from 'axios';

export const useHostCreation = () => {
return useMutation<ApiResponse<null>, Error, HostCreationRequest>({
mutationFn: async (requestBody: HostCreationRequest) => {
return await createHost(requestBody);
},
onError: (error) => {
console.log("error", error.message);
onError: error => {
console.log('error', error.message);
},
});
};
Expand All @@ -22,9 +23,17 @@ export const useUpdateHostChannelInfo = (hostChannelId: number) => {
};

export const useHostDeletion = () => {
return useMutation<ApiResponse<null>, Error, number>({
return useMutation<ApiResponse<null>, AxiosError<HostDeletionResponse>, number>({
mutationFn: async (hostChannelId: number) => {
return await deleteHost(hostChannelId);
},
onError: error => {
const code = error.response?.data?.code;

if (code === 'HOST_CHANNEL4002' || code === 'HOST_CHANNEL4005') {
const message = error.response?.data?.message || '알 수 없는 오류가 발생했습니다.';
alert(message);
}
},
});
};
6 changes: 3 additions & 3 deletions src/features/host/hook/useHostInvitation.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { useMutation } from '@tanstack/react-query';
import { ApiResponse } from '../../../shared/types/api/apiResponse';
import { HostInvitationRequest } from '../model/hostInvitation';
import { HostInvitationRequest, HostInvitationResponse } from '../model/hostInvitation';
import { inviteMember } from '../api/hostInvitation';
import { AxiosError } from 'axios';

export const useHostInvitation = (hostChannelId: number) => {
return useMutation<ApiResponse<null>, Error, HostInvitationRequest>({
return useMutation<HostInvitationResponse, AxiosError<HostInvitationResponse>, HostInvitationRequest>({
mutationFn: async (requestBody: HostInvitationRequest) => {
return await inviteMember(hostChannelId, requestBody);
},
Expand Down
34 changes: 24 additions & 10 deletions src/features/host/hook/useInviteHostHook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,27 +13,41 @@ export const useInviteMembers = (hostChannelId: number) => {

const invitationPromises = emails.map(
email =>
new Promise((resolve, reject) => {
new Promise<void>((resolve, reject) => {
inviteMember(
{ email },
{
onSuccess: resolve,
onError: reject,
onSuccess: () => resolve(),
onError: error => reject(error),
}
);
})
);

Promise.all(invitationPromises)
.then(() => {
Promise.allSettled(invitationPromises).then(results => {
const failed = results.filter(r => r.status === 'rejected') as PromiseRejectedResult[];

if (failed.length > 0) {
console.log('🚨 first error:', failed[0].reason);
}

if (failed.length === 0) {
alert('초대가 전송되었습니다.');
queryClient.invalidateQueries({ queryKey: ['hostInfo', hostChannelId] });
onSuccess?.();
})
.catch(() => {
alert('초대 중 일부 실패했습니다.');
onError?.();
});
return;
}

const firstError = failed[0].reason;

const errorMessage =
firstError?.response?.data?.message || // AxiosError일 경우
firstError?.message || // 일반 에러 객체일 경우
'알 수 없는 오류가 발생했습니다.';

alert(errorMessage);
onError?.();
});
};

return { inviteMembers };
Expand Down
5 changes: 5 additions & 0 deletions src/features/host/model/host.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,8 @@ export interface UpdateHostChannelInfoRequest {
hostEmail: string;
channelDescription: string;
}

export interface HostDeletionResponse {
code: string;
message: string;
}
6 changes: 6 additions & 0 deletions src/features/host/model/hostInvitation.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
export interface HostInvitationRequest {
email: string;
}

export interface HostInvitationResponse {
code: string;
message: string;
result?: string;
}
16 changes: 11 additions & 5 deletions src/features/ticket/hooks/useOrderHook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,13 +50,19 @@ export const useOrderTicket = () => {
// qr 스캔
export const useTicketQrCodeValidate = () => {
return useMutation({
mutationFn: ({ orderId, sig }: { orderId: number; sig: string }) =>
ticketQrCode(orderId, sig),
mutationFn: ({ orderId, sig }: { orderId: number; sig: string }) => ticketQrCode(orderId, sig),
onSuccess: () => {
alert('체크인 성공!');
},
onError: () => {
alert('체크인 실패했습니다. 다시 시도해주세요.');
onError: (error: { code?: string }) => {
const errorCode = error?.code;
if (errorCode === 'QR_CODE4001') {
alert('이미 사용된 QR 코드입니다.');
} else if (errorCode === 'QR_CODE4002') {
alert('잘못된 QR 코드 형식입니다.');
} else {
alert('QR 코드 검증 중 오류가 발생했습니다.');
}
},
});
};
};
136 changes: 66 additions & 70 deletions src/features/ticket/ui/QrScanner.tsx
Original file line number Diff line number Diff line change
@@ -1,83 +1,79 @@
import { useEffect, useRef, useState } from "react";
import QrScanner from "qr-scanner";
import { useTicketQrCodeValidate } from "../hooks/useOrderHook";
import Button from "../../../../design-system/ui/Button";
import { useEffect, useRef, useState } from 'react';
import QrScanner from 'qr-scanner';
import { useTicketQrCodeValidate } from '../hooks/useOrderHook';
import Button from '../../../../design-system/ui/Button';

const QrScannerComponent = () => {
const videoRef = useRef<HTMLVideoElement>(null);
const [isScanning, setIsScanning] = useState(false);
const qrScannerRef = useRef<QrScanner | null>(null);
const videoRef = useRef<HTMLVideoElement>(null);
const [isScanning, setIsScanning] = useState(false);
const qrScannerRef = useRef<QrScanner | null>(null);

const { mutate: validateQr } = useTicketQrCodeValidate();
const { mutate: validateQr } = useTicketQrCodeValidate();

useEffect(() => {
if (!videoRef.current) return;
useEffect(() => {
if (!videoRef.current) return;

const scanner = new QrScanner(
videoRef.current,
(decoded) => {
const data = decoded.data;
setIsScanning(false);
scanner.stop();
checkInApiCall(data);
},
{
onDecodeError: (err) => {
console.warn("QR decode error:", err);
},
highlightScanRegion: true,
maxScansPerSecond: 5,
}
);

qrScannerRef.current = scanner;
const scanner = new QrScanner(
videoRef.current,
decoded => {
const data = decoded.data;
setIsScanning(false);
scanner.stop();
checkInApiCall(data);
},
{
onDecodeError: err => {
console.warn('QR decode error:', err);
},
highlightScanRegion: true,
maxScansPerSecond: 5,
}
);

return () => {
scanner.destroy();
qrScannerRef.current = null;
};
}, []);
qrScannerRef.current = scanner;

const handleStartScan = async () => {
try {
await navigator.mediaDevices.getUserMedia({ video: true });
qrScannerRef.current?.start();
setIsScanning(true);
} catch (e) {
alert(
"카메라 접근이 차단되어 있어 스캔할 수 없습니다.\n시스템 설정 또는 브라우저 설정에서 권한을 허용해 주세요."
);
}
return () => {
scanner.destroy();
qrScannerRef.current = null;
};
}, []);

const checkInApiCall = async (qrData: string) => {
try {
const params = new URLSearchParams(qrData.replace(/-/g, '='));
const orderIdStr = params.get('orderId');
const sig = params.get('sig');
const orderId = orderIdStr ? parseInt(orderIdStr, 10) : NaN;
const handleStartScan = async () => {
try {
await navigator.mediaDevices.getUserMedia({ video: true });
qrScannerRef.current?.start();
setIsScanning(true);
} catch {
alert(
'카메라 접근이 차단되어 있어 스캔할 수 없습니다.\n시스템 설정 또는 브라우저 설정에서 권한을 허용해 주세요.'
);
}
};

if (!isNaN(orderId) && sig) {
validateQr({ orderId, sig });
} else {
alert("QR 코드 데이터 형식이 올바르지 않습니다.");
}
} catch {
alert("QR 코드 데이터를 파싱할 수 없습니다.");
}
};
const checkInApiCall = async (qrData: string) => {
try {
const params = new URLSearchParams(qrData.replace(/-/g, '='));
const orderIdStr = params.get('orderId');
const sig = params.get('sig');
const orderId = orderIdStr ? parseInt(orderIdStr, 10) : NaN;

return (
<div className="p-4">
<video
ref={videoRef}
className="border rounded w-full max-w-md"
style={{ aspectRatio: "3 / 4" }}
/>
{!isScanning && (
<Button label="스캔하기" onClick={handleStartScan} className="w-full h-12 rounded-full mt-10 px-4 py-2" />
)}
</div>
);
if (!isNaN(orderId) && sig) {
validateQr({ orderId, sig });
} else {
alert('QR 코드 데이터 형식이 올바르지 않습니다.');
}
} catch {
alert('QR 코드 데이터를 파싱할 수 없습니다.');
}
};

return (
<div className="p-4">
<video ref={videoRef} className="border rounded w-full max-w-md" style={{ aspectRatio: '3 / 4' }} />
{!isScanning && (
<Button label="스캔하기" onClick={handleStartScan} className="w-full h-12 rounded-full mt-10 px-4 py-2" />
)}
</div>
);
};
export default QrScannerComponent;
2 changes: 1 addition & 1 deletion src/pages/menu/ui/MyTicketPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@ import completedImg from '../../../../public/assets/menu/Completed.svg';
import pendingImg from '../../../../public/assets/menu/Pending.svg';
import ticketImg from '../../../../public/assets/menu/Ticket.svg';
import { useCancelTicket, useTicketOrders } from '../../../features/ticket/hooks/useOrderHook';
import { OrderTicketResponse } from '../../../features/ticket/model/Order';
import EmailDeleteModal from '../../../widgets/dashboard/ui/email/EmailDeleteModal';
import TertiaryButton from '../../../../design-system/ui/buttons/TertiaryButton';
import useAuthStore from '../../../app/provider/authStore';
import TextModal from '../../../shared/ui/TextModal';
import { OrderTicketResponse } from '../../../features/ticket/model/Order';

const MyTicketPage = () => {
const [isModalOpen, setIsModalOpen] = useState(false);
Expand Down