import React, { useState, useEffect } from 'react'; import { supabase } from '../utils/supabase'; import CheckHistory from './CheckHistory'; const CheckPage: React.FC = () => { const [input, setInput] = useState(''); const [loading, setLoading] = useState(false); const [currentId, setCurrentId] = useState(null); const [history, setHistory] = useState([]); useEffect(() => { if (!currentId) return; const channel = supabase .channel('check_list_updates') .on( 'postgres_changes', { event: 'UPDATE', schema: 'public', table: 'check_list', filter: `id=eq.${currentId}`, }, (payload) => { if (payload.new.status === 'completed' || payload.new.status === 'failed') { setLoading(false); } } ) .subscribe(); return () => { supabase.removeChannel(channel); }; }, [currentId]); // Fetch history on mount useEffect(() => { fetchHistory(); }, []); const fetchHistory = async () => { try { const response = await fetch('/api/check/history'); const data = await response.json(); if (data.success) { setHistory(data.data); } } catch (error) { console.error('Failed to fetch history:', error); } }; // Subscribe to check_list changes for auto-refresh useEffect(() => { const channel = supabase .channel('check_list_all') .on( 'postgres_changes', { event: '*', schema: 'public', table: 'check_list', }, () => { fetchHistory(); } ) .subscribe(); return () => { supabase.removeChannel(channel); }; }, []); const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); if (!input.trim()) return; setLoading(true); setCurrentId(null); try { const response = await fetch('/api/check/submit', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ check_input: input }), }); const data = await response.json(); if (data.success) { setCurrentId(data.id); // Refresh history after submission setTimeout(() => fetchHistory(), 1000); } else { alert('Error: ' + data.error); setLoading(false); } } catch (error) { console.error(error); setLoading(false); alert('Error submitting request'); } }; const handleDeleteHistory = async (id: string) => { try { const response = await fetch(`/api/check/${id}`, { method: 'DELETE', }); const data = await response.json(); if (data.success) { fetchHistory(); } else { alert('Lỗi xoá: ' + data.error); } } catch (error) { console.error('Failed to delete:', error); alert('Lỗi xoá lịch sử'); } }; return (

Check Upload Status (QC Subset)