This commit is contained in:
Aditya Siregar 2025-09-13 16:53:25 +07:00
parent fb6e2571a5
commit 50a8f4a295
2 changed files with 412 additions and 224 deletions

View File

@ -26,16 +26,24 @@ interface WinnerHistory {
const RandomDrawApp: React.FC = () => {
const [spinRows, setSpinRows] = useState<SpinRow[]>([]);
const [numberOfRows, setNumberOfRows] = useState<number>(4);
const [numberOfRows, setNumberOfRows] = useState<number>(5);
const [winnersHistory, setWinnersHistory] = useState<WinnerHistory[]>([]);
const [isRevealingWinners, setIsRevealingWinners] = useState<boolean>(false);
const [revealedWinners, setRevealedWinners] = useState<Set<number>>(new Set());
const [isSequentialSpinning, setIsSequentialSpinning] = useState<boolean>(false);
const [currentSpinningRow, setCurrentSpinningRow] = useState<number | null>(null);
const [selectedPrize, setSelectedPrize] = useState<number>(1); // 1 for Emas 0.25 Gram, 2 for Emas 3 Gram
const audioContextRef = useRef<AudioContext | null>(null);
const tickIntervalRefs = useRef<Map<string, NodeJS.Timeout>>(new Map());
const shuffleIntervalRefs = useRef<Map<string, NodeJS.Timeout>>(new Map());
// Use React Query hook for fetching voucher data
const { data: voucherData, isLoading: isLoadingData, refetch: refetchVouchers, error: fetchError } = useVoucherRows({ rows: numberOfRows });
// Use React Query hook for fetching voucher data - disabled by default
const { data: voucherData, isLoading: isLoadingData, refetch: refetchVouchers, error: fetchError } = useVoucherRows({
rows: numberOfRows,
winner_number: selectedPrize
}, {
enabled: false // Disable automatic fetching - only fetch when Load Data is clicked
});
// Initialize Audio Context
useEffect(() => {
@ -200,10 +208,7 @@ const RandomDrawApp: React.FC = () => {
}
}, [fetchError]);
// Refetch when numberOfRows changes
useEffect(() => {
refetchVouchers();
}, [numberOfRows]);
// Remove auto-refetch - data will only load when Load Data button is clicked
// Shuffle all rows (Acak functionality)
const shuffleAllRows = () => {
@ -375,7 +380,7 @@ const RandomDrawApp: React.FC = () => {
setIsRevealingWinners(false);
};
const performSpin = (row: SpinRow) => {
const performDramaticSpin = (row: SpinRow, isSequential: boolean = false) => {
const wheelElement = row.wheelRef.current;
if (!wheelElement) return;
@ -388,17 +393,25 @@ const RandomDrawApp: React.FC = () => {
const CARD_HEIGHT = 80;
const WINNER_ZONE_TOP = 260; // Top position of winner zone
const winnerIndex = row.displayVouchers.findIndex(v => v.voucher_code === winner.voucher_code);
// Shuffle the display vouchers to create more dramatic effect
const shuffledVouchers = shuffleArray([...row.vouchers]);
const winnerIndex = shuffledVouchers.findIndex(v => v.voucher_code === winner.voucher_code);
// Update display vouchers with shuffled order
setSpinRows(prev => prev.map(r =>
r.id === row.id ? { ...r, displayVouchers: shuffledVouchers } : r
));
wheelElement.style.transition = 'none';
wheelElement.style.transform = 'translateY(0px)';
wheelElement.offsetHeight;
setTimeout(() => {
const minSpins = 10;
const maxSpins = 20;
// More dramatic spinning with multiple phases
const minSpins = 15;
const maxSpins = 25;
const spins = minSpins + Math.random() * (maxSpins - minSpins);
const totalItems = row.displayVouchers.length;
const totalItems = shuffledVouchers.length;
const totalRotations = Math.floor(spins);
const baseScrollDistance = totalRotations * totalItems * CARD_HEIGHT;
@ -406,12 +419,22 @@ const RandomDrawApp: React.FC = () => {
const finalPosition = -(baseScrollDistance + winnerScrollPosition) + WINNER_ZONE_TOP;
const distance = Math.abs(finalPosition);
const baseDuration = 3000;
const maxDuration = 5000;
const duration = Math.min(baseDuration + (distance / 10000) * 1000, maxDuration);
const baseDuration = 4000; // Longer base duration
const maxDuration = 7000; // Longer max duration
const duration = Math.min(baseDuration + (distance / 8000) * 2000, maxDuration);
// Phase 1: Fast initial spin
const phase1Duration = duration * 0.3;
const phase1Distance = finalPosition * 0.7;
wheelElement.style.transform = `translateY(${phase1Distance}px)`;
wheelElement.style.transition = `transform ${phase1Duration}ms cubic-bezier(0.25, 0.46, 0.45, 0.94)`;
// Phase 2: Slower approach to final position
setTimeout(() => {
wheelElement.style.transform = `translateY(${finalPosition}px)`;
wheelElement.style.transition = `transform ${duration}ms cubic-bezier(0.17, 0.67, 0.12, 0.99)`;
wheelElement.style.transition = `transform ${duration - phase1Duration}ms cubic-bezier(0.17, 0.67, 0.12, 0.99)`;
}, phase1Duration);
startTickSound(row.id, duration);
@ -436,16 +459,175 @@ const RandomDrawApp: React.FC = () => {
timestamp: new Date()
}]);
// If this is sequential spinning, trigger next row
if (isSequential) {
const nextRowIndex = spinRows.findIndex(r => r.id === row.id) + 1;
if (nextRowIndex < spinRows.length) {
setTimeout(() => {
wheelElement.style.transition = 'none';
wheelElement.style.transform = 'translateY(0px)';
wheelElement.offsetHeight;
}, 1500);
spinSequentialRow(nextRowIndex);
}, 2000); // Wait 2 seconds before next spin
} else {
// All rows completed
setIsSequentialSpinning(false);
setCurrentSpinningRow(null);
}
}
// Keep the winner in the winner zone - don't reset position
// The winning card will stay exactly where it landed in the winner zone
}, duration);
}, 100);
};
const performSpin = (row: SpinRow) => {
const wheelElement = row.wheelRef.current;
if (!wheelElement) return;
const winner = row.vouchers.find(v => v.is_winner);
if (!winner) {
console.error('No winner found in vouchers');
return;
}
const CARD_HEIGHT = 80;
const WINNER_ZONE_TOP = 260; // Top position of winner zone
// Shuffle the display vouchers to create more dramatic effect
const shuffledVouchers = shuffleArray([...row.vouchers]);
const winnerIndex = shuffledVouchers.findIndex(v => v.voucher_code === winner.voucher_code);
// Update display vouchers with shuffled order
setSpinRows(prev => prev.map(r =>
r.id === row.id ? { ...r, displayVouchers: shuffledVouchers } : r
));
wheelElement.style.transition = 'none';
wheelElement.style.transform = 'translateY(0px)';
wheelElement.offsetHeight;
setTimeout(() => {
// More dramatic spinning with multiple phases
const minSpins = 15;
const maxSpins = 25;
const spins = minSpins + Math.random() * (maxSpins - minSpins);
const totalItems = shuffledVouchers.length;
const totalRotations = Math.floor(spins);
const baseScrollDistance = totalRotations * totalItems * CARD_HEIGHT;
const winnerScrollPosition = winnerIndex * CARD_HEIGHT;
const finalPosition = -(baseScrollDistance + winnerScrollPosition) + WINNER_ZONE_TOP;
const distance = Math.abs(finalPosition);
const baseDuration = 4000; // Longer base duration
const maxDuration = 7000; // Longer max duration
const duration = Math.min(baseDuration + (distance / 8000) * 2000, maxDuration);
// Phase 1: Fast initial spin
const phase1Duration = duration * 0.3;
const phase1Distance = finalPosition * 0.7;
wheelElement.style.transform = `translateY(${phase1Distance}px)`;
wheelElement.style.transition = `transform ${phase1Duration}ms cubic-bezier(0.25, 0.46, 0.45, 0.94)`;
// Phase 2: Slower approach to final position
setTimeout(() => {
wheelElement.style.transform = `translateY(${finalPosition}px)`;
wheelElement.style.transition = `transform ${duration - phase1Duration}ms cubic-bezier(0.17, 0.67, 0.12, 0.99)`;
}, phase1Duration);
startTickSound(row.id, duration);
setTimeout(() => {
const interval = tickIntervalRefs.current.get(row.id);
if (interval) {
clearTimeout(interval);
tickIntervalRefs.current.delete(row.id);
}
playWinnerSound();
setSpinRows(prev => prev.map(r =>
r.id === row.id
? { ...r, isSpinning: false, winner: winner, selectedWinner: winner }
: r
));
setWinnersHistory(prev => [...prev, {
rowNumber: row.rowNumber,
winner: winner,
timestamp: new Date()
}]);
// Keep the winner in the winner zone - don't reset position
// The winning card will stay exactly where it landed in the winner zone
}, duration);
}, 100);
};
const spinSequentialRow = (rowIndex: number) => {
if (rowIndex >= spinRows.length) {
setIsSequentialSpinning(false);
setCurrentSpinningRow(null);
return;
}
const row = spinRows[rowIndex];
if (!row || row.isSpinning || row.winner) {
// Skip this row and go to next
spinSequentialRow(rowIndex + 1);
return;
}
setCurrentSpinningRow(row.rowNumber);
setSpinRows(prev => prev.map(r =>
r.id === row.id ? { ...r, isSpinning: true, selectedWinner: null } : r
));
const wheelElement = row.wheelRef.current;
if (wheelElement) {
wheelElement.style.transition = 'none';
wheelElement.style.transform = 'translateY(0px)';
wheelElement.offsetHeight;
}
performDramaticSpin(row, true);
};
const startSequentialSpinning = () => {
if (spinRows.length === 0) return;
// Clear any existing results
setWinnersHistory([]);
setRevealedWinners(new Set());
setSpinRows(prev => prev.map(row => ({
...row,
isSpinning: false,
isShuffling: false,
winner: null,
selectedWinner: null,
displayVouchers: [...row.vouchers]
})));
// Reset all wheel positions
spinRows.forEach(row => {
const wheelElement = row.wheelRef.current;
if (wheelElement) {
wheelElement.style.transition = 'none';
wheelElement.style.transform = 'translateY(0px)';
}
});
setIsSequentialSpinning(true);
setCurrentSpinningRow(null);
// Start with first row after a short delay
setTimeout(() => {
spinSequentialRow(0);
}, 500);
};
const spinWheel = (rowId: string) => {
const row = spinRows.find(r => r.id === rowId);
if (!row || row.isSpinning || row.winner) return;
@ -472,6 +654,8 @@ const RandomDrawApp: React.FC = () => {
setWinnersHistory([]);
setRevealedWinners(new Set());
setIsSequentialSpinning(false);
setCurrentSpinningRow(null);
setSpinRows(prev => prev.map(row => ({
...row,
isSpinning: false,
@ -539,21 +723,21 @@ const RandomDrawApp: React.FC = () => {
<h1 className="text-5xl font-bold bg-gradient-to-r from-primary to-purple-600 bg-clip-text text-transparent mb-2">
Voucher Lucky Draw
</h1>
<p className="text-gray-600 text-lg">Select random winners from voucher database</p>
</div>
<div className="space-y-6">
{/* Controls Section */}
<div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
<div className="space-y-4">
{/* Controls Section - Compact Layout */}
<div className="grid grid-cols-1 lg:grid-cols-3 gap-3">
{/* Configuration Card */}
<div className="bg-white rounded-lg p-6 border border-gray-200 shadow-sm">
<h2 className="text-xl font-semibold mb-4 text-gray-900">
<div className="bg-white rounded-lg p-4 border border-gray-200 shadow-sm">
<h2 className="text-lg font-semibold mb-3 text-gray-900">
Configuration
</h2>
<div className="space-y-4">
<div className="space-y-3">
<div className="grid grid-cols-2 gap-2">
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
<label className="block text-xs font-medium text-gray-700 mb-1">
Number of Rows
</label>
<input
@ -562,62 +746,75 @@ const RandomDrawApp: React.FC = () => {
max="10"
value={numberOfRows}
onChange={(e) => setNumberOfRows(parseInt(e.target.value) || 1)}
className="w-full bg-white border border-gray-300 rounded-lg p-2 text-gray-900 focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20"
className="w-full bg-white border border-gray-300 rounded p-1.5 text-sm text-gray-900 focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary/20"
disabled={isLoadingData}
/>
</div>
<div>
<label className="block text-xs font-medium text-gray-700 mb-1">
Prize Selection
</label>
<select
value={selectedPrize}
onChange={(e) => setSelectedPrize(parseInt(e.target.value))}
className="w-full bg-white border border-gray-300 rounded p-1.5 text-sm text-gray-900 focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary/20"
disabled={isLoadingData}
>
<option value={1}>🥇 Emas 0.25 Gram</option>
<option value={2}>🥇 Emas 3 Gram</option>
</select>
</div>
</div>
<button
onClick={refreshData}
disabled={isLoadingData}
className="w-full px-4 py-2 bg-primary hover:bg-primary/90 disabled:bg-gray-400 text-white font-semibold rounded-lg flex items-center justify-center gap-2 transition-colors"
className="w-full px-3 py-1.5 bg-primary hover:bg-primary/90 disabled:bg-gray-400 text-white text-sm font-semibold rounded flex items-center justify-center gap-1 transition-colors"
>
<RefreshCw size={16} className={isLoadingData ? 'animate-spin' : ''} />
<RefreshCw size={14} className={isLoadingData ? 'animate-spin' : ''} />
{isLoadingData ? 'Loading...' : 'Load Data'}
</button>
</div>
{spinRows.length > 0 && (
<div className="mt-4 p-3 bg-gray-50 rounded-lg">
<div className="text-sm text-gray-600">
<div>Rows: {spinRows.length}</div>
<div>Total Vouchers: {spinRows.reduce((acc, row) => acc + row.vouchers.length, 0)}</div>
</div>
<div className="mt-3 p-2 bg-gray-50 rounded text-xs text-gray-600">
<div>Rows: {spinRows.length} | Vouchers: {spinRows.reduce((acc, row) => acc + row.vouchers.length, 0)}</div>
</div>
)}
</div>
{/* Actions Card */}
<div className="bg-white rounded-lg p-6 border border-gray-200 shadow-sm">
<h2 className="text-xl font-semibold mb-4 text-gray-900">
<div className="bg-white rounded-lg p-4 border border-gray-200 shadow-sm">
<h2 className="text-lg font-semibold mb-3 text-gray-900">
Actions
</h2>
<div className="space-y-3">
<div className="space-y-2">
<button
onClick={shuffleAllRows}
disabled={isLoadingData || spinRows.some(r => r.isShuffling) || spinRows.length === 0}
className="w-full px-4 py-2 bg-purple-600 hover:bg-purple-700 disabled:bg-gray-400 text-white font-semibold rounded-lg flex items-center justify-center gap-2 transition-colors"
className="w-full px-3 py-1.5 bg-purple-600 hover:bg-purple-700 disabled:bg-gray-400 text-white text-sm font-semibold rounded flex items-center justify-center gap-1 transition-colors"
>
<Shuffle size={16} className={spinRows.some(r => r.isShuffling) ? 'animate-pulse' : ''} />
Shuffle All Rows
<Shuffle size={14} className={spinRows.some(r => r.isShuffling) ? 'animate-pulse' : ''} />
Shuffle All
</button>
<button
onClick={revealWinnersDramatically}
disabled={isRevealingWinners || spinRows.length === 0}
className="w-full px-4 py-2 bg-gradient-to-r from-yellow-400 to-orange-500 hover:from-yellow-500 hover:to-orange-600 disabled:from-gray-400 disabled:to-gray-500 text-white font-bold rounded-lg flex items-center justify-center gap-2 transition-all transform hover:scale-105"
onClick={startSequentialSpinning}
disabled={isSequentialSpinning || spinRows.length === 0}
className="w-full px-3 py-1.5 bg-gradient-to-r from-blue-500 to-purple-600 hover:from-blue-600 hover:to-purple-700 disabled:from-gray-400 disabled:to-gray-500 text-white text-sm font-bold rounded flex items-center justify-center gap-1 transition-all"
>
<Trophy size={16} className={isRevealingWinners ? 'animate-bounce' : ''} />
{isRevealingWinners ? 'Revealing...' : 'Reveal All Winners'}
<Trophy size={14} className={isSequentialSpinning ? 'animate-spin' : ''} />
{isSequentialSpinning ? 'Spinning...' : 'Spin for Winner'}
</button>
{winnersHistory.length > 0 && (
<button
onClick={clearResults}
className="w-full px-4 py-2 bg-red-600 hover:bg-red-700 text-white font-semibold rounded-lg flex items-center justify-center gap-2 transition-colors"
className="w-full px-3 py-1.5 bg-red-600 hover:bg-red-700 text-white text-sm font-semibold rounded flex items-center justify-center gap-1 transition-colors"
>
<Trash2 size={16} />
<Trash2 size={14} />
Clear Results
</button>
)}
@ -625,18 +822,18 @@ const RandomDrawApp: React.FC = () => {
</div>
{/* Winners Summary Card */}
<div className="bg-white rounded-lg p-6 border border-gray-200 shadow-sm">
<h2 className="text-xl font-semibold mb-4 text-gray-900 flex items-center gap-2">
<Trophy className="text-yellow-500" size={24} />
<div className="bg-white rounded-lg p-4 border border-gray-200 shadow-sm">
<h2 className="text-lg font-semibold mb-3 text-gray-900 flex items-center gap-2">
<Trophy className="text-yellow-500" size={18} />
Winners
</h2>
{winnersHistory.length > 0 ? (
<div className="space-y-2 max-h-48 overflow-y-auto">
<div className="space-y-1 max-h-32 overflow-y-auto">
{winnersHistory.map((history) => (
<div
key={`${history.rowNumber}-${history.timestamp.getTime()}`}
className="p-2 bg-yellow-50 border border-yellow-200 rounded text-sm"
className="p-1.5 bg-yellow-50 border border-yellow-200 rounded text-xs"
>
<div className="font-semibold text-yellow-700">
Row {history.rowNumber}: {history.winner.name}
@ -648,9 +845,9 @@ const RandomDrawApp: React.FC = () => {
))}
</div>
) : (
<div className="text-center py-4">
<Trophy className="mx-auto text-gray-300 mb-2" size={32} />
<p className="text-gray-500 text-sm">No winners yet</p>
<div className="text-center py-2">
<Trophy className="mx-auto text-gray-300 mb-1" size={20} />
<p className="text-gray-500 text-xs">No winners yet</p>
</div>
)}
</div>
@ -670,21 +867,6 @@ const RandomDrawApp: React.FC = () => {
row.isShuffling ? 'border-purple-400 animate-pulse' : 'border-gray-200'
}`}>
<div className="p-4 border-b border-gray-200">
<div className="flex flex-col gap-2">
<h3 className="text-base font-semibold text-gray-900">
Row {row.rowNumber}
<span className="text-sm text-gray-600 ml-1">({row.vouchers.length})</span>
</h3>
<button
onClick={() => spinWheel(row.id)}
disabled={row.isSpinning || row.winner !== null || row.isShuffling}
className="w-full px-3 py-2 bg-primary hover:bg-primary/90 disabled:bg-gray-400 disabled:cursor-not-allowed text-white font-semibold rounded-lg flex items-center justify-center gap-2 transition-colors text-sm"
>
<RotateCw size={14} className={row.isSpinning ? 'animate-spin' : ''} />
{row.isSpinning ? 'Spinning...' : row.winner ? 'Winner' : 'Spin'}
</button>
</div>
{row.winner && (
<div className="mt-2 p-2 bg-yellow-50 border border-yellow-200 rounded-lg animate-bounce-in">
@ -706,22 +888,21 @@ const RandomDrawApp: React.FC = () => {
className="relative bg-gray-50 overflow-hidden"
style={{ height: '600px' }}
>
{/* Winner Selection Zone - Exactly 80px matching card height */}
{/* Subtle Winner Zone Indicator */}
<div
className="absolute left-0 right-0 z-50"
className="absolute left-0 right-0 z-10 pointer-events-none"
style={{
top: '260px',
height: '80px',
border: '3px solid #ef4444',
backgroundColor: 'rgba(239, 68, 68, 0.15)',
display: 'flex',
alignItems: 'center',
justifyContent: 'flex-end',
paddingRight: '10px'
background: 'linear-gradient(90deg, transparent 0%, rgba(34, 197, 94, 0.1) 20%, rgba(34, 197, 94, 0.2) 50%, rgba(34, 197, 94, 0.1) 80%, transparent 100%)',
borderTop: '2px dashed rgba(34, 197, 94, 0.3)',
borderBottom: '2px dashed rgba(34, 197, 94, 0.3)'
}}
>
<div className="bg-red-600 text-white px-3 py-1 rounded font-bold text-xs tracking-wider shadow-lg">
WINNER
<div className="absolute right-2 top-1/2 transform -translate-y-1/2">
<div className="bg-green-500 text-white px-2 py-1 rounded text-xs font-bold shadow-lg">
🏆 WINNER
</div>
</div>
</div>
@ -738,14 +919,18 @@ const RandomDrawApp: React.FC = () => {
return (
<div
key={`${repeatIndex}-${voucherIndex}`}
className={`flex items-center px-4 border-b border-gray-300 transition-colors ${
isSelectedWinner ? 'bg-yellow-100' :
voucherIndex % 2 === 0 ? 'bg-white' : 'bg-gray-50'
className={`flex items-center px-4 border-b border-gray-300 transition-all duration-300 ${
isSelectedWinner
? 'bg-gradient-to-r from-yellow-100 to-yellow-200 border-yellow-300 shadow-lg'
: voucherIndex % 2 === 0
? 'bg-white hover:bg-gray-50'
: 'bg-gray-50 hover:bg-gray-100'
}`}
style={{
height: '80px',
minHeight: '80px',
maxHeight: '80px'
maxHeight: '80px',
boxSizing: 'border-box'
}}
>
<div className="flex-1">

View File

@ -4,28 +4,31 @@ import { api } from '../api'
export interface VouchersQueryParams {
rows?: number
winner_number?: number
}
export function useVoucherRows(params: VouchersQueryParams = {}) {
const { rows = 4 } = params
export function useVoucherRows(params: VouchersQueryParams = {}, options: { enabled?: boolean } = {}) {
const { rows = 5, winner_number = 1 } = params
const { enabled = true } = options
return useQuery<VoucherRowsResponse>({
queryKey: ['voucher-rows', { rows }],
queryKey: ['voucher-rows', { rows, winner_number }],
queryFn: async () => {
const res = await api.get(`/vouchers/rows`, {
params: { rows }
params: { rows, winner_number }
})
return res.data.data
},
enabled,
staleTime: 5 * 60 * 1000,
refetchOnWindowFocus: false
})
}
// Manual fetch function for cases where you need to fetch without using the hook
export async function fetchVoucherRows(rows: number = 4): Promise<VoucherRowsResponse> {
export async function fetchVoucherRows(rows: number = 5, winner_number: number = 1): Promise<VoucherRowsResponse> {
const res = await api.get(`/vouchers/rows`, {
params: { rows }
params: { rows, winner_number }
})
return res.data.data
}