Enforce assignment permissions and show active milestones

Gate assignment creation and editing by the relevant permissions, show ongoing milestones on the timeline, and restrict the forbidden-page admin link to authorized users. Also use the shared RBAC role type and tighten sidebar active-state matching.
This commit is contained in:
Ichsan Kurniawan
2026-11-10 11:27:05 +07:00
parent 279b642a7a
commit e67f671983
9 changed files with 147 additions and 56 deletions
+1 -1
View File
@@ -4,7 +4,7 @@ import { IDivision } from "@/app/admin/administration/division/component/type"
import { IEmployeeType } from "@/app/admin/information/employee-type/component/type"
import { IMasterStatus } from "@/app/admin/information/master-status/component/type"
import { IPosition } from "@/app/admin/information/position/component/type"
import { IRole } from "@/app/admin/information/user-role/component/type"
import { IRole } from "@/types/rbac"
export type IProfile = {
id: number
@@ -133,13 +133,16 @@ export default function ClientDetailComponent({ clientId, assignmentLists, actio
This client doesn't have any projects or internal memos yet. Try to change the filter or create one to get started.
</p>
</div>
<Link href={`/task/client-detail/${clientId}/project-assignments`}>
<Button variant="outline" className="mt-4">Create Assignment</Button>
</Link>
{actions?.includes("CREATE_ASSIGNMENT") &&
<Link href={`/task/client-detail/${clientId}/project-assignments`}>
<Button variant="outline" className="mt-4">Create Assignment</Button>
</Link>
}
</CardContent>
</Card>
) : activeLayout === 'grid' ? (
<AssignmentGrid
actions={actions}
assignments={assignmentLists}
clientId={clientId}
onManageTeam={(a) => {
@@ -161,6 +164,7 @@ export default function ClientDetailComponent({ clientId, assignmentLists, actio
/>
) : (
<AssignmentList
actions={actions}
assignments={assignmentLists}
clientId={clientId}
onManageTeam={(a) => {
@@ -61,7 +61,7 @@ export default function ClientProfileCard({ client, clientId, actions }: Props)
{/* Right: + New assignment Button */}
<div className="shrink-0 self-start lg:self-center">
{actions?.includes("CREATE") &&
{actions?.includes("CREATE_ASSIGNMENT") &&
<Link href={`/task/client-detail/${clientId}/project-assignments`}>
<Button className="gap-2 bg-his hover:bg-his/90 text-white font-medium rounded-xl px-5 py-2.5 shadow-sm transition-transform active:scale-[0.98]">
<Plus className="h-4 w-4" />
@@ -105,6 +105,7 @@ export default async function ClientDetailPage({ params, searchParams }: Props)
<ClientDetailComponent
clientId={client_id}
assignmentLists={filterAssignments}
actions={actions}
/>
</div>
);
@@ -1,6 +1,7 @@
import type { Metadata } from 'next';
import ProjectAssignmentForm from "./ProjectAssignmentForm";
import { getClientById, getAssignmentById } from "../../../utils/queries";
import { getNonAdminAccessPagePermission } from '@/lib/get-access-data';
type Props = {
params: Promise<{ client_id?: string }>
@@ -14,6 +15,8 @@ export async function generateMetadata({ params, searchParams }: Props): Promise
const assignmentId = typeof resolvedSearchParams?.assignment_id === 'string' ? resolvedSearchParams.assignment_id : undefined;
const isPromote = resolvedSearchParams?.promote === 'true' || resolvedSearchParams?.is_promote === 'true';
await getNonAdminAccessPagePermission('/task', isPromote ? 'PROMOTE_ASSIGNMENT' : isEdit ? 'UPDATE_ASSIGNMENT' : 'CREATE_ASSIGNMENT');
try {
const clientPromise = client_id ? getClientById(client_id) : Promise.resolve(undefined);
const assignmentPromise = assignmentId && (isEdit || isPromote) ? getAssignmentById(assignmentId) : Promise.resolve(undefined);
@@ -3,6 +3,8 @@
import React from 'react';
import Link from 'next/link';
import dayjs from 'dayjs';
import isSameOrAfter from 'dayjs/plugin/isSameOrAfter';
import isSameOrBefore from 'dayjs/plugin/isSameOrBefore';
import { Calendar, ChevronRight, Clock } from 'lucide-react';
import { HoverCard, HoverCardContent, HoverCardTrigger } from '@/components/ui/hover-card';
import BadgeStatus from '@/components/ui/badge-status';
@@ -10,6 +12,9 @@ import { cn } from '@/lib/utils';
import { IClient, IClientMilestone } from '../../types';
import { resolveTechnicalStatusMeta } from '../../utils/client-overview-helpers';
dayjs.extend(isSameOrAfter);
dayjs.extend(isSameOrBefore);
interface ClientMilestoneTimelineProps {
client: IClient;
variant?: 'list' | 'grid';
@@ -20,6 +25,8 @@ interface GroupedMilestone {
date: dayjs.Dayjs;
percent: number;
diffDays: number;
isOngoing: boolean;
hideDate: boolean;
items: IClientMilestone[];
}
@@ -38,37 +45,98 @@ export default function ClientMilestoneTimeline({ client, variant = 'list' }: Cl
const maxDate = today.add(2, 'month').startOf('day');
const totalDays = maxDate.diff(today, 'day') || 60;
// Filter milestones whose start_date is within the 2-month range [today, today + 2 months]
// Helper to safely parse and normalize start and end dates (handling edge cases or inverted dates)
const getNormalizedDates = (m: IClientMilestone) => {
const d1 = m.start_date ? dayjs(m.start_date).startOf('day') : null;
const d2 = m.end_date ? dayjs(m.end_date).startOf('day') : null;
if (!d1 && !d2) return null;
if (d1 && !d2) return { startDate: d1, endDate: d1 };
if (!d1 && d2) return { startDate: d2, endDate: d2 };
const startDate = d1!.isBefore(d2!) ? d1! : d2!;
const endDate = d1!.isAfter(d2!) ? d1! : d2!;
return { startDate, endDate };
};
// Filter milestones:
// 1. Ongoing agendas: started in the past (startDate < today), but endDate is still today or in the future (endDate >= today)
// 2. Upcoming agendas: startDate is between today and maxDate (within next 2 months)
const processedMilestones: {
item: IClientMilestone;
isOngoing: boolean;
targetDate: dayjs.Dayjs;
startDate: dayjs.Dayjs;
endDate: dayjs.Dayjs;
}[] = [];
const rawMilestones = client.milestone || [];
const validMilestones = rawMilestones.filter((m) => {
if (!m.start_date) return false;
const mDate = dayjs(m.start_date).startOf('day');
const diff = mDate.diff(today, 'day');
return diff >= 0 && diff <= totalDays;
rawMilestones.forEach((m) => {
const dates = getNormalizedDates(m);
if (!dates) return;
const { startDate, endDate } = dates;
const isOngoing = startDate.isBefore(today) && (endDate.isAfter(today) || endDate.isSame(today, 'day'));
const isUpcoming = (startDate.isAfter(today) || startDate.isSame(today, 'day')) && (startDate.isBefore(maxDate) || startDate.isSame(maxDate, 'day'));
if (isOngoing) {
processedMilestones.push({
item: m,
isOngoing: true,
targetDate: today, // Position at the start of milestone
startDate,
endDate,
});
} else if (isUpcoming) {
processedMilestones.push({
item: m,
isOngoing: false,
targetDate: startDate,
startDate,
endDate,
});
}
});
// Group milestones by start_date to handle multiple agendas on the exact same date
// Group milestones by target date / start milestone to handle multiple agendas on the same point
const groupsMap: { [key: string]: GroupedMilestone } = {};
validMilestones.forEach((item) => {
const mDate = dayjs(item.start_date).startOf('day');
const dateKey = mDate.format('YYYY-MM-DD');
const diffDays = mDate.diff(today, 'day');
const rawPercent = (diffDays / totalDays) * 100;
const percent = Math.max(0, Math.min(100, rawPercent));
processedMilestones.forEach(({ item, isOngoing, targetDate }) => {
let dateKey: string;
let percent: number;
let diffDays: number;
const isAtStart = isOngoing || targetDate.isSame(today, 'day');
if (isAtStart) {
// Group ongoing agendas at the beginning of milestone (0%)
dateKey = 'start-milestone';
percent = 0;
diffDays = 0;
} else {
dateKey = targetDate.format('YYYY-MM-DD');
diffDays = targetDate.diff(today, 'day');
const rawPercent = (diffDays / totalDays) * 100;
percent = Math.max(0, Math.min(100, rawPercent));
}
if (!groupsMap[dateKey]) {
groupsMap[dateKey] = {
dateKey,
date: mDate,
date: targetDate,
percent,
diffDays,
isOngoing: false,
hideDate: false,
items: [],
};
}
groupsMap[dateKey].items.push(item);
if (isOngoing) {
groupsMap[dateKey].isOngoing = true;
// Hide date label underneath start dot because varying start dates in past would confuse users
groupsMap[dateKey].hideDate = true;
}
});
const groups = Object.values(groupsMap).sort((a, b) => a.diffDays - b.diffDays);
const groups = Object.values(groupsMap).sort((a, b) => a.percent - b.percent);
// Compute sequential line gradient segments:
// Starts at Hari Ini (0%, Merah Rose) -> Agenda 1 -> Agenda 2 -> ... -> Agenda N
@@ -78,6 +146,13 @@ export default function ClientMilestoneTimeline({ client, variant = 'list' }: Cl
let currentPercent = 0;
let currentHex = START_LINE_HEX;
// If the first group is at 0%, its status color initiates the line gradient
if (groups[0]?.percent === 0) {
const firstGroup = groups[0];
const firstMeta = resolveTechnicalStatusMeta(firstGroup.items[0]?.project_assignment_status?.name);
currentHex = firstMeta.hexColor;
}
for (let i = 0; i < groups.length; i++) {
const group = groups[i];
const targetPercent = group.percent;
@@ -91,10 +166,9 @@ export default function ClientMilestoneTimeline({ client, variant = 'list' }: Cl
fromHex: currentHex,
toHex: targetHex,
});
currentPercent = targetPercent;
currentHex = targetHex;
}
currentPercent = targetPercent;
currentHex = targetHex;
}
}
@@ -138,7 +212,7 @@ export default function ClientMilestoneTimeline({ client, variant = 'list' }: Cl
<div className="flex items-center gap-1.5">
{hasAgendas ? (
<span className="text-[10px] px-2 py-0.5 rounded-full bg-primary/10 text-primary font-bold">
{validMilestones.length} {validMilestones.length === 1 ? 'Agenda' : 'Agendas'}
{processedMilestones.length} {processedMilestones.length === 1 ? 'Agenda' : 'Agendas'}
</span>
) : (
<span className="text-[10px] text-muted-foreground italic">
@@ -150,7 +224,7 @@ export default function ClientMilestoneTimeline({ client, variant = 'list' }: Cl
{/* Timeline Viewport Container with group/rail for sibling hover coordination */}
<div className={cn("w-full min-w-0", isGrid ? "" : "overflow-x-auto scrollbar-hide")}>
<div className={cn("relative pt-3 group/rail", !hasAgendas && !isGrid ? 'pb-6' : '', hasAgendas && !isGrid ? 'mb-20' : 'mb-10', isGrid ? "px-3" : "min-w-105 px-6")}>
<div className={cn("relative pt-3 group/rail", !hasAgendas && !isGrid ? 'pb-6' : '', hasAgendas && !isGrid ? 'mb-20' : 'mb-10', isGrid ? "px-5" : "min-w-105 px-6")}>
{/* Continuous 2-Month Horizontal Rail */}
<div className="relative h-1.5 sm:h-2 w-full bg-zinc-200/70 dark:bg-zinc-700/50 rounded-full">
{/* Gradient Segments connecting Hari Ini -> Agenda 1 -> Agenda 2 -> ... */}
@@ -300,15 +374,17 @@ export default function ClientMilestoneTimeline({ client, variant = 'list' }: Cl
{isMulti ? `${group.items.length} Agendas` : primaryMeta.shortName}
</div>
{/* Date Label strictly underneath */}
<span
className={cn(
"text-[9px] sm:text-[10px] text-zinc-600 dark:text-zinc-300 font-medium whitespace-nowrap mt-0.5 select-none transition-all duration-200",
"group-hover/node:text-foreground group-hover/node:font-bold"
)}
>
{group.date.format('DD MMM')}
</span>
{/* Date Label strictly underneath (hidden for ongoing agendas with varying start dates) */}
{!group.hideDate ? (
<span
className={cn(
"text-[9px] sm:text-[10px] text-zinc-600 dark:text-zinc-300 font-medium whitespace-nowrap mt-0.5 select-none transition-all duration-200",
"group-hover/node:text-foreground group-hover/node:font-bold"
)}
>
{group.date.format('DD MMM')}
</span>
) : null}
</Link>
</HoverCardTrigger>
@@ -323,22 +399,28 @@ export default function ClientMilestoneTimeline({ client, variant = 'list' }: Cl
<div className="flex items-center justify-between pb-2 mb-2.5 border-b border-border/60">
<div className="flex items-center gap-1.5 text-foreground font-semibold text-xs">
<Calendar className="w-3.5 h-3.5 text-primary shrink-0" />
<span>{group.date.format('dddd, DD MMMM YYYY')}</span>
<span>
{group.isOngoing
? 'Ongoing Milestones (Active Today)'
: group.date.format('dddd, DD MMMM YYYY')}
</span>
</div>
<span className="text-[10px] font-medium px-2 py-0.5 rounded-md bg-muted text-muted-foreground">
{group.diffDays === 0
? 'Today'
: group.diffDays === 1
? 'Tomorrow'
: `In ${group.diffDays} days`}
{group.isOngoing
? 'Currently Active'
: group.diffDays === 0
? 'Today'
: group.diffDays === 1
? 'Tomorrow'
: `In ${group.diffDays} days`}
</span>
</div>
{/* Subtitle / Counter */}
<div className="text-[11px] text-muted-foreground mb-2">
{group.items.length === 1
? '1 milestone agenda on this date:'
: `${group.items.length} milestone agendas on this date:`}
? (group.isOngoing ? '1 ongoing milestone agenda currently active:' : '1 milestone agenda on this date:')
: (group.isOngoing ? `${group.items.length} ongoing milestone agendas currently active:` : `${group.items.length} milestone agendas on this date:`)}
</div>
{/* List of Assignment Milestones */}
@@ -15,13 +15,13 @@ import { titleCase } from '@/lib/helper';
import PageLoading from '@/components/loader/PageLoading';
import LazyLoading from '@/components/loader/LazyLoading';
import { type IUser } from '../component/type';
import { type IRole } from '@/app/admin/information/user-role/component/type';
import { type ICompany } from '../../company/component/type';
import { type IArea } from '../../area/component/type';
import { type IDivision } from '../../division/component/type';
import { type IPosition } from '@/app/admin/information/position/component/type';
import { type IEmployeeType } from '@/app/admin/information/employee-type/component/type';
import { toast } from 'sonner';
import { IRole } from '@/types/rbac';
type Props = {};
+1 -5
View File
@@ -41,11 +41,7 @@ const SidebarItem: FC<Props> = ({ menu, expand, onChangeExpand }) => {
}
const getActiveBackgroundMenu = () => {
const currentPath = pathanme || '';
const fullPath = '/admin' + (menu.path || '');
const isActive = menu.path === '' ? currentPath === '/admin' || currentPath === '/admin/' : currentPath === fullPath || (menu.path && currentPath.startsWith(fullPath + '/'));
if (isActive) {
if (pathanme === '/admin' + menu.path) {
return {
color: theme === 'dark' ? '#fff' : theme === 'system' && systemTheme === 'dark' ? '#fff' : '#fff',
fontWeight: theme === 'light' ? 600 : theme === 'system' && systemTheme === 'light' ? 600 : undefined,
+13 -8
View File
@@ -1,14 +1,17 @@
import { Metadata } from 'next';
import Link from 'next/link';
import { Button } from '@/components/ui/button';
import { Home, LayoutDashboard, ArrowLeft, ShieldX, Lock } from 'lucide-react';
import { Home, LayoutDashboard, ArrowLeft, Lock } from 'lucide-react';
import { getCacheServerSession } from '@/lib/get-access-data';
export const metadata: Metadata = {
title: '403 Forbidden | H.A.T.s',
description: 'You do not have permission to access this page.',
};
export default function ForbiddenPage() {
export default async function ForbiddenPage() {
const session = await getCacheServerSession()
return (
<div className="min-h-screen flex flex-col items-center justify-center px-4 py-12">
<div className="w-full max-w-md text-center">
@@ -50,12 +53,14 @@ export default function ForbiddenPage() {
</Button>
</Link>
<Link href="/admin" className="w-full sm:w-auto">
<Button variant="outline" className="w-full sm:w-auto inline-flex items-center justify-center gap-2 font-medium">
<LayoutDashboard size={15} />
Admin Panel
</Button>
</Link>
{session?.user.detail.role.allow_admin_panel &&
<Link href="/admin" className="w-full sm:w-auto">
<Button variant="outline" className="w-full sm:w-auto inline-flex items-center justify-center gap-2 font-medium">
<LayoutDashboard size={15} />
Admin Panel
</Button>
</Link>
}
</div>
{/* Switch Account Option */}