Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

feat: employee time clock with breaks, flags, and overtime (#584)

Chase Foster3b904b1dc113
diff --git a/apps/erp/app/components/TimeCardWarning.tsx b/apps/erp/app/components/TimeCardWarning.tsx
new file mode 100644
index 0000000000..7938c984d0
--- /dev/null
+++ b/apps/erp/app/components/TimeCardWarning.tsx
@@ -0,0 +1,148 @@
+"use client";
+
+import {
+ Button,
+ Input,
+ Modal,
+ ModalBody,
+ ModalContent,
+ ModalDescription,
+ ModalFooter,
+ ModalHeader,
+ ModalTitle,
+ toast,
+ VStack
+} from "@carbon/react";
+import { useEffect, useState } from "react";
+import { useFetcher } from "react-router";
+import { path } from "~/utils/path";
+
+const TWELVE_HOURS_MS = 12 * 60 * 60 * 1000;
+const CHECK_INTERVAL_MS = 5 * 60 * 1000;
+const CLOCK_STORAGE_KEY = "timeclock-warning-ack";
+
+type TimeCardWarningProps = {
+ openClockEntry: {
+ id: string;
+ clockIn: string;
+ } | null;
+};
+
+export function TimeCardWarning({ openClockEntry }: TimeCardWarningProps) {
+ const [showClockWarning, setShowClockWarning] = useState(false);
+ const [editClockOut, setEditClockOut] = useState("");
+ const fetcher = useFetcher();
+
+ useEffect(() => {
+ if (!openClockEntry) {
+ setShowClockWarning(false);
+ return;
+ }
+
+ const checkStale = () => {
+ const elapsed = Date.now() - new Date(openClockEntry.clockIn).getTime();
+ if (elapsed < TWELVE_HOURS_MS) {
+ setShowClockWarning(false);
+ return;
+ }
+
+ const acked = sessionStorage.getItem(CLOCK_STORAGE_KEY);
+ if (acked === openClockEntry.id) {
+ setShowClockWarning(false);
+ return;
+ }
+
+ setShowClockWarning(true);
+ };
+
+ checkStale();
+ const interval = setInterval(checkStale, CHECK_INTERVAL_MS);
+ return () => clearInterval(interval);
+ }, [openClockEntry]);
+
+ useEffect(() => {
+ if (fetcher.data && fetcher.state === "idle") {
+ if ((fetcher.data as { success?: boolean }).success) {
+ toast.success("Updated successfully");
+ setShowClockWarning(false);
+ }
+ }
+ }, [fetcher.data, fetcher.state]);
+
+ const handleClockAcknowledge = () => {
+ if (openClockEntry) {
+ sessionStorage.setItem(CLOCK_STORAGE_KEY, openClockEntry.id);
+ }
+ setShowClockWarning(false);
+ };
+
+ const handleEditClockOut = () => {
+ if (!editClockOut || !openClockEntry) return;
+ const formData = new FormData();
+ formData.append("intent", "clockOut");
+ formData.append("clockOut", new Date(editClockOut).toISOString());
+ fetcher.submit(formData, {
+ method: "post",
+ action: path.to.api.timecard
+ });
+ };
+
+ if (showClockWarning && openClockEntry) {
+ const hoursElapsed = Math.floor(
+ (Date.now() - new Date(openClockEntry.clockIn).getTime()) / 3600000
+ );
+
+ return (
+ <Modal
+ open
+ onOpenChange={() => {
+ /* intentionally non-dismissable */
+ }}
+ >
+ <ModalContent>
+ <ModalHeader>
+ <ModalTitle>Forgot to Clock Out?</ModalTitle>
+ <ModalDescription>
+ You&apos;ve been clocked in for {hoursElapsed} hours. Did you
+ forget to clock out?
+ </ModalDescription>
+ </ModalHeader>
+ <ModalBody>
+ <VStack spacing={4}>
+ <p className="text-sm text-muted-foreground">
+ You clocked in at{" "}
+ {new Date(openClockEntry.clockIn).toLocaleString()}. You can
+ edit your clock-out time below or acknowledge that you&apos;re
+ still working.
+ </p>
+ <div className="flex flex-col gap-2">
+ <label className="text-sm font-medium">
+ Set clock-out time
+ </label>
+ <Input
+ type="datetime-local"
+ value={editClockOut}
+ onChange={(e) => setEditClockOut(e.target.value)}
+ />
+ </div>
+ </VStack>
+ </ModalBody>
+ <ModalFooter>
+ <Button variant="secondary" onClick={handleClockAcknowledge}>
+ I&apos;m Still Working
+ </Button>
+ <Button
+ onClick={handleEditClockOut}
+ isDisabled={!editClockOut || fetcher.state !== "idle"}
+ isLoading={fetcher.state !== "idle"}
+ >
+ Set Clock Out
+ </Button>
+ </ModalFooter>
+ </ModalContent>
+ </Modal>
+ );
+ }
+
+ return null;
+}
diff --git a/apps/erp/app/modules/people/people.models.ts b/apps/erp/app/modules/people/people.models.ts
index a948720520..16d1ab47f8 100644
--- a/apps/erp/app/modules/people/people.models.ts
+++ b/apps/erp/app/modules/people/people.models.ts
@@ -65,3 +65,35 @@ export const shiftValidator = z.object({
saturday: zfd.checkbox(),
sunday: zfd.checkbox()
});
+
+export const clockInValidator = z.object({
+ intent: z.literal("clockIn"),
+ employeeId: zfd.text(z.string().optional())
+});
+
+export const clockOutValidator = z.object({
+ intent: z.literal("clockOut"),
+ employeeId: zfd.text(z.string().optional()),
+ note: zfd.text(z.string().optional())
+});
+
+export const timecardValidator = z.object({
+ id: zfd.text(z.string().optional()),
+ employeeId: z.string().min(1, { message: "Employee is required" }),
+ clockIn: z.string().min(1, { message: "Clock in is required" }),
+ clockOut: zfd.text(z.string().optional()),
+ note: zfd.text(z.string().optional())
+});
+
+export const updateTimeCardEntryValidator = z.object({
+ intent: z.literal("updateEntry"),
+ entryId: z.string().min(1),
+ clockIn: z.string().min(1),
+ clockOut: zfd.text(z.string().optional()),
+ note: zfd.text(z.string().optional())
+});
+
+export const deleteTimeCardEntryValidator = z.object({
+ intent: z.literal("deleteEntry"),
+ entryId: z.string().min(1)
+});
diff --git a/apps/erp/app/modules/people/people.service.ts b/apps/erp/app/modules/people/people.service.ts
index 92fca79b42..b89b22f7ce 100644
--- a/apps/erp/app/modules/people/people.service.ts
+++ b/apps/erp/app/modules/people/people.service.ts
@@ -619,3 +619,259 @@ export async function upsertShift(
}
return client.from("shift").update(sanitize(shift)).eq("id", shift.id);
}
+
+export async function clockIn(
+ client: SupabaseClient<Database>,
+ args: {
+ employeeId: string;
+ companyId: string;
+ createdBy: string;
+ }
+) {
+ const existing = await getOpenClockEntry(
+ client,
+ args.employeeId,
+ args.companyId
+ );
+ if (existing.data) {
+ return { data: null, error: { message: "Already clocked in" } };
+ }
+
+ return client.from("timeCardEntry").insert({
+ employeeId: args.employeeId,
+ companyId: args.companyId,
+ createdBy: args.createdBy
+ });
+}
+
+export async function clockOut(
+ client: SupabaseClient<Database>,
+ args: {
+ employeeId: string;
+ companyId: string;
+ updatedBy: string;
+ clockOut?: string;
+ note?: string;
+ }
+) {
+ const open = await getOpenClockEntry(client, args.employeeId, args.companyId);
+ if (!open.data) {
+ return { data: null, error: { message: "Not currently clocked in" } };
+ }
+
+ return client
+ .from("timeCardEntry")
+ .update(
+ sanitize({
+ clockOut: args.clockOut ?? new Date().toISOString(),
+ note: args.note,
+ updatedBy: args.updatedBy,
+ updatedAt: new Date().toISOString()
+ })
+ )
+ .eq("id", open.data.id);
+}
+
+export async function createTimeCardEntry(
+ client: SupabaseClient<Database>,
+ entry: {
+ employeeId: string;
+ companyId: string;
+ clockIn: string;
+ clockOut?: string | null;
+ note?: string | null;
+ createdBy: string;
+ }
+) {
+ return client
+ .from("timeCardEntry")
+ .insert(sanitize(entry))
+ .select("id")
+ .single();
+}
+
+export async function deleteTimeCardEntry(
+ client: SupabaseClient<Database>,
+ entryId: string
+) {
+ return client.from("timeCardEntry").delete().eq("id", entryId);
+}
+
+export async function getClockedInEmployees(
+ client: SupabaseClient<Database>,
+ companyId: string
+) {
+ return client
+ .from("timeCardEntries")
+ .select("*")
+ .eq("companyId", companyId)
+ .is("clockOut", null)
+ .order("clockIn", { ascending: true });
+}
+
+export async function getOpenClockEntry(
+ client: SupabaseClient<Database>,
+ employeeId: string,
+ companyId: string
+) {
+ return client
+ .from("timeCardEntry")
+ .select("*")
+ .eq("employeeId", employeeId)
+ .eq("companyId", companyId)
+ .is("clockOut", null)
+ .maybeSingle();
+}
+
+export async function getRecentTimecards(
+ client: SupabaseClient<Database>,
+ companyId: string
+) {
+ return client
+ .from("timeCardEntries")
+ .select("*")
+ .eq("companyId", companyId)
+ .order("clockIn", { ascending: false })
+ .limit(100);
+}
+
+export async function getScheduledEmployeesToday(
+ client: SupabaseClient<Database>,
+ companyId: string
+) {
+ const { data } = await client
+ .from("employeeJob")
+ .select(
+ "id, shiftId, shift:shift(id, name, startTime, endTime, sunday, monday, tuesday, wednesday, thursday, friday, saturday)"
+ )
+ .eq("companyId", companyId)
+ .not("shiftId", "is", null);
+
+ if (!data) return [];
+
+ const dayNames = [
+ "sunday",
+ "monday",
+ "tuesday",
+ "wednesday",
+ "thursday",
+ "friday",
+ "saturday"
+ ] as const;
+ const today = dayNames[new Date().getDay()];
+
+ return data.filter((ej) => {
+ const shift = ej.shift as Record<string, unknown> | null;
+ return shift && shift[today] === true;
+ });
+}
+
+export async function getTimeCardEntry(
+ client: SupabaseClient<Database>,
+ entryId: string
+) {
+ return client.from("timeCardEntry").select("*").eq("id", entryId).single();
+}
+
+export async function getTimeCardEntries(
+ client: SupabaseClient<Database>,
+ args: {
+ employeeId: string;
+ companyId: string;
+ from?: string;
+ to?: string;
+ }
+) {
+ let query = client
+ .from("timeCardEntry")
+ .select("*")
+ .eq("employeeId", args.employeeId)
+ .eq("companyId", args.companyId)
+ .order("clockIn", { ascending: false });
+
+ if (args.from) {
+ query = query.gte("clockIn", args.from);
+ }
+ if (args.to) {
+ query = query.lte("clockIn", args.to);
+ }
+
+ return query;
+}
+
+export async function getTimecardEntries(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ args: GenericQueryFilters & { search: string | null }
+) {
+ let query = client
+ .from("timeCardEntries")
+ .select("*", { count: "exact" })
+ .eq("companyId", companyId);
+
+ if (args.search) {
+ query = query.or(
+ `firstName.ilike.%${args.search}%,lastName.ilike.%${args.search}%`
+ );
+ }
+
+ query = setGenericQueryFilters(query, args, [
+ { column: "clockIn", ascending: false }
+ ]);
+
+ return query;
+}
+
+export async function getWeeklyHoursForEmployees(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ employeeIds: string[]
+): Promise<Record<string, number>> {
+ const now = new Date();
+ const dayOfWeek = now.getDay();
+ const monday = new Date(now);
+ monday.setDate(now.getDate() - ((dayOfWeek + 6) % 7));
+ monday.setHours(0, 0, 0, 0);
+
+ const { data: entries } = await client
+ .from("timeCardEntry")
+ .select("employeeId, clockIn, clockOut")
+ .eq("companyId", companyId)
+ .in("employeeId", employeeIds)
+ .gte("clockIn", monday.toISOString());
+
+ const weeklyMs: Record<string, number> = {};
+ for (const entry of entries ?? []) {
+ const end = entry.clockOut
+ ? new Date(entry.clockOut).getTime()
+ : Date.now();
+ const ms = end - new Date(entry.clockIn).getTime();
+ weeklyMs[entry.employeeId] = (weeklyMs[entry.employeeId] ?? 0) + ms;
+ }
+
+ return weeklyMs;
+}
+
+export async function updateTimeCardEntry(
+ client: SupabaseClient<Database>,
+ args: {
+ entryId: string;
+ clockIn?: string;
+ clockOut?: string | null;
+ note?: string | null;
+ updatedBy: string;
+ }
+) {
+ return client
+ .from("timeCardEntry")
+ .update(
+ sanitize({
+ clockIn: args.clockIn,
+ clockOut: args.clockOut,
+ note: args.note,
+ updatedBy: args.updatedBy,
+ updatedAt: new Date().toISOString()
+ })
+ )
+ .eq("id", args.entryId);
+}
diff --git a/apps/erp/app/modules/people/ui/Person/PersonSidebar/PersonSidebar.tsx b/apps/erp/app/modules/people/ui/Person/PersonSidebar/PersonSidebar.tsx
index c28fce134f..3d51fb08db 100644
--- a/apps/erp/app/modules/people/ui/Person/PersonSidebar/PersonSidebar.tsx
+++ b/apps/erp/app/modules/people/ui/Person/PersonSidebar/PersonSidebar.tsx
@@ -4,10 +4,14 @@ import { usePersonSidebar } from "./usePersonSidebar";
type PersonSidebarProps = {
attributeCategories: PublicAttributes[];
+ timeCardEnabled?: boolean;
};
-const PersonSidebar = ({ attributeCategories }: PersonSidebarProps) => {
- const links = usePersonSidebar(attributeCategories);
+const PersonSidebar = ({
+ attributeCategories,
+ timeCardEnabled
+}: PersonSidebarProps) => {
+ const links = usePersonSidebar(attributeCategories, timeCardEnabled);
return <DetailSidebar links={links} />;
};
diff --git a/apps/erp/app/modules/people/ui/Person/PersonSidebar/usePersonSidebar.tsx b/apps/erp/app/modules/people/ui/Person/PersonSidebar/usePersonSidebar.tsx
index b5bf238a6d..d97ff94c87 100644
--- a/apps/erp/app/modules/people/ui/Person/PersonSidebar/usePersonSidebar.tsx
+++ b/apps/erp/app/modules/people/ui/Person/PersonSidebar/usePersonSidebar.tsx
@@ -1,7 +1,16 @@
-import { LuHardHat, LuList, LuStickyNote, LuUser } from "react-icons/lu";
+import {
+ LuClock,
+ LuHardHat,
+ LuList,
+ LuStickyNote,
+ LuUser
+} from "react-icons/lu";
import type { PublicAttributes } from "~/modules/account";
-export function usePersonSidebar(attributeCategories: PublicAttributes[]) {
+export function usePersonSidebar(
+ attributeCategories: PublicAttributes[],
+ timeCardEnabled?: boolean
+) {
const baseLinks = [
{
name: "Profile",
@@ -17,7 +26,16 @@ export function usePersonSidebar(attributeCategories: PublicAttributes[]) {
name: "Notes",
to: "notes",
icon: <LuStickyNote />
- }
+ },
+ ...(timeCardEnabled
+ ? [
+ {
+ name: "Timecards",
+ to: "timecard",
+ icon: <LuClock />
+ }
+ ]
+ : [])
];
const categoryLinks = attributeCategories.map((category) => ({
diff --git a/apps/erp/app/modules/people/ui/Timecards/TimecardForm.tsx b/apps/erp/app/modules/people/ui/Timecards/TimecardForm.tsx
new file mode 100644
index 0000000000..36f1e7ebc1
--- /dev/null
+++ b/apps/erp/app/modules/people/ui/Timecards/TimecardForm.tsx
@@ -0,0 +1,117 @@
+import { TextArea, ValidatedForm } from "@carbon/form";
+import {
+ Button,
+ Drawer,
+ DrawerBody,
+ DrawerContent,
+ DrawerFooter,
+ DrawerHeader,
+ DrawerTitle,
+ HStack,
+ VStack
+} from "@carbon/react";
+import type { CalendarDateTime } from "@internationalized/date";
+import {
+ getLocalTimeZone,
+ now,
+ parseAbsolute,
+ toCalendarDateTime
+} from "@internationalized/date";
+import { useState } from "react";
+import { useNavigate } from "react-router";
+import type { z } from "zod";
+import { DateTimePicker, Employee, Hidden, Submit } from "~/components/Form";
+import { usePermissions } from "~/hooks";
+import { path } from "~/utils/path";
+import { timecardValidator } from "../../people.models";
+
+type TimecardFormProps = {
+ initialValues: z.infer<typeof timecardValidator>;
+};
+
+const TimecardForm = ({ initialValues }: TimecardFormProps) => {
+ const permissions = usePermissions();
+ const navigate = useNavigate();
+ const onClose = () => navigate(-1);
+
+ const isEditing = initialValues.id !== undefined;
+ const isDisabled = isEditing
+ ? !permissions.can("update", "people")
+ : !permissions.can("create", "people");
+
+ const [clockIn, setClockIn] = useState<CalendarDateTime>(
+ initialValues.clockIn
+ ? toCalendarDateTime(
+ parseAbsolute(initialValues.clockIn, getLocalTimeZone())
+ )
+ : toCalendarDateTime(now(getLocalTimeZone()))
+ );
+
+ const [clockOut, setClockOut] = useState<CalendarDateTime | undefined>(
+ initialValues.clockOut
+ ? toCalendarDateTime(
+ parseAbsolute(initialValues.clockOut, getLocalTimeZone())
+ )
+ : undefined
+ );
+
+ return (
+ <Drawer
+ open
+ onOpenChange={(open) => {
+ if (!open) onClose();
+ }}
+ >
+ <DrawerContent>
+ <ValidatedForm
+ validator={timecardValidator}
+ method="post"
+ action={
+ isEditing
+ ? path.to.timecard(initialValues.id!)
+ : path.to.newTimecard
+ }
+ defaultValues={initialValues}
+ className="flex flex-col h-full"
+ >
+ <DrawerHeader>
+ <DrawerTitle>{isEditing ? "Edit" : "New"} Timecard</DrawerTitle>
+ </DrawerHeader>
+ <DrawerBody>
+ <Hidden name="id" />
+ <VStack spacing={4}>
+ {!isEditing ? (
+ <Employee name="employeeId" label="Employee" />
+ ) : (
+ <Hidden name="employeeId" />
+ )}
+ <DateTimePicker
+ name="clockIn"
+ label="Clock In"
+ maxValue={clockOut}
+ onChange={setClockIn}
+ />
+ <DateTimePicker
+ name="clockOut"
+ label="Clock Out"
+ minValue={clockIn}
+ onChange={setClockOut}
+ />
+ <TextArea name="note" label="Note" />
+ </VStack>
+ </DrawerBody>
+ <DrawerFooter>
+ <HStack>
+ <Submit isDisabled={isDisabled}>Save</Submit>
+ <Button variant="solid" onClick={onClose}>
+ Cancel
+ </Button>
+ </HStack>
+ </DrawerFooter>
+ </ValidatedForm>
+ </DrawerContent>
+ </Drawer>
+ );
+};
+
+export default TimecardForm;
diff --git a/apps/erp/app/modules/people/ui/Timecards/TimecardsTable.tsx b/apps/erp/app/modules/people/ui/Timecards/TimecardsTable.tsx
new file mode 100644
index 0000000000..d4e19393c7
--- /dev/null
+++ b/apps/erp/app/modules/people/ui/Timecards/TimecardsTable.tsx
@@ -0,0 +1,225 @@
+import { Avatar, Badge, HStack, MenuIcon, MenuItem } from "@carbon/react";
+import { formatDate } from "@carbon/utils";
+import type { ColumnDef } from "@tanstack/react-table";
+import { memo, useCallback, useMemo } from "react";
+import {
+ LuCalendar,
+ LuClock,
+ LuMapPin,
+ LuPencil,
+ LuRadar,
+ LuTrash,
+ LuUser
+} from "react-icons/lu";
+import { useNavigate } from "react-router";
+import { Hyperlink, New, Table } from "~/components";
+import { Enumerable } from "~/components/Enumerable";
+import { useLocations } from "~/components/Form/Location";
+import { usePermissions, useUrlParams } from "~/hooks";
+import { path } from "~/utils/path";
+
+type TimeCardEntry = {
+ id: string | null;
+ employeeId: string | null;
+ avatarUrl: string | null;
+ firstName: string | null;
+ lastName: string | null;
+ clockIn: string | null;
+ clockOut: string | null;
+ shiftName: string | null;
+ locationName: string | null;
+ status: string | null;
+ note: string | null;
+};
+
+type TimecardsTableProps = {
+ data: TimeCardEntry[];
+ count: number;
+};
+
+function formatTime(dateStr: string) {
+ return new Date(dateStr).toLocaleTimeString([], {
+ hour: "2-digit",
+ minute: "2-digit"
+ });
+}
+
+function formatDuration(clockInStr: string, clockOutStr: string) {
+ const ms = new Date(clockOutStr).getTime() - new Date(clockInStr).getTime();
+ const hours = Math.floor(ms / 3600000);
+ const minutes = Math.floor((ms % 3600000) / 60000);
+ return `${hours}h ${minutes}m`;
+}
+
+const TimecardsTable = memo(({ data, count }: TimecardsTableProps) => {
+ const navigate = useNavigate();
+ const permissions = usePermissions();
+ const [params] = useUrlParams();
+ const locations = useLocations();
+
+ const columns = useMemo<ColumnDef<TimeCardEntry>[]>(
+ () => [
+ {
+ header: "Employee",
+ cell: ({ row }) => (
+ <Hyperlink to={path.to.personTimecard(row.original.employeeId!)}>
+ <HStack className="items-center gap-2">
+ <Avatar
+ className="size-6"
+ src={row.original.avatarUrl ?? undefined}
+ name={`${row.original.firstName ?? ""} ${row.original.lastName ?? ""}`}
+ />
+ <span className="text-sm">
+ {row.original.firstName} {row.original.lastName}
+ </span>
+ </HStack>
+ </Hyperlink>
+ ),
+ meta: {
+ icon: <LuUser />
+ }
+ },
+ {
+ accessorKey: "clockIn",
+ header: "Date",
+ cell: ({ row }) =>
+ row.original.clockIn
+ ? formatDate(row.original.clockIn, { dateStyle: "medium" })
+ : "—",
+ meta: {
+ icon: <LuCalendar />
+ }
+ },
+ {
+ id: "clockInTime",
+ header: "Clock In",
+ cell: ({ row }) =>
+ row.original.clockIn ? formatTime(row.original.clockIn) : "—",
+ meta: {
+ icon: <LuClock />
+ }
+ },
+ {
+ id: "clockOutTime",
+ header: "Clock Out",
+ cell: ({ row }) =>
+ row.original.clockOut ? formatTime(row.original.clockOut) : "—",
+ meta: {
+ icon: <LuClock />
+ }
+ },
+ {
+ id: "duration",
+ header: "Duration",
+ cell: ({ row }) => {
+ if (!row.original.clockIn || !row.original.clockOut) return "—";
+ return formatDuration(row.original.clockIn, row.original.clockOut);
+ },
+ meta: {
+ icon: <LuClock />
+ }
+ },
+ {
+ accessorKey: "status",
+ header: "Status",
+ cell: ({ row }) => (
+ <Badge
+ variant={row.original.status === "Active" ? "green" : "secondary"}
+ >
+ {row.original.status}
+ </Badge>
+ ),
+ meta: {
+ icon: <LuRadar />,
+ filter: {
+ type: "static" as const,
+ options: [
+ {
+ value: "Active",
+ label: <Badge variant="green">Active</Badge>
+ },
+ {
+ value: "Complete",
+ label: <Badge variant="secondary">Complete</Badge>
+ }
+ ],
+ isArray: false
+ }
+ }
+ },
+ {
+ accessorKey: "locationName",
+ header: "Location",
+ cell: ({ row }) => (
+ <Enumerable value={row.original.locationName ?? null} />
+ ),
+ meta: {
+ icon: <LuMapPin />,
+ filter: {
+ type: "static" as const,
+ options: locations.map((location) => ({
+ value: location.label,
+ label: <Enumerable value={location.label} />
+ })),
+ isArray: false
+ }
+ }
+ }
+ ],
+ [locations]
+ );
+
+ const renderContextMenu = useCallback(
+ (row: TimeCardEntry) => {
+ if (!row.id) return null;
+ return (
+ <>
+ <MenuItem
+ disabled={!permissions.can("update", "people")}
+ onClick={() =>
+ navigate(`${path.to.timecard(row.id!)}?${params.toString()}`)
+ }
+ >
+ <MenuIcon icon={<LuPencil />} />
+ Edit Timecard
+ </MenuItem>
+ <MenuItem
+ destructive
+ disabled={!permissions.can("delete", "people")}
+ onClick={() =>
+ navigate(
+ `${path.to.deleteTimecard(row.id!)}?${params.toString()}`
+ )
+ }
+ >
+ <MenuIcon icon={<LuTrash />} />
+ Delete Timecard
+ </MenuItem>
+ </>
+ );
+ },
+ [navigate, params, permissions]
+ );
+
+ return (
+ <Table<TimeCardEntry>
+ data={data}
+ count={count}
+ columns={columns}
+ primaryAction={
+ permissions.can("create", "people") && (
+ <New label="Timecard" to={`new?${params.toString()}`} />
+ )
+ }
+ renderContextMenu={renderContextMenu}
+ withSearch
+ withPagination
+ withSavedView
+ title="Timecards"
+ table="timeCardEntry"
+ />
+ );
+});
+
+TimecardsTable.displayName = "TimecardsTable";
+export default TimecardsTable;
diff --git a/apps/erp/app/modules/people/ui/Timecards/index.ts b/apps/erp/app/modules/people/ui/Timecards/index.ts
new file mode 100644
index 0000000000..7664a1fc02
--- /dev/null
+++ b/apps/erp/app/modules/people/ui/Timecards/index.ts
@@ -0,0 +1,4 @@
+import TimecardForm from "./TimecardForm";
+import TimecardsTable from "./TimecardsTable";
+
+export { TimecardForm, TimecardsTable };
diff --git a/apps/erp/app/modules/people/ui/usePeopleSubmodules.tsx b/apps/erp/app/modules/people/ui/usePeopleSubmodules.tsx
index 8c163968a1..06d2893f1e 100644
--- a/apps/erp/app/modules/people/ui/usePeopleSubmodules.tsx
+++ b/apps/erp/app/modules/people/ui/usePeopleSubmodules.tsx
@@ -1,12 +1,13 @@
import {
- LuBookUser,
LuCalendarClock,
LuCalendarHeart,
+ LuClock,
LuListChecks,
LuNetwork,
LuUsers
} from "react-icons/lu";
import { useSavedViews } from "~/hooks/useSavedViews";
+import { useSettings } from "~/hooks/useSettings";
import type { RouteGroup } from "~/types";
import { path } from "~/utils/path";
@@ -21,10 +22,11 @@ const peopleRoutes: RouteGroup[] = [
table: "employee"
},
{
- name: "Contacts",
- to: path.to.contact,
- icon: <LuBookUser />,
- table: "contact"
+ name: "Timecards",
+ to: path.to.peopleTimecard,
+ icon: <LuClock />,
+ setting: "timeCardEnabled",
+ table: "timeCardEntry"
}
]
},
@@ -58,10 +60,18 @@ const peopleRoutes: RouteGroup[] = [
export default function usePeopleSubmodules() {
const { addSavedViewsToRoutes } = useSavedViews();
+ const settings = useSettings();
+
return {
groups: peopleRoutes.map((group) => ({
...group,
- routes: group.routes.map(addSavedViewsToRoutes)
+ routes: group.routes
+ .filter(
+ (route) =>
+ !route.setting ||
+ settings[route.setting as keyof typeof settings] === true
+ )
+ .map(addSavedViewsToRoutes)
}))
};
}
diff --git a/apps/erp/app/modules/settings/settings.models.ts b/apps/erp/app/modules/settings/settings.models.ts
index eccb1fc97e..19e27c713a 100644
--- a/apps/erp/app/modules/settings/settings.models.ts
+++ b/apps/erp/app/modules/settings/settings.models.ts
@@ -282,3 +282,7 @@ export const supplierApprovalValidator = z.object({
export const accountsPayableBillingAddressValidator = z.object(billingAddress);
export const accountsReceivableBillingAddressValidator =
z.object(billingAddress);
+
+export const timeCardSettingsValidator = z.object({
+ timeCardEnabled: zfd.checkbox()
+});
diff --git a/apps/erp/app/modules/settings/settings.service.ts b/apps/erp/app/modules/settings/settings.service.ts
index 8958e48727..369745eaa2 100644
--- a/apps/erp/app/modules/settings/settings.service.ts
+++ b/apps/erp/app/modules/settings/settings.service.ts
@@ -695,6 +695,17 @@ export async function updateJobTravelerWorkInstructions(
.eq("id", companyId);
}
+export async function updateTimeCardSetting(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ timeCardEnabled: boolean
+) {
+ return client
+ .from("companySettings")
+ .update(sanitize({ timeCardEnabled }))
+ .eq("id", companyId);
+}
+
export async function updateRfqReadySetting(
client: SupabaseClient<Database>,
companyId: string,
diff --git a/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx b/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx
index 378e54a0c7..61bc54b59d 100644
--- a/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx
+++ b/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx
@@ -13,6 +13,7 @@ import {
LuSheet,
LuShoppingCart,
LuSquareStack,
+ LuUsers,
LuWebhook,
LuWorkflow,
LuWrench
@@ -72,6 +73,12 @@ const settingsRoutes: AuthenticatedRouteGroup<{
role: "employee",
icon: <LuSquareStack />
},
+ {
+ name: "People",
+ to: path.to.peopleSettings,
+ role: "employee",
+ icon: <LuUsers />
+ },
{
name: "Purchasing",
to: path.to.purchasingSettings,
diff --git a/apps/erp/app/routes/api+/people.timecard.ts b/apps/erp/app/routes/api+/people.timecard.ts
new file mode 100644
index 0000000000..d862f82447
--- /dev/null
+++ b/apps/erp/app/routes/api+/people.timecard.ts
@@ -0,0 +1,34 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import type { ActionFunctionArgs } from "react-router";
+import { clockIn, clockOut } from "~/modules/people";
+
+export async function action({ request }: ActionFunctionArgs) {
+ const { client, companyId, userId } = await requirePermissions(request, {});
+
+ const formData = await request.formData();
+ const intent = formData.get("intent");
+
+ if (intent === "clockIn") {
+ const result = await clockIn(client, {
+ employeeId: userId,
+ companyId,
+ createdBy: userId
+ });
+ return { success: !result.error, error: result.error?.message };
+ }
+
+ if (intent === "clockOut") {
+ const clockOutTime = formData.get("clockOut") as string | null;
+ const note = formData.get("note") as string | null;
+ const result = await clockOut(client, {
+ employeeId: userId,
+ companyId,
+ updatedBy: userId,
+ clockOut: clockOutTime ?? undefined,
+ note: note ?? undefined
+ });
+ return { success: !result.error, error: result.error?.message };
+ }
+
+ return { success: false, error: "Unknown intent" };
+}
diff --git a/apps/erp/app/routes/x+/_layout.tsx b/apps/erp/app/routes/x+/_layout.tsx
index 66c04b91c1..1d0f6eb43a 100644
--- a/apps/erp/app/routes/x+/_layout.tsx
+++ b/apps/erp/app/routes/x+/_layout.tsx
@@ -29,8 +29,10 @@ import {
} from "react-router";
import { RealtimeDataProvider } from "~/components";
import { PrimaryNavigation, Topbar } from "~/components/Layout";
+import { TimeCardWarning } from "~/components/TimeCardWarning";
import TrainingPanel from "~/components/TrainingPanel";
import { useTrainingPanel } from "~/hooks/useTrainingPanel";
+import { getOpenClockEntry } from "~/modules/people";
import {
getCompanies,
getCompanyIntegrations,
@@ -89,7 +91,8 @@ export async function loader({ request }: LoaderFunctionArgs) {
user,
claims,
groups,
- defaults
+ defaults,
+ openClockEntry
] = await Promise.all([
getCompanies(client, userId),
getStripeCustomerByCompanyId(companyId, userId),
@@ -100,7 +103,8 @@ export async function loader({ request }: LoaderFunctionArgs) {
getUser(client, userId),
getUserClaims(userId, companyId),
getUserGroups(client, userId),
- getUserDefaults(client, userId, companyId)
+ getUserDefaults(client, userId, companyId),
+ getOpenClockEntry(client, userId, companyId)
]);
if (!claims || user.error || !user.data || !groups.data) {
@@ -145,12 +149,16 @@ export async function loader({ request }: LoaderFunctionArgs) {
plan: stripeCustomer?.planId,
role: claims?.role,
user: user.data,
- savedViews: savedViews.data ?? []
+ savedViews: savedViews.data ?? [],
+ openClockEntry: openClockEntry.data
+ ? { id: openClockEntry.data.id, clockIn: openClockEntry.data.clockIn }
+ : null
});
}
export default function AuthenticatedRoute() {
- const { session, user } = useLoaderData<typeof loader>();
+ const { session, user, companySettings, openClockEntry } =
+ useLoaderData<typeof loader>();
const navigate = useNavigate();
const { isOpen, training, dismiss } = useTrainingPanel();
@@ -201,6 +209,9 @@ export default function AuthenticatedRoute() {
isOpen={isOpen}
onDismiss={dismiss}
/>
+ {companySettings?.timeCardEnabled && (
+ <TimeCardWarning openClockEntry={openClockEntry} />
+ )}
</TooltipProvider>
</RealtimeDataProvider>
</CarbonProvider>
diff --git a/apps/erp/app/routes/x+/people+/contact.tsx b/apps/erp/app/routes/x+/people+/contact.tsx
deleted file mode 100644
index 1b4c82af1e..0000000000
--- a/apps/erp/app/routes/x+/people+/contact.tsx
+++ /dev/null
@@ -1,55 +0,0 @@
-import { error } from "@carbon/auth";
-import { requirePermissions } from "@carbon/auth/auth.server";
-import { flash } from "@carbon/auth/session.server";
-import { VStack } from "@carbon/react";
-import type { LoaderFunctionArgs } from "react-router";
-import { Outlet, redirect, useLoaderData } from "react-router";
-import { getContacts } from "~/modules/people";
-import { ContactTable } from "~/modules/people/ui/Contact";
-import { path } from "~/utils/path";
-import { getGenericQueryFilters } from "~/utils/query";
-
-export async function loader({ request }: LoaderFunctionArgs) {
- const { client, companyId } = await requirePermissions(request, {
- view: "sales",
- role: "employee"
- });
-
- const url = new URL(request.url);
- const searchParams = new URLSearchParams(url.search);
- const search = searchParams.get("search");
-
- const { limit, offset, sorts, filters } =
- getGenericQueryFilters(searchParams);
-
- const contacts = await getContacts(client, companyId, {
- search,
- limit,
- offset,
- sorts,
- filters
- });
-
- if (contacts.error) {
- throw redirect(
- path.to.authenticatedRoot,
- await flash(request, error(contacts.error, "Error loading contacts"))
- );
- }
-
- return {
- contacts: contacts.data ?? [],
- count: contacts.count
- };
-}
-
-export default function ResourcesContactRoute() {
- const { contacts, count } = useLoaderData<typeof loader>();
-
- return (
- <VStack spacing={0} className="h-full">
- <ContactTable data={contacts} count={count ?? 0} />
- <Outlet />
- </VStack>
- );
-}
diff --git a/apps/erp/app/routes/x+/people+/timecard.$entryId.tsx b/apps/erp/app/routes/x+/people+/timecard.$entryId.tsx
new file mode 100644
index 0000000000..37290e09ea
--- /dev/null
+++ b/apps/erp/app/routes/x+/people+/timecard.$entryId.tsx
@@ -0,0 +1,86 @@
+import { assertIsPost, error, notFound, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validationError, validator } from "@carbon/form";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
+import { redirect, useLoaderData } from "react-router";
+import {
+ getTimeCardEntry,
+ timecardValidator,
+ updateTimeCardEntry
+} from "~/modules/people";
+import { TimecardForm } from "~/modules/people/ui/Timecards";
+import { path } from "~/utils/path";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "people"
+ });
+
+ const { entryId } = params;
+ if (!entryId) throw notFound("Entry ID was not found");
+
+ const entry = await getTimeCardEntry(client, entryId);
+
+ if (entry.error) {
+ throw redirect(
+ path.to.peopleTimecard,
+ await flash(request, error(entry.error, "Failed to get timecard"))
+ );
+ }
+
+ return {
+ entry: entry.data
+ };
+}
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ update: "people"
+ });
+
+ const formData = await request.formData();
+ const validation = await validator(timecardValidator).validate(formData);
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, clockIn, clockOut, note } = validation.data;
+ if (!id) throw notFound("Entry ID was not found");
+
+ const result = await updateTimeCardEntry(client, {
+ entryId: id,
+ clockIn,
+ clockOut: clockOut || null,
+ note: note || null,
+ updatedBy: userId
+ });
+
+ if (result.error) {
+ throw redirect(
+ path.to.peopleTimecard,
+ await flash(request, error(result.error, "Failed to update timecard"))
+ );
+ }
+
+ throw redirect(
+ path.to.peopleTimecard,
+ await flash(request, success("Timecard updated"))
+ );
+}
+
+export default function TimecardRoute() {
+ const { entry } = useLoaderData<typeof loader>();
+
+ const initialValues = {
+ id: entry.id,
+ employeeId: entry.employeeId,
+ clockIn: entry.clockIn,
+ clockOut: entry.clockOut ?? "",
+ note: entry.note ?? ""
+ };
+
+ return <TimecardForm key={initialValues.id} initialValues={initialValues} />;
+}
diff --git a/apps/erp/app/routes/x+/people+/timecard.delete.$entryId.tsx b/apps/erp/app/routes/x+/people+/timecard.delete.$entryId.tsx
new file mode 100644
index 0000000000..52b92b0921
--- /dev/null
+++ b/apps/erp/app/routes/x+/people+/timecard.delete.$entryId.tsx
@@ -0,0 +1,79 @@
+import { error, notFound, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
+import { redirect, useLoaderData, useNavigate, useParams } from "react-router";
+import { ConfirmDelete } from "~/components/Modals";
+import { deleteTimeCardEntry, getTimeCardEntry } from "~/modules/people";
+import { path } from "~/utils/path";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "people",
+ role: "employee"
+ });
+
+ const { entryId } = params;
+ if (!entryId) throw notFound("entryId not found");
+
+ const entry = await getTimeCardEntry(client, entryId);
+ if (entry.error) {
+ throw redirect(
+ path.to.peopleTimecard,
+ await flash(request, error(entry.error, "Failed to get timecard"))
+ );
+ }
+
+ return {
+ entry: entry.data
+ };
+}
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ delete: "people"
+ });
+
+ const { entryId } = params;
+ if (!entryId) {
+ throw redirect(
+ path.to.peopleTimecard,
+ await flash(request, error(params, "Failed to get entry id"))
+ );
+ }
+
+ const { error: deleteError } = await deleteTimeCardEntry(client, entryId);
+ if (deleteError) {
+ throw redirect(
+ path.to.peopleTimecard,
+ await flash(request, error(deleteError, "Failed to delete timecard"))
+ );
+ }
+
+ throw redirect(
+ path.to.peopleTimecard,
+ await flash(request, success("Successfully deleted timecard"))
+ );
+}
+
+export default function DeleteTimecardRoute() {
+ const { entryId } = useParams();
+ const { entry } = useLoaderData<typeof loader>();
+ const navigate = useNavigate();
+
+ if (!entry) return null;
+ if (!entryId) throw new Error("entryId is not found");
+
+ const onCancel = () => navigate(path.to.peopleTimecard);
+
+ const clockIn = new Date(entry.clockIn).toLocaleString();
+
+ return (
+ <ConfirmDelete
+ action={path.to.deleteTimecard(entryId)}
+ name={`Timecard (${clockIn})`}
+ text="Are you sure you want to delete this timecard? This cannot be undone."
+ onCancel={onCancel}
+ />
+ );
+}
diff --git a/apps/erp/app/routes/x+/people+/timecard.new.tsx b/apps/erp/app/routes/x+/people+/timecard.new.tsx
new file mode 100644
index 0000000000..e6deb925db
--- /dev/null
+++ b/apps/erp/app/routes/x+/people+/timecard.new.tsx
@@ -0,0 +1,57 @@
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validationError, validator } from "@carbon/form";
+import type { ActionFunctionArgs } from "react-router";
+import { redirect } from "react-router";
+import { createTimeCardEntry, timecardValidator } from "~/modules/people";
+import { TimecardForm } from "~/modules/people/ui/Timecards";
+import { path } from "~/utils/path";
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ create: "people"
+ });
+
+ const formData = await request.formData();
+ const validation = await validator(timecardValidator).validate(formData);
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id: _id, ...data } = validation.data;
+
+ const result = await createTimeCardEntry(client, {
+ employeeId: data.employeeId,
+ companyId,
+ clockIn: data.clockIn,
+ clockOut: data.clockOut || null,
+ note: data.note || null,
+ createdBy: userId
+ });
+
+ if (result.error) {
+ throw redirect(
+ path.to.peopleTimecard,
+ await flash(request, error(result.error, "Failed to create timecard"))
+ );
+ }
+
+ throw redirect(
+ path.to.peopleTimecard,
+ await flash(request, success("Timecard created"))
+ );
+}
+
+export default function NewTimecardRoute() {
+ const initialValues = {
+ employeeId: "",
+ clockIn: "",
+ clockOut: "",
+ note: ""
+ };
+
+ return <TimecardForm initialValues={initialValues} />;
+}
diff --git a/apps/erp/app/routes/x+/people+/timecard.tsx b/apps/erp/app/routes/x+/people+/timecard.tsx
new file mode 100644
index 0000000000..8611e44f69
--- /dev/null
+++ b/apps/erp/app/routes/x+/people+/timecard.tsx
@@ -0,0 +1,77 @@
+import { error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { VStack } from "@carbon/react";
+import type { LoaderFunctionArgs } from "react-router";
+import { Outlet, redirect, useLoaderData } from "react-router";
+import { getTimecardEntries } from "~/modules/people";
+import { TimecardsTable } from "~/modules/people/ui/Timecards";
+import { getCompanySettings } from "~/modules/settings";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+import { getGenericQueryFilters } from "~/utils/query";
+
+export const handle: Handle = {
+ breadcrumb: "Timecards",
+ to: path.to.peopleTimecard
+};
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "people"
+ });
+
+ const companySettings = await getCompanySettings(client, companyId);
+ if (!companySettings.data?.timeCardEnabled) {
+ throw redirect(
+ path.to.people,
+ await flash(
+ request,
+ error(
+ null,
+ "Timecards are not enabled. To enable this feature, go to Settings → People to enable Timecards."
+ )
+ )
+ );
+ }
+
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ const search = searchParams.get("search");
+ const { limit, offset, sorts, filters } =
+ getGenericQueryFilters(searchParams);
+
+ const entries = await getTimecardEntries(client, companyId, {
+ search,
+ limit,
+ offset,
+ sorts,
+ filters
+ });
+
+ if (entries.error) {
+ throw redirect(
+ path.to.people,
+ await flash(
+ request,
+ error(entries.error, "Failed to load timecard entries")
+ )
+ );
+ }
+
+ return {
+ entries: entries.data ?? [],
+ count: entries.count ?? 0
+ };
+}
+
+export default function Route() {
+ const { entries, count } = useLoaderData<typeof loader>();
+
+ return (
+ <VStack spacing={0} className="h-full">
+ <TimecardsTable data={entries} count={count} />
+ <Outlet />
+ </VStack>
+ );
+}
diff --git a/apps/erp/app/routes/x+/person+/$personId.timecard.tsx b/apps/erp/app/routes/x+/person+/$personId.timecard.tsx
new file mode 100644
index 0000000000..3d21f5811e
--- /dev/null
+++ b/apps/erp/app/routes/x+/person+/$personId.timecard.tsx
@@ -0,0 +1,760 @@
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validator } from "@carbon/form";
+import {
+ Badge,
+ Button,
+ Card,
+ CardContent,
+ CardHeader,
+ CardTitle,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuIcon,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ HStack,
+ IconButton,
+ Input,
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+ Table as TableBase,
+ Tbody,
+ Td,
+ Th,
+ Thead,
+ Tr
+} from "@carbon/react";
+import { formatDate } from "@carbon/utils";
+import { useEffect, useState } from "react";
+import {
+ LuChevronLeft,
+ LuChevronRight,
+ LuEllipsisVertical,
+ LuPencil,
+ LuPlay,
+ LuPlus,
+ LuTrash
+} from "react-icons/lu";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
+import {
+ data,
+ redirect,
+ useFetcher,
+ useLoaderData,
+ useParams
+} from "react-router";
+import { Link } from "react-router-dom";
+import { ConfirmDelete } from "~/components/Modals";
+import {
+ clockIn,
+ clockInValidator,
+ clockOut,
+ clockOutValidator,
+ deleteTimeCardEntry,
+ deleteTimeCardEntryValidator,
+ getOpenClockEntry,
+ getTimeCardEntries,
+ updateTimeCardEntry,
+ updateTimeCardEntryValidator
+} from "~/modules/people";
+import { getCompanySettings } from "~/modules/settings";
+import { path } from "~/utils/path";
+
+function getWeekBounds(offset: number = 0) {
+ const now = new Date();
+ const dayOfWeek = now.getDay(); // 0 = Sunday
+ const monday = new Date(now);
+ monday.setDate(now.getDate() - ((dayOfWeek + 6) % 7) + offset * 7);
+ monday.setHours(0, 0, 0, 0);
+
+ const sunday = new Date(monday);
+ sunday.setDate(monday.getDate() + 6);
+ sunday.setHours(23, 59, 59, 999);
+
+ return {
+ from: monday.toISOString(),
+ to: sunday.toISOString(),
+ monday,
+ sunday
+ };
+}
+
+function formatDuration(clockIn: string, clockOut: string | null) {
+ const end = clockOut ? new Date(clockOut).getTime() : Date.now();
+ const ms = end - new Date(clockIn).getTime();
+ const hours = Math.floor(ms / 3600000);
+ const minutes = Math.floor((ms % 3600000) / 60000);
+ return `${hours}h ${minutes}m`;
+}
+
+function formatTotalHours(
+ entries: { clockIn: string; clockOut: string | null }[]
+) {
+ let totalMs = 0;
+ for (const entry of entries) {
+ const end = entry.clockOut
+ ? new Date(entry.clockOut).getTime()
+ : Date.now();
+ totalMs += end - new Date(entry.clockIn).getTime();
+ }
+ const hours = Math.floor(totalMs / 3600000);
+ const minutes = Math.floor((totalMs % 3600000) / 60000);
+ return `${hours}h ${minutes}m`;
+}
+
+function formatTime(dateStr: string) {
+ return new Date(dateStr).toLocaleTimeString([], {
+ hour: "2-digit",
+ minute: "2-digit"
+ });
+}
+
+function formatDay(dateStr: string) {
+ return new Date(dateStr).toLocaleDateString([], {
+ weekday: "short",
+ month: "short",
+ day: "numeric"
+ });
+}
+
+/** Format a UTC date string to a local datetime-local input value */
+function toLocalDatetimeInput(dateStr: string) {
+ const d = new Date(dateStr);
+ const year = d.getFullYear();
+ const month = String(d.getMonth() + 1).padStart(2, "0");
+ const day = String(d.getDate()).padStart(2, "0");
+ const hours = String(d.getHours()).padStart(2, "0");
+ const minutes = String(d.getMinutes()).padStart(2, "0");
+ return `${year}-${month}-${day}T${hours}:${minutes}`;
+}
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "people"
+ });
+
+ const { personId } = params;
+ if (!personId) throw new Error("Could not find personId");
+
+ const url = new URL(request.url);
+ const weekOffset = parseInt(url.searchParams.get("week") ?? "0", 10);
+ const { from, to } = getWeekBounds(weekOffset);
+
+ const [entries, openEntry, companySettings, employeeShift] =
+ await Promise.all([
+ getTimeCardEntries(client, {
+ employeeId: personId,
+ companyId,
+ from,
+ to
+ }),
+ getOpenClockEntry(client, personId, companyId),
+ getCompanySettings(client, companyId),
+ client
+ .from("employeeJob")
+ .select(
+ "shiftId, shift:shift(startTime, endTime, sunday, monday, tuesday, wednesday, thursday, friday, saturday)"
+ )
+ .eq("id", personId)
+ .eq("companyId", companyId)
+ .maybeSingle()
+ ]);
+
+ if (!companySettings.data?.timeCardEnabled) {
+ throw redirect(path.to.personDetails(personId));
+ }
+
+ const shift = employeeShift?.data?.shift as {
+ startTime: string;
+ endTime: string;
+ sunday: boolean;
+ monday: boolean;
+ tuesday: boolean;
+ wednesday: boolean;
+ thursday: boolean;
+ friday: boolean;
+ saturday: boolean;
+ } | null;
+
+ return {
+ entries: entries.data ?? [],
+ openEntry: openEntry.data,
+ weekOffset,
+ from,
+ to,
+ shift
+ };
+}
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ view: "people"
+ });
+
+ const { personId } = params;
+ if (!personId) throw new Error("No person ID provided");
+
+ const formData = await request.formData();
+ const intent = formData.get("intent");
+
+ if (intent === "clockIn") {
+ const validation = await validator(clockInValidator).validate(formData);
+ if (validation.error) return data({}, { status: 400 });
+
+ const employeeId = validation.data.employeeId || personId;
+ const result = await clockIn(client, {
+ employeeId,
+ companyId,
+ createdBy: userId
+ });
+
+ if (result.error) {
+ return data(
+ {},
+ await flash(request, error(result.error, result.error.message))
+ );
+ }
+ return data({}, await flash(request, success("Clocked in")));
+ }
+
+ if (intent === "clockOut") {
+ const validation = await validator(clockOutValidator).validate(formData);
+ if (validation.error) return data({}, { status: 400 });
+
+ const employeeId = validation.data.employeeId || personId;
+ const result = await clockOut(client, {
+ employeeId,
+ companyId,
+ updatedBy: userId,
+ note: validation.data.note
+ });
+
+ if (result.error) {
+ return data(
+ {},
+ await flash(request, error(result.error, result.error.message))
+ );
+ }
+ return data({}, await flash(request, success("Clocked out")));
+ }
+
+ if (intent === "updateEntry") {
+ const validation = await validator(updateTimeCardEntryValidator).validate(
+ formData
+ );
+ if (validation.error) return data({}, { status: 400 });
+
+ const result = await updateTimeCardEntry(client, {
+ entryId: validation.data.entryId,
+ clockIn: validation.data.clockIn,
+ clockOut: validation.data.clockOut || null,
+ note: validation.data.note || null,
+ updatedBy: userId
+ });
+
+ if (result.error) {
+ return data(
+ {},
+ await flash(request, error(result.error, "Failed to update entry"))
+ );
+ }
+ return data({}, await flash(request, success("Entry updated")));
+ }
+
+ if (intent === "deleteEntry") {
+ const validation = await validator(deleteTimeCardEntryValidator).validate(
+ formData
+ );
+ if (validation.error) return data({}, { status: 400 });
+
+ const result = await deleteTimeCardEntry(client, validation.data.entryId);
+ if (result.error) {
+ return data(
+ {},
+ await flash(request, error(result.error, "Failed to delete entry"))
+ );
+ }
+ return data({}, await flash(request, success("Entry deleted")));
+ }
+
+ if (intent === "addEntry") {
+ const clockInVal = formData.get("clockIn") as string;
+ const clockOutVal = formData.get("clockOut") as string | null;
+ if (!clockInVal) return data({}, { status: 400 });
+
+ const result = await client.from("timeCardEntry").insert({
+ employeeId: personId,
+ companyId,
+ clockIn: clockInVal,
+ clockOut: clockOutVal || null,
+ createdBy: userId
+ });
+
+ if (result.error) {
+ return data(
+ {},
+ await flash(request, error(result.error, "Failed to add entry"))
+ );
+ }
+ return data({}, await flash(request, success("Entry added")));
+ }
+
+ return data({}, { status: 400 });
+}
+
+function getShiftTimesForDate(
+ dateStr: string,
+ shift: {
+ startTime: string;
+ endTime: string;
+ sunday: boolean;
+ monday: boolean;
+ tuesday: boolean;
+ wednesday: boolean;
+ thursday: boolean;
+ friday: boolean;
+ saturday: boolean;
+ } | null
+): { clockIn: string; clockOut: string } | null {
+ if (!shift) return null;
+ // Parse YYYY-MM-DD as local date (not UTC)
+ const [year, month, day2] = dateStr.split("-").map(Number);
+ const date = new Date(year, month - 1, day2);
+ const dayNames = [
+ "sunday",
+ "monday",
+ "tuesday",
+ "wednesday",
+ "thursday",
+ "friday",
+ "saturday"
+ ] as const;
+ const day = dayNames[date.getDay()];
+ if (!shift[day]) return null;
+
+ const [startH, startM] = shift.startTime.split(":").map(Number);
+ const [endH, endM] = shift.endTime.split(":").map(Number);
+
+ const clockIn = new Date(date);
+ clockIn.setHours(startH, startM, 0, 0);
+
+ const clockOut = new Date(date);
+ clockOut.setHours(endH, endM, 0, 0);
+ if (clockOut <= clockIn) clockOut.setDate(clockOut.getDate() + 1);
+
+ return {
+ clockIn: toLocalDatetimeInput(clockIn.toISOString()),
+ clockOut: toLocalDatetimeInput(clockOut.toISOString())
+ };
+}
+
+export default function PersonTimecardRoute() {
+ const { entries, openEntry, weekOffset, from, to, shift } =
+ useLoaderData<typeof loader>();
+ const { personId } = useParams();
+ const fetcher = useFetcher<typeof action>();
+ const [editingId, setEditingId] = useState<string | null>(null);
+ const [editClockIn, setEditClockIn] = useState("");
+ const [editClockOut, setEditClockOut] = useState("");
+ const [editNote, setEditNote] = useState("");
+ const [, setTick] = useState(0);
+ const [showAddForm, setShowAddForm] = useState(false);
+ const [addDate, setAddDate] = useState("");
+ const [addClockIn, setAddClockIn] = useState("");
+ const [addClockOut, setAddClockOut] = useState("");
+ const [deletingEntry, setDeletingEntry] = useState<{
+ id: string;
+ clockIn: string;
+ } | null>(null);
+
+ // Update live durations every minute
+ useEffect(() => {
+ const interval = setInterval(() => setTick((t) => t + 1), 60000);
+ return () => clearInterval(interval);
+ }, []);
+
+ const monday = new Date(from);
+ const sunday = new Date(to);
+ const isCurrentWeek = weekOffset === 0;
+
+ useEffect(() => {
+ if (fetcher.data && fetcher.state === "idle") {
+ setEditingId(null);
+ setShowAddForm(false);
+ }
+ }, [fetcher.data, fetcher.state]);
+
+ // Auto-populate shift times when date is selected for new entry
+ useEffect(() => {
+ if (!addDate) return;
+ const shiftTimes = getShiftTimesForDate(addDate, shift ?? null);
+ if (shiftTimes) {
+ setAddClockIn(shiftTimes.clockIn);
+ setAddClockOut(shiftTimes.clockOut);
+ } else {
+ // No shift for this day, default 9am-5pm
+ const [y, m, dy] = addDate.split("-").map(Number);
+ const d = new Date(y, m - 1, dy);
+ d.setHours(9, 0, 0, 0);
+ setAddClockIn(toLocalDatetimeInput(d.toISOString()));
+ d.setHours(17, 0, 0, 0);
+ setAddClockOut(toLocalDatetimeInput(d.toISOString()));
+ }
+ }, [addDate, shift]);
+
+ function startEdit(entry: {
+ id: string;
+ clockIn: string;
+ clockOut: string | null;
+ note: string | null;
+ }) {
+ setEditingId(entry.id);
+ setEditClockIn(toLocalDatetimeInput(entry.clockIn));
+ setEditClockOut(entry.clockOut ? toLocalDatetimeInput(entry.clockOut) : "");
+ setEditNote(entry.note ?? "");
+ }
+
+ return (
+ <Card className="overflow-hidden">
+ <CardHeader>
+ <HStack className="justify-between items-center">
+ <CardTitle>Timecards</CardTitle>
+ <HStack className="gap-1">
+ <Button
+ variant="secondary"
+ leftIcon={<LuPlus />}
+ onClick={() => {
+ setShowAddForm(!showAddForm);
+ setAddDate("");
+ setAddClockIn("");
+ setAddClockOut("");
+ }}
+ >
+ Add Entry
+ </Button>
+ {openEntry ? (
+ <fetcher.Form method="post">
+ <input type="hidden" name="intent" value="clockOut" />
+ <Button
+ variant="destructive"
+ type="submit"
+ disabled={fetcher.state !== "idle"}
+ >
+ Clock Out
+ </Button>
+ </fetcher.Form>
+ ) : (
+ <fetcher.Form method="post">
+ <input type="hidden" name="intent" value="clockIn" />
+ <Button
+ leftIcon={<LuPlay />}
+ type="submit"
+ disabled={fetcher.state !== "idle"}
+ >
+ Clock In
+ </Button>
+ </fetcher.Form>
+ )}
+ </HStack>
+ </HStack>
+ {openEntry && (
+ <Badge variant="green" className="w-fit">
+ Clocked in since {formatTime(openEntry.clockIn)}
+ </Badge>
+ )}
+ </CardHeader>
+ <CardContent>
+ <HStack className="justify-between items-center mb-4">
+ <Button variant="outline" asChild leftIcon={<LuChevronLeft />}>
+ <Link
+ to={`${path.to.personTimecard(personId!)}?week=${weekOffset - 1}`}
+ >
+ Prev
+ </Link>
+ </Button>
+ <span className="text-sm text-muted-foreground">
+ {formatDate(monday.toISOString(), { dateStyle: "medium" })} —{" "}
+ {formatDate(sunday.toISOString(), { dateStyle: "medium" })}
+ </span>
+ <Button
+ variant="outline"
+ disabled={isCurrentWeek}
+ asChild={!isCurrentWeek}
+ rightIcon={<LuChevronRight />}
+ >
+ {isCurrentWeek ? (
+ <span>Next</span>
+ ) : (
+ <Link
+ to={`${path.to.personTimecard(personId!)}?week=${weekOffset + 1}`}
+ >
+ Next
+ </Link>
+ )}
+ </Button>
+ </HStack>
+
+ <TableBase className="table-fixed w-full">
+ <colgroup>
+ <col className="w-[16%]" />
+ <col className="w-[28%]" />
+ <col className="w-[28%]" />
+ <col className="w-[12%]" />
+ <col className="w-[16%]" />
+ </colgroup>
+ <Thead>
+ <Tr>
+ <Th className="whitespace-nowrap">Date</Th>
+ <Th>Clock In</Th>
+ <Th>Clock Out</Th>
+ <Th className="text-center">Duration</Th>
+ <Th />
+ </Tr>
+ </Thead>
+ <Tbody>
+ {showAddForm && (
+ <Tr>
+ <Td>
+ <Select
+ value={addDate}
+ onValueChange={(value) => setAddDate(value)}
+ >
+ <SelectTrigger size="sm">
+ <SelectValue placeholder="Date" />
+ </SelectTrigger>
+ <SelectContent>
+ {Array.from({ length: 7 }, (_, i) => {
+ const d = new Date(monday);
+ d.setDate(monday.getDate() + i);
+ const val = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
+ return (
+ <SelectItem key={val} value={val}>
+ {d.toLocaleDateString([], {
+ weekday: "short",
+ month: "short",
+ day: "numeric"
+ })}
+ </SelectItem>
+ );
+ })}
+ </SelectContent>
+ </Select>
+ </Td>
+ <Td>
+ <Input
+ type="datetime-local"
+ value={addClockIn}
+ onChange={(e) => setAddClockIn(e.target.value)}
+ className="h-8 text-xs w-full [&::-webkit-calendar-picker-indicator]:hidden"
+ />
+ </Td>
+ <Td>
+ <Input
+ type="datetime-local"
+ value={addClockOut}
+ onChange={(e) => setAddClockOut(e.target.value)}
+ className="h-8 text-xs w-full [&::-webkit-calendar-picker-indicator]:hidden"
+ />
+ </Td>
+ <Td className="text-muted-foreground text-center">—</Td>
+ <Td className="text-center">
+ <HStack className="justify-center">
+ <fetcher.Form method="post">
+ <input type="hidden" name="intent" value="addEntry" />
+ <input
+ type="hidden"
+ name="clockIn"
+ value={
+ isNaN(new Date(addClockIn).getTime())
+ ? ""
+ : new Date(addClockIn).toISOString()
+ }
+ />
+ {addClockOut &&
+ !isNaN(new Date(addClockOut).getTime()) && (
+ <input
+ type="hidden"
+ name="clockOut"
+ value={new Date(addClockOut).toISOString()}
+ />
+ )}
+ <Button
+ variant="secondary"
+ type="submit"
+ disabled={isNaN(new Date(addClockIn).getTime())}
+ >
+ Save
+ </Button>
+ </fetcher.Form>
+ <Button
+ variant="ghost"
+ onClick={() => setShowAddForm(false)}
+ >
+ Cancel
+ </Button>
+ </HStack>
+ </Td>
+ </Tr>
+ )}
+ {entries.length === 0 && !showAddForm ? (
+ <Tr>
+ <Td
+ colSpan={5}
+ className="text-center text-muted-foreground py-8"
+ >
+ No time entries for this week
+ </Td>
+ </Tr>
+ ) : (
+ entries.map((entry) =>
+ editingId === entry.id ? (
+ <Tr key={entry.id}>
+ <Td className="whitespace-nowrap">
+ {formatDay(entry.clockIn)}
+ </Td>
+ <Td>
+ <Input
+ type="datetime-local"
+ value={editClockIn}
+ onChange={(e) => setEditClockIn(e.target.value)}
+ className="h-8 text-xs w-full [&::-webkit-calendar-picker-indicator]:hidden"
+ />
+ </Td>
+ <Td>
+ <Input
+ type="datetime-local"
+ value={editClockOut}
+ onChange={(e) => setEditClockOut(e.target.value)}
+ className="h-8 text-xs w-full [&::-webkit-calendar-picker-indicator]:hidden"
+ />
+ </Td>
+ <Td className="text-muted-foreground text-center">—</Td>
+ <Td className="text-center">
+ <HStack className="justify-center">
+ <fetcher.Form method="post">
+ <input
+ type="hidden"
+ name="intent"
+ value="updateEntry"
+ />
+ <input
+ type="hidden"
+ name="entryId"
+ value={entry.id}
+ />
+ <input
+ type="hidden"
+ name="clockIn"
+ value={
+ isNaN(new Date(editClockIn).getTime())
+ ? ""
+ : new Date(editClockIn).toISOString()
+ }
+ />
+ {editClockOut &&
+ !isNaN(new Date(editClockOut).getTime()) && (
+ <input
+ type="hidden"
+ name="clockOut"
+ value={new Date(editClockOut).toISOString()}
+ />
+ )}
+ <input type="hidden" name="note" value={editNote} />
+ <Button
+ variant="secondary"
+ type="submit"
+ disabled={isNaN(new Date(editClockIn).getTime())}
+ >
+ Save
+ </Button>
+ </fetcher.Form>
+ <Button
+ variant="ghost"
+ onClick={() => setEditingId(null)}
+ >
+ Cancel
+ </Button>
+ </HStack>
+ </Td>
+ </Tr>
+ ) : (
+ <Tr key={entry.id}>
+ <Td className="whitespace-nowrap">
+ {formatDay(entry.clockIn)}
+ </Td>
+ <Td>{formatTime(entry.clockIn)}</Td>
+ <Td>
+ {entry.clockOut ? (
+ formatTime(entry.clockOut)
+ ) : (
+ <Badge variant="green">Active</Badge>
+ )}
+ </Td>
+ <Td className="text-center">
+ {formatDuration(entry.clockIn, entry.clockOut)}
+ </Td>
+ <Td className="text-right">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ aria-label="More options"
+ variant="ghost"
+ icon={<LuEllipsisVertical />}
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem onClick={() => startEdit(entry)}>
+ <DropdownMenuIcon icon={<LuPencil />} />
+ Edit
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onClick={() =>
+ setDeletingEntry({
+ id: entry.id,
+ clockIn: entry.clockIn
+ })
+ }
+ className="text-destructive"
+ >
+ <DropdownMenuIcon icon={<LuTrash />} />
+ Delete
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </Td>
+ </Tr>
+ )
+ )
+ )}
+ </Tbody>
+ </TableBase>
+
+ {entries.length > 0 && (
+ <div className="mt-4 text-right text-sm font-medium">
+ Total: {formatTotalHours(entries)}
+ </div>
+ )}
+ </CardContent>
+ {deletingEntry && (
+ <ConfirmDelete
+ name={`Timecard (${new Date(deletingEntry.clockIn).toLocaleString()})`}
+ text="Are you sure you want to delete this timecard? This cannot be undone."
+ onCancel={() => setDeletingEntry(null)}
+ onSubmit={() => {
+ const formData = new FormData();
+ formData.append("intent", "deleteEntry");
+ formData.append("entryId", deletingEntry.id);
+ fetcher.submit(formData, { method: "post" });
+ setDeletingEntry(null);
+ }}
+ />
+ )}
+ </Card>
+ );
+}
diff --git a/apps/erp/app/routes/x+/person+/$personId.tsx b/apps/erp/app/routes/x+/person+/$personId.tsx
index 7a0acd88d9..ee2e6d18cd 100644
--- a/apps/erp/app/routes/x+/person+/$personId.tsx
+++ b/apps/erp/app/routes/x+/person+/$personId.tsx
@@ -11,6 +11,7 @@ import {
} from "~/modules/account";
import { getEmployeeSummary } from "~/modules/people";
import { PersonPreview, PersonSidebar } from "~/modules/people/ui/Person";
+import { getCompanySettings } from "~/modules/settings";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
@@ -27,10 +28,12 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const { personId } = params;
if (!personId) throw new Error("Could not find personId");
- const [employeeSummary, attributeCategories] = await Promise.all([
- getEmployeeSummary(client, personId, companyId),
- getAllAttributeCategories(client, personId, companyId)
- ]);
+ const [employeeSummary, attributeCategories, companySettings] =
+ await Promise.all([
+ getEmployeeSummary(client, personId, companyId),
+ getAllAttributeCategories(client, personId, companyId),
+ getCompanySettings(client, companyId)
+ ]);
if (employeeSummary.error) {
throw redirect(
@@ -44,7 +47,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
return {
employeeSummary: employeeSummary.data,
- attributeCategories: attributeCategories.data ?? []
+ attributeCategories: attributeCategories.data ?? [],
+ timeCardEnabled: companySettings.data?.timeCardEnabled ?? false
};
}
@@ -85,13 +89,17 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
export default function PersonRoute() {
- const { attributeCategories } = useLoaderData<typeof loader>();
+ const { attributeCategories, timeCardEnabled } =
+ useLoaderData<typeof loader>();
return (
<>
<PersonPreview />
<div className="grid grid-cols-1 md:grid-cols-[1fr_4fr] h-full w-full gap-4">
- <PersonSidebar attributeCategories={attributeCategories} />
+ <PersonSidebar
+ attributeCategories={attributeCategories}
+ timeCardEnabled={timeCardEnabled}
+ />
<Outlet />
</div>
</>
diff --git a/apps/erp/app/routes/x+/settings+/people.tsx b/apps/erp/app/routes/x+/settings+/people.tsx
new file mode 100644
index 0000000000..671c6bc8c8
--- /dev/null
+++ b/apps/erp/app/routes/x+/settings+/people.tsx
@@ -0,0 +1,150 @@
+import { error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { Boolean, Submit, ValidatedForm, validator } from "@carbon/form";
+import {
+ Badge,
+ Card,
+ CardContent,
+ CardDescription,
+ CardFooter,
+ CardHeader,
+ CardTitle,
+ Heading,
+ ScrollArea,
+ toast,
+ VStack
+} from "@carbon/react";
+import { useEffect } from "react";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
+import { redirect, useFetcher, useLoaderData } from "react-router";
+import {
+ getCompanySettings,
+ timeCardSettingsValidator,
+ updateTimeCardSetting
+} from "~/modules/settings";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+
+export const handle: Handle = {
+ breadcrumb: "People",
+ to: path.to.peopleSettings
+};
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "settings"
+ });
+
+ const companySettings = await getCompanySettings(client, companyId);
+
+ if (!companySettings.data)
+ throw redirect(
+ path.to.settings,
+ await flash(
+ request,
+ error(companySettings.error, "Failed to get company settings")
+ )
+ );
+ return { companySettings: companySettings.data };
+}
+
+export async function action({ request }: ActionFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ update: "settings"
+ });
+
+ const formData = await request.formData();
+ const intent = formData.get("intent");
+
+ if (intent === "timeCard") {
+ const validation = await validator(timeCardSettingsValidator).validate(
+ formData
+ );
+
+ if (validation.error) {
+ return { success: false, message: "Invalid form data" };
+ }
+
+ const update = await updateTimeCardSetting(
+ client,
+ companyId,
+ validation.data.timeCardEnabled
+ );
+
+ if (update.error) return { success: false, message: update.error.message };
+
+ return { success: true, message: "Timecard settings updated" };
+ }
+
+ return { success: false, message: "Unknown intent" };
+}
+
+export default function PeopleSettingsRoute() {
+ const { companySettings } = useLoaderData<typeof loader>();
+ const fetcher = useFetcher<typeof action>();
+
+ useEffect(() => {
+ if (fetcher.data?.success === true && fetcher?.data?.message) {
+ toast.success(fetcher.data.message);
+ }
+
+ if (fetcher.data?.success === false && fetcher?.data?.message) {
+ toast.error(fetcher.data.message);
+ }
+ }, [fetcher.data?.message, fetcher.data?.success]);
+
+ return (
+ <ScrollArea className="w-full h-[calc(100dvh-49px)]">
+ <VStack
+ spacing={4}
+ className="py-12 px-4 max-w-[60rem] h-full mx-auto gap-4"
+ >
+ <Heading size="h3">People</Heading>
+
+ <Card>
+ <ValidatedForm
+ method="post"
+ validator={timeCardSettingsValidator}
+ defaultValues={{
+ timeCardEnabled: companySettings.timeCardEnabled ?? false
+ }}
+ fetcher={fetcher}
+ >
+ <input type="hidden" name="intent" value="timeCard" />
+ <CardHeader>
+ <CardTitle className="flex items-center gap-2">
+ Timecards
+ </CardTitle>
+ <CardDescription>
+ Enable timecard tracking for work shifts.
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <div className="flex items-center justify-start gap-2">
+ <Boolean
+ name="timeCardEnabled"
+ description="Enable Timecards"
+ />
+ <div>
+ <Badge variant="yellow">Beta</Badge>
+ </div>
+ </div>
+ </CardContent>
+ <CardFooter>
+ <Submit
+ isDisabled={fetcher.state !== "idle"}
+ isLoading={
+ fetcher.state !== "idle" &&
+ fetcher.formData?.get("intent") === "timeCard"
+ }
+ >
+ Save
+ </Submit>
+ </CardFooter>
+ </ValidatedForm>
+ </Card>
+ </VStack>
+ </ScrollArea>
+ );
+}
diff --git a/apps/erp/app/types/index.ts b/apps/erp/app/types/index.ts
index e9887a31b8..f58e41c9ce 100644
--- a/apps/erp/app/types/index.ts
+++ b/apps/erp/app/types/index.ts
@@ -2,6 +2,7 @@ import type { ValidationErrorResponseData } from "@carbon/form";
import type { FileObject } from "@supabase/storage-js";
import type { ReactElement } from "react";
import type { IconType } from "react-icons";
+import type { useSettings } from "~/hooks";
export type Action = {
label: string;
@@ -54,10 +55,11 @@ export type Result = {
export type Role = "employee" | "customer" | "supplier";
-export type Route = {
+export type Route<T = {}> = T & {
name: string;
to: string;
icon?: any;
+ setting?: keyof ReturnType<typeof useSettings>;
views?: {
id: string;
name: string;
@@ -68,10 +70,10 @@ export type Route = {
table?: string;
};
-export type RouteGroup = {
+export type RouteGroup<T = {}> = {
name: string;
icon?: any;
- routes: Route[];
+ routes: (Route & T)[];
};
export interface SelectOption {
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index 6b1e142d4c..9b5271a86f 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -41,6 +41,7 @@ export const path = {
customFieldOptions: (table: string, fieldId: string) =>
generatePath(`${api}/settings/custom-fields/${table}/${fieldId}`),
departments: `${api}/people/departments`,
+ timecard: `${api}/people/timecard`,
outstandingTrainings: `${api}/resources/trainings`,
digitalQuote: (id: string) =>
generatePath(`${api}/sales/digital-quote/${id}`),
@@ -600,6 +601,8 @@ export const path = {
deleteGroup: (id: string) => generatePath(`${x}/users/groups/delete/${id}`),
deleteHoliday: (id: string) =>
generatePath(`${x}/people/holidays/delete/${id}`),
+ deleteTimecard: (id: string) =>
+ generatePath(`${x}/people/timecard/delete/${id}`),
deleteLocation: (id: string) =>
generatePath(`${x}/resources/locations/delete/${id}`),
deleteItem: (id: string) => generatePath(`${x}/items/delete/${id}`),
@@ -1040,6 +1043,7 @@ export const path = {
newGaugeType: `${x}/quality/gauge-types/new`,
newGroup: `${x}/users/groups/new`,
newHoliday: `${x}/people/holidays/new`,
+ newTimecard: `${x}/people/timecard/new`,
newInvestigationType: `${x}/quality/investigation-types/new`,
newIssue: `${x}/issue/new`,
newIssueAssociation: (id: string) =>
@@ -1191,10 +1195,13 @@ export const path = {
generatePath(`${x}/accounting/payment-terms/${id}`),
paymentTerms: `${x}/accounting/payment-terms`,
people: `${x}/people/employee`,
+ peopleTimecard: `${x}/people/timecard`,
+ timecard: (id: string) => generatePath(`${x}/people/timecard/${id}`),
contact: `${x}/people/contact`,
person: (id: string) => generatePath(`${x}/person/${id}`),
personDetails: (id: string) => generatePath(`${x}/person/${id}/details`),
personJob: (id: string) => generatePath(`${x}/person/${id}/job`),
+ personTimecard: (id: string) => generatePath(`${x}/person/${id}/timecard`),
personAttributeCategory: (personId: string, categoryId: string) =>
generatePath(`${x}/person/${personId}/attributes/${categoryId}`),
stockTransfer: (id: string) => generatePath(`${x}/stock-transfer/${id}`),
@@ -1230,6 +1237,7 @@ export const path = {
productionPlanning: `${x}/production/planning`,
productionPlanningItem: (itemId: string) =>
generatePath(`${x}/production/planning/${itemId}`),
+ peopleSettings: `${x}/settings/people`,
productionSettings: `${x}/settings/production`,
profile: `${x}/account/profile`,
purchaseInvoice: (id: string) =>
diff --git a/apps/mes/app/components/AdjustInventory.tsx b/apps/mes/app/components/AdjustInventory.tsx
index 941a8bb6de..ad1c5cc30c 100644
--- a/apps/mes/app/components/AdjustInventory.tsx
+++ b/apps/mes/app/components/AdjustInventory.tsx
@@ -108,7 +108,10 @@ export function AdjustInventory({ add }: { add: boolean }) {
return (
<>
- <SidebarMenuButton onClick={modal.onOpen}>
+ <SidebarMenuButton
+ tooltip={add ? "Add Inventory" : "Remove Inventory"}
+ onClick={modal.onOpen}
+ >
{add ? <LuGitPullRequestCreateArrow /> : <LuGitBranchPlus />}
<span>{add ? "Add" : "Remove"} Inventory</span>
</SidebarMenuButton>
diff --git a/apps/mes/app/components/AppSidebar.tsx b/apps/mes/app/components/AppSidebar.tsx
index e6175b9b0d..faa4af2dfa 100644
--- a/apps/mes/app/components/AppSidebar.tsx
+++ b/apps/mes/app/components/AppSidebar.tsx
@@ -42,7 +42,7 @@ import {
LuCalendarDays,
LuChevronDown,
LuClipboardList,
- LuClock,
+ LuHistory,
LuLogOut,
LuMapPin,
LuMoon,
@@ -59,6 +59,7 @@ import { ERP_URL, path } from "~/utils/path";
import { AdjustInventory } from "./AdjustInventory";
import { EndShift } from "./EndShift";
import Suggestion from "./Suggestion";
+import { TimeCardButton } from "./TimeCardButton";
export function AppSidebar({
activeEvents,
@@ -67,6 +68,8 @@ export function AppSidebar({
companies,
location,
locations,
+ timeCardEnabled,
+ openClockEntry,
...props
}: ComponentProps<typeof Sidebar> & {
activeEvents: number;
@@ -75,6 +78,8 @@ export function AppSidebar({
companies: Company[];
location: string;
locations: Location[];
+ timeCardEnabled?: boolean;
+ openClockEntry?: { id: string; clockIn: string } | null;
}) {
return (
<Sidebar collapsible="icon" {...props}>
@@ -89,6 +94,11 @@ export function AppSidebar({
<ToolsNav />
</SidebarContent>
<SidebarFooter>
+ {timeCardEnabled && (
+ <SidebarMenu>
+ <TimeCardButton openClockEntry={openClockEntry ?? null} />
+ </SidebarMenu>
+ )}
<UserNav
company={company}
companies={companies}
@@ -162,7 +172,7 @@ export function OperationsNav({
},
{
title: "Recent",
- icon: LuClock,
+ icon: LuHistory,
to: path.to.recent
},
{
diff --git a/apps/mes/app/components/EndShift.tsx b/apps/mes/app/components/EndShift.tsx
index 526049d427..169445fc28 100644
--- a/apps/mes/app/components/EndShift.tsx
+++ b/apps/mes/app/components/EndShift.tsx
@@ -38,11 +38,11 @@ export function EndShift() {
useEffect(() => {
if (fetcher.data?.success === true) {
confirmModal.onClose();
- toast.success(fetcher.data?.message ?? "Shift ended");
+ toast.success(fetcher.data?.message ?? "Operations ended");
}
if (fetcher.data?.success === false) {
- toast.error(fetcher.data?.message ?? "Failed to end shift");
+ toast.error(fetcher.data?.message ?? "Failed to end operations");
}
}, [fetcher.data?.success]);
@@ -66,9 +66,9 @@ export function EndShift() {
return (
<>
- <SidebarMenuButton onClick={openModal}>
+ <SidebarMenuButton tooltip="End Operations" onClick={openModal}>
<LuCircleStop />
- <span>End Shift</span>
+ <span>End Operations</span>
</SidebarMenuButton>
{confirmModal.isOpen && (
<Modal
@@ -77,7 +77,7 @@ export function EndShift() {
>
<ModalContent>
<ModalHeader>
- <ModalTitle>End Shift</ModalTitle>
+ <ModalTitle>End Operations</ModalTitle>
<ModalDescription>
Are you sure you want to end all production events? This will
end all active operations without completing or finishing them.
@@ -141,7 +141,7 @@ export function EndShift() {
isLoading={fetcher.state !== "idle"}
variant="destructive"
>
- End Shift
+ End Operations
</Button>
</ModalFooter>
</fetcher.Form>
diff --git a/apps/mes/app/components/Suggestion.tsx b/apps/mes/app/components/Suggestion.tsx
index e0ab85a2da..b2c9d435ce 100644
--- a/apps/mes/app/components/Suggestion.tsx
+++ b/apps/mes/app/components/Suggestion.tsx
@@ -108,7 +108,7 @@ const Suggestion = () => {
return (
<Popover>
<PopoverTrigger ref={popoverTriggerRef} asChild>
- <SidebarMenuButton>
+ <SidebarMenuButton tooltip="Suggestion">
<LuMailbox />
<span>Suggestion</span>
</SidebarMenuButton>
diff --git a/apps/mes/app/components/TimeCardButton.tsx b/apps/mes/app/components/TimeCardButton.tsx
new file mode 100644
index 0000000000..f6918a4694
--- /dev/null
+++ b/apps/mes/app/components/TimeCardButton.tsx
@@ -0,0 +1,114 @@
+import {
+ Badge,
+ SidebarMenuButton,
+ SidebarMenuItem,
+ useSidebar
+} from "@carbon/react";
+import { useEffect, useState } from "react";
+import { LuClock, LuPlay, LuSquare } from "react-icons/lu";
+import { Link, useFetcher, useLocation } from "react-router";
+import { path } from "~/utils/path";
+
+type TimeCardButtonProps = {
+ openClockEntry: {
+ id: string;
+ clockIn: string;
+ } | null;
+};
+
+function formatElapsed(since: string) {
+ const ms = Date.now() - new Date(since).getTime();
+ const hours = Math.floor(ms / 3600000);
+ const minutes = Math.floor((ms % 3600000) / 60000);
+ return `${hours}h ${minutes}m`;
+}
+
+export function TimeCardButton({ openClockEntry }: TimeCardButtonProps) {
+ const fetcher = useFetcher();
+ const { isMobile, setOpenMobile } = useSidebar();
+ const { pathname } = useLocation();
+ const [, setTick] = useState(0);
+
+ const isClockedIn =
+ openClockEntry !== null ||
+ (fetcher.formData?.get("intent") === "clockIn" && fetcher.state !== "idle");
+
+ useEffect(() => {
+ if (!openClockEntry) return;
+ const interval = setInterval(() => setTick((t) => t + 1), 60000);
+ return () => clearInterval(interval);
+ }, [openClockEntry]);
+
+ const handleClockOut = () => {
+ if (isMobile) setOpenMobile(false);
+ const formData = new FormData();
+ formData.append("intent", "clockOut");
+ fetcher.submit(formData, {
+ method: "post",
+ action: path.to.timecard
+ });
+ };
+
+ const handleClockIn = () => {
+ if (isMobile) setOpenMobile(false);
+ const formData = new FormData();
+ formData.append("intent", "clockIn");
+ fetcher.submit(formData, {
+ method: "post",
+ action: path.to.timecard
+ });
+ };
+
+ const isOnTimeCardPage = pathname.includes("/timecard");
+
+ return (
+ <>
+ {isClockedIn ? (
+ <SidebarMenuItem>
+ <SidebarMenuButton
+ tooltip="Clock Out"
+ onClick={handleClockOut}
+ disabled={fetcher.state !== "idle"}
+ className="font-medium"
+ >
+ <LuSquare className="size-4" />
+ <span>Clock Out</span>
+ {openClockEntry && (
+ <Badge variant="red" className="ml-auto">
+ {formatElapsed(openClockEntry.clockIn)}
+ </Badge>
+ )}
+ </SidebarMenuButton>
+ </SidebarMenuItem>
+ ) : (
+ <SidebarMenuItem>
+ <SidebarMenuButton
+ tooltip="Clock In"
+ onClick={handleClockIn}
+ disabled={fetcher.state !== "idle"}
+ className="font-medium"
+ >
+ <LuPlay className="size-4" />
+ <span>Clock In</span>
+ </SidebarMenuButton>
+ </SidebarMenuItem>
+ )}
+
+ <SidebarMenuItem>
+ <SidebarMenuButton
+ tooltip="My Hours"
+ isActive={isOnTimeCardPage}
+ asChild
+ >
+ <Link
+ to={path.to.timeCardPage}
+ onClick={() => isMobile && setOpenMobile(false)}
+ >
+ <LuClock />
+ <span>My Hours</span>
+ </Link>
+ </SidebarMenuButton>
+ </SidebarMenuItem>
+ </>
+ );
+}
diff --git a/apps/mes/app/components/TimeCardWarning.tsx b/apps/mes/app/components/TimeCardWarning.tsx
new file mode 100644
index 0000000000..f9ff55d3d9
--- /dev/null
+++ b/apps/mes/app/components/TimeCardWarning.tsx
@@ -0,0 +1,148 @@
+"use client";
+
+import {
+ Button,
+ Input,
+ Modal,
+ ModalBody,
+ ModalContent,
+ ModalDescription,
+ ModalFooter,
+ ModalHeader,
+ ModalTitle,
+ toast,
+ VStack
+} from "@carbon/react";
+import { useEffect, useState } from "react";
+import { useFetcher } from "react-router";
+import { path } from "~/utils/path";
+
+const TWELVE_HOURS_MS = 12 * 60 * 60 * 1000;
+const CHECK_INTERVAL_MS = 5 * 60 * 1000;
+const CLOCK_STORAGE_KEY = "timeclock-warning-ack";
+
+type TimeCardWarningProps = {
+ openClockEntry: {
+ id: string;
+ clockIn: string;
+ } | null;
+};
+
+export function TimeCardWarning({ openClockEntry }: TimeCardWarningProps) {
+ const [showClockWarning, setShowClockWarning] = useState(false);
+ const [editClockOut, setEditClockOut] = useState("");
+ const fetcher = useFetcher();
+
+ useEffect(() => {
+ if (!openClockEntry) {
+ setShowClockWarning(false);
+ return;
+ }
+
+ const checkStale = () => {
+ const elapsed = Date.now() - new Date(openClockEntry.clockIn).getTime();
+ if (elapsed < TWELVE_HOURS_MS) {
+ setShowClockWarning(false);
+ return;
+ }
+
+ const acked = sessionStorage.getItem(CLOCK_STORAGE_KEY);
+ if (acked === openClockEntry.id) {
+ setShowClockWarning(false);
+ return;
+ }
+
+ setShowClockWarning(true);
+ };
+
+ checkStale();
+ const interval = setInterval(checkStale, CHECK_INTERVAL_MS);
+ return () => clearInterval(interval);
+ }, [openClockEntry]);
+
+ useEffect(() => {
+ if (fetcher.data && fetcher.state === "idle") {
+ if ((fetcher.data as { success?: boolean }).success) {
+ toast.success("Updated successfully");
+ setShowClockWarning(false);
+ }
+ }
+ }, [fetcher.data, fetcher.state]);
+
+ const handleClockAcknowledge = () => {
+ if (openClockEntry) {
+ sessionStorage.setItem(CLOCK_STORAGE_KEY, openClockEntry.id);
+ }
+ setShowClockWarning(false);
+ };
+
+ const handleEditClockOut = () => {
+ if (!editClockOut || !openClockEntry) return;
+ const formData = new FormData();
+ formData.append("intent", "clockOut");
+ formData.append("clockOut", new Date(editClockOut).toISOString());
+ fetcher.submit(formData, {
+ method: "post",
+ action: path.to.timecard
+ });
+ };
+
+ if (showClockWarning && openClockEntry) {
+ const hoursElapsed = Math.floor(
+ (Date.now() - new Date(openClockEntry.clockIn).getTime()) / 3600000
+ );
+
+ return (
+ <Modal
+ open
+ onOpenChange={() => {
+ /* intentionally non-dismissable */
+ }}
+ >
+ <ModalContent>
+ <ModalHeader>
+ <ModalTitle>Forgot to Clock Out?</ModalTitle>
+ <ModalDescription>
+ You&apos;ve been clocked in for {hoursElapsed} hours. Did you
+ forget to clock out?
+ </ModalDescription>
+ </ModalHeader>
+ <ModalBody>
+ <VStack spacing={4}>
+ <p className="text-sm text-muted-foreground">
+ You clocked in at{" "}
+ {new Date(openClockEntry.clockIn).toLocaleString()}. You can
+ edit your clock-out time below or acknowledge that you&apos;re
+ still working.
+ </p>
+ <div className="flex flex-col gap-2">
+ <label className="text-sm font-medium">
+ Set clock-out time
+ </label>
+ <Input
+ type="datetime-local"
+ value={editClockOut}
+ onChange={(e) => setEditClockOut(e.target.value)}
+ />
+ </div>
+ </VStack>
+ </ModalBody>
+ <ModalFooter>
+ <Button variant="secondary" onClick={handleClockAcknowledge}>
+ I&apos;m Still Working
+ </Button>
+ <Button
+ onClick={handleEditClockOut}
+ isDisabled={!editClockOut || fetcher.state !== "idle"}
+ isLoading={fetcher.state !== "idle"}
+ >
+ Set Clock Out
+ </Button>
+ </ModalFooter>
+ </ModalContent>
+ </Modal>
+ );
+ }
+
+ return null;
+}
diff --git a/apps/mes/app/routes/api+/timecard.ts b/apps/mes/app/routes/api+/timecard.ts
new file mode 100644
index 0000000000..efc417f55c
--- /dev/null
+++ b/apps/mes/app/routes/api+/timecard.ts
@@ -0,0 +1,32 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import type { ActionFunctionArgs } from "react-router";
+import { clockIn, clockOut } from "~/services/people.service";
+
+export async function action({ request }: ActionFunctionArgs) {
+ const { client, companyId, userId } = await requirePermissions(request, {});
+
+ const formData = await request.formData();
+ const intent = formData.get("intent");
+
+ if (intent === "clockIn") {
+ const result = await clockIn(client, {
+ employeeId: userId,
+ companyId,
+ createdBy: userId
+ });
+ return { success: !result.error, error: result.error?.message };
+ }
+
+ if (intent === "clockOut") {
+ const note = formData.get("note") as string | null;
+ const result = await clockOut(client, {
+ employeeId: userId,
+ companyId,
+ updatedBy: userId,
+ note: note ?? undefined
+ });
+ return { success: !result.error, error: result.error?.message };
+ }
+
+ return { success: false, error: "Unknown intent" };
+}
diff --git a/apps/mes/app/routes/x+/_layout.tsx b/apps/mes/app/routes/x+/_layout.tsx
index bf4eda4a77..0e901e205f 100644
--- a/apps/mes/app/routes/x+/_layout.tsx
+++ b/apps/mes/app/routes/x+/_layout.tsx
@@ -30,6 +30,7 @@ import {
} from "react-router";
import { AppSidebar } from "~/components";
import RealtimeDataProvider from "~/components/RealtimeDataProvider";
+import { TimeCardWarning } from "~/components/TimeCardWarning";
import { userContext } from "~/context";
import { userMiddleware } from "~/middleware/user";
import { getActiveMaintenanceEventsCount } from "~/services/maintenance.service";
@@ -37,6 +38,7 @@ import {
getActiveJobCount,
getLocationsByCompany
} from "~/services/operations.service";
+import { getOpenClockEntry } from "~/services/people.service";
import { ERP_URL, MES_URL, path } from "~/utils/path";
export const shouldRevalidate: ShouldRevalidateFunction = ({
@@ -80,14 +82,21 @@ export async function loader({ request, context }: LoaderFunctionArgs) {
// Get the location from middleware context
const locationId = context.get(userContext)?.locationId;
- let [companyPlan, locations, activeEvents] = await Promise.all([
- getStripeCustomerByCompanyId(companyId, userId),
- getLocationsByCompany(client, companyId),
- getActiveJobCount(client, {
- employeeId: userId,
- companyId
- })
- ]);
+ let [companyPlan, locations, activeEvents, companySettings, openClockEntry] =
+ await Promise.all([
+ getStripeCustomerByCompanyId(companyId, userId),
+ getLocationsByCompany(client, companyId),
+ getActiveJobCount(client, {
+ employeeId: userId,
+ companyId
+ }),
+ client
+ .from("companySettings")
+ .select("timeCardEnabled")
+ .eq("id", companyId)
+ .single(),
+ getOpenClockEntry(client, userId, companyId)
+ ]);
// Get active maintenance count after we have the location
const activeMaintenanceCount = await getActiveMaintenanceEventsCount(
@@ -116,7 +125,11 @@ export async function loader({ request, context }: LoaderFunctionArgs) {
location: locationId,
locations: locations.data ?? [],
plan: companyPlan?.planId,
- user: user.data
+ user: user.data,
+ timeCardEnabled: companySettings.data?.timeCardEnabled ?? false,
+ openClockEntry: openClockEntry.data
+ ? { id: openClockEntry.data.id, clockIn: openClockEntry.data.clockIn }
+ : null
});
}
@@ -129,7 +142,9 @@ export default function AuthenticatedRoute() {
companies,
location,
locations,
- user
+ user,
+ timeCardEnabled,
+ openClockEntry
} = useLoaderData<typeof loader>();
const navigate = useNavigate();
@@ -175,8 +190,13 @@ export default function AuthenticatedRoute() {
companies={companies}
location={location}
locations={locations}
+ timeCardEnabled={timeCardEnabled}
+ openClockEntry={openClockEntry}
/>
<Outlet />
+ {timeCardEnabled && (
+ <TimeCardWarning openClockEntry={openClockEntry} />
+ )}
</TooltipProvider>
</SidebarProvider>
</RealtimeDataProvider>
diff --git a/apps/mes/app/routes/x+/timecard.tsx b/apps/mes/app/routes/x+/timecard.tsx
new file mode 100644
index 0000000000..b4c7c6fb6b
--- /dev/null
+++ b/apps/mes/app/routes/x+/timecard.tsx
@@ -0,0 +1,505 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import {
+ Badge,
+ Button,
+ Card,
+ CardContent,
+ CardHeader,
+ CardTitle,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuIcon,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ HStack,
+ IconButton,
+ Input,
+ Modal,
+ ModalBody,
+ ModalContent,
+ ModalFooter,
+ ModalHeader,
+ ModalOverlay,
+ ModalTitle,
+ Table as TableBase,
+ Tbody,
+ Td,
+ Th,
+ Thead,
+ Tr
+} from "@carbon/react";
+import { formatDate } from "@carbon/utils";
+import { useEffect, useState } from "react";
+import {
+ LuChevronLeft,
+ LuChevronRight,
+ LuEllipsisVertical,
+ LuPencil,
+ LuPlay,
+ LuTrash
+} from "react-icons/lu";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
+import { Link, useFetcher, useLoaderData } from "react-router";
+import {
+ clockIn,
+ clockOut,
+ getOpenClockEntry,
+ updateTimeCardEntry
+} from "~/services/people.service";
+import { path } from "~/utils/path";
+
+function getWeekBounds(offset: number = 0) {
+ const now = new Date();
+ const dayOfWeek = now.getDay();
+ const monday = new Date(now);
+ monday.setDate(now.getDate() - ((dayOfWeek + 6) % 7) + offset * 7);
+ monday.setHours(0, 0, 0, 0);
+
+ const sunday = new Date(monday);
+ sunday.setDate(monday.getDate() + 6);
+ sunday.setHours(23, 59, 59, 999);
+
+ return {
+ from: monday.toISOString(),
+ to: sunday.toISOString(),
+ monday,
+ sunday
+ };
+}
+
+function formatDuration(clockInStr: string, clockOutStr: string | null) {
+ const end = clockOutStr ? new Date(clockOutStr).getTime() : Date.now();
+ const ms = end - new Date(clockInStr).getTime();
+ const hours = Math.floor(ms / 3600000);
+ const minutes = Math.floor((ms % 3600000) / 60000);
+ return `${hours}h ${minutes}m`;
+}
+
+function formatTotalHours(
+ entries: { clockIn: string; clockOut: string | null }[]
+) {
+ let totalMs = 0;
+ for (const entry of entries) {
+ const end = entry.clockOut
+ ? new Date(entry.clockOut).getTime()
+ : Date.now();
+ totalMs += end - new Date(entry.clockIn).getTime();
+ }
+ const hours = Math.floor(totalMs / 3600000);
+ const minutes = Math.floor((totalMs % 3600000) / 60000);
+ return `${hours}h ${minutes}m`;
+}
+
+function formatTime(dateStr: string) {
+ return new Date(dateStr).toLocaleTimeString([], {
+ hour: "2-digit",
+ minute: "2-digit"
+ });
+}
+
+function formatDay(dateStr: string) {
+ return new Date(dateStr).toLocaleDateString([], {
+ weekday: "short",
+ month: "short",
+ day: "numeric"
+ });
+}
+
+function toLocalDatetimeInput(dateStr: string) {
+ const d = new Date(dateStr);
+ const year = d.getFullYear();
+ const month = String(d.getMonth() + 1).padStart(2, "0");
+ const day = String(d.getDate()).padStart(2, "0");
+ const hours = String(d.getHours()).padStart(2, "0");
+ const minutes = String(d.getMinutes()).padStart(2, "0");
+ return `${year}-${month}-${day}T${hours}:${minutes}`;
+}
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId, userId } = await requirePermissions(request, {});
+
+ const url = new URL(request.url);
+ const weekOffset = parseInt(url.searchParams.get("week") ?? "0", 10);
+ const { from, to } = getWeekBounds(weekOffset);
+
+ const [entries, openEntry] = await Promise.all([
+ client
+ .from("timeCardEntry")
+ .select("*")
+ .eq("employeeId", userId)
+ .eq("companyId", companyId)
+ .gte("clockIn", from)
+ .lte("clockIn", to)
+ .order("clockIn", { ascending: false }),
+ getOpenClockEntry(client, userId, companyId)
+ ]);
+
+ return {
+ entries: entries.data ?? [],
+ openEntry: openEntry.data,
+ weekOffset,
+ from,
+ to
+ };
+}
+
+export async function action({ request }: ActionFunctionArgs) {
+ const { client, companyId, userId } = await requirePermissions(request, {});
+
+ const formData = await request.formData();
+ const intent = formData.get("intent");
+
+ if (intent === "clockIn") {
+ const result = await clockIn(client, {
+ employeeId: userId,
+ companyId,
+ createdBy: userId
+ });
+ return { success: !result.error, error: result.error?.message };
+ }
+
+ if (intent === "clockOut") {
+ const result = await clockOut(client, {
+ employeeId: userId,
+ companyId,
+ updatedBy: userId
+ });
+ return { success: !result.error, error: result.error?.message };
+ }
+
+ if (intent === "updateEntry") {
+ const entryId = formData.get("entryId") as string;
+ const clockInVal = formData.get("clockIn") as string;
+ const clockOutVal = formData.get("clockOut") as string | null;
+ const result = await updateTimeCardEntry(client, {
+ entryId,
+ clockIn: clockInVal,
+ clockOut: clockOutVal || null,
+ updatedBy: userId
+ });
+ return { success: !result.error, error: result.error?.message };
+ }
+
+ if (intent === "deleteEntry") {
+ const entryId = formData.get("entryId") as string;
+ const result = await client
+ .from("timeCardEntry")
+ .delete()
+ .eq("id", entryId);
+ return { success: !result.error, error: result.error?.message };
+ }
+
+ return { success: false, error: "Unknown intent" };
+}
+
+export default function MESTimecardPage() {
+ const { entries, openEntry, weekOffset, from, to } =
+ useLoaderData<typeof loader>();
+ const fetcher = useFetcher<typeof action>();
+ const [editingId, setEditingId] = useState<string | null>(null);
+ const [editClockIn, setEditClockIn] = useState("");
+ const [editClockOut, setEditClockOut] = useState("");
+ const [, setTick] = useState(0);
+ const [deletingEntry, setDeletingEntry] = useState<{
+ id: string;
+ clockIn: string;
+ } | null>(null);
+
+ const monday = new Date(from);
+ const sunday = new Date(to);
+ const isCurrentWeek = weekOffset === 0;
+
+ useEffect(() => {
+ const interval = setInterval(() => setTick((t) => t + 1), 60000);
+ return () => clearInterval(interval);
+ }, []);
+
+ useEffect(() => {
+ if (fetcher.data && fetcher.state === "idle") {
+ setEditingId(null);
+ }
+ }, [fetcher.data, fetcher.state]);
+
+ function startEdit(entry: {
+ id: string;
+ clockIn: string;
+ clockOut: string | null;
+ }) {
+ setEditingId(entry.id);
+ setEditClockIn(toLocalDatetimeInput(entry.clockIn));
+ setEditClockOut(entry.clockOut ? toLocalDatetimeInput(entry.clockOut) : "");
+ }
+
+ return (
+ <div className="flex flex-col h-full w-full overflow-y-auto p-4 md:p-6">
+ <div className="max-w-[60rem] mx-auto w-full">
+ <Card className="overflow-hidden">
+ <CardHeader>
+ <HStack className="justify-between items-center">
+ <CardTitle>My Hours</CardTitle>
+ <HStack className="gap-1">
+ {openEntry ? (
+ <fetcher.Form method="post">
+ <input type="hidden" name="intent" value="clockOut" />
+ <Button
+ variant="destructive"
+ type="submit"
+ disabled={fetcher.state !== "idle"}
+ >
+ Clock Out
+ </Button>
+ </fetcher.Form>
+ ) : (
+ <fetcher.Form method="post">
+ <input type="hidden" name="intent" value="clockIn" />
+ <Button
+ leftIcon={<LuPlay />}
+ type="submit"
+ disabled={fetcher.state !== "idle"}
+ >
+ Clock In
+ </Button>
+ </fetcher.Form>
+ )}
+ </HStack>
+ </HStack>
+ {openEntry && (
+ <Badge variant="green" className="w-fit">
+ Clocked in since {formatTime(openEntry.clockIn)}
+ </Badge>
+ )}
+ </CardHeader>
+ <CardContent>
+ <HStack className="justify-between items-center mb-4">
+ <Button variant="outline" asChild leftIcon={<LuChevronLeft />}>
+ <Link to={`${path.to.timeCardPage}?week=${weekOffset - 1}`}>
+ Prev
+ </Link>
+ </Button>
+ <span className="text-sm text-muted-foreground">
+ {formatDate(monday.toISOString(), { dateStyle: "medium" })} —{" "}
+ {formatDate(sunday.toISOString(), { dateStyle: "medium" })}
+ </span>
+ <Button
+ variant="outline"
+ disabled={isCurrentWeek}
+ asChild={!isCurrentWeek}
+ rightIcon={<LuChevronRight />}
+ >
+ {isCurrentWeek ? (
+ <span>Next</span>
+ ) : (
+ <Link to={`${path.to.timeCardPage}?week=${weekOffset + 1}`}>
+ Next
+ </Link>
+ )}
+ </Button>
+ </HStack>
+
+ <TableBase className="table-fixed w-full">
+ <colgroup>
+ <col className="w-[16%]" />
+ <col className="w-[28%]" />
+ <col className="w-[28%]" />
+ <col className="w-[12%]" />
+ <col className="w-[16%]" />
+ </colgroup>
+ <Thead>
+ <Tr>
+ <Th className="whitespace-nowrap">Date</Th>
+ <Th>Clock In</Th>
+ <Th>Clock Out</Th>
+ <Th className="text-center">Duration</Th>
+ <Th />
+ </Tr>
+ </Thead>
+ <Tbody>
+ {entries.length === 0 ? (
+ <Tr>
+ <Td
+ colSpan={5}
+ className="text-center text-muted-foreground py-8"
+ >
+ No time entries for this week
+ </Td>
+ </Tr>
+ ) : (
+ entries.map((entry) =>
+ editingId === entry.id ? (
+ <Tr key={entry.id}>
+ <Td className="whitespace-nowrap">
+ {formatDay(entry.clockIn)}
+ </Td>
+ <Td>
+ <Input
+ type="datetime-local"
+ value={editClockIn}
+ onChange={(e) => setEditClockIn(e.target.value)}
+ className="h-8 text-xs w-full [&::-webkit-calendar-picker-indicator]:hidden"
+ />
+ </Td>
+ <Td>
+ <Input
+ type="datetime-local"
+ value={editClockOut}
+ onChange={(e) => setEditClockOut(e.target.value)}
+ className="h-8 text-xs w-full [&::-webkit-calendar-picker-indicator]:hidden"
+ />
+ </Td>
+ <Td className="text-muted-foreground text-center">—</Td>
+ <Td className="text-center">
+ <HStack className="justify-center">
+ <fetcher.Form method="post">
+ <input
+ type="hidden"
+ name="intent"
+ value="updateEntry"
+ />
+ <input
+ type="hidden"
+ name="entryId"
+ value={entry.id}
+ />
+ <input
+ type="hidden"
+ name="clockIn"
+ value={
+ isNaN(new Date(editClockIn).getTime())
+ ? ""
+ : new Date(editClockIn).toISOString()
+ }
+ />
+ {editClockOut &&
+ !isNaN(new Date(editClockOut).getTime()) && (
+ <input
+ type="hidden"
+ name="clockOut"
+ value={new Date(editClockOut).toISOString()}
+ />
+ )}
+ <Button
+ variant="secondary"
+ type="submit"
+ disabled={isNaN(
+ new Date(editClockIn).getTime()
+ )}
+ >
+ Save
+ </Button>
+ </fetcher.Form>
+ <Button
+ variant="ghost"
+ onClick={() => setEditingId(null)}
+ >
+ Cancel
+ </Button>
+ </HStack>
+ </Td>
+ </Tr>
+ ) : (
+ <Tr key={entry.id}>
+ <Td className="whitespace-nowrap">
+ {formatDay(entry.clockIn)}
+ </Td>
+ <Td>{formatTime(entry.clockIn)}</Td>
+ <Td>
+ {entry.clockOut ? (
+ formatTime(entry.clockOut)
+ ) : (
+ <Badge variant="green">Active</Badge>
+ )}
+ </Td>
+ <Td className="text-center">
+ {formatDuration(entry.clockIn, entry.clockOut)}
+ </Td>
+ <Td className="text-right">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ aria-label="More options"
+ variant="ghost"
+ icon={<LuEllipsisVertical />}
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem
+ onClick={() => startEdit(entry)}
+ >
+ <DropdownMenuIcon icon={<LuPencil />} />
+ Edit
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onClick={() =>
+ setDeletingEntry({
+ id: entry.id,
+ clockIn: entry.clockIn
+ })
+ }
+ className="text-destructive"
+ >
+ <DropdownMenuIcon icon={<LuTrash />} />
+ Delete
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </Td>
+ </Tr>
+ )
+ )
+ )}
+ </Tbody>
+ </TableBase>
+
+ {entries.length > 0 && (
+ <div className="mt-4 text-right text-sm font-medium">
+ Total: {formatTotalHours(entries)}
+ </div>
+ )}
+ </CardContent>
+ </Card>
+ </div>
+ {deletingEntry && (
+ <Modal
+ open
+ onOpenChange={(open) => {
+ if (!open) setDeletingEntry(null);
+ }}
+ >
+ <ModalOverlay />
+ <ModalContent>
+ <ModalHeader>
+ <ModalTitle>
+ Delete Timecard (
+ {new Date(deletingEntry.clockIn).toLocaleString()})
+ </ModalTitle>
+ </ModalHeader>
+ <ModalBody>
+ Are you sure you want to delete this timecard? This cannot be
+ undone.
+ </ModalBody>
+ <ModalFooter>
+ <Button
+ variant="secondary"
+ onClick={() => setDeletingEntry(null)}
+ >
+ Cancel
+ </Button>
+ <Button
+ variant="destructive"
+ onClick={() => {
+ const formData = new FormData();
+ formData.append("intent", "deleteEntry");
+ formData.append("entryId", deletingEntry.id);
+ fetcher.submit(formData, { method: "post" });
+ setDeletingEntry(null);
+ }}
+ >
+ Delete
+ </Button>
+ </ModalFooter>
+ </ModalContent>
+ </Modal>
+ )}
+ </div>
+ );
+}
diff --git a/apps/mes/app/services/people.service.ts b/apps/mes/app/services/people.service.ts
new file mode 100644
index 0000000000..4576f39914
--- /dev/null
+++ b/apps/mes/app/services/people.service.ts
@@ -0,0 +1,93 @@
+import type { Database } from "@carbon/database";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import { sanitize } from "~/utils/supabase";
+
+export async function getOpenClockEntry(
+ client: SupabaseClient<Database>,
+ employeeId: string,
+ companyId: string
+) {
+ return client
+ .from("timeCardEntry")
+ .select("*")
+ .eq("employeeId", employeeId)
+ .eq("companyId", companyId)
+ .is("clockOut", null)
+ .maybeSingle();
+}
+
+export async function clockIn(
+ client: SupabaseClient<Database>,
+ args: {
+ employeeId: string;
+ companyId: string;
+ createdBy: string;
+ }
+) {
+ const existing = await getOpenClockEntry(
+ client,
+ args.employeeId,
+ args.companyId
+ );
+ if (existing.data) {
+ return { data: null, error: { message: "Already clocked in" } };
+ }
+
+ return client.from("timeCardEntry").insert({
+ employeeId: args.employeeId,
+ companyId: args.companyId,
+ createdBy: args.createdBy
+ });
+}
+
+export async function clockOut(
+ client: SupabaseClient<Database>,
+ args: {
+ employeeId: string;
+ companyId: string;
+ updatedBy: string;
+ clockOut?: string;
+ note?: string;
+ }
+) {
+ const open = await getOpenClockEntry(client, args.employeeId, args.companyId);
+ if (!open.data) {
+ return { data: null, error: { message: "Not currently clocked in" } };
+ }
+
+ return client
+ .from("timeCardEntry")
+ .update(
+ sanitize({
+ clockOut: args.clockOut ?? new Date().toISOString(),
+ note: args.note,
+ updatedBy: args.updatedBy,
+ updatedAt: new Date().toISOString()
+ })
+ )
+ .eq("id", open.data.id);
+}
+
+export async function updateTimeCardEntry(
+ client: SupabaseClient<Database>,
+ args: {
+ entryId: string;
+ clockIn?: string;
+ clockOut?: string | null;
+ note?: string | null;
+ updatedBy: string;
+ }
+) {
+ return client
+ .from("timeCardEntry")
+ .update(
+ sanitize({
+ clockIn: args.clockIn,
+ clockOut: args.clockOut,
+ note: args.note,
+ updatedBy: args.updatedBy,
+ updatedAt: new Date().toISOString()
+ })
+ )
+ .eq("id", args.entryId);
+}
diff --git a/apps/mes/app/utils/path.ts b/apps/mes/app/utils/path.ts
index 60bbad957b..9217d4f96f 100644
--- a/apps/mes/app/utils/path.ts
+++ b/apps/mes/app/utils/path.ts
@@ -140,6 +140,8 @@ export const path = {
switchCompany: (companyId: string) =>
generatePath(`${x}/company/switch/${companyId}`),
suggestion: `${x}/suggestion`,
+ timecard: `${api}/timecard`,
+ timeCardPage: `${x}/timecard`,
unconsume: `${x}/unconsume`,
workCenter: (workCenter: string) =>
generatePath(`${x}/operations/${workCenter}`),
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index 78ef0027c8..e3731f1e2b 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -17469,6 +17469,105 @@ export default {
tags: ["nonConformanceCustomer"],
},
},
+ "/timeCardEntries": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.timeCardEntries.id",
+ },
+ {
+ $ref: "#/parameters/rowFilter.timeCardEntries.employeeId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.timeCardEntries.companyId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.timeCardEntries.clockIn",
+ },
+ {
+ $ref: "#/parameters/rowFilter.timeCardEntries.clockOut",
+ },
+ {
+ $ref: "#/parameters/rowFilter.timeCardEntries.note",
+ },
+ {
+ $ref: "#/parameters/rowFilter.timeCardEntries.autoCloseShiftId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.timeCardEntries.createdBy",
+ },
+ {
+ $ref: "#/parameters/rowFilter.timeCardEntries.createdAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.timeCardEntries.updatedBy",
+ },
+ {
+ $ref: "#/parameters/rowFilter.timeCardEntries.updatedAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.timeCardEntries.firstName",
+ },
+ {
+ $ref: "#/parameters/rowFilter.timeCardEntries.lastName",
+ },
+ {
+ $ref: "#/parameters/rowFilter.timeCardEntries.avatarUrl",
+ },
+ {
+ $ref: "#/parameters/rowFilter.timeCardEntries.jobTitle",
+ },
+ {
+ $ref: "#/parameters/rowFilter.timeCardEntries.shiftId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.timeCardEntries.locationId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.timeCardEntries.shiftName",
+ },
+ {
+ $ref: "#/parameters/rowFilter.timeCardEntries.locationName",
+ },
+ {
+ $ref: "#/parameters/select",
+ },
+ {
+ $ref: "#/parameters/order",
+ },
+ {
+ $ref: "#/parameters/range",
+ },
+ {
+ $ref: "#/parameters/rangeUnit",
+ },
+ {
+ $ref: "#/parameters/offset",
+ },
+ {
+ $ref: "#/parameters/limit",
+ },
+ {
+ $ref: "#/parameters/preferCount",
+ },
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ schema: {
+ items: {
+ $ref: "#/definitions/timeCardEntries",
+ },
+ type: "array",
+ },
+ },
+ "206": {
+ description: "Partial Content",
+ },
+ },
+ tags: ["timeCardEntries"],
+ },
+ },
"/materialDimensions": {
get: {
parameters: [
@@ -56328,6 +56427,195 @@ export default {
tags: ["supplier"],
},
},
+ "/timeCardEntry": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.timeCardEntry.id",
+ },
+ {
+ $ref: "#/parameters/rowFilter.timeCardEntry.employeeId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.timeCardEntry.companyId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.timeCardEntry.clockIn",
+ },
+ {
+ $ref: "#/parameters/rowFilter.timeCardEntry.clockOut",
+ },
+ {
+ $ref: "#/parameters/rowFilter.timeCardEntry.note",
+ },
+ {
+ $ref: "#/parameters/rowFilter.timeCardEntry.autoCloseShiftId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.timeCardEntry.createdBy",
+ },
+ {
+ $ref: "#/parameters/rowFilter.timeCardEntry.createdAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.timeCardEntry.updatedBy",
+ },
+ {
+ $ref: "#/parameters/rowFilter.timeCardEntry.updatedAt",
+ },
+ {
+ $ref: "#/parameters/select",
+ },
+ {
+ $ref: "#/parameters/order",
+ },
+ {
+ $ref: "#/parameters/range",
+ },
+ {
+ $ref: "#/parameters/rangeUnit",
+ },
+ {
+ $ref: "#/parameters/offset",
+ },
+ {
+ $ref: "#/parameters/limit",
+ },
+ {
+ $ref: "#/parameters/preferCount",
+ },
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ schema: {
+ items: {
+ $ref: "#/definitions/timeCardEntry",
+ },
+ type: "array",
+ },
+ },
+ "206": {
+ description: "Partial Content",
+ },
+ },
+ tags: ["timeCardEntry"],
+ },
+ post: {
+ parameters: [
+ {
+ $ref: "#/parameters/body.timeCardEntry",
+ },
+ {
+ $ref: "#/parameters/select",
+ },
+ {
+ $ref: "#/parameters/preferPost",
+ },
+ ],
+ responses: {
+ "201": {
+ description: "Created",
+ },
+ },
+ tags: ["timeCardEntry"],
+ },
+ delete: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.timeCardEntry.id",
+ },
+ {
+ $ref: "#/parameters/rowFilter.timeCardEntry.employeeId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.timeCardEntry.companyId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.timeCardEntry.clockIn",
+ },
+ {
+ $ref: "#/parameters/rowFilter.timeCardEntry.clockOut",
+ },
+ {
+ $ref: "#/parameters/rowFilter.timeCardEntry.note",
+ },
+ {
+ $ref: "#/parameters/rowFilter.timeCardEntry.autoCloseShiftId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.timeCardEntry.createdBy",
+ },
+ {
+ $ref: "#/parameters/rowFilter.timeCardEntry.createdAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.timeCardEntry.updatedBy",
+ },
+ {
+ $ref: "#/parameters/rowFilter.timeCardEntry.updatedAt",
+ },
+ {
+ $ref: "#/parameters/preferReturn",
+ },
+ ],
+ responses: {
+ "204": {
+ description: "No Content",
+ },
+ },
+ tags: ["timeCardEntry"],
+ },
+ patch: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.timeCardEntry.id",
+ },
+ {
+ $ref: "#/parameters/rowFilter.timeCardEntry.employeeId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.timeCardEntry.companyId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.timeCardEntry.clockIn",
+ },
+ {
+ $ref: "#/parameters/rowFilter.timeCardEntry.clockOut",
+ },
+ {
+ $ref: "#/parameters/rowFilter.timeCardEntry.note",
+ },
+ {
+ $ref: "#/parameters/rowFilter.timeCardEntry.autoCloseShiftId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.timeCardEntry.createdBy",
+ },
+ {
+ $ref: "#/parameters/rowFilter.timeCardEntry.createdAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.timeCardEntry.updatedBy",
+ },
+ {
+ $ref: "#/parameters/rowFilter.timeCardEntry.updatedAt",
+ },
+ {
+ $ref: "#/parameters/body.timeCardEntry",
+ },
+ {
+ $ref: "#/parameters/preferReturn",
+ },
+ ],
+ responses: {
+ "204": {
+ description: "No Content",
+ },
+ },
+ tags: ["timeCardEntry"],
+ },
+ },
"/stockTransfer": {
get: {
parameters: [
@@ -62703,6 +62991,9 @@ export default {
{
$ref: "#/parameters/rowFilter.companySettings.qualityIssueTarget",
},
+ {
+ $ref: "#/parameters/rowFilter.companySettings.timeCardEnabled",
+ },
{
$ref: "#/parameters/select",
},
@@ -62861,6 +63152,9 @@ export default {
{
$ref: "#/parameters/rowFilter.companySettings.qualityIssueTarget",
},
+ {
+ $ref: "#/parameters/rowFilter.companySettings.timeCardEnabled",
+ },
{
$ref: "#/parameters/preferReturn",
},
@@ -62973,6 +63267,9 @@ export default {
{
$ref: "#/parameters/rowFilter.companySettings.qualityIssueTarget",
},
+ {
+ $ref: "#/parameters/rowFilter.companySettings.timeCardEnabled",
+ },
{
$ref: "#/parameters/body.companySettings",
},
@@ -77701,6 +77998,102 @@ export default {
},
type: "object",
},
+ timeCardEntries: {
+ properties: {
+ id: {
+ description: "Note:\nThis is a Primary Key.<pk/>",
+ format: "text",
+ type: "string",
+ },
+ employeeId: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ companyId: {
+ description:
+ "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ clockIn: {
+ format: "timestamp with time zone",
+ type: "string",
+ },
+ clockOut: {
+ format: "timestamp with time zone",
+ type: "string",
+ },
+ note: {
+ format: "text",
+ type: "string",
+ },
+ autoCloseShiftId: {
+ description:
+ "Note:\nThis is a Foreign Key to `shift.id`.<fk table='shift' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ createdBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ createdAt: {
+ format: "timestamp with time zone",
+ type: "string",
+ },
+ updatedBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ updatedAt: {
+ format: "timestamp with time zone",
+ type: "string",
+ },
+ firstName: {
+ format: "text",
+ type: "string",
+ },
+ lastName: {
+ format: "text",
+ type: "string",
+ },
+ avatarUrl: {
+ format: "text",
+ type: "string",
+ },
+ jobTitle: {
+ format: "text",
+ type: "string",
+ },
+ shiftId: {
+ description:
+ "Note:\nThis is a Foreign Key to `shift.id`.<fk table='shift' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ locationId: {
+ description:
+ "Note:\nThis is a Foreign Key to `location.id`.<fk table='location' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ shiftName: {
+ format: "text",
+ type: "string",
+ },
+ locationName: {
+ format: "text",
+ type: "string",
+ },
+ },
+ type: "object",
+ },
materialDimensions: {
properties: {
id: {
@@ -95992,6 +96385,77 @@ export default {
},
type: "object",
},
+ timeCardEntry: {
+ required: [
+ "id",
+ "employeeId",
+ "companyId",
+ "clockIn",
+ "createdBy",
+ "createdAt",
+ ],
+ properties: {
+ id: {
+ default: "public.xid()",
+ description: "Note:\nThis is a Primary Key.<pk/>",
+ format: "text",
+ type: "string",
+ },
+ employeeId: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ companyId: {
+ description:
+ "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ clockIn: {
+ default: "now()",
+ format: "timestamp with time zone",
+ type: "string",
+ },
+ clockOut: {
+ format: "timestamp with time zone",
+ type: "string",
+ },
+ note: {
+ format: "text",
+ type: "string",
+ },
+ autoCloseShiftId: {
+ description:
+ "Note:\nThis is a Foreign Key to `shift.id`.<fk table='shift' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ createdBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ createdAt: {
+ default: "now()",
+ format: "timestamp with time zone",
+ type: "string",
+ },
+ updatedBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ updatedAt: {
+ format: "timestamp with time zone",
+ type: "string",
+ },
+ },
+ type: "object",
+ },
stockTransfer: {
required: [
"id",
@@ -99156,6 +99620,7 @@ export default {
"jobTravelerIncludeWorkInstructions",
"supplierApproval",
"qualityIssueTarget",
+ "timeCardEnabled",
],
properties: {
id: {
@@ -99346,6 +99811,11 @@ export default {
format: "integer",
type: "integer",
},
+ timeCardEnabled: {
+ default: false,
+ format: "boolean",
+ type: "boolean",
+ },
},
type: "object",
},
@@ -109286,6 +109756,129 @@ export default {
in: "query",
type: "string",
},
+ "body.timeCardEntries": {
+ name: "timeCardEntries",
+ description: "timeCardEntries",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/timeCardEntries",
+ },
+ },
+ "rowFilter.timeCardEntries.id": {
+ name: "id",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.timeCardEntries.employeeId": {
+ name: "employeeId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.timeCardEntries.companyId": {
+ name: "companyId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.timeCardEntries.clockIn": {
+ name: "clockIn",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.timeCardEntries.clockOut": {
+ name: "clockOut",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.timeCardEntries.note": {
+ name: "note",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.timeCardEntries.autoCloseShiftId": {
+ name: "autoCloseShiftId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.timeCardEntries.createdBy": {
+ name: "createdBy",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.timeCardEntries.createdAt": {
+ name: "createdAt",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.timeCardEntries.updatedBy": {
+ name: "updatedBy",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.timeCardEntries.updatedAt": {
+ name: "updatedAt",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.timeCardEntries.firstName": {
+ name: "firstName",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.timeCardEntries.lastName": {
+ name: "lastName",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.timeCardEntries.avatarUrl": {
+ name: "avatarUrl",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.timeCardEntries.jobTitle": {
+ name: "jobTitle",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.timeCardEntries.shiftId": {
+ name: "shiftId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.timeCardEntries.locationId": {
+ name: "locationId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.timeCardEntries.shiftName": {
+ name: "shiftName",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.timeCardEntries.locationName": {
+ name: "locationName",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"body.materialDimensions": {
name: "materialDimensions",
description: "materialDimensions",
@@ -129982,6 +130575,81 @@ export default {
in: "query",
type: "string",
},
+ "body.timeCardEntry": {
+ name: "timeCardEntry",
+ description: "timeCardEntry",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/timeCardEntry",
+ },
+ },
+ "rowFilter.timeCardEntry.id": {
+ name: "id",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.timeCardEntry.employeeId": {
+ name: "employeeId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.timeCardEntry.companyId": {
+ name: "companyId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.timeCardEntry.clockIn": {
+ name: "clockIn",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.timeCardEntry.clockOut": {
+ name: "clockOut",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.timeCardEntry.note": {
+ name: "note",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.timeCardEntry.autoCloseShiftId": {
+ name: "autoCloseShiftId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.timeCardEntry.createdBy": {
+ name: "createdBy",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.timeCardEntry.createdAt": {
+ name: "createdAt",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.timeCardEntry.updatedBy": {
+ name: "updatedBy",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.timeCardEntry.updatedAt": {
+ name: "updatedAt",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"body.stockTransfer": {
name: "stockTransfer",
description: "stockTransfer",
@@ -133663,6 +134331,12 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.companySettings.timeCardEnabled": {
+ name: "timeCardEnabled",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"body.part": {
name: "part",
description: "part",
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 8c9ff8ac20..5d7f22a143 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -2951,6 +2951,7 @@ export type Database = {
shelfLabelSize: string | null
supplierApproval: boolean
supplierQuoteNotificationGroup: string[]
+ timeCardEnabled: boolean
useMetric: boolean
}
Insert: {
@@ -2986,6 +2987,7 @@ export type Database = {
shelfLabelSize?: string | null
supplierApproval?: boolean
supplierQuoteNotificationGroup?: string[]
+ timeCardEnabled?: boolean
useMetric?: boolean
}
Update: {
@@ -3021,6 +3023,7 @@ export type Database = {
shelfLabelSize?: string | null
supplierApproval?: boolean
supplierQuoteNotificationGroup?: string[]
+ timeCardEnabled?: boolean
useMetric?: boolean
}
Relationships: [
@@ -39014,6 +39017,196 @@ export type Database = {
},
]
}
+ timeCardEntry: {
+ Row: {
+ autoCloseShiftId: string | null
+ clockIn: string
+ clockOut: string | null
+ companyId: string
+ createdAt: string
+ createdBy: string
+ employeeId: string
+ id: string
+ note: string | null
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Insert: {
+ autoCloseShiftId?: string | null
+ clockIn?: string
+ clockOut?: string | null
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ employeeId: string
+ id?: string
+ note?: string | null
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Update: {
+ autoCloseShiftId?: string | null
+ clockIn?: string
+ clockOut?: string | null
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ employeeId?: string
+ id?: string
+ note?: string | null
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "timeCardEntry_autoCloseShiftId_fkey"
+ columns: ["autoCloseShiftId"]
+ isOneToOne: false
+ referencedRelation: "shift"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_autoCloseShiftId_fkey"
+ columns: ["autoCloseShiftId"]
+ isOneToOne: false
+ referencedRelation: "shifts"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_employeeId_fkey"
+ columns: ["employeeId"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_employeeId_fkey"
+ columns: ["employeeId"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_employeeId_fkey"
+ columns: ["employeeId"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_employeeId_fkey"
+ columns: ["employeeId"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_employeeId_fkey"
+ columns: ["employeeId"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
tool: {
Row: {
approved: boolean
@@ -55289,6 +55482,199 @@ export type Database = {
},
]
}
+ timeCardEntries: {
+ Row: {
+ autoCloseShiftId: string | null
+ avatarUrl: string | null
+ clockIn: string | null
+ clockOut: string | null
+ companyId: string | null
+ createdAt: string | null
+ createdBy: string | null
+ employeeId: string | null
+ firstName: string | null
+ id: string | null
+ jobTitle: string | null
+ lastName: string | null
+ locationId: string | null
+ locationName: string | null
+ note: string | null
+ shiftId: string | null
+ shiftName: string | null
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "employeeJob_locationId_fkey"
+ columns: ["locationId"]
+ isOneToOne: false
+ referencedRelation: "location"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "employeeJob_shiftId_fkey"
+ columns: ["shiftId"]
+ isOneToOne: false
+ referencedRelation: "shift"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "employeeJob_shiftId_fkey"
+ columns: ["shiftId"]
+ isOneToOne: false
+ referencedRelation: "shifts"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_autoCloseShiftId_fkey"
+ columns: ["autoCloseShiftId"]
+ isOneToOne: false
+ referencedRelation: "shift"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_autoCloseShiftId_fkey"
+ columns: ["autoCloseShiftId"]
+ isOneToOne: false
+ referencedRelation: "shifts"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_employeeId_fkey"
+ columns: ["employeeId"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_employeeId_fkey"
+ columns: ["employeeId"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_employeeId_fkey"
+ columns: ["employeeId"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_employeeId_fkey"
+ columns: ["employeeId"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_employeeId_fkey"
+ columns: ["employeeId"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
tools: {
Row: {
active: boolean | null
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 8c9ff8ac20..5d7f22a143 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -2951,6 +2951,7 @@ export type Database = {
shelfLabelSize: string | null
supplierApproval: boolean
supplierQuoteNotificationGroup: string[]
+ timeCardEnabled: boolean
useMetric: boolean
}
Insert: {
@@ -2986,6 +2987,7 @@ export type Database = {
shelfLabelSize?: string | null
supplierApproval?: boolean
supplierQuoteNotificationGroup?: string[]
+ timeCardEnabled?: boolean
useMetric?: boolean
}
Update: {
@@ -3021,6 +3023,7 @@ export type Database = {
shelfLabelSize?: string | null
supplierApproval?: boolean
supplierQuoteNotificationGroup?: string[]
+ timeCardEnabled?: boolean
useMetric?: boolean
}
Relationships: [
@@ -39014,6 +39017,196 @@ export type Database = {
},
]
}
+ timeCardEntry: {
+ Row: {
+ autoCloseShiftId: string | null
+ clockIn: string
+ clockOut: string | null
+ companyId: string
+ createdAt: string
+ createdBy: string
+ employeeId: string
+ id: string
+ note: string | null
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Insert: {
+ autoCloseShiftId?: string | null
+ clockIn?: string
+ clockOut?: string | null
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ employeeId: string
+ id?: string
+ note?: string | null
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Update: {
+ autoCloseShiftId?: string | null
+ clockIn?: string
+ clockOut?: string | null
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ employeeId?: string
+ id?: string
+ note?: string | null
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "timeCardEntry_autoCloseShiftId_fkey"
+ columns: ["autoCloseShiftId"]
+ isOneToOne: false
+ referencedRelation: "shift"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_autoCloseShiftId_fkey"
+ columns: ["autoCloseShiftId"]
+ isOneToOne: false
+ referencedRelation: "shifts"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_employeeId_fkey"
+ columns: ["employeeId"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_employeeId_fkey"
+ columns: ["employeeId"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_employeeId_fkey"
+ columns: ["employeeId"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_employeeId_fkey"
+ columns: ["employeeId"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_employeeId_fkey"
+ columns: ["employeeId"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
tool: {
Row: {
approved: boolean
@@ -55289,6 +55482,199 @@ export type Database = {
},
]
}
+ timeCardEntries: {
+ Row: {
+ autoCloseShiftId: string | null
+ avatarUrl: string | null
+ clockIn: string | null
+ clockOut: string | null
+ companyId: string | null
+ createdAt: string | null
+ createdBy: string | null
+ employeeId: string | null
+ firstName: string | null
+ id: string | null
+ jobTitle: string | null
+ lastName: string | null
+ locationId: string | null
+ locationName: string | null
+ note: string | null
+ shiftId: string | null
+ shiftName: string | null
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "employeeJob_locationId_fkey"
+ columns: ["locationId"]
+ isOneToOne: false
+ referencedRelation: "location"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "employeeJob_shiftId_fkey"
+ columns: ["shiftId"]
+ isOneToOne: false
+ referencedRelation: "shift"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "employeeJob_shiftId_fkey"
+ columns: ["shiftId"]
+ isOneToOne: false
+ referencedRelation: "shifts"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_autoCloseShiftId_fkey"
+ columns: ["autoCloseShiftId"]
+ isOneToOne: false
+ referencedRelation: "shift"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_autoCloseShiftId_fkey"
+ columns: ["autoCloseShiftId"]
+ isOneToOne: false
+ referencedRelation: "shifts"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_employeeId_fkey"
+ columns: ["employeeId"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_employeeId_fkey"
+ columns: ["employeeId"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_employeeId_fkey"
+ columns: ["employeeId"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_employeeId_fkey"
+ columns: ["employeeId"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_employeeId_fkey"
+ columns: ["employeeId"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "timeCardEntry_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
tools: {
Row: {
active: boolean | null
diff --git a/packages/database/supabase/migrations/20260319200000_employee-time-clock.sql b/packages/database/supabase/migrations/20260319200000_employee-time-clock.sql
new file mode 100644
index 0000000000..98eec20fd6
--- /dev/null
+++ b/packages/database/supabase/migrations/20260319200000_employee-time-clock.sql
@@ -0,0 +1,117 @@
+-- Employee Time Clock feature: shift clock-in/clock-out tracking
+
+-- 1. Add timeCardEnabled toggle to companySettings
+ALTER TABLE "companySettings" ADD COLUMN "timeCardEnabled" BOOLEAN NOT NULL DEFAULT false;
+
+-- 2. Create timeCardEntry table
+CREATE TABLE "timeCardEntry" (
+ "id" TEXT NOT NULL DEFAULT id('tce'),
+ "employeeId" TEXT NOT NULL,
+ "companyId" TEXT NOT NULL,
+ "clockIn" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
+ "clockOut" TIMESTAMP WITH TIME ZONE,
+ "note" TEXT,
+ "autoCloseShiftId" TEXT,
+ "createdBy" TEXT NOT NULL,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
+ "updatedBy" TEXT,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+
+ CONSTRAINT "timeCardEntry_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "timeCardEntry_employeeId_fkey" FOREIGN KEY ("employeeId") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "timeCardEntry_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "timeCardEntry_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE,
+ CONSTRAINT "timeCardEntry_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE,
+ CONSTRAINT "timeCardEntry_autoCloseShiftId_fkey" FOREIGN KEY ("autoCloseShiftId") REFERENCES "shift"("id") ON DELETE SET NULL ON UPDATE CASCADE,
+ CONSTRAINT "timeCardEntry_clockOut_after_clockIn" CHECK ("clockOut" IS NULL OR "clockOut" >= "clockIn")
+);
+
+-- 3. Indexes
+CREATE INDEX "timeCardEntry_employeeId_companyId_idx" ON "timeCardEntry" ("employeeId", "companyId");
+CREATE INDEX "timeCardEntry_clockIn_idx" ON "timeCardEntry" ("clockIn");
+CREATE INDEX "timeCardEntry_open_entries_idx" ON "timeCardEntry" ("companyId", "employeeId") WHERE "clockOut" IS NULL;
+
+-- 4. RLS Policies
+ALTER TABLE "timeCardEntry" ENABLE ROW LEVEL SECURITY;
+
+-- SELECT: Employee can see own entries OR user has people_view permission
+CREATE POLICY "SELECT" ON "timeCardEntry"
+FOR SELECT USING (
+ (
+ "employeeId" = auth.uid()::text
+ AND "companyId" = ANY (
+ (SELECT get_companies_with_employee_role())::text[]
+ )
+ )
+ OR
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('people_view'))::text[]
+ )
+);
+
+-- INSERT: Employee can clock themselves in OR user has people_create permission
+CREATE POLICY "INSERT" ON "timeCardEntry"
+FOR INSERT WITH CHECK (
+ (
+ "employeeId" = auth.uid()::text
+ AND "companyId" = ANY (
+ (SELECT get_companies_with_employee_role())::text[]
+ )
+ )
+ OR
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('people_create'))::text[]
+ )
+);
+
+-- UPDATE: Employee can update own entries OR user has people_update permission
+CREATE POLICY "UPDATE" ON "timeCardEntry"
+FOR UPDATE USING (
+ (
+ "employeeId" = auth.uid()::text
+ AND "companyId" = ANY (
+ (SELECT get_companies_with_employee_role())::text[]
+ )
+ )
+ OR
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('people_update'))::text[]
+ )
+);
+
+-- DELETE: Only users with people_delete permission
+CREATE POLICY "DELETE" ON "timeCardEntry"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (SELECT get_companies_with_employee_permission('people_delete'))::text[]
+ )
+);
+
+-- 5. Dashboard view
+CREATE OR REPLACE VIEW "timeCardEntries" WITH (SECURITY_INVOKER=true) AS
+SELECT
+ tce."id",
+ tce."employeeId",
+ tce."companyId",
+ tce."clockIn",
+ tce."clockOut",
+ tce."note",
+ tce."autoCloseShiftId",
+ tce."createdBy",
+ tce."createdAt",
+ tce."updatedBy",
+ tce."updatedAt",
+ u."firstName",
+ u."lastName",
+ u."avatarUrl",
+ ej."title" AS "jobTitle",
+ ej."shiftId",
+ ej."locationId",
+ s."name" AS "shiftName",
+ l."name" AS "locationName",
+ CASE WHEN tce."clockOut" IS NULL THEN 'Active' ELSE 'Complete' END AS "status"
+FROM "timeCardEntry" tce
+INNER JOIN "user" u ON tce."employeeId" = u."id"
+LEFT JOIN "employeeJob" ej ON ej."id" = tce."employeeId" AND ej."companyId" = tce."companyId"
+LEFT JOIN "shift" s ON ej."shiftId" = s."id"
+LEFT JOIN "location" l ON ej."locationId" = l."id";
diff --git a/packages/jobs/trigger/timecard-auto-close.ts b/packages/jobs/trigger/timecard-auto-close.ts
new file mode 100644
index 0000000000..ba0c831eb0
--- /dev/null
+++ b/packages/jobs/trigger/timecard-auto-close.ts
@@ -0,0 +1,138 @@
+import { getCarbonServiceRole } from "@carbon/auth";
+import { schedules } from "@trigger.dev/sdk";
+
+const serviceRole = getCarbonServiceRole();
+
+export const timeCardAutoClose = schedules.task({
+ id: "timecard-auto-close",
+ // Run every Sunday at 11pm UTC (after weekly task at 9pm)
+ cron: "0 23 * * 0",
+ run: async () => {
+ console.log(
+ `🕐 Starting timecard auto-close: ${new Date().toISOString()}`
+ );
+
+ try {
+ // 1. Get all companies with time clock enabled
+ const { data: companies, error: companiesError } = await serviceRole
+ .from("companySettings")
+ .select("id")
+ .eq("timeCardEnabled", true);
+
+ if (companiesError) {
+ console.error(
+ `Failed to fetch companies: ${companiesError.message}`
+ );
+ return;
+ }
+
+ console.log(
+ `Found ${companies?.length || 0} companies with time clock enabled`
+ );
+
+ let totalClosed = 0;
+
+ for (const company of companies ?? []) {
+ // 2. Get all open time clock entries for this company
+ const { data: openEntries, error: entriesError } = await serviceRole
+ .from("timeCardEntry")
+ .select("id, employeeId, clockIn")
+ .eq("companyId", company.id)
+ .is("clockOut", null);
+
+ if (entriesError) {
+ console.error(
+ `Failed to fetch open entries for company ${company.id}: ${entriesError.message}`
+ );
+ continue;
+ }
+
+ if (!openEntries || openEntries.length === 0) continue;
+
+ console.log(
+ `Company ${company.id}: ${openEntries.length} open entries`
+ );
+
+ for (const entry of openEntries) {
+ // 3. Get the employee's assigned shift
+ const { data: employeeJob } = await serviceRole
+ .from("employeeJob")
+ .select("shiftId")
+ .eq("id", entry.employeeId)
+ .eq("companyId", company.id)
+ .single();
+
+ let clockOut: Date;
+ let shiftId: string | null = null;
+
+ if (employeeJob?.shiftId) {
+ const { data: shift } = await serviceRole
+ .from("shift")
+ .select("startTime, endTime")
+ .eq("id", employeeJob.shiftId)
+ .single();
+
+ if (shift) {
+ // Calculate shift duration
+ const startParts = shift.startTime.split(":").map(Number);
+ const endParts = shift.endTime.split(":").map(Number);
+ let durationMinutes =
+ endParts[0] * 60 +
+ endParts[1] -
+ (startParts[0] * 60 + startParts[1]);
+ // Handle overnight shifts
+ if (durationMinutes <= 0) durationMinutes += 24 * 60;
+
+ clockOut = new Date(
+ new Date(entry.clockIn).getTime() + durationMinutes * 60000
+ );
+ shiftId = employeeJob.shiftId;
+ } else {
+ // Shift not found, fall back to 8 hours
+ clockOut = new Date(
+ new Date(entry.clockIn).getTime() + 8 * 3600000
+ );
+ }
+ } else {
+ // No shift assigned, fall back to 8 hours
+ clockOut = new Date(
+ new Date(entry.clockIn).getTime() + 8 * 3600000
+ );
+ }
+
+ // 4. Update the entry
+ const { error: updateError } = await serviceRole
+ .from("timeCardEntry")
+ .update({
+ clockOut: clockOut.toISOString(),
+ autoCloseShiftId: shiftId,
+ updatedAt: new Date().toISOString(),
+ note: "Auto-closed by system (Sunday weekly close)"
+ })
+ .eq("id", entry.id);
+
+ if (updateError) {
+ console.error(
+ `Failed to auto-close entry ${entry.id}: ${updateError.message}`
+ );
+ } else {
+ totalClosed++;
+ console.log(
+ `Auto-closed entry ${entry.id} for employee ${entry.employeeId}`
+ );
+ }
+ }
+ }
+
+ console.log(
+ `🕐 Timecard auto-close completed: ${totalClosed} entries closed`
+ );
+ } catch (err) {
+ console.error(
+ `Unexpected error in timecard auto-close: ${
+ err instanceof Error ? err.message : String(err)
+ }`
+ );
+ }
+ }
+});