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.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat: add serviceSupplier table and data fetching methods for services
Brad Barbinac4198208c52
diff --git a/apps/carbon/app/modules/parts/parts.models.ts b/apps/carbon/app/modules/parts/parts.models.tsindex b186f7c687..36ebe67001 100644--- a/apps/carbon/app/modules/parts/parts.models.ts+++ b/apps/carbon/app/modules/parts/parts.models.ts@@ -26,6 +26,8 @@ export const partManufacturingPolicies = ["Make to Order",] as const;+export const serviceType = ["Internal", "External"] as const;+export const partValidator = withZod(z.object({id: z.string().min(1, { message: "Part ID is required" }).max(255),diff --git a/apps/carbon/app/modules/parts/parts.service.ts b/apps/carbon/app/modules/parts/parts.service.tsindex 064eb96c17..349dbca318 100644--- a/apps/carbon/app/modules/parts/parts.service.ts+++ b/apps/carbon/app/modules/parts/parts.service.ts@@ -15,7 +15,7 @@ import type {partUnitSalePriceValidator,partValidator,} from "./parts.models";-import type { PartReplenishmentSystem } from "./types";+import type { PartReplenishmentSystem, ServiceType } from "./types";export async function deletePartGroup(client: SupabaseClient<Database>,@@ -224,8 +224,94 @@ export async function getPartUnitSalePrice(return client.from("partUnitSalePrice").select("*").eq("partId", id).single();}-export function getPartCostingMethods(): Database["public"]["Enums"]["partCostingMethod"][] {- return ["Standard", "Average", "FIFO", "LIFO"];+export async function getServices(+ client: SupabaseClient<Database>,+ args: GenericQueryFilters & {+ search: string | null;+ type: string | null;+ group: string | null;+ supplierId: string | null;+ }+) {+ let query = client.from("services").select("*", {+ count: "exact",+ });++ if (args.search) {+ query = query.or(+ `name.ilike.%${args.search}%,description.ilike.%${args.search}%`+ );+ }++ if (args.type) {+ query = query.eq("serviceType", args.type);+ }++ if (args.group) {+ query = query.eq("serviceGroupId", args.group);+ }++ if (args.supplierId) {+ query = query.contains("supplierIds", [args.supplierId]);+ }++ query = setGenericQueryFilters(query, args, "id");+ return query;+}++export async function getServicesList(+ client: SupabaseClient<Database>,+ type: ServiceType | null+) {+ let query = client+ .from("service")+ .select("id, name")+ .eq("blocked", false)+ .eq("active", true);++ if (type) {+ query = query.eq("serviceType", type);+ }++ return query;+}++export async function getServiceGroups(+ client: SupabaseClient<Database>,+ args?: GenericQueryFilters & { name: string | null }+) {+ let query = client.from("serviceGroup").select("*", {+ count: "exact",+ });++ if (args?.name) {+ query = query.ilike("name", `%${args.name}%`);+ }++ if (args) {+ query = setGenericQueryFilters(query, args, "name");+ }++ return query;+}++export async function getServiceGroupsList(+ client: SupabaseClient<Database>,+ args?: GenericQueryFilters & { name: string | null }+) {+ let query = client+ .from("serviceGroup")+ .select("id, name", { count: "exact" });++ if (args?.name) {+ query = query.ilike("name", `%${args.name}%`);+ }++ if (args) {+ query = setGenericQueryFilters(query, args, "name");+ }++ return query;}export async function getShelvesList(diff --git a/apps/carbon/app/modules/parts/types.ts b/apps/carbon/app/modules/parts/types.tsindex 64946df9bd..b2f18544cd 100644--- a/apps/carbon/app/modules/parts/types.ts+++ b/apps/carbon/app/modules/parts/types.ts@@ -53,6 +53,8 @@ export type PartsTableRow = NonNullable<export type PartType = Database["public"]["Enums"]["partType"];+export type ServiceType = Database["public"]["Enums"]["serviceType"];+export type UnitOfMeasure = NonNullable<Awaited<ReturnType<typeof getUnitOfMeasure>>["data"]>;diff --git a/apps/carbon/app/routes/x+/part+/_layout.tsx b/apps/carbon/app/routes/x+/part+/_layout.tsxindex 5429020cd6..66dc41fd38 100644--- a/apps/carbon/app/routes/x+/part+/_layout.tsx+++ b/apps/carbon/app/routes/x+/part+/_layout.tsx@@ -1,11 +1,7 @@import { VStack } from "@chakra-ui/react";import type { LoaderFunctionArgs, MetaFunction } from "@remix-run/node";import { Outlet } from "@remix-run/react";-import {- getPartCostingMethods,- getPartGroupsList,- getUnitOfMeasuresList,-} from "~/modules/parts";+import { getPartGroupsList, getUnitOfMeasuresList } from "~/modules/parts";import { getLocationsList } from "~/modules/resources";import { requirePermissions } from "~/services/auth";import type { Handle } from "~/utils/handle";@@ -34,7 +30,6 @@ export async function loader({ request }: LoaderFunctionArgs) {return {locations: locations?.data ?? [],- partCostingMethods: getPartCostingMethods(),partGroups: partGroups?.data ?? [],unitOfMeasures: unitOfMeasures?.data ?? [],};diff --git a/apps/carbon/app/routes/x+/parts+/services.tsx b/apps/carbon/app/routes/x+/parts+/services.tsxnew file mode 100644index 0000000000..4d63415f43--- /dev/null+++ b/apps/carbon/app/routes/x+/parts+/services.tsx@@ -0,0 +1,70 @@+import { VStack } from "@chakra-ui/react";+import type { LoaderFunctionArgs } from "@remix-run/node";+import { json, redirect } from "@remix-run/node";+import { Outlet, useLoaderData } from "@remix-run/react";+import {+ ServicesTable,+ ServicesTableFilters,+ getServiceGroupsList,+ getServices,+} from "~/modules/parts";+import { requirePermissions } from "~/services/auth";+import { flash } from "~/services/session";+import { path } from "~/utils/path";+import { getGenericQueryFilters } from "~/utils/query";+import { error } from "~/utils/result";++export async function loader({ request }: LoaderFunctionArgs) {+ const { client } = await requirePermissions(request, {+ view: "parts",+ });++ const url = new URL(request.url);+ const searchParams = new URLSearchParams(url.search);+ 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 [services, serviceGroups] = await Promise.all([+ getServices(client, {+ search,+ type,+ group,+ supplierId,+ limit,+ offset,+ sorts,+ filters,+ }),+ getServiceGroupsList(client),+ ]);++ if (services.error) {+ redirect(+ path.to.parts,+ await flash(request, error(services.error, "Failed to fetch services"))+ );+ }++ return json({+ count: services.count ?? 0,+ services: services.data ?? [],+ serviceGroups: serviceGroups.data ?? [],+ });+}++export default function ServicesSearchRoute() {+ const { count, services, serviceGroups } = useLoaderData<typeof loader>();++ return (+ <VStack w="full" h="full" spacing={0}>+ <ServicesTableFilters serviceGroups={serviceGroups} />+ <ServicesTable data={services} count={count} />+ <Outlet />+ </VStack>+ );+}diff --git a/packages/database/SCHEMA.md b/packages/database/SCHEMA.mdindex 943fdf1de9..9ed75257fe 100644--- a/packages/database/SCHEMA.md+++ b/packages/database/SCHEMA.md@@ -3601,7 +3601,7 @@ CREATE POLICY "Employees with parts_delete can delete part suppliers" ON "partSuAND (get_my_claim('role'::text)) = '"employee"'::jsonb);-CREATE POLICY "Suppliers with parts can view their own part suppliers" ON "partSupplier"+CREATE POLICY "Suppliers with parts_view can view their own part suppliers" ON "partSupplier"FOR SELECTUSING (coalesce(get_my_claim('parts_view')::boolean,false)@@ -3621,15 +3621,6 @@ CREATE POLICY "Suppliers with parts_update can update their own part suppliers"));-CREATE POLICY "Suppliers with parts_create can create part suppliers" ON "partSupplier"- FOR INSERT- WITH CHECK (- coalesce(get_my_claim('parts_create')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"supplier"'::jsonb- AND "supplierId" IN (- SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()- )- );CREATE TABLE "partReplenishment" ("partId" TEXT NOT NULL,@@ -7119,5 +7110,100 @@ CREATE POLICY "Employees with parts_delete can delete services" ON "service"coalesce(get_my_claim('parts_delete')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);+++CREATE TABLE "serviceSupplier" (+ "id" TEXT NOT NULL DEFAULT xid(),+ "serviceId" TEXT NOT NULL,+ "supplierId" TEXT NOT NULL,+ "supplierServiceId" TEXT,+ "active" BOOLEAN NOT NULL DEFAULT true,+ "createdBy" TEXT NOT NULL,+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "updatedBy" TEXT,+ "updatedAt" TIMESTAMP WITH TIME ZONE,++ CONSTRAINT "serviceSupplier_id_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "serviceSupplier_serviceId_fkey" FOREIGN KEY ("serviceId") REFERENCES "service"("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "serviceSupplier_supplierId_fkey" FOREIGN KEY ("supplierId") REFERENCES "supplier"("id") ON DELETE CASCADE,+ CONSTRAINT "serviceSupplier_service_supplier_unique" UNIQUE ("serviceId", "supplierId"),+ CONSTRAINT "serviceSupplier_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),+ CONSTRAINT "serviceSupplier_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")+);++CREATE INDEX "serviceSupplier_serviceId_index" ON "serviceSupplier"("serviceId");++ALTER TABLE "serviceSupplier" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Employees with part_view can view service suppliers" ON "serviceSupplier"+ FOR SELECT+ USING (+ coalesce(get_my_claim('parts_view')::boolean,false)+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with parts_update can update service suppliers" ON "serviceSupplier"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('parts_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with parts_create can create service suppliers" ON "serviceSupplier"+ FOR INSERT+ WITH CHECK (+ coalesce(get_my_claim('parts_create')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with parts_delete can delete service suppliers" ON "serviceSupplier"+ FOR DELETE+ USING (+ coalesce(get_my_claim('parts_delete')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Suppliers with parts_view can view their own part suppliers" ON "partSupplier"+ FOR SELECT+ USING (+ coalesce(get_my_claim('parts_view')::boolean,false)+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonb+ AND "serviceTypeId" = 'External'+ AND "supplierId" IN (+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()+ )+ );++CREATE POLICY "Suppliers with parts_update can update their own part suppliers" ON "partSupplier"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('parts_update')::boolean,false)+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonb+ AND "serviceTypeId" = 'External'+ AND "supplierId" IN (+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()+ )+ );++CREATE OR REPLACE VIEW "view" WITH(SECURITY_INVOKER=true) AS+ SELECT+ s.id,+ s.name,+ s.description,+ s."serviceType",+ s."serviceGroupId",+ sg.name AS "serviceGroup",+ s.active,+ array_agg(ps."supplierId") AS "supplierIds"+ FROM "supplier" s+ LEFT JOIN "serviceGroup" sg ON sg.id = s."serviceGroupId"+ LEFT JOIN "serviceSupplier" ss ON ss."serviceId" = s.id+ GROUP BY s.id,+ s.name,+ s.description,+ s."serviceType",+ s."serviceGroupId",+ sg.name,+ s.active;```diff --git a/packages/database/supabase/migrations/20230330024716_parts.sql b/packages/database/supabase/migrations/20230330024716_parts.sqlindex 4faadebd3d..9c26782990 100644--- a/packages/database/supabase/migrations/20230330024716_parts.sql+++ b/packages/database/supabase/migrations/20230330024716_parts.sql@@ -367,7 +367,7 @@ CREATE POLICY "Employees with parts_delete can delete part suppliers" ON "partSuAND (get_my_claim('role'::text)) = '"employee"'::jsonb);-CREATE POLICY "Suppliers with parts can view their own part suppliers" ON "partSupplier"+CREATE POLICY "Suppliers with parts_view can view their own part suppliers" ON "partSupplier"FOR SELECTUSING (coalesce(get_my_claim('parts_view')::boolean,false)@@ -387,15 +387,6 @@ CREATE POLICY "Suppliers with parts_update can update their own part suppliers"));-CREATE POLICY "Suppliers with parts_create can create part suppliers" ON "partSupplier"- FOR INSERT- WITH CHECK (- coalesce(get_my_claim('parts_create')::boolean, false) = true- AND (get_my_claim('role'::text)) = '"supplier"'::jsonb- AND "supplierId" IN (- SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()- )- );CREATE TABLE "partReplenishment" ("partId" TEXT NOT NULL,diff --git a/packages/database/supabase/migrations/20231212120726_services.sql b/packages/database/supabase/migrations/20231212120726_services.sqlindex 36568e776b..eb0f04c8dd 100644--- a/packages/database/supabase/migrations/20231212120726_services.sql+++ b/packages/database/supabase/migrations/20231212120726_services.sql@@ -99,4 +99,99 @@ CREATE POLICY "Employees with parts_delete can delete services" ON "service"USING (coalesce(get_my_claim('parts_delete')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb- );\ No newline at end of file+ );+++CREATE TABLE "serviceSupplier" (+ "id" TEXT NOT NULL DEFAULT xid(),+ "serviceId" TEXT NOT NULL,+ "supplierId" TEXT NOT NULL,+ "supplierServiceId" TEXT,+ "active" BOOLEAN NOT NULL DEFAULT true,+ "createdBy" TEXT NOT NULL,+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "updatedBy" TEXT,+ "updatedAt" TIMESTAMP WITH TIME ZONE,++ CONSTRAINT "serviceSupplier_id_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "serviceSupplier_serviceId_fkey" FOREIGN KEY ("serviceId") REFERENCES "service"("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "serviceSupplier_supplierId_fkey" FOREIGN KEY ("supplierId") REFERENCES "supplier"("id") ON DELETE CASCADE,+ CONSTRAINT "serviceSupplier_service_supplier_unique" UNIQUE ("serviceId", "supplierId"),+ CONSTRAINT "serviceSupplier_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),+ CONSTRAINT "serviceSupplier_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")+);++CREATE INDEX "serviceSupplier_serviceId_index" ON "serviceSupplier"("serviceId");++ALTER TABLE "serviceSupplier" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Employees with part_view can view service suppliers" ON "serviceSupplier"+ FOR SELECT+ USING (+ coalesce(get_my_claim('parts_view')::boolean,false)+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with parts_update can update service suppliers" ON "serviceSupplier"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('parts_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with parts_create can create service suppliers" ON "serviceSupplier"+ FOR INSERT+ WITH CHECK (+ coalesce(get_my_claim('parts_create')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with parts_delete can delete service suppliers" ON "serviceSupplier"+ FOR DELETE+ USING (+ coalesce(get_my_claim('parts_delete')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Suppliers with parts_view can view their own part suppliers" ON "partSupplier"+ FOR SELECT+ USING (+ coalesce(get_my_claim('parts_view')::boolean,false)+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonb+ AND "serviceTypeId" = 'External'+ AND "supplierId" IN (+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()+ )+ );++CREATE POLICY "Suppliers with parts_update can update their own part suppliers" ON "partSupplier"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('parts_update')::boolean,false)+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonb+ AND "serviceTypeId" = 'External'+ AND "supplierId" IN (+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()+ )+ );++CREATE OR REPLACE VIEW "view" WITH(SECURITY_INVOKER=true) AS+ SELECT+ s.id,+ s.name,+ s.description,+ s."serviceType",+ s."serviceGroupId",+ sg.name AS "serviceGroup",+ s.active,+ array_agg(ps."supplierId") AS "supplierIds"+ FROM "supplier" s+ LEFT JOIN "serviceGroup" sg ON sg.id = s."serviceGroupId"+ LEFT JOIN "serviceSupplier" ss ON ss."serviceId" = s.id+ GROUP BY s.id,+ s.name,+ s.description,+ s."serviceType",+ s."serviceGroupId",+ sg.name,+ s.active;\ No newline at end of file