feat: redesign auction engine with redis sot

This commit is contained in:
dahyeon committed 2026-06-23 03:16:04 -07:00
1 parent 737702d78c
commit e8bb20d988
75 files changed
+12737 -542

No files matched your search

+46 -2
View File
@@ -221,9 +221,21 @@ export function useAuctionHistory(
export function useUndoAuction(communityId = DEFAULT_COMMUNITY_ID) {
return useMutation({
mutationFn: ({
auctionActionRequestId,
clientObservedAuctionLifecycleId,
clientObservedCurrentAuctionPlayerOrderIndex,
clientObservedCurrentBidRoundPlayerUserId,
clientObservedPhase,
clientObservedRevision,
matchId,
sequence,
}: {
auctionActionRequestId?: string;
clientObservedAuctionLifecycleId?: string;
clientObservedCurrentAuctionPlayerOrderIndex?: number;
clientObservedCurrentBidRoundPlayerUserId?: string;
clientObservedPhase?: string;
clientObservedRevision?: number;
matchId: string;
sequence: number;
}) =>
@@ -231,7 +243,15 @@ export function useUndoAuction(communityId = DEFAULT_COMMUNITY_ID) {
`/communities/${communityId}/matches/${matchId}/auction/undo`,
{
method: 'POST',
body: JSON.stringify({ sequence }),
body: JSON.stringify({
auctionActionRequestId,
clientObservedAuctionLifecycleId,
clientObservedCurrentAuctionPlayerOrderIndex,
clientObservedCurrentBidRoundPlayerUserId,
clientObservedPhase,
clientObservedRevision,
sequence,
}),
},
),
});
@@ -239,9 +259,33 @@ export function useUndoAuction(communityId = DEFAULT_COMMUNITY_ID) {
export function useResetAuction(communityId = DEFAULT_COMMUNITY_ID) {
return useMutation({
mutationFn: ({ matchId }: { matchId: string }) =>
mutationFn: ({
auctionActionRequestId,
clientObservedAuctionLifecycleId,
clientObservedCurrentAuctionPlayerOrderIndex,
clientObservedCurrentBidRoundPlayerUserId,
clientObservedPhase,
clientObservedRevision,
matchId,
}: {
auctionActionRequestId?: string;
clientObservedAuctionLifecycleId?: string;
clientObservedCurrentAuctionPlayerOrderIndex?: number;
clientObservedCurrentBidRoundPlayerUserId?: string;
clientObservedPhase?: string;
clientObservedRevision?: number;
matchId: string;
}) =>
apiFetch<void>(`/communities/${communityId}/matches/${matchId}/auction`, {
method: 'DELETE',
body: JSON.stringify({
auctionActionRequestId,
clientObservedAuctionLifecycleId,
clientObservedCurrentAuctionPlayerOrderIndex,
clientObservedCurrentBidRoundPlayerUserId,
clientObservedPhase,
clientObservedRevision,
}),
}),
});
}
+71 -20
View File
@@ -119,6 +119,8 @@ export interface AuctionTeamView {
export interface AuctionStateView {
matchId: string;
phase: ApiAuction["phase"];
matchSideEffectRevision?: number;
matchSideEffectStatus?: ApiAuction["matchSideEffectStatus"];
teams: AuctionTeamView[];
currentPlayer: AuctionPlayerView | null;
currentPlayerIndex: number;
@@ -273,7 +275,7 @@ function createFallbackParticipant(userId: string): ParticipantView {
}
function mapAuctionTeamToView(
team: ApiAuctionTeam,
team: NormalizedApiAuctionTeam,
playerLookup: Map<string, AuctionPlayerView>,
participantLookup: Map<string, ParticipantView>,
): AuctionTeamView {
@@ -489,12 +491,33 @@ export function mapApiAuctionToAuctionState(
.map(mapMatchParticipantToView)
.map((participant) => [participant.userId, participant]),
);
const auctionOrder = auction.order.map(mapAuctionPlayerToView);
const passedQueue = (auction.passedQueue ?? []).map(mapAuctionPlayerToView);
const rawAuctionOrder = auction.auctionPlayerOrder ?? auction.order ?? [];
const rawPassedQueue =
auction.passedAuctionPlayerQueue ?? auction.passedQueue ?? [];
const rawAuctionTeams = auction.auctionTeams ?? auction.teams ?? [];
const currentAuctionPlayerOrderIndex =
auction.currentAuctionPlayerOrderIndex ?? auction.currentIndex ?? 0;
const currentBid =
auction.currentHighestBidPointAmount ?? auction.currentBid ?? 0;
const rawCurrentBidderTeamIndex =
auction.currentHighestBidderTeamIndex ?? auction.currentBidderTeamIndex;
const currentBidderTeamIndex =
rawCurrentBidderTeamIndex !== undefined && rawCurrentBidderTeamIndex > 0
? rawCurrentBidderTeamIndex
: undefined;
const maximumBidRoundDurationSeconds =
auction.maximumBidRoundDurationSeconds ?? auction.maxTimerSeconds ?? 30;
const bidRoundExtensionSeconds =
auction.bidRoundExtensionSeconds ?? auction.bidExtensionSeconds ?? 5;
const currentBidRoundDeadlineTimestampMS =
auction.currentBidRoundDeadlineTimestampMS ??
(auction.currentDeadline ? Date.parse(auction.currentDeadline) : undefined);
const auctionOrder = rawAuctionOrder.map(mapAuctionPlayerToView);
const passedQueue = rawPassedQueue.map(mapAuctionPlayerToView);
const auctionPlayerLookup = new Map(
auctionOrder.map((player) => [player.userId, player]),
);
const teams = [...auction.teams].sort(
const teams = rawAuctionTeams.map(normalizeApiAuctionTeam).sort(
(left, right) => left.teamIndex - right.teamIndex,
);
@@ -503,15 +526,15 @@ export function mapApiAuctionToAuctionState(
auction.phase === "complete"
? null
: (auctionPlayerLookup.get(
auction.order[auction.currentIndex]?.userId ?? "",
rawAuctionOrder[currentAuctionPlayerOrderIndex]?.userId ?? "",
) ?? null);
const currentPlayerIndex =
auction.phase === "complete" ? totalPlayers : auction.currentIndex;
const timer = auction.currentDeadline
auction.phase === "complete" ? totalPlayers : currentAuctionPlayerOrderIndex;
const timer = currentBidRoundDeadlineTimestampMS
? Math.max(
0,
Math.ceil(
(new Date(auction.currentDeadline).getTime() - now.getTime()) / 1000,
(currentBidRoundDeadlineTimestampMS - now.getTime()) / 1000,
),
)
: 0;
@@ -519,6 +542,8 @@ export function mapApiAuctionToAuctionState(
return {
matchId: auction.matchId,
phase: auction.phase,
matchSideEffectRevision: auction.matchSideEffectRevision,
matchSideEffectStatus: auction.matchSideEffectStatus,
teams: teams.map((team) =>
mapAuctionTeamToView(team, auctionPlayerLookup, participantLookup),
),
@@ -527,21 +552,47 @@ export function mapApiAuctionToAuctionState(
totalPlayers,
auctionOrder,
passedQueue,
auctionRound: auction.auctionRound ?? 1,
bids: auction.bids.map((bid) => ({
teamIndex: bid.teamIndex,
amount: bid.amount,
timestamp: bid.timestamp,
})),
currentBid: auction.currentBid,
currentBidder: auction.currentBidderTeamIndex
auctionRound: auction.currentAuctionRound ?? auction.auctionRound ?? 1,
bids: normalizeApiAuctionBids(auction),
currentBid,
currentBidder: currentBidderTeamIndex !== undefined
? {
teamIndex: auction.currentBidderTeamIndex,
teamIndex: currentBidderTeamIndex,
}
: null,
timer,
maxTimer: auction.maxTimerSeconds,
bidExtensionSeconds: auction.bidExtensionSeconds ?? 5,
deadline: auction.currentDeadline,
maxTimer: maximumBidRoundDurationSeconds,
bidExtensionSeconds: bidRoundExtensionSeconds,
deadline: currentBidRoundDeadlineTimestampMS
? new Date(currentBidRoundDeadlineTimestampMS).toISOString()
: undefined,
};
}
type NormalizedApiAuctionTeam = ApiAuctionTeam & { points: number };
function normalizeApiAuctionTeam(team: ApiAuctionTeam): NormalizedApiAuctionTeam {
return {
...team,
points: team.points ?? team.remainingBidPointAmount ?? 0,
members: (team.members ?? []).map((member) => ({
...member,
cost: member.cost ?? member.memberAcquisitionBidPointAmount ?? 0,
})),
};
}
function normalizeApiAuctionBids(auction: ApiAuction) {
if (auction.auctionBidHistory) {
return auction.auctionBidHistory.map((bid) => ({
amount: bid.bidPointAmount,
teamIndex: bid.bidderTeamIndex,
timestamp: new Date(bid.bidPlacedAtTimestampMS).toISOString(),
}));
}
return (auction.bids ?? []).map((bid) => ({
teamIndex: bid.teamIndex,
amount: bid.amount,
timestamp: bid.timestamp,
}));
}
+46 -14
View File
@@ -278,12 +278,14 @@ export interface ApiAuctionTeamMember {
userId: string;
assignedPosition: Position;
cost: number;
memberAcquisitionBidPointAmount?: number;
}
export interface ApiAuctionTeam {
teamIndex: number;
captainUserId: string;
points: number;
points?: number;
remainingBidPointAmount?: number;
members: ApiAuctionTeamMember[];
}
@@ -306,20 +308,48 @@ export interface ApiAuction {
_id: string;
matchId: string;
phase: AuctionPhase;
teams: ApiAuctionTeam[];
order: ApiAuctionPlayerSnapshot[];
passedQueue: ApiAuctionPlayerSnapshot[];
auctionRound: number;
currentIndex: number;
bids: ApiAuctionBid[];
currentBid: number;
teams?: ApiAuctionTeam[];
auctionTeams: ApiAuctionTeam[];
order?: ApiAuctionPlayerSnapshot[];
auctionPlayerOrder: ApiAuctionPlayerSnapshot[];
passedQueue?: ApiAuctionPlayerSnapshot[];
passedAuctionPlayerQueue: ApiAuctionPlayerSnapshot[];
auctionRound?: number;
currentAuctionRound: number;
currentIndex?: number;
currentAuctionPlayerOrderIndex: number;
bids?: ApiAuctionBid[];
auctionBidHistory?: Array<{
bidderTeamIndex: number;
bidPointAmount: number;
bidderUserId: string;
bidPlacedAtTimestampMS: number;
}>;
currentBid?: number;
currentHighestBidPointAmount: number;
currentBidderTeamIndex?: number;
maxTimerSeconds: number;
bidExtensionSeconds: number;
currentHighestBidderTeamIndex?: number;
maxTimerSeconds?: number;
maximumBidRoundDurationSeconds: number;
bidExtensionSeconds?: number;
bidRoundExtensionSeconds: number;
currentDeadline?: string;
initialPoints: number;
topTierThreshold: AuctionTopTierThreshold;
manualTopTierUserIds: string[];
currentBidRoundDeadlineTimestampMS?: number;
currentBidRoundPlayerUserId?: string;
currentServerTimestampMS?: number;
initialPoints?: number;
initialTeamBidPointAmount: number;
topTierThreshold?: AuctionTopTierThreshold;
topTierAuctionPriorityThreshold: AuctionTopTierThreshold;
manualTopTierUserIds?: string[];
manualTopTierAuctionPriorityUserIds: string[];
revision?: number;
auctionLifecycleId?: string;
matchSideEffectRevision?: number;
matchSideEffectStatus?: 'none' | 'pending' | 'processing' | 'completed' | 'failed';
canPlaceBidInCurrentBidRound?: boolean;
isAuctionStateTransitionInProgress?: boolean;
shouldForceAuctionStateResync?: boolean;
chatMessages?: ApiAuctionChatMessage[];
startedAt?: string;
completedAt?: string;
@@ -336,7 +366,9 @@ export interface ApiAuctionHistoryEntry {
| 'sold'
| 'passed'
| 'next'
| 'complete';
| 'complete'
| 'undo'
| 'reset';
actionLabel: string;
takenAt: string;
}
+439 -22
View File
@@ -12,9 +12,11 @@ type ConnectionStatus =
| 'error';
interface BidPayload {
teamIndex: number;
amount: number;
bidderUserId?: string;
bidderTeamIndex: number;
bidPointAmount: number;
bidRequestId?: string;
clientObservedAuctionLifecycleId?: string;
clientObservedCurrentBidRoundPlayerUserId?: string;
}
interface ChatMessagePayload {
@@ -22,6 +24,19 @@ interface ChatMessagePayload {
message: string;
}
interface AuctionActionPayload {
auctionActionRequestId?: string;
clientObservedAuctionLifecycleId?: string;
clientObservedCurrentAuctionPlayerOrderIndex?: number;
clientObservedCurrentBidRoundPlayerUserId?: string;
clientObservedPhase?: string;
clientObservedRevision?: number;
}
interface SoldPayload extends AuctionActionPayload {
assignedPosition?: Position;
}
interface ChatHistoryPayload {
messages?: ApiAuctionChatMessage[];
}
@@ -30,9 +45,29 @@ interface ResetPayload {
matchId?: string;
}
interface TickPayload {
deadline?: string;
serverTime?: string;
type MatchSideEffectStatus = NonNullable<ApiAuction['matchSideEffectStatus']>;
interface MatchSideEffectPayload {
auctionLifecycleId?: string;
currentServerTimestampMS?: number;
matchSideEffectRevision?: number;
matchSideEffectStatus?: MatchSideEffectStatus;
}
interface BidDeltaPayload {
auctionBidHistoryEntry?: {
bidderTeamIndex?: number;
bidPointAmount?: number;
bidderUserId?: string;
bidPlacedAtTimestampMS?: number;
};
auctionLifecycleId?: string;
bidRequestId?: string;
currentBidRoundDeadlineTimestampMS?: number;
currentHighestBidderTeamIndex?: number;
currentHighestBidPointAmount?: number;
currentServerTimestampMS?: number;
revision?: number;
}
const MAX_CHAT_MESSAGES = 200;
@@ -54,8 +89,20 @@ function mergeChatMessages(
export function useAuctionSocket(matchId: string | undefined) {
const authUserId = useAuthUserId();
const socketRef = useRef<Socket | null>(null);
const pendingBidTimeoutsRef = useRef<
Record<string, ReturnType<typeof setTimeout>>
>({});
const pendingActionTimeoutsRef = useRef<
Record<string, ReturnType<typeof setTimeout>>
>({});
const [auction, setAuction] = useState<ApiAuction | null>(null);
const [chatMessages, setChatMessages] = useState<ApiAuctionChatMessage[]>([]);
const [pendingBidRequests, setPendingBidRequests] = useState<
Record<string, { amount: number; teamIndex: number }>
>({});
const [pendingActionRequests, setPendingActionRequests] = useState<
Record<string, { action: string }>
>({});
const [resetAt, setResetAt] = useState<number | null>(null);
const [connectionStatus, setConnectionStatus] =
useState<ConnectionStatus>('idle');
@@ -99,23 +146,20 @@ export function useAuctionSocket(matchId: string | undefined) {
});
socket.on('state', (nextAuction: ApiAuction) => {
setAuction(nextAuction);
setAuction((current) =>
shouldApplyIncomingAuctionState(current, nextAuction)
? nextAuction
: current,
);
if (typeof nextAuction.currentServerTimestampMS === 'number') {
setServerTimeOffsetMs(nextAuction.currentServerTimestampMS - Date.now());
}
if (nextAuction.chatMessages) {
setChatMessages(mergeChatMessages([], nextAuction.chatMessages));
}
setError(null);
});
socket.on('tick', (payload: TickPayload) => {
const serverTime =
typeof payload?.serverTime === 'string'
? Date.parse(payload.serverTime)
: NaN;
if (Number.isFinite(serverTime)) {
setServerTimeOffsetMs(serverTime - Date.now());
}
});
socket.on('chat-history', (payload: ChatHistoryPayload) => {
setChatMessages(mergeChatMessages([], payload.messages ?? []));
});
@@ -124,6 +168,52 @@ export function useAuctionSocket(matchId: string | undefined) {
setChatMessages((current) => mergeChatMessages(current, [message]));
});
socket.on('bid', (payload: BidDeltaPayload) => {
if (typeof payload?.currentServerTimestampMS === 'number') {
setServerTimeOffsetMs(payload.currentServerTimestampMS - Date.now());
}
if (payload?.bidRequestId) {
clearPendingBidRequest(payload.bidRequestId);
}
setAuction((current) => applyBidDelta(current, payload));
});
socket.on('match-side-effect', (payload: MatchSideEffectPayload) => {
if (typeof payload?.currentServerTimestampMS === 'number') {
setServerTimeOffsetMs(payload.currentServerTimestampMS - Date.now());
}
if (
!payload?.matchSideEffectStatus ||
typeof payload.matchSideEffectRevision !== 'number'
) {
return;
}
const matchSideEffectRevision = payload.matchSideEffectRevision;
const matchSideEffectStatus = payload.matchSideEffectStatus;
setAuction((current) => {
if (!current) return current;
if (
payload.auctionLifecycleId &&
current.auctionLifecycleId &&
payload.auctionLifecycleId !== current.auctionLifecycleId
) {
return current;
}
if (
matchSideEffectRevision <=
(current.matchSideEffectRevision ?? -1)
) {
return current;
}
return {
...current,
matchSideEffectRevision,
matchSideEffectStatus,
};
});
});
socket.on('reset', (payload: ResetPayload) => {
if (payload.matchId && payload.matchId !== matchId) return;
setAuction(null);
@@ -144,11 +234,43 @@ export function useAuctionSocket(matchId: string | undefined) {
socket?.removeAllListeners();
socket?.disconnect();
socketRef.current = null;
Object.values(pendingBidTimeoutsRef.current).forEach((timeoutId) =>
clearTimeout(timeoutId),
);
Object.values(pendingActionTimeoutsRef.current).forEach((timeoutId) =>
clearTimeout(timeoutId),
);
pendingBidTimeoutsRef.current = {};
pendingActionTimeoutsRef.current = {};
setPendingBidRequests({});
setPendingActionRequests({});
setConnectionStatus('idle');
setServerTimeOffsetMs(0);
};
}, [authUserId, matchId]);
function clearPendingBidRequest(bidRequestId: string) {
const timeoutId = pendingBidTimeoutsRef.current[bidRequestId];
if (timeoutId) clearTimeout(timeoutId);
delete pendingBidTimeoutsRef.current[bidRequestId];
setPendingBidRequests((current) => {
const next = { ...current };
delete next[bidRequestId];
return next;
});
}
function clearPendingActionRequest(auctionActionRequestId: string) {
const timeoutId = pendingActionTimeoutsRef.current[auctionActionRequestId];
if (timeoutId) clearTimeout(timeoutId);
delete pendingActionTimeoutsRef.current[auctionActionRequestId];
setPendingActionRequests((current) => {
const next = { ...current };
delete next[auctionActionRequestId];
return next;
});
}
function emit(eventName: string, payload?: unknown) {
const socket = socketRef.current;
if (!socket || !socket.connected) {
@@ -166,7 +288,74 @@ export function useAuctionSocket(matchId: string | undefined) {
socket.emit(eventName, payload);
}
const visibleAuction = auction?.matchId === matchId ? auction : null;
function buildAuctionActionPayload(): AuctionActionPayload {
return {
auctionActionRequestId: createClientRequestId(),
clientObservedAuctionLifecycleId: auction?.auctionLifecycleId,
clientObservedCurrentAuctionPlayerOrderIndex:
auction?.currentAuctionPlayerOrderIndex,
clientObservedCurrentBidRoundPlayerUserId:
auction?.currentBidRoundPlayerUserId,
clientObservedPhase: auction?.phase,
clientObservedRevision: auction?.revision,
};
}
function emitAuctionAction(eventName: string, payload: AuctionActionPayload) {
const socket = socketRef.current;
if (!socket || !socket.connected) {
setError('소켓이 아직 연결되지 않았습니다.');
return;
}
const auctionActionRequestId =
payload.auctionActionRequestId ?? createClientRequestId();
const actionPayload = {
...payload,
auctionActionRequestId,
};
setError(null);
setPendingActionRequests((current) => ({
...current,
[auctionActionRequestId]: { action: eventName },
}));
pendingActionTimeoutsRef.current[auctionActionRequestId] = setTimeout(() => {
clearPendingActionRequest(auctionActionRequestId);
setError('경매 진행 응답이 지연되어 최신 상태를 다시 확인해주세요.');
}, 10_000);
socket.emit(
eventName,
actionPayload,
(ack?: {
auctionActionRequestId?: string;
code?: string;
rejected?: boolean;
state?: ApiAuction;
}) => {
clearPendingActionRequest(
ack?.auctionActionRequestId ?? auctionActionRequestId,
);
if (ack?.rejected) {
setError(ack.code ?? '경매 진행 상태가 반영되지 않았습니다.');
return;
}
const ackState = ack?.state;
if (ackState) {
setAuction((current) =>
shouldApplyIncomingAuctionState(current, ackState)
? ackState
: current,
);
}
},
);
}
const currentAuction = auction;
const visibleAuction =
currentAuction && currentAuction.matchId === matchId
? applyPendingBidOverlay(currentAuction, pendingBidRequests)
: null;
const visibleConnectionStatus: ConnectionStatus = matchId
? connectionStatus
: 'idle';
@@ -174,24 +363,252 @@ export function useAuctionSocket(matchId: string | undefined) {
return {
auction: visibleAuction,
chatMessages: visibleAuction ? chatMessages : [],
isAuctionActionPending: Object.keys(pendingActionRequests).length > 0,
isBidPending: Object.keys(pendingBidRequests).length > 0,
pendingActionRequests,
pendingBidRequests,
resetAt,
connectionStatus: visibleConnectionStatus,
error,
serverTimeOffsetMs: matchId ? serverTimeOffsetMs : 0,
placeBid(payload: BidPayload) {
emit('bid', payload);
const socket = socketRef.current;
if (!socket || !socket.connected) {
setError('소켓이 아직 연결되지 않았습니다.');
return;
}
const bidRequestId = payload.bidRequestId ?? createClientRequestId();
const bidPayload: BidPayload = {
...payload,
bidRequestId,
clientObservedAuctionLifecycleId:
payload.clientObservedAuctionLifecycleId ??
auction?.auctionLifecycleId,
clientObservedCurrentBidRoundPlayerUserId:
payload.clientObservedCurrentBidRoundPlayerUserId ??
auction?.currentBidRoundPlayerUserId,
};
setError(null);
setPendingBidRequests((current) => ({
...current,
[bidRequestId]: {
amount: bidPayload.bidPointAmount,
teamIndex: bidPayload.bidderTeamIndex,
},
}));
pendingBidTimeoutsRef.current[bidRequestId] = setTimeout(() => {
clearPendingBidRequest(bidRequestId);
setError('입찰 응답이 지연되어 최신 상태를 다시 확인해주세요.');
}, 10_000);
socket.emit(
'bid',
bidPayload,
(ack?: {
code?: string;
rejected?: boolean;
state?: ApiAuction;
}) => {
clearPendingBidRequest(bidRequestId);
if (ack?.rejected) {
setError(ack.code ?? '입찰이 반영되지 않았습니다.');
return;
}
const ackState = ack?.state;
if (ackState) {
setAuction((current) =>
shouldApplyIncomingAuctionState(current, ackState)
? ackState
: current,
);
}
},
);
},
openBidding() {
emit('open-bidding', {});
emitAuctionAction('open-bidding', buildAuctionActionPayload());
},
markSold(assignedPosition?: Position) {
emit('sold', assignedPosition ? { assignedPosition } : {});
const payload: SoldPayload = {
...buildAuctionActionPayload(),
assignedPosition,
};
emitAuctionAction('sold', payload);
},
markPassed() {
emitAuctionAction('passed', buildAuctionActionPayload());
},
next() {
emit('next', {});
emitAuctionAction('next', buildAuctionActionPayload());
},
sendChatMessage(payload: ChatMessagePayload) {
emit('chat-message', payload);
},
};
}
function createClientRequestId(): string {
if (typeof crypto !== 'undefined' && 'randomUUID' in crypto) {
return crypto.randomUUID();
}
return `${Date.now()}-${Math.random().toString(16).slice(2)}`;
}
function shouldApplyIncomingAuctionState(
current: ApiAuction | null,
incoming: ApiAuction,
): boolean {
if (!current) return true;
if (incoming.shouldForceAuctionStateResync) return true;
if (
current.auctionLifecycleId &&
incoming.auctionLifecycleId &&
current.auctionLifecycleId !== incoming.auctionLifecycleId
) {
return true;
}
if (
typeof current.revision === 'number' &&
typeof incoming.revision === 'number' &&
incoming.revision <= current.revision
) {
return false;
}
return true;
}
function applyBidDelta(
current: ApiAuction | null,
payload: BidDeltaPayload,
): ApiAuction | null {
if (!current) return current;
if (
payload.auctionLifecycleId &&
current.auctionLifecycleId &&
payload.auctionLifecycleId !== current.auctionLifecycleId
) {
return current;
}
if (
typeof current.revision === 'number' &&
typeof payload.revision === 'number' &&
payload.revision <= current.revision
) {
return current;
}
const bidPointAmount = Number(payload.currentHighestBidPointAmount);
const bidderTeamIndex = Number(payload.currentHighestBidderTeamIndex);
if (!Number.isFinite(bidPointAmount) || !Number.isFinite(bidderTeamIndex)) {
return current;
}
const bidHistoryEntry = normalizeBidHistoryEntry(payload.auctionBidHistoryEntry);
const currentBidRoundDeadlineTimestampMS =
typeof payload.currentBidRoundDeadlineTimestampMS === 'number'
? payload.currentBidRoundDeadlineTimestampMS
: current.currentBidRoundDeadlineTimestampMS;
return {
...current,
auctionBidHistory: appendUniqueAuctionBidHistoryEntry(
current.auctionBidHistory ?? [],
bidHistoryEntry,
),
bids: bidHistoryEntry
? appendUniqueLegacyBidEntry(current.bids ?? [], bidHistoryEntry)
: current.bids,
currentBid: bidPointAmount,
currentBidderTeamIndex: bidderTeamIndex,
currentDeadline: currentBidRoundDeadlineTimestampMS
? new Date(currentBidRoundDeadlineTimestampMS).toISOString()
: current.currentDeadline,
currentHighestBidPointAmount: bidPointAmount,
currentHighestBidderTeamIndex: bidderTeamIndex,
currentBidRoundDeadlineTimestampMS,
currentServerTimestampMS:
payload.currentServerTimestampMS ?? current.currentServerTimestampMS,
revision: payload.revision ?? current.revision,
};
}
function normalizeBidHistoryEntry(
entry: BidDeltaPayload['auctionBidHistoryEntry'],
): NonNullable<ApiAuction['auctionBidHistory']>[number] | null {
if (!entry) return null;
const bidderTeamIndex = Number(entry.bidderTeamIndex);
const bidPointAmount = Number(entry.bidPointAmount);
const bidPlacedAtTimestampMS = Number(entry.bidPlacedAtTimestampMS);
if (!Number.isFinite(bidderTeamIndex) || !Number.isFinite(bidPointAmount)) {
return null;
}
return {
bidderTeamIndex,
bidPointAmount,
bidderUserId: entry.bidderUserId ?? '',
bidPlacedAtTimestampMS: Number.isFinite(bidPlacedAtTimestampMS)
? bidPlacedAtTimestampMS
: Date.now(),
};
}
function appendUniqueAuctionBidHistoryEntry(
current: NonNullable<ApiAuction['auctionBidHistory']>,
entry: NonNullable<ApiAuction['auctionBidHistory']>[number] | null,
) {
if (!entry) return current;
if (
current.some(
(existing) =>
existing.bidderTeamIndex === entry.bidderTeamIndex &&
existing.bidPointAmount === entry.bidPointAmount &&
existing.bidPlacedAtTimestampMS === entry.bidPlacedAtTimestampMS,
)
) {
return current;
}
return [...current, entry];
}
function appendUniqueLegacyBidEntry(
current: ApiAuction['bids'],
entry: NonNullable<ApiAuction['auctionBidHistory']>[number],
) {
const currentBids = current ?? [];
const legacyBid = {
amount: entry.bidPointAmount,
bidderUserId: entry.bidderUserId,
teamIndex: entry.bidderTeamIndex,
timestamp: new Date(entry.bidPlacedAtTimestampMS).toISOString(),
};
if (
currentBids.some(
(existing) =>
existing.teamIndex === legacyBid.teamIndex &&
existing.amount === legacyBid.amount &&
existing.timestamp === legacyBid.timestamp,
)
) {
return currentBids;
}
return [...currentBids, legacyBid];
}
function applyPendingBidOverlay(
auction: ApiAuction,
pendingBidRequests: Record<string, { amount: number; teamIndex: number }>,
): ApiAuction {
const pendingBids = Object.values(pendingBidRequests);
const latestPendingBid = pendingBids[pendingBids.length - 1];
if (!latestPendingBid || latestPendingBid.amount <= (auction.currentBid ?? 0)) {
return auction;
}
return {
...auction,
currentBid: latestPendingBid.amount,
currentBidderTeamIndex: latestPendingBid.teamIndex,
currentHighestBidPointAmount: latestPendingBid.amount,
currentHighestBidderTeamIndex: latestPendingBid.teamIndex,
};
}
+98 -8
View File
@@ -64,6 +64,13 @@ function formatPoints(value: number) {
return value.toLocaleString();
}
function createClientRequestId(): string {
if (typeof crypto !== 'undefined' && 'randomUUID' in crypto) {
return crypto.randomUUID();
}
return `${Date.now()}-${Math.random().toString(16).slice(2)}`;
}
function relativeTime(dateLike: string) {
const seconds = Math.max(
0,
@@ -114,12 +121,27 @@ function getAuctionUpdatedAt(auction: ApiAuction | null | undefined) {
return Date.parse(auction.updatedAt ?? auction.createdAt ?? '') || 0;
}
function getAuctionRevision(auction: ApiAuction | null | undefined) {
return typeof auction?.revision === 'number' ? auction.revision : null;
}
function pickLatestAuction(
socketAuction: ApiAuction | null,
queryAuction: ApiAuction | undefined,
) {
if (!socketAuction) return queryAuction ?? null;
if (!queryAuction) return socketAuction;
if (
socketAuction.auctionLifecycleId &&
queryAuction.auctionLifecycleId &&
socketAuction.auctionLifecycleId === queryAuction.auctionLifecycleId
) {
const socketRevision = getAuctionRevision(socketAuction);
const queryRevision = getAuctionRevision(queryAuction);
if (socketRevision !== null && queryRevision !== null) {
return queryRevision > socketRevision ? queryAuction : socketAuction;
}
}
return getAuctionUpdatedAt(queryAuction) > getAuctionUpdatedAt(socketAuction)
? queryAuction
: socketAuction;
@@ -574,10 +596,12 @@ function PlayerSpotlight({
function BidControls({
state,
captainRole,
isBidPending,
onBid,
}: {
state: AuctionStateView;
captainRole: CaptainRole | null;
isBidPending: boolean;
onBid: (teamIndex: number, amount: number) => void;
}) {
const [bidAmount, setBidAmount] = useState(100);
@@ -641,7 +665,11 @@ function BidControls({
<button
key={preset}
onClick={() => setBidAmount(Math.min(maxBid, Math.max(minBid, preset)))}
disabled={!canAffordNextBid || Math.max(minBid, preset) > maxBid}
disabled={
isBidPending ||
!canAffordNextBid ||
Math.max(minBid, preset) > maxBid
}
className={`text-xs px-2.5 py-1 border transition-colors ${
bidAmount === preset
? 'border-primary/40 bg-primary/10 text-primary'
@@ -659,13 +687,14 @@ function BidControls({
}
min={minBid}
max={maxBid}
disabled={!canAffordNextBid}
disabled={isBidPending || !canAffordNextBid}
className="w-24 text-xs px-2 py-1 border border-base-content/10 bg-transparent text-base-content tabular-nums text-right focus:outline-none focus:border-primary/30"
/>
</div>
<button
onClick={() => onBid(activeTeam.teamIndex, bidAmount)}
disabled={
isBidPending ||
!canAffordNextBid ||
bidAmount > maxBid ||
bidAmount <= state.currentBid
@@ -676,6 +705,8 @@ function BidControls({
>
{isActiveTeamFull
? `${teamIndexLabel(activeTeam.teamIndex, activeTeam.name)} 정원 완료 (${activeTeamSize}/${AUCTION_MAX_TEAM_SIZE})`
: isBidPending
? '입찰 반영 중...'
: !canAffordNextBid
? `입찰 불가 (다음 ${formatPoints(minBid)}P · 최대 ${formatPoints(maxBid)}P)`
: `${teamIndexLabel(activeTeam.teamIndex, activeTeam.name)} 입찰 (${formatPoints(bidAmount)}P)`}
@@ -872,12 +903,26 @@ export default function AuctionPage() {
const errorMessage =
socket.error ??
(auctionQuery.error instanceof Error ? auctionQuery.error.message : null);
const matchSideEffectMessage = resolveMatchSideEffectMessage(
auctionState.matchSideEffectStatus,
);
function handleUndo(sequence: number) {
if (!id) return;
if (!window.confirm(`${sequence}번 액션 직전으로 되돌릴까요?`)) return;
undoMutation.mutate(
{ matchId: id, sequence },
{
auctionActionRequestId: createClientRequestId(),
clientObservedAuctionLifecycleId: liveAuction?.auctionLifecycleId,
clientObservedCurrentAuctionPlayerOrderIndex:
liveAuction?.currentAuctionPlayerOrderIndex,
clientObservedCurrentBidRoundPlayerUserId:
liveAuction?.currentBidRoundPlayerUserId,
clientObservedPhase: liveAuction?.phase,
clientObservedRevision: liveAuction?.revision,
matchId: id,
sequence,
},
{
onSuccess: async () => {
await Promise.all([
@@ -899,7 +944,17 @@ export default function AuctionPage() {
function handleResetAuction() {
if (!id || !canConfirmAuctionCancel) return;
resetAuctionMutation.mutate(
{ matchId: id },
{
auctionActionRequestId: createClientRequestId(),
clientObservedAuctionLifecycleId: liveAuction?.auctionLifecycleId,
clientObservedCurrentAuctionPlayerOrderIndex:
liveAuction?.currentAuctionPlayerOrderIndex,
clientObservedCurrentBidRoundPlayerUserId:
liveAuction?.currentBidRoundPlayerUserId,
clientObservedPhase: liveAuction?.phase,
clientObservedRevision: liveAuction?.revision,
matchId: id,
},
{
onSuccess: async () => {
setShowCancelModal(false);
@@ -1074,6 +1129,11 @@ export default function AuctionPage() {
<div className="text-xs text-base-content/40">
모든 선수가 팀에 배정되었습니다.
</div>
{matchSideEffectMessage && (
<div className="mt-3 border border-amber-500/20 bg-amber-500/10 px-3 py-2 text-xs text-amber-600">
{matchSideEffectMessage}
</div>
)}
<Link
to={`/match/${id}`}
className="btn btn-primary btn-sm mt-4 px-6 text-xs"
@@ -1104,8 +1164,12 @@ export default function AuctionPage() {
<BidControls
state={auctionState}
captainRole={captainRole}
isBidPending={socket.isBidPending}
onBid={(teamIndex, amount) =>
socket.placeBid({ teamIndex, amount })
socket.placeBid({
bidderTeamIndex: teamIndex,
bidPointAmount: amount,
})
}
/>
<BidLog bids={auctionState.bids} />
@@ -1120,8 +1184,9 @@ export default function AuctionPage() {
type="button"
className="btn btn-primary btn-sm px-5 text-xs"
onClick={() => socket.openBidding()}
disabled={socket.isAuctionActionPending}
>
입찰 열기
{socket.isAuctionActionPending ? '반영 중...' : '입찰 열기'}
</button>
)}
{auctionState.phase === 'bidding' && (
@@ -1141,8 +1206,20 @@ export default function AuctionPage() {
type="button"
className="btn btn-primary btn-sm px-5 text-xs"
onClick={() => socket.markSold(assignedPosition)}
disabled={socket.isAuctionActionPending}
>
낙찰 처리
{socket.isAuctionActionPending ? '반영 중...' : '낙찰 처리'}
</button>
<button
type="button"
className="btn btn-outline btn-sm px-5 text-xs"
onClick={() => socket.markPassed()}
disabled={
socket.isAuctionActionPending ||
auctionState.currentBid > 0
}
>
{socket.isAuctionActionPending ? '반영 중...' : '유찰 처리'}
</button>
</div>
)}
@@ -1152,8 +1229,9 @@ export default function AuctionPage() {
type="button"
className="btn btn-primary btn-sm px-5 text-xs"
onClick={() => socket.next()}
disabled={socket.isAuctionActionPending}
>
다음 선수
{socket.isAuctionActionPending ? '반영 중...' : '다음 선수'}
</button>
)}
<div className="border-t border-base-content/10 pt-3">
@@ -1562,3 +1640,15 @@ function ChatPanel({
</div>
);
}
function resolveMatchSideEffectMessage(
status: AuctionStateView['matchSideEffectStatus'],
): string | null {
if (status === 'pending' || status === 'processing') {
return '팀 편성, 토너먼트 코드, 결과 수집 예약을 반영 중입니다.';
}
if (status === 'failed') {
return '팀 편성 후속 처리에 실패했습니다. 운영진 확인이 필요합니다.';
}
return null;
}
+91 -57
View File
@@ -52,7 +52,7 @@ type CaptainSelectionSlot = {
type CaptainSelection = {
userId: string;
initialPoints: string;
initialTeamBidPointAmountInput: string;
};
const DEFAULT_AUCTION_MAX_TIMER_SECONDS = 30;
@@ -2387,17 +2387,23 @@ export default function MatchDetailPage() {
const [captainSelections, setCaptainSelections] = useState<
Record<string, CaptainSelection>
>({});
const [topTierThreshold, setTopTierThreshold] =
const [
topTierAuctionPriorityThreshold,
setTopTierAuctionPriorityThreshold,
] =
useState<AuctionTopTierThreshold>("NONE");
const [manualTopTierUserIds, setManualTopTierUserIds] = useState<string[]>(
[],
);
const [maxTimerSeconds, setMaxTimerSeconds] = useState(
const [
manualTopTierAuctionPriorityUserIds,
setManualTopTierAuctionPriorityUserIds,
] = useState<string[]>([]);
const [
maximumBidRoundDurationSecondsInput,
setMaximumBidRoundDurationSecondsInput,
] = useState(
String(DEFAULT_AUCTION_MAX_TIMER_SECONDS),
);
const [bidExtensionSeconds, setBidExtensionSeconds] = useState(
String(DEFAULT_AUCTION_BID_EXTENSION_SECONDS),
);
const [bidRoundExtensionSecondsInput, setBidRoundExtensionSecondsInput] =
useState(String(DEFAULT_AUCTION_BID_EXTENSION_SECONDS));
const [manualResultStartTime, setManualResultStartTime] = useState("");
const [manualResultEndTime, setManualResultEndTime] = useState("");
const [manualRiotMatchId, setManualRiotMatchId] = useState("");
@@ -2550,29 +2556,33 @@ export default function MatchDetailPage() {
});
const startAuctionMutation = useMutation({
mutationFn: () =>
mutationFn: (startAuctionRequestId: string) =>
apiFetch(`/communities/${DEFAULT_COMMUNITY_ID}/matches/${id}/auction`, {
method: "POST",
body: JSON.stringify({
startAuctionRequestId,
captains: buildCaptainSlots(matchQuery.data?.participants ?? []).map(
(slot) => ({
teamIndex: slot.teamIndex,
userId: captainSelections[captainSlotKey(slot)]?.userId,
initialPoints:
initialTeamBidPointAmount:
parseInitialPointsInput(
captainSelections[captainSlotKey(slot)]?.initialPoints ?? "",
captainSelections[captainSlotKey(slot)]
?.initialTeamBidPointAmountInput ?? "",
) ?? 1000,
}),
),
initialPoints: 1000,
topTierThreshold,
manualTopTierUserIds:
topTierThreshold === "MANUAL" ? selectedManualTopTierUserIds : [],
maxTimerSeconds:
parseAuctionSecondsInput(maxTimerSeconds, 5) ??
initialTeamBidPointAmount: 1000,
topTierAuctionPriorityThreshold,
manualTopTierAuctionPriorityUserIds:
topTierAuctionPriorityThreshold === "MANUAL"
? selectedManualTopTierUserIds
: [],
maximumBidRoundDurationSeconds:
parseAuctionSecondsInput(maximumBidRoundDurationSecondsInput, 5) ??
DEFAULT_AUCTION_MAX_TIMER_SECONDS,
bidExtensionSeconds:
parseAuctionSecondsInput(bidExtensionSeconds, 0) ??
bidRoundExtensionSeconds:
parseAuctionSecondsInput(bidRoundExtensionSecondsInput, 0) ??
DEFAULT_AUCTION_BID_EXTENSION_SECONDS,
}),
}),
@@ -2681,7 +2691,8 @@ export default function MatchDetailPage() {
if (currentIsValid) {
next[key] = {
userId: currentUserId,
initialPoints: currentSelection?.initialPoints ?? "1000",
initialTeamBidPointAmountInput:
currentSelection?.initialTeamBidPointAmountInput ?? "1000",
};
usedUserIds.add(currentUserId);
continue;
@@ -2692,7 +2703,8 @@ export default function MatchDetailPage() {
);
next[key] = {
userId: fallback?.userId ?? "",
initialPoints: currentSelection?.initialPoints ?? "1000",
initialTeamBidPointAmountInput:
currentSelection?.initialTeamBidPointAmountInput ?? "1000",
};
if (fallback) usedUserIds.add(fallback.userId);
}
@@ -2754,7 +2766,8 @@ export default function MatchDetailPage() {
const hasValidCaptainInitialPoints = captainSlots.every((slot) =>
Boolean(
parseInitialPointsInput(
captainSelections[captainSlotKey(slot)]?.initialPoints ?? "",
captainSelections[captainSlotKey(slot)]
?.initialTeamBidPointAmountInput ?? "",
),
),
);
@@ -2764,12 +2777,16 @@ export default function MatchDetailPage() {
const manualPriorityCandidateIds = new Set(
manualPriorityCandidates.map((participant) => participant.userId),
);
const selectedManualTopTierUserIds = manualTopTierUserIds.filter((userId) =>
manualPriorityCandidateIds.has(userId),
const selectedManualTopTierUserIds =
manualTopTierAuctionPriorityUserIds.filter((userId) =>
manualPriorityCandidateIds.has(userId),
);
const parsedMaxTimerSeconds = parseAuctionSecondsInput(
maximumBidRoundDurationSecondsInput,
5,
);
const parsedMaxTimerSeconds = parseAuctionSecondsInput(maxTimerSeconds, 5);
const parsedBidExtensionSeconds = parseAuctionSecondsInput(
bidExtensionSeconds,
bidRoundExtensionSecondsInput,
0,
);
const hasValidAuctionTimerSettings =
@@ -2997,8 +3014,9 @@ export default function MatchDetailPage() {
...current,
[key]: {
userId: event.target.value,
initialPoints:
current[key]?.initialPoints ??
initialTeamBidPointAmountInput:
current[key]
?.initialTeamBidPointAmountInput ??
"1000",
},
}))
@@ -3035,28 +3053,34 @@ export default function MatchDetailPage() {
step={50}
className="w-full border border-base-content/10 bg-transparent px-2 py-2 text-sm tabular-nums"
value={
currentSelection?.initialPoints ?? "1000"
currentSelection
?.initialTeamBidPointAmountInput ??
"1000"
}
onChange={(event) =>
setCaptainSelections((current) => ({
...current,
[key]: {
userId: current[key]?.userId ?? "",
initialPoints: event.target.value,
initialTeamBidPointAmountInput:
event.target.value,
},
}))
}
onBlur={() =>
setCaptainSelections((current) => {
const points = parseInitialPointsInput(
current[key]?.initialPoints ?? "",
current[key]
?.initialTeamBidPointAmountInput ??
"",
);
if (points !== null) return current;
return {
...current,
[key]: {
userId: current[key]?.userId ?? "",
initialPoints: "1000",
initialTeamBidPointAmountInput:
"1000",
},
};
})
@@ -3082,17 +3106,22 @@ export default function MatchDetailPage() {
max={MAX_AUCTION_TIMER_SECONDS}
step={5}
className="min-w-0 flex-1 bg-transparent px-2 py-2 text-sm tabular-nums focus:outline-none"
value={maxTimerSeconds}
value={maximumBidRoundDurationSecondsInput}
onChange={(event) =>
setMaxTimerSeconds(event.target.value)
setMaximumBidRoundDurationSecondsInput(
event.target.value,
)
}
onBlur={() => {
if (
parseAuctionSecondsInput(maxTimerSeconds, 5)
parseAuctionSecondsInput(
maximumBidRoundDurationSecondsInput,
5,
)
) {
return;
}
setMaxTimerSeconds(
setMaximumBidRoundDurationSecondsInput(
String(DEFAULT_AUCTION_MAX_TIMER_SECONDS),
);
}}
@@ -3111,20 +3140,22 @@ export default function MatchDetailPage() {
max={MAX_AUCTION_TIMER_SECONDS}
step={1}
className="min-w-0 flex-1 bg-transparent px-2 py-2 text-sm tabular-nums focus:outline-none"
value={bidExtensionSeconds}
value={bidRoundExtensionSecondsInput}
onChange={(event) =>
setBidExtensionSeconds(event.target.value)
setBidRoundExtensionSecondsInput(
event.target.value,
)
}
onBlur={() => {
if (
parseAuctionSecondsInput(
bidExtensionSeconds,
bidRoundExtensionSecondsInput,
0,
) !== null
) {
return;
}
setBidExtensionSeconds(
setBidRoundExtensionSecondsInput(
String(DEFAULT_AUCTION_BID_EXTENSION_SECONDS),
);
}}
@@ -3142,9 +3173,9 @@ export default function MatchDetailPage() {
상위 티어 우선 등장
<select
className="mt-1 h-[38px] w-full border border-base-content/10 bg-transparent px-2 py-2 text-sm focus:border-primary/30 focus:outline-none"
value={topTierThreshold}
value={topTierAuctionPriorityThreshold}
onChange={(event) =>
setTopTierThreshold(
setTopTierAuctionPriorityThreshold(
event.target.value as AuctionTopTierThreshold,
)
}
@@ -3157,7 +3188,7 @@ export default function MatchDetailPage() {
</select>
</label>
</div>
{topTierThreshold === "MANUAL" && (
{topTierAuctionPriorityThreshold === "MANUAL" && (
<div className="border border-base-content/10 bg-base-200/20 p-3">
<div className="mb-2 text-xs font-bold uppercase tracking-wider text-base-content/35">
우선 등장 선수
@@ -3193,18 +3224,19 @@ export default function MatchDetailPage() {
className="checkbox checkbox-primary checkbox-xs"
checked={checked}
onChange={(event) =>
setManualTopTierUserIds((current) =>
event.target.checked
? [
...new Set([
...current,
participant.userId,
]),
]
: current.filter(
(userId) =>
userId !== participant.userId,
),
setManualTopTierAuctionPriorityUserIds(
(current) =>
event.target.checked
? [
...new Set([
...current,
participant.userId,
]),
]
: current.filter(
(userId) =>
userId !== participant.userId,
),
)
}
/>
@@ -3226,7 +3258,9 @@ export default function MatchDetailPage() {
disabled={
!canStartAuction || startAuctionMutation.isPending
}
onClick={() => startAuctionMutation.mutate()}
onClick={() =>
startAuctionMutation.mutate(crypto.randomUUID())
}
>
{startAuctionMutation.isPending
? "시작 중..."