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: remove favorite function from tables

Brad Barbin8b29426d0321
diff --git a/apps/carbon/app/modules/purchasing/purchasing.service.ts b/apps/carbon/app/modules/purchasing/purchasing.service.ts
index 28c0b86379..0703860275 100644
--- a/apps/carbon/app/modules/purchasing/purchasing.service.ts
+++ b/apps/carbon/app/modules/purchasing/purchasing.service.ts
@@ -218,8 +218,7 @@ export async function getPurchaseOrders(
}
query = setGenericQueryFilters(query, args, [
- { column: "favorite", ascending: false },
- { column: "purchaseOrderId", ascending: false },
+ { column: "id", ascending: false },
]);
return query;
@@ -471,7 +470,6 @@ export async function getSupplierQuotes(
}
query = setGenericQueryFilters(query, args, [
- { column: "favorite", ascending: false },
{ column: "id", ascending: false },
]);
return query;
diff --git a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrdersTable.tsx b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrdersTable.tsx
index 7d7f82dade..6f5125e510 100644
--- a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrdersTable.tsx
+++ b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrdersTable.tsx
@@ -6,7 +6,6 @@ import {
useDisclosure,
} from "@carbon/react";
import { formatDate } from "@carbon/utils";
-import { useFetcher, useFetchers } from "@remix-run/react";
import type { ColumnDef } from "@tanstack/react-table";
import { memo, useMemo, useState } from "react";
import {
@@ -16,7 +15,6 @@ import {
LuContainer,
LuCreditCard,
LuPencil,
- LuPin,
LuQrCode,
LuStar,
LuTrash,
@@ -37,7 +35,6 @@ import { useCustomColumns } from "~/hooks/useCustomColumns";
import type { PurchaseOrder } from "~/modules/purchasing";
import { purchaseOrderStatusType } from "~/modules/purchasing";
import { usePeople, useSuppliers } from "~/stores";
-import { favoriteSchema } from "~/types/validators";
import { path } from "~/utils/path";
import PurchasingStatus from "./PurchasingStatus";
import { usePurchaseOrder } from "./usePurchaseOrder";
@@ -59,23 +56,7 @@ const PurchaseOrdersTable = memo(
const [people] = usePeople();
const [suppliers] = useSuppliers();
- const fetcher = useFetcher<{}>();
- const optimisticFavorite = useOptimisticFavorite();
-
- const rows = useMemo<PurchaseOrder[]>(
- () =>
- data.map((d) =>
- d.id === optimisticFavorite?.id
- ? {
- ...d,
- favorite: optimisticFavorite?.favorite
- ? optimisticFavorite.favorite === "favorite"
- : d.favorite,
- }
- : d
- ),
- [data, optimisticFavorite]
- );
+ // const optimisticFavorite = useOptimisticFavorite();
const { edit, receive } = usePurchaseOrder();
@@ -88,38 +69,6 @@ const PurchaseOrdersTable = memo(
header: "PO Number",
cell: ({ row }) => (
<HStack>
- {row.original.favorite ? (
- <fetcher.Form
- method="post"
- action={path.to.purchaseOrderFavorite}
- 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="cursor-pointer w-4 h-4 outline-foreground fill-foreground flex-shrink-0"
- type="submit"
- />
- </button>
- </fetcher.Form>
- ) : (
- <fetcher.Form
- method="post"
- action={path.to.purchaseOrderFavorite}
- 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="cursor-pointer w-4 h-4 text-muted-foreground flex-shrink-0"
- type="submit"
- />
- </button>
- </fetcher.Form>
- )}
-
<Hyperlink to={path.to.purchaseOrderDetails(row.original.id!)}>
{row.original.purchaseOrderId}
</Hyperlink>
@@ -297,7 +246,7 @@ const PurchaseOrdersTable = memo(
];
return [...defaultColumns, ...customColumns];
- }, [suppliers, people, customColumns, fetcher]);
+ }, [suppliers, people, customColumns]);
const renderContextMenu = useMemo(() => {
// eslint-disable-next-line react/display-name
@@ -343,7 +292,7 @@ const PurchaseOrdersTable = memo(
<Table<PurchaseOrder>
count={count}
columns={columns}
- data={rows}
+ data={data}
defaultColumnPinning={{
left: ["purchaseOrderId"],
}}
@@ -389,19 +338,3 @@ const PurchaseOrdersTable = memo(
PurchaseOrdersTable.displayName = "PurchaseOrdersTable";
export default PurchaseOrdersTable;
-
-function useOptimisticFavorite() {
- const fetchers = useFetchers();
- const favoriteFetcher = fetchers.find(
- (f) => f.formAction === path.to.purchaseOrderFavorite
- );
-
- 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/SupplierQuote/SupplierQuotesTable.tsx b/apps/carbon/app/modules/purchasing/ui/SupplierQuote/SupplierQuotesTable.tsx
index d130cdfb60..4ee7593aee 100644
--- a/apps/carbon/app/modules/purchasing/ui/SupplierQuote/SupplierQuotesTable.tsx
+++ b/apps/carbon/app/modules/purchasing/ui/SupplierQuote/SupplierQuotesTable.tsx
@@ -1,13 +1,12 @@
import { HStack, MenuIcon, MenuItem, useDisclosure } from "@carbon/react";
import { formatDate } from "@carbon/utils";
-import { useFetcher, useFetchers, useNavigate } from "@remix-run/react";
+import { useNavigate } from "@remix-run/react";
import type { ColumnDef } from "@tanstack/react-table";
import { memo, useMemo, useState } from "react";
import {
LuBookMarked,
LuCalendar,
LuPencil,
- LuPin,
LuQrCode,
LuStar,
LuTrash,
@@ -26,7 +25,6 @@ import { ConfirmDelete } from "~/components/Modals";
import { usePermissions } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
import { usePeople, useSuppliers } from "~/stores";
-import { favoriteSchema } from "~/types/validators";
import { path } from "~/utils/path";
import { supplierQuoteStatusType } from "../../purchasing.models";
import type { SupplierQuote } from "../../types";
@@ -52,23 +50,8 @@ const SupplierQuotesTable = memo(
const [suppliers] = useSuppliers();
const [people] = usePeople();
- const fetcher = useFetcher<{}>();
- const optimisticFavorite = useOptimisticFavorite();
+ // const optimisticFavorite = useOptimisticFavorite();
- const rows = useMemo<SupplierQuote[]>(
- () =>
- data.map((d) =>
- d.id === optimisticFavorite?.id
- ? {
- ...d,
- favorite: optimisticFavorite?.favorite
- ? optimisticFavorite.favorite === "favorite"
- : d.favorite,
- }
- : d
- ),
- [data, optimisticFavorite]
- );
const customColumns = useCustomColumns<SupplierQuote>("quote");
const columns = useMemo<ColumnDef<SupplierQuote>[]>(() => {
const employeeOptions = people.map((employee) => ({
@@ -82,37 +65,6 @@ const SupplierQuotesTable = memo(
header: "Quote Number",
cell: ({ row }) => (
<HStack>
- {row.original.favorite ? (
- <fetcher.Form
- method="post"
- action={path.to.supplierQuoteFavorite}
- 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="cursor-pointer w-4 h-4 outline-foreground fill-foreground flex-shrink-0"
- type="submit"
- />
- </button>
- </fetcher.Form>
- ) : (
- <fetcher.Form
- method="post"
- action={path.to.supplierQuoteFavorite}
- 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="cursor-pointer w-4 h-4 text-muted-foreground flex-shrink-0"
- type="submit"
- />
- </button>
- </fetcher.Form>
- )}
<ItemThumbnail
size="sm"
thumbnailPath={row.original.thumbnailPath}
@@ -257,7 +209,7 @@ const SupplierQuotesTable = memo(
];
return [...defaultColumns, ...customColumns];
- }, [suppliers, people, customColumns, fetcher]);
+ }, [suppliers, people, customColumns]);
const renderContextMenu = useMemo(() => {
// eslint-disable-next-line react/display-name
@@ -288,7 +240,7 @@ const SupplierQuotesTable = memo(
<Table<SupplierQuote>
count={count}
columns={columns}
- data={rows}
+ data={data}
defaultColumnPinning={{
left: ["supplierQuoteId"],
}}
@@ -329,19 +281,3 @@ const SupplierQuotesTable = memo(
SupplierQuotesTable.displayName = "SupplierQuotesTable";
export default SupplierQuotesTable;
-
-function useOptimisticFavorite() {
- const fetchers = useFetchers();
- const favoriteFetcher = fetchers.find(
- (f) => f.formAction === path.to.supplierQuoteFavorite
- );
-
- 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/sales/sales.service.ts b/apps/carbon/app/modules/sales/sales.service.ts
index ec24672789..61f08f7109 100644
--- a/apps/carbon/app/modules/sales/sales.service.ts
+++ b/apps/carbon/app/modules/sales/sales.service.ts
@@ -521,6 +521,18 @@ export async function getQuote(
return client.from("quotes").select("*").eq("id", quoteId).single();
}
+export async function getQuoteFavorites(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ userId: string
+) {
+ return client
+ .from("quoteFavorite")
+ .select("*")
+ .eq("companyId", companyId)
+ .eq("userId", userId);
+}
+
export async function getQuotes(
client: SupabaseClient<Database>,
companyId: string,
@@ -540,7 +552,6 @@ export async function getQuotes(
}
query = setGenericQueryFilters(query, args, [
- { column: "favorite", ascending: false },
{ column: "id", ascending: false },
]);
return query;
@@ -856,6 +867,18 @@ export async function getSalesOrder(
return client.from("salesOrders").select("*").eq("id", salesOrderId).single();
}
+export async function getSalesOrderFavorites(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ userId: string
+) {
+ return client
+ .from("salesOrderFavorite")
+ .select("*")
+ .eq("companyId", companyId)
+ .eq("userId", userId);
+}
+
export async function getSalesOrders(
client: SupabaseClient<Database>,
companyId: string,
@@ -881,8 +904,7 @@ export async function getSalesOrders(
}
query = setGenericQueryFilters(query, args, [
- { column: "favorite", ascending: false },
- { column: "salesOrderId", ascending: false },
+ { column: "id", ascending: false },
]);
return query;
@@ -950,6 +972,18 @@ export async function getSalesRFQ(
return client.from("salesRfqs").select("*").eq("id", id).single();
}
+export async function getSalesRFQFavorites(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ userId: string
+) {
+ return client
+ .from("salesRfqFavorite")
+ .select("*")
+ .eq("companyId", companyId)
+ .eq("userId", userId);
+}
+
export async function getSalesRFQs(
client: SupabaseClient<Database>,
companyId: string,
@@ -969,7 +1003,6 @@ export async function getSalesRFQs(
}
query = setGenericQueryFilters(query, args, [
- { column: "favorite", ascending: false },
{ column: "id", ascending: false },
]);
return query;
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuotesTable.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuotesTable.tsx
index df441b52c0..b1dd2d4472 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuotesTable.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuotesTable.tsx
@@ -6,7 +6,7 @@ import {
useDisclosure,
} from "@carbon/react";
import { formatDate } from "@carbon/utils";
-import { useFetcher, useFetchers, useNavigate } from "@remix-run/react";
+import { useNavigate } from "@remix-run/react";
import type { ColumnDef } from "@tanstack/react-table";
import { memo, useMemo, useState } from "react";
import {
@@ -14,7 +14,6 @@ import {
LuCalendar,
LuMap,
LuPencil,
- LuPin,
LuQrCode,
LuStar,
LuTrash,
@@ -34,7 +33,6 @@ import { ConfirmDelete } from "~/components/Modals";
import { usePermissions } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
import { useCustomers, usePeople } from "~/stores";
-import { favoriteSchema } from "~/types/validators";
import { path } from "~/utils/path";
import { quoteStatusType } from "../../sales.models";
import type { Quotation } from "../../types";
@@ -57,23 +55,6 @@ const QuotesTable = memo(({ data, count }: QuotesTableProps) => {
const [customers] = useCustomers();
const [people] = usePeople();
- const fetcher = useFetcher<{}>();
- const optimisticFavorite = useOptimisticFavorite();
-
- const rows = useMemo<Quotation[]>(
- () =>
- data.map((d) =>
- d.id === optimisticFavorite?.id
- ? {
- ...d,
- favorite: optimisticFavorite?.favorite
- ? optimisticFavorite.favorite === "favorite"
- : d.favorite,
- }
- : d
- ),
- [data, optimisticFavorite]
- );
const customColumns = useCustomColumns<Quotation>("quote");
const columns = useMemo<ColumnDef<Quotation>[]>(() => {
const employeeOptions = people.map((employee) => ({
@@ -87,37 +68,6 @@ const QuotesTable = memo(({ data, count }: QuotesTableProps) => {
header: "Quote Number",
cell: ({ row }) => (
<HStack>
- {row.original.favorite ? (
- <fetcher.Form
- method="post"
- action={path.to.quoteFavorite}
- 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="cursor-pointer w-4 h-4 outline-foreground fill-foreground flex-shrink-0"
- type="submit"
- />
- </button>
- </fetcher.Form>
- ) : (
- <fetcher.Form
- method="post"
- action={path.to.quoteFavorite}
- 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="cursor-pointer w-4 h-4 text-muted-foreground flex-shrink-0"
- type="submit"
- />
- </button>
- </fetcher.Form>
- )}
<ItemThumbnail
size="sm"
thumbnailPath={row.original.thumbnailPath}
@@ -317,7 +267,7 @@ const QuotesTable = memo(({ data, count }: QuotesTableProps) => {
];
return [...defaultColumns, ...customColumns];
- }, [customers, people, customColumns, fetcher]);
+ }, [customers, people, customColumns]);
const renderContextMenu = useMemo(() => {
// eslint-disable-next-line react/display-name
@@ -346,7 +296,7 @@ const QuotesTable = memo(({ data, count }: QuotesTableProps) => {
<Table<Quotation>
count={count}
columns={columns}
- data={rows}
+ data={data}
defaultColumnPinning={{
left: ["quoteId"],
}}
@@ -386,19 +336,3 @@ const QuotesTable = memo(({ data, count }: QuotesTableProps) => {
QuotesTable.displayName = "QuotesTable";
export default QuotesTable;
-
-function useOptimisticFavorite() {
- const fetchers = useFetchers();
- const favoriteFetcher = fetchers.find(
- (f) => f.formAction === path.to.quoteFavorite
- );
-
- 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/sales/ui/SalesOrder/SalesOrdersTable.tsx b/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrdersTable.tsx
index cb3023318f..151c9b20a4 100644
--- a/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrdersTable.tsx
+++ b/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrdersTable.tsx
@@ -11,7 +11,7 @@ import {
useDisclosure,
} from "@carbon/react";
import { formatDate } from "@carbon/utils";
-import { useFetcher, useFetchers, useNavigate } from "@remix-run/react";
+import { useNavigate } from "@remix-run/react";
import type { ColumnDef } from "@tanstack/react-table";
import { memo, useCallback, useMemo, useState } from "react";
import {
@@ -21,7 +21,6 @@ import {
LuDollarSign,
LuExternalLink,
LuPencil,
- LuPin,
LuQrCode,
LuStar,
LuTrash,
@@ -44,7 +43,6 @@ import { useCustomColumns } from "~/hooks/useCustomColumns";
import JobStatus from "~/modules/production/ui/Jobs/JobStatus";
import { useCustomers, usePeople } from "~/stores";
-import { favoriteSchema } from "~/types/validators";
import { path } from "~/utils/path";
import { salesOrderStatusType } from "../../sales.models";
import type { SalesOrder } from "../../types";
@@ -67,24 +65,6 @@ const SalesOrdersTable = memo(({ data, count }: SalesOrdersTableProps) => {
const [people] = usePeople();
const [customers] = useCustomers();
- const fetcher = useFetcher<{}>();
- const optimisticFavorite = useOptimisticFavorite();
-
- const rows = useMemo<SalesOrder[]>(
- () =>
- data.map((d) =>
- d.id === optimisticFavorite?.id
- ? {
- ...d,
- favorite: optimisticFavorite?.favorite
- ? optimisticFavorite.favorite === "favorite"
- : d.favorite,
- }
- : d
- ),
- [data, optimisticFavorite]
- );
-
const { edit } = useSalesOrder();
const customColumns = useCustomColumns<SalesOrder>("salesOrder");
@@ -96,38 +76,6 @@ const SalesOrdersTable = memo(({ data, count }: SalesOrdersTableProps) => {
header: "Sales Order Number",
cell: ({ row }) => (
<HStack>
- {row.original.favorite ? (
- <fetcher.Form
- method="post"
- action={path.to.salesOrderFavorite}
- 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="cursor-pointer w-4 h-4 outline-foreground fill-foreground flex-shrink-0"
- type="submit"
- />
- </button>
- </fetcher.Form>
- ) : (
- <fetcher.Form
- method="post"
- action={path.to.salesOrderFavorite}
- 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="cursor-pointer w-4 h-4 text-muted-foreground flex-shrink-0"
- type="submit"
- />
- </button>
- </fetcher.Form>
- )}
-
<ItemThumbnail
size="sm"
thumbnailPath={row.original.thumbnailPath}
@@ -365,7 +313,7 @@ const SalesOrdersTable = memo(({ data, count }: SalesOrdersTableProps) => {
];
return [...defaultColumns, ...customColumns];
- }, [customers, people, customColumns, fetcher, currencyFormatter]);
+ }, [customers, people, customColumns, currencyFormatter]);
const renderContextMenu = useMemo(() => {
// eslint-disable-next-line react/display-name
@@ -411,7 +359,7 @@ const SalesOrdersTable = memo(({ data, count }: SalesOrdersTableProps) => {
<Table<SalesOrder>
count={count}
columns={columns}
- data={rows}
+ data={data}
defaultColumnPinning={{
left: ["salesOrderId"],
}}
@@ -457,22 +405,6 @@ SalesOrdersTable.displayName = "SalesOrdersTable";
export default SalesOrdersTable;
-function useOptimisticFavorite() {
- const fetchers = useFetchers();
- const favoriteFetcher = fetchers.find(
- (f) => f.formAction === path.to.salesOrderFavorite
- );
-
- 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;
- }
- }
-}
-
export const useSalesOrder = () => {
const navigate = useNavigate();
diff --git a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQsTable.tsx b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQsTable.tsx
index 5c67294571..f3045b103a 100644
--- a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQsTable.tsx
+++ b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQsTable.tsx
@@ -1,6 +1,6 @@
import { HStack, MenuIcon, MenuItem, useDisclosure } from "@carbon/react";
import { formatDate } from "@carbon/utils";
-import { useFetcher, useFetchers, useNavigate } from "@remix-run/react";
+import { useNavigate } from "@remix-run/react";
import type { ColumnDef } from "@tanstack/react-table";
import { memo, useMemo, useState } from "react";
import {
@@ -8,7 +8,6 @@ import {
LuCalendar,
LuMap,
LuPencil,
- LuPin,
LuQrCode,
LuStar,
LuTrash,
@@ -27,7 +26,6 @@ import { ConfirmDelete } from "~/components/Modals";
import { usePermissions } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
import { useCustomers, usePeople } from "~/stores";
-import { favoriteSchema } from "~/types/validators";
import { path } from "~/utils/path";
import { SalesRFQStatus } from ".";
import { salesRFQStatusType } from "../../sales.models";
@@ -50,23 +48,6 @@ const SalesRFQsTable = memo(({ data, count }: SalesRFQsTableProps) => {
const [customers] = useCustomers();
const [people] = usePeople();
- const fetcher = useFetcher<{}>();
- const optimisticFavorite = useOptimisticFavorite();
-
- const rows = useMemo<SalesRFQ[]>(
- () =>
- data.map((d) =>
- d.id === optimisticFavorite?.id
- ? {
- ...d,
- favorite: optimisticFavorite?.favorite
- ? optimisticFavorite.favorite === "favorite"
- : d.favorite,
- }
- : d
- ),
- [data, optimisticFavorite]
- );
const customColumns = useCustomColumns<SalesRFQ>("salesRFQ");
const columns = useMemo<ColumnDef<SalesRFQ>[]>(() => {
const defaultColumns: ColumnDef<SalesRFQ>[] = [
@@ -75,37 +56,6 @@ const SalesRFQsTable = memo(({ data, count }: SalesRFQsTableProps) => {
header: "RFQ Number",
cell: ({ row }) => (
<HStack>
- {row.original.favorite ? (
- <fetcher.Form
- method="post"
- action={path.to.salesRfqFavorite}
- 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="cursor-pointer w-4 h-4 outline-foreground fill-foreground"
- type="submit"
- />
- </button>
- </fetcher.Form>
- ) : (
- <fetcher.Form
- method="post"
- action={path.to.salesRfqFavorite}
- 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="cursor-pointer w-4 h-4 text-muted-foreground"
- type="submit"
- />
- </button>
- </fetcher.Form>
- )}
<Hyperlink to={path.to.salesRfqDetails(row.original.id!)}>
{row.original.rfqId}
</Hyperlink>
@@ -264,7 +214,7 @@ const SalesRFQsTable = memo(({ data, count }: SalesRFQsTableProps) => {
];
return [...defaultColumns, ...customColumns];
- }, [customers, people, customColumns, fetcher]);
+ }, [customers, people, customColumns]);
const renderContextMenu = useMemo(() => {
// eslint-disable-next-line react/display-name
@@ -293,7 +243,7 @@ const SalesRFQsTable = memo(({ data, count }: SalesRFQsTableProps) => {
<Table<SalesRFQ>
count={count}
columns={columns}
- data={rows}
+ data={data}
defaultColumnPinning={{
left: ["rfqId"],
}}
@@ -332,19 +282,3 @@ const SalesRFQsTable = memo(({ data, count }: SalesRFQsTableProps) => {
SalesRFQsTable.displayName = "SalesRFQsTable";
export default SalesRFQsTable;
-
-function useOptimisticFavorite() {
- const fetchers = useFetchers();
- const favoriteFetcher = fetchers.find(
- (f) => f.formAction === path.to.salesRfqFavorite
- );
-
- 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/routes/x+/job+/$jobId.tsx b/apps/carbon/app/routes/x+/job+/$jobId.tsx
index 354d3de366..d65790c46e 100644
--- a/apps/carbon/app/routes/x+/job+/$jobId.tsx
+++ b/apps/carbon/app/routes/x+/job+/$jobId.tsx
@@ -36,19 +36,23 @@ export const handle: Handle = {
};
export async function loader({ request, params }: LoaderFunctionArgs) {
- const { companyId } = await requirePermissions(request, {
+ const { client, companyId } = await requirePermissions(request, {
view: "production",
});
const { jobId } = params;
if (!jobId) throw new Error("Could not find jobId");
- const serviceRole = await getCarbonServiceRole();
const [job, tags] = await Promise.all([
- getJob(serviceRole, jobId),
- getTagsList(serviceRole, companyId, "job"),
+ getJob(client, jobId),
+ getTagsList(client, companyId, "job"),
]);
+ if (companyId !== job.data?.companyId) {
+ throw redirect(path.to.jobs);
+ }
+ const serviceRole = await getCarbonServiceRole();
+
if (job.error) {
throw redirect(
path.to.jobs,
diff --git a/apps/carbon/app/routes/x+/job+/new.tsx b/apps/carbon/app/routes/x+/job+/new.tsx
index 11c93b924c..047ea98cfd 100644
--- a/apps/carbon/app/routes/x+/job+/new.tsx
+++ b/apps/carbon/app/routes/x+/job+/new.tsx
@@ -26,6 +26,7 @@ export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
const { companyId, userId } = await requirePermissions(request, {
create: "production",
+ bypassRls: true,
});
const serviceRole = getCarbonServiceRole();
diff --git a/apps/carbon/app/routes/x+/purchase-order+/$orderId.tsx b/apps/carbon/app/routes/x+/purchase-order+/$orderId.tsx
index 351704ad63..68c57d2ece 100644
--- a/apps/carbon/app/routes/x+/purchase-order+/$orderId.tsx
+++ b/apps/carbon/app/routes/x+/purchase-order+/$orderId.tsx
@@ -1,4 +1,4 @@
-import { error, getCarbonServiceRole } from "@carbon/auth";
+import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { Outlet, useLoaderData } from "@remix-run/react";
@@ -25,18 +25,17 @@ export const handle: Handle = {
};
export async function loader({ request, params }: LoaderFunctionArgs) {
- const { companyId } = await requirePermissions(request, {
+ const { client, companyId } = await requirePermissions(request, {
view: "purchasing",
+ bypassRls: true,
});
const { orderId } = params;
if (!orderId) throw new Error("Could not find orderId");
- const serviceRole = await getCarbonServiceRole();
-
const [purchaseOrder, purchaseOrderLines] = await Promise.all([
- getPurchaseOrder(serviceRole, orderId),
- getPurchaseOrderLines(serviceRole, orderId),
+ getPurchaseOrder(client, orderId),
+ getPurchaseOrderLines(client, orderId),
]);
if (purchaseOrder.error) {
@@ -49,16 +48,20 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
);
}
+ if (companyId !== purchaseOrder.data?.companyId) {
+ throw redirect(path.to.purchaseOrders);
+ }
+
return defer({
purchaseOrder: purchaseOrder.data,
purchaseOrderLines: purchaseOrderLines.data ?? [],
externalDocuments: getPurchaseOrderExternalDocuments(
- serviceRole,
+ client,
companyId,
orderId
),
internalDocuments: getPurchaseOrderInternalDocuments(
- serviceRole,
+ client,
companyId,
orderId
),
diff --git a/apps/carbon/app/routes/x+/purchase-order+/new.tsx b/apps/carbon/app/routes/x+/purchase-order+/new.tsx
index 9092ad27e6..9f7f105b71 100644
--- a/apps/carbon/app/routes/x+/purchase-order+/new.tsx
+++ b/apps/carbon/app/routes/x+/purchase-order+/new.tsx
@@ -30,6 +30,7 @@ export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
const { client, companyId, userId } = await requirePermissions(request, {
create: "purchasing",
+ bypassRls: true,
});
const formData = await request.formData();
diff --git a/apps/carbon/app/routes/x+/quote+/$quoteId.tsx b/apps/carbon/app/routes/x+/quote+/$quoteId.tsx
index ef978a8b08..2f73d8f8a6 100644
--- a/apps/carbon/app/routes/x+/quote+/$quoteId.tsx
+++ b/apps/carbon/app/routes/x+/quote+/$quoteId.tsx
@@ -1,4 +1,4 @@
-import { error, getCarbonServiceRole } from "@carbon/auth";
+import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { ClientOnly, VStack } from "@carbon/react";
@@ -35,27 +35,31 @@ export const handle: Handle = {
};
export async function loader({ request, params }: LoaderFunctionArgs) {
- const { companyId } = await requirePermissions(request, {
+ const { client, companyId } = await requirePermissions(request, {
view: "sales",
+ bypassRls: true,
});
const { quoteId } = params;
if (!quoteId) throw new Error("Could not find quoteId");
- const serviceRole = await getCarbonServiceRole();
const [quote, shipment, payment, lines, prices, opportunity, methods] =
await Promise.all([
- getQuote(serviceRole, quoteId),
- getQuoteShipment(serviceRole, quoteId),
- getQuotePayment(serviceRole, quoteId),
- getQuoteLines(serviceRole, quoteId),
- getQuoteLinePricesByQuoteId(serviceRole, quoteId),
- getOpportunityByQuote(serviceRole, quoteId),
- getQuoteMethodTrees(serviceRole, quoteId),
+ getQuote(client, quoteId),
+ getQuoteShipment(client, quoteId),
+ getQuotePayment(client, quoteId),
+ getQuoteLines(client, quoteId),
+ getQuoteLinePricesByQuoteId(client, quoteId),
+ getOpportunityByQuote(client, quoteId),
+ getQuoteMethodTrees(client, quoteId),
]);
if (!opportunity.data) throw new Error("Failed to get opportunity record");
+ if (companyId !== quote.data?.companyId) {
+ throw redirect(path.to.quotes);
+ }
+
if (quote.error) {
throw redirect(
path.to.quotes,
@@ -83,7 +87,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
let exchangeRate = 1;
if (quote.data?.currencyCode) {
const presentationCurrency = await getCurrencyByCode(
- serviceRole,
+ client,
companyId,
quote.data.currencyCode
);
@@ -95,7 +99,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
let salesOrderLines: PostgrestResponse<SalesOrderLine> | null = null;
if (opportunity.data?.salesOrderId) {
salesOrderLines = await getSalesOrderLines(
- serviceRole,
+ client,
opportunity.data.salesOrderId
);
}
@@ -104,7 +108,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
quote: quote.data,
lines: lines.data ?? [],
methods: methods.data ?? [],
- files: getOpportunityDocuments(serviceRole, companyId, opportunity.data.id),
+ files: getOpportunityDocuments(client, companyId, opportunity.data.id),
prices: prices.data ?? [],
shipment: shipment.data,
payment: payment.data,
diff --git a/apps/carbon/app/routes/x+/quote+/new.tsx b/apps/carbon/app/routes/x+/quote+/new.tsx
index 8b4fc1bdf1..4366094903 100644
--- a/apps/carbon/app/routes/x+/quote+/new.tsx
+++ b/apps/carbon/app/routes/x+/quote+/new.tsx
@@ -24,6 +24,7 @@ export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
const { client, companyId, userId } = await requirePermissions(request, {
create: "sales",
+ bypassRls: true,
});
const formData = await request.formData();
diff --git a/apps/carbon/app/routes/x+/sales-order+/$orderId.tsx b/apps/carbon/app/routes/x+/sales-order+/$orderId.tsx
index c1833ab1d3..c5b0875784 100644
--- a/apps/carbon/app/routes/x+/sales-order+/$orderId.tsx
+++ b/apps/carbon/app/routes/x+/sales-order+/$orderId.tsx
@@ -1,4 +1,4 @@
-import { error, getCarbonServiceRole } from "@carbon/auth";
+import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { ClientOnly, VStack } from "@carbon/react";
@@ -28,21 +28,24 @@ export const handle: Handle = {
};
export async function loader({ request, params }: LoaderFunctionArgs) {
- const { companyId } = await requirePermissions(request, {
+ const { client, companyId } = await requirePermissions(request, {
view: "sales",
+ bypassRls: true,
});
const { orderId } = params;
if (!orderId) throw new Error("Could not find orderId");
- const serviceRole = await getCarbonServiceRole();
-
const [salesOrder, lines, opportunity] = await Promise.all([
- getSalesOrder(serviceRole, orderId),
- getSalesOrderLines(serviceRole, orderId),
- getOpportunityBySalesOrder(serviceRole, orderId),
+ getSalesOrder(client, orderId),
+ getSalesOrderLines(client, orderId),
+ getOpportunityBySalesOrder(client, orderId),
]);
+ if (companyId !== salesOrder.data?.companyId) {
+ throw redirect(path.to.salesOrders);
+ }
+
if (!opportunity.data) throw new Error("Failed to get opportunity record");
if (salesOrder.error) {
@@ -53,13 +56,13 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
}
const customer = salesOrder.data?.customerId
- ? await getCustomer(serviceRole, salesOrder.data.customerId)
+ ? await getCustomer(client, salesOrder.data.customerId)
: null;
return defer({
salesOrder: salesOrder.data,
lines: lines.data ?? [],
- files: getOpportunityDocuments(serviceRole, companyId, opportunity.data.id),
+ files: getOpportunityDocuments(client, companyId, opportunity.data.id),
opportunity: opportunity.data,
customer: customer?.data ?? null,
});
diff --git a/apps/carbon/app/routes/x+/sales-order+/new.tsx b/apps/carbon/app/routes/x+/sales-order+/new.tsx
index 2e974bac5c..5b43bcc278 100644
--- a/apps/carbon/app/routes/x+/sales-order+/new.tsx
+++ b/apps/carbon/app/routes/x+/sales-order+/new.tsx
@@ -23,6 +23,7 @@ export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
const { client, companyId, userId } = await requirePermissions(request, {
create: "sales",
+ bypassRls: true,
});
const formData = await request.formData();
diff --git a/apps/carbon/app/routes/x+/supplier-quote+/new.tsx b/apps/carbon/app/routes/x+/supplier-quote+/new.tsx
index 0fb616f2bd..0a639ca10a 100644
--- a/apps/carbon/app/routes/x+/supplier-quote+/new.tsx
+++ b/apps/carbon/app/routes/x+/supplier-quote+/new.tsx
@@ -26,6 +26,7 @@ export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
const { client, companyId, userId } = await requirePermissions(request, {
create: "purchasing",
+ bypassRls: true,
});
const formData = await request.formData();
diff --git a/packages/auth/src/services/auth.server.ts b/packages/auth/src/services/auth.server.ts
index f63fe16d46..7db9b5b3a9 100644
--- a/packages/auth/src/services/auth.server.ts
+++ b/packages/auth/src/services/auth.server.ts
@@ -122,6 +122,7 @@ export async function requirePermissions(
const hasRequiredPermissions = Object.entries(requiredPermissions).every(
([action, permission]) => {
+ if (action === "bypassRls") return true;
if (typeof permission === "string") {
if (action === "role") {
return myClaims.role === permission;
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 69aba8b9ce..6e54774bf8 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -26658,14 +26658,14 @@ export type Database = {
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["supplierLocationId"]
+ columns: ["id"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["id"]
+ columns: ["supplierLocationId"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
@@ -27564,8 +27564,9 @@ export type Database = {
dropShipment: boolean | null
exchangeRate: number | null
exchangeRateUpdatedAt: string | null
- favorite: boolean | null
+ externalNotes: Json | null
id: string | null
+ internalNotes: Json | null
locationId: string | null
locationName: string | null
notes: string | null
@@ -27582,6 +27583,7 @@ export type Database = {
supplierId: string | null
supplierLocationId: string | null
supplierReference: string | null
+ tags: string[] | null
type: Database["public"]["Enums"]["purchaseOrderType"] | null
updatedAt: string | null
updatedBy: string | null
@@ -28549,7 +28551,6 @@ export type Database = {
expirationDate: string | null
externalLinkId: string | null
externalNotes: Json | null
- favorite: boolean | null
id: string | null
internalNotes: Json | null
itemType: Database["public"]["Enums"]["itemType"] | null
@@ -29324,14 +29325,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["paymentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["paymentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -29356,7 +29357,6 @@ export type Database = {
exchangeRate: number | null
exchangeRateUpdatedAt: string | null
externalNotes: Json | null
- favorite: boolean | null
id: string | null
internalNotes: Json | null
itemType: Database["public"]["Enums"]["itemType"] | null
@@ -29365,14 +29365,14 @@ export type Database = {
locationName: string | null
orderDate: string | null
orderTotal: number | null
- paymentTermName: string | null
+ paymentTermId: string | null
receiptPromisedDate: string | null
receiptRequestedDate: string | null
revisionId: number | null
salesOrderId: string | null
salesPersonId: string | null
shippingCost: number | null
- shippingMethodName: string | null
+ shippingMethodId: string | null
shippingTermName: string | null
status: Database["public"]["Enums"]["salesOrderStatus"] | null
thumbnailPath: string | null
@@ -29604,6 +29604,20 @@ export type Database = {
referencedRelation: "customerLocation"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "salesOrderPayment_paymentTermId_fkey"
+ columns: ["paymentTermId"]
+ isOneToOne: false
+ referencedRelation: "paymentTerm"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "salesOrderShipment_shippingMethodId_fkey"
+ columns: ["shippingMethodId"]
+ isOneToOne: false
+ referencedRelation: "shippingMethod"
+ referencedColumns: ["id"]
+ },
]
}
salesRfqLines: {
@@ -29781,7 +29795,6 @@ export type Database = {
employeeId: string | null
expirationDate: string | null
externalNotes: Json | null
- favorite: boolean | null
id: string | null
internalNotes: Json | null
locationId: string | null
@@ -29793,6 +29806,7 @@ export type Database = {
salesOrderId: string | null
salesPersonId: string | null
status: Database["public"]["Enums"]["salesRfqStatus"] | null
+ tags: string[] | null
updatedAt: string | null
updatedBy: string | null
}
@@ -30535,7 +30549,6 @@ export type Database = {
exchangeRateUpdatedAt: string | null
expirationDate: string | null
externalNotes: Json | null
- favorite: boolean | null
id: string | null
internalNotes: Json | null
itemType: Database["public"]["Enums"]["itemType"] | null
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 69aba8b9ce..6e54774bf8 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -26658,14 +26658,14 @@ export type Database = {
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["supplierLocationId"]
+ columns: ["id"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["id"]
+ columns: ["supplierLocationId"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
@@ -27564,8 +27564,9 @@ export type Database = {
dropShipment: boolean | null
exchangeRate: number | null
exchangeRateUpdatedAt: string | null
- favorite: boolean | null
+ externalNotes: Json | null
id: string | null
+ internalNotes: Json | null
locationId: string | null
locationName: string | null
notes: string | null
@@ -27582,6 +27583,7 @@ export type Database = {
supplierId: string | null
supplierLocationId: string | null
supplierReference: string | null
+ tags: string[] | null
type: Database["public"]["Enums"]["purchaseOrderType"] | null
updatedAt: string | null
updatedBy: string | null
@@ -28549,7 +28551,6 @@ export type Database = {
expirationDate: string | null
externalLinkId: string | null
externalNotes: Json | null
- favorite: boolean | null
id: string | null
internalNotes: Json | null
itemType: Database["public"]["Enums"]["itemType"] | null
@@ -29324,14 +29325,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["paymentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["paymentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -29356,7 +29357,6 @@ export type Database = {
exchangeRate: number | null
exchangeRateUpdatedAt: string | null
externalNotes: Json | null
- favorite: boolean | null
id: string | null
internalNotes: Json | null
itemType: Database["public"]["Enums"]["itemType"] | null
@@ -29365,14 +29365,14 @@ export type Database = {
locationName: string | null
orderDate: string | null
orderTotal: number | null
- paymentTermName: string | null
+ paymentTermId: string | null
receiptPromisedDate: string | null
receiptRequestedDate: string | null
revisionId: number | null
salesOrderId: string | null
salesPersonId: string | null
shippingCost: number | null
- shippingMethodName: string | null
+ shippingMethodId: string | null
shippingTermName: string | null
status: Database["public"]["Enums"]["salesOrderStatus"] | null
thumbnailPath: string | null
@@ -29604,6 +29604,20 @@ export type Database = {
referencedRelation: "customerLocation"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "salesOrderPayment_paymentTermId_fkey"
+ columns: ["paymentTermId"]
+ isOneToOne: false
+ referencedRelation: "paymentTerm"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "salesOrderShipment_shippingMethodId_fkey"
+ columns: ["shippingMethodId"]
+ isOneToOne: false
+ referencedRelation: "shippingMethod"
+ referencedColumns: ["id"]
+ },
]
}
salesRfqLines: {
@@ -29781,7 +29795,6 @@ export type Database = {
employeeId: string | null
expirationDate: string | null
externalNotes: Json | null
- favorite: boolean | null
id: string | null
internalNotes: Json | null
locationId: string | null
@@ -29793,6 +29806,7 @@ export type Database = {
salesOrderId: string | null
salesPersonId: string | null
status: Database["public"]["Enums"]["salesRfqStatus"] | null
+ tags: string[] | null
updatedAt: string | null
updatedBy: string | null
}
@@ -30535,7 +30549,6 @@ export type Database = {
exchangeRateUpdatedAt: string | null
expirationDate: string | null
externalNotes: Json | null
- favorite: boolean | null
id: string | null
internalNotes: Json | null
itemType: Database["public"]["Enums"]["itemType"] | null
diff --git a/packages/database/supabase/migrations/20241210140215_rls-performance.sql b/packages/database/supabase/migrations/20241210140215_rls-performance.sql
index 73c622f3c3..8e1a7e426e 100644
--- a/packages/database/supabase/migrations/20241210140215_rls-performance.sql
+++ b/packages/database/supabase/migrations/20241210140215_rls-performance.sql
@@ -832,8 +832,6 @@ ALTER POLICY "Authenticated users can view custom field tables" ON "customFieldT
);
--- pointer
-
ALTER POLICY "Users can view their own sales order favorites" ON "salesOrderFavorite"
USING (
(SELECT auth.uid())::text = "userId"
@@ -1178,4 +1176,386 @@ ALTER POLICY "Customers with sales_delete can delete lines on their own quote" O
)
);
-DROP POLICY "Customers with sales_view can their own quote make methods" ON "quoteMakeMethod";
\ No newline at end of file
+DROP POLICY "Customers with sales_view can their own quote make methods" ON "quoteMakeMethod";
+
+
+
+ALTER POLICY "Employees can view processes" ON "process"
+ USING (
+ has_role('employee', "companyId") AND
+ "companyId" = ANY(
+ select "companyId" from "userToCompany" where "userId" = (SELECT auth.uid())::text
+ )
+ );
+
+
+ALTER POLICY "Employees can view work centers" ON "workCenter"
+ USING (
+ has_role('employee', "companyId") AND
+ "companyId" = ANY(
+ select "companyId" from "userToCompany" where "userId" = (SELECT auth.uid())::text
+ )
+ );
+
+ALTER POLICY "Employees can view work center/processes" ON "workCenterProcess"
+ USING (
+ has_role('employee', "companyId") AND
+ "companyId" = ANY(
+ select "companyId" from "userToCompany" where "userId" = (SELECT auth.uid())::text
+ )
+ );
+
+
+ALTER POLICY "Authenticated users can view countries" ON "country" USING ((SELECT auth.role()) = 'authenticated');
+
+ALTER POLICY "Employees can view jobs" ON "job"
+ USING (
+ has_role('employee', "companyId")
+ AND "companyId" = ANY(
+ SELECT "companyId" from "userToCompany" where "userId" = (SELECT auth.uid())::text
+ )
+ );
+
+ALTER POLICY "Customers with production_view can view their own jobs" ON "job"
+ USING (
+ has_role('customer', "companyId") AND
+ has_company_permission('production_view', "companyId") AND
+ "customerId" IN (
+ SELECT "customerId" FROM "customerAccount" WHERE id::uuid = (SELECT auth.uid())
+ )
+ );
+
+ALTER POLICY "Customers with production_view can search for their own jobs" ON "search"
+ USING (
+ has_role('customer', "companyId") AND
+ has_company_permission('production_view', "companyId") AND
+ entity = 'Job' AND
+ uuid IN (
+ SELECT id FROM "job" WHERE "customerId" IN (
+ SELECT "customerId" FROM "customerAccount" WHERE id::uuid = (SELECT auth.uid())
+ )
+ )
+ );
+
+ALTER POLICY "Employees can view job materials" ON "jobMaterial"
+ USING (
+ has_role('employee', "companyId")
+ AND "companyId" = ANY(
+ SELECT "companyId" from "userToCompany" where "userId" = (SELECT auth.uid())::text
+ )
+ );
+
+DROP POLICY "Customers with production_view can view their own job materials" ON "jobMaterial";
+
+
+ALTER POLICY "Employees can view job operations" ON "jobOperation"
+ USING (
+ has_role('employee', "companyId")
+ AND "companyId" = ANY(
+ SELECT "companyId" from "userToCompany" where "userId" = (SELECT auth.uid())::text
+ )
+ );
+
+DROP POLICY "Customers with production_view can view their own job operations" ON "jobOperation";
+
+
+ALTER POLICY "Users can view their own job favorites" ON "jobFavorite"
+ USING (
+ (SELECT auth.uid())::text = "userId"
+ );
+
+ALTER POLICY "Users can create their own job favorites" ON "jobFavorite"
+ WITH CHECK (
+ (SELECT auth.uid())::text = "userId"
+ );
+
+ALTER POLICY "Users can delete their own job favorites" ON "jobFavorite"
+ USING (
+ (SELECT auth.uid())::text = "userId"
+ );
+
+
+
+ALTER POLICY "Authenticated users can view currency codes" ON "currencyCode"
+ USING ((SELECT auth.role()) = 'authenticated');
+
+ALTER POLICY "Employees can view production quantities" ON "productionQuantity"
+ USING (
+ has_role('employee', "companyId")
+ AND "companyId" = ANY(
+ SELECT "companyId" from "userToCompany" where "userId" = (SELECT auth.uid())::text
+ )
+ );
+
+ALTER POLICY "Employees can insert production quantities" ON "productionQuantity"
+ WITH CHECK (
+ has_role('employee', "companyId")
+ AND "companyId" = ANY(
+ SELECT "companyId" from "userToCompany" where "userId" = (SELECT auth.uid())::text
+ )
+);
+
+ALTER POLICY "Employees can delete production quantities" ON "productionQuantity"
+ USING (
+ has_role('employee', "companyId")
+ AND "companyId" = ANY(
+ SELECT "companyId" from "userToCompany" where "userId" = (SELECT auth.uid())::text
+ )
+ );
+
+ALTER POLICY "Employees can insert production events for their company's job operations" ON "productionEvent"
+ WITH CHECK (
+ has_role('employee', "companyId") AND
+ (SELECT auth.uid())::text = "employeeId" AND
+ "jobOperationId" IN (
+ SELECT "id" FROM "jobOperation" WHERE "companyId" = ANY(
+ SELECT "companyId" from "userToCompany" where "userId" = (SELECT auth.uid())::text
+ )
+ )
+ );
+
+ALTER POLICY "Employees can update production events for their company's job operations" ON "productionEvent"
+ USING (
+ (SELECT auth.uid())::text = "employeeId"
+ );
+
+ALTER POLICY "Employees can insert production quantities for their company's job operations" ON "productionQuantity"
+ WITH CHECK (
+ has_role('employee', "companyId") AND
+ "jobOperationId" IN (
+ SELECT "id" FROM "jobOperation" WHERE "companyId" = ANY(
+ SELECT "companyId" from "userToCompany" where "userId" = (SELECT auth.uid())::text
+ )
+ )
+ );
+
+
+
+ALTER POLICY "Anyone can read the feedback buckets" ON storage.objects
+ USING (
+ bucket_id = 'feedback'
+ AND ((SELECT auth.role()) = 'authenticated')
+);
+
+ALTER POLICY "Anyone with settings_create can insert into the feedback bucket" ON storage.objects
+ WITH CHECK (
+ bucket_id = 'feedback'
+ AND ((SELECT auth.role()) = 'authenticated')
+);
+
+ALTER POLICY "Employees can view scrap reasons" ON "scrapReason"
+ USING (
+ has_role('employee', "companyId") AND
+ "companyId" = ANY(
+ select "companyId" from "userToCompany" where "userId" = (SELECT auth.uid())::text
+ )
+ );
+
+ALTER POLICY "Users can view tags in their company" ON "tag"
+ USING (
+ (SELECT auth.uid())::text IN (
+ SELECT "userId" FROM "userToCompany" WHERE "companyId" = "tag"."companyId"
+ )
+ );
+
+ALTER POLICY "Users can insert tags in their company" ON "tag"
+ WITH CHECK (
+ (SELECT auth.uid())::text IN (
+ SELECT "userId" FROM "userToCompany" WHERE "companyId" = "tag"."companyId"
+ )
+ );
+
+ALTER POLICY "Authenticated users can view company settings" ON "companySettings"
+ USING (
+ (SELECT auth.role()) = 'authenticated' AND "id" IN (
+ SELECT "companyId" FROM "userToCompany" WHERE "userId" = (SELECT auth.uid())::text
+ )
+ );
+
+ALTER POLICY "Users can view their own supplier quote favorites" ON "supplierQuoteFavorite"
+ USING (
+ (SELECT auth.uid())::text = "userId"
+ );
+
+ALTER POLICY "Users can create their own supplier quote favorites" ON "supplierQuoteFavorite"
+ WITH CHECK (
+ (SELECT auth.uid())::text = "userId"
+ );
+
+ALTER POLICY "Users can delete their own supplier quote favorites" ON "supplierQuoteFavorite"
+ USING (
+ (SELECT auth.uid())::text = "userId"
+ );
+
+ALTER POLICY "Suppliers with purchasing_create can create lines on their own supplier quote" ON "supplierQuoteLine"
+ WITH CHECK (
+ has_company_permission('purchasing_create', "companyId")
+ AND has_role('supplier', "companyId")
+ AND "supplierQuoteId" IN (
+ SELECT id FROM "supplierQuote" WHERE "supplierId" IN (
+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = (SELECT auth.uid())
+ )
+ )
+ );
+
+ALTER POLICY "Suppliers with purchasing_view can view their own quote line pricing" ON "supplierQuoteLinePrice"
+ USING (
+ has_company_permission('purchasing_view', get_company_id_from_foreign_key("supplierQuoteId", 'supplierQuote'))
+ AND has_role('supplier', get_company_id_from_foreign_key("supplierQuoteId", 'supplierQuote'))
+ AND "supplierQuoteId" IN (
+ SELECT id FROM "supplierQuote" WHERE "supplierId" IN (
+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = (SELECT auth.uid())
+ )
+ )
+ );
+
+ALTER POLICY "Employees can view job operation tools" ON "jobOperationTool"
+ USING (
+ has_role('employee', "companyId")
+ AND "companyId" = ANY(
+ select "companyId" from "userToCompany" where "userId" = (SELECT auth.uid())::text
+ )
+);
+
+
+DROP VIEW "salesRfqs";
+CREATE OR REPLACE VIEW "salesRfqs" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ rfq.*,
+ l."name" AS "locationName",
+ opp."quoteId",
+ opp."salesOrderId"
+ FROM "salesRfq" rfq
+ LEFT JOIN "location" l
+ ON l.id = rfq."locationId"
+ LEFT JOIN "opportunity" opp
+ ON opp."salesRfqId" = rfq.id;
+
+DROP VIEW IF EXISTS "salesOrders";
+CREATE OR REPLACE VIEW "salesOrders" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ s.*,
+ sl."thumbnailPath",
+ sl."itemType",
+ sl."orderTotal",
+ sl."jobs",
+ st."name" AS "shippingTermName",
+ sp."paymentTermId",
+ ss."shippingMethodId",
+ ss."receiptRequestedDate",
+ ss."receiptPromisedDate",
+ ss."dropShipment",
+ ss."shippingCost",
+ l."name" AS "locationName"
+ FROM "salesOrder" s
+ LEFT JOIN (
+ SELECT
+ sol."salesOrderId",
+ MIN(CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END) AS "thumbnailPath",
+ SUM((1+COALESCE(sol."taxPercent", 0))*(COALESCE(sol."saleQuantity", 0)*(COALESCE(sol."unitPrice", 0)) + COALESCE(sol."shippingCost", 0) + COALESCE(sol."addOnCost", 0))) AS "orderTotal",
+ MIN(i."type") AS "itemType",
+ ARRAY_AGG(
+ CASE
+ WHEN j.id IS NOT NULL THEN json_build_object('id', j.id, 'jobId', j."jobId", 'status', j."status")
+ ELSE NULL
+ END
+ ) FILTER (WHERE j.id IS NOT NULL) AS "jobs"
+ FROM "salesOrderLine" sol
+ LEFT JOIN "item" i
+ ON i."id" = sol."itemId"
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+ LEFT JOIN "job" j ON j."salesOrderId" = sol."salesOrderId" AND j."salesOrderLineId" = sol."id"
+ GROUP BY sol."salesOrderId"
+ ) sl ON sl."salesOrderId" = s."id"
+ LEFT JOIN "salesOrderShipment" ss ON ss."id" = s."id"
+ LEFT JOIN "shippingTerm" st ON st."id" = ss."shippingTermId"
+ LEFT JOIN "salesOrderPayment" sp ON sp."id" = s."id"
+ LEFT JOIN "location" l ON l."id" = ss."locationId";
+
+DROP VIEW IF EXISTS "purchaseOrders";
+CREATE OR REPLACE VIEW "purchaseOrders" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ p.*,
+ sm."name" AS "shippingMethodName",
+ st."name" AS "shippingTermName",
+ pt."name" AS "paymentTermName",
+ pd."receiptRequestedDate",
+ pd."receiptPromisedDate",
+ pd."dropShipment",
+ l."id" AS "locationId",
+ l."name" AS "locationName"
+ FROM "purchaseOrder" p
+ LEFT JOIN "purchaseOrderDelivery" pd ON pd."id" = p."id"
+ LEFT JOIN "shippingMethod" sm ON sm."id" = pd."shippingMethodId"
+ LEFT JOIN "shippingTerm" st ON st."id" = pd."shippingTermId"
+ LEFT JOIN "purchaseOrderPayment" pp ON pp."id" = p."id"
+ LEFT JOIN "paymentTerm" pt ON pt."id" = pp."paymentTermId"
+ LEFT JOIN "location" l ON l."id" = pd."locationId";
+
+
+DROP VIEW IF EXISTS "quotes";
+CREATE OR REPLACE VIEW "quotes" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ q.*,
+ ql."thumbnailPath",
+ ql."itemType",
+ l."name" AS "locationName",
+ ql."lines",
+ ql."completedLines",
+ opp."salesRfqId",
+ opp."salesOrderId",
+ qs."shippingCost"
+ FROM "quote" q
+ LEFT JOIN (
+ SELECT
+ "quoteId",
+ COUNT("quoteLine"."id") FILTER (WHERE "quoteLine"."status" != 'No Quote') AS "lines",
+ COUNT("quoteLine"."id") FILTER (WHERE "quoteLine"."status" = 'Complete') AS "completedLines",
+ MIN(CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END) AS "thumbnailPath",
+ MIN(i."type") AS "itemType"
+ FROM "quoteLine"
+ INNER JOIN "item" i
+ ON i."id" = "quoteLine"."itemId"
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+ GROUP BY "quoteId"
+ ) ql ON ql."quoteId" = q.id
+ LEFT JOIN "quoteShipment" qs ON qs."id" = q."id"
+ LEFT JOIN "location" l
+ ON l.id = q."locationId"
+ LEFT JOIN "opportunity" opp
+ ON opp."quoteId" = q.id;
+
+DROP VIEW IF EXISTS "supplierQuotes";
+CREATE OR REPLACE VIEW "supplierQuotes"
+WITH
+ (SECURITY_INVOKER = true) AS
+SELECT
+ q.*,
+ ql."thumbnailPath",
+ ql."itemType"
+FROM
+ "supplierQuote" q
+ LEFT JOIN (
+ SELECT
+ "supplierQuoteId",
+ MIN(
+ CASE
+ WHEN i."thumbnailPath" IS NULL
+ AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END
+ ) AS "thumbnailPath",
+ MIN(i."type") AS "itemType"
+ FROM
+ "supplierQuoteLine"
+ INNER JOIN "item" i ON i."id" = "supplierQuoteLine"."itemId"
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+ GROUP BY
+ "supplierQuoteId"
+ ) ql ON ql."supplierQuoteId" = q.id;
\ No newline at end of file