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: suggestion box
Brad Barbincc7864eb25c4
diff --git a/apps/erp/README.md b/apps/erp/README.mdindex 00931246be..04e70cfe09 100644--- a/apps/erp/README.md+++ b/apps/erp/README.md@@ -14,7 +14,7 @@ Where services, ui and form validators are defined for each module.### `app/routes`-File-based route definitions using Remix. This is where the services and interfaces meet. Each route is loaded in parallel for performance, so each route is responsible for defining it's own authorization and data needs. Each route has three parts (none are required):+File-based route definitions using React Router's framework mode. This is where the services and interfaces meet. Each route is loaded in parallel for performance, so each route is responsible for defining it's own authorization and data needs. Each route has three parts (none are required):1. `export async function loader`: The data that the route returns, which can be accessed via `GET` or `useLoaderData` in the component (3)2. `export async function action`: The actions (`POST` or `DELETE`) for the route, which can be accessed via http methods or through the `ValidatedForm` component.diff --git a/apps/erp/app/components/Layout/Topbar/Feedback.tsx b/apps/erp/app/components/Layout/Topbar/Feedback.tsxindex f11dfe2ceb..7e4cb3317b 100644--- a/apps/erp/app/components/Layout/Topbar/Feedback.tsx+++ b/apps/erp/app/components/Layout/Topbar/Feedback.tsx@@ -21,7 +21,7 @@ import { SUPPORT_EMAIL } from "@carbon/utils";import { nanoid } from "nanoid";import type { ChangeEvent } from "react";import { useEffect, useRef, useState } from "react";-import { LuImage } from "react-icons/lu";+import { LuImage, LuLightbulb } from "react-icons/lu";import { useFetcher, useLocation } from "react-router";import { feedbackValidator } from "~/modules/shared";import type { action } from "~/routes/x+/feedback";diff --git a/apps/erp/app/components/Layout/Topbar/Suggestion.tsx b/apps/erp/app/components/Layout/Topbar/Suggestion.tsxnew file mode 100644index 0000000000..faf588f8a3--- /dev/null+++ b/apps/erp/app/components/Layout/Topbar/Suggestion.tsx@@ -0,0 +1,219 @@+import { useCarbon } from "@carbon/auth";+import {+ Hidden,+ Submit,+ TextAreaControlled,+ ValidatedForm+} from "@carbon/form";+import {+ Badge,+ BadgeCloseButton,+ Button,+ Checkbox,+ File,+ HStack,+ Popover,+ PopoverContent,+ PopoverTrigger,+ toast,+ VStack+} from "@carbon/react";+import data from "@emoji-mart/data";+import Picker from "@emoji-mart/react";+import { nanoid } from "nanoid";+import type { ChangeEvent } from "react";+import { useEffect, useRef, useState } from "react";+import { LuImage, LuLightbulb } from "react-icons/lu";+import { useFetcher, useLocation } from "react-router";+import { useUser } from "~/hooks";+import { suggestionValidator } from "~/modules/shared";+import type { action } from "~/routes/x+/resources+/suggestions.new";+import { path } from "~/utils/path";++const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB in bytes++type EmojiData = {+ native: string;+ id: string;+ name: string;+};++const Suggestion = () => {+ const fetcher = useFetcher<typeof action>();+ const location = useLocation();+ const popoverTriggerRef = useRef<HTMLButtonElement>(null);+ const [suggestion, setSuggestion] = useState("");+ const [emoji, setEmoji] = useState("💡");+ const [emojiPickerOpen, setEmojiPickerOpen] = useState(false);+ const [anonymous, setAnonymous] = useState(true);+ const [attachment, setAttachment] = useState<{+ name: string;+ path: string;+ } | null>(null);+ const { carbon } = useCarbon();+ const user = useUser();+ const companyId = user.company.id;++ useEffect(() => {+ if (fetcher.data?.success) {+ toast.success(fetcher.data.message);+ setSuggestion("");+ setEmoji("💡");+ setAttachment(null);+ setAnonymous(true);+ 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];+ toast.info(`Uploading ${file.name}`);+ const fileExtension = file.name.substring(file.name.lastIndexOf(".") + 1);++ if (file.size > MAX_FILE_SIZE) {+ toast.error("File size exceeds 10MB limit");+ return;+ }++ const fileName = `${companyId}/suggestions/${nanoid()}.${fileExtension}`;+ const imageUpload = await carbon.storage+ .from("private")+ .upload(fileName, 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+ });+ }+ }+ };++ const onEmojiSelect = (emojiData: EmojiData) => {+ setEmoji(emojiData.native);+ setEmojiPickerOpen(false);+ };++ return (+ <Popover>+ <PopoverTrigger ref={popoverTriggerRef} asChild>+ <Button variant="secondary">Suggestion</Button>+ </PopoverTrigger>+ <PopoverContent align="end" className="w-[380px] ">+ <ValidatedForm+ method="post"+ action={path.to.newSuggestion}+ validator={suggestionValidator}+ fetcher={fetcher}+ >+ <Hidden name="path" value={location.pathname} />+ <Hidden name="emoji" value={emoji} />+ <Hidden name="attachmentPath" value={attachment?.path ?? ""} />+ <Hidden name="userId" value={anonymous ? "" : user.id} />+ <VStack spacing={2}>+ <VStack spacing={2} className="w-full">+ <TextAreaControlled+ name="suggestion"+ label=""+ value={suggestion}+ onChange={(value) => setSuggestion(value)}+ placeholder="Ideas, suggestions or problems?"+ />+ {attachment && (+ <Badge className="-mt-2 truncate" variant="secondary">+ {attachment.name}+ <BadgeCloseButton+ type="button"+ onClick={() => {+ setAttachment(null);+ }}+ />+ </Badge>+ )}+ </VStack>+ <HStack className="w-full justify-between">+ <HStack spacing={2}>+ <Checkbox+ isChecked={anonymous}+ onCheckedChange={(checked) => setAnonymous(checked === true)}+ />+ <span className="text-sm">Submit anonymously</span>+ </HStack>+ <Popover open={emojiPickerOpen} onOpenChange={setEmojiPickerOpen}>+ <PopoverTrigger asChild>+ <button+ type="button"+ className="inline-flex items-center justify-center rounded-md h-10 w-10 text-2xl hover:bg-accent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 shrink-0"+ >+ {emoji}+ </button>+ </PopoverTrigger>+ <PopoverContent+ className="w-auto p-0 border-0 bg-white"+ align="end"+ sideOffset={8}+ >+ <Picker+ data={data}+ onEmojiSelect={onEmojiSelect}+ theme="light"+ previewPosition="none"+ skinTonePosition="none"+ navPosition="bottom"+ perLine={8}+ />+ </PopoverContent>+ </Popover>+ </HStack>+ <HStack className="w-full justify-between">+ <Button+ variant="secondary"+ onClick={() => {+ setSuggestion("");+ setEmoji("💡");+ setAttachment(null);+ popoverTriggerRef.current?.click();+ }}+ >+ Cancel+ </Button>+ <HStack spacing={1}>+ <Button+ isDisabled={suggestion.length === 0}+ variant="secondary"+ onClick={() => setSuggestion("")}+ >+ Clear+ </Button>+ <File+ accept="image/*"+ aria-label="Attach File"+ className="px-2"+ isDisabled={!!attachment}+ variant="secondary"+ onChange={uploadImage}+ >+ <LuImage />+ </File>+ <Submit isDisabled={suggestion.length < 3}>Send</Submit>+ </HStack>+ </HStack>+ </VStack>+ </ValidatedForm>+ </PopoverContent>+ </Popover>+ );+};++export default Suggestion;diff --git a/apps/erp/app/components/Layout/Topbar/Topbar.tsx b/apps/erp/app/components/Layout/Topbar/Topbar.tsxindex 242aaf1e82..8b42acde4d 100644--- a/apps/erp/app/components/Layout/Topbar/Topbar.tsx+++ b/apps/erp/app/components/Layout/Topbar/Topbar.tsx@@ -5,9 +5,9 @@ import AvatarMenu from "../../AvatarMenu";import Breadcrumbs from "./Breadcrumbs";import CompanySwitcher from "./CompanySwitcher";import CreateMenu from "./CreateMenu";-import Feedback from "./Feedback";import Notifications from "./Notifications";import Search from "./Search";+import Suggestion from "./Suggestion";const Topbar = () => {const permissions = usePermissions();@@ -26,7 +26,7 @@ const Topbar = () => {{permissions.is("employee") ? <Search /> : <div />}</div><HStack spacing={1} className="flex-1 justify-end py-2">- <Feedback />+ <Suggestion /><CreateMenutrigger={<IconButtondiff --git a/apps/erp/app/modules/accounting/ui/ChartOfAccounts/ChartOfAccountsTable.tsx b/apps/erp/app/modules/accounting/ui/ChartOfAccounts/ChartOfAccountsTable.tsxindex f1a0c3ed99..10aa604685 100644--- a/apps/erp/app/modules/accounting/ui/ChartOfAccounts/ChartOfAccountsTable.tsx+++ b/apps/erp/app/modules/accounting/ui/ChartOfAccounts/ChartOfAccountsTable.tsx@@ -2,7 +2,7 @@ import { Button, Checkbox, cn, HStack } from "@carbon/react";import type { ColumnDef } from "@tanstack/react-table";import { memo, useMemo } from "react";import { LuEllipsisVertical } from "react-icons/lu";-import { Link as RemixLink } from "react-router";+import { Link as ReactRouterLink } from "react-router";import { Hyperlink } from "~/components";import { Enumerable } from "~/components/Enumerable";import Grid from "~/components/Grid";@@ -45,9 +45,9 @@ const ChartOfAccountsTable = memo(({ data }: ChartOfAccountsTableProps) => {aria-label="Edit account"onClick={(e) => e.stopPropagation()}>- <RemixLink to={`${row.original.id}`}>+ <ReactRouterLink to={`${row.original.id}`}><LuEllipsisVertical />- </RemixLink>+ </ReactRouterLink></Button></div></HStack>diff --git a/apps/erp/app/modules/production/ui/Schedule/Kanban/components/ItemCard.tsx b/apps/erp/app/modules/production/ui/Schedule/Kanban/components/ItemCard.tsxindex e36095a9ff..442a8078d1 100644--- a/apps/erp/app/modules/production/ui/Schedule/Kanban/components/ItemCard.tsx+++ b/apps/erp/app/modules/production/ui/Schedule/Kanban/components/ItemCard.tsx@@ -80,6 +80,7 @@ const cardVariants = cva(Done: "",Paused: "",Canceled: "border-red-500/30",+ Cancelled: "border-red-500/30",Waiting: "opacity-50",Todo: "border-border"}@@ -101,6 +102,7 @@ const cardHeaderVariants = cva(Todo: "",Paused: "",Canceled: "",+ Cancelled: "",Waiting: ""}},diff --git a/apps/erp/app/modules/resources/resources.service.ts b/apps/erp/app/modules/resources/resources.service.tsindex 83f917ca0e..7f9ab0608e 100644--- a/apps/erp/app/modules/resources/resources.service.ts+++ b/apps/erp/app/modules/resources/resources.service.ts@@ -76,6 +76,13 @@ export async function deleteShift(return client.from("shift").update({ active: false }).eq("id", shiftId);}+export async function deleteSuggestion(+ client: SupabaseClient<Database>,+ suggestionId: string+) {+ return client.from("suggestion").delete().eq("id", suggestionId);+}+export async function deleteTraining(client: SupabaseClient<Database>,trainingId: string@@ -368,6 +375,36 @@ export async function getProcessesList(.order("name");}+export async function getSuggestion(+ client: SupabaseClient<Database>,+ suggestionId: string+) {+ return client.from("suggestions").select("*").eq("id", suggestionId).single();+}++export async function getSuggestions(+ client: SupabaseClient<Database>,+ companyId: string,+ args?: GenericQueryFilters & { search: string | null }+) {+ let query = client+ .from("suggestions")+ .select("*", { count: "exact" })+ .eq("companyId", companyId);++ if (args?.search) {+ query = query.ilike("suggestion", `%${args.search}%`);+ }++ if (args) {+ query = setGenericQueryFilters(query, args, [+ { column: "createdAt", ascending: false }+ ]);+ }++ return query;+}+export async function getTraining(client: SupabaseClient<Database>,id: string@@ -678,6 +715,22 @@ export async function updateAbility(return client.from("ability").update(sanitize(ability)).eq("id", id);}+export async function updateSuggestionEmoji(+ client: SupabaseClient<Database>,+ suggestionId: string,+ emoji: string+) {+ return client.from("suggestion").update({ emoji }).eq("id", suggestionId);+}++export async function updateSuggestionTags(+ client: SupabaseClient<Database>,+ suggestionId: string,+ tags: string[]+) {+ return client.from("suggestion").update({ tags }).eq("id", suggestionId);+}+export async function updateTrainingQuestionOrder(client: SupabaseClient<Database>,updates: {diff --git a/apps/erp/app/modules/resources/types.ts b/apps/erp/app/modules/resources/types.tsindex af21c867dd..db7088435e 100644--- a/apps/erp/app/modules/resources/types.ts+++ b/apps/erp/app/modules/resources/types.ts@@ -10,6 +10,8 @@ import type {getLocations,getPartners,getProcesses,+ getSuggestion,+ getSuggestions,getTraining,getTrainingAssignment,getTrainingQuestions,@@ -125,3 +127,11 @@ export type TrainingAssignmentSummaryItem = {export type TrainingAssignment = NonNullable<Awaited<ReturnType<typeof getTrainingAssignment>>["data"]>;++export type Suggestion = NonNullable<+ Awaited<ReturnType<typeof getSuggestion>>["data"]+>;++export type SuggestionListItem = NonNullable<+ Awaited<ReturnType<typeof getSuggestions>>["data"]+>[number];diff --git a/apps/erp/app/modules/resources/ui/Suggestions/SuggestionDetails.tsx b/apps/erp/app/modules/resources/ui/Suggestions/SuggestionDetails.tsxnew file mode 100644index 0000000000..88b12ad087--- /dev/null+++ b/apps/erp/app/modules/resources/ui/Suggestions/SuggestionDetails.tsx@@ -0,0 +1,179 @@+import { ValidatedForm } from "@carbon/form";+import {+ Avatar,+ Drawer,+ DrawerBody,+ DrawerContent,+ DrawerHeader,+ DrawerTitle,+ HStack,+ Popover,+ PopoverContent,+ PopoverTrigger,+ VStack+} from "@carbon/react";+import { formatDate } from "@carbon/utils";+import data from "@emoji-mart/data";+import Picker from "@emoji-mart/react";+import { useCallback, useState } from "react";+import { useFetcher, useNavigate } from "react-router";+import z from "zod/v3";+import { Tags } from "~/components/Form";+import { useTags } from "~/hooks/useTags";+import type { Suggestion } from "~/modules/resources";+import { path } from "~/utils/path";++type SuggestionDetailsProps = {+ suggestion: Suggestion;+ tags: { name: string }[];+};++type EmojiData = {+ native: string;+ id: string;+ name: string;+};++export default function SuggestionDetails({+ suggestion,+ tags+}: SuggestionDetailsProps) {+ const navigate = useNavigate();+ const onClose = () => navigate(-1);+ const fetcher = useFetcher();+ const [emojiPickerOpen, setEmojiPickerOpen] = useState(false);++ const { onUpdateTags } = useTags({+ id: suggestion.id ?? "",+ table: "suggestion"+ });++ const onUpdateEmoji = useCallback(+ (emojiData: EmojiData) => {+ if (!suggestion.id) return;+ const formData = new FormData();+ formData.append("emoji", emojiData.native);+ fetcher.submit(formData, {+ method: "post",+ action: path.to.suggestion(suggestion.id)+ });+ setEmojiPickerOpen(false);+ },+ [suggestion.id, fetcher]+ );++ // Use optimistic emoji value+ const currentEmoji =+ fetcher.formData?.get("emoji")?.toString() ??+ (suggestion as { emoji?: string }).emoji ??+ "💡";++ return (+ <Drawer+ open+ onOpenChange={(open) => {+ if (!open) onClose();+ }}+ >+ <DrawerContent>+ <DrawerHeader>+ <DrawerTitle>Suggestion</DrawerTitle>+ </DrawerHeader>+ <DrawerBody>+ <VStack spacing={4}>+ <VStack spacing={2} className="w-full">+ <h3 className="text-xs text-muted-foreground">Emoji</h3>+ <Popover open={emojiPickerOpen} onOpenChange={setEmojiPickerOpen}>+ <PopoverTrigger asChild>+ <button+ type="button"+ className="inline-flex items-center justify-center rounded-md h-12 w-12 text-3xl hover:bg-accent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"+ >+ {currentEmoji}+ </button>+ </PopoverTrigger>+ <PopoverContent+ className="w-auto p-0 border-0 bg-white"+ align="start"+ sideOffset={8}+ >+ <Picker+ data={data}+ onEmojiSelect={onUpdateEmoji}+ theme="light"+ previewPosition="none"+ skinTonePosition="none"+ navPosition="bottom"+ perLine={8}+ />+ </PopoverContent>+ </Popover>+ </VStack>++ <VStack spacing={2} className="w-full">+ <h3 className="text-xs text-muted-foreground">Suggestion</h3>+ <div className="whitespace-pre-wrap text-sm">+ {suggestion.suggestion}+ </div>+ </VStack>++ <VStack spacing={2} className="w-full">+ <h3 className="text-xs text-muted-foreground">Submitted By</h3>+ <HStack spacing={2}>+ <Avatar+ size="sm"+ name={suggestion.employeeName ?? undefined}+ src={suggestion.employeeAvatarUrl ?? undefined}+ />+ <span>{suggestion.employeeName ?? "Anonymous"}</span>+ </HStack>+ </VStack>++ <VStack spacing={2} className="w-full">+ <h3 className="text-xs text-muted-foreground">Date</h3>+ <span>{formatDate(suggestion.createdAt)}</span>+ </VStack>++ <VStack spacing={2} className="w-full">+ <h3 className="text-xs text-muted-foreground">Path</h3>+ <span className="text-sm font-mono">{suggestion.path}</span>+ </VStack>++ {suggestion.attachmentPath && (+ <VStack spacing={2} className="w-full">+ <h3 className="text-xs text-muted-foreground">Attachment</h3>+ <a+ href={`/file/preview/private/${suggestion.attachmentPath}`}+ target="_blank"+ rel="noopener noreferrer"+ className="text-primary underline text-sm"+ >+ View Attachment+ </a>+ </VStack>+ )}++ <ValidatedForm+ defaultValues={{+ tags: suggestion.tags ?? []+ }}+ validator={z.object({+ tags: z.array(z.string()).optional()+ })}+ className="w-full"+ >+ <Tags+ availableTags={tags}+ label="Tags"+ name="tags"+ table="suggestion"+ inline+ onChange={onUpdateTags}+ />+ </ValidatedForm>+ </VStack>+ </DrawerBody>+ </DrawerContent>+ </Drawer>+ );+}diff --git a/apps/erp/app/modules/resources/ui/Suggestions/SuggestionsTable.tsx b/apps/erp/app/modules/resources/ui/Suggestions/SuggestionsTable.tsxnew file mode 100644index 0000000000..613db97d63--- /dev/null+++ b/apps/erp/app/modules/resources/ui/Suggestions/SuggestionsTable.tsx@@ -0,0 +1,163 @@+import { Avatar, Badge, HStack, MenuIcon, MenuItem } from "@carbon/react";+import { formatDate } from "@carbon/utils";+import type { ColumnDef } from "@tanstack/react-table";+import { memo, useCallback, useMemo } from "react";+import {+ LuCalendar,+ LuEye,+ LuFileText,+ LuTag,+ LuTrash,+ LuUser+} from "react-icons/lu";+import { useNavigate } from "react-router";+import { Hyperlink, Table } from "~/components";+import { usePermissions, useUrlParams } from "~/hooks";+import type { SuggestionListItem } from "~/modules/resources";+import { usePeople } from "~/stores";+import { path } from "~/utils/path";++type SuggestionsTableProps = {+ data: SuggestionListItem[];+ tags: { name: string }[];+ count: number;+};++const defaultColumnVisibility = {};++const SuggestionsTable = memo(+ ({ data, tags, count }: SuggestionsTableProps) => {+ const navigate = useNavigate();+ const permissions = usePermissions();+ const [params] = useUrlParams();+ const [people] = usePeople();++ const columns = useMemo<ColumnDef<SuggestionListItem>[]>(() => {+ const defaultColumns: ColumnDef<SuggestionListItem>[] = [+ {+ accessorKey: "suggestion",+ header: "Suggestion",+ cell: ({ row }) => (+ <Hyperlink to={row.original.id!}>+ <HStack spacing={2} className="max-w-[400px]">+ <span className="text-xl shrink-0">+ {row.original.emoji ?? "💡"}+ </span>+ <span className="truncate">+ {row.original.suggestion?.slice(0, 100)}+ {(row.original.suggestion?.length ?? 0) > 100 ? "..." : ""}+ </span>+ </HStack>+ </Hyperlink>+ ),+ meta: {+ icon: <LuFileText />+ }+ },+ {+ id: "employee",+ header: "Employee",+ cell: ({ row }) => (+ <HStack spacing={2}>+ <Avatar+ size="sm"+ name={row.original.employeeName ?? undefined}+ src={row.original.employeeAvatarUrl ?? undefined}+ />+ <span>{row.original.employeeName ?? "Anonymous"}</span>+ </HStack>+ ),+ meta: {+ icon: <LuUser />,+ filter: {+ type: "static",+ options: people.map((employee) => ({+ value: employee.id,+ label: employee.name+ }))+ }+ }+ },+ {+ accessorKey: "tags",+ header: "Tags",+ cell: ({ row }) => (+ <HStack spacing={0} className="gap-1">+ {row.original.tags?.map((tag) => (+ <Badge key={tag} variant="secondary">+ {tag}+ </Badge>+ ))}+ </HStack>+ ),+ meta: {+ filter: {+ type: "static",+ options: tags?.map((tag) => ({+ value: tag.name,+ label: <Badge variant="secondary">{tag.name}</Badge>+ })),+ isArray: true+ },+ icon: <LuTag />+ }+ },+ {+ accessorKey: "createdAt",+ header: "Date",+ cell: (item) => formatDate(item.getValue<string>()),+ meta: {+ icon: <LuCalendar />+ }+ }+ ];+ return defaultColumns;+ }, [tags, people]);++ const renderContextMenu = useCallback(+ (row: SuggestionListItem) => {+ return (+ <>+ <MenuItem+ onClick={() => {+ navigate(path.to.suggestion(row.id!));+ }}+ >+ <MenuIcon icon={<LuEye />} />+ View Suggestion+ </MenuItem>+ <MenuItem+ destructive+ disabled={!permissions.can("delete", "resources")}+ onClick={() => {+ navigate(+ `${path.to.deleteSuggestion(row.id!)}?${params.toString()}`+ );+ }}+ >+ <MenuIcon icon={<LuTrash />} />+ Delete Suggestion+ </MenuItem>+ </>+ );+ },+ [navigate, params, permissions]+ );++ return (+ <Table<SuggestionListItem>+ data={data}+ count={count}+ columns={columns}+ defaultColumnVisibility={defaultColumnVisibility}+ renderContextMenu={renderContextMenu}+ title="Suggestions"+ table="suggestion"+ withSavedView+ />+ );+ }+);++SuggestionsTable.displayName = "SuggestionsTable";+export default SuggestionsTable;diff --git a/apps/erp/app/modules/resources/ui/Suggestions/index.ts b/apps/erp/app/modules/resources/ui/Suggestions/index.tsnew file mode 100644index 0000000000..d78ebda8cf--- /dev/null+++ b/apps/erp/app/modules/resources/ui/Suggestions/index.ts@@ -0,0 +1,2 @@+export { default as SuggestionDetails } from "./SuggestionDetails";+export { default as SuggestionsTable } from "./SuggestionsTable";diff --git a/apps/erp/app/modules/resources/ui/index.ts b/apps/erp/app/modules/resources/ui/index.tsindex 1b2f73dfe9..c206d7d8f1 100644--- a/apps/erp/app/modules/resources/ui/index.ts+++ b/apps/erp/app/modules/resources/ui/index.ts@@ -4,6 +4,7 @@ export * from "./Contractors";export * from "./Locations";export * from "./Partners";export * from "./Processes";+export * from "./Suggestions";export * from "./Training";export * from "./WorkCenters";export { useResourcesSubmodules };diff --git a/apps/erp/app/modules/resources/ui/useResourcesSubmodules.tsx b/apps/erp/app/modules/resources/ui/useResourcesSubmodules.tsxindex 38caf1f30b..d450d681ea 100644--- a/apps/erp/app/modules/resources/ui/useResourcesSubmodules.tsx+++ b/apps/erp/app/modules/resources/ui/useResourcesSubmodules.tsx@@ -2,6 +2,7 @@ import {LuClipboardCheck,LuCog,LuGraduationCap,+ LuMailbox,LuMapPin,LuWrench} from "react-icons/lu";@@ -11,7 +12,7 @@ import { path } from "~/utils/path";const resourcesRoutes: RouteGroup[] = [{- name: "Manage",+ name: "Infrastructure",routes: [{name: "Locations",@@ -34,7 +35,7 @@ const resourcesRoutes: RouteGroup[] = []},{- name: "Training",+ name: "People",routes: [{name: "Training",@@ -46,6 +47,12 @@ const resourcesRoutes: RouteGroup[] = [name: "Assignments",to: path.to.trainingAssignments,icon: <LuClipboardCheck />+ },+ {+ name: "Suggestions",+ to: path.to.suggestions,+ icon: <LuMailbox />,+ table: "suggestion"}]}diff --git a/apps/erp/app/modules/settings/settings.models.ts b/apps/erp/app/modules/settings/settings.models.tsindex 7eeb787ae8..0c01fdfb4d 100644--- a/apps/erp/app/modules/settings/settings.models.ts+++ b/apps/erp/app/modules/settings/settings.models.ts@@ -114,6 +114,12 @@ export const rfqReadyValidator = z.object({.optional()});+export const suggestionNotificationValidator = z.object({+ suggestionNotificationGroup: z+ .array(z.string().min(1, { message: "Invalid selection" }))+ .optional()+});+export const sequenceValidator = z.object({table: z.string().min(1, { message: "Table is required" }),prefix: zfd.text(z.string().optional()),diff --git a/apps/erp/app/modules/settings/settings.service.ts b/apps/erp/app/modules/settings/settings.service.tsindex 9959692d94..5df6c1a960 100644--- a/apps/erp/app/modules/settings/settings.service.ts+++ b/apps/erp/app/modules/settings/settings.service.ts@@ -577,6 +577,17 @@ export async function updateRfqReadySetting(.eq("id", companyId);}+export async function updateSuggestionNotificationSetting(+ client: SupabaseClient<Database>,+ companyId: string,+ suggestionNotificationGroup: string[]+) {+ return client+ .from("company")+ .update(sanitize({ suggestionNotificationGroup }))+ .eq("id", companyId);+}+export async function updatePurchasePriceUpdateTimingSetting(client: SupabaseClient<Database>,companyId: string,diff --git a/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx b/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsxindex 410bb4d048..fe0a6989ae 100644--- a/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx+++ b/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx@@ -7,6 +7,7 @@ import {LuFactory,LuImage,LuLayoutDashboard,+ LuLightbulb,LuSheet,LuShoppingCart,LuSquareStack,@@ -91,6 +92,12 @@ const settingsRoutes: AuthenticatedRouteGroup<{to: path.to.salesSettings,role: "employee",icon: <LuCrown />+ },+ {+ name: "Resources",+ to: path.to.resourcesSettings,+ role: "employee",+ icon: <LuLightbulb />}]},diff --git a/apps/erp/app/modules/shared/shared.models.ts b/apps/erp/app/modules/shared/shared.models.tsindex 9263e1dddc..987e5fa4dd 100644--- a/apps/erp/app/modules/shared/shared.models.ts+++ b/apps/erp/app/modules/shared/shared.models.ts@@ -31,6 +31,7 @@ export const tablesWithTags = ["job","material","part",+ "suggestion","tool"];@@ -96,6 +97,14 @@ export const feedbackValidator = z.object({location: z.string()});+export const suggestionValidator = z.object({+ suggestion: z.string().min(1, { message: "Suggestion is required" }),+ emoji: z.string().default("💡"),+ attachmentPath: z.string().optional(),+ path: z.string(),+ userId: zfd.text(z.string().optional())+});+export const operationStepValidator = z.object({id: zfd.text(z.string().optional()),diff --git a/apps/erp/app/routes/x+/account+/$userId.delete.attribute.tsx b/apps/erp/app/routes/x+/account+/$userId.delete.attribute.tsxindex c8cef6d227..a56b39d078 100644--- a/apps/erp/app/routes/x+/account+/$userId.delete.attribute.tsx+++ b/apps/erp/app/routes/x+/account+/$userId.delete.attribute.tsx@@ -78,6 +78,6 @@ export async function action({ request, params }: ActionFunctionArgs) {}export default function UserAttributeValueRoute() {- // Remix bug+ // React Router bugreturn null;}diff --git a/apps/erp/app/routes/x+/resources+/suggestions.$suggestionId.tsx b/apps/erp/app/routes/x+/resources+/suggestions.$suggestionId.tsxnew file mode 100644index 0000000000..bf9df143cc--- /dev/null+++ b/apps/erp/app/routes/x+/resources+/suggestions.$suggestionId.tsx@@ -0,0 +1,68 @@+import { error, notFound } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";+import { redirect, useLoaderData } from "react-router";+import {+ getSuggestion,+ SuggestionDetails,+ updateSuggestionEmoji+} from "~/modules/resources";+import { getTagsList } from "~/modules/shared";+import { path } from "~/utils/path";++export async function loader({ request, params }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ view: "resources"+ });++ const { suggestionId } = params;+ if (!suggestionId) throw notFound("suggestionId was not found");++ const [suggestion, tags] = await Promise.all([+ getSuggestion(client, suggestionId),+ getTagsList(client, companyId, "suggestion")+ ]);++ if (suggestion.error) {+ throw redirect(+ path.to.suggestions,+ await flash(request, error(suggestion.error, "Failed to get suggestion"))+ );+ }++ return {+ suggestion: suggestion.data,+ tags: tags.data ?? []+ };+}++export async function action({ request, params }: ActionFunctionArgs) {+ const { client } = await requirePermissions(request, {+ update: "resources"+ });++ const { suggestionId } = params;+ if (!suggestionId) throw notFound("suggestionId was not found");++ const formData = await request.formData();+ const emoji = formData.get("emoji")?.toString();++ if (emoji) {+ const result = await updateSuggestionEmoji(client, suggestionId, emoji);+ if (result.error) {+ throw redirect(+ path.to.suggestion(suggestionId),+ await flash(request, error(result.error, "Failed to update emoji"))+ );+ }+ }++ return { success: true };+}++export default function SuggestionRoute() {+ const { suggestion, tags } = useLoaderData<typeof loader>();++ return <SuggestionDetails suggestion={suggestion} tags={tags} />;+}diff --git a/apps/erp/app/routes/x+/resources+/suggestions.delete.$suggestionId.tsx b/apps/erp/app/routes/x+/resources+/suggestions.delete.$suggestionId.tsxnew file mode 100644index 0000000000..2b3642ce16--- /dev/null+++ b/apps/erp/app/routes/x+/resources+/suggestions.delete.$suggestionId.tsx@@ -0,0 +1,68 @@+import { assertIsPost, error, notFound } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";+import { redirect, useLoaderData, useNavigate, useParams } from "react-router";+import { ConfirmDelete } from "~/components/Modals";+import { deleteSuggestion, getSuggestion } from "~/modules/resources";+import { path } from "~/utils/path";++export async function loader({ request, params }: LoaderFunctionArgs) {+ const { client } = await requirePermissions(request, {+ delete: "resources"+ });++ const { suggestionId } = params;+ if (!suggestionId) throw notFound("suggestionId was not found");++ const suggestion = await getSuggestion(client, suggestionId);++ if (suggestion.error) {+ throw redirect(+ path.to.suggestions,+ await flash(request, error(suggestion.error, "Failed to get suggestion"))+ );+ }++ return {+ suggestion: suggestion.data+ };+}++export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client } = await requirePermissions(request, {+ delete: "resources"+ });++ const { suggestionId } = params;+ if (!suggestionId) throw notFound("suggestionId was not found");++ const result = await deleteSuggestion(client, suggestionId);++ if (result.error) {+ throw redirect(+ path.to.suggestions,+ await flash(request, error(result.error, "Failed to delete suggestion"))+ );+ }++ throw redirect(path.to.suggestions);+}++export default function DeleteSuggestionRoute() {+ const { suggestion } = useLoaderData<typeof loader>();+ const navigate = useNavigate();+ const { suggestionId } = useParams();++ const onClose = () => navigate(path.to.suggestions);++ return (+ <ConfirmDelete+ action={path.to.deleteSuggestion(suggestionId!)}+ name={`Suggestion: ${suggestion.suggestion?.slice(0, 50)}...`}+ text="Are you sure you want to delete this suggestion? This action cannot be undone."+ onCancel={onClose}+ />+ );+}diff --git a/apps/erp/app/routes/x+/resources+/suggestions.new.tsx b/apps/erp/app/routes/x+/resources+/suggestions.new.tsxnew file mode 100644index 0000000000..d3bd3b6dd7--- /dev/null+++ b/apps/erp/app/routes/x+/resources+/suggestions.new.tsx@@ -0,0 +1,48 @@+import { getCarbonServiceRole } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { validator } from "@carbon/form";+import type { ActionFunctionArgs } from "react-router";+import { suggestionValidator } from "~/modules/shared";++export async function action({ request }: ActionFunctionArgs) {+ const { userId, companyId } = await requirePermissions(request, {});++ const formData = await request.formData();+ const validation = await validator(suggestionValidator).validate(formData);++ if (validation.error) {+ return {+ success: false,+ message: "Failed to submit suggestion"+ };+ }++ const {+ attachmentPath,+ emoji,+ suggestion,+ path,+ userId: formUserId+ } = validation.data;+ const serviceRole = await getCarbonServiceRole();++ const insertSuggestion = await serviceRole.from("suggestion").insert([+ {+ suggestion,+ emoji,+ path,+ attachmentPath: attachmentPath || null,+ userId: formUserId || null,+ companyId+ }+ ]);++ if (insertSuggestion.error) {+ return {+ success: false,+ message: "Failed to submit suggestion"+ };+ }++ return { success: true, message: "Suggestion submitted" };+}diff --git a/apps/erp/app/routes/x+/resources+/suggestions.tsx b/apps/erp/app/routes/x+/resources+/suggestions.tsxnew file mode 100644index 0000000000..3c5302ddea--- /dev/null+++ b/apps/erp/app/routes/x+/resources+/suggestions.tsx@@ -0,0 +1,68 @@+import { error } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { VStack } from "@carbon/react";+import type { LoaderFunctionArgs } from "react-router";+import { Outlet, redirect, useLoaderData } from "react-router";+import { getSuggestions, SuggestionsTable } from "~/modules/resources";+import { getTagsList } from "~/modules/shared";+import type { Handle } from "~/utils/handle";+import { path } from "~/utils/path";+import { getGenericQueryFilters } from "~/utils/query";++export const handle: Handle = {+ breadcrumb: "Suggestions",+ to: path.to.suggestions+};++export async function loader({ request }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ view: "resources",+ role: "employee",+ bypassRls: true+ });++ const url = new URL(request.url);+ const searchParams = new URLSearchParams(url.search);+ const search = searchParams.get("search");+ const { limit, offset, sorts, filters } =+ getGenericQueryFilters(searchParams);++ const [suggestions, tags] = await Promise.all([+ getSuggestions(client, companyId, {+ search,+ limit,+ offset,+ sorts,+ filters+ }),+ getTagsList(client, companyId, "suggestion")+ ]);++ if (suggestions.error) {+ throw redirect(+ path.to.resources,+ await flash(+ request,+ error(suggestions.error, "Failed to load suggestions")+ )+ );+ }++ return {+ suggestions: suggestions.data ?? [],+ tags: tags.data ?? [],+ count: suggestions.count ?? 0+ };+}++export default function SuggestionsRoute() {+ const { suggestions, tags, count } = useLoaderData<typeof loader>();++ return (+ <VStack spacing={0} className="h-full">+ <SuggestionsTable data={suggestions} tags={tags} count={count} />+ <Outlet />+ </VStack>+ );+}diff --git a/apps/erp/app/routes/x+/settings+/resources.tsx b/apps/erp/app/routes/x+/settings+/resources.tsxnew file mode 100644index 0000000000..c333eaaae3--- /dev/null+++ b/apps/erp/app/routes/x+/settings+/resources.tsx@@ -0,0 +1,142 @@+import { error } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { Submit, ValidatedForm, validator } from "@carbon/form";+import {+ Card,+ CardContent,+ CardDescription,+ CardFooter,+ CardHeader,+ CardTitle,+ Heading,+ Label,+ ScrollArea,+ toast,+ VStack+} from "@carbon/react";+import { useEffect } from "react";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";+import { redirect, useFetcher, useLoaderData } from "react-router";+import { Users } from "~/components/Form";+import {+ getCompany,+ suggestionNotificationValidator,+ updateSuggestionNotificationSetting+} from "~/modules/settings";+import type { Handle } from "~/utils/handle";+import { path } from "~/utils/path";++export const handle: Handle = {+ breadcrumb: "Resources",+ to: path.to.resourcesSettings+};++export async function loader({ request }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ view: "settings"+ });++ const company = await getCompany(client, companyId);++ if (!company.data)+ throw redirect(+ path.to.settings,+ await flash(request, error(company.error, "Failed to get company"))+ );+ return { company: company.data };+}++export async function action({ request }: ActionFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ update: "settings"+ });++ const formData = await request.formData();+ const validation = await validator(suggestionNotificationValidator).validate(+ formData+ );++ if (validation.error) {+ return { success: false, message: "Invalid form data" };+ }++ const update = await updateSuggestionNotificationSetting(+ client,+ companyId,+ validation.data.suggestionNotificationGroup ?? []+ );++ if (update.error) return { success: false, message: update.error.message };++ return {+ success: true,+ message: "Suggestion notification settings updated"+ };+}++export default function ResourcesSettingsRoute() {+ const { company } = useLoaderData<typeof loader>();+ const fetcher = useFetcher<typeof action>();++ useEffect(() => {+ if (fetcher.data?.success === true && fetcher?.data?.message) {+ toast.success(fetcher.data.message);+ }++ if (fetcher.data?.success === false && fetcher?.data?.message) {+ toast.error(fetcher.data.message);+ }+ }, [fetcher.data?.message, fetcher.data?.success]);++ return (+ <ScrollArea className="w-full h-[calc(100dvh-49px)]">+ <VStack+ spacing={4}+ className="py-12 px-4 max-w-[60rem] h-full mx-auto gap-4"+ >+ <Heading size="h3">Resources</Heading>++ <Card>+ <ValidatedForm+ method="post"+ validator={suggestionNotificationValidator}+ defaultValues={{+ suggestionNotificationGroup:+ company.suggestionNotificationGroup ?? []+ }}+ fetcher={fetcher}+ >+ <CardHeader>+ <CardTitle className="flex items-center gap-2">+ Suggestion Notifications+ </CardTitle>+ <CardDescription>+ Configure notifications for when new suggestions are submitted.+ </CardDescription>+ </CardHeader>+ <CardContent>+ <div className="flex flex-col gap-8 max-w-[400px]">+ <div className="flex flex-col gap-2">+ <Label>Suggestion Notifications</Label>+ <Users+ name="suggestionNotificationGroup"+ label="Who should receive notifications when a new suggestion is submitted?"+ />+ </div>+ </div>+ </CardContent>+ <CardFooter>+ <Submit+ isDisabled={fetcher.state !== "idle"}+ isLoading={fetcher.state !== "idle"}+ >+ Save+ </Submit>+ </CardFooter>+ </ValidatedForm>+ </Card>+ </VStack>+ </ScrollArea>+ );+}diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.tsindex 988d82257a..268a3529d8 100644--- a/apps/erp/app/utils/path.ts+++ b/apps/erp/app/utils/path.ts@@ -687,7 +687,13 @@ export const path = {generatePath(`${x}/purchasing/supplier-statuses/delete/${id}`),deleteSupplierType: (id: string) =>generatePath(`${x}/purchasing/supplier-types/delete/${id}`),+ deleteSuggestion: (id: string) =>+ generatePath(`${x}/resources/suggestions/delete/${id}`),deleteTraining: (id: string) => generatePath(`${x}/training/delete/${id}`),+ deleteTrainingAssignment: (assignmentId: string) =>+ generatePath(+ `${x}/resources/assignments/assignment/${assignmentId}/delete`+ ),deleteTrainingQuestion: (id: string, questionId: string) =>generatePath(`${x}/training/${id}/questions/delete/${questionId}`),deleteUom: (id: string) => generatePath(`${x}/items/uom/delete/${id}`),@@ -729,6 +735,7 @@ export const path = {externalTraining: (assignmentId: string) =>generatePath(`/share/training/${assignmentId}`),feedback: `${x}/feedback`,+ resourcesSettings: `${x}/settings/resources`,fiscalYears: `${x}/accounting/years`,gauge: (id: string) => generatePath(`${x}/quality/gauges/${id}`),gauges: `${x}/quality/gauges`,@@ -978,6 +985,7 @@ export const path = {newStockTransfer: `${x}/stock-transfer/new`,newStockTransferLine: (id: string) =>generatePath(`${x}/stock-transfer/${id}/line/new`),+ newSuggestion: `${x}/resources/suggestions/new`,newProcedure: `${x}/production/procedures/new`,newProcedureStep: (id: string) =>generatePath(`${x}/procedure/${id}/steps/new`),@@ -1116,6 +1124,9 @@ export const path = {stockTransferStatus: (id: string) =>generatePath(`${x}/stock-transfer/${id}/status`),stockTransfers: `${x}/inventory/stock-transfers`,+ suggestion: (id: string) =>+ generatePath(`${x}/resources/suggestions/${id}`),+ suggestions: `${x}/resources/suggestions`,procedure: (id: string) => generatePath(`${x}/procedure/${id}`),procedureStep: (id: string, attributeId: string) =>generatePath(`${x}/procedure/${id}/steps/${attributeId}`),@@ -1133,7 +1144,6 @@ export const path = {generatePath(`${x}/production/planning/${itemId}`),productionSettings: `${x}/settings/production`,profile: `${x}/account/profile`,- qualitySettings: `${x}/settings/quality`,purchaseInvoice: (id: string) =>generatePath(`${x}/purchase-invoice/${id}`),purchaseInvoiceDelivery: (id: string) =>@@ -1195,10 +1205,8 @@ export const path = {newTrainingAssignment: `${x}/resources/assignments/new`,trainingAssignment: (assignmentId: string) =>generatePath(`${x}/resources/assignments/assignment/${assignmentId}`),- deleteTrainingAssignment: (assignmentId: string) =>- generatePath(- `${x}/resources/assignments/assignment/${assignmentId}/delete`- ),++ qualitySettings: `${x}/settings/quality`,quote: (id: string) => generatePath(`${x}/quote/${id}`),quoteAssembly: (quoteId: string, lineId: string, assemblyId: string) =>diff --git a/apps/mes/app/components/AppSidebar.tsx b/apps/mes/app/components/AppSidebar.tsxindex fc958b7498..601d3720ee 100644--- a/apps/mes/app/components/AppSidebar.tsx+++ b/apps/mes/app/components/AppSidebar.tsx@@ -55,7 +55,7 @@ import type { Location } from "~/services/types";import { ERP_URL, path } from "~/utils/path";import { AdjustInventory } from "./AdjustInventory";import { EndShift } from "./EndShift";-import Feedback from "./Feedback";+import Suggestion from "./Suggestion";export function AppSidebar({activeEvents,@@ -220,7 +220,7 @@ export function ToolsNav() {</SidebarMenuItem><SidebarMenuItem>- <Feedback />+ <Suggestion /></SidebarMenuItem></SidebarMenu></SidebarGroup>diff --git a/apps/mes/app/components/Suggestion.tsx b/apps/mes/app/components/Suggestion.tsxnew file mode 100644index 0000000000..914bce0ca8--- /dev/null+++ b/apps/mes/app/components/Suggestion.tsx@@ -0,0 +1,222 @@+import { useCarbon } from "@carbon/auth";+import {+ Hidden,+ Submit,+ TextAreaControlled,+ ValidatedForm+} from "@carbon/form";+import {+ Badge,+ BadgeCloseButton,+ Button,+ Checkbox,+ File,+ HStack,+ Popover,+ PopoverContent,+ PopoverTrigger,+ SidebarMenuButton,+ toast,+ VStack+} from "@carbon/react";+import data from "@emoji-mart/data";+import Picker from "@emoji-mart/react";+import { nanoid } from "nanoid";+import type { ChangeEvent } from "react";+import { useEffect, useRef, useState } from "react";+import { LuImage, LuLightbulb } from "react-icons/lu";+import { useFetcher, useLocation } from "react-router";+import { useUser } from "~/hooks";+import type { action } from "~/routes/x+/suggestion";+import { suggestionValidator } from "~/services/models";+import { path } from "~/utils/path";++const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB in bytes++type EmojiData = {+ native: string;+ id: string;+ name: string;+};++const Suggestion = () => {+ const fetcher = useFetcher<typeof action>();+ const location = useLocation();+ const popoverTriggerRef = useRef<HTMLButtonElement>(null);+ const [suggestion, setSuggestion] = useState("");+ const [emoji, setEmoji] = useState("💡");+ const [emojiPickerOpen, setEmojiPickerOpen] = useState(false);+ const [anonymous, setAnonymous] = useState(true);+ const [attachment, setAttachment] = useState<{+ name: string;+ path: string;+ } | null>(null);+ const { carbon } = useCarbon();+ const user = useUser();+ const companyId = user.company.id;++ useEffect(() => {+ if (fetcher.data?.success) {+ toast.success(fetcher.data.message);+ setSuggestion("");+ setEmoji("💡");+ setAttachment(null);+ setAnonymous(true);+ 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 fileName = `${companyId}/suggestions/${nanoid()}.${fileExtension}`;+ const imageUpload = await carbon.storage+ .from("private")+ .upload(fileName, 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+ });+ }+ }+ };++ const onEmojiSelect = (emojiData: EmojiData) => {+ setEmoji(emojiData.native);+ setEmojiPickerOpen(false);+ };++ return (+ <Popover>+ <PopoverTrigger ref={popoverTriggerRef} asChild>+ <SidebarMenuButton>+ <LuLightbulb />+ <span>Suggestion</span>+ </SidebarMenuButton>+ </PopoverTrigger>+ <PopoverContent className="w-[380px] ">+ <ValidatedForm+ method="post"+ action={path.to.suggestion}+ validator={suggestionValidator}+ fetcher={fetcher}+ >+ <Hidden name="path" value={location.pathname} />+ <Hidden name="emoji" value={emoji} />+ <Hidden name="attachmentPath" value={attachment?.path ?? ""} />+ <Hidden name="userId" value={anonymous ? "" : user.id} />+ <VStack spacing={2}>+ <VStack spacing={2} className="w-full">+ <TextAreaControlled+ name="suggestion"+ label=""+ value={suggestion}+ onChange={(value) => setSuggestion(value)}+ placeholder="Ideas, suggestions or problems?"+ />+ {attachment && (+ <Badge className="-mt-2 truncate" variant="secondary">+ {attachment.name}+ <BadgeCloseButton+ type="button"+ onClick={() => {+ setAttachment(null);+ }}+ />+ </Badge>+ )}+ </VStack>+ <HStack className="w-full justify-between">+ <HStack spacing={2}>+ <Checkbox+ isChecked={anonymous}+ onCheckedChange={(checked) => setAnonymous(checked === true)}+ />+ <span className="text-sm">Submit anonymously</span>+ </HStack>+ <Popover open={emojiPickerOpen} onOpenChange={setEmojiPickerOpen}>+ <PopoverTrigger asChild>+ <button+ type="button"+ className="inline-flex items-center justify-center rounded-md h-10 w-10 text-2xl hover:bg-accent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 shrink-0"+ >+ {emoji}+ </button>+ </PopoverTrigger>+ <PopoverContent+ className="w-auto p-0 border-0 bg-white"+ align="end"+ sideOffset={8}+ >+ <Picker+ data={data}+ onEmojiSelect={onEmojiSelect}+ theme="light"+ previewPosition="none"+ skinTonePosition="none"+ navPosition="bottom"+ perLine={8}+ />+ </PopoverContent>+ </Popover>+ </HStack>+ <HStack className="w-full justify-between">+ <Button+ variant="secondary"+ onClick={() => {+ setSuggestion("");+ setEmoji("💡");+ setAttachment(null);+ popoverTriggerRef.current?.click();+ }}+ >+ Cancel+ </Button>+ <HStack spacing={1}>+ <Button+ isDisabled={suggestion.length === 0}+ variant="secondary"+ onClick={() => setSuggestion("")}+ >+ Clear+ </Button>+ <File+ accept="image/*"+ aria-label="Attach File"+ className="px-2"+ isDisabled={!!attachment}+ variant="secondary"+ onChange={uploadImage}+ >+ <LuImage />+ </File>+ <Submit isDisabled={suggestion.length < 3}>Send</Submit>+ </HStack>+ </HStack>+ </VStack>+ </ValidatedForm>+ </PopoverContent>+ </Popover>+ );+};++export default Suggestion;diff --git a/apps/mes/app/routes/x+/suggestion.tsx b/apps/mes/app/routes/x+/suggestion.tsxnew file mode 100644index 0000000000..1e4ceb94d7--- /dev/null+++ b/apps/mes/app/routes/x+/suggestion.tsx@@ -0,0 +1,48 @@+import { getCarbonServiceRole } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { validator } from "@carbon/form";+import type { ActionFunctionArgs } from "react-router";+import { suggestionValidator } from "~/services/models";++export async function action({ request }: ActionFunctionArgs) {+ const { userId, companyId } = await requirePermissions(request, {});++ const formData = await request.formData();+ const validation = await validator(suggestionValidator).validate(formData);++ if (validation.error) {+ return {+ success: false,+ message: "Failed to submit suggestion"+ };+ }++ const {+ attachmentPath,+ emoji,+ suggestion,+ path,+ userId: formUserId+ } = validation.data;+ const serviceRole = await getCarbonServiceRole();++ const insertSuggestion = await serviceRole.from("suggestion").insert([+ {+ suggestion,+ emoji,+ path,+ attachmentPath: attachmentPath || null,+ userId: formUserId || null,+ companyId+ }+ ]);++ if (insertSuggestion.error) {+ return {+ success: false,+ message: "Failed to submit suggestion"+ };+ }++ return { success: true, message: "Suggestion submitted" };+}diff --git a/apps/mes/app/services/models.ts b/apps/mes/app/services/models.tsindex e2b2067323..856aa20fb2 100644--- a/apps/mes/app/services/models.ts+++ b/apps/mes/app/services/models.ts@@ -72,6 +72,14 @@ export const feedbackValidator = z.object({location: z.string()});+export const suggestionValidator = z.object({+ suggestion: z.string().min(1, { message: "Suggestion is required" }),+ emoji: z.string().default("💡"),+ attachmentPath: z.string().optional(),+ path: z.string(),+ userId: zfd.text(z.string().optional())+});+export const productionEventType = ["Setup", "Labor", "Machine"] as const;export const productionEventAction = ["Start", "End"] as const;diff --git a/apps/mes/app/utils/path.ts b/apps/mes/app/utils/path.tsindex 1b6aa74281..4d9dfb8883 100644--- a/apps/mes/app/utils/path.ts+++ b/apps/mes/app/utils/path.ts@@ -124,14 +124,15 @@ export const path = {root: "/",scrap: `${x}/scrap`,scrapReasons: `${api}/scrap-reasons`,- startOperation: (id: string) => generatePath(`${x}/start/${id}`),- switchCompany: (companyId: string) =>- generatePath(`${x}/company/switch/${companyId}`),- unconsume: `${x}/unconsume`,scrapEntity: (operationId: string, id: string, parentId?: string) => {const basePath = generatePath(`${x}/entity/${operationId}/${id}/scrap`);return parentId ? `${basePath}?parentId=${parentId}` : basePath;},+ startOperation: (id: string) => generatePath(`${x}/start/${id}`),+ switchCompany: (companyId: string) =>+ generatePath(`${x}/company/switch/${companyId}`),+ suggestion: `${x}/suggestion`,+ unconsume: `${x}/unconsume`,workCenter: (workCenter: string) =>generatePath(`${x}/operations/${workCenter}`)}diff --git a/llm/cache/clientAction-patterns.md b/llm/cache/clientAction-patterns.mdindex 9845f3f27b..d1dfbcc904 100644--- a/llm/cache/clientAction-patterns.md+++ b/llm/cache/clientAction-patterns.md@@ -2,7 +2,7 @@## Overview-ClientAction is a Remix feature used to handle client-side operations before calling the server action. In this codebase, it's primarily used for cache invalidation with React Query.+ClientAction is a React Router feature used to handle client-side operations before calling the server action. In this codebase, it's primarily used for cache invalidation with React Query.## Common Patternsdiff --git a/llm/cache/coding-conventions.md b/llm/cache/coding-conventions.mdindex 5c86687deb..4b770ef193 100644--- a/llm/cache/coding-conventions.md+++ b/llm/cache/coding-conventions.md@@ -103,7 +103,7 @@ export async function action({ request }: ActionFunctionArgs) {- Uses nanostores for global state- React Query for server state-- Remix's built-in data loading for route-specific data+- React Router's built-in data loading for route-specific data## Error Handlingdiff --git a/llm/cache/flash-system.md b/llm/cache/flash-system.mdindex 9cb9f9b708..bb5d0c8d7f 100644--- a/llm/cache/flash-system.md+++ b/llm/cache/flash-system.md@@ -54,7 +54,7 @@ export async function flash(request: Request, result: Result) {**How it works:**1. Retrieves the current session from the request-2. Uses Remix's `session.flash()` to store temporary data that will be cleared after being read once+2. Uses React Router's `session.flash()` to store temporary data that will be cleared after being read once3. Stores three pieces of data: `success` (boolean), `message` (string), and optionally `flash` (visual effect type)4. Returns headers to commit the session cookiediff --git a/llm/cache/project-overview.md b/llm/cache/project-overview.mdindex fa18e41742..db22f0da38 100644--- a/llm/cache/project-overview.md+++ b/llm/cache/project-overview.md@@ -12,7 +12,7 @@ Carbon is a manufacturing system built with modern web technologies. It consists### Frontend-- **Framework**: Remix (React-based)+- **Framework**: React Router (React-based)- **UI Components**: Custom component library at `/packages/react/`- **Styling**: Tailwind CSS- **Forms**: Custom form library at `/packages/form/`@@ -43,7 +43,7 @@ The monorepo uses NPM workspaces with packages located in `/packages/`:- `logger` - Logging utilities- `notifications` - Notification services- `react` - Shared React components-- `remix` - Remix-specific utilities+- `remix` - React Router-specific utilities- `utils` - Common utilities## Common Patterns@@ -54,7 +54,7 @@ Each app follows a consistent structure:- `components/` - React components- `hooks/` - Custom React hooks-- `routes/` - Remix routes+- `routes/` - React Router routes- `services/` - Business logic and API calls- `stores/` - State management (appears to use nanostores)- `styles/` - CSS files@@ -77,7 +77,7 @@ The ERP app organizes business logic into modules:### Routing-- Uses Remix flat routes+- Uses React Router flat routes- Protected routes under `x+/` prefix- Public routes under `_public+/` prefix- API routes under `api+/` prefixdiff --git a/llm/cache/shipments-receipts-ui-patterns.md b/llm/cache/shipments-receipts-ui-patterns.mdindex c31771279a..bd73583108 100644--- a/llm/cache/shipments-receipts-ui-patterns.md+++ b/llm/cache/shipments-receipts-ui-patterns.md@@ -190,7 +190,7 @@ To refactor warehouse transfers to match this pattern:## Data Flow Patterns### Optimistic Updates-- Uses Remix fetchers for optimistic UI updates+- Uses React Router fetchers for optimistic UI updates- Pending changes merged with server data- Real-time feedback without full page reloadsdiff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex a672071271..0521ffd9ac 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -1995,6 +1995,7 @@ export type Database = {postalCode: string | nullslackChannel: string | nullstateProvince: string | null+ suggestionNotificationGroup: string[]taxId: string | nullupdatedBy: string | nullwebsite: string | null@@ -2020,6 +2021,7 @@ export type Database = {postalCode?: string | nullslackChannel?: string | nullstateProvince?: string | null+ suggestionNotificationGroup?: string[]taxId?: string | nullupdatedBy?: string | nullwebsite?: string | null@@ -2045,6 +2047,7 @@ export type Database = {postalCode?: string | nullslackChannel?: string | nullstateProvince?: string | null+ suggestionNotificationGroup?: string[]taxId?: string | nullupdatedBy?: string | nullwebsite?: string | null@@ -31476,6 +31479,106 @@ export type Database = {},]}+ suggestion: {+ Row: {+ attachmentPath: string | null+ companyId: string+ createdAt: string+ emoji: string+ id: string+ path: string+ suggestion: string+ tags: string[] | null+ userId: string | null+ }+ Insert: {+ attachmentPath?: string | null+ companyId: string+ createdAt?: string+ emoji?: string+ id?: string+ path: string+ suggestion: string+ tags?: string[] | null+ userId?: string | null+ }+ Update: {+ attachmentPath?: string | null+ companyId?: string+ createdAt?: string+ emoji?: string+ id?: string+ path?: string+ suggestion?: string+ tags?: string[] | null+ userId?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "suggestion_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "suggestion_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "suggestion_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "suggestion_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "suggestion_userId_fkey"+ columns: ["userId"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "suggestion_userId_fkey"+ columns: ["userId"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "suggestion_userId_fkey"+ columns: ["userId"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "suggestion_userId_fkey"+ columns: ["userId"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "suggestion_userId_fkey"+ columns: ["userId"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ ]+ }supplier: {Row: {accountManagerId: string | null@@ -38486,6 +38589,7 @@ export type Database = {defaultMethodType: Database["public"]["Enums"]["methodType"] | nulldescription: string | nullid: string | null+ itemPostingGroupId: string | nullitemTrackingType:| Database["public"]["Enums"]["itemTrackingType"]| null@@ -38672,6 +38776,13 @@ export type Database = {referencedRelation: "userDefaults"referencedColumns: ["userId"]},+ {+ foreignKeyName: "itemCost_itemPostingGroupId_fkey"+ columns: ["itemPostingGroupId"]+ isOneToOne: false+ referencedRelation: "itemPostingGroup"+ referencedColumns: ["id"]+ },]}contractors: {@@ -41728,6 +41839,7 @@ export type Database = {finish: string | nullgrade: string | nullid: string | null+ itemPostingGroupId: string | nullitemTrackingType:| Database["public"]["Enums"]["itemTrackingType"]| null@@ -41919,6 +42031,13 @@ export type Database = {referencedRelation: "userDefaults"referencedColumns: ["userId"]},+ {+ foreignKeyName: "itemCost_itemPostingGroupId_fkey"+ columns: ["itemPostingGroupId"]+ isOneToOne: false+ referencedRelation: "itemPostingGroup"+ referencedColumns: ["id"]+ },{foreignKeyName: "material_materialFormId_fkey"columns: ["materialFormId"]@@ -42619,6 +42738,7 @@ export type Database = {defaultMethodType: Database["public"]["Enums"]["methodType"] | nulldescription: string | nullid: string | null+ itemPostingGroupId: string | nullitemTrackingType:| Database["public"]["Enums"]["itemTrackingType"]| null@@ -42783,6 +42903,13 @@ export type Database = {referencedRelation: "userDefaults"referencedColumns: ["userId"]},+ {+ foreignKeyName: "itemCost_itemPostingGroupId_fkey"+ columns: ["itemPostingGroupId"]+ isOneToOne: false+ referencedRelation: "itemPostingGroup"+ referencedColumns: ["id"]+ },]}procedures: {@@ -43931,14 +44058,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["supplierCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["supplierCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -46994,14 +47121,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["paymentCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["paymentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -48301,6 +48428,86 @@ export type Database = {},]}+ suggestions: {+ Row: {+ attachmentPath: string | null+ companyId: string | null+ createdAt: string | null+ emoji: string | null+ employeeAvatarUrl: string | null+ employeeName: string | null+ id: string | null+ path: string | null+ suggestion: string | null+ tags: string[] | null+ userId: string | null+ }+ Relationships: [+ {+ foreignKeyName: "suggestion_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "suggestion_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "suggestion_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "suggestion_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "suggestion_userId_fkey"+ columns: ["userId"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "suggestion_userId_fkey"+ columns: ["userId"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "suggestion_userId_fkey"+ columns: ["userId"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "suggestion_userId_fkey"+ columns: ["userId"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "suggestion_userId_fkey"+ columns: ["userId"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ ]+ }supplierProcesses: {Row: {companyId: string | null@@ -49126,6 +49333,7 @@ export type Database = {defaultMethodType: Database["public"]["Enums"]["methodType"] | nulldescription: string | nullid: string | null+ itemPostingGroupId: string | nullitemTrackingType:| Database["public"]["Enums"]["itemTrackingType"]| null@@ -49290,6 +49498,13 @@ export type Database = {referencedRelation: "userDefaults"referencedColumns: ["userId"]},+ {+ foreignKeyName: "itemCost_itemPostingGroupId_fkey"+ columns: ["itemPostingGroupId"]+ isOneToOne: false+ referencedRelation: "itemPostingGroup"+ referencedColumns: ["id"]+ },]}trainings: {@@ -49760,6 +49975,7 @@ export type Database = {defaultMethodType: Database["public"]["Enums"]["methodType"]description: stringid: string+ itemPostingGroupId: stringitemTrackingType: Database["public"]["Enums"]["itemTrackingType"]modelName: stringmodelPath: string@@ -50157,6 +50373,7 @@ export type Database = {grade: stringgradeId: stringid: string+ itemPostingGroupId: stringitemTrackingType: Database["public"]["Enums"]["itemTrackingType"]materialForm: stringmaterialFormId: string@@ -50271,6 +50488,7 @@ export type Database = {defaultMethodType: Database["public"]["Enums"]["methodType"]description: stringid: string+ itemPostingGroupId: stringitemTrackingType: Database["public"]["Enums"]["itemTrackingType"]modelId: stringmodelName: string@@ -50727,6 +50945,7 @@ export type Database = {defaultMethodType: Database["public"]["Enums"]["methodType"]description: stringid: string+ itemPostingGroupId: stringitemTrackingType: Database["public"]["Enums"]["itemTrackingType"]modelId: stringmodelName: stringdiff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex a672071271..0521ffd9ac 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -1995,6 +1995,7 @@ export type Database = {postalCode: string | nullslackChannel: string | nullstateProvince: string | null+ suggestionNotificationGroup: string[]taxId: string | nullupdatedBy: string | nullwebsite: string | null@@ -2020,6 +2021,7 @@ export type Database = {postalCode?: string | nullslackChannel?: string | nullstateProvince?: string | null+ suggestionNotificationGroup?: string[]taxId?: string | nullupdatedBy?: string | nullwebsite?: string | null@@ -2045,6 +2047,7 @@ export type Database = {postalCode?: string | nullslackChannel?: string | nullstateProvince?: string | null+ suggestionNotificationGroup?: string[]taxId?: string | nullupdatedBy?: string | nullwebsite?: string | null@@ -31476,6 +31479,106 @@ export type Database = {},]}+ suggestion: {+ Row: {+ attachmentPath: string | null+ companyId: string+ createdAt: string+ emoji: string+ id: string+ path: string+ suggestion: string+ tags: string[] | null+ userId: string | null+ }+ Insert: {+ attachmentPath?: string | null+ companyId: string+ createdAt?: string+ emoji?: string+ id?: string+ path: string+ suggestion: string+ tags?: string[] | null+ userId?: string | null+ }+ Update: {+ attachmentPath?: string | null+ companyId?: string+ createdAt?: string+ emoji?: string+ id?: string+ path?: string+ suggestion?: string+ tags?: string[] | null+ userId?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "suggestion_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "suggestion_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "suggestion_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "suggestion_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "suggestion_userId_fkey"+ columns: ["userId"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "suggestion_userId_fkey"+ columns: ["userId"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "suggestion_userId_fkey"+ columns: ["userId"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "suggestion_userId_fkey"+ columns: ["userId"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "suggestion_userId_fkey"+ columns: ["userId"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ ]+ }supplier: {Row: {accountManagerId: string | null@@ -38486,6 +38589,7 @@ export type Database = {defaultMethodType: Database["public"]["Enums"]["methodType"] | nulldescription: string | nullid: string | null+ itemPostingGroupId: string | nullitemTrackingType:| Database["public"]["Enums"]["itemTrackingType"]| null@@ -38672,6 +38776,13 @@ export type Database = {referencedRelation: "userDefaults"referencedColumns: ["userId"]},+ {+ foreignKeyName: "itemCost_itemPostingGroupId_fkey"+ columns: ["itemPostingGroupId"]+ isOneToOne: false+ referencedRelation: "itemPostingGroup"+ referencedColumns: ["id"]+ },]}contractors: {@@ -41728,6 +41839,7 @@ export type Database = {finish: string | nullgrade: string | nullid: string | null+ itemPostingGroupId: string | nullitemTrackingType:| Database["public"]["Enums"]["itemTrackingType"]| null@@ -41919,6 +42031,13 @@ export type Database = {referencedRelation: "userDefaults"referencedColumns: ["userId"]},+ {+ foreignKeyName: "itemCost_itemPostingGroupId_fkey"+ columns: ["itemPostingGroupId"]+ isOneToOne: false+ referencedRelation: "itemPostingGroup"+ referencedColumns: ["id"]+ },{foreignKeyName: "material_materialFormId_fkey"columns: ["materialFormId"]@@ -42619,6 +42738,7 @@ export type Database = {defaultMethodType: Database["public"]["Enums"]["methodType"] | nulldescription: string | nullid: string | null+ itemPostingGroupId: string | nullitemTrackingType:| Database["public"]["Enums"]["itemTrackingType"]| null@@ -42783,6 +42903,13 @@ export type Database = {referencedRelation: "userDefaults"referencedColumns: ["userId"]},+ {+ foreignKeyName: "itemCost_itemPostingGroupId_fkey"+ columns: ["itemPostingGroupId"]+ isOneToOne: false+ referencedRelation: "itemPostingGroup"+ referencedColumns: ["id"]+ },]}procedures: {@@ -43931,14 +44058,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["supplierCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["supplierCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -46994,14 +47121,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["paymentCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["paymentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -48301,6 +48428,86 @@ export type Database = {},]}+ suggestions: {+ Row: {+ attachmentPath: string | null+ companyId: string | null+ createdAt: string | null+ emoji: string | null+ employeeAvatarUrl: string | null+ employeeName: string | null+ id: string | null+ path: string | null+ suggestion: string | null+ tags: string[] | null+ userId: string | null+ }+ Relationships: [+ {+ foreignKeyName: "suggestion_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "suggestion_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "suggestion_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "suggestion_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "suggestion_userId_fkey"+ columns: ["userId"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "suggestion_userId_fkey"+ columns: ["userId"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "suggestion_userId_fkey"+ columns: ["userId"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "suggestion_userId_fkey"+ columns: ["userId"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "suggestion_userId_fkey"+ columns: ["userId"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ ]+ }supplierProcesses: {Row: {companyId: string | null@@ -49126,6 +49333,7 @@ export type Database = {defaultMethodType: Database["public"]["Enums"]["methodType"] | nulldescription: string | nullid: string | null+ itemPostingGroupId: string | nullitemTrackingType:| Database["public"]["Enums"]["itemTrackingType"]| null@@ -49290,6 +49498,13 @@ export type Database = {referencedRelation: "userDefaults"referencedColumns: ["userId"]},+ {+ foreignKeyName: "itemCost_itemPostingGroupId_fkey"+ columns: ["itemPostingGroupId"]+ isOneToOne: false+ referencedRelation: "itemPostingGroup"+ referencedColumns: ["id"]+ },]}trainings: {@@ -49760,6 +49975,7 @@ export type Database = {defaultMethodType: Database["public"]["Enums"]["methodType"]description: stringid: string+ itemPostingGroupId: stringitemTrackingType: Database["public"]["Enums"]["itemTrackingType"]modelName: stringmodelPath: string@@ -50157,6 +50373,7 @@ export type Database = {grade: stringgradeId: stringid: string+ itemPostingGroupId: stringitemTrackingType: Database["public"]["Enums"]["itemTrackingType"]materialForm: stringmaterialFormId: string@@ -50271,6 +50488,7 @@ export type Database = {defaultMethodType: Database["public"]["Enums"]["methodType"]description: stringid: string+ itemPostingGroupId: stringitemTrackingType: Database["public"]["Enums"]["itemTrackingType"]modelId: stringmodelName: string@@ -50727,6 +50945,7 @@ export type Database = {defaultMethodType: Database["public"]["Enums"]["methodType"]description: stringid: string+ itemPostingGroupId: stringitemTrackingType: Database["public"]["Enums"]["itemTrackingType"]modelId: stringmodelName: stringdiff --git a/packages/database/supabase/migrations/20251213153733_suggestions.sql b/packages/database/supabase/migrations/20251213153733_suggestions.sqlnew file mode 100644index 0000000000..e29ed15db6--- /dev/null+++ b/packages/database/supabase/migrations/20251213153733_suggestions.sql@@ -0,0 +1,77 @@+CREATE TABLE "suggestion" (+ "id" TEXT NOT NULL DEFAULT id(),+ "suggestion" TEXT NOT NULL,+ "emoji" TEXT NOT NULL DEFAULT '💡',+ "path" TEXT NOT NULL,+ "attachmentPath" TEXT,+ "tags" TEXT[] DEFAULT '{}',+ "userId" TEXT,+ "companyId" TEXT NOT NULL,+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),++ CONSTRAINT "suggestion_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "suggestion_userId_fkey" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE SET NULL ON UPDATE CASCADE,+ CONSTRAINT "suggestion_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE+);++ALTER TABLE "suggestion" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "SELECT" ON "suggestion"+FOR SELECT USING (+ "companyId" = ANY (+ (+ SELECT+ get_companies_with_employee_permission ('resources_view')+ )::text[]+ )+);++CREATE POLICY "INSERT" ON "suggestion"+FOR INSERT WITH CHECK (+ "companyId" = ANY (+ (+ SELECT+ get_companies_with_employee_role()+ )::text[]+ )+);++CREATE POLICY "UPDATE" ON "suggestion"+FOR UPDATE USING (+ "companyId" = ANY (+ (+ SELECT+ get_companies_with_employee_permission ('resources_update')+ )::text[]+ )+);++CREATE POLICY "DELETE" ON "suggestion"+FOR DELETE USING (+ "companyId" = ANY (+ (+ SELECT+ get_companies_with_employee_permission ('resources_delete')+ )::text[]+ )+);++ALTER TABLE "company"+ ADD COLUMN IF NOT EXISTS "suggestionNotificationGroup" text[] NOT NULL DEFAULT '{}';++DROP VIEW IF EXISTS "suggestions";+CREATE OR REPLACE VIEW "suggestions" AS+ SELECT+ s."id",+ s."suggestion",+ s."emoji",+ s."path",+ s."attachmentPath",+ s."tags",+ s."userId",+ s."companyId",+ s."createdAt",+ u."fullName" AS "employeeName",+ u."avatarUrl" AS "employeeAvatarUrl"+ FROM "suggestion" s+ LEFT JOIN "user" u ON s."userId" = u."id";\ No newline at end of filediff --git a/packages/form/src/ValidatedForm.tsx b/packages/form/src/ValidatedForm.tsxindex 41fb7771dc..f305a47d51 100644--- a/packages/form/src/ValidatedForm.tsx+++ b/packages/form/src/ValidatedForm.tsx@@ -12,7 +12,7 @@ import type {FormMethod,SubmitOptions} from "react-router";-import { Form as RemixForm, useSubmit } from "react-router";+import { Form as ReactRouterForm, useSubmit } from "react-router";import * as R from "remeda";import type { z } from "zod/v3";import { useIsSubmitting, useIsValid } from "./hooks";@@ -82,7 +82,7 @@ export type FormProps<DataType, Subaction extends string | undefined> = {*/onAfterSubmit?: () => void | Promise<void>;/**- * Allows you to provide a `fetcher` from Remix's `useFetcher` hook.+ * Allows you to provide a `fetcher` from React Router's `useFetcher` hook.* The form will use the fetcher for loading states, action data, etc* instead of the default form action.*/@@ -113,7 +113,7 @@ export type FormProps<DataType, Subaction extends string | undefined> = {* Set this to `false` to disable this behavior.*/disableFocusOnError?: boolean;-} & Omit<ComponentProps<typeof RemixForm>, "onSubmit">;+} & Omit<ComponentProps<typeof ReactRouterForm>, "onSubmit">;const getDataFromForm = (el: HTMLFormElement) => new FormData(el);@@ -298,7 +298,7 @@ export function ValidatedForm<const backendDefaultValues = useDefaultValuesFromLoader(contextValue);const hasActiveSubmission = useHasActiveFormSubmit(contextValue);const formRef = useRef<HTMLFormElement>(null);- const Form = fetcher?.Form ?? RemixForm;+ const Form = fetcher?.Form ?? ReactRouterForm;const submit = useSubmit();const setFieldErrors = useSetFieldErrors(formId);@@ -426,8 +426,8 @@ export function ValidatedForm<encType: encType as FormEncType | undefined};- // We deviate from the Remix code here a bit because of our async submit.- // In Remix's `FormImpl`, they use `event.currentTarget` to get the form,+ // We deviate from the React Routers code here a bit because of our async submit.+ // In React Routers's `FormImpl`, they use `event.currentTarget` to get the form,// but we already have the form in `formRef.current` so we can just use that.// If we use `event.currentTarget` here, it will break because `currentTarget`// will have changed since the start of the submission.diff --git a/packages/form/src/hooks.ts b/packages/form/src/hooks.tsindex a0a275fcb6..b8e6b5a7c2 100644--- a/packages/form/src/hooks.ts+++ b/packages/form/src/hooks.ts@@ -23,7 +23,7 @@ import {/*** Returns whether or not the parent form is currently being submitted.- * This is different from Remix's `useNavigation()` in that it+ * This is different from React Router's `useNavigation()` in that it* is aware of what form it's in and when _that_ form is being submitted.** @param formIddiff --git a/patches/@ai-sdk-tools+store+1.2.0.patch b/patches/@ai-sdk-tools+store+1.2.0.patchnew file mode 100644index 0000000000..c10c7b2e1f--- /dev/null+++ b/patches/@ai-sdk-tools+store+1.2.0.patch@@ -0,0 +1,26 @@+diff --git a/node_modules/@ai-sdk-tools/store/dist/index.js b/node_modules/@ai-sdk-tools/store/dist/index.js+index dcd0f3d..9fdc5aa 100644+--- a/node_modules/@ai-sdk-tools/store/dist/index.js++++ b/node_modules/@ai-sdk-tools/store/dist/index.js+@@ -60,7 +60,7 @@ module.exports = __toCommonJS(index_exports);+ // src/debug.ts+ var DebugLogger = class {+ constructor(options = {}) {+- this.enabled = options.enabled ?? process.env.DEBUG === "true";++ this.enabled = options.enabled ?? false;+ this.prefix = options.prefix ?? "[Store]";+ this.level = options.level ?? "warn";+ }+diff --git a/node_modules/@ai-sdk-tools/store/dist/index.mjs b/node_modules/@ai-sdk-tools/store/dist/index.mjs+index b733596..e39e45f 100644+--- a/node_modules/@ai-sdk-tools/store/dist/index.mjs++++ b/node_modules/@ai-sdk-tools/store/dist/index.mjs+@@ -3,7 +3,7 @@+ // src/debug.ts+ var DebugLogger = class {+ constructor(options = {}) {+- this.enabled = options.enabled ?? process.env.DEBUG === "true";++ this.enabled = options.enabled ?? false;+ this.prefix = options.prefix ?? "[Store]";+ this.level = options.level ?? "warn";+ }