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.

feat: role-per-company

Brad Barbin59118add1b3d
diff --git a/README.md b/README.md
index 3bfb040d53..10ffc5b700 100644
--- a/README.md
+++ b/README.md
@@ -149,7 +149,7 @@ $ npm run dev # npm run dev in all apps & packages
You can now sign in with:
password: carbon
Go ahead and create your own user account
diff --git a/apps/carbon/app/modules/items/ui/useItemsSubmodules.tsx b/apps/carbon/app/modules/items/ui/useItemsSubmodules.tsx
index 4129a55746..7db1a1c669 100644
--- a/apps/carbon/app/modules/items/ui/useItemsSubmodules.tsx
+++ b/apps/carbon/app/modules/items/ui/useItemsSubmodules.tsx
@@ -57,11 +57,13 @@ const itemsRoutes: AuthenticatedRouteGroup[] = [
name: "Shapes",
to: path.to.materialForms,
icon: <LuShapes />,
+ role: "employee",
},
{
name: "Substances",
to: path.to.materialSubstances,
icon: <GiWoodBeam />,
+ role: "employee",
},
{
name: "Posting Groups",
diff --git a/apps/carbon/app/modules/purchasing/purchasing.models.ts b/apps/carbon/app/modules/purchasing/purchasing.models.ts
index 768543493d..176f608ddf 100644
--- a/apps/carbon/app/modules/purchasing/purchasing.models.ts
+++ b/apps/carbon/app/modules/purchasing/purchasing.models.ts
@@ -168,54 +168,6 @@ export const purchaseOrderReleaseValidator = z
}
);
-export const requestForQuoteStatusType = [
- "Draft",
- "Sent",
- "Expired",
- "Closed",
-] as const;
-
-export const requestForQuoteValidator = z.object({
- id: zfd.text(z.string().optional()),
- name: z.string().min(1, { message: "Name is required" }),
- status: z.enum(requestForQuoteStatusType).optional(),
- notes: zfd.text(z.string().optional()),
- receiptDate: z.string().min(1, { message: "Receipt Date is required" }),
- expirationDate: zfd.text(z.string().optional()),
- locationId: zfd.text(z.string().optional()),
-});
-
-export const requestForQuoteLineValidator = z.object({
- id: zfd.text(z.string().optional()),
- requestForQuoteId: z.string().min(36, { message: "Request is required" }),
- itemId: zfd.text(z.string().optional()),
- description: zfd.text(z.string().optional()),
- quantity: zfd.numeric(z.number()),
- unitPrice: zfd.numeric(z.number().optional()),
- unitOfMeasureCode: zfd.text(z.string().optional()),
- locationId: zfd.text(z.string().optional()),
- shelfId: zfd.text(z.string().optional()),
-});
-
-export const requestForQuoteSupplierValidator = z.object({
- id: zfd.text(z.string().optional()),
- requestForQuoteId: z.string().min(36, { message: "Request is required" }),
- supplierId: z.string().min(36, { message: "Supplier is required" }),
- supplierLocationId: zfd.text(z.string().optional()),
- supplierContactId: zfd.text(z.string().optional()),
-});
-
-export const requestForQuoteSupplierLineValidator = z.object({
- id: zfd.text(z.string().optional()),
- requestForQuoteSupplierId: z.string().min(36, {
- message: "Request supplier is required",
- }),
- requestForQuoteLineId: z.string().min(36, {
- message: "Request line is required",
- }),
- unitPrice: zfd.numeric(z.number().optional()),
-});
-
export const supplierValidator = z.object({
id: zfd.text(z.string().optional()),
name: z.string().min(1, { message: "Name is required" }),
diff --git a/apps/carbon/app/modules/purchasing/purchasing.service.ts b/apps/carbon/app/modules/purchasing/purchasing.service.ts
index 8ec08a2be0..16f6141097 100644
--- a/apps/carbon/app/modules/purchasing/purchasing.service.ts
+++ b/apps/carbon/app/modules/purchasing/purchasing.service.ts
@@ -11,7 +11,6 @@ import type {
purchaseOrderLineValidator,
purchaseOrderPaymentValidator,
purchaseOrderValidator,
- requestForQuoteValidator,
supplierContactValidator,
supplierPaymentValidator,
supplierShippingValidator,
@@ -54,23 +53,6 @@ export async function deletePurchaseOrderLine(
.eq("id", purchaseOrderLineId);
}
-export async function deleteRequestForQuote(
- client: SupabaseClient<Database>,
- requestForQuoteId: string
-) {
- return client.from("requestForQuote").delete().eq("id", requestForQuoteId);
-}
-
-export async function deleteRequestForQuoteLine(
- client: SupabaseClient<Database>,
- requestForQuoteLineId: string
-) {
- return client
- .from("requestForQuoteLine")
- .delete()
- .eq("id", requestForQuoteLineId);
-}
-
export async function deleteSupplierContact(
client: SupabaseClient<Database>,
supplierId: string,
@@ -238,31 +220,6 @@ export async function getPurchaseOrderSuppliers(
.order("name");
}
-export async function getRequestsForQuotes(
- client: SupabaseClient<Database>,
- companyId: string,
- args: GenericQueryFilters & {
- search: string | null;
- }
-) {
- let query = client
- .from("requestForQuotes")
- .select("*", { count: "exact" })
- .eq("companyId", companyId);
-
- if (args.search) {
- query = query.or(
- `id.ilike.%${args.search}%,requestForQuoteId.ilike.%${args.search}%,name.ilike.%${args.search}%`
- );
- }
-
- query = setGenericQueryFilters(query, args, [
- { column: "favorite", ascending: false },
- { column: "id", ascending: false },
- ]);
- return query;
-}
-
export async function getSupplier(
client: SupabaseClient<Database>,
supplierId: string
@@ -609,28 +566,6 @@ export async function updatePurchaseOrderFavorite(
}
}
-export async function updateRequestForQuoteFavorite(
- client: SupabaseClient<Database>,
- args: {
- id: string;
- favorite: boolean;
- userId: string;
- }
-) {
- const { id, favorite, userId } = args;
- if (!favorite) {
- return client
- .from("requestForQuoteFavorite")
- .delete()
- .eq("requestForQuoteId", id)
- .eq("userId", userId);
- } else {
- return client
- .from("requestForQuoteFavorite")
- .insert({ requestForQuoteId: id, userId: userId });
- }
-}
-
export async function upsertSupplier(
client: SupabaseClient<Database>,
supplier:
@@ -925,44 +860,6 @@ export async function upsertPurchaseOrderPayment(
.single();
}
-export async function upsertRequestForQuote(
- client: SupabaseClient<Database>,
- requestForQuote:
- | (Omit<
- z.infer<typeof requestForQuoteValidator>,
- "id" | "requestForQuoteId"
- > & {
- requestForQuoteId: string;
- companyId: string;
- createdBy: string;
- customFields?: Json;
- })
- | (Omit<
- z.infer<typeof requestForQuoteValidator>,
- "id" | "requestForQuoteId"
- > & {
- id: string;
- requestForQuoteId: string;
- updatedBy: string;
- customFields?: Json;
- })
-) {
- if ("createdBy" in requestForQuote) {
- return client
- .from("requestForQuote")
- .insert([requestForQuote])
- .select("id, requestForQuoteId");
- } else {
- return client
- .from("requestForQuote")
- .update({
- ...sanitize(requestForQuote),
- updatedAt: today(getLocalTimeZone()).toString(),
- })
- .eq("id", requestForQuote.id);
- }
-}
-
export async function upsertSupplierStatus(
client: SupabaseClient<Database>,
supplierStatus:
diff --git a/apps/carbon/app/modules/purchasing/ui/RequestForQuote/RequestForQuoteForm.tsx b/apps/carbon/app/modules/purchasing/ui/RequestForQuote/RequestForQuoteForm.tsx
deleted file mode 100644
index 487e7ac1cf..0000000000
--- a/apps/carbon/app/modules/purchasing/ui/RequestForQuote/RequestForQuoteForm.tsx
+++ /dev/null
@@ -1,113 +0,0 @@
-import {
- Card,
- CardContent,
- CardDescription,
- CardFooter,
- CardHeader,
- CardTitle,
- VStack,
- cn,
-} from "@carbon/react";
-import { ValidatedForm } from "@carbon/remix-validated-form";
-import type { z } from "zod";
-import {
- CustomFormFields,
- DatePicker,
- Hidden,
- Input,
- Location,
- Select,
- Submit,
- TextArea,
-} from "~/components/Form";
-import { usePermissions } from "~/hooks";
-import {
- requestForQuoteStatusType,
- requestForQuoteValidator,
-} from "~/modules/purchasing";
-
-type RequestForQuoteFormValues = z.infer<typeof requestForQuoteValidator>;
-
-type RequestForQuoteFormProps = {
- initialValues: RequestForQuoteFormValues;
-};
-
-const RequestForQuoteForm = ({ initialValues }: RequestForQuoteFormProps) => {
- const permissions = usePermissions();
-
- const isEditing = initialValues.id !== undefined;
- const isSupplier = permissions.is("supplier");
-
- const statusOptions = requestForQuoteStatusType.map((status) => ({
- label: status,
- value: status,
- }));
-
- return (
- <ValidatedForm
- method="post"
- validator={requestForQuoteValidator}
- defaultValues={initialValues}
- >
- <Card>
- <CardHeader>
- <CardTitle>
- {isEditing ? "Request for Quote" : "New Request for Quote"}
- </CardTitle>
- {!isEditing && (
- <CardDescription>
- A request for quote is a document that asks suppliers to provide
- price quotes for the purchase of goods or services.
- </CardDescription>
- )}
- </CardHeader>
- <CardContent>
- <Hidden name="requestForQuoteId" />
- <VStack>
- <div
- className={cn(
- "grid w-full gap-x-8 gap-y-4",
- isEditing ? "grid-cols-1 lg:grid-cols-3" : "grid-cols-2"
- )}
- >
- <Input autoFocus={!isEditing} name="name" label="Name" />
- <DatePicker name="receiptDate" label="Receipt Date" />
- <DatePicker name="expirationDate" label="Expiration Date" />
-
- <Location name="locationId" label="Location" />
- {isEditing && (
- <>
- <Select
- name="status"
- label="Status"
- value={initialValues.status}
- options={statusOptions}
- isReadOnly={
- isSupplier || !permissions.can("delete", "purchasing")
- }
- />
-
- <TextArea name="notes" label="Notes" readOnly={isSupplier} />
- </>
- )}
- <CustomFormFields table="requestForQuote" />
- </div>
- </VStack>
- </CardContent>
- <CardFooter>
- <Submit
- isDisabled={
- isEditing
- ? !permissions.can("update", "purchasing")
- : !permissions.can("create", "purchasing")
- }
- >
- Save
- </Submit>
- </CardFooter>
- </Card>
- </ValidatedForm>
- );
-};
-
-export default RequestForQuoteForm;
diff --git a/apps/carbon/app/modules/purchasing/ui/RequestForQuote/RequestForQuoteStatus.tsx b/apps/carbon/app/modules/purchasing/ui/RequestForQuote/RequestForQuoteStatus.tsx
deleted file mode 100644
index d3598cdcbd..0000000000
--- a/apps/carbon/app/modules/purchasing/ui/RequestForQuote/RequestForQuoteStatus.tsx
+++ /dev/null
@@ -1,23 +0,0 @@
-import { Status } from "@carbon/react";
-import type { requestForQuoteStatusType } from "~/modules/purchasing";
-
-type RequestForQuoteStatusProps = {
- status?: (typeof requestForQuoteStatusType)[number] | null;
-};
-
-const RequestForQuoteStatus = ({ status }: RequestForQuoteStatusProps) => {
- switch (status) {
- case "Draft":
- return <Status color="gray">{status}</Status>;
- case "Sent":
- return <Status color="orange">{status}</Status>;
- case "Closed":
- return <Status color="green">{status}</Status>;
- case "Expired":
- return <Status color="red">{status}</Status>;
- default:
- return null;
- }
-};
-
-export default RequestForQuoteStatus;
diff --git a/apps/carbon/app/modules/purchasing/ui/RequestForQuote/index.ts b/apps/carbon/app/modules/purchasing/ui/RequestForQuote/index.ts
deleted file mode 100644
index d381df36d4..0000000000
--- a/apps/carbon/app/modules/purchasing/ui/RequestForQuote/index.ts
+++ /dev/null
@@ -1,4 +0,0 @@
-import RequestForQuoteForm from "./RequestForQuoteForm";
-import RequestForQuoteStatus from "./RequestForQuoteStatus";
-
-export { RequestForQuoteForm, RequestForQuoteStatus };
diff --git a/apps/carbon/app/modules/purchasing/ui/RequestForQuotes/RequestForQuotesTable.tsx b/apps/carbon/app/modules/purchasing/ui/RequestForQuotes/RequestForQuotesTable.tsx
deleted file mode 100644
index 01d183f5b1..0000000000
--- a/apps/carbon/app/modules/purchasing/ui/RequestForQuotes/RequestForQuotesTable.tsx
+++ /dev/null
@@ -1,321 +0,0 @@
-import { HStack, MenuIcon, MenuItem, useDisclosure } from "@carbon/react";
-import { formatDate } from "@carbon/utils";
-import { useFetcher, useFetchers, useNavigate } from "@remix-run/react";
-import type { ColumnDef } from "@tanstack/react-table";
-import { memo, useMemo, useState } from "react";
-import { LuPencil, LuPin, LuTrash } from "react-icons/lu";
-import { EmployeeAvatar, Hyperlink, New, Table } from "~/components";
-import { ConfirmDelete } from "~/components/Modals";
-import { usePermissions } from "~/hooks";
-import { useCustomColumns } from "~/hooks/useCustomColumns";
-import {
- requestForQuoteStatusType,
- type RequestForQuote,
-} from "~/modules/purchasing";
-import { useParts, usePeople, useSuppliers } from "~/stores";
-import { favoriteSchema } from "~/types/validators";
-import { path } from "~/utils/path";
-import { RequestForQuoteStatus } from "../RequestForQuote";
-
-type RequestForQuotesTableProps = {
- data: RequestForQuote[];
- count: number;
-};
-
-const RequestForQuotesTable = memo(
- ({ data, count }: RequestForQuotesTableProps) => {
- const permissions = usePermissions();
- const navigate = useNavigate();
- const fetcher = useFetcher();
- const optimisticFavorite = useOptimisticFavorite();
-
- const parts = useParts();
- const [people] = usePeople();
- const [suppliers] = useSuppliers();
-
- const rows = useMemo<RequestForQuote[]>(
- () =>
- data.map((d) =>
- d.id === optimisticFavorite?.id
- ? {
- ...d,
- favorite: optimisticFavorite?.favorite
- ? optimisticFavorite.favorite === "favorite"
- : d.favorite,
- }
- : d
- ),
- [data, optimisticFavorite]
- );
-
- const [selectedRequestForQuote, setSelectedRequestForQuote] =
- useState<RequestForQuote | null>(null);
- const deleteRequestForQuoteModal = useDisclosure();
-
- const customColumns = useCustomColumns<RequestForQuote>("requestForQuote");
- const columns = useMemo<ColumnDef<RequestForQuote>[]>(() => {
- const defaultColumns: ColumnDef<RequestForQuote>[] = [
- {
- accessorKey: "requestForQuoteId",
- header: "RFQ Number",
- cell: ({ row }) => (
- <HStack>
- {row.original.favorite ? (
- <fetcher.Form
- method="post"
- action={path.to.requestForQuoteFavorite}
- className="flex items-center"
- >
- <input type="hidden" name="id" value={row.original.id!} />
- <input type="hidden" name="favorite" value="unfavorite" />
- <button type="submit">
- <LuPin
- className="text-yellow-400 cursor-pointer h-4 w-4"
- type="submit"
- />
- </button>
- </fetcher.Form>
- ) : (
- <fetcher.Form
- method="post"
- action={path.to.requestForQuoteFavorite}
- className="flex items-center"
- >
- <input type="hidden" name="id" value={row.original.id!} />
- <input type="hidden" name="favorite" value="favorite" />
- <button type="submit">
- <LuPin
- className="text-yellow-400 cursor-pointer h-4 w-4"
- type="submit"
- />
- </button>
- </fetcher.Form>
- )}
- <Hyperlink to={path.to.requestForQuote(row.original.id!)}>
- {row.original.requestForQuoteId}
- </Hyperlink>
- </HStack>
- ),
- },
- {
- accessorKey: "name",
- header: "Name",
- cell: (item) => {
- if (item.getValue<string>()) {
- return item.getValue<string>().substring(0, 50);
- }
- return null;
- },
- },
- {
- accessorKey: "status",
- header: "Status",
- cell: (item) => {
- const status =
- item.getValue<(typeof requestForQuoteStatusType)[number]>();
- return <RequestForQuoteStatus status={status} />;
- },
- meta: {
- filter: {
- type: "static",
- options: requestForQuoteStatusType.map((status) => ({
- value: status,
- label: <RequestForQuoteStatus status={status} />,
- })),
- },
- },
- },
- {
- id: "assignee",
- header: "Assignee",
- cell: ({ row }) => (
- <EmployeeAvatar employeeId={row.original.assignee} />
- ),
- meta: {
- filter: {
- type: "static",
- options: people.map((employee) => ({
- value: employee.id,
- label: employee.name,
- })),
- },
- },
- },
- {
- accessorKey: "receiptDate",
- header: "Receipt Date",
- cell: (item) => item.getValue(),
- },
- {
- accessorKey: "expirationDate",
- header: "Expiration Date",
- cell: (item) => item.getValue(),
- },
- {
- accessorKey: "supplierIds",
- header: "Suppliers",
- cell: ({ row }) => row.original.supplierIds?.length ?? 0,
- meta: {
- filter: {
- type: "static",
- options: suppliers.map((supplier) => ({
- value: supplier.id,
- label: supplier.name,
- })),
- isArray: true,
- },
- pluralHeader: "Suppliers",
- },
- },
- {
- id: "itemIds",
- header: "Items",
- cell: ({ row }) => row.original.itemIds?.length ?? 0,
- meta: {
- filter: {
- type: "static",
- options: parts.map((part) => ({
- value: part.id,
- label: part.id,
- helperText: part.name,
- })),
- isArray: true,
- },
- pluralHeader: "Parts",
- },
- },
- {
- id: "createdBy",
- header: "Created By",
- cell: ({ row }) => (
- <EmployeeAvatar employeeId={row.original.createdBy} />
- ),
- meta: {
- filter: {
- type: "static",
- options: people.map((employee) => ({
- value: employee.id,
- label: employee.name,
- })),
- },
- },
- },
- {
- accessorKey: "createdAt",
- header: "Created At",
- cell: (item) => formatDate(item.getValue<string>()),
- },
- {
- id: "updatedBy",
- header: "Updated By",
- cell: ({ row }) => (
- <EmployeeAvatar employeeId={row.original.updatedBy} />
- ),
- meta: {
- filter: {
- type: "static",
- options: people.map((employee) => ({
- value: employee.id,
- label: employee.name,
- })),
- },
- },
- },
- {
- accessorKey: "updatedAt",
- header: "Created At",
- cell: (item) => formatDate(item.getValue<string>()),
- },
- ];
- return [...defaultColumns, ...customColumns];
- }, [people, suppliers, parts, customColumns, fetcher]);
-
- const defaultColumnVisibility = {
- createdAt: false,
- createdBy: false,
- updatedAt: false,
- updatedBy: false,
- itemIds: false,
- supplierIds: false,
- };
-
- const renderContextMenu = useMemo(() => {
- // eslint-disable-next-line react/display-name
- return (row: RequestForQuote) => (
- <>
- <MenuItem onClick={() => navigate(path.to.requestForQuote(row.id!))}>
- <MenuIcon icon={<LuPencil />} />
- Edit
- </MenuItem>
- <MenuItem
- disabled={!permissions.can("delete", "purchasing")}
- onClick={() => {
- setSelectedRequestForQuote(row);
- deleteRequestForQuoteModal.onOpen();
- }}
- >
- <MenuIcon icon={<LuTrash />} />
- Delete
- </MenuItem>
- </>
- );
- }, [deleteRequestForQuoteModal, navigate, permissions]);
-
- return (
- <>
- <Table<RequestForQuote>
- count={count}
- columns={columns}
- data={rows}
- defaultColumnPinning={{
- left: ["requestForQuoteId"],
- }}
- defaultColumnVisibility={defaultColumnVisibility}
- primaryAction={
- permissions.can("create", "purchasing") && (
- <New label="Request for Quote" to={path.to.newRequestForQuote} />
- )
- }
- renderContextMenu={renderContextMenu}
- withColumnOrdering
- />
- {selectedRequestForQuote && selectedRequestForQuote.id && (
- <ConfirmDelete
- action={path.to.deleteRequestForQuote(selectedRequestForQuote.id)}
- isOpen={deleteRequestForQuoteModal.isOpen}
- name={selectedRequestForQuote.requestForQuoteId!}
- text={`Are you sure you want to delete ${selectedRequestForQuote.requestForQuoteId!}? This cannot be undone.`}
- onCancel={() => {
- deleteRequestForQuoteModal.onClose();
- setSelectedRequestForQuote(null);
- }}
- onSubmit={() => {
- deleteRequestForQuoteModal.onClose();
- setSelectedRequestForQuote(null);
- }}
- />
- )}
- </>
- );
- }
-);
-
-RequestForQuotesTable.displayName = "RequestForQuotesTable";
-
-export default RequestForQuotesTable;
-
-function useOptimisticFavorite() {
- const fetchers = useFetchers();
- const favoriteFetcher = fetchers.find(
- (f) => f.formAction === path.to.requestForQuoteFavorite
- );
-
- if (favoriteFetcher && favoriteFetcher.formData) {
- const id = favoriteFetcher.formData.get("id");
- const favorite = favoriteFetcher.formData.get("favorite") ?? "off";
- const submission = favoriteSchema.safeParse({ id, favorite });
- if (submission.success) {
- return submission.data;
- }
- }
-}
diff --git a/apps/carbon/app/modules/purchasing/ui/RequestForQuotes/index.ts b/apps/carbon/app/modules/purchasing/ui/RequestForQuotes/index.ts
deleted file mode 100644
index 69c31c057f..0000000000
--- a/apps/carbon/app/modules/purchasing/ui/RequestForQuotes/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import RequestForQuotesTable from "./RequestForQuotesTable";
-
-export { RequestForQuotesTable };
diff --git a/apps/carbon/app/modules/purchasing/ui/index.ts b/apps/carbon/app/modules/purchasing/ui/index.ts
index f7b63c0d1f..70cc1a71ea 100644
--- a/apps/carbon/app/modules/purchasing/ui/index.ts
+++ b/apps/carbon/app/modules/purchasing/ui/index.ts
@@ -2,8 +2,6 @@ import usePurchasingSubmodules from "./usePurchasingSubmodules";
export * from "./PurchaseOrder";
export * from "./PurchaseOrders";
-export * from "./RequestForQuote";
-export * from "./RequestForQuotes";
export * from "./Supplier";
export * from "./SupplierStatuses";
export * from "./SupplierTypes";
diff --git a/apps/carbon/app/modules/purchasing/ui/usePurchasingSubmodules.tsx b/apps/carbon/app/modules/purchasing/ui/usePurchasingSubmodules.tsx
index 26f30568b4..f1c34e96eb 100644
--- a/apps/carbon/app/modules/purchasing/ui/usePurchasingSubmodules.tsx
+++ b/apps/carbon/app/modules/purchasing/ui/usePurchasingSubmodules.tsx
@@ -10,11 +10,6 @@ const purchasingRoutes: AuthenticatedRouteGroup[] = [
name: "Purchase Orders",
to: path.to.purchaseOrders,
},
- // {
- // name: "Request for Quotes",
- // to: path.to.requestForQuotes,
- // permission: "employee",
- // },
{
name: "Suppliers",
to: path.to.suppliers,
diff --git a/apps/carbon/app/modules/users/users.server.ts b/apps/carbon/app/modules/users/users.server.ts
index 421e7b1e49..d0a00de103 100644
--- a/apps/carbon/app/modules/users/users.server.ts
+++ b/apps/carbon/app/modules/users/users.server.ts
@@ -1,7 +1,7 @@
import type { Database, Json } from "@carbon/database";
import { redis } from "@carbon/redis";
import { redirect } from "@remix-run/node";
-import type { PostgrestResponse, SupabaseClient } from "@supabase/supabase-js";
+import type { SupabaseClient } from "@supabase/supabase-js";
import crypto from "crypto";
import logger from "~/lib/logger";
import { getSupabaseServiceRole } from "~/lib/supabase";
@@ -32,6 +32,7 @@ export async function addUserToCompany(
userToCompany: {
userId: string;
companyId: string;
+ role: "employee" | "customer" | "supplier";
}
) {
return client.from("userToCompany").insert(userToCompany);
@@ -100,7 +101,6 @@ export async function createCustomerAccount(
updateContact,
createCustomerAccount,
userToCompany,
- claimsUpdate,
permissionsUpdate,
] = await Promise.all([
client.from("customerContact").update({ userId }).eq("id", id),
@@ -109,10 +109,7 @@ export async function createCustomerAccount(
customerId,
companyId,
}),
- addUserToCompany(client, { userId, companyId }),
- setUserClaims(supabaseAdmin, userId, {
- role: "customer",
- }),
+ addUserToCompany(client, { userId, companyId, role: "customer" }),
setUserPermissions(supabaseAdmin, userId, permissions),
]);
@@ -134,11 +131,6 @@ export async function createCustomerAccount(
return error(userToCompany.error, "Failed to add user to company");
}
- if (claimsUpdate.error) {
- await deleteAuthAccount(userId);
- return error(claimsUpdate.error, "Failed to add user");
- }
-
if (permissionsUpdate.error) {
await deleteAuthAccount(userId);
return error(permissionsUpdate.error, "Failed to add user permissions");
@@ -207,33 +199,20 @@ export async function createEmployeeAccount(
return error(insertUser, "No data returned from create user");
}
- const [
- employeeInsert,
- jobInsert,
- userToCompany,
- permissionsUpdate,
- claimsUpdate,
- ] = await Promise.all([
- insertEmployee(client, {
- id: userId,
- employeeTypeId: employeeType,
- companyId,
- }),
- insertEmployeeJob(client, {
- id: userId,
- companyId,
- }),
- addUserToCompany(client, { userId, companyId }),
- setUserPermissions(supabaseAdmin, userId, permissions),
- userExists
- ? new Promise<PostgrestResponse<unknown>>((resolve) =>
- // @ts-ignore
- resolve({ data: null, error: null })
- )
- : setUserClaims(supabaseAdmin, userId, {
- role: "employee",
- }),
- ]);
+ const [employeeInsert, jobInsert, userToCompany, permissionsUpdate] =
+ await Promise.all([
+ insertEmployee(client, {
+ id: userId,
+ employeeTypeId: employeeType,
+ companyId,
+ }),
+ insertEmployeeJob(client, {
+ id: userId,
+ companyId,
+ }),
+ addUserToCompany(client, { userId, companyId, role: "employee" }),
+ setUserPermissions(supabaseAdmin, userId, permissions),
+ ]);
if (employeeInsert.error) {
if (!userExists) await deleteAuthAccount(userId);
@@ -250,13 +229,6 @@ export async function createEmployeeAccount(
return error(userToCompany.error, "Failed to add user to company");
}
- if (claimsUpdate.error) {
- if (!userExists) await deleteAuthAccount(userId);
- if (claimsUpdate.error) {
- return error(claimsUpdate.error, "Failed to udpate user claims");
- }
- }
-
if (permissionsUpdate.error) {
if (!userExists) await deleteAuthAccount(userId);
return error(permissionsUpdate.error, "Failed to update user permissions");
@@ -293,7 +265,7 @@ export async function createSupplierAccount(
const user = await getUserByEmail(email);
if (user.data) {
// TODO: user already exists -- send company invite
- // await addUserToCompany(client, { userId: user.data.id, companyId });
+ // await addUserToCompany(client, { userId: user.data.id, companyId, role: "supplier"});
return error(
null,
"User already exists. Adding to team not implemented yet."
@@ -328,7 +300,6 @@ export async function createSupplierAccount(
updateContact,
createSupplierAccount,
userToCompany,
- claimsUpdate,
permissionsUpdate,
] = await Promise.all([
client.from("supplierContact").update({ userId }).eq("id", id),
@@ -337,10 +308,7 @@ export async function createSupplierAccount(
supplierId,
companyId,
}),
- addUserToCompany(client, { userId, companyId }),
- setUserClaims(supabaseAdmin, userId, {
- role: "supplier",
- }),
+ addUserToCompany(client, { userId, companyId, role: "supplier" }),
setUserPermissions(supabaseAdmin, userId, permissions),
]);
@@ -362,11 +330,6 @@ export async function createSupplierAccount(
return error(userToCompany.error, "Failed to add user to company");
}
- if (claimsUpdate.error) {
- await deleteAuthAccount(userId);
- return error(claimsUpdate.error, "Failed to create user");
- }
-
if (permissionsUpdate.error) {
await deleteAuthAccount(userId);
return error(
@@ -414,8 +377,12 @@ export async function deactivateUser(
return success("Sucessfully deactivated user");
}
-export async function getClaims(client: SupabaseClient<Database>, uid: string) {
- return client.rpc("get_claims", { uid });
+export async function getClaims(
+ client: SupabaseClient<Database>,
+ uid: string,
+ company?: string
+) {
+ return client.rpc("get_claims", { uid, company: company ?? "" });
}
export async function getCurrentUser(
@@ -456,7 +423,7 @@ export async function getUserByEmail(email: string) {
.maybeSingle();
}
-export async function getUserClaims(userId: string) {
+export async function getUserClaims(userId: string, companyId: string) {
let claims: {
permissions: Record<string, Permission>;
role: string | null;
@@ -470,7 +437,11 @@ export async function getUserClaims(userId: string) {
// if we don't have permissions from redis, get them from the database
if (!claims) {
// TODO: remove service role from here, and move it up a level
- const rawClaims = await getClaims(getSupabaseServiceRole(), userId);
+ const rawClaims = await getClaims(
+ getSupabaseServiceRole(),
+ userId,
+ companyId
+ );
if (rawClaims.error || rawClaims.data === null) {
logger.error(rawClaims);
throw new Error("Failed to get claims");
@@ -802,22 +773,6 @@ export async function resetPassword(userId: string, password: string) {
});
}
-async function setUserClaims(
- client: SupabaseClient<Database>,
- userId: string,
- claims: Record<string, string>
-) {
- const user = await client.auth.admin.getUserById(userId);
- if (user.error) return user;
-
- const currentClaims = user.data?.user.app_metadata ?? {};
- const newClaims = { ...currentClaims, ...claims };
-
- return client.auth.admin.updateUserById(userId, {
- app_metadata: newClaims,
- });
-}
-
async function setUserPermissions(
client: SupabaseClient<Database>,
userId: string,
diff --git a/apps/carbon/app/routes/onboarding+/user.tsx b/apps/carbon/app/routes/onboarding+/user.tsx
index 44ced8a7bd..1c0f0f607e 100644
--- a/apps/carbon/app/routes/onboarding+/user.tsx
+++ b/apps/carbon/app/routes/onboarding+/user.tsx
@@ -90,7 +90,7 @@ export default function OnboardingUser() {
const initialValues = {} as z.infer<typeof onboardingUserValidator>;
- if (user?.email && user.email !== "[email protected]") {
+ if (user?.email && user.email !== "[email protected]") {
initialValues.email = user.email;
}
if (
diff --git a/apps/carbon/app/routes/x+/_layout.tsx b/apps/carbon/app/routes/x+/_layout.tsx
index 92ac1ebf62..5352c959b4 100644
--- a/apps/carbon/app/routes/x+/_layout.tsx
+++ b/apps/carbon/app/routes/x+/_layout.tsx
@@ -58,7 +58,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
getCustomFieldsSchemas(client, { companyId }),
getCompanyIntegrations(client, companyId),
getUser(client, userId),
- getUserClaims(userId),
+ getUserClaims(userId, companyId),
getUserGroups(client, userId),
getUserDefaults(client, userId, companyId),
]);
diff --git a/apps/carbon/app/routes/x+/account+/$userId.attribute.tsx b/apps/carbon/app/routes/x+/account+/$userId.attribute.tsx
index 3c2cdce40b..68f6b61320 100644
--- a/apps/carbon/app/routes/x+/account+/$userId.attribute.tsx
+++ b/apps/carbon/app/routes/x+/account+/$userId.attribute.tsx
@@ -31,7 +31,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
const attributeId = formData.get("userAttributeId") as string;
if (!attributeId) throw new Error("No attribute id provided");
- const clientClaims = await getUserClaims(userId);
+ const clientClaims = await getUserClaims(userId, companyId);
const canUpdateAnyUser =
clientClaims.permissions["users"]?.update?.includes(companyId);
diff --git a/apps/carbon/app/routes/x+/account+/$userId.delete.attribute.tsx b/apps/carbon/app/routes/x+/account+/$userId.delete.attribute.tsx
index baae9444c3..823d4daa03 100644
--- a/apps/carbon/app/routes/x+/account+/$userId.delete.attribute.tsx
+++ b/apps/carbon/app/routes/x+/account+/$userId.delete.attribute.tsx
@@ -26,7 +26,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
const userAttributeValueId = formData.get("userAttributeValueId") as string;
if (!userAttributeValueId) throw new Error("No attribute value id provided");
- const clientClaims = await getUserClaims(userId);
+ const clientClaims = await getUserClaims(userId, companyId);
const canUpdateAnyUser =
clientClaims.permissions["resources"]?.update?.includes(companyId);
diff --git a/apps/carbon/app/routes/x+/purchasing+/rfqs.favorite.tsx b/apps/carbon/app/routes/x+/purchasing+/rfqs.favorite.tsx
deleted file mode 100644
index 2d8e7c0610..0000000000
--- a/apps/carbon/app/routes/x+/purchasing+/rfqs.favorite.tsx
+++ /dev/null
@@ -1,37 +0,0 @@
-import { validationError, validator } from "@carbon/remix-validated-form";
-import { json, type ActionFunctionArgs } from "@remix-run/node";
-import { updateRequestForQuoteFavorite } from "~/modules/purchasing";
-import { requirePermissions } from "~/services/auth/auth.server";
-import { flash } from "~/services/session.server";
-import { favoriteSchema } from "~/types/validators";
-import { error } from "~/utils/result";
-
-export async function action({ request }: ActionFunctionArgs) {
- const { client, userId } = await requirePermissions(request, {
- view: "purchasing",
- });
-
- const validation = await validator(favoriteSchema).validate(
- await request.formData()
- );
- if (validation.error) {
- return validationError(validation.error);
- }
-
- const { id, favorite } = validation.data;
-
- const result = await updateRequestForQuoteFavorite(client, {
- id,
- favorite: favorite === "favorite",
- userId,
- });
-
- if (result.error) {
- return json(
- {},
- await flash(request, error(result, "Failed to favorite RFQ"))
- );
- }
-
- return json({});
-}
diff --git a/apps/carbon/app/routes/x+/purchasing+/rfqs.tsx b/apps/carbon/app/routes/x+/purchasing+/rfqs.tsx
deleted file mode 100644
index 81ae57d078..0000000000
--- a/apps/carbon/app/routes/x+/purchasing+/rfqs.tsx
+++ /dev/null
@@ -1,68 +0,0 @@
-import { VStack } from "@carbon/react";
-import type { LoaderFunctionArgs } from "@remix-run/node";
-import { json, redirect } from "@remix-run/node";
-import { Outlet, useLoaderData } from "@remix-run/react";
-import {
- RequestForQuotesTable,
- getRequestsForQuotes,
-} from "~/modules/purchasing";
-import { requirePermissions } from "~/services/auth/auth.server";
-import { flash } from "~/services/session.server";
-import type { Handle } from "~/utils/handle";
-import { path } from "~/utils/path";
-import { getGenericQueryFilters } from "~/utils/query";
-import { error } from "~/utils/result";
-
-export const handle: Handle = {
- breadcrumb: "Requests for Quotes",
- to: path.to.requestForQuotes,
-};
-
-export async function loader({ request }: LoaderFunctionArgs) {
- const { client, companyId } = await requirePermissions(request, {
- view: "purchasing",
- });
-
- const url = new URL(request.url);
- const searchParams = new URLSearchParams(url.search);
- const search = searchParams.get("search");
-
- const { limit, offset, sorts, filters } =
- getGenericQueryFilters(searchParams);
-
- const [requestForQuotes] = await Promise.all([
- getRequestsForQuotes(client, companyId, {
- search,
- limit,
- offset,
- sorts,
- filters,
- }),
- ]);
-
- if (requestForQuotes.error) {
- redirect(
- path.to.authenticatedRoot,
- await flash(
- request,
- error(requestForQuotes.error, "Failed to fetch request for quotes")
- )
- );
- }
-
- return json({
- count: requestForQuotes.count ?? 0,
- requestForQuotes: requestForQuotes.data ?? [],
- });
-}
-
-export default function RequestForQuotesSearchRoute() {
- const { count, requestForQuotes } = useLoaderData<typeof loader>();
-
- return (
- <VStack spacing={0} className="h-full">
- <RequestForQuotesTable data={requestForQuotes} count={count} />
- <Outlet />
- </VStack>
- );
-}
diff --git a/apps/carbon/app/routes/x+/rfq+/$id.tsx b/apps/carbon/app/routes/x+/rfq+/$id.tsx
deleted file mode 100644
index 90a22f1847..0000000000
--- a/apps/carbon/app/routes/x+/rfq+/$id.tsx
+++ /dev/null
@@ -1,9 +0,0 @@
-import { VStack } from "@carbon/react";
-
-export default function RequestForQuoteRoute() {
- return (
- <VStack spacing={4} className="h-full p-2">
- <pre>TODO</pre>
- </VStack>
- );
-}
diff --git a/apps/carbon/app/routes/x+/rfq+/_layout.tsx b/apps/carbon/app/routes/x+/rfq+/_layout.tsx
deleted file mode 100644
index d482e92191..0000000000
--- a/apps/carbon/app/routes/x+/rfq+/_layout.tsx
+++ /dev/null
@@ -1,23 +0,0 @@
-import { VStack } from "@carbon/react";
-import type { MetaFunction } from "@remix-run/node";
-import { Outlet } from "@remix-run/react";
-import type { Handle } from "~/utils/handle";
-import { path } from "~/utils/path";
-
-export const meta: MetaFunction = () => {
- return [{ title: "Carbon | Request for Quote" }];
-};
-
-export const handle: Handle = {
- breadcrumb: "Purchasing",
- to: path.to.purchaseOrders,
- module: "purchasing",
-};
-
-export default function RequestForQuoteRoute() {
- return (
- <VStack spacing={4} className="h-full p-2">
- <Outlet />
- </VStack>
- );
-}
diff --git a/apps/carbon/app/routes/x+/rfq+/delete.$id.tsx b/apps/carbon/app/routes/x+/rfq+/delete.$id.tsx
deleted file mode 100644
index 00b5d08947..0000000000
--- a/apps/carbon/app/routes/x+/rfq+/delete.$id.tsx
+++ /dev/null
@@ -1,32 +0,0 @@
-import type { ActionFunctionArgs } from "@remix-run/node";
-import { redirect } from "@remix-run/node";
-import { deleteRequestForQuote } from "~/modules/purchasing";
-import { requirePermissions } from "~/services/auth/auth.server";
-import { flash } from "~/services/session.server";
-import { assertIsPost, notFound } from "~/utils/http";
-import { path } from "~/utils/path";
-import { error } from "~/utils/result";
-
-export async function action({ request, params }: ActionFunctionArgs) {
- assertIsPost(request);
- const { client } = await requirePermissions(request, {
- delete: "purchasing",
- });
-
- const { id } = params;
- if (!id) throw notFound("id not found");
-
- const remove = await deleteRequestForQuote(client, id);
-
- if (remove.error) {
- throw redirect(
- path.to.requestForQuotes,
- await flash(
- request,
- error(remove.error, "Failed to delete request for quote")
- )
- );
- }
-
- throw redirect(path.to.requestForQuotes);
-}
diff --git a/apps/carbon/app/routes/x+/rfq+/new.tsx b/apps/carbon/app/routes/x+/rfq+/new.tsx
deleted file mode 100644
index ee3f08d543..0000000000
--- a/apps/carbon/app/routes/x+/rfq+/new.tsx
+++ /dev/null
@@ -1,85 +0,0 @@
-import { validationError, validator } from "@carbon/remix-validated-form";
-import type { ActionFunctionArgs } from "@remix-run/node";
-import { redirect } from "@remix-run/node";
-import {
- RequestForQuoteForm,
- requestForQuoteValidator,
- upsertRequestForQuote,
-} from "~/modules/purchasing";
-import { getNextSequence, rollbackNextSequence } from "~/modules/settings";
-import { requirePermissions } from "~/services/auth/auth.server";
-import { flash } from "~/services/session.server";
-import { setCustomFields } from "~/utils/form";
-import { assertIsPost } from "~/utils/http";
-import { path } from "~/utils/path";
-import { error } from "~/utils/result";
-
-export async function action({ request }: ActionFunctionArgs) {
- assertIsPost(request);
- const { client, companyId, userId } = await requirePermissions(request, {
- create: "purchasing",
- });
-
- const formData = await request.formData();
- const validation = await validator(requestForQuoteValidator).validate(
- formData
- );
-
- if (validation.error) {
- return validationError(validation.error);
- }
-
- const nextSequence = await getNextSequence(
- client,
- "requestForQuote",
- companyId
- );
- if (nextSequence.error) {
- throw redirect(
- path.to.newRequestForQuote,
- await flash(
- request,
- error(nextSequence.error, "Failed to get next sequence")
- )
- );
- }
-
- const createRequestForQuote = await upsertRequestForQuote(client, {
- ...validation.data,
- requestForQuoteId: nextSequence.data,
- companyId,
- createdBy: userId,
- customFields: setCustomFields(formData),
- });
-
- if (createRequestForQuote.error || !createRequestForQuote.data?.[0]) {
- // TODO: this should be done as a transaction
- await rollbackNextSequence(client, "requestForQuote", companyId);
- throw redirect(
- path.to.requestForQuotes,
- await flash(
- request,
- error(createRequestForQuote.error, "Failed to insert request for quote")
- )
- );
- }
-
- const order = createRequestForQuote.data?.[0];
-
- throw redirect(path.to.requestForQuote(order.id!));
-}
-
-export default function RequestForQuoteNewRoute() {
- const today = new Date().toISOString().split("T")[0];
- const initialValues = {
- name: "",
- receiptDate: today,
- status: "Draft" as "Draft",
- };
-
- return (
- <div className="w-1/2 max-w-[600px] min-w-[420px] mx-auto mt-8">
- <RequestForQuoteForm initialValues={initialValues} />
- </div>
- );
-}
diff --git a/apps/carbon/app/routes/x+/users+/employees.$employeeId.tsx b/apps/carbon/app/routes/x+/users+/employees.$employeeId.tsx
index 12d4029f90..aee1eed342 100644
--- a/apps/carbon/app/routes/x+/users+/employees.$employeeId.tsx
+++ b/apps/carbon/app/routes/x+/users+/employees.$employeeId.tsx
@@ -34,7 +34,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const client = getSupabaseServiceRole();
const [rawClaims, employee, employeeTypes] = await Promise.all([
- getClaims(client, employeeId),
+ getClaims(client, employeeId, companyId),
getEmployee(client, employeeId, companyId),
getEmployeeTypes(client, companyId),
]);
diff --git a/apps/carbon/app/services/auth/auth.server.ts b/apps/carbon/app/services/auth/auth.server.ts
index 25be21e799..f8acbdb8f6 100644
--- a/apps/carbon/app/services/auth/auth.server.ts
+++ b/apps/carbon/app/services/auth/auth.server.ts
@@ -100,7 +100,7 @@ export async function requirePermissions(
if (Object.keys(requiredPermissions).length === 0)
return { client, companyId, email, userId };
- const myClaims = await getUserClaims(userId);
+ const myClaims = await getUserClaims(userId, companyId);
const hasRequiredPermissions = Object.entries(requiredPermissions).every(
([action, permission]) => {
diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.ts
index fa670cd934..70a2c497f9 100644
--- a/apps/carbon/app/utils/path.ts
+++ b/apps/carbon/app/utils/path.ts
@@ -570,9 +570,6 @@ export const path = {
receiptPost: (id: string) => generatePath(`${x}/receipt/${id}/post`),
receiptRoot: `${x}/receipt`,
refreshSession: "/refresh-session",
- requestForQuote: (id: string) => generatePath(`${x}/rfq/${id}`),
- requestForQuoteFavorite: `${x}/purchasing/rfqs/favorite`,
- requestForQuotes: `${x}/purchasing/rfqs`,
resendInvite: `${x}/users/resend-invite`,
resetPassword: "/reset-password",
resources: `${x}/resources`,
diff --git a/apps/docs/pages/core-concepts/permissions.mdx b/apps/docs/pages/core-concepts/permissions.mdx
index 21a3e5a072..32035889a0 100644
--- a/apps/docs/pages/core-concepts/permissions.mdx
+++ b/apps/docs/pages/core-concepts/permissions.mdx
@@ -71,14 +71,14 @@ ALTER TABLE "customer" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with sales_view can view customer" ON "customer"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permissions('sales_view', "companyId")
);
CREATE POLICY "Customers with sales_view can their own organization" ON "customer"
FOR SELECT
USING (
- has_role('customer') AND
+ has_role('customer', "companyId") AND
has_company_permissions('sales_view', "companyId")
AND id IN (
SELECT "customerId" FROM "customerAccount" WHERE id::uuid = auth.uid()
@@ -88,21 +88,21 @@ CREATE POLICY "Customers with sales_view can their own organization" ON "custome
CREATE POLICY "Employees with sales_create can create customers" ON "customer"
FOR INSERT
WITH CHECK (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permissions('sales_create', "companyId")
);
CREATE POLICY "Employees with sales_update can update customers" ON "customer"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permissions('sales_update', "companyId")
);
CREATE POLICY "Customers with sales_update can their own organization" ON "customer"
FOR UPDATE
USING (
- has_role('customer') AND
+ has_role('customer', "companyId") AND
has_company_permissions('sales_update', "companyId")
AND id IN (
SELECT "customerId" FROM "customerAccount" WHERE id::uuid = auth.uid()
@@ -112,7 +112,7 @@ CREATE POLICY "Customers with sales_update can their own organization" ON "custo
CREATE POLICY "Employees with sales_delete can delete customers" ON "customer"
FOR DELETE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permissions('sales_delete', "companyId")
);
diff --git a/packages/database/src/seed/admin.ts b/packages/database/src/seed/admin.ts
index 2719039d76..d2c3c4126d 100644
--- a/packages/database/src/seed/admin.ts
+++ b/packages/database/src/seed/admin.ts
@@ -1,5 +1,5 @@
const admin = {
- email: "[email protected]",
+ email: "[email protected]",
password: "carbon",
firstName: "Carbon",
lastName: "Admin",
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 090d19d29a..9675da3e50 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -14017,834 +14017,6 @@ export type Database = {
},
]
}
- requestForQuote: {
- Row: {
- assignee: string | null
- companyId: string
- createdAt: string | null
- createdBy: string
- customFields: Json | null
- expirationDate: string | null
- id: string
- locationId: string | null
- name: string | null
- notes: string | null
- receiptDate: string
- requestForQuoteId: string
- revisionId: number
- status: Database["public"]["Enums"]["requestForQuoteStatus"]
- updatedAt: string | null
- updatedBy: string | null
- }
- Insert: {
- assignee?: string | null
- companyId: string
- createdAt?: string | null
- createdBy: string
- customFields?: Json | null
- expirationDate?: string | null
- id?: string
- locationId?: string | null
- name?: string | null
- notes?: string | null
- receiptDate: string
- requestForQuoteId: string
- revisionId?: number
- status?: Database["public"]["Enums"]["requestForQuoteStatus"]
- updatedAt?: string | null
- updatedBy?: string | null
- }
- Update: {
- assignee?: string | null
- companyId?: string
- createdAt?: string | null
- createdBy?: string
- customFields?: Json | null
- expirationDate?: string | null
- id?: string
- locationId?: string | null
- name?: string | null
- notes?: string | null
- receiptDate?: string
- requestForQuoteId?: string
- revisionId?: number
- status?: Database["public"]["Enums"]["requestForQuoteStatus"]
- updatedAt?: string | null
- updatedBy?: string | null
- }
- Relationships: [
- {
- foreignKeyName: "requestForQuote_assignee_fkey"
- columns: ["assignee"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_assignee_fkey"
- columns: ["assignee"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_assignee_fkey"
- columns: ["assignee"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_assignee_fkey"
- columns: ["assignee"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_assignee_fkey"
- columns: ["assignee"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- {
- foreignKeyName: "requestForQuote_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "companies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "company"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "customFieldTables"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "requestForQuote_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "integrations"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "requestForQuote_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- {
- foreignKeyName: "requestForQuote_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
- {
- foreignKeyName: "requestForQuote_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "location"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "purchaseOrders"
- referencedColumns: ["locationId"]
- },
- {
- foreignKeyName: "requestForQuote_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "salesOrders"
- referencedColumns: ["locationId"]
- },
- {
- foreignKeyName: "requestForQuote_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- ]
- }
- requestForQuoteFavorite: {
- Row: {
- requestForQuoteId: string
- userId: string
- }
- Insert: {
- requestForQuoteId: string
- userId: string
- }
- Update: {
- requestForQuoteId?: string
- userId?: string
- }
- Relationships: [
- {
- foreignKeyName: "requestForQuoteFavorites_requestForQuoteId_fkey"
- columns: ["requestForQuoteId"]
- isOneToOne: false
- referencedRelation: "requestForQuote"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteFavorites_requestForQuoteId_fkey"
- columns: ["requestForQuoteId"]
- isOneToOne: false
- referencedRelation: "requestForQuotes"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteFavorites_userId_fkey"
- columns: ["userId"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteFavorites_userId_fkey"
- columns: ["userId"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteFavorites_userId_fkey"
- columns: ["userId"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteFavorites_userId_fkey"
- columns: ["userId"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteFavorites_userId_fkey"
- columns: ["userId"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- ]
- }
- requestForQuoteLine: {
- Row: {
- companyId: string
- createdAt: string | null
- createdBy: string
- customFields: Json | null
- description: string | null
- id: string
- itemId: string
- locationId: string | null
- quantity: number
- requestForQuoteId: string
- shelfId: string | null
- unitOfMeasureCode: string | null
- unitPrice: number
- updatedAt: string | null
- updatedBy: string | null
- }
- Insert: {
- companyId: string
- createdAt?: string | null
- createdBy: string
- customFields?: Json | null
- description?: string | null
- id?: string
- itemId: string
- locationId?: string | null
- quantity: number
- requestForQuoteId: string
- shelfId?: string | null
- unitOfMeasureCode?: string | null
- unitPrice?: number
- updatedAt?: string | null
- updatedBy?: string | null
- }
- Update: {
- companyId?: string
- createdAt?: string | null
- createdBy?: string
- customFields?: Json | null
- description?: string | null
- id?: string
- itemId?: string
- locationId?: string | null
- quantity?: number
- requestForQuoteId?: string
- shelfId?: string | null
- unitOfMeasureCode?: string | null
- unitPrice?: number
- updatedAt?: string | null
- updatedBy?: string | null
- }
- Relationships: [
- {
- foreignKeyName: "requestForQuoteLine_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "companies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteLine_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "company"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteLine_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "customFieldTables"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "requestForQuoteLine_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "integrations"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "requestForQuoteLine_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteLine_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteLine_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteLine_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteLine_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- {
- foreignKeyName: "requestForQuoteLine_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "item"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteLine_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
- {
- foreignKeyName: "requestForQuoteLine_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
- {
- foreignKeyName: "requestForQuoteLine_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "location"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteLine_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "purchaseOrders"
- referencedColumns: ["locationId"]
- },
- {
- foreignKeyName: "requestForQuoteLine_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "salesOrders"
- referencedColumns: ["locationId"]
- },
- {
- foreignKeyName: "requestForQuoteLine_requestForQuoteId_fkey"
- columns: ["requestForQuoteId"]
- isOneToOne: false
- referencedRelation: "requestForQuote"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteLine_requestForQuoteId_fkey"
- columns: ["requestForQuoteId"]
- isOneToOne: false
- referencedRelation: "requestForQuotes"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteLine_shelfId_fkey"
- columns: ["shelfId", "locationId"]
- isOneToOne: false
- referencedRelation: "shelf"
- referencedColumns: ["id", "locationId"]
- },
- {
- foreignKeyName: "requestForQuoteLine_unitOfMeasureCode_fkey"
- columns: ["unitOfMeasureCode", "companyId"]
- isOneToOne: false
- referencedRelation: "unitOfMeasure"
- referencedColumns: ["code", "companyId"]
- },
- {
- foreignKeyName: "requestForQuoteLine_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteLine_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteLine_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteLine_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteLine_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- ]
- }
- requestForQuoteSupplier: {
- Row: {
- completedAt: string | null
- createdAt: string | null
- createdBy: string
- customFields: Json | null
- id: string
- password: string | null
- requestForQuoteId: string
- supplierContactId: string | null
- supplierId: string
- supplierLocationId: string | null
- token: string | null
- updatedAt: string | null
- updatedBy: string | null
- }
- Insert: {
- completedAt?: string | null
- createdAt?: string | null
- createdBy: string
- customFields?: Json | null
- id?: string
- password?: string | null
- requestForQuoteId: string
- supplierContactId?: string | null
- supplierId: string
- supplierLocationId?: string | null
- token?: string | null
- updatedAt?: string | null
- updatedBy?: string | null
- }
- Update: {
- completedAt?: string | null
- createdAt?: string | null
- createdBy?: string
- customFields?: Json | null
- id?: string
- password?: string | null
- requestForQuoteId?: string
- supplierContactId?: string | null
- supplierId?: string
- supplierLocationId?: string | null
- token?: string | null
- updatedAt?: string | null
- updatedBy?: string | null
- }
- Relationships: [
- {
- foreignKeyName: "requestForQuoteSupplier_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteSupplier_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteSupplier_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteSupplier_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteSupplier_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- {
- foreignKeyName: "requestForQuoteSupplier_requestForQuoteId_fkey"
- columns: ["requestForQuoteId"]
- isOneToOne: false
- referencedRelation: "requestForQuote"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteSupplier_requestForQuoteId_fkey"
- columns: ["requestForQuoteId"]
- isOneToOne: false
- referencedRelation: "requestForQuotes"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteSupplier_supplierContactId_fkey"
- columns: ["supplierContactId"]
- isOneToOne: false
- referencedRelation: "contact"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteSupplier_supplierId_fkey"
- columns: ["supplierId"]
- isOneToOne: false
- referencedRelation: "contractors"
- referencedColumns: ["supplierId"]
- },
- {
- foreignKeyName: "requestForQuoteSupplier_supplierId_fkey"
- columns: ["supplierId"]
- isOneToOne: false
- referencedRelation: "partners"
- referencedColumns: ["supplierId"]
- },
- {
- foreignKeyName: "requestForQuoteSupplier_supplierId_fkey"
- columns: ["supplierId"]
- isOneToOne: false
- referencedRelation: "purchaseOrderSuppliers"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteSupplier_supplierId_fkey"
- columns: ["supplierId"]
- isOneToOne: false
- referencedRelation: "supplier"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteSupplier_supplierId_fkey"
- columns: ["supplierId"]
- isOneToOne: false
- referencedRelation: "suppliers"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteSupplier_supplierLocationId_fkey"
- columns: ["supplierLocationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
- {
- foreignKeyName: "requestForQuoteSupplier_supplierLocationId_fkey"
- columns: ["supplierLocationId"]
- isOneToOne: false
- referencedRelation: "location"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteSupplier_supplierLocationId_fkey"
- columns: ["supplierLocationId"]
- isOneToOne: false
- referencedRelation: "purchaseOrders"
- referencedColumns: ["locationId"]
- },
- {
- foreignKeyName: "requestForQuoteSupplier_supplierLocationId_fkey"
- columns: ["supplierLocationId"]
- isOneToOne: false
- referencedRelation: "salesOrders"
- referencedColumns: ["locationId"]
- },
- {
- foreignKeyName: "requestForQuoteSupplier_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteSupplier_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteSupplier_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteSupplier_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteSupplier_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- ]
- }
- requestForQuoteSupplierLine: {
- Row: {
- createdAt: string | null
- createdBy: string
- id: string
- requestForQuoteLineId: string
- requestForQuoteSupplierId: string
- unitPrice: number
- updatedAt: string | null
- updatedBy: string | null
- }
- Insert: {
- createdAt?: string | null
- createdBy: string
- id?: string
- requestForQuoteLineId: string
- requestForQuoteSupplierId: string
- unitPrice: number
- updatedAt?: string | null
- updatedBy?: string | null
- }
- Update: {
- createdAt?: string | null
- createdBy?: string
- id?: string
- requestForQuoteLineId?: string
- requestForQuoteSupplierId?: string
- unitPrice?: number
- updatedAt?: string | null
- updatedBy?: string | null
- }
- Relationships: [
- {
- foreignKeyName: "requestForQuoteSupplierLine_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteSupplierLine_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteSupplierLine_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteSupplierLine_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteSupplierLine_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- {
- foreignKeyName: "requestForQuoteSupplierLine_requestForQuoteLineId_fkey"
- columns: ["requestForQuoteLineId"]
- isOneToOne: false
- referencedRelation: "requestForQuoteLine"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteSupplierLine_requestForQuoteSupplierId_fkey"
- columns: ["requestForQuoteSupplierId"]
- isOneToOne: false
- referencedRelation: "requestForQuoteSupplier"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteSupplierLine_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteSupplierLine_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteSupplierLine_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteSupplierLine_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteSupplierLine_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- ]
- }
salesOrder: {
Row: {
assignee: string | null
@@ -19166,14 +18338,17 @@ export type Database = {
userToCompany: {
Row: {
companyId: string
+ role: Database["public"]["Enums"]["role"]
userId: string
}
Insert: {
companyId: string
+ role: Database["public"]["Enums"]["role"]
userId: string
}
Update: {
companyId?: string
+ role?: Database["public"]["Enums"]["role"]
userId?: string
}
Relationships: [
@@ -20118,6 +19293,7 @@ export type Database = {
name: string | null
phone: string | null
postalCode: string | null
+ role: Database["public"]["Enums"]["role"] | null
state: string | null
taxId: string | null
updatedBy: string | null
@@ -23437,193 +22613,6 @@ export type Database = {
},
]
}
- requestForQuotes: {
- Row: {
- assignee: string | null
- companyId: string | null
- createdAt: string | null
- createdBy: string | null
- customFields: Json | null
- expirationDate: string | null
- favorite: boolean | null
- id: string | null
- itemIds: string[] | null
- locationId: string | null
- locationName: string | null
- name: string | null
- notes: string | null
- receiptDate: string | null
- requestForQuoteId: string | null
- revisionId: number | null
- status: Database["public"]["Enums"]["requestForQuoteStatus"] | null
- supplierIds: string[] | null
- updatedAt: string | null
- updatedBy: string | null
- }
- Relationships: [
- {
- foreignKeyName: "requestForQuote_assignee_fkey"
- columns: ["assignee"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_assignee_fkey"
- columns: ["assignee"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_assignee_fkey"
- columns: ["assignee"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_assignee_fkey"
- columns: ["assignee"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_assignee_fkey"
- columns: ["assignee"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- {
- foreignKeyName: "requestForQuote_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "company"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "companies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "customFieldTables"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "requestForQuote_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "integrations"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "requestForQuote_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- {
- foreignKeyName: "requestForQuote_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "location"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
- {
- foreignKeyName: "requestForQuote_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "purchaseOrders"
- referencedColumns: ["locationId"]
- },
- {
- foreignKeyName: "requestForQuote_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "salesOrders"
- referencedColumns: ["locationId"]
- },
- {
- foreignKeyName: "requestForQuote_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- ]
- }
salesOrderCustomers: {
Row: {
companyId: string | null
@@ -24974,6 +23963,7 @@ export type Database = {
get_claims: {
Args: {
uid: string
+ company: string
}
Returns: Json
}
@@ -25041,7 +24031,8 @@ export type Database = {
}
has_role: {
Args: {
- role: string
+ required_role: string
+ company: string
}
Returns: boolean
}
@@ -25343,7 +24334,7 @@ export type Database = {
| "Manufacturing Consumption"
| "Manufacturing Output"
receiptStatus: "Draft" | "Pending" | "Posted"
- requestForQuoteStatus: "Draft" | "Sent" | "Expired" | "Closed"
+ role: "customer" | "employee" | "supplier"
salesOrderLineType:
| "Comment"
| "Part"
diff --git a/packages/database/supabase/functions/lib/seed.ts b/packages/database/supabase/functions/lib/seed.ts
index fb985de206..0a155386f8 100644
--- a/packages/database/supabase/functions/lib/seed.ts
+++ b/packages/database/supabase/functions/lib/seed.ts
@@ -2077,15 +2077,6 @@ export const sequences = [
size: 6,
step: 1,
},
- {
- table: "requestForQuote",
- name: "Request For Quote",
- prefix: "RFQ",
- suffix: null,
- next: 0,
- size: 6,
- step: 1,
- },
{
table: "quote",
name: "Quote",
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 090d19d29a..9675da3e50 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -14017,834 +14017,6 @@ export type Database = {
},
]
}
- requestForQuote: {
- Row: {
- assignee: string | null
- companyId: string
- createdAt: string | null
- createdBy: string
- customFields: Json | null
- expirationDate: string | null
- id: string
- locationId: string | null
- name: string | null
- notes: string | null
- receiptDate: string
- requestForQuoteId: string
- revisionId: number
- status: Database["public"]["Enums"]["requestForQuoteStatus"]
- updatedAt: string | null
- updatedBy: string | null
- }
- Insert: {
- assignee?: string | null
- companyId: string
- createdAt?: string | null
- createdBy: string
- customFields?: Json | null
- expirationDate?: string | null
- id?: string
- locationId?: string | null
- name?: string | null
- notes?: string | null
- receiptDate: string
- requestForQuoteId: string
- revisionId?: number
- status?: Database["public"]["Enums"]["requestForQuoteStatus"]
- updatedAt?: string | null
- updatedBy?: string | null
- }
- Update: {
- assignee?: string | null
- companyId?: string
- createdAt?: string | null
- createdBy?: string
- customFields?: Json | null
- expirationDate?: string | null
- id?: string
- locationId?: string | null
- name?: string | null
- notes?: string | null
- receiptDate?: string
- requestForQuoteId?: string
- revisionId?: number
- status?: Database["public"]["Enums"]["requestForQuoteStatus"]
- updatedAt?: string | null
- updatedBy?: string | null
- }
- Relationships: [
- {
- foreignKeyName: "requestForQuote_assignee_fkey"
- columns: ["assignee"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_assignee_fkey"
- columns: ["assignee"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_assignee_fkey"
- columns: ["assignee"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_assignee_fkey"
- columns: ["assignee"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_assignee_fkey"
- columns: ["assignee"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- {
- foreignKeyName: "requestForQuote_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "companies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "company"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "customFieldTables"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "requestForQuote_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "integrations"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "requestForQuote_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- {
- foreignKeyName: "requestForQuote_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
- {
- foreignKeyName: "requestForQuote_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "location"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "purchaseOrders"
- referencedColumns: ["locationId"]
- },
- {
- foreignKeyName: "requestForQuote_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "salesOrders"
- referencedColumns: ["locationId"]
- },
- {
- foreignKeyName: "requestForQuote_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- ]
- }
- requestForQuoteFavorite: {
- Row: {
- requestForQuoteId: string
- userId: string
- }
- Insert: {
- requestForQuoteId: string
- userId: string
- }
- Update: {
- requestForQuoteId?: string
- userId?: string
- }
- Relationships: [
- {
- foreignKeyName: "requestForQuoteFavorites_requestForQuoteId_fkey"
- columns: ["requestForQuoteId"]
- isOneToOne: false
- referencedRelation: "requestForQuote"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteFavorites_requestForQuoteId_fkey"
- columns: ["requestForQuoteId"]
- isOneToOne: false
- referencedRelation: "requestForQuotes"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteFavorites_userId_fkey"
- columns: ["userId"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteFavorites_userId_fkey"
- columns: ["userId"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteFavorites_userId_fkey"
- columns: ["userId"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteFavorites_userId_fkey"
- columns: ["userId"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteFavorites_userId_fkey"
- columns: ["userId"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- ]
- }
- requestForQuoteLine: {
- Row: {
- companyId: string
- createdAt: string | null
- createdBy: string
- customFields: Json | null
- description: string | null
- id: string
- itemId: string
- locationId: string | null
- quantity: number
- requestForQuoteId: string
- shelfId: string | null
- unitOfMeasureCode: string | null
- unitPrice: number
- updatedAt: string | null
- updatedBy: string | null
- }
- Insert: {
- companyId: string
- createdAt?: string | null
- createdBy: string
- customFields?: Json | null
- description?: string | null
- id?: string
- itemId: string
- locationId?: string | null
- quantity: number
- requestForQuoteId: string
- shelfId?: string | null
- unitOfMeasureCode?: string | null
- unitPrice?: number
- updatedAt?: string | null
- updatedBy?: string | null
- }
- Update: {
- companyId?: string
- createdAt?: string | null
- createdBy?: string
- customFields?: Json | null
- description?: string | null
- id?: string
- itemId?: string
- locationId?: string | null
- quantity?: number
- requestForQuoteId?: string
- shelfId?: string | null
- unitOfMeasureCode?: string | null
- unitPrice?: number
- updatedAt?: string | null
- updatedBy?: string | null
- }
- Relationships: [
- {
- foreignKeyName: "requestForQuoteLine_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "companies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteLine_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "company"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteLine_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "customFieldTables"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "requestForQuoteLine_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "integrations"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "requestForQuoteLine_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteLine_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteLine_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteLine_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteLine_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- {
- foreignKeyName: "requestForQuoteLine_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "item"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteLine_itemId_fkey"
- columns: ["itemId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["itemId"]
- },
- {
- foreignKeyName: "requestForQuoteLine_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
- {
- foreignKeyName: "requestForQuoteLine_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "location"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteLine_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "purchaseOrders"
- referencedColumns: ["locationId"]
- },
- {
- foreignKeyName: "requestForQuoteLine_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "salesOrders"
- referencedColumns: ["locationId"]
- },
- {
- foreignKeyName: "requestForQuoteLine_requestForQuoteId_fkey"
- columns: ["requestForQuoteId"]
- isOneToOne: false
- referencedRelation: "requestForQuote"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteLine_requestForQuoteId_fkey"
- columns: ["requestForQuoteId"]
- isOneToOne: false
- referencedRelation: "requestForQuotes"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteLine_shelfId_fkey"
- columns: ["shelfId", "locationId"]
- isOneToOne: false
- referencedRelation: "shelf"
- referencedColumns: ["id", "locationId"]
- },
- {
- foreignKeyName: "requestForQuoteLine_unitOfMeasureCode_fkey"
- columns: ["unitOfMeasureCode", "companyId"]
- isOneToOne: false
- referencedRelation: "unitOfMeasure"
- referencedColumns: ["code", "companyId"]
- },
- {
- foreignKeyName: "requestForQuoteLine_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteLine_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteLine_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteLine_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteLine_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- ]
- }
- requestForQuoteSupplier: {
- Row: {
- completedAt: string | null
- createdAt: string | null
- createdBy: string
- customFields: Json | null
- id: string
- password: string | null
- requestForQuoteId: string
- supplierContactId: string | null
- supplierId: string
- supplierLocationId: string | null
- token: string | null
- updatedAt: string | null
- updatedBy: string | null
- }
- Insert: {
- completedAt?: string | null
- createdAt?: string | null
- createdBy: string
- customFields?: Json | null
- id?: string
- password?: string | null
- requestForQuoteId: string
- supplierContactId?: string | null
- supplierId: string
- supplierLocationId?: string | null
- token?: string | null
- updatedAt?: string | null
- updatedBy?: string | null
- }
- Update: {
- completedAt?: string | null
- createdAt?: string | null
- createdBy?: string
- customFields?: Json | null
- id?: string
- password?: string | null
- requestForQuoteId?: string
- supplierContactId?: string | null
- supplierId?: string
- supplierLocationId?: string | null
- token?: string | null
- updatedAt?: string | null
- updatedBy?: string | null
- }
- Relationships: [
- {
- foreignKeyName: "requestForQuoteSupplier_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteSupplier_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteSupplier_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteSupplier_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteSupplier_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- {
- foreignKeyName: "requestForQuoteSupplier_requestForQuoteId_fkey"
- columns: ["requestForQuoteId"]
- isOneToOne: false
- referencedRelation: "requestForQuote"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteSupplier_requestForQuoteId_fkey"
- columns: ["requestForQuoteId"]
- isOneToOne: false
- referencedRelation: "requestForQuotes"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteSupplier_supplierContactId_fkey"
- columns: ["supplierContactId"]
- isOneToOne: false
- referencedRelation: "contact"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteSupplier_supplierId_fkey"
- columns: ["supplierId"]
- isOneToOne: false
- referencedRelation: "contractors"
- referencedColumns: ["supplierId"]
- },
- {
- foreignKeyName: "requestForQuoteSupplier_supplierId_fkey"
- columns: ["supplierId"]
- isOneToOne: false
- referencedRelation: "partners"
- referencedColumns: ["supplierId"]
- },
- {
- foreignKeyName: "requestForQuoteSupplier_supplierId_fkey"
- columns: ["supplierId"]
- isOneToOne: false
- referencedRelation: "purchaseOrderSuppliers"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteSupplier_supplierId_fkey"
- columns: ["supplierId"]
- isOneToOne: false
- referencedRelation: "supplier"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteSupplier_supplierId_fkey"
- columns: ["supplierId"]
- isOneToOne: false
- referencedRelation: "suppliers"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteSupplier_supplierLocationId_fkey"
- columns: ["supplierLocationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
- {
- foreignKeyName: "requestForQuoteSupplier_supplierLocationId_fkey"
- columns: ["supplierLocationId"]
- isOneToOne: false
- referencedRelation: "location"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteSupplier_supplierLocationId_fkey"
- columns: ["supplierLocationId"]
- isOneToOne: false
- referencedRelation: "purchaseOrders"
- referencedColumns: ["locationId"]
- },
- {
- foreignKeyName: "requestForQuoteSupplier_supplierLocationId_fkey"
- columns: ["supplierLocationId"]
- isOneToOne: false
- referencedRelation: "salesOrders"
- referencedColumns: ["locationId"]
- },
- {
- foreignKeyName: "requestForQuoteSupplier_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteSupplier_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteSupplier_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteSupplier_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteSupplier_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- ]
- }
- requestForQuoteSupplierLine: {
- Row: {
- createdAt: string | null
- createdBy: string
- id: string
- requestForQuoteLineId: string
- requestForQuoteSupplierId: string
- unitPrice: number
- updatedAt: string | null
- updatedBy: string | null
- }
- Insert: {
- createdAt?: string | null
- createdBy: string
- id?: string
- requestForQuoteLineId: string
- requestForQuoteSupplierId: string
- unitPrice: number
- updatedAt?: string | null
- updatedBy?: string | null
- }
- Update: {
- createdAt?: string | null
- createdBy?: string
- id?: string
- requestForQuoteLineId?: string
- requestForQuoteSupplierId?: string
- unitPrice?: number
- updatedAt?: string | null
- updatedBy?: string | null
- }
- Relationships: [
- {
- foreignKeyName: "requestForQuoteSupplierLine_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteSupplierLine_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteSupplierLine_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteSupplierLine_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteSupplierLine_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- {
- foreignKeyName: "requestForQuoteSupplierLine_requestForQuoteLineId_fkey"
- columns: ["requestForQuoteLineId"]
- isOneToOne: false
- referencedRelation: "requestForQuoteLine"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteSupplierLine_requestForQuoteSupplierId_fkey"
- columns: ["requestForQuoteSupplierId"]
- isOneToOne: false
- referencedRelation: "requestForQuoteSupplier"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteSupplierLine_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteSupplierLine_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteSupplierLine_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteSupplierLine_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuoteSupplierLine_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- ]
- }
salesOrder: {
Row: {
assignee: string | null
@@ -19166,14 +18338,17 @@ export type Database = {
userToCompany: {
Row: {
companyId: string
+ role: Database["public"]["Enums"]["role"]
userId: string
}
Insert: {
companyId: string
+ role: Database["public"]["Enums"]["role"]
userId: string
}
Update: {
companyId?: string
+ role?: Database["public"]["Enums"]["role"]
userId?: string
}
Relationships: [
@@ -20118,6 +19293,7 @@ export type Database = {
name: string | null
phone: string | null
postalCode: string | null
+ role: Database["public"]["Enums"]["role"] | null
state: string | null
taxId: string | null
updatedBy: string | null
@@ -23437,193 +22613,6 @@ export type Database = {
},
]
}
- requestForQuotes: {
- Row: {
- assignee: string | null
- companyId: string | null
- createdAt: string | null
- createdBy: string | null
- customFields: Json | null
- expirationDate: string | null
- favorite: boolean | null
- id: string | null
- itemIds: string[] | null
- locationId: string | null
- locationName: string | null
- name: string | null
- notes: string | null
- receiptDate: string | null
- requestForQuoteId: string | null
- revisionId: number | null
- status: Database["public"]["Enums"]["requestForQuoteStatus"] | null
- supplierIds: string[] | null
- updatedAt: string | null
- updatedBy: string | null
- }
- Relationships: [
- {
- foreignKeyName: "requestForQuote_assignee_fkey"
- columns: ["assignee"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_assignee_fkey"
- columns: ["assignee"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_assignee_fkey"
- columns: ["assignee"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_assignee_fkey"
- columns: ["assignee"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_assignee_fkey"
- columns: ["assignee"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- {
- foreignKeyName: "requestForQuote_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "company"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "companies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "customFieldTables"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "requestForQuote_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "integrations"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "requestForQuote_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- {
- foreignKeyName: "requestForQuote_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "location"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "itemQuantities"
- referencedColumns: ["locationId"]
- },
- {
- foreignKeyName: "requestForQuote_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "purchaseOrders"
- referencedColumns: ["locationId"]
- },
- {
- foreignKeyName: "requestForQuote_locationId_fkey"
- columns: ["locationId"]
- isOneToOne: false
- referencedRelation: "salesOrders"
- referencedColumns: ["locationId"]
- },
- {
- foreignKeyName: "requestForQuote_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "requestForQuote_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- ]
- }
salesOrderCustomers: {
Row: {
companyId: string | null
@@ -24974,6 +23963,7 @@ export type Database = {
get_claims: {
Args: {
uid: string
+ company: string
}
Returns: Json
}
@@ -25041,7 +24031,8 @@ export type Database = {
}
has_role: {
Args: {
- role: string
+ required_role: string
+ company: string
}
Returns: boolean
}
@@ -25343,7 +24334,7 @@ export type Database = {
| "Manufacturing Consumption"
| "Manufacturing Output"
receiptStatus: "Draft" | "Pending" | "Posted"
- requestForQuoteStatus: "Draft" | "Sent" | "Expired" | "Closed"
+ role: "customer" | "employee" | "supplier"
salesOrderLineType:
| "Comment"
| "Part"
diff --git a/packages/database/supabase/functions/seed-company/index.ts b/packages/database/supabase/functions/seed-company/index.ts
index 12966cf2ee..fe8e807a49 100644
--- a/packages/database/supabase/functions/seed-company/index.ts
+++ b/packages/database/supabase/functions/seed-company/index.ts
@@ -43,7 +43,7 @@ serve(async (req: Request) => {
await db.transaction().execute(async (trx) => {
await trx
.insertInto("userToCompany")
- .values([{ userId, companyId }])
+ .values([{ userId, companyId, role: "employee" }])
.execute();
// high-order groups
diff --git a/packages/database/supabase/migrations/20230123004116_users-and-companies.sql b/packages/database/supabase/migrations/20230123004116_users-and-companies.sql
new file mode 100644
index 0000000000..531bcda45b
--- /dev/null
+++ b/packages/database/supabase/migrations/20230123004116_users-and-companies.sql
@@ -0,0 +1,56 @@
+CREATE TABLE "user" (
+ "id" TEXT NOT NULL,
+ "email" TEXT NOT NULL,
+ "firstName" TEXT NOT NULL,
+ "lastName" TEXT NOT NULL,
+ "fullName" TEXT GENERATED ALWAYS AS ("firstName" || ' ' || "lastName") STORED,
+ "about" TEXT NOT NULL DEFAULT '',
+ "avatarUrl" TEXT,
+ "active" BOOLEAN DEFAULT TRUE,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+
+ CONSTRAINT "user_pkey" PRIMARY KEY ("id")
+);
+
+CREATE UNIQUE INDEX "index_user_email_key" ON "user"("email");
+CREATE INDEX "index_user_fullName" ON "user"("fullName");
+
+CREATE TABLE "company" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "name" TEXT NOT NULL,
+ "taxId" TEXT,
+ "logo" TEXT,
+ "addressLine1" TEXT,
+ "addressLine2" TEXT,
+ "city" TEXT,
+ "state" TEXT,
+ "postalCode" TEXT,
+ "countryCode" TEXT,
+ "phone" TEXT,
+ "fax" TEXT,
+ "email" TEXT,
+ "website" TEXT,
+ "updatedBy" TEXT,
+
+ CONSTRAINT "company_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "accountDefault_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")
+);
+
+CREATE TYPE "role" AS ENUM ('customer', 'employee', 'supplier');
+
+CREATE TABLE "userToCompany" (
+ "userId" TEXT NOT NULL REFERENCES "user" ("id") ON UPDATE CASCADE ON DELETE CASCADE,
+ "companyId" TEXT NOT NULL REFERENCES "company" ("id") ON UPDATE CASCADE ON DELETE CASCADE,
+ "role" "role" NOT NULL,
+
+ CONSTRAINT "userToCompany_pkey" PRIMARY KEY ("userId", "companyId")
+);
+
+CREATE TABLE "userPermission" (
+ "id" TEXT NOT NULL,
+ "permissions" JSONB DEFAULT '{}',
+
+ CONSTRAINT "userPermission_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "userPermission_id_fkey" FOREIGN KEY ("id") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE
+);
\ No newline at end of file
diff --git a/packages/database/supabase/migrations/20230123004206_claims.sql b/packages/database/supabase/migrations/20230123004206_claims.sql
index d19ee200ec..c363085eb1 100644
--- a/packages/database/supabase/migrations/20230123004206_claims.sql
+++ b/packages/database/supabase/migrations/20230123004206_claims.sql
@@ -72,15 +72,14 @@ CREATE OR REPLACE FUNCTION get_permission_companies(claim text) RETURNS text[]
END;
$$;
-CREATE OR REPLACE FUNCTION has_role(role text) RETURNS "bool"
+CREATE OR REPLACE FUNCTION has_role(required_role text, company text) RETURNS "bool"
LANGUAGE "plpgsql" SECURITY DEFINER SET search_path = public
AS $$
+ DECLARE
+ user_role text;
BEGIN
- IF (get_my_claim('role'::text)) = ('"' || role || '"'::text)::jsonb THEN
- return true;
- ELSE
- return false;
- END IF;
+ SELECT role INTO user_role FROM public."userToCompany" WHERE "userId" = auth.uid()::text AND "companyId" = company;
+ return user_role = required_role;
END;
$$;
@@ -133,18 +132,22 @@ CREATE OR REPLACE FUNCTION get_company_id_from_foreign_key(foreign_key TEXT, tbl
END;
$$;
-CREATE OR REPLACE FUNCTION get_claims(uid text) RETURNS "jsonb"
- LANGUAGE "plpgsql" SECURITY DEFINER SET search_path = public
- AS $$
- DECLARE claims jsonb;
- DECLARE perms jsonb;
- BEGIN
- select raw_app_meta_data from auth.users into claims where id = uid::uuid;
- select permissions from "userPermission" into perms where id = uid::text;
- return (claims || perms)::jsonb;
-
- END;
+CREATE OR REPLACE FUNCTION get_claims(uid text, company text) RETURNS "jsonb"
+ LANGUAGE "plpgsql" SECURITY DEFINER SET search_path = public
+ AS $$
+ DECLARE company_role text;
+ DECLARE role_object jsonb;
+ DECLARE perms jsonb;
+ BEGIN
+ select role from "userToCompany" into company_role where "userId" = uid AND "companyId" = company;
+ select permissions from "userPermission" into perms where id = uid;
+ role_object := jsonb_build_object('role', company_role);
+
+
+ return (role_object || perms)::jsonb;
+ END;
$$;
+
NOTIFY pgrst, 'reload schema';
\ No newline at end of file
diff --git a/packages/database/supabase/migrations/20230123004316_users.sql b/packages/database/supabase/migrations/20230123004316_users.sql
deleted file mode 100644
index 6edd2fba1e..0000000000
--- a/packages/database/supabase/migrations/20230123004316_users.sql
+++ /dev/null
@@ -1,17 +0,0 @@
-CREATE TABLE "user" (
- "id" TEXT NOT NULL,
- "email" TEXT NOT NULL,
- "firstName" TEXT NOT NULL,
- "lastName" TEXT NOT NULL,
- "fullName" TEXT GENERATED ALWAYS AS ("firstName" || ' ' || "lastName") STORED,
- "about" TEXT NOT NULL DEFAULT '',
- "avatarUrl" TEXT,
- "active" BOOLEAN DEFAULT TRUE,
- "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
- "updatedAt" TIMESTAMP WITH TIME ZONE,
-
- CONSTRAINT "user_pkey" PRIMARY KEY ("id")
-);
-
-CREATE UNIQUE INDEX "index_user_email_key" ON "user"("email");
-CREATE INDEX "index_user_fullName" ON "user"("fullName");
diff --git a/packages/database/supabase/migrations/20230123004317_companies.sql b/packages/database/supabase/migrations/20230123004317_companies-rls.sql
similarity index 69%
rename from packages/database/supabase/migrations/20230123004317_companies.sql
rename to packages/database/supabase/migrations/20230123004317_companies-rls.sql
index ac4d418c20..03a176e87c 100644
--- a/packages/database/supabase/migrations/20230123004317_companies.sql
+++ b/packages/database/supabase/migrations/20230123004317_companies-rls.sql
@@ -1,27 +1,6 @@
-CREATE TABLE "company" (
- "id" TEXT NOT NULL DEFAULT xid(),
- "name" TEXT NOT NULL,
- "taxId" TEXT,
- "logo" TEXT,
- "addressLine1" TEXT,
- "addressLine2" TEXT,
- "city" TEXT,
- "state" TEXT,
- "postalCode" TEXT,
- "countryCode" TEXT,
- "phone" TEXT,
- "fax" TEXT,
- "email" TEXT,
- "website" TEXT,
- "updatedBy" TEXT,
-
- CONSTRAINT "company_pkey" PRIMARY KEY ("id"),
- CONSTRAINT "accountDefault_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")
-);
-
ALTER TABLE "company" ENABLE ROW LEVEL SECURITY;
-CREATE POLICY "Employees with settings_create can create company" ON "company"
+CREATE POLICY "Anyone with settings_create can create company" ON "company"
FOR INSERT
WITH CHECK (
has_any_company_permission('settings_create')
@@ -30,22 +9,17 @@ CREATE POLICY "Employees with settings_create can create company" ON "company"
CREATE POLICY "Employees with settings_update can update company" ON "company"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "id") AND
has_company_permission('settings_update', "id")
);
CREATE POLICY "Employees with settings_delete can delete company" ON "company"
FOR DELETE
USING (
+ has_role('employee', "id") AND
has_company_permission('settings_delete', "id")
);
-CREATE TABLE "userToCompany" (
- "userId" TEXT NOT NULL REFERENCES "user" ("id") ON UPDATE CASCADE ON DELETE CASCADE,
- "companyId" TEXT NOT NULL REFERENCES "company" ("id") ON UPDATE CASCADE ON DELETE CASCADE,
-
- CONSTRAINT "userToCompany_pkey" PRIMARY KEY ("userId", "companyId")
-);
CREATE POLICY "Authenticated users can view company" ON "company"
FOR SELECT
@@ -66,18 +40,21 @@ CREATE POLICY "Authenticated users can view userToCompany" ON "userToCompany"
CREATE POLICY "Employees with users_create can create userToCompany" ON "userToCompany"
FOR INSERT
WITH CHECK (
+ has_role('employee', "companyId") AND
has_company_permission('users_create', "companyId")
);
CREATE POLICY "Employees with users_update can update userToCompany" ON "userToCompany"
FOR UPDATE
USING (
+ has_role('employee', "companyId") AND
has_company_permission('users_update', "companyId")
);
CREATE POLICY "Employees with users_delete can delete userToCompany" ON "userToCompany"
FOR DELETE
USING (
+ has_role('employee', "companyId") AND
has_company_permission('users_delete', "companyId")
);
@@ -99,14 +76,6 @@ INSERT INTO "user" ("id", "email", "firstName", "lastName")
VALUES ('system', '[email protected]', 'System', 'Operation');
-CREATE TABLE "userPermission" (
- "id" TEXT NOT NULL,
- "permissions" JSONB DEFAULT '{}',
-
- CONSTRAINT "userPermission_pkey" PRIMARY KEY ("id"),
- CONSTRAINT "userPermission_id_fkey" FOREIGN KEY ("id") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE
-);
-
ALTER TABLE "userPermission" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Users can view their own permissions" ON "userPermission" FOR SELECT USING (TRUE);
diff --git a/packages/database/supabase/migrations/20230123004339_employee-types.sql b/packages/database/supabase/migrations/20230123004339_employee-types.sql
index aa99dcc549..572d87dfa6 100644
--- a/packages/database/supabase/migrations/20230123004339_employee-types.sql
+++ b/packages/database/supabase/migrations/20230123004339_employee-types.sql
@@ -18,7 +18,7 @@ CREATE INDEX "employeeType_companyId_idx" ON "employeeType" ("companyId");
ALTER TABLE "employeeType" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with users_update can view/modify employee types" ON "employeeType" FOR ALL USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('users_update', "companyId")
);
diff --git a/packages/database/supabase/migrations/20230123004409_permissions.sql b/packages/database/supabase/migrations/20230123004409_permissions.sql
index d7ded14311..d9a76148c1 100644
--- a/packages/database/supabase/migrations/20230123004409_permissions.sql
+++ b/packages/database/supabase/migrations/20230123004409_permissions.sql
@@ -37,7 +37,7 @@ CREATE TABLE "employeeTypePermission" (
ALTER TABLE "employeeTypePermission" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with users_update can view/modify permissions for employee type permissions" ON "employeeTypePermission" FOR ALL USING (
- has_role('employee') AND
+ has_role('employee', get_company_id_from_foreign_key("employeeTypeId", 'employeeType')) AND
has_company_permission('users_update', get_company_id_from_foreign_key("employeeTypeId", 'employeeType'))
);
diff --git a/packages/database/supabase/migrations/20230123004436_employee.sql b/packages/database/supabase/migrations/20230123004436_employee.sql
index 4c37981c99..bdf1e5ee92 100644
--- a/packages/database/supabase/migrations/20230123004436_employee.sql
+++ b/packages/database/supabase/migrations/20230123004436_employee.sql
@@ -19,14 +19,17 @@ CREATE POLICY "Employees can view employees from their company" ON "employee" FO
);
CREATE POLICY "Employees with users_update can create employees" ON "employee" FOR INSERT WITH CHECK (
+ has_role('employee', "companyId") AND
has_company_permission('users_create', "companyId")
);
CREATE POLICY "Employees with users_update can update employees" ON "employee" FOR UPDATE USING (
+ has_role('employee', "companyId") AND
has_company_permission('users_update', "companyId")
);
CREATE POLICY "Employees with users_update can delete employees" ON "employee" FOR DELETE USING (
+ has_role('employee', "companyId") AND
has_company_permission('users_delete', "companyId")
);
diff --git a/packages/database/supabase/migrations/20230123004514_buckets.sql b/packages/database/supabase/migrations/20230123004514_buckets.sql
index 070f2fb201..2191863a49 100644
--- a/packages/database/supabase/migrations/20230123004514_buckets.sql
+++ b/packages/database/supabase/migrations/20230123004514_buckets.sql
@@ -10,10 +10,9 @@ ON storage.objects FOR SELECT USING (
AND (auth.role() = 'authenticated')
);
-CREATE POLICY "Employees with settings_create can insert into the public bucket"
+CREATE POLICY "Anyone with settings_create can insert into the public bucket"
ON storage.objects FOR INSERT WITH CHECK (
- bucket_id = 'public'
- AND has_role('employee')
+ bucket_id = 'public'
AND (
'0' = ANY(
get_permission_companies('settings_create')
@@ -24,10 +23,9 @@ ON storage.objects FOR INSERT WITH CHECK (
)
);
-CREATE POLICY "Employees with settings_update can update the public bucket"
+CREATE POLICY "Anyone with settings_update can update the public bucket"
ON storage.objects FOR UPDATE USING (
bucket_id = 'public'
- AND has_role('employee')
AND (
'0' = ANY(
get_permission_companies('settings_create')
@@ -38,10 +36,9 @@ ON storage.objects FOR UPDATE USING (
)
);
-CREATE POLICY "Employees with settings_delete can delete from public bucket"
+CREATE POLICY "Anyone with settings_delete can delete from public bucket"
ON storage.objects FOR DELETE USING (
bucket_id = 'public'
- AND has_role('employee')
AND (
'0' = ANY(
get_permission_companies('settings_create')
diff --git a/packages/database/supabase/migrations/20230123004632_groups.sql b/packages/database/supabase/migrations/20230123004632_groups.sql
index b8a760477f..72e1a496d4 100644
--- a/packages/database/supabase/migrations/20230123004632_groups.sql
+++ b/packages/database/supabase/migrations/20230123004632_groups.sql
@@ -43,6 +43,28 @@ CREATE INDEX index_membership_groupId ON "membership" ("groupId");
CREATE INDEX index_membership_memberGroupId ON "membership" ("memberGroupId");
CREATE INDEX index_membership_memberUserId ON "membership" ("memberUserId");
+ALTER TABLE "membership" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "All employees can view memberships" ON "membership" FOR SELECT USING (
+ has_role('employee', get_company_id_from_foreign_key("groupId", 'group'))
+);
+
+CREATE POLICY "Employees with users_update can create memberships" ON "membership" FOR INSERT WITH CHECK (
+ has_role('employee', get_company_id_from_foreign_key("groupId", 'group')) AND
+ has_company_permission('users_update', get_company_id_from_foreign_key("groupId", 'group'))
+);
+
+CREATE POLICY "Employees with users_update can update memberships" ON "membership" FOR UPDATE USING (
+ has_role('employee', get_company_id_from_foreign_key("groupId", 'group')) AND
+ has_company_permission('users_update', get_company_id_from_foreign_key("groupId", 'group'))
+);
+
+CREATE POLICY "Employees with users_update can delete memberships" ON "membership" FOR DELETE USING (
+ has_role('employee', get_company_id_from_foreign_key("groupId", 'group')) AND
+ has_company_permission('users_update', get_company_id_from_foreign_key("groupId", 'group'))
+);
+
+
CREATE FUNCTION public.create_employee_type_group()
RETURNS TRIGGER AS $$
BEGIN
diff --git a/packages/database/supabase/migrations/20230123212853_search.sql b/packages/database/supabase/migrations/20230123212853_search.sql
index be859c5d09..8f7d7aee1a 100644
--- a/packages/database/supabase/migrations/20230123212853_search.sql
+++ b/packages/database/supabase/migrations/20230123212853_search.sql
@@ -121,7 +121,11 @@ 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 (has_company_permission('sales_view', "companyId") AND entity IN ('Customer', 'Sales Order', 'Quotation') AND has_role('employee'));
+ USING (
+ has_company_permission('sales_view', "companyId") AND
+ entity IN ('Customer', 'Sales Order', 'Quotation') AND
+ has_role('employee', "companyId")
+ );
-- 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"
diff --git a/packages/database/supabase/migrations/20230126050441_abac.sql b/packages/database/supabase/migrations/20230126050441_abac.sql
index dfac870bcb..bd5c454cc2 100644
--- a/packages/database/supabase/migrations/20230126050441_abac.sql
+++ b/packages/database/supabase/migrations/20230126050441_abac.sql
@@ -5,7 +5,7 @@ ALTER TABLE "contact" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with purchasing_view can view contacts that are suppliers" ON "contact"
FOR SELECT
USING (
- has_role('employee')
+ has_role('employee', "companyId")
AND has_company_permission('purchasing_view', "companyId")
AND id IN (
SELECT "contactId" FROM "supplierContact"
@@ -15,7 +15,7 @@ CREATE POLICY "Employees with purchasing_view can view contacts that are supplie
CREATE POLICY "Employees with sales_view can view contacts that are customer" ON "contact"
FOR SELECT
USING (
- has_role('employee')
+ has_role('employee', "companyId")
AND has_company_permission('sales_view', "companyId")
AND id IN (
SELECT "contactId" FROM "customerContact"
@@ -25,7 +25,7 @@ CREATE POLICY "Employees with sales_view can view contacts that are customer" ON
CREATE POLICY "Suppliers with purchasing_view can view contacts from their organization" ON "contact"
FOR SELECT
USING (
- has_role('supplier')
+ has_role('supplier', "companyId")
AND has_company_permission('sales_view', "companyId")
AND (
id IN (
@@ -39,7 +39,7 @@ CREATE POLICY "Suppliers with purchasing_view can view contacts from their organ
CREATE POLICY "Customers with sales_view can view contacts from their organization" ON "contact"
FOR SELECT
USING (
- has_role('customer')
+ has_role('customer', "companyId")
AND has_company_permission('sales_view', "companyId")
AND (
id IN (
@@ -53,7 +53,7 @@ CREATE POLICY "Customers with sales_view can view contacts from their organizati
CREATE POLICY "Many employees can create contacts" ON "contact"
FOR INSERT
WITH CHECK (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
(
has_company_permission('purchasing_create', "companyId") OR
has_company_permission('sales_create', "companyId") OR
@@ -65,7 +65,7 @@ CREATE POLICY "Many employees can create contacts" ON "contact"
CREATE POLICY "Suppliers with purchasing_create can create contacts from their organization" ON "contact"
FOR INSERT
WITH CHECK (
- has_role('supplier')
+ has_role('supplier', "companyId")
AND has_company_permission('purchasing_create', "companyId")
AND (
id IN (
@@ -79,7 +79,7 @@ CREATE POLICY "Suppliers with purchasing_create can create contacts from their o
CREATE POLICY "Customers with sales_create can create contacts from their organization" ON "contact"
FOR INSERT
WITH CHECK (
- has_role('customer')
+ has_role('customer', "companyId")
AND has_company_permission('sales_create', "companyId")
AND (
id IN (
@@ -93,7 +93,7 @@ CREATE POLICY "Customers with sales_create can create contacts from their organi
CREATE POLICY "Employees with purchasing_update can update supplier contacts" ON "contact"
FOR UPDATE
USING (
- has_role('employee')
+ has_role('employee', "companyId")
AND has_company_permission('purchasing_update', "companyId")
AND id IN (
SELECT "contactId" FROM "supplierContact"
@@ -103,7 +103,7 @@ CREATE POLICY "Employees with purchasing_update can update supplier contacts" ON
CREATE POLICY "Suppliers with purchasing_update can update contacts from their organization" ON "contact"
FOR UPDATE
USING (
- has_role('supplier')
+ has_role('supplier', "companyId")
AND has_company_permission('purchasing_update', "companyId")
AND (
id IN (
@@ -117,7 +117,7 @@ CREATE POLICY "Suppliers with purchasing_update can update contacts from their o
CREATE POLICY "Employees with sales_update can update customer contacts" ON "contact"
FOR UPDATE
USING (
- has_role('employee')
+ has_role('employee', "companyId")
AND has_company_permission('sales_update', "companyId")
AND id IN (
SELECT "contactId" FROM "customerContact"
@@ -127,7 +127,7 @@ CREATE POLICY "Employees with sales_update can update customer contacts" ON "con
CREATE POLICY "Customers with sales_update can update contacts from their organization" ON "contact"
FOR UPDATE
USING (
- has_role('customer')
+ has_role('customer', "companyId")
AND has_company_permission('sales_update', "companyId")
AND (
id IN (
@@ -141,7 +141,7 @@ CREATE POLICY "Customers with sales_update can update contacts from their organi
CREATE POLICY "Employees with purchasing_delete can delete supplier contacts" ON "contact"
FOR DELETE
USING (
- has_role('employee')
+ has_role('employee', "companyId")
AND has_company_permission('purchasing_delete', "companyId")
AND id IN (
SELECT "contactId" FROM "supplierContact"
@@ -151,7 +151,7 @@ CREATE POLICY "Employees with purchasing_delete can delete supplier contacts" ON
CREATE POLICY "Suppliers with purchasing_delete can delete contacts from their organization" ON "contact"
FOR DELETE
USING (
- has_role('supplier')
+ has_role('supplier', "companyId")
AND has_company_permission('purchasing_delete', "companyId")
AND (
id IN (
@@ -165,7 +165,7 @@ CREATE POLICY "Suppliers with purchasing_delete can delete contacts from their o
CREATE POLICY "Employees with sales_delete can delete customer contacts" ON "contact"
FOR DELETE
USING (
- has_role('employee')
+ has_role('employee', "companyId")
AND has_company_permission('sales_delete', "companyId")
AND id IN (
SELECT "contactId" FROM "customerContact"
@@ -175,7 +175,7 @@ CREATE POLICY "Employees with sales_delete can delete customer contacts" ON "con
CREATE POLICY "Customers with sales_delete can delete contacts from their organization" ON "contact"
FOR DELETE
USING (
- has_role('customer')
+ has_role('customer', "companyId")
AND has_company_permission('sales_delete', "companyId")
AND (
id IN (
@@ -193,28 +193,28 @@ ALTER TABLE "customerType" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with sales_view can view customer types" ON "customerType"
FOR SELECT
USING (
- has_role('employee')
+ has_role('employee', "companyId")
AND has_company_permission('sales_view', "companyId")
);
CREATE POLICY "Employees with sales_create can create customer types" ON "customerType"
FOR INSERT
WITH CHECK (
- has_role('employee')
+ has_role('employee', "companyId")
AND has_company_permission('sales_create', "companyId")
);
CREATE POLICY "Employees with sales_update can update customer types" ON "customerType"
FOR UPDATE
USING (
- has_role('employee')
+ has_role('employee', "companyId")
AND has_company_permission('sales_update', "companyId")
);
CREATE POLICY "Employees with sales_delete can delete customer types" ON "customerType"
FOR DELETE
USING (
- has_role('employee')
+ has_role('employee', "companyId")
AND has_company_permission('sales_delete', "companyId")
);
@@ -225,14 +225,14 @@ ALTER TABLE "customer" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with sales_view can view customer" ON "customer"
FOR SELECT
USING (
- has_role('employee')
+ has_role('employee', "companyId")
AND has_company_permission('sales_view', "companyId")
);
CREATE POLICY "Customers with sales_view can their own organization" ON "customer"
FOR SELECT
USING (
- has_role('customer')
+ has_role('customer', "companyId")
AND has_company_permission('sales_view', "companyId")
AND id IN (
SELECT "customerId" FROM "customerAccount" WHERE id::uuid = auth.uid()
@@ -242,21 +242,21 @@ CREATE POLICY "Customers with sales_view can their own organization" ON "custome
CREATE POLICY "Employees with sales_create can create customers" ON "customer"
FOR INSERT
WITH CHECK (
- has_role('employee')
+ has_role('employee', "companyId")
AND has_company_permission('sales_create', "companyId")
);
CREATE POLICY "Employees with sales_update can update customers" ON "customer"
FOR UPDATE
USING (
- has_role('employee')
+ has_role('employee', "companyId")
AND has_company_permission('sales_update', "companyId")
);
CREATE POLICY "Customers with sales_update can update their own organization" ON "customer"
FOR UPDATE
USING (
- has_role('customer')
+ has_role('customer', "companyId")
AND has_company_permission('sales_update', "companyId")
AND id IN (
SELECT "customerId" FROM "customerAccount" WHERE id::uuid = auth.uid()
@@ -266,7 +266,7 @@ CREATE POLICY "Customers with sales_update can update their own organization" ON
CREATE POLICY "Employees with sales_delete can delete customers" ON "customer"
FOR DELETE
USING (
- has_role('employee')
+ has_role('employee', "companyId")
AND has_company_permission('sales_delete', "companyId")
);
@@ -277,21 +277,15 @@ ALTER TABLE "customerContact" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with sales_view can view customer contact" ON "customerContact"
FOR SELECT
USING (
- has_role('employee')
- AND (
- '0' = ANY(
- get_permission_companies('sales_view')
- )
- OR "customerId" IN (
- SELECT "customerId" FROM "customer" WHERE "companyId" = ANY(get_permission_companies('sales_view'))
- )
- )
+ has_role('employee', get_company_id_from_foreign_key("customerId", 'customer')) AND
+ has_company_permission('sales_view', get_company_id_from_foreign_key("customerId", 'customer'))
);
CREATE POLICY "Customers with sales_view can their own customer contacts" ON "customerContact"
FOR SELECT
USING (
- has_role('customer')
+ has_role('customer', get_company_id_from_foreign_key("customerId", 'customer')) AND
+ has_company_permission('sales_view', get_company_id_from_foreign_key("customerId", 'customer'))
AND "customerId" IN (
SELECT "customerId" FROM "customerAccount" WHERE id::uuid = auth.uid()
)
@@ -300,22 +294,15 @@ CREATE POLICY "Customers with sales_view can their own customer contacts" ON "cu
CREATE POLICY "Employees with sales_create can create customer contacts" ON "customerContact"
FOR INSERT
WITH CHECK (
- has_role('employee')
- AND (
- '0' = ANY(
- get_permission_companies('sales_create')
- )
- OR "customerId" IN (
- SELECT "customerId" FROM "customer" WHERE "companyId" = ANY(get_permission_companies('sales_create'))
- )
- )
+ has_role('employee', get_company_id_from_foreign_key("customerId", 'customer')) AND
+ has_company_permission('sales_create', get_company_id_from_foreign_key("customerId", 'customer'))
);
CREATE POLICY "Customers with sales_create can create customer contacts" ON "customerContact"
FOR INSERT
WITH CHECK (
- has_role('customer')
- -- TODO: get_permission_companies('sales_create').length > 0
+ has_role('customer', get_company_id_from_foreign_key("customerId", 'customer')) AND
+ has_company_permission('sales_create', get_company_id_from_foreign_key("customerId", 'customer'))
AND "customerId" IN (
SELECT "customerId" FROM "customerAccount" WHERE id::uuid = auth.uid()
)
@@ -324,22 +311,15 @@ CREATE POLICY "Customers with sales_create can create customer contacts" ON "cus
CREATE POLICY "Employees with sales_update can update customer contacts" ON "customerContact"
FOR UPDATE
USING (
- has_role('employee')
- AND (
- '0' = ANY(
- get_permission_companies('sales_update')
- )
- OR "customerId" IN (
- SELECT "customerId" FROM "customer" WHERE "companyId" = ANY(get_permission_companies('sales_update'))
- )
- )
+ has_role('employee', get_company_id_from_foreign_key("customerId", 'customer')) AND
+ has_company_permission('sales_update', get_company_id_from_foreign_key("customerId", 'customer'))
);
CREATE POLICY "Customers with sales_update can update their customer contacts" ON "customerContact"
FOR UPDATE
USING (
- has_role('customer')
- -- TODO: get_permission_companies('sales_update').length > 0
+ has_role('customer', get_company_id_from_foreign_key("customerId", 'customer'))
+ AND has_company_permission('sales_update', get_company_id_from_foreign_key("customerId", 'customer'))
AND "customerId" IN (
SELECT "customerId" FROM "customerAccount" WHERE id::uuid = auth.uid()
)
@@ -348,15 +328,8 @@ CREATE POLICY "Customers with sales_update can update their customer contacts" O
CREATE POLICY "Employees with sales_delete can delete customer contacts" ON "customerContact"
FOR DELETE
USING (
- has_role('employee')
- AND (
- '0' = ANY(
- get_permission_companies('sales_delete')
- )
- OR "customerId" IN (
- SELECT "customerId" FROM "customer" WHERE "companyId" = ANY(get_permission_companies('sales_delete'))
- )
- )
+ has_role('employee', get_company_id_from_foreign_key("customerId", 'customer')) AND
+ has_company_permission('sales_delete', get_company_id_from_foreign_key("customerId", 'customer'))
);
-- supplierType
@@ -366,28 +339,28 @@ ALTER TABLE "supplierType" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with purchasing_view can view supplier types" ON "supplierType"
FOR SELECT
USING (
- has_role('employee')
+ has_role('employee', "companyId")
AND has_company_permission('purchasing_view', "companyId")
);
CREATE POLICY "Employees with purchasing_create can create supplier types" ON "supplierType"
FOR INSERT
WITH CHECK (
- has_role('employee')
+ has_role('employee', "companyId")
AND has_company_permission('purchasing_create', "companyId")
);
CREATE POLICY "Employees with purchasing_update can update supplier types" ON "supplierType"
FOR UPDATE
USING (
- has_role('employee')
+ has_role('employee', "companyId")
AND has_company_permission('purchasing_update', "companyId")
);
CREATE POLICY "Employees with purchasing_delete can delete supplier types" ON "supplierType"
FOR DELETE
USING (
- has_role('employee')
+ has_role('employee', "companyId")
AND has_company_permission('purchasing_delete', "companyId")
);
@@ -398,14 +371,14 @@ ALTER TABLE "supplier" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with purchasing_view can view supplier" ON "supplier"
FOR SELECT
USING (
- has_role('employee')
+ has_role('employee', "companyId")
AND has_company_permission('purchasing_view', "companyId")
);
CREATE POLICY "Suppliers with purchasing_view can their own organization" ON "supplier"
FOR SELECT
USING (
- has_role('supplier')
+ has_role('supplier', "companyId")
AND has_company_permission('purchasing_view', "companyId")
AND id IN (
SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
@@ -415,21 +388,21 @@ CREATE POLICY "Suppliers with purchasing_view can their own organization" ON "su
CREATE POLICY "Employees with purchasing_create can create suppliers" ON "supplier"
FOR INSERT
WITH CHECK (
- has_role('employee')
+ has_role('employee', "companyId")
AND has_company_permission('purchasing_create', "companyId")
);
CREATE POLICY "Employees with purchasing_update can update suppliers" ON "supplier"
FOR UPDATE
USING (
- has_role('employee')
+ has_role('employee', "companyId")
AND has_company_permission('purchasing_update', "companyId")
);
CREATE POLICY "Suppliers with purchasing_update can update their own organization" ON "supplier"
FOR UPDATE
USING (
- has_role('supplier')
+ has_role('supplier', "companyId")
AND has_company_permission('purchasing_update', "companyId")
AND id IN (
SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
@@ -439,7 +412,7 @@ CREATE POLICY "Suppliers with purchasing_update can update their own organizatio
CREATE POLICY "Employees with purchasing_delete can delete suppliers" ON "supplier"
FOR DELETE
USING (
- has_role('employee')
+ has_role('employee', "companyId")
AND has_company_permission('purchasing_delete', "companyId")
);
@@ -450,22 +423,15 @@ ALTER TABLE "supplierContact" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with purchasing_view can view supplier contact" ON "supplierContact"
FOR SELECT
USING (
- has_role('employee')
- AND (
- '0' = ANY(
- get_permission_companies('purchasing_view')
- )
- OR "supplierId" IN (
- SELECT "supplierId" FROM "supplier" WHERE "companyId" = ANY(get_permission_companies('purchasing_view'))
- )
- )
+ has_role('employee', get_company_id_from_foreign_key("supplierId", 'supplier')) AND
+ has_company_permission('purchasing_view', get_company_id_from_foreign_key("supplierId", 'supplier'))
);
CREATE POLICY "Suppliers with purchasing_view can their own supplier contacts" ON "supplierContact"
FOR SELECT
USING (
- has_role('supplier')
- -- TODO: get_permission_companies('purchasing_view').length > 0
+ has_role('supplier', get_company_id_from_foreign_key("supplierId", 'supplier')) AND
+ has_company_permission('purchasing_view', get_company_id_from_foreign_key("supplierId", 'supplier'))
AND "supplierId" IN (
SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
)
@@ -474,61 +440,34 @@ CREATE POLICY "Suppliers with purchasing_view can their own supplier contacts" O
CREATE POLICY "Employees with purchasing_create can create supplier contacts" ON "supplierContact"
FOR INSERT
WITH CHECK (
- has_role('employee')
- AND (
- '0' = ANY(
- get_permission_companies('purchasing_create')
- )
- OR "supplierId" IN (
- SELECT "supplierId" FROM "supplier" WHERE "companyId" = ANY(get_permission_companies('purchasing_create'))
- )
- )
+ has_role('employee', get_company_id_from_foreign_key("supplierId", 'supplier')) AND
+ has_company_permission('purchasing_create', get_company_id_from_foreign_key("supplierId", 'supplier'))
);
CREATE POLICY "Suppliers with purchasing_create can create supplier contacts" ON "supplierContact"
FOR INSERT
WITH CHECK (
- has_role('supplier')
- -- TODO: get_permission_companies('purchasing_create').length > 0
- AND "supplierId" IN (
- SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
- )
+ has_role('supplier', get_company_id_from_foreign_key("supplierId", 'supplier')) AND
+ has_company_permission('purchasing_create', get_company_id_from_foreign_key("supplierId", 'supplier'))
);
CREATE POLICY "Employees with purchasing_update can update supplier contacts" ON "supplierContact"
FOR UPDATE
USING (
- has_role('employee')
- AND (
- '0' = ANY(
- get_permission_companies('purchasing_update')
- )
- OR "supplierId" IN (
- SELECT "supplierId" FROM "supplier" WHERE "companyId" = ANY(get_permission_companies('purchasing_update'))
- )
- )
+ has_role('employee', get_company_id_from_foreign_key("supplierId", 'supplier')) AND
+ has_company_permission('purchasing_update', get_company_id_from_foreign_key("supplierId", 'supplier'))
);
CREATE POLICY "Suppliers with purchasing_update can update their supplier contacts" ON "supplierContact"
FOR UPDATE
USING (
- has_role('supplier')
- -- TODO: get_permission_companies('purchasing_update').length > 0
- AND "supplierId" IN (
- SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
- )
+ has_role('supplier', get_company_id_from_foreign_key("supplierId", 'supplier')) AND
+ has_company_permission('purchasing_update', get_company_id_from_foreign_key("supplierId", 'supplier'))
);
CREATE POLICY "Employees with purchasing_delete can delete supplier contacts" ON "supplierContact"
FOR DELETE
USING (
- has_role('employee')
- AND (
- '0' = ANY(
- get_permission_companies('purchasing_delete')
- )
- OR "supplierId" IN (
- SELECT "supplierId" FROM "supplier" WHERE "companyId" = ANY(get_permission_companies('purchasing_delete'))
- )
- )
+ has_role('employee', get_company_id_from_foreign_key("supplierId", 'supplier')) AND
+ has_company_permission('purchasing_delete', get_company_id_from_foreign_key("supplierId", 'supplier'))
);
\ No newline at end of file
diff --git a/packages/database/supabase/migrations/20230209041302_notes.sql b/packages/database/supabase/migrations/20230209041302_notes.sql
index 381164b1c5..6f18a0f80f 100644
--- a/packages/database/supabase/migrations/20230209041302_notes.sql
+++ b/packages/database/supabase/migrations/20230209041302_notes.sql
@@ -22,7 +22,7 @@ ALTER TABLE "note" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees can view notes" ON "note"
FOR SELECT
USING (
- has_role('employee')
+ has_role('employee', "companyId")
AND "companyId" = ANY(
SELECT "companyId" from "userToCompany" where "userId" = auth.uid()::text
)
@@ -31,7 +31,7 @@ CREATE POLICY "Employees can view notes" ON "note"
CREATE POLICY "Employees can insert notes" ON "note"
FOR INSERT
WITH CHECK (
- has_role('employee')
+ has_role('employee', "companyId")
AND "companyId" = ANY(
SELECT "companyId" from "userToCompany" where "userId" = auth.uid()::text
)
@@ -40,13 +40,13 @@ CREATE POLICY "Employees can insert notes" ON "note"
CREATE POLICY "Employees can update their own notes" ON "note"
FOR UPDATE
USING (
- has_role('employee')
+ has_role('employee', "companyId")
AND "createdBy"::uuid = auth.uid()
);
CREATE POLICY "Employees can delete their own notes" ON "note"
FOR DELETE
USING (
- has_role('employee')
+ has_role('employee', "companyId")
AND "createdBy"::uuid = auth.uid()
);
diff --git a/packages/database/supabase/migrations/20230215023746_abilities.sql b/packages/database/supabase/migrations/20230215023746_abilities.sql
index 2f183932d6..32b0983503 100644
--- a/packages/database/supabase/migrations/20230215023746_abilities.sql
+++ b/packages/database/supabase/migrations/20230215023746_abilities.sql
@@ -23,28 +23,28 @@ ALTER TABLE "ability" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with resources_view can view abilities" ON "ability"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('resources_view', "companyId")
);
CREATE POLICY "Employees with resources_create can insert abilities" ON "ability"
FOR INSERT
WITH CHECK (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('resources_create', "companyId")
);
CREATE POLICY "Employees with resources_update can update abilities" ON "ability"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('resources_update', "companyId")
);
CREATE POLICY "Employees with resources_delete can delete abilities" ON "ability"
FOR DELETE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('resources_delete', "companyId")
);
@@ -69,55 +69,27 @@ ALTER TABLE "employeeAbility" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with resources_view can view employeeAbilities" ON "employeeAbility"
FOR SELECT
USING (
- has_role('employee')
- AND (
- '0' = ANY(
- get_permission_companies('resources_view')
- )
- OR "employeeId" IN (
- SELECT "employeeId" FROM "employee" WHERE "companyId" = ANY(get_permission_companies('resources_view'))
- )
- )
+ has_role('employee', get_company_id_from_foreign_key("employeeId", 'employee')) AND
+ has_company_permission('resources_view', get_company_id_from_foreign_key("employeeId", 'employee'))
);
CREATE POLICY "Employees with resources_create can insert employeeAbilities" ON "employeeAbility"
FOR INSERT
WITH CHECK (
- has_role('employee')
- AND (
- '0' = ANY(
- get_permission_companies('resources_create')
- )
- OR "employeeId" IN (
- SELECT "employeeId" FROM "employee" WHERE "companyId" = ANY(get_permission_companies('resources_create'))
- )
- )
+ has_role('employee', get_company_id_from_foreign_key("employeeId", 'employee')) AND
+ has_company_permission('resources_create', get_company_id_from_foreign_key("employeeId", 'employee'))
);
CREATE POLICY "Employees with resources_update can update employeeAbilities" ON "employeeAbility"
FOR UPDATE
USING (
- has_role('employee')
- AND (
- '0' = ANY(
- get_permission_companies('resources_update')
- )
- OR "employeeId" IN (
- SELECT "employeeId" FROM "employee" WHERE "companyId" = ANY(get_permission_companies('resources_update'))
- )
- )
+ has_role('employee', get_company_id_from_foreign_key("employeeId", 'employee')) AND
+ has_company_permission('resources_update', get_company_id_from_foreign_key("employeeId", 'employee'))
);
CREATE POLICY "Employees with resources_delete can delete employeeAbilities" ON "employeeAbility"
FOR DELETE
USING (
- has_role('employee')
- AND (
- '0' = ANY(
- get_permission_companies('resources_delete')
- )
- OR "employeeId" IN (
- SELECT "employeeId" FROM "employee" WHERE "companyId" = ANY(get_permission_companies('resources_delete'))
- )
- )
+ has_role('employee', get_company_id_from_foreign_key("employeeId", 'employee')) AND
+ has_company_permission('resources_delete', get_company_id_from_foreign_key("employeeId", 'employee'))
);
diff --git a/packages/database/supabase/migrations/20230224035103_shifts.sql b/packages/database/supabase/migrations/20230224035103_shifts.sql
index be17bc829c..388fb7729c 100644
--- a/packages/database/supabase/migrations/20230224035103_shifts.sql
+++ b/packages/database/supabase/migrations/20230224035103_shifts.sql
@@ -30,7 +30,7 @@ ALTER TABLE "location" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees can view locations for their companies" ON "location"
FOR SELECT
USING (
- has_role('employee')
+ has_role('employee', "companyId")
AND "companyId" = ANY(
select "companyId" from "userToCompany" where "userId" = auth.uid()::text
)
@@ -40,21 +40,21 @@ CREATE POLICY "Employees with resources_create can insert locations" ON "locatio
FOR INSERT
WITH CHECK (
has_company_permission('resources_create', "companyId")
- AND has_role('employee')
+ AND has_role('employee', "companyId")
);
CREATE POLICY "Employees with resources_update can update locations" ON "location"
FOR UPDATE
USING (
has_company_permission('resources_update', "companyId")
- AND has_role('employee')
+ AND has_role('employee', "companyId")
);
CREATE POLICY "Employees with resources_delete can delete locations" ON "location"
FOR DELETE
USING (
has_company_permission('resources_delete', "companyId")
- AND has_role('employee')
+ AND has_role('employee', "companyId")
);
@@ -93,7 +93,7 @@ ALTER TABLE "shift" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees can view shifts" ON "shift"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
"companyId" = ANY(
select "companyId" from "userToCompany" where "userId" = auth.uid()::text
)
@@ -102,21 +102,21 @@ CREATE POLICY "Employees can view shifts" ON "shift"
CREATE POLICY "Employees with resources_create can insert shifts" ON "shift"
FOR INSERT
WITH CHECK (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('resources_create', "companyId")
);
CREATE POLICY "Employees with resources_update can update shifts" ON "shift"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('resources_update', "companyId")
);
CREATE POLICY "Employees with resources_delete can delete shifts" ON "shift"
FOR DELETE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('resources_delete', "companyId")
);
@@ -138,71 +138,40 @@ ALTER TABLE "employeeShift" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees can view employee shifts" ON "employeeShift"
FOR SELECT
USING (
- has_role('employee')
- AND "shiftId" IN (
- SELECT "id" FROM "shift" WHERE "companyId" = ANY(
- select "companyId" from "userToCompany" where "userId" = auth.uid()::text
- )
- )
+ has_role('employee', get_company_id_from_foreign_key("employeeId", 'employee')) AND
+ has_company_permission('resources_view', get_company_id_from_foreign_key("employeeId", 'employee'))
);
CREATE POLICY "Employees with resources_create can insert employee shifts" ON "employeeShift"
FOR INSERT
WITH CHECK (
- has_role('employee')
- AND (
- '0' = ANY(get_permission_companies('resources_create'))
- OR (
- "shiftId" IN (
- SELECT "id" FROM "shift" WHERE "companyId" = ANY(
- get_permission_companies('resources_create')
- )
- )
- )
- )
+ has_role('employee', get_company_id_from_foreign_key("employeeId", 'employee')) AND
+ has_company_permission('resources_create', get_company_id_from_foreign_key("employeeId", 'employee'))
);
CREATE POLICY "Employees with resources_update can update employee shifts" ON "employeeShift"
FOR UPDATE
USING (
- has_role('employee')
- AND (
- '0' = ANY(get_permission_companies('resources_update'))
- OR (
- "shiftId" IN (
- SELECT "id" FROM "shift" WHERE "companyId" = ANY(
- get_permission_companies('resources_update')
- )
- )
- )
- )
+ has_role('employee', get_company_id_from_foreign_key("employeeId", 'employee')) AND
+ has_company_permission('resources_update', get_company_id_from_foreign_key("employeeId", 'employee'))
);
CREATE POLICY "Employees with resources_delete can delete employee shifts" ON "employeeShift"
FOR DELETE
USING (
- has_role('employee')
- AND (
- '0' = ANY(get_permission_companies('resources_delete'))
- OR (
- "shiftId" IN (
- SELECT "id" FROM "shift" WHERE "companyId" = ANY(
- get_permission_companies('resources_delete')
- )
- )
- )
- )
+ has_role('employee', get_company_id_from_foreign_key("employeeId", 'employee')) AND
+ has_company_permission('resources_delete', get_company_id_from_foreign_key("employeeId", 'employee'))
);
CREATE TABLE "employeeJob" (
"id" TEXT NOT NULL,
- "companyId" TEXT NOT NULL,
"locationId" TEXT,
"shiftId" TEXT,
"managerId" TEXT,
"title" TEXT,
"startDate" DATE,
+ "companyId" TEXT NOT NULL,
"updatedAt" TIMESTAMP,
"updatedBy" TEXT,
"customFields" JSONB,
@@ -220,7 +189,7 @@ ALTER TABLE "employeeJob" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees can view employee jobs" ON "employeeJob"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
"companyId" = ANY(
SELECT "companyId" from "userToCompany" where "userId" = auth.uid()::text
)
@@ -229,21 +198,21 @@ CREATE POLICY "Employees can view employee jobs" ON "employeeJob"
CREATE POLICY "Employees with resources_create can insert employee jobs" ON "employeeJob"
FOR INSERT
WITH CHECK (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('resources_create', "companyId")
);
CREATE POLICY "Employees with resources_update can update employee jobs" ON "employeeJob"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('resources_create', "companyId")
);
CREATE POLICY "Employees with resources_delete can delete employee jobs" ON "employeeJob"
FOR DELETE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('resources_delete', "companyId")
);
diff --git a/packages/database/supabase/migrations/20230302030217_equipment.sql b/packages/database/supabase/migrations/20230302030217_equipment.sql
index 46963dcc37..2501df8574 100644
--- a/packages/database/supabase/migrations/20230302030217_equipment.sql
+++ b/packages/database/supabase/migrations/20230302030217_equipment.sql
@@ -36,7 +36,7 @@ ALTER TABLE "department" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees can view departments" ON "department"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
"companyId" = ANY(
select "companyId" from "userToCompany" where "userId" = auth.uid()::text
)
@@ -45,21 +45,21 @@ CREATE POLICY "Employees can view departments" ON "department"
CREATE POLICY "Employees with resources_create can insert departments" ON "department"
FOR INSERT
WITH CHECK (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('resources_create', "companyId")
);
CREATE POLICY "Employees with resources_update can update departments" ON "department"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('resources_update', "companyId")
);
CREATE POLICY "Employees with resources_delete can delete departments" ON "department"
FOR DELETE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('resources_delete', "companyId")
);
@@ -94,7 +94,7 @@ ALTER TABLE "workCellType" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees can view work cell types" ON "workCellType"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
"companyId" = ANY(
select "companyId" from "userToCompany" where "userId" = auth.uid()::text
)
@@ -103,21 +103,21 @@ CREATE POLICY "Employees can view work cell types" ON "workCellType"
CREATE POLICY "Employees with resources_create can insert work cell types" ON "workCellType"
FOR INSERT
WITH CHECK (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('resources_create', "companyId")
);
CREATE POLICY "Employees with resources_update can update work cell types" ON "workCellType"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('resources_update', "companyId")
);
CREATE POLICY "Employees with resources_delete can delete work cell types" ON "workCellType"
FOR DELETE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('resources_delete', "companyId")
);
@@ -155,7 +155,7 @@ ALTER TABLE "workCell" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees can view work cells" ON "workCell"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
"companyId" = ANY(
select "companyId" from "userToCompany" where "userId" = auth.uid()::text
)
@@ -164,21 +164,21 @@ CREATE POLICY "Employees can view work cells" ON "workCell"
CREATE POLICY "Employees with resources_create can insert work cells" ON "workCell"
FOR INSERT
WITH CHECK (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('resources_create', "companyId")
);
CREATE POLICY "Employees with resources_update can update work cells" ON "workCell"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('resources_update', "companyId")
);
CREATE POLICY "Employees with resources_delete can delete work cells" ON "workCell"
FOR DELETE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('resources_delete', "companyId")
);
@@ -213,7 +213,7 @@ ALTER TABLE "crew" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees can view crews" ON "crew"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
"companyId" = ANY(
select "companyId" from "userToCompany" where "userId" = auth.uid()::text
)
@@ -222,21 +222,21 @@ CREATE POLICY "Employees can view crews" ON "crew"
CREATE POLICY "Employees with resources_create can insert crews" ON "crew"
FOR INSERT
WITH CHECK (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('resources_create', "companyId")
);
CREATE POLICY "Employees with resources_update can update crews" ON "crew"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('resources_update', "companyId")
);
CREATE POLICY "Employees with resources_delete can delete crews" ON "crew"
FOR DELETE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('resources_delete', "companyId")
);
@@ -256,65 +256,29 @@ ALTER TABLE "crewAbility" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with resources_view can view crew abilities" ON "crewAbility"
FOR SELECT
USING (
- has_role('employee')
- AND (
- '0' = ANY(get_permission_companies('resources_view'))
- OR (
- "crewId" IN (
- SELECT "id" FROM "crew" WHERE "companyId" = ANY(
- get_permission_companies('resources_view')
- )
- )
- )
- )
+ has_role('employee', get_company_id_from_foreign_key("crewId", 'crew')) AND
+ has_company_permission('resources_view', get_company_id_from_foreign_key("crewId", 'crew'))
);
CREATE POLICY "Employees with resources_create can insert crew abilities" ON "crewAbility"
FOR INSERT
WITH CHECK (
- has_role('employee')
- AND (
- '0' = ANY(get_permission_companies('resources_create'))
- OR (
- "crewId" IN (
- SELECT "id" FROM "crew" WHERE "companyId" = ANY(
- get_permission_companies('resources_create')
- )
- )
- )
- )
+ has_role('employee', get_company_id_from_foreign_key("crewId", 'crew')) AND
+ has_company_permission('resources_create', get_company_id_from_foreign_key("crewId", 'crew'))
);
CREATE POLICY "Employees with resources_update can update crew abilities" ON "crewAbility"
FOR UPDATE
USING (
- has_role('employee')
- AND (
- '0' = ANY(get_permission_companies('resources_update'))
- OR (
- "crewId" IN (
- SELECT "id" FROM "crew" WHERE "companyId" = ANY(
- get_permission_companies('resources_update')
- )
- )
- )
- )
+ has_role('employee', get_company_id_from_foreign_key("crewId", 'crew')) AND
+ has_company_permission('resources_update', get_company_id_from_foreign_key("crewId", 'crew'))
);
CREATE POLICY "Employees with resources_delete can delete crew abilities" ON "crewAbility"
FOR DELETE
USING (
- has_role('employee')
- AND (
- '0' = ANY(get_permission_companies('resources_delete'))
- OR (
- "crewId" IN (
- SELECT "id" FROM "crew" WHERE "companyId" = ANY(
- get_permission_companies('resources_delete')
- )
- )
- )
- )
+ has_role('employee', get_company_id_from_foreign_key("crewId", 'crew')) AND
+ has_company_permission('resources_delete', get_company_id_from_foreign_key("crewId", 'crew'))
);
CREATE TABLE "equipmentType" (
@@ -345,7 +309,7 @@ ALTER TABLE "equipmentType" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees can view equipment types" ON "equipmentType"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
"companyId" = ANY(
select "companyId" from "userToCompany" where "userId" = auth.uid()::text
)
@@ -354,21 +318,21 @@ CREATE POLICY "Employees can view equipment types" ON "equipmentType"
CREATE POLICY "Employees with resources_create can insert equipment types" ON "equipmentType"
FOR INSERT
WITH CHECK (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('resources_create', "companyId")
);
CREATE POLICY "Employees with resources_update can update equipment types" ON "equipmentType"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('resources_update', "companyId")
);
CREATE POLICY "Employees with resources_delete can delete equipment types" ON "equipmentType"
FOR DELETE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('resources_update', "companyId")
);
@@ -406,7 +370,7 @@ ALTER TABLE "equipment" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees can view equipment" ON "equipment"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
"companyId" = ANY(
select "companyId" from "userToCompany" where "userId" = auth.uid()::text
)
@@ -415,21 +379,21 @@ CREATE POLICY "Employees can view equipment" ON "equipment"
CREATE POLICY "Employees with resources_create can insert equipment" ON "equipment"
FOR INSERT
WITH CHECK (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('resources_create', "companyId")
);
CREATE POLICY "Employees with resources_update can update equipment" ON "equipment"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('resources_update', "companyId")
);
CREATE POLICY "Employees with resources_delete can delete equipment" ON "equipment"
FOR DELETE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('resources_update', "companyId")
);
diff --git a/packages/database/supabase/migrations/20230315222231_holidays.sql b/packages/database/supabase/migrations/20230315222231_holidays.sql
index 4475528d94..d60880cca5 100644
--- a/packages/database/supabase/migrations/20230315222231_holidays.sql
+++ b/packages/database/supabase/migrations/20230315222231_holidays.sql
@@ -26,7 +26,7 @@ ALTER TABLE "holiday" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees can view holidays" ON "holiday"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
"companyId" = ANY(
select "companyId" from "userToCompany" where "userId" = auth.uid()::text
)
@@ -35,20 +35,20 @@ CREATE POLICY "Employees can view holidays" ON "holiday"
CREATE POLICY "Employees with resources_create can insert holidays" ON "holiday"
FOR INSERT
WITH CHECK (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('resources_create', "companyId")
);
CREATE POLICY "Employees with resources_update can update holidays" ON "holiday"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('resources_update', "companyId")
);
CREATE POLICY "Employees with resources_delete can delete holidays" ON "holiday"
FOR DELETE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('resources_delete', "companyId")
);
diff --git a/packages/database/supabase/migrations/20230319224154_partners.sql b/packages/database/supabase/migrations/20230319224154_partners.sql
index ccb4e32be9..fc6c662800 100644
--- a/packages/database/supabase/migrations/20230319224154_partners.sql
+++ b/packages/database/supabase/migrations/20230319224154_partners.sql
@@ -21,6 +21,36 @@ CREATE TABLE "partner" (
CREATE INDEX "partner_abilityId_idx" ON "partner" ("abilityId");
CREATE INDEX "partner_companyId_idx" ON "partner" ("companyId");
+ALTER TABLE "partner" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "Employees with resources_view can view partners" ON "partner"
+ FOR SELECT
+ USING (
+ has_role('employee', "companyId") AND
+ has_company_permission('resources_view', "companyId")
+ );
+
+CREATE POLICY "Employees with resources_create can insert partners" ON "partner"
+ FOR INSERT
+ WITH CHECK (
+ has_role('employee', "companyId") AND
+ has_company_permission('resources_create', "companyId")
+);
+
+CREATE POLICY "Employees with resources_update can update partners" ON "partner"
+ FOR UPDATE
+ USING (
+ has_role('employee', "companyId") AND
+ has_company_permission('resources_update', "companyId")
+ );
+
+CREATE POLICY "Employees with resources_delete can delete partners" ON "partner"
+ FOR DELETE
+ USING (
+ has_role('employee', "companyId") AND
+ has_company_permission('resources_delete', "companyId")
+ );
+
CREATE OR REPLACE VIEW "partners" AS
SELECT
p.*,
diff --git a/packages/database/supabase/migrations/20230329021751_contractors.sql b/packages/database/supabase/migrations/20230329021751_contractors.sql
index 831076ad5a..40a700d1bc 100644
--- a/packages/database/supabase/migrations/20230329021751_contractors.sql
+++ b/packages/database/supabase/migrations/20230329021751_contractors.sql
@@ -23,28 +23,28 @@ ALTER TABLE "contractor" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with resources_view can view contractors" ON "contractor"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('resources_view', "companyId")
);
CREATE POLICY "Employees with resources_create can insert contractors" ON "contractor"
FOR INSERT
WITH CHECK (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('resources_create', "companyId")
);
CREATE POLICY "Employees with resources_update can update contractors" ON "contractor"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('resources_update', "companyId")
);
CREATE POLICY "Employees with resources_delete can delete contractors" ON "contractor"
FOR DELETE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('resources_delete', "companyId")
);
@@ -66,65 +66,29 @@ ALTER TABLE "contractorAbility" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with resources_view can view contractor abilities" ON "contractorAbility"
FOR SELECT
USING (
- has_role('employee')
- AND (
- '0' = ANY(get_permission_companies('resources_view'))
- OR (
- "contractorId" IN (
- SELECT "id" FROM "contractor" WHERE "companyId" = ANY(
- get_permission_companies('resources_view')
- )
- )
- )
- )
+ has_role('employee', get_company_id_from_foreign_key("contractorId", 'contractor')) AND
+ has_company_permission('resources_view', get_company_id_from_foreign_key("contractorId", 'contractor'))
);
CREATE POLICY "Employees with resources_create can insert contractor abilities" ON "contractorAbility"
FOR INSERT
WITH CHECK (
- has_role('employee')
- AND (
- '0' = ANY(get_permission_companies('resources_create'))
- OR (
- "contractorId" IN (
- SELECT "id" FROM "contractor" WHERE "companyId" = ANY(
- get_permission_companies('resources_create')
- )
- )
- )
- )
+ has_role('employee', get_company_id_from_foreign_key("contractorId", 'contractor')) AND
+ has_company_permission('resources_create', get_company_id_from_foreign_key("contractorId", 'contractor'))
);
CREATE POLICY "Employees with resources_update can update contractor abilities" ON "contractorAbility"
FOR UPDATE
USING (
- has_role('employee')
- AND (
- '0' = ANY(get_permission_companies('resources_update'))
- OR (
- "contractorId" IN (
- SELECT "id" FROM "contractor" WHERE "companyId" = ANY(
- get_permission_companies('resources_update')
- )
- )
- )
- )
+ has_role('employee', get_company_id_from_foreign_key("contractorId", 'contractor')) AND
+ has_company_permission('resources_update', get_company_id_from_foreign_key("contractorId", 'contractor'))
);
CREATE POLICY "Employees with resources_delete can delete contractor abilities" ON "contractorAbility"
FOR DELETE
USING (
- has_role('employee')
- AND (
- '0' = ANY(get_permission_companies('resources_delete'))
- OR (
- "contractorId" IN (
- SELECT "id" FROM "contractor" WHERE "companyId" = ANY(
- get_permission_companies('resources_delete')
- )
- )
- )
- )
+ has_role('employee', get_company_id_from_foreign_key("contractorId", 'contractor')) AND
+ has_company_permission('resources_delete', get_company_id_from_foreign_key("contractorId", 'contractor'))
);
diff --git a/packages/database/supabase/migrations/20230330024715_accounts.sql b/packages/database/supabase/migrations/20230330024715_accounts.sql
index 296f13b768..5e582b9c9b 100644
--- a/packages/database/supabase/migrations/20230330024715_accounts.sql
+++ b/packages/database/supabase/migrations/20230330024715_accounts.sql
@@ -34,21 +34,21 @@ CREATE POLICY "Authenticated users can view currencies" ON "currency"
CREATE POLICY "Employees with accounting_create can insert currencies" ON "currency"
FOR INSERT
WITH CHECK (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('accounting_create', "companyId")
);
CREATE POLICY "Employees with accounting_update can update currencies" ON "currency"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('accounting_update', "companyId")
);
CREATE POLICY "Employees with accounting_delete can delete currencies" ON "currency"
FOR DELETE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('accounting_delete', "companyId")
);
@@ -120,7 +120,7 @@ ALTER TABLE "accountCategory" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with accounting_view can view account categories" ON "accountCategory"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('accounting_view', "companyId")
);
@@ -128,21 +128,21 @@ CREATE POLICY "Employees with accounting_view can view account categories" ON "a
CREATE POLICY "Employees with accounting_create can insert account categories" ON "accountCategory"
FOR INSERT
WITH CHECK (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('accounting_create', "companyId")
);
CREATE POLICY "Employees with accounting_update can update account categories" ON "accountCategory"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('accounting_update', "companyId")
);
CREATE POLICY "Employees with accounting_delete can delete account categories" ON "accountCategory"
FOR DELETE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('accounting_delete', "companyId")
);
@@ -177,66 +177,30 @@ ALTER TABLE "accountSubcategory" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with accounting_view can view account subcategories" ON "accountSubcategory"
FOR SELECT
USING (
- has_role('employee')
- AND (
- '0' = ANY(get_permission_companies('accounting_view'))
- OR (
- "accountCategoryId" IN (
- SELECT "id" FROM "accountCategory" WHERE "companyId" = ANY(
- get_permission_companies('accounting_view')
- )
- )
- )
- )
+ has_role('employee', get_company_id_from_foreign_key("accountCategoryId", 'accountCategory')) AND
+ has_company_permission('accounting_view', get_company_id_from_foreign_key("accountCategoryId", 'accountCategory'))
);
CREATE POLICY "Employees with accounting_create can insert account subcategories" ON "accountSubcategory"
FOR INSERT
WITH CHECK (
- has_role('employee')
- AND (
- '0' = ANY(get_permission_companies('accounting_create'))
- OR (
- "accountCategoryId" IN (
- SELECT "id" FROM "accountCategory" WHERE "companyId" = ANY(
- get_permission_companies('accounting_create')
- )
- )
- )
- )
+ has_role('employee', get_company_id_from_foreign_key("accountCategoryId", 'accountCategory')) AND
+ has_company_permission('accounting_create', get_company_id_from_foreign_key("accountCategoryId", 'accountCategory'))
);
CREATE POLICY "Employees with accounting_update can update account subcategories" ON "accountSubcategory"
FOR UPDATE
USING (
- has_role('employee')
- AND (
- '0' = ANY(get_permission_companies('accounting_update'))
- OR (
- "accountCategoryId" IN (
- SELECT "id" FROM "accountCategory" WHERE "companyId" = ANY(
- get_permission_companies('accounting_update')
- )
- )
- )
- )
+ has_role('employee', get_company_id_from_foreign_key("accountCategoryId", 'accountCategory')) AND
+ has_company_permission('accounting_update', get_company_id_from_foreign_key("accountCategoryId", 'accountCategory'))
);
CREATE POLICY "Employees with accounting_delete can delete account subcategories" ON "accountSubcategory"
FOR DELETE
USING (
- has_role('employee')
- AND (
- '0' = ANY(get_permission_companies('accounting_delete'))
- OR (
- "accountCategoryId" IN (
- SELECT "id" FROM "accountCategory" WHERE "companyId" = ANY(
- get_permission_companies('accounting_delete')
- )
- )
- )
- )
+ has_role('employee', get_company_id_from_foreign_key("accountCategoryId", 'accountCategory')) AND
+ has_company_permission('accounting_delete', get_company_id_from_foreign_key("accountCategoryId", 'accountCategory'))
);
CREATE TABLE "account" (
@@ -280,7 +244,7 @@ ALTER TABLE "account" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Certain employees can view accounts" ON "account"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
(
has_company_permission('accounting_view', "companyId") OR
has_company_permission('parts_view', "companyId") OR
@@ -294,21 +258,21 @@ CREATE POLICY "Certain employees can view accounts" ON "account"
CREATE POLICY "Employees with accounting_create can insert accounts" ON "account"
FOR INSERT
WITH CHECK (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('accounting_create', "companyId")
);
CREATE POLICY "Employees with accounting_update can update accounts" ON "account"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('accounting_update', "companyId")
);
CREATE POLICY "Employees with accounting_delete can delete accounts" ON "account"
FOR DELETE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('accounting_delete', "companyId")
);
diff --git a/packages/database/supabase/migrations/20230330024716_parts.sql b/packages/database/supabase/migrations/20230330024716_parts.sql
index 46b9c5e71a..4e9403acca 100644
--- a/packages/database/supabase/migrations/20230330024716_parts.sql
+++ b/packages/database/supabase/migrations/20230330024716_parts.sql
@@ -35,21 +35,21 @@ CREATE POLICY "Authenticated users can view units of measure" ON "unitOfMeasure"
CREATE POLICY "Employees with parts_create can insert units of measure" ON "unitOfMeasure"
FOR INSERT
WITH CHECK (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_create', "companyId")
);
CREATE POLICY "Employees with parts_update can update units of measure" ON "unitOfMeasure"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_update', "companyId")
);
CREATE POLICY "Employees with parts_delete can delete units of measure" ON "unitOfMeasure"
FOR DELETE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_delete', "companyId")
);
@@ -80,7 +80,7 @@ ALTER TABLE "itemPostingGroup" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with parts_view can view item groups" ON "itemPostingGroup"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_view', "companyId")
);
@@ -88,21 +88,21 @@ CREATE POLICY "Employees with parts_view can view item groups" ON "itemPostingGr
CREATE POLICY "Employees with parts_create can insert item groups" ON "itemPostingGroup"
FOR INSERT
WITH CHECK (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_create', "companyId")
);
CREATE POLICY "Employees with parts_update can update item groups" ON "itemPostingGroup"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_update', "companyId")
);
CREATE POLICY "Employees with parts_delete can delete item groups" ON "itemPostingGroup"
FOR DELETE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_update', "companyId")
);
@@ -171,7 +171,7 @@ ALTER TABLE "item" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees can view items" ON "item"
FOR SELECT
USING (
- has_role('employee')
+ has_role('employee', "companyId")
AND "companyId" = ANY(
select "companyId" from "userToCompany" where "userId" = auth.uid()::text
)
@@ -180,27 +180,25 @@ CREATE POLICY "Employees can view items" ON "item"
CREATE POLICY "Employees with parts_create can insert items" ON "item"
FOR INSERT
WITH CHECK (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_create', "companyId")
);
CREATE POLICY "Employees with parts_update can update items" ON "item"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_update', "companyId")
);
CREATE POLICY "Employees with parts_delete can delete items" ON "item"
FOR DELETE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_delete', "companyId")
);
-
-
CREATE TYPE "partManufacturingPolicy" AS ENUM (
'Make to Order',
'Make to Stock'
@@ -251,35 +249,35 @@ CREATE INDEX "part_companyId_idx" ON "part" ("companyId");
ALTER publication supabase_realtime ADD TABLE "part";
-ALTER TABLE "part" ENABLE ROW LEVEL SECURITY;
+ALTER TABLE "item" ENABLE ROW LEVEL SECURITY;
-CREATE POLICY "Employees can view parts" ON "part"
+CREATE POLICY "Employees can view parts" ON "item"
FOR SELECT
USING (
- has_role('employee')
+ has_role('employee', "companyId")
AND "companyId" = ANY(
select "companyId" from "userToCompany" where "userId" = auth.uid()::text
)
);
-CREATE POLICY "Employees with parts_create can insert parts" ON "part"
+CREATE POLICY "Employees with parts_create can insert parts" ON "item"
FOR INSERT
WITH CHECK (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_create', "companyId")
);
-CREATE POLICY "Employees with parts_update can update parts" ON "part"
+CREATE POLICY "Employees with parts_update can update parts" ON "item"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_update', "companyId")
);
-CREATE POLICY "Employees with parts_delete can delete parts" ON "part"
+CREATE POLICY "Employees with parts_delete can delete parts" ON "item"
FOR DELETE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_delete', "companyId")
);
@@ -375,14 +373,14 @@ ALTER TABLE "itemCost" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with parts_view can view part costs" ON "itemCost"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_view', "companyId")
);
CREATE POLICY "Employees with parts_update can update part costs" ON "itemCost"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_update', "companyId")
);
@@ -417,14 +415,14 @@ ALTER TABLE "itemUnitSalePrice" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with part_view can view part sale prices" ON "itemUnitSalePrice"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_view', "companyId")
);
CREATE POLICY "Employees with parts_update can update part sale prices" ON "itemUnitSalePrice"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_update', "companyId")
);
@@ -465,34 +463,34 @@ CREATE POLICY "Employees with part/purchasing_view can view part suppliers" ON "
has_company_permission('parts_view', "companyId") OR
has_company_permission('purchasing_view', "companyId")
)
- AND has_role('employee')
+ AND has_role('employee', "companyId")
);
CREATE POLICY "Employees with parts_create can create part suppliers" ON "buyMethod"
FOR INSERT
WITH CHECK (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_create', "companyId")
);
CREATE POLICY "Employees with parts_update can update part suppliers" ON "buyMethod"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_update', "companyId")
);
CREATE POLICY "Employees with parts_delete can delete part suppliers" ON "buyMethod"
FOR DELETE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_delete', "companyId")
);
CREATE POLICY "Suppliers with parts_view can view their own part suppliers" ON "buyMethod"
FOR SELECT
USING (
- has_role('supplier') AND
+ has_role('supplier', "companyId") AND
has_company_permission('parts_view', "companyId") AND
"supplierId" IN (
SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
@@ -502,7 +500,7 @@ CREATE POLICY "Suppliers with parts_view can view their own part suppliers" ON "
CREATE POLICY "Suppliers with parts_update can update their own part suppliers" ON "buyMethod"
FOR UPDATE
USING (
- has_role('supplier') AND
+ has_role('supplier', "companyId") AND
has_company_permission('parts_update', "companyId") AND
"supplierId" IN (
SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
@@ -547,22 +545,22 @@ ALTER TABLE "itemReplenishment" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with part_view can view part costs" ON "itemReplenishment"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_view', "companyId")
);
CREATE POLICY "Employees with parts_update can update part costs" ON "itemReplenishment"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_update', "companyId")
);
-CREATE POLICY "Suppliers with parts can view parts they created or supply" ON "part"
+CREATE POLICY "Suppliers with parts can view parts they created or supply" ON "item"
FOR SELECT
USING (
- has_role('supplier') AND
+ has_role('supplier', "companyId") AND
has_company_permission('parts_view', "companyId")
AND (
"createdBy" = auth.uid()::text
@@ -576,17 +574,17 @@ CREATE POLICY "Suppliers with parts can view parts they created or supply" ON "p
)
);
-CREATE POLICY "Supliers with parts_create can insert parts" ON "part"
+CREATE POLICY "Supliers with parts_create can insert parts" ON "item"
FOR INSERT
WITH CHECK (
- has_role('supplier') AND
+ has_role('supplier', "companyId") AND
has_company_permission('parts_create', "companyId")
);
-CREATE POLICY "Suppliers with parts_update can update parts that they created or supply" ON "part"
+CREATE POLICY "Suppliers with parts_update can update parts that they created or supply" ON "item"
FOR UPDATE
USING (
- has_role('supplier') AND
+ has_role('supplier', "companyId") AND
has_company_permission('parts_create', "companyId")
AND (
"createdBy" = auth.uid()::text
@@ -600,10 +598,10 @@ CREATE POLICY "Suppliers with parts_update can update parts that they created or
)
);
-CREATE POLICY "Suppliers with parts_delete can delete parts that they created or supply" ON "part"
+CREATE POLICY "Suppliers with parts_delete can delete parts that they created or supply" ON "item"
FOR DELETE
USING (
- has_role('supplier') AND
+ has_role('supplier', "companyId") AND
has_company_permission('parts_create', "companyId")
AND (
"createdBy" = auth.uid()::text
@@ -620,7 +618,7 @@ CREATE POLICY "Suppliers with parts_delete can delete parts that they created or
CREATE POLICY "Suppliers with parts_view can view part costs they supply" ON "itemCost"
FOR SELECT
USING (
- has_role('supplier') AND
+ has_role('supplier', "companyId") AND
has_company_permission('parts_view', "companyId")
AND (
"itemId" IN (
@@ -634,7 +632,7 @@ CREATE POLICY "Suppliers with parts_view can view part costs they supply" ON "it
CREATE POLICY "Suppliers with parts_update can update parts costs that they supply" ON "itemCost"
FOR UPDATE
USING (
- has_role('supplier') AND
+ has_role('supplier', "companyId") AND
has_company_permission('parts_update', "companyId")
AND (
"itemId" IN (
@@ -648,7 +646,7 @@ CREATE POLICY "Suppliers with parts_update can update parts costs that they supp
CREATE POLICY "Suppliers with parts_view can view part replenishments they supply" ON "itemReplenishment"
FOR SELECT
USING (
- has_role('supplier') AND
+ has_role('supplier', "companyId") AND
has_company_permission('parts_create', "companyId")
AND (
"itemId" IN (
@@ -662,7 +660,7 @@ CREATE POLICY "Suppliers with parts_view can view part replenishments they suppl
CREATE POLICY "Suppliers with parts_update can update parts replenishments that they supply" ON "itemReplenishment"
FOR UPDATE
USING (
- has_role('supplier') AND
+ has_role('supplier', "companyId") AND
has_company_permission('parts_update', "companyId")
AND (
"itemId" IN (
@@ -699,6 +697,38 @@ CREATE TABLE "warehouse" (
CREATE INDEX "warehouse_companyId_idx" ON "warehouse" ("companyId");
+ALTER TABLE "warehouse" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "Employees can view warehouses" ON "warehouse"
+ FOR SELECT
+ USING (
+ has_role('employee', "companyId")
+ AND "companyId" = ANY(
+ select "companyId" from "userToCompany" where "userId" = auth.uid()::text
+ )
+ );
+
+CREATE POLICY "Employees with parts_create can insert warehouses" ON "warehouse"
+ FOR INSERT
+ WITH CHECK (
+ has_role('employee', "companyId") AND
+ has_company_permission('parts_create', "companyId")
+ );
+
+CREATE POLICY "Employees with parts_update can update warehouses" ON "warehouse"
+ FOR UPDATE
+ USING (
+ has_role('employee', "companyId") AND
+ has_company_permission('parts_update', "companyId")
+ );
+
+CREATE POLICY "Employees with parts_delete can delete warehouses" ON "warehouse"
+ FOR DELETE
+ USING (
+ has_role('employee', "companyId") AND
+ has_company_permission('parts_delete', "companyId")
+ );
+
CREATE TABLE "shelf" (
"id" TEXT NOT NULL,
"locationId" TEXT NOT NULL,
@@ -729,7 +759,7 @@ ALTER TABLE "shelf" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Authenticated users can view shelves" ON "shelf"
FOR SELECT
USING (
- has_role('employee')
+ has_role('employee', "companyId")
AND "companyId" = ANY(
select "companyId" from "userToCompany" where "userId" = auth.uid()::text
)
@@ -739,21 +769,21 @@ CREATE POLICY "Authenticated users can view shelves" ON "shelf"
CREATE POLICY "Employees with parts_create can insert shelves" ON "shelf"
FOR INSERT
WITH CHECK (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_create', "companyId")
);
CREATE POLICY "Employees with parts_update can update shelves" ON "shelf"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_update', "companyId")
);
CREATE POLICY "Employees with parts_delete can delete shelves" ON "shelf"
FOR DELETE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_delete', "companyId")
);
@@ -795,7 +825,7 @@ ALTER TABLE "itemPlanning" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with parts can view part planning" ON "itemPlanning"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_view', "companyId")
);
@@ -803,14 +833,14 @@ CREATE POLICY "Employees with parts can view part planning" ON "itemPlanning"
CREATE POLICY "Employees with parts can insert part planning" ON "itemPlanning"
FOR INSERT
WITH CHECK (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_view', "companyId")
);
CREATE POLICY "Employees with parts_update can update part planning" ON "itemPlanning"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_update', "companyId")
);
@@ -843,7 +873,7 @@ ALTER TABLE "pickMethod" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with part_view can view part planning" ON "pickMethod"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_view', "companyId")
);
@@ -851,14 +881,14 @@ CREATE POLICY "Employees with part_view can view part planning" ON "pickMethod"
CREATE POLICY "Employees with part_view can insert part planning" ON "pickMethod"
FOR INSERT
WITH CHECK (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_view', "companyId")
);
CREATE POLICY "Employees with parts_update can update part planning" ON "pickMethod"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_update', "companyId")
);
diff --git a/packages/database/supabase/migrations/20230412120726_services.sql b/packages/database/supabase/migrations/20230412120726_services.sql
index 9a93e342dc..6d8299161e 100644
--- a/packages/database/supabase/migrations/20230412120726_services.sql
+++ b/packages/database/supabase/migrations/20230412120726_services.sql
@@ -35,7 +35,7 @@ CREATE INDEX "service_serviceType_idx" ON "service"("serviceType", "companyId");
CREATE POLICY "Employees can view services" ON "service"
FOR SELECT
USING (
- has_role('employee')
+ has_role('employee', "companyId")
AND "companyId" = ANY(
select "companyId" from "userToCompany" where "userId" = auth.uid()::text
)
@@ -44,21 +44,21 @@ CREATE POLICY "Employees can view services" ON "service"
CREATE POLICY "Employees with parts_create can insert services" ON "service"
FOR INSERT
WITH CHECK (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_create', "companyId")
);
CREATE POLICY "Employees with parts_update can update services" ON "service"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_update', "companyId")
);
CREATE POLICY "Employees with parts_delete can delete services" ON "service"
FOR DELETE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_delete', "companyId")
);
@@ -92,7 +92,7 @@ ALTER TABLE "serviceSupplier" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with part/purchasing_view can view service suppliers" ON "serviceSupplier"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
(
has_company_permission('parts_create', "companyId") OR
has_company_permission('purchase_view', "companyId")
@@ -102,28 +102,28 @@ CREATE POLICY "Employees with part/purchasing_view can view service suppliers" O
CREATE POLICY "Employees with parts_update can update service suppliers" ON "serviceSupplier"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_update', "companyId")
);
CREATE POLICY "Employees with parts_create can create service suppliers" ON "serviceSupplier"
FOR INSERT
WITH CHECK (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_create', "companyId")
);
CREATE POLICY "Employees with parts_delete can delete service suppliers" ON "serviceSupplier"
FOR DELETE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_delete', "companyId")
);
CREATE POLICY "Suppliers with parts_view can view their own part suppliers" ON "serviceSupplier"
FOR SELECT
USING (
- has_role('supplier') AND
+ has_role('supplier', "companyId") AND
has_company_permission('parts_view', "companyId")
AND "supplierId" IN (
SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
@@ -133,7 +133,7 @@ CREATE POLICY "Suppliers with parts_view can view their own part suppliers" ON "
CREATE POLICY "Suppliers with parts_update can update their own part suppliers" ON "serviceSupplier"
FOR UPDATE
USING (
- has_role('supplier') AND
+ has_role('supplier', "companyId") AND
has_company_permission('parts_update', "companyId")
AND "supplierId" IN (
SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
diff --git a/packages/database/supabase/migrations/20230510035345_purchasing.sql b/packages/database/supabase/migrations/20230510035345_purchasing.sql
index e49463994e..db134c4461 100644
--- a/packages/database/supabase/migrations/20230510035345_purchasing.sql
+++ b/packages/database/supabase/migrations/20230510035345_purchasing.sql
@@ -40,7 +40,7 @@ CREATE POLICY "Certain employees can view payment terms" ON "paymentTerm"
has_company_permission('sales_view', "companyId") = true OR
has_company_permission('purchasing_view', "companyId") = true
)
- AND has_role('employee')
+ AND has_role('employee', "companyId")
);
@@ -48,21 +48,21 @@ CREATE POLICY "Employees with accounting_create can insert payment terms" ON "pa
FOR INSERT
WITH CHECK (
has_company_permission('accounting_create', "companyId")
- AND has_role('employee')
+ AND has_role('employee', "companyId")
);
CREATE POLICY "Employees with accounting_update can update payment terms" ON "paymentTerm"
FOR UPDATE
USING (
has_company_permission('accounting_update', "companyId") = true
- AND has_role('employee')
+ AND has_role('employee', "companyId")
);
CREATE POLICY "Employees with accounting_delete can delete payment terms" ON "paymentTerm"
FOR DELETE
USING (
has_company_permission('accounting_delete', "companyId") = true
- AND has_role('employee')
+ AND has_role('employee', "companyId")
);
@@ -109,7 +109,7 @@ CREATE POLICY "Certain employees can view shipping methods" ON "shippingMethod"
has_company_permission('purchasing_view', "companyId") OR
has_company_permission('sales_view', "companyId")
)
- AND has_role('employee')
+ AND has_role('employee', "companyId")
);
@@ -117,21 +117,21 @@ CREATE POLICY "Employees with inventory_create can insert shipping methods" ON "
FOR INSERT
WITH CHECK (
has_company_permission('inventory_create', "companyId")
- AND has_role('employee')
+ AND has_role('employee', "companyId")
);
CREATE POLICY "Employees with inventory_update can update shipping methods" ON "shippingMethod"
FOR UPDATE
USING (
has_company_permission('inventory_update', "companyId")
- AND has_role('employee')
+ AND has_role('employee', "companyId")
);
CREATE POLICY "Employees with inventory_delete can delete shipping methods" ON "shippingMethod"
FOR DELETE
USING (
has_company_permission('inventory_delete', "companyId")
- AND has_role('employee')
+ AND has_role('employee', "companyId")
);
CREATE TABLE "shippingTerm" (
@@ -163,28 +163,28 @@ CREATE POLICY "Certain employees can view shipping terms" ON "shippingTerm"
has_company_permission('purchasing_view', "companyId") OR
has_company_permission('sales_view', "companyId")
)
- AND has_role('employee')
+ AND has_role('employee', "companyId")
);
CREATE POLICY "Employees with inventory_create can insert shipping terms" ON "shippingTerm"
FOR INSERT
WITH CHECK (
has_company_permission('inventory_create', "companyId")
- AND has_role('employee')
+ AND has_role('employee', "companyId")
);
CREATE POLICY "Employees with inventory_update can update shipping terms" ON "shippingTerm"
FOR UPDATE
USING (
has_company_permission('inventory_update', "companyId")
- AND has_role('employee')
+ AND has_role('employee', "companyId")
);
CREATE POLICY "Employees with inventory_delete can delete shipping terms" ON "shippingTerm"
FOR DELETE
USING (
has_company_permission('inventory_delete', "companyId")
- AND has_role('employee')
+ AND has_role('employee', "companyId")
);
@@ -448,7 +448,7 @@ ALTER TABLE "purchaseOrderTransaction" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with purchasing_view can view purchase order transactions" ON "purchaseOrderTransaction"
FOR SELECT USING (
- has_role('employee') AND
+ has_role('employee', get_company_id_from_foreign_key("purchaseOrderId", 'purchaseOrder')) AND
has_company_permission('purchasing_view', get_company_id_from_foreign_key("purchaseOrderId", 'purchaseOrder'))
);
diff --git a/packages/database/supabase/migrations/20230629113514_purchasing-files.sql b/packages/database/supabase/migrations/20230629113514_purchasing-files.sql
index ecb4bb9e1d..7419e7c81f 100644
--- a/packages/database/supabase/migrations/20230629113514_purchasing-files.sql
+++ b/packages/database/supabase/migrations/20230629113514_purchasing-files.sql
@@ -3,10 +3,8 @@
CREATE POLICY "Internal purchasing documents view requires purchasing_view" ON storage.objects
FOR SELECT USING (
bucket_id = 'private'
- AND has_role('employee')
- AND (storage.foldername(name))[1] = ANY(
- get_permission_companies('purchasing_view')
- )
+ AND has_role('employee', (storage.foldername(name))[1])
+ AND has_company_permission('purchasing_view', (storage.foldername(name))[1])
AND (storage.foldername(name))[2] = 'purchasing'
AND (storage.foldername(name))[3] = 'internal'
);
@@ -14,10 +12,8 @@ FOR SELECT USING (
CREATE POLICY "Internal purchasing documents insert requires purchasing_create" ON storage.objects
FOR INSERT WITH CHECK (
bucket_id = 'private'
- AND has_role('employee')
- AND (storage.foldername(name))[1] = ANY(
- get_permission_companies('purchasing_create')
- )
+ AND has_role('employee', (storage.foldername(name))[1])
+ AND has_company_permission('purchasing_create', (storage.foldername(name))[1])
AND (storage.foldername(name))[2] = 'purchasing'
AND (storage.foldername(name))[3] = 'internal'
);
@@ -25,10 +21,8 @@ FOR INSERT WITH CHECK (
CREATE POLICY "Internal purchasing documents update requires purchasing_update" ON storage.objects
FOR UPDATE USING (
bucket_id = 'private'
- AND has_role('employee')
- AND (storage.foldername(name))[1] = ANY(
- get_permission_companies('purchasing_update')
- )
+ AND has_role('employee', (storage.foldername(name))[1])
+ AND has_company_permission('purchasing_update', (storage.foldername(name))[1])
AND (storage.foldername(name))[2] = 'purchasing'
AND (storage.foldername(name))[3] = 'internal'
);
@@ -36,10 +30,8 @@ FOR UPDATE USING (
CREATE POLICY "Internal purchasing documents delete requires purchasing_delete" ON storage.objects
FOR DELETE USING (
bucket_id = 'private'
- AND has_role('employee')
- AND (storage.foldername(name))[1] = ANY(
- get_permission_companies('purchasing_delete')
- )
+ AND has_role('employee', (storage.foldername(name))[1])
+ AND has_company_permission('purchasing_delete', (storage.foldername(name))[1])
AND (storage.foldername(name))[2] = 'purchasing'
AND (storage.foldername(name))[3] = 'internal'
);
@@ -49,10 +41,8 @@ FOR DELETE USING (
CREATE POLICY "External purchasing documents view requires purchasing_view" ON storage.objects
FOR SELECT USING (
bucket_id = 'private'
- AND has_role('employee')
- AND (storage.foldername(name))[1] = ANY(
- get_permission_companies('purchasing_view')
- )
+ AND has_role('employee', (storage.foldername(name))[1])
+ AND has_company_permission('purchasing_view', (storage.foldername(name))[1])
AND (storage.foldername(name))[2] = 'purchasing'
AND (storage.foldername(name))[3] = 'external'
);
@@ -60,10 +50,8 @@ FOR SELECT USING (
CREATE POLICY "External purchasing documents insert requires purchasing_create" ON storage.objects
FOR INSERT WITH CHECK (
bucket_id = 'private'
- AND has_role('employee')
- AND (storage.foldername(name))[1] = ANY(
- get_permission_companies('purchasing_create')
- )
+ AND has_role('employee', (storage.foldername(name))[1])
+ AND has_company_permission('purchasing_create', (storage.foldername(name))[1])
AND (storage.foldername(name))[2] = 'purchasing'
AND (storage.foldername(name))[3] = 'external'
);
@@ -71,10 +59,8 @@ FOR INSERT WITH CHECK (
CREATE POLICY "External purchasing documents update requires purchasing_update" ON storage.objects
FOR UPDATE USING (
bucket_id = 'private'
- AND has_role('employee')
- AND (storage.foldername(name))[1] = ANY(
- get_permission_companies('purchasing_update')
- )
+ AND has_role('employee', (storage.foldername(name))[1])
+ AND has_company_permission('purchasing_update', (storage.foldername(name))[1])
AND (storage.foldername(name))[2] = 'purchasing'
AND (storage.foldername(name))[3] = 'external'
);
@@ -82,10 +68,8 @@ FOR UPDATE USING (
CREATE POLICY "External purchasing documents delete requires purchasing_delete" ON storage.objects
FOR DELETE USING (
bucket_id = 'private'
- AND has_role('employee')
- AND (storage.foldername(name))[1] = ANY(
- get_permission_companies('purchasing_delete')
- )
+ AND has_role('employee', (storage.foldername(name))[1])
+ AND has_company_permission('purchasing_delete', (storage.foldername(name))[1])
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 6dc933213b..4c39ab7825 100644
--- a/packages/database/supabase/migrations/20230702114301_purchasing-rls.sql
+++ b/packages/database/supabase/migrations/20230702114301_purchasing-rls.sql
@@ -7,14 +7,14 @@ CREATE POLICY "Employees with purchasing_view, inventory_view, or invoicing_view
has_company_permission('purchasing_view', "companyId") OR
has_company_permission('inventory_view', "companyId") OR
has_company_permission('invoicing_view', "companyId")
- ) AND has_role('employee')
+ ) AND has_role('employee', "companyId")
);
CREATE POLICY "Suppliers with purchasing_view can their own purchase orders" ON "purchaseOrder"
FOR SELECT
USING (
has_company_permission('purchasing_view', "companyId")
- AND has_role('supplier')
+ AND has_role('supplier', "companyId")
AND "supplierId" IN (
SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
)
@@ -22,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 (has_company_permission('purchasing_create', "companyId") AND has_role('employee'));
+ WITH CHECK (has_company_permission('purchasing_create', "companyId") AND has_role('employee', "companyId"));
CREATE POLICY "Employees with purchasing_update can update purchase orders" ON "purchaseOrder"
FOR UPDATE
- USING (has_company_permission('purchasing_update', "companyId") AND has_role('employee'));
+ USING (has_company_permission('purchasing_update', "companyId") AND has_role('employee', "companyId"));
CREATE POLICY "Suppliers with purchasing_update can their own purchase orders" ON "purchaseOrder"
FOR UPDATE
USING (
has_company_permission('purchasing_update', "companyId")
- AND has_role('supplier')
+ AND has_role('supplier', "companyId")
AND "supplierId" IN (
SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
)
@@ -41,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 (has_company_permission('purchasing_delete', "companyId") AND has_role('employee'));
+ USING (has_company_permission('purchasing_delete', "companyId") AND has_role('employee', "companyId"));
CREATE POLICY "Suppliers with purchasing_view can search for their own purchase orders" ON "search"
FOR SELECT
USING (
has_company_permission('purchasing_view', "companyId")
- AND has_role('supplier')
+ AND has_role('supplier', "companyId")
AND entity = 'Purchase Order'
AND uuid IN (
SELECT id FROM "purchaseOrder" WHERE "supplierId" IN (
@@ -106,10 +106,10 @@ CREATE TRIGGER delete_purchase_order_search_result
ALTER TABLE "purchaseOrderStatusHistory" ENABLE ROW LEVEL SECURITY;
-CREATE POLICY "Anyone with purchasing_view can view purchase order status history" ON "purchaseOrderStatusHistory"
+CREATE POLICY "Employees with purchasing_view can view purchase order status history" ON "purchaseOrderStatusHistory"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', get_company_id_from_foreign_key("purchaseOrderId", 'purchaseOrder')) AND
has_company_permission('purchasing_view', get_company_id_from_foreign_key("purchaseOrderId", 'purchaseOrder'))
);
@@ -119,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 (has_company_permission('purchasing_view', "companyId") AND has_role('employee'));
+ USING (has_company_permission('purchasing_view', "companyId") AND has_role('employee', "companyId"));
CREATE POLICY "Suppliers with purchasing_view can their own purchase order lines" ON "purchaseOrderLine"
FOR SELECT
USING (
has_company_permission('purchasing_view', "companyId")
- AND has_role('supplier')
+ AND has_role('supplier', "companyId")
AND "purchaseOrderId" IN (
SELECT id FROM "purchaseOrder" WHERE "supplierId" IN (
SELECT "supplierId" FROM "purchaseOrder" WHERE "supplierId" IN (
@@ -137,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 (has_company_permission('purchasing_create', "companyId") AND has_role('employee'));
+ WITH CHECK (has_company_permission('purchasing_create', "companyId") AND has_role('employee', "companyId"));
CREATE POLICY "Suppliers with purchasing_create can create lines on their own purchase order" ON "purchaseOrderLine"
FOR INSERT
WITH CHECK (
has_company_permission('purchasing_create', "companyId")
- AND has_role('supplier')
+ AND has_role('supplier', "companyId")
AND "purchaseOrderId" IN (
SELECT id FROM "purchaseOrder" WHERE "supplierId" IN (
SELECT "supplierId" FROM "purchaseOrder" WHERE "supplierId" IN (
@@ -155,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 (has_company_permission('purchasing_update', "companyId") AND has_role('employee'));
+ USING (has_company_permission('purchasing_update', "companyId") AND has_role('employee', "companyId"));
CREATE POLICY "Suppliers with purchasing_update can their own purchase order lines" ON "purchaseOrderLine"
FOR UPDATE
USING (
has_company_permission('purchasing_update', "companyId")
- AND has_role('supplier')
+ AND has_role('supplier', "companyId")
AND "purchaseOrderId" IN (
SELECT id FROM "purchaseOrder" WHERE "supplierId" IN (
SELECT "supplierId" FROM "purchaseOrder" WHERE "supplierId" IN (
@@ -173,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 (has_company_permission('purchasing_delete', "companyId") AND has_role('employee'));
+ USING (has_company_permission('purchasing_delete', "companyId") AND has_role('employee', "companyId"));
CREATE POLICY "Suppliers with purchasing_delete can delete lines on their own purchase order" ON "purchaseOrderLine"
FOR DELETE
USING (
has_company_permission('purchasing_delete', "companyId")
- AND has_role('supplier')
+ AND has_role('supplier', "companyId")
AND "purchaseOrderId" IN (
SELECT id FROM "purchaseOrder" WHERE "supplierId" IN (
SELECT "supplierId" FROM "purchaseOrder" WHERE "supplierId" IN (
@@ -196,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 (has_company_permission('purchasing_view', "companyId") AND has_role('employee'));
+ USING (has_company_permission('purchasing_view', "companyId") AND has_role('employee', "companyId"));
CREATE POLICY "Suppliers with purchasing_view can their own purchase order deliveries" ON "purchaseOrderDelivery"
FOR SELECT
USING (
has_company_permission('purchasing_view', "companyId")
- AND has_role('supplier')
+ AND has_role('supplier', "companyId")
AND id IN (
SELECT id FROM "purchaseOrder" WHERE "supplierId" IN (
SELECT "supplierId" FROM "purchaseOrder" WHERE "supplierId" IN (
@@ -214,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 (has_company_permission('purchasing_create', "companyId") AND has_role('employee'));
+ WITH CHECK (has_company_permission('purchasing_create', "companyId") AND has_role('employee', "companyId"));
CREATE POLICY "Employees with purchasing_update can update purchase order deliveries" ON "purchaseOrderDelivery"
FOR UPDATE
- USING (has_company_permission('purchasing_update', "companyId") AND has_role('employee'));
+ USING (has_company_permission('purchasing_update', "companyId") AND has_role('employee', "companyId"));
CREATE POLICY "Suppliers with purchasing_update can their own purchase order deliveries" ON "purchaseOrderDelivery"
FOR UPDATE
USING (
has_company_permission('purchasing_update', "companyId")
- AND has_role('supplier')
+ AND has_role('supplier', "companyId")
AND id IN (
SELECT id FROM "purchaseOrder" WHERE "supplierId" IN (
SELECT "supplierId" FROM "purchaseOrder" WHERE "supplierId" IN (
@@ -236,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 (has_company_permission('purchasing_delete', "companyId") AND has_role('employee'));
+ USING (has_company_permission('purchasing_delete', "companyId") AND has_role('employee', "companyId"));
-- Purchase Order Payments
@@ -245,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 (has_company_permission('purchasing_view', "companyId") AND has_role('employee'));
+ USING (has_company_permission('purchasing_view', "companyId") AND has_role('employee', "companyId"));
CREATE POLICY "Employees with purchasing_create can create purchase order payments" ON "purchaseOrderPayment"
FOR INSERT
- WITH CHECK (has_company_permission('purchasing_create', "companyId") AND has_role('employee'));
+ WITH CHECK (has_company_permission('purchasing_create', "companyId") AND has_role('employee', "companyId"));
CREATE POLICY "Employees with purchasing_update can update purchase order payments" ON "purchaseOrderPayment"
FOR UPDATE
- USING (has_company_permission('purchasing_update', "companyId") AND has_role('employee'));
+ USING (has_company_permission('purchasing_update', "companyId") AND has_role('employee', "companyId"));
CREATE POLICY "Employees with purchasing_delete can delete purchase order payments" ON "purchaseOrderPayment"
FOR DELETE
- USING (has_company_permission('purchasing_delete', "companyId") AND has_role('employee'));
+ USING (has_company_permission('purchasing_delete', "companyId") AND has_role('employee', "companyId"));
diff --git a/packages/database/supabase/migrations/20230704175831_view-rls.sql b/packages/database/supabase/migrations/20230704175831_view-rls.sql
index d025926566..37ba3602b8 100644
--- a/packages/database/supabase/migrations/20230704175831_view-rls.sql
+++ b/packages/database/supabase/migrations/20230704175831_view-rls.sql
@@ -6,5 +6,3 @@ ALTER VIEW "documentLabels" SET (security_invoker = on);
ALTER VIEW "documents" SET (security_invoker = on);
ALTER VIEW "purchaseOrders" SET (security_invoker = on);
ALTER VIEW "purchaseOrderSuppliers" SET (security_invoker = on);
-ALTER VIEW "suppliers" SET (security_invoker = on);
-ALTER VIEW "parts" SET (security_invoker = on);
diff --git a/packages/database/supabase/migrations/20230705033432_ledgers.sql b/packages/database/supabase/migrations/20230705033432_ledgers.sql
index c2e40192ee..fe7ee14a5e 100644
--- a/packages/database/supabase/migrations/20230705033432_ledgers.sql
+++ b/packages/database/supabase/migrations/20230705033432_ledgers.sql
@@ -77,7 +77,7 @@ ALTER TABLE "journal" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with accounting_view can view journals" ON "journal"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('accounting_view', "companyId")
);
@@ -85,7 +85,7 @@ CREATE POLICY "Employees with accounting_view can view journals" ON "journal"
CREATE POLICY "Employees with accounting_create can insert journals" ON "journal"
FOR INSERT
WITH CHECK (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('accounting_create', "companyId")
);
@@ -128,7 +128,7 @@ ALTER TABLE "journalLine" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with accounting_view can view journal lines" ON "journalLine"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('accounting_view', "companyId")
);
@@ -136,7 +136,7 @@ CREATE POLICY "Employees with accounting_view can view journal lines" ON "journa
CREATE POLICY "Employees with accounting_create can insert journal lines" ON "journalLine"
FOR INSERT
WITH CHECK (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('accounting_create', "companyId")
);
@@ -213,7 +213,7 @@ ALTER TABLE "costLedger" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with accounting_view can view the value ledger" ON "costLedger"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('accounting_view', "companyId")
);
@@ -246,7 +246,7 @@ ALTER TABLE "itemLedger" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Certain employees can view the parts ledger" ON "itemLedger"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
(
has_company_permission('accounting_view', "companyId") OR
has_company_permission('parts_view', "companyId")
@@ -284,7 +284,7 @@ ALTER TABLE "supplierLedger" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Certain employees can view the parts ledger" ON "supplierLedger"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
(
has_company_permission('invoicing_view', "companyId") OR
has_company_permission('purchasing_view', "companyId") OR
diff --git a/packages/database/supabase/migrations/20230728025201_receipts.sql b/packages/database/supabase/migrations/20230728025201_receipts.sql
index ad8cdc5337..63d2fbe788 100644
--- a/packages/database/supabase/migrations/20230728025201_receipts.sql
+++ b/packages/database/supabase/migrations/20230728025201_receipts.sql
@@ -59,7 +59,7 @@ ALTER TABLE "receipt" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with inventory_view can view receipts" ON "receipt"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('inventory_view', "companyId")
);
@@ -67,21 +67,21 @@ CREATE POLICY "Employees with inventory_view can view receipts" ON "receipt"
CREATE POLICY "Employees with inventory_create can insert receipts" ON "receipt"
FOR INSERT
WITH CHECK (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('inventory_create', "companyId")
);
CREATE POLICY "Employees with inventory_update can update receipts" ON "receipt"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('inventory_update', "companyId")
);
CREATE POLICY "Employees with inventory_delete can delete receipts" ON "receipt"
FOR DELETE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('inventory_delete', "companyId")
);
@@ -124,7 +124,7 @@ ALTER TABLE "receiptLine" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with inventory_view can view receipt lines" ON "receiptLine"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('inventory_view', "companyId")
);
@@ -132,21 +132,21 @@ CREATE POLICY "Employees with inventory_view can view receipt lines" ON "receipt
CREATE POLICY "Employees with inventory_create can insert receipt lines" ON "receiptLine"
FOR INSERT
WITH CHECK (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('inventory_create', "companyId")
);
CREATE POLICY "Employees with inventory_update can update receipt lines" ON "receiptLine"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('inventory_update', "companyId")
);
CREATE POLICY "Employees with inventory_delete can delete receipt lines" ON "receiptLine"
FOR DELETE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('inventory_delete', "companyId")
);
diff --git a/packages/database/supabase/migrations/20230820020844_posting-groups.sql b/packages/database/supabase/migrations/20230820020844_posting-groups.sql
index b871919a34..19fb932b6a 100644
--- a/packages/database/supabase/migrations/20230820020844_posting-groups.sql
+++ b/packages/database/supabase/migrations/20230820020844_posting-groups.sql
@@ -111,14 +111,14 @@ ALTER TABLE "accountDefault" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with accounting_view can view account defaults" ON "accountDefault"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('accounting_view', "companyId")
);
CREATE POLICY "Employees with accounting_update can update account defaults" ON "accountDefault"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('accounting_update', "companyId")
);
@@ -174,14 +174,14 @@ ALTER TABLE "postingGroupInventory" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with accounting_view can view inventory posting groups" ON "postingGroupInventory"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('accounting_view', "companyId")
);
CREATE POLICY "Employees with accounting_update can update inventory posting groups" ON "postingGroupInventory"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('accounting_update', "companyId")
);
@@ -221,14 +221,14 @@ ALTER TABLE "postingGroupPurchasing" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with accounting_view can view purchasing posting groups" ON "postingGroupPurchasing"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('accounting_view', "companyId")
);
CREATE POLICY "Employees with accounting_update can update purchasing posting groups" ON "postingGroupPurchasing"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('accounting_update', "companyId")
);
@@ -265,26 +265,26 @@ CREATE INDEX "postingGroupSales_companyId_idx" ON "postingGroupSales" ("companyI
CREATE POLICY "Employees with accounting_view can view sales posting groups" ON "postingGroupSales"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('accounting_view', "companyId")
);
CREATE POLICY "Employees with accounting_update can update sales posting groups" ON "postingGroupSales"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('accounting_update', "companyId")
);
CREATE FUNCTION public.create_posting_groups_for_location()
RETURNS TRIGGER AS $$
DECLARE
- part_group RECORD;
+ item_posting_group RECORD;
account_defaults RECORD;
BEGIN
SELECT * INTO account_defaults FROM "accountDefault" WHERE "companyId" = new."companyId";
- FOR part_group IN SELECT "id" FROM "itemPostingGroup"
+ FOR item_posting_group IN SELECT "id" FROM "itemPostingGroup"
LOOP
INSERT INTO "postingGroupInventory" (
"itemPostingGroupId",
@@ -306,7 +306,7 @@ BEGIN
"companyId",
"updatedBy"
) VALUES (
- part_group."id",
+ item_posting_group."id",
new."id",
account_defaults."costOfGoodsSoldAccount",
account_defaults."inventoryAccount",
@@ -377,7 +377,7 @@ CREATE TRIGGER create_location
FOR EACH ROW EXECUTE PROCEDURE public.create_posting_groups_for_location();
-CREATE FUNCTION public.create_posting_groups_for_part_group()
+CREATE FUNCTION public.create_posting_groups_for_item_posting_group()
RETURNS TRIGGER AS $$
DECLARE
rec RECORD;
@@ -578,9 +578,9 @@ END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-CREATE TRIGGER create_part_group
+CREATE TRIGGER create_item_posting_group
AFTER INSERT on public."itemPostingGroup"
- FOR EACH ROW EXECUTE PROCEDURE public.create_posting_groups_for_part_group();
+ FOR EACH ROW EXECUTE PROCEDURE public.create_posting_groups_for_item_posting_group();
CREATE FUNCTION public.create_posting_groups_for_customer_type()
RETURNS TRIGGER AS $$
diff --git a/packages/database/supabase/migrations/20230924004608_accounts-payable.sql b/packages/database/supabase/migrations/20230924004608_accounts-payable.sql
index 99bcb09881..8c8af2de99 100644
--- a/packages/database/supabase/migrations/20230924004608_accounts-payable.sql
+++ b/packages/database/supabase/migrations/20230924004608_accounts-payable.sql
@@ -64,28 +64,28 @@ ALTER TABLE "purchaseInvoice" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with invoicing_view can view AP invoices" ON "purchaseInvoice"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('invoicing_view', "companyId")
);
CREATE POLICY "Employees with invoicing_create can insert AP invoices" ON "purchaseInvoice"
FOR INSERT
WITH CHECK (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('invoicing_create', "companyId")
);
CREATE POLICY "Employees with invoicing_update can update AP invoices" ON "purchaseInvoice"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('invoicing_update', "companyId")
);
CREATE POLICY "Employees with invoicing_delete can delete AP invoices" ON "purchaseInvoice"
FOR DELETE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('invoicing_delete', "companyId")
);
@@ -106,7 +106,7 @@ ALTER TABLE "purchaseInvoiceStatusHistory" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with invoicing_view can view AP invoices status history" ON "purchaseInvoiceStatusHistory"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', get_company_id_from_foreign_key("invoiceId", 'purchaseInvoice')) AND
has_company_permission('invoicing_view', get_company_id_from_foreign_key("invoiceId", 'purchaseInvoice'))
);
@@ -213,28 +213,28 @@ ALTER TABLE "purchaseInvoiceLine" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with invoicing_view can view AP invoice lines" ON "purchaseInvoiceLine"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('invoicing_view', "companyId")
);
CREATE POLICY "Employees with invoicing_create can insert AP invoice lines" ON "purchaseInvoiceLine"
FOR INSERT
WITH CHECK (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('invoicing_create', "companyId")
);
CREATE POLICY "Employees with invoicing_update can update AP invoice lines" ON "purchaseInvoiceLine"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('invoicing_update', "companyId")
);
CREATE POLICY "Employees with invoicing_delete can delete AP invoice lines" ON "purchaseInvoiceLine"
FOR DELETE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('invoicing_delete', "companyId")
);
@@ -259,7 +259,7 @@ ALTER TABLE "purchaseInvoicePriceChange" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with invoicing_view can view AP invoice price changes" ON "purchaseInvoicePriceChange"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', get_company_id_from_foreign_key("invoiceId", 'purchaseInvoice')) AND
has_company_permission('invoicing_view', get_company_id_from_foreign_key("invoiceId", 'purchaseInvoice'))
);
@@ -324,21 +324,21 @@ ALTER TABLE "purchasePayment" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with invoicing_view can view AP payments" ON "purchasePayment"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('invoicing_view', "companyId")
);
CREATE POLICY "Employees with invoicing_create can insert AP payments" ON "purchasePayment"
FOR INSERT
WITH CHECK (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('invoicing_create', "companyId")
);
CREATE POLICY "Employees with invoicing_update can update AP payments" ON "purchasePayment"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('invoicing_update', "companyId")
);
@@ -346,7 +346,7 @@ CREATE POLICY "Employees with invoicing_delete can delete AP payments" ON "purch
FOR DELETE
USING (
"paymentDate" IS NULL AND
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('invoicing_delete', "companyId")
);
@@ -365,7 +365,7 @@ ALTER TABLE "purchaseInvoicePaymentRelation" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with invoicing_view can view AP invoice/payment relations" ON "purchaseInvoicePaymentRelation"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', get_company_id_from_foreign_key("invoiceId", 'purchaseInvoice')) AND
has_company_permission('invoicing_view', get_company_id_from_foreign_key("invoiceId", 'purchaseInvoice'))
);
diff --git a/packages/database/supabase/migrations/20231109050239_supplier-details.sql b/packages/database/supabase/migrations/20231109050239_supplier-details.sql
index 57f5ca83ab..531024bcb5 100644
--- a/packages/database/supabase/migrations/20231109050239_supplier-details.sql
+++ b/packages/database/supabase/migrations/20231109050239_supplier-details.sql
@@ -30,14 +30,14 @@ ALTER TABLE "supplierPayment" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with purchasing_view can view supplier payment" ON "supplierPayment"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('purchasing_view', "companyId")
);
CREATE POLICY "Employees with purchasing_update can update supplier payment" ON "supplierPayment"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('purchasing_update', "companyId")
);
@@ -72,14 +72,14 @@ CREATE INDEX "supplierShipping_supplierId_idx" ON "supplierShipping"("supplierId
CREATE POLICY "Employees with purchasing_view can view supplier shipping" ON "supplierShipping"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('purchasing_view', "companyId")
);
CREATE POLICY "Employees with purchasing_update can update supplier shipping" ON "supplierShipping"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('purchasing_update', "companyId")
);
diff --git a/packages/database/supabase/migrations/20231109050252_customer-details.sql b/packages/database/supabase/migrations/20231109050252_customer-details.sql
index 15a7545eda..7a6e2db0f4 100644
--- a/packages/database/supabase/migrations/20231109050252_customer-details.sql
+++ b/packages/database/supabase/migrations/20231109050252_customer-details.sql
@@ -28,14 +28,14 @@ ALTER TABLE "customerPayment" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with sales_view can view customer payment" ON "customerPayment"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('sales_view', "companyId")
);
CREATE POLICY "Employees with sales_update can update customer payment" ON "customerPayment"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('sales_update', "companyId")
);
@@ -68,14 +68,14 @@ ALTER TABLE "customerShipping" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with purchasing_view can view customer shipping" ON "customerShipping"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('purchasing_view', "companyId")
);
CREATE POLICY "Employees with purchasing_update can update customer shipping" ON "customerShipping"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('purchasing_update', "companyId")
);
diff --git a/packages/database/supabase/migrations/20240119095150_integrations.sql b/packages/database/supabase/migrations/20240119095150_integrations.sql
index 8d65186fbe..ed66802ac4 100644
--- a/packages/database/supabase/migrations/20240119095150_integrations.sql
+++ b/packages/database/supabase/migrations/20240119095150_integrations.sql
@@ -18,15 +18,9 @@ VALUES
('exchange-rates-v1', 'Exchange Rates', 'Pulls currency rates from exchange rates API', '/integrations/exchange-rates.png', '{"type": "object", "properties": {"apiKey": {"type": "string"}}, "required": ["apiKey"]}'::json),
('resend', 'Resend Emails', 'Sends Transactional Emails with Resend API', '/integrations/resend.png', '{"type": "object", "properties": {"apiKey": {"type": "string"}}, "required": ["apiKey"]}'::json);
-CREATE POLICY "Employees with settings_view can view integrations." ON "integration"
+CREATE POLICY "Authenticated users can view integrations." ON "integration"
FOR SELECT USING (
- has_role('employee')
- );
-
-CREATE POLICY "Employees with settings_update can update integrations." ON "integration"
- FOR UPDATE
- USING (
- has_role('employee')
+ auth.role() = 'authenticated'
);
CREATE TABLE "companyIntegration" (
@@ -42,23 +36,21 @@ CREATE TABLE "companyIntegration" (
CONSTRAINT "companyIntegration_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE
);
+ALTER TABLE "companyIntegration" ENABLE ROW LEVEL SECURITY;
+
CREATE POLICY "Employees with settings_view can view company integrations." ON "companyIntegration"
FOR SELECT USING (
- has_role('employee') AND
- "companyId" = ANY(
- select "companyId" from "userToCompany" where "userId" = auth.uid()::text
- )
+ has_role('employee', "companyId") AND
+ has_company_permission('settings_view', "companyId")
);
CREATE POLICY "Employees with settings_update can update company integrations." ON "companyIntegration"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('settings_update', "companyId")
);
-
-
CREATE FUNCTION verify_integration() RETURNS trigger AS $verify_integration$
DECLARE integration_schema JSON;
BEGIN
diff --git a/packages/database/supabase/migrations/20240204025905_rfq.sql b/packages/database/supabase/migrations/20240204025905_rfq.sql
deleted file mode 100644
index cf9b89ce5a..0000000000
--- a/packages/database/supabase/migrations/20240204025905_rfq.sql
+++ /dev/null
@@ -1,187 +0,0 @@
-CREATE TYPE "requestForQuoteStatus" AS ENUM ('Draft', 'Sent', 'Expired', 'Closed');
-
-CREATE TABLE "requestForQuote" (
- "id" TEXT NOT NULL DEFAULT xid(),
- "requestForQuoteId" TEXT NOT NULL,
- "revisionId" INTEGER NOT NULL DEFAULT 0,
- "name" TEXT,
- "status" "requestForQuoteStatus" NOT NULL DEFAULT 'Draft',
- "notes" TEXT,
- "receiptDate" DATE NOT NULL,
- "expirationDate" DATE,
- "locationId" TEXT,
- "assignee" TEXT,
- "customFields" JSONB,
- "companyId" TEXT NOT NULL,
- "createdAt" TIMESTAMP WITH TIME ZONE DEFAULT now(),
- "createdBy" TEXT NOT NULL,
- "updatedAt" TIMESTAMP WITH TIME ZONE DEFAULT now(),
- "updatedBy" TEXT,
-
- CONSTRAINT "requestForQuote_pkey" PRIMARY KEY ("id"),
- CONSTRAINT "requestForQuote_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "location"("id"),
- CONSTRAINT "requestForQuote_assignee_fkey" FOREIGN KEY ("assignee") REFERENCES "user"("id"),
- CONSTRAINT "requestForQuote_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE RESTRICT ON UPDATE CASCADE,
- CONSTRAINT "requestForQuote_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE,
- CONSTRAINT "requestForQuote_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE
-);
-
-CREATE INDEX "requestForQuote_companyId_idx" ON "requestForQuote" ("companyId");
-CREATE INDEX "requestForQuote_locationId_idx" ON "requestForQuote" ("locationId", "companyId");
-
-CREATE TABLE "requestForQuoteLine" (
- "id" TEXT NOT NULL DEFAULT xid(),
- "requestForQuoteId" TEXT NOT NULL,
- "itemId" TEXT NOT NULL,
- "description" TEXT,
- "quantity" NUMERIC(20, 2) NOT NULL,
- "unitPrice" NUMERIC(20, 2) NOT NULL DEFAULT 0,
- "unitOfMeasureCode" TEXT,
- "locationId" TEXT,
- "shelfId" TEXT,
- "companyId" TEXT NOT NULL,
- "createdAt" TIMESTAMP WITH TIME ZONE DEFAULT now(),
- "createdBy" TEXT NOT NULL,
- "updatedAt" TIMESTAMP WITH TIME ZONE DEFAULT now(),
- "updatedBy" TEXT,
- "customFields" JSONB,
-
- CONSTRAINT "requestForQuoteLine_pkey" PRIMARY KEY ("id"),
- CONSTRAINT "requestForQuoteLine_requestForQuoteId_fkey" FOREIGN KEY ("requestForQuoteId") REFERENCES "requestForQuote"("id") ON DELETE CASCADE ON UPDATE CASCADE,
- CONSTRAINT "requestForQuoteLine_itemId_fkey" FOREIGN KEY ("itemId") REFERENCES "item"("id") ON DELETE RESTRICT ON UPDATE CASCADE,
- CONSTRAINT "requestForQuoteLine_unitOfMeasureCode_fkey" FOREIGN KEY ("unitOfMeasureCode", "companyId") REFERENCES "unitOfMeasure"("code", "companyId") ON UPDATE CASCADE ON DELETE SET NULL,
- CONSTRAINT "requestForQuoteLine_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "location"("id") ON UPDATE CASCADE ON DELETE SET NULL,
- CONSTRAINT "requestForQuoteLine_shelfId_fkey" FOREIGN KEY ("shelfId", "locationId") REFERENCES "shelf" ("id", "locationId") ON DELETE CASCADE,
- CONSTRAINT "requestForQuoteLine_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE RESTRICT ON UPDATE CASCADE,
- CONSTRAINT "requestForQuoteLine_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE,
- CONSTRAINT "requestForQuoteLine_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE
-);
-
-CREATE INDEX "requestForQuoteLine_requestForQuoteId_idx" ON "requestForQuoteLine" ("requestForQuoteId");
-CREATE INDEX "requestForQuoteLine_itemId_idx" ON "requestForQuoteLine" ("itemId");
-CREATE INDEX "requestForQuoteLine_locationId_idx" ON "requestForQuoteLine" ("locationId");
-
-CREATE TABLE "requestForQuoteSupplier" (
- "id" TEXT NOT NULL DEFAULT xid(),
- "requestForQuoteId" TEXT NOT NULL,
- "supplierId" TEXT NOT NULL,
- "supplierLocationId" TEXT,
- "supplierContactId" TEXT,
- "token" TEXT,
- "password" TEXT,
- "completedAt" TIMESTAMP WITH TIME ZONE,
- "createdAt" TIMESTAMP WITH TIME ZONE DEFAULT now(),
- "createdBy" TEXT NOT NULL,
- "updatedAt" TIMESTAMP WITH TIME ZONE DEFAULT now(),
- "updatedBy" TEXT,
- "customFields" JSONB,
-
- CONSTRAINT "requestForQuoteSupplier_pkey" PRIMARY KEY ("id"),
- CONSTRAINT "requestForQuoteSupplier_requestForQuoteId_fkey" FOREIGN KEY ("requestForQuoteId") REFERENCES "requestForQuote"("id") ON DELETE CASCADE ON UPDATE CASCADE,
- CONSTRAINT "requestForQuoteSupplier_supplierId_fkey" FOREIGN KEY ("supplierId") REFERENCES "supplier"("id") ON DELETE RESTRICT ON UPDATE CASCADE,
- CONSTRAINT "requestForQuoteSupplier_supplierLocationId_fkey" FOREIGN KEY ("supplierLocationId") REFERENCES "location"("id") ON DELETE RESTRICT ON UPDATE CASCADE,
- CONSTRAINT "requestForQuoteSupplier_supplierContactId_fkey" FOREIGN KEY ("supplierContactId") REFERENCES "contact"("id") ON DELETE RESTRICT ON UPDATE CASCADE,
- CONSTRAINT "requestForQuoteSupplier_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE,
- CONSTRAINT "requestForQuoteSupplier_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE
-);
-
-CREATE INDEX "requestForQuoteSupplier_requestForQuoteId_idx" ON "requestForQuoteSupplier" ("requestForQuoteId");
-CREATE INDEX "requestForQuoteSupplier_supplierId_idx" ON "requestForQuoteSupplier" ("supplierId");
-
-CREATE TABLE "requestForQuoteSupplierLine" (
- "id" TEXT NOT NULL DEFAULT xid(),
- "requestForQuoteSupplierId" TEXT NOT NULL,
- "requestForQuoteLineId" TEXT NOT NULL,
- "unitPrice" NUMERIC(20, 2) NOT NULL,
- "createdAt" TIMESTAMP WITH TIME ZONE DEFAULT now(),
- "createdBy" TEXT NOT NULL,
- "updatedAt" TIMESTAMP WITH TIME ZONE DEFAULT now(),
- "updatedBy" TEXT,
-
- CONSTRAINT "requestForQuoteSupplierLine_pkey" PRIMARY KEY ("id"),
- CONSTRAINT "requestForQuoteSupplierLine_requestForQuoteSupplierId_fkey" FOREIGN KEY ("requestForQuoteSupplierId") REFERENCES "requestForQuoteSupplier"("id") ON DELETE CASCADE ON UPDATE CASCADE,
- CONSTRAINT "requestForQuoteSupplierLine_requestForQuoteLineId_fkey" FOREIGN KEY ("requestForQuoteLineId") REFERENCES "requestForQuoteLine"("id") ON DELETE CASCADE ON UPDATE CASCADE,
- CONSTRAINT "requestForQuoteSupplierLine_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE,
- CONSTRAINT "requestForQuoteSupplierLine_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE
-);
-
-
-CREATE TABLE "requestForQuoteFavorite" (
- "requestForQuoteId" TEXT NOT NULL,
- "userId" TEXT NOT NULL,
-
- CONSTRAINT "requestForQuoteFavorites_pkey" PRIMARY KEY ("requestForQuoteId", "userId"),
- CONSTRAINT "requestForQuoteFavorites_requestForQuoteId_fkey" FOREIGN KEY ("requestForQuoteId") REFERENCES "requestForQuote"("id") ON DELETE CASCADE,
- CONSTRAINT "requestForQuoteFavorites_userId_fkey" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE
-);
-
-CREATE INDEX "requestForQuoteFavorites_userId_idx" ON "requestForQuoteFavorite" ("userId");
-CREATE INDEX "requestForQuoteFavorites_requestForQuoteId_idx" ON "requestForQuoteFavorite" ("requestForQuoteId");
-
-ALTER TABLE "requestForQuoteFavorite" ENABLE ROW LEVEL SECURITY;
-
-CREATE POLICY "Users can view their own rfq favorites" ON "requestForQuoteFavorite"
- FOR SELECT USING (
- auth.uid()::text = "userId"
- );
-
-CREATE POLICY "Users can create their own rfq favorites" ON "requestForQuoteFavorite"
- FOR INSERT WITH CHECK (
- auth.uid()::text = "userId"
- );
-
-CREATE POLICY "Users can delete their own rfq favorites" ON "requestForQuoteFavorite"
- FOR DELETE USING (
- auth.uid()::text = "userId"
- );
-
-CREATE OR REPLACE VIEW "requestForQuotes" WITH(SECURITY_INVOKER=true) AS
- SELECT
- r."id",
- r."requestForQuoteId",
- r."name",
- r."status",
- r."notes",
- r."receiptDate",
- r."expirationDate",
- r."locationId",
- r."customFields",
- r."companyId",
- r."createdAt",
- r."createdBy",
- uc."fullName" AS "createdByFullName",
- uc."avatarUrl" AS "createdByAvatar",
- uu."fullName" AS "updatedByFullName",
- uu."avatarUrl" AS "updatedByAvatar",
- l."name" AS "locationName",
- array_agg(rs."supplierId") AS "supplierIds",
- array_agg(rl."itemId") AS "itemIds",
- EXISTS(SELECT 1 FROM "requestForQuoteFavorite" pf WHERE pf."requestForQuoteId" = r.id AND pf."userId" = auth.uid()::text) AS favorite
-FROM "requestForQuote" r
-LEFT JOIN "location" l
- ON l.id = r."locationId"
-LEFT JOIN "requestForQuoteSupplier" rs
- ON rs."requestForQuoteId" = r.id
-LEFT JOIN "requestForQuoteLine" rl
- ON rl."requestForQuoteId" = r.id
-LEFT JOIN "user" uc
- ON uc.id = r."createdBy"
-LEFT JOIN "user" uu
- ON uu.id = r."updatedBy"
-GROUP BY
- r."id",
- r."requestForQuoteId",
- r."name",
- r."status",
- r."notes",
- r."receiptDate",
- r."expirationDate",
- r."locationId",
- r."customFields",
- r."createdAt",
- r."createdBy",
- uc."fullName",
- uc."avatarUrl",
- uu."fullName",
- uu."avatarUrl",
- l."name";
\ No newline at end of file
diff --git a/packages/database/supabase/migrations/20240209055738_quote-files.sql b/packages/database/supabase/migrations/20240209055738_quote-files.sql
index 81e092c967..51e167f70f 100644
--- a/packages/database/supabase/migrations/20240209055738_quote-files.sql
+++ b/packages/database/supabase/migrations/20240209055738_quote-files.sql
@@ -3,10 +3,8 @@
CREATE POLICY "Internal quote documents view requires sales_view" ON storage.objects
FOR SELECT USING (
bucket_id = 'private'
- AND has_role('employee')
- AND (storage.foldername(name))[1] = ANY(
- get_permission_companies('sales_view')
- )
+ AND has_role('employee', (storage.foldername(name))[1])
+ AND has_company_permission('sales_view', (storage.foldername(name))[1])
AND (storage.foldername(name))[2] = 'quote'
AND (storage.foldername(name))[3] = 'internal'
);
@@ -14,10 +12,8 @@ FOR SELECT USING (
CREATE POLICY "Internal quote documents insert requires sales_create" ON storage.objects
FOR INSERT WITH CHECK (
bucket_id = 'private'
- AND has_role('employee')
- AND (storage.foldername(name))[1] = ANY(
- get_permission_companies('sales_create')
- )
+ AND has_role('employee', (storage.foldername(name))[1])
+ AND has_company_permission('sales_create', (storage.foldername(name))[1])
AND (storage.foldername(name))[2] = 'quote'
AND (storage.foldername(name))[3] = 'internal'
);
@@ -25,10 +21,8 @@ FOR INSERT WITH CHECK (
CREATE POLICY "Internal quote documents update requires sales_update" ON storage.objects
FOR UPDATE USING (
bucket_id = 'private'
- AND has_role('employee')
- AND (storage.foldername(name))[1] = ANY(
- get_permission_companies('sales_update')
- )
+ AND has_role('employee', (storage.foldername(name))[1])
+ AND has_company_permission('sales_update', (storage.foldername(name))[1])
AND (storage.foldername(name))[2] = 'quote'
AND (storage.foldername(name))[3] = 'internal'
);
@@ -36,10 +30,8 @@ FOR UPDATE USING (
CREATE POLICY "Internal quote documents delete requires sales_delete" ON storage.objects
FOR DELETE USING (
bucket_id = 'private'
- AND has_role('employee')
- AND (storage.foldername(name))[1] = ANY(
- get_permission_companies('sales_delete')
- )
+ AND has_role('employee', (storage.foldername(name))[1])
+ AND has_company_permission('sales_delete', (storage.foldername(name))[1])
AND (storage.foldername(name))[2] = 'quote'
AND (storage.foldername(name))[3] = 'internal'
);
@@ -49,10 +41,8 @@ FOR DELETE USING (
CREATE POLICY "External quote documents view requires sales_view" ON storage.objects
FOR SELECT USING (
bucket_id = 'private'
- AND has_role('employee')
- AND (storage.foldername(name))[1] = ANY(
- get_permission_companies('sales_view')
- )
+ AND has_role('employee', (storage.foldername(name))[1])
+ AND has_company_permission('sales_view', (storage.foldername(name))[1])
AND (storage.foldername(name))[2] = 'quote'
AND (storage.foldername(name))[3] = 'external'
);
@@ -60,10 +50,8 @@ FOR SELECT USING (
CREATE POLICY "External quote documents insert requires sales_create" ON storage.objects
FOR INSERT WITH CHECK (
bucket_id = 'private'
- AND has_role('employee')
- AND (storage.foldername(name))[1] = ANY(
- get_permission_companies('sales_create')
- )
+ AND has_role('employee', (storage.foldername(name))[1])
+ AND has_company_permission('sales_create', (storage.foldername(name))[1])
AND (storage.foldername(name))[2] = 'quote'
AND (storage.foldername(name))[3] = 'external'
);
@@ -71,10 +59,8 @@ FOR INSERT WITH CHECK (
CREATE POLICY "External quote documents update requires sales_update" ON storage.objects
FOR UPDATE USING (
bucket_id = 'private'
- AND has_role('employee')
- AND (storage.foldername(name))[1] = ANY(
- get_permission_companies('sales_update')
- )
+ AND has_role('employee', (storage.foldername(name))[1])
+ AND has_company_permission('sales_update', (storage.foldername(name))[1])
AND (storage.foldername(name))[2] = 'quote'
AND (storage.foldername(name))[3] = 'external'
);
@@ -82,10 +68,8 @@ FOR UPDATE USING (
CREATE POLICY "External quote documents delete requires sales_delete" ON storage.objects
FOR DELETE USING (
bucket_id = 'private'
- AND has_role('employee')
- AND (storage.foldername(name))[1] = ANY(
- get_permission_companies('sales_delete')
- )
+ AND has_role('employee', (storage.foldername(name))[1])
+ AND has_company_permission('sales_delete', (storage.foldername(name))[1])
AND (storage.foldername(name))[2] = 'quote'
AND (storage.foldername(name))[3] = 'external'
);
\ No newline at end of file
diff --git a/packages/database/supabase/migrations/20240213043906_quote-rls.sql b/packages/database/supabase/migrations/20240213043906_quote-rls.sql
index f0f9e028c2..3abe8b4ffa 100644
--- a/packages/database/supabase/migrations/20240213043906_quote-rls.sql
+++ b/packages/database/supabase/migrations/20240213043906_quote-rls.sql
@@ -3,14 +3,14 @@ ALTER TABLE "quote" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with sales_view can view quotes" ON "quote"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('sales_view', "companyId")
);
CREATE POLICY "Customers with sales_view can their own quotes" ON "quote"
FOR SELECT
USING (
- has_role('customer') AND
+ has_role('customer', "companyId") AND
has_company_permission('sales_view', "companyId") AND
"customerId" IN (
SELECT "customerId" FROM "customerAccount" WHERE id::uuid = auth.uid()
@@ -20,7 +20,7 @@ CREATE POLICY "Customers with sales_view can their own quotes" ON "quote"
CREATE POLICY "Employees with sales_create can create quotes" ON "quote"
FOR INSERT
WITH CHECK (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('sales_create', "companyId")
);
@@ -28,14 +28,14 @@ CREATE POLICY "Employees with sales_create can create quotes" ON "quote"
CREATE POLICY "Employees with sales_update can update quotes" ON "quote"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('sales_update', "companyId")
);
CREATE POLICY "Customers with sales_update can their own quotes" ON "quote"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('sales_update', "companyId") AND
"customerId" IN (
SELECT "customerId" FROM "customerAccount" WHERE id::uuid = auth.uid()
@@ -45,7 +45,7 @@ CREATE POLICY "Customers with sales_update can their own quotes" ON "quote"
CREATE POLICY "Employees with sales_delete can delete quotes" ON "quote"
FOR DELETE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('sales_delete', "companyId")
);
@@ -53,7 +53,7 @@ CREATE POLICY "Employees with sales_delete can delete quotes" ON "quote"
CREATE POLICY "Customers with sales_view can search for their own quotes" ON "search"
FOR SELECT
USING (
- has_role('customer') AND
+ has_role('customer', "companyId") AND
has_company_permission('sales_view', "companyId") AND
entity = 'Quotation' AND
uuid IN (
@@ -72,14 +72,14 @@ ALTER TABLE "quoteLine" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with sales_view can view quote lines" ON "quoteLine"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('sales_view', "companyId")
);
CREATE POLICY "Customers with sales_view can their own quote lines" ON "quoteLine"
FOR SELECT
USING (
- has_role('customer') AND
+ has_role('customer', "companyId") AND
has_company_permission('sales_view', "companyId") AND
"quoteId" IN (
SELECT id FROM "quote" WHERE "customerId" IN (
@@ -93,14 +93,14 @@ CREATE POLICY "Customers with sales_view can their own quote lines" ON "quoteLin
CREATE POLICY "Employees with sales_create can create quote lines" ON "quoteLine"
FOR INSERT
WITH CHECK (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('sales_create', "companyId")
);
CREATE POLICY "Customers with sales_create can create lines on their own quote" ON "quoteLine"
FOR INSERT
WITH CHECK (
- has_role('customer') AND
+ has_role('customer', "companyId") AND
has_company_permission('sales_create', "companyId") AND
"quoteId" IN (
SELECT id FROM "quote" WHERE "customerId" IN (
@@ -114,14 +114,14 @@ CREATE POLICY "Customers with sales_create can create lines on their own quote"
CREATE POLICY "Employees with sales_update can update quote lines" ON "quoteLine"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('sales_update', "companyId")
);
CREATE POLICY "Customers with sales_update can their own quote lines" ON "quoteLine"
FOR UPDATE
USING (
- has_role('customer') AND
+ has_role('customer', "companyId") AND
has_company_permission('sales_update', "companyId") AND
"quoteId" IN (
SELECT id FROM "quote" WHERE "customerId" IN (
@@ -135,14 +135,14 @@ CREATE POLICY "Customers with sales_update can their own quote lines" ON "quoteL
CREATE POLICY "Employees with sales_delete can delete quote lines" ON "quoteLine"
FOR DELETE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('sales_delete', "companyId")
);
CREATE POLICY "Customers with sales_delete can delete lines on their own quote" ON "quoteLine"
FOR DELETE
USING (
- has_role('customer') AND
+ has_role('customer', "companyId") AND
has_company_permission('sales_delete', "companyId") AND
"quoteId" IN (
SELECT id FROM "quote" WHERE "customerId" IN (
@@ -158,14 +158,14 @@ ALTER TABLE "quoteAssembly" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with sales_view can view quote assemblies" ON "quoteAssembly"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', get_company_id_from_foreign_key("quoteId", 'quote')) AND
has_company_permission('sales_view', get_company_id_from_foreign_key("quoteId", 'quote'))
);
CREATE POLICY "Customers with sales_view can their own quote assemblies" ON "quoteAssembly"
FOR SELECT
USING (
- has_role('customer') AND
+ has_role('customer', get_company_id_from_foreign_key("quoteId", 'quote')) AND
has_company_permission('sales_view', get_company_id_from_foreign_key("quoteId", 'quote')) AND
"quoteId" IN (
SELECT id FROM "quote" WHERE "customerId" IN (
@@ -179,21 +179,21 @@ CREATE POLICY "Customers with sales_view can their own quote assemblies" ON "quo
CREATE POLICY "Employees with sales_create can create quote assemblies" ON "quoteAssembly"
FOR INSERT
WITH CHECK (
- has_role('employee') AND
+ has_role('employee', get_company_id_from_foreign_key("quoteId", 'quote')) AND
has_company_permission('sales_create', get_company_id_from_foreign_key("quoteId", 'quote'))
);
CREATE POLICY "Employees with sales_update can update quote assemblies" ON "quoteAssembly"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', get_company_id_from_foreign_key("quoteId", 'quote')) AND
has_company_permission('sales_update', get_company_id_from_foreign_key("quoteId", 'quote'))
);
CREATE POLICY "Employees with sales_delete can delete quote assemblies" ON "quoteAssembly"
FOR DELETE
USING (
- has_role('employee') AND
+ has_role('employee', get_company_id_from_foreign_key("quoteId", 'quote')) AND
has_company_permission('sales_delete', get_company_id_from_foreign_key("quoteId", 'quote'))
);
@@ -202,43 +202,31 @@ ALTER TABLE "quoteOperation" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with sales_view can view quote operations" ON "quoteOperation"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', get_company_id_from_foreign_key("quoteId", 'quote')) AND
has_company_permission('sales_view', get_company_id_from_foreign_key("quoteId", 'quote'))
);
-CREATE POLICY "Customers with sales_view can their own quote operations" ON "quoteOperation"
- FOR SELECT
- USING (
- has_role('customer') AND
- has_company_permission('sales_view', get_company_id_from_foreign_key("quoteId", 'quote')) AND
- "quoteId" IN (
- SELECT id FROM "quote" WHERE "customerId" IN (
- SELECT "customerId" FROM "quote" WHERE "customerId" IN (
- SELECT "customerId" FROM "customerAccount" WHERE id::uuid = auth.uid()
- )
- )
- )
- );
+
-- TODO: fix these kinds of policies where we pass a select statement to has_company_permission
CREATE POLICY "Employees with sales_create can create quote operations" ON "quoteOperation"
FOR INSERT
WITH CHECK (
- has_role('employee') AND
+ has_role('employee', get_company_id_from_foreign_key("quoteId", 'quote')) AND
has_company_permission('sales_create', get_company_id_from_foreign_key("quoteId", 'quote'))
);
CREATE POLICY "Employees with sales_update can update quote operations" ON "quoteOperation"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', get_company_id_from_foreign_key("quoteId", 'quote')) AND
has_company_permission('sales_update', get_company_id_from_foreign_key("quoteId", 'quote'))
);
CREATE POLICY "Employees with sales_delete can delete quote operations" ON "quoteOperation"
FOR DELETE
USING (
- has_role('employee') AND
+ has_role('employee', get_company_id_from_foreign_key("quoteId", 'quote')) AND
has_company_permission('sales_delete', get_company_id_from_foreign_key("quoteId", 'quote'))
);
@@ -247,42 +235,29 @@ ALTER TABLE "quoteMaterial" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with sales_view can view quote materials" ON "quoteMaterial"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', get_company_id_from_foreign_key("quoteId", 'quote')) AND
has_company_permission('sales_view', get_company_id_from_foreign_key("quoteId", 'quote'))
);
-CREATE POLICY "Customers with sales_view can their own quote materials" ON "quoteMaterial"
- FOR SELECT
- USING (
- has_role('customer') AND
- has_company_permission('sales_view', get_company_id_from_foreign_key("quoteId", 'quote')) AND
- "quoteId" IN (
- SELECT id FROM "quote" WHERE "customerId" IN (
- SELECT "customerId" FROM "quote" WHERE "customerId" IN (
- SELECT "customerId" FROM "customerAccount" WHERE id::uuid = auth.uid()
- )
- )
- )
- );
CREATE POLICY "Employees with sales_create can create quote materials" ON "quoteMaterial"
FOR INSERT
WITH CHECK (
- has_role('employee') AND
+ has_role('employee', get_company_id_from_foreign_key("quoteId", 'quote')) AND
has_company_permission('sales_create', get_company_id_from_foreign_key("quoteId", 'quote'))
);
CREATE POLICY "Employees with sales_update can update quote materials" ON "quoteMaterial"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', get_company_id_from_foreign_key("quoteId", 'quote')) AND
has_company_permission('sales_update', get_company_id_from_foreign_key("quoteId", 'quote'))
);
CREATE POLICY "Employees with sales_delete can delete quote materials" ON "quoteMaterial"
FOR DELETE
USING (
- has_role('employee') AND
+ has_role('employee', get_company_id_from_foreign_key("quoteId", 'quote')) AND
has_company_permission('sales_delete', get_company_id_from_foreign_key("quoteId", 'quote'))
);
diff --git a/packages/database/supabase/migrations/20240311021818_custom-fields.sql b/packages/database/supabase/migrations/20240311021818_custom-fields.sql
index 83854aa190..f24ca45cc1 100644
--- a/packages/database/supabase/migrations/20240311021818_custom-fields.sql
+++ b/packages/database/supabase/migrations/20240311021818_custom-fields.sql
@@ -12,10 +12,10 @@ CREATE INDEX "customFieldTable_module_idx" ON "customFieldTable" ("module");
ALTER TABLE "customFieldTable" ENABLE ROW LEVEL SECURITY;
-CREATE POLICY "Employees can view custom field tables" ON "customFieldTable"
+CREATE POLICY "Authenticated users can view custom field tables" ON "customFieldTable"
FOR SELECT
USING (
- has_role('employee')
+ auth.role() = 'authenticated'
);
CREATE TABLE "customField" (
@@ -46,27 +46,27 @@ ALTER TABLE "customField" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees can view custom fields" ON "customField"
FOR SELECT
USING (
- has_role('employee')
+ has_role('employee', "companyId")
);
CREATE POLICY "Employees with settings_create can insert custom fields" ON "customField"
FOR INSERT
WITH CHECK (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('settings_create', "companyId")
);
CREATE POLICY "Employees with settings_update can update custom fields" ON "customField"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('settings_update', "companyId")
);
CREATE POLICY "Employees with settings_delete can delete custom fields" ON "customField"
FOR DELETE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('settings_delete', "companyId")
);
diff --git a/packages/database/supabase/migrations/20240324175747_assignee.sql b/packages/database/supabase/migrations/20240324175747_assignee.sql
index 3a38726670..891e4d92a1 100644
--- a/packages/database/supabase/migrations/20240324175747_assignee.sql
+++ b/packages/database/supabase/migrations/20240324175747_assignee.sql
@@ -114,33 +114,6 @@ CREATE OR REPLACE VIEW "receipts" WITH(SECURITY_INVOKER=true) AS
LEFT JOIN "location" l
ON l.id = r."locationId";
-DROP VIEW "requestForQuotes";
-CREATE OR REPLACE VIEW "requestForQuotes" WITH(SECURITY_INVOKER=true) AS
- SELECT
- r.*,
- l."name" AS "locationName",
- rs."supplierIds",
- rp."itemIds",
- EXISTS(SELECT 1 FROM "requestForQuoteFavorite" pf WHERE pf."requestForQuoteId" = r.id AND pf."userId" = auth.uid()::text) AS favorite
-FROM "requestForQuote" r
-LEFT JOIN "location" l
- ON l.id = r."locationId"
-LEFT JOIN (
- SELECT
- "requestForQuoteId",
- array_agg(rs."supplierId") AS "supplierIds"
- FROM "requestForQuoteSupplier" rs
- GROUP BY "requestForQuoteId"
-) rs
- ON rs."requestForQuoteId" = r.id
-LEFT JOIN (
- SELECT
- "requestForQuoteId",
- array_agg(rp."itemId") AS "itemIds"
- FROM "requestForQuoteLine" rp
- GROUP BY "requestForQuoteId"
-) rp
- ON rp."requestForQuoteId" = r.id;
DROP VIEW "services";
CREATE OR REPLACE VIEW "services" WITH(SECURITY_INVOKER=true) AS
diff --git a/packages/database/supabase/migrations/20240329034816_quote-pricing.sql b/packages/database/supabase/migrations/20240329034816_quote-pricing.sql
index 665ff3da87..513bb634cf 100644
--- a/packages/database/supabase/migrations/20240329034816_quote-pricing.sql
+++ b/packages/database/supabase/migrations/20240329034816_quote-pricing.sql
@@ -40,27 +40,29 @@ ALTER TABLE "quoteLinePrice" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with sales_view can view quote line pricing" ON "quoteLinePrice"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', get_company_id_from_foreign_key("quoteId", 'quote')) AND
has_company_permission('sales_view', get_company_id_from_foreign_key("quoteId", 'quote'))
);
CREATE POLICY "Employees with sales_create can insert quote line pricing" ON "quoteLinePrice"
FOR INSERT
WITH CHECK (
- has_role('employee') AND
+ has_role('employee', get_company_id_from_foreign_key("quoteId", 'quote')) AND
has_company_permission('sales_create', get_company_id_from_foreign_key("quoteId", 'quote'))
);
CREATE POLICY "Employees with sales_update can update quote line pricing" ON "quoteLinePrice"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', get_company_id_from_foreign_key("quoteId", 'quote')) AND
has_company_permission('sales_update', get_company_id_from_foreign_key("quoteId", 'quote'))
);
CREATE POLICY "Employees with sales_delete can delete quote line pricing" ON "quoteLinePrice"
FOR DELETE
USING (
- has_role('employee') AND
+ has_role('employee', get_company_id_from_foreign_key("quoteId", 'quote')) AND
has_company_permission('sales_delete', get_company_id_from_foreign_key("quoteId", 'quote'))
);
+
+
diff --git a/packages/database/supabase/migrations/20240330054035_purchasing-documents.sql b/packages/database/supabase/migrations/20240330054035_purchasing-documents.sql
index 88d0d80d68..d6be65339e 100644
--- a/packages/database/supabase/migrations/20240330054035_purchasing-documents.sql
+++ b/packages/database/supabase/migrations/20240330054035_purchasing-documents.sql
@@ -2,37 +2,29 @@
CREATE POLICY "Users with purchasing_view can view documents that start with purchasing" ON "document"
FOR SELECT USING (
- has_role('employee')
- AND (storage.foldername(path))[1] = ANY(
- get_permission_companies('purchasing_view')
- )
+ has_role('employee', (storage.foldername(name))[1])
+ AND has_company_permission('purchasing_view', (storage.foldername(name))[1])
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 (
- has_role('employee')
- AND (storage.foldername(path))[1] = ANY(
- get_permission_companies('purchasing_create')
- )
+ has_role('employee', (storage.foldername(name))[1])
+ AND has_company_permission('purchasing_create', (storage.foldername(name))[1])
AND (storage.foldername(path))[2] = 'purchasing'
);
CREATE POLICY "Users with purchasing_update can update documents that start with purchasing" ON "document"
FOR UPDATE USING (
- has_role('employee')
- AND (storage.foldername(path))[1] = ANY(
- get_permission_companies('purchasing_update')
- )
+ has_role('employee', (storage.foldername(name))[1])
+ AND has_company_permission('purchasing_update', (storage.foldername(name))[1])
AND (storage.foldername(path))[2] = 'purchasing'
);
CREATE POLICY "Users with purchasing_delete can delete documents that start with purchasing" ON "document"
FOR DELETE USING (
- has_role('employee')
- AND (storage.foldername(path))[1] = ANY(
- get_permission_companies('purchasing_delete')
- )
+ has_role('employee', (storage.foldername(name))[1])
+ AND has_company_permission('purchasing_delete', (storage.foldername(name))[1])
AND (storage.foldername(path))[2] = 'purchasing'
);
diff --git a/packages/database/supabase/migrations/20240330164855_quote-documents.sql b/packages/database/supabase/migrations/20240330164855_quote-documents.sql
index 41a1c7a4a7..42c1815e32 100644
--- a/packages/database/supabase/migrations/20240330164855_quote-documents.sql
+++ b/packages/database/supabase/migrations/20240330164855_quote-documents.sql
@@ -2,37 +2,29 @@
CREATE POLICY "Users with sales_view can view documents that start with quote" ON "document"
FOR SELECT USING (
- has_role('employee')
- AND (storage.foldername(path))[1] = ANY(
- get_permission_companies('sales_view')
- )
+ has_role('employee', (storage.foldername(name))[1])
+ AND has_company_permission('sales_view', (storage.foldername(name))[1])
AND (storage.foldername(path))[2] = 'quote'
);
CREATE POLICY "Users with sales_create can create documents that start with quote" ON "document"
FOR INSERT WITH CHECK (
- has_role('employee')
- AND (storage.foldername(path))[1] = ANY(
- get_permission_companies('sales_create')
- )
+ has_role('employee', (storage.foldername(name))[1])
+ AND has_company_permission('sales_create', (storage.foldername(name))[1])
AND (storage.foldername(path))[2] = 'quote'
);
CREATE POLICY "Users with sales_update can update documents that start with quote" ON "document"
FOR UPDATE USING (
- has_role('employee')
- AND (storage.foldername(path))[1] = ANY(
- get_permission_companies('sales_update')
- )
+ has_role('employee', (storage.foldername(name))[1])
+ AND has_company_permission('sales_update', (storage.foldername(name))[1])
AND (storage.foldername(path))[2] = 'quote'
);
CREATE POLICY "Users with sales_delete can delete documents that start with quote" ON "document"
FOR DELETE USING (
- has_role('employee')
- AND (storage.foldername(path))[1] = ANY(
- get_permission_companies('sales_delete')
- )
+ has_role('employee', (storage.foldername(name))[1])
+ AND has_company_permission('sales_delete', (storage.foldername(name))[1])
AND (storage.foldername(path))[2] = 'quote'
);
diff --git a/packages/database/supabase/migrations/20240412224648_sales-orders.sql b/packages/database/supabase/migrations/20240412224648_sales-orders.sql
index 2f79bde286..a69dda7869 100644
--- a/packages/database/supabase/migrations/20240412224648_sales-orders.sql
+++ b/packages/database/supabase/migrations/20240412224648_sales-orders.sql
@@ -312,13 +312,13 @@ CREATE POLICY "Employees with sales_view, inventory_view, or invoicing_view can
(
has_company_permission('sales_view', "companyId") OR
has_company_permission('invoicing_view', "companyId")
- ) AND has_role('employee')
+ ) AND has_role('employee', "companyId")
);
CREATE POLICY "Customers with sales_view can their own sales orders" ON "salesOrder"
FOR SELECT
USING (
- has_role('customer') AND
+ has_role('customer', "companyId") AND
has_company_permission('sales_view', "companyId") AND
"customerId" IN (
SELECT "customerId" FROM "customerAccount" WHERE id::uuid = auth.uid()
@@ -328,20 +328,20 @@ CREATE POLICY "Customers with sales_view can their own sales orders" ON "salesOr
CREATE POLICY "Employees with sales_create can create sales orders" ON "salesOrder"
FOR INSERT
WITH CHECK (
- has_company_permission('sales_create', "companyId") AND has_role('employee')
+ has_company_permission('sales_create', "companyId") AND has_role('employee', "companyId")
);
CREATE POLICY "Employees with sales_update can update sales orders" ON "salesOrder"
FOR UPDATE
USING (
- has_company_permission('sales_update', "companyId") AND has_role('employee')
+ has_company_permission('sales_update', "companyId") AND has_role('employee', "companyId")
);
CREATE POLICY "Customers with sales_update can update their own sales orders" ON "salesOrder"
FOR UPDATE
USING (
- has_role('customer') AND
+ has_role('customer', "companyId") AND
has_company_permission('sales_update', "companyId")
AND "customerId" IN (
SELECT "customerId" FROM "customerAccount" WHERE id::uuid = auth.uid()
@@ -351,14 +351,14 @@ CREATE POLICY "Customers with sales_update can update their own sales orders" ON
CREATE POLICY "Employees with sales_delete can delete sales orders" ON "salesOrder"
FOR DELETE
USING (
- has_company_permission('sales_delete', "companyId") AND has_role('employee')
+ has_company_permission('sales_delete', "companyId") AND has_role('employee', "companyId")
);
CREATE POLICY "Customers with sales_view can search for their own sales orders" ON "search"
FOR SELECT
USING (
- has_role('customer') AND
+ has_role('customer', "companyId") AND
has_company_permission('sales_view', "companyId") AND
entity = 'Sales Order' AND
uuid IN (
@@ -420,7 +420,7 @@ ALTER TABLE "salesOrderStatusHistory" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Anyone with sales_view can view sales order status history" ON "salesOrderStatusHistory"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', get_company_id_from_foreign_key("salesOrderId", 'salesOrder')) AND
has_company_permission('sales_view', get_company_id_from_foreign_key("salesOrderId", 'salesOrder'))
);
@@ -431,14 +431,14 @@ ALTER TABLE "salesOrderLine" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with sales_view can view sales order lines" ON "salesOrderLine"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('sales_view', "companyId")
);
CREATE POLICY "Customers with sales_view can their own sales order lines" ON "salesOrderLine"
FOR SELECT
USING (
- has_role('customer') AND
+ has_role('customer', "companyId") AND
has_company_permission('sales_view', "companyId") AND
"salesOrderId" IN (
SELECT id FROM "salesOrder" WHERE "customerId" IN (
@@ -452,14 +452,14 @@ CREATE POLICY "Customers with sales_view can their own sales order lines" ON "sa
CREATE POLICY "Employees with sales_create can create sales order lines" ON "salesOrderLine"
FOR INSERT
WITH CHECK (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('sales_create', "companyId")
);
CREATE POLICY "Customers with sales_create can create lines on their own sales order" ON "salesOrderLine"
FOR INSERT
WITH CHECK (
- has_role('customer') AND
+ has_role('customer', "companyId") AND
has_company_permission('sales_create', "companyId") AND
"salesOrderId" IN (
SELECT id FROM "salesOrder" WHERE "customerId" IN (
@@ -473,14 +473,14 @@ CREATE POLICY "Customers with sales_create can create lines on their own sales o
CREATE POLICY "Employees with sales_update can update sales order lines" ON "salesOrderLine"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('sales_update', "companyId")
);
CREATE POLICY "Customers with sales_update can update their own sales order lines" ON "salesOrderLine"
FOR UPDATE
USING (
- has_role('customer') AND
+ has_role('customer', "companyId") AND
has_company_permission('sales_update', "companyId") AND
"salesOrderId" IN (
SELECT id FROM "salesOrder" WHERE "customerId" IN (
@@ -494,14 +494,14 @@ CREATE POLICY "Customers with sales_update can update their own sales order line
CREATE POLICY "Employees with sales_delete can delete sales order lines" ON "salesOrderLine"
FOR DELETE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('sales_delete', "companyId")
);
CREATE POLICY "Customers with sales_delete can delete lines on their own sales order" ON "salesOrderLine"
FOR DELETE
USING (
- has_role('customer') AND
+ has_role('customer', "companyId") AND
has_company_permission('sales_delete', "companyId") AND
"salesOrderId" IN (
SELECT id FROM "salesOrder" WHERE "customerId" IN (
@@ -520,14 +520,14 @@ ALTER TABLE "salesOrderShipment" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with sales_view can view sales order shipments" ON "salesOrderShipment"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('sales_view', "companyId")
);
CREATE POLICY "Customers with sales_view can their own sales order shipments" ON "salesOrderShipment"
FOR SELECT
USING (
- has_role('customer') AND
+ has_role('customer', "companyId") AND
has_company_permission('sales_view', "companyId") AND
id IN (
SELECT id FROM "salesOrder" WHERE "customerId" IN (
@@ -541,21 +541,21 @@ CREATE POLICY "Customers with sales_view can their own sales order shipments" ON
CREATE POLICY "Employees with sales_create can create sales order shipments" ON "salesOrderShipment"
FOR INSERT
WITH CHECK (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('sales_create', "companyId")
);
CREATE POLICY "Employees with sales_update can update sales order shipments" ON "salesOrderShipment"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('sales_update', "companyId")
);
CREATE POLICY "Customers with sales_update can their own sales order shipments" ON "salesOrderShipment"
FOR UPDATE
USING (
- has_role('customer') AND
+ has_role('customer', "companyId") AND
has_company_permission('sales_update', "companyId") AND
id IN (
SELECT id FROM "salesOrder" WHERE "customerId" IN (
@@ -569,7 +569,7 @@ CREATE POLICY "Customers with sales_update can their own sales order shipments"
CREATE POLICY "Employees with sales_delete can delete sales order shipments" ON "salesOrderShipment"
FOR DELETE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('sales_delete', "companyId")
);
@@ -581,28 +581,28 @@ ALTER TABLE "salesOrderPayment" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with sales_view can view sales order payments" ON "salesOrderPayment"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('sales_view', "companyId")
);
CREATE POLICY "Employees with sales_create can create sales order payments" ON "salesOrderPayment"
FOR INSERT
WITH CHECK (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('sales_create', "companyId")
);
CREATE POLICY "Employees with sales_update can update sales order payments" ON "salesOrderPayment"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('sales_update', "companyId")
);
CREATE POLICY "Employees with sales_delete can delete sales order payments" ON "salesOrderPayment"
FOR DELETE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('sales_delete', "companyId")
);
diff --git a/packages/database/supabase/migrations/20240511125727_seed_custom_fields.sql b/packages/database/supabase/migrations/20240511125727_seed_custom_fields.sql
index e0df7b25d9..1771c746e5 100644
--- a/packages/database/supabase/migrations/20240511125727_seed_custom_fields.sql
+++ b/packages/database/supabase/migrations/20240511125727_seed_custom_fields.sql
@@ -43,9 +43,6 @@ VALUES
('quoteMaterial', 'Quote Material', 'Sales'),
('quoteOperation', 'Quote Operation', 'Sales'),
('receipt', 'Receipt', 'Inventory'),
-('requestForQuote', 'RFQ', 'Purchasing'),
-('requestForQuoteLine', 'RFQ Line', 'Purchasing'),
-('requestForQuoteSupplier', 'RFQ Supplier', 'Purchasing'),
('service', 'Service', 'Parts'),
('serviceSupplier', 'Service Supplier', 'Parts'),
('shelf', 'Shelf', 'Inventory'),
diff --git a/packages/database/supabase/migrations/20240608103855_tools.sql b/packages/database/supabase/migrations/20240608103855_tools.sql
index 65c7b85d51..c3a8a975b7 100644
--- a/packages/database/supabase/migrations/20240608103855_tools.sql
+++ b/packages/database/supabase/migrations/20240608103855_tools.sql
@@ -30,7 +30,7 @@ ALTER TABLE "tool" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees can view tools" ON "tool"
FOR SELECT
USING (
- has_role('employee')
+ has_role('employee', "companyId")
AND "companyId" = ANY(
select "companyId" from "userToCompany" where "userId" = auth.uid()::text
)
@@ -39,21 +39,21 @@ CREATE POLICY "Employees can view tools" ON "tool"
CREATE POLICY "Employees with parts_create can insert tools" ON "tool"
FOR INSERT
WITH CHECK (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_create', "companyId")
);
CREATE POLICY "Employees with parts_update can update tools" ON "tool"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_update', "companyId")
);
CREATE POLICY "Employees with parts_delete can delete tools" ON "tool"
FOR DELETE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_delete', "companyId")
);
diff --git a/packages/database/supabase/migrations/20240608105638_consumables.sql b/packages/database/supabase/migrations/20240608105638_consumables.sql
index be856695aa..1d1e2232bb 100644
--- a/packages/database/supabase/migrations/20240608105638_consumables.sql
+++ b/packages/database/supabase/migrations/20240608105638_consumables.sql
@@ -26,7 +26,7 @@ ALTER TABLE "consumable" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees can view consumables" ON "consumable"
FOR SELECT
USING (
- has_role('employee')
+ has_role('employee', "companyId")
AND "companyId" = ANY(
select "companyId" from "userToCompany" where "userId" = auth.uid()::text
)
@@ -35,21 +35,21 @@ CREATE POLICY "Employees can view consumables" ON "consumable"
CREATE POLICY "Employees with parts_create can insert consumables" ON "consumable"
FOR INSERT
WITH CHECK (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_create', "companyId")
);
CREATE POLICY "Employees with parts_update can update consumables" ON "consumable"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_update', "companyId")
);
CREATE POLICY "Employees with parts_delete can delete consumables" ON "consumable"
FOR DELETE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_delete', "companyId")
);
diff --git a/packages/database/supabase/migrations/20240608111319_fixtures.sql b/packages/database/supabase/migrations/20240608111319_fixtures.sql
index 60736b15ef..9d7af041da 100644
--- a/packages/database/supabase/migrations/20240608111319_fixtures.sql
+++ b/packages/database/supabase/migrations/20240608111319_fixtures.sql
@@ -28,7 +28,7 @@ ALTER TABLE "fixture" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees can view fixtures" ON "fixture"
FOR SELECT
USING (
- has_role('employee')
+ has_role('employee', "companyId")
AND "companyId" = ANY(
select "companyId" from "userToCompany" where "userId" = auth.uid()::text
)
@@ -37,21 +37,21 @@ CREATE POLICY "Employees can view fixtures" ON "fixture"
CREATE POLICY "Employees with parts_create can insert fixtures" ON "fixture"
FOR INSERT
WITH CHECK (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_create', "companyId")
);
CREATE POLICY "Employees with parts_update can update fixtures" ON "fixture"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_update', "companyId")
);
CREATE POLICY "Employees with parts_delete can delete fixtures" ON "fixture"
FOR DELETE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_delete', "companyId")
);
diff --git a/packages/database/supabase/migrations/20240608114413_materials.sql b/packages/database/supabase/migrations/20240608114413_materials.sql
index a12969b855..571f847432 100644
--- a/packages/database/supabase/migrations/20240608114413_materials.sql
+++ b/packages/database/supabase/migrations/20240608114413_materials.sql
@@ -2,7 +2,7 @@ ALTER TABLE "item" ALTER COLUMN "companyId" DROP NOT NULL;
ALTER POLICY "Employees can view items" ON "item"
USING (
- has_role('employee')
+ has_role('employee', "companyId")
AND (
"companyId" IS NULL OR
"companyId" = ANY(
@@ -33,7 +33,7 @@ ALTER TABLE "materialForm" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees can view material forms" ON "materialForm"
FOR SELECT
USING (
- has_role('employee')
+ has_role('employee', "companyId")
AND (
"companyId" IS NULL OR
"companyId" = ANY(
@@ -45,21 +45,21 @@ CREATE POLICY "Employees can view material forms" ON "materialForm"
CREATE POLICY "Employees with parts_create can insert material forms" ON "materialForm"
FOR INSERT
WITH CHECK (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_create', "companyId")
);
CREATE POLICY "Employees with parts_update can update material forms" ON "materialForm"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_update', "companyId")
);
CREATE POLICY "Employees with parts_delete can delete material forms" ON "materialForm"
FOR DELETE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_delete', "companyId")
);
@@ -89,7 +89,7 @@ ALTER TABLE "materialSubstance" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees can view material substances" ON "materialSubstance"
FOR SELECT
USING (
- has_role('employee')
+ has_role('employee', "companyId")
AND (
"companyId" IS NULL OR
"companyId" = ANY(
@@ -101,21 +101,21 @@ CREATE POLICY "Employees can view material substances" ON "materialSubstance"
CREATE POLICY "Employees with parts_create can insert material substances" ON "materialSubstance"
FOR INSERT
WITH CHECK (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_create', "companyId")
);
CREATE POLICY "Employees with parts_update can update material substances" ON "materialSubstance"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_update', "companyId")
);
CREATE POLICY "Employees with parts_delete can delete material substances" ON "materialSubstance"
FOR DELETE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_delete', "companyId")
);
@@ -158,7 +158,7 @@ ALTER TABLE "material" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees can view materials" ON "material"
FOR SELECT
USING (
- has_role('employee')
+ has_role('employee', "companyId")
AND (
"companyId" IS NULL OR
"companyId" = ANY(
@@ -170,21 +170,21 @@ CREATE POLICY "Employees can view materials" ON "material"
CREATE POLICY "Employees with parts_create can insert materials" ON "material"
FOR INSERT
WITH CHECK (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_create', "companyId")
);
CREATE POLICY "Employees with parts_update can update materials" ON "material"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_update', "companyId")
);
CREATE POLICY "Employees with parts_delete can delete materials" ON "material"
FOR DELETE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_delete', "companyId")
);
diff --git a/packages/database/supabase/migrations/20240608124217_item-search.sql b/packages/database/supabase/migrations/20240608124217_item-search.sql
index 3a8e3692e4..0f341a3e22 100644
--- a/packages/database/supabase/migrations/20240608124217_item-search.sql
+++ b/packages/database/supabase/migrations/20240608124217_item-search.sql
@@ -33,5 +33,5 @@ ALTER POLICY "Employees with parts can search for parts" ON "search"
(
"companyId" = NULL OR
has_company_permission('parts_view', "companyId")
- ) AND entity = 'Part' AND has_role('employee')
+ ) AND entity = 'Part' AND has_role('employee', "companyId")
);
diff --git a/packages/database/supabase/migrations/20240621114604_method-rls.sql b/packages/database/supabase/migrations/20240621114604_method-rls.sql
index a8ab66cc7b..48b694b29f 100644
--- a/packages/database/supabase/migrations/20240621114604_method-rls.sql
+++ b/packages/database/supabase/migrations/20240621114604_method-rls.sql
@@ -71,28 +71,28 @@ ALTER TABLE "makeMethod" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with parts_view can view make methods" ON "makeMethod"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_view', "companyId")
);
CREATE POLICY "Employees with parts_create can create make methods" ON "makeMethod"
FOR INSERT
WITH CHECK (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_create', "companyId")
);
CREATE POLICY "Employees with parts_update can update make methods" ON "makeMethod"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_update', "companyId")
);
CREATE POLICY "Employees with parts_delete can delete make methods" ON "makeMethod"
FOR DELETE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_delete', "companyId")
);
@@ -101,28 +101,28 @@ ALTER TABLE "methodMaterial" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with parts_view can view method materials" ON "methodMaterial"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_view', "companyId")
);
CREATE POLICY "Employees with parts_create can create method materials" ON "methodMaterial"
FOR INSERT
WITH CHECK (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_create', "companyId")
);
CREATE POLICY "Employees with parts_update can update method materials" ON "methodMaterial"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_update', "companyId")
);
CREATE POLICY "Employees with parts_delete can delete method materials" ON "methodMaterial"
FOR DELETE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_delete', "companyId")
);
@@ -131,28 +131,28 @@ ALTER TABLE "methodOperation" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with parts_view can view method operation" ON "methodOperation"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_view', "companyId")
);
CREATE POLICY "Employees with parts_create can create method operation" ON "methodOperation"
FOR INSERT
WITH CHECK (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_create', "companyId")
);
CREATE POLICY "Employees with parts_update can update method operation" ON "methodOperation"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_update', "companyId")
);
CREATE POLICY "Employees with parts_delete can delete method operation" ON "methodOperation"
FOR DELETE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_delete', "companyId")
);
@@ -161,7 +161,7 @@ ALTER TABLE "methodOperationWorkInstruction" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees can view work instructions" ON "methodOperationWorkInstruction"
FOR SELECT
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
"companyId" = ANY(
select "companyId" from "userToCompany" where "userId" = auth.uid()::text
)
@@ -170,20 +170,20 @@ CREATE POLICY "Employees can view work instructions" ON "methodOperationWorkInst
CREATE POLICY "Employees with parts_create can create work instructions" ON "methodOperationWorkInstruction"
FOR INSERT
WITH CHECK (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_create', "companyId")
);
CREATE POLICY "Employees with parts_update can update work instructions" ON "methodOperationWorkInstruction"
FOR UPDATE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_update', "companyId")
);
CREATE POLICY "Employees with parts_delete can delete work instructions" ON "methodOperationWorkInstruction"
FOR DELETE
USING (
- has_role('employee') AND
+ has_role('employee', "companyId") AND
has_company_permission('parts_delete', "companyId")
);
\ No newline at end of file
diff --git a/packages/database/supabase/migrations/20240623115054_parts-documents-rls.sql b/packages/database/supabase/migrations/20240623115054_parts-documents-rls.sql
index 6efc9f7489..84aaa0c4c1 100644
--- a/packages/database/supabase/migrations/20240623115054_parts-documents-rls.sql
+++ b/packages/database/supabase/migrations/20240623115054_parts-documents-rls.sql
@@ -2,39 +2,31 @@
CREATE POLICY "Employees can view internal parts documents" ON storage.objects
FOR SELECT USING (
bucket_id = 'private'
- AND has_role('employee')
- AND (storage.foldername(name))[1] = ANY(
- select "companyId" from "userToCompany" where "userId" = auth.uid()::text
- )
+ AND has_role('employee', (storage.foldername(name))[1])
+ AND has_company_permission('parts_view', (storage.foldername(name))[1])
AND (storage.foldername(name))[2] = 'parts'
);
CREATE POLICY "Internal parts documents insert requires parts_create" ON storage.objects
FOR INSERT WITH CHECK (
bucket_id = 'private'
- AND has_role('employee')
- AND (storage.foldername(name))[1] = ANY(
- get_permission_companies('parts_create')
- )
+ AND has_role('employee', (storage.foldername(name))[1])
+ AND has_company_permission('parts_create', (storage.foldername(name))[1])
AND (storage.foldername(name))[2] = 'parts'
);
CREATE POLICY "Internal parts documents update requires parts_update" ON storage.objects
FOR UPDATE USING (
bucket_id = 'private'
- AND has_role('employee')
- AND (storage.foldername(name))[1] = ANY(
- get_permission_companies('parts_update')
- )
+ AND has_role('employee', (storage.foldername(name))[1])
+ AND has_company_permission('parts_update', (storage.foldername(name))[1])
AND (storage.foldername(name))[2] = 'parts'
);
CREATE POLICY "Internal parts documents delete requires parts_delete" ON storage.objects
FOR DELETE USING (
bucket_id = 'private'
- AND has_role('employee')
- AND (storage.foldername(name))[1] = ANY(
- get_permission_companies('parts_delete')
- )
+ AND has_role('employee', (storage.foldername(name))[1])
+ AND has_company_permission('parts_delete', (storage.foldername(name))[1])
AND (storage.foldername(name))[2] = 'parts'
);