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: update rls for customer accounts

Brad Barbin1b33deb883c4
diff --git a/apps/erp/app/components/Assignee.tsx b/apps/erp/app/components/Assignee.tsx
index 62dae169b4..033fe2432b 100644
--- a/apps/erp/app/components/Assignee.tsx
+++ b/apps/erp/app/components/Assignee.tsx
@@ -18,7 +18,7 @@ import type { ComponentPropsWithoutRef } from "react";
import { forwardRef, useMemo, useState } from "react";
import { LuSettings2, LuUser } from "react-icons/lu";
import { RxCheck } from "react-icons/rx";
-import { useUser } from "~/hooks";
+import { usePermissions, useUser } from "~/hooks";
import { usePeople } from "~/stores";
import { path } from "~/utils/path";
import EmployeeAvatar from "./EmployeeAvatar";
@@ -59,6 +59,7 @@ const Assign = forwardRef<HTMLButtonElement, AssigneeProps>(
const [people] = usePeople();
const fetcher = useFetcher<{}>();
const user = useUser();
+ const permissions = usePermissions();
const handleChange = (value: string) => {
const formData = new FormData();
@@ -112,7 +113,7 @@ const Assign = forwardRef<HTMLButtonElement, AssigneeProps>(
buttonVariants({
variant: "secondary",
size: size,
- isDisabled: isReadOnly,
+ isDisabled: isReadOnly || !permissions.is("employee"),
isLoading: fetcher.state !== "idle",
isIcon: false,
className,
@@ -146,6 +147,7 @@ const Assign = forwardRef<HTMLButtonElement, AssigneeProps>(
icon={<LuSettings2 />}
size="sm"
variant="secondary"
+ isDisabled={!permissions.is("employee")}
/>
)}
</PopoverTrigger>
diff --git a/apps/erp/app/modules/invoicing/invoicing.service.ts b/apps/erp/app/modules/invoicing/invoicing.service.ts
index 9f162d4e1d..b56ebd6357 100644
--- a/apps/erp/app/modules/invoicing/invoicing.service.ts
+++ b/apps/erp/app/modules/invoicing/invoicing.service.ts
@@ -371,7 +371,11 @@ export async function upsertPurchaseInvoice(
const [supplierInteraction, supplierPayment, supplierShipping, purchaser] =
await Promise.all([
- insertSupplierInteraction(client, purchaseInvoice.companyId),
+ insertSupplierInteraction(
+ client,
+ purchaseInvoice.companyId,
+ purchaseInvoice.supplierId
+ ),
getSupplierPayment(client, purchaseInvoice.supplierId),
getSupplierShipping(client, purchaseInvoice.supplierId),
getEmployeeJob(
@@ -532,7 +536,12 @@ export async function upsertSalesInvoice(
await Promise.all([
client
.from("opportunity")
- .insert([{ companyId: salesInvoice.companyId }])
+ .insert([
+ {
+ companyId: salesInvoice.companyId,
+ customerId: salesInvoice.customerId,
+ },
+ ])
.select("id")
.single(),
getCustomerPayment(client, salesInvoice.customerId),
diff --git a/apps/erp/app/modules/purchasing/purchasing.service.ts b/apps/erp/app/modules/purchasing/purchasing.service.ts
index febebea708..513ea15dbf 100644
--- a/apps/erp/app/modules/purchasing/purchasing.service.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.service.ts
@@ -1,12 +1,16 @@
import type { Database, Json } from "@carbon/database";
import { getLocalTimeZone, today } from "@internationalized/date";
-import type { SupabaseClient } from "@supabase/supabase-js";
+import type {
+ PostgrestSingleResponse,
+ SupabaseClient,
+} from "@supabase/supabase-js";
import type { z } from "zod";
import { getEmployeeJob } from "~/modules/people";
import type { GenericQueryFilters } from "~/utils/query";
import { setGenericQueryFilters } from "~/utils/query";
import { sanitize } from "~/utils/supabase";
import { getCurrencyByCode } from "../accounting/accounting.service";
+import type { PurchaseInvoice } from "../invoicing/types";
import type {
purchaseOrderDeliveryValidator,
purchaseOrderLineValidator,
@@ -26,6 +30,7 @@ import type {
supplierTypeValidator,
supplierValidator,
} from "./purchasing.models";
+import type { PurchaseOrder, SupplierQuote } from "./types";
export async function closePurchaseOrder(
client: SupabaseClient<Database>,
@@ -393,9 +398,41 @@ export async function getSupplierContacts(
export async function getSupplierInteraction(
client: SupabaseClient<Database>,
- id: string
-) {
- return client.from("supplierInteraction").select("*").eq("id", id).single();
+ opportunityId: string | null
+): Promise<
+ PostgrestSingleResponse<{
+ id: string;
+ companyId: string;
+ supplierQuotes: SupplierQuote[];
+ purchaseOrders: PurchaseOrder[];
+ purchaseInvoices: PurchaseInvoice[];
+ } | null>
+> {
+ if (!opportunityId) {
+ // @ts-expect-error
+ return {
+ data: null,
+ error: null,
+ };
+ }
+
+ const response = await client.rpc(
+ "get_supplier_interaction_with_related_records",
+ {
+ supplier_interaction_id: opportunityId,
+ }
+ );
+
+ return {
+ data: response.data?.[0],
+ error: response.error,
+ } as unknown as PostgrestSingleResponse<{
+ id: string;
+ companyId: string;
+ supplierQuotes: SupplierQuote[];
+ purchaseOrders: PurchaseOrder[];
+ purchaseInvoices: PurchaseInvoice[];
+ }>;
}
export async function getSupplierInteractionDocuments(
@@ -797,11 +834,12 @@ export async function insertSupplierContact(
export async function insertSupplierInteraction(
client: SupabaseClient<Database>,
- companyId: string
+ companyId: string,
+ supplierId: string
) {
return client
.from("supplierInteraction")
- .insert([{ companyId }])
+ .insert([{ companyId, supplierId }])
.select("id")
.single();
}
@@ -1122,7 +1160,11 @@ export async function upsertPurchaseOrder(
const [supplierInteraction, supplierPayment, supplierShipping, purchaser] =
await Promise.all([
- insertSupplierInteraction(client, purchaseOrder.companyId),
+ insertSupplierInteraction(
+ client,
+ purchaseOrder.companyId,
+ purchaseOrder.supplierId
+ ),
getSupplierPayment(client, purchaseOrder.supplierId),
getSupplierShipping(client, purchaseOrder.supplierId),
getEmployeeJob(client, purchaseOrder.createdBy, purchaseOrder.companyId),
@@ -1391,7 +1433,8 @@ export async function upsertSupplierQuote(
const supplierInteraction = await insertSupplierInteraction(
client,
- supplierQuote.companyId
+ supplierQuote.companyId,
+ supplierQuote.supplierId
);
if (supplierInteraction.error) return supplierInteraction;
diff --git a/apps/erp/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionLineNotes.tsx b/apps/erp/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionLineNotes.tsx
index a4c880c0ff..bd2bd1d733 100644
--- a/apps/erp/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionLineNotes.tsx
+++ b/apps/erp/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionLineNotes.tsx
@@ -43,7 +43,8 @@ const SupplierInteractionLineNotes = ({
} = useUser();
const { carbon } = useCarbon();
const permissions = usePermissions();
- const [tab, setTab] = useState("internal");
+ const isEmployee = permissions.is("employee");
+ const [tab, setTab] = useState(isEmployee ? "internal" : "external");
const [internalNotes, setInternalNotes] = useState(
initialInternalNotes ?? {}
);
@@ -114,12 +115,13 @@ const SupplierInteractionLineNotes = ({
</CardDescription>
</CardHeader>
<CardAction>
- {["supplierQuoteLine", "purchaseOrderLine"].includes(table) && (
- <TabsList>
- <TabsTrigger value="internal">Internal</TabsTrigger>
- <TabsTrigger value="external">External</TabsTrigger>
- </TabsList>
- )}
+ {["supplierQuoteLine", "purchaseOrderLine"].includes(table) &&
+ isEmployee && (
+ <TabsList>
+ <TabsTrigger value="internal">Internal</TabsTrigger>
+ <TabsTrigger value="external">External</TabsTrigger>
+ </TabsList>
+ )}
</CardAction>
</HStack>
<CardContent>
diff --git a/apps/erp/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionNotes.tsx b/apps/erp/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionNotes.tsx
index 502994d310..b18736a047 100644
--- a/apps/erp/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionNotes.tsx
+++ b/apps/erp/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionNotes.tsx
@@ -41,7 +41,8 @@ const SupplierInteractionNotes = ({
} = useUser();
const { carbon } = useCarbon();
const permissions = usePermissions();
- const [tab, setTab] = useState("internal");
+ const isEmployee = permissions.is("employee");
+ const [tab, setTab] = useState(isEmployee ? "internal" : "external");
const [internalNotes, setInternalNotes] = useState(
initialInternalNotes ?? {}
);
@@ -111,7 +112,7 @@ const SupplierInteractionNotes = ({
</CardDescription>
</CardHeader>
<CardAction>
- {["purchaseOrder"].includes(table) && (
+ {["purchaseOrder"].includes(table) && isEmployee && (
<TabsList>
<TabsTrigger value="internal">Internal</TabsTrigger>
<TabsTrigger value="external">External</TabsTrigger>
diff --git a/apps/erp/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionState.tsx b/apps/erp/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionState.tsx
new file mode 100644
index 0000000000..43954660c7
--- /dev/null
+++ b/apps/erp/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionState.tsx
@@ -0,0 +1,250 @@
+import { Button, cn, Menubar, SplitButton } from "@carbon/react";
+import { useOptimisticLocation } from "@carbon/remix";
+import { Link, useNavigate } from "@remix-run/react";
+import { LuCircle, LuCreditCard } from "react-icons/lu";
+import {
+ RiProgress2Line,
+ RiProgress4Line,
+ RiProgress8Line,
+} from "react-icons/ri";
+import { path } from "~/utils/path";
+import type { SupplierInteraction } from "../../types";
+
+function getSupplierInteractionStarted(
+ interaction: SupplierInteraction,
+ state: string
+) {
+ switch (state) {
+ // case "RFQ":
+ // return interaction.purchaseRfqs.length > 0;
+ case "Quote":
+ return interaction.supplierQuotes.length > 0;
+ case "Order":
+ return interaction.purchaseOrders.length > 0;
+ // case "Invoice":
+ // return interaction.purchaseInvoices.length > 0;
+ }
+}
+
+function getSupplierInteractionCompleted(
+ interaction: SupplierInteraction,
+ state: string
+) {
+ switch (state) {
+ // case "RFQ":
+ // return (
+ // interaction.purchaseRfqs?.[0]?.completedDate &&
+ // interaction.purchaseRfqs?.[0]?.completedDate !== null
+ // );
+ case "Quote":
+ return interaction.supplierQuotes.length > 0;
+ case "Order":
+ return interaction.purchaseOrders?.[0]?.status === "Completed";
+ // case "Invoice":
+ // return (
+ // interaction.purchaseInvoices?.[0]?.completedDate &&
+ // interaction.purchaseInvoices?.[0]?.completedDate !== null
+ // );
+ }
+}
+
+function getSupplierInteractionIcon(state: string) {
+ switch (state) {
+ case "RFQ":
+ return RiProgress2Line;
+ case "Quote":
+ return RiProgress4Line;
+ case "Order":
+ return RiProgress8Line;
+ case "Invoice":
+ return LuCreditCard;
+ default:
+ return LuCircle;
+ }
+}
+
+function getPath(interaction: SupplierInteraction, state: string) {
+ switch (state) {
+ // case "RFQ":
+ // return path.to.purchaseRfqDetails(interaction.purchaseRfqs?.[0]?.id!);
+ case "Quote":
+ return path.to.supplierQuoteDetails(interaction.supplierQuotes?.[0]?.id!);
+ case "Order":
+ return path.to.purchaseOrderDetails(interaction.purchaseOrders?.[0]?.id!);
+ case "Invoice":
+ return path.to.purchaseInvoiceDetails(
+ interaction.purchaseInvoices?.[0]?.id!
+ );
+ }
+}
+
+function getIsCurrent(
+ interaction: SupplierInteraction,
+ pathname: string,
+ state: string
+) {
+ switch (state) {
+ // case "RFQ":
+ // return interaction.purchaseRfqs.some((rfq) =>
+ // pathname.includes(path.to.purchaseRfqDetails(rfq.id!))
+ // );
+ case "Quote":
+ return interaction.supplierQuotes.some((quote) =>
+ pathname.includes(path.to.supplierQuoteDetails(quote.id!))
+ );
+ case "Order":
+ return interaction.purchaseOrders.some((order) =>
+ pathname.includes(path.to.purchaseOrderDetails(order.id!))
+ );
+ case "Invoice":
+ return interaction.purchaseInvoices.some((invoice) =>
+ pathname.includes(path.to.purchaseInvoiceDetails(invoice.id!))
+ );
+ default:
+ return false;
+ }
+}
+
+function getItems(interaction: SupplierInteraction, state: string) {
+ switch (state) {
+ // case "RFQ":
+ // return interaction.purchaseRfqs.map((rfq) => ({
+ // id: rfq.id!,
+ // label: rfq.rfqId
+ // ? `${rfq.rfqId}${
+ // rfq.revisionId && rfq.revisionId > 0 ? `-${rfq.revisionId}` : ""
+ // }`
+ // : `RFQ ${rfq.id}`,
+ // path: path.to.purchaseRfqDetails(rfq.id!),
+ // }));
+ case "Quote":
+ return interaction.supplierQuotes.map((quote) => ({
+ id: quote.id!,
+ label: quote.supplierQuoteId
+ ? `${quote.supplierQuoteId}${
+ quote.revisionId && quote.revisionId > 0
+ ? `-${quote.revisionId}`
+ : ""
+ }`
+ : `Quote ${quote.id}`,
+ path: path.to.supplierQuoteDetails(quote.id!),
+ }));
+ case "Order":
+ return interaction.purchaseOrders.map((order) => ({
+ id: order.id!,
+ label: order.purchaseOrderId
+ ? `${order.purchaseOrderId}${
+ order.revisionId && order.revisionId > 0
+ ? `-${order.revisionId}`
+ : ""
+ }`
+ : `Order ${order.id}`,
+ path: path.to.purchaseOrderDetails(order.id!),
+ }));
+ case "Invoice":
+ return interaction.purchaseInvoices.map((invoice) => ({
+ id: invoice.id!,
+ label: invoice.invoiceId
+ ? `${invoice.invoiceId}`
+ : `Invoice ${invoice.id}`,
+ path: path.to.purchaseInvoiceDetails(invoice.id!),
+ }));
+ default:
+ return [];
+ }
+}
+
+const states = ["RFQ", "Quote", "Order", "Invoice"];
+
+const SupplierInteractionState = ({
+ interaction,
+}: {
+ interaction: SupplierInteraction;
+}) => {
+ const { pathname } = useOptimisticLocation();
+ const navigate = useNavigate();
+
+ return (
+ <Menubar>
+ {states
+ .filter((state) => ["Quote", "Order"].includes(state))
+ .map((state, index) => {
+ const isStarted = getSupplierInteractionStarted(interaction, state);
+ const isCompleted = getSupplierInteractionCompleted(
+ interaction,
+ state
+ );
+ const isCurrent = getIsCurrent(interaction, pathname, state);
+ const Icon = getSupplierInteractionIcon(state);
+ const to = getPath(interaction, state);
+ const items = getItems(interaction, state);
+ const hasMultipleItems = items.length > 1;
+
+ if (isStarted && to) {
+ if (hasMultipleItems) {
+ const Icon = getSupplierInteractionIcon(state);
+ return (
+ <SplitButton
+ key={state}
+ leftIcon={
+ <Icon
+ className={cn(
+ isCurrent && "text-emerald-500",
+ !isCurrent && "opacity-80 hover:opacity-100"
+ )}
+ />
+ }
+ variant="ghost"
+ onClick={() => navigate(to)}
+ dropdownItems={items.map((item) => ({
+ label: item.label,
+ onClick: () => navigate(item.path),
+ }))}
+ >
+ {state}
+ </SplitButton>
+ );
+ } else {
+ return (
+ <Button
+ key={state}
+ leftIcon={
+ <Icon
+ className={cn(
+ isCurrent && "text-emerald-500",
+ !isCurrent && "opacity-80 hover:opacity-100"
+ )}
+ />
+ }
+ variant="ghost"
+ asChild
+ >
+ <Link to={to}>{state}</Link>
+ </Button>
+ );
+ }
+ } else {
+ return (
+ <Button
+ key={state}
+ variant="ghost"
+ isDisabled
+ leftIcon={
+ <Icon
+ className={cn(
+ isCompleted && "text-emerald-500",
+ !isCurrent && "opacity-80 hover:opacity-100"
+ )}
+ />
+ }
+ >
+ {state}
+ </Button>
+ );
+ }
+ })}
+ </Menubar>
+ );
+};
+
+export default SupplierInteractionState;
diff --git a/apps/erp/app/modules/sales/sales.service.ts b/apps/erp/app/modules/sales/sales.service.ts
index 18c519bf2b..02395d02eb 100644
--- a/apps/erp/app/modules/sales/sales.service.ts
+++ b/apps/erp/app/modules/sales/sales.service.ts
@@ -626,6 +626,7 @@ export async function getNoQuoteReasons(
return query;
}
+
export async function getOpportunity(
client: SupabaseClient<Database>,
opportunityId: string | null
@@ -1954,7 +1955,9 @@ export async function upsertQuote(
getEmployeeJob(client, quote.createdBy, quote.companyId),
client
.from("opportunity")
- .insert([{ companyId: quote.companyId }])
+ .insert([
+ { companyId: quote.companyId, customerId: quote.customerId },
+ ])
.select("id")
.single(),
]);
@@ -2573,7 +2576,12 @@ export async function upsertSalesOrder(
getEmployeeJob(client, salesOrder.createdBy, salesOrder.companyId),
client
.from("opportunity")
- .insert([{ companyId: salesOrder.companyId }])
+ .insert([
+ {
+ companyId: salesOrder.companyId,
+ customerId: salesOrder.customerId,
+ },
+ ])
.select("id")
.single(),
]);
@@ -2763,7 +2771,7 @@ export async function upsertSalesRFQ(
if ("createdBy" in rfq) {
const opportunity = await client
.from("opportunity")
- .insert([{ companyId: rfq.companyId }])
+ .insert([{ companyId: rfq.companyId, customerId: rfq.customerId }])
.select("id")
.single();
diff --git a/apps/erp/app/modules/sales/ui/Opportunity/OpportunityLineNotes.tsx b/apps/erp/app/modules/sales/ui/Opportunity/OpportunityLineNotes.tsx
index 5cb6b6414d..d061a0b211 100644
--- a/apps/erp/app/modules/sales/ui/Opportunity/OpportunityLineNotes.tsx
+++ b/apps/erp/app/modules/sales/ui/Opportunity/OpportunityLineNotes.tsx
@@ -43,7 +43,8 @@ const OpportunityLineNotes = ({
} = useUser();
const { carbon } = useCarbon();
const permissions = usePermissions();
- const [tab, setTab] = useState("internal");
+ const isEmployee = permissions.is("employee");
+ const [tab, setTab] = useState(isEmployee ? "internal" : "external");
const [internalNotes, setInternalNotes] = useState(
initialInternalNotes ?? {}
);
@@ -114,10 +115,12 @@ const OpportunityLineNotes = ({
</CardDescription>
</CardHeader>
<CardAction>
- <TabsList>
- <TabsTrigger value="internal">Internal</TabsTrigger>
- <TabsTrigger value="external">External</TabsTrigger>
- </TabsList>
+ {isEmployee && (
+ <TabsList>
+ <TabsTrigger value="internal">Internal</TabsTrigger>
+ <TabsTrigger value="external">External</TabsTrigger>
+ </TabsList>
+ )}
</CardAction>
</HStack>
<CardContent>
diff --git a/apps/erp/app/modules/sales/ui/Opportunity/OpportunityNotes.tsx b/apps/erp/app/modules/sales/ui/Opportunity/OpportunityNotes.tsx
index a5186afa0e..24d17fee77 100644
--- a/apps/erp/app/modules/sales/ui/Opportunity/OpportunityNotes.tsx
+++ b/apps/erp/app/modules/sales/ui/Opportunity/OpportunityNotes.tsx
@@ -41,7 +41,8 @@ const OpportunityNotes = ({
} = useUser();
const { carbon } = useCarbon();
const permissions = usePermissions();
- const [tab, setTab] = useState("internal");
+ const isEmployee = permissions.is("employee");
+ const [tab, setTab] = useState(isEmployee ? "internal" : "external");
const [internalNotes, setInternalNotes] = useState(
initialInternalNotes ?? {}
);
@@ -111,10 +112,12 @@ const OpportunityNotes = ({
</CardDescription>
</CardHeader>
<CardAction>
- <TabsList>
- <TabsTrigger value="internal">Internal</TabsTrigger>
- <TabsTrigger value="external">External</TabsTrigger>
- </TabsList>
+ {isEmployee && (
+ <TabsList>
+ <TabsTrigger value="internal">Internal</TabsTrigger>
+ <TabsTrigger value="external">External</TabsTrigger>
+ </TabsList>
+ )}
</CardAction>
</HStack>
<CardContent>
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteLinePricing.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteLinePricing.tsx
index 72a563a6e2..27e9f60ac5 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteLinePricing.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteLinePricing.tsx
@@ -84,8 +84,10 @@ const QuoteLinePricing = ({
const routeData = useRouteData<{
quote: Quotation;
}>(path.to.quote(quoteId));
+ const isEmployee = permissions.is("employee");
const isEditable =
permissions.can("update", "sales") &&
+ isEmployee &&
["Draft"].includes(routeData?.quote?.status ?? "");
const fetcher = useFetcher<{ id?: string; error: string | null }>();
@@ -292,7 +294,7 @@ const QuoteLinePricing = ({
<CardHeader>
<CardTitle>Pricing</CardTitle>
</CardHeader>
- {permissions.can("update", "sales") && (
+ {isEditable && (
<CardAction>
<HStack>
<DropdownMenu>
@@ -443,97 +445,103 @@ const QuoteLinePricing = ({
);
})}
</Tr>
- <Tr className={cn(isMade && "[&>td]:bg-muted/60")}>
- <Td className="border-r border-border group-hover:bg-muted/50">
- <HStack className="w-full justify-between ">
- <span>Unit Cost</span>
- </HStack>
- </Td>
-
- {unitCostsByQuantity.map((cost, index) => {
- return isMade ? (
- <Td key={index} className="group-hover:bg-muted/50">
- <VStack spacing={0}>
- <span>
- {unitPriceFormatter.format(unitCostsByQuantity[index])}
- </span>
- </VStack>
- </Td>
- ) : (
- <Td key={index} className="group-hover:bg-muted/50">
- <NumberField
- value={optimisticUnitCost}
- formatOptions={{
- style: "currency",
- currency: baseCurrency,
- }}
- minValue={0}
- onChange={(value) => {
- if (Number.isFinite(value) && value !== cost) {
- onUpdateCost(value);
- }
- }}
- >
- <NumberInput
- className="border-0 -ml-3 shadow-none disabled:bg-transparent disabled:opacity-100"
- isDisabled={!isEditable}
- size="sm"
- min={0}
- />
- </NumberField>
- </Td>
- );
- })}
- </Tr>
- <Tr>
- <Td className="border-r border-border">
- <HStack className="w-full justify-between ">
- <span className="flex items-center justify-start gap-2">
- Markup Percent
- <Tooltip>
- <TooltipTrigger tabIndex={-1}>
- <LuInfo className="w-4 h-4" />
- </TooltipTrigger>
- <TooltipContent>(Price - Cost) / Cost</TooltipContent>
- </Tooltip>
- </span>
- </HStack>
- </Td>
- {quantities.map((quantity, index) => {
- const price = prices[quantity]?.unitPrice ?? 0;
- const cost = unitCostsByQuantity[index];
-
- const markup = price ? (price - cost) / cost : 0;
-
- return (
- <Td key={quantity.toString()}>
- <NumberField
- value={markup}
- formatOptions={{
- style: "percent",
- maximumFractionDigits: 2,
- }}
- onChange={(value) => {
- if (Number.isFinite(value) && value !== price) {
- onUpdatePrice(
- "unitPrice",
- quantity,
- cost * (1 + value)
- );
- }
- }}
- >
- <NumberInput
- className="border-0 -ml-3 shadow-none disabled:bg-transparent disabled:opacity-100"
- isDisabled={!isEditable}
- size="sm"
- min={0}
- />
- </NumberField>
- </Td>
- );
- })}
- </Tr>
+ {isEmployee && (
+ <Tr className={cn(isMade && "[&>td]:bg-muted/60")}>
+ <Td className="border-r border-border group-hover:bg-muted/50">
+ <HStack className="w-full justify-between ">
+ <span>Unit Cost</span>
+ </HStack>
+ </Td>
+
+ {unitCostsByQuantity.map((cost, index) => {
+ return isMade ? (
+ <Td key={index} className="group-hover:bg-muted/50">
+ <VStack spacing={0}>
+ <span>
+ {unitPriceFormatter.format(
+ unitCostsByQuantity[index]
+ )}
+ </span>
+ </VStack>
+ </Td>
+ ) : (
+ <Td key={index} className="group-hover:bg-muted/50">
+ <NumberField
+ value={optimisticUnitCost}
+ formatOptions={{
+ style: "currency",
+ currency: baseCurrency,
+ }}
+ minValue={0}
+ onChange={(value) => {
+ if (Number.isFinite(value) && value !== cost) {
+ onUpdateCost(value);
+ }
+ }}
+ >
+ <NumberInput
+ className="border-0 -ml-3 shadow-none disabled:bg-transparent disabled:opacity-100"
+ isDisabled={!isEditable}
+ size="sm"
+ min={0}
+ />
+ </NumberField>
+ </Td>
+ );
+ })}
+ </Tr>
+ )}
+ {isEmployee && (
+ <Tr>
+ <Td className="border-r border-border">
+ <HStack className="w-full justify-between ">
+ <span className="flex items-center justify-start gap-2">
+ Markup Percent
+ <Tooltip>
+ <TooltipTrigger tabIndex={-1}>
+ <LuInfo className="w-4 h-4" />
+ </TooltipTrigger>
+ <TooltipContent>(Price - Cost) / Cost</TooltipContent>
+ </Tooltip>
+ </span>
+ </HStack>
+ </Td>
+ {quantities.map((quantity, index) => {
+ const price = prices[quantity]?.unitPrice ?? 0;
+ const cost = unitCostsByQuantity[index];
+
+ const markup = price ? (price - cost) / cost : 0;
+
+ return (
+ <Td key={quantity.toString()}>
+ <NumberField
+ value={markup}
+ formatOptions={{
+ style: "percent",
+ maximumFractionDigits: 2,
+ }}
+ onChange={(value) => {
+ if (Number.isFinite(value) && value !== price) {
+ onUpdatePrice(
+ "unitPrice",
+ quantity,
+ cost * (1 + value)
+ );
+ }
+ }}
+ >
+ <NumberInput
+ className="border-0 -ml-3 shadow-none disabled:bg-transparent disabled:opacity-100"
+ isDisabled={!isEditable}
+ size="sm"
+ min={0}
+ />
+ </NumberField>
+ </Td>
+ );
+ })}
+ </Tr>
+ )}
<Tr>
<Td className="border-r border-border">
<HStack className="w-full justify-between ">
@@ -622,64 +630,71 @@ const QuoteLinePricing = ({
})}
</Tr>
- <Tr className="[&>td]:bg-muted/60">
- <Td className="border-r border-border group-hover:bg-muted/50">
- <HStack className="w-full justify-between ">
- <span className="flex items-center justify-start gap-2">
- Profit Percent
- <Tooltip>
- <TooltipTrigger tabIndex={-1}>
- <LuInfo className="w-4 h-4" />
- </TooltipTrigger>
- <TooltipContent>(Price - Cost) / Price</TooltipContent>
- </Tooltip>
- </span>
- </HStack>
- </Td>
- {netPricesByQuantity.map((price, index) => {
- const cost = unitCostsByQuantity[index];
- const profit = ((price - cost) / price) * 100;
- return (
- <Td key={index} className="group-hover:bg-muted/50">
- <VStack spacing={0}>
- {Number.isFinite(profit) ? (
- <span className={cn(profit < -0.01 && "text-red-500")}>
- {profit.toFixed(2)}%
- </span>
- ) : (
- <span>-</span>
- )}
- </VStack>
- </Td>
- );
- })}
- </Tr>
-
- <Tr className="[&>td]:bg-muted/60">
- <Td className="border-r border-border group-hover:bg-muted/50">
- <HStack className="w-full justify-between ">
- <span>Total Profit</span>
- </HStack>
- </Td>
- {quantities.map((quantity, index) => {
- const price = netPricesByQuantity[index];
- const cost = unitCostsByQuantity[index];
- const profit = (price - cost) * quantity;
- return (
- <Td key={index} className="group-hover:bg-muted/50">
- <VStack spacing={0}>
- {price ? (
- <span className={cn(profit < -0.01 && "text-red-500")}>
- {formatter.format(profit)}
- </span>
- ) : (
- <span>-</span>
- )}
- </VStack>
- </Td>
- );
- })}
- </Tr>
+ {isEmployee && (
+ <Tr className="[&>td]:bg-muted/60">
+ <Td className="border-r border-border group-hover:bg-muted/50">
+ <HStack className="w-full justify-between ">
+ <span className="flex items-center justify-start gap-2">
+ Profit Percent
+ <Tooltip>
+ <TooltipTrigger tabIndex={-1}>
+ <LuInfo className="w-4 h-4" />
+ </TooltipTrigger>
+ <TooltipContent>(Price - Cost) / Price</TooltipContent>
+ </Tooltip>
+ </span>
+ </HStack>
+ </Td>
+ {netPricesByQuantity.map((price, index) => {
+ const cost = unitCostsByQuantity[index];
+ const profit = ((price - cost) / price) * 100;
+ return (
+ <Td key={index} className="group-hover:bg-muted/50">
+ <VStack spacing={0}>
+ {Number.isFinite(profit) ? (
+ <span
+ className={cn(profit < -0.01 && "text-red-500")}
+ >
+ {profit.toFixed(2)}%
+ </span>
+ ) : (
+ <span>-</span>
+ )}
+ </VStack>
+ </Td>
+ );
+ })}
+ </Tr>
+ )}
+ {isEmployee && (
+ <Tr className="[&>td]:bg-muted/60">
+ <Td className="border-r border-border group-hover:bg-muted/50">
+ <HStack className="w-full justify-between ">
+ <span>Total Profit</span>
+ </HStack>
+ </Td>
+ {quantities.map((quantity, index) => {
+ const price = netPricesByQuantity[index];
+ const cost = unitCostsByQuantity[index];
+ const profit = (price - cost) * quantity;
+ return (
+ <Td key={index} className="group-hover:bg-muted/50">
+ <VStack spacing={0}>
+ {price ? (
+ <span
+ className={cn(profit < -0.01 && "text-red-500")}
+ >
+ {formatter.format(profit)}
+ </span>
+ ) : (
+ <span>-</span>
+ )}
+ </VStack>
+ </Td>
+ );
+ })}
+ </Tr>
+ )}
<Tr>
<Td className="border-r border-border">
<HStack className="w-full justify-between ">
diff --git a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderHeader.tsx b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderHeader.tsx
index e6c81fcd79..6660b83426 100644
--- a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderHeader.tsx
+++ b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderHeader.tsx
@@ -255,6 +255,7 @@ const SalesOrderHeader = () => {
routeData?.salesOrder?.status ?? ""
) ||
!permissions.can("create", "production") ||
+ !permissions.is("employee") ||
!!routeData?.salesOrder?.jobs
}
onClick={salesOrderToJobsModal.onOpen}
diff --git a/apps/erp/app/routes/_public+/invite.$code.tsx b/apps/erp/app/routes/_public+/invite.$code.tsx
index 22e594d4cf..afb608d1dd 100644
--- a/apps/erp/app/routes/_public+/invite.$code.tsx
+++ b/apps/erp/app/routes/_public+/invite.$code.tsx
@@ -108,10 +108,7 @@ export default function Invite() {
return (
<AnimatePresence>
- <VStack
- spacing={4}
- className="max-w-lg pt-[16dvh] items-center text-center"
- >
+ <VStack spacing={4} className="max-w-lg items-center text-center">
<motion.img
initial={{ opacity: 0, scale: 0.4 }}
animate={{ opacity: 1, scale: 1 }}
diff --git a/apps/erp/app/routes/x+/job+/update.tsx b/apps/erp/app/routes/x+/job+/update.tsx
index 7fdc54ee4f..82326ea34d 100644
--- a/apps/erp/app/routes/x+/job+/update.tsx
+++ b/apps/erp/app/routes/x+/job+/update.tsx
@@ -28,11 +28,6 @@ export async function action({ request }: ActionFunctionArgs) {
const serviceRole = await getCarbonServiceRole();
- console.log({
- field,
- ids,
- });
-
if (field === "delete") {
return json(
await client
diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.details.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.details.tsx
index 09c4489cdd..f8ad77ff0a 100644
--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.details.tsx
+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.details.tsx
@@ -14,6 +14,7 @@ import type {
PurchaseOrder,
PurchaseOrderDelivery,
PurchaseOrderLine,
+ SupplierInteraction,
} from "~/modules/purchasing";
import {
getPurchaseOrder,
@@ -31,6 +32,7 @@ import {
SupplierInteractionDocuments,
SupplierInteractionNotes,
} from "~/modules/purchasing/ui/SupplierInteraction";
+import SupplierInteractionState from "~/modules/purchasing/ui/SupplierInteraction/SupplierInteractionState";
import { getCustomFields, setCustomFields } from "~/utils/form";
import { path } from "~/utils/path";
@@ -120,6 +122,7 @@ export default function PurchaseOrderBasicRoute() {
purchaseOrderDelivery: PurchaseOrderDelivery;
lines: PurchaseOrderLine[];
files: Promise<FileObject[]>;
+ interaction: SupplierInteraction;
}>(path.to.purchaseOrder(orderId));
if (!orderData) throw new Error("Could not find order data");
@@ -181,6 +184,7 @@ export default function PurchaseOrderBasicRoute() {
return (
<>
+ <SupplierInteractionState interaction={orderData.interaction} />
<PurchaseOrderSummary onEditShippingCost={handleEditShippingCost} />
<SupplierInteractionNotes
key={`notes-${initialValues.id}`}
diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx
index b3e8d4dcd1..b756a0ce07 100644
--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx
+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx
@@ -11,8 +11,8 @@ import {
getPurchaseOrderDelivery,
getPurchaseOrderLines,
getSupplier,
+ getSupplierInteraction,
getSupplierInteractionDocuments,
- getSupplierQuoteByInteractionId,
} from "~/modules/purchasing";
import {
PurchaseOrderExplorer,
@@ -68,16 +68,11 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
throw redirect(path.to.purchaseOrders);
}
- const [supplier, supplierQuote] = await Promise.all([
+ const [supplier, interaction] = await Promise.all([
purchaseOrder.data?.supplierId
? getSupplier(client, purchaseOrder.data.supplierId)
: null,
- purchaseOrder.data?.supplierInteractionId
- ? getSupplierQuoteByInteractionId(
- client,
- purchaseOrder.data.supplierInteractionId
- )
- : null,
+ getSupplierInteraction(client, purchaseOrder.data.supplierInteractionId),
]);
return defer({
@@ -89,7 +84,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
companyId,
purchaseOrder.data.supplierInteractionId!
),
- supplierQuote: supplierQuote?.data,
+ interaction: interaction?.data,
supplier: supplier?.data ?? null,
});
}
diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsx
index f2aa4cdc59..908fbcc843 100644
--- a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsx
+++ b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsx
@@ -175,13 +175,15 @@ export default function QuoteLine() {
<Fragment key={lineId}>
<QuoteLineForm key={lineId} initialValues={initialValues} />
- {line.methodType === "Make" && line.status !== "No Quote" && (
- <QuoteLineCosting
- quantities={line.quantity ?? [1]}
- getLineCosts={getLineCosts}
- unitPricePrecision={line.unitPricePrecision ?? 2}
- />
- )}
+ {line.methodType === "Make" &&
+ line.status !== "No Quote" &&
+ permissions.is("employee") && (
+ <QuoteLineCosting
+ quantities={line.quantity ?? [1]}
+ getLineCosts={getLineCosts}
+ unitPricePrecision={line.unitPricePrecision ?? 2}
+ />
+ )}
{line.status !== "No Quote" && (
<>
<Suspense fallback={null}>
diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.details.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.details.tsx
index 261fc10f04..9e721b8994 100644
--- a/apps/erp/app/routes/x+/quote+/$quoteId.details.tsx
+++ b/apps/erp/app/routes/x+/quote+/$quoteId.details.tsx
@@ -110,6 +110,8 @@ export default function QuoteDetailsRoute() {
opportunity: Opportunity;
}>(path.to.quote(quoteId));
+ console.log({ quoteData });
+
if (!quoteData) throw new Error("Could not find quote data");
const shipmentFormRef = useRef<QuoteShipmentFormRef>(null);
diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.tsx
index 2f558e25c8..f3741865ad 100644
--- a/apps/erp/app/routes/x+/quote+/$quoteId.tsx
+++ b/apps/erp/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 { VStack } from "@carbon/react";
@@ -57,19 +57,17 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
throw redirect(path.to.quotes);
}
- const serviceRole = getCarbonServiceRole();
-
const [customer, shipment, payment, lines, prices, opportunity, methods] =
await Promise.all([
- getCustomer(serviceRole, quote.data?.customerId ?? ""),
- getQuoteShipment(serviceRole, quoteId),
- getQuotePayment(serviceRole, quoteId),
- getQuoteLines(serviceRole, quoteId),
- getQuoteLinePricesByQuoteId(serviceRole, quoteId),
- getOpportunity(serviceRole, quote.data?.opportunityId),
- getQuoteMethodTrees(serviceRole, quoteId),
+ getCustomer(client, quote.data?.customerId ?? ""),
+ getQuoteShipment(client, quoteId),
+ getQuotePayment(client, quoteId),
+ getQuoteLines(client, quoteId),
+ getQuoteLinePricesByQuoteId(client, quoteId),
+ getOpportunity(client, quote.data?.opportunityId),
+ getQuoteMethodTrees(client, quoteId),
getOpportunityDocuments(
- serviceRole,
+ client,
companyId,
quote.data?.opportunityId ?? ""
),
@@ -101,7 +99,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
);
@@ -116,7 +114,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
opportunity.data.salesOrders[0]?.id
) {
salesOrderLines = await getSalesOrderLines(
- serviceRole,
+ client,
opportunity.data.salesOrders[0]?.id
);
}
diff --git a/apps/erp/app/routes/x+/supplier-quote+/$id.details.tsx b/apps/erp/app/routes/x+/supplier-quote+/$id.details.tsx
index 31b1c54428..35eaa1fa72 100644
--- a/apps/erp/app/routes/x+/supplier-quote+/$id.details.tsx
+++ b/apps/erp/app/routes/x+/supplier-quote+/$id.details.tsx
@@ -23,6 +23,7 @@ import {
SupplierInteractionDocuments,
SupplierInteractionNotes,
} from "~/modules/purchasing/ui/SupplierInteraction";
+import SupplierInteractionState from "~/modules/purchasing/ui/SupplierInteraction/SupplierInteractionState";
import SupplierQuoteSummary from "~/modules/purchasing/ui/SupplierQuote/SupplierQuoteSummary";
import { setCustomFields } from "~/utils/form";
import { path } from "~/utils/path";
@@ -122,6 +123,7 @@ export default function SupplierQuoteDetailsRoute() {
return (
<>
+ <SupplierInteractionState interaction={routeData.interaction} />
<SupplierQuoteSummary />
<SupplierInteractionNotes
key={`notes-${initialValues.id}`}
diff --git a/packages/auth/src/services/auth.server.ts b/packages/auth/src/services/auth.server.ts
index a77f813ed0..2d5095b2f2 100644
--- a/packages/auth/src/services/auth.server.ts
+++ b/packages/auth/src/services/auth.server.ts
@@ -169,10 +169,7 @@ export async function requirePermissions(
myClaims.permissions[p][
action as "view" | "create" | "update" | "delete"
];
- return (
- permissionForCompany.includes("0") || // 0 is the wildcard for all companies
- permissionForCompany.includes(companyId)
- );
+ return permissionForCompany.includes(companyId);
});
} else {
return false;
@@ -195,7 +192,7 @@ export async function requirePermissions(
return {
client:
- requiredPermissions.bypassRls && myClaims.role === "employee"
+ !!requiredPermissions.bypassRls && myClaims.role === "employee"
? getCarbonServiceRole()
: getCarbon(accessToken),
companyId,
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index a87baa36b5..946a0a9118 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -5739,6 +5739,9 @@ export default {
{
$ref: "#/parameters/rowFilter.supplierInteraction.companyId",
},
+ {
+ $ref: "#/parameters/rowFilter.supplierInteraction.supplierId",
+ },
{
$ref: "#/parameters/select",
},
@@ -5804,6 +5807,9 @@ export default {
{
$ref: "#/parameters/rowFilter.supplierInteraction.companyId",
},
+ {
+ $ref: "#/parameters/rowFilter.supplierInteraction.supplierId",
+ },
{
$ref: "#/parameters/preferReturn",
},
@@ -5823,6 +5829,9 @@ export default {
{
$ref: "#/parameters/rowFilter.supplierInteraction.companyId",
},
+ {
+ $ref: "#/parameters/rowFilter.supplierInteraction.supplierId",
+ },
{
$ref: "#/parameters/body.supplierInteraction",
},
@@ -49872,6 +49881,9 @@ export default {
{
$ref: "#/parameters/rowFilter.opportunity.requestForQuoteDocumentPath",
},
+ {
+ $ref: "#/parameters/rowFilter.opportunity.customerId",
+ },
{
$ref: "#/parameters/select",
},
@@ -49943,6 +49955,9 @@ export default {
{
$ref: "#/parameters/rowFilter.opportunity.requestForQuoteDocumentPath",
},
+ {
+ $ref: "#/parameters/rowFilter.opportunity.customerId",
+ },
{
$ref: "#/parameters/preferReturn",
},
@@ -49968,6 +49983,9 @@ export default {
{
$ref: "#/parameters/rowFilter.opportunity.requestForQuoteDocumentPath",
},
+ {
+ $ref: "#/parameters/rowFilter.opportunity.customerId",
+ },
{
$ref: "#/parameters/body.opportunity",
},
@@ -52400,6 +52418,63 @@ export default {
tags: ["(rpc) create_rfq_from_models_v2"],
},
},
+ "/rpc/get_supplier_interaction_with_related_records": {
+ get: {
+ parameters: [
+ {
+ format: "text",
+ in: "query",
+ name: "supplier_interaction_id",
+ required: true,
+ type: "string",
+ },
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json",
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ },
+ },
+ tags: ["(rpc) get_supplier_interaction_with_related_records"],
+ },
+ post: {
+ parameters: [
+ {
+ in: "body",
+ name: "args",
+ required: true,
+ schema: {
+ properties: {
+ supplier_interaction_id: {
+ format: "text",
+ type: "string",
+ },
+ },
+ required: ["supplier_interaction_id"],
+ type: "object",
+ },
+ },
+ {
+ $ref: "#/parameters/preferParams",
+ },
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json",
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ },
+ },
+ tags: ["(rpc) get_supplier_interaction_with_related_records"],
+ },
+ },
"/rpc/check_operation_dependencies": {
get: {
parameters: [
@@ -59365,7 +59440,7 @@ export default {
type: "object",
},
supplierInteraction: {
- required: ["id", "companyId"],
+ required: ["id", "companyId", "supplierId"],
properties: {
id: {
default: "public.xid()",
@@ -59379,6 +59454,12 @@ export default {
format: "text",
type: "string",
},
+ supplierId: {
+ description:
+ "Note:\nThis is a Foreign Key to `supplier.id`.<fk table='supplier' column='id'/>",
+ format: "text",
+ type: "string",
+ },
},
type: "object",
},
@@ -80503,7 +80584,7 @@ export default {
type: "object",
},
opportunity: {
- required: ["id", "companyId"],
+ required: ["id", "companyId", "customerId"],
properties: {
id: {
default: "public.xid()",
@@ -80525,6 +80606,12 @@ export default {
format: "text",
type: "string",
},
+ customerId: {
+ description:
+ "Note:\nThis is a Foreign Key to `customer.id`.<fk table='customer' column='id'/>",
+ format: "text",
+ type: "string",
+ },
},
type: "object",
},
@@ -84273,6 +84360,12 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.supplierInteraction.supplierId": {
+ name: "supplierId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"body.receipt": {
name: "receipt",
description: "receipt",
@@ -108156,6 +108249,12 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.opportunity.customerId": {
+ name: "customerId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"body.customField": {
name: "customField",
description: "customField",
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index fa9c967941..d4a91baa2a 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -16671,18 +16671,21 @@ export type Database = {
opportunity: {
Row: {
companyId: string
+ customerId: string
id: string
purchaseOrderDocumentPath: string | null
requestForQuoteDocumentPath: string | null
}
Insert: {
companyId: string
+ customerId: string
id?: string
purchaseOrderDocumentPath?: string | null
requestForQuoteDocumentPath?: string | null
}
Update: {
companyId?: string
+ customerId?: string
id?: string
purchaseOrderDocumentPath?: string | null
requestForQuoteDocumentPath?: string | null
@@ -16716,6 +16719,27 @@ export type Database = {
referencedRelation: "integrations"
referencedColumns: ["companyId"]
},
+ {
+ foreignKeyName: "opportunity_customerId_fkey"
+ columns: ["customerId"]
+ isOneToOne: false
+ referencedRelation: "customer"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "opportunity_customerId_fkey"
+ columns: ["customerId"]
+ isOneToOne: false
+ referencedRelation: "customers"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "opportunity_customerId_fkey"
+ columns: ["customerId"]
+ isOneToOne: false
+ referencedRelation: "salesOrderCustomers"
+ referencedColumns: ["id"]
+ },
]
}
part: {
@@ -29490,14 +29514,17 @@ export type Database = {
Row: {
companyId: string
id: string
+ supplierId: string
}
Insert: {
companyId: string
id?: string
+ supplierId: string
}
Update: {
companyId?: string
id?: string
+ supplierId?: string
}
Relationships: [
{
@@ -29528,6 +29555,41 @@ export type Database = {
referencedRelation: "integrations"
referencedColumns: ["companyId"]
},
+ {
+ foreignKeyName: "supplierInteraction_supplierId_fkey"
+ columns: ["supplierId"]
+ isOneToOne: false
+ referencedRelation: "contractors"
+ referencedColumns: ["supplierId"]
+ },
+ {
+ foreignKeyName: "supplierInteraction_supplierId_fkey"
+ columns: ["supplierId"]
+ isOneToOne: false
+ referencedRelation: "partners"
+ referencedColumns: ["supplierId"]
+ },
+ {
+ foreignKeyName: "supplierInteraction_supplierId_fkey"
+ columns: ["supplierId"]
+ isOneToOne: false
+ referencedRelation: "purchaseOrderSuppliers"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierInteraction_supplierId_fkey"
+ columns: ["supplierId"]
+ isOneToOne: false
+ referencedRelation: "supplier"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierInteraction_supplierId_fkey"
+ columns: ["supplierId"]
+ isOneToOne: false
+ referencedRelation: "suppliers"
+ referencedColumns: ["id"]
+ },
]
}
supplierLedger: {
@@ -45232,6 +45294,7 @@ export type Database = {
Returns: {
id: string
companyId: string
+ customerId: string
purchaseOrderDocumentPath: string
requestForQuoteDocumentPath: string
salesRfqs: Json
@@ -45548,6 +45611,19 @@ export type Database = {
}
Returns: string[]
}
+ get_supplier_interaction_with_related_records: {
+ Args: {
+ supplier_interaction_id: string
+ }
+ Returns: {
+ id: string
+ companyId: string
+ supplierId: string
+ supplierQuotes: Json
+ purchaseOrders: Json
+ purchaseInvoices: Json
+ }[]
+ }
get_tool_details: {
Args: {
item_id: string
diff --git a/packages/database/supabase/functions/lib/api/purchasing.ts b/packages/database/supabase/functions/lib/api/purchasing.ts
index 1f1d4be9ea..fb6a88303c 100644
--- a/packages/database/supabase/functions/lib/api/purchasing.ts
+++ b/packages/database/supabase/functions/lib/api/purchasing.ts
@@ -39,11 +39,12 @@ export async function getSupplierShipping(
export async function insertSupplierInteraction(
db: Kysely<DB> | Transaction<DB>,
- companyId: string
+ companyId: string,
+ supplierId: string
) {
return await db
.insertInto("supplierInteraction")
- .values({ companyId })
+ .values({ companyId, supplierId })
.returning(["id"])
.executeTakeFirst();
}
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index fa9c967941..d4a91baa2a 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -16671,18 +16671,21 @@ export type Database = {
opportunity: {
Row: {
companyId: string
+ customerId: string
id: string
purchaseOrderDocumentPath: string | null
requestForQuoteDocumentPath: string | null
}
Insert: {
companyId: string
+ customerId: string
id?: string
purchaseOrderDocumentPath?: string | null
requestForQuoteDocumentPath?: string | null
}
Update: {
companyId?: string
+ customerId?: string
id?: string
purchaseOrderDocumentPath?: string | null
requestForQuoteDocumentPath?: string | null
@@ -16716,6 +16719,27 @@ export type Database = {
referencedRelation: "integrations"
referencedColumns: ["companyId"]
},
+ {
+ foreignKeyName: "opportunity_customerId_fkey"
+ columns: ["customerId"]
+ isOneToOne: false
+ referencedRelation: "customer"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "opportunity_customerId_fkey"
+ columns: ["customerId"]
+ isOneToOne: false
+ referencedRelation: "customers"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "opportunity_customerId_fkey"
+ columns: ["customerId"]
+ isOneToOne: false
+ referencedRelation: "salesOrderCustomers"
+ referencedColumns: ["id"]
+ },
]
}
part: {
@@ -29490,14 +29514,17 @@ export type Database = {
Row: {
companyId: string
id: string
+ supplierId: string
}
Insert: {
companyId: string
id?: string
+ supplierId: string
}
Update: {
companyId?: string
id?: string
+ supplierId?: string
}
Relationships: [
{
@@ -29528,6 +29555,41 @@ export type Database = {
referencedRelation: "integrations"
referencedColumns: ["companyId"]
},
+ {
+ foreignKeyName: "supplierInteraction_supplierId_fkey"
+ columns: ["supplierId"]
+ isOneToOne: false
+ referencedRelation: "contractors"
+ referencedColumns: ["supplierId"]
+ },
+ {
+ foreignKeyName: "supplierInteraction_supplierId_fkey"
+ columns: ["supplierId"]
+ isOneToOne: false
+ referencedRelation: "partners"
+ referencedColumns: ["supplierId"]
+ },
+ {
+ foreignKeyName: "supplierInteraction_supplierId_fkey"
+ columns: ["supplierId"]
+ isOneToOne: false
+ referencedRelation: "purchaseOrderSuppliers"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierInteraction_supplierId_fkey"
+ columns: ["supplierId"]
+ isOneToOne: false
+ referencedRelation: "supplier"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierInteraction_supplierId_fkey"
+ columns: ["supplierId"]
+ isOneToOne: false
+ referencedRelation: "suppliers"
+ referencedColumns: ["id"]
+ },
]
}
supplierLedger: {
@@ -45232,6 +45294,7 @@ export type Database = {
Returns: {
id: string
companyId: string
+ customerId: string
purchaseOrderDocumentPath: string
requestForQuoteDocumentPath: string
salesRfqs: Json
@@ -45548,6 +45611,19 @@ export type Database = {
}
Returns: string[]
}
+ get_supplier_interaction_with_related_records: {
+ Args: {
+ supplier_interaction_id: string
+ }
+ Returns: {
+ id: string
+ companyId: string
+ supplierId: string
+ supplierQuotes: Json
+ purchaseOrders: Json
+ purchaseInvoices: Json
+ }[]
+ }
get_tool_details: {
Args: {
item_id: string
diff --git a/packages/database/supabase/functions/mcp/tools.ts b/packages/database/supabase/functions/mcp/tools.ts
index a18a77e700..cec9e147d2 100644
--- a/packages/database/supabase/functions/mcp/tools.ts
+++ b/packages/database/supabase/functions/mcp/tools.ts
@@ -43,7 +43,7 @@ const createPurchaseOrder = tool({
"purchaseOrder",
context.companyId
),
- insertSupplierInteraction(context.db, context.companyId),
+ insertSupplierInteraction(context.db, context.companyId, args.supplierId),
getSupplierById(context.db, args.supplierId),
getSupplierPayment(context.db, args.supplierId),
getSupplierShipping(context.db, args.supplierId),
diff --git a/packages/database/supabase/migrations/20250707135534_customer-opportunity.sql b/packages/database/supabase/migrations/20250707135534_customer-opportunity.sql
new file mode 100644
index 0000000000..2934372596
--- /dev/null
+++ b/packages/database/supabase/migrations/20250707135534_customer-opportunity.sql
@@ -0,0 +1,839 @@
+-- Add customerId field to opportunity table
+ALTER TABLE "opportunity" ADD COLUMN "customerId" TEXT;
+
+-- Add supplierId field to supplierInteraction table
+ALTER TABLE "supplierInteraction" ADD COLUMN "supplierId" TEXT;
+
+-- Update opportunity table with customerId from various sources in order of priority
+UPDATE "opportunity" o
+SET "customerId" = COALESCE(
+ -- First try salesRfq
+ (
+ SELECT r."customerId"
+ FROM "salesRfq" r
+ WHERE r."opportunityId" = o."id"
+ LIMIT 1
+ ),
+ -- Then try quote
+ (
+ SELECT q."customerId"
+ FROM "quote" q
+ WHERE q."opportunityId" = o."id"
+ LIMIT 1
+ ),
+ -- Then try salesOrder
+ (
+ SELECT so."customerId"
+ FROM "salesOrder" so
+ WHERE so."opportunityId" = o."id"
+ LIMIT 1
+ ),
+ -- Finally try salesInvoice
+ (
+ SELECT si."customerId"
+ FROM "salesInvoice" si
+ WHERE si."opportunityId" = o."id"
+ LIMIT 1
+ )
+)
+WHERE o."customerId" IS NULL;
+
+-- Update supplierInteraction table with supplierId from various sources in order of priority
+UPDATE "supplierInteraction" si
+SET "supplierId" = COALESCE(
+ -- First try purchaseOrder
+ (
+ SELECT po."supplierId"
+ FROM "purchaseOrder" po
+ WHERE po."supplierInteractionId" = si."id"
+ LIMIT 1
+ ),
+ -- Then try supplierQuote
+ (
+ SELECT sq."supplierId"
+ FROM "supplierQuote" sq
+ WHERE sq."supplierInteractionId" = si."id"
+ LIMIT 1
+ ),
+ -- Finally try purchaseInvoice
+ (
+ SELECT pi."supplierId"
+ FROM "purchaseInvoice" pi
+ WHERE pi."supplierInteractionId" = si."id"
+ LIMIT 1
+ )
+)
+WHERE si."supplierId" IS NULL;
+
+-- Make customerId NOT NULL on opportunity table
+ALTER TABLE "opportunity" ALTER COLUMN "customerId" SET NOT NULL;
+
+-- Make supplierId NOT NULL on supplierInteraction table
+ALTER TABLE "supplierInteraction" ALTER COLUMN "supplierId" SET NOT NULL;
+
+-- Add foreign key constraints
+ALTER TABLE "opportunity" ADD CONSTRAINT "opportunity_customerId_fkey"
+ FOREIGN KEY ("customerId") REFERENCES "customer" ("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+ALTER TABLE "supplierInteraction" ADD CONSTRAINT "supplierInteraction_supplierId_fkey"
+ FOREIGN KEY ("supplierId") REFERENCES "supplier" ("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- Add indexes for performance
+CREATE INDEX "opportunity_customerId_idx" ON "opportunity" ("customerId");
+CREATE INDEX "supplierInteraction_supplierId_idx" ON "supplierInteraction" ("supplierId");
+
+
+
+-- Drop old policies
+DO $$
+BEGIN
+ -- Drop opportunity policies
+ DROP POLICY IF EXISTS "Employees with sales_view can view opportunities" ON "opportunity";
+ DROP POLICY IF EXISTS "Employees with sales_create can insert opportunities" ON "opportunity";
+ DROP POLICY IF EXISTS "Employees with sales_create can update opportunities" ON "opportunity";
+ DROP POLICY IF EXISTS "Employees with sales_delete can delete opportunities" ON "opportunity";
+
+ -- Drop supplierInteraction policies
+ DROP POLICY IF EXISTS "Employees with purchasing_view can view supplierInteractions" ON "supplierInteraction";
+ DROP POLICY IF EXISTS "Employees with purchasing_create can insert supplierInteractions" ON "supplierInteraction";
+ DROP POLICY IF EXISTS "Employees with purchasing_update can update supplierInteractions" ON "supplierInteraction";
+ DROP POLICY IF EXISTS "Employees with purchasing_delete can delete supplierInteractions" ON "supplierInteraction";
+
+ -- Drop quote policies
+ DROP POLICY IF EXISTS "Customers with sales_update can their own quotes" ON "quote";
+ DROP POLICY IF EXISTS "Customers with sales_view can their own quotes" ON "quote";
+ DROP POLICY IF EXISTS "Employees with sales_create can create quotes" ON "quote";
+ DROP POLICY IF EXISTS "Employees with sales_delete can delete quotes" ON "quote";
+ DROP POLICY IF EXISTS "Employees with sales_update can update quotes" ON "quote";
+ DROP POLICY IF EXISTS "Employees with sales_view can view quotes" ON "quote";
+ DROP POLICY IF EXISTS "Requests with an API key can access quotes" ON "quote";
+
+ -- Drop quoteLine policies
+ DROP POLICY IF EXISTS "Customers with sales_create can create lines on their own quote" ON "quoteLine";
+ DROP POLICY IF EXISTS "Customers with sales_delete can delete lines on their own quote" ON "quoteLine";
+ DROP POLICY IF EXISTS "Customers with sales_update can their own quote lines" ON "quoteLine";
+ DROP POLICY IF EXISTS "Customers with sales_view can their own quote lines" ON "quoteLine";
+ DROP POLICY IF EXISTS "Employees with sales_create can create quote lines" ON "quoteLine";
+ DROP POLICY IF EXISTS "Employees with sales_delete can delete quote lines" ON "quoteLine";
+ DROP POLICY IF EXISTS "Employees with sales_update can update quote lines" ON "quoteLine";
+ DROP POLICY IF EXISTS "Employees with sales_view can view quote lines" ON "quoteLine";
+ DROP POLICY IF EXISTS "Requests with an API key can access quote lines" ON "quoteLine";
+
+ -- Drop quoteShipment policies
+ DROP POLICY IF EXISTS "Employees with sales_view can view quote shipments" ON "quoteShipment";
+ DROP POLICY IF EXISTS "Employees with sales_create can create quote shipments" ON "quoteShipment";
+ DROP POLICY IF EXISTS "Employees with sales_update can update quote shipments" ON "quoteShipment";
+ DROP POLICY IF EXISTS "Employees with sales_delete can delete quote shipments" ON "quoteShipment";
+ DROP POLICY IF EXISTS "Requests with an API key can access quote shipments" ON "quoteShipment";
+
+ -- Drop quotePayment policies
+ DROP POLICY IF EXISTS "Employees with sales_view can view quote payments" ON "quotePayment";
+ DROP POLICY IF EXISTS "Employees with sales_create can create quote payments" ON "quotePayment";
+ DROP POLICY IF EXISTS "Employees with sales_update can update quote payments" ON "quotePayment";
+ DROP POLICY IF EXISTS "Employees with sales_delete can delete quote payments" ON "quotePayment";
+ DROP POLICY IF EXISTS "Requests with an API key can access quote payments" ON "quotePayment";
+
+ -- DROP salesOrder
+
+ DROP POLICY IF EXISTS "Customers with sales_update can update their own sales orders" ON "salesOrder";
+ DROP POLICY IF EXISTS "Customers with sales_view can their own sales orders" ON "salesOrder";
+ DROP POLICY IF EXISTS "Employees with sales_create can create sales orders" ON "salesOrder";
+ DROP POLICY IF EXISTS "Employees with sales_delete can delete sales orders" ON "salesOrder";
+ DROP POLICY IF EXISTS "Employees with sales_update can update sales orders" ON "salesOrder";
+ DROP POLICY IF EXISTS "Employees with sales_view, inventory_view, or invoicing_view ca" ON "salesOrder";
+ DROP POLICY IF EXISTS "Requests with an API key can access requests for sales order" ON "salesOrder";
+
+ -- DROP salesOrderLine
+ DROP POLICY IF EXISTS "Customers with sales_create can create lines on their own sales" ON "salesOrderLine";
+ DROP POLICY IF EXISTS "Customers with sales_delete can delete lines on their own sales" ON "salesOrderLine";
+ DROP POLICY IF EXISTS "Customers with sales_update can update their own sales order li" ON "salesOrderLine";
+ DROP POLICY IF EXISTS "Customers with sales_view can their own sales order lines" ON "salesOrderLine";
+ DROP POLICY IF EXISTS "Employees with sales_create can create sales order lines" ON "salesOrderLine";
+ DROP POLICY IF EXISTS "Employees with sales_delete can delete sales order lines" ON "salesOrderLine";
+ DROP POLICY IF EXISTS "Employees with sales_update can update sales order lines" ON "salesOrderLine";
+ DROP POLICY IF EXISTS "Employees with sales_view can view sales order lines" ON "salesOrderLine";
+ DROP POLICY IF EXISTS "Requests with an API key can access requests for sales order li" ON "salesOrderLine";
+
+ -- Drop salesOrderShipment policies
+ DROP POLICY IF EXISTS "Employees with sales_view can view sales order shipments" ON "salesOrderShipment";
+ DROP POLICY IF EXISTS "Employees with sales_create can create sales order shipments" ON "salesOrderShipment";
+ DROP POLICY IF EXISTS "Employees with sales_update can update sales order shipments" ON "salesOrderShipment";
+ DROP POLICY IF EXISTS "Employees with sales_delete can delete sales order shipments" ON "salesOrderShipment";
+ DROP POLICY IF EXISTS "Requests with an API key can access sales order shipments" ON "salesOrderShipment";
+
+ -- Drop salesOrderPayment policies
+ DROP POLICY IF EXISTS "Employees with sales_view can view sales order payments" ON "salesOrderPayment";
+ DROP POLICY IF EXISTS "Employees with sales_create can create sales order payments" ON "salesOrderPayment";
+ DROP POLICY IF EXISTS "Employees with sales_update can update sales order payments" ON "salesOrderPayment";
+ DROP POLICY IF EXISTS "Employees with sales_delete can delete sales order payments" ON "salesOrderPayment";
+ DROP POLICY IF EXISTS "Requests with an API key can access sales order payments" ON "salesOrderPayment";
+
+ -- Drop salesRFQ policies
+ DROP POLICY IF EXISTS "Customer with sales_view can view their own sales rfqs" ON "salesRfq";
+ DROP POLICY IF EXISTS "Employees with sales_create can create sales rfqs" ON "salesRfq";
+ DROP POLICY IF EXISTS "Employees with sales_delete can delete sales rfqs" ON "salesRfq";
+ DROP POLICY IF EXISTS "Employees with sales_update can edit sales rfqs" ON "salesRfq";
+ DROP POLICY IF EXISTS "Employees with sales_view can view sales rfqs" ON "salesRfq";
+ DROP POLICY IF EXISTS "Requests with an API key can access sales RFQs" ON "salesRfq";
+
+ -- Drop salesRfqLine policies
+ DROP POLICY IF EXISTS "Customers with sales_view can their own purchase order lines" ON "salesRfqLine";
+ DROP POLICY IF EXISTS "Employees with sales_create can create sales rfq lines" ON "salesRfqLine";
+ DROP POLICY IF EXISTS "Employees with sales_create can insert salesRfqLine" ON "salesRfqLine";
+ DROP POLICY IF EXISTS "Employees with sales_delete can delete sales rfq lines" ON "salesRfqLine";
+ DROP POLICY IF EXISTS "Employees with sales_delete can delete salesRfqLine" ON "salesRfqLine";
+ DROP POLICY IF EXISTS "Employees with sales_update can edit sales rfq lines" ON "salesRfqLine";
+ DROP POLICY IF EXISTS "Employees with sales_update can update salesRfqLine" ON "salesRfqLine";
+ DROP POLICY IF EXISTS "Employees with sales_view can view sales rfq lines" ON "salesRfqLine";
+ DROP POLICY IF EXISTS "Employees with sales_view can view salesRfqLine" ON "salesRfqLine";
+ DROP POLICY IF EXISTS "Requests with an API key can access sales RFQ lines" ON "salesRfqLine";
+
+ -- Drop job policies
+ DROP POLICY IF EXISTS "Employees can view jobs" ON "job";
+ DROP POLICY IF EXISTS "Employees with production_create can insert jobs" ON "job";
+ DROP POLICY IF EXISTS "Employees with production_update can update jobs" ON "job";
+ DROP POLICY IF EXISTS "Employees with production_delete can delete jobs" ON "job";
+ DROP POLICY IF EXISTS "Customers with production_view can view their own jobs" ON "job";
+ DROP POLICY IF EXISTS "Requests with an API key can access jobs" ON "job";
+
+ -- Drop jobOperation policies
+ DROP POLICY IF EXISTS "Employees can view job operations" ON "jobOperation";
+ DROP POLICY IF EXISTS "Employees with production_create can insert job operations" ON "jobOperation";
+ DROP POLICY IF EXISTS "Employees with production_update can update job operations" ON "jobOperation";
+ DROP POLICY IF EXISTS "Employees with production_delete can delete job operations" ON "jobOperation";
+ DROP POLICY IF EXISTS "Requests with an API key can access jobs" ON "jobOperation";
+
+ -- Drop jobMaterial policies
+ DROP POLICY IF EXISTS "Employees can view job materials" ON "jobMaterial";
+ DROP POLICY IF EXISTS "Employees with production_create can insert job materials" ON "jobMaterial";
+ DROP POLICY IF EXISTS "Employees with production_update can update job materials" ON "jobMaterial";
+ DROP POLICY IF EXISTS "Employees with production_delete can delete job materials" ON "jobMaterial";
+ DROP POLICY IF EXISTS "Requests with an API key can access jobs" ON "jobMaterial";
+
+ -- Drop standardized policies
+ DROP POLICY IF EXISTS "SELECT" ON "public"."opportunity";
+ DROP POLICY IF EXISTS "INSERT" ON "public"."opportunity";
+ DROP POLICY IF EXISTS "UPDATE" ON "public"."opportunity";
+ DROP POLICY IF EXISTS "DELETE" ON "public"."opportunity";
+
+ DROP POLICY IF EXISTS "SELECT" ON "public"."supplierInteraction";
+ DROP POLICY IF EXISTS "INSERT" ON "public"."supplierInteraction";
+ DROP POLICY IF EXISTS "UPDATE" ON "public"."supplierInteraction";
+ DROP POLICY IF EXISTS "DELETE" ON "public"."supplierInteraction";
+
+ DROP POLICY IF EXISTS "SELECT" ON "public"."quoteShipment";
+ DROP POLICY IF EXISTS "INSERT" ON "public"."quoteShipment";
+ DROP POLICY IF EXISTS "UPDATE" ON "public"."quoteShipment";
+ DROP POLICY IF EXISTS "DELETE" ON "public"."quoteShipment";
+
+ DROP POLICY IF EXISTS "SELECT" ON "public"."quotePayment";
+ DROP POLICY IF EXISTS "INSERT" ON "public"."quotePayment";
+ DROP POLICY IF EXISTS "UPDATE" ON "public"."quotePayment";
+ DROP POLICY IF EXISTS "DELETE" ON "public"."quotePayment";
+
+ DROP POLICY IF EXISTS "SELECT" ON "public"."salesOrderShipment";
+ DROP POLICY IF EXISTS "INSERT" ON "public"."salesOrderShipment";
+ DROP POLICY IF EXISTS "UPDATE" ON "public"."salesOrderShipment";
+ DROP POLICY IF EXISTS "DELETE" ON "public"."salesOrderShipment";
+
+ DROP POLICY IF EXISTS "SELECT" ON "public"."salesOrderPayment";
+ DROP POLICY IF EXISTS "INSERT" ON "public"."salesOrderPayment";
+ DROP POLICY IF EXISTS "UPDATE" ON "public"."salesOrderPayment";
+ DROP POLICY IF EXISTS "DELETE" ON "public"."salesOrderPayment";
+
+ DROP POLICY IF EXISTS "SELECT" ON "public"."job";
+ DROP POLICY IF EXISTS "INSERT" ON "public"."job";
+ DROP POLICY IF EXISTS "UPDATE" ON "public"."job";
+ DROP POLICY IF EXISTS "DELETE" ON "public"."job";
+
+ DROP POLICY IF EXISTS "SELECT" ON "public"."jobOperation";
+ DROP POLICY IF EXISTS "INSERT" ON "public"."jobOperation";
+ DROP POLICY IF EXISTS "UPDATE" ON "public"."jobOperation";
+ DROP POLICY IF EXISTS "DELETE" ON "public"."jobOperation";
+
+ DROP POLICY IF EXISTS "SELECT" ON "public"."jobMaterial";
+ DROP POLICY IF EXISTS "INSERT" ON "public"."jobMaterial";
+ DROP POLICY IF EXISTS "UPDATE" ON "public"."jobMaterial";
+ DROP POLICY IF EXISTS "DELETE" ON "public"."jobMaterial";
+END $$;
+
+-- Create new standardized policies
+CREATE POLICY "SELECT" ON "public"."opportunity"
+FOR SELECT TO public USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_view'))::text[]) OR
+ "customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('sales_view'))::text[])
+);
+
+CREATE POLICY "INSERT" ON "public"."opportunity"
+FOR INSERT TO public WITH CHECK (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_create'))::text[]) OR
+ "customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('sales_create'))::text[])
+);
+
+CREATE POLICY "UPDATE" ON "public"."opportunity"
+FOR UPDATE TO public USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_update'))::text[]) OR
+ "customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('sales_update'))::text[])
+);
+
+CREATE POLICY "DELETE" ON "public"."opportunity"
+FOR DELETE TO public USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_delete'))::text[]) OR
+ "customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('sales_delete'))::text[])
+);
+
+CREATE POLICY "SELECT" ON "public"."supplierInteraction"
+FOR SELECT TO public USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('purchasing_view'))::text[]) OR
+ "supplierId" = ANY ((SELECT get_supplier_ids_with_supplier_permission('purchasing_view'))::text[])
+);
+
+CREATE POLICY "INSERT" ON "public"."supplierInteraction"
+FOR INSERT TO public WITH CHECK (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('purchasing_create'))::text[]) OR
+ "supplierId" = ANY ((SELECT get_supplier_ids_with_supplier_permission('purchasing_create'))::text[])
+);
+
+CREATE POLICY "UPDATE" ON "public"."supplierInteraction"
+FOR UPDATE TO public USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('purchasing_update'))::text[]) OR
+ "supplierId" = ANY ((SELECT get_supplier_ids_with_supplier_permission('purchasing_update'))::text[])
+);
+
+CREATE POLICY "DELETE" ON "public"."supplierInteraction"
+FOR DELETE TO public USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('purchasing_delete'))::text[]) OR
+ "supplierId" = ANY ((SELECT get_supplier_ids_with_supplier_permission('purchasing_delete'))::text[])
+);
+
+
+CREATE POLICY "SELECT" ON "public"."quote"
+FOR SELECT TO public USING (
+ "companyId" = ANY (
+ SELECT DISTINCT unnest(ARRAY(
+ SELECT unnest(get_companies_with_employee_permission('sales_view'))
+ UNION
+ SELECT unnest(get_companies_with_employee_permission('production_view'))
+ ))
+ ) OR
+ "customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('sales_view'))::text[])
+);
+
+CREATE POLICY "INSERT" ON "public"."quote"
+FOR INSERT TO public WITH CHECK (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_create'))::text[]) OR
+ "customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('sales_create'))::text[])
+);
+
+CREATE POLICY "UPDATE" ON "public"."quote"
+FOR UPDATE TO public USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_update'))::text[]) OR
+ "customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('sales_update'))::text[])
+);
+
+CREATE POLICY "DELETE" ON "public"."quote"
+FOR DELETE TO public USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_delete'))::text[]) OR
+ "customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('sales_delete'))::text[])
+);
+
+CREATE POLICY "SELECT" ON "public"."quoteLine"
+FOR SELECT TO public USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_view'))::text[]) OR
+ EXISTS (
+ SELECT 1 FROM "quote" so
+ WHERE so."id" = "quoteLine"."quoteId"
+ AND so."customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('sales_view'))::text[])
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."quoteLine"
+FOR INSERT TO public WITH CHECK (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_create'))::text[]) OR
+ EXISTS (
+ SELECT 1 FROM "quote" so
+ WHERE so."id" = "quoteLine"."quoteId"
+ AND so."customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('sales_create'))::text[])
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."quoteLine"
+FOR UPDATE TO public USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_update'))::text[]) OR
+ EXISTS (
+ SELECT 1 FROM "quote" so
+ WHERE so."id" = "quoteLine"."quoteId"
+ AND so."customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('sales_update'))::text[])
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."quoteLine"
+FOR DELETE TO public USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_delete'))::text[]) OR
+ EXISTS (
+ SELECT 1 FROM "quote" so
+ WHERE so."id" = "quoteLine"."quoteId"
+ AND so."customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('sales_delete'))::text[])
+ )
+);
+
+CREATE POLICY "SELECT" ON "public"."quoteShipment"
+FOR SELECT TO public USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_view'))::text[]) OR
+ EXISTS (
+ SELECT 1 FROM "quote" q
+ WHERE q."id" = "quoteShipment"."id"
+ AND q."customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('sales_view'))::text[])
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."quoteShipment"
+FOR INSERT TO public WITH CHECK (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_create'))::text[]) OR
+ EXISTS (
+ SELECT 1 FROM "quote" q
+ WHERE q."id" = "quoteShipment"."id"
+ AND q."customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('sales_create'))::text[])
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."quoteShipment"
+FOR UPDATE TO public USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_update'))::text[]) OR
+ EXISTS (
+ SELECT 1 FROM "quote" q
+ WHERE q."id" = "quoteShipment"."id"
+ AND q."customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('sales_update'))::text[])
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."quoteShipment"
+FOR DELETE TO public USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_delete'))::text[]) OR
+ EXISTS (
+ SELECT 1 FROM "quote" q
+ WHERE q."id" = "quoteShipment"."id"
+ AND q."customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('sales_delete'))::text[])
+ )
+);
+
+CREATE POLICY "SELECT" ON "public"."quotePayment"
+FOR SELECT TO public USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_view'))::text[]) OR
+ EXISTS (
+ SELECT 1 FROM "quote" q
+ WHERE q."id" = "quotePayment"."id"
+ AND q."customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('sales_view'))::text[])
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."quotePayment"
+FOR INSERT TO public WITH CHECK (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_create'))::text[]) OR
+ EXISTS (
+ SELECT 1 FROM "quote" q
+ WHERE q."id" = "quotePayment"."id"
+ AND q."customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('sales_create'))::text[])
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."quotePayment"
+FOR UPDATE TO public USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_update'))::text[]) OR
+ EXISTS (
+ SELECT 1 FROM "quote" q
+ WHERE q."id" = "quotePayment"."id"
+ AND q."customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('sales_update'))::text[])
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."quotePayment"
+FOR DELETE TO public USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_delete'))::text[]) OR
+ EXISTS (
+ SELECT 1 FROM "quote" q
+ WHERE q."id" = "quotePayment"."id"
+ AND q."customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('sales_delete'))::text[])
+ )
+);
+
+CREATE POLICY "SELECT" ON "public"."salesOrder"
+FOR SELECT TO public USING (
+ "companyId" = ANY (
+ SELECT DISTINCT unnest(ARRAY(
+ SELECT unnest(get_companies_with_employee_permission('sales_view'))
+ UNION
+ SELECT unnest(get_companies_with_employee_permission('production_view'))
+ ))
+ ) OR
+ "customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('sales_view'))::text[])
+);
+
+CREATE POLICY "INSERT" ON "public"."salesOrder"
+FOR INSERT TO public WITH CHECK (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_create'))::text[]) OR
+ "customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('sales_create'))::text[])
+);
+
+CREATE POLICY "UPDATE" ON "public"."salesOrder"
+FOR UPDATE TO public USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_update'))::text[]) OR
+ "customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('sales_update'))::text[])
+);
+
+CREATE POLICY "DELETE" ON "public"."salesOrder"
+FOR DELETE TO public USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_delete'))::text[]) OR
+ "customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('sales_delete'))::text[])
+);
+
+CREATE POLICY "SELECT" ON "public"."salesOrderLine"
+FOR SELECT TO public USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_view'))::text[]) OR
+ EXISTS (
+ SELECT 1 FROM "salesOrder" so
+ WHERE so."id" = "salesOrderLine"."salesOrderId"
+ AND so."customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('sales_view'))::text[])
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."salesOrderLine"
+FOR INSERT TO public WITH CHECK (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_create'))::text[]) OR
+ EXISTS (
+ SELECT 1 FROM "salesOrder" so
+ WHERE so."id" = "salesOrderLine"."salesOrderId"
+ AND so."customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('sales_create'))::text[])
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."salesOrderLine"
+FOR UPDATE TO public USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_update'))::text[]) OR
+ EXISTS (
+ SELECT 1 FROM "salesOrder" so
+ WHERE so."id" = "salesOrderLine"."salesOrderId"
+ AND so."customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('sales_update'))::text[])
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."salesOrderLine"
+FOR DELETE TO public USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_delete'))::text[]) OR
+ EXISTS (
+ SELECT 1 FROM "salesOrder" so
+ WHERE so."id" = "salesOrderLine"."salesOrderId"
+ AND so."customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('sales_delete'))::text[])
+ )
+);
+
+CREATE POLICY "SELECT" ON "public"."salesOrderShipment"
+FOR SELECT TO public USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_view'))::text[]) OR
+ EXISTS (
+ SELECT 1 FROM "salesOrder" so
+ WHERE so."id" = "salesOrderShipment"."id"
+ AND so."customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('sales_view'))::text[])
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."salesOrderShipment"
+FOR INSERT TO public WITH CHECK (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_create'))::text[]) OR
+ EXISTS (
+ SELECT 1 FROM "salesOrder" so
+ WHERE so."id" = "salesOrderShipment"."id"
+ AND so."customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('sales_create'))::text[])
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."salesOrderShipment"
+FOR UPDATE TO public USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_update'))::text[]) OR
+ EXISTS (
+ SELECT 1 FROM "salesOrder" so
+ WHERE so."id" = "salesOrderShipment"."id"
+ AND so."customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('sales_update'))::text[])
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."salesOrderShipment"
+FOR DELETE TO public USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_delete'))::text[]) OR
+ EXISTS (
+ SELECT 1 FROM "salesOrder" so
+ WHERE so."id" = "salesOrderShipment"."id"
+ AND so."customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('sales_delete'))::text[])
+ )
+);
+
+CREATE POLICY "SELECT" ON "public"."salesOrderPayment"
+FOR SELECT TO public USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_view'))::text[]) OR
+ EXISTS (
+ SELECT 1 FROM "salesOrder" so
+ WHERE so."id" = "salesOrderPayment"."id"
+ AND so."customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('sales_view'))::text[])
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."salesOrderPayment"
+FOR INSERT TO public WITH CHECK (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_create'))::text[]) OR
+ EXISTS (
+ SELECT 1 FROM "salesOrder" so
+ WHERE so."id" = "salesOrderPayment"."id"
+ AND so."customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('sales_create'))::text[])
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."salesOrderPayment"
+FOR UPDATE TO public USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_update'))::text[]) OR
+ EXISTS (
+ SELECT 1 FROM "salesOrder" so
+ WHERE so."id" = "salesOrderPayment"."id"
+ AND so."customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('sales_update'))::text[])
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."salesOrderPayment"
+FOR DELETE TO public USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_delete'))::text[]) OR
+ EXISTS (
+ SELECT 1 FROM "salesOrder" so
+ WHERE so."id" = "salesOrderPayment"."id"
+ AND so."customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('sales_delete'))::text[])
+ )
+);
+
+CREATE POLICY "SELECT" ON "public"."salesRfq"
+FOR SELECT TO public USING (
+ "companyId" = ANY (
+ SELECT DISTINCT unnest(ARRAY(
+ SELECT unnest(get_companies_with_employee_permission('sales_view'))
+ UNION
+ SELECT unnest(get_companies_with_employee_permission('production_view'))
+ ))
+ ) OR
+ "customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('sales_view'))::text[])
+);
+
+CREATE POLICY "INSERT" ON "public"."salesRfq"
+FOR INSERT TO public WITH CHECK (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_create'))::text[]) OR
+ "customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('sales_create'))::text[])
+);
+
+CREATE POLICY "UPDATE" ON "public"."salesRfq"
+FOR UPDATE TO public USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_update'))::text[]) OR
+ "customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('sales_update'))::text[])
+);
+
+CREATE POLICY "DELETE" ON "public"."salesRfq"
+FOR DELETE TO public USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_delete'))::text[]) OR
+ "customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('sales_delete'))::text[])
+);
+
+CREATE POLICY "SELECT" ON "public"."salesRfqLine"
+FOR SELECT TO public USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_view'))::text[]) OR
+ EXISTS (
+ SELECT 1 FROM "salesRfq" so
+ WHERE so."id" = "salesRfqLine"."salesRfqId"
+ AND so."customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('sales_view'))::text[])
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."salesRfqLine"
+FOR INSERT TO public WITH CHECK (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_create'))::text[]) OR
+ EXISTS (
+ SELECT 1 FROM "salesRfq" so
+ WHERE so."id" = "salesRfqLine"."salesRfqId"
+ AND so."customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('sales_create'))::text[])
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."salesRfqLine"
+FOR UPDATE TO public USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_update'))::text[]) OR
+ EXISTS (
+ SELECT 1 FROM "salesRfq" so
+ WHERE so."id" = "salesRfqLine"."salesRfqId"
+ AND so."customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('sales_update'))::text[])
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."salesRfqLine"
+FOR DELETE TO public USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_delete'))::text[]) OR
+ EXISTS (
+ SELECT 1 FROM "salesRfq" so
+ WHERE so."id" = "salesRfqLine"."salesRfqId"
+ AND so."customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('sales_delete'))::text[])
+ )
+);
+
+
+CREATE POLICY "SELECT" ON "public"."job"
+FOR SELECT TO public USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('production_view'))::text[]) OR
+ "customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('production_view'))::text[])
+);
+
+CREATE POLICY "INSERT" ON "public"."job"
+FOR INSERT TO public WITH CHECK (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('production_create'))::text[]) OR
+ "customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('production_create'))::text[])
+);
+
+CREATE POLICY "UPDATE" ON "public"."job"
+FOR UPDATE TO public USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('production_update'))::text[]) OR
+ "customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('production_update'))::text[])
+);
+
+CREATE POLICY "DELETE" ON "public"."job"
+FOR DELETE TO public USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('production_delete'))::text[]) OR
+ "customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('production_delete'))::text[])
+);
+
+CREATE POLICY "SELECT" ON "public"."jobOperation"
+FOR SELECT TO public USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('production_view'))::text[]) OR
+ EXISTS (
+ SELECT 1 FROM "job" j
+ WHERE j."id" = "jobOperation"."jobId"
+ AND j."customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('production_view'))::text[])
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."jobOperation"
+FOR INSERT TO public WITH CHECK (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('production_create'))::text[]) OR
+ EXISTS (
+ SELECT 1 FROM "job" j
+ WHERE j."id" = "jobOperation"."jobId"
+ AND j."customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('production_create'))::text[])
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."jobOperation"
+FOR UPDATE TO public USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('production_update'))::text[]) OR
+ EXISTS (
+ SELECT 1 FROM "job" j
+ WHERE j."id" = "jobOperation"."jobId"
+ AND j."customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('production_update'))::text[])
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."jobOperation"
+FOR DELETE TO public USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('production_delete'))::text[]) OR
+ EXISTS (
+ SELECT 1 FROM "job" j
+ WHERE j."id" = "jobOperation"."jobId"
+ AND j."customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('production_delete'))::text[])
+ )
+);
+
+CREATE POLICY "SELECT" ON "public"."jobMaterial"
+FOR SELECT TO public USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('production_view'))::text[])
+);
+
+CREATE POLICY "INSERT" ON "public"."jobMaterial"
+FOR INSERT TO public WITH CHECK (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('production_create'))::text[])
+);
+
+CREATE POLICY "UPDATE" ON "public"."jobMaterial"
+FOR UPDATE TO public USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('production_update'))::text[])
+);
+
+CREATE POLICY "DELETE" ON "public"."jobMaterial"
+FOR DELETE TO public USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('production_delete'))::text[])
+);
+
+DROP FUNCTION IF EXISTS get_opportunity_with_related_records(TEXT);
+CREATE FUNCTION get_opportunity_with_related_records(opportunity_id TEXT)
+RETURNS TABLE (
+ "id" TEXT,
+ "companyId" TEXT,
+ "customerId" TEXT,
+ "purchaseOrderDocumentPath" TEXT,
+ "requestForQuoteDocumentPath" TEXT,
+ "salesRfqs" JSONB,
+ "quotes" JSONB,
+ "salesOrders" JSONB
+) AS $$
+BEGIN
+ RETURN QUERY
+ SELECT
+ o."id",
+ o."companyId",
+ o."customerId",
+ o."purchaseOrderDocumentPath",
+ o."requestForQuoteDocumentPath",
+ (
+ SELECT COALESCE(jsonb_agg(rfq.* ORDER BY rfq."revisionId" DESC), '[]'::jsonb)
+ FROM "salesRfq" rfq
+ WHERE rfq."opportunityId" = o.id
+ ) AS "salesRfqs",
+ (
+ SELECT COALESCE(jsonb_agg(q.* ORDER BY q."revisionId" DESC), '[]'::jsonb)
+ FROM "quote" q
+ WHERE q."opportunityId" = o.id
+ ) AS "quotes",
+ (
+ SELECT COALESCE(jsonb_agg(so.* ORDER BY so."revisionId" DESC), '[]'::jsonb)
+ FROM "salesOrder" so
+ WHERE so."opportunityId" = o.id
+ ) AS "salesOrders"
+ FROM "opportunity" o
+ WHERE o.id = opportunity_id::text;
+END;
+$$ LANGUAGE plpgsql SECURITY INVOKER;
+
+DROP FUNCTION IF EXISTS get_supplier_interaction_with_related_records(TEXT);
+CREATE FUNCTION get_supplier_interaction_with_related_records(supplier_interaction_id TEXT)
+RETURNS TABLE (
+ "id" TEXT,
+ "companyId" TEXT,
+ "supplierId" TEXT,
+ "supplierQuotes" JSONB,
+ "purchaseOrders" JSONB,
+ "purchaseInvoices" JSONB
+) AS $$
+BEGIN
+ RETURN QUERY
+ SELECT
+ si."id",
+ si."companyId",
+ si."supplierId",
+ (
+ SELECT COALESCE(jsonb_agg(sq.* ORDER BY sq."supplierQuoteId" DESC), '[]'::jsonb)
+ FROM "supplierQuote" sq
+ WHERE sq."supplierInteractionId" = si.id
+ ) AS "supplierQuotes",
+ (
+ SELECT COALESCE(jsonb_agg(po.* ORDER BY po."purchaseOrderId" DESC), '[]'::jsonb)
+ FROM "purchaseOrder" po
+ WHERE po."supplierInteractionId" = si.id
+ ) AS "purchaseOrders",
+ (
+ SELECT COALESCE(jsonb_agg(pi.* ORDER BY pi."invoiceId" DESC), '[]'::jsonb)
+ FROM "purchaseInvoice" pi
+ WHERE pi."supplierInteractionId" = si.id
+ ) AS "purchaseInvoices"
+ FROM "supplierInteraction" si
+ WHERE si.id = supplier_interaction_id::text;
+END;
+$$ LANGUAGE plpgsql SECURITY INVOKER;
\ No newline at end of file
diff --git a/packages/database/supabase/migrations/20250707204426_sales-rls-refactor.sql b/packages/database/supabase/migrations/20250707204426_sales-rls-refactor.sql
new file mode 100644
index 0000000000..daeb070882
--- /dev/null
+++ b/packages/database/supabase/migrations/20250707204426_sales-rls-refactor.sql
@@ -0,0 +1,94 @@
+-- Drop old policies
+DO $$
+BEGIN
+ -- Drop salesRfq policies
+ DROP POLICY IF EXISTS "Employees with sales_view can view sales rfqs" ON "salesRfq";
+ DROP POLICY IF EXISTS "Employees with sales_create can create sales rfqs" ON "salesRfq";
+ DROP POLICY IF EXISTS "Employees with sales_update can edit sales rfqs" ON "salesRfq";
+ DROP POLICY IF EXISTS "Employees with sales_delete can delete sales rfqs" ON "salesRfq";
+ DROP POLICY IF EXISTS "Customer with sales_view can view their own sales rfqs" ON "salesRfq";
+
+ -- Drop salesRfqLine policies
+ DROP POLICY IF EXISTS "Employees with sales_view can view sales rfq lines" ON "salesRfqLine";
+ DROP POLICY IF EXISTS "Employees with sales_create can create sales rfq lines" ON "salesRfqLine";
+ DROP POLICY IF EXISTS "Employees with sales_update can edit sales rfq lines" ON "salesRfqLine";
+ DROP POLICY IF EXISTS "Employees with sales_delete can delete sales rfq lines" ON "salesRfqLine";
+ DROP POLICY IF EXISTS "Customers with sales_view can their own purchase order lines" ON "salesRfqLine";
+
+ -- Drop standardized policies if they exist
+ DROP POLICY IF EXISTS "SELECT" ON "public"."salesRfq";
+ DROP POLICY IF EXISTS "INSERT" ON "public"."salesRfq";
+ DROP POLICY IF EXISTS "UPDATE" ON "public"."salesRfq";
+ DROP POLICY IF EXISTS "DELETE" ON "public"."salesRfq";
+
+ DROP POLICY IF EXISTS "SELECT" ON "public"."salesRfqLine";
+ DROP POLICY IF EXISTS "INSERT" ON "public"."salesRfqLine";
+ DROP POLICY IF EXISTS "UPDATE" ON "public"."salesRfqLine";
+ DROP POLICY IF EXISTS "DELETE" ON "public"."salesRfqLine";
+END $$;
+
+-- Create new standardized policies for salesRfq
+CREATE POLICY "SELECT" ON "public"."salesRfq"
+FOR SELECT TO public USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_view'))::text[]) OR
+ "customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('sales_view'))::text[])
+);
+
+CREATE POLICY "INSERT" ON "public"."salesRfq"
+FOR INSERT TO public WITH CHECK (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_create'))::text[]) OR
+ "customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('sales_create'))::text[])
+);
+
+CREATE POLICY "UPDATE" ON "public"."salesRfq"
+FOR UPDATE TO public USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_update'))::text[]) OR
+ "customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('sales_update'))::text[])
+);
+
+CREATE POLICY "DELETE" ON "public"."salesRfq"
+FOR DELETE TO public USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_delete'))::text[]) OR
+ "customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('sales_delete'))::text[])
+);
+
+-- Create new standardized policies for salesRfqLine
+CREATE POLICY "SELECT" ON "public"."salesRfqLine"
+FOR SELECT TO public USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_view'))::text[]) OR
+ EXISTS (
+ SELECT 1 FROM "salesRfq" rfq
+ WHERE rfq."id" = "salesRfqLine"."salesRfqId"
+ AND rfq."customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('sales_view'))::text[])
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."salesRfqLine"
+FOR INSERT TO public WITH CHECK (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_create'))::text[]) OR
+ EXISTS (
+ SELECT 1 FROM "salesRfq" rfq
+ WHERE rfq."id" = "salesRfqLine"."salesRfqId"
+ AND rfq."customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('sales_create'))::text[])
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."salesRfqLine"
+FOR UPDATE TO public USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_update'))::text[]) OR
+ EXISTS (
+ SELECT 1 FROM "salesRfq" rfq
+ WHERE rfq."id" = "salesRfqLine"."salesRfqId"
+ AND rfq."customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('sales_update'))::text[])
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."salesRfqLine"
+FOR DELETE TO public USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('sales_delete'))::text[]) OR
+ EXISTS (
+ SELECT 1 FROM "salesRfq" rfq
+ WHERE rfq."id" = "salesRfqLine"."salesRfqId"
+ AND rfq."customerId" = ANY ((SELECT get_customer_ids_with_customer_permission('sales_delete'))::text[])
+ )
+);
diff --git a/packages/documents/src/email/components/Logo.tsx b/packages/documents/src/email/components/Logo.tsx
index 5af6a7ba44..b08da06ba3 100644
--- a/packages/documents/src/email/components/Logo.tsx
+++ b/packages/documents/src/email/components/Logo.tsx
@@ -1,14 +1,11 @@
-import { getAppUrl } from "@carbon/auth";
import { Img, Section } from "@react-email/components";
-const baseUrl = getAppUrl();
-
export function Logo() {
return (
<Section className="mt-[32px]">
<Img
- src={`${baseUrl}/carbon-logo-mark.svg`}
- width="45"
+ src="https://app.carbonos.dev/carbon-word-light.svg"
+ width="auto"
height="45"
alt="Carbon"
className="my-0 mx-auto block"