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);
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 query = searchParams.get('query');
const [result, setResult] = useState<{ businessName: string }[] | "">("");
const [results, setResults] = useState<Business[]>([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
if (query) {
getQuery(query);
}
}, [query]);
const getQuery = async (query: string) => {
console.log('Query is: ', query);
const fetchData = async () => {
setLoading(true);
// search for relevant Business names first
let { data: businessData, error: businessError } = await supabase
.from('Business')
.select('id, businessName')
.ilike('businessName', `%${query}%`);
// fetch businesses
const { data: businesses, error: businessError } = await supabase
.from('Business')
.select('id, businessName, joinedDate')
.ilike('businessName', `%${query}%`);
if (businessError) {
console.error('Error fetching businesses:', businessError);
return;
}
if (businessError) {
console.error('Error fetching businesses:', businessError);
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
let { data: projectData, error: projectError } = await supabase
.from('Projects')
.select('id, projectName')
.ilike('projectName', `%${query}%`);
if (projectError) {
console.error('Error fetching projects:', projectError);
setLoading(false);
return;
}
if (projectError) {
console.error('Error fetching projects:', projectError);
return;
}
// fetch tags for these projects
const { data: tags, error: tagError } = await supabase
.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 {
businesses: businessData,
projects: projectData,
// fetch investment counts
const { data: investmentCounts, error: investmentError } = await supabase
.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 (
<div>
<div className='ml-10 md:ml-48 mt-10'>
<h1 className='font-bold text-lg md:text-2xl'>You searched for "{query}"</h1>
{Array.isArray(result) ? (
result.map((item, index) => (
<div key={index}>{item.businessName}</div>
))
) : (
result
)}
</div>
{loading && <p>Loading...</p>}
{!loading && results.length === 0 && <p>No results found.</p>}
{!loading && results.length > 0 && (
<ul>
{results.map(business => (
<li key={business.id}>
<h2>{business.businessName}</h2>
<p>Joined Date: {new Date(business.joinedDate).toLocaleDateString()}</p>
<ul>
{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>
);
}