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 feedback function to MES
Rob Carringtonc58ec85b7a2a
diff --git a/apps/mes/app/components/Feedback.tsx b/apps/mes/app/components/Feedback.tsxnew file mode 100644index 0000000000..efd665012d--- /dev/null+++ b/apps/mes/app/components/Feedback.tsx@@ -0,0 +1,168 @@+import { useCarbon } from "@carbon/auth";+import {+ Hidden,+ Submit,+ TextAreaControlled,+ ValidatedForm,+} from "@carbon/form";+import {+ Badge,+ BadgeCloseButton,+ Button,+ File,+ HStack,+ Popover,+ PopoverContent,+ PopoverTrigger,+ VStack,+ toast,+} from "@carbon/react";+import { SUPPORT_EMAIL } from "@carbon/utils";+import { useFetcher, useLocation } from "@remix-run/react";+import { nanoid } from "nanoid";+import type { ChangeEvent } from "react";+import { useEffect, useRef, useState } from "react";+import { LuImage } from "react-icons/lu";+import { feedbackValidator } from "~/models/feedback";+import type { action } from "~/routes/x+/feedback";+import { path } from "~/utils/path";++const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB in bytes+const Feedback = () => {+ const fetcher = useFetcher<typeof action>();+ const location = useLocation();+ const popoverTriggerRef = useRef<HTMLButtonElement>(null);+ const [feedback, setFeedback] = useState("");+ const [attachment, setAttachment] = useState<{+ name: string;+ path: string;+ } | null>(null);+ const { carbon } = useCarbon();++ useEffect(() => {+ if (fetcher.data?.success) {+ toast.success(fetcher.data.message);+ popoverTriggerRef.current?.click();+ } else if (fetcher.data?.message) {+ toast.error(fetcher.data.message);+ }+ }, [fetcher.data]);++ const uploadImage = async (e: ChangeEvent<HTMLInputElement>) => {+ if (e.target.files && carbon) {+ const file = e.target.files[0];+ const fileExtension = file.name.substring(file.name.lastIndexOf(".") + 1);++ if (file.size > MAX_FILE_SIZE) {+ toast.error("File size exceeds 10MB limit");+ return;+ }++ const imageUpload = await carbon.storage+ .from("feedback")+ .upload(`${nanoid()}.${fileExtension}`, file, {+ cacheControl: `${12 * 60 * 60}`,+ upsert: true,+ });++ if (imageUpload.error) {+ console.error(imageUpload.error);+ toast.error("Failed to upload image");+ }++ if (imageUpload.data?.path) {+ setAttachment({+ name: file.name,+ path: imageUpload.data.path,+ });+ }+ }+ };++ return (+ <Popover>+ <PopoverTrigger ref={popoverTriggerRef} asChild>+ <Button variant="secondary" className="text-muted-foreground">+ Feedback+ </Button>+ </PopoverTrigger>+ <PopoverContent align="end" className="w-[380px] ">+ <ValidatedForm+ method="post"+ action={path.to.feedback}+ validator={feedbackValidator}+ fetcher={fetcher}+ onSubmit={() => {+ setFeedback("");+ setAttachment(null);+ }}+ >+ <Hidden name="location" value={location.pathname} />+ <Hidden name="attachmentPath" value={attachment?.path ?? ""} />+ <VStack spacing={4}>+ <VStack spacing={2}>+ <TextAreaControlled+ name="feedback"+ label=""+ value={feedback}+ onChange={(value) => setFeedback(value)}+ placeholder="Ideas, suggestions or problems with this page?"+ />+ {attachment && (+ <Badge className="-mt-2 truncate" variant="secondary">+ {attachment.name}+ <BadgeCloseButton+ type="button"+ onClick={(e) => {+ setAttachment(null);+ }}+ />+ </Badge>+ )}+ </VStack>+ <HStack className="w-full justify-between">+ <Button+ variant="secondary"+ onClick={() => {+ setFeedback("");+ setAttachment(null);+ popoverTriggerRef.current?.click();+ }}+ >+ Cancel+ </Button>+ <HStack spacing={1}>+ <Button+ isDisabled={feedback.length === 0}+ variant="secondary"+ onClick={() => setFeedback("")}+ >+ Clear+ </Button>+ <File+ accept="image/*"+ aria-label="Attach File"+ className="px-2"+ isDisabled={!!attachment}+ variant="secondary"+ onChange={uploadImage}+ >+ <LuImage />+ </File>+ <Submit isDisabled={feedback.length < 3}>Send</Submit>+ </HStack>+ </HStack>+ <p className="text-sm">+ Have a technical issue? Contact{" "}+ <a className="text-primary" href={`mailto:${SUPPORT_EMAIL}`}>+ CarbonOS Support.+ </a>+ </p>+ </VStack>+ </ValidatedForm>+ </PopoverContent>+ </Popover>+ );+};++export default Feedback;diff --git a/apps/mes/app/lib/slack.server.ts b/apps/mes/app/lib/slack.server.tsnew file mode 100644index 0000000000..97953c94f3--- /dev/null+++ b/apps/mes/app/lib/slack.server.ts@@ -0,0 +1,32 @@+import { SLACK_BOT_TOKEN } from "@carbon/auth";+import { WebClient } from "@slack/web-api";++interface SlackMessage {+ channel: string;+ text: string;+ blocks?: any[];+}++class SlackClient {+ private client: WebClient;++ constructor(token: string) {+ this.client = new WebClient(token);+ }++ async sendMessage({ channel, text, blocks }: SlackMessage): Promise<void> {+ try {+ await this.client.chat.postMessage({+ channel,+ text,+ blocks,+ });+ } catch (error) {+ console.error("Error sending Slack message:", error);+ }+ }+}++export function getSlackClient(): SlackClient {+ return new SlackClient(SLACK_BOT_TOKEN);+}diff --git a/apps/mes/app/models/feedback.ts b/apps/mes/app/models/feedback.tsnew file mode 100644index 0000000000..028a25bda8--- /dev/null+++ b/apps/mes/app/models/feedback.ts@@ -0,0 +1,7 @@+import { z } from "zod";++export const feedbackValidator = z.object({+ feedback: z.string().min(1, { message: "" }),+ attachmentPath: z.string().optional(),+ location: z.string(),+});diff --git a/apps/mes/app/routes/x+/_layout.tsx b/apps/mes/app/routes/x+/_layout.tsxindex 87326a1bee..c6fb6e0c37 100644--- a/apps/mes/app/routes/x+/_layout.tsx+++ b/apps/mes/app/routes/x+/_layout.tsx@@ -21,6 +21,7 @@ import { useEffect, useRef, useState } from "react";import { LuActivity, LuClock, LuInbox } from "react-icons/lu";import type { ImperativePanelHandle } from "react-resizable-panels";import { AvatarMenu, Nav } from "~/components";+import Feedback from "~/components/Feedback";import { useMediaQuery } from "~/hooks";import {getActiveJobCount,@@ -187,6 +188,7 @@ export default function AuthenticatedRoute() {location={location}locations={locations}/>+ <Feedback /></div></div><div className="flex flex-col h-[calc(100%-52px)] justify-between overflow-y-auto bg-background">diff --git a/apps/mes/app/routes/x+/feedback.tsx b/apps/mes/app/routes/x+/feedback.tsxnew file mode 100644index 0000000000..5b26022d98--- /dev/null+++ b/apps/mes/app/routes/x+/feedback.tsx@@ -0,0 +1,85 @@+import { getCarbonServiceRole, SUPABASE_API_URL } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { validator } from "@carbon/form";+import { json, type ActionFunctionArgs } from "@vercel/remix";+import { getSlackClient } from "~/lib/slack.server";+import { feedbackValidator } from "~/models/feedback";++export const config = {+ runtime: "nodejs",+};++export async function action({ request }: ActionFunctionArgs) {+ const { userId } = await requirePermissions(request, {});++ const formData = await request.formData();+ const validation = await validator(feedbackValidator).validate(formData);++ if (validation.error) {+ return json({+ success: false,+ message: "Failed to submit feedback",+ });+ }++ const { attachmentPath, feedback, location } = validation.data;+ const serviceRole = await getCarbonServiceRole();+ const slackClient = getSlackClient();++ const [user, insertFeedback] = await Promise.all([+ serviceRole+ .from("user")+ .select("firstName,lastName,email")+ .eq("id", userId)+ .single(),+ serviceRole.from("feedback").insert([+ {+ feedback,+ location,+ attachmentPath: attachmentPath ? `feedback/${attachmentPath}` : null,+ userId,+ },+ ]),+ ]);++ if (insertFeedback.error) {+ return json({+ success: false,+ message: "Failed to submit feedback",+ });+ }++ await slackClient.sendMessage({+ channel: "#feedback",+ text: `New feedback submitted`,+ blocks: [+ {+ type: "section",+ text: { type: "mrkdwn", text: `New feedback submitted` },+ },+ {+ type: "section",+ fields: [+ { type: "mrkdwn", text: `*Location:*\n${location}` },+ { type: "mrkdwn", text: `*Feedback:*\n${feedback}` },+ {+ type: "mrkdwn",+ text: `*User:*\n${user.data?.firstName ?? ""} ${+ user.data?.lastName ?? ""+ } <${user.data?.email ?? ""}>`,+ },+ {+ type: "mrkdwn",+ text: `*Attachment:*\n${+ attachmentPath+ ? `${SUPABASE_API_URL}/storage/v1/object/public/feedback/${attachmentPath}`+ : "None"+ }`,+ },+ ],+ },+ ],+ });++ return json({ success: true, message: "Feedback submitted" });+}diff --git a/apps/mes/app/utils/path.ts b/apps/mes/app/utils/path.tsindex c8e0a6c577..d83d8343fb 100644--- a/apps/mes/app/utils/path.ts+++ b/apps/mes/app/utils/path.ts@@ -25,6 +25,7 @@ export const path = {authenticatedRoot: x,callback: "/callback",complete: `${x}/complete`,+ feedback: `${x}/feedback`,finish: `${x}/finish`,forgotPassword: "/forgot-password",healthcheck: "/healthcheck",