@@ -0,0 +1,17 @@ | |||
import { getServerI18n } from "@/i18n"; | |||
import { Stack, Typography, Link } from "@mui/material"; | |||
import NextLink from "next/link"; | |||
export default async function NotFound() { | |||
const { t } = await getServerI18n("projects", "common"); | |||
return ( | |||
<Stack spacing={2}> | |||
<Typography variant="h4">{t("Not Found")}</Typography> | |||
<Typography variant="body1">{t("The create project page was not found!")}</Typography> | |||
<Link href="/projects" component={NextLink} variant="body2"> | |||
{t("Return to all projects")} | |||
</Link> | |||
</Stack> | |||
); | |||
} |
@@ -11,10 +11,13 @@ import { | |||
} from "@/app/api/projects"; | |||
import { preloadStaff, preloadTeamLeads } from "@/app/api/staff"; | |||
import { fetchAllTasks, fetchTaskTemplates } from "@/app/api/tasks"; | |||
import { getUserAbilities } from "@/app/utils/commonUtil"; | |||
import CreateProject from "@/components/CreateProject"; | |||
import { I18nProvider, getServerI18n } from "@/i18n"; | |||
import { MAINTAIN_PROJECT } from "@/middleware"; | |||
import Typography from "@mui/material/Typography"; | |||
import { Metadata } from "next"; | |||
import { notFound } from "next/navigation"; | |||
export const metadata: Metadata = { | |||
title: "Create Project", | |||
@@ -23,6 +26,12 @@ export const metadata: Metadata = { | |||
const Projects: React.FC = async () => { | |||
const { t } = await getServerI18n("projects"); | |||
const abilities = await getUserAbilities() | |||
if (!abilities.includes(MAINTAIN_PROJECT)) { | |||
notFound(); | |||
} | |||
// Preload necessary dependencies | |||
fetchAllTasks(); | |||
fetchTaskTemplates(); | |||
@@ -13,9 +13,11 @@ import { | |||
} from "@/app/api/projects"; | |||
import { preloadStaff, preloadTeamLeads } from "@/app/api/staff"; | |||
import { fetchAllTasks, fetchTaskTemplates } from "@/app/api/tasks"; | |||
import { getUserAbilities } from "@/app/utils/commonUtil"; | |||
import { ServerFetchError } from "@/app/utils/fetchUtil"; | |||
import CreateProject from "@/components/CreateProject"; | |||
import { I18nProvider, getServerI18n } from "@/i18n"; | |||
import { MAINTAIN_PROJECT } from "@/middleware"; | |||
import Typography from "@mui/material/Typography"; | |||
import { Metadata } from "next"; | |||
import { notFound } from "next/navigation"; | |||
@@ -26,6 +28,11 @@ export const metadata: Metadata = { | |||
const Projects: React.FC = async () => { | |||
const { t } = await getServerI18n("projects"); | |||
const abilities = await getUserAbilities() | |||
if (!abilities.includes(MAINTAIN_PROJECT)) { | |||
notFound(); | |||
} | |||
// Preload necessary dependencies | |||
fetchAllTasks(); | |||
@@ -12,9 +12,11 @@ import { | |||
} from "@/app/api/projects"; | |||
import { preloadStaff, preloadTeamLeads } from "@/app/api/staff"; | |||
import { fetchAllTasks, fetchTaskTemplates } from "@/app/api/tasks"; | |||
import { getUserAbilities } from "@/app/utils/commonUtil"; | |||
import { ServerFetchError } from "@/app/utils/fetchUtil"; | |||
import CreateProject from "@/components/CreateProject"; | |||
import { I18nProvider, getServerI18n } from "@/i18n"; | |||
import { MAINTAIN_PROJECT } from "@/middleware"; | |||
import Typography from "@mui/material/Typography"; | |||
import { isArray } from "lodash"; | |||
import { Metadata } from "next"; | |||
@@ -32,8 +34,9 @@ const Projects: React.FC<Props> = async ({ searchParams }) => { | |||
const { t } = await getServerI18n("projects"); | |||
// Assume projectId is string here | |||
const projectId = searchParams["id"]; | |||
const abilities = await getUserAbilities() | |||
if (!projectId || isArray(projectId)) { | |||
if (!projectId || isArray(projectId) || abilities.includes(MAINTAIN_PROJECT)) { | |||
notFound(); | |||
} | |||
@@ -13,8 +13,10 @@ import { | |||
} from "@/app/api/projects"; | |||
import { preloadStaff, preloadTeamLeads } from "@/app/api/staff"; | |||
import { fetchAllTasks, fetchTaskTemplates } from "@/app/api/tasks"; | |||
import { getUserAbilities } from "@/app/utils/commonUtil"; | |||
import CreateProject from "@/components/CreateProject"; | |||
import { I18nProvider, getServerI18n } from "@/i18n"; | |||
import { MAINTAIN_PROJECT } from "@/middleware"; | |||
import Typography from "@mui/material/Typography"; | |||
import { isArray } from "lodash"; | |||
import { Metadata } from "next"; | |||
@@ -32,7 +34,8 @@ const Projects: React.FC<Props> = async ({ searchParams }) => { | |||
const { t } = await getServerI18n("projects"); | |||
const projectId = searchParams["id"]; | |||
if (!projectId || isArray(projectId)) { | |||
const abilities = await getUserAbilities() | |||
if (!projectId || isArray(projectId) || !abilities.includes(MAINTAIN_PROJECT)) { | |||
notFound(); | |||
} | |||
@@ -0,0 +1,17 @@ | |||
import { getServerI18n } from "@/i18n"; | |||
import { Stack, Typography, Link } from "@mui/material"; | |||
import NextLink from "next/link"; | |||
export default async function NotFound() { | |||
const { t } = await getServerI18n("projects", "common"); | |||
return ( | |||
<Stack spacing={2}> | |||
<Typography variant="h4">{t("Not Found")}</Typography> | |||
<Typography variant="body1">{t("The project page was not found!")}</Typography> | |||
<Link href="/home" component={NextLink} variant="body2"> | |||
{t("Return to home")} | |||
</Link> | |||
</Stack> | |||
); | |||
} |
@@ -1,13 +1,15 @@ | |||
import { fetchProjectCategories, fetchProjects, preloadProjects } from "@/app/api/projects"; | |||
import { getUserAbilities } from "@/app/utils/commonUtil"; | |||
import ProjectSearch from "@/components/ProjectSearch"; | |||
import { getServerI18n } from "@/i18n"; | |||
import { MAINTAIN_PROJECT, VIEW_PROJECT } from "@/middleware"; | |||
import Add from "@mui/icons-material/Add"; | |||
import { ButtonGroup } from "@mui/material"; | |||
import Button from "@mui/material/Button"; | |||
import Stack from "@mui/material/Stack"; | |||
import Typography from "@mui/material/Typography"; | |||
import { Metadata } from "next"; | |||
import Link from "next/link"; | |||
import { notFound } from "next/navigation"; | |||
import { Suspense } from "react"; | |||
export const metadata: Metadata = { | |||
@@ -19,6 +21,10 @@ const Projects: React.FC = async () => { | |||
// preloadProjects(); | |||
fetchProjectCategories(); | |||
const projects = await fetchProjects(); | |||
const abilities = await getUserAbilities() | |||
if (![MAINTAIN_PROJECT].some(ability => abilities.includes(ability))) { | |||
notFound(); | |||
} | |||
return ( | |||
<> | |||
@@ -31,7 +37,7 @@ const Projects: React.FC = async () => { | |||
<Typography variant="h4" marginInlineEnd={2}> | |||
{t("Projects")} | |||
</Typography> | |||
<Stack | |||
{abilities.includes(MAINTAIN_PROJECT) && <Stack | |||
direction="row" | |||
justifyContent="space-between" | |||
flexWrap="wrap" | |||
@@ -55,7 +61,7 @@ const Projects: React.FC = async () => { | |||
> | |||
{t("Create Project")} | |||
</Button> | |||
</Stack > | |||
</Stack >} | |||
</Stack> | |||
<Suspense fallback={<ProjectSearch.Loading />}> | |||
<ProjectSearch /> | |||
@@ -1,3 +1,4 @@ | |||
import { WildCard } from "@/app/utils/commonUtil"; | |||
import { records } from "../staff/actions"; | |||
export interface FinancialStatusReportFilter { | |||
@@ -36,17 +37,17 @@ export interface ProjectCashFlowReportRequest { | |||
// - Project Potential Delay Report | |||
export interface ProjectPotentialDelayReportFilter { | |||
team: AutocompleteOptions[]; | |||
team: string[]; | |||
client: AutocompleteOptions[]; | |||
numberOfDays: number; | |||
projectCompletion: number; | |||
daysUntilCurrentStageEnd: number; | |||
resourceUtilizationPercentage: number; | |||
} | |||
export interface ProjectPotentialDelayReportRequest { | |||
teamId: number | "All"; | |||
clientId: number | "All"; | |||
numberOfDays: number; | |||
projectCompletion: number; | |||
daysUntilCurrentStageEnd: number; | |||
resourceUtilizationPercentage: number; | |||
type: string; | |||
} | |||
@@ -68,9 +69,10 @@ export interface ProjectResourceOverconsumptionReportFilter { | |||
lowerLimit: number; | |||
} | |||
export interface ProjectResourceOverconsumptionReportRequest { | |||
export interface ProjectResourceOverconsumptionReportRequest extends WildCard { | |||
teamId?: number | |||
custId?: number | |||
subsidiaryId?: number | |||
status: "All" | "Within Budget" | "Potential Overconsumption" | "Overconsumption" | |||
lowerLimit: number | |||
} | |||
@@ -99,6 +101,7 @@ export interface ProjectCompletionReportRequest { | |||
startDate: String; | |||
endDate: String; | |||
outstanding: Boolean; | |||
teamId?: number | |||
} | |||
export interface CostAndExpenseReportFilter { | |||
team: string[]; | |||
@@ -10,6 +10,7 @@ export interface ResourceSummaryResult { | |||
customerCode: string; | |||
customerName: string; | |||
customerCodeAndName: string; | |||
subsidiaryCodeAndName: string; | |||
} | |||
export const preloadProjects = () => { | |||
@@ -94,6 +94,34 @@ export const saveMemberLeave = async (data: { | |||
); | |||
}; | |||
export const deleteMemberEntry = async (data: { | |||
staffId: number; | |||
entryId: number; | |||
}) => { | |||
return serverFetchJson<RecordTimesheetInput>( | |||
`${BASE_API_URL}/timesheets/deleteMemberEntry`, | |||
{ | |||
method: "POST", | |||
body: JSON.stringify(data), | |||
headers: { "Content-Type": "application/json" }, | |||
}, | |||
); | |||
}; | |||
export const deleteMemberLeave = async (data: { | |||
staffId: number; | |||
entryId: number; | |||
}) => { | |||
return serverFetchJson<RecordLeaveInput>( | |||
`${BASE_API_URL}/timesheets/deleteMemberLeave`, | |||
{ | |||
method: "POST", | |||
body: JSON.stringify(data), | |||
headers: { "Content-Type": "application/json" }, | |||
}, | |||
); | |||
}; | |||
export const revalidateCacheAfterAmendment = () => { | |||
revalidatePath("/(main)/home"); | |||
}; |
@@ -28,7 +28,7 @@ export const validateTimeEntry = ( | |||
if (!entry.inputHours && !entry.otHours) { | |||
error[isHoliday ? "otHours" : "inputHours"] = "Required"; | |||
} else if (entry.inputHours && isHoliday) { | |||
error.inputHours = "Cannot input normal hours for holidays"; | |||
error.inputHours = "Cannot input normal hours on holidays"; | |||
} else if (entry.inputHours && entry.inputHours <= 0) { | |||
error.inputHours = | |||
"Input hours should be between 0 and {{DAILY_NORMAL_MAX_HOURS}}"; | |||
@@ -55,16 +55,31 @@ export const validateTimeEntry = ( | |||
return Object.keys(error).length > 0 ? error : undefined; | |||
}; | |||
export const isValidLeaveEntry = (entry: Partial<LeaveEntry>): string => { | |||
export type LeaveEntryError = { | |||
[field in keyof LeaveEntry]?: string; | |||
}; | |||
export const validateLeaveEntry = ( | |||
entry: Partial<LeaveEntry>, | |||
isHoliday: boolean, | |||
): LeaveEntryError | undefined => { | |||
// Test for errrors | |||
let error: keyof LeaveEntry | "" = ""; | |||
const error: LeaveEntryError = {}; | |||
if (!entry.leaveTypeId) { | |||
error = "leaveTypeId"; | |||
} else if (!entry.inputHours || !(entry.inputHours >= 0)) { | |||
error = "inputHours"; | |||
error.leaveTypeId = "Required"; | |||
} else if (entry.inputHours && isHoliday) { | |||
error.inputHours = "Cannot input normal hours on holidays"; | |||
} else if (!entry.inputHours) { | |||
error.inputHours = "Required"; | |||
} else if ( | |||
entry.inputHours && | |||
(entry.inputHours <= 0 || entry.inputHours > DAILY_NORMAL_MAX_HOURS) | |||
) { | |||
error.inputHours = | |||
"Input hours should be between 0 and {{DAILY_NORMAL_MAX_HOURS}}"; | |||
} | |||
return error; | |||
return Object.keys(error).length > 0 ? error : undefined; | |||
}; | |||
export const validateTimesheet = ( | |||
@@ -95,27 +110,10 @@ export const validateTimesheet = ( | |||
} | |||
// Check total hours | |||
const leaves = leaveRecords[date]; | |||
const leaveHours = | |||
leaves?.reduce((acc, entry) => acc + entry.inputHours, 0) || 0; | |||
const totalInputHours = timeEntries.reduce((acc, entry) => { | |||
return acc + (entry.inputHours || 0); | |||
}, 0); | |||
const totalOtHours = timeEntries.reduce((acc, entry) => { | |||
return acc + (entry.otHours || 0); | |||
}, 0); | |||
if (totalInputHours + leaveHours > DAILY_NORMAL_MAX_HOURS) { | |||
errors[date] = | |||
"The daily normal hours (timesheet hours + leave hours) cannot be more than {{DAILY_NORMAL_MAX_HOURS}}. Please use other hours for exceeding hours or decrease the leave hours."; | |||
} else if ( | |||
totalInputHours + totalOtHours + leaveHours > | |||
TIMESHEET_DAILY_MAX_HOURS | |||
) { | |||
errors[date] = | |||
"The daily total hours cannot be more than {{TIMESHEET_DAILY_MAX_HOURS}}"; | |||
const leaves = leaveRecords[date] || []; | |||
const totalHourError = checkTotalHours(timeEntries, leaves); | |||
if (totalHourError) { | |||
errors[date] = totalHourError; | |||
} | |||
}); | |||
@@ -125,48 +123,64 @@ export const validateTimesheet = ( | |||
export const validateLeaveRecord = ( | |||
leaveRecords: RecordLeaveInput, | |||
timesheet: RecordTimesheetInput, | |||
companyHolidays: HolidaysResult[], | |||
): { [date: string]: string } | undefined => { | |||
const errors: { [date: string]: string } = {}; | |||
const holidays = new Set( | |||
compact([ | |||
...getPublicHolidaysForNYears(2).map((h) => h.date), | |||
...companyHolidays.map((h) => convertDateArrayToString(h.date)), | |||
]), | |||
); | |||
Object.keys(leaveRecords).forEach((date) => { | |||
const leaves = leaveRecords[date]; | |||
// Check each leave entry | |||
for (const entry of leaves) { | |||
const entryError = isValidLeaveEntry(entry); | |||
const entryError = validateLeaveEntry(entry, holidays.has(date)); | |||
if (entryError) { | |||
errors[date] = "There are errors in the entries"; | |||
return; | |||
} | |||
} | |||
// Check total hours | |||
const timeEntries = timesheet[date] || []; | |||
const leaveHours = leaves.reduce((acc, entry) => acc + entry.inputHours, 0); | |||
const totalInputHours = timeEntries.reduce((acc, entry) => { | |||
return acc + (entry.inputHours || 0); | |||
}, 0); | |||
const totalOtHours = timeEntries.reduce((acc, entry) => { | |||
return acc + (entry.otHours || 0); | |||
}, 0); | |||
if (totalInputHours + leaveHours > DAILY_NORMAL_MAX_HOURS) { | |||
errors[date] = | |||
"The daily normal hours (timesheet hours + leave hours) cannot be more than {{DAILY_NORMAL_MAX_HOURS}}. Please use other hours for exceeding hours or decrease the leave hours."; | |||
} else if ( | |||
totalInputHours + totalOtHours + leaveHours > | |||
TIMESHEET_DAILY_MAX_HOURS | |||
) { | |||
errors[date] = | |||
"The daily total hours cannot be more than {{TIMESHEET_DAILY_MAX_HOURS}}"; | |||
const totalHourError = checkTotalHours(timeEntries, leaves); | |||
if (totalHourError) { | |||
errors[date] = totalHourError; | |||
} | |||
}); | |||
return Object.keys(errors).length > 0 ? errors : undefined; | |||
}; | |||
export const checkTotalHours = ( | |||
timeEntries: TimeEntry[], | |||
leaves: LeaveEntry[], | |||
): string | undefined => { | |||
const leaveHours = leaves.reduce((acc, entry) => acc + entry.inputHours, 0); | |||
const totalInputHours = timeEntries.reduce((acc, entry) => { | |||
return acc + (entry.inputHours || 0); | |||
}, 0); | |||
const totalOtHours = timeEntries.reduce((acc, entry) => { | |||
return acc + (entry.otHours || 0); | |||
}, 0); | |||
if (totalInputHours + leaveHours > DAILY_NORMAL_MAX_HOURS) { | |||
return "The daily normal hours (timesheet hours + leave hours) cannot be more than {{DAILY_NORMAL_MAX_HOURS}}. Please use other hours for exceeding hours or decrease the leave hours."; | |||
} else if ( | |||
totalInputHours + totalOtHours + leaveHours > | |||
TIMESHEET_DAILY_MAX_HOURS | |||
) { | |||
return "The daily total hours cannot be more than {{TIMESHEET_DAILY_MAX_HOURS}}"; | |||
} | |||
}; | |||
export const DAILY_NORMAL_MAX_HOURS = 8; | |||
export const LEAVE_DAILY_MAX_HOURS = 8; | |||
export const TIMESHEET_DAILY_MAX_HOURS = 20; |
@@ -1,3 +1,9 @@ | |||
import { SessionWithTokens, authOptions } from "@/config/authConfig" | |||
import { getServerSession } from "next-auth" | |||
export interface WildCard { | |||
[key: string]: any; | |||
} | |||
export const dateInRange = (currentDate: string, startDate: string, endDate: string) => { | |||
if (currentDate === undefined) { | |||
@@ -28,4 +34,24 @@ export const downloadFile = (blobData: Uint8Array, filename: string) => { | |||
link.href = url; | |||
link.setAttribute("download", filename); | |||
link.click(); | |||
} | |||
export function readIntFromString(input: string): [string, number | null] | string { | |||
// Split the input string by the "-" character | |||
if (!input.includes("-")) { | |||
return [input, null] | |||
} | |||
const parts = input.split("-"); | |||
// Extract the string part and the integer part (if available) | |||
const stringPart = parts.slice(0, parts.length - 1).join("-"); | |||
const intPartStr = parts[parts.length - 1]; | |||
const intPart = intPartStr ? parseInt(intPartStr, 10) : null; | |||
return [stringPart, intPart]; | |||
} | |||
export const getUserAbilities = async () => { | |||
const session = await getServerSession(authOptions) as SessionWithTokens; | |||
return session?.abilities ?? [] as string[] | |||
} |
@@ -22,7 +22,7 @@ export const serverFetch: typeof fetch = async (input, init) => { | |||
const session = await getServerSession<any, SessionWithTokens>(authOptions); | |||
const accessToken = session?.accessToken; | |||
console.log(accessToken); | |||
// console.log(accessToken); | |||
return fetch(input, { | |||
...init, | |||
headers: { | |||
@@ -16,7 +16,7 @@ export interface AppBarProps { | |||
const AppBar: React.FC<AppBarProps> = async ({ avatarImageSrc, profileName }) => { | |||
const session = await getServerSession(authOptions) as any; | |||
const abilities: string[] = session.abilities | |||
console.log(abilities) | |||
// console.log(abilities) | |||
return ( | |||
<I18nProvider namespaces={["common"]}> | |||
<MUIAppBar position="sticky" color="default" elevation={4}> | |||
@@ -11,12 +11,13 @@ import { downloadFile } from "@/app/utils/commonUtil"; | |||
interface Props { | |||
team: TeamResult[]; | |||
customer: Customer[]; | |||
needAll: boolean | undefined; | |||
} | |||
type SearchQuery = Partial<Omit<CostAndExpenseReportFilter, "id">>; | |||
type SearchParamNames = keyof SearchQuery; | |||
const CostAndExpenseReport: React.FC<Props> = ({ team, customer }) => { | |||
const CostAndExpenseReport: React.FC<Props> = ({ team, customer, needAll }) => { | |||
const { t } = useTranslation("report"); | |||
const teamCombo = team.map((t) => `${t.name} - ${t.code}`); | |||
const custCombo = customer.map(c => ({label: `${c.name} - ${c.code}`, value: c.id})) | |||
@@ -28,7 +29,7 @@ const CostAndExpenseReport: React.FC<Props> = ({ team, customer }) => { | |||
paramName: "team", | |||
type: "select", | |||
options: teamCombo, | |||
needAll: true, | |||
needAll: needAll, | |||
}, | |||
{ | |||
label: t("Client"), | |||
@@ -1,18 +1,30 @@ | |||
import React from "react"; | |||
import { fetchAllCustomers } from "@/app/api/customer"; | |||
import { fetchTeam } from "@/app/api/team"; | |||
import { fetchIndivTeam, fetchTeam } from "@/app/api/team"; | |||
import CostAndExpenseReport from "./CostAndExpenseReport"; | |||
import CostAndExpenseReportLoading from "./CostAndExpenseReportLoading"; | |||
import { headers, cookies } from 'next/headers'; | |||
import { getServerSession } from "next-auth"; | |||
import { authOptions } from "@/config/authConfig"; | |||
import { TEAM_LEAD } from "@/middleware"; | |||
interface SubComponents { | |||
Loading: typeof CostAndExpenseReportLoading; | |||
} | |||
const CostAndExpenseReportWrapper: React.FC & SubComponents = async () => { | |||
const customers = await fetchAllCustomers() | |||
const teams = await fetchTeam () | |||
const session: any = await getServerSession(authOptions) | |||
const teamId = session.staff?.team.id | |||
const role = session.role | |||
let customers = await fetchAllCustomers() | |||
let teams = await fetchTeam() | |||
let needAll = true | |||
if (role === TEAM_LEAD) { | |||
needAll = false | |||
teams = teams.filter((team) => team.id === teamId); | |||
} | |||
return <CostAndExpenseReport team={teams} customer={customers}/> | |||
return <CostAndExpenseReport team={teams} customer={customers} needAll={needAll} /> | |||
}; | |||
CostAndExpenseReportWrapper.Loading = CostAndExpenseReportLoading; | |||
@@ -50,6 +50,7 @@ import { | |||
successDialog, | |||
} from "../Swal/CustomAlerts"; | |||
import dayjs from "dayjs"; | |||
import { DELETE_PROJECT } from "@/middleware"; | |||
export interface Props { | |||
isEditMode: boolean; | |||
@@ -70,6 +71,7 @@ export interface Props { | |||
workNatures: WorkNature[]; | |||
allStaffs: StaffResult[]; | |||
grades: Grade[]; | |||
abilities: string[]; | |||
} | |||
const hasErrorsInTab = ( | |||
@@ -113,6 +115,7 @@ const CreateProject: React.FC<Props> = ({ | |||
buildingTypes, | |||
workNatures, | |||
allStaffs, | |||
abilities, | |||
}) => { | |||
const [serverError, setServerError] = useState(""); | |||
const [tabIndex, setTabIndex] = useState(0); | |||
@@ -302,7 +305,7 @@ const CreateProject: React.FC<Props> = ({ | |||
{isEditMode && !(formProps.getValues("projectDeleted") === true) && ( | |||
<Stack direction="row" gap={1}> | |||
{/* {!formProps.getValues("projectActualStart") && ( */} | |||
{formProps.getValues("projectStatus").toLowerCase() === "pending to start" && ( | |||
{formProps.getValues("projectStatus")?.toLowerCase() === "pending to start" && ( | |||
<Button | |||
name="start" | |||
type="submit" | |||
@@ -315,7 +318,7 @@ const CreateProject: React.FC<Props> = ({ | |||
)} | |||
{/* {formProps.getValues("projectActualStart") && | |||
!formProps.getValues("projectActualEnd") && ( */} | |||
{formProps.getValues("projectStatus").toLowerCase() === "on-going" && ( | |||
{formProps.getValues("projectStatus")?.toLowerCase() === "on-going" && ( | |||
<Button | |||
name="complete" | |||
type="submit" | |||
@@ -329,9 +332,9 @@ const CreateProject: React.FC<Props> = ({ | |||
{!( | |||
// formProps.getValues("projectActualStart") && | |||
// formProps.getValues("projectActualEnd") | |||
formProps.getValues("projectStatus") === "Completed" || | |||
formProps.getValues("projectStatus") === "Deleted" | |||
) && ( | |||
formProps.getValues("projectStatus")?.toLowerCase() === "completed" || | |||
formProps.getValues("projectStatus")?.toLowerCase() === "deleted" | |||
) && abilities.includes(DELETE_PROJECT) && ( | |||
<Button | |||
variant="outlined" | |||
startIcon={<Delete />} | |||
@@ -14,6 +14,7 @@ import { | |||
import { fetchStaff, fetchTeamLeads } from "@/app/api/staff"; | |||
import { fetchAllCustomers, fetchAllSubsidiaries } from "@/app/api/customer"; | |||
import { fetchGrades } from "@/app/api/grades"; | |||
import { getUserAbilities } from "@/app/utils/commonUtil"; | |||
type CreateProjectProps = { | |||
isEditMode: false; | |||
@@ -43,6 +44,7 @@ const CreateProjectWrapper: React.FC<Props> = async (props) => { | |||
workNatures, | |||
allStaffs, | |||
grades, | |||
abilities, | |||
] = await Promise.all([ | |||
fetchAllTasks(), | |||
fetchTaskTemplates(), | |||
@@ -58,6 +60,7 @@ const CreateProjectWrapper: React.FC<Props> = async (props) => { | |||
fetchProjectWorkNatures(), | |||
fetchStaff(), | |||
fetchGrades(), | |||
getUserAbilities(), | |||
]); | |||
const projectInfo = props.isEditMode | |||
@@ -88,6 +91,7 @@ const CreateProjectWrapper: React.FC<Props> = async (props) => { | |||
allStaffs={allStaffs} | |||
grades={grades} | |||
mainProjects={mainProjects} | |||
abilities={abilities} | |||
/> | |||
); | |||
}; | |||
@@ -96,7 +96,7 @@ const Allocation: React.FC<Props> = ({ allStaffs: staff, teamLead }) => { | |||
[addStaff, selectedStaff] | |||
); | |||
const clearSubsidiary = useCallback(() => { | |||
const clearValues = useCallback(() => { | |||
if (defaultValues !== undefined) { | |||
resetField("addStaffIds"); | |||
setSelectedStaff( | |||
@@ -169,9 +169,9 @@ const Allocation: React.FC<Props> = ({ allStaffs: staff, teamLead }) => { | |||
initialStaffs.filter((i) => { | |||
const q = query.toLowerCase(); | |||
return ( | |||
i.staffId.toLowerCase().includes(q) || | |||
i.name.toLowerCase().includes(q) || | |||
i.currentPosition.toLowerCase().includes(q) | |||
i.staffId.toLowerCase().includes(q) | |||
|| i.name.toLowerCase().includes(q) | |||
|| i.currentPosition?.toLowerCase().includes(q) | |||
); | |||
}) | |||
); | |||
@@ -183,8 +183,8 @@ const Allocation: React.FC<Props> = ({ allStaffs: staff, teamLead }) => { | |||
const resetStaff = React.useCallback(() => { | |||
clearQueryInput(); | |||
clearSubsidiary(); | |||
}, [clearQueryInput, clearSubsidiary]); | |||
clearValues(); | |||
}, [clearQueryInput, clearValues]); | |||
const formProps = useForm({}); | |||
@@ -52,7 +52,7 @@ const GenerateMonthlyWorkHoursReport: React.FC<Props> = ({ staffs }) => { | |||
onSearch={async (query: any) => { | |||
console.log(query); | |||
let postData = { | |||
id: query.staffs.id, | |||
id: query.staff, | |||
yearMonth: dayjs().format("YYYY-MM").toString(), | |||
}; | |||
console.log(query.date.length > 0) | |||
@@ -1,19 +1,28 @@ | |||
import React from "react"; | |||
import GenerateMonthlyWorkHoursReportLoading from "./GenerateMonthlyWorkHoursReportLoading"; | |||
import { fetchProjects } from "@/app/api/projects"; | |||
import GenerateMonthlyWorkHoursReport from "./GenerateMonthlyWorkHoursReport"; | |||
import { fetchStaff } from "@/app/api/staff"; | |||
import { getServerSession } from "next-auth"; | |||
import { authOptions } from "@/config/authConfig"; | |||
import { TEAM_LEAD } from "@/middleware"; | |||
interface SubComponents { | |||
Loading: typeof GenerateMonthlyWorkHoursReportLoading; | |||
} | |||
const GenerateMonthlyWorkHoursReportWrapper: React.FC & SubComponents = async () => { | |||
const staffs = await fetchStaff(); | |||
const GenerateMonthlyWorkHoursReportWrapper: React.FC & | |||
SubComponents = async () => { | |||
const session: any = await getServerSession(authOptions); | |||
const teamId = session.staff?.team.id; | |||
const role = session.role; | |||
let staffs = await fetchStaff(); | |||
if (role === TEAM_LEAD) { | |||
staffs = staffs.filter((staff) => staff.teamId === teamId); | |||
} | |||
return <GenerateMonthlyWorkHoursReport staffs={staffs}/>; | |||
return <GenerateMonthlyWorkHoursReport staffs={staffs} />; | |||
}; | |||
GenerateMonthlyWorkHoursReportWrapper.Loading = GenerateMonthlyWorkHoursReportLoading; | |||
export default GenerateMonthlyWorkHoursReportWrapper; | |||
export default GenerateMonthlyWorkHoursReportWrapper; |
@@ -36,6 +36,7 @@ const GenerateProjectCashFlowReport: React.FC<Props> = ({ projects }) => { | |||
<SearchBox | |||
criteria={searchCriteria} | |||
onSearch={async (query) => { | |||
if (Boolean(query.project) && query.project !== "All") { | |||
// const projectIndex = projectCombo.findIndex(({value}) => value === parseInt(query.project)) | |||
const response = await fetchProjectCashFlowReport({ projectId: parseInt(query.project), dateType: query.dateType }) | |||
@@ -21,10 +21,8 @@ type SearchParamNames = keyof SearchQuery; | |||
const GenerateProjectPotentialDelayReport: React.FC<Props> = ({ teams, clients, subsidiaries }) => { | |||
const { t } = useTranslation("report"); | |||
const teamCombo = teams.map(team => ({ | |||
value: team.id, | |||
label: `${team.code} - ${team.name}`, | |||
})) | |||
const teamCombo = teams.map(team => `${team.code} - ${team.name}`) | |||
const clientCombo = clients.map(client => ({ | |||
value: `client: ${client.id}` , | |||
label: `${client.code} - ${client.name}`, | |||
@@ -38,16 +36,16 @@ const GenerateProjectPotentialDelayReport: React.FC<Props> = ({ teams, clients, | |||
})) | |||
const [errors, setErrors] = React.useState({ | |||
numberOfDays: false, | |||
projectCompletion: false, | |||
daysUntilCurrentStageEnd: false, | |||
resourceUtilizationPercentage: false, | |||
}) | |||
const searchCriteria: Criterion<SearchParamNames>[] = useMemo( | |||
() => [ | |||
{ label: t("Team"), paramName: "team", type: "autocomplete", options: teamCombo }, | |||
{ label: t("Team"), paramName: "team", type: "select", options: teamCombo }, | |||
{ label: t("Client"), paramName: "client", type: "autocomplete", options: [...subsidiaryCombo, ...clientCombo] }, | |||
{ label: t("Number Of Days"), paramName: "numberOfDays", type: "text", textType: "number", error: errors.numberOfDays, helperText: t("Can not be null and decimal, and should be >= 0") }, | |||
{ label: t("Project Completion (<= %)"), paramName: "projectCompletion", type: "text", textType: "number", error: errors.projectCompletion, helperText: t("Can not be null and decimal, and should be in range of 0 - 100") }, | |||
{ label: t("Days until current stage end"), paramName: "daysUntilCurrentStageEnd", type: "text", textType: "number", error: errors.daysUntilCurrentStageEnd, helperText: t("Can not be null and decimal, and should be >= 0") }, | |||
{ label: t("Resource Utilization Percentage (<= %)"), paramName: "resourceUtilizationPercentage", type: "text", textType: "number", error: errors.resourceUtilizationPercentage, helperText: t("Can not be null and decimal, and should be in range of 0 - 100") }, | |||
], | |||
[t, errors], | |||
); | |||
@@ -59,30 +57,31 @@ const GenerateProjectPotentialDelayReport: React.FC<Props> = ({ teams, clients, | |||
onSearch={async (query) => { | |||
let hasError = false | |||
if (query.numberOfDays.length === 0 || !Number.isInteger(parseFloat(query.numberOfDays)) || parseInt(query.numberOfDays) < 0) { | |||
setErrors((prev) => ({...prev, numberOfDays: true})) | |||
if (query.daysUntilCurrentStageEnd.length === 0 || !Number.isInteger(parseFloat(query.daysUntilCurrentStageEnd)) || parseInt(query.daysUntilCurrentStageEnd) < 0) { | |||
setErrors((prev) => ({...prev, daysUntilCurrentStageEnd: true})) | |||
hasError = true | |||
} else { | |||
setErrors((prev) => ({...prev, numberOfDays: false})) | |||
setErrors((prev) => ({...prev, daysUntilCurrentStageEnd: false})) | |||
} | |||
if (query.projectCompletion.length === 0 || !Number.isInteger(parseFloat(query.projectCompletion)) || parseInt(query.projectCompletion) < 0 || parseInt(query.projectCompletion) > 100) { | |||
setErrors((prev) => ({...prev, projectCompletion: true})) | |||
if (query.resourceUtilizationPercentage.length === 0 || !Number.isInteger(parseFloat(query.resourceUtilizationPercentage)) || parseInt(query.resourceUtilizationPercentage) < 0 || parseInt(query.resourceUtilizationPercentage) > 100) { | |||
setErrors((prev) => ({...prev, resourceUtilizationPercentage: true})) | |||
hasError = true | |||
} else { | |||
setErrors((prev) => ({...prev, projectCompletion: false})) | |||
setErrors((prev) => ({...prev, resourceUtilizationPercentage: false})) | |||
} | |||
if (hasError) return false | |||
const teamIndex = teamCombo.findIndex(team => team === query.team) | |||
const clientIndex = clientCombo.findIndex(client => client.value === query.client) | |||
const subsidiaryIndex = subsidiaryCombo.findIndex(subsidiary => subsidiary.value === query.client) | |||
const response = await fetchProjectPotentialDelayReport({ | |||
teamId: typeof query.team === "number" ? query.team : "All", | |||
teamId: teamIndex >= 0 ? teams[teamIndex].id : "All", | |||
clientId: clientIndex >= 0 ? clients[clientIndex].id : subsidiaryIndex >= 0 ? subsidiaries[subsidiaryIndex].id : "All", | |||
numberOfDays: parseInt(query.numberOfDays), | |||
projectCompletion: parseInt(query.projectCompletion), | |||
daysUntilCurrentStageEnd: parseInt(query.daysUntilCurrentStageEnd), | |||
resourceUtilizationPercentage: parseInt(query.resourceUtilizationPercentage), | |||
type: clientIndex >= 0 ? "client" : subsidiaryIndex >= 0 ? "subsidiary" : "All", | |||
}) | |||
if (response) { | |||
@@ -81,7 +81,11 @@ const LeaveModal: React.FC<Props> = ({ | |||
const onSubmit = useCallback<SubmitHandler<RecordLeaveInput>>( | |||
async (data) => { | |||
const errors = validateLeaveRecord(data, timesheetRecords); | |||
const errors = validateLeaveRecord( | |||
data, | |||
timesheetRecords, | |||
companyHolidays, | |||
); | |||
if (errors) { | |||
Object.keys(errors).forEach((date) => | |||
formProps.setError(date, { | |||
@@ -106,7 +110,7 @@ const LeaveModal: React.FC<Props> = ({ | |||
formProps.reset(newFormValues); | |||
onClose(); | |||
}, | |||
[formProps, onClose, timesheetRecords, username], | |||
[companyHolidays, formProps, onClose, timesheetRecords, username], | |||
); | |||
const onCancel = useCallback(() => { | |||
@@ -1,6 +1,6 @@ | |||
import { LeaveType } from "@/app/api/timesheets"; | |||
import { LeaveEntry } from "@/app/api/timesheets/actions"; | |||
import { LEAVE_DAILY_MAX_HOURS } from "@/app/api/timesheets/utils"; | |||
import { DAILY_NORMAL_MAX_HOURS } from "@/app/api/timesheets/utils"; | |||
import { shortDateFormatter } from "@/app/utils/formatUtil"; | |||
import { roundToNearestQuarter } from "@/app/utils/manhourUtils"; | |||
import { Check, Delete } from "@mui/icons-material"; | |||
@@ -24,7 +24,7 @@ import { useTranslation } from "react-i18next"; | |||
export interface Props extends Omit<ModalProps, "children"> { | |||
onSave: (leaveEntry: LeaveEntry, recordDate?: string) => Promise<void>; | |||
onDelete?: () => void; | |||
onDelete?: () => Promise<void>; | |||
leaveTypes: LeaveType[]; | |||
defaultValues?: Partial<LeaveEntry>; | |||
modalSx?: SxProps; | |||
@@ -59,7 +59,7 @@ const LeaveEditModal: React.FC<Props> = ({ | |||
t, | |||
i18n: { language }, | |||
} = useTranslation("home"); | |||
const { register, control, reset, getValues, trigger, formState } = | |||
const { register, control, reset, getValues, trigger, formState, setError } = | |||
useForm<LeaveEntry>({ | |||
defaultValues: { | |||
leaveTypeId: leaveTypes[0].id, | |||
@@ -73,10 +73,16 @@ const LeaveEditModal: React.FC<Props> = ({ | |||
const saveHandler = useCallback(async () => { | |||
const valid = await trigger(); | |||
if (valid) { | |||
await onSave(getValues(), recordDate); | |||
reset({ id: Date.now() }); | |||
try { | |||
await onSave(getValues(), recordDate); | |||
reset({ id: Date.now() }); | |||
} catch (e) { | |||
setError("root", { | |||
message: e instanceof Error ? e.message : "Unknown error", | |||
}); | |||
} | |||
} | |||
}, [getValues, onSave, recordDate, reset, trigger]); | |||
}, [getValues, onSave, recordDate, reset, setError, trigger]); | |||
const closeHandler = useCallback<NonNullable<ModalProps["onClose"]>>( | |||
(...args) => { | |||
@@ -121,12 +127,19 @@ const LeaveEditModal: React.FC<Props> = ({ | |||
fullWidth | |||
{...register("inputHours", { | |||
setValueAs: (value) => roundToNearestQuarter(parseFloat(value)), | |||
validate: (value) => | |||
(0 < value && value <= LEAVE_DAILY_MAX_HOURS) || | |||
t( | |||
"Input hours should be between 0 and {{LEAVE_DAILY_MAX_HOURS}}", | |||
{ LEAVE_DAILY_MAX_HOURS }, | |||
), | |||
validate: (value) => { | |||
if (isHoliday) { | |||
return t("Cannot input normal hours on holidays"); | |||
} | |||
return ( | |||
(0 < value && value <= DAILY_NORMAL_MAX_HOURS) || | |||
t( | |||
"Input hours should be between 0 and {{DAILY_NORMAL_MAX_HOURS}}", | |||
{ DAILY_NORMAL_MAX_HOURS }, | |||
) | |||
); | |||
}, | |||
})} | |||
error={Boolean(formState.errors.inputHours)} | |||
helperText={formState.errors.inputHours?.message} | |||
@@ -138,6 +151,11 @@ const LeaveEditModal: React.FC<Props> = ({ | |||
rows={2} | |||
{...register("remark")} | |||
/> | |||
{formState.errors.root?.message && ( | |||
<Typography variant="caption" color="error"> | |||
{t(formState.errors.root.message, { DAILY_NORMAL_MAX_HOURS })} | |||
</Typography> | |||
)} | |||
<Box display="flex" justifyContent="flex-end" gap={1}> | |||
{onDelete && ( | |||
<Button | |||
@@ -1,10 +1,14 @@ | |||
import { Add, Check, Close, Delete } from "@mui/icons-material"; | |||
import { Box, Button, Typography } from "@mui/material"; | |||
import { Box, Button, Tooltip, Typography } from "@mui/material"; | |||
import { | |||
FooterPropsOverrides, | |||
GridActionsCellItem, | |||
GridCellParams, | |||
GridColDef, | |||
GridEditInputCell, | |||
GridEditSingleSelectCell, | |||
GridEventListener, | |||
GridRenderEditCellParams, | |||
GridRowId, | |||
GridRowModel, | |||
GridRowModes, | |||
@@ -21,7 +25,11 @@ import { manhourFormatter } from "@/app/utils/formatUtil"; | |||
import dayjs from "dayjs"; | |||
import isBetween from "dayjs/plugin/isBetween"; | |||
import { LeaveType } from "@/app/api/timesheets"; | |||
import { isValidLeaveEntry } from "@/app/api/timesheets/utils"; | |||
import { | |||
DAILY_NORMAL_MAX_HOURS, | |||
LeaveEntryError, | |||
validateLeaveEntry, | |||
} from "@/app/api/timesheets/utils"; | |||
import { roundToNearestQuarter } from "@/app/utils/manhourUtils"; | |||
dayjs.extend(isBetween); | |||
@@ -35,11 +43,11 @@ interface Props { | |||
type LeaveEntryRow = Partial< | |||
LeaveEntry & { | |||
_isNew: boolean; | |||
_error: string; | |||
_error: LeaveEntryError; | |||
} | |||
>; | |||
const EntryInputTable: React.FC<Props> = ({ day, leaveTypes }) => { | |||
const EntryInputTable: React.FC<Props> = ({ day, leaveTypes, isHoliday }) => { | |||
const { t } = useTranslation("home"); | |||
const { getValues, setValue, clearErrors } = | |||
@@ -67,12 +75,12 @@ const EntryInputTable: React.FC<Props> = ({ day, leaveTypes }) => { | |||
"", | |||
) as LeaveEntryRow; | |||
const error = isValidLeaveEntry(row); | |||
const error = validateLeaveEntry(row, isHoliday); | |||
apiRef.current.updateRows([{ id, _error: error }]); | |||
return !error; | |||
}, | |||
[apiRef], | |||
[apiRef, isHoliday], | |||
); | |||
const handleCancel = useCallback( | |||
@@ -163,6 +171,20 @@ const EntryInputTable: React.FC<Props> = ({ day, leaveTypes }) => { | |||
width: 200, | |||
editable: true, | |||
type: "singleSelect", | |||
renderEditCell(params: GridRenderEditCellParams<LeaveEntryRow>) { | |||
const errorMessage = | |||
params.row._error?.[params.field as keyof LeaveEntry]; | |||
const content = ( | |||
<GridEditSingleSelectCell variant="outlined" {...params} /> | |||
); | |||
return errorMessage ? ( | |||
<Tooltip title={t(errorMessage)} placement="top"> | |||
<Box width="100%">{content}</Box> | |||
</Tooltip> | |||
) : ( | |||
content | |||
); | |||
}, | |||
valueOptions() { | |||
return leaveTypes.map((p) => ({ value: p.id, label: p.name })); | |||
}, | |||
@@ -176,6 +198,18 @@ const EntryInputTable: React.FC<Props> = ({ day, leaveTypes }) => { | |||
width: 150, | |||
editable: true, | |||
type: "number", | |||
renderEditCell(params: GridRenderEditCellParams<LeaveEntryRow>) { | |||
const errorMessage = | |||
params.row._error?.[params.field as keyof LeaveEntry]; | |||
const content = <GridEditInputCell {...params} />; | |||
return errorMessage ? ( | |||
<Tooltip title={t(errorMessage, { DAILY_NORMAL_MAX_HOURS })}> | |||
<Box width="100%">{content}</Box> | |||
</Tooltip> | |||
) : ( | |||
content | |||
); | |||
}, | |||
valueParser(value) { | |||
return value ? roundToNearestQuarter(value) : value; | |||
}, | |||
@@ -248,16 +282,10 @@ const EntryInputTable: React.FC<Props> = ({ day, leaveTypes }) => { | |||
onRowEditStop={handleEditStop} | |||
processRowUpdate={processRowUpdate} | |||
columns={columns} | |||
getCellClassName={(params) => { | |||
getCellClassName={(params: GridCellParams<LeaveEntryRow>) => { | |||
let classname = ""; | |||
if (params.row._error === params.field) { | |||
if (params.row._error?.[params.field as keyof LeaveEntry]) { | |||
classname = "hasError"; | |||
} else if ( | |||
params.field === "taskGroupId" && | |||
params.row.isPlanned !== undefined && | |||
!params.row.isPlanned | |||
) { | |||
classname = "hasWarning"; | |||
} | |||
return classname; | |||
}} | |||
@@ -50,9 +50,9 @@ const MobileLeaveEntry: React.FC<Props> = ({ | |||
const openEditModal = useCallback( | |||
(defaultValues?: LeaveEntry) => () => { | |||
setEditModalProps({ | |||
defaultValues, | |||
defaultValues: defaultValues ? { ...defaultValues } : undefined, | |||
onDelete: defaultValues | |||
? () => { | |||
? async () => { | |||
setValue( | |||
date, | |||
currentEntries.filter((entry) => entry.id !== defaultValues.id), | |||
@@ -139,6 +139,7 @@ const MobileLeaveEntry: React.FC<Props> = ({ | |||
open={editModalOpen} | |||
onClose={closeEditModal} | |||
onSave={onSaveEntry} | |||
isHoliday={Boolean(isHoliday)} | |||
{...editModalProps} | |||
/> | |||
</Box> | |||
@@ -37,8 +37,11 @@ import EmojiEventsIcon from "@mui/icons-material/EmojiEvents"; | |||
import { | |||
GENERATE_REPORTS, | |||
MAINTAIN_MASTERDATA, | |||
MAINTAIN_PROJECT, | |||
MAINTAIN_TASK_TEMPLATE, | |||
MAINTAIN_USER, | |||
VIEW_MASTERDATA, | |||
VIEW_PROJECT, | |||
VIEW_USER, | |||
} from "@/middleware"; | |||
import { SessionWithAbilities } from "../AppBar/NavigationToggle"; | |||
@@ -131,8 +134,8 @@ const NavigationContent: React.FC<Props> = ({ abilities }) => { | |||
// }, | |||
// ], | |||
// }, | |||
{ icon: <Assignment />, label: "Project Management", path: "/projects" }, | |||
{ icon: <Task />, label: "Task Template", path: "/tasks" }, | |||
{ icon: <Assignment />, label: "Project Management", path: "/projects", isHidden: ![MAINTAIN_PROJECT].some((ability) => abilities?.includes(ability)) }, | |||
{ icon: <Task />, label: "Task Template", path: "/tasks", isHidden: ![MAINTAIN_TASK_TEMPLATE].some((ability) => abilities?.includes(ability)) }, | |||
{ icon: <Payments />, label: "Invoice", path: "/invoice" }, | |||
{ | |||
icon: <Analytics />, | |||
@@ -97,8 +97,8 @@ const ProjectCashFlow: React.FC = () => { | |||
cumulativeIncome.push(cashFlowMonthlyChartData[0].incomeList[i].cumulativeIncome) | |||
} | |||
for (var i = 0; i < cashFlowMonthlyChartData[0].expenditureList.length; i++) { | |||
if (rightMax < cashFlowMonthlyChartData[0].incomeList[i].income || rightMax < cashFlowMonthlyChartData[0].expenditureList[i].expenditure){ | |||
rightMax = Math.max(cashFlowMonthlyChartData[0].incomeList[i].income,cashFlowMonthlyChartData[0].expenditureList[i].expenditure) | |||
if (rightMax < cashFlowMonthlyChartData[0].incomeList[i].cumulativeIncome || rightMax < cashFlowMonthlyChartData[0].expenditureList[i].cumulativeExpenditure){ | |||
rightMax = Math.max(cashFlowMonthlyChartData[0].incomeList[i].cumulativeIncome,cashFlowMonthlyChartData[0].expenditureList[i].cumulativeExpenditure) | |||
} | |||
monthlyExpenditure.push(cashFlowMonthlyChartData[0].expenditureList[i].expenditure) | |||
cumulativeExpenditure.push(cashFlowMonthlyChartData[0].expenditureList[i].cumulativeExpenditure) | |||
@@ -141,11 +141,12 @@ const ProjectCashFlow: React.FC = () => { | |||
} | |||
monthlyAnticipateIncome.push(cashFlowAnticipateData[0].anticipateIncomeList[i].anticipateIncome) | |||
} | |||
setMonthlyAnticipateIncomeList(monthlyAnticipateIncome) | |||
} else { | |||
setMonthlyAnticipateIncomeList([0,0,0,0,0,0,0,0,0,0,0,0]) | |||
setMonthlyAnticipateExpenditureList([0,0,0,0,0,0,0,0,0,0,0,0]) | |||
} | |||
setMonthlyAnticipateIncomeList(monthlyAnticipateIncome) | |||
console.log(cashFlowAnticipateData) | |||
if(cashFlowAnticipateData.length !== 0){ | |||
if (cashFlowAnticipateData[0].anticipateExpenditureList.length !== 0) { | |||
@@ -175,7 +176,7 @@ const ProjectCashFlow: React.FC = () => { | |||
} | |||
setMonthlyAnticipateExpenditureList(result) | |||
for (var i = 0; i < monthlyAnticipateIncome.length; i++) { | |||
if (anticipateLeftMax < monthlyAnticipateIncome[i] || result[i]){ | |||
if (anticipateLeftMax < monthlyAnticipateIncome[i] || anticipateLeftMax < result[i]){ | |||
anticipateLeftMax = Math.max(monthlyAnticipateIncome[i],result[i]) | |||
} | |||
setMonthlyAnticipateLeftMax(anticipateLeftMax) | |||
@@ -432,6 +433,13 @@ const ProjectCashFlow: React.FC = () => { | |||
}; | |||
const anticipateOptions: ApexOptions = { | |||
tooltip: { | |||
y: { | |||
formatter: function(val) { | |||
return val.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }); | |||
} | |||
} | |||
}, | |||
chart: { | |||
height: 350, | |||
type: "line", | |||
@@ -12,6 +12,7 @@ import { downloadFile } from "@/app/utils/commonUtil"; | |||
import { fetchProjectCompletionReport } from "@/app/api/reports/actions"; | |||
interface Props { | |||
teamId: number| null | |||
} | |||
type SearchQuery = Partial<Omit<ProjectCompletionReportFilter, "id">>; | |||
@@ -19,6 +20,7 @@ type SearchParamNames = keyof SearchQuery; | |||
const ProjectCompletionReport: React.FC<Props> = ( | |||
{ | |||
teamId | |||
} | |||
) => { | |||
const { t } = useTranslation("report"); | |||
@@ -28,8 +30,8 @@ const ProjectCompletionReport: React.FC<Props> = ( | |||
const searchCriteria: Criterion<SearchParamNames>[] = useMemo( | |||
() => [ | |||
{ | |||
label: t("startDate"), | |||
label2: t("endDate"), | |||
label: t("Completion Date From"), | |||
label2: t("Completion Date To"), | |||
paramName: "startDate", | |||
type: "dateRange", | |||
}, | |||
@@ -50,37 +52,26 @@ const ProjectCompletionReport: React.FC<Props> = ( | |||
formType={"download"} | |||
criteria={searchCriteria} | |||
onSearch={async (query: any) => { | |||
console.log(query); | |||
let postData: ProjectCompletionReportRequest = { | |||
startDate: "", | |||
endDate: dayjs().format(INPUT_DATE_FORMAT).toString(), | |||
outstanding: false | |||
outstanding: query.outstanding && query.outstanding === "Outstanding Accounts Receivable" | |||
}; | |||
if (query.endDate && query.endDate.length > 0) { | |||
postData.endDate = query.endDate; | |||
if (query.startDateTo && query.startDateTo.length > 0) { | |||
postData.endDate = query.startDateTo; | |||
} | |||
if (teamId) { | |||
postData.teamId = teamId | |||
} | |||
// check if start date exist | |||
if (query.startDate.length === 0) { | |||
setError(t("Start Date cant be empty")); | |||
} else { | |||
postData.startDate = query.startDate; | |||
if (query.outstanding && query.outstanding === "Outstanding Accounts Receivable") { | |||
// outstanding report | |||
postData.outstanding = true | |||
} | |||
console.log(postData) | |||
const response = | |||
await fetchProjectCompletionReport( | |||
postData | |||
); | |||
// normal report | |||
const response = await fetchProjectCompletionReport(postData); | |||
if (response) { | |||
downloadFile( | |||
new Uint8Array(response.blobValue), | |||
response.filename!! | |||
); | |||
downloadFile(new Uint8Array(response.blobValue), response.filename!!); | |||
} | |||
} | |||
}} | |||
@@ -3,14 +3,20 @@ import { fetchAllCustomers } from "@/app/api/customer"; | |||
import { fetchTeam } from "@/app/api/team"; | |||
import ProjectCompletionReportLoading from "./ProjectCompletionReportLoading"; | |||
import ProjectCompletionReport from "./ProjectCompletionReport"; | |||
import { getServerSession } from "next-auth"; | |||
import { authOptions } from "@/config/authConfig"; | |||
import { TEAM_LEAD } from "@/middleware"; | |||
interface SubComponents { | |||
Loading: typeof ProjectCompletionReportLoading; | |||
} | |||
const ProjectCompletionReportWrapper: React.FC & SubComponents = async () => { | |||
return <ProjectCompletionReport/> | |||
const session: any = await getServerSession(authOptions) | |||
const teamId = session.staff?.team.id | |||
const role = session.role | |||
return <ProjectCompletionReport teamId={role === TEAM_LEAD && session.staff?.team ? teamId : null}/> | |||
}; | |||
ProjectCompletionReportWrapper.Loading = ProjectCompletionReportLoading; | |||
@@ -135,6 +135,10 @@ const ProjectResourceSummary: React.FC = () => { | |||
subStageList.push(subStageResult[i].plannedResources) | |||
subStageList.push(subStageResult[i].actualResourcesSpent) | |||
} | |||
if (i === subStageResult.length-1) { | |||
subStageSecondLayerList.push(subStageList) | |||
subStageFullList.push(subStageSecondLayerList) | |||
} | |||
} | |||
console.log(subStageFullList) | |||
@@ -157,6 +161,9 @@ const ProjectResourceSummary: React.FC = () => { | |||
mainStageList.push(mainStageResult[i].plannedResources) | |||
mainStageList.push(mainStageResult[i].actualResourcesSpent) | |||
} | |||
if (i === mainStageResult.length - 1) { | |||
mainStageFullList.push(createData(mainStageList,subStageFullList[arrayNumber])) | |||
} | |||
} | |||
setRows(mainStageFullList) | |||
} | |||
@@ -238,20 +245,20 @@ const ProjectResourceSummary: React.FC = () => { | |||
</IconButton> | |||
)} | |||
</TableCell> | |||
<TableCell style={{fontSize:10}}>{row.stage}</TableCell> | |||
<TableCell style={{fontSize:10}}>{row.taskCount}</TableCell> | |||
<TableCell style={{fontSize:10}}>{row.g1Planned.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</TableCell> | |||
<TableCell style={{fontSize:10}}>{row.g1Actual.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</TableCell> | |||
<TableCell style={{fontSize:10}}>{row.g2Planned.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</TableCell> | |||
<TableCell style={{fontSize:10}}>{row.g2Actual.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</TableCell> | |||
<TableCell style={{fontSize:10}}>{row.g3Planned.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</TableCell> | |||
<TableCell style={{fontSize:10}}>{row.g3Actual.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</TableCell> | |||
<TableCell style={{fontSize:10}}>{row.g4Planned.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</TableCell> | |||
<TableCell style={{fontSize:10}}>{row.g4Actual.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</TableCell> | |||
<TableCell style={{fontSize:10}}>{row.g5Planned.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</TableCell> | |||
<TableCell style={{fontSize:10}}>{row.g5Actual.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</TableCell> | |||
<TableCell style={{fontSize:10}}>{row.totalPlanned.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</TableCell> | |||
<TableCell style={{fontSize:10}}>{row.totalActual.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</TableCell> | |||
<TableCell style={{fontSize:13}}>{row.stage}</TableCell> | |||
<TableCell style={{fontSize:13}}>{row.taskCount}</TableCell> | |||
<TableCell style={{fontSize:13}}>{row.g1Planned.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</TableCell> | |||
<TableCell style={{fontSize:13}}>{row.g1Actual.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</TableCell> | |||
<TableCell style={{fontSize:13}}>{row.g2Planned.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</TableCell> | |||
<TableCell style={{fontSize:13}}>{row.g2Actual.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</TableCell> | |||
<TableCell style={{fontSize:13}}>{row.g3Planned.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</TableCell> | |||
<TableCell style={{fontSize:13}}>{row.g3Actual.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</TableCell> | |||
<TableCell style={{fontSize:13}}>{row.g4Planned.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</TableCell> | |||
<TableCell style={{fontSize:13}}>{row.g4Actual.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</TableCell> | |||
<TableCell style={{fontSize:13}}>{row.g5Planned.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</TableCell> | |||
<TableCell style={{fontSize:13}}>{row.g5Actual.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</TableCell> | |||
<TableCell style={{fontSize:13}}>{row.totalPlanned.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</TableCell> | |||
<TableCell style={{fontSize:13}}>{row.totalActual.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</TableCell> | |||
</TableRow> | |||
{row.task.map((taskRow:any) => ( | |||
<TableRow key={taskRow[0]} style={{backgroundColor:"#f0f3f7"}}> | |||
@@ -274,7 +281,7 @@ const ProjectResourceSummary: React.FC = () => { | |||
<Table size="small" aria-label="tasks"> | |||
<TableBody> | |||
<TableRow> | |||
<TableCell style={{fontSize:10}} colSpan={1}>{taskRow[0]}</TableCell> | |||
<TableCell style={{fontSize:13}} colSpan={1}>{taskRow[0]}</TableCell> | |||
</TableRow> | |||
</TableBody> | |||
</Table> | |||
@@ -287,7 +294,7 @@ const ProjectResourceSummary: React.FC = () => { | |||
<Table size="small" aria-label="tasks"> | |||
<TableBody> | |||
<TableRow> | |||
<TableCell style={{fontSize:10}} colSpan={1}>{taskRow[1]}</TableCell> | |||
<TableCell style={{fontSize:13}} colSpan={1}>{taskRow[1]}</TableCell> | |||
</TableRow> | |||
</TableBody> | |||
</Table> | |||
@@ -300,7 +307,7 @@ const ProjectResourceSummary: React.FC = () => { | |||
<Table size="small" aria-label="tasks"> | |||
<TableBody> | |||
<TableRow> | |||
<TableCell style={{fontSize:10}} colSpan={1}>{taskRow[4].toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</TableCell> | |||
<TableCell style={{fontSize:13}} colSpan={1}>{taskRow[4].toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</TableCell> | |||
</TableRow> | |||
</TableBody> | |||
</Table> | |||
@@ -313,7 +320,7 @@ const ProjectResourceSummary: React.FC = () => { | |||
<Table size="small" aria-label="tasks"> | |||
<TableBody> | |||
<TableRow> | |||
<TableCell style={{fontSize:10}} colSpan={1}>{taskRow[5].toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</TableCell> | |||
<TableCell style={{fontSize:13}} colSpan={1}>{taskRow[5].toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</TableCell> | |||
</TableRow> | |||
</TableBody> | |||
</Table> | |||
@@ -326,7 +333,7 @@ const ProjectResourceSummary: React.FC = () => { | |||
<Table size="small" aria-label="tasks"> | |||
<TableBody> | |||
<TableRow> | |||
<TableCell style={{fontSize:10}} colSpan={1}>{taskRow[6].toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</TableCell> | |||
<TableCell style={{fontSize:13}} colSpan={1}>{taskRow[6].toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</TableCell> | |||
</TableRow> | |||
</TableBody> | |||
</Table> | |||
@@ -339,7 +346,7 @@ const ProjectResourceSummary: React.FC = () => { | |||
<Table size="small" aria-label="tasks"> | |||
<TableBody> | |||
<TableRow> | |||
<TableCell style={{fontSize:10}} colSpan={1}>{taskRow[7].toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</TableCell> | |||
<TableCell style={{fontSize:13}} colSpan={1}>{taskRow[7].toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</TableCell> | |||
</TableRow> | |||
</TableBody> | |||
</Table> | |||
@@ -352,7 +359,7 @@ const ProjectResourceSummary: React.FC = () => { | |||
<Table size="small" aria-label="tasks"> | |||
<TableBody> | |||
<TableRow> | |||
<TableCell style={{fontSize:10}} colSpan={1}>{taskRow[8].toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</TableCell> | |||
<TableCell style={{fontSize:13}} colSpan={1}>{taskRow[8].toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</TableCell> | |||
</TableRow> | |||
</TableBody> | |||
</Table> | |||
@@ -365,7 +372,7 @@ const ProjectResourceSummary: React.FC = () => { | |||
<Table size="small" aria-label="tasks"> | |||
<TableBody> | |||
<TableRow> | |||
<TableCell style={{fontSize:10}} colSpan={1}>{taskRow[9].toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</TableCell> | |||
<TableCell style={{fontSize:13}} colSpan={1}>{taskRow[9].toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</TableCell> | |||
</TableRow> | |||
</TableBody> | |||
</Table> | |||
@@ -378,7 +385,7 @@ const ProjectResourceSummary: React.FC = () => { | |||
<Table size="small" aria-label="tasks"> | |||
<TableBody> | |||
<TableRow> | |||
<TableCell style={{fontSize:10}} colSpan={1}>{taskRow[10].toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</TableCell> | |||
<TableCell style={{fontSize:13}} colSpan={1}>{taskRow[10].toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</TableCell> | |||
</TableRow> | |||
</TableBody> | |||
</Table> | |||
@@ -391,7 +398,7 @@ const ProjectResourceSummary: React.FC = () => { | |||
<Table size="small" aria-label="tasks"> | |||
<TableBody> | |||
<TableRow> | |||
<TableCell style={{fontSize:10}} colSpan={1}>{taskRow[11].toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</TableCell> | |||
<TableCell style={{fontSize:13}} colSpan={1}>{taskRow[11].toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</TableCell> | |||
</TableRow> | |||
</TableBody> | |||
</Table> | |||
@@ -404,7 +411,7 @@ const ProjectResourceSummary: React.FC = () => { | |||
<Table size="small" aria-label="tasks"> | |||
<TableBody> | |||
<TableRow> | |||
<TableCell style={{fontSize:10}} colSpan={1}>{taskRow[12].toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</TableCell> | |||
<TableCell style={{fontSize:13}} colSpan={1}>{taskRow[12].toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</TableCell> | |||
</TableRow> | |||
</TableBody> | |||
</Table> | |||
@@ -417,7 +424,7 @@ const ProjectResourceSummary: React.FC = () => { | |||
<Table size="small" aria-label="tasks"> | |||
<TableBody> | |||
<TableRow> | |||
<TableCell style={{fontSize:10}} colSpan={1}>{taskRow[13].toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</TableCell> | |||
<TableCell style={{fontSize:13}} colSpan={1}>{taskRow[13].toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</TableCell> | |||
</TableRow> | |||
</TableBody> | |||
</Table> | |||
@@ -430,7 +437,7 @@ const ProjectResourceSummary: React.FC = () => { | |||
<Table size="small" aria-label="tasks"> | |||
<TableBody> | |||
<TableRow> | |||
<TableCell style={{fontSize:10}} colSpan={1}>{taskRow[2].toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</TableCell> | |||
<TableCell style={{fontSize:13}} colSpan={1}>{taskRow[2].toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</TableCell> | |||
</TableRow> | |||
</TableBody> | |||
</Table> | |||
@@ -443,7 +450,7 @@ const ProjectResourceSummary: React.FC = () => { | |||
<Table size="small" aria-label="tasks"> | |||
<TableBody> | |||
<TableRow> | |||
<TableCell style={{fontSize:10}} colSpan={1}>{taskRow[3].toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</TableCell> | |||
<TableCell style={{fontSize:13}} colSpan={1}>{taskRow[3].toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</TableCell> | |||
</TableRow> | |||
</TableBody> | |||
</Table> | |||
@@ -666,11 +673,11 @@ const columns2 = [ | |||
</div> | |||
</div> | |||
{/* <div style={{display:"inline-block",width:"99%",marginLeft:10}}> | |||
<CustomDatagrid rows={projectResourcesRows} columns={columns2} columnWidth={200} dataGridHeight={480} pageSize={100} columnGroupingModel={columnGroupingModel} sx={{fontSize:10}}/> | |||
<CustomDatagrid rows={projectResourcesRows} columns={columns2} columnWidth={200} dataGridHeight={480} pageSize={100} columnGroupingModel={columnGroupingModel} sx={{fontSize:13}}/> | |||
</div> */} | |||
{/* <div style={{display:"inline-block",width:"99%",marginLeft:10, marginRight:10, marginTop:10}}> */} | |||
<TableContainer component={Paper}> | |||
<Table sx={{ minWidth: 650 }} aria-label="simple table"> | |||
<Table sx={{ minWidth: 650, maxWidth:1080}} aria-label="simple table"> | |||
<TableHead> | |||
<TableRow> | |||
<TableCell align="center" colSpan={3}> | |||
@@ -697,20 +704,20 @@ const columns2 = [ | |||
</TableRow> | |||
<TableRow> | |||
<TableCell style={{width:"5%"}}/> | |||
<TableCell style={{fontSize:10, width:"20%"}}>Stage</TableCell> | |||
<TableCell style={{fontSize:10, width:"5%"}}>Task Count</TableCell> | |||
<TableCell style={{fontSize:10, width:"5%"}}>Planned</TableCell> | |||
<TableCell style={{fontSize:10, width:"5%"}}>Actual</TableCell> | |||
<TableCell style={{fontSize:10, width:"5%"}}>Planned</TableCell> | |||
<TableCell style={{fontSize:10, width:"5%"}}>Actual</TableCell> | |||
<TableCell style={{fontSize:10, width:"5%"}}>Planned</TableCell> | |||
<TableCell style={{fontSize:10, width:"5%"}}>Actual</TableCell> | |||
<TableCell style={{fontSize:10, width:"5%"}}>Planned</TableCell> | |||
<TableCell style={{fontSize:10, width:"5%"}}>Actual</TableCell> | |||
<TableCell style={{fontSize:10, width:"5%"}}>Planned</TableCell> | |||
<TableCell style={{fontSize:10, width:"5%"}}>Actual</TableCell> | |||
<TableCell style={{fontSize:10, width:"5%"}}>Planned</TableCell> | |||
<TableCell style={{fontSize:10, width:"5%"}}>Actual</TableCell> | |||
<TableCell style={{fontSize:13, minWidth:300}}>Stage</TableCell> | |||
<TableCell style={{fontSize:13, width:"5%"}}>Task Count</TableCell> | |||
<TableCell style={{fontSize:13, width:"5%"}}>Planned</TableCell> | |||
<TableCell style={{fontSize:13, width:"5%"}}>Actual</TableCell> | |||
<TableCell style={{fontSize:13, width:"5%"}}>Planned</TableCell> | |||
<TableCell style={{fontSize:13, width:"5%"}}>Actual</TableCell> | |||
<TableCell style={{fontSize:13, width:"5%"}}>Planned</TableCell> | |||
<TableCell style={{fontSize:13, width:"5%"}}>Actual</TableCell> | |||
<TableCell style={{fontSize:13, width:"5%"}}>Planned</TableCell> | |||
<TableCell style={{fontSize:13, width:"5%"}}>Actual</TableCell> | |||
<TableCell style={{fontSize:13, width:"5%"}}>Planned</TableCell> | |||
<TableCell style={{fontSize:13, width:"5%"}}>Actual</TableCell> | |||
<TableCell style={{fontSize:13, width:"5%"}}>Planned</TableCell> | |||
<TableCell style={{fontSize:13, width:"5%"}}>Actual</TableCell> | |||
</TableRow> | |||
</TableHead> | |||
<TableBody> | |||
@@ -58,6 +58,7 @@ const ProjectResourceSummarySearch: React.FC<Props> = ({ projects }) => { | |||
{ name: "projectCode", label: t("Project Code") }, | |||
{ name: "projectName", label: t("Project Name") }, | |||
{ name: "customerCodeAndName", label: t("Client Code And Name") }, | |||
{ name: "subsidiaryCodeAndName", label: t("Subsidiary Code And Name")} | |||
], | |||
[onTaskClick, t], | |||
// [t], | |||
@@ -8,16 +8,18 @@ import SearchResults, { Column } from "../SearchResults"; | |||
import EditNote from "@mui/icons-material/EditNote"; | |||
import uniq from "lodash/uniq"; | |||
import { useRouter } from "next/navigation"; | |||
import { MAINTAIN_PROJECT } from "@/middleware"; | |||
interface Props { | |||
projects: ProjectResult[]; | |||
projectCategories: ProjectCategory[]; | |||
abilities: string[] | |||
} | |||
type SearchQuery = Partial<Omit<ProjectResult, "id">>; | |||
type SearchParamNames = keyof SearchQuery; | |||
const ProjectSearch: React.FC<Props> = ({ projects, projectCategories }) => { | |||
const ProjectSearch: React.FC<Props> = ({ projects, projectCategories, abilities }) => { | |||
const router = useRouter(); | |||
const { t } = useTranslation("projects"); | |||
@@ -75,6 +77,7 @@ const ProjectSearch: React.FC<Props> = ({ projects, projectCategories }) => { | |||
label: t("Details"), | |||
onClick: onProjectClick, | |||
buttonIcon: <EditNote />, | |||
disabled: !abilities.includes(MAINTAIN_PROJECT), | |||
}, | |||
{ name: "code", label: t("Project Code") }, | |||
{ name: "name", label: t("Project Name") }, | |||
@@ -2,6 +2,7 @@ import { fetchProjectCategories, fetchProjects } from "@/app/api/projects"; | |||
import React from "react"; | |||
import ProjectSearch from "./ProjectSearch"; | |||
import ProjectSearchLoading from "./ProjectSearchLoading"; | |||
import { getUserAbilities } from "@/app/utils/commonUtil"; | |||
interface SubComponents { | |||
Loading: typeof ProjectSearchLoading; | |||
@@ -11,7 +12,9 @@ const ProjectSearchWrapper: React.FC & SubComponents = async () => { | |||
const projectCategories = await fetchProjectCategories(); | |||
const projects = await fetchProjects(); | |||
return <ProjectSearch projects={projects} projectCategories={projectCategories} />; | |||
const abilities = await getUserAbilities() | |||
return <ProjectSearch projects={projects} projectCategories={projectCategories} abilities={abilities}/>; | |||
}; | |||
ProjectSearchWrapper.Loading = ProjectSearchLoading; | |||
@@ -4,26 +4,39 @@ import SearchBox, { Criterion } from "../SearchBox"; | |||
import { useTranslation } from "react-i18next"; | |||
import { ProjectResult } from "@/app/api/projects"; | |||
import { fetchMonthlyWorkHoursReport, fetchProjectCashFlowReport, fetchProjectResourceOverconsumptionReport } from "@/app/api/reports/actions"; | |||
import { downloadFile } from "@/app/utils/commonUtil"; | |||
import { downloadFile, readIntFromString } from "@/app/utils/commonUtil"; | |||
import { BASE_API_URL } from "@/config/api"; | |||
import { ProjectResourceOverconsumptionReportFilter, ProjectResourceOverconsumptionReportRequest } from "@/app/api/reports"; | |||
import { StaffResult } from "@/app/api/staff"; | |||
import { TeamResult } from "@/app/api/team"; | |||
import { Customer } from "@/app/api/customer"; | |||
import { Subsidiary } from "@/app/api/subsidiary"; | |||
interface Props { | |||
team: TeamResult[] | |||
customer: Customer[] | |||
subsidiaries: Subsidiary[] | |||
needAll: boolean | |||
} | |||
type SearchQuery = Partial<Omit<ProjectResourceOverconsumptionReportFilter, "id">>; | |||
type SearchParamNames = keyof SearchQuery; | |||
const ResourceOverconsumptionReport: React.FC<Props> = ({ team, customer }) => { | |||
const ResourceOverconsumptionReport: React.FC<Props> = ({ team, customer, subsidiaries, needAll }) => { | |||
const { t } = useTranslation("report"); | |||
const teamCombo = team.map(t => `${t.name} - ${t.code}`) | |||
const custCombo = customer.map(c => ({label: `${c.name} - ${c.code}`, value: c.id})) | |||
console.log(customer) | |||
const statusCombo = ["Overconsumption", "Potential Overconsumption"] | |||
const teamCombo = team.map(t => `${t.name} - ${t.code}`) | |||
const custCombo = customer.map(c => ({ | |||
value: `custId-${c.id}`, | |||
label: `${c.code} - ${c.name}`, | |||
group: t("Client") | |||
})) | |||
const subsidiariesCombo = subsidiaries.map(sub => ({ | |||
value: `subsidiaryId-${sub.id}`, | |||
label: `${sub.code} - ${sub.name}`, | |||
group: t("Subsidiary") | |||
})) | |||
// const staffCombo = staffs.map(staff => `${staff.name} - ${staff.staffId}`) | |||
// console.log(staffs) | |||
@@ -34,14 +47,14 @@ const ResourceOverconsumptionReport: React.FC<Props> = ({ team, customer }) => { | |||
paramName: "team", | |||
type: "select", | |||
options: teamCombo, | |||
needAll: true | |||
needAll: needAll | |||
}, | |||
{ | |||
label: t("Client"), | |||
paramName: "customer", | |||
type: "autocomplete", | |||
options: custCombo, | |||
needAll: true | |||
options: [...subsidiariesCombo, ...custCombo], | |||
// needAll: true | |||
}, | |||
{ | |||
label: t("Status"), | |||
@@ -51,7 +64,7 @@ const ResourceOverconsumptionReport: React.FC<Props> = ({ team, customer }) => { | |||
needAll: true | |||
}, | |||
{ | |||
label: t("lowerLimit"), | |||
label: t("Potential Overconsumption Threshold"), | |||
paramName: "lowerLimit", | |||
type: "number", | |||
}, | |||
@@ -65,6 +78,7 @@ return ( | |||
formType={"download"} | |||
criteria={searchCriteria} | |||
onSearch={async (query: any) => { | |||
const [custType, id] = readIntFromString(query.customer) as [string, number] | |||
let index = 0 | |||
let postData: ProjectResourceOverconsumptionReportRequest = { | |||
status: "All", | |||
@@ -73,13 +87,13 @@ return ( | |||
if (query.team.length > 0 && query.team.toLocaleLowerCase() !== "all") { | |||
index = teamCombo.findIndex(team => team === query.team) | |||
postData.teamId = team[index].id | |||
} | |||
if (typeof query.customer === "string" && query.customer.toLocaleLowerCase() !== "all") { | |||
postData.custId = query.customer | |||
} | |||
if (Boolean(query.lowerLimit)) { | |||
postData.lowerLimit = query.lowerLimit/100 | |||
} | |||
if (id) { | |||
postData[custType] = id | |||
} | |||
postData.status = query.status | |||
console.log(postData) | |||
const response = await fetchProjectResourceOverconsumptionReport(postData) | |||
@@ -1,20 +1,45 @@ | |||
import React from "react"; | |||
import ResourceOvercomsumptionReportLoading from "./ResourceOverconsumptionReportLoading"; | |||
import ResourceOverconsumptionReport from "./ResourceOverconsumptionReport"; | |||
import { fetchAllCustomers } from "@/app/api/customer"; | |||
import { fetchTeam } from "@/app/api/team"; | |||
import { fetchAllCustomers } from "@/app/api/customer"; | |||
import { fetchAllSubsidiaries } from "@/app/api/subsidiary"; | |||
import { getServerSession } from "next-auth"; | |||
import { authOptions } from "@/config/authConfig"; | |||
import { TEAM_LEAD } from "@/middleware"; | |||
interface SubComponents { | |||
Loading: typeof ResourceOvercomsumptionReportLoading; | |||
} | |||
const ResourceOvercomsumptionReportWrapper: React.FC & SubComponents = async () => { | |||
const customers = await fetchAllCustomers() | |||
const teams = await fetchTeam () | |||
const ResourceOvercomsumptionReportWrapper: React.FC & | |||
SubComponents = async () => { | |||
const session: any = await getServerSession(authOptions); | |||
const teamId = session.staff?.team.id; | |||
const role = session.role; | |||
let needAll = true; | |||
let teams = await fetchTeam(); | |||
const [customers, subsidiaries] = await Promise.all([ | |||
fetchAllCustomers(), | |||
fetchAllSubsidiaries(), | |||
]); | |||
if (role === TEAM_LEAD) { | |||
needAll = false; | |||
teams = teams.filter((team) => team.id === teamId); | |||
} | |||
return <ResourceOverconsumptionReport team={teams} customer={customers}/>; | |||
return ( | |||
<ResourceOverconsumptionReport | |||
team={teams} | |||
customer={customers} | |||
subsidiaries={subsidiaries} | |||
needAll={needAll} | |||
/> | |||
); | |||
}; | |||
ResourceOvercomsumptionReportWrapper.Loading = ResourceOvercomsumptionReportLoading; | |||
ResourceOvercomsumptionReportWrapper.Loading = | |||
ResourceOvercomsumptionReportLoading; | |||
export default ResourceOvercomsumptionReportWrapper; | |||
export default ResourceOvercomsumptionReportWrapper; |
@@ -32,6 +32,7 @@ interface BaseColumn<T extends ResultWithId> { | |||
interface ColumnWithAction<T extends ResultWithId> extends BaseColumn<T> { | |||
onClick: (item: T) => void; | |||
buttonIcon: React.ReactNode; | |||
disabled?: boolean; | |||
} | |||
export type Column<T extends ResultWithId> = | |||
@@ -101,6 +102,7 @@ function SearchResults<T extends ResultWithId>({ | |||
<IconButton | |||
color={column.color ?? "primary"} | |||
onClick={() => column.onClick(item)} | |||
disabled={Boolean(column.disabled)} | |||
> | |||
{column.buttonIcon} | |||
</IconButton> | |||
@@ -20,6 +20,8 @@ import { ProjectWithTasks } from "@/app/api/projects"; | |||
import { | |||
LeaveEntry, | |||
TimeEntry, | |||
deleteMemberEntry, | |||
deleteMemberLeave, | |||
saveMemberEntry, | |||
saveMemberLeave, | |||
} from "@/app/api/timesheets/actions"; | |||
@@ -29,6 +31,8 @@ import TimesheetEditModal, { | |||
import { Props as LeaveEditModalProps } from "../LeaveTable/LeaveEditModal"; | |||
import LeaveEditModal from "../LeaveTable/LeaveEditModal"; | |||
import dayjs from "dayjs"; | |||
import { checkTotalHours } from "@/app/api/timesheets/utils"; | |||
import unionBy from "lodash/unionBy"; | |||
export interface Props { | |||
leaveTypes: LeaveType[]; | |||
@@ -119,13 +123,30 @@ const TimesheetAmendment: React.FC<Props> = ({ | |||
const openEditModal = useCallback( | |||
(defaultValues?: TimeEntry, recordDate?: string, isHoliday?: boolean) => { | |||
setEditModalProps({ | |||
defaultValues, | |||
defaultValues: defaultValues ? { ...defaultValues } : undefined, | |||
recordDate, | |||
isHoliday, | |||
onDelete: defaultValues | |||
? async () => { | |||
const intStaffId = parseInt(selectedStaff.id); | |||
const newMemberTimesheets = await deleteMemberEntry({ | |||
staffId: intStaffId, | |||
entryId: defaultValues.id, | |||
}); | |||
setLocalTeamTimesheets((timesheets) => ({ | |||
...timesheets, | |||
[intStaffId]: { | |||
...timesheets[intStaffId], | |||
timeEntries: newMemberTimesheets, | |||
}, | |||
})); | |||
setEditModalOpen(false); | |||
} | |||
: undefined, | |||
}); | |||
setEditModalOpen(true); | |||
}, | |||
[], | |||
[selectedStaff.id], | |||
); | |||
const closeEditModal = useCallback(() => { | |||
@@ -141,13 +162,30 @@ const TimesheetAmendment: React.FC<Props> = ({ | |||
const openLeaveEditModal = useCallback( | |||
(defaultValues?: LeaveEntry, recordDate?: string, isHoliday?: boolean) => { | |||
setLeaveEditModalProps({ | |||
defaultValues, | |||
defaultValues: defaultValues ? { ...defaultValues } : undefined, | |||
recordDate, | |||
isHoliday, | |||
onDelete: defaultValues | |||
? async () => { | |||
const intStaffId = parseInt(selectedStaff.id); | |||
const newMemberLeaves = await deleteMemberLeave({ | |||
staffId: intStaffId, | |||
entryId: defaultValues.id, | |||
}); | |||
setLocalTeamLeaves((leaves) => ({ | |||
...leaves, | |||
[intStaffId]: { | |||
...leaves[intStaffId], | |||
leaveEntries: newMemberLeaves, | |||
}, | |||
})); | |||
setLeaveEditModalOpen(false); | |||
} | |||
: undefined, | |||
}); | |||
setLeaveEditModalOpen(true); | |||
}, | |||
[], | |||
[selectedStaff.id], | |||
); | |||
const closeLeaveEditModal = useCallback(() => { | |||
@@ -260,10 +298,44 @@ const TimesheetAmendment: React.FC<Props> = ({ | |||
[companyHolidays, openEditModal], | |||
); | |||
const checkTotalHoursForDate = useCallback( | |||
(newEntry: TimeEntry | LeaveEntry, date?: string) => { | |||
if (!date) { | |||
throw Error("Invalid date"); | |||
} | |||
const intStaffId = parseInt(selectedStaff.id); | |||
const leaves = localTeamLeaves[intStaffId].leaveEntries[date] || []; | |||
const timesheets = | |||
localTeamTimesheets[intStaffId].timeEntries[date] || []; | |||
let totalHourError; | |||
if ((newEntry as LeaveEntry).leaveTypeId) { | |||
// newEntry is a leave entry | |||
const leavesWithNewEntry = unionBy( | |||
[newEntry as LeaveEntry], | |||
leaves, | |||
"id", | |||
); | |||
totalHourError = checkTotalHours(timesheets, leavesWithNewEntry); | |||
} else { | |||
// newEntry is a timesheet entry | |||
const timesheetsWithNewEntry = unionBy( | |||
[newEntry as TimeEntry], | |||
timesheets, | |||
"id", | |||
); | |||
totalHourError = checkTotalHours(timesheetsWithNewEntry, leaves); | |||
} | |||
if (totalHourError) throw Error(totalHourError); | |||
}, | |||
[localTeamLeaves, localTeamTimesheets, selectedStaff.id], | |||
); | |||
const handleSave = useCallback( | |||
async (timeEntry: TimeEntry, recordDate?: string) => { | |||
// TODO: should be fine, but can handle parse error | |||
const intStaffId = parseInt(selectedStaff.id); | |||
checkTotalHoursForDate(timeEntry, recordDate); | |||
const newMemberTimesheets = await saveMemberEntry({ | |||
staffId: intStaffId, | |||
entry: timeEntry, | |||
@@ -278,12 +350,13 @@ const TimesheetAmendment: React.FC<Props> = ({ | |||
})); | |||
setEditModalOpen(false); | |||
}, | |||
[selectedStaff.id], | |||
[checkTotalHoursForDate, selectedStaff.id], | |||
); | |||
const handleSaveLeave = useCallback( | |||
async (leaveEntry: LeaveEntry, recordDate?: string) => { | |||
const intStaffId = parseInt(selectedStaff.id); | |||
checkTotalHoursForDate(leaveEntry, recordDate); | |||
const newMemberLeaves = await saveMemberLeave({ | |||
staffId: intStaffId, | |||
recordDate, | |||
@@ -298,7 +371,7 @@ const TimesheetAmendment: React.FC<Props> = ({ | |||
})); | |||
setLeaveEditModalOpen(false); | |||
}, | |||
[selectedStaff.id], | |||
[checkTotalHoursForDate, selectedStaff.id], | |||
); | |||
return ( | |||
@@ -328,7 +328,7 @@ const EntryInputTable: React.FC<Props> = ({ | |||
const content = <GridEditInputCell {...params} />; | |||
return errorMessage ? ( | |||
<Tooltip title={t(errorMessage, { DAILY_NORMAL_MAX_HOURS })}> | |||
{content} | |||
<Box width="100%">{content}</Box> | |||
</Tooltip> | |||
) : ( | |||
content | |||
@@ -352,7 +352,9 @@ const EntryInputTable: React.FC<Props> = ({ | |||
params.row._error?.[params.field as keyof TimeEntry]; | |||
const content = <GridEditInputCell {...params} />; | |||
return errorMessage ? ( | |||
<Tooltip title={t(errorMessage)}>{content}</Tooltip> | |||
<Tooltip title={t(errorMessage)}> | |||
<Box width="100%">{content}</Box> | |||
</Tooltip> | |||
) : ( | |||
content | |||
); | |||
@@ -375,7 +377,9 @@ const EntryInputTable: React.FC<Props> = ({ | |||
params.row._error?.[params.field as keyof TimeEntry]; | |||
const content = <GridEditInputCell {...params} />; | |||
return errorMessage ? ( | |||
<Tooltip title={t(errorMessage)}>{content}</Tooltip> | |||
<Tooltip title={t(errorMessage)}> | |||
<Box width="100%">{content}</Box> | |||
</Tooltip> | |||
) : ( | |||
content | |||
); | |||
@@ -207,7 +207,7 @@ const FastTimeEntryModal: React.FC<Props> = ({ | |||
validate: (value) => { | |||
if (value) { | |||
if (isHoliday) { | |||
return t("Cannot input normal hours for holidays"); | |||
return t("Cannot input normal hours on holidays"); | |||
} | |||
return ( | |||
@@ -60,9 +60,9 @@ const MobileTimesheetEntry: React.FC<Props> = ({ | |||
const openEditModal = useCallback( | |||
(defaultValues?: TimeEntry) => () => { | |||
setEditModalProps({ | |||
defaultValues, | |||
defaultValues: defaultValues ? { ...defaultValues } : undefined, | |||
onDelete: defaultValues | |||
? () => { | |||
? async () => { | |||
setValue( | |||
date, | |||
currentEntries.filter((entry) => entry.id !== defaultValues.id), | |||
@@ -27,7 +27,7 @@ import { DAILY_NORMAL_MAX_HOURS } from "@/app/api/timesheets/utils"; | |||
export interface Props extends Omit<ModalProps, "children"> { | |||
onSave: (timeEntry: TimeEntry, recordDate?: string) => Promise<void>; | |||
onDelete?: () => void; | |||
onDelete?: () => Promise<void>; | |||
defaultValues?: Partial<TimeEntry>; | |||
allProjects: ProjectWithTasks[]; | |||
assignedProjects: AssignedProject[]; | |||
@@ -94,6 +94,7 @@ const TimesheetEditModal: React.FC<Props> = ({ | |||
getValues, | |||
setValue, | |||
trigger, | |||
setError, | |||
formState, | |||
watch, | |||
} = useForm<TimeEntry>(); | |||
@@ -105,10 +106,16 @@ const TimesheetEditModal: React.FC<Props> = ({ | |||
const saveHandler = useCallback(async () => { | |||
const valid = await trigger(); | |||
if (valid) { | |||
await onSave(getValues(), recordDate); | |||
reset({ id: Date.now() }); | |||
try { | |||
await onSave(getValues(), recordDate); | |||
reset({ id: Date.now() }); | |||
} catch (e) { | |||
setError("root", { | |||
message: e instanceof Error ? e.message : "Unknown error", | |||
}); | |||
} | |||
} | |||
}, [getValues, onSave, recordDate, reset, trigger]); | |||
}, [getValues, onSave, recordDate, reset, setError, trigger]); | |||
const closeHandler = useCallback<NonNullable<ModalProps["onClose"]>>( | |||
(...args) => { | |||
@@ -227,7 +234,7 @@ const TimesheetEditModal: React.FC<Props> = ({ | |||
validate: (value) => { | |||
if (value) { | |||
if (isHoliday) { | |||
return t("Cannot input normal hours for holidays"); | |||
return t("Cannot input normal hours on holidays"); | |||
} | |||
return ( | |||
@@ -268,6 +275,11 @@ const TimesheetEditModal: React.FC<Props> = ({ | |||
})} | |||
helperText={formState.errors.remark?.message} | |||
/> | |||
{formState.errors.root?.message && ( | |||
<Typography variant="caption" color="error"> | |||
{t(formState.errors.root.message, { DAILY_NORMAL_MAX_HOURS })} | |||
</Typography> | |||
)} | |||
<Box display="flex" justifyContent="flex-end" gap={1}> | |||
{onDelete && ( | |||
<Button | |||
@@ -3,7 +3,9 @@ import CredentialsProvider from "next-auth/providers/credentials"; | |||
import { LOGIN_API_PATH } from "./api"; | |||
export interface SessionWithTokens extends Session { | |||
abilities?: any[]; | |||
staff?: any; | |||
role?: String; | |||
abilities?: string[]; | |||
accessToken?: string; | |||
refreshToken?: string; | |||
} | |||
@@ -52,12 +54,14 @@ export const authOptions: AuthOptions = { | |||
session({ session, token }) { | |||
const sessionWithToken: SessionWithTokens = { | |||
...session, | |||
role: token.role as String, | |||
// Add the data from the token to the session | |||
abilities: (token.abilities as ability[]).map( | |||
(item: ability) => item.actionSubjectCombo, | |||
) as string[], | |||
accessToken: token.accessToken as string | undefined, | |||
refreshToken: token.refreshToken as string | undefined, | |||
staff: token.staff as any | |||
}; | |||
// console.log(sessionWithToken) | |||
return sessionWithToken; | |||
@@ -1,6 +1,6 @@ | |||
{ | |||
"Number Of Days": "Number Of Days", | |||
"Project Completion (<= %)": "Project Completion (<= %)", | |||
"Days until current stage end": "Days until current stage end", | |||
"Resource Utilization Percentage (<= %)": "Resource Utilization Percentage (<= %)", | |||
"Project": "Project", | |||
"Date Type": "Date Type", | |||
@@ -2,8 +2,8 @@ | |||
"Staff Monthly Work Hours Analysis Report": "Staff Monthly Work Hours Analysis Report", | |||
"Project Resource Overconsumption Report": "Project Resource Overconsumption Report", | |||
"Number Of Days": "天數", | |||
"Project Completion (<= %)": "項目完成度 (<= %)", | |||
"Days until current stage end": "當前階段結束剩餘天數", | |||
"Resource Utilization Percentage (<= %)": "資源利用率百分比 (<= %)", | |||
"Project": "項目", | |||
"Date Type": "日期類型", | |||
@@ -3,6 +3,21 @@ import { ability, authOptions } from "@/config/authConfig"; | |||
import { NextFetchEvent, NextResponse } from "next/server"; | |||
import { getToken } from "next-auth/jwt"; | |||
// user groups | |||
export const [ | |||
SUPER_ADMIN, | |||
TOP_MANAGEMENT, | |||
TEAM_LEAD, | |||
NORMAL_STAFF, | |||
SUPPORTING_STAFF | |||
] = [ | |||
"Super Admin", | |||
"Top Management", | |||
"Team Leader", | |||
"Normal Staff", | |||
"Supporting Staff" | |||
] | |||
// abilities | |||
export const [ | |||
VIEW_USER, | |||
@@ -23,6 +38,7 @@ export const [ | |||
MAINTAIN_TIMESHEET_7DAYS, | |||
VIEW_PROJECT, | |||
MAINTAIN_PROJECT, | |||
DELETE_PROJECT, | |||
] = [ | |||
'VIEW_USER', | |||
'MAINTAIN_USER', | |||
@@ -41,7 +57,8 @@ export const [ | |||
'MAINTAIN_TASK_TEMPLATE', | |||
'MAINTAIN_TIMESHEET_7DAYS', | |||
'VIEW_PROJECT', | |||
'MAINTAIN_PROJECT' | |||
'MAINTAIN_PROJECT', | |||
'DELETE_PROJECT' | |||
] | |||
const PRIVATE_ROUTES = [ | |||
@@ -61,7 +78,7 @@ export default async function middleware( | |||
event: NextFetchEvent, | |||
) { | |||
const langPref = req.nextUrl.searchParams.get(LANG_QUERY_PARAM); | |||
const token = await getToken({ req: req, secret: process.env.SECRET }); | |||
// const token = await getToken({ req: req, secret: process.env.SECRET }); | |||
if (langPref) { | |||
// Redirect to same url without the lang query param + set cookies | |||
const newUrl = new URL(req.nextUrl); | |||
@@ -80,6 +97,15 @@ export default async function middleware( | |||
return Boolean(token) | |||
} | |||
const abilities = (token!.abilities as ability[]).map((item: ability) => item.actionSubjectCombo); | |||
if (req.nextUrl.pathname.startsWith('/projects')) { | |||
isAuth = [MAINTAIN_PROJECT].some((ability) => abilities.includes(ability)); | |||
} | |||
if (req.nextUrl.pathname.startsWith('/tasks')) { | |||
isAuth = [MAINTAIN_TASK_TEMPLATE].some((ability) => abilities.includes(ability)); | |||
} | |||
if (req.nextUrl.pathname.startsWith('/settings')) { | |||
isAuth = [VIEW_MASTERDATA, MAINTAIN_MASTERDATA].some((ability) => abilities.includes(ability)); | |||
} | |||