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: services for multi-tenant - users

Brad Barbin5f9333eb8a02
diff --git a/apps/carbon/app/modules/resources/resources.service.ts b/apps/carbon/app/modules/resources/resources.service.ts
index d1808c5b21..f9fc4f6bc6 100644
--- a/apps/carbon/app/modules/resources/resources.service.ts
+++ b/apps/carbon/app/modules/resources/resources.service.ts
@@ -628,21 +628,16 @@ export async function getPeople(
if (!employees.data) throw new Error("Failed to get employee data");
- const userIds = employees.data.map((employee) => {
- if (!employee.user || Array.isArray(employee.user))
- throw new Error("employee.user is an array");
- // @ts-ignore
- return employee.user?.id;
- });
+ const userIds = employees.data.reduce<string[]>((acc, employee) => {
+ if (employee.id) acc.push(employee.id);
+ return acc;
+ }, []);
const attributeCategories = await getAttributes(client, companyId, userIds);
if (attributeCategories.error) return attributeCategories;
const people: Person[] = employees.data.map((employee) => {
- if (!employee.user || Array.isArray(employee.user))
- throw new Error("employee.user is an array");
- // @ts-ignore
- const userId = employee.user?.id;
+ const userId = employee.id;
const employeeAttributes =
attributeCategories.data.reduce<PersonAttributes>((acc, category) => {
diff --git a/apps/carbon/app/modules/shared/shared.service.ts b/apps/carbon/app/modules/shared/shared.service.ts
index 2dc6e177cb..e3b2ce4946 100644
--- a/apps/carbon/app/modules/shared/shared.service.ts
+++ b/apps/carbon/app/modules/shared/shared.service.ts
@@ -25,6 +25,7 @@ export async function insertNote(
note: {
note: string;
documentId: string;
+ companyId: number;
createdBy: string;
}
) {
diff --git a/apps/carbon/app/modules/users/types.ts b/apps/carbon/app/modules/users/types.ts
index 97639f3973..36146fe21e 100644
--- a/apps/carbon/app/modules/users/types.ts
+++ b/apps/carbon/app/modules/users/types.ts
@@ -3,7 +3,7 @@ import type {
getCustomers,
getEmployees,
getEmployeeTypes,
- getFeatures,
+ getModules,
getPermissionsByEmployeeType,
getSuppliers,
getUsers,
@@ -27,8 +27,8 @@ export type EmployeeType = NonNullable<
Awaited<ReturnType<typeof getEmployeeTypes>>["data"]
>[number];
-export type Feature = NonNullable<
- Awaited<ReturnType<typeof getFeatures>>["data"]
+export type Module = NonNullable<
+ Awaited<ReturnType<typeof getModules>>["data"]
>[number];
export type Group = {
diff --git a/apps/carbon/app/modules/users/ui/EmployeeTypes/EmployeeTypeForm.tsx b/apps/carbon/app/modules/users/ui/EmployeeTypes/EmployeeTypeForm.tsx
index 61d8675b16..e585a06391 100644
--- a/apps/carbon/app/modules/users/ui/EmployeeTypes/EmployeeTypeForm.tsx
+++ b/apps/carbon/app/modules/users/ui/EmployeeTypes/EmployeeTypeForm.tsx
@@ -25,7 +25,7 @@ type EmployeeTypeFormProps = {
permissions: Record<
string,
{
- id: string;
+ name: string;
permission: Permission;
}
>;
@@ -42,7 +42,7 @@ const EmployeeTypeForm = ({ initialValues }: EmployeeTypeFormProps) => {
setPermissions((prevPermissions) => ({
...prevPermissions,
[module]: {
- id: prevPermissions[module].id,
+ name: prevPermissions[module].name,
permission,
},
}));
diff --git a/apps/carbon/app/modules/users/ui/Employees/BulkEditPermissionsForm.tsx b/apps/carbon/app/modules/users/ui/Employees/BulkEditPermissionsForm.tsx
index 387fad9c6f..5d52328e2f 100644
--- a/apps/carbon/app/modules/users/ui/Employees/BulkEditPermissionsForm.tsx
+++ b/apps/carbon/app/modules/users/ui/Employees/BulkEditPermissionsForm.tsx
@@ -45,7 +45,7 @@ const BulkEditPermissions = ({
permissions: Record<
string,
{
- id: string;
+ name: string;
permission: Permission;
}
>;
diff --git a/apps/carbon/app/modules/users/users.server.ts b/apps/carbon/app/modules/users/users.server.ts
index 317c1b2035..8752764d4f 100644
--- a/apps/carbon/app/modules/users/users.server.ts
+++ b/apps/carbon/app/modules/users/users.server.ts
@@ -2,6 +2,7 @@ import type { Database, Json } from "@carbon/database";
import { redis } from "@carbon/redis";
import { redirect } from "@remix-run/node";
import type { SupabaseClient } from "@supabase/supabase-js";
+import crypto from "crypto";
import { getSupabaseServiceRole } from "~/lib/supabase";
import { getSupplierContact } from "~/modules/purchasing";
import { getCustomerContact } from "~/modules/sales";
@@ -9,7 +10,7 @@ import {
getPermissionsByEmployeeType,
type EmployeeRow,
type EmployeeTypePermission,
- type Feature,
+ type Module,
type Permission,
type User,
} from "~/modules/users";
@@ -19,7 +20,7 @@ import {
sendMagicLink,
} from "~/services/auth/auth.server";
import { flash, requireAuthSession } from "~/services/session.server";
-import type { ListItem, Result } from "~/types";
+import type { Result } from "~/types";
import { path } from "~/utils/path";
import { error, success } from "~/utils/result";
@@ -38,11 +39,14 @@ export async function createCustomerAccount(
{
id,
customerId,
+ companyId,
}: {
id: string;
customerId: string;
+ companyId: number;
}
): Promise<Result> {
+ // TODO: convert to transaction and call this at the end of the transaction
const customerContact = await getCustomerContact(client, id);
if (
customerContact.error ||
@@ -55,61 +59,75 @@ export async function createCustomerAccount(
const { email, firstName, lastName } = customerContact.data.contact;
- // TODO: convert to transaction and call this at the end of the transaction
- const invitation = await sendInviteByEmail(email);
+ const user = await getUserByEmail(email);
+ if (user.data) {
+ // TODO: user already exists -- send company invite
+ await addUserToCompany(client, { userId: user.data.id, companyId });
+ return error(
+ null,
+ "User already exists. Adding to team not implemented yet."
+ );
+ } else {
+ // user does not exist -- create user
+ const invitation = await sendInviteByEmail(email);
- if (invitation.error)
- return error(invitation.error.message, "Failed to send invitation email");
+ if (invitation.error)
+ return error(invitation.error.message, "Failed to send invitation email");
- const userId = invitation.data.user.id;
+ const userId = invitation.data.user.id;
+ const userToCompany = await addUserToCompany(client, { userId, companyId });
- const claims = makeCustomerClaims();
- const claimsUpdate = await setUserClaims(userId, {
- role: "customer",
- ...claims,
- });
- if (claimsUpdate.error) {
- await deleteAuthAccount(userId);
- return error(claimsUpdate.error, "Failed to set user claims");
- }
+ const claims = makeCustomerClaims(companyId);
+ const claimsUpdate = await setUserClaims(userId, {
+ role: "customer",
+ ...claims,
+ });
- const insertUser = await createUser(client, {
- id: userId,
- email,
- firstName,
- lastName,
- avatarUrl: null,
- });
+ if (claimsUpdate.error || userToCompany.error) {
+ await deleteAuthAccount(userId);
+ return error(claimsUpdate.error, "Failed to add user");
+ }
- if (insertUser.error)
- return error(insertUser.error, "Failed to create a new user");
+ const insertUser = await createUser(client, {
+ id: userId,
+ email,
+ firstName,
+ lastName,
+ avatarUrl: null,
+ });
- if (!insertUser.data)
- return error(insertUser, "No data returned from create user");
+ if (insertUser.error)
+ return error(insertUser.error, "Failed to create a new user");
- const updateContact = await client
- .from("customerContact")
- .update({ userId })
- .eq("id", id);
- if (updateContact.error) {
- await deleteAuthAccount(userId);
- return error(updateContact.error, "Failed to update customer contact");
- }
+ if (!insertUser.data)
+ return error(insertUser, "No data returned from create user");
- const generatedId = Array.isArray(insertUser.data)
- ? insertUser.data[0].id
- : // @ts-ignore
- insertUser.data?.id!;
+ const updateContact = await client
+ .from("customerContact")
+ .update({ userId })
+ .eq("id", id);
- const createCustomerAccount = await insertCustomerAccount(client, {
- id: generatedId,
- customerId,
- });
+ if (updateContact.error) {
+ await deleteAuthAccount(userId);
+ return error(updateContact.error, "Failed to update customer contact");
+ }
+
+ const generatedId = Array.isArray(insertUser.data)
+ ? insertUser.data[0].id
+ : // @ts-ignore
+ insertUser.data?.id!;
+
+ const createCustomerAccount = await insertCustomerAccount(client, {
+ id: generatedId,
+ customerId,
+ companyId,
+ });
- if (createCustomerAccount.error)
- return error(createCustomerAccount.error, "Failed to create an employee");
+ if (createCustomerAccount.error)
+ return error(createCustomerAccount.error, "Failed to create an employee");
- return success("Customer account created");
+ return success("Customer account created");
+ }
}
export async function createEmployeeAccount(
@@ -128,6 +146,7 @@ export async function createEmployeeAccount(
companyId: number;
}
): Promise<Result> {
+ // TODO: convert to transaction and call this at the end of the transaction
const employeeTypePermissions = await getPermissionsByEmployeeType(
client,
employeeType
@@ -138,48 +157,58 @@ export async function createEmployeeAccount(
"Failed to get employee type permissions"
);
- // TODO: convert to transaction and call this at the end of the transaction
- const invitation = await sendInviteByEmail(email);
+ const user = await getUserByEmail(email);
+ if (user.data) {
+ // TODO: user already exists -- send company invite
+ await addUserToCompany(client, { userId: user.data.id, companyId });
+ return error(
+ null,
+ "User already exists. Adding to team not implemented yet."
+ );
+ } else {
+ const invitation = await sendInviteByEmail(email);
- if (invitation.error)
- return error(invitation.error.message, "Failed to send invitation email");
+ if (invitation.error)
+ return error(invitation.error.message, "Failed to send invitation email");
- const userId = invitation.data.user.id;
+ const userId = invitation.data.user.id;
+ const userToCompany = await addUserToCompany(client, { userId, companyId });
- const claims = makeClaimsFromEmployeeType(employeeTypePermissions);
- const claimsUpdate = await setUserClaims(userId, {
- role: "employee",
- ...claims,
- });
- if (claimsUpdate.error) {
- await deleteAuthAccount(userId);
- return error(claimsUpdate.error, "Failed to set user claims");
- }
+ const claims = makeClaimsFromEmployeeType(employeeTypePermissions);
+ const claimsUpdate = await setUserClaims(userId, {
+ role: "employee",
+ ...claims,
+ });
+ if (claimsUpdate.error || userToCompany.error) {
+ await deleteAuthAccount(userId);
+ return error(claimsUpdate.error, "Failed to create user");
+ }
- const insertUser = await createUser(client, {
- id: userId,
- email,
- firstName,
- lastName,
- avatarUrl: null,
- });
+ const insertUser = await createUser(client, {
+ id: userId,
+ email,
+ firstName,
+ lastName,
+ avatarUrl: null,
+ });
- if (insertUser.error)
- return error(insertUser.error, "Failed to create a new user");
+ if (insertUser.error)
+ return error(insertUser.error, "Failed to create a new user");
- if (!insertUser.data)
- return error(insertUser, "No data returned from create user");
+ if (!insertUser.data)
+ return error(insertUser, "No data returned from create user");
- const createEmployee = await insertEmployee(client, {
- id: insertUser.data[0].id,
- employeeTypeId: employeeType,
- companyId,
- });
+ const createEmployee = await insertEmployee(client, {
+ id: insertUser.data[0].id,
+ employeeTypeId: employeeType,
+ companyId,
+ });
- if (createEmployee.error)
- return error(createEmployee.error, "Failed to create an employee");
+ if (createEmployee.error)
+ return error(createEmployee.error, "Failed to create an employee");
- return success("Employee account created");
+ return success("Employee account created");
+ }
}
export async function createSupplierAccount(
@@ -187,11 +216,14 @@ export async function createSupplierAccount(
{
id,
supplierId,
+ companyId,
}: {
id: string;
supplierId: string;
+ companyId: number;
}
): Promise<Result> {
+ // TODO: convert to transaction and call this at the end of the transaction
const supplierContact = await getSupplierContact(client, id);
if (
supplierContact.error ||
@@ -204,56 +236,68 @@ export async function createSupplierAccount(
const { email, firstName, lastName } = supplierContact.data.contact;
- // TODO: convert to transaction and call this at the end of the transaction
- const invitation = await sendInviteByEmail(email);
+ const user = await getUserByEmail(email);
+ if (user.data) {
+ // TODO: user already exists -- send company invite
+ await addUserToCompany(client, { userId: user.data.id, companyId });
+ return error(
+ null,
+ "User already exists. Adding to team not implemented yet."
+ );
+ } else {
+ // user does not exist -- create user
+ const invitation = await sendInviteByEmail(email);
- if (invitation.error)
- return error(invitation.error.message, "Failed to send invitation email");
+ if (invitation.error)
+ return error(invitation.error.message, "Failed to send invitation email");
- const userId = invitation.data.user.id;
+ const userId = invitation.data.user.id;
+ const userToCompany = await addUserToCompany(client, { userId, companyId });
- const claims = makeSupplierClaims();
- const claimsUpdate = await setUserClaims(userId, {
- role: "supplier",
- ...claims,
- });
- if (claimsUpdate.error) {
- await deleteAuthAccount(userId);
- return error(claimsUpdate.error, "Failed to set user claims");
- }
+ const claims = makeSupplierClaims(companyId);
+ const claimsUpdate = await setUserClaims(userId, {
+ role: "supplier",
+ ...claims,
+ });
+ if (claimsUpdate.error || userToCompany.error) {
+ await deleteAuthAccount(userId);
+ return error(claimsUpdate.error, "Failed to create user");
+ }
- const insertUser = await createUser(client, {
- id: userId,
- email,
- firstName,
- lastName,
- avatarUrl: null,
- });
+ const insertUser = await createUser(client, {
+ id: userId,
+ email,
+ firstName,
+ lastName,
+ avatarUrl: null,
+ });
- if (insertUser.error)
- return error(insertUser.error, "Failed to create a new user");
+ if (insertUser.error)
+ return error(insertUser.error, "Failed to create a new user");
- if (!insertUser.data)
- return error(insertUser, "No data returned from create user");
+ if (!insertUser.data)
+ return error(insertUser, "No data returned from create user");
- const updateContact = await client
- .from("supplierContact")
- .update({ userId })
- .eq("id", id);
- if (updateContact.error) {
- await deleteAuthAccount(userId);
- return error(updateContact.error, "Failed to update supplier contact");
- }
+ const updateContact = await client
+ .from("supplierContact")
+ .update({ userId })
+ .eq("id", id);
+ if (updateContact.error) {
+ await deleteAuthAccount(userId);
+ return error(updateContact.error, "Failed to update supplier contact");
+ }
- const createSupplierAccount = await insertSupplierAccount(client, {
- id: insertUser.data[0].id,
- supplierId,
- });
+ const createSupplierAccount = await insertSupplierAccount(client, {
+ id: insertUser.data[0].id,
+ supplierId,
+ companyId,
+ });
- if (createSupplierAccount.error)
- return error(createSupplierAccount.error, "Failed to create an employee");
+ if (createSupplierAccount.error)
+ return error(createSupplierAccount.error, "Failed to create an employee");
- return success("Supplier account created");
+ return success("Supplier account created");
+ }
}
async function createUser(
@@ -275,12 +319,13 @@ export async function deactivateUser(
): Promise<Result> {
const updateActiveStatus = await client
.from("user")
- .update({ active: false })
+ .update({ active: false, firstName: "Deactivate", lastName: "User" })
.eq("id", userId);
if (updateActiveStatus.error) {
return error(updateActiveStatus.error, "Failed to deactivate user");
}
- const randomPassword = Math.random().toString(36).slice(-8);
+
+ const randomPassword = crypto.randomBytes(20).toString("hex");
const updatePassword = await resetPassword(userId, randomPassword);
if (updatePassword.error) {
@@ -329,7 +374,7 @@ export async function getUserByEmail(email: string) {
.from("user")
.select("*")
.eq("email", email)
- .single();
+ .maybeSingle();
}
export async function getUserClaims(userId: string) {
@@ -390,6 +435,7 @@ async function insertCustomerAccount(
customerAccount: {
id: string;
customerId: string;
+ companyId: number;
}
) {
return client
@@ -411,6 +457,7 @@ async function insertSupplierAccount(
supplierAccount: {
id: string;
supplierId: string;
+ companyId: number;
}
) {
return client
@@ -422,7 +469,6 @@ async function insertSupplierAccount(
async function insertUser(
client: SupabaseClient<Database>,
- //TODO: fix this type
user: Omit<User, "fullName" | "createdAt">
) {
return client.from("user").insert([user]).select("*");
@@ -436,23 +482,19 @@ function makeClaimsFromEmployeeType({
create: number[];
update: number[];
delete: number[];
- feature: ListItem | ListItem[] | null;
+ module: string;
}[];
}) {
const claims: Record<string, number[]> = {};
data.forEach((permission) => {
- if (permission.feature === null || Array.isArray(permission.feature)) {
+ if (!permission.module) {
throw new Error(
- `TODO: permission.feature is an array or null for permission ${JSON.stringify(
- permission,
- null,
- 2
- )}`
+ `Permission module is missing for permission ${JSON.stringify(data)}`
);
}
- const module = permission.feature.name.toLowerCase();
+ const module = permission.module.toLowerCase();
claims[`${module}_view`] = permission.view;
claims[`${module}_create`] = permission.create;
@@ -472,30 +514,32 @@ function isClaimPermission(key: string, value: unknown) {
);
}
-function makeCustomerClaims() {
+function makeCustomerClaims(companyId: number) {
// TODO: this should be more dynamic
- const claims: Record<string, boolean> = {
- documents_view: true,
- jobs_view: true,
- sales_view: true,
- parts_view: true,
+ const claims: Record<string, number[]> = {
+ documents_view: [companyId],
+ jobs_view: [companyId],
+ sales_view: [companyId],
+ parts_view: [companyId],
};
return claims;
}
-export function makeEmptyPermissionsFromFeatures(data: Feature[]) {
- return data.reduce<Record<string, { id: string; permission: Permission }>>(
- (acc, module) => {
- acc[module.name] = {
- id: module.id,
- permission: {
- view: [],
- create: [],
- update: [],
- delete: [],
- },
- };
+export function makeEmptyPermissionsFromModules(data: Module[]) {
+ return data.reduce<Record<string, { name: string; permission: Permission }>>(
+ (acc, m) => {
+ if (m.name) {
+ acc[m.name] = {
+ name: m.name.toLowerCase(),
+ permission: {
+ view: [],
+ create: [],
+ update: [],
+ delete: [],
+ },
+ };
+ }
return acc;
},
{}
@@ -546,21 +590,16 @@ export function makePermissionsFromClaims(claims: Json[] | null) {
export function makePermissionsFromEmployeeType(
data: EmployeeTypePermission[]
) {
- const result: Record<string, { id: string; permission: Permission }> = {};
+ const result: Record<string, { name: string; permission: Permission }> = {};
if (!data) return result;
data.forEach((permission) => {
- if (Array.isArray(permission.feature) || !permission.feature) {
- // hmm... TODO: handle this
+ if (!permission.module) {
throw new Error(
- `TODO: permission.Feature is an array or null for permission ${JSON.stringify(
- permission,
- null,
- 2
- )}`
+ `Module is missing for permission ${JSON.stringify(permission)}`
);
} else {
- result[permission.feature.name] = {
- id: permission?.feature?.id!,
+ result[permission.module] = {
+ name: permission.module.toLowerCase(),
permission: {
view: permission.view,
create: permission.create,
@@ -574,12 +613,12 @@ export function makePermissionsFromEmployeeType(
return result;
}
-function makeSupplierClaims() {
+function makeSupplierClaims(companyId: number) {
// TODO: this should be more dynamic
- const claims: Record<string, boolean> = {
- documents_view: true,
- purchasing_view: true,
- parts_view: true,
+ const claims: Record<string, number[]> = {
+ documents_view: [companyId],
+ purchasing_view: [companyId],
+ parts_view: [companyId],
};
return claims;
@@ -612,8 +651,29 @@ async function setUserClaims(
userId: string,
claims: Record<string, number[] | string>
) {
- return getSupabaseServiceRole().auth.admin.updateUserById(userId, {
- app_metadata: claims,
+ const client = getSupabaseServiceRole();
+ const user = await client.auth.admin.getUserById(userId);
+ if (user.error) throw new Error(user.error.message);
+
+ const currentClaims = user.data?.user.app_metadata ?? {};
+ const newClaims = { ...currentClaims };
+
+ Object.entries(claims).forEach(([key, value]) => {
+ if (key === "role") {
+ newClaims["role"] = value;
+ }
+
+ if (isClaimPermission(key, value)) {
+ if (key in newClaims) {
+ newClaims[key] = [...newClaims[key], ...value];
+ } else {
+ newClaims[key] = value;
+ }
+ }
+ });
+
+ return client.auth.admin.updateUserById(userId, {
+ app_metadata: newClaims,
});
}
diff --git a/apps/carbon/app/modules/users/users.service.ts b/apps/carbon/app/modules/users/users.service.ts
index e0966d4e68..084425261b 100644
--- a/apps/carbon/app/modules/users/users.service.ts
+++ b/apps/carbon/app/modules/users/users.service.ts
@@ -3,6 +3,8 @@ import type { SupabaseClient } from "@supabase/supabase-js";
import logger from "~/lib/logger";
import type { GenericQueryFilters } from "~/utils/query";
import { setGenericQueryFilters } from "~/utils/query";
+import { capitalize } from "~/utils/string";
+import { sanitize } from "~/utils/supabase";
import type { Permission } from "./types";
export async function deleteEmployeeType(
@@ -38,16 +40,20 @@ export async function getCompaniesForUser(
export async function getCustomers(
client: SupabaseClient<Database>,
+ companyId: number,
args: GenericQueryFilters & {
search: string | null;
}
) {
// TODO: this breaks on customerType filters -- convert to view
- let query = client.from("customerAccount").select(
- `user!inner(id, fullName, firstName, lastName, email, avatarUrl, active),
+ let query = client
+ .from("customerAccount")
+ .select(
+ `user!inner(id, fullName, firstName, lastName, email, avatarUrl, active),
customer!inner(name, customerType!left(name))`,
- { count: "exact" }
- );
+ { count: "exact" }
+ )
+ .eq("companyId", companyId);
if (args.search) {
query = query.ilike("user.fullName", `%${args.search}%`);
@@ -77,13 +83,10 @@ export async function getEmployees(
search: string | null;
}
) {
- // TODO: convert to view
let query = client
- .from("employee")
- .select(
- "user!inner(id, fullName, firstName, lastName, email, avatarUrl, active), employeeType!inner(name)",
- { count: "exact" }
- );
+ .from("employees")
+ .select("*", { count: "exact" })
+ .eq("companyId", companyId);
if (args.search) {
query = query.ilike("user.fullName", `%${args.search}%`);
@@ -152,15 +155,18 @@ export async function getGroupMembers(
export async function getGroups(
client: SupabaseClient<Database>,
+ companyId: number,
args?: GenericQueryFilters & {
search: string | null;
uid: string | null;
}
) {
- let query = client.rpc("groups_query", {
- _uid: args?.uid ?? "",
- _name: args?.search ?? "",
- });
+ let query = client
+ .rpc("groups_query", {
+ _uid: args?.uid ?? "",
+ _name: args?.search ?? "",
+ })
+ .eq("companyId", companyId);
if (args) query = setGenericQueryFilters(query, args);
@@ -173,22 +179,26 @@ export async function getPermissionsByEmployeeType(
) {
return client
.from("employeeTypePermission")
- .select("view, create, update, delete, module (id, name)")
+ .select("view, create, update, delete, module")
.eq("employeeTypeId", employeeTypeId);
}
export async function getSuppliers(
client: SupabaseClient<Database>,
+ companyId: number,
args: GenericQueryFilters & {
search: string | null;
}
) {
// TODO: this breaks on supplierType filters -- convert to view
- let query = client.from("supplierAccount").select(
- `user!inner(id, fullName, firstName, lastName, email, avatarUrl, active),
+ let query = client
+ .from("supplierAccount")
+ .select(
+ `user!inner(id, fullName, firstName, lastName, email, avatarUrl, active),
supplier!inner(name, supplierType!left(name))`,
- { count: "exact" }
- );
+ { count: "exact" }
+ )
+ .eq("companyId", companyId);
if (args.search) {
query = query.ilike("user.fullName", `%${args.search}%`);
@@ -210,7 +220,7 @@ export async function getUsers(client: SupabaseClient<Database>) {
export async function insertEmployeeType(
client: SupabaseClient<Database>,
- employeeType: { id?: string; name: string; color?: string }
+ employeeType: { id?: string; name: string; companyId: number }
) {
return client
.from("employeeType")
@@ -221,18 +231,27 @@ export async function insertEmployeeType(
export async function insertGroup(
client: SupabaseClient<Database>,
- group: { name: string }
+ group: { name: string; companyId: number }
) {
return client.from("group").insert(group).select("*").single();
}
export async function upsertEmployeeType(
client: SupabaseClient<Database>,
- employeeType: { id?: string; name: string; color?: string }
+ employeeType:
+ | { name: string; companyId: number }
+ | { id: string; name: string }
) {
+ if ("id" in employeeType) {
+ return client
+ .from("employeeType")
+ .update(sanitize(employeeType))
+ .select("id")
+ .single();
+ }
return client
.from("employeeType")
- .upsert([employeeType])
+ .insert([employeeType])
.select("id")
.single();
}
@@ -240,11 +259,11 @@ export async function upsertEmployeeType(
export async function upsertEmployeeTypePermissions(
client: SupabaseClient<Database>,
employeeTypeId: string,
- permissions: { id: string; permission: Permission }[]
+ permissions: { name: string; permission: Permission }[]
) {
- const employeeTypePermissions = permissions.map(({ id, permission }) => ({
+ const employeeTypePermissions = permissions.map(({ name, permission }) => ({
employeeTypeId,
- moduleId: id,
+ module: capitalize(name) as "Accounting",
view: permission.view,
create: permission.create,
update: permission.update,
@@ -259,12 +278,14 @@ export async function upsertGroup(
{
id,
name,
+ companyId,
}: {
id: string;
name: string;
+ companyId: number;
}
) {
- return client.from("group").upsert([{ id, name }]);
+ return client.from("group").upsert([{ id, name, companyId }]);
}
export async function upsertGroupMembers(
diff --git a/apps/carbon/app/routes/api+/users.empty-permissions.ts b/apps/carbon/app/routes/api+/users.empty-permissions.ts
index 9c8a39a446..70ceadbe3f 100644
--- a/apps/carbon/app/routes/api+/users.empty-permissions.ts
+++ b/apps/carbon/app/routes/api+/users.empty-permissions.ts
@@ -1,28 +1,28 @@
import type { LoaderFunctionArgs } from "@remix-run/node";
import { json } from "@remix-run/node";
-import { getFeatures } from "~/modules/users";
-import { makeEmptyPermissionsFromFeatures } from "~/modules/users/users.server";
+import { getModules } from "~/modules/users";
+import { makeEmptyPermissionsFromModules } from "~/modules/users/users.server";
import { requirePermissions } from "~/services/auth/auth.server";
import { flash } from "~/services/session.server";
import { error } from "~/utils/result";
export async function loader({ request }: LoaderFunctionArgs) {
- const authorized = await requirePermissions(request, {
+ const { client } = await requirePermissions(request, {
view: "users",
role: "employee",
});
- const features = await getFeatures(authorized.client);
- if (features.error || features.data === null) {
+ const modules = await getModules(client);
+ if (modules.error || modules.data === null) {
return json(
{
permissions: {},
},
- await flash(request, error(features.error, "Failed to fetch features"))
+ await flash(request, error(modules.error, "Failed to fetch modules"))
);
}
return json({
- permissions: makeEmptyPermissionsFromFeatures(features.data),
+ permissions: makeEmptyPermissionsFromModules(modules.data),
});
}
diff --git a/apps/carbon/app/routes/x+/shared+/notes.new.tsx b/apps/carbon/app/routes/x+/shared+/notes.new.tsx
index 305dd7ee8b..42b7b7ad47 100644
--- a/apps/carbon/app/routes/x+/shared+/notes.new.tsx
+++ b/apps/carbon/app/routes/x+/shared+/notes.new.tsx
@@ -9,7 +9,7 @@ import { error } from "~/utils/result";
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
- const { client, userId } = await requirePermissions(request, {});
+ const { client, companyId, userId } = await requirePermissions(request, {});
const validation = await validator(noteValidator).validate(
await request.formData()
@@ -23,6 +23,7 @@ export async function action({ request }: ActionFunctionArgs) {
const createNote = await insertNote(client, {
documentId,
note,
+ companyId,
createdBy: userId,
});
if (createNote.error) {
diff --git a/apps/carbon/app/routes/x+/users+/customers.new.tsx b/apps/carbon/app/routes/x+/users+/customers.new.tsx
index a42429e518..5055bda6a1 100644
--- a/apps/carbon/app/routes/x+/users+/customers.new.tsx
+++ b/apps/carbon/app/routes/x+/users+/customers.new.tsx
@@ -13,7 +13,7 @@ import { path } from "~/utils/path";
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
- const { client } = await requirePermissions(request, {
+ const { client, companyId } = await requirePermissions(request, {
view: "users",
});
@@ -33,6 +33,7 @@ export async function action({ request }: ActionFunctionArgs) {
const result = await createCustomerAccount(client, {
id,
customerId: customer,
+ companyId,
});
if (customerRedirect) {
diff --git a/apps/carbon/app/routes/x+/users+/customers.tsx b/apps/carbon/app/routes/x+/users+/customers.tsx
index 055084c02f..c0cfebe196 100644
--- a/apps/carbon/app/routes/x+/users+/customers.tsx
+++ b/apps/carbon/app/routes/x+/users+/customers.tsx
@@ -29,7 +29,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
getGenericQueryFilters(searchParams);
const [customers, customerTypes] = await Promise.all([
- getCustomers(client, { search, limit, offset, sorts, filters }),
+ getCustomers(client, companyId, { search, limit, offset, sorts, filters }),
getCustomerTypes(client, companyId),
]);
diff --git a/apps/carbon/app/routes/x+/users+/employee-types.new.tsx b/apps/carbon/app/routes/x+/users+/employee-types.new.tsx
index 6bcc394be5..20d62d415f 100644
--- a/apps/carbon/app/routes/x+/users+/employee-types.new.tsx
+++ b/apps/carbon/app/routes/x+/users+/employee-types.new.tsx
@@ -6,11 +6,11 @@ import {
EmployeeTypeForm,
employeeTypePermissionsValidator,
employeeTypeValidator,
- getFeatures,
+ getModules,
insertEmployeeType,
upsertEmployeeTypePermissions,
} from "~/modules/users";
-import { makeEmptyPermissionsFromFeatures } from "~/modules/users/users.server";
+import { makeEmptyPermissionsFromModules } from "~/modules/users/users.server";
import { requirePermissions } from "~/services/auth/auth.server";
import { flash } from "~/services/session.server";
import { assertIsPost } from "~/utils/http";
@@ -22,22 +22,22 @@ export async function loader({ request }: LoaderFunctionArgs) {
create: "users",
});
- const features = await getFeatures(client);
- if (features.error || features.data === null) {
+ const modules = await getModules(client);
+ if (modules.error || modules.data === null) {
throw redirect(
path.to.employeeTypes,
- await flash(request, error(features.error, "Failed to get features"))
+ await flash(request, error(modules.error, "Failed to get modules"))
);
}
return json({
- permissions: makeEmptyPermissionsFromFeatures(features.data),
+ permissions: makeEmptyPermissionsFromModules(modules.data),
});
}
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
- const { client } = await requirePermissions(request, {
+ const { client, companyId } = await requirePermissions(request, {
create: "users",
});
@@ -66,6 +66,7 @@ export async function action({ request }: ActionFunctionArgs) {
const createEmployeeType = await insertEmployeeType(client, {
name,
+ companyId,
});
if (createEmployeeType.error) {
return json(
diff --git a/apps/carbon/app/routes/x+/users+/employees.tsx b/apps/carbon/app/routes/x+/users+/employees.tsx
index 18e47da33a..f1b69ad7b5 100644
--- a/apps/carbon/app/routes/x+/users+/employees.tsx
+++ b/apps/carbon/app/routes/x+/users+/employees.tsx
@@ -20,7 +20,7 @@ export const handle: Handle = {
};
export async function loader({ request }: LoaderFunctionArgs) {
- const { client } = await requirePermissions(request, {
+ const { client, companyId } = await requirePermissions(request, {
view: "users",
role: "employee",
});
@@ -33,8 +33,8 @@ export async function loader({ request }: LoaderFunctionArgs) {
getGenericQueryFilters(searchParams);
const [employees, employeeTypes] = await Promise.all([
- getEmployees(client, { search, limit, offset, sorts, filters }),
- getEmployeeTypes(client),
+ getEmployees(client, companyId, { search, limit, offset, sorts, filters }),
+ getEmployeeTypes(client, companyId),
]);
if (employees.error) {
diff --git a/apps/carbon/app/routes/x+/users+/groups.$groupId.tsx b/apps/carbon/app/routes/x+/users+/groups.$groupId.tsx
index dbfab08888..858c06f608 100644
--- a/apps/carbon/app/routes/x+/users+/groups.$groupId.tsx
+++ b/apps/carbon/app/routes/x+/users+/groups.$groupId.tsx
@@ -59,7 +59,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
- const { client } = await requirePermissions(request, {
+ const { client, companyId } = await requirePermissions(request, {
view: "users",
});
@@ -74,7 +74,7 @@ export async function action({ request }: ActionFunctionArgs) {
const { id, name, selections } = validation.data;
const [updateGroup, updateGroupMembers] = await Promise.all([
- upsertGroup(client, { id, name }),
+ upsertGroup(client, { id, name, companyId }),
upsertGroupMembers(client, id, selections),
]);
diff --git a/apps/carbon/app/routes/x+/users+/groups.new.tsx b/apps/carbon/app/routes/x+/users+/groups.new.tsx
index 6737902d1b..765f1aac7d 100644
--- a/apps/carbon/app/routes/x+/users+/groups.new.tsx
+++ b/apps/carbon/app/routes/x+/users+/groups.new.tsx
@@ -16,7 +16,7 @@ import { error, success } from "~/utils/result";
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
- const { client } = await requirePermissions(request, {
+ const { client, companyId } = await requirePermissions(request, {
create: "users",
});
@@ -30,7 +30,7 @@ export async function action({ request }: ActionFunctionArgs) {
const { name, selections } = validation.data;
- const createGroup = await insertGroup(client, { name });
+ const createGroup = await insertGroup(client, { name, companyId });
if (createGroup.error) {
return json(
{},
diff --git a/apps/carbon/app/routes/x+/users+/groups.tsx b/apps/carbon/app/routes/x+/users+/groups.tsx
index 930bde6b68..cb2ee2c8d4 100644
--- a/apps/carbon/app/routes/x+/users+/groups.tsx
+++ b/apps/carbon/app/routes/x+/users+/groups.tsx
@@ -18,7 +18,7 @@ export const handle: Handle = {
};
export async function loader({ request }: LoaderFunctionArgs) {
- const { client } = await requirePermissions(request, {
+ const { client, companyId } = await requirePermissions(request, {
view: "users",
role: "employee",
});
@@ -30,7 +30,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
const { limit, offset, sorts, filters } =
getGenericQueryFilters(searchParams);
- const groups = await getGroups(client, {
+ const groups = await getGroups(client, companyId, {
search,
uid,
limit,
diff --git a/apps/carbon/app/routes/x+/users+/suppliers.new.tsx b/apps/carbon/app/routes/x+/users+/suppliers.new.tsx
index 8030b9eda9..c75ab12309 100644
--- a/apps/carbon/app/routes/x+/users+/suppliers.new.tsx
+++ b/apps/carbon/app/routes/x+/users+/suppliers.new.tsx
@@ -13,7 +13,7 @@ import { path } from "~/utils/path";
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
- const { client } = await requirePermissions(request, {
+ const { client, companyId } = await requirePermissions(request, {
view: "users",
});
const formData = await request.formData();
@@ -33,6 +33,7 @@ export async function action({ request }: ActionFunctionArgs) {
const result = await createSupplierAccount(client, {
id,
supplierId: supplier,
+ companyId,
});
if (supplierRedirect) {
diff --git a/apps/carbon/app/routes/x+/users+/suppliers.tsx b/apps/carbon/app/routes/x+/users+/suppliers.tsx
index 1e7ef4e31f..e59c186589 100644
--- a/apps/carbon/app/routes/x+/users+/suppliers.tsx
+++ b/apps/carbon/app/routes/x+/users+/suppliers.tsx
@@ -29,7 +29,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
getGenericQueryFilters(searchParams);
const [suppliers, supplierTypes] = await Promise.all([
- getSuppliers(client, {
+ getSuppliers(client, companyId, {
search,
limit,
offset,
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 870cdbf981..314695aa70 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -15981,7 +15981,10 @@ export type Database = {
Row: {
avatarUrl: string | null
companyId: number | null
+ email: string | null
+ firstName: string | null
id: string | null
+ lastName: string | null
name: string | null
}
Relationships: [
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 870cdbf981..314695aa70 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -15981,7 +15981,10 @@ export type Database = {
Row: {
avatarUrl: string | null
companyId: number | null
+ email: string | null
+ firstName: string | null
id: string | null
+ lastName: string | null
name: string | null
}
Relationships: [
diff --git a/packages/database/supabase/migrations/20240323161015_employees-view.sql b/packages/database/supabase/migrations/20240323161015_employees-view.sql
index d889bdd4ca..3f65fd9e16 100644
--- a/packages/database/supabase/migrations/20240323161015_employees-view.sql
+++ b/packages/database/supabase/migrations/20240323161015_employees-view.sql
@@ -1,6 +1,9 @@
CREATE OR REPLACE VIEW "employees" WITH(SECURITY_INVOKER=true) AS
SELECT
u.id,
+ u."email",
+ u."firstName",
+ u."lastName",
u."fullName" AS "name",
u."avatarUrl",
e."companyId"