Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

9.1 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-only
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.

import { CARBON_SLACK_ENABLED, useCarbon } from "@carbon/auth";
import { getCompanyPrivateBucket, storage } from "@carbon/files";
import { convertHeicToJpeg, isHeic } from "@carbon/files/media";
import {
  Hidden,
  Submit,
  TextAreaControlled,
  ValidatedForm
} from "@carbon/form";
import { getLogger } from "@carbon/logger";
import {
  Badge,
  BadgeCloseButton,
  Button,
  Checkbox,
  File,
  HStack,
  NavRailItem,
  Popover,
  PopoverContent,
  PopoverTrigger,
  toast,
  useMode,
  VStack
} from "@carbon/react";
import data from "@emoji-mart/data";
import { Trans, useLingui } from "@lingui/react/macro";
import { nanoid } from "nanoid";
import type { ChangeEvent } from "react";
import { lazy, Suspense, useEffect, useRef, useState } from "react";
import { LuImage, LuMailbox } 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";
import { MorePage, useMorePage } from "./MoreSheet";

// Lazy, not a static import: @emoji-mart/react is CommonJS, so under SSR its
// default import is `{ default: Picker }` and dev React warns "type is
// invalid" the moment the element is created, even in a closed popover.
const Picker = lazy(() => import("@emoji-mart/react"));

const log = getLogger("mes");

const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB in bytes

type EmojiData = {
  native: string;
  id: string;
  name: string;
};

const Suggestion = () => {
  const { t } = useLingui();
  const fetcher = useFetcher<typeof action>();
  const location = useLocation();
  const popoverTriggerRef = useRef<HTMLButtonElement>(null);
  // Phones: the form is a page of the More sheet, not a popover.
  const morePage = useMorePage();
  const close = () =>
    morePage ? morePage.back() : popoverTriggerRef.current?.click();
  const [suggestion, setSuggestion] = useState("");
  const [emoji, setEmoji] = useState("💡");
  const [emojiPickerOpen, setEmojiPickerOpen] = useState(false);
  const [anonymous, setAnonymous] = useState(true);
  const [sendToCarbon, setSendToCarbon] = useState(CARBON_SLACK_ENABLED);
  const mode = useMode();
  const pickerTheme = mode;
  const [attachment, setAttachment] = useState<{
    name: string;
    path: string;
  } | null>(null);
  const { carbon } = useCarbon();
  const user = useUser();

  const companyId = user.company.id;

  // biome-ignore lint/correctness/useExhaustiveDependencies: runs once per submission result
  useEffect(() => {
    if (fetcher.data?.success) {
      toast.success(fetcher.data.message);
      setSuggestion("");
      setEmoji("💡");
      setAttachment(null);
      setAnonymous(true);
      setSendToCarbon(CARBON_SLACK_ENABLED);
      if (morePage) morePage.done();
      else 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) {
      let file = e.target.files[0];

      if (file.size > MAX_FILE_SIZE) {
        toast.error(t`File size exceeds 10MB limit`);
        return;
      }

      if (isHeic(file.name, file.type)) {
        try {
          file = await convertHeicToJpeg(carbon, {
            bucket: getCompanyPrivateBucket(companyId),
            directory: `${companyId}/tmp`,
            file
          });
        } catch {
          toast.error(t`Failed to convert image`);
          return;
        }
      }

      const fileExtension = file.name.substring(file.name.lastIndexOf(".") + 1);
      const fileName = `${companyId}/suggestions/${nanoid()}.${fileExtension}`;
      const imageUpload = await storage(carbon)
        .company(companyId)
        .upload(fileName, file, {
          cacheControl: `${12 * 60 * 60}`,
          upsert: true
        });

      if (imageUpload.error) {
        log.error("Failed to upload image", { error: imageUpload.error });
        toast.error(t`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);
  };

  const form = (
    <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} />
      <Hidden name="sendToCarbon" value={sendToCarbon ? "true" : ""} />
      <VStack spacing={2}>
        <VStack spacing={2} className="w-full">
          <TextAreaControlled
            name="suggestion"
            label=""
            value={suggestion}
            onChange={(value) => setSuggestion(value)}
            placeholder={t`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">
          <VStack spacing={2}>
            <HStack spacing={2}>
              <Checkbox
                isChecked={anonymous}
                onCheckedChange={(checked) => setAnonymous(checked === true)}
              />
              <span className="text-sm">
                <Trans>Submit anonymously</Trans>
              </span>
            </HStack>
            {CARBON_SLACK_ENABLED && (
              <HStack spacing={2}>
                <Checkbox
                  isChecked={sendToCarbon}
                  onCheckedChange={(checked) =>
                    setSendToCarbon(checked === true)
                  }
                />
                <span className="text-sm">
                  <Trans>Send to Carbon</Trans>
                </span>
              </HStack>
            )}
          </VStack>
          <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"
              align="end"
              sideOffset={8}
            >
              <Suspense>
                <Picker
                  data={data}
                  onEmojiSelect={onEmojiSelect}
                  theme={pickerTheme}
                  previewPosition="none"
                  skinTonePosition="none"
                  navPosition="bottom"
                  perLine={8}
                />
              </Suspense>
            </PopoverContent>
          </Popover>
        </HStack>
        <HStack className="w-full justify-between">
          <Button
            variant="secondary"
            onClick={() => {
              setSuggestion("");
              setEmoji("💡");
              setAttachment(null);
              close();
            }}
          >
            <Trans>Cancel</Trans>
          </Button>
          <HStack spacing={1}>
            <Button
              isDisabled={suggestion.length === 0}
              variant="secondary"
              onClick={() => setSuggestion("")}
            >
              <Trans>Clear</Trans>
            </Button>
            <File
              accept="image/*"
              aria-label="Attach File"
              className="px-2"
              isDisabled={!!attachment}
              variant="secondary"
              onChange={uploadImage}
            >
              <LuImage />
            </File>
            <Submit isDisabled={suggestion.length < 3}>
              <Trans>Send</Trans>
            </Submit>
          </HStack>
        </HStack>
      </VStack>
    </ValidatedForm>
  );

  if (morePage) {
    return (
      <>
        <NavRailItem
          icon={<LuMailbox />}
          label={t`Suggestion`}
          onClick={() => morePage.open("suggestion", t`Suggestion`)}
        />
        <MorePage tool="suggestion">{form}</MorePage>
      </>
    );
  }

  return (
    <Popover>
      <PopoverTrigger ref={popoverTriggerRef} asChild>
        <NavRailItem icon={<LuMailbox />} label={t`Suggestion`} />
      </PopoverTrigger>
      <PopoverContent className="w-[380px] ">{form}</PopoverContent>
    </Popover>
  );
};

export default Suggestion;