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: assignment crud

Brad Barbin09fa6bfd6e42
diff --git a/apps/erp/app/modules/people/people.models.ts b/apps/erp/app/modules/people/people.models.ts
index 8afef947dd..3d6e11fe03 100644
--- a/apps/erp/app/modules/people/people.models.ts
+++ b/apps/erp/app/modules/people/people.models.ts
@@ -200,3 +200,22 @@ export const trainingQuestionValidator = z
path: ["correctNumber"],
}
);
+
+export const trainingAssignmentValidator = z.object({
+ id: zfd.numeric(z.number().optional()),
+ trainingId: z.string().min(1, { message: "Training is required" }),
+ groupIds: z.array(z.string()).min(1, { message: "At least one group is required" }),
+});
+
+export const trainingCompletionValidator = z.object({
+ trainingAssignmentId: zfd.numeric(),
+ employeeId: z.string().min(1, { message: "Employee is required" }),
+ period: zfd.text(z.string().optional()),
+});
+
+export const trainingAssignmentStatusOptions = [
+ "Completed",
+ "Pending",
+ "Overdue",
+ "Not Required",
+] as const;
diff --git a/apps/erp/app/modules/people/people.service.ts b/apps/erp/app/modules/people/people.service.ts
index 43ed480cff..051b8ace41 100644
--- a/apps/erp/app/modules/people/people.service.ts
+++ b/apps/erp/app/modules/people/people.service.ts
@@ -476,6 +476,43 @@ export async function getTrainingsList(
.order("name", { ascending: true });
}
+export async function getTrainingAssignmentStatus(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ args?: {
+ trainingId?: string;
+ status?: "Completed" | "Pending" | "Overdue" | "Not Required";
+ search?: string;
+ } & GenericQueryFilters
+) {
+ let query = client
+ .from("trainingAssignmentStatus")
+ .select("*", { count: "exact" })
+ .eq("companyId", companyId);
+
+ if (args?.trainingId) query = query.eq("trainingId", args.trainingId);
+ if (args?.status) query = query.eq("status", args.status);
+ if (args?.search)
+ query = query.or(
+ `trainingName.ilike.%${args.search}%,employeeName.ilike.%${args.search}%`
+ );
+ if (args)
+ query = setGenericQueryFilters(query, args, [
+ { column: "employeeName", ascending: true },
+ ]);
+
+ return query;
+}
+
+export async function getTrainingAssignmentSummary(
+ client: SupabaseClient<Database>,
+ companyId: string
+) {
+ return client.rpc("get_training_assignment_summary", {
+ company_id: companyId,
+ });
+}
+
export async function insertAttribute(
client: SupabaseClient<Database>,
attribute: {
@@ -734,3 +771,93 @@ export async function upsertTrainingQuestion(
.select("id")
.single();
}
+
+export async function upsertTrainingAssignment(
+ client: SupabaseClient<Database>,
+ assignment: {
+ id?: number;
+ trainingId: string;
+ groupIds: string[];
+ companyId: string;
+ createdBy?: string;
+ updatedBy?: string;
+ }
+) {
+ if (assignment.id) {
+ return client
+ .from("trainingAssignment")
+ .update({
+ groupIds: assignment.groupIds,
+ updatedBy: assignment.updatedBy,
+ })
+ .eq("id", assignment.id)
+ .select("id")
+ .single();
+ }
+ return client
+ .from("trainingAssignment")
+ .insert({
+ trainingId: assignment.trainingId,
+ groupIds: assignment.groupIds,
+ companyId: assignment.companyId,
+ createdBy: assignment.createdBy!,
+ })
+ .select("id")
+ .single();
+}
+
+export async function insertTrainingCompletion(
+ client: SupabaseClient<Database>,
+ completion: {
+ trainingAssignmentId: number;
+ employeeId: string;
+ period: string | null;
+ companyId: string;
+ completedBy: string;
+ createdBy: string;
+ }
+) {
+ return client
+ .from("trainingCompletion")
+ .insert({
+ ...completion,
+ completedAt: new Date().toISOString(),
+ })
+ .select("id")
+ .single();
+}
+
+export async function getTrainingAssignment(
+ client: SupabaseClient<Database>,
+ assignmentId: number
+) {
+ return client
+ .from("trainingAssignment")
+ .select("*, training(id, name, frequency, type, status)")
+ .eq("id", assignmentId)
+ .single();
+}
+
+export async function getTrainingAssignments(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ trainingId?: string
+) {
+ let query = client
+ .from("trainingAssignment")
+ .select("*, training(id, name, frequency)")
+ .eq("companyId", companyId);
+
+ if (trainingId) {
+ query = query.eq("trainingId", trainingId);
+ }
+
+ return query;
+}
+
+export async function deleteTrainingAssignment(
+ client: SupabaseClient<Database>,
+ assignmentId: number
+) {
+ return client.from("trainingAssignment").delete().eq("id", assignmentId);
+}
diff --git a/apps/erp/app/modules/people/types.ts b/apps/erp/app/modules/people/types.ts
index b860c879ee..e0c1af5d23 100644
--- a/apps/erp/app/modules/people/types.ts
+++ b/apps/erp/app/modules/people/types.ts
@@ -9,9 +9,11 @@ import type {
getPeople,
getShifts,
getTraining,
+ getTrainingAssignment,
getTrainingQuestions,
getTrainings,
} from "./people.service";
+import type { trainingAssignmentStatusOptions, trainingFrequency } from "./people.models";
export type Attribute = NonNullable<
Awaited<ReturnType<typeof getAttribute>>["data"]
@@ -73,3 +75,36 @@ export type TrainingListItem = NonNullable<
export type TrainingQuestion = NonNullable<
Awaited<ReturnType<typeof getTrainingQuestions>>["data"]
>[number];
+
+export type TrainingAssignmentStatusItem = {
+ trainingAssignmentId: number;
+ trainingId: string;
+ trainingName: string;
+ frequency: (typeof trainingFrequency)[number];
+ type: "Mandatory" | "Optional";
+ employeeId: string;
+ employeeName: string | null;
+ avatarUrl: string | null;
+ employeeStartDate: string | null;
+ companyId: string;
+ currentPeriod: string | null;
+ completionId: number | null;
+ completedAt: string | null;
+ status: (typeof trainingAssignmentStatusOptions)[number];
+};
+
+export type TrainingAssignmentSummaryItem = {
+ trainingId: string;
+ trainingName: string;
+ frequency: (typeof trainingFrequency)[number];
+ currentPeriod: string | null;
+ totalAssigned: number;
+ completed: number;
+ pending: number;
+ overdue: number;
+ completionPercent: number;
+};
+
+export type TrainingAssignment = NonNullable<
+ Awaited<ReturnType<typeof getTrainingAssignment>>["data"]
+>;
diff --git a/apps/erp/app/modules/people/ui/Training/TrainingAssignmentForm.tsx b/apps/erp/app/modules/people/ui/Training/TrainingAssignmentForm.tsx
new file mode 100644
index 0000000000..7cff4ae7c4
--- /dev/null
+++ b/apps/erp/app/modules/people/ui/Training/TrainingAssignmentForm.tsx
@@ -0,0 +1,329 @@
+import { Select, ValidatedForm } from "@carbon/form";
+import {
+ Badge,
+ Button,
+ HStack,
+ ModalDrawer,
+ ModalDrawerBody,
+ ModalDrawerContent,
+ ModalDrawerFooter,
+ ModalDrawerHeader,
+ ModalDrawerProvider,
+ ModalDrawerTitle,
+ Tabs,
+ TabsContent,
+ TabsList,
+ TabsTrigger,
+ VStack,
+} from "@carbon/react";
+import { useFetcher } from "@remix-run/react";
+import { memo, useState } from "react";
+import type { ColumnDef } from "@tanstack/react-table";
+import {
+ LuTriangleAlert,
+ LuCalendar,
+ LuCircleCheck,
+ LuClock,
+ LuUser,
+} from "react-icons/lu";
+import type { z } from "zod/v3";
+import { EmployeeAvatar, Table } from "~/components";
+import { Hidden, Submit, Users } from "~/components/Form";
+import { usePermissions } from "~/hooks";
+import { trainingAssignmentValidator } from "~/modules/people";
+import type {
+ TrainingAssignmentStatusItem,
+ TrainingListItem,
+} from "~/modules/people/types";
+import { path } from "~/utils/path";
+
+type TrainingAssignmentFormProps = {
+ initialValues: z.infer<typeof trainingAssignmentValidator>;
+ trainings: TrainingListItem[];
+ assignmentStatus?: TrainingAssignmentStatusItem[];
+ currentPeriod?: string | null;
+ open?: boolean;
+ onClose: () => void;
+};
+
+function StatusBadge({ status }: { status: string }) {
+ switch (status) {
+ case "Completed":
+ return (
+ <Badge variant="green">
+ <LuCircleCheck className="mr-1" />
+ Completed
+ </Badge>
+ );
+ case "Pending":
+ return (
+ <Badge variant="secondary">
+ <LuClock className="mr-1" />
+ Pending
+ </Badge>
+ );
+ case "Overdue":
+ return (
+ <Badge variant="red">
+ <LuTriangleAlert className="mr-1" />
+ Overdue
+ </Badge>
+ );
+ case "Not Required":
+ return <Badge variant="outline">Not Required</Badge>;
+ default:
+ return <Badge variant="secondary">{status}</Badge>;
+ }
+}
+
+const StatusTable = memo(
+ ({
+ data,
+ currentPeriod,
+ }: {
+ data: TrainingAssignmentStatusItem[];
+ currentPeriod: string | null;
+ }) => {
+ const permissions = usePermissions();
+ const fetcher = useFetcher();
+
+ const columns: ColumnDef<TrainingAssignmentStatusItem>[] = [
+ {
+ accessorKey: "employeeName",
+ header: "Employee",
+ cell: ({ row }) => (
+ <HStack spacing={2}>
+ <EmployeeAvatar employeeId={row.original.employeeId} />
+ <span>{row.original.employeeName}</span>
+ </HStack>
+ ),
+ meta: {
+ icon: <LuUser />,
+ },
+ },
+ {
+ accessorKey: "employeeStartDate",
+ header: "Start Date",
+ cell: ({ row }) =>
+ row.original.employeeStartDate
+ ? new Date(row.original.employeeStartDate).toLocaleDateString()
+ : "-",
+ meta: {
+ icon: <LuCalendar />,
+ },
+ },
+ {
+ accessorKey: "status",
+ header: "Status",
+ cell: ({ row }) => <StatusBadge status={row.original.status} />,
+ },
+ {
+ accessorKey: "completedAt",
+ header: "Completed At",
+ cell: ({ row }) =>
+ row.original.completedAt
+ ? new Date(row.original.completedAt).toLocaleDateString()
+ : "-",
+ meta: {
+ icon: <LuClock />,
+ },
+ },
+ {
+ id: "actions",
+ header: "",
+ cell: ({ row }) => {
+ if (
+ row.original.status === "Completed" ||
+ row.original.status === "Not Required"
+ ) {
+ return null;
+ }
+ const isSubmitting = fetcher.state !== "idle";
+ return (
+ <fetcher.Form method="post" action={path.to.markTrainingComplete}>
+ <input
+ type="hidden"
+ name="trainingAssignmentId"
+ value={row.original.trainingAssignmentId}
+ />
+ <input
+ type="hidden"
+ name="employeeId"
+ value={row.original.employeeId}
+ />
+ <input type="hidden" name="period" value={currentPeriod ?? ""} />
+ <Button
+ type="submit"
+ variant="secondary"
+ size="sm"
+ leftIcon={<LuCircleCheck />}
+ disabled={!permissions.can("update", "people") || isSubmitting}
+ isLoading={isSubmitting}
+ >
+ Mark Complete
+ </Button>
+ </fetcher.Form>
+ );
+ },
+ },
+ ];
+
+ return (
+ <Table<TrainingAssignmentStatusItem>
+ data={data}
+ columns={columns}
+ count={data.length}
+ withPagination={false}
+ />
+ );
+ }
+);
+
+StatusTable.displayName = "StatusTable";
+
+const TrainingAssignmentForm = ({
+ initialValues,
+ trainings,
+ assignmentStatus = [],
+ currentPeriod = null,
+ open = true,
+ onClose,
+}: TrainingAssignmentFormProps) => {
+ const permissions = usePermissions();
+ const fetcher = useFetcher();
+
+ const isEditing = initialValues.id !== undefined;
+ const isDisabled = isEditing
+ ? !permissions.can("update", "people")
+ : !permissions.can("create", "people");
+
+ const [activeTab, setActiveTab] = useState<string>("details");
+
+ return (
+ <ModalDrawerProvider type="drawer">
+ <ModalDrawer
+ open={open}
+ onOpenChange={(open) => {
+ if (!open) onClose?.();
+ }}
+ >
+ <ModalDrawerContent>
+ <Tabs
+ value={activeTab}
+ onValueChange={setActiveTab}
+ className="flex flex-col h-full"
+ >
+ <ValidatedForm
+ method="post"
+ validator={trainingAssignmentValidator}
+ defaultValues={initialValues}
+ fetcher={fetcher}
+ action={
+ isEditing
+ ? path.to.trainingAssignment(initialValues.id!)
+ : path.to.newTrainingAssignment
+ }
+ className="flex flex-col h-full"
+ >
+ <ModalDrawerHeader className="flex flex-col gap-4">
+ <HStack className="w-full justify-between pr-8">
+ <VStack>
+ <ModalDrawerTitle>
+ {isEditing ? "Edit Assignment" : "New Assignment"}
+ </ModalDrawerTitle>
+ </VStack>
+
+ {isEditing && (
+ <div>
+ <TabsList>
+ <TabsTrigger value="details">Details</TabsTrigger>
+ <TabsTrigger value="status">Status</TabsTrigger>
+ </TabsList>
+ </div>
+ )}
+ </HStack>
+ </ModalDrawerHeader>
+ <ModalDrawerBody className="w-full">
+ <Hidden name="id" />
+
+ {isEditing ? (
+ <>
+ <TabsContent value="details" className="w-full">
+ <AssignmentFormContent
+ trainings={trainings}
+ isEditing={isEditing}
+ />
+ </TabsContent>
+ <TabsContent
+ value="status"
+ className="w-full flex flex-col gap-4"
+ >
+ {assignmentStatus.length > 0 ? (
+ <StatusTable
+ data={assignmentStatus}
+ currentPeriod={currentPeriod}
+ />
+ ) : (
+ <div className="py-8 text-center text-muted-foreground">
+ No employees assigned yet. Add groups to see status.
+ </div>
+ )}
+ </TabsContent>
+ </>
+ ) : (
+ <AssignmentFormContent
+ trainings={trainings}
+ isEditing={isEditing}
+ />
+ )}
+ </ModalDrawerBody>
+ <ModalDrawerFooter>
+ <HStack>
+ <Submit
+ isLoading={fetcher.state !== "idle"}
+ isDisabled={fetcher.state !== "idle" || isDisabled}
+ >
+ Save
+ </Submit>
+ <Button size="md" variant="solid" onClick={onClose}>
+ Cancel
+ </Button>
+ </HStack>
+ </ModalDrawerFooter>
+ </ValidatedForm>
+ </Tabs>
+ </ModalDrawerContent>
+ </ModalDrawer>
+ </ModalDrawerProvider>
+ );
+};
+
+function AssignmentFormContent({
+ trainings,
+ isEditing,
+}: {
+ trainings: TrainingListItem[];
+ isEditing: boolean;
+}) {
+ return (
+ <VStack spacing={4}>
+ <Select
+ name="trainingId"
+ label="Training"
+ isReadOnly={isEditing}
+ options={trainings.map((training) => ({
+ label: training.name ?? "",
+ value: training.id ?? "",
+ }))}
+ />
+ <Users
+ name="groupIds"
+ label="Assign to Groups"
+ type="employee"
+ helperText="Select the groups that should complete this training"
+ />
+ </VStack>
+ );
+}
+
+export default TrainingAssignmentForm;
diff --git a/apps/erp/app/modules/people/ui/Training/TrainingProperties.tsx b/apps/erp/app/modules/people/ui/Training/TrainingProperties.tsx
index 42f52d259f..43069d16c8 100644
--- a/apps/erp/app/modules/people/ui/Training/TrainingProperties.tsx
+++ b/apps/erp/app/modules/people/ui/Training/TrainingProperties.tsx
@@ -14,7 +14,7 @@ import { useCallback, useEffect } from "react";
import { LuCopy, LuKeySquare, LuLink } from "react-icons/lu";
import { z } from "zod/v3";
import Assignee, { useOptimisticAssignment } from "~/components/Assignee";
-import { Tags } from "~/components/Form";
+import { InputControlled, Tags } from "~/components/Form";
import { usePermissions, useRouteData } from "~/hooks";
import { useTags } from "~/hooks/useTags";
import {
@@ -207,14 +207,16 @@ const TrainingProperties = () => {
label="Type"
name="type"
inline={(value) => (
- <Badge variant={value === "Mandatory" ? "red" : "blue"}>
+ <Badge variant={value === "Mandatory" ? "default" : "secondary"}>
{value}
</Badge>
)}
options={trainingType.map((t) => ({
value: t,
label: (
- <Badge variant={t === "Mandatory" ? "red" : "blue"}>{t}</Badge>
+ <Badge variant={t === "Mandatory" ? "default" : "secondary"}>
+ {t}
+ </Badge>
),
}))}
value={routeData?.training?.type ?? ""}
@@ -251,6 +253,32 @@ const TrainingProperties = () => {
</span>
</ValidatedForm>
+ <ValidatedForm
+ defaultValues={{
+ estimatedDuration:
+ routeData?.training?.estimatedDuration ?? undefined,
+ }}
+ validator={z.object({
+ estimatedDuration: z.string(),
+ })}
+ className="w-full -mt-2"
+ >
+ <span className="text-xs text-muted-foreground">
+ <InputControlled
+ label="Estimated Duration"
+ name="estimatedDuration"
+ inline
+ placeholder="45m"
+ size="sm"
+ value={routeData?.training?.estimatedDuration ?? ""}
+ onBlur={(e) => {
+ onUpdate("estimatedDuration", e.target.value ?? null);
+ }}
+ className="text-muted-foreground"
+ />
+ </span>
+ </ValidatedForm>
+
<ValidatedForm
defaultValues={{
tags: routeData?.training?.tags ?? [],
diff --git a/apps/erp/app/modules/people/ui/Training/TrainingStatus.tsx b/apps/erp/app/modules/people/ui/Training/TrainingStatus.tsx
index 3a06e7371a..72634311ac 100644
--- a/apps/erp/app/modules/people/ui/Training/TrainingStatus.tsx
+++ b/apps/erp/app/modules/people/ui/Training/TrainingStatus.tsx
@@ -1,4 +1,4 @@
-import { Badge } from "@carbon/react";
+import { Status } from "@carbon/react";
import type { trainingStatus } from "~/modules/people";
type TrainingStatusProps = {
@@ -8,11 +8,11 @@ type TrainingStatusProps = {
export default function TrainingStatus({ status }: TrainingStatusProps) {
switch (status) {
case "Draft":
- return <Badge variant="secondary">Draft</Badge>;
+ return <Status color="gray">Draft</Status>;
case "Active":
- return <Badge variant="green">Active</Badge>;
+ return <Status color="green">Active</Status>;
case "Archived":
- return <Badge variant="outline">Archived</Badge>;
+ return <Status color="red">Archived</Status>;
default:
return null;
}
diff --git a/apps/erp/app/modules/people/ui/Training/TrainingsTable.tsx b/apps/erp/app/modules/people/ui/Training/TrainingsTable.tsx
index eb44d43fab..7fd96fd58a 100644
--- a/apps/erp/app/modules/people/ui/Training/TrainingsTable.tsx
+++ b/apps/erp/app/modules/people/ui/Training/TrainingsTable.tsx
@@ -11,12 +11,12 @@ import { memo, useCallback, useMemo, useState } from "react";
import { flushSync } from "react-dom";
import {
LuBookOpen,
- LuCalendar,
LuClock,
LuPencil,
LuRepeat,
LuTag,
LuShapes,
+ LuStar,
LuTrash,
LuUser,
} from "react-icons/lu";
@@ -60,14 +60,29 @@ const TrainingsTable = memo(({ data, count, tags }: TrainingsTableProps) => {
header: "Status",
cell: ({ row }) => <TrainingStatus status={row.original.status} />,
meta: {
- icon: <LuCalendar />,
+ filter: {
+ type: "static",
+ options: [
+ { value: "Draft", label: <TrainingStatus status="Draft" /> },
+ { value: "Active", label: <TrainingStatus status="Active" /> },
+ {
+ value: "Archived",
+ label: <TrainingStatus status="Archived" />,
+ },
+ ],
+ },
+ icon: <LuStar />,
},
},
{
accessorKey: "type",
header: "Type",
cell: ({ row }) => (
- <Badge variant={row.original.type === "Mandatory" ? "red" : "blue"}>
+ <Badge
+ variant={
+ row.original.type === "Mandatory" ? "default" : "secondary"
+ }
+ >
{row.original.type}
</Badge>
),
@@ -103,7 +118,17 @@ const TrainingsTable = memo(({ data, count, tags }: TrainingsTableProps) => {
{
accessorKey: "estimatedDuration",
header: "Duration",
- cell: ({ row }) => row.original.estimatedDuration || "-",
+ cell: ({ row }) =>
+ row.original.estimatedDuration ? (
+ <div className="flex items-center gap-1">
+ <LuClock />{" "}
+ <span className="text-xs text-muted-foreground">
+ {row.original.estimatedDuration}
+ </span>
+ </div>
+ ) : (
+ "-"
+ ),
meta: {
icon: <LuClock />,
},
diff --git a/apps/erp/app/modules/people/ui/usePeopleSubmodules.tsx b/apps/erp/app/modules/people/ui/usePeopleSubmodules.tsx
index faa5a5633a..b8738428d4 100644
--- a/apps/erp/app/modules/people/ui/usePeopleSubmodules.tsx
+++ b/apps/erp/app/modules/people/ui/usePeopleSubmodules.tsx
@@ -1,6 +1,7 @@
import {
LuCalendarClock,
LuCalendarHeart,
+ LuClipboardCheck,
LuGraduationCap,
LuListChecks,
LuNetwork,
@@ -20,12 +21,22 @@ const peopleRoutes: RouteGroup[] = [
icon: <LuUsers />,
table: "employee",
},
+ ],
+ },
+ {
+ name: "Compliance",
+ routes: [
{
name: "Training",
to: path.to.trainings,
icon: <LuGraduationCap />,
table: "training",
},
+ {
+ name: "Assignments",
+ to: path.to.trainingAssignments,
+ icon: <LuClipboardCheck />,
+ },
],
},
{
diff --git a/apps/erp/app/routes/x+/people+/assignments.$trainingId.tsx b/apps/erp/app/routes/x+/people+/assignments.$trainingId.tsx
new file mode 100644
index 0000000000..64781a879b
--- /dev/null
+++ b/apps/erp/app/routes/x+/people+/assignments.$trainingId.tsx
@@ -0,0 +1,351 @@
+import { error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import {
+ Badge,
+ Button,
+ HStack,
+ MenuIcon,
+ MenuItem,
+ VStack,
+} from "@carbon/react";
+import {
+ redirect,
+ useFetcher,
+ useLoaderData,
+ useParams,
+} from "@remix-run/react";
+import type { LoaderFunctionArgs } from "@vercel/remix";
+import { json } from "@vercel/remix";
+import type { ColumnDef } from "@tanstack/react-table";
+import { memo, useMemo } from "react";
+import {
+ LuTriangleAlert,
+ LuCalendar,
+ LuCircleCheck,
+ LuClock,
+ LuUser,
+} from "react-icons/lu";
+import { EmployeeAvatar, Table } from "~/components";
+import { usePermissions } from "~/hooks";
+import { getTraining, getTrainingAssignmentStatus } from "~/modules/people";
+import type { TrainingAssignmentStatusItem } from "~/modules/people/types";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+import { getGenericQueryFilters } from "~/utils/query";
+
+export const handle: Handle = {
+ breadcrumb: "Detail",
+ to: path.to.trainingAssignments,
+};
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "people",
+ role: "employee",
+ });
+
+ const { trainingId } = params;
+ if (!trainingId) {
+ throw redirect(
+ path.to.trainingAssignments,
+ await flash(request, error(null, "Training ID is required"))
+ );
+ }
+
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ const search = searchParams.get("search");
+ const status = searchParams.get("status") as
+ | "Completed"
+ | "Pending"
+ | "Overdue"
+ | "Not Required"
+ | null;
+ const { limit, offset, sorts, filters } =
+ getGenericQueryFilters(searchParams);
+
+ const [training, assignmentStatus] = await Promise.all([
+ getTraining(client, trainingId),
+ getTrainingAssignmentStatus(client, companyId, {
+ trainingId,
+ status: status ?? undefined,
+ search: search ?? undefined,
+ limit,
+ offset,
+ sorts,
+ filters,
+ }),
+ ]);
+
+ if (training.error) {
+ throw redirect(
+ path.to.trainingAssignments,
+ await flash(request, error(training.error, "Error loading training"))
+ );
+ }
+
+ if (assignmentStatus.error) {
+ throw redirect(
+ path.to.trainingAssignments,
+ await flash(
+ request,
+ error(assignmentStatus.error, "Error loading assignment status")
+ )
+ );
+ }
+
+ return json({
+ training: training.data,
+ assignments: (assignmentStatus.data ??
+ []) as TrainingAssignmentStatusItem[],
+ count: assignmentStatus.count ?? 0,
+ });
+}
+
+function StatusBadge({ status }: { status: string }) {
+ switch (status) {
+ case "Completed":
+ return (
+ <Badge variant="green">
+ <LuCircleCheck className="mr-1" />
+ Completed
+ </Badge>
+ );
+ case "Pending":
+ return (
+ <Badge variant="secondary">
+ <LuClock className="mr-1" />
+ Pending
+ </Badge>
+ );
+ case "Overdue":
+ return (
+ <Badge variant="red">
+ <LuTriangleAlert className="mr-1" />
+ Overdue
+ </Badge>
+ );
+ case "Not Required":
+ return <Badge variant="outline">Not Required</Badge>;
+ default:
+ return <Badge variant="secondary">{status}</Badge>;
+ }
+}
+
+const TrainingAssignmentDetailTable = memo(
+ ({
+ data,
+ count,
+ trainingId,
+ currentPeriod,
+ }: {
+ data: TrainingAssignmentStatusItem[];
+ count: number;
+ trainingId: string;
+ currentPeriod: string | null;
+ }) => {
+ const permissions = usePermissions();
+
+ const columns = useMemo<ColumnDef<TrainingAssignmentStatusItem>[]>(
+ () => [
+ {
+ accessorKey: "employeeName",
+ header: "Employee",
+ cell: ({ row }) => (
+ <HStack spacing={2}>
+ <EmployeeAvatar employeeId={row.original.employeeId} />
+ <span>{row.original.employeeName}</span>
+ </HStack>
+ ),
+ meta: {
+ icon: <LuUser />,
+ },
+ },
+ {
+ accessorKey: "employeeStartDate",
+ header: "Start Date",
+ cell: ({ row }) =>
+ row.original.employeeStartDate
+ ? new Date(row.original.employeeStartDate).toLocaleDateString()
+ : "-",
+ meta: {
+ icon: <LuCalendar />,
+ },
+ },
+ {
+ accessorKey: "status",
+ header: "Status",
+ cell: ({ row }) => <StatusBadge status={row.original.status} />,
+ meta: {
+ filter: {
+ type: "static",
+ options: [
+ { value: "Completed", label: "Completed" },
+ { value: "Pending", label: "Pending" },
+ { value: "Overdue", label: "Overdue" },
+ { value: "Not Required", label: "Not Required" },
+ ],
+ },
+ },
+ },
+ {
+ accessorKey: "completedAt",
+ header: "Completed At",
+ cell: ({ row }) =>
+ row.original.completedAt
+ ? new Date(row.original.completedAt).toLocaleDateString()
+ : "-",
+ meta: {
+ icon: <LuClock />,
+ },
+ },
+ {
+ id: "actions",
+ header: "",
+ cell: ({ row }) => {
+ if (
+ row.original.status === "Completed" ||
+ row.original.status === "Not Required"
+ ) {
+ return null;
+ }
+ return (
+ <MarkCompleteButton
+ trainingAssignmentId={row.original.trainingAssignmentId}
+ employeeId={row.original.employeeId}
+ period={currentPeriod}
+ disabled={!permissions.can("update", "people")}
+ />
+ );
+ },
+ },
+ ],
+ [permissions, currentPeriod]
+ );
+
+ const renderContextMenu = useMemo(() => {
+ return (row: TrainingAssignmentStatusItem) => {
+ if (row.status === "Completed" || row.status === "Not Required") {
+ return null;
+ }
+ return (
+ <MarkCompleteMenuItem
+ trainingAssignmentId={row.trainingAssignmentId}
+ employeeId={row.employeeId}
+ period={currentPeriod}
+ disabled={!permissions.can("update", "people")}
+ />
+ );
+ };
+ }, [permissions, currentPeriod]);
+
+ return (
+ <Table<TrainingAssignmentStatusItem>
+ data={data}
+ columns={columns}
+ count={count}
+ title="Employee Status"
+ table="trainingAssignmentStatus"
+ renderContextMenu={renderContextMenu}
+ />
+ );
+ }
+);
+
+TrainingAssignmentDetailTable.displayName = "TrainingAssignmentDetailTable";
+
+function MarkCompleteButton({
+ trainingAssignmentId,
+ employeeId,
+ period,
+ disabled,
+}: {
+ trainingAssignmentId: number;
+ employeeId: string;
+ period: string | null;
+ disabled: boolean;
+}) {
+ const fetcher = useFetcher();
+ const isSubmitting = fetcher.state !== "idle";
+
+ return (
+ <fetcher.Form method="post" action={path.to.markTrainingComplete}>
+ <input
+ type="hidden"
+ name="trainingAssignmentId"
+ value={trainingAssignmentId}
+ />
+ <input type="hidden" name="employeeId" value={employeeId} />
+ <input type="hidden" name="period" value={period ?? ""} />
+ <Button
+ type="submit"
+ variant="secondary"
+ size="sm"
+ disabled={disabled || isSubmitting}
+ isLoading={isSubmitting}
+ leftIcon={<LuCircleCheck />}
+ >
+ Mark Complete
+ </Button>
+ </fetcher.Form>
+ );
+}
+
+function MarkCompleteMenuItem({
+ trainingAssignmentId,
+ employeeId,
+ period,
+ disabled,
+}: {
+ trainingAssignmentId: number;
+ employeeId: string;
+ period: string | null;
+ disabled: boolean;
+}) {
+ const fetcher = useFetcher();
+
+ return (
+ <MenuItem
+ disabled={disabled}
+ onClick={() => {
+ fetcher.submit(
+ {
+ trainingAssignmentId: trainingAssignmentId.toString(),
+ employeeId,
+ period: period ?? "",
+ },
+ { method: "post", action: path.to.markTrainingComplete }
+ );
+ }}
+ >
+ <MenuIcon icon={<LuCircleCheck />} />
+ Mark Complete
+ </MenuItem>
+ );
+}
+
+export default function TrainingAssignmentDetailRoute() {
+ const { training, assignments, count } = useLoaderData<typeof loader>();
+ const params = useParams();
+
+ const currentPeriod =
+ assignments.length > 0 ? assignments[0].currentPeriod : null;
+
+ return (
+ <VStack spacing={4} className="h-full p-4">
+ <HStack className="w-full justify-between">
+ <HStack spacing={2}>
+ <h1 className="text-xl font-semibold">{training?.name}</h1>
+ {currentPeriod && <Badge variant="secondary">{currentPeriod}</Badge>}
+ </HStack>
+ </HStack>
+ <TrainingAssignmentDetailTable
+ data={assignments}
+ count={count}
+ trainingId={params.trainingId!}
+ currentPeriod={currentPeriod}
+ />
+ </VStack>
+ );
+}
diff --git a/apps/erp/app/routes/x+/people+/assignments.assignment.$assignmentId.delete.tsx b/apps/erp/app/routes/x+/people+/assignments.assignment.$assignmentId.delete.tsx
new file mode 100644
index 0000000000..63c8104d4b
--- /dev/null
+++ b/apps/erp/app/routes/x+/people+/assignments.assignment.$assignmentId.delete.tsx
@@ -0,0 +1,51 @@
+import { error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { redirect } from "@remix-run/react";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";
+import { deleteTrainingAssignment } from "~/modules/people";
+import { path } from "~/utils/path";
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ throw redirect(path.to.trainingAssignments);
+}
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ delete: "people",
+ role: "employee",
+ });
+
+ const { assignmentId } = params;
+ if (!assignmentId) {
+ throw redirect(
+ path.to.trainingAssignments,
+ await flash(request, error(null, "Assignment ID is required"))
+ );
+ }
+
+ const assignmentIdNum = parseInt(assignmentId, 10);
+ if (isNaN(assignmentIdNum)) {
+ throw redirect(
+ path.to.trainingAssignments,
+ await flash(request, error(null, "Invalid assignment ID"))
+ );
+ }
+
+ const result = await deleteTrainingAssignment(client, assignmentIdNum);
+
+ if (result.error) {
+ throw redirect(
+ path.to.trainingAssignments,
+ await flash(
+ request,
+ error(result.error, "Failed to delete assignment")
+ )
+ );
+ }
+
+ throw redirect(
+ path.to.trainingAssignments,
+ await flash(request, success("Assignment deleted successfully"))
+ );
+}
diff --git a/apps/erp/app/routes/x+/people+/assignments.assignment.$assignmentId.tsx b/apps/erp/app/routes/x+/people+/assignments.assignment.$assignmentId.tsx
new file mode 100644
index 0000000000..6939cd83b0
--- /dev/null
+++ b/apps/erp/app/routes/x+/people+/assignments.assignment.$assignmentId.tsx
@@ -0,0 +1,166 @@
+import { validationError, validator } from "@carbon/form";
+import { error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { redirect, useLoaderData, useNavigate, useParams } from "@remix-run/react";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";
+import { json } from "@vercel/remix";
+import {
+ getTrainingAssignment,
+ getTrainingAssignmentStatus,
+ getTrainingsList,
+ trainingAssignmentValidator,
+ upsertTrainingAssignment,
+} from "~/modules/people";
+import type { TrainingAssignmentStatusItem, TrainingListItem } from "~/modules/people/types";
+import TrainingAssignmentForm from "~/modules/people/ui/Training/TrainingAssignmentForm";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+
+export const handle: Handle = {
+ breadcrumb: "Edit Assignment",
+ to: path.to.trainingAssignments,
+};
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "people",
+ role: "employee",
+ });
+
+ const { assignmentId } = params;
+ if (!assignmentId) {
+ throw redirect(
+ path.to.trainingAssignments,
+ await flash(request, error(null, "Assignment ID is required"))
+ );
+ }
+
+ const assignmentIdNum = parseInt(assignmentId, 10);
+ if (isNaN(assignmentIdNum)) {
+ throw redirect(
+ path.to.trainingAssignments,
+ await flash(request, error(null, "Invalid assignment ID"))
+ );
+ }
+
+ const [assignment, trainings, assignmentStatus] = await Promise.all([
+ getTrainingAssignment(client, assignmentIdNum),
+ getTrainingsList(client, companyId),
+ getTrainingAssignmentStatus(client, companyId, {
+ // We'll filter by trainingId which we'll get from the assignment
+ }),
+ ]);
+
+ if (assignment.error) {
+ throw redirect(
+ path.to.trainingAssignments,
+ await flash(request, error(assignment.error, "Error loading assignment"))
+ );
+ }
+
+ if (trainings.error) {
+ throw redirect(
+ path.to.trainingAssignments,
+ await flash(request, error(trainings.error, "Error loading trainings"))
+ );
+ }
+
+ // Filter assignment status by trainingAssignmentId
+ const filteredStatus = (assignmentStatus.data ?? []).filter(
+ (s) => s.trainingAssignmentId === assignmentIdNum
+ );
+
+ const currentPeriod =
+ filteredStatus.length > 0 ? filteredStatus[0].currentPeriod : null;
+
+ return json({
+ assignment: assignment.data,
+ trainings: (trainings.data ?? []) as TrainingListItem[],
+ assignmentStatus: filteredStatus as TrainingAssignmentStatusItem[],
+ currentPeriod,
+ });
+}
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ const { client, userId } = await requirePermissions(request, {
+ update: "people",
+ role: "employee",
+ });
+
+ const { assignmentId } = params;
+ if (!assignmentId) {
+ return json(
+ { error: "Assignment ID is required" },
+ { status: 400 }
+ );
+ }
+
+ const assignmentIdNum = parseInt(assignmentId, 10);
+ if (isNaN(assignmentIdNum)) {
+ return json(
+ { error: "Invalid assignment ID" },
+ { status: 400 }
+ );
+ }
+
+ const formData = await request.formData();
+ const validation = await validator(trainingAssignmentValidator).validate(
+ formData
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { trainingId, groupIds } = validation.data;
+
+ const result = await upsertTrainingAssignment(client, {
+ id: assignmentIdNum,
+ trainingId,
+ groupIds,
+ companyId: "", // not used for updates
+ updatedBy: userId,
+ });
+
+ if (result.error) {
+ return json(
+ { error: result.error.message },
+ {
+ status: 500,
+ headers: await flash(
+ request,
+ error(result.error, "Failed to update assignment")
+ ),
+ }
+ );
+ }
+
+ throw redirect(
+ path.to.trainingAssignments,
+ await flash(request, success("Assignment updated successfully"))
+ );
+}
+
+export default function EditTrainingAssignmentRoute() {
+ const { assignment, trainings, assignmentStatus, currentPeriod } =
+ useLoaderData<typeof loader>();
+ const navigate = useNavigate();
+ const params = useParams();
+
+ const initialValues = {
+ id: parseInt(params.assignmentId!, 10),
+ trainingId: assignment?.trainingId ?? "",
+ groupIds: assignment?.groupIds ?? [],
+ };
+
+ return (
+ <TrainingAssignmentForm
+ initialValues={initialValues}
+ trainings={trainings}
+ assignmentStatus={assignmentStatus}
+ currentPeriod={currentPeriod}
+ onClose={() => navigate(path.to.trainingAssignments)}
+ />
+ );
+}
diff --git a/apps/erp/app/routes/x+/people+/assignments.complete.tsx b/apps/erp/app/routes/x+/people+/assignments.complete.tsx
new file mode 100644
index 0000000000..288da50a16
--- /dev/null
+++ b/apps/erp/app/routes/x+/people+/assignments.complete.tsx
@@ -0,0 +1,69 @@
+import { error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { redirect } from "@remix-run/react";
+import type { ActionFunctionArgs } from "@vercel/remix";
+import { json } from "@vercel/remix";
+import { insertTrainingCompletion } from "~/modules/people";
+import { path } from "~/utils/path";
+
+export async function action({ request }: ActionFunctionArgs) {
+ const { client, companyId, userId } = await requirePermissions(request, {
+ update: "people",
+ role: "employee",
+ });
+
+ const formData = await request.formData();
+ const trainingAssignmentId = formData.get("trainingAssignmentId");
+ const employeeId = formData.get("employeeId");
+ const period = formData.get("period");
+
+ if (!trainingAssignmentId || !employeeId) {
+ return json(
+ { error: "Missing required fields" },
+ {
+ status: 400,
+ headers: await flash(
+ request,
+ error(null, "Missing required fields")
+ ),
+ }
+ );
+ }
+
+ const result = await insertTrainingCompletion(client, {
+ trainingAssignmentId: parseInt(trainingAssignmentId.toString(), 10),
+ employeeId: employeeId.toString(),
+ period: period?.toString() || null,
+ companyId,
+ completedBy: userId,
+ createdBy: userId,
+ });
+
+ if (result.error) {
+ return json(
+ { error: result.error.message },
+ {
+ status: 500,
+ headers: await flash(
+ request,
+ error(result.error, "Failed to mark training complete")
+ ),
+ }
+ );
+ }
+
+ return json(
+ { success: true },
+ {
+ headers: await flash(
+ request,
+ success("Training marked as complete")
+ ),
+ }
+ );
+}
+
+export async function loader() {
+ return redirect(path.to.trainingAssignments);
+}
diff --git a/apps/erp/app/routes/x+/people+/assignments.new.tsx b/apps/erp/app/routes/x+/people+/assignments.new.tsx
new file mode 100644
index 0000000000..5af1983e01
--- /dev/null
+++ b/apps/erp/app/routes/x+/people+/assignments.new.tsx
@@ -0,0 +1,103 @@
+import { validationError, validator } from "@carbon/form";
+import { error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { redirect, useLoaderData, useNavigate } from "@remix-run/react";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";
+import { json } from "@vercel/remix";
+import {
+ getTrainingsList,
+ trainingAssignmentValidator,
+ upsertTrainingAssignment,
+} from "~/modules/people";
+import type { TrainingListItem } from "~/modules/people/types";
+import TrainingAssignmentForm from "~/modules/people/ui/Training/TrainingAssignmentForm";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+
+export const handle: Handle = {
+ breadcrumb: "New Assignment",
+ to: path.to.newTrainingAssignment,
+};
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ create: "people",
+ role: "employee",
+ });
+
+ const trainings = await getTrainingsList(client, companyId);
+
+ if (trainings.error) {
+ throw redirect(
+ path.to.trainingAssignments,
+ await flash(request, error(trainings.error, "Error loading trainings"))
+ );
+ }
+
+ return json({
+ trainings: (trainings.data ?? []) as TrainingListItem[],
+ });
+}
+
+export async function action({ request }: ActionFunctionArgs) {
+ const { client, companyId, userId } = await requirePermissions(request, {
+ create: "people",
+ role: "employee",
+ });
+
+ const formData = await request.formData();
+ const validation = await validator(trainingAssignmentValidator).validate(
+ formData
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { trainingId, groupIds } = validation.data;
+
+ const result = await upsertTrainingAssignment(client, {
+ trainingId,
+ groupIds,
+ companyId,
+ createdBy: userId,
+ });
+
+ if (result.error) {
+ return json(
+ { error: result.error.message },
+ {
+ status: 500,
+ headers: await flash(
+ request,
+ error(result.error, "Failed to create assignment")
+ ),
+ }
+ );
+ }
+
+ throw redirect(
+ path.to.trainingAssignments,
+ await flash(request, success("Assignment created successfully"))
+ );
+}
+
+export default function NewTrainingAssignmentRoute() {
+ const { trainings } = useLoaderData<typeof loader>();
+ const navigate = useNavigate();
+
+ const initialValues = {
+ id: undefined,
+ trainingId: "",
+ groupIds: [] as string[],
+ };
+
+ return (
+ <TrainingAssignmentForm
+ initialValues={initialValues}
+ trainings={trainings}
+ onClose={() => navigate(path.to.trainingAssignments)}
+ />
+ );
+}
diff --git a/apps/erp/app/routes/x+/people+/assignments.tsx b/apps/erp/app/routes/x+/people+/assignments.tsx
new file mode 100644
index 0000000000..f9f808cb5a
--- /dev/null
+++ b/apps/erp/app/routes/x+/people+/assignments.tsx
@@ -0,0 +1,283 @@
+import { error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import {
+ Badge,
+ HStack,
+ MenuIcon,
+ MenuItem,
+ Progress,
+ VStack,
+} from "@carbon/react";
+import {
+ Link,
+ Outlet,
+ redirect,
+ useFetcher,
+ useLoaderData,
+} from "@remix-run/react";
+import type { LoaderFunctionArgs } from "@vercel/remix";
+import { json } from "@vercel/remix";
+import type { ColumnDef } from "@tanstack/react-table";
+import { memo, useMemo } from "react";
+import {
+ LuTriangleAlert,
+ LuBookOpen,
+ LuChartColumnIncreasing,
+ LuCircleCheck,
+ LuClock,
+ LuPencil,
+ LuRepeat,
+ LuTrash,
+ LuUsers,
+} from "react-icons/lu";
+import { Hyperlink, New, Table } from "~/components";
+import {
+ getTrainingAssignmentSummary,
+ getTrainingAssignments,
+} from "~/modules/people";
+import type { TrainingAssignmentSummaryItem } from "~/modules/people/types";
+import { usePermissions } from "~/hooks";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+
+export const handle: Handle = {
+ breadcrumb: "Assignments",
+ to: path.to.trainingAssignments,
+};
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "people",
+ role: "employee",
+ });
+
+ const [summary, assignments] = await Promise.all([
+ getTrainingAssignmentSummary(client, companyId),
+ getTrainingAssignments(client, companyId),
+ ]);
+
+ if (summary.error) {
+ throw redirect(
+ path.to.authenticatedRoot,
+ await flash(
+ request,
+ error(summary.error, "Error loading training assignments")
+ )
+ );
+ }
+
+ // Create a map of trainingId to assignment id for edit/delete links
+ const assignmentsByTraining = (assignments.data ?? []).reduce(
+ (acc, assignment) => {
+ if (!acc[assignment.trainingId]) {
+ acc[assignment.trainingId] = [];
+ }
+ acc[assignment.trainingId].push(assignment.id);
+ return acc;
+ },
+ {} as Record<string, number[]>
+ );
+
+ return json({
+ summary: (summary.data ?? []) as TrainingAssignmentSummaryItem[],
+ assignmentsByTraining,
+ });
+}
+
+const TrainingAssignmentsTable = memo(
+ ({
+ data,
+ assignmentsByTraining,
+ }: {
+ data: TrainingAssignmentSummaryItem[];
+ assignmentsByTraining: Record<string, number[]>;
+ }) => {
+ const permissions = usePermissions();
+ const fetcher = useFetcher();
+ const columns = useMemo<ColumnDef<TrainingAssignmentSummaryItem>[]>(
+ () => [
+ {
+ accessorKey: "trainingName",
+ header: "Training",
+ cell: ({ row }) => (
+ <Hyperlink
+ to={path.to.trainingAssignmentDetail(row.original.trainingId)}
+ >
+ {row.original.trainingName}
+ </Hyperlink>
+ ),
+ meta: {
+ icon: <LuBookOpen />,
+ },
+ },
+ {
+ accessorKey: "frequency",
+ header: "Frequency",
+ cell: ({ row }) => (
+ <Badge variant="secondary">{row.original.frequency}</Badge>
+ ),
+ meta: {
+ icon: <LuRepeat />,
+ },
+ },
+ {
+ accessorKey: "currentPeriod",
+ header: "Period",
+ cell: ({ row }) => row.original.currentPeriod ?? "-",
+ meta: {
+ icon: <LuClock />,
+ },
+ },
+ {
+ accessorKey: "totalAssigned",
+ header: "Assigned",
+ cell: ({ row }) => (
+ <HStack spacing={2}>
+ <LuUsers />
+ <span className="text-muted-foreground ">
+ {row.original.totalAssigned}
+ </span>
+ </HStack>
+ ),
+ meta: {
+ icon: <LuUsers />,
+ },
+ },
+ {
+ accessorKey: "completed",
+ header: "Completed",
+ cell: ({ row }) => (
+ <HStack spacing={2}>
+ <LuCircleCheck className="text-emerald-500" />
+ <span className="text-muted-foreground">
+ {row.original.completed}
+ </span>
+ </HStack>
+ ),
+ meta: {
+ icon: <LuCircleCheck />,
+ },
+ },
+ {
+ accessorKey: "pending",
+ header: "Pending",
+ cell: ({ row }) => (
+ <HStack spacing={2}>
+ <LuClock className="text-yellow-500" />
+ <span className="text-muted-foreground text-xs">
+ {row.original.pending}
+ </span>
+ </HStack>
+ ),
+ meta: {
+ icon: <LuClock />,
+ },
+ },
+ {
+ accessorKey: "overdue",
+ header: "Overdue",
+ cell: ({ row }) => (
+ <HStack spacing={2}>
+ <LuTriangleAlert className="text-red-500" />
+ <span className="text-muted-foreground text-xs">
+ {row.original.overdue}
+ </span>
+ </HStack>
+ ),
+ meta: {
+ icon: <LuTriangleAlert />,
+ },
+ },
+ {
+ accessorKey: "completionPercent",
+ header: "Progress",
+ cell: ({ row }) => (
+ <HStack spacing={2} className="w-32">
+ <Progress
+ value={row.original.completionPercent}
+ className="h-2"
+ />
+ <span className="text-xs text-muted-foreground">
+ {row.original.completionPercent}%
+ </span>
+ </HStack>
+ ),
+ meta: {
+ icon: <LuChartColumnIncreasing />,
+ },
+ },
+ ],
+ []
+ );
+
+ const renderContextMenu = useMemo(() => {
+ return (row: TrainingAssignmentSummaryItem) => {
+ const assignmentIds = assignmentsByTraining[row.trainingId] ?? [];
+ // If there are multiple assignments for this training, we need a different approach
+ // For now, we'll use the first one (or show nothing if no assignments)
+ const assignmentId = assignmentIds[0];
+
+ if (!assignmentId) return null;
+
+ return (
+ <>
+ {permissions.can("update", "people") && (
+ <MenuItem asChild>
+ <Link to={path.to.trainingAssignment(assignmentId)}>
+ <MenuIcon icon={<LuPencil />} />
+ Edit Assignment
+ </Link>
+ </MenuItem>
+ )}
+ {permissions.can("delete", "people") && (
+ <MenuItem
+ onClick={() => {
+ fetcher.submit(null, {
+ method: "post",
+ action: path.to.deleteTrainingAssignment(assignmentId),
+ });
+ }}
+ >
+ <MenuIcon icon={<LuTrash />} />
+ Delete Assignment
+ </MenuItem>
+ )}
+ </>
+ );
+ };
+ }, [assignmentsByTraining, permissions, fetcher]);
+
+ return (
+ <Table<TrainingAssignmentSummaryItem>
+ data={data}
+ columns={columns}
+ count={data.length}
+ primaryAction={
+ permissions.can("create", "people") && (
+ <New label="Assignment" to={path.to.newTrainingAssignment} />
+ )
+ }
+ title="Training Assignments"
+ table="trainingAssignmentSummary"
+ renderContextMenu={renderContextMenu}
+ />
+ );
+ }
+);
+
+TrainingAssignmentsTable.displayName = "TrainingAssignmentsTable";
+
+export default function TrainingAssignmentsRoute() {
+ const { summary, assignmentsByTraining } = useLoaderData<typeof loader>();
+
+ return (
+ <VStack spacing={0} className="h-full">
+ <TrainingAssignmentsTable
+ data={summary}
+ assignmentsByTraining={assignmentsByTraining}
+ />
+ <Outlet />
+ </VStack>
+ );
+}
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index fdaa626037..26fa6cdf03 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -381,6 +381,7 @@ export const path = {
bulkUpdateShipmentLine: `${x}/shipment/lines/update`,
bulkUpdateStockTransferLine: `${x}/stock-transfer/lines/update`,
bulkUpdateSupplierQuote: `${x}/supplier-quote/update`,
+ bulkUpdateTraining: `${x}/training/update`,
calibrations: `${x}/quality/calibrations`,
chartOfAccount: (id: string) =>
generatePath(`${x}/accounting/charts/${id}`),
@@ -680,11 +681,16 @@ export const path = {
generatePath(`${x}/purchasing/supplier-statuses/delete/${id}`),
deleteSupplierType: (id: string) =>
generatePath(`${x}/purchasing/supplier-types/delete/${id}`),
+ deleteTraining: (id: string) => generatePath(`${x}/training/delete/${id}`),
+ deleteTrainingQuestion: (id: string, questionId: string) =>
+ generatePath(`${x}/training/${id}/questions/delete/${questionId}`),
deleteUom: (id: string) => generatePath(`${x}/items/uom/delete/${id}`),
deleteUserAttribute: (id: string) =>
generatePath(`${x}/account/${id}/delete/attribute`),
deleteWebhook: (id: string) =>
generatePath(`${x}/settings/webhooks/delete/${id}`),
+ deleteWarehouseTransfer: (id: string) =>
+ generatePath(`${x}/warehouse-transfer/${id}/delete`),
deleteWorkCenter: (id: string) =>
generatePath(`${x}/resources/work-centers/delete/${id}`),
demandProjection: (itemId: string, locationId: string) =>
@@ -822,6 +828,7 @@ export const path = {
logos: `${x}/settings/logos`,
makeMethodGet: `${x}/items/methods/get`,
makeMethodSave: `${x}/items/methods/save`,
+ markTrainingComplete: `${x}/people/assignments/complete`,
material: (id: string) => generatePath(`${x}/material/${id}`),
materialCosting: (id: string) =>
generatePath(`${x}/material/${id}/view/costing`),
@@ -1030,6 +1037,9 @@ export const path = {
newTool: `${x}/tool/new`,
newToolSupplier: (id: string) =>
generatePath(`${x}/tool/${id}/view/purchasing/new`),
+ newTraining: `${x}/people/training/new`,
+ newTrainingQuestion: (id: string) =>
+ generatePath(`${x}/training/${id}/questions/new`),
newUom: `${x}/items/uom/new`,
newWarehouseTransfer: `${x}/warehouse-transfer/new`,
newWarehouseTransferLine: (transferId: string) =>
@@ -1165,17 +1175,18 @@ export const path = {
training: (id: string) => generatePath(`${x}/training/${id}`),
trainings: `${x}/people/training`,
- newTraining: `${x}/people/training/new`,
- newTrainingQuestion: (id: string) =>
- generatePath(`${x}/training/${id}/questions/new`),
trainingQuestion: (id: string, questionId: string) =>
generatePath(`${x}/training/${id}/questions/${questionId}`),
- deleteTraining: (id: string) => generatePath(`${x}/training/delete/${id}`),
- deleteTrainingQuestion: (id: string, questionId: string) =>
- generatePath(`${x}/training/${id}/questions/delete/${questionId}`),
trainingQuestionOrder: (id: string) =>
generatePath(`${x}/training/${id}/questions/order`),
- bulkUpdateTraining: `${x}/training/update`,
+ trainingAssignments: `${x}/people/assignments`,
+ trainingAssignmentDetail: (trainingId: string) =>
+ generatePath(`${x}/people/assignments/${trainingId}`),
+ newTrainingAssignment: `${x}/people/assignments/new`,
+ trainingAssignment: (assignmentId: string | number) =>
+ generatePath(`${x}/people/assignments/assignment/${assignmentId}`),
+ deleteTrainingAssignment: (assignmentId: string | number) =>
+ generatePath(`${x}/people/assignments/assignment/${assignmentId}/delete`),
quote: (id: string) => generatePath(`${x}/quote/${id}`),
quoteAssembly: (quoteId: string, lineId: string, assemblyId: string) =>
@@ -1366,8 +1377,6 @@ export const path = {
generatePath(`${x}/warehouse-transfer/${transferId}/lines`),
warehouseTransferLine: (transferId: string, lineId: string) =>
generatePath(`${x}/warehouse-transfer/${transferId}/details/${lineId}`),
- deleteWarehouseTransfer: (id: string) =>
- generatePath(`${x}/warehouse-transfer/${id}/delete`),
shippingMethods: `${x}/inventory/shipping-methods`,
supplier: (id: string) => generatePath(`${x}/supplier/${id}`),
suppliers: `${x}/purchasing/suppliers`,
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index 0832b85940..e05cf36639 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -3675,6 +3675,84 @@ export default {
tags: ["scrapReason"],
},
},
+ "/trainings": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.trainings.id",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainings.name",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainings.description",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainings.version",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainings.status",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainings.type",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainings.frequency",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainings.assignee",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainings.estimatedDuration",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainings.tags",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainings.companyId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainings.versions",
+ },
+ {
+ $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/trainings",
+ },
+ type: "array",
+ },
+ },
+ "206": {
+ description: "Partial Content",
+ },
+ },
+ tags: ["trainings"],
+ },
+ },
"/companyUsage": {
get: {
parameters: [
@@ -15702,6 +15780,9 @@ export default {
{
$ref: "#/parameters/rowFilter.trainingCompletion.updatedBy",
},
+ {
+ $ref: "#/parameters/rowFilter.trainingCompletion.period",
+ },
{
$ref: "#/parameters/select",
},
@@ -15791,6 +15872,9 @@ export default {
{
$ref: "#/parameters/rowFilter.trainingCompletion.updatedBy",
},
+ {
+ $ref: "#/parameters/rowFilter.trainingCompletion.period",
+ },
{
$ref: "#/parameters/preferReturn",
},
@@ -15834,6 +15918,9 @@ export default {
{
$ref: "#/parameters/rowFilter.trainingCompletion.updatedBy",
},
+ {
+ $ref: "#/parameters/rowFilter.trainingCompletion.period",
+ },
{
$ref: "#/parameters/body.trainingCompletion",
},
@@ -48417,6 +48504,90 @@ export default {
tags: ["nonConformanceJobOperation"],
},
},
+ "/trainingAssignmentStatus": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.trainingAssignmentStatus.trainingAssignmentId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainingAssignmentStatus.trainingId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainingAssignmentStatus.trainingName",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainingAssignmentStatus.frequency",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainingAssignmentStatus.type",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainingAssignmentStatus.employeeId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainingAssignmentStatus.employeeName",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainingAssignmentStatus.avatarUrl",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainingAssignmentStatus.employeeStartDate",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainingAssignmentStatus.companyId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainingAssignmentStatus.currentPeriod",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainingAssignmentStatus.completionId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainingAssignmentStatus.completedAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainingAssignmentStatus.status",
+ },
+ {
+ $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/trainingAssignmentStatus",
+ },
+ type: "array",
+ },
+ },
+ "206": {
+ description: "Partial Content",
+ },
+ },
+ tags: ["trainingAssignmentStatus"],
+ },
+ },
"/salesInvoiceShipment": {
get: {
parameters: [
@@ -53331,6 +53502,9 @@ export default {
{
$ref: "#/parameters/rowFilter.training.version",
},
+ {
+ $ref: "#/parameters/rowFilter.training.processId",
+ },
{
$ref: "#/parameters/rowFilter.training.status",
},
@@ -53438,6 +53612,9 @@ export default {
{
$ref: "#/parameters/rowFilter.training.version",
},
+ {
+ $ref: "#/parameters/rowFilter.training.processId",
+ },
{
$ref: "#/parameters/rowFilter.training.status",
},
@@ -53499,6 +53676,9 @@ export default {
{
$ref: "#/parameters/rowFilter.training.version",
},
+ {
+ $ref: "#/parameters/rowFilter.training.processId",
+ },
{
$ref: "#/parameters/rowFilter.training.status",
},
@@ -53847,44 +54027,59 @@ export default {
tags: ["gauge"],
},
},
- "/demandProjection": {
+ "/trainingQuestion": {
get: {
parameters: [
{
- $ref: "#/parameters/rowFilter.demandProjection.itemId",
+ $ref: "#/parameters/rowFilter.trainingQuestion.id",
},
{
- $ref: "#/parameters/rowFilter.demandProjection.locationId",
+ $ref: "#/parameters/rowFilter.trainingQuestion.trainingId",
},
{
- $ref: "#/parameters/rowFilter.demandProjection.periodId",
+ $ref: "#/parameters/rowFilter.trainingQuestion.question",
},
{
- $ref: "#/parameters/rowFilter.demandProjection.forecastQuantity",
+ $ref: "#/parameters/rowFilter.trainingQuestion.type",
},
{
- $ref: "#/parameters/rowFilter.demandProjection.forecastMethod",
+ $ref: "#/parameters/rowFilter.trainingQuestion.sortOrder",
},
{
- $ref: "#/parameters/rowFilter.demandProjection.confidence",
+ $ref: "#/parameters/rowFilter.trainingQuestion.required",
},
{
- $ref: "#/parameters/rowFilter.demandProjection.notes",
+ $ref: "#/parameters/rowFilter.trainingQuestion.options",
},
{
- $ref: "#/parameters/rowFilter.demandProjection.companyId",
+ $ref: "#/parameters/rowFilter.trainingQuestion.correctAnswers",
},
{
- $ref: "#/parameters/rowFilter.demandProjection.createdBy",
+ $ref: "#/parameters/rowFilter.trainingQuestion.correctBoolean",
},
{
- $ref: "#/parameters/rowFilter.demandProjection.createdAt",
+ $ref: "#/parameters/rowFilter.trainingQuestion.matchingPairs",
},
{
- $ref: "#/parameters/rowFilter.demandProjection.updatedAt",
+ $ref: "#/parameters/rowFilter.trainingQuestion.correctNumber",
},
{
- $ref: "#/parameters/rowFilter.demandProjection.updatedBy",
+ $ref: "#/parameters/rowFilter.trainingQuestion.tolerance",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainingQuestion.companyId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainingQuestion.createdAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainingQuestion.createdBy",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainingQuestion.updatedAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainingQuestion.updatedBy",
},
{
$ref: "#/parameters/select",
@@ -53913,7 +54108,7 @@ export default {
description: "OK",
schema: {
items: {
- $ref: "#/definitions/demandProjection",
+ $ref: "#/definitions/trainingQuestion",
},
type: "array",
},
@@ -53922,12 +54117,12 @@ export default {
description: "Partial Content",
},
},
- tags: ["demandProjection"],
+ tags: ["trainingQuestion"],
},
post: {
parameters: [
{
- $ref: "#/parameters/body.demandProjection",
+ $ref: "#/parameters/body.trainingQuestion",
},
{
$ref: "#/parameters/select",
@@ -53941,7 +54136,235 @@ export default {
description: "Created",
},
},
- tags: ["demandProjection"],
+ tags: ["trainingQuestion"],
+ },
+ delete: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.trainingQuestion.id",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainingQuestion.trainingId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainingQuestion.question",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainingQuestion.type",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainingQuestion.sortOrder",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainingQuestion.required",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainingQuestion.options",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainingQuestion.correctAnswers",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainingQuestion.correctBoolean",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainingQuestion.matchingPairs",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainingQuestion.correctNumber",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainingQuestion.tolerance",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainingQuestion.companyId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainingQuestion.createdAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainingQuestion.createdBy",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainingQuestion.updatedAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainingQuestion.updatedBy",
+ },
+ {
+ $ref: "#/parameters/preferReturn",
+ },
+ ],
+ responses: {
+ "204": {
+ description: "No Content",
+ },
+ },
+ tags: ["trainingQuestion"],
+ },
+ patch: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.trainingQuestion.id",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainingQuestion.trainingId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainingQuestion.question",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainingQuestion.type",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainingQuestion.sortOrder",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainingQuestion.required",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainingQuestion.options",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainingQuestion.correctAnswers",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainingQuestion.correctBoolean",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainingQuestion.matchingPairs",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainingQuestion.correctNumber",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainingQuestion.tolerance",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainingQuestion.companyId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainingQuestion.createdAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainingQuestion.createdBy",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainingQuestion.updatedAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trainingQuestion.updatedBy",
+ },
+ {
+ $ref: "#/parameters/body.trainingQuestion",
+ },
+ {
+ $ref: "#/parameters/preferReturn",
+ },
+ ],
+ responses: {
+ "204": {
+ description: "No Content",
+ },
+ },
+ tags: ["trainingQuestion"],
+ },
+ },
+ "/demandProjection": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.demandProjection.itemId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.demandProjection.locationId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.demandProjection.periodId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.demandProjection.forecastQuantity",
+ },
+ {
+ $ref: "#/parameters/rowFilter.demandProjection.forecastMethod",
+ },
+ {
+ $ref: "#/parameters/rowFilter.demandProjection.confidence",
+ },
+ {
+ $ref: "#/parameters/rowFilter.demandProjection.notes",
+ },
+ {
+ $ref: "#/parameters/rowFilter.demandProjection.companyId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.demandProjection.createdBy",
+ },
+ {
+ $ref: "#/parameters/rowFilter.demandProjection.createdAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.demandProjection.updatedAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.demandProjection.updatedBy",
+ },
+ {
+ $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/demandProjection",
+ },
+ type: "array",
+ },
+ },
+ "206": {
+ description: "Partial Content",
+ },
+ },
+ tags: ["demandProjection"],
+ },
+ post: {
+ parameters: [
+ {
+ $ref: "#/parameters/body.demandProjection",
+ },
+ {
+ $ref: "#/parameters/select",
+ },
+ {
+ $ref: "#/parameters/preferPost",
+ },
+ ],
+ responses: {
+ "201": {
+ description: "Created",
+ },
+ },
+ tags: ["demandProjection"],
},
delete: {
parameters: [
@@ -57250,6 +57673,63 @@ export default {
tags: ["(rpc) get_item_shelf_requirements_by_location_and_item"],
},
},
+ "/rpc/get_current_training_period": {
+ get: {
+ parameters: [
+ {
+ format: '"trainingFrequency"',
+ in: "query",
+ name: "frequency",
+ required: true,
+ type: "string",
+ },
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json",
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ },
+ },
+ tags: ["(rpc) get_current_training_period"],
+ },
+ post: {
+ parameters: [
+ {
+ in: "body",
+ name: "args",
+ required: true,
+ schema: {
+ properties: {
+ frequency: {
+ format: '"trainingFrequency"',
+ type: "string",
+ },
+ },
+ required: ["frequency"],
+ type: "object",
+ },
+ },
+ {
+ $ref: "#/parameters/preferParams",
+ },
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json",
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ },
+ },
+ tags: ["(rpc) get_current_training_period"],
+ },
+ },
"/rpc/has_company_permission": {
post: {
parameters: [
@@ -57915,26 +58395,15 @@ export default {
tags: ["(rpc) get_jobs_by_date_range"],
},
},
- "/rpc/get_companies_with_permission": {
- post: {
+ "/rpc/get_period_end_date": {
+ get: {
parameters: [
{
- in: "body",
- name: "args",
+ format: "text",
+ in: "query",
+ name: "period",
required: true,
- schema: {
- properties: {
- permission: {
- format: "text",
- type: "string",
- },
- },
- required: ["permission"],
- type: "object",
- },
- },
- {
- $ref: "#/parameters/preferParams",
+ type: "string",
},
],
produces: [
@@ -57947,10 +58416,8 @@ export default {
description: "OK",
},
},
- tags: ["(rpc) get_companies_with_permission"],
+ tags: ["(rpc) get_period_end_date"],
},
- },
- "/rpc/get_companies_with_employee_role": {
post: {
parameters: [
{
@@ -57958,6 +58425,13 @@ export default {
name: "args",
required: true,
schema: {
+ properties: {
+ period: {
+ format: "text",
+ type: "string",
+ },
+ },
+ required: ["period"],
type: "object",
},
},
@@ -57975,23 +58449,10 @@ export default {
description: "OK",
},
},
- tags: ["(rpc) get_companies_with_employee_role"],
+ tags: ["(rpc) get_period_end_date"],
},
},
- "/rpc/_xid_machine_id": {
- get: {
- produces: [
- "application/json",
- "application/vnd.pgrst.object+json;nulls=stripped",
- "application/vnd.pgrst.object+json",
- ],
- responses: {
- "200": {
- description: "OK",
- },
- },
- tags: ["(rpc) _xid_machine_id"],
- },
+ "/rpc/get_companies_with_permission": {
post: {
parameters: [
{
@@ -57999,6 +58460,13 @@ export default {
name: "args",
required: true,
schema: {
+ properties: {
+ permission: {
+ format: "text",
+ type: "string",
+ },
+ },
+ required: ["permission"],
type: "object",
},
},
@@ -58016,32 +58484,10 @@ export default {
description: "OK",
},
},
- tags: ["(rpc) _xid_machine_id"],
+ tags: ["(rpc) get_companies_with_permission"],
},
},
- "/rpc/jsonb_to_text_array": {
- get: {
- parameters: [
- {
- format: "jsonb",
- in: "query",
- name: "",
- required: true,
- type: "string",
- },
- ],
- produces: [
- "application/json",
- "application/vnd.pgrst.object+json;nulls=stripped",
- "application/vnd.pgrst.object+json",
- ],
- responses: {
- "200": {
- description: "OK",
- },
- },
- tags: ["(rpc) jsonb_to_text_array"],
- },
+ "/rpc/get_companies_with_employee_role": {
post: {
parameters: [
{
@@ -58049,12 +58495,6 @@ export default {
name: "args",
required: true,
schema: {
- properties: {
- "": {
- format: "jsonb",
- },
- },
- required: [""],
type: "object",
},
},
@@ -58072,31 +58512,11 @@ export default {
description: "OK",
},
},
- tags: ["(rpc) jsonb_to_text_array"],
+ tags: ["(rpc) get_companies_with_employee_role"],
},
},
- "/rpc/has_any_company_permission": {
- post: {
- parameters: [
- {
- in: "body",
- name: "args",
- required: true,
- schema: {
- properties: {
- claim: {
- format: "text",
- type: "string",
- },
- },
- required: ["claim"],
- type: "object",
- },
- },
- {
- $ref: "#/parameters/preferParams",
- },
- ],
+ "/rpc/_xid_machine_id": {
+ get: {
produces: [
"application/json",
"application/vnd.pgrst.object+json;nulls=stripped",
@@ -58107,10 +58527,127 @@ export default {
description: "OK",
},
},
- tags: ["(rpc) has_any_company_permission"],
+ tags: ["(rpc) _xid_machine_id"],
},
- },
- "/rpc/is_claims_admin": {
+ post: {
+ parameters: [
+ {
+ in: "body",
+ name: "args",
+ required: true,
+ schema: {
+ type: "object",
+ },
+ },
+ {
+ $ref: "#/parameters/preferParams",
+ },
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json",
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ },
+ },
+ tags: ["(rpc) _xid_machine_id"],
+ },
+ },
+ "/rpc/jsonb_to_text_array": {
+ get: {
+ parameters: [
+ {
+ format: "jsonb",
+ in: "query",
+ name: "",
+ required: true,
+ type: "string",
+ },
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json",
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ },
+ },
+ tags: ["(rpc) jsonb_to_text_array"],
+ },
+ post: {
+ parameters: [
+ {
+ in: "body",
+ name: "args",
+ required: true,
+ schema: {
+ properties: {
+ "": {
+ format: "jsonb",
+ },
+ },
+ required: [""],
+ type: "object",
+ },
+ },
+ {
+ $ref: "#/parameters/preferParams",
+ },
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json",
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ },
+ },
+ tags: ["(rpc) jsonb_to_text_array"],
+ },
+ },
+ "/rpc/has_any_company_permission": {
+ post: {
+ parameters: [
+ {
+ in: "body",
+ name: "args",
+ required: true,
+ schema: {
+ properties: {
+ claim: {
+ format: "text",
+ type: "string",
+ },
+ },
+ required: ["claim"],
+ type: "object",
+ },
+ },
+ {
+ $ref: "#/parameters/preferParams",
+ },
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json",
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ },
+ },
+ tags: ["(rpc) has_any_company_permission"],
+ },
+ },
+ "/rpc/is_claims_admin": {
post: {
parameters: [
{
@@ -58636,6 +59173,74 @@ export default {
tags: ["(rpc) get_sales_order_lines_by_customer_id"],
},
},
+ "/rpc/employee_requires_period": {
+ get: {
+ parameters: [
+ {
+ format: "date",
+ in: "query",
+ name: "employee_start_date",
+ required: true,
+ type: "string",
+ },
+ {
+ format: "text",
+ in: "query",
+ name: "period",
+ required: true,
+ type: "string",
+ },
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json",
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ },
+ },
+ tags: ["(rpc) employee_requires_period"],
+ },
+ post: {
+ parameters: [
+ {
+ in: "body",
+ name: "args",
+ required: true,
+ schema: {
+ properties: {
+ employee_start_date: {
+ format: "date",
+ type: "string",
+ },
+ period: {
+ format: "text",
+ type: "string",
+ },
+ },
+ required: ["employee_start_date", "period"],
+ type: "object",
+ },
+ },
+ {
+ $ref: "#/parameters/preferParams",
+ },
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json",
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ },
+ },
+ tags: ["(rpc) employee_requires_period"],
+ },
+ },
"/rpc/get_my_permission": {
post: {
parameters: [
@@ -59057,6 +59662,63 @@ export default {
tags: ["(rpc) groups_for_user"],
},
},
+ "/rpc/get_period_start_date": {
+ get: {
+ parameters: [
+ {
+ format: "text",
+ in: "query",
+ name: "period",
+ required: true,
+ type: "string",
+ },
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json",
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ },
+ },
+ tags: ["(rpc) get_period_start_date"],
+ },
+ post: {
+ parameters: [
+ {
+ in: "body",
+ name: "args",
+ required: true,
+ schema: {
+ properties: {
+ period: {
+ format: "text",
+ type: "string",
+ },
+ },
+ required: ["period"],
+ type: "object",
+ },
+ },
+ {
+ $ref: "#/parameters/preferParams",
+ },
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json",
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ },
+ },
+ tags: ["(rpc) get_period_start_date"],
+ },
+ },
"/rpc/create_rfq_from_model_v1": {
post: {
parameters: [
@@ -59971,6 +60633,41 @@ export default {
tags: ["(rpc) is_last_job_operation"],
},
},
+ "/rpc/get_training_assignment_summary": {
+ post: {
+ parameters: [
+ {
+ in: "body",
+ name: "args",
+ required: true,
+ schema: {
+ properties: {
+ company_id: {
+ format: "text",
+ type: "string",
+ },
+ },
+ required: ["company_id"],
+ type: "object",
+ },
+ },
+ {
+ $ref: "#/parameters/preferParams",
+ },
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json",
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ },
+ },
+ tags: ["(rpc) get_training_assignment_summary"],
+ },
+ },
"/rpc/get_next_sequence": {
post: {
parameters: [
@@ -62428,6 +63125,69 @@ export default {
},
type: "object",
},
+ trainings: {
+ properties: {
+ id: {
+ description: "Note:\nThis is a Primary Key.<pk/>",
+ format: "text",
+ type: "string",
+ },
+ name: {
+ format: "text",
+ type: "string",
+ },
+ description: {
+ format: "text",
+ type: "string",
+ },
+ version: {
+ format: "numeric",
+ type: "number",
+ },
+ status: {
+ enum: ["Draft", "Active", "Archived"],
+ format: 'public."trainingStatus"',
+ type: "string",
+ },
+ type: {
+ enum: ["Mandatory", "Optional"],
+ format: 'public."trainingType"',
+ type: "string",
+ },
+ frequency: {
+ enum: ["Once", "Quarterly", "Annual"],
+ format: 'public."trainingFrequency"',
+ type: "string",
+ },
+ assignee: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ estimatedDuration: {
+ format: "text",
+ type: "string",
+ },
+ tags: {
+ format: "text[]",
+ items: {
+ type: "string",
+ },
+ type: "array",
+ },
+ companyId: {
+ description:
+ "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ versions: {
+ format: "jsonb",
+ },
+ },
+ type: "object",
+ },
companyUsage: {
required: [
"id",
@@ -68426,6 +69186,10 @@ export default {
format: "text",
type: "string",
},
+ period: {
+ format: "text",
+ type: "string",
+ },
},
type: "object",
},
@@ -83785,6 +84549,76 @@ export default {
},
type: "object",
},
+ trainingAssignmentStatus: {
+ properties: {
+ trainingAssignmentId: {
+ description: "Note:\nThis is a Primary Key.<pk/>",
+ format: "integer",
+ type: "integer",
+ },
+ trainingId: {
+ description:
+ "Note:\nThis is a Foreign Key to `training.id`.<fk table='training' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ trainingName: {
+ format: "text",
+ type: "string",
+ },
+ frequency: {
+ enum: ["Once", "Quarterly", "Annual"],
+ format: 'public."trainingFrequency"',
+ type: "string",
+ },
+ type: {
+ enum: ["Mandatory", "Optional"],
+ format: 'public."trainingType"',
+ type: "string",
+ },
+ employeeId: {
+ description: "Note:\nThis is a Primary Key.<pk/>",
+ format: "text",
+ type: "string",
+ },
+ employeeName: {
+ format: "text",
+ type: "string",
+ },
+ avatarUrl: {
+ format: "text",
+ type: "string",
+ },
+ employeeStartDate: {
+ format: "date",
+ type: "string",
+ },
+ companyId: {
+ description:
+ "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ currentPeriod: {
+ format: "text",
+ type: "string",
+ },
+ completionId: {
+ description: "Note:\nThis is a Primary Key.<pk/>",
+ format: "integer",
+ type: "integer",
+ },
+ completedAt: {
+ format: "timestamp with time zone",
+ type: "string",
+ },
+ status: {
+ format: "text",
+ type: "string",
+ },
+ },
+ type: "object",
+ },
salesInvoiceShipment: {
required: [
"id",
@@ -86287,6 +87121,12 @@ export default {
format: "numeric",
type: "number",
},
+ processId: {
+ description:
+ "Note:\nThis is a Foreign Key to `process.id`.<fk table='process' column='id'/>",
+ format: "text",
+ type: "string",
+ },
status: {
default: "Draft",
enum: ["Draft", "Active", "Archived"],
@@ -86490,6 +87330,114 @@ export default {
},
type: "object",
},
+ trainingQuestion: {
+ required: [
+ "id",
+ "trainingId",
+ "question",
+ "type",
+ "sortOrder",
+ "companyId",
+ "createdAt",
+ "createdBy",
+ ],
+ properties: {
+ id: {
+ default: "public.id('tq'::text)",
+ description: "Note:\nThis is a Primary Key.<pk/>",
+ format: "text",
+ type: "string",
+ },
+ trainingId: {
+ description:
+ "Note:\nThis is a Foreign Key to `training.id`.<fk table='training' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ question: {
+ format: "text",
+ type: "string",
+ },
+ type: {
+ enum: [
+ "MultipleChoice",
+ "TrueFalse",
+ "MultipleAnswers",
+ "MatchingPairs",
+ "Numerical",
+ ],
+ format: 'public."trainingQuestionType"',
+ type: "string",
+ },
+ sortOrder: {
+ default: 1,
+ format: "double precision",
+ type: "number",
+ },
+ required: {
+ default: true,
+ format: "boolean",
+ type: "boolean",
+ },
+ options: {
+ format: "text[]",
+ items: {
+ type: "string",
+ },
+ type: "array",
+ },
+ correctAnswers: {
+ format: "text[]",
+ items: {
+ type: "string",
+ },
+ type: "array",
+ },
+ correctBoolean: {
+ format: "boolean",
+ type: "boolean",
+ },
+ matchingPairs: {
+ format: "json",
+ },
+ correctNumber: {
+ format: "numeric",
+ type: "number",
+ },
+ tolerance: {
+ format: "numeric",
+ type: "number",
+ },
+ companyId: {
+ description:
+ "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ createdAt: {
+ default: "now()",
+ format: "timestamp with time zone",
+ type: "string",
+ },
+ createdBy: {
+ 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",
+ },
+ updatedBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ },
+ type: "object",
+ },
demandProjection: {
required: [
"itemId",
@@ -89720,6 +90668,87 @@ export default {
in: "query",
type: "string",
},
+ "body.trainings": {
+ name: "trainings",
+ description: "trainings",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/trainings",
+ },
+ },
+ "rowFilter.trainings.id": {
+ name: "id",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.trainings.name": {
+ name: "name",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.trainings.description": {
+ name: "description",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.trainings.version": {
+ name: "version",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.trainings.status": {
+ name: "status",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.trainings.type": {
+ name: "type",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.trainings.frequency": {
+ name: "frequency",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.trainings.assignee": {
+ name: "assignee",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.trainings.estimatedDuration": {
+ name: "estimatedDuration",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.trainings.tags": {
+ name: "tags",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.trainings.companyId": {
+ name: "companyId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.trainings.versions": {
+ name: "versions",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"body.companyUsage": {
name: "companyUsage",
description: "companyUsage",
@@ -96443,6 +97472,12 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.trainingCompletion.period": {
+ name: "period",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"body.nonConformanceCustomer": {
name: "nonConformanceCustomer",
description: "nonConformanceCustomer",
@@ -113810,6 +114845,99 @@ export default {
in: "query",
type: "string",
},
+ "body.trainingAssignmentStatus": {
+ name: "trainingAssignmentStatus",
+ description: "trainingAssignmentStatus",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/trainingAssignmentStatus",
+ },
+ },
+ "rowFilter.trainingAssignmentStatus.trainingAssignmentId": {
+ name: "trainingAssignmentId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.trainingAssignmentStatus.trainingId": {
+ name: "trainingId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.trainingAssignmentStatus.trainingName": {
+ name: "trainingName",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.trainingAssignmentStatus.frequency": {
+ name: "frequency",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.trainingAssignmentStatus.type": {
+ name: "type",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.trainingAssignmentStatus.employeeId": {
+ name: "employeeId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.trainingAssignmentStatus.employeeName": {
+ name: "employeeName",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.trainingAssignmentStatus.avatarUrl": {
+ name: "avatarUrl",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.trainingAssignmentStatus.employeeStartDate": {
+ name: "employeeStartDate",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.trainingAssignmentStatus.companyId": {
+ name: "companyId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.trainingAssignmentStatus.currentPeriod": {
+ name: "currentPeriod",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.trainingAssignmentStatus.completionId": {
+ name: "completionId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.trainingAssignmentStatus.completedAt": {
+ name: "completedAt",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.trainingAssignmentStatus.status": {
+ name: "status",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"body.salesInvoiceShipment": {
name: "salesInvoiceShipment",
description: "salesInvoiceShipment",
@@ -116615,6 +117743,12 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.training.processId": {
+ name: "processId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"rowFilter.training.status": {
name: "status",
required: false,
@@ -116834,6 +117968,117 @@ export default {
in: "query",
type: "string",
},
+ "body.trainingQuestion": {
+ name: "trainingQuestion",
+ description: "trainingQuestion",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/trainingQuestion",
+ },
+ },
+ "rowFilter.trainingQuestion.id": {
+ name: "id",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.trainingQuestion.trainingId": {
+ name: "trainingId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.trainingQuestion.question": {
+ name: "question",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.trainingQuestion.type": {
+ name: "type",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.trainingQuestion.sortOrder": {
+ name: "sortOrder",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.trainingQuestion.required": {
+ name: "required",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.trainingQuestion.options": {
+ name: "options",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.trainingQuestion.correctAnswers": {
+ name: "correctAnswers",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.trainingQuestion.correctBoolean": {
+ name: "correctBoolean",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.trainingQuestion.matchingPairs": {
+ name: "matchingPairs",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.trainingQuestion.correctNumber": {
+ name: "correctNumber",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.trainingQuestion.tolerance": {
+ name: "tolerance",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.trainingQuestion.companyId": {
+ name: "companyId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.trainingQuestion.createdAt": {
+ name: "createdAt",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.trainingQuestion.createdBy": {
+ name: "createdBy",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.trainingQuestion.updatedAt": {
+ name: "updatedAt",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.trainingQuestion.updatedBy": {
+ name: "updatedBy",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"body.demandProjection": {
name: "demandProjection",
description: "demandProjection",
diff --git a/packages/database/supabase/migrations/20251205021915_training.sql b/packages/database/supabase/migrations/20251205021915_training.sql
index 7ea8e7beca..4a23205a30 100644
--- a/packages/database/supabase/migrations/20251205021915_training.sql
+++ b/packages/database/supabase/migrations/20251205021915_training.sql
@@ -20,6 +20,7 @@ CREATE TABLE "training" (
"name" TEXT NOT NULL,
"description" TEXT,
"version" NUMERIC NOT NULL DEFAULT 0,
+ "processId" TEXT,
"status" "trainingStatus" NOT NULL DEFAULT 'Draft',
"frequency" "trainingFrequency" NOT NULL DEFAULT 'Once',
"type" "trainingType" NOT NULL DEFAULT 'Mandatory',
@@ -36,6 +37,7 @@ CREATE TABLE "training" (
CONSTRAINT "training_pkey" PRIMARY KEY ("id"),
CONSTRAINT "training_version_check" CHECK ("version" >= 0),
CONSTRAINT "training_version_unique" UNIQUE ("name", "companyId", "version"),
+ CONSTRAINT "training_processId_fkey" FOREIGN KEY ("processId") REFERENCES "process"("id") ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT "training_assignee_fkey" FOREIGN KEY ("assignee") REFERENCES "user"("id") ON UPDATE CASCADE,
CONSTRAINT "training_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT "training_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON UPDATE CASCADE,
@@ -43,6 +45,7 @@ CREATE TABLE "training" (
);
CREATE INDEX "training_companyId_idx" ON "training" ("companyId");
+CREATE INDEX "training_processId_idx" ON "training" ("processId");
ALTER TABLE "training" ENABLE ROW LEVEL SECURITY;
diff --git a/packages/database/supabase/migrations/20251206000000_training_assignments.sql b/packages/database/supabase/migrations/20251206000000_training_assignments.sql
new file mode 100644
index 0000000000..d369df8108
--- /dev/null
+++ b/packages/database/supabase/migrations/20251206000000_training_assignments.sql
@@ -0,0 +1,155 @@
+-- Add period column to trainingCompletion for recurring training tracking
+ALTER TABLE "trainingCompletion" ADD COLUMN "period" TEXT;
+
+CREATE INDEX "trainingCompletion_period_idx" ON "trainingCompletion" ("period");
+
+-- Prevent duplicate completions for same employee/assignment/period
+CREATE UNIQUE INDEX "trainingCompletion_unique_period_idx"
+ON "trainingCompletion" ("trainingAssignmentId", "employeeId", "period")
+WHERE "period" IS NOT NULL;
+
+-- For 'Once' trainings, only one completion per employee/assignment
+CREATE UNIQUE INDEX "trainingCompletion_unique_once_idx"
+ON "trainingCompletion" ("trainingAssignmentId", "employeeId")
+WHERE "period" IS NULL;
+
+-- Get current period for a frequency
+CREATE OR REPLACE FUNCTION get_current_training_period(frequency "trainingFrequency")
+RETURNS TEXT LANGUAGE plpgsql IMMUTABLE AS $$
+BEGIN
+ CASE frequency
+ WHEN 'Once' THEN RETURN NULL;
+ WHEN 'Quarterly' THEN RETURN 'Q' || CEIL(EXTRACT(MONTH FROM CURRENT_DATE)::numeric / 3) || '-' || EXTRACT(YEAR FROM CURRENT_DATE);
+ WHEN 'Annual' THEN RETURN EXTRACT(YEAR FROM CURRENT_DATE)::TEXT;
+ END CASE;
+END;
+$$;
+
+-- Get period start date
+CREATE OR REPLACE FUNCTION get_period_start_date(period TEXT)
+RETURNS DATE LANGUAGE plpgsql IMMUTABLE AS $$
+DECLARE
+ year_part INTEGER;
+ quarter_part INTEGER;
+BEGIN
+ IF period IS NULL THEN RETURN NULL; END IF;
+ IF position('Q' in period) > 0 THEN
+ quarter_part := SUBSTRING(period FROM 2 FOR 1)::INTEGER;
+ year_part := SUBSTRING(period FROM 4)::INTEGER;
+ RETURN make_date(year_part, (quarter_part - 1) * 3 + 1, 1);
+ ELSE
+ RETURN make_date(period::INTEGER, 1, 1);
+ END IF;
+END;
+$$;
+
+-- Get period end date
+CREATE OR REPLACE FUNCTION get_period_end_date(period TEXT)
+RETURNS DATE LANGUAGE plpgsql IMMUTABLE AS $$
+DECLARE
+ year_part INTEGER;
+ quarter_part INTEGER;
+BEGIN
+ IF period IS NULL THEN RETURN NULL; END IF;
+ IF position('Q' in period) > 0 THEN
+ quarter_part := SUBSTRING(period FROM 2 FOR 1)::INTEGER;
+ year_part := SUBSTRING(period FROM 4)::INTEGER;
+ RETURN (make_date(year_part, quarter_part * 3, 1) + interval '1 month - 1 day')::DATE;
+ ELSE
+ RETURN make_date(period::INTEGER, 12, 31);
+ END IF;
+END;
+$$;
+
+-- Check if employee requires a period based on start date
+CREATE OR REPLACE FUNCTION employee_requires_period(employee_start_date DATE, period TEXT)
+RETURNS BOOLEAN LANGUAGE plpgsql IMMUTABLE AS $$
+BEGIN
+ IF period IS NULL THEN RETURN TRUE; END IF;
+ IF employee_start_date IS NULL THEN RETURN TRUE; END IF;
+ -- Required if started before period ends
+ RETURN employee_start_date <= get_period_end_date(period);
+END;
+$$;
+
+-- View for training assignment status
+CREATE OR REPLACE VIEW "trainingAssignmentStatus" WITH(SECURITY_INVOKER=true) AS
+WITH assigned_employees AS (
+ SELECT DISTINCT
+ ta.id AS "trainingAssignmentId",
+ ta."trainingId",
+ t."name" AS "trainingName",
+ t."frequency",
+ t."type",
+ u.id AS "employeeId",
+ u."fullName" AS "employeeName",
+ u."avatarUrl",
+ ej."startDate" AS "employeeStartDate",
+ ta."companyId"
+ FROM "trainingAssignment" ta
+ JOIN "training" t ON t.id = ta."trainingId" AND t."status" = 'Active'
+ CROSS JOIN LATERAL (
+ SELECT DISTINCT m."memberUserId" AS user_id
+ FROM "membership" m
+ WHERE m."groupId" = ANY(ta."groupIds") AND m."memberUserId" IS NOT NULL
+ ) group_members
+ JOIN "user" u ON u.id = group_members.user_id AND u.active = TRUE
+ JOIN "employee" e ON e.id = u.id AND e."companyId" = ta."companyId"
+ LEFT JOIN "employeeJob" ej ON ej.id = u.id AND ej."companyId" = ta."companyId"
+),
+with_period AS (
+ SELECT *, get_current_training_period("frequency") AS "currentPeriod"
+ FROM assigned_employees
+)
+SELECT
+ wp.*,
+ tc.id AS "completionId",
+ tc."completedAt",
+ CASE
+ WHEN wp."frequency" = 'Once' THEN
+ CASE WHEN tc.id IS NOT NULL THEN 'Completed' ELSE 'Pending' END
+ WHEN tc.id IS NOT NULL THEN 'Completed'
+ WHEN NOT employee_requires_period(wp."employeeStartDate", wp."currentPeriod") THEN 'Not Required'
+ WHEN get_period_end_date(wp."currentPeriod") < CURRENT_DATE THEN 'Overdue'
+ ELSE 'Pending'
+ END AS "status"
+FROM with_period wp
+LEFT JOIN "trainingCompletion" tc ON
+ tc."trainingAssignmentId" = wp."trainingAssignmentId"
+ AND tc."employeeId" = wp."employeeId"
+ AND ((wp."frequency" = 'Once' AND tc."period" IS NULL) OR tc."period" = wp."currentPeriod");
+
+-- Function to get training assignment summary
+CREATE OR REPLACE FUNCTION get_training_assignment_summary(company_id TEXT)
+RETURNS TABLE (
+ "trainingId" TEXT,
+ "trainingName" TEXT,
+ "frequency" "trainingFrequency",
+ "currentPeriod" TEXT,
+ "totalAssigned" BIGINT,
+ "completed" BIGINT,
+ "pending" BIGINT,
+ "overdue" BIGINT,
+ "completionPercent" NUMERIC
+) LANGUAGE plpgsql SECURITY DEFINER AS $$
+BEGIN
+ RETURN QUERY
+ SELECT
+ tas."trainingId",
+ tas."trainingName",
+ tas."frequency",
+ tas."currentPeriod",
+ COUNT(*) FILTER (WHERE tas."status" != 'Not Required'),
+ COUNT(*) FILTER (WHERE tas."status" = 'Completed'),
+ COUNT(*) FILTER (WHERE tas."status" = 'Pending'),
+ COUNT(*) FILTER (WHERE tas."status" = 'Overdue'),
+ CASE
+ WHEN COUNT(*) FILTER (WHERE tas."status" != 'Not Required') = 0 THEN 100
+ ELSE ROUND(COUNT(*) FILTER (WHERE tas."status" = 'Completed')::NUMERIC * 100 /
+ NULLIF(COUNT(*) FILTER (WHERE tas."status" != 'Not Required'), 0), 1)
+ END
+ FROM "trainingAssignmentStatus" tas
+ WHERE tas."companyId" = company_id
+ GROUP BY tas."trainingId", tas."trainingName", tas."frequency", tas."currentPeriod";
+END;
+$$;
diff --git a/packages/react/src/Status.tsx b/packages/react/src/Status.tsx
index 545d6ca7f4..02c7aff206 100644
--- a/packages/react/src/Status.tsx
+++ b/packages/react/src/Status.tsx
@@ -43,7 +43,7 @@ const Status = ({
return (
<Badge
variant={color}
- className={cn("flex items-center gap-1", className)}
+ className={cn("inline-flex items-center gap-1", className)}
{...props}
>
{getStatusIcon(color)}