Improve task search and filtering

Search clients and assignments by employee, add end-user filters to client details, and refine filter options and sorting behavior.
This commit is contained in:
Ichsan Kurniawan
2026-11-04 16:03:26 +07:00
parent f0cc469d24
commit 47076b1d09
6 changed files with 141 additions and 65 deletions
@@ -1,11 +1,11 @@
"use client";
import { useState } from 'react';
import { useState, useMemo } from 'react';
import { Briefcase } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import Link from 'next/link';
import { IProjectAssignment } from '../../../type.assignment';
import { EndUser, IProjectAssignment } from '../../../type.assignment';
import { useRouter, useSearchParams } from 'next/navigation';
import dynamic from 'next/dynamic';
import FilterComponent from '../../../component/FilterComponent';
@@ -89,13 +89,35 @@ export default function ClientDetailComponent({ clientId, assignmentLists }: Pro
setAction(undefined);
};
const uniqueEndUsers = useMemo(() => {
const seen = new Set<string>();
const result: EndUser[] = [];
for (const item of assignmentLists) {
const endUser = item?.end_user;
if (!endUser) continue;
const key = String(endUser.id ?? endUser.code ?? endUser.name ?? '');
if (key && !seen.has(key)) {
seen.add(key);
result.push(endUser);
}
}
return result;
}, [assignmentLists]);
return (
<div className="space-y-6">
{/* --- PROJECT ASSIGNMENT DASHBOARD STATS --- */}
<ProjectAssignmentDashboardStats assignments={assignmentLists} />
{/* --- FILTER & SEARCH TOOLBAR --- */}
<FilterComponent showLayoutToggle placeholder="Search projects..." />
<FilterComponent
hideEndUser={false}
showLayoutToggle
placeholder="Search projects..."
endUserList={uniqueEndUsers}
/>
{/* --- EMPTY STATE --- */}
{assignmentLists.length === 0 ? (
@@ -199,4 +221,4 @@ export default function ClientDetailComponent({ clientId, assignmentLists }: Pro
) : null}
</div>
);
}
}
@@ -11,6 +11,8 @@ import {
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';
import useDebounce from '@/hooks/useDebounce';
import { EndUser } from '../type.assignment';
import { IEndUser } from '../types';
const FilterModal = dynamic(
() => import('./FilterModal').then((mod) => mod.FilterModal),
@@ -26,6 +28,7 @@ const FilterModal = dynamic(
);
type Props = {
endUserList?: (EndUser | IEndUser)[]
hideClient?: boolean
hideEndUser?: boolean
hideStatus?: boolean;
@@ -41,6 +44,7 @@ type Props = {
};
const FilterComponent: FC<Props> = ({
endUserList,
hideFilterModal,
hideClient,
hideEndUser,
@@ -52,7 +56,7 @@ const FilterComponent: FC<Props> = ({
hideCategory,
hideSort,
showLayoutToggle,
placeholder = "Search client...",
placeholder = "Search client or employee...",
}) => {
const router = useRouter();
const pathname = usePathname();
@@ -60,6 +64,7 @@ const FilterComponent: FC<Props> = ({
const currentQuery = searchParams?.get('q') || '';
const currentSort = searchParams?.get('sort') || '';
const sortValue = (currentSort === 'active_first' || !currentSort) ? 'default' : currentSort;
const currentLayout = searchParams?.get('layout') === 'grid' ? 'grid' : 'list';
const [searchText, setSearchText] = useState(currentQuery);
@@ -117,6 +122,7 @@ const FilterComponent: FC<Props> = ({
{!hideFilterModal ?
<FilterModal
endUserList={endUserList}
hideClient={hideClient} hideEndUser={hideEndUser}
hideCategory={hideCategory} hideStatus={hideStatus} hideAssignedTo={hideAssignedTo}
hideProjectDateFilter={hideProjectDateFilter} hideWoDateFilter={hideWoDateFilter} hideImDateFilter={hideImDateFilter} />
@@ -159,12 +165,11 @@ const FilterComponent: FC<Props> = ({
) : null}
{!hideSort ? (
<Select value={currentSort} onValueChange={handleSortChange}>
<Select value={sortValue} onValueChange={handleSortChange}>
<SelectTrigger className="flex-1 md:flex-none md:w-max min-w-32.5 bg-white dark:bg-zinc-900 h-9 text-xs sm:text-sm">
<SelectValue placeholder="Active First" />
<SelectValue placeholder="Default" />
</SelectTrigger>
<SelectContent>
<SelectItem value="active_first">Active First</SelectItem>
<SelectItem value="default">Default</SelectItem>
<SelectItem value="latest">Latest</SelectItem>
<SelectItem value="oldest">Oldest</SelectItem>
@@ -178,4 +183,4 @@ const FilterComponent: FC<Props> = ({
);
}
export default FilterComponent;
export default FilterComponent;
+32 -17
View File
@@ -1,6 +1,6 @@
"use client"
import { useState, useEffect, type FC } from 'react';
import { useState, useEffect, useMemo, type FC } from 'react';
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import { format, parseISO } from 'date-fns';
import { ListFilter } from 'lucide-react';
@@ -23,11 +23,12 @@ import { DatePickerMultiMode } from '@/components/ui/datepicker-multi-mode';
import { MultiSelect } from '@/components/ui/multi-select';
import { useFetchWithAxios } from '@/lib/axios/useFetch';
import { ProjectStatus } from '../type.assignment';
import { EndUser, ProjectStatus } from '../type.assignment';
import { IUser } from '@/app/admin/administration/user/component/type';
import { IClient, IEndUser } from '../types';
interface Props {
endUserList?: (EndUser | IEndUser)[]
hideClient?: boolean
hideEndUser?: boolean
hideStatus?: boolean;
@@ -38,16 +39,15 @@ interface Props {
hideCategory?: boolean;
}
export const FilterModal: FC<Props> = ({ hideClient = true, hideEndUser = true, hideStatus, hideAssignedTo, hideProjectDateFilter, hideWoDateFilter, hideImDateFilter, hideCategory }) => {
export const FilterModal: FC<Props> = ({ hideClient = true, hideEndUser = true, endUserList, hideStatus, hideAssignedTo, hideProjectDateFilter, hideWoDateFilter, hideImDateFilter, hideCategory }) => {
const [open, setOpen] = useState(false);
const router = useRouter();
const pathname = usePathname();
const searchParams = useSearchParams();
const { data: clientList } = useFetchWithAxios(!hideClient ? '/client' : null)
const { data: endUserList } = useFetchWithAxios(!hideEndUser ? '/end-user' : null)
const { data: statusList } = useFetchWithAxios(!hideStatus ? '/project-assignment-status' : null);
const { data: userList } = useFetchWithAxios(!hideAssignedTo ? '/user' : null);
const { data: statusList } = useFetchWithAxios(!hideStatus ? '/project-assignment-status?type=master' : null);
const { data: userList } = useFetchWithAxios(!hideAssignedTo ? '/user/active' : null);
const [clientFilter, setClientFilter] = useState<any[]>([]);
const [enduserFilter, setEnduserFilter] = useState<any[]>([]);
@@ -58,6 +58,23 @@ export const FilterModal: FC<Props> = ({ hideClient = true, hideEndUser = true,
const [woDate, setWoDate] = useState<DateRange | undefined>();
const [imDate, setImDate] = useState<DateRange | undefined>();
// Deduplicate end users options
const endUserOptions = useMemo(() => {
if (!endUserList || endUserList.length === 0) return [];
const seen = new Set<string>();
const options: { label: string; value: string }[] = [];
for (const item of endUserList) {
if (!item || item.id === undefined || item.id === null) continue;
const val = String(item.id);
if (!seen.has(val)) {
seen.add(val);
options.push({ label: item.name, value: val });
}
}
return options;
}, [endUserList]);
// Set initial filter if values exist in URL
useEffect(() => {
if (open) {
@@ -91,14 +108,13 @@ export const FilterModal: FC<Props> = ({ hideClient = true, hideEndUser = true,
}
}, [open, searchParams]);
const handleApplyFilters = () => {
const params = new URLSearchParams(searchParams?.toString());
if (clientFilter.length > 0) params.set('client', clientFilter.join(','));
if (clientFilter?.length > 0) params.set('client', clientFilter.join(','));
else params.delete('client');
if (endUserList.length > 0) params.set('end_user', endUserList.join(','));
if (enduserFilter?.length > 0) params.set('end_user', enduserFilter.join(','));
else params.delete('end_user');
// Single string values
@@ -111,7 +127,6 @@ export const FilterModal: FC<Props> = ({ hideClient = true, hideEndUser = true,
if (assignedToFilter.length > 0) params.set('users', assignedToFilter.join(','));
else params.delete('users');
// Helper to format DateRange into URL params
const applyDateRangeToParams = (range: DateRange | undefined, prefix: string) => {
if (range?.from) {
@@ -152,7 +167,7 @@ export const FilterModal: FC<Props> = ({ hideClient = true, hideEndUser = true,
// Calculate active filter count for the badge
const activeFilterCount = Array.from(searchParams!.keys()).filter(key =>
['category', 'status', 'users', 'project_date_from', 'wo_date_from', 'im_date_from'].includes(key)
['client', 'end_user', 'category', 'status', 'users', 'project_date_from', 'wo_date_from', 'im_date_from'].includes(key)
).length;
return (
@@ -189,17 +204,17 @@ export const FilterModal: FC<Props> = ({ hideClient = true, hideEndUser = true,
placeholder='Select end user to filter'
value={enduserFilter}
onChange={setEnduserFilter}
options={endUserList && endUserList.length > 0 ? endUserList.map((item: IEndUser) => ({ label: item.name, value: String(item.id) })) : []}
options={endUserOptions}
maxCount={1}
/>
</div> : null
}
{!hideCategory ?
<div className='flex flex-col gap-2'>
<Label>Assignment Category</Label>
<Label>Assignment Type</Label>
<Select value={category} onValueChange={setCategory}>
<SelectTrigger className='w-full'>
<SelectValue placeholder="Select category" />
<SelectValue placeholder="Select type" />
</SelectTrigger>
<SelectContent>
<SelectItem value="project">Project</SelectItem>
@@ -232,7 +247,7 @@ export const FilterModal: FC<Props> = ({ hideClient = true, hideEndUser = true,
}
{!hideStatus ?
<div className='flex flex-col gap-2'>
<Label>Status</Label>
<Label>Administration Status</Label>
<MultiSelect
placeholder='Select status'
value={statusFilter}
@@ -249,7 +264,7 @@ export const FilterModal: FC<Props> = ({ hideClient = true, hideEndUser = true,
placeholder='Select user to filter'
value={assignedToFilter}
onChange={setAssignedToFilter}
options={userList && userList.length > 0 ? userList.map((item: IUser) => ({ label: item.name, value: String(item.id) })) : []}
options={userList && userList?.user && userList?.user?.length > 0 ? userList?.user?.map((item: IUser) => ({ label: item.fullname, value: String(item.id) })) : []}
maxCount={1}
/>
</div> : null
@@ -267,4 +282,4 @@ export const FilterModal: FC<Props> = ({ hideClient = true, hideEndUser = true,
</PopoverContent>
</Popover>
);
}
}
+1 -10
View File
@@ -91,16 +91,6 @@ export default function HomeTask({ clients = [] }: HomeTaskProps) {
<span className="text-xl md:text-3xl font-extrabold tracking-tight text-foreground">
{card.value}
</span>
{/* {card.trend && (
<div className="flex flex-col text-[10px] leading-tight font-medium pl-0.5">
<span className="text-emerald-600 dark:text-emerald-400 font-bold flex items-center gap-0.5 whitespace-nowrap">
↑ {card.trend}
</span>
<span className="text-muted-foreground text-[9px] sm:text-[10px] whitespace-nowrap">
vs last month
</span>
</div>
)} */}
</div>
</div>
</Card900>
@@ -113,6 +103,7 @@ export default function HomeTask({ clients = [] }: HomeTaskProps) {
<FilterComponent
hideFilterModal
showLayoutToggle={true}
placeholder="Search client or employee..."
/>
{showForm && (
+71 -28
View File
@@ -6,19 +6,48 @@ export const COMPLETE_STATUS_LIST = ['BAST', 'WARRANTY', 'END OF SUPPORT']
export const ONPROGRESS_STATUS_LIST = ['ON PROGRESS', 'ON GOING', 'HALTED', 'ISSUE', 'SIT', 'UAT', 'PTR']
export const getFilteredClients = (clientLists: IClient[], query?: string, sortBy?: string) => {
let processedData = clientLists.filter((c) =>
c.name.toLowerCase().includes(query!) ||
c.code?.toLowerCase().includes(query!) ||
c.description?.toLowerCase().includes(query!)
);
if (!clientLists || !Array.isArray(clientLists) || clientLists.length === 0) return [];
const q = (query || '').toLowerCase().trim();
let processedData = clientLists.filter((c) => {
if (!q) return true;
const matchesClientName = c.name?.toLowerCase().includes(q);
const matchesClientCode = c.code?.toLowerCase().includes(q);
const matchesClientDesc = typeof c.description === 'string' && c.description.toLowerCase().includes(q);
const matchesEmployee = c.users?.some((u) =>
u?.fullname?.toLowerCase().includes(q) ||
u?.nickname?.toLowerCase().includes(q) ||
u?.name?.toLowerCase().includes(q)
);
return Boolean(matchesClientName || matchesClientCode || matchesClientDesc || matchesEmployee);
});
// If searching by employee, prioritize matching users to the front of avatars
if (q) {
processedData = processedData.map((c) => {
if (!c.users || c.users.length <= 1) return c;
const hasMatchingUser = c.users.some((u) =>
u?.fullname?.toLowerCase().includes(q) ||
u?.nickname?.toLowerCase().includes(q) ||
u?.name?.toLowerCase().includes(q)
);
if (!hasMatchingUser) return c;
const sortedUsers = [...c.users].sort((a, b) => {
const aMatch = (a?.fullname?.toLowerCase().includes(q) || a?.nickname?.toLowerCase().includes(q) || a?.name?.toLowerCase().includes(q)) ? 1 : 0;
const bMatch = (b?.fullname?.toLowerCase().includes(q) || b?.nickname?.toLowerCase().includes(q) || b?.name?.toLowerCase().includes(q)) ? 1 : 0;
return bMatch - aMatch;
});
return { ...c, users: sortedUsers };
});
}
processedData = processedData.sort((a, b) => {
if (sortBy === 'active_first') {
const aActive = (a.status_name || '').toLowerCase() === 'active' ? 1 : 0;
const bActive = (b.status_name || '').toLowerCase() === 'active' ? 1 : 0;
return bActive - aActive;
}
if (sortBy === 'latest') {
return new Date(b.created_at!).getTime() - new Date(a.created_at!).getTime();
}
@@ -39,7 +68,8 @@ export const getFilteredClients = (clientLists: IClient[], query?: string, sortB
return aCount - bCount; // Lowest count first
}
return 0; // 'default' - keeps original array order
// 'default', 'alphabet', or fallback: sort alphabetically by client name (A-Z)
return (a.name || '').trim().localeCompare((b.name || '').trim(), undefined, { sensitivity: 'base', numeric: true });
});
return processedData;
@@ -48,23 +78,30 @@ export const getFilteredClients = (clientLists: IClient[], query?: string, sortB
export const getFilteredAssignments = (assignmentList: IProjectAssignment[], query?: string, sortBy?: string) => {
if (assignmentList && assignmentList.length === 0) return []
// const activeStatuses = status ? status.toLowerCase()?.split(',') : [];
const q = (query || '').toLowerCase().trim();
// 1. FILTERING
let processedData = assignmentList?.filter((item) => {
const matchesSearch = query === '' || (
(item.client.name?.toLowerCase().includes(query!)) ||
(item.client.code?.toLowerCase().includes(query!)) ||
(item.end_user.name?.toLowerCase().includes(query!)) ||
(item.end_user.code?.toLowerCase().includes(query!)) ||
(item.im_name?.toLowerCase().includes(query)) ||
(item.im_code?.toLowerCase().includes(query)) ||
(item.im_description?.toLowerCase().includes(query)) ||
(item.project?.name?.toLowerCase().includes(query!)) ||
(item.project?.code?.toLowerCase().includes(query!)) ||
(item.project?.description?.toLowerCase().includes(query!)) ||
(item.wo_name?.toLowerCase().includes(query!)) ||
(item.wo_code?.toLowerCase().includes(query!))
if (!q) return true;
const matchesSearch = (
(item.client?.name?.toLowerCase().includes(q)) ||
(item.client?.code?.toLowerCase().includes(q)) ||
(item.end_user?.name?.toLowerCase().includes(q)) ||
(item.end_user?.code?.toLowerCase().includes(q)) ||
(item.im_name?.toLowerCase().includes(q)) ||
(item.im_code?.toLowerCase().includes(q)) ||
(item.im_description?.toLowerCase().includes(q)) ||
(item.project?.name?.toLowerCase().includes(q)) ||
(item.project?.code?.toLowerCase().includes(q)) ||
(item.project?.description?.toLowerCase().includes(q)) ||
(item.wo_name?.toLowerCase().includes(q)) ||
(item.wo_code?.toLowerCase().includes(q)) ||
(item.project_assignment_work_order_detail?.some((wo) =>
wo.user?.fullname?.toLowerCase().includes(q) ||
wo.user?.nickname?.toLowerCase().includes(q) ||
wo.user?.name?.toLowerCase().includes(q)
))
);
// --- Status Filter ---
@@ -72,7 +109,7 @@ export const getFilteredAssignments = (assignmentList: IProjectAssignment[], que
// const matchesStatus = activeStatuses.length === 0 || (itemStatus && activeStatuses.includes(itemStatus));
// return matchesSearch && matchesStatus;
return matchesSearch;
return Boolean(matchesSearch);
});
// 2. SORTING
@@ -97,8 +134,14 @@ export const getFilteredAssignments = (assignmentList: IProjectAssignment[], que
return aCount - bCount; // Lowest count first
}
if (sortBy === 'alphabet') {
const nameA = a.project?.name || a.wo_name || a.im_name || a.client?.name || '';
const nameB = b.project?.name || b.wo_name || b.im_name || b.client?.name || '';
return nameA.trim().localeCompare(nameB.trim(), undefined, { sensitivity: 'base', numeric: true });
}
return 0; // 'default' - keeps original array order
});
return processedData;
}
}
+1 -1
View File
@@ -356,7 +356,7 @@ export default function TaskError({ error, reset }: TaskErrorProps) {
<h3 className="text-xs font-semibold text-foreground">Technical Support</h3>
</div>
<p className="text-xs text-muted-foreground leading-relaxed">
If this message persists after several retries, copy the diagnostic report below and share it with the dev team.
If this message persists after several retries, copy the diagnostic report above and share it with the dev team.
</p>
</div>
</div>