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 ui for service crud
Brad Barbin85f8678dfb37
diff --git a/apps/carbon/app/modules/parts/parts.models.ts b/apps/carbon/app/modules/parts/parts.models.tsindex 36ebe67001..2ce559b017 100644--- a/apps/carbon/app/modules/parts/parts.models.ts+++ b/apps/carbon/app/modules/parts/parts.models.ts@@ -160,6 +160,30 @@ export const partUnitSalePriceValidator = withZod(}));+export const serviceValidator = withZod(+ z.object({+ id: zfd.text(z.string().optional()),+ name: z.string().min(1, { message: "Name is required" }).max(255),+ description: z.string().optional(),+ serviceType: z.enum(serviceType, {+ errorMap: (issue, ctx) => ({+ message: "Service type is required",+ }),+ }),+ blocked: zfd.checkbox(),+ active: zfd.checkbox(),+ })+);++export const serviceSupplierValidator = withZod(+ z.object({+ id: zfd.text(z.string().optional()),+ serviceId: z.string().min(1, { message: "Part ID is required" }),+ supplierId: z.string().min(36, { message: "Supplier ID is required" }),+ supplierServiceId: z.string().optional(),+ })+);+export const unitOfMeasureValidator = withZod(z.object({id: zfd.text(z.string().optional()),diff --git a/apps/carbon/app/modules/parts/parts.service.ts b/apps/carbon/app/modules/parts/parts.service.tsindex 349dbca318..1c145fbba4 100644--- a/apps/carbon/app/modules/parts/parts.service.ts+++ b/apps/carbon/app/modules/parts/parts.service.ts@@ -14,6 +14,8 @@ import type {partSupplierValidator,partUnitSalePriceValidator,partValidator,+ serviceSupplierValidator,+ serviceValidator,} from "./parts.models";import type { PartReplenishmentSystem, ServiceType } from "./types";@@ -259,6 +261,10 @@ export async function getServices(return query;}+export async function getService(client: SupabaseClient<Database>, id: string) {+ return client.from("services").select("*").eq("id", id).single();+}+export async function getServicesList(client: SupabaseClient<Database>,type: ServiceType | null@@ -314,6 +320,17 @@ export async function getServiceGroupsList(return query;}+export async function getServiceSuppliers(+ client: SupabaseClient<Database>,+ id: string+) {+ return client+ .from("serviceSupplier")+ .select(`id, supplier(id, name), supplierServiceId`)+ .eq("active", true)+ .eq("serviceId", id);+}+export async function getShelvesList(client: SupabaseClient<Database>,locationId: string@@ -543,6 +560,47 @@ export async function upsertPartUnitSalePrice(.eq("partId", partUnitSalePrice.partId);}+export async function upsertService(+ client: SupabaseClient<Database>,+ service:+ | (TypeOfValidator<typeof serviceValidator> & { createdBy: string })+ | (Omit<TypeOfValidator<typeof serviceValidator>, "id"> & {+ id: string;+ updatedBy: string;+ })+) {+ if ("createdBy" in service) {+ return client.from("service").insert(service).select("id").single();+ }+ return client.from("service").update(sanitize(service)).eq("id", service.id);+}++export async function upsertServiceSupplier(+ client: SupabaseClient<Database>,+ serviceSupplier:+ | (Omit<TypeOfValidator<typeof serviceSupplierValidator>, "id"> & {+ createdBy: string;+ })+ | (Omit<TypeOfValidator<typeof serviceSupplierValidator>, "id"> & {+ id: string;+ updatedBy: string;+ })+) {+ if ("createdBy" in serviceSupplier) {+ return client+ .from("serviceSupplier")+ .insert([serviceSupplier])+ .select("id")+ .single();+ }+ return client+ .from("serviceSupplier")+ .update(sanitize(serviceSupplier))+ .eq("id", serviceSupplier.id)+ .select("id")+ .single();+}+export async function upsertUnitOfMeasure(client: SupabaseClient<Database>,unitOfMeasure:diff --git a/apps/carbon/app/modules/parts/types.ts b/apps/carbon/app/modules/parts/types.tsindex 824720d049..77ba987a09 100644--- a/apps/carbon/app/modules/parts/types.ts+++ b/apps/carbon/app/modules/parts/types.ts@@ -8,6 +8,7 @@ import type {getPartSummary,getPartSuppliers,getServices,+ getServiceSuppliers,getUnitOfMeasure,getUnitOfMeasuresList,} from "./parts.service";@@ -58,6 +59,10 @@ export type Service = NonNullable<Awaited<ReturnType<typeof getServices>>["data"]>[number];+export type ServiceSupplier = NonNullable<+ Awaited<ReturnType<typeof getServiceSuppliers>>["data"]+>[number];+export type ServiceType = Database["public"]["Enums"]["serviceType"];export type UnitOfMeasure = NonNullable<diff --git a/apps/carbon/app/modules/parts/ui/Part/PartForm/PartForm.tsx b/apps/carbon/app/modules/parts/ui/Part/PartForm/PartForm.tsxindex 3d7cf400ae..d02f4f8436 100644--- a/apps/carbon/app/modules/parts/ui/Part/PartForm/PartForm.tsx+++ b/apps/carbon/app/modules/parts/ui/Part/PartForm/PartForm.tsx@@ -20,33 +20,17 @@ import {} from "~/components/Form";import { usePermissions, useRouteData } from "~/hooks";import { useSupabase } from "~/lib/supabase";-import type {- PartGroupListItem,- PartReplenishmentSystem,- PartType,- UnitOfMeasureListItem,-} from "~/modules/parts";+import type { PartGroupListItem, UnitOfMeasureListItem } from "~/modules/parts";import {partReplenishmentSystems,partTypes,partValidator,} from "~/modules/parts";+import type { TypeOfValidator } from "~/types/validators";import { path } from "~/utils/path";-type PartFormValues = {- id?: string;- name: string;- description?: string;- partType?: PartType;- partGroupId?: string;- replenishmentSystem?: PartReplenishmentSystem;- unitOfMeasureCode?: string;- blocked?: boolean;- active?: boolean;-};-type PartFormProps = {- initialValues: PartFormValues;+ initialValues: TypeOfValidator<typeof partValidator>;};const useNextPartIdShortcut = () => {diff --git a/apps/carbon/app/modules/parts/ui/Part/PartSupplierForm/PartSupplierForm.tsx b/apps/carbon/app/modules/parts/ui/Part/PartSupplierForm/PartSupplierForm.tsxindex fcd0bc3585..f64ea05214 100644--- a/apps/carbon/app/modules/parts/ui/Part/PartSupplierForm/PartSupplierForm.tsx+++ b/apps/carbon/app/modules/parts/ui/Part/PartSupplierForm/PartSupplierForm.tsx@@ -74,7 +74,7 @@ const PartSupplierForm = ({ initialValues }: PartSupplierFormProps) => {<DrawerContent><DrawerCloseButton /><DrawerHeader>- {isEditing ? "Edit" : "New"} Purchase Order Line+ {isEditing ? "Edit" : "New"} Part Supplier</DrawerHeader><DrawerBody pb={8}><Hidden name="id" />diff --git a/apps/carbon/app/modules/parts/ui/Part/PartSuppliers/PartSuppliers.tsx b/apps/carbon/app/modules/parts/ui/Part/PartSuppliers/PartSuppliers.tsxindex 02833f65d3..e5ed94a7e4 100644--- a/apps/carbon/app/modules/parts/ui/Part/PartSuppliers/PartSuppliers.tsx+++ b/apps/carbon/app/modules/parts/ui/Part/PartSuppliers/PartSuppliers.tsx@@ -73,7 +73,7 @@ const PartSuppliers = ({ partSuppliers }: PartSuppliersProps) => {},{accessorKey: "supplierPartId",- header: "Part ID",+ header: "Supplier ID",cell: (item) => item.getValue(),},{diff --git a/apps/carbon/app/modules/parts/ui/Service/ServiceForm/ServiceForm.tsx b/apps/carbon/app/modules/parts/ui/Service/ServiceForm/ServiceForm.tsxnew file mode 100644index 0000000000..36dfd0aec3--- /dev/null+++ b/apps/carbon/app/modules/parts/ui/Service/ServiceForm/ServiceForm.tsx@@ -0,0 +1,115 @@+import {+ Card,+ CardBody,+ CardFooter,+ CardHeader,+ Grid,+ Heading,+ Text,+ VStack,+} from "@chakra-ui/react";+import { ValidatedForm } from "remix-validated-form";+import {+ Boolean,+ Hidden,+ Input,+ Select,+ Submit,+ TextArea,+} from "~/components/Form";+import { usePermissions, useRouteData } from "~/hooks";+import { serviceType, serviceValidator } from "~/modules/parts";+import type { ListItem } from "~/types";+import type { TypeOfValidator } from "~/types/validators";+import { path } from "~/utils/path";++type ServiceFormProps = {+ initialValues: TypeOfValidator<typeof serviceValidator>;+};++const ServiceForm = ({ initialValues }: ServiceFormProps) => {+ const sharedData = useRouteData<{+ serviceGroups: ListItem[];+ }>(path.to.serviceRoot);++ const permissions = usePermissions();+ const isEditing = initialValues.id !== undefined;++ const serviceGroupOptions =+ sharedData?.serviceGroups.map((serviceGroup) => ({+ label: serviceGroup.name,+ value: serviceGroup.id,+ })) ?? [];++ const serviceTypeOptions =+ serviceType.map((type) => ({+ label: type,+ value: type,+ })) ?? [];++ return (+ <ValidatedForm+ method="post"+ validator={serviceValidator}+ defaultValues={initialValues}+ >+ <Card w="full">+ <CardHeader>+ <Heading size="md">+ {isEditing ? "Service Details" : "New Service"}+ </Heading>+ {!isEditing && (+ <Text color="gray.500" fontWeight="normal">+ A service is an intangible activity that can be purchased or sold.+ </Text>+ )}+ </CardHeader>+ <CardBody>+ <Hidden name="id" />+ <Grid+ gridTemplateColumns={+ isEditing ? ["1fr", "1fr", "1fr 1fr 1fr"] : "1fr"+ }+ gridColumnGap={8}+ gridRowGap={2}+ w="full"+ >+ <VStack alignItems="start" spacing={2} w="full">+ <Input name="name" label="Name" />+ <TextArea name="description" label="Description" />+ </VStack>+ <VStack alignItems="start" spacing={2} w="full">+ <Select+ name="serviceType"+ label="Service Type"+ options={serviceTypeOptions}+ />+ <Select+ name="serviceGroupId"+ label="Service Group"+ options={serviceGroupOptions}+ />+ </VStack>+ <VStack alignItems="start" spacing={2} w="full">+ <Boolean name="blocked" label="Blocked" />+ {isEditing && <Boolean name="active" label="Active" />}+ </VStack>+ </Grid>+ </CardBody>+ <CardFooter>+ <Submit+ isDisabled={+ isEditing+ ? !permissions.can("update", "parts")+ : !permissions.can("create", "parts")+ }+ >+ Save+ </Submit>+ </CardFooter>+ </Card>+ </ValidatedForm>+ );+};++export default ServiceForm;diff --git a/apps/carbon/app/modules/parts/ui/Service/ServiceForm/index.ts b/apps/carbon/app/modules/parts/ui/Service/ServiceForm/index.tsnew file mode 100644index 0000000000..147b4e46b4--- /dev/null+++ b/apps/carbon/app/modules/parts/ui/Service/ServiceForm/index.ts@@ -0,0 +1,3 @@+import ServiceForm from "./ServiceForm";++export default ServiceForm;diff --git a/apps/carbon/app/modules/parts/ui/Service/ServicePreview/ServicePreview.tsx b/apps/carbon/app/modules/parts/ui/Service/ServicePreview/ServicePreview.tsxnew file mode 100644index 0000000000..b645f8c682--- /dev/null+++ b/apps/carbon/app/modules/parts/ui/Service/ServicePreview/ServicePreview.tsx@@ -0,0 +1,64 @@+import {+ Button,+ Card,+ CardBody,+ CardHeader,+ Heading,+ HStack,+ Stack,+ Text,+} from "@chakra-ui/react";+import { useParams } from "@remix-run/react";+import { FaHistory } from "react-icons/fa";+import { useRouteData } from "~/hooks";+import type { Service } from "~/modules/parts";+import { path } from "~/utils/path";++const ServicePreview = () => {+ const { serviceId } = useParams();+ if (!serviceId) throw new Error("serviceId not found");++ const routeData = useRouteData<{ service: Service }>(+ path.to.service(serviceId)+ );++ return (+ <Card w="full">+ <CardHeader>+ <HStack justifyContent="space-between" alignItems="start">+ <Stack direction="column" spacing={2}>+ <Heading size="md">{routeData?.service?.name}</Heading>+ <Text color="gray.500" noOfLines={1}>+ {routeData?.service?.description}+ </Text>+ </Stack>+ <Button onClick={() => alert("TODO")} leftIcon={<FaHistory />}>+ View History+ </Button>+ </HStack>+ </CardHeader>+ <CardBody>+ <Stack direction={["column", "column", "row"]} spacing={8}>+ <Stack+ direction={["row", "row", "column"]}+ alignItems="start"+ justifyContent="space-between"+ >+ <Text color="gray.500">Type</Text>+ <Text fontWeight="bold">{routeData?.service?.serviceType}</Text>+ </Stack>+ <Stack+ direction={["row", "row", "column"]}+ alignItems="start"+ justifyContent="space-between"+ >+ <Text color="gray.500">Service Group</Text>+ <Text fontWeight="bold">{routeData?.service?.serviceGroup}</Text>+ </Stack>+ </Stack>+ </CardBody>+ </Card>+ );+};++export default ServicePreview;diff --git a/apps/carbon/app/modules/parts/ui/Service/ServicePreview/index.ts b/apps/carbon/app/modules/parts/ui/Service/ServicePreview/index.tsnew file mode 100644index 0000000000..47ce0ada47--- /dev/null+++ b/apps/carbon/app/modules/parts/ui/Service/ServicePreview/index.ts@@ -0,0 +1,3 @@+import ServicePreview from "./ServicePreview";++export default ServicePreview;diff --git a/apps/carbon/app/modules/parts/ui/Service/ServiceSidebar/ServiceSidebar.tsx b/apps/carbon/app/modules/parts/ui/Service/ServiceSidebar/ServiceSidebar.tsxnew file mode 100644index 0000000000..a367985cc9--- /dev/null+++ b/apps/carbon/app/modules/parts/ui/Service/ServiceSidebar/ServiceSidebar.tsx@@ -0,0 +1,59 @@+import { useColor } from "@carbon/react";+import { Box, Button, VStack } from "@chakra-ui/react";+import { Link, useMatches, useParams } from "@remix-run/react";+import { useRouteData } from "~/hooks";+import type { Service } from "~/modules/parts/types";+import { path } from "~/utils/path";+import { useServiceSidebar } from "./useServiceSidebar";++const ServiceSidebar = () => {+ const { serviceId } = useParams();+ const borderColor = useColor("gray.200");+ if (!serviceId) throw new Error("serviceId not found");++ const routeData = useRouteData<{ service: Service }>(+ path.to.service(serviceId)+ );+ if (!routeData?.service?.serviceType)+ throw new Error("Could not find service type in routeData");++ const links = useServiceSidebar(routeData.service.serviceType);+ const matches = useMatches();++ return (+ <VStack h="full" alignItems="start">+ <Box overflowY="auto" w="full" h="full">+ <VStack spacing={2}>+ <VStack spacing={1} alignItems="start" w="full">+ {links.map((route) => {+ const isActive = matches.some(+ (match) =>+ (match.pathname.includes(route.to) && route.to !== "") ||+ (match.id.includes(".index") && route.to === "")+ );++ return (+ <Button+ key={route.name}+ as={Link}+ to={route.to}+ variant={isActive ? "solid" : "ghost"}+ border={isActive ? "1px solid" : "none"}+ borderColor={borderColor}+ fontWeight={isActive ? "bold" : "normal"}+ justifyContent="start"+ size="md"+ w="full"+ >+ {route.name}+ </Button>+ );+ })}+ </VStack>+ </VStack>+ </Box>+ </VStack>+ );+};++export default ServiceSidebar;diff --git a/apps/carbon/app/modules/parts/ui/Service/ServiceSidebar/index.ts b/apps/carbon/app/modules/parts/ui/Service/ServiceSidebar/index.tsnew file mode 100644index 0000000000..80447118a6--- /dev/null+++ b/apps/carbon/app/modules/parts/ui/Service/ServiceSidebar/index.ts@@ -0,0 +1,3 @@+import ServiceSidebar from "./ServiceSidebar";++export default ServiceSidebar;diff --git a/apps/carbon/app/modules/parts/ui/Service/ServiceSidebar/useServiceSidebar.tsx b/apps/carbon/app/modules/parts/ui/Service/ServiceSidebar/useServiceSidebar.tsxnew file mode 100644index 0000000000..c25b9adf31--- /dev/null+++ b/apps/carbon/app/modules/parts/ui/Service/ServiceSidebar/useServiceSidebar.tsx@@ -0,0 +1,24 @@+import { usePermissions } from "~/hooks";+import type { ServiceType } from "~/modules/parts/types";+import type { Role } from "~/types";++export function useServiceSidebar(type: ServiceType) {+ const permissions = usePermissions();+ return [+ {+ name: "Details",+ to: "",+ },+ {+ name: "Suppliers",+ to: "suppliers",+ isDisabled: type === "Internal",+ role: ["employee", "supplier"],+ },+ ].filter(+ (item) =>+ !item.isDisabled &&+ (item.role === undefined ||+ item.role.some((role) => permissions.is(role as Role)))+ );+}diff --git a/apps/carbon/app/modules/parts/ui/Service/ServiceSupplierForm/ServiceSupplierForm.tsx b/apps/carbon/app/modules/parts/ui/Service/ServiceSupplierForm/ServiceSupplierForm.tsxnew file mode 100644index 0000000000..53ed378bb3--- /dev/null+++ b/apps/carbon/app/modules/parts/ui/Service/ServiceSupplierForm/ServiceSupplierForm.tsx@@ -0,0 +1,80 @@+import {+ Button,+ Drawer,+ DrawerBody,+ DrawerCloseButton,+ DrawerContent,+ DrawerFooter,+ DrawerHeader,+ DrawerOverlay,+ HStack,+ VStack,+} from "@chakra-ui/react";+import { useNavigate, useParams } from "@remix-run/react";+import { ValidatedForm } from "remix-validated-form";+import { Hidden, Input, Submit, Supplier } from "~/components/Form";+import { usePermissions } from "~/hooks";+import { serviceSupplierValidator } from "~/modules/parts";+import type { TypeOfValidator } from "~/types/validators";+import { path } from "~/utils/path";++type ServiceSupplierFormProps = {+ initialValues: TypeOfValidator<typeof serviceSupplierValidator>;+};++const ServiceSupplierForm = ({ initialValues }: ServiceSupplierFormProps) => {+ const permissions = usePermissions();+ const navigate = useNavigate();+ const { serviceId } = useParams();++ if (!serviceId) throw new Error("serviceId not found");++ const isEditing = initialValues.id !== undefined;+ const isDisabled = isEditing+ ? !permissions.can("update", "parts")+ : !permissions.can("create", "parts");++ const onClose = () => navigate(-1);++ return (+ <Drawer onClose={onClose} isOpen={true} size="sm">+ <ValidatedForm+ defaultValues={initialValues}+ validator={serviceSupplierValidator}+ method="post"+ action={+ isEditing+ ? path.to.serviceSupplier(serviceId, initialValues.id!)+ : path.to.newServiceSupplier(serviceId)+ }+ >+ <DrawerOverlay />+ <DrawerContent>+ <DrawerCloseButton />+ <DrawerHeader>+ {isEditing ? "Edit" : "New"} Service Supplier+ </DrawerHeader>+ <DrawerBody pb={8}>+ <Hidden name="id" />+ <Hidden name="serviceId" />++ <VStack spacing={4} alignItems="start">+ <Supplier name="supplierId" label="Supplier" />+ <Input name="supplierServiceId" label="Supplier Service ID" />+ </VStack>+ </DrawerBody>+ <DrawerFooter>+ <HStack>+ <Submit isDisabled={isDisabled}>Save</Submit>+ <Button size="md" variant="ghost" onClick={onClose}>+ Cancel+ </Button>+ </HStack>+ </DrawerFooter>+ </DrawerContent>+ </ValidatedForm>+ </Drawer>+ );+};++export default ServiceSupplierForm;diff --git a/apps/carbon/app/modules/parts/ui/Service/ServiceSupplierForm/index.ts b/apps/carbon/app/modules/parts/ui/Service/ServiceSupplierForm/index.tsnew file mode 100644index 0000000000..0b4d70eeaa--- /dev/null+++ b/apps/carbon/app/modules/parts/ui/Service/ServiceSupplierForm/index.ts@@ -0,0 +1,3 @@+import ServiceSupplierForm from "./ServiceSupplierForm";++export default ServiceSupplierForm;diff --git a/apps/carbon/app/modules/parts/ui/Service/ServiceSuppliers/ServiceSuppliers.tsx b/apps/carbon/app/modules/parts/ui/Service/ServiceSuppliers/ServiceSuppliers.tsxnew file mode 100644index 0000000000..7c02040cf0--- /dev/null+++ b/apps/carbon/app/modules/parts/ui/Service/ServiceSuppliers/ServiceSuppliers.tsx@@ -0,0 +1,99 @@+import {+ Box,+ Button,+ Card,+ CardBody,+ CardHeader,+ Heading,+ HStack,+ IconButton,+} from "@chakra-ui/react";+import { Link, Outlet, useNavigate } from "@remix-run/react";+import type { ColumnDef } from "@tanstack/react-table";+import { useMemo } from "react";+import { MdMoreHoriz } from "react-icons/md";+import { EditableText } from "~/components/Editable";+import Grid from "~/components/Grid";+import type { ServiceSupplier } from "~/modules/parts";+import useServiceSuppliers from "./useServiceSuppliers";++type ServiceSuppliersProps = {+ serviceSuppliers: ServiceSupplier[];+};++const ServiceSuppliers = ({ serviceSuppliers }: ServiceSuppliersProps) => {+ const navigate = useNavigate();+ const { canEdit, onCellEdit } = useServiceSuppliers();++ const columns = useMemo<ColumnDef<ServiceSupplier>[]>(() => {+ return [+ {+ accessorKey: "supplier.id",+ header: "Supplier",+ cell: ({ row }) => (+ <HStack justify="space-between">+ {/* @ts-ignore */}+ <span>{row.original.supplier.name}</span>+ {canEdit && (+ <Box position="relative" w={6} h={5}>+ <IconButton+ aria-label="Edit service supplier"+ as={Link}+ icon={<MdMoreHoriz />}+ size="sm"+ position="absolute"+ right={-1}+ top={-1}+ to={`${row.original.id}`}+ onClick={(e) => e.stopPropagation()}+ variant="ghost"+ />+ </Box>+ )}+ </HStack>+ ),+ },+ {+ accessorKey: "supplierServiceId",+ header: "Supplier ID",+ cell: (item) => item.getValue(),+ },+ ];+ }, [canEdit]);++ const editableComponents = useMemo(+ () => ({+ supplierServiceId: EditableText(onCellEdit),+ }),+ [onCellEdit]+ );++ return (+ <>+ <Card w="full">+ <CardHeader display="flex" justifyContent="space-between">+ <Heading size="md" display="inline-flex">+ Suppliers+ </Heading>+ {canEdit && (+ <Button colorScheme="brand" as={Link} to="new">+ New+ </Button>+ )}+ </CardHeader>+ <CardBody>+ <Grid<ServiceSupplier>+ data={serviceSuppliers}+ columns={columns}+ canEdit={canEdit}+ editableComponents={editableComponents}+ onNewRow={canEdit ? () => navigate("new") : undefined}+ />+ </CardBody>+ </Card>+ <Outlet />+ </>+ );+};++export default ServiceSuppliers;diff --git a/apps/carbon/app/modules/parts/ui/Service/ServiceSuppliers/index.ts b/apps/carbon/app/modules/parts/ui/Service/ServiceSuppliers/index.tsnew file mode 100644index 0000000000..ba2553589a--- /dev/null+++ b/apps/carbon/app/modules/parts/ui/Service/ServiceSuppliers/index.ts@@ -0,0 +1,3 @@+import ServiceSuppliers from "./ServiceSuppliers";++export default ServiceSuppliers;diff --git a/apps/carbon/app/modules/parts/ui/Service/ServiceSuppliers/useServiceSuppliers.tsx b/apps/carbon/app/modules/parts/ui/Service/ServiceSuppliers/useServiceSuppliers.tsxnew file mode 100644index 0000000000..077b059940--- /dev/null+++ b/apps/carbon/app/modules/parts/ui/Service/ServiceSuppliers/useServiceSuppliers.tsx@@ -0,0 +1,32 @@+import { useCallback } from "react";+import { usePermissions } from "~/hooks";+import { useSupabase } from "~/lib/supabase";+import type { ServiceSupplier } from "~/modules/parts";++export default function useServiceSuppliers() {+ const { supabase } = useSupabase();+ const permissions = usePermissions();++ const canEdit = permissions.can("update", "parts");+ const canDelete = permissions.can("delete", "parts");++ const onCellEdit = useCallback(+ async (id: string, value: unknown, row: ServiceSupplier) => {+ if (!supabase) throw new Error("Supabase client not found");+ return await supabase+ .from("serviceSupplier")+ .update({+ [id]: value,+ })+ .eq("id", row.id);+ },+ [supabase]+ );++ return {+ canDelete,+ canEdit,+ supabase,+ onCellEdit,+ };+}diff --git a/apps/carbon/app/modules/parts/ui/Service/index.ts b/apps/carbon/app/modules/parts/ui/Service/index.tsnew file mode 100644index 0000000000..885a53d6f0--- /dev/null+++ b/apps/carbon/app/modules/parts/ui/Service/index.ts@@ -0,0 +1,13 @@+import ServiceForm from "./ServiceForm";+import ServicePreview from "./ServicePreview";+import ServiceSidebar from "./ServiceSidebar";+import ServiceSupplierForm from "./ServiceSupplierForm";+import ServiceSuppliers from "./ServiceSuppliers";++export {+ ServiceForm,+ ServicePreview,+ ServiceSidebar,+ ServiceSupplierForm,+ ServiceSuppliers,+};diff --git a/apps/carbon/app/modules/parts/ui/Services/ServicesTableFilters/ServicesTableFilters.tsx b/apps/carbon/app/modules/parts/ui/Services/ServicesTableFilters/ServicesTableFilters.tsxindex 7909fe4ee2..f05c018303 100644--- a/apps/carbon/app/modules/parts/ui/Services/ServicesTableFilters/ServicesTableFilters.tsx+++ b/apps/carbon/app/modules/parts/ui/Services/ServicesTableFilters/ServicesTableFilters.tsx@@ -76,7 +76,7 @@ const ServicesTableFilters = ({ serviceGroups }: ServicesTableFiltersProps) => {)}</HStack><HStack spacing={2}>- {permissions.can("create", "services") && (+ {permissions.can("create", "parts") && (<Buttonas={Link}to={path.to.newService}diff --git a/apps/carbon/app/modules/parts/ui/index.ts b/apps/carbon/app/modules/parts/ui/index.tsindex f1982293f4..249ab55a51 100644--- a/apps/carbon/app/modules/parts/ui/index.ts+++ b/apps/carbon/app/modules/parts/ui/index.ts@@ -4,6 +4,7 @@ export * from "./Part";export * from "./PartGroups";export * from "./Parts";export * from "./Routing";+export * from "./Service";export * from "./Services";export * from "./UnitOfMeasure";export { usePartsSidebar };diff --git a/apps/carbon/app/routes/x+/part+/$partId.index.tsx b/apps/carbon/app/routes/x+/part+/$partId.index.tsxindex bb8b80ced0..a42c8849c5 100644--- a/apps/carbon/app/routes/x+/part+/$partId.index.tsx+++ b/apps/carbon/app/routes/x+/part+/$partId.index.tsx@@ -54,15 +54,15 @@ export default function PartBasicRoute() {if (!partData) throw new Error("Could not find part data");const initialValues = {- id: partData.partSummary?.id,+ id: partData.partSummary?.id ?? "",name: partData.partSummary?.name ?? "",description: partData.partSummary?.description ?? undefined,- partType: partData.partSummary?.partType,+ partType: partData.partSummary?.partType ?? "Inventory",partGroupId: partData.partSummary?.partGroupId ?? undefined,- replenishmentSystem: partData.partSummary?.replenishmentSystem,- unitOfMeasureCode: partData.partSummary?.unitOfMeasureCode,- blocked: partData.partSummary?.blocked,- active: partData.partSummary?.active,+ replenishmentSystem: partData.partSummary?.replenishmentSystem ?? "Buy",+ unitOfMeasureCode: partData.partSummary?.unitOfMeasureCode ?? "EA",+ blocked: partData.partSummary?.blocked ?? false,+ active: partData.partSummary?.active ?? false,};return <PartForm initialValues={initialValues} />;diff --git a/apps/carbon/app/routes/x+/part+/$partId.suppliers.new.tsx b/apps/carbon/app/routes/x+/part+/$partId.suppliers.new.tsxindex c2cb0d0595..3149d0d145 100644--- a/apps/carbon/app/routes/x+/part+/$partId.suppliers.new.tsx+++ b/apps/carbon/app/routes/x+/part+/$partId.suppliers.new.tsx@@ -53,7 +53,7 @@ export async function action({ request, params }: ActionFunctionArgs) {export default function NewPartSupplierRoute() {const { partId } = useParams();- if (!partId) throw new Error("Could not find purchase order id");+ if (!partId) throw new Error("partId not found");const initialValues = {partId: partId,diff --git a/apps/carbon/app/routes/x+/service+/$serviceId.index.tsx b/apps/carbon/app/routes/x+/service+/$serviceId.index.tsxnew file mode 100644index 0000000000..79aa1055fe--- /dev/null+++ b/apps/carbon/app/routes/x+/service+/$serviceId.index.tsx@@ -0,0 +1,68 @@+import type { ActionFunctionArgs } from "@remix-run/node";+import { redirect } from "@remix-run/node";+import { useParams } from "@remix-run/react";+import { validationError } from "remix-validated-form";+import { useRouteData } from "~/hooks";+import type { Service } from "~/modules/parts";+import { ServiceForm, serviceValidator, upsertService } from "~/modules/parts";+import { requirePermissions } from "~/services/auth";+import { flash } from "~/services/session";+import { assertIsPost } from "~/utils/http";+import { path } from "~/utils/path";+import { error, success } from "~/utils/result";++export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, userId } = await requirePermissions(request, {+ update: "parts",+ });++ const { serviceId } = params;+ if (!serviceId) throw new Error("Could not find serviceId");++ // validate with partsValidator+ const validation = await serviceValidator.validate(await request.formData());++ if (validation.error) {+ return validationError(validation.error);+ }++ const updatePart = await upsertService(client, {+ ...validation.data,+ id: serviceId,+ updatedBy: userId,+ });++ if (updatePart.error) {+ return redirect(+ path.to.service(serviceId),+ await flash(request, error(updatePart.error, "Failed to update part"))+ );+ }++ return redirect(+ path.to.service(serviceId),+ await flash(request, success("Updated part"))+ );+}++export default function ServiceDetailsRoute() {+ const { serviceId } = useParams();+ if (!serviceId) throw new Error("Could not find serviceId");+ const routeData = useRouteData<{ service: Service }>(+ path.to.service(serviceId)+ );+ if (!routeData) throw new Error("Could not find part data");++ const initialValues = {+ id: routeData.service?.id!,+ name: routeData.service?.name ?? "",+ description: routeData.service?.description ?? undefined,+ serviceType: routeData.service?.serviceType ?? "Internal",+ serviceGroupId: routeData.service?.serviceGroupId ?? undefined,+ active: routeData.service?.active ?? true,+ blocked: routeData.service?.blocked ?? false,+ };++ return <ServiceForm initialValues={initialValues} />;+}diff --git a/apps/carbon/app/routes/x+/service+/$serviceId.suppliers.new.tsx b/apps/carbon/app/routes/x+/service+/$serviceId.suppliers.new.tsxnew file mode 100644index 0000000000..4618e64a56--- /dev/null+++ b/apps/carbon/app/routes/x+/service+/$serviceId.suppliers.new.tsx@@ -0,0 +1,65 @@+import type { ActionFunctionArgs } from "@remix-run/node";+import { redirect } from "@remix-run/node";+import { useParams } from "@remix-run/react";+import { validationError } from "remix-validated-form";+import {+ ServiceSupplierForm,+ serviceSupplierValidator,+ upsertServiceSupplier,+} from "~/modules/parts";+import { requirePermissions } from "~/services/auth";+import { flash } from "~/services/session";+import { assertIsPost } from "~/utils/http";+import { path } from "~/utils/path";+import { error } from "~/utils/result";++export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, userId } = await requirePermissions(request, {+ create: "parts",+ });++ const { serviceId } = params;+ if (!serviceId) throw new Error("Could not find serviceId");++ const validation = await serviceSupplierValidator.validate(+ await request.formData()+ );++ if (validation.error) {+ return validationError(validation.error);+ }++ const { id, ...data } = validation.data;++ const createServiceSupplier = await upsertServiceSupplier(client, {+ ...data,+ createdBy: userId,+ });++ if (createServiceSupplier.error) {+ return redirect(+ path.to.serviceSuppliers(serviceId),+ await flash(+ request,+ error(createServiceSupplier.error, "Failed to create service supplier.")+ )+ );+ }++ return redirect(path.to.serviceSuppliers(serviceId));+}++export default function NewServiceSupplierRoute() {+ const { serviceId } = useParams();++ if (!serviceId) throw new Error("serviceId not found");++ const initialValues = {+ serviceId,+ supplierId: "",+ supplierServiceId: "",+ };++ return <ServiceSupplierForm initialValues={initialValues} />;+}diff --git a/apps/carbon/app/routes/x+/service+/$serviceId.suppliers.tsx b/apps/carbon/app/routes/x+/service+/$serviceId.suppliers.tsxnew file mode 100644index 0000000000..6bf3098141--- /dev/null+++ b/apps/carbon/app/routes/x+/service+/$serviceId.suppliers.tsx@@ -0,0 +1,41 @@+import type { LoaderFunctionArgs } from "@remix-run/node";+import { json, redirect } from "@remix-run/node";+import { useLoaderData } from "@remix-run/react";+import { ServiceSuppliers, getServiceSuppliers } from "~/modules/parts";+import { requirePermissions } from "~/services/auth";+import { flash } from "~/services/session";+import { path } from "~/utils/path";+import { error } from "~/utils/result";++export async function loader({ request, params }: LoaderFunctionArgs) {+ const { client } = await requirePermissions(request, {+ view: "parts",+ });++ const { serviceId } = params;+ if (!serviceId) throw new Error("Could not find serviceId");++ const [serviceSuppliers] = await Promise.all([+ getServiceSuppliers(client, serviceId),+ ]);++ if (serviceSuppliers.error) {+ return redirect(+ path.to.service(serviceId),+ await flash(+ request,+ error(serviceSuppliers.error, "Failed to load service suppliers")+ )+ );+ }++ return json({+ serviceSuppliers: serviceSuppliers.data ?? [],+ });+}++export default function ServiceSuppliersRoute() {+ const { serviceSuppliers } = useLoaderData<typeof loader>();++ return <ServiceSuppliers serviceSuppliers={serviceSuppliers} />;+}diff --git a/apps/carbon/app/routes/x+/service+/$serviceId.tsx b/apps/carbon/app/routes/x+/service+/$serviceId.tsxnew file mode 100644index 0000000000..4a705d6e9d--- /dev/null+++ b/apps/carbon/app/routes/x+/service+/$serviceId.tsx@@ -0,0 +1,53 @@+import { Grid } from "@chakra-ui/react";+import type { LoaderFunctionArgs } from "@remix-run/node";+import { json, redirect } from "@remix-run/node";+import { Outlet } from "@remix-run/react";+import { ServicePreview, ServiceSidebar, getService } from "~/modules/parts";+import { requirePermissions } from "~/services/auth";+import { flash } from "~/services/session";+import type { Handle } from "~/utils/handle";+import { path } from "~/utils/path";+import { error } from "~/utils/result";++export const handle: Handle = {+ breadcrumb: "Services",+ to: path.to.services,+};++export async function loader({ request, params }: LoaderFunctionArgs) {+ const { client } = await requirePermissions(request, {+ view: "parts",+ });++ const { serviceId } = params;+ if (!serviceId) throw new Error("Could not find serviceId");++ const [service] = await Promise.all([getService(client, serviceId)]);++ if (service.error) {+ return redirect(+ path.to.parts,+ await flash(request, error(service.error, "Failed to load service"))+ );+ }++ return json({+ service: service.data,+ });+}++export default function ServiceRoute() {+ return (+ <>+ <ServicePreview />+ <Grid+ gridTemplateColumns={["1fr", "1fr", "1fr 4fr"]}+ gridColumnGap={4}+ w="full"+ >+ <ServiceSidebar />+ <Outlet />+ </Grid>+ </>+ );+}diff --git a/apps/carbon/app/routes/x+/service+/_layout.tsx b/apps/carbon/app/routes/x+/service+/_layout.tsxnew file mode 100644index 0000000000..7e28700b2f--- /dev/null+++ b/apps/carbon/app/routes/x+/service+/_layout.tsx@@ -0,0 +1,42 @@+import { VStack } from "@chakra-ui/react";+import type { LoaderFunctionArgs, MetaFunction } from "@remix-run/node";+import { Outlet } from "@remix-run/react";+import { getServiceGroupsList } from "~/modules/parts";+import { getLocationsList } from "~/modules/resources";+import { requirePermissions } from "~/services/auth";+import type { Handle } from "~/utils/handle";+import { path } from "~/utils/path";++export const meta: MetaFunction = () => {+ return [{ title: "Carbon | Service" }];+};++export const handle: Handle = {+ breadcrumb: "Parts",+ to: path.to.parts,+ module: "parts",+};++export async function loader({ request }: LoaderFunctionArgs) {+ const { client } = await requirePermissions(request, {+ view: "parts",+ });++ const [serviceGroups, locations] = await Promise.all([+ getServiceGroupsList(client),+ getLocationsList(client),+ ]);++ return {+ locations: locations?.data ?? [],+ serviceGroups: serviceGroups?.data ?? [],+ };+}++export default function ServiceRoute() {+ return (+ <VStack w="full" h="full" spacing={4} p={4}>+ <Outlet />+ </VStack>+ );+}diff --git a/apps/carbon/app/routes/x+/service+/new.tsx b/apps/carbon/app/routes/x+/service+/new.tsxnew file mode 100644index 0000000000..11902d113a--- /dev/null+++ b/apps/carbon/app/routes/x+/service+/new.tsx@@ -0,0 +1,72 @@+import { Box } from "@chakra-ui/react";+import type { ActionFunctionArgs } from "@remix-run/node";+import { redirect } from "@remix-run/node";+import { validationError } from "remix-validated-form";+import { ServiceForm, serviceValidator, upsertService } from "~/modules/parts";+import { requirePermissions } from "~/services/auth";+import { flash } from "~/services/session";+import type { Handle } from "~/utils/handle";+import { assertIsPost } from "~/utils/http";+import { path } from "~/utils/path";+import { error } from "~/utils/result";++export const handle: Handle = {+ breadcrumb: "Services",+ to: path.to.services,+};++export async function action({ request }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, userId } = await requirePermissions(request, {+ create: "parts",+ });++ const validation = await serviceValidator.validate(await request.formData());++ if (validation.error) {+ return validationError(validation.error);+ }++ const createService = await upsertService(client, {+ ...validation.data,+ active: true,+ createdBy: userId,+ });+ if (createService.error) {+ return redirect(+ path.to.services,+ await flash(+ request,+ error(createService.error, "Failed to create service")+ )+ );+ }++ const serviceId = createService.data?.id;+ if (!serviceId) {+ return redirect(+ path.to.services,+ await flash(+ request,+ error(createService.error, "Failed to create service")+ )+ );+ }++ return redirect(path.to.service(serviceId));+}++export default function ServiceNewRoute() {+ const initialValues = {+ name: "",+ description: "",+ serviceType: "External" as "External",+ };++ return (+ <Box w="50%" maxW={720} minW={420}>+ {/* @ts-ignore */}+ <ServiceForm initialValues={initialValues} />+ </Box>+ );+}diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.tsindex 1397cd3d0e..d7edee7d71 100644--- a/apps/carbon/app/utils/path.ts+++ b/apps/carbon/app/utils/path.ts@@ -253,6 +253,8 @@ export const path = {newShift: `${x}/resources/shifts/new`,newShippingMethod: `${x}/inventory/shipping-methods/new`,newService: `${x}/service/new`,+ newServiceSupplier: (id: string) =>+ generatePath(`${x}/service/${id}/suppliers/new`),newSupplier: `${x}/supplier/new`,newSupplierAccount: `${x}/users/suppliers/new`,newSupplierContact: (id: string) =>@@ -331,6 +333,11 @@ export const path = {scheduling: `${x}/scheduling`,service: (id: string) => generatePath(`${x}/service/${id}`),services: `${x}/parts/services`,+ serviceRoot: `${x}/service`,+ serviceSupplier: (serviceId: string, id: string) =>+ generatePath(`${x}/service/${serviceId}/suppliers/${id}`),+ serviceSuppliers: (id: string) =>+ generatePath(`${x}/service/${id}/suppliers`),settings: `${x}/settings`,sequences: `${x}/settings/sequences`,shift: (id: string) => generatePath(`${x}/resources/shifts/${id}`),diff --git a/packages/database/SCHEMA.md b/packages/database/SCHEMA.mdindex a7928dc95d..e977a867b7 100644--- a/packages/database/SCHEMA.md+++ b/packages/database/SCHEMA.md@@ -7192,6 +7192,7 @@ CREATE OR REPLACE VIEW "services" WITH(SECURITY_INVOKER=true) ASsg.id AS "serviceGroupId",sg.name AS "serviceGroup",s.active,+ s.blocked,array_agg(ss."supplierId") AS "supplierIds"FROM "service" sLEFT JOIN "serviceGroup" sg ON sg.id = s."serviceGroupId"diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex 2c017b0e9d..8c866c4255 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -8872,6 +8872,7 @@ export interface Database {services: {Row: {active: boolean | null;+ blocked: boolean | null;description: string | null;id: string | null;name: string | null;diff --git a/packages/database/supabase/migrations/20231212120726_services.sql b/packages/database/supabase/migrations/20231212120726_services.sqlindex 7a92ff2a91..a350bc3bdf 100644--- a/packages/database/supabase/migrations/20231212120726_services.sql+++ b/packages/database/supabase/migrations/20231212120726_services.sql@@ -182,6 +182,7 @@ CREATE OR REPLACE VIEW "services" WITH(SECURITY_INVOKER=true) ASsg.id AS "serviceGroupId",sg.name AS "serviceGroup",s.active,+ s.blocked,array_agg(ss."supplierId") AS "supplierIds"FROM "service" sLEFT JOIN "serviceGroup" sg ON sg.id = s."serviceGroupId"