Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

refactor: migrations for multi-tenant - batch 13

Brad Barbin844176b7f9dd
diff --git a/apps/carbon/app/hooks/useUser.tsx b/apps/carbon/app/hooks/useUser.tsx
index 9352986542..7a9f3d5ae9 100644
--- a/apps/carbon/app/hooks/useUser.tsx
+++ b/apps/carbon/app/hooks/useUser.tsx
@@ -9,6 +9,12 @@ type PersonalData = {
avatarUrl: string | null;
};
+type Company = {
+ id: number;
+ name: string;
+ logo: string | null;
+};
+
type Groups = string[];
type Defaults = {
@@ -16,17 +22,21 @@ type Defaults = {
};
type User = PersonalData & {
+ company: Company;
groups: Groups;
defaults: Defaults;
};
export function useUser(): User {
const data = useRouteData<{
+ company: unknown;
user: unknown;
groups: unknown;
defaults: unknown;
}>(path.to.authenticatedRoot);
if (
+ data?.company &&
+ isCompany(data.company) &&
data?.user &&
isUser(data.user) &&
data?.groups &&
@@ -36,6 +46,7 @@ export function useUser(): User {
) {
return {
...data.user,
+ company: data.company,
groups: data.groups,
defaults: data.defaults,
};
@@ -46,6 +57,14 @@ export function useUser(): User {
);
}
+function isCompany(value: any): value is Company {
+ return (
+ typeof value.id === "number" &&
+ typeof value.name === "string" &&
+ (typeof value.logo === "string" || value.logo === null)
+ );
+}
+
function isDefaults(value: any): value is Defaults {
return typeof value.locationId === "string" || value.locationId === null;
}
diff --git a/apps/carbon/app/modules/purchasing/purchasing.service.ts b/apps/carbon/app/modules/purchasing/purchasing.service.ts
index 449394c590..d9c0a6e133 100644
--- a/apps/carbon/app/modules/purchasing/purchasing.service.ts
+++ b/apps/carbon/app/modules/purchasing/purchasing.service.ts
@@ -111,20 +111,22 @@ export async function deleteSupplierType(
export async function getPurchaseOrderExternalDocuments(
client: SupabaseClient<Database>,
+ companyId: number,
purchaseOrderId: string
) {
return client.storage
.from("private")
- .list(`purchasing/external/${purchaseOrderId}`);
+ .list(`${companyId}/purchasing/external/${purchaseOrderId}`);
}
export async function getPurchaseOrderInternalDocuments(
client: SupabaseClient<Database>,
+ companyId: number,
purchaseOrderId: string
) {
return client.storage
.from("private")
- .list(`purchasing/internal/${purchaseOrderId}`);
+ .list(`${companyId}/purchasing/internal/${purchaseOrderId}`);
}
export async function getPurchaseOrder(
@@ -723,6 +725,7 @@ export async function upsertPurchaseOrder(
"id" | "purchaseOrderId"
> & {
purchaseOrderId: string;
+ companyId: number;
createdBy: string;
customFields?: Json;
})
@@ -781,6 +784,7 @@ export async function upsertPurchaseOrder(
locationId: locationId,
shippingMethodId: shippingMethodId,
shippingTermId: shippingTermId,
+ companyId: purchaseOrder.companyId,
},
]),
client.from("purchaseOrderPayment").insert([
@@ -791,6 +795,7 @@ export async function upsertPurchaseOrder(
invoiceSupplierContactId: invoiceSupplierContactId,
invoiceSupplierLocationId: invoiceSupplierLocationId,
paymentTermId: paymentTermId,
+ companyId: purchaseOrder.companyId,
},
]),
]);
diff --git a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderDocuments/usePurchaseOrderDocuments.ts b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderDocuments/usePurchaseOrderDocuments.ts
index b04c5edd4a..c0b123c241 100644
--- a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderDocuments/usePurchaseOrderDocuments.ts
+++ b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderDocuments/usePurchaseOrderDocuments.ts
@@ -1,7 +1,7 @@
import { toast } from "@carbon/react";
import { useFetcher } from "@remix-run/react";
import { useCallback } from "react";
-import { usePermissions } from "~/hooks";
+import { usePermissions, useUser } from "~/hooks";
import { useSupabase } from "~/lib/supabase";
import type { PurchaseOrderAttachment } from "~/modules/purchasing/types";
@@ -14,6 +14,7 @@ export const usePurchaseOrderDocuments = ({ isExternal, orderId }: Props) => {
const fetcher = useFetcher();
const permissions = usePermissions();
const { supabase } = useSupabase();
+ const { id: companyId } = useUser();
const canDelete = permissions.can("delete", "purchasing"); // TODO: or is document owner
@@ -24,11 +25,11 @@ export const usePurchaseOrderDocuments = ({ isExternal, orderId }: Props) => {
const getPath = useCallback(
(attachment: PurchaseOrderAttachment) => {
- return `purchasing/${isExternal ? "external" : "internal"}/${orderId}/${
- attachment.name
- }`;
+ return `/${companyId}/purchasing/${
+ isExternal ? "external" : "internal"
+ }/${orderId}/${attachment.name}`;
},
- [isExternal, orderId]
+ [companyId, isExternal, orderId]
);
const deleteAttachment = useCallback(
diff --git a/apps/carbon/app/modules/sales/sales.service.ts b/apps/carbon/app/modules/sales/sales.service.ts
index 7f2221a185..ff8eb4723a 100644
--- a/apps/carbon/app/modules/sales/sales.service.ts
+++ b/apps/carbon/app/modules/sales/sales.service.ts
@@ -331,16 +331,22 @@ export async function getQuoteAssemblies(
export async function getQuoteExternalDocuments(
client: SupabaseClient<Database>,
+ companyId: number,
quoteId: string
) {
- return client.storage.from("private").list(`quote/external/${quoteId}`);
+ return client.storage
+ .from("private")
+ .list(`${companyId}/quote/external/${quoteId}`);
}
export async function getQuoteInternalDocuments(
client: SupabaseClient<Database>,
+ companyId: number,
quoteId: string
) {
- return client.storage.from("private").list(`quote/internal/${quoteId}`);
+ return client.storage
+ .from("private")
+ .list(`${companyId}/quote/internal/${quoteId}`);
}
export async function getQuoteLine(
@@ -998,18 +1004,22 @@ export async function deleteSalesOrderLine(
export async function getSalesOrderExternalDocuments(
client: SupabaseClient<Database>,
+ companyId: number,
salesOrderId: string
) {
- return client.storage.from("private").list(`sales/external/${salesOrderId}`);
+ return client.storage
+ .from("private")
+ .list(`${companyId}/sales/external/${salesOrderId}`);
}
/*export async function getSalesOrderInternalDocuments(
client: SupabaseClient<Database>,
+ companyId: number,
salesOrderId: string
) {
return client.storage
.from("private")
- .list(`sales/internal/${salesOrderId}`);
+ .list(`${companyId}/sales/internal/${salesOrderId}`);
}*/
export async function getSalesOrder(
@@ -1148,6 +1158,7 @@ export async function upsertSalesOrder(
salesOrder:
| (Omit<z.infer<typeof salesOrderValidator>, "id" | "salesOrderId"> & {
salesOrderId: string;
+ companyId: number;
createdBy: string;
customFields?: Json;
})
@@ -1203,6 +1214,7 @@ export async function upsertSalesOrder(
locationId: locationId,
shippingMethodId: shippingMethodId,
shippingTermId: shippingTermId,
+ companyId: salesOrder.companyId,
},
]),
client.from("salesOrderPayment").insert([
@@ -1213,6 +1225,7 @@ export async function upsertSalesOrder(
invoiceCustomerContactId: invoiceCustomerContactId,
invoiceCustomerLocationId: invoiceCustomerLocationId,
paymentTermId: paymentTermId,
+ companyId: salesOrder.companyId,
},
]),
]);
diff --git a/apps/carbon/app/modules/sales/ui/Quotation/QuotationDocuments/QuotationDocumentForm.tsx b/apps/carbon/app/modules/sales/ui/Quotation/QuotationDocuments/QuotationDocumentForm.tsx
index 2572660307..cca34f685e 100644
--- a/apps/carbon/app/modules/sales/ui/Quotation/QuotationDocuments/QuotationDocumentForm.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotation/QuotationDocuments/QuotationDocumentForm.tsx
@@ -2,6 +2,7 @@ import { File, toast } from "@carbon/react";
import { useSubmit } from "@remix-run/react";
import type { ChangeEvent } from "react";
import { IoMdAdd } from "react-icons/io";
+import { useUser } from "~/hooks";
import { useSupabase } from "~/lib/supabase";
import { path } from "~/utils/path";
@@ -16,13 +17,14 @@ const QuotationDocumentForm = ({
}: QuotationDocumentFormProps) => {
const submit = useSubmit();
const { supabase } = useSupabase();
+ const { id: companyId } = useUser();
const uploadFile = async (e: ChangeEvent<HTMLInputElement>) => {
if (e.target.files && supabase) {
const file = e.target.files[0];
- const fileName = `quote/${isExternal ? "external" : "internal"}/${id}/${
- file.name
- }`;
+ const fileName = `${companyId}/quote/${
+ isExternal ? "external" : "internal"
+ }/${id}/${file.name}`;
const fileUpload = await supabase.storage
.from("private")
diff --git a/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderDocuments/SalesOrderDocumentForm.tsx b/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderDocuments/SalesOrderDocumentForm.tsx
index 3ac06965cd..5d6d863cf2 100644
--- a/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderDocuments/SalesOrderDocumentForm.tsx
+++ b/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderDocuments/SalesOrderDocumentForm.tsx
@@ -2,6 +2,7 @@ import { File, toast } from "@carbon/react";
import { useSubmit } from "@remix-run/react";
import type { ChangeEvent } from "react";
import { IoMdAdd } from "react-icons/io";
+import { useUser } from "~/hooks";
import { useSupabase } from "~/lib/supabase";
import { path } from "~/utils/path";
@@ -16,11 +17,12 @@ const SalesOrderDocumentForm = ({
}: SalesOrderDocumentFormProps) => {
const submit = useSubmit();
const { supabase } = useSupabase();
+ const { id: companyId } = useUser();
const uploadFile = async (e: ChangeEvent<HTMLInputElement>) => {
if (e.target.files && supabase) {
const file = e.target.files[0];
- const fileName = `sales-order/${
+ const fileName = `${companyId}/sales-order/${
isExternal ? "external" : "internal"
}/${orderId}/${file.name}`;
diff --git a/apps/carbon/app/routes/x+/purchase-order+/$orderId.release.tsx b/apps/carbon/app/routes/x+/purchase-order+/$orderId.release.tsx
index 184d14dea4..a510a49fa2 100644
--- a/apps/carbon/app/routes/x+/purchase-order+/$orderId.release.tsx
+++ b/apps/carbon/app/routes/x+/purchase-order+/$orderId.release.tsx
@@ -68,7 +68,7 @@ export async function action(args: ActionFunctionArgs) {
.toISOString()
.slice(0, -5)}.pdf`;
- const documentFilePath = `purchasing/external/${orderId}/${fileName}`;
+ const documentFilePath = `${companyId}/purchasing/external/${orderId}/${fileName}`;
const documentFileUpload = await client.storage
.from("private")
diff --git a/apps/carbon/app/routes/x+/quote+/$id.release.tsx b/apps/carbon/app/routes/x+/quote+/$id.release.tsx
index d9543799a5..963a6dce9a 100644
--- a/apps/carbon/app/routes/x+/quote+/$id.release.tsx
+++ b/apps/carbon/app/routes/x+/quote+/$id.release.tsx
@@ -62,7 +62,7 @@ export async function action(args: ActionFunctionArgs) {
.toISOString()
.slice(0, -5)}.pdf`;
- const documentFilePath = `quote/internal/${id}/${fileName}`;
+ const documentFilePath = `${companyId}/quote/internal/${id}/${fileName}`;
const documentFileUpload = await client.storage
.from("private")
diff --git a/packages/database/supabase/migrations/20230629113514_purchasing-files.sql b/packages/database/supabase/migrations/20230629113514_purchasing-files.sql
index ab8f2b7755..786855bb6c 100644
--- a/packages/database/supabase/migrations/20230629113514_purchasing-files.sql
+++ b/packages/database/supabase/migrations/20230629113514_purchasing-files.sql
@@ -1,92 +1,91 @@
-INSERT INTO storage.buckets (id, name, public)
-VALUES
- ('purchasing-internal', 'purchasing-internal', false),
- ('purchasing-external', 'purchasing-external', false);
-
-- Internal purchasing documents
CREATE POLICY "Internal purchasing documents view requires purchasing_view" ON storage.objects
FOR SELECT USING (
- bucket_id = 'purchasing-internal'
- AND (auth.role() = 'authenticated')
- AND coalesce(get_my_claim('purchasing_view')::boolean, false) = true
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ bucket_id = 'private'
+ AND has_role('employee')
+ AND (storage.foldername(name))[1] = ANY(
+ get_permission_companies_as_text('purchasing_view')
+ )
+ AND (storage.foldername(name))[2] = 'purchasing'
+ AND (storage.foldername(name))[3] = 'internal'
);
CREATE POLICY "Internal purchasing documents insert requires purchasing_create" ON storage.objects
FOR INSERT WITH CHECK (
- bucket_id = 'purchasing-internal'
- AND (auth.role() = 'authenticated')
- AND coalesce(get_my_claim('purchasing_create')::boolean, false) = true
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ bucket_id = 'private'
+ AND has_role('employee')
+ AND (storage.foldername(name))[1] = ANY(
+ get_permission_companies_as_text('purchasing_create')
+ )
+ AND (storage.foldername(name))[2] = 'purchasing'
+ AND (storage.foldername(name))[3] = 'internal'
);
CREATE POLICY "Internal purchasing documents update requires purchasing_update" ON storage.objects
FOR UPDATE USING (
- bucket_id = 'purchasing-internal'
- AND (auth.role() = 'authenticated')
- AND coalesce(get_my_claim('purchasing_update')::boolean, false) = true
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ bucket_id = 'private'
+ AND has_role('employee')
+ AND (storage.foldername(name))[1] = ANY(
+ get_permission_companies_as_text('purchasing_update')
+ )
+ AND (storage.foldername(name))[2] = 'purchasing'
+ AND (storage.foldername(name))[3] = 'internal'
);
CREATE POLICY "Internal purchasing documents delete requires purchasing_delete" ON storage.objects
FOR DELETE USING (
- bucket_id = 'purchasing-internal'
- AND (auth.role() = 'authenticated')
- AND coalesce(get_my_claim('purchasing_delete')::boolean, false) = true
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ bucket_id = 'private'
+ AND has_role('employee')
+ AND (storage.foldername(name))[1] = ANY(
+ get_permission_companies_as_text('purchasing_delete')
+ )
+ AND (storage.foldername(name))[2] = 'purchasing'
+ AND (storage.foldername(name))[3] = 'internal'
);
-- External purchasing documents
CREATE POLICY "External purchasing documents view requires purchasing_view" ON storage.objects
FOR SELECT USING (
- bucket_id = 'purchasing-external'
- AND (auth.role() = 'authenticated')
- AND coalesce(get_my_claim('purchasing_view')::boolean, false) = true
- AND (
- (get_my_claim('role'::text)) = '"employee"'::jsonb OR
- (
- (get_my_claim('role'::text)) = '"supplier"'::jsonb
- )
- )
+ bucket_id = 'private'
+ AND has_role('employee')
+ AND (storage.foldername(name))[1] = ANY(
+ get_permission_companies_as_text('purchasing_view')
+ )
+ AND (storage.foldername(name))[2] = 'purchasing'
+ AND (storage.foldername(name))[3] = 'external'
);
-CREATE POLICY "External purchasing documents insert requires purchasing_view" ON storage.objects
+CREATE POLICY "External purchasing documents insert requires purchasing_create" ON storage.objects
FOR INSERT WITH CHECK (
- bucket_id = 'purchasing-external'
- AND (auth.role() = 'authenticated')
- AND coalesce(get_my_claim('purchasing_view')::boolean, false) = true
- AND (
- (get_my_claim('role'::text)) = '"employee"'::jsonb OR
- (
- (get_my_claim('role'::text)) = '"supplier"'::jsonb
- )
- )
+ bucket_id = 'private'
+ AND has_role('employee')
+ AND (storage.foldername(name))[1] = ANY(
+ get_permission_companies_as_text('purchasing_create')
+ )
+ AND (storage.foldername(name))[2] = 'purchasing'
+ AND (storage.foldername(name))[3] = 'external'
);
CREATE POLICY "External purchasing documents update requires purchasing_update" ON storage.objects
FOR UPDATE USING (
- bucket_id = 'purchasing-external'
- AND (auth.role() = 'authenticated')
- AND coalesce(get_my_claim('purchasing_update')::boolean, false) = true
- AND (
- (get_my_claim('role'::text)) = '"employee"'::jsonb OR
- (
- (get_my_claim('role'::text)) = '"supplier"'::jsonb
- )
- )
+ bucket_id = 'private'
+ AND has_role('employee')
+ AND (storage.foldername(name))[1] = ANY(
+ get_permission_companies_as_text('purchasing_update')
+ )
+ AND (storage.foldername(name))[2] = 'purchasing'
+ AND (storage.foldername(name))[3] = 'external'
);
CREATE POLICY "External purchasing documents delete requires purchasing_delete" ON storage.objects
FOR DELETE USING (
- bucket_id = 'purchasing-external'
- AND (auth.role() = 'authenticated')
- AND coalesce(get_my_claim('purchasing_delete')::boolean, false) = true
- AND (
- (get_my_claim('role'::text)) = '"employee"'::jsonb OR
- (
- (get_my_claim('role'::text)) = '"supplier"'::jsonb
- )
- )
+ bucket_id = 'private'
+ AND has_role('employee')
+ AND (storage.foldername(name))[1] = ANY(
+ get_permission_companies_as_text('purchasing_delete')
+ )
+ AND (storage.foldername(name))[2] = 'purchasing'
+ AND (storage.foldername(name))[3] = 'external'
);
\ No newline at end of file
diff --git a/packages/database/supabase/migrations/20230702114301_purchasing-rls.sql b/packages/database/supabase/migrations/20230702114301_purchasing-rls.sql
index 4d34590eb4..a5ab57e351 100644
--- a/packages/database/supabase/migrations/20230702114301_purchasing-rls.sql
+++ b/packages/database/supabase/migrations/20230702114301_purchasing-rls.sql
@@ -4,16 +4,17 @@ CREATE POLICY "Employees with purchasing_view, inventory_view, or invoicing_view
FOR SELECT
USING (
(
- coalesce(get_my_claim('purchasing_view')::boolean, false) = true OR
- coalesce(get_my_claim('inventory_view')::boolean, false) = true OR
- coalesce(get_my_claim('invoicing_view')::boolean, false) = true
- ) AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
+ has_company_permission('purchasing_view', "companyId") OR
+ has_company_permission('inventory_view', "companyId") OR
+ has_company_permission('invoicing_view', "companyId")
+ ) AND has_role('employee')
+ );
CREATE POLICY "Suppliers with purchasing_view can their own purchase orders" ON "purchaseOrder"
FOR SELECT
USING (
- coalesce(get_my_claim('purchasing_view')::boolean, false) = true
- AND (get_my_claim('role'::text)) = '"supplier"'::jsonb
+ has_company_permission('purchasing_view', "companyId")
+ AND has_role('supplier')
AND "supplierId" IN (
SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
)
@@ -21,18 +22,18 @@ CREATE POLICY "Suppliers with purchasing_view can their own purchase orders" ON
CREATE POLICY "Employees with purchasing_create can create purchase orders" ON "purchaseOrder"
FOR INSERT
- WITH CHECK (coalesce(get_my_claim('purchasing_create')::boolean,false) AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
+ WITH CHECK (has_company_permission('purchasing_create', "companyId") AND has_role('employee'));
CREATE POLICY "Employees with purchasing_update can update purchase orders" ON "purchaseOrder"
FOR UPDATE
- USING (coalesce(get_my_claim('purchasing_update')::boolean,false) AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
+ USING (has_company_permission('purchasing_update', "companyId") AND has_role('employee'));
CREATE POLICY "Suppliers with purchasing_update can their own purchase orders" ON "purchaseOrder"
FOR UPDATE
USING (
- coalesce(get_my_claim('purchasing_update')::boolean, false) = true
- AND (get_my_claim('role'::text)) = '"supplier"'::jsonb
+ has_company_permission('purchasing_update', "companyId")
+ AND has_role('supplier')
AND "supplierId" IN (
SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
)
@@ -40,14 +41,14 @@ CREATE POLICY "Suppliers with purchasing_update can their own purchase orders" O
CREATE POLICY "Employees with purchasing_delete can delete purchase orders" ON "purchaseOrder"
FOR DELETE
- USING (coalesce(get_my_claim('purchasing_delete')::boolean, false) = true AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
+ USING (has_company_permission('purchasing_delete', "companyId") AND has_role('employee'));
CREATE POLICY "Suppliers with purchasing_view can search for their own purchase orders" ON "search"
FOR SELECT
USING (
- coalesce(get_my_claim('purchasing_view')::boolean, false) = true
- AND (get_my_claim('role'::text)) = '"supplier"'::jsonb
+ has_company_permission('purchasing_view', "companyId")
+ AND has_role('supplier')
AND entity = 'Purchase Order'
AND uuid IN (
SELECT id FROM "purchaseOrder" WHERE "supplierId" IN (
@@ -107,7 +108,10 @@ ALTER TABLE "purchaseOrderStatusHistory" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Anyone with purchasing_view can view purchase order status history" ON "purchaseOrderStatusHistory"
FOR SELECT
- USING (coalesce(get_my_claim('purchasing_view')::boolean, false) = true);
+ USING (
+ has_role('employee') AND
+ has_company_permission('purchasing_view', (SELECT "companyId" FROM "purchaseOrder" WHERE id = "purchaseOrderId"))
+ );
-- Purchase Order Lines
@@ -115,13 +119,13 @@ ALTER TABLE "purchaseOrderLine" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with purchasing_view can view purchase order lines" ON "purchaseOrderLine"
FOR SELECT
- USING (coalesce(get_my_claim('purchasing_view')::boolean, false) = true AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
+ USING (has_company_permission('purchasing_view', "companyId") AND has_role('employee'));
CREATE POLICY "Suppliers with purchasing_view can their own purchase order lines" ON "purchaseOrderLine"
FOR SELECT
USING (
- coalesce(get_my_claim('purchasing_view')::boolean, false) = true
- AND (get_my_claim('role'::text)) = '"supplier"'::jsonb
+ has_company_permission('purchasing_view', "companyId")
+ AND has_role('supplier')
AND "purchaseOrderId" IN (
SELECT id FROM "purchaseOrder" WHERE "supplierId" IN (
SELECT "supplierId" FROM "purchaseOrder" WHERE "supplierId" IN (
@@ -133,13 +137,13 @@ CREATE POLICY "Suppliers with purchasing_view can their own purchase order lines
CREATE POLICY "Employees with purchasing_create can create purchase order lines" ON "purchaseOrderLine"
FOR INSERT
- WITH CHECK (coalesce(get_my_claim('purchasing_create')::boolean,false) AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
+ WITH CHECK (has_company_permission('purchasing_create', "companyId") AND has_role('employee'));
CREATE POLICY "Suppliers with purchasing_create can create lines on their own purchase order" ON "purchaseOrderLine"
FOR INSERT
WITH CHECK (
- coalesce(get_my_claim('purchasing_create')::boolean, false) = true
- AND (get_my_claim('role'::text)) = '"supplier"'::jsonb
+ has_company_permission('purchasing_create', "companyId")
+ AND has_role('supplier')
AND "purchaseOrderId" IN (
SELECT id FROM "purchaseOrder" WHERE "supplierId" IN (
SELECT "supplierId" FROM "purchaseOrder" WHERE "supplierId" IN (
@@ -151,13 +155,13 @@ CREATE POLICY "Suppliers with purchasing_create can create lines on their own pu
CREATE POLICY "Employees with purchasing_update can update purchase order lines" ON "purchaseOrderLine"
FOR UPDATE
- USING (coalesce(get_my_claim('purchasing_update')::boolean,false) AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
+ USING (has_company_permission('purchasing_update', "companyId") AND has_role('employee'));
CREATE POLICY "Suppliers with purchasing_update can their own purchase order lines" ON "purchaseOrderLine"
FOR UPDATE
USING (
- coalesce(get_my_claim('purchasing_update')::boolean, false) = true
- AND (get_my_claim('role'::text)) = '"supplier"'::jsonb
+ has_company_permission('purchasing_update', "companyId")
+ AND has_role('supplier')
AND "purchaseOrderId" IN (
SELECT id FROM "purchaseOrder" WHERE "supplierId" IN (
SELECT "supplierId" FROM "purchaseOrder" WHERE "supplierId" IN (
@@ -169,13 +173,13 @@ CREATE POLICY "Suppliers with purchasing_update can their own purchase order lin
CREATE POLICY "Employees with purchasing_delete can delete purchase order lines" ON "purchaseOrderLine"
FOR DELETE
- USING (coalesce(get_my_claim('purchasing_delete')::boolean, false) = true AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
+ USING (has_company_permission('purchasing_delete', "companyId") AND has_role('employee'));
CREATE POLICY "Suppliers with purchasing_delete can delete lines on their own purchase order" ON "purchaseOrderLine"
FOR DELETE
USING (
- coalesce(get_my_claim('purchasing_delete')::boolean, false) = true
- AND (get_my_claim('role'::text)) = '"supplier"'::jsonb
+ has_company_permission('purchasing_delete', "companyId")
+ AND has_role('supplier')
AND "purchaseOrderId" IN (
SELECT id FROM "purchaseOrder" WHERE "supplierId" IN (
SELECT "supplierId" FROM "purchaseOrder" WHERE "supplierId" IN (
@@ -192,13 +196,13 @@ ALTER TABLE "purchaseOrderDelivery" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with purchasing_view can view purchase order deliveries" ON "purchaseOrderDelivery"
FOR SELECT
- USING (coalesce(get_my_claim('purchasing_view')::boolean, false) = true AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
+ USING (has_company_permission('purchasing_view', "companyId") AND has_role('employee'));
CREATE POLICY "Suppliers with purchasing_view can their own purchase order deliveries" ON "purchaseOrderDelivery"
FOR SELECT
USING (
- coalesce(get_my_claim('purchasing_view')::boolean, false) = true
- AND (get_my_claim('role'::text)) = '"supplier"'::jsonb
+ has_company_permission('purchasing_view', "companyId")
+ AND has_role('supplier')
AND id IN (
SELECT id FROM "purchaseOrder" WHERE "supplierId" IN (
SELECT "supplierId" FROM "purchaseOrder" WHERE "supplierId" IN (
@@ -210,17 +214,17 @@ CREATE POLICY "Suppliers with purchasing_view can their own purchase order deliv
CREATE POLICY "Employees with purchasing_create can create purchase order deliveries" ON "purchaseOrderDelivery"
FOR INSERT
- WITH CHECK (coalesce(get_my_claim('purchasing_create')::boolean,false) AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
+ WITH CHECK (has_company_permission('purchasing_create', "companyId") AND has_role('employee'));
CREATE POLICY "Employees with purchasing_update can update purchase order deliveries" ON "purchaseOrderDelivery"
FOR UPDATE
- USING (coalesce(get_my_claim('purchasing_update')::boolean,false) AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
+ USING (has_company_permission('purchasing_update', "companyId") AND has_role('employee'));
CREATE POLICY "Suppliers with purchasing_update can their own purchase order deliveries" ON "purchaseOrderDelivery"
FOR UPDATE
USING (
- coalesce(get_my_claim('purchasing_update')::boolean, false) = true
- AND (get_my_claim('role'::text)) = '"supplier"'::jsonb
+ has_company_permission('purchasing_update', "companyId")
+ AND has_role('supplier')
AND id IN (
SELECT id FROM "purchaseOrder" WHERE "supplierId" IN (
SELECT "supplierId" FROM "purchaseOrder" WHERE "supplierId" IN (
@@ -232,7 +236,7 @@ CREATE POLICY "Suppliers with purchasing_update can their own purchase order del
CREATE POLICY "Employees with purchasing_delete can delete purchase order deliveries" ON "purchaseOrderDelivery"
FOR DELETE
- USING (coalesce(get_my_claim('purchasing_delete')::boolean, false) = true AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
+ USING (has_company_permission('purchasing_delete', "companyId") AND has_role('employee'));
-- Purchase Order Payments
@@ -241,16 +245,16 @@ ALTER TABLE "purchaseOrderPayment" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with purchasing_view can view purchase order payments" ON "purchaseOrderPayment"
FOR SELECT
- USING (coalesce(get_my_claim('purchasing_view')::boolean, false) = true AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
+ USING (has_company_permission('purchasing_view', "companyId") AND has_role('employee'));
CREATE POLICY "Employees with purchasing_create can create purchase order payments" ON "purchaseOrderPayment"
FOR INSERT
- WITH CHECK (coalesce(get_my_claim('purchasing_create')::boolean,false) AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
+ WITH CHECK (has_company_permission('purchasing_create', "companyId") AND has_role('employee'));
CREATE POLICY "Employees with purchasing_update can update purchase order payments" ON "purchaseOrderPayment"
FOR UPDATE
- USING (coalesce(get_my_claim('purchasing_update')::boolean,false) AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
+ USING (has_company_permission('purchasing_update', "companyId") AND has_role('employee'));
CREATE POLICY "Employees with purchasing_delete can delete purchase order payments" ON "purchaseOrderPayment"
FOR DELETE
- USING (coalesce(get_my_claim('purchasing_delete')::boolean, false) = true AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
+ USING (has_company_permission('purchasing_delete', "companyId") AND has_role('employee'));
diff --git a/packages/database/supabase/migrations/20240330054035_purchasing-documents.sql b/packages/database/supabase/migrations/20240330054035_purchasing-documents.sql
index 05872f7fb4..9e0b48ca5f 100644
--- a/packages/database/supabase/migrations/20240330054035_purchasing-documents.sql
+++ b/packages/database/supabase/migrations/20240330054035_purchasing-documents.sql
@@ -1,144 +1,39 @@
--- these policies were taken from the purchasing-files migration
-ALTER POLICY "Internal purchasing documents view requires purchasing_view" ON storage.objects
-USING (
- bucket_id = 'private'
- AND (auth.role() = 'authenticated')
- AND coalesce(get_my_claim('purchasing_view')::boolean, false) = true
- AND (storage.foldername(name))[1] = 'purchasing'
- AND (storage.foldername(name))[2] = 'internal'
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
-);
-
-ALTER POLICY "Internal purchasing documents insert requires purchasing_create" ON storage.objects
-WITH CHECK (
- bucket_id = 'private'
- AND (auth.role() = 'authenticated')
- AND coalesce(get_my_claim('purchasing_create')::boolean, false) = true
- AND (storage.foldername(name))[1] = 'purchasing'
- AND (storage.foldername(name))[2] = 'internal'
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
-);
-
-
-
-ALTER POLICY "Internal purchasing documents update requires purchasing_update" ON storage.objects
-USING (
- bucket_id = 'private'
- AND (auth.role() = 'authenticated')
- AND coalesce(get_my_claim('purchasing_update')::boolean, false) = true
- AND (storage.foldername(name))[1] = 'purchasing'
- AND (storage.foldername(name))[2] = 'internal'
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
-);
-
-
-ALTER POLICY "Internal purchasing documents delete requires purchasing_delete" ON storage.objects
-USING (
- bucket_id = 'private'
- AND (auth.role() = 'authenticated')
- AND coalesce(get_my_claim('purchasing_delete')::boolean, false) = true
- AND (storage.foldername(name))[1] = 'purchasing'
- AND (storage.foldername(name))[2] = 'internal'
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
-);
-
-DELETE FROM storage.objects WHERE bucket_id = 'purchasing-internal';
-DELETE FROM storage.buckets WHERE id = 'purchasing-internal';
-
-
--- External purchasing storage
-
-ALTER POLICY "External purchasing documents view requires purchasing_view" ON storage.objects
-USING (
- bucket_id = 'private'
- AND (auth.role() = 'authenticated')
- AND coalesce(get_my_claim('purchasing_view')::boolean, false) = true
- AND (storage.foldername(name))[1] = 'purchasing'
- AND (storage.foldername(name))[2] = 'external'
- AND (
- (get_my_claim('role'::text)) = '"employee"'::jsonb OR
- (
- (get_my_claim('role'::text)) = '"supplier"'::jsonb
- )
- )
-);
-
-ALTER POLICY "External purchasing documents insert requires purchasing_view" ON storage.objects
-WITH CHECK (
- bucket_id = 'private'
- AND (auth.role() = 'authenticated')
- AND coalesce(get_my_claim('purchasing_view')::boolean, false) = true
- AND (storage.foldername(name))[1] = 'purchasing'
- AND (storage.foldername(name))[2] = 'external'
- AND (
- (get_my_claim('role'::text)) = '"employee"'::jsonb OR
- (
- (get_my_claim('role'::text)) = '"supplier"'::jsonb
- )
- )
-);
-
-ALTER POLICY "External purchasing documents update requires purchasing_update" ON storage.objects
-USING (
- bucket_id = 'private'
- AND (auth.role() = 'authenticated')
- AND coalesce(get_my_claim('purchasing_update')::boolean, false) = true
- AND (storage.foldername(name))[1] = 'purchasing'
- AND (storage.foldername(name))[2] = 'external'
- AND (
- (get_my_claim('role'::text)) = '"employee"'::jsonb OR
- (
- (get_my_claim('role'::text)) = '"supplier"'::jsonb
- )
- )
-);
-
-ALTER POLICY "External purchasing documents delete requires purchasing_delete" ON storage.objects
-USING (
- bucket_id = 'private'
- AND (auth.role() = 'authenticated')
- AND coalesce(get_my_claim('purchasing_delete')::boolean, false) = true
- AND (storage.foldername(name))[1] = 'purchasing'
- AND (storage.foldername(name))[2] = 'external'
- AND (
- (get_my_claim('role'::text)) = '"employee"'::jsonb OR
- (
- (get_my_claim('role'::text)) = '"supplier"'::jsonb
- )
- )
-);
-
-DELETE FROM storage.objects WHERE bucket_id = 'purchasing-external';
-DELETE FROM storage.buckets WHERE id = 'purchasing-external';
-
-- Internal purchasing documents view
CREATE POLICY "Users with purchasing_view can view documents that start with purchasing" ON "document"
FOR SELECT USING (
- coalesce(get_my_claim('purchasing_view')::boolean, false) = true
- AND (path LIKE 'purchasing%')
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ has_role('employee')
+ AND (storage.foldername(path))[1] = ANY(
+ get_permission_companies_as_text('purchasing_view')
+ )
+ AND (storage.foldername(path))[2] = 'purchasing'
);
CREATE POLICY "Users with purchasing_create can create documents that start with purchasing" ON "document"
FOR INSERT WITH CHECK (
- coalesce(get_my_claim('purchasing_create')::boolean, false) = true
- AND (path LIKE 'purchasing%')
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ has_role('employee')
+ AND (storage.foldername(path))[1] = ANY(
+ get_permission_companies_as_text('purchasing_create')
+ )
+ AND (storage.foldername(path))[2] = 'purchasing'
);
CREATE POLICY "Users with purchasing_update can update documents that start with purchasing" ON "document"
FOR UPDATE USING (
- coalesce(get_my_claim('purchasing_update')::boolean, false) = true
- AND (path LIKE 'purchasing%')
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ has_role('employee')
+ AND (storage.foldername(path))[1] = ANY(
+ get_permission_companies_as_text('purchasing_update')
+ )
+ AND (storage.foldername(path))[2] = 'purchasing'
);
CREATE POLICY "Users with purchasing_delete can delete documents that start with purchasing" ON "document"
FOR DELETE USING (
- coalesce(get_my_claim('purchasing_delete')::boolean, false) = true
- AND (path LIKE 'purchasing%')
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ has_role('employee')
+ AND (storage.foldername(path))[1] = ANY(
+ get_permission_companies_as_text('purchasing_delete')
+ )
+ AND (storage.foldername(path))[2] = 'purchasing'
);
-- TODO: policies for suppliers