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.

add rls to purchasing and links to suppliers table (#33)

Brad Barbina90e9dc17784
diff --git a/SCHEMA.md b/SCHEMA.md
index 4051ad89a8..7a82aa6c6e 100644
--- a/SCHEMA.md
+++ b/SCHEMA.md
@@ -4528,6 +4528,13 @@ ALTER TABLE "supplier"
ADD CONSTRAINT "supplier_defaultShippingMethodId_fkey" FOREIGN KEY ("defaultShippingMethodId") REFERENCES "shippingMethod" ("id") ON DELETE SET NULL,
ADD CONSTRAINT "supplier_defaultShippingTermId_fkey" FOREIGN KEY ("defaultShippingTermId") REFERENCES "shippingTerm" ("id") ON DELETE SET NULL;
+CREATE VIEW "purchase_order_suppliers_view" AS
+ SELECT DISTINCT
+ s."id",
+ s."name"
+ FROM "supplier" s
+ INNER JOIN "purchaseOrder" p ON p."supplierId" = s."id";
+
```
@@ -4661,19 +4668,6 @@ FOR DELETE USING (
-## `view-rls`
-
-```sql
--- TODO: after Postgres 15, we can use security_invoker = on
--- ALTER VIEW "contractors_view" SET (security_invoker = on);
--- ALTER VIEW "partners_view" SET (security_invoker = on);
--- ALTER VIEW "documents_labels_view" SET (security_invoker = on);
--- ALTER VIEW "documents_view" SET (security_invoker = on);
--- ALTER VIEW "purchase_order_view" SET (security_invoker = on);
-```
-
-
-
## `purchasing-rls`
```sql
@@ -4683,7 +4677,7 @@ CREATE POLICY "Employees with purchasing_view can view purchase orders" ON "purc
FOR SELECT
USING (coalesce(get_my_claim('purchasing_view')::boolean, false) = true AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
-CREATE POLICY "Suppliers with purchasing_view can their own organization" ON "purchaseOrder"
+CREATE POLICY "Suppliers with purchasing_view can their own purchase orders" ON "purchaseOrder"
FOR SELECT
USING (
coalesce(get_my_claim('purchasing_view')::boolean, false) = true
@@ -4761,5 +4755,233 @@ CREATE POLICY "Suppliers with purchasing_view can search for their own purchase
)
)
);
+
+-- Purchase Order Lines
+
+ALTER TABLE "purchaseOrderLine" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "Employees with purchasing_view can view purchase order lines" ON "purchaseOrderLine"
+ FOR SELECT
+ USING (coalesce(get_my_claim('purchasing_view')::boolean, false) = true AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
+
+CREATE POLICY "Suppliers with purchasing_view can their own purchase order lines" ON "purchaseOrderLine"
+ FOR SELECT
+ USING (
+ coalesce(get_my_claim('purchasing_view')::boolean, false) = true
+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonb
+ AND "purchaseOrderId" IN (
+ SELECT id FROM "purchaseOrder" WHERE "supplierId" IN (
+ SELECT "supplierId" FROM "purchaseOrder" WHERE "supplierId" IN (
+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
+ )
+ )
+ )
+ );
+
+CREATE POLICY "Employees with purchasing_create can create purchase order lines" ON "purchaseOrderLine"
+ FOR INSERT
+ WITH CHECK (coalesce(get_my_claim('purchasing_create')::boolean,false) AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
+
+CREATE POLICY "Suppliers with purchasing_create can create lines on their own purchase order" ON "purchaseOrderLine"
+ FOR INSERT
+ WITH CHECK (
+ coalesce(get_my_claim('purchasing_create')::boolean, false) = true
+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonb
+ AND "purchaseOrderId" IN (
+ SELECT id FROM "purchaseOrder" WHERE "supplierId" IN (
+ SELECT "supplierId" FROM "purchaseOrder" WHERE "supplierId" IN (
+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
+ )
+ )
+ )
+ );
+
+CREATE POLICY "Employees with purchasing_update can update purchase order lines" ON "purchaseOrderLine"
+ FOR UPDATE
+ USING (coalesce(get_my_claim('purchasing_update')::boolean,false) AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
+
+CREATE POLICY "Suppliers with purchasing_update can their own purchase order lines" ON "purchaseOrderLine"
+ FOR UPDATE
+ USING (
+ coalesce(get_my_claim('purchasing_update')::boolean, false) = true
+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonb
+ AND "purchaseOrderId" IN (
+ SELECT id FROM "purchaseOrder" WHERE "supplierId" IN (
+ SELECT "supplierId" FROM "purchaseOrder" WHERE "supplierId" IN (
+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
+ )
+ )
+ )
+ );
+
+CREATE POLICY "Employees with purchasing_delete can delete purchase order lines" ON "purchaseOrderLine"
+ FOR DELETE
+ USING (coalesce(get_my_claim('purchasing_delete')::boolean, false) = true AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
+
+CREATE POLICY "Suppliers with purchasing_delete can delete lines on their own purchase order" ON "purchaseOrderLine"
+ FOR DELETE
+ USING (
+ coalesce(get_my_claim('purchasing_delete')::boolean, false) = true
+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonb
+ AND "purchaseOrderId" IN (
+ SELECT id FROM "purchaseOrder" WHERE "supplierId" IN (
+ SELECT "supplierId" FROM "purchaseOrder" WHERE "supplierId" IN (
+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
+ )
+ )
+ )
+ );
+
+
+-- Purchase Order Deliveries
+
+ALTER TABLE "purchaseOrderDelivery" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "Employees with purchasing_view can view purchase order deliveries" ON "purchaseOrderDelivery"
+ FOR SELECT
+ USING (coalesce(get_my_claim('purchasing_view')::boolean, false) = true AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
+
+CREATE POLICY "Suppliers with purchasing_view can their own purchase order deliveries" ON "purchaseOrderDelivery"
+ FOR SELECT
+ USING (
+ coalesce(get_my_claim('purchasing_view')::boolean, false) = true
+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonb
+ AND id IN (
+ SELECT id FROM "purchaseOrder" WHERE "supplierId" IN (
+ SELECT "supplierId" FROM "purchaseOrder" WHERE "supplierId" IN (
+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
+ )
+ )
+ )
+ );
+
+CREATE POLICY "Employees with purchasing_create can create purchase order deliveries" ON "purchaseOrderDelivery"
+ FOR INSERT
+ WITH CHECK (coalesce(get_my_claim('purchasing_create')::boolean,false) AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
+
+CREATE POLICY "Employees with purchasing_update can update purchase order deliveries" ON "purchaseOrderDelivery"
+ FOR UPDATE
+ USING (coalesce(get_my_claim('purchasing_update')::boolean,false) AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
+
+CREATE POLICY "Suppliers with purchasing_update can their own purchase order deliveries" ON "purchaseOrderDelivery"
+ FOR UPDATE
+ USING (
+ coalesce(get_my_claim('purchasing_update')::boolean, false) = true
+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonb
+ AND id IN (
+ SELECT id FROM "purchaseOrder" WHERE "supplierId" IN (
+ SELECT "supplierId" FROM "purchaseOrder" WHERE "supplierId" IN (
+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
+ )
+ )
+ )
+ );
+
+CREATE POLICY "Employees with purchasing_delete can delete purchase order deliveries" ON "purchaseOrderDelivery"
+ FOR DELETE
+ USING (coalesce(get_my_claim('purchasing_delete')::boolean, false) = true AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
+
+
+-- Purchase Order Payments
+
+ALTER TABLE "purchaseOrderPayment" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "Employees with purchasing_view can view purchase order payments" ON "purchaseOrderPayment"
+ FOR SELECT
+ USING (coalesce(get_my_claim('purchasing_view')::boolean, false) = true AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
+
+CREATE POLICY "Employees with purchasing_create can create purchase order payments" ON "purchaseOrderPayment"
+ FOR INSERT
+ WITH CHECK (coalesce(get_my_claim('purchasing_create')::boolean,false) AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
+
+CREATE POLICY "Employees with purchasing_update can update purchase order payments" ON "purchaseOrderPayment"
+ FOR UPDATE
+ USING (coalesce(get_my_claim('purchasing_update')::boolean,false) AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
+
+CREATE POLICY "Employees with purchasing_delete can delete purchase order payments" ON "purchaseOrderPayment"
+ FOR DELETE
+ USING (coalesce(get_my_claim('purchasing_delete')::boolean, false) = true AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
+
+```
+
+
+
+## `supplier-view`
+
+```sql
+CREATE VIEW "suppliers_view" AS
+ SELECT
+ s.id,
+ s.name,
+ s."supplierTypeId",
+ st.name AS "type",
+ s."supplierStatusId",
+ ss.name AS "status",
+ po.count AS "orderCount",
+ p.count AS "partCount"
+ FROM "supplier" s
+ LEFT JOIN "supplierType" st ON st.id = s."supplierTypeId"
+ LEFT JOIN "supplierStatus" ss ON ss.id = s."supplierStatusId"
+ LEFT JOIN (
+ SELECT
+ "supplierId",
+ COUNT(*) AS "count"
+ FROM "purchaseOrder"
+ GROUP BY "supplierId"
+ ) po ON po."supplierId" = s.id
+ LEFT JOIN (
+ SELECT
+ "supplierId",
+ COUNT(*) AS "count"
+ FROM "partSupplier"
+ GROUP BY "supplierId"
+ ) p ON p."supplierId" = s.id;
+```
+
+
+
+## `parts-view`
+
+```sql
+CREATE VIEW "parts_view" AS
+ SELECT
+ p.id,
+ p.name,
+ p.description,
+ p."partType",
+ p."partGroupId",
+ pg.name AS "partGroup",
+ p."replenishmentSystem",
+ p.active,
+ array_agg(ps."supplierId") AS "supplierIds"
+ FROM "part" p
+ LEFT JOIN "partGroup" pg ON pg.id = p."partGroupId"
+ LEFT JOIN "partSupplier" ps ON ps."partId" = p.id
+ GROUP BY p.id,
+ p.name,
+ p.description,
+ p."partType",
+ p."partGroupId",
+ pg.name,
+ p."replenishmentSystem",
+ p.active;
+
+
+```
+
+
+
+## `view-rls`
+
+```sql
+-- TODO: after Postgres 15, we can use security_invoker = on
+-- ALTER VIEW "contractors_view" SET (security_invoker = on);
+-- ALTER VIEW "partners_view" SET (security_invoker = on);
+-- ALTER VIEW "documents_labels_view" SET (security_invoker = on);
+-- ALTER VIEW "documents_view" SET (security_invoker = on);
+-- ALTER VIEW "purchase_order_view" SET (security_invoker = on);
+-- ALTER VIEW "purchase_order_suppliers_view" SET (security_invoker = on);
+-- ALTER VIEW "suppliers_view" SET (security_invoker = on);
+-- ALTER VIEW "parts_view" SET (security_invoker = on);
```
diff --git a/apps/carbon/app/components/Layout/Topbar/useNewMenu.tsx b/apps/carbon/app/components/Layout/Topbar/useNewMenu.tsx
index ff5fbc8224..947dd35b33 100644
--- a/apps/carbon/app/components/Layout/Topbar/useNewMenu.tsx
+++ b/apps/carbon/app/components/Layout/Topbar/useNewMenu.tsx
@@ -1,6 +1,8 @@
import { useMemo } from "react";
import { AiOutlinePartition } from "react-icons/ai";
import { BsCartDash, BsShieldLock } from "react-icons/bs";
+import { IoMdPeople } from "react-icons/io";
+import { SiHandshake } from "react-icons/si";
import { usePermissions } from "~/hooks";
import type { Route } from "~/types";
@@ -26,6 +28,22 @@ export default function useNewMenu(): Route[] {
});
}
+ if (permissions.can("create", "purchasing")) {
+ links.push({
+ name: "New Supplier",
+ to: "/x/purchasing/suppliers/new",
+ icon: <SiHandshake />,
+ });
+ }
+
+ if (permissions.can("create", "sales")) {
+ links.push({
+ name: "New Customer",
+ to: "/x/sales/customers/new",
+ icon: <IoMdPeople />,
+ });
+ }
+
if (permissions.can("create", "users")) {
links.push({
name: "New Employee",
@@ -34,13 +52,6 @@ export default function useNewMenu(): Route[] {
});
}
- // if (permissions.can("create", "sales")) {
- // links.push({
- // name: "New Customer",
- // to: "/x/sales/customers/new",
- // });
- // }
-
return links;
}, [permissions]);
diff --git a/apps/carbon/app/modules/parts/interfaces/Parts/PartsTable/PartsTable.tsx b/apps/carbon/app/modules/parts/interfaces/Parts/PartsTable/PartsTable.tsx
index bd5d460252..db333f8160 100644
--- a/apps/carbon/app/modules/parts/interfaces/Parts/PartsTable/PartsTable.tsx
+++ b/apps/carbon/app/modules/parts/interfaces/Parts/PartsTable/PartsTable.tsx
@@ -45,7 +45,7 @@ const PartsTable = memo(({ data, count }: PartsTableProps) => {
},
{
// @ts-ignore
- accessorFn: (item) => item.partGroup?.name ?? "",
+ accessorKey: "partGroup",
header: "Part Group",
cell: (item) => item.getValue(),
},
diff --git a/apps/carbon/app/modules/parts/services/parts.server.ts b/apps/carbon/app/modules/parts/services/parts.server.ts
index 599534d060..9b26feab1b 100644
--- a/apps/carbon/app/modules/parts/services/parts.server.ts
+++ b/apps/carbon/app/modules/parts/services/parts.server.ts
@@ -131,16 +131,12 @@ export async function getParts(
search: string | null;
type: string | null;
group: string | null;
+ supplierId: string | null;
}
) {
- let query = client
- .from("part")
- .select(
- "id, name, description, partType, partGroup(name), replenishmentSystem",
- {
- count: "exact",
- }
- );
+ let query = client.from("parts_view").select("*", {
+ count: "exact",
+ });
if (args.search) {
query = query.or(
@@ -156,6 +152,10 @@ export async function getParts(
query = query.eq("partGroupId", args.group);
}
+ if (args.supplierId) {
+ query = query.contains("supplierIds", [args.supplierId]);
+ }
+
query = setGenericQueryFilters(query, args, "id");
return query;
}
diff --git a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderLines/PurchaseOrderLines.tsx b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderLines/PurchaseOrderLines.tsx
index 6cab8c39de..96d440cfb7 100644
--- a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderLines/PurchaseOrderLines.tsx
+++ b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderLines/PurchaseOrderLines.tsx
@@ -34,6 +34,10 @@ const PurchaseOrderLines = ({
const columns = useMemo<ColumnDef<PurchaseOrderLine>[]>(() => {
return [
+ {
+ header: "Line",
+ cell: ({ row }) => row.index + 1,
+ },
{
accessorKey: "purchaseOrderLineType",
header: "Type",
@@ -157,7 +161,7 @@ const PurchaseOrderLines = ({
return (
<>
- <Card w="full">
+ <Card w="full" minH={320}>
<CardHeader display="flex" justifyContent="space-between">
<Heading size="md" display="inline-flex">
Purchase Order Lines
diff --git a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrders/PurchaseOrdersTableFilters/PurchaseOrdersTableFilters.tsx b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrders/PurchaseOrdersTableFilters/PurchaseOrdersTableFilters.tsx
index 1b9f1527c9..6a6b94bffc 100644
--- a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrders/PurchaseOrdersTableFilters/PurchaseOrdersTableFilters.tsx
+++ b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrders/PurchaseOrdersTableFilters/PurchaseOrdersTableFilters.tsx
@@ -17,12 +17,25 @@ const purchaseOrderStatusOptions = [
value: type,
}));
-const PurchaseOrdersTableFilters = () => {
+type PurchaseOrdersTableFiltersProps = {
+ suppliers: { id: string | null; name: string | null }[];
+};
+
+const PurchaseOrdersTableFilters = ({
+ suppliers,
+}: PurchaseOrdersTableFiltersProps) => {
const [params, setParams] = useUrlParams();
const permissions = usePermissions();
const borderColor = useColor("gray.200");
+ const supplierOptions = suppliers
+ .filter((supplier) => supplier.id && supplier.name)
+ .map((supplier) => ({
+ label: supplier.name,
+ value: supplier.id,
+ }));
+
return (
<HStack
px={4}
@@ -55,6 +68,21 @@ const PurchaseOrdersTableFilters = () => {
minW={180}
placeholder="Status"
/>
+ <Select
+ // @ts-ignore
+ size="sm"
+ value={supplierOptions.filter(
+ (supplier) => supplier.value === params.get("supplierId")
+ )}
+ isClearable
+ options={supplierOptions}
+ onChange={(selected) => {
+ setParams({ supplierId: selected?.value });
+ }}
+ aria-label="Supplier"
+ minW={180}
+ placeholder="Supplier"
+ />
</HStack>
<HStack spacing={2}>
{permissions.can("create", "purchasing") && (
diff --git a/apps/carbon/app/modules/purchasing/interfaces/Suppliers/SuppliersTable/SuppliersTable.tsx b/apps/carbon/app/modules/purchasing/interfaces/Suppliers/SuppliersTable/SuppliersTable.tsx
index e648ec2874..b8c2d2b97d 100644
--- a/apps/carbon/app/modules/purchasing/interfaces/Suppliers/SuppliersTable/SuppliersTable.tsx
+++ b/apps/carbon/app/modules/purchasing/interfaces/Suppliers/SuppliersTable/SuppliersTable.tsx
@@ -24,32 +24,33 @@ const SuppliersTable = memo(({ data, count }: SuppliersTableProps) => {
cell: (item) => item.getValue(),
},
{
- // @ts-ignore
- accessorFn: (item) => item.supplierType?.name ?? "",
+ accessorKey: "type",
header: "Supplier Type",
cell: (item) => item.getValue(),
},
{
- // @ts-ignore
- accessorFn: (item) => item.supplierStatus?.name ?? "",
+ accessorKey: "status",
header: "Supplier Status",
cell: (item) => item.getValue(),
},
{
id: "orders",
header: "Orders",
- cell: () => (
- <ButtonGroup
- size="sm"
- isAttached
- variant="outline"
- onClick={(e) => e.stopPropagation()}
- >
- <Button onClick={() => console.log("orders")}>0 Orders</Button>
+ cell: ({ row }) => (
+ <ButtonGroup size="sm" isAttached variant="outline">
+ <Button
+ onClick={() =>
+ navigate(`/x/purchasing/orders?supplierId=${row.original.id}`)
+ }
+ >
+ {row.original.orderCount ?? 0} Orders
+ </Button>
<IconButton
aria-label="New Order"
icon={<BsPlus />}
- onClick={() => console.log("new order")}
+ onClick={() =>
+ navigate(`/x/purchase-order/new?supplierId=${row.original.id}`)
+ }
/>
</ButtonGroup>
),
@@ -57,18 +58,21 @@ const SuppliersTable = memo(({ data, count }: SuppliersTableProps) => {
{
id: "parts",
header: "Parts",
- cell: () => (
- <ButtonGroup
- size="sm"
- isAttached
- variant="outline"
- onClick={(e) => e.stopPropagation()}
- >
- <Button onClick={() => console.log("orders")}>0 Parts</Button>
+ cell: ({ row }) => (
+ <ButtonGroup size="sm" isAttached variant="outline">
+ <Button
+ onClick={() =>
+ navigate(`/x/parts/search?supplierId=${row.original.id}`)
+ }
+ >
+ {row.original.partCount ?? 0} Parts
+ </Button>
<IconButton
aria-label="New Part"
icon={<BsPlus />}
- onClick={() => console.log("new part")}
+ onClick={() =>
+ navigate(`/x/part/new?supplierId=${row.original.id}`)
+ }
/>
</ButtonGroup>
),
@@ -87,7 +91,7 @@ const SuppliersTable = memo(({ data, count }: SuppliersTableProps) => {
navigate(`/x/purchasing/suppliers/${row.id}?${params.toString()}`)
}
>
- Edit Supplier
+ View Supplier
</MenuItem>
),
[navigate, params]
diff --git a/apps/carbon/app/modules/purchasing/services/purchasing.server.ts b/apps/carbon/app/modules/purchasing/services/purchasing.server.ts
index f8351b534e..eeb5a8b5db 100644
--- a/apps/carbon/app/modules/purchasing/services/purchasing.server.ts
+++ b/apps/carbon/app/modules/purchasing/services/purchasing.server.ts
@@ -187,6 +187,12 @@ export function getPurchaseOrderLineTypes(): Database["public"]["Enums"]["purcha
return ["Part", "G/L Account", "Fixed Asset", "Comment"];
}
+export async function getPurchaseOrderSuppliers(
+ client: SupabaseClient<Database>
+) {
+ return client.from("purchase_order_suppliers_view").select("id, name");
+}
+
export function getPurchaseOrderTypes(): Database["public"]["Enums"]["purchaseOrderType"][] {
return ["Draft", "Purchase", "Return"];
}
@@ -243,11 +249,9 @@ export async function getSuppliers(
status: string | null;
}
) {
- let query = client
- .from("supplier")
- .select("id, name, supplierType(name), supplierStatus(name)", {
- count: "exact",
- });
+ let query = client.from("suppliers_view").select("*", {
+ count: "exact",
+ });
if (args.name) {
query = query.ilike("name", `%${args.name}%`);
diff --git a/apps/carbon/app/modules/sales/interfaces/Customers/CustomersTable/CustomersTable.tsx b/apps/carbon/app/modules/sales/interfaces/Customers/CustomersTable/CustomersTable.tsx
index 189e35ffb5..1354e80d07 100644
--- a/apps/carbon/app/modules/sales/interfaces/Customers/CustomersTable/CustomersTable.tsx
+++ b/apps/carbon/app/modules/sales/interfaces/Customers/CustomersTable/CustomersTable.tsx
@@ -86,7 +86,7 @@ const CustomersTable = memo(({ data, count }: CustomersTableProps) => {
navigate(`/x/sales/customers/${row.id}?${params.toString()}`)
}
>
- Edit Customer
+ View Customer
</MenuItem>
),
[navigate, params]
diff --git a/apps/carbon/app/modules/users/interfaces/Customers/CreateCustomerModal/CreateCustomerModal.tsx b/apps/carbon/app/modules/users/interfaces/Customers/CreateCustomerModal/CreateCustomerModal.tsx
index c37f037f0d..852ba1cc0d 100644
--- a/apps/carbon/app/modules/users/interfaces/Customers/CreateCustomerModal/CreateCustomerModal.tsx
+++ b/apps/carbon/app/modules/users/interfaces/Customers/CreateCustomerModal/CreateCustomerModal.tsx
@@ -50,7 +50,11 @@ const CreateCustomerModal = () => {
<ModalBody pb={6}>
<ValidatedForm
method="post"
- action="/x/users/customers/new"
+ action={`/x/users/customers/new${
+ params.get("customer")
+ ? `?customer=${params.get("customer")}`
+ : ""
+ }`}
validator={createCustomerAccountValidator}
defaultValues={{
id: params.get("id") ?? "",
diff --git a/apps/carbon/app/modules/users/interfaces/Suppliers/CreateSupplierModal/CreateSupplierModal.tsx b/apps/carbon/app/modules/users/interfaces/Suppliers/CreateSupplierModal/CreateSupplierModal.tsx
index afd3d7c009..d7c15a65ed 100644
--- a/apps/carbon/app/modules/users/interfaces/Suppliers/CreateSupplierModal/CreateSupplierModal.tsx
+++ b/apps/carbon/app/modules/users/interfaces/Suppliers/CreateSupplierModal/CreateSupplierModal.tsx
@@ -50,7 +50,11 @@ const CreateSupplierModal = () => {
<ModalBody pb={6}>
<ValidatedForm
method="post"
- action="/x/users/suppliers/new"
+ action={`/x/users/suppliers/new${
+ params.get("supplier")
+ ? `?supplier=${params.get("supplier")}`
+ : ""
+ }`}
validator={createSupplierAccountValidator}
defaultValues={{
id: params.get("id") ?? "",
diff --git a/apps/carbon/app/routes/x+/parts+/search.tsx b/apps/carbon/app/routes/x+/parts+/search.tsx
index 648de0c967..6570fbbfac 100644
--- a/apps/carbon/app/routes/x+/parts+/search.tsx
+++ b/apps/carbon/app/routes/x+/parts+/search.tsx
@@ -25,12 +25,22 @@ export async function loader({ request }: LoaderArgs) {
const search = searchParams.get("search");
const type = searchParams.get("type");
const group = searchParams.get("group");
+ const supplierId = searchParams.get("supplierId");
const { limit, offset, sorts, filters } =
getGenericQueryFilters(searchParams);
const [parts, partTypes, partGroups] = await Promise.all([
- getParts(client, { search, type, group, limit, offset, sorts, filters }),
+ getParts(client, {
+ search,
+ type,
+ group,
+ supplierId,
+ limit,
+ offset,
+ sorts,
+ filters,
+ }),
getPartTypes(),
getPartGroupsList(client),
]);
diff --git a/apps/carbon/app/routes/x+/purchasing+/orders.tsx b/apps/carbon/app/routes/x+/purchasing+/orders.tsx
index e5d2286ab8..8a9b8baaea 100644
--- a/apps/carbon/app/routes/x+/purchasing+/orders.tsx
+++ b/apps/carbon/app/routes/x+/purchasing+/orders.tsx
@@ -7,6 +7,7 @@ import {
PurchaseOrdersTable,
PurchaseOrdersTableFilters,
getPurchaseOrders,
+ getPurchaseOrderSuppliers,
} from "~/modules/purchasing";
import { requirePermissions } from "~/services/auth";
import { flash } from "~/services/session";
@@ -27,7 +28,7 @@ export async function loader({ request }: LoaderArgs) {
const { limit, offset, sorts, filters } =
getGenericQueryFilters(searchParams);
- const [purchasOrders] = await Promise.all([
+ const [purchasOrders, suppliers] = await Promise.all([
getPurchaseOrders(client, {
search,
status,
@@ -37,6 +38,7 @@ export async function loader({ request }: LoaderArgs) {
sorts,
filters,
}),
+ getPurchaseOrderSuppliers(client),
]);
if (purchasOrders.error) {
@@ -52,15 +54,16 @@ export async function loader({ request }: LoaderArgs) {
return json({
count: purchasOrders.count ?? 0,
purchasOrders: purchasOrders.data ?? [],
+ suppliers: suppliers.data ?? [],
});
}
export default function PurchaseOrdersSearchRoute() {
- const { count, purchasOrders } = useLoaderData<typeof loader>();
+ const { count, purchasOrders, suppliers } = useLoaderData<typeof loader>();
return (
<VStack w="full" h="full" spacing={0}>
- <PurchaseOrdersTableFilters />
+ <PurchaseOrdersTableFilters suppliers={suppliers} />
<PurchaseOrdersTable data={purchasOrders} count={count} />
<Outlet />
</VStack>
diff --git a/apps/carbon/app/routes/x+/users+/suppliers.new.tsx b/apps/carbon/app/routes/x+/users+/suppliers.new.tsx
index c04a7e6a88..6135389339 100644
--- a/apps/carbon/app/routes/x+/users+/suppliers.new.tsx
+++ b/apps/carbon/app/routes/x+/users+/suppliers.new.tsx
@@ -24,12 +24,23 @@ export async function action({ request }: ActionArgs) {
return validationError(validation.error);
}
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ const supplierRedirect = searchParams.get("supplier");
+
const { id, supplier } = validation.data;
const result = await createSupplierAccount(client, {
id,
supplierId: supplier,
});
+ if (supplierRedirect) {
+ return redirect(
+ `/x/purchasing/suppliers/${supplierRedirect}`,
+ await flash(request, result)
+ );
+ }
+
return redirect("/x/users/suppliers", await flash(request, result));
}
diff --git a/packages/carbon-database/src/types.ts b/packages/carbon-database/src/types.ts
index 4fd35ff647..a51084f63a 100644
--- a/packages/carbon-database/src/types.ts
+++ b/packages/carbon-database/src/types.ts
@@ -2603,6 +2603,27 @@ export interface Database {
abilityIds: string[] | null;
};
};
+ parts_view: {
+ Row: {
+ id: string | null;
+ name: string | null;
+ description: string | null;
+ partType: Database["public"]["Enums"]["partType"] | null;
+ partGroupId: string | null;
+ partGroup: string | null;
+ replenishmentSystem:
+ | Database["public"]["Enums"]["partReplenishmentSystem"]
+ | null;
+ active: boolean | null;
+ supplierIds: string[] | null;
+ };
+ };
+ purchase_order_suppliers_view: {
+ Row: {
+ id: string | null;
+ name: string | null;
+ };
+ };
purchase_order_view: {
Row: {
id: string | null;
@@ -2637,6 +2658,18 @@ export interface Database {
favorite: boolean | null;
};
};
+ suppliers_view: {
+ Row: {
+ id: string | null;
+ name: string | null;
+ supplierTypeId: string | null;
+ type: string | null;
+ supplierStatusId: string | null;
+ status: string | null;
+ orderCount: number | null;
+ partCount: number | null;
+ };
+ };
};
Functions: {
_xid_machine_id: {
diff --git a/packages/carbon-database/supabase/migrations/20230510035345_purchasing.sql b/packages/carbon-database/supabase/migrations/20230510035345_purchasing.sql
index aff0084df8..9f2ce556ce 100644
--- a/packages/carbon-database/supabase/migrations/20230510035345_purchasing.sql
+++ b/packages/carbon-database/supabase/migrations/20230510035345_purchasing.sql
@@ -352,3 +352,10 @@ ALTER TABLE "supplier"
ADD CONSTRAINT "supplier_defaultShippingMethodId_fkey" FOREIGN KEY ("defaultShippingMethodId") REFERENCES "shippingMethod" ("id") ON DELETE SET NULL,
ADD CONSTRAINT "supplier_defaultShippingTermId_fkey" FOREIGN KEY ("defaultShippingTermId") REFERENCES "shippingTerm" ("id") ON DELETE SET NULL;
+CREATE VIEW "purchase_order_suppliers_view" AS
+ SELECT DISTINCT
+ s."id",
+ s."name"
+ FROM "supplier" s
+ INNER JOIN "purchaseOrder" p ON p."supplierId" = s."id";
+
diff --git a/packages/carbon-database/supabase/migrations/20230702114301_purchasing-rls.sql b/packages/carbon-database/supabase/migrations/20230702114301_purchasing-rls.sql
index 26d219474c..66bbf8e4c7 100644
--- a/packages/carbon-database/supabase/migrations/20230702114301_purchasing-rls.sql
+++ b/packages/carbon-database/supabase/migrations/20230702114301_purchasing-rls.sql
@@ -4,7 +4,7 @@ CREATE POLICY "Employees with purchasing_view can view purchase orders" ON "purc
FOR SELECT
USING (coalesce(get_my_claim('purchasing_view')::boolean, false) = true AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
-CREATE POLICY "Suppliers with purchasing_view can their own organization" ON "purchaseOrder"
+CREATE POLICY "Suppliers with purchasing_view can their own purchase orders" ON "purchaseOrder"
FOR SELECT
USING (
coalesce(get_my_claim('purchasing_view')::boolean, false) = true
@@ -81,4 +81,150 @@ CREATE POLICY "Suppliers with purchasing_view can search for their own purchase
)
)
)
- );
\ No newline at end of file
+ );
+
+-- Purchase Order Lines
+
+ALTER TABLE "purchaseOrderLine" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "Employees with purchasing_view can view purchase order lines" ON "purchaseOrderLine"
+ FOR SELECT
+ USING (coalesce(get_my_claim('purchasing_view')::boolean, false) = true AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
+
+CREATE POLICY "Suppliers with purchasing_view can their own purchase order lines" ON "purchaseOrderLine"
+ FOR SELECT
+ USING (
+ coalesce(get_my_claim('purchasing_view')::boolean, false) = true
+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonb
+ AND "purchaseOrderId" IN (
+ SELECT id FROM "purchaseOrder" WHERE "supplierId" IN (
+ SELECT "supplierId" FROM "purchaseOrder" WHERE "supplierId" IN (
+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
+ )
+ )
+ )
+ );
+
+CREATE POLICY "Employees with purchasing_create can create purchase order lines" ON "purchaseOrderLine"
+ FOR INSERT
+ WITH CHECK (coalesce(get_my_claim('purchasing_create')::boolean,false) AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
+
+CREATE POLICY "Suppliers with purchasing_create can create lines on their own purchase order" ON "purchaseOrderLine"
+ FOR INSERT
+ WITH CHECK (
+ coalesce(get_my_claim('purchasing_create')::boolean, false) = true
+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonb
+ AND "purchaseOrderId" IN (
+ SELECT id FROM "purchaseOrder" WHERE "supplierId" IN (
+ SELECT "supplierId" FROM "purchaseOrder" WHERE "supplierId" IN (
+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
+ )
+ )
+ )
+ );
+
+CREATE POLICY "Employees with purchasing_update can update purchase order lines" ON "purchaseOrderLine"
+ FOR UPDATE
+ USING (coalesce(get_my_claim('purchasing_update')::boolean,false) AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
+
+CREATE POLICY "Suppliers with purchasing_update can their own purchase order lines" ON "purchaseOrderLine"
+ FOR UPDATE
+ USING (
+ coalesce(get_my_claim('purchasing_update')::boolean, false) = true
+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonb
+ AND "purchaseOrderId" IN (
+ SELECT id FROM "purchaseOrder" WHERE "supplierId" IN (
+ SELECT "supplierId" FROM "purchaseOrder" WHERE "supplierId" IN (
+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
+ )
+ )
+ )
+ );
+
+CREATE POLICY "Employees with purchasing_delete can delete purchase order lines" ON "purchaseOrderLine"
+ FOR DELETE
+ USING (coalesce(get_my_claim('purchasing_delete')::boolean, false) = true AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
+
+CREATE POLICY "Suppliers with purchasing_delete can delete lines on their own purchase order" ON "purchaseOrderLine"
+ FOR DELETE
+ USING (
+ coalesce(get_my_claim('purchasing_delete')::boolean, false) = true
+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonb
+ AND "purchaseOrderId" IN (
+ SELECT id FROM "purchaseOrder" WHERE "supplierId" IN (
+ SELECT "supplierId" FROM "purchaseOrder" WHERE "supplierId" IN (
+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
+ )
+ )
+ )
+ );
+
+
+-- Purchase Order Deliveries
+
+ALTER TABLE "purchaseOrderDelivery" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "Employees with purchasing_view can view purchase order deliveries" ON "purchaseOrderDelivery"
+ FOR SELECT
+ USING (coalesce(get_my_claim('purchasing_view')::boolean, false) = true AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
+
+CREATE POLICY "Suppliers with purchasing_view can their own purchase order deliveries" ON "purchaseOrderDelivery"
+ FOR SELECT
+ USING (
+ coalesce(get_my_claim('purchasing_view')::boolean, false) = true
+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonb
+ AND id IN (
+ SELECT id FROM "purchaseOrder" WHERE "supplierId" IN (
+ SELECT "supplierId" FROM "purchaseOrder" WHERE "supplierId" IN (
+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
+ )
+ )
+ )
+ );
+
+CREATE POLICY "Employees with purchasing_create can create purchase order deliveries" ON "purchaseOrderDelivery"
+ FOR INSERT
+ WITH CHECK (coalesce(get_my_claim('purchasing_create')::boolean,false) AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
+
+CREATE POLICY "Employees with purchasing_update can update purchase order deliveries" ON "purchaseOrderDelivery"
+ FOR UPDATE
+ USING (coalesce(get_my_claim('purchasing_update')::boolean,false) AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
+
+CREATE POLICY "Suppliers with purchasing_update can their own purchase order deliveries" ON "purchaseOrderDelivery"
+ FOR UPDATE
+ USING (
+ coalesce(get_my_claim('purchasing_update')::boolean, false) = true
+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonb
+ AND id IN (
+ SELECT id FROM "purchaseOrder" WHERE "supplierId" IN (
+ SELECT "supplierId" FROM "purchaseOrder" WHERE "supplierId" IN (
+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
+ )
+ )
+ )
+ );
+
+CREATE POLICY "Employees with purchasing_delete can delete purchase order deliveries" ON "purchaseOrderDelivery"
+ FOR DELETE
+ USING (coalesce(get_my_claim('purchasing_delete')::boolean, false) = true AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
+
+
+-- Purchase Order Payments
+
+ALTER TABLE "purchaseOrderPayment" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "Employees with purchasing_view can view purchase order payments" ON "purchaseOrderPayment"
+ FOR SELECT
+ USING (coalesce(get_my_claim('purchasing_view')::boolean, false) = true AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
+
+CREATE POLICY "Employees with purchasing_create can create purchase order payments" ON "purchaseOrderPayment"
+ FOR INSERT
+ WITH CHECK (coalesce(get_my_claim('purchasing_create')::boolean,false) AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
+
+CREATE POLICY "Employees with purchasing_update can update purchase order payments" ON "purchaseOrderPayment"
+ FOR UPDATE
+ USING (coalesce(get_my_claim('purchasing_update')::boolean,false) AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
+
+CREATE POLICY "Employees with purchasing_delete can delete purchase order payments" ON "purchaseOrderPayment"
+ FOR DELETE
+ USING (coalesce(get_my_claim('purchasing_delete')::boolean, false) = true AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
diff --git a/packages/carbon-database/supabase/migrations/20230704160029_supplier-view.sql b/packages/carbon-database/supabase/migrations/20230704160029_supplier-view.sql
new file mode 100644
index 0000000000..5fe4c4ee35
--- /dev/null
+++ b/packages/carbon-database/supabase/migrations/20230704160029_supplier-view.sql
@@ -0,0 +1,27 @@
+CREATE VIEW "suppliers_view" AS
+ SELECT
+ s.id,
+ s.name,
+ s."supplierTypeId",
+ st.name AS "type",
+ s."supplierStatusId",
+ ss.name AS "status",
+ po.count AS "orderCount",
+ p.count AS "partCount"
+ FROM "supplier" s
+ LEFT JOIN "supplierType" st ON st.id = s."supplierTypeId"
+ LEFT JOIN "supplierStatus" ss ON ss.id = s."supplierStatusId"
+ LEFT JOIN (
+ SELECT
+ "supplierId",
+ COUNT(*) AS "count"
+ FROM "purchaseOrder"
+ GROUP BY "supplierId"
+ ) po ON po."supplierId" = s.id
+ LEFT JOIN (
+ SELECT
+ "supplierId",
+ COUNT(*) AS "count"
+ FROM "partSupplier"
+ GROUP BY "supplierId"
+ ) p ON p."supplierId" = s.id;
\ No newline at end of file
diff --git a/packages/carbon-database/supabase/migrations/20230704161623_parts-view.sql b/packages/carbon-database/supabase/migrations/20230704161623_parts-view.sql
new file mode 100644
index 0000000000..1e88e99fa4
--- /dev/null
+++ b/packages/carbon-database/supabase/migrations/20230704161623_parts-view.sql
@@ -0,0 +1,23 @@
+CREATE VIEW "parts_view" AS
+ SELECT
+ p.id,
+ p.name,
+ p.description,
+ p."partType",
+ p."partGroupId",
+ pg.name AS "partGroup",
+ p."replenishmentSystem",
+ p.active,
+ array_agg(ps."supplierId") AS "supplierIds"
+ FROM "part" p
+ LEFT JOIN "partGroup" pg ON pg.id = p."partGroupId"
+ LEFT JOIN "partSupplier" ps ON ps."partId" = p.id
+ GROUP BY p.id,
+ p.name,
+ p.description,
+ p."partType",
+ p."partGroupId",
+ pg.name,
+ p."replenishmentSystem",
+ p.active;
+
diff --git a/packages/carbon-database/supabase/migrations/20230702105831_view-rls.sql b/packages/carbon-database/supabase/migrations/20230704175831_view-rls.sql
similarity index 66%
rename from packages/carbon-database/supabase/migrations/20230702105831_view-rls.sql
rename to packages/carbon-database/supabase/migrations/20230704175831_view-rls.sql
index 8428052f46..e0f5b063be 100644
--- a/packages/carbon-database/supabase/migrations/20230702105831_view-rls.sql
+++ b/packages/carbon-database/supabase/migrations/20230704175831_view-rls.sql
@@ -3,4 +3,7 @@
-- ALTER VIEW "partners_view" SET (security_invoker = on);
-- ALTER VIEW "documents_labels_view" SET (security_invoker = on);
-- ALTER VIEW "documents_view" SET (security_invoker = on);
--- ALTER VIEW "purchase_order_view" SET (security_invoker = on);
\ No newline at end of file
+-- ALTER VIEW "purchase_order_view" SET (security_invoker = on);
+-- ALTER VIEW "purchase_order_suppliers_view" SET (security_invoker = on);
+-- ALTER VIEW "suppliers_view" SET (security_invoker = on);
+-- ALTER VIEW "parts_view" SET (security_invoker = on);
\ No newline at end of file