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.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
refactor: migrations for multi-tenant - batch 1
Brad Barbina09d0374282a
diff --git a/apps/carbon/app/modules/resources/resources.service.ts b/apps/carbon/app/modules/resources/resources.service.tsindex 3f222b8684..91d6e86c50 100644--- a/apps/carbon/app/modules/resources/resources.service.ts+++ b/apps/carbon/app/modules/resources/resources.service.ts@@ -1111,6 +1111,7 @@ export async function upsertLocation(client: SupabaseClient<Database>,location:| (Omit<z.infer<typeof locationValidator>, "id"> & {+ companyId: number;createdBy: string;customFields?: Json;})diff --git a/apps/carbon/app/modules/settings/settings.service.ts b/apps/carbon/app/modules/settings/settings.service.tsindex d8b861613d..ab5b198da8 100644--- a/apps/carbon/app/modules/settings/settings.service.ts+++ b/apps/carbon/app/modules/settings/settings.service.ts@@ -170,7 +170,7 @@ export async function insertCompany(client: SupabaseClient<Database>,company: z.infer<typeof companyValidator>) {- return client.from("company").insert(company);+ return client.from("company").insert(company).select("id").single();}export async function rollbackNextSequence(diff --git a/apps/carbon/app/modules/users/users.server.ts b/apps/carbon/app/modules/users/users.server.tsindex 586addd3ed..dd7fbe7edb 100644--- a/apps/carbon/app/modules/users/users.server.ts+++ b/apps/carbon/app/modules/users/users.server.ts@@ -23,6 +23,14 @@ import type { ListItem, Result } from "~/types";import { path } from "~/utils/path";import { error, success } from "~/utils/result";+export async function addUserToCompany(+ client: SupabaseClient<Database>,+ userId: string,+ companyId: number+) {+ return client.from("userToCompany").insert({ companyId, userId });+}+export async function createCustomerAccount(client: SupabaseClient<Database>,{diff --git a/apps/carbon/app/routes/onboarding+/company.tsx b/apps/carbon/app/routes/onboarding+/company.tsxindex 66033c46a0..99541452c6 100644--- a/apps/carbon/app/routes/onboarding+/company.tsx+++ b/apps/carbon/app/routes/onboarding+/company.tsx@@ -19,6 +19,7 @@ import { json, redirect, type ActionFunctionArgs } from "@remix-run/node";import { Link, useLoaderData } from "@remix-run/react";import { Hidden, Input, Submit } from "~/components/Form";import { useOnboarding } from "~/hooks";+import { getSupabaseServiceRole } from "~/lib/supabase";import {getLocationsList,insertEmployeeJob,@@ -30,6 +31,7 @@ import {onboardingCompanyValidator,updateCompany,} from "~/modules/settings";+import { addUserToCompany } from "~/modules/users/users.server";import { requirePermissions } from "~/services/auth/auth.server";import { assertIsPost } from "~/utils/http";@@ -54,6 +56,10 @@ export async function action({ request }: ActionFunctionArgs) {update: "settings",});+ // there are no entries in the userToCompany table which+ // dictates RLS for the company table+ const supabaseClient = getSupabaseServiceRole();+const validation = await validator(onboardingCompanyValidator).validate(await request.formData());@@ -73,8 +79,8 @@ export async function action({ request }: ActionFunctionArgs) {if (company.data && location) {const [companyUpdate, locationUpdate] = await Promise.all([- updateCompany(client, { ...data, updatedBy: userId }),- upsertLocation(client, {+ updateCompany(supabaseClient, { ...data, updatedBy: userId }),+ upsertLocation(supabaseClient, {...location,...data,timezone: getLocalTimeZone(),@@ -90,20 +96,25 @@ export async function action({ request }: ActionFunctionArgs) {throw new Error("Fatal: failed to update location");}} else {- const [companyInsert, locationInsert] = await Promise.all([- insertCompany(client, data),- upsertLocation(client, {- ...data,- name: "Headquarters",- timezone: getLocalTimeZone(),- createdBy: userId,- }),- ]);+ const companyInsert = await insertCompany(supabaseClient, data);if (companyInsert.error) {console.error(companyInsert.error);throw new Error("Fatal: failed to insert company");}+ const companyId = companyInsert.data?.id;+ if (!companyId) {+ throw new Error("Fatal: failed to get company ID");+ }++ const locationInsert = await upsertLocation(supabaseClient, {+ ...data,+ name: "Headquarters",+ companyId,+ timezone: getLocalTimeZone(),+ createdBy: userId,+ });+if (locationInsert.error) {console.error(locationInsert.error);throw new Error("Fatal: failed to insert location");@@ -114,10 +125,24 @@ export async function action({ request }: ActionFunctionArgs) {throw new Error("Fatal: failed to get location ID");}- await insertEmployeeJob(client, {- id: userId,- locationId,- });+ const [userToCompany, job] = await Promise.all([+ addUserToCompany(supabaseClient, userId, companyId),+ insertEmployeeJob(supabaseClient, {+ id: userId,+ locationId,+ }),+ // TODO: seed company+ ]);++ if (userToCompany.error) {+ console.error(userToCompany.error);+ throw new Error("Fatal: failed to add user to company");+ }++ if (job.error) {+ console.error(job.error);+ throw new Error("Fatal: failed to insert job");+ }}throw redirect(next);diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex f9e22ff5dc..73bca86690 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -2593,6 +2593,7 @@ export type Database = {};customerStatus: {Row: {+ companyId: number | null;createdAt: string;createdBy: string;customFields: Json | null;@@ -2602,6 +2603,7 @@ export type Database = {updatedBy: string | null;};Insert: {+ companyId?: number | null;createdAt?: string;createdBy: string;customFields?: Json | null;@@ -2611,6 +2613,7 @@ export type Database = {updatedBy?: string | null;};Update: {+ companyId?: number | null;createdAt?: string;createdBy?: string;customFields?: Json | null;@@ -2620,6 +2623,13 @@ export type Database = {updatedBy?: string | null;};Relationships: [+ {+ foreignKeyName: "customerStatus_companyId_fkey";+ columns: ["companyId"];+ isOneToOne: false;+ referencedRelation: "company";+ referencedColumns: ["id"];+ },{foreignKeyName: "customerStatus_createdBy_fkey";columns: ["createdBy"];@@ -2713,6 +2723,13 @@ export type Database = {updatedBy?: string | null;};Relationships: [+ {+ foreignKeyName: "customerType_companyId_fkey";+ columns: ["companyId"];+ isOneToOne: false;+ referencedRelation: "company";+ referencedColumns: ["id"];+ },{foreignKeyName: "customerType_createdBy_fkey";columns: ["createdBy"];@@ -3261,52 +3278,34 @@ export type Database = {};employee: {Row: {+ companyId: number | null;employeeTypeId: string;id: string;};Insert: {+ companyId?: number | null;employeeTypeId: string;id: string;};Update: {+ companyId?: number | null;employeeTypeId?: string;id?: string;};Relationships: [{- foreignKeyName: "employee_employeeTypeId_fkey";- columns: ["employeeTypeId"];+ foreignKeyName: "employee_companyId_fkey";+ columns: ["companyId"];isOneToOne: false;- referencedRelation: "employeeType";- referencedColumns: ["id"];- },- {- foreignKeyName: "employee_id_fkey";- columns: ["id"];- isOneToOne: true;- referencedRelation: "employees";- referencedColumns: ["id"];- },- {- foreignKeyName: "employee_id_fkey";- columns: ["id"];- isOneToOne: true;- referencedRelation: "employeeSummary";+ referencedRelation: "company";referencedColumns: ["id"];},{- foreignKeyName: "employee_id_fkey";- columns: ["id"];- isOneToOne: true;- referencedRelation: "user";+ foreignKeyName: "employee_employeeTypeId_fkey";+ columns: ["employeeTypeId"];+ isOneToOne: false;+ referencedRelation: "employeeType";referencedColumns: ["id"];- },- {- foreignKeyName: "employee_id_fkey";- columns: ["id"];- isOneToOne: true;- referencedRelation: "userDefaults";- referencedColumns: ["userId"];}];};@@ -4356,6 +4355,7 @@ export type Database = {addressLine1: string;addressLine2: string | null;city: string;+ companyId: number;countryCode: string | null;createdAt: string;createdBy: string;@@ -4374,6 +4374,7 @@ export type Database = {addressLine1: string;addressLine2?: string | null;city: string;+ companyId: number;countryCode?: string | null;createdAt?: string;createdBy: string;@@ -4392,6 +4393,7 @@ export type Database = {addressLine1?: string;addressLine2?: string | null;city?: string;+ companyId?: number;countryCode?: string | null;createdAt?: string;createdBy?: string;@@ -4406,7 +4408,15 @@ export type Database = {updatedAt?: string | null;updatedBy?: string | null;};- Relationships: [];+ Relationships: [+ {+ foreignKeyName: "location_companyId_fkey";+ columns: ["companyId"];+ isOneToOne: false;+ referencedRelation: "company";+ referencedColumns: ["id"];+ }+ ];};membership: {Row: {@@ -11690,6 +11700,7 @@ export type Database = {};search: {Row: {+ companyId: number | null;description: string | null;entity: Database["public"]["Enums"]["searchEntity"] | null;fts: unknown | null;@@ -11699,6 +11710,7 @@ export type Database = {uuid: string | null;};Insert: {+ companyId?: number | null;description?: string | null;entity?: Database["public"]["Enums"]["searchEntity"] | null;fts?: unknown | null;@@ -11708,6 +11720,7 @@ export type Database = {uuid?: string | null;};Update: {+ companyId?: number | null;description?: string | null;entity?: Database["public"]["Enums"]["searchEntity"] | null;fts?: unknown | null;@@ -11716,7 +11729,15 @@ export type Database = {name?: string;uuid?: string | null;};- Relationships: [];+ Relationships: [+ {+ foreignKeyName: "search_companyid_fkey";+ columns: ["companyId"];+ isOneToOne: false;+ referencedRelation: "company";+ referencedColumns: ["id"];+ }+ ];};sequence: {Row: {@@ -12242,6 +12263,7 @@ export type Database = {shift: {Row: {active: boolean;+ companyId: number;createdAt: string;createdBy: string;customFields: Json | null;@@ -12262,6 +12284,7 @@ export type Database = {};Insert: {active?: boolean;+ companyId: number;createdAt?: string;createdBy: string;customFields?: Json | null;@@ -12282,6 +12305,7 @@ export type Database = {};Update: {active?: boolean;+ companyId?: number;createdAt?: string;createdBy?: string;customFields?: Json | null;@@ -12301,6 +12325,13 @@ export type Database = {wednesday?: boolean;};Relationships: [+ {+ foreignKeyName: "shifts_companyId_fkey";+ columns: ["companyId"];+ isOneToOne: false;+ referencedRelation: "company";+ referencedColumns: ["id"];+ },{foreignKeyName: "shifts_createdBy_fkey";columns: ["createdBy"];@@ -13409,6 +13440,7 @@ export type Database = {};supplierStatus: {Row: {+ companyId: number | null;createdAt: string;createdBy: string;customFields: Json | null;@@ -13418,6 +13450,7 @@ export type Database = {updatedBy: string | null;};Insert: {+ companyId?: number | null;createdAt?: string;createdBy: string;customFields?: Json | null;@@ -13427,6 +13460,7 @@ export type Database = {updatedBy?: string | null;};Update: {+ companyId?: number | null;createdAt?: string;createdBy?: string;customFields?: Json | null;@@ -13436,6 +13470,13 @@ export type Database = {updatedBy?: string | null;};Relationships: [+ {+ foreignKeyName: "supplierStatus_companyId_fkey";+ columns: ["companyId"];+ isOneToOne: false;+ referencedRelation: "company";+ referencedColumns: ["id"];+ },{foreignKeyName: "supplierStatus_createdBy_fkey";columns: ["createdBy"];@@ -13898,6 +13939,7 @@ export type Database = {userAttributeCategory: {Row: {active: boolean | null;+ companyId: number | null;createdAt: string;createdBy: string;id: string;@@ -13909,6 +13951,7 @@ export type Database = {};Insert: {active?: boolean | null;+ companyId?: number | null;createdAt?: string;createdBy: string;id?: string;@@ -13920,6 +13963,7 @@ export type Database = {};Update: {active?: boolean | null;+ companyId?: number | null;createdAt?: string;createdBy?: string;id?: string;@@ -13930,6 +13974,13 @@ export type Database = {updatedBy?: string | null;};Relationships: [+ {+ foreignKeyName: "userAttributeCategory_companyId_fkey";+ columns: ["companyId"];+ isOneToOne: false;+ referencedRelation: "company";+ referencedColumns: ["id"];+ },{foreignKeyName: "userAttributeCategory_createdBy_fkey";columns: ["createdBy"];@@ -17394,6 +17445,7 @@ export type Database = {shifts: {Row: {active: boolean | null;+ companyId: number | null;createdAt: string | null;createdBy: string | null;customFields: Json | null;@@ -17414,6 +17466,13 @@ export type Database = {wednesday: boolean | null;};Relationships: [+ {+ foreignKeyName: "shifts_companyId_fkey";+ columns: ["companyId"];+ isOneToOne: false;+ referencedRelation: "company";+ referencedColumns: ["id"];+ },{foreignKeyName: "shifts_createdBy_fkey";columns: ["createdBy"];@@ -17735,6 +17794,12 @@ export type Database = {Args: Record<PropertyKey, never>;Returns: Json;};+ get_permission_companies: {+ Args: {+ claim: string;+ };+ Returns: unknown;+ };groups_for_user: {Args: {uid: string;diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex d6443b91bf..f369e95b87 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -2603,6 +2603,7 @@ export type Database = {}customerStatus: {Row: {+ companyId: number | nullcreatedAt: stringcreatedBy: stringcustomFields: Json | null@@ -2612,6 +2613,7 @@ export type Database = {updatedBy: string | null}Insert: {+ companyId?: number | nullcreatedAt?: stringcreatedBy: stringcustomFields?: Json | null@@ -2621,6 +2623,7 @@ export type Database = {updatedBy?: string | null}Update: {+ companyId?: number | nullcreatedAt?: stringcreatedBy?: stringcustomFields?: Json | null@@ -2630,6 +2633,13 @@ export type Database = {updatedBy?: string | null}Relationships: [+ {+ foreignKeyName: "customerStatus_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },{foreignKeyName: "customerStatus_createdBy_fkey"columns: ["createdBy"]@@ -2723,6 +2733,13 @@ export type Database = {updatedBy?: string | null}Relationships: [+ {+ foreignKeyName: "customerType_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },{foreignKeyName: "customerType_createdBy_fkey"columns: ["createdBy"]@@ -3271,53 +3288,35 @@ export type Database = {}employee: {Row: {+ companyId: number | nullemployeeTypeId: stringid: string}Insert: {+ companyId?: number | nullemployeeTypeId: stringid: string}Update: {+ companyId?: number | nullemployeeTypeId?: stringid?: string}Relationships: [{- foreignKeyName: "employee_employeeTypeId_fkey"- columns: ["employeeTypeId"]+ foreignKeyName: "employee_companyId_fkey"+ columns: ["companyId"]isOneToOne: false- referencedRelation: "employeeType"- referencedColumns: ["id"]- },- {- foreignKeyName: "employee_id_fkey"- columns: ["id"]- isOneToOne: true- referencedRelation: "employees"- referencedColumns: ["id"]- },- {- foreignKeyName: "employee_id_fkey"- columns: ["id"]- isOneToOne: true- referencedRelation: "employeeSummary"+ referencedRelation: "company"referencedColumns: ["id"]},{- foreignKeyName: "employee_id_fkey"- columns: ["id"]- isOneToOne: true- referencedRelation: "user"+ foreignKeyName: "employee_employeeTypeId_fkey"+ columns: ["employeeTypeId"]+ isOneToOne: false+ referencedRelation: "employeeType"referencedColumns: ["id"]},- {- foreignKeyName: "employee_id_fkey"- columns: ["id"]- isOneToOne: true- referencedRelation: "userDefaults"- referencedColumns: ["userId"]- },]}employeeAbility: {@@ -4366,6 +4365,7 @@ export type Database = {addressLine1: stringaddressLine2: string | nullcity: string+ companyId: numbercountryCode: string | nullcreatedAt: stringcreatedBy: string@@ -4384,6 +4384,7 @@ export type Database = {addressLine1: stringaddressLine2?: string | nullcity: string+ companyId: numbercountryCode?: string | nullcreatedAt?: stringcreatedBy: string@@ -4402,6 +4403,7 @@ export type Database = {addressLine1?: stringaddressLine2?: string | nullcity?: string+ companyId?: numbercountryCode?: string | nullcreatedAt?: stringcreatedBy?: string@@ -4416,7 +4418,15 @@ export type Database = {updatedAt?: string | nullupdatedBy?: string | null}- Relationships: []+ Relationships: [+ {+ foreignKeyName: "location_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ ]}membership: {Row: {@@ -11700,6 +11710,7 @@ export type Database = {}search: {Row: {+ companyId: number | nulldescription: string | nullentity: Database["public"]["Enums"]["searchEntity"] | nullfts: unknown | null@@ -11709,6 +11720,7 @@ export type Database = {uuid: string | null}Insert: {+ companyId?: number | nulldescription?: string | nullentity?: Database["public"]["Enums"]["searchEntity"] | nullfts?: unknown | null@@ -11718,6 +11730,7 @@ export type Database = {uuid?: string | null}Update: {+ companyId?: number | nulldescription?: string | nullentity?: Database["public"]["Enums"]["searchEntity"] | nullfts?: unknown | null@@ -11726,7 +11739,15 @@ export type Database = {name?: stringuuid?: string | null}- Relationships: []+ Relationships: [+ {+ foreignKeyName: "search_companyid_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ ]}sequence: {Row: {@@ -12252,6 +12273,7 @@ export type Database = {shift: {Row: {active: boolean+ companyId: numbercreatedAt: stringcreatedBy: stringcustomFields: Json | null@@ -12272,6 +12294,7 @@ export type Database = {}Insert: {active?: boolean+ companyId: numbercreatedAt?: stringcreatedBy: stringcustomFields?: Json | null@@ -12292,6 +12315,7 @@ export type Database = {}Update: {active?: boolean+ companyId?: numbercreatedAt?: stringcreatedBy?: stringcustomFields?: Json | null@@ -12311,6 +12335,13 @@ export type Database = {wednesday?: boolean}Relationships: [+ {+ foreignKeyName: "shifts_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },{foreignKeyName: "shifts_createdBy_fkey"columns: ["createdBy"]@@ -13429,6 +13460,7 @@ export type Database = {}supplierStatus: {Row: {+ companyId: number | nullcreatedAt: stringcreatedBy: stringcustomFields: Json | null@@ -13438,6 +13470,7 @@ export type Database = {updatedBy: string | null}Insert: {+ companyId?: number | nullcreatedAt?: stringcreatedBy: stringcustomFields?: Json | null@@ -13447,6 +13480,7 @@ export type Database = {updatedBy?: string | null}Update: {+ companyId?: number | nullcreatedAt?: stringcreatedBy?: stringcustomFields?: Json | null@@ -13456,6 +13490,13 @@ export type Database = {updatedBy?: string | null}Relationships: [+ {+ foreignKeyName: "supplierStatus_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },{foreignKeyName: "supplierStatus_createdBy_fkey"columns: ["createdBy"]@@ -13918,6 +13959,7 @@ export type Database = {userAttributeCategory: {Row: {active: boolean | null+ companyId: number | nullcreatedAt: stringcreatedBy: stringid: string@@ -13929,6 +13971,7 @@ export type Database = {}Insert: {active?: boolean | null+ companyId?: number | nullcreatedAt?: stringcreatedBy: stringid?: string@@ -13940,6 +13983,7 @@ export type Database = {}Update: {active?: boolean | null+ companyId?: number | nullcreatedAt?: stringcreatedBy?: stringid?: string@@ -13950,6 +13994,13 @@ export type Database = {updatedBy?: string | null}Relationships: [+ {+ foreignKeyName: "userAttributeCategory_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },{foreignKeyName: "userAttributeCategory_createdBy_fkey"columns: ["createdBy"]@@ -17415,6 +17466,7 @@ export type Database = {shifts: {Row: {active: boolean | null+ companyId: number | nullcreatedAt: string | nullcreatedBy: string | nullcustomFields: Json | null@@ -17435,6 +17487,13 @@ export type Database = {wednesday: boolean | null}Relationships: [+ {+ foreignKeyName: "shifts_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },{foreignKeyName: "shifts_createdBy_fkey"columns: ["createdBy"]@@ -17756,6 +17815,12 @@ export type Database = {Args: Record<PropertyKey, never>Returns: Json}+ get_permission_companies: {+ Args: {+ claim: string+ }+ Returns: unknown+ }groups_for_user: {Args: {uid: stringdiff --git a/packages/database/supabase/migrations/20230123004206_claims.sql b/packages/database/supabase/migrations/20230123004206_claims.sqlindex cdef06b128..90b3aa866b 100644--- a/packages/database/supabase/migrations/20230123004206_claims.sql+++ b/packages/database/supabase/migrations/20230123004206_claims.sql@@ -53,6 +53,17 @@ CREATE OR REPLACE FUNCTION get_my_claim(claim text) RETURNS "jsonb"END;$$;+CREATE OR REPLACE FUNCTION get_permission_companies(claim text) RETURNS integer[]+ LANGUAGE "plpgsql" SECURITY DEFINER SET search_path = public+ AS $$+ DECLARE retval integer[];+ BEGIN+ select coalesce(raw_app_meta_data->claim, null) from auth.users into retval where id = auth.uid();+ return retval;++ END;+$$;+CREATE OR REPLACE FUNCTION has_company_permission(claim text, company integer) RETURNS "bool"LANGUAGE "plpgsql" SECURITY DEFINER SET search_path = publicAS $$diff --git a/packages/database/supabase/migrations/20230123004339_employee-types.sql b/packages/database/supabase/migrations/20230123004339_employee-types.sqlindex 2f913babc6..76d2928faa 100644--- a/packages/database/supabase/migrations/20230123004339_employee-types.sql+++ b/packages/database/supabase/migrations/20230123004339_employee-types.sql@@ -15,5 +15,9 @@ CREATE TABLE "employeeType" (ALTER TABLE "employeeType" ENABLE ROW LEVEL SECURITY;-CREATE POLICY "Only claims admin can view/modify permissions for employee types" ON "employeeType" FOR ALL USING (is_claims_admin());+CREATE POLICY "Only claims admin can view/modify permissions for employee types" ON "employeeType" FOR ALL USING (+ has_company_permission('update_users', "companyId")+);++diff --git a/packages/database/supabase/migrations/20230123004409_permissions.sql b/packages/database/supabase/migrations/20230123004409_permissions.sqlindex cee8d88022..8754973d16 100644--- a/packages/database/supabase/migrations/20230123004409_permissions.sql+++ b/packages/database/supabase/migrations/20230123004409_permissions.sql@@ -3,7 +3,6 @@ CREATE TABLE "feature" ("name" TEXT NOT NULL,"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),"updatedAt" TIMESTAMP WITH TIME ZONE,-CONSTRAINT "feature_pkey" PRIMARY KEY ("id"));diff --git a/packages/database/supabase/migrations/20230123004436_employee.sql b/packages/database/supabase/migrations/20230123004436_employee.sqlindex ea355e7160..b41838c862 100644--- a/packages/database/supabase/migrations/20230123004436_employee.sql+++ b/packages/database/supabase/migrations/20230123004436_employee.sql@@ -1,14 +1,14 @@CREATE TABLE "employee" ("id" TEXT NOT NULL,+ "companyId" INTEGER,"employeeTypeId" TEXT NOT NULL,-CONSTRAINT "employee_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "employee_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,CONSTRAINT "employee_employeeTypeId_fkey" FOREIGN KEY ("employeeTypeId") REFERENCES "employeeType"("id") ON DELETE RESTRICT ON UPDATE CASCADE,- CONSTRAINT "employee_id_fkey" FOREIGN KEY ("id") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE+ CONSTRAINT "employee_employeeCompany_unique" UNIQUE ("id", "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');-diff --git a/packages/database/supabase/migrations/20230123004514_buckets.sql b/packages/database/supabase/migrations/20230123004514_buckets.sqlindex ed5ae5ac4b..e45df5f21d 100644--- a/packages/database/supabase/migrations/20230123004514_buckets.sql+++ b/packages/database/supabase/migrations/20230123004514_buckets.sql@@ -14,21 +14,21 @@ CREATE POLICY "Employees with settings_create can insert into the public bucket"ON storage.objects FOR INSERT WITH CHECK (bucket_id = 'public'AND (auth.role() = 'authenticated')- AND coalesce(get_my_claim('settings_create')::boolean,false)+ -- AND has_company_permission('settings_create', (storage.foldername(name))[1]));CREATE POLICY "Employees with settings_update can update the public bucket"ON storage.objects FOR UPDATE USING (bucket_id = 'public'AND (auth.role() = 'authenticated')- AND coalesce(get_my_claim('settings_update')::boolean,false)+ -- AND has_company_permission('settings_update', (storage.foldername(name))[1]));CREATE POLICY "Employees with settings_delete can delete from public bucket"ON storage.objects FOR DELETE USING (bucket_id = 'public'AND (auth.role() = 'authenticated')- AND coalesce(get_my_claim('settings_delete')::boolean,false)+ -- AND has_company_permission('settings_delete', (storage.foldername(name))[1]));CREATE POLICY "Anyone can view avatars"diff --git a/packages/database/supabase/migrations/20230123004536_attributes.sql b/packages/database/supabase/migrations/20230123004536_attributes.sqlindex b1b17d9149..f1e9536260 100644--- a/packages/database/supabase/migrations/20230123004536_attributes.sql+++ b/packages/database/supabase/migrations/20230123004536_attributes.sql@@ -4,6 +4,7 @@ CREATE TABLE "userAttributeCategory" ("name" TEXT NOT NULL,"public" BOOLEAN DEFAULT FALSE,"protected" BOOLEAN DEFAULT FALSE,+ "companyId" INTEGER,"active" BOOLEAN DEFAULT TRUE,"createdAt" TIMESTAMP WITH TIME ZONE DEFAULT NOW() NOT NULL,"createdBy" TEXT NOT NULL,@@ -11,10 +12,13 @@ CREATE TABLE "userAttributeCategory" ("updatedBy" TEXT,CONSTRAINT "userAttributeCategory_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "userAttributeCategory_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,CONSTRAINT "userAttributeCategory_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON UPDATE CASCADE,CONSTRAINT "userAttributeCategory_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON UPDATE CASCADE);+CREATE INDEX "userAttributeCategory_companyId_index" ON "userAttributeCategory" ("companyId");+-- ALTER TABLE "userAttributeCategory" ENABLE ROW LEVEL SECURITY;CREATE TABLE "attributeDataType" (@@ -104,6 +108,8 @@ CREATE TABLE "userAttribute" ();+CREATE INDEX "userAttribute_userAttributeCategoryId_index" ON "userAttribute" ("userAttributeCategoryId");+-- ALTER TABLE "userAttribute" ENABLE ROW LEVEL SECURITY;CREATE TABLE "userAttributeValue" (@@ -172,16 +178,33 @@ CREATE INDEX "userAttributeValue_userAttributeId_index" ON "userAttributeValue"CREATE INDEX "userAttributeValue_userId_index" ON "userAttributeValue" ("userId");ALTER TABLE "userAttributeValue" ENABLE ROW LEVEL SECURITY;-CREATE POLICY "Claims admin can view/modify user attribute values" ON "userAttributeValue" FOR ALL USING (is_claims_admin());+CREATE POLICY "Users with resource update can view/modify user attribute values" ON "userAttributeValue" FOR ALL USING (+ "userAttributeId" IN (+ SELECT "id" FROM "userAttribute" WHERE "userAttributeCategoryId" IN (+ SELECT "id" FROM "userAttributeCategory" WHERE+ "companyId" = ANY(+ coalesce(+ get_permission_companies('resource_update')::integer[],+ array[]::integer[]+ )+ )+ )+ )+);CREATE POLICY "Users can insert attributes for themselves" ON "userAttributeValue" FOR UPDATE WITH CHECK (auth.uid() = "userId"::uuid);CREATE POLICY "Users can modify attributes for themselves" ON "userAttributeValue" FOR UPDATE WITH CHECK (auth.uid() = "userId"::uuid);-CREATE POLICY "Users can view their own attribtues" ON "userAttributeValue" FOR SELECT USING (auth.uid() = "userId"::uuid);+CREATE POLICY "Users can view their own attributes" ON "userAttributeValue" FOR SELECT USING (auth.uid() = "userId"::uuid);CREATE POLICY "Users can view other users attributes if the category is public" ON "userAttributeValue" FOR SELECTUSING (auth.role() = 'authenticated' AND"userAttributeValue"."userAttributeId" IN (SELECT "id" FROM "userAttribute" WHERE "userAttributeCategoryId" IN (- SELECT "id" FROM "userAttributeCategory" WHERE "public" = true+ SELECT "id" FROM "userAttributeCategory" WHERE "public" = true AND "companyId" = ANY(+ coalesce(+ get_permission_companies('resource_view')::integer[],+ array[]::integer[]+ )+ ))));diff --git a/packages/database/supabase/migrations/20230123004612_suppliers-and-customers.sql b/packages/database/supabase/migrations/20230123004612_suppliers-and-customers.sqlindex 4225cf7bef..6c1761aba0 100644--- a/packages/database/supabase/migrations/20230123004612_suppliers-and-customers.sql+++ b/packages/database/supabase/migrations/20230123004612_suppliers-and-customers.sql@@ -47,6 +47,7 @@ CREATE TABLE "address" (CREATE TABLE "supplierStatus" ("id" TEXT NOT NULL DEFAULT xid(),"name" TEXT NOT NULL,+ "companyId" INTEGER,"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),"createdBy" TEXT NOT NULL,"updatedBy" TEXT,@@ -54,11 +55,14 @@ CREATE TABLE "supplierStatus" ("customFields" JSONB,CONSTRAINT "supplierStatus_pkey" PRIMARY KEY ("id"),- CONSTRAINT "supplierStatus_name_unique" UNIQUE ("name"),+ CONSTRAINT "supplierStatus_name_unique" UNIQUE ("name", "companyId"),+ CONSTRAINT "supplierStatus_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON UPDATE CASCADE ON DELETE CASCADE,CONSTRAINT "supplierStatus_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON UPDATE CASCADE ON DELETE RESTRICT,CONSTRAINT "supplierStatus_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON UPDATE CASCADE ON DELETE SET NULL);+CREATE INDEX "supplierStatus_companyId_fkey" ON "supplierStatus"("companyId");+CREATE TABLE "supplierType" ("id" TEXT NOT NULL DEFAULT uuid_generate_v4(),"name" TEXT NOT NULL,@@ -72,11 +76,13 @@ CREATE TABLE "supplierType" (CONSTRAINT "supplierType_pkey" PRIMARY KEY ("id"),CONSTRAINT "supplierType_name_unique" UNIQUE ("name", "companyId"),- CONSTRAINT "supplierType_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON UPDATE CASCADE ON DELETE SET NULL,+ CONSTRAINT "supplierType_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON UPDATE CASCADE ON DELETE CASCADE,CONSTRAINT "supplierType_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON UPDATE CASCADE ON DELETE RESTRICT,CONSTRAINT "supplierType_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON UPDATE CASCADE ON DELETE SET NULL);+CREATE INDEX "supplierType_companyId_fkey" ON "supplierType"("companyId");+CREATE TABLE "supplier" ("id" TEXT NOT NULL DEFAULT uuid_generate_v4(),"name" TEXT NOT NULL,@@ -96,12 +102,14 @@ CREATE TABLE "supplier" (CONSTRAINT "supplier_supplierTypeId_fkey" FOREIGN KEY ("supplierTypeId") REFERENCES "supplierType"("id") ON UPDATE CASCADE ON DELETE SET NULL,CONSTRAINT "supplier_supplierStatusId_fkey" FOREIGN KEY ("supplierStatusId") REFERENCES "supplierStatus"("id") ON UPDATE CASCADE ON DELETE SET NULL,CONSTRAINT "supplier_accountManagerId_fkey" FOREIGN KEY ("accountManagerId") REFERENCES "user"("id") ON UPDATE CASCADE ON DELETE SET NULL,- CONSTRAINT "supplier_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON UPDATE CASCADE ON DELETE SET NULL,+ CONSTRAINT "supplier_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON UPDATE CASCADE ON DELETE CASCADE,CONSTRAINT "supplier_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON UPDATE CASCADE,CONSTRAINT "supplier_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON UPDATE CASCADE,- CONSTRAINT "supplier_name_unique" UNIQUE ("name")+ CONSTRAINT "supplier_name_unique" UNIQUE ("name", "companyId"));+CREATE INDEX "supplier_companyId_fkey" ON "supplier"("companyId");+ALTER publication supabase_realtime ADD TABLE "supplier";CREATE TABLE "supplierLocation" (@@ -146,6 +154,7 @@ CREATE INDEX "supplierAccount_supplierId_index" ON "supplierAccount"("supplierIdCREATE TABLE "customerStatus" ("id" TEXT NOT NULL DEFAULT xid(),"name" TEXT NOT NULL,+ "companyId" INTEGER,"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),"createdBy" TEXT NOT NULL,"updatedBy" TEXT,@@ -153,11 +162,14 @@ CREATE TABLE "customerStatus" ("customFields" JSONB,CONSTRAINT "customerStatus_pkey" PRIMARY KEY ("id"),- CONSTRAINT "customerStatus_name_unique" UNIQUE ("name"),+ CONSTRAINT "customerStatus_name_unique" UNIQUE ("name", "companyId"),+ CONSTRAINT "customerStatus_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON UPDATE CASCADE ON DELETE CASCADE,CONSTRAINT "customerStatus_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON UPDATE CASCADE ON DELETE RESTRICT,CONSTRAINT "customerStatus_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON UPDATE CASCADE ON DELETE SET NULL);+CREATE INDEX "customerStatus_companyId_fkey" ON "customerStatus"("companyId");+CREATE TABLE "customerType" ("id" TEXT NOT NULL DEFAULT uuid_generate_v4(),"name" TEXT NOT NULL,@@ -171,10 +183,13 @@ CREATE TABLE "customerType" (CONSTRAINT "customerType_pkey" PRIMARY KEY ("id"),CONSTRAINT "customerType_name_unique" UNIQUE ("name", "companyId"),+ CONSTRAINT "customerType_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON UPDATE CASCADE ON DELETE CASCADE,CONSTRAINT "customerType_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON UPDATE CASCADE ON DELETE RESTRICT,CONSTRAINT "customerType_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON UPDATE CASCADE ON DELETE SET NULL);+CREATE INDEX "customerType_companyId_fkey" ON "customerType"("companyId");+CREATE TABLE "customer" ("id" TEXT NOT NULL DEFAULT uuid_generate_v4(),"name" TEXT NOT NULL,@@ -194,12 +209,14 @@ CREATE TABLE "customer" (CONSTRAINT "customer_customerTypeId_fkey" FOREIGN KEY ("customerTypeId") REFERENCES "customerType"("id") ON UPDATE CASCADE ON DELETE SET NULL,CONSTRAINT "customer_customerStatusId_fkey" FOREIGN KEY ("customerStatusId") REFERENCES "customerStatus"("id") ON UPDATE CASCADE ON DELETE SET NULL,CONSTRAINT "customer_accountManagerId_fkey" FOREIGN KEY ("accountManagerId") REFERENCES "user"("id") ON UPDATE CASCADE ON DELETE SET NULL,- CONSTRAINT "customer_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON UPDATE CASCADE ON DELETE SET NULL,+ CONSTRAINT "customer_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON UPDATE CASCADE ON DELETE CASCADE,CONSTRAINT "customer_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON UPDATE CASCADE ON DELETE SET NULL,CONSTRAINT "customer_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON UPDATE CASCADE ON DELETE SET NULL,- CONSTRAINT "customer_name_unique" UNIQUE ("name")+ CONSTRAINT "customer_name_unique" UNIQUE ("name", "companyId"));+CREATE INDEX "customer_companyId_fkey" ON "customer"("companyId");+ALTER publication supabase_realtime ADD TABLE "customer";CREATE TABLE "customerLocation" (diff --git a/packages/database/supabase/migrations/20230123004632_groups.sql b/packages/database/supabase/migrations/20230123004632_groups.sqlindex 2261713fc8..42bc565747 100644--- a/packages/database/supabase/migrations/20230123004632_groups.sql+++ b/packages/database/supabase/migrations/20230123004632_groups.sql@@ -15,6 +15,8 @@ CREATE TABLE "group" (CONSTRAINT "group_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE);+CREATE INDEX "group_companyId_idx" ON "group" ("companyId");+CREATE TABLE "membership" ("id" SERIAL NOT NULL,"groupId" TEXT NOT NULL,@@ -355,7 +357,7 @@ CREATE FUNCTION public.add_customer_account_to_customer_group()RETURNS TRIGGER AS $$BEGININSERT INTO public."membership" ("groupId", "memberUserId")- VALUES (new."companyId", new.id);+ VALUES (new."customerId", new.id);RETURN new;END;$$ LANGUAGE plpgsql SECURITY DEFINER;diff --git a/packages/database/supabase/migrations/20230123212853_search.sql b/packages/database/supabase/migrations/20230123212853_search.sqlindex 29c31eefab..3f6cfea7fb 100644--- a/packages/database/supabase/migrations/20230123212853_search.sql+++ b/packages/database/supabase/migrations/20230123212853_search.sql@@ -7,7 +7,11 @@ CREATE TABLE search (description TEXT DEFAULT '',entity "searchEntity",uuid TEXT,- link TEXT NOT NULL+ link TEXT NOT NULL,+ "companyId" INTEGER,++ CONSTRAINT search_uuid_unique UNIQUE (uuid),+ CONSTRAINT search_companyId_fkey FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE);ALTER TABLE@@ -17,6 +21,7 @@ ADD COLUMNCREATE INDEX index_search_uuid ON public.search (uuid);CREATE INDEX index_search_fts ON public.search USING GIN (fts);+CREATE INDEX index_search_companyId ON public.search ("companyId");CREATE FUNCTION public.create_employee_search_result()RETURNS TRIGGER AS $$@@ -24,14 +29,14 @@ DECLAREemployee TEXT;BEGINemployee := (SELECT u."fullName" FROM public.user u WHERE u.id = new.id);- INSERT INTO public.search(name, entity, uuid, link)- VALUES (employee, 'Person', new.id, '/x/person/' || new.id);+ INSERT INTO public.search(name, entity, uuid, link, "companyId")+ VALUES (employee, 'Person', new.id, '/x/person/' || new.id, new."companyId");RETURN new;END;$$ LANGUAGE plpgsql SECURITY DEFINER;CREATE TRIGGER create_employee_search_result- AFTER INSERT on public.user+ AFTER INSERT on public.employeeFOR EACH ROW EXECUTE PROCEDURE public.create_employee_search_result();CREATE FUNCTION public.update_employee_search_result()@@ -57,8 +62,8 @@ CREATE TRIGGER update_employee_search_resultCREATE FUNCTION public.create_customer_search_result()RETURNS TRIGGER AS $$BEGIN- INSERT INTO public.search(name, entity, uuid, link)- VALUES (new.name, 'Customer', new.id, '/x/customer/' || new.id);+ INSERT INTO public.search(name, entity, uuid, link, "companyId")+ VALUES (new.name, 'Customer', new.id, '/x/customer/' || new.id, new."companyId");RETURN new;END;$$ LANGUAGE plpgsql SECURITY DEFINER;@@ -85,8 +90,8 @@ CREATE TRIGGER update_customer_search_resultCREATE FUNCTION public.create_supplier_search_result()RETURNS TRIGGER AS $$BEGIN- INSERT INTO public.search(name, entity, uuid, link)- VALUES (new.name, 'Supplier', new.id, '/x/supplier/' || new.id);+ INSERT INTO public.search(name, entity, uuid, link, "companyId")+ VALUES (new.name, 'Supplier', new.id, '/x/supplier/' || new.id, new."companyId");RETURN new;END;$$ LANGUAGE plpgsql SECURITY DEFINER;@@ -114,13 +119,13 @@ ALTER TABLE "search" ENABLE ROW LEVEL SECURITY;CREATE POLICY "Employees with sales_view can search for customers and sales orders" ON "search"FOR SELECT- USING (coalesce(get_my_claim('sales_view')::boolean, false) = true AND entity IN ('Customer', 'Sales Order') AND (get_my_claim('role'::text)) = '"employee"'::jsonb);+ USING (has_company_permission('sales_view', "companyId") AND entity IN ('Customer', 'Sales Order') AND (get_my_claim('role'::text)) = '"employee"'::jsonb);-- TODO: customers should be able to search for their own sales orders-- CREATE POLICY "Customers with sales_view can search for their own sales orders" ON "search"-- FOR SELECT-- USING (--- coalesce(get_my_claim('sales_view')::boolean, false) = true+-- has_company_permission('sales_view', "companyId")-- AND entity = 'Sales Order'-- AND (get_my_claim('role'::text)) = '"customer"'::jsonb-- AND uuid IN (@@ -134,30 +139,30 @@ CREATE POLICY "Employees with sales_view can search for customers and sales ordeCREATE POLICY "Employees with purchasing_view can search for suppliers and purchase orders" ON "search"FOR SELECT- USING (coalesce(get_my_claim('purchasing_view')::boolean, false) = true AND entity IN ('Supplier', 'Purchase Order') AND (get_my_claim('role'::text)) = '"employee"'::jsonb);+ USING (has_company_permission('purchasing_view', "companyId") AND entity IN ('Supplier', 'Purchase Order') AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_view can search for resources" ON "search"FOR SELECT- USING (coalesce(get_my_claim('resources_view')::boolean, false) = true AND entity = 'Resource');+ USING (has_company_permission('resources_view', "companyId") AND entity = 'Resource');CREATE POLICY "Employees with resources_view can search for people" ON "search"FOR SELECT- USING (coalesce(get_my_claim('resources_view')::boolean, false) = true AND entity = 'Person');+ USING (has_company_permission('resources_view', "companyId") AND entity = 'Person');-- TODO: documents should be filtered based on visibilityCREATE POLICY "Employees with document_view can search for documents" ON "search"FOR SELECT- USING (coalesce(get_my_claim('document_view')::boolean, false) = true AND entity = 'Document' AND (get_my_claim('role'::text)) = '"employee"'::jsonb);+ USING (has_company_permission('document_view', "companyId") AND entity = 'Document' AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with parts can search for parts" ON "search"FOR SELECT- USING (coalesce(get_my_claim('parts_view')::boolean, false) = true AND entity = 'Part' AND (get_my_claim('role'::text)) = '"employee"'::jsonb);+ USING (has_company_permission('parts_view', "companyId") AND entity = 'Part' AND (get_my_claim('role'::text)) = '"employee"'::jsonb);-- TODO: suppliers should be able to search for parts that they supplyCREATE POLICY "Employees with jobs_view can search for jobs" ON "search"FOR SELECT- USING (coalesce(get_my_claim('jobs_view')::boolean, false) = true AND entity = 'Job' AND (get_my_claim('role'::text)) = '"employee"'::jsonb);+ USING (has_company_permission('jobs_view', "companyId") AND entity = 'Job' AND (get_my_claim('role'::text)) = '"employee"'::jsonb);-- TODO: customers should be able to search for their jobs\ No newline at end of filediff --git a/packages/database/supabase/migrations/20230224035103_shifts.sql b/packages/database/supabase/migrations/20230224035103_shifts.sqlindex b1eb73df84..8bbfbe1abd 100644--- a/packages/database/supabase/migrations/20230224035103_shifts.sql+++ b/packages/database/supabase/migrations/20230224035103_shifts.sql@@ -18,38 +18,41 @@ CREATE TABLE "location" ("customFields" JSONB,CONSTRAINT "location_pkey" PRIMARY KEY ("id"),- CONSTRAINT "location_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "location_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE);CREATE INDEX "location_name_idx" ON "location" ("name");ALTER TABLE "location" ENABLE ROW LEVEL SECURITY;-CREATE POLICY "Employees can view locations" ON "location"+CREATE POLICY "Employees can view locations for their companies" ON "location"FOR SELECTUSING (auth.role() = 'authenticated'- AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ AND "companyId" = ANY(+ select "companyId" from "userToCompany" where "userId" = auth.uid()::text+ ));CREATE POLICY "Employees with resources_create can insert locations" ON "location"FOR INSERTWITH CHECK (- coalesce(get_my_claim('resources_create')::boolean,false)+ has_company_permission('resources_create', "companyId")AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_update can update locations" ON "location"FOR UPDATEUSING (- coalesce(get_my_claim('resources_update')::boolean, false) = true+ has_company_permission('resources_update', "companyId")AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_delete can delete locations" ON "location"FOR DELETEUSING (- coalesce(get_my_claim('resources_delete')::boolean, false) = true+ has_company_permission('resources_delete', "companyId")AND (get_my_claim('role'::text)) = '"employee"'::jsonb);@@ -68,6 +71,7 @@ CREATE TABLE "shift" ("friday" BOOLEAN NOT NULL DEFAULT false,"saturday" BOOLEAN NOT NULL DEFAULT false,"active" BOOLEAN NOT NULL DEFAULT true,+ "companyId" INTEGER NOT NULL,"createdBy" TEXT NOT NULL,"createdAt" TIMESTAMP NOT NULL DEFAULT now(),"updatedBy" TEXT,@@ -76,6 +80,7 @@ CREATE TABLE "shift" (CONSTRAINT "shifts_pkey" PRIMARY KEY ("id"),CONSTRAINT "shifts_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "location"("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "shifts_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,CONSTRAINT "shifts_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE,CONSTRAINT "shifts_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE);@@ -87,26 +92,29 @@ CREATE POLICY "Employees can view shifts" ON "shift"USING (auth.role() = 'authenticated'AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ AND "companyId" = ANY(+ select "companyId" from "userToCompany" where "userId" = auth.uid()::text+ ));CREATE POLICY "Employees with resources_create can insert shifts" ON "shift"FOR INSERTWITH CHECK (- coalesce(get_my_claim('resources_create')::boolean,false)+ has_company_permission('resources_create', "companyId")AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_update can update shifts" ON "shift"FOR UPDATEUSING (- coalesce(get_my_claim('resources_update')::boolean, false) = true+ has_company_permission('resources_update', "companyId")AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_delete can delete shifts" ON "shift"FOR DELETEUSING (- coalesce(get_my_claim('resources_delete')::boolean, false) = true+ has_company_permission('resources_delete', "companyId")AND (get_my_claim('role'::text)) = '"employee"'::jsonb);@@ -130,26 +138,52 @@ CREATE POLICY "Employees can view employee shifts" ON "employeeShift"USING (auth.role() = 'authenticated'AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ AND "shiftId" IN (+ SELECT "id" FROM "shift" WHERE "companyId" = ANY(+ select "companyId" from "userToCompany" where "userId" = auth.uid()::text+ )+ ));CREATE POLICY "Employees with resources_create can insert employee shifts" ON "employeeShift"FOR INSERTWITH CHECK (- coalesce(get_my_claim('resources_create')::boolean,false)+ "shiftId" IN (+ SELECT "id" FROM "shift" WHERE "companyId" = ANY(+ coalesce(+ get_permission_companies('resource_create')::integer[],+ array[]::integer[]+ )+ )+ )AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_update can update employee shifts" ON "employeeShift"FOR UPDATEUSING (- coalesce(get_my_claim('resources_update')::boolean, false) = true+ "shiftId" IN (+ SELECT "id" FROM "shift" WHERE "companyId" = ANY(+ coalesce(+ get_permission_companies('resource_update')::integer[],+ array[]::integer[]+ )+ )+ )AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_delete can delete employee shifts" ON "employeeShift"FOR DELETEUSING (- coalesce(get_my_claim('resources_delete')::boolean, false) = true+ "shiftId" IN (+ SELECT "id" FROM "shift" WHERE "companyId" = ANY(+ coalesce(+ get_permission_companies('resource_delete')::integer[],+ array[]::integer[]+ )+ )+ )AND (get_my_claim('role'::text)) = '"employee"'::jsonb);@@ -174,35 +208,61 @@ CREATE TABLE "employeeJob" ();ALTER TABLE "employeeJob" ENABLE ROW LEVEL SECURITY;-CREATE POLICY "Employees can view employee jobs" ON "employeeJob"FOR SELECTUSING (auth.role() = 'authenticated'AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ AND "id" IN (+ SELECT "id" FROM "shift" WHERE "companyId" = ANY(+ select "companyId" from "userToCompany" where "userId" = auth.uid()::text+ )+ ));CREATE POLICY "Employees with resources_create can insert employee jobs" ON "employeeJob"FOR INSERTWITH CHECK (- coalesce(get_my_claim('resources_create')::boolean,false)+ "shiftId" IN (+ SELECT "id" FROM "shift" WHERE "companyId" = ANY(+ coalesce(+ get_permission_companies('resource_create')::integer[],+ array[]::integer[]+ )+ )+ )AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_update can update employee jobs" ON "employeeJob"FOR UPDATEUSING (- coalesce(get_my_claim('resources_update')::boolean, false) = true+ "shiftId" IN (+ SELECT "id" FROM "shift" WHERE "companyId" = ANY(+ coalesce(+ get_permission_companies('resource_update')::integer[],+ array[]::integer[]+ )+ )+ )AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Employees with resources_delete can delete employee jobs" ON "employeeJob"FOR DELETEUSING (- coalesce(get_my_claim('resources_delete')::boolean, false) = true+ "shiftId" IN (+ SELECT "id" FROM "shift" WHERE "companyId" = ANY(+ coalesce(+ get_permission_companies('resource_delete')::integer[],+ array[]::integer[]+ )+ )+ )AND (get_my_claim('role'::text)) = '"employee"'::jsonb);+CREATE OR REPLACE VIEW "shifts" WITH(SECURITY_INVOKER=true) ASSELECTs.*, l."name" as "locationName"diff --git a/packages/database/supabase/seed.sql b/packages/database/supabase/seed.sqlindex 7d31622f53..b527167666 100644--- a/packages/database/supabase/seed.sql+++ b/packages/database/supabase/seed.sql@@ -148,13 +148,13 @@ VALUES('User', false, false, false, false, false, true);--- supplier status+-- -- supplier status+-- TODO:+-- INSERT INTO "supplierStatus" ("name", "createdBy") VALUES ('Active', 'system'), ('Inactive', 'system'), ('Pending', 'system'), ('Rejected', 'system');-INSERT INTO "supplierStatus" ("name", "createdBy") VALUES ('Active', 'system'), ('Inactive', 'system'), ('Pending', 'system'), ('Rejected', 'system');---- customer status--INSERT INTO "customerStatus" ("name", "createdBy") VALUES ('Active', 'system'), ('Inactive', 'system'), ('Lead', 'system'), ('On Hold', 'system'), ('Cancelled', 'system'), ('Archived', 'system');+-- -- customer status+-- TODO:+-- INSERT INTO "customerStatus" ("name", "createdBy") VALUES ('Active', 'system'), ('Inactive', 'system'), ('Lead', 'system'), ('On Hold', 'system'), ('Cancelled', 'system'), ('Archived', 'system');-- unit of measurediff --git a/www/pages/develop/core-concepts/permissions.mdx b/www/pages/develop/core-concepts/permissions.mdxindex 349247fad5..8943190407 100644--- a/www/pages/develop/core-concepts/permissions.mdx+++ b/www/pages/develop/core-concepts/permissions.mdx@@ -60,7 +60,7 @@ It is most important to use RLS. But server-side and client-side mechanisms can### Database Row-Level Security-Here is an example of how to use RLS policies to limit a user's rights to modify a table using the `get_my_claim` function. This is SQL that's run against the database to create a security policy for the `customer` table. If you're not familiar with the `::bolean` and `::jsonb` syntax, that's just casting the value to a boolean or jsonb type. The `get_my_claim` function is a custom function that returns the value of a claim from the user's permissions record. The `auth.uid()` function returns the user's ID.+Here is an example of how to use RLS policies to limit a user's rights to modify a table using the `get_my_claim` function. This is SQL that's run against the database to create a security policy for the `customer` table. If you're not familiar with the `::boolean` and `::jsonb` syntax, that's just casting the value to a boolean or jsonb type. The `get_my_claim` function is a custom function that returns the value of a claim from the user's permissions record. The `auth.uid()` function returns the user's ID.```sql-- SQL