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.

fix: account create for users, customers, and suppliers

Brad Barbin0965c2abd035
diff --git a/apps/carbon/app/hooks/useUser.tsx b/apps/carbon/app/hooks/useUser.tsx
index 7a9f3d5ae9..30cdc667ec 100644
--- a/apps/carbon/app/hooks/useUser.tsx
+++ b/apps/carbon/app/hooks/useUser.tsx
@@ -41,16 +41,16 @@ export function useUser(): User {
isUser(data.user) &&
data?.groups &&
isGroups(data.groups) &&
- data?.defaults &&
isDefaults(data.defaults)
) {
return {
...data.user,
company: data.company,
groups: data.groups,
- defaults: data.defaults,
+ defaults: data.defaults ?? { locationId: null },
};
}
+
// TODO: force logout -- the likely cause is development changes
throw new Error(
"useUser must be used within an authenticated route. If you are seeing this error, you are likely in development and have changed the session variables. Try deleting the cookies."
@@ -66,7 +66,11 @@ function isCompany(value: any): value is Company {
}
function isDefaults(value: any): value is Defaults {
- return typeof value.locationId === "string" || value.locationId === null;
+ return (
+ value === null ||
+ typeof value.locationId === "string" ||
+ value.locationId === null
+ );
}
function isGroups(value: any): value is string[] {
diff --git a/apps/carbon/app/modules/users/users.server.ts b/apps/carbon/app/modules/users/users.server.ts
index 13b9aaa59a..f4372aa54c 100644
--- a/apps/carbon/app/modules/users/users.server.ts
+++ b/apps/carbon/app/modules/users/users.server.ts
@@ -76,7 +76,6 @@ export async function createCustomerAccount(
return error(invitation.error.message, "Failed to send invitation email");
const userId = invitation.data.user.id;
- const userToCompany = await addUserToCompany(client, { userId, companyId });
const claims = makeCustomerClaims(companyId);
const claimsUpdate = await setUserClaims(userId, {
@@ -84,7 +83,7 @@ export async function createCustomerAccount(
...claims,
});
- if (claimsUpdate.error || userToCompany.error) {
+ if (claimsUpdate.error) {
await deleteAuthAccount(userId);
return error(claimsUpdate.error, "Failed to add user");
}
@@ -103,29 +102,34 @@ export async function createCustomerAccount(
if (!insertUser.data)
return error(insertUser, "No data returned from create user");
- const updateContact = await client
- .from("customerContact")
- .update({ userId })
- .eq("id", id);
+ const [updateContact, createCustomerAccount, userToCompany] =
+ await Promise.all([
+ client.from("customerContact").update({ userId }).eq("id", id),
+ insertCustomerAccount(client, {
+ id: userId,
+ customerId,
+ companyId,
+ }),
+ addUserToCompany(client, { userId, companyId }),
+ ]);
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) {
+ await deleteAuthAccount(userId);
+ return error(
+ createCustomerAccount.error,
+ "Failed to create a customer account"
+ );
+ }
- if (createCustomerAccount.error)
- return error(createCustomerAccount.error, "Failed to create an employee");
+ if (userToCompany.error) {
+ await deleteAuthAccount(userId);
+ return error(userToCompany.error, "Failed to add user to company");
+ }
return success("Customer account created");
}
@@ -159,6 +163,7 @@ export async function createEmployeeAccount(
);
const user = await getUserByEmail(email);
+
if (user.data) {
// TODO: user already exists -- send company invite
await addUserToCompany(client, { userId: user.data.id, companyId });
@@ -173,16 +178,17 @@ export async function createEmployeeAccount(
return error(invitation.error.message, "Failed to send invitation email");
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 || userToCompany.error) {
+ if (claimsUpdate.error) {
await deleteAuthAccount(userId);
- return error(claimsUpdate.error, "Failed to create user");
+ if (claimsUpdate.error) {
+ return error(claimsUpdate.error, "Failed to udpate user claims");
+ }
}
const insertUser = await createUser(client, {
@@ -199,14 +205,24 @@ export async function createEmployeeAccount(
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, userToCompany] = await Promise.all([
+ insertEmployee(client, {
+ id: insertUser.data[0].id,
+ employeeTypeId: employeeType,
+ companyId,
+ }),
+ addUserToCompany(client, { userId, companyId }),
+ ]);
- if (createEmployee.error)
- return error(createEmployee.error, "Failed to create an employee");
+ if (createEmployee.error) {
+ await deleteAuthAccount(userId);
+ return error(createEmployee.error, "Failed to create a employee account");
+ }
+
+ if (userToCompany.error) {
+ await deleteAuthAccount(userId);
+ return error(userToCompany.error, "Failed to add user to company");
+ }
return success("Employee account created");
}
@@ -253,14 +269,13 @@ export async function createSupplierAccount(
return error(invitation.error.message, "Failed to send invitation email");
const userId = invitation.data.user.id;
- const userToCompany = await addUserToCompany(client, { userId, companyId });
const claims = makeSupplierClaims(companyId);
const claimsUpdate = await setUserClaims(userId, {
role: "supplier",
...claims,
});
- if (claimsUpdate.error || userToCompany.error) {
+ if (claimsUpdate.error) {
await deleteAuthAccount(userId);
return error(claimsUpdate.error, "Failed to create user");
}
@@ -279,23 +294,34 @@ export async function createSupplierAccount(
if (!insertUser.data)
return error(insertUser, "No data returned from create user");
- const updateContact = await client
- .from("supplierContact")
- .update({ userId })
- .eq("id", id);
+ const [updateContact, createSupplierAccount, userToCompany] =
+ await Promise.all([
+ client.from("supplierContact").update({ userId }).eq("id", id),
+ insertSupplierAccount(client, {
+ id: insertUser.data[0].id,
+ supplierId,
+ companyId,
+ }),
+ addUserToCompany(client, { userId, companyId }),
+ ]);
+
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,
- companyId,
- });
+ if (createSupplierAccount.error) {
+ await deleteAuthAccount(userId);
+ return error(
+ createSupplierAccount.error,
+ "Failed to create a supplier account"
+ );
+ }
- if (createSupplierAccount.error)
- return error(createSupplierAccount.error, "Failed to create an employee");
+ if (userToCompany.error) {
+ await deleteAuthAccount(userId);
+ return error(userToCompany.error, "Failed to add user to company");
+ }
return success("Supplier account created");
}
diff --git a/apps/carbon/app/routes/x+/invoicing+/purchasing.tsx b/apps/carbon/app/routes/x+/invoicing+/purchasing.tsx
index 772f9438bb..bf2f33f61b 100644
--- a/apps/carbon/app/routes/x+/invoicing+/purchasing.tsx
+++ b/apps/carbon/app/routes/x+/invoicing+/purchasing.tsx
@@ -47,7 +47,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
path.to.invoicing,
await flash(
request,
- error(purchaseInvoices.error, "Failed to fetch purchas orders")
+ error(purchaseInvoices.error, "Failed to fetch purchase invoices")
)
);
}
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index e41dd77cb5..c70676e14a 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -16443,6 +16443,7 @@ export type Database = {
Row: {
assignee: string | null
balance: number | null
+ companyId: number | null
createdAt: string | null
createdBy: string | null
currencyCode: string | null
@@ -16496,6 +16497,13 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
+ {
+ foreignKeyName: "purchaseInvoice_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "purchaseInvoice_createdBy_fkey"
columns: ["createdBy"]
@@ -16524,6 +16532,13 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
+ {
+ foreignKeyName: "purchaseInvoice_currencyCode_fkey"
+ columns: ["currencyCode", "companyId"]
+ isOneToOne: false
+ referencedRelation: "currency"
+ referencedColumns: ["code", "companyId"]
+ },
{
foreignKeyName: "purchaseInvoice_invoiceSupplierId_fkey"
columns: ["invoiceSupplierId"]
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index e41dd77cb5..c70676e14a 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -16443,6 +16443,7 @@ export type Database = {
Row: {
assignee: string | null
balance: number | null
+ companyId: number | null
createdAt: string | null
createdBy: string | null
currencyCode: string | null
@@ -16496,6 +16497,13 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
+ {
+ foreignKeyName: "purchaseInvoice_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "purchaseInvoice_createdBy_fkey"
columns: ["createdBy"]
@@ -16524,6 +16532,13 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
+ {
+ foreignKeyName: "purchaseInvoice_currencyCode_fkey"
+ columns: ["currencyCode", "companyId"]
+ isOneToOne: false
+ referencedRelation: "currency"
+ referencedColumns: ["code", "companyId"]
+ },
{
foreignKeyName: "purchaseInvoice_invoiceSupplierId_fkey"
columns: ["invoiceSupplierId"]
diff --git a/packages/database/supabase/migrations/20230123004206_claims.sql b/packages/database/supabase/migrations/20230123004206_claims.sql
index 747c9c5b1b..256db7418b 100644
--- a/packages/database/supabase/migrations/20230123004206_claims.sql
+++ b/packages/database/supabase/migrations/20230123004206_claims.sql
@@ -133,7 +133,7 @@ CREATE OR REPLACE FUNCTION has_any_company_permission(claim text) RETURNS "bool"
SELECT jsonb_to_integer_array(coalesce(raw_app_meta_data->claim, '[]')) INTO claim_value FROM auth.users WHERE id = auth.uid();
IF claim_value IS NULL THEN
return false;
- ELSIF array_length(claim_value) > 0 THEN
+ ELSIF array_length(claim_value, 1) > 0 THEN
return true;
ELSE
return false;
diff --git a/packages/database/supabase/migrations/20230123004316_users.sql b/packages/database/supabase/migrations/20230123004316_users.sql
index d78ff7fdf0..c37522c63f 100644
--- a/packages/database/supabase/migrations/20230123004316_users.sql
+++ b/packages/database/supabase/migrations/20230123004316_users.sql
@@ -19,7 +19,7 @@ CREATE INDEX "index_user_fullName" ON "user"("fullName");
ALTER TABLE "user" ENABLE ROW LEVEL SECURITY;
-CREATE POLICY "Claims admin can view/modify users" ON "user" FOR ALL USING (is_claims_admin());
+CREATE POLICY "Claims admin can view/modify users" ON "user" FOR ALL USING (has_any_company_permission('users_update'));
CREATE POLICY "Users can modify themselves" ON "user" FOR UPDATE WITH CHECK (auth.uid() = id::uuid);
CREATE POLICY "Anyone that's authenticated can view users" ON "user" FOR SELECT USING (auth.role() = 'authenticated');
diff --git a/packages/database/supabase/migrations/20230123004317_companies.sql b/packages/database/supabase/migrations/20230123004317_companies.sql
index 0b86938702..4ed08fb959 100644
--- a/packages/database/supabase/migrations/20230123004317_companies.sql
+++ b/packages/database/supabase/migrations/20230123004317_companies.sql
@@ -29,7 +29,7 @@ CREATE POLICY "Authenticated users can view company" ON "company"
CREATE POLICY "Employees with settings_create can create company" ON "company"
FOR INSERT
WITH CHECK (
- is_claims_admin()
+ has_any_company_permission('settings_create')
);
CREATE POLICY "Employees with settings_update can update company" ON "company"
@@ -42,7 +42,7 @@ CREATE POLICY "Employees with settings_update can update company" ON "company"
CREATE POLICY "Employees with settings_delete can delete company" ON "company"
FOR DELETE
USING (
- is_claims_admin()
+ has_company_permission('settings_delete', "id")
);
CREATE TABLE "userToCompany" (
diff --git a/packages/database/supabase/migrations/20230123004339_employee-types.sql b/packages/database/supabase/migrations/20230123004339_employee-types.sql
index 550e42efac..ca9428e875 100644
--- a/packages/database/supabase/migrations/20230123004339_employee-types.sql
+++ b/packages/database/supabase/migrations/20230123004339_employee-types.sql
@@ -17,7 +17,8 @@ CREATE INDEX "employeeType_companyId_idx" ON "employeeType" ("companyId");
ALTER TABLE "employeeType" ENABLE ROW LEVEL SECURITY;
-CREATE POLICY "Only claims admin can view/modify permissions for employee types" ON "employeeType" FOR ALL USING (
+CREATE POLICY "Employees with users_update can view/modify employee types" ON "employeeType" FOR ALL USING (
+ has_role('employee') AND
has_company_permission('users_update', "companyId")
);
diff --git a/packages/database/supabase/migrations/20230123004409_permissions.sql b/packages/database/supabase/migrations/20230123004409_permissions.sql
index ef78be47ff..1b19a0c1b0 100644
--- a/packages/database/supabase/migrations/20230123004409_permissions.sql
+++ b/packages/database/supabase/migrations/20230123004409_permissions.sql
@@ -36,6 +36,10 @@ CREATE TABLE "employeeTypePermission" (
ALTER TABLE "employeeTypePermission" ENABLE ROW LEVEL SECURITY;
-CREATE POLICY "Only claims admin can view/modify permissions for employee types" ON "employeeTypePermission" FOR ALL USING (is_claims_admin());
+CREATE POLICY "Employees with users_update can view/modify permissions for employee type permissions" ON "employeeTypePermission" FOR ALL USING (
+ has_role('employee') AND
+ has_company_permission('users_update', (
+ SELECT "companyId" FROM "employeeType" WHERE "id" = "employeeTypeId"))
+);
diff --git a/packages/database/supabase/migrations/20230123004436_employee.sql b/packages/database/supabase/migrations/20230123004436_employee.sql
index 891816fd22..4f76f55bee 100644
--- a/packages/database/supabase/migrations/20230123004436_employee.sql
+++ b/packages/database/supabase/migrations/20230123004436_employee.sql
@@ -12,5 +12,22 @@ CREATE INDEX "employee_companyId_idx" ON "employee" ("companyId");
ALTER TABLE "employee" ENABLE ROW LEVEL SECURITY;
-CREATE POLICY "Only claims admin can view/modify employees" ON "employee" FOR ALL USING (is_claims_admin());
-CREATE POLICY "Anyone that's authenticated can view employees" ON "employee" FOR SELECT USING (auth.role() = 'authenticated');
+
+CREATE POLICY "Employees can view employees from their company" ON "employee" FOR SELECT USING (
+ is_claims_admin() OR
+ "companyId" IN (
+ SELECT "companyId" FROM "userToCompany" WHERE "userId" = auth.uid()::text
+ )
+);
+
+CREATE POLICY "Employees with users_update can create employees" ON "employee" FOR INSERT WITH CHECK (
+ has_company_permission('users_create', "companyId")
+);
+
+CREATE POLICY "Employees with users_update can update employees" ON "employee" FOR UPDATE USING (
+ has_company_permission('users_update', "companyId")
+);
+
+CREATE POLICY "Employees with users_update can delete employees" ON "employee" FOR DELETE USING (
+ has_company_permission('users_delete', "companyId")
+);
\ No newline at end of file
diff --git a/packages/database/supabase/migrations/20231109050239_supplier-details.sql b/packages/database/supabase/migrations/20231109050239_supplier-details.sql
index 81b674245d..8781e379a4 100644
--- a/packages/database/supabase/migrations/20231109050239_supplier-details.sql
+++ b/packages/database/supabase/migrations/20231109050239_supplier-details.sql
@@ -89,7 +89,7 @@ RETURNS TRIGGER AS $$
BEGIN
INSERT INTO public."supplierPayment"("supplierId", "invoiceSupplierId", "companyId")
VALUES (new.id, new.id, new."companyId");
- INSERT INTO public."supplierShipping"("supplierId", "shippingSupplierId")
+ INSERT INTO public."supplierShipping"("supplierId", "shippingSupplierId", "companyId")
VALUES (new.id, new.id, new."companyId");
RETURN new;
END;
diff --git a/packages/database/supabase/migrations/20240324175747_assignee.sql b/packages/database/supabase/migrations/20240324175747_assignee.sql
index 501f95a30f..a032cc630e 100644
--- a/packages/database/supabase/migrations/20240324175747_assignee.sql
+++ b/packages/database/supabase/migrations/20240324175747_assignee.sql
@@ -71,6 +71,7 @@ CREATE OR REPLACE VIEW "purchaseInvoices" WITH(SECURITY_INVOKER=true) AS
pi."updatedBy",
pi."updatedAt",
pi."customFields",
+ pi."companyId",
CASE
WHEN pi."dateDue" < CURRENT_DATE AND pi."status" = 'Submitted' THEN 'Overdue'
ELSE pi."status"