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 2
Brad Barbin9476698e7399
diff --git a/apps/carbon/app/modules/purchasing/purchasing.service.ts b/apps/carbon/app/modules/purchasing/purchasing.service.tsindex bd8a6e3b85..449394c590 100644--- a/apps/carbon/app/modules/purchasing/purchasing.service.ts+++ b/apps/carbon/app/modules/purchasing/purchasing.service.ts@@ -445,13 +445,16 @@ export async function insertSupplierContact(client: SupabaseClient<Database>,supplierContact: {supplierId: string;+ companyId: number;contact: z.infer<typeof supplierContactValidator>;customFields?: Json;}) {const insertContact = await client.from("contact")- .insert([supplierContact.contact])+ .insert([+ { ...supplierContact.contact, companyId: supplierContact.companyId },+ ]).select("id").single();@@ -836,6 +839,7 @@ export async function upsertPurchaseOrderLine(client: SupabaseClient<Database>,purchaseOrderLine:| (Omit<z.infer<typeof purchaseOrderLineValidator>, "id"> & {+ companyId: number;createdBy: string;customFields?: Json;})diff --git a/apps/carbon/app/modules/sales/sales.service.ts b/apps/carbon/app/modules/sales/sales.service.tsindex 47b437719c..7f2221a185 100644--- a/apps/carbon/app/modules/sales/sales.service.ts+++ b/apps/carbon/app/modules/sales/sales.service.ts@@ -2,10 +2,10 @@ import type { Database, Json } from "@carbon/database";import { getLocalTimeZone, today } from "@internationalized/date";import type { SupabaseClient } from "@supabase/supabase-js";import type { z } from "zod";+import { getEmployeeJob } from "~/modules/resources";import type { GenericQueryFilters } from "~/utils/query";import { setGenericQueryFilters } from "~/utils/query";import { sanitize } from "~/utils/supabase";-import { getEmployeeJob } from "~/modules/resources";import type {customerContactValidator,customerPaymentValidator,@@ -19,9 +19,9 @@ import type {quotationOperationValidator,quotationPricingValidator,quotationValidator,- salesOrderShipmentValidator,salesOrderLineValidator,salesOrderPaymentValidator,+ salesOrderShipmentValidator,salesOrderValidator,} from "./sales.models";@@ -449,13 +449,16 @@ export async function insertCustomerContact(client: SupabaseClient<Database>,customerContact: {customerId: string;+ companyId: number;contact: z.infer<typeof customerContactValidator>;customFields?: Json;}) {const insertContact = await client.from("contact")- .insert([customerContact.contact])+ .insert([+ { ...customerContact.contact, companyId: customerContact.companyId },+ ]).select("id").single();if (insertContact.error) {@@ -1111,7 +1114,7 @@ export async function releaseSalesOrder(return client.from("salesOrder").update({- status: "To Receive and Invoice",+ status: "Confirmed",updatedAt: today(getLocalTimeZone()).toString(),updatedBy: userId,})@@ -1258,6 +1261,7 @@ export async function upsertSalesOrderLine(client: SupabaseClient<Database>,salesOrderLine:| (Omit<z.infer<typeof salesOrderLineValidator>, "id"> & {+ companyId: number;createdBy: string;customFields?: Json;})@@ -1286,19 +1290,12 @@ export async function insertSalesOrderLines(client: SupabaseClient<Database>,salesOrderLines:| (Omit<z.infer<typeof salesOrderLineValidator>, "id"> & {+ companyId: number;createdBy: string;customFields?: Json;})[]- | (Omit<z.infer<typeof salesOrderLineValidator>, "id"> & {- id: string;- updatedBy: string;- customFields?: Json;- })[]) {- return client- .from("salesOrderLine")- .insert([...salesOrderLines])- .select("id");+ return client.from("salesOrderLine").insert(salesOrderLines).select("id");}export async function upsertSalesOrderPayment(diff --git a/apps/carbon/app/routes/x+/customer+/$customerId.contacts.new.tsx b/apps/carbon/app/routes/x+/customer+/$customerId.contacts.new.tsxindex 5bc13995c5..85b9530913 100644--- a/apps/carbon/app/routes/x+/customer+/$customerId.contacts.new.tsx+++ b/apps/carbon/app/routes/x+/customer+/$customerId.contacts.new.tsx@@ -17,7 +17,7 @@ import { error, success } from "~/utils/result";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);- await requirePermissions(request, {+ const { companyId } = await requirePermissions(request, {create: "sales",});@@ -42,6 +42,7 @@ export async function action({ request, params }: ActionFunctionArgs) {const createCustomerContact = await insertCustomerContact(client, {customerId,+ companyId,contact,customFields: setCustomFields(formData),});diff --git a/apps/carbon/app/routes/x+/purchase-order+/$orderId.lines.new.tsx b/apps/carbon/app/routes/x+/purchase-order+/$orderId.lines.new.tsxindex ec0f7ca7af..cb4f5e75c2 100644--- a/apps/carbon/app/routes/x+/purchase-order+/$orderId.lines.new.tsx+++ b/apps/carbon/app/routes/x+/purchase-order+/$orderId.lines.new.tsx@@ -17,7 +17,7 @@ import { error } from "~/utils/result";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);- const { client, userId } = await requirePermissions(request, {+ const { client, companyId, userId } = await requirePermissions(request, {create: "purchasing",});@@ -37,6 +37,7 @@ export async function action({ request, params }: ActionFunctionArgs) {const createPurchaseOrderLine = await upsertPurchaseOrderLine(client, {...data,+ companyId,createdBy: userId,customFields: setCustomFields(formData),});diff --git a/apps/carbon/app/routes/x+/quote+/$id.convert-to-order.tsx b/apps/carbon/app/routes/x+/quote+/$id.convert-to-order.tsxindex 6c1dd64504..96c81b4df5 100644--- a/apps/carbon/app/routes/x+/quote+/$id.convert-to-order.tsx+++ b/apps/carbon/app/routes/x+/quote+/$id.convert-to-order.tsx@@ -1,11 +1,10 @@import { redirect, type ActionFunctionArgs } from "@remix-run/node";-import type { SalesOrderLine } from "~/modules/sales";import {+ convertQuoteToOrder,getQuote,getQuoteLines,- convertQuoteToOrder,- upsertSalesOrder,insertSalesOrderLines,+ upsertSalesOrder,} from "~/modules/sales";import { getNextSequence, rollbackNextSequence } from "~/modules/settings";import { requirePermissions } from "~/services/auth/auth.server";@@ -18,7 +17,7 @@ export async function action(args: ActionFunctionArgs) {const { request, params } = args;assertIsPost(request);- const { client, userId } = await requirePermissions(request, {+ const { client, companyId, userId } = await requirePermissions(request, {create: "sales",role: "employee",});@@ -64,8 +63,8 @@ export async function action(args: ActionFunctionArgs) {const createSalesOrder = await upsertSalesOrder(client, {salesOrderId: nextSequence.data,createdBy: userId,- quoteId: quote.data.id,- customerId: quote.data.customerId,+ quoteId: quote.data.id!,+ customerId: quote.data.customerId!,orderDate: new Date().toISOString(),});@@ -87,22 +86,18 @@ export async function action(args: ActionFunctionArgs) {// construct and insert the sales order linesconst quoteLines = await getQuoteLines(client, id);if (quoteLines.data) {- const constructedSalesOrderLines: SalesOrderLine[] = quoteLines?.data.map(- (quoteLine) => {- return {- salesOrderId: newSalesOrderId,- salesOrderLineType: "Part",- partId: quoteLine.partId,- description: quoteLine.description,- createdBy: userId,- };- }- );+ const lines = quoteLines?.data.map((quoteLine) => {+ return {+ salesOrderId: newSalesOrderId,+ salesOrderLineType: "Part" as "Part",+ companyId,+ partId: quoteLine.partId!,+ description: quoteLine.description!,+ createdBy: userId,+ };+ });- const salesOrderLines = await insertSalesOrderLines(- client,- constructedSalesOrderLines- );+ const salesOrderLines = await insertSalesOrderLines(client, lines);if (salesOrderLines.error) {throw redirect(diff --git a/apps/carbon/app/routes/x+/sales-order+/$orderId.lines.new.tsx b/apps/carbon/app/routes/x+/sales-order+/$orderId.lines.new.tsxindex 4549027886..db1e7e27d1 100644--- a/apps/carbon/app/routes/x+/sales-order+/$orderId.lines.new.tsx+++ b/apps/carbon/app/routes/x+/sales-order+/$orderId.lines.new.tsx@@ -17,7 +17,7 @@ import { error } from "~/utils/result";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);- const { client, userId } = await requirePermissions(request, {+ const { client, companyId, userId } = await requirePermissions(request, {create: "sales",});@@ -37,6 +37,7 @@ export async function action({ request, params }: ActionFunctionArgs) {const createSalesOrderLine = await upsertSalesOrderLine(client, {...data,+ companyId,createdBy: userId,customFields: setCustomFields(formData),});diff --git a/apps/carbon/app/routes/x+/supplier+/$supplierId.contacts.new.tsx b/apps/carbon/app/routes/x+/supplier+/$supplierId.contacts.new.tsxindex c8abcec06b..d4d2785272 100644--- a/apps/carbon/app/routes/x+/supplier+/$supplierId.contacts.new.tsx+++ b/apps/carbon/app/routes/x+/supplier+/$supplierId.contacts.new.tsx@@ -17,7 +17,7 @@ import { error, success } from "~/utils/result";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);- await requirePermissions(request, {+ const { companyId } = await requirePermissions(request, {create: "purchasing",});@@ -42,6 +42,7 @@ export async function action({ request, params }: ActionFunctionArgs) {const createSupplierContact = await insertSupplierContact(client, {supplierId,+ companyId,contact,customFields: setCustomFields(formData),});diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex 35d4e4eb20..420621b60b 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -1283,6 +1283,7 @@ export type Database = {addressLine1: string | nulladdressLine2: string | nullcity: string | null+ companyId: number | nullcountryCode: number | nullfax: string | nullid: string@@ -1294,6 +1295,7 @@ export type Database = {addressLine1?: string | nulladdressLine2?: string | nullcity?: string | null+ companyId?: number | nullcountryCode?: number | nullfax?: string | nullid?: string@@ -1305,6 +1307,7 @@ export type Database = {addressLine1?: string | nulladdressLine2?: string | nullcity?: string | null+ companyId?: number | nullcountryCode?: number | nullfax?: string | nullid?: string@@ -1313,6 +1316,13 @@ export type Database = {state?: string | null}Relationships: [+ {+ foreignKeyName: "address_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },{foreignKeyName: "address_countryCode_fkey"columns: ["countryCode"]@@ -1444,6 +1454,7 @@ export type Database = {addressLine2: string | nullbirthday: string | nullcity: string | null+ companyId: number | nullcountryCode: number | nullemail: stringfax: string | null@@ -1464,6 +1475,7 @@ export type Database = {addressLine2?: string | nullbirthday?: string | nullcity?: string | null+ companyId?: number | nullcountryCode?: number | nullemail: stringfax?: string | null@@ -1484,6 +1496,7 @@ export type Database = {addressLine2?: string | nullbirthday?: string | nullcity?: string | null+ companyId?: number | nullcountryCode?: number | nullemail?: stringfax?: string | null@@ -1500,6 +1513,13 @@ export type Database = {workPhone?: string | null}Relationships: [+ {+ foreignKeyName: "contact_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },{foreignKeyName: "contact_countryCode_fkey"columns: ["countryCode"]@@ -2140,18 +2160,28 @@ export type Database = {}customerAccount: {Row: {+ companyId: numbercustomerId: stringid: string}Insert: {+ companyId: numbercustomerId: stringid: string}Update: {+ companyId?: numbercustomerId?: stringid?: string}Relationships: [+ {+ foreignKeyName: "customerAccount_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },{foreignKeyName: "customerAccount_customerId_fkey"columns: ["customerId"]@@ -2176,28 +2206,28 @@ export type Database = {{foreignKeyName: "customerAccount_id_fkey"columns: ["id"]- isOneToOne: true+ isOneToOne: falsereferencedRelation: "employees"referencedColumns: ["id"]},{foreignKeyName: "customerAccount_id_fkey"columns: ["id"]- isOneToOne: true+ isOneToOne: falsereferencedRelation: "employeeSummary"referencedColumns: ["id"]},{foreignKeyName: "customerAccount_id_fkey"columns: ["id"]- isOneToOne: true+ isOneToOne: falsereferencedRelation: "user"referencedColumns: ["id"]},{foreignKeyName: "customerAccount_id_fkey"columns: ["id"]- isOneToOne: true+ isOneToOne: falsereferencedRelation: "userDefaults"referencedColumns: ["userId"]},@@ -12891,43 +12921,53 @@ export type Database = {}supplierAccount: {Row: {+ companyId: numberid: stringsupplierId: string}Insert: {+ companyId: numberid: stringsupplierId: string}Update: {+ companyId?: numberid?: stringsupplierId?: string}Relationships: [+ {+ foreignKeyName: "supplierAccount_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },{foreignKeyName: "supplierAccount_id_fkey"columns: ["id"]- isOneToOne: true+ isOneToOne: falsereferencedRelation: "employees"referencedColumns: ["id"]},{foreignKeyName: "supplierAccount_id_fkey"columns: ["id"]- isOneToOne: true+ isOneToOne: falsereferencedRelation: "employeeSummary"referencedColumns: ["id"]},{foreignKeyName: "supplierAccount_id_fkey"columns: ["id"]- isOneToOne: true+ isOneToOne: falsereferencedRelation: "user"referencedColumns: ["id"]},{foreignKeyName: "supplierAccount_id_fkey"columns: ["id"]- isOneToOne: true+ isOneToOne: falsereferencedRelation: "userDefaults"referencedColumns: ["userId"]},@@ -17954,6 +17994,12 @@ export type Database = {}Returns: boolean}+ has_role: {+ Args: {+ role: string+ }+ Returns: boolean+ }is_claims_admin: {Args: Record<PropertyKey, never>Returns: booleandiff --git a/packages/database/supabase/migrations/20230123004206_claims.sql b/packages/database/supabase/migrations/20230123004206_claims.sqlindex 1c4ded852f..728db10abd 100644--- a/packages/database/supabase/migrations/20230123004206_claims.sql+++ b/packages/database/supabase/migrations/20230123004206_claims.sql@@ -87,6 +87,18 @@ CREATE OR REPLACE FUNCTION get_permission_companies_as_text(claim text) RETURNSEND;$$;+CREATE OR REPLACE FUNCTION has_role(role text) RETURNS "bool"+ LANGUAGE "plpgsql" SECURITY DEFINER SET search_path = public+ AS $$+ BEGIN+ IF (get_my_claim('role'::text)) = ('"' || role || '"'::text)::jsonb THEN+ return true;+ ELSE+ return false;+ END IF;+ 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/20230123004317_companies.sql b/packages/database/supabase/migrations/20230123004317_companies.sqlindex a350d7eef4..0b86938702 100644--- a/packages/database/supabase/migrations/20230123004317_companies.sql+++ b/packages/database/supabase/migrations/20230123004317_companies.sql@@ -35,8 +35,8 @@ CREATE POLICY "Employees with settings_create can create company" ON "company"CREATE POLICY "Employees with settings_update can update company" ON "company"FOR UPDATEUSING (- has_company_permission('settings_update', "id") AND- (get_my_claim('role'::text)) = '"employee"'::jsonb+ has_role('employee') AND+ has_company_permission('settings_update', "id"));CREATE POLICY "Employees with settings_delete can delete company" ON "company"diff --git a/packages/database/supabase/migrations/20230123004514_buckets.sql b/packages/database/supabase/migrations/20230123004514_buckets.sqlindex 56a1683f22..2c688e05bc 100644--- a/packages/database/supabase/migrations/20230123004514_buckets.sql+++ b/packages/database/supabase/migrations/20230123004514_buckets.sql@@ -13,7 +13,7 @@ ON storage.objects FOR SELECT USING (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 has_role('employee')AND (0 = ANY(get_permission_companies('settings_create')@@ -27,7 +27,7 @@ ON storage.objects FOR INSERT WITH CHECK (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 has_role('employee')AND (0 = ANY(get_permission_companies('settings_create')@@ -41,7 +41,7 @@ ON storage.objects FOR UPDATE USING (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 has_role('employee')AND (0 = ANY(get_permission_companies('settings_create')diff --git a/packages/database/supabase/migrations/20230123004612_suppliers-and-customers.sql b/packages/database/supabase/migrations/20230123004612_suppliers-and-customers.sqlindex 6c1761aba0..b5ed286ba1 100644--- a/packages/database/supabase/migrations/20230123004612_suppliers-and-customers.sql+++ b/packages/database/supabase/migrations/20230123004612_suppliers-and-customers.sql@@ -23,9 +23,11 @@ CREATE TABLE "contact" ("countryCode" INTEGER,"birthday" DATE,"notes" TEXT,+ "companyId" INTEGER,CONSTRAINT "contact_pkey" PRIMARY KEY ("id"),- CONSTRAINT "contact_countryCode_fkey" FOREIGN KEY ("countryCode") REFERENCES "country"("id") ON DELETE SET NULL ON UPDATE CASCADE+ CONSTRAINT "contact_countryCode_fkey" FOREIGN KEY ("countryCode") REFERENCES "country"("id") ON DELETE SET NULL ON UPDATE CASCADE,+ CONSTRAINT "contact_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE);@@ -39,9 +41,11 @@ CREATE TABLE "address" ("countryCode" INTEGER,"phone" TEXT,"fax" TEXT,+ "companyId" INTEGER,CONSTRAINT "address_pkey" PRIMARY KEY ("id"),- CONSTRAINT "address_countryCode_fkey" FOREIGN KEY ("countryCode") REFERENCES "country"("id") ON DELETE SET NULL ON UPDATE CASCADE+ CONSTRAINT "address_countryCode_fkey" FOREIGN KEY ("countryCode") REFERENCES "country"("id") ON DELETE SET NULL ON UPDATE CASCADE,+ CONSTRAINT "address_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE);CREATE TABLE "supplierStatus" (@@ -143,10 +147,12 @@ CREATE INDEX "supplierContact_supplierId_index" ON "supplierContact"("supplierIdCREATE TABLE "supplierAccount" ("id" TEXT NOT NULL,"supplierId" TEXT NOT NULL,+ "companyId" INTEGER NOT NULL,- CONSTRAINT "supplierAccount_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "supplierAccount_pkey" PRIMARY KEY ("id", "companyId"),CONSTRAINT "supplierAccount_supplierId_fkey" FOREIGN KEY ("supplierId") REFERENCES "supplier"("id") ON DELETE CASCADE ON UPDATE CASCADE,- CONSTRAINT "supplierAccount_id_fkey" FOREIGN KEY ("id") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE+ CONSTRAINT "supplierAccount_id_fkey" FOREIGN KEY ("id") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "supplierAccount_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE);CREATE INDEX "supplierAccount_supplierId_index" ON "supplierAccount"("supplierId");@@ -250,10 +256,12 @@ CREATE INDEX "customerContact_customerId_index" ON "customerContact"("customerIdCREATE TABLE "customerAccount" ("id" TEXT NOT NULL,"customerId" TEXT NOT NULL,+ "companyId" INTEGER NOT NULL,- CONSTRAINT "customerAccount_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "customerAccount_pkey" PRIMARY KEY ("id", "companyId"),CONSTRAINT "customerAccount_customerId_fkey" FOREIGN KEY ("customerId") REFERENCES "customer"("id") ON DELETE CASCADE ON UPDATE CASCADE,- CONSTRAINT "customerAccount_id_fkey" FOREIGN KEY ("id") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE+ CONSTRAINT "customerAccount_id_fkey" FOREIGN KEY ("id") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "customerAccount_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE);CREATE INDEX "customerAccount_customerId_index" ON "customerAccount"("customerId");diff --git a/packages/database/supabase/migrations/20230126050441_abac.sql b/packages/database/supabase/migrations/20230126050441_abac.sqlindex cf378f360b..4fbdf16f2c 100644--- a/packages/database/supabase/migrations/20230126050441_abac.sql+++ b/packages/database/supabase/migrations/20230126050441_abac.sql@@ -5,32 +5,32 @@ ALTER TABLE "contact" ENABLE ROW LEVEL SECURITY;CREATE POLICY "Employees with purchasing_view can view contacts that are suppliers" ON "contact"FOR SELECTUSING (- coalesce(get_my_claim('purchasing_view')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ has_role('employee')+ AND has_company_permission('purchasing_view', "companyId")AND id IN (- SELECT "contactId" FROM "supplierContact"+ SELECT "contactId" FROM "supplierContact"));CREATE POLICY "Employees with sales_view can view contacts that are customer" ON "contact"FOR SELECTUSING (- coalesce(get_my_claim('sales_view')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ has_role('employee')+ AND has_company_permission('sales_view', "companyId")AND id IN (- SELECT "contactId" FROM "customerContact"+ SELECT "contactId" FROM "customerContact"));CREATE POLICY "Suppliers with purchasing_view can view contacts from their organization" ON "contact"FOR SELECTUSING (- coalesce(get_my_claim('purchasing_view')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"supplier"'::jsonb+ has_role('supplier')+ AND has_company_permission('sales_view', "companyId")AND (id IN (- SELECT "contactId" FROM "supplierContact" WHERE "supplierId" IN (- SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()+ SELECT "contactId" FROM "customerContact" WHERE "customerId" IN (+ SELECT "customerId" FROM "customerAccount" WHERE id::uuid = auth.uid())))@@ -39,8 +39,8 @@ CREATE POLICY "Suppliers with purchasing_view can view contacts from their organCREATE POLICY "Customers with sales_view can view contacts from their organization" ON "contact"FOR SELECTUSING (- coalesce(get_my_claim('sales_view')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"customer"'::jsonb+ has_role('customer')+ AND has_company_permission('sales_view', "companyId")AND (id IN (SELECT "contactId" FROM "customerContact" WHERE "customerId" IN (@@ -53,32 +53,34 @@ CREATE POLICY "Customers with sales_view can view contacts from their organizatiCREATE POLICY "Many employees can create contacts" ON "contact"FOR INSERTWITH CHECK (+ has_role('employee') AND(- coalesce(get_my_claim('purchasing_create')::boolean,false) OR- coalesce(get_my_claim('sales_create')::boolean,false) OR- coalesce(get_my_claim('users_create')::boolean,false)- ) AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ has_company_permission('purchasing_create', "companyId") OR+ has_company_permission('sales_create', "companyId") OR+ has_company_permission('invoicing_create', "companyId") OR+ has_company_permission('users_create', "companyId")+ ));-CREATE POLICY "Suppliers with purchasing_update can create contacts from their organization" ON "contact"+CREATE POLICY "Suppliers with purchasing_create can create contacts from their organization" ON "contact"FOR INSERTWITH CHECK (- coalesce(get_my_claim('purchasing_update')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"supplier"'::jsonb+ has_role('supplier')+ AND has_company_permission('purchasing_create', "companyId")AND (id IN (SELECT "contactId" FROM "supplierContact" WHERE "supplierId" IN (- SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()+ SELECT "supplierId" FROM "supplierAccount" sa WHERE id::uuid = auth.uid()))));-CREATE POLICY "Customers with sales_update can create contacts from their organization" ON "contact"+CREATE POLICY "Customers with sales_create can create contacts from their organization" ON "contact"FOR INSERTWITH CHECK (- coalesce(get_my_claim('sales_update')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"customer"'::jsonb+ has_role('customer')+ AND has_company_permission('sales_create', "companyId")AND (id IN (SELECT "contactId" FROM "customerContact" WHERE "customerId" IN (@@ -91,8 +93,8 @@ CREATE POLICY "Customers with sales_update can create contacts from their organiCREATE POLICY "Employees with purchasing_update can update supplier contacts" ON "contact"FOR UPDATEUSING (- coalesce(get_my_claim('purchasing_update')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ has_role('employee')+ AND has_company_permission('purchasing_update', "companyId")AND id IN (SELECT "contactId" FROM "supplierContact")@@ -101,12 +103,12 @@ CREATE POLICY "Employees with purchasing_update can update supplier contacts" ONCREATE POLICY "Suppliers with purchasing_update can update contacts from their organization" ON "contact"FOR UPDATEUSING (- coalesce(get_my_claim('purchasing_update')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"supplier"'::jsonb+ has_role('supplier')+ AND has_company_permission('purchasing_update', "companyId")AND (id IN (SELECT "contactId" FROM "supplierContact" WHERE "supplierId" IN (- SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()+ SELECT "supplierId" FROM "supplierAccount" sa WHERE id::uuid = auth.uid())))@@ -115,8 +117,8 @@ CREATE POLICY "Suppliers with purchasing_update can update contacts from their oCREATE POLICY "Employees with sales_update can update customer contacts" ON "contact"FOR UPDATEUSING (- coalesce(get_my_claim('purchasing_update')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ has_role('employee')+ AND has_company_permission('sales_update', "companyId")AND id IN (SELECT "contactId" FROM "customerContact")@@ -125,12 +127,12 @@ CREATE POLICY "Employees with sales_update can update customer contacts" ON "conCREATE POLICY "Customers with sales_update can update contacts from their organization" ON "contact"FOR UPDATEUSING (- coalesce(get_my_claim('sales_update')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"customer"'::jsonb+ has_role('customer')+ AND has_company_permission('sales_update', "companyId")AND (id IN (SELECT "contactId" FROM "customerContact" WHERE "customerId" IN (- SELECT "customerId" FROM "customerAccount" WHERE id::uuid = auth.uid()+ SELECT "customerId" FROM "customerAccount" sa WHERE id::uuid = auth.uid())))@@ -140,7 +142,7 @@ CREATE POLICY "Employees with purchasing_delete can delete supplier contacts" ONFOR DELETEUSING (coalesce(get_my_claim('purchasing_delete')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ AND has_role('employee')AND id IN (SELECT "contactId" FROM "supplierContact")@@ -150,7 +152,7 @@ CREATE POLICY "Suppliers with purchasing_delete can delete contacts from their oFOR DELETEUSING (coalesce(get_my_claim('purchasing_delete')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"supplier"'::jsonb+ AND has_role('supplier')AND (id IN (SELECT "contactId" FROM "supplierContact" WHERE "supplierId" IN (@@ -164,7 +166,7 @@ CREATE POLICY "Employees with sales_delete can delete customer contacts" ON "conFOR DELETEUSING (coalesce(get_my_claim('sales_delete')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ AND has_role('employee')AND id IN (SELECT "contactId" FROM "customerContact")@@ -174,7 +176,7 @@ CREATE POLICY "Customers with sales_delete can delete contacts from their organiFOR DELETEUSING (coalesce(get_my_claim('sales_delete')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"customer"'::jsonb+ AND has_role('customer')AND (id IN (SELECT "contactId" FROM "customerContact" WHERE "customerId" IN (@@ -190,19 +192,19 @@ ALTER TABLE "customerType" ENABLE ROW LEVEL SECURITY;CREATE POLICY "Employees with sales_view can view customer types" ON "customerType"FOR SELECT- USING (coalesce(get_my_claim('sales_view')::boolean, false) = true AND (get_my_claim('role'::text)) = '"employee"'::jsonb);+ USING (coalesce(get_my_claim('sales_view')::boolean, false) = true AND has_role('employee'));CREATE POLICY "Employees with sales_create can create customer types" ON "customerType"FOR INSERT- WITH CHECK (coalesce(get_my_claim('sales_create')::boolean,false) AND (get_my_claim('role'::text)) = '"employee"'::jsonb);+ WITH CHECK (coalesce(get_my_claim('sales_create')::boolean,false) AND has_role('employee'));CREATE POLICY "Employees with sales_update can update customer types" ON "customerType"FOR UPDATE- USING (coalesce(get_my_claim('sales_update')::boolean,false) AND (get_my_claim('role'::text)) = '"employee"'::jsonb);+ USING (coalesce(get_my_claim('sales_update')::boolean,false) AND has_role('employee'));CREATE POLICY "Employees with sales_delete can delete customer types" ON "customerType"FOR DELETE- USING (coalesce(get_my_claim('sales_delete')::boolean, false) = true AND (get_my_claim('role'::text)) = '"employee"'::jsonb);+ USING (coalesce(get_my_claim('sales_delete')::boolean, false) = true AND has_role('employee'));-- customer@@ -210,13 +212,13 @@ ALTER TABLE "customer" ENABLE ROW LEVEL SECURITY;CREATE POLICY "Employees with sales_view can view customer" ON "customer"FOR SELECT- USING (coalesce(get_my_claim('sales_view')::boolean, false) = true AND (get_my_claim('role'::text)) = '"employee"'::jsonb);+ USING (coalesce(get_my_claim('sales_view')::boolean, false) = true AND has_role('employee'));CREATE POLICY "Customers with sales_view can their own organization" ON "customer"FOR SELECTUSING (coalesce(get_my_claim('sales_view')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"customer"'::jsonb+ AND has_role('customer')AND id IN (SELECT "customerId" FROM "customerAccount" WHERE id::uuid = auth.uid())@@ -224,17 +226,17 @@ CREATE POLICY "Customers with sales_view can their own organization" ON "customeCREATE POLICY "Employees with sales_create can create customers" ON "customer"FOR INSERT- WITH CHECK (coalesce(get_my_claim('sales_create')::boolean,false) AND (get_my_claim('role'::text)) = '"employee"'::jsonb);+ WITH CHECK (coalesce(get_my_claim('sales_create')::boolean,false) AND has_role('employee'));CREATE POLICY "Employees with sales_update can update customers" ON "customer"FOR UPDATE- USING (coalesce(get_my_claim('sales_update')::boolean,false) AND (get_my_claim('role'::text)) = '"employee"'::jsonb);+ USING (coalesce(get_my_claim('sales_update')::boolean,false) AND has_role('employee'));CREATE POLICY "Customers with sales_update can their own organization" ON "customer"FOR UPDATEUSING (coalesce(get_my_claim('sales_update')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"customer"'::jsonb+ AND has_role('customer')AND id IN (SELECT "customerId" FROM "customerAccount" WHERE id::uuid = auth.uid())@@ -242,7 +244,7 @@ CREATE POLICY "Customers with sales_update can their own organization" ON "custoCREATE POLICY "Employees with sales_delete can delete customers" ON "customer"FOR DELETE- USING (coalesce(get_my_claim('sales_delete')::boolean, false) = true AND (get_my_claim('role'::text)) = '"employee"'::jsonb);+ USING (coalesce(get_my_claim('sales_delete')::boolean, false) = true AND has_role('employee'));-- customerContact@@ -250,13 +252,13 @@ ALTER TABLE "customerContact" ENABLE ROW LEVEL SECURITY;CREATE POLICY "Employees with sales_view can view customer contact" ON "customerContact"FOR SELECT- USING (coalesce(get_my_claim('sales_view')::boolean, false) = true AND (get_my_claim('role'::text)) = '"employee"'::jsonb);+ USING (coalesce(get_my_claim('sales_view')::boolean, false) = true AND has_role('employee'));CREATE POLICY "Customers with sales_view can their own customer contacts" ON "customerContact"FOR SELECTUSING (coalesce(get_my_claim('sales_view')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"customer"'::jsonb+ AND has_role('customer')AND "customerId" IN (SELECT "customerId" FROM "customerAccount" WHERE id::uuid = auth.uid())@@ -264,12 +266,12 @@ CREATE POLICY "Customers with sales_view can their own customer contacts" ON "cuCREATE POLICY "Employees with sales_create can create customer contacts" ON "customerContact"FOR INSERT- WITH CHECK (coalesce(get_my_claim('sales_create')::boolean,false) AND (get_my_claim('role'::text)) = '"employee"'::jsonb);+ WITH CHECK (coalesce(get_my_claim('sales_create')::boolean,false) AND has_role('employee'));CREATE POLICY "Customers with sales_create can create customer contacts" ON "customerContact"FOR INSERTWITH CHECK (coalesce(get_my_claim('sales_create')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"customer"'::jsonb+ AND has_role('customer')AND "customerId" IN (SELECT "customerId" FROM "customerAccount" WHERE id::uuid = auth.uid())@@ -277,12 +279,12 @@ CREATE POLICY "Customers with sales_create can create customer contacts" ON "cusCREATE POLICY "Employees with sales_update can update customer contacts" ON "customerContact"FOR UPDATE- USING (coalesce(get_my_claim('sales_update')::boolean,false) AND (get_my_claim('role'::text)) = '"employee"'::jsonb);+ USING (coalesce(get_my_claim('sales_update')::boolean,false) AND has_role('employee'));CREATE POLICY "Customers with sales_update can update their customer contacts" ON "customerContact"FOR UPDATEUSING (coalesce(get_my_claim('sales_update')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"customer"'::jsonb+ AND has_role('customer')AND "customerId" IN (SELECT "customerId" FROM "customerAccount" WHERE id::uuid = auth.uid())@@ -290,7 +292,7 @@ CREATE POLICY "Customers with sales_update can update their customer contacts" OCREATE POLICY "Employees with sales_delete can delete customer contacts" ON "customerContact"FOR DELETE- USING (coalesce(get_my_claim('sales_delete')::boolean, false) = true AND (get_my_claim('role'::text)) = '"employee"'::jsonb);+ USING (coalesce(get_my_claim('sales_delete')::boolean, false) = true AND has_role('employee'));-- supplierType@@ -298,19 +300,19 @@ ALTER TABLE "supplierType" ENABLE ROW LEVEL SECURITY;CREATE POLICY "Employees with purchasing_view can view supplier types" ON "supplierType"FOR SELECT- USING (coalesce(get_my_claim('purchasing_view')::boolean, false) = true AND (get_my_claim('role'::text)) = '"employee"'::jsonb);+ USING (coalesce(get_my_claim('purchasing_view')::boolean, false) = true AND has_role('employee'));CREATE POLICY "Employees with purchasing_create can create supplier types" ON "supplierType"FOR INSERT- WITH CHECK (coalesce(get_my_claim('purchasing_create')::boolean,false) AND (get_my_claim('role'::text)) = '"employee"'::jsonb);+ WITH CHECK (coalesce(get_my_claim('purchasing_create')::boolean,false) AND has_role('employee'));CREATE POLICY "Employees with purchasing_update can update supplier types" ON "supplierType"FOR UPDATE- USING (coalesce(get_my_claim('purchasing_update')::boolean,false) AND (get_my_claim('role'::text)) = '"employee"'::jsonb);+ USING (coalesce(get_my_claim('purchasing_update')::boolean,false) AND has_role('employee'));CREATE POLICY "Employees with purchasing_delete can delete supplier types" ON "supplierType"FOR DELETE- USING (coalesce(get_my_claim('purchasing_delete')::boolean, false) = true AND (get_my_claim('role'::text)) = '"employee"'::jsonb);+ USING (coalesce(get_my_claim('purchasing_delete')::boolean, false) = true AND has_role('employee'));-- supplier@@ -318,13 +320,13 @@ ALTER TABLE "supplier" ENABLE ROW LEVEL SECURITY;CREATE POLICY "Employees with purchasing_view can view supplier" ON "supplier"FOR SELECT- USING (coalesce(get_my_claim('purchasing_view')::boolean, false) = true AND (get_my_claim('role'::text)) = '"employee"'::jsonb);+ USING (coalesce(get_my_claim('purchasing_view')::boolean, false) = true AND has_role('employee'));CREATE POLICY "Suppliers with purchasing_view can their own organization" ON "supplier"FOR SELECTUSING (coalesce(get_my_claim('purchasing_view')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"supplier"'::jsonb+ AND has_role('supplier')AND id IN (SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid())@@ -332,17 +334,17 @@ CREATE POLICY "Suppliers with purchasing_view can their own organization" ON "suCREATE POLICY "Employees with purchasing_create can create suppliers" ON "supplier"FOR INSERT- WITH CHECK (coalesce(get_my_claim('purchasing_create')::boolean,false) AND (get_my_claim('role'::text)) = '"employee"'::jsonb);+ WITH CHECK (coalesce(get_my_claim('purchasing_create')::boolean,false) AND has_role('employee'));CREATE POLICY "Employees with purchasing_update can update suppliers" ON "supplier"FOR UPDATE- USING (coalesce(get_my_claim('purchasing_update')::boolean,false) AND (get_my_claim('role'::text)) = '"employee"'::jsonb);+ USING (coalesce(get_my_claim('purchasing_update')::boolean,false) AND has_role('employee'));CREATE POLICY "Suppliers with purchasing_update can their own organization" ON "supplier"FOR UPDATEUSING (coalesce(get_my_claim('purchasing_update')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"supplier"'::jsonb+ AND has_role('supplier')AND id IN (SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid())@@ -350,7 +352,7 @@ CREATE POLICY "Suppliers with purchasing_update can their own organization" ON "CREATE POLICY "Employees with purchasing_delete can delete suppliers" ON "supplier"FOR DELETE- USING (coalesce(get_my_claim('purchasing_delete')::boolean, false) = true AND (get_my_claim('role'::text)) = '"employee"'::jsonb);+ USING (coalesce(get_my_claim('purchasing_delete')::boolean, false) = true AND has_role('employee'));-- supplierContact@@ -358,13 +360,13 @@ ALTER TABLE "supplierContact" ENABLE ROW LEVEL SECURITY;CREATE POLICY "Employees with purchasing_view can view supplier contact" ON "supplierContact"FOR SELECT- USING (coalesce(get_my_claim('purchasing_view')::boolean, false) = true AND (get_my_claim('role'::text)) = '"employee"'::jsonb);+ USING (coalesce(get_my_claim('purchasing_view')::boolean, false) = true AND has_role('employee'));CREATE POLICY "Suppliers with purchasing_view can their own supplier contacts" ON "supplierContact"FOR SELECTUSING (coalesce(get_my_claim('purchasing_view')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"supplier"'::jsonb+ AND has_role('supplier')AND "supplierId" IN (SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid())@@ -372,12 +374,12 @@ CREATE POLICY "Suppliers with purchasing_view can their own supplier contacts" OCREATE POLICY "Employees with purchasing_create can create supplier contacts" ON "supplierContact"FOR INSERT- WITH CHECK (coalesce(get_my_claim('purchasing_create')::boolean,false) AND (get_my_claim('role'::text)) = '"employee"'::jsonb);+ WITH CHECK (coalesce(get_my_claim('purchasing_create')::boolean,false) AND has_role('employee'));CREATE POLICY "Suppliers with purchasing_create can create supplier contacts" ON "supplierContact"FOR INSERTWITH CHECK (coalesce(get_my_claim('purchasing_create')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"supplier"'::jsonb+ AND has_role('supplier')AND "supplierId" IN (SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid())@@ -385,12 +387,12 @@ CREATE POLICY "Suppliers with purchasing_create can create supplier contacts" ONCREATE POLICY "Employees with purchasing_update can update supplier contacts" ON "supplierContact"FOR UPDATE- USING (coalesce(get_my_claim('purchasing_update')::boolean,false) AND (get_my_claim('role'::text)) = '"employee"'::jsonb);+ USING (coalesce(get_my_claim('purchasing_update')::boolean,false) AND has_role('employee'));CREATE POLICY "Suppliers with purchasing_update can update their supplier contacts" ON "supplierContact"FOR UPDATEUSING (coalesce(get_my_claim('purchasing_update')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"supplier"'::jsonb+ AND has_role('supplier')AND "supplierId" IN (SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid())@@ -398,5 +400,5 @@ CREATE POLICY "Suppliers with purchasing_update can update their supplier contacCREATE POLICY "Employees with purchasing_delete can delete supplier contacts" ON "supplierContact"FOR DELETE- USING (coalesce(get_my_claim('purchasing_delete')::boolean, false) = true AND (get_my_claim('role'::text)) = '"employee"'::jsonb);+ USING (coalesce(get_my_claim('purchasing_delete')::boolean, false) = true AND has_role('employee'));