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: move employee type and permissions generation from seed.ts to seed-company function

Brad Barbin471e66d4222c
diff --git a/apps/carbon/app/modules/users/users.service.ts b/apps/carbon/app/modules/users/users.service.ts
index 7f273a34ed..e0966d4e68 100644
--- a/apps/carbon/app/modules/users/users.service.ts
+++ b/apps/carbon/app/modules/users/users.service.ts
@@ -129,8 +129,8 @@ export async function getEmployeeTypes(
return query;
}
-export async function getFeatures(client: SupabaseClient<Database>) {
- return client.from("feature").select("id, name").order("name");
+export async function getModules(client: SupabaseClient<Database>) {
+ return client.from("modules").select("name").order("name");
}
export async function getGroup(
@@ -173,7 +173,7 @@ export async function getPermissionsByEmployeeType(
) {
return client
.from("employeeTypePermission")
- .select("view, create, update, delete, feature (id, name)")
+ .select("view, create, update, delete, module (id, name)")
.eq("employeeTypeId", employeeTypeId);
}
@@ -244,7 +244,7 @@ export async function upsertEmployeeTypePermissions(
) {
const employeeTypePermissions = permissions.map(({ id, permission }) => ({
employeeTypeId,
- featureId: id,
+ moduleId: id,
view: permission.view,
create: permission.create,
update: permission.update,
diff --git a/packages/database/src/seed.ts b/packages/database/src/seed.ts
index 815779735e..680961dcab 100644
--- a/packages/database/src/seed.ts
+++ b/packages/database/src/seed.ts
@@ -1,13 +1,6 @@
import { createClient } from "@supabase/supabase-js";
import * as dotenv from "dotenv";
-import type { EmployeeType, Feature } from "./seed/index";
-import {
- admin,
- claims,
- employeeTypePermissionsDefinitions,
- employeeTypes,
- features,
-} from "./seed/index";
+import { admin, claims } from "./seed/index";
import type { Database } from "./types";
dotenv.config();
@@ -46,7 +39,6 @@ const getUserId = async (): Promise<string> => {
};
async function seed() {
- // TODO: this should all be moved to the migration or seed function
const id = await getUserId();
const upsertAdmin = await supabaseAdmin.from("user").upsert([
@@ -65,83 +57,6 @@ async function seed() {
app_metadata: claims,
});
- const deleteFeatures = await supabaseAdmin
- .from("feature")
- .delete()
- .neq("id", 0);
- if (deleteFeatures.error) throw deleteFeatures.error;
-
- const insertFeatures = await supabaseAdmin
- .from("feature")
- .insert([...Object.values(features)]);
- if (insertFeatures.error) throw insertFeatures.error;
-
- const deleteEmployeeTypes = await supabaseAdmin
- .from("employeeType")
- .delete()
- .neq("id", 0);
- if (deleteEmployeeTypes.error) throw deleteEmployeeTypes.error;
-
- const insertGroups = await supabaseAdmin.from("group").insert([
- {
- id: "00000000-0000-0000-0000-000000000000",
- name: "All Employees",
- isCustomerTypeGroup: false,
- isEmployeeTypeGroup: true,
- isSupplierTypeGroup: false,
- },
- {
- id: "11111111-1111-1111-1111-111111111111",
- name: "All Customers",
- isCustomerTypeGroup: true,
- isEmployeeTypeGroup: false,
- isSupplierTypeGroup: false,
- },
- {
- id: "22222222-2222-2222-2222-222222222222",
- name: "All Suppliers",
- isCustomerTypeGroup: false,
- isEmployeeTypeGroup: false,
- isSupplierTypeGroup: true,
- },
- ]);
- if (insertGroups.error) throw insertGroups.error;
-
- const insertEmployeeTypes = await supabaseAdmin
- .from("employeeType")
- .insert([...Object.values(employeeTypes)]);
- if (insertEmployeeTypes.error) throw insertEmployeeTypes.error;
-
- const employeeTypePermissions = [] as {
- employeeTypeId: string;
- featureId: string;
- create: number[];
- update: number[];
- delete: number[];
- view: number[];
- }[];
-
- Object.entries(employeeTypePermissionsDefinitions).forEach(
- ([empType, featurePermissions]) => {
- const employeeTypeId = employeeTypes[empType as EmployeeType].id;
- Object.keys(featurePermissions).forEach((feature) => {
- const featureId = features[feature as Feature].id;
- employeeTypePermissions.push({
- employeeTypeId,
- featureId,
- ...featurePermissions[feature as Feature],
- });
- });
- }
- );
-
- const insertEmployeeTypePermissions = await supabaseAdmin
- .from("employeeTypePermission")
- .insert(employeeTypePermissions);
-
- if (insertEmployeeTypePermissions.error)
- throw insertEmployeeTypePermissions.error;
-
console.log(`Database has been seeded. 🌱\n`);
console.log(
`Admin user is 👇 \n🆔: ${id}\n📧: ${admin.email}\n🔑: ${admin.password}`
diff --git a/packages/database/src/seed/admin.ts b/packages/database/src/seed/admin.ts
index d2676050c8..cd77f82bd6 100644
--- a/packages/database/src/seed/admin.ts
+++ b/packages/database/src/seed/admin.ts
@@ -1,5 +1,4 @@
-import { ALL_TEAMS_ID } from "./employee-types";
-import { possibleFeatures } from "./features";
+import { modules } from "./modules";
const admin = {
@@ -8,11 +7,13 @@ const admin = {
lastName: "Admin",
};
+const ALL_TEAMS_ID = 0;
+
const claims: Record<string, string | number[]> = {
role: "employee",
};
-possibleFeatures.forEach((name) => {
+modules.forEach((name) => {
const moduleName = name.toLowerCase();
claims[`${moduleName}_view`] = [ALL_TEAMS_ID];
claims[`${moduleName}_create`] = [ALL_TEAMS_ID];
diff --git a/packages/database/src/seed/employee-types.ts b/packages/database/src/seed/employee-types.ts
deleted file mode 100644
index 1e1e10c1ae..0000000000
--- a/packages/database/src/seed/employee-types.ts
+++ /dev/null
@@ -1,117 +0,0 @@
-import { v4 as uuidv4 } from "uuid";
-import type { Feature } from "./features";
-
-export const initialEmployeeTypes = ["Admin"] as const;
-
-export type EmployeeType = (typeof initialEmployeeTypes)[number];
-
-const employeeTypes = {} as Record<
- EmployeeType,
- { id: string; name: string; protected?: boolean }
->;
-
-initialEmployeeTypes.forEach((type) => {
- employeeTypes[type] = {
- id: uuidv4(),
- name: type,
- protected: type === "Admin",
- };
-});
-
-export const ALL_TEAMS_ID = 0;
-
-export { employeeTypes };
-export const employeeTypePermissionsDefinitions: Record<
- EmployeeType,
- Record<
- Feature,
- { create: number[]; update: number[]; delete: number[]; view: number[] }
- >
-> = {
- Admin: {
- Accounting: {
- create: [ALL_TEAMS_ID],
- update: [ALL_TEAMS_ID],
- delete: [ALL_TEAMS_ID],
- view: [ALL_TEAMS_ID],
- },
- Invoicing: {
- create: [ALL_TEAMS_ID],
- update: [ALL_TEAMS_ID],
- delete: [ALL_TEAMS_ID],
- view: [ALL_TEAMS_ID],
- },
- Parts: {
- create: [ALL_TEAMS_ID],
- update: [ALL_TEAMS_ID],
- delete: [ALL_TEAMS_ID],
- view: [ALL_TEAMS_ID],
- },
- // Jobs: {
- // create: [ALL_TEAMS_ID],
- // update: [ALL_TEAMS_ID],
- // delete: [ALL_TEAMS_ID],
- // view: [ALL_TEAMS_ID],
- // },
- Inventory: {
- create: [ALL_TEAMS_ID],
- update: [ALL_TEAMS_ID],
- delete: [ALL_TEAMS_ID],
- view: [ALL_TEAMS_ID],
- },
- // Scheduling: {
- // create: [ALL_TEAMS_ID],
- // update: [ALL_TEAMS_ID],
- // delete: [ALL_TEAMS_ID],
- // view: [ALL_TEAMS_ID],
- // },
- Sales: {
- create: [ALL_TEAMS_ID],
- update: [ALL_TEAMS_ID],
- delete: [ALL_TEAMS_ID],
- view: [ALL_TEAMS_ID],
- },
- Purchasing: {
- create: [ALL_TEAMS_ID],
- update: [ALL_TEAMS_ID],
- delete: [ALL_TEAMS_ID],
- view: [ALL_TEAMS_ID],
- },
- Documents: {
- create: [ALL_TEAMS_ID],
- update: [ALL_TEAMS_ID],
- delete: [ALL_TEAMS_ID],
- view: [ALL_TEAMS_ID],
- },
- // Messaging: {
- // create: [ALL_TEAMS_ID],
- // update: [ALL_TEAMS_ID],
- // delete: [ALL_TEAMS_ID],
- // view: [ALL_TEAMS_ID],
- // },
- // Timecards: {
- // create: [ALL_TEAMS_ID],
- // update: [ALL_TEAMS_ID],
- // delete: [ALL_TEAMS_ID],
- // view: [ALL_TEAMS_ID],
- // },
- Resources: {
- create: [ALL_TEAMS_ID],
- update: [ALL_TEAMS_ID],
- delete: [ALL_TEAMS_ID],
- view: [ALL_TEAMS_ID],
- },
- Users: {
- create: [ALL_TEAMS_ID],
- update: [ALL_TEAMS_ID],
- delete: [ALL_TEAMS_ID],
- view: [ALL_TEAMS_ID],
- },
- Settings: {
- create: [ALL_TEAMS_ID],
- update: [ALL_TEAMS_ID],
- delete: [ALL_TEAMS_ID],
- view: [ALL_TEAMS_ID],
- },
- },
-};
diff --git a/packages/database/src/seed/features.ts b/packages/database/src/seed/features.ts
deleted file mode 100644
index 0b4534f4ab..0000000000
--- a/packages/database/src/seed/features.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import { v4 as uuidv4 } from "uuid";
-
-const possibleFeatures = [
- "Accounting",
- "Documents",
- "Inventory",
- "Invoicing",
- // "Jobs",
- // "Messaging",
- "Parts",
- "Purchasing",
- "Resources",
- "Sales",
- // "Scheduling",
- "Settings",
- // "Timecards",
- "Users",
-] as const;
-
-export type Feature = (typeof possibleFeatures)[number];
-
-const features = {} as Record<Feature, { id: string; name: string }>;
-
-possibleFeatures.forEach((name) => {
- features[name] = {
- id: uuidv4(),
- name,
- };
-});
-
-export { features, possibleFeatures };
diff --git a/packages/database/src/seed/index.ts b/packages/database/src/seed/index.ts
index f219f6cff5..330b288a38 100644
--- a/packages/database/src/seed/index.ts
+++ b/packages/database/src/seed/index.ts
@@ -1,3 +1,2 @@
export * from "./admin";
-export * from "./employee-types";
-export * from "./features";
+export * from "./modules";
diff --git a/packages/database/src/seed/modules.ts b/packages/database/src/seed/modules.ts
new file mode 100644
index 0000000000..efd223849d
--- /dev/null
+++ b/packages/database/src/seed/modules.ts
@@ -0,0 +1,20 @@
+const modules = [
+ "Accounting",
+ "Documents",
+ "Inventory",
+ "Invoicing",
+ "Jobs",
+ "Messaging",
+ "Parts",
+ "Purchasing",
+ "Resources",
+ "Sales",
+ "Scheduling",
+ "Settings",
+ "Timecards",
+ "Users",
+] as const;
+
+export type Module = (typeof modules)[number];
+
+export { modules };
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 01289fb757..30a85c1416 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -3863,7 +3863,7 @@ export type Database = {
}
employeeType: {
Row: {
- companyId: number | null
+ companyId: number
createdAt: string
id: string
name: string
@@ -3871,7 +3871,7 @@ export type Database = {
updatedAt: string | null
}
Insert: {
- companyId?: number | null
+ companyId: number
createdAt?: string
id?: string
name: string
@@ -3879,7 +3879,7 @@ export type Database = {
updatedAt?: string | null
}
Update: {
- companyId?: number | null
+ companyId?: number
createdAt?: string
id?: string
name?: string
@@ -3902,7 +3902,7 @@ export type Database = {
createdAt: string
delete: number[]
employeeTypeId: string
- featureId: string
+ module: Database["public"]["Enums"]["module"]
update: number[]
updatedAt: string | null
view: number[]
@@ -3912,7 +3912,7 @@ export type Database = {
createdAt?: string
delete?: number[]
employeeTypeId: string
- featureId: string
+ module: Database["public"]["Enums"]["module"]
update?: number[]
updatedAt?: string | null
view?: number[]
@@ -3922,7 +3922,7 @@ export type Database = {
createdAt?: string
delete?: number[]
employeeTypeId?: string
- featureId?: string
+ module?: Database["public"]["Enums"]["module"]
update?: number[]
updatedAt?: string | null
view?: number[]
@@ -3935,13 +3935,6 @@ export type Database = {
referencedRelation: "employeeType"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "employeeTypePermission_featureId_fkey"
- columns: ["featureId"]
- isOneToOne: false
- referencedRelation: "feature"
- referencedColumns: ["id"]
- },
]
}
equipment: {
@@ -4223,27 +4216,6 @@ export type Database = {
},
]
}
- feature: {
- Row: {
- createdAt: string
- id: string
- name: string
- updatedAt: string | null
- }
- Insert: {
- createdAt?: string
- id?: string
- name: string
- updatedAt?: string | null
- }
- Update: {
- createdAt?: string
- id?: string
- name?: string
- updatedAt?: string | null
- }
- Relationships: []
- }
fiscalYearSettings: {
Row: {
companyId: number
@@ -16158,6 +16130,12 @@ export type Database = {
},
]
}
+ modules: {
+ Row: {
+ name: Database["public"]["Enums"]["module"] | null
+ }
+ Relationships: []
+ }
partners: {
Row: {
abilityId: string | null
@@ -18971,6 +18949,7 @@ export type Database = {
| "Purchasing"
| "Resources"
| "Sales"
+ | "Settings"
| "Scheduling"
| "Timecards"
| "Users"
diff --git a/packages/database/supabase/functions/lib/database.ts b/packages/database/supabase/functions/lib/database.ts
index c4bb066e4b..b326803f5c 100644
--- a/packages/database/supabase/functions/lib/database.ts
+++ b/packages/database/supabase/functions/lib/database.ts
@@ -5,13 +5,16 @@ import {
PostgresIntrospector,
PostgresQueryCompiler,
} from "https://esm.sh/[email protected]";
-import { Database } from "../lib/types.ts";
import { PostgresDriver } from "../lib/driver.ts";
+import { Database } from "../lib/types.ts";
type Tables = Database["public"]["Tables"];
+type Views = Database["public"]["Views"];
export type DB = {
[TableName in keyof Tables]: Tables[TableName]["Insert"];
+} & {
+ [ViewName in keyof Views]: Views[ViewName]["Row"];
};
export function getConnectionPool(connections: number) {
diff --git a/packages/database/supabase/functions/lib/seed.ts b/packages/database/supabase/functions/lib/seed.ts
index 2e16bb9207..a50743a12a 100644
--- a/packages/database/supabase/functions/lib/seed.ts
+++ b/packages/database/supabase/functions/lib/seed.ts
@@ -2196,6 +2196,31 @@ function getDefaultAccount(key: string) {
return accountDefaults[key];
}
+export const groupCompanyTemplate = "<%=12-digit-company-id=%>";
+export const groups = [
+ {
+ id: `00000000-0000-0000-0000-${groupCompanyTemplate}`,
+ name: "All Employees",
+ isCustomerTypeGroup: false,
+ isEmployeeTypeGroup: true,
+ isSupplierTypeGroup: false,
+ },
+ {
+ id: `11111111-1111-1111-1111-${groupCompanyTemplate}`,
+ name: "All Customers",
+ isCustomerTypeGroup: true,
+ isEmployeeTypeGroup: false,
+ isSupplierTypeGroup: false,
+ },
+ {
+ id: `22222222-2222-2222-2222-${groupCompanyTemplate}`,
+ name: "All Suppliers",
+ isCustomerTypeGroup: false,
+ isEmployeeTypeGroup: false,
+ isSupplierTypeGroup: true,
+ },
+];
+
export const integrations = [
{
id: "exchange-rates-v1",
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 01289fb757..30a85c1416 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -3863,7 +3863,7 @@ export type Database = {
}
employeeType: {
Row: {
- companyId: number | null
+ companyId: number
createdAt: string
id: string
name: string
@@ -3871,7 +3871,7 @@ export type Database = {
updatedAt: string | null
}
Insert: {
- companyId?: number | null
+ companyId: number
createdAt?: string
id?: string
name: string
@@ -3879,7 +3879,7 @@ export type Database = {
updatedAt?: string | null
}
Update: {
- companyId?: number | null
+ companyId?: number
createdAt?: string
id?: string
name?: string
@@ -3902,7 +3902,7 @@ export type Database = {
createdAt: string
delete: number[]
employeeTypeId: string
- featureId: string
+ module: Database["public"]["Enums"]["module"]
update: number[]
updatedAt: string | null
view: number[]
@@ -3912,7 +3912,7 @@ export type Database = {
createdAt?: string
delete?: number[]
employeeTypeId: string
- featureId: string
+ module: Database["public"]["Enums"]["module"]
update?: number[]
updatedAt?: string | null
view?: number[]
@@ -3922,7 +3922,7 @@ export type Database = {
createdAt?: string
delete?: number[]
employeeTypeId?: string
- featureId?: string
+ module?: Database["public"]["Enums"]["module"]
update?: number[]
updatedAt?: string | null
view?: number[]
@@ -3935,13 +3935,6 @@ export type Database = {
referencedRelation: "employeeType"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "employeeTypePermission_featureId_fkey"
- columns: ["featureId"]
- isOneToOne: false
- referencedRelation: "feature"
- referencedColumns: ["id"]
- },
]
}
equipment: {
@@ -4223,27 +4216,6 @@ export type Database = {
},
]
}
- feature: {
- Row: {
- createdAt: string
- id: string
- name: string
- updatedAt: string | null
- }
- Insert: {
- createdAt?: string
- id?: string
- name: string
- updatedAt?: string | null
- }
- Update: {
- createdAt?: string
- id?: string
- name?: string
- updatedAt?: string | null
- }
- Relationships: []
- }
fiscalYearSettings: {
Row: {
companyId: number
@@ -16158,6 +16130,12 @@ export type Database = {
},
]
}
+ modules: {
+ Row: {
+ name: Database["public"]["Enums"]["module"] | null
+ }
+ Relationships: []
+ }
partners: {
Row: {
abilityId: string | null
@@ -18971,6 +18949,7 @@ export type Database = {
| "Purchasing"
| "Resources"
| "Sales"
+ | "Settings"
| "Scheduling"
| "Timecards"
| "Users"
diff --git a/packages/database/supabase/functions/seed-company/index.ts b/packages/database/supabase/functions/seed-company/index.ts
index 154dfc3b67..9de3ea7903 100644
--- a/packages/database/supabase/functions/seed-company/index.ts
+++ b/packages/database/supabase/functions/seed-company/index.ts
@@ -10,6 +10,8 @@ import {
customFields,
customerStatuses,
fiscalYearSettings,
+ groupCompanyTemplate,
+ groups,
integrations,
paymentTerms,
postingGroupInventory,
@@ -19,6 +21,8 @@ import {
supplierStauses,
unitOfMeasures,
} from "../lib/seed.ts";
+import { getSupabaseServiceRole } from "../lib/supabase.ts";
+import { Database } from "../lib/types.ts";
const pool = getConnectionPool(1);
const db = getDatabaseClient<DB>(pool);
@@ -33,9 +37,72 @@ serve(async (req: Request) => {
if (!id) throw new Error("Payload is missing id");
if (!userId) throw new Error("Payload is missing userId");
const companyId = Number(id);
+ const supabaseClient = getSupabaseServiceRole(
+ req.headers.get("Authorization")
+ );
await db.transaction().execute(async (trx) => {
- // TODO: insert employee types and groups
+ await trx
+ .insertInto("userToCompany")
+ .values([{ userId, companyId }])
+ .execute();
+
+ // high-order groups
+ await trx
+ .insertInto("group")
+ .values(
+ groups.map((g) => ({
+ ...g,
+ id: g.id.replace(
+ groupCompanyTemplate,
+ companyId.toString().padStart(12, "0")
+ ),
+ companyId,
+ }))
+ )
+ .execute();
+
+ const employeeTypes = await trx
+ .insertInto("employeeType")
+ .values([
+ {
+ name: "Admin",
+ companyId,
+ protected: true,
+ },
+ ])
+ .returning(["id"])
+ .execute();
+
+ const employeeTypeId = employeeTypes[0].id;
+ if (!employeeTypeId)
+ throw new Error("Failed to insert admin employee type");
+
+ // get the modules
+ const modules = await trx.selectFrom("modules").select("name").execute();
+
+ // create employee type permissions for admin
+ const employeeTypePermissions = modules.reduce<
+ Database["public"]["Tables"]["employeeTypePermission"]["Insert"][]
+ >((acc, module) => {
+ if (module.name) {
+ acc.push({
+ employeeTypeId: employeeTypeId,
+ module: module.name,
+ create: [companyId],
+ update: [companyId],
+ delete: [companyId],
+ view: [companyId],
+ });
+ }
+ return acc;
+ }, []);
+
+ // insert employee type permissions
+ await trx
+ .insertInto("employeeTypePermission")
+ .values(employeeTypePermissions)
+ .execute();
// insert employee
await trx
@@ -43,6 +110,7 @@ serve(async (req: Request) => {
.values([
{
id: String(userId),
+ employeeTypeId,
companyId,
},
])
@@ -163,6 +231,43 @@ serve(async (req: Request) => {
.insertInto("customFieldTable")
.values(customFields.map((cf) => ({ ...cf, companyId })))
.execute();
+
+ const user = await supabaseClient.auth.admin.getUserById(userId);
+ if (user.error) throw new Error(user.error.message);
+
+ const currentClaims = user.data?.user.app_metadata ?? {};
+ const newClaims = { ...currentClaims };
+ modules.forEach(({ name }) => {
+ const module = name?.toLowerCase();
+ if (`${module}_view` in newClaims) {
+ newClaims[`${module}_view`].push(companyId);
+ } else {
+ newClaims[`${module}_view`] = [companyId];
+ }
+
+ if (`${module}_create` in newClaims) {
+ newClaims[`${module}_create`].push(companyId);
+ } else {
+ newClaims[`${module}_create`] = [companyId];
+ }
+
+ if (`${module}_update` in newClaims) {
+ newClaims[`${module}_update`].push(companyId);
+ } else {
+ newClaims[`${module}_update`] = [companyId];
+ }
+
+ if (`${module}_delete` in newClaims) {
+ newClaims[`${module}_delete`].push(companyId);
+ } else {
+ newClaims[`${module}_delete`] = [companyId];
+ }
+ });
+
+ const { error } = await supabaseClient.auth.admin.updateUserById(userId, {
+ app_metadata: newClaims,
+ });
+ if (error) throw new Error(error.message);
});
return new Response(
diff --git a/packages/database/supabase/migrations/20230123004339_employee-types.sql b/packages/database/supabase/migrations/20230123004339_employee-types.sql
index c9d8742887..240116fd86 100644
--- a/packages/database/supabase/migrations/20230123004339_employee-types.sql
+++ b/packages/database/supabase/migrations/20230123004339_employee-types.sql
@@ -4,7 +4,7 @@ CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
CREATE TABLE "employeeType" (
"id" TEXT NOT NULL DEFAULT uuid_generate_v4(),
"name" TEXT NOT NULL,
- "companyId" INTEGER,
+ "companyId" INTEGER NOT NULL,
"protected" BOOLEAN NOT NULL DEFAULT false,
"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
"updatedAt" TIMESTAMP WITH TIME ZONE,
diff --git a/packages/database/supabase/migrations/20230123004409_permissions.sql b/packages/database/supabase/migrations/20230123004409_permissions.sql
index 8754973d16..ef78be47ff 100644
--- a/packages/database/supabase/migrations/20230123004409_permissions.sql
+++ b/packages/database/supabase/migrations/20230123004409_permissions.sql
@@ -1,18 +1,28 @@
-CREATE TABLE "feature" (
- "id" TEXT NOT NULL DEFAULT uuid_generate_v4(),
- "name" TEXT NOT NULL,
- "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
- "updatedAt" TIMESTAMP WITH TIME ZONE,
- CONSTRAINT "feature_pkey" PRIMARY KEY ("id")
+
+CREATE TYPE module AS ENUM (
+ 'Accounting',
+ 'Documents',
+ 'Invoicing',
+ 'Inventory',
+ 'Jobs',
+ 'Messaging',
+ 'Parts',
+ 'Purchasing',
+ 'Resources',
+ 'Sales',
+ 'Settings',
+ 'Scheduling',
+ 'Timecards',
+ 'Users'
);
-ALTER TABLE "feature" ENABLE ROW LEVEL SECURITY;
+CREATE VIEW "modules" AS
+ SELECT unnest(enum_range(NULL::module)) AS name;
-CREATE POLICY "Only claims admin can view/modify modules" ON "feature" FOR ALL USING (is_claims_admin());
CREATE TABLE "employeeTypePermission" (
"employeeTypeId" TEXT NOT NULL,
- "featureId" TEXT NOT NULL,
+ "module" module NOT NULL,
"create" INTEGER[] NOT NULL DEFAULT '{}',
"delete" INTEGER[] NOT NULL DEFAULT '{}',
"update" INTEGER[] NOT NULL DEFAULT '{}',
@@ -20,9 +30,8 @@ CREATE TABLE "employeeTypePermission" (
"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
"updatedAt" TIMESTAMP WITH TIME ZONE,
- CONSTRAINT "employeeTypePermission_pkey" PRIMARY KEY ("employeeTypeId", "featureId"),
- CONSTRAINT "employeeTypePermission_employeeTypeId_fkey" FOREIGN KEY ("employeeTypeId") REFERENCES "employeeType"("id") ON DELETE CASCADE ON UPDATE CASCADE,
- CONSTRAINT "employeeTypePermission_featureId_fkey" FOREIGN KEY ("featureId") REFERENCES "feature"("id") ON DELETE CASCADE ON UPDATE CASCADE
+ CONSTRAINT "employeeTypePermission_pkey" PRIMARY KEY ("employeeTypeId", "module"),
+ CONSTRAINT "employeeTypePermission_employeeTypeId_fkey" FOREIGN KEY ("employeeTypeId") REFERENCES "employeeType"("id") ON DELETE CASCADE ON UPDATE CASCADE
);
ALTER TABLE "employeeTypePermission" ENABLE ROW LEVEL SECURITY;
diff --git a/packages/database/supabase/migrations/20230123004632_groups.sql b/packages/database/supabase/migrations/20230123004632_groups.sql
index 7328bfd0d9..5ef347a438 100644
--- a/packages/database/supabase/migrations/20230123004632_groups.sql
+++ b/packages/database/supabase/migrations/20230123004632_groups.sql
@@ -50,7 +50,7 @@ BEGIN
VALUES (new.id, new.name, TRUE, new."companyId");
INSERT INTO public."membership"("groupId", "memberGroupId")
- VALUES ('00000000-0000-0000-0000-000000000000', new.id);
+ VALUES ('00000000-0000-0000-0000-' || lpad(new."companyId"::text, 12, '0'), new.id);
RETURN new;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
@@ -306,7 +306,7 @@ BEGIN
VALUES (new.id, new.name, TRUE, new."companyId");
INSERT INTO public."membership"("groupId", "memberGroupId")
- VALUES ('11111111-1111-1111-1111-111111111111', new.id);
+ VALUES ('11111111-1111-1111-1111-' || lpad(new."companyId"::text, 12, '0'), new.id);
RETURN new;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
@@ -318,7 +318,7 @@ BEGIN
VALUES (new.id, new.name, TRUE, new."companyId");
INSERT INTO public."membership"("groupId", "memberGroupId")
- VALUES ('22222222-2222-2222-2222-222222222222', new.id);
+ VALUES ('22222222-2222-2222-2222-' || lpad(new."companyId"::text, 12, '0'), new.id);
RETURN new;
END;
diff --git a/packages/database/supabase/migrations/20240311021818_custom-fields.sql b/packages/database/supabase/migrations/20240311021818_custom-fields.sql
index bd356340a6..3da050be7f 100644
--- a/packages/database/supabase/migrations/20240311021818_custom-fields.sql
+++ b/packages/database/supabase/migrations/20240311021818_custom-fields.sql
@@ -1,20 +1,4 @@
-CREATE TYPE module AS ENUM (
- 'Accounting',
- 'Documents',
- 'Invoicing',
- 'Inventory',
- 'Jobs',
- 'Messaging',
- 'Parts',
- 'Purchasing',
- 'Resources',
- 'Sales',
- 'Scheduling',
- 'Timecards',
- 'Users'
-);
-
CREATE TABLE "customFieldTable" (
"id" TEXT NOT NULL DEFAULT xid(),
"module" module NOT NULL,