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.

refactor: merge training models/services to people models/services

Brad Barbin52b8ce9323ac
diff --git a/apps/erp/app/modules/people/index.ts b/apps/erp/app/modules/people/index.ts
index 35cf0d0dca..0572980c5f 100644
--- a/apps/erp/app/modules/people/index.ts
+++ b/apps/erp/app/modules/people/index.ts
@@ -1,5 +1,3 @@
export * from "./people.models";
export * from "./people.service";
-export * from "./training.models";
-export * from "./training.service";
export * from "./types";
diff --git a/apps/erp/app/modules/people/people.models.ts b/apps/erp/app/modules/people/people.models.ts
index 69879b6a8b..8afef947dd 100644
--- a/apps/erp/app/modules/people/people.models.ts
+++ b/apps/erp/app/modules/people/people.models.ts
@@ -65,3 +65,138 @@ export const shiftValidator = z.object({
saturday: zfd.checkbox(),
sunday: zfd.checkbox(),
});
+
+export const trainingStatus = ["Draft", "Active", "Archived"] as const;
+export const trainingFrequency = ["Once", "Quarterly", "Annual"] as const;
+export const trainingType = ["Mandatory", "Optional"] as const;
+export const trainingQuestionType = [
+ "MultipleChoice",
+ "TrueFalse",
+ "MultipleAnswers",
+ "MatchingPairs",
+ "Numerical",
+] as const;
+
+export const trainingValidator = z.object({
+ id: zfd.text(z.string().optional()),
+ name: z.string().min(1, { message: "Name is required" }),
+ content: zfd.text(z.string().optional()),
+});
+
+export const trainingQuestionValidator = z
+ .object({
+ id: zfd.text(z.string().optional()),
+ trainingId: z.string().min(1, { message: "Training is required" }),
+ question: z.string().min(1, { message: "Question is required" }),
+ type: z.enum(trainingQuestionType, {
+ errorMap: () => ({ message: "Type is required" }),
+ }),
+ sortOrder: zfd.numeric(z.number().min(0).optional()),
+ required: zfd.checkbox().optional(),
+
+ // For MultipleChoice and MultipleAnswers
+ options: z.array(z.string()).optional(),
+ // Accept string (from Select) or array (from MultiSelect), normalize to array
+ correctAnswers: z
+ .union([z.string(), z.array(z.string())])
+ .optional()
+ .transform((val) => {
+ if (!val) return undefined;
+ if (Array.isArray(val)) return val.filter((v) => v.trim() !== "");
+ return val.trim() !== "" ? [val] : undefined;
+ }),
+
+ // For TrueFalse - accept string "true"/"false" and transform to boolean
+ correctBoolean: z
+ .union([z.boolean(), z.string()])
+ .optional()
+ .transform((val) => {
+ if (typeof val === "boolean") return val;
+ if (typeof val === "string") return val === "true";
+ return false;
+ }),
+
+ // For MatchingPairs - stored as JSON string
+ matchingPairs: zfd.text(z.string().optional()),
+
+ // For Numerical
+ correctNumber: zfd.numeric(z.number().optional()),
+ tolerance: zfd.numeric(z.number().min(0).optional()),
+ })
+ .refine(
+ (data) => {
+ if (data.type === "MultipleChoice" || data.type === "MultipleAnswers") {
+ return (
+ !!data.options &&
+ data.options.length >= 2 &&
+ data.options.every((option) => option.trim() !== "")
+ );
+ }
+ return true;
+ },
+ {
+ message: "At least 2 options are required",
+ path: ["options"],
+ }
+ )
+ .refine(
+ (data) => {
+ if (data.type === "MultipleChoice") {
+ return !!data.correctAnswers && data.correctAnswers.length === 1;
+ }
+ return true;
+ },
+ {
+ message: "Exactly one correct answer is required for multiple choice",
+ path: ["correctAnswers"],
+ }
+ )
+ .refine(
+ (data) => {
+ if (data.type === "MultipleAnswers") {
+ return !!data.correctAnswers && data.correctAnswers.length >= 1;
+ }
+ return true;
+ },
+ {
+ message: "At least one correct answer is required",
+ path: ["correctAnswers"],
+ }
+ )
+ .refine(
+ (data) => {
+ if (data.type === "MatchingPairs") {
+ if (!data.matchingPairs) return false;
+ try {
+ const pairs = JSON.parse(data.matchingPairs);
+ return (
+ Array.isArray(pairs) &&
+ pairs.length >= 2 &&
+ pairs.every(
+ (pair: { left?: string; right?: string }) =>
+ pair.left?.trim() && pair.right?.trim()
+ )
+ );
+ } catch {
+ return false;
+ }
+ }
+ return true;
+ },
+ {
+ message: "At least 2 matching pairs are required",
+ path: ["matchingPairs"],
+ }
+ )
+ .refine(
+ (data) => {
+ if (data.type === "Numerical") {
+ return data.correctNumber !== undefined && data.correctNumber !== null;
+ }
+ return true;
+ },
+ {
+ message: "Correct number is required",
+ path: ["correctNumber"],
+ }
+ );
diff --git a/apps/erp/app/modules/people/people.service.ts b/apps/erp/app/modules/people/people.service.ts
index 2bcfccece2..43ed480cff 100644
--- a/apps/erp/app/modules/people/people.service.ts
+++ b/apps/erp/app/modules/people/people.service.ts
@@ -12,6 +12,8 @@ import type {
employeeJobValidator,
holidayValidator,
shiftValidator,
+ trainingQuestionValidator,
+ trainingValidator,
} from "./people.models";
export async function deleteAttribute(
@@ -56,6 +58,25 @@ export async function deleteShift(
return client.from("shift").update({ active: false }).eq("id", shiftId);
}
+export async function deleteTraining(
+ client: SupabaseClient<Database>,
+ trainingId: string
+) {
+ return client.from("training").delete().eq("id", trainingId);
+}
+
+export async function deleteTrainingQuestion(
+ client: SupabaseClient<Database>,
+ trainingQuestionId: string,
+ companyId: string
+) {
+ return client
+ .from("trainingQuestion")
+ .delete()
+ .eq("id", trainingQuestionId)
+ .eq("companyId", companyId);
+}
+
export async function getAttribute(
client: SupabaseClient<Database>,
attributeId: string
@@ -396,6 +417,65 @@ export async function getShiftsList(
return query.order("name");
}
+export async function getTraining(
+ client: SupabaseClient<Database>,
+ id: string
+) {
+ return client
+ .from("training")
+ .select("*, trainingQuestion(*)")
+ .eq("id", id)
+ .single();
+}
+
+export async function getTrainingQuestions(
+ client: SupabaseClient<Database>,
+ trainingId: string
+) {
+ return client
+ .from("trainingQuestion")
+ .select("*")
+ .eq("trainingId", trainingId)
+ .order("sortOrder", { ascending: true });
+}
+
+export async function getTrainings(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ args?: { search: string | null } & GenericQueryFilters
+) {
+ let query = client
+ .from("trainings")
+ .select("*", {
+ count: "exact",
+ })
+ .eq("companyId", companyId);
+
+ if (args?.search) {
+ query = query.ilike("name", `%${args.search}%`);
+ }
+
+ if (args) {
+ query = setGenericQueryFilters(query, args, [
+ { column: "name", ascending: true },
+ ]);
+ }
+
+ return query;
+}
+
+export async function getTrainingsList(
+ client: SupabaseClient<Database>,
+ companyId: string
+) {
+ return client
+ .from("training")
+ .select("id, name, status")
+ .eq("companyId", companyId)
+ .eq("status", "Active")
+ .order("name", { ascending: true });
+}
+
export async function insertAttribute(
client: SupabaseClient<Database>,
attribute: {
@@ -524,6 +604,23 @@ export async function updateEmployeeJob(
.eq("companyId", employeeJob.companyId);
}
+export async function updateTrainingQuestionOrder(
+ client: SupabaseClient<Database>,
+ updates: {
+ id: string;
+ sortOrder: number;
+ updatedBy: string;
+ }[]
+) {
+ const updatePromises = updates.map(({ id, sortOrder, updatedBy }) =>
+ client
+ .from("trainingQuestion")
+ .update({ sortOrder, updatedBy })
+ .eq("id", id)
+ );
+ return Promise.all(updatePromises);
+}
+
export async function upsertDepartment(
client: SupabaseClient<Database>,
department:
@@ -586,3 +683,54 @@ export async function upsertShift(
}
return client.from("shift").update(sanitize(shift)).eq("id", shift.id);
}
+
+export async function upsertTraining(
+ client: SupabaseClient<Database>,
+ training:
+ | (Omit<z.infer<typeof trainingValidator>, "id"> & {
+ companyId: string;
+ createdBy: string;
+ })
+ | (Omit<z.infer<typeof trainingValidator>, "id"> & {
+ id: string;
+ updatedBy: string;
+ })
+) {
+ if ("id" in training) {
+ return client
+ .from("training")
+ .update(sanitize(training))
+ .eq("id", training.id)
+ .select("id")
+ .single();
+ }
+
+ return client.from("training").insert([training]).select("id").single();
+}
+
+export async function upsertTrainingQuestion(
+ client: SupabaseClient<Database>,
+ trainingQuestion:
+ | (Omit<z.infer<typeof trainingQuestionValidator>, "id"> & {
+ companyId: string;
+ createdBy: string;
+ })
+ | (Omit<z.infer<typeof trainingQuestionValidator>, "id"> & {
+ id: string;
+ updatedBy: string;
+ })
+) {
+ if ("id" in trainingQuestion) {
+ return client
+ .from("trainingQuestion")
+ .update(sanitize(trainingQuestion))
+ .eq("id", trainingQuestion.id)
+ .select("id")
+ .single();
+ }
+ return client
+ .from("trainingQuestion")
+ .insert([trainingQuestion])
+ .select("id")
+ .single();
+}
diff --git a/apps/erp/app/modules/people/training.models.ts b/apps/erp/app/modules/people/training.models.ts
deleted file mode 100644
index 5f5130d586..0000000000
--- a/apps/erp/app/modules/people/training.models.ts
+++ /dev/null
@@ -1,137 +0,0 @@
-import { zfd } from "zod-form-data";
-import { z } from "zod/v3";
-
-export const trainingStatus = ["Draft", "Active", "Archived"] as const;
-export const trainingFrequency = ["Once", "Quarterly", "Annual"] as const;
-export const trainingType = ["Mandatory", "Optional"] as const;
-export const trainingQuestionType = [
- "MultipleChoice",
- "TrueFalse",
- "MultipleAnswers",
- "MatchingPairs",
- "Numerical",
-] as const;
-
-export const trainingValidator = z.object({
- id: zfd.text(z.string().optional()),
- name: z.string().min(1, { message: "Name is required" }),
- content: zfd.text(z.string().optional()),
-});
-
-export const trainingQuestionValidator = z
- .object({
- id: zfd.text(z.string().optional()),
- trainingId: z.string().min(1, { message: "Training is required" }),
- question: z.string().min(1, { message: "Question is required" }),
- type: z.enum(trainingQuestionType, {
- errorMap: () => ({ message: "Type is required" }),
- }),
- sortOrder: zfd.numeric(z.number().min(0).optional()),
- required: zfd.checkbox().optional(),
-
- // For MultipleChoice and MultipleAnswers
- options: z.array(z.string()).optional(),
- // Accept string (from Select) or array (from MultiSelect), normalize to array
- correctAnswers: z
- .union([z.string(), z.array(z.string())])
- .optional()
- .transform((val) => {
- if (!val) return undefined;
- if (Array.isArray(val)) return val.filter((v) => v.trim() !== "");
- return val.trim() !== "" ? [val] : undefined;
- }),
-
- // For TrueFalse - accept string "true"/"false" and transform to boolean
- correctBoolean: z
- .union([z.boolean(), z.string()])
- .optional()
- .transform((val) => {
- if (typeof val === "boolean") return val;
- if (typeof val === "string") return val === "true";
- return false;
- }),
-
- // For MatchingPairs - stored as JSON string
- matchingPairs: zfd.text(z.string().optional()),
-
- // For Numerical
- correctNumber: zfd.numeric(z.number().optional()),
- tolerance: zfd.numeric(z.number().min(0).optional()),
- })
- .refine(
- (data) => {
- if (data.type === "MultipleChoice" || data.type === "MultipleAnswers") {
- return (
- !!data.options &&
- data.options.length >= 2 &&
- data.options.every((option) => option.trim() !== "")
- );
- }
- return true;
- },
- {
- message: "At least 2 options are required",
- path: ["options"],
- }
- )
- .refine(
- (data) => {
- if (data.type === "MultipleChoice") {
- return !!data.correctAnswers && data.correctAnswers.length === 1;
- }
- return true;
- },
- {
- message: "Exactly one correct answer is required for multiple choice",
- path: ["correctAnswers"],
- }
- )
- .refine(
- (data) => {
- if (data.type === "MultipleAnswers") {
- return !!data.correctAnswers && data.correctAnswers.length >= 1;
- }
- return true;
- },
- {
- message: "At least one correct answer is required",
- path: ["correctAnswers"],
- }
- )
- .refine(
- (data) => {
- if (data.type === "MatchingPairs") {
- if (!data.matchingPairs) return false;
- try {
- const pairs = JSON.parse(data.matchingPairs);
- return (
- Array.isArray(pairs) &&
- pairs.length >= 2 &&
- pairs.every(
- (pair: { left?: string; right?: string }) =>
- pair.left?.trim() && pair.right?.trim()
- )
- );
- } catch {
- return false;
- }
- }
- return true;
- },
- {
- message: "At least 2 matching pairs are required",
- path: ["matchingPairs"],
- }
- )
- .refine(
- (data) => {
- if (data.type === "Numerical") {
- return data.correctNumber !== undefined && data.correctNumber !== null;
- }
- return true;
- },
- {
- message: "Correct number is required",
- path: ["correctNumber"],
- }
- );
diff --git a/apps/erp/app/modules/people/training.service.ts b/apps/erp/app/modules/people/training.service.ts
deleted file mode 100644
index f3908efa0b..0000000000
--- a/apps/erp/app/modules/people/training.service.ts
+++ /dev/null
@@ -1,160 +0,0 @@
-import type { Database } from "@carbon/database";
-import type { SupabaseClient } from "@supabase/supabase-js";
-import type { z } from "zod/v3";
-import type { GenericQueryFilters } from "~/utils/query";
-import { setGenericQueryFilters } from "~/utils/query";
-import { sanitize } from "~/utils/supabase";
-import type {
- trainingQuestionValidator,
- trainingValidator,
-} from "./training.models";
-
-export async function deleteTraining(
- client: SupabaseClient<Database>,
- trainingId: string
-) {
- return client.from("training").delete().eq("id", trainingId);
-}
-
-export async function deleteTrainingQuestion(
- client: SupabaseClient<Database>,
- trainingQuestionId: string,
- companyId: string
-) {
- return client
- .from("trainingQuestion")
- .delete()
- .eq("id", trainingQuestionId)
- .eq("companyId", companyId);
-}
-
-export async function getTraining(
- client: SupabaseClient<Database>,
- id: string
-) {
- return client
- .from("training")
- .select("*, trainingQuestion(*)")
- .eq("id", id)
- .single();
-}
-
-export async function getTrainingQuestions(
- client: SupabaseClient<Database>,
- trainingId: string
-) {
- return client
- .from("trainingQuestion")
- .select("*")
- .eq("trainingId", trainingId)
- .order("sortOrder", { ascending: true });
-}
-
-export async function getTrainings(
- client: SupabaseClient<Database>,
- companyId: string,
- args?: { search: string | null } & GenericQueryFilters
-) {
- let query = client
- .from("trainings")
- .select("*", {
- count: "exact",
- })
- .eq("companyId", companyId);
-
- if (args?.search) {
- query = query.ilike("name", `%${args.search}%`);
- }
-
- if (args) {
- query = setGenericQueryFilters(query, args, [
- { column: "name", ascending: true },
- ]);
- }
-
- return query;
-}
-
-export async function getTrainingsList(
- client: SupabaseClient<Database>,
- companyId: string
-) {
- return client
- .from("training")
- .select("id, name, status")
- .eq("companyId", companyId)
- .eq("status", "Active")
- .order("name", { ascending: true });
-}
-
-export async function updateTrainingQuestionOrder(
- client: SupabaseClient<Database>,
- updates: {
- id: string;
- sortOrder: number;
- updatedBy: string;
- }[]
-) {
- const updatePromises = updates.map(({ id, sortOrder, updatedBy }) =>
- client
- .from("trainingQuestion")
- .update({ sortOrder, updatedBy })
- .eq("id", id)
- );
- return Promise.all(updatePromises);
-}
-
-export async function upsertTraining(
- client: SupabaseClient<Database>,
- training:
- | (Omit<z.infer<typeof trainingValidator>, "id"> & {
- companyId: string;
- createdBy: string;
- })
- | (Omit<z.infer<typeof trainingValidator>, "id"> & {
- id: string;
- updatedBy: string;
- })
-) {
- if ("id" in training) {
- return client
- .from("training")
- .update(sanitize(training))
- .eq("id", training.id)
- .select("id")
- .single();
- }
-
- return client
- .from("training")
- .insert([training])
- .select("id")
- .single();
-}
-
-export async function upsertTrainingQuestion(
- client: SupabaseClient<Database>,
- trainingQuestion:
- | (Omit<z.infer<typeof trainingQuestionValidator>, "id"> & {
- companyId: string;
- createdBy: string;
- })
- | (Omit<z.infer<typeof trainingQuestionValidator>, "id"> & {
- id: string;
- updatedBy: string;
- })
-) {
- if ("id" in trainingQuestion) {
- return client
- .from("trainingQuestion")
- .update(sanitize(trainingQuestion))
- .eq("id", trainingQuestion.id)
- .select("id")
- .single();
- }
- return client
- .from("trainingQuestion")
- .insert([trainingQuestion])
- .select("id")
- .single();
-}
diff --git a/apps/erp/app/modules/people/types.ts b/apps/erp/app/modules/people/types.ts
index 1d09185c3d..b860c879ee 100644
--- a/apps/erp/app/modules/people/types.ts
+++ b/apps/erp/app/modules/people/types.ts
@@ -8,12 +8,10 @@ import type {
getHolidays,
getPeople,
getShifts,
-} from "./people.service";
-import type {
getTraining,
getTrainingQuestions,
getTrainings,
-} from "./training.service";
+} from "./people.service";
export type Attribute = NonNullable<
Awaited<ReturnType<typeof getAttribute>>["data"]