Refactor Find page to implement search functionality using Supabase

This commit is contained in:
THIS ONE IS A LITTLE BIT TRICKY KRUB 2024-10-02 19:44:58 +07:00
parent fa7ce4e1e3
commit 30e4c9fe10

View File

@ -11,63 +11,140 @@ if (!supabaseUrl || !supabaseKey) {
} }
const supabase = createClient(supabaseUrl, supabaseKey); const supabase = createClient(supabaseUrl, supabaseKey);
export default function Find(){ interface ProjectInvestmentDetail {
minInvestment: number;
totalInvestment: number;
targetInvestment: number;
}
interface Project {
id: string;
projectName: string;
businessId: string;
investmentCount: number;
ProjectInvestmentDetail: ProjectInvestmentDetail[];
tags: string[];
}
interface Business {
id: string;
businessName: string;
joinedDate: string;
Projects: Project[];
}
export default function Find() {
const searchParams = useSearchParams(); const searchParams = useSearchParams();
const query = searchParams.get('query'); const query = searchParams.get('query');
const [result, setResult] = useState<{ businessName: string }[] | "">(""); const [results, setResults] = useState<Business[]>([]);
const [loading, setLoading] = useState(true);
useEffect(() => { useEffect(() => {
if (query) { const fetchData = async () => {
getQuery(query); setLoading(true);
}
}, [query]);
const getQuery = async (query: string) => {
console.log('Query is: ', query);
// search for relevant Business names first // fetch businesses
let { data: businessData, error: businessError } = await supabase const { data: businesses, error: businessError } = await supabase
.from('Business') .from('Business')
.select('id, businessName') .select('id, businessName, joinedDate')
.ilike('businessName', `%${query}%`); .ilike('businessName', `%${query}%`);
if (businessError) { if (businessError) {
console.error('Error fetching businesses:', businessError); console.error('Error fetching businesses:', businessError);
return; setLoading(false);
} return;
}
console.log('Business Search Results:', businessData); // fetch projects for these businesses
const { data: projects, error: projectError } = await supabase
.from('Project')
.select(`
id,
projectName,
businessId,
ProjectInvestmentDetail (
minInvestment,
totalInvestment,
targetInvestment
)
`)
.in('businessId', businesses?.map(b => b.id) || []);
// then search for relevant Project names if (projectError) {
let { data: projectData, error: projectError } = await supabase console.error('Error fetching projects:', projectError);
.from('Projects') setLoading(false);
.select('id, projectName') return;
.ilike('projectName', `%${query}%`); }
if (projectError) { // fetch tags for these projects
console.error('Error fetching projects:', projectError); const { data: tags, error: tagError } = await supabase
return; .from('ItemTag')
} .select('itemId, Tag (value)')
.in('itemId', projects?.map(p => p.id) || []);
console.log('Project Search Results:', projectData); if (tagError) {
console.error('Error fetching tags:', tagError);
}
return { // fetch investment counts
businesses: businessData, const { data: investmentCounts, error: investmentError } = await supabase
projects: projectData, .from('InvestmentDeal')
.select('projectId, count', { count: 'exact', head: false })
.in('projectId', projects?.map(p => p.id) || []);
if (investmentError) {
console.error('Error fetching investment counts:', investmentError);
}
// combine all data
const processedResults = businesses?.map(business => ({
...business,
Projects: projects
?.filter(project => project.businessId === business.id)
.map(project => ({
...project,
tags: tags
?.filter(t => t.itemId === project.id)
.map(t => t.Tag.values as unknown as string) || [],
investmentCount: investmentCounts?.find(ic => ic.projectId === project.id)?.count || 0
})) || []
})) || [];
setResults(processedResults);
setLoading(false);
}; };
};
if (query) {
fetchData();
}
}, [query]);
return ( return (
<div> <div>
<div className='ml-10 md:ml-48 mt-10'> {loading && <p>Loading...</p>}
<h1 className='font-bold text-lg md:text-2xl'>You searched for "{query}"</h1> {!loading && results.length === 0 && <p>No results found.</p>}
{Array.isArray(result) ? ( {!loading && results.length > 0 && (
result.map((item, index) => ( <ul>
<div key={index}>{item.businessName}</div> {results.map(business => (
)) <li key={business.id}>
) : ( <h2>{business.businessName}</h2>
result <p>Joined Date: {new Date(business.joinedDate).toLocaleDateString()}</p>
)} <ul>
</div> {business.Projects.map((project) => (
<li key={project.id}>
<h3>{project.projectName}</h3>
<p>Investment Count: {project.investmentCount}</p>
<p>Min Investment: ${project.ProjectInvestmentDetail[0]?.minInvestment}</p>
<p>Total Investment: ${project.ProjectInvestmentDetail[0]?.totalInvestment}</p>
<p>Target Investment: ${project.ProjectInvestmentDetail[0]?.targetInvestment}</p>
<p>Tags: {project.tags.join(', ')}</p>
</li>
))}
</ul>
</li>
))}
</ul>
)}
</div> </div>
); );
} }