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.

Add Linear integration – issue sync, UI, webhook, notifications & 2‑way sync (#379)

Sid1a4193db6cb8
diff --git a/apps/academy/app/config.tsx b/apps/academy/app/config.tsx
index bcd6c8bbcf..33918e21ef 100644
--- a/apps/academy/app/config.tsx
+++ b/apps/academy/app/config.tsx
@@ -1485,6 +1485,15 @@ export const modules: Config = [
"Learn how to sync orders from Paperless Parts to Carbon.",
duration: 160,
},
+ {
+ id: "linear-integration",
+ loomUrl:
+ "https://www.loom.com/share/714bda8164a64ad28ce7cb6f02b3260a?sid=85542655-886a-4053-9c2f-79426e62232b",
+ name: "Linear Integration",
+ description: "Learn how to sync issues from Linear to Carbon.",
+ duration: 143,
+ },
+
{
id: "slack-integration",
loomUrl:
diff --git a/apps/erp/app/components/Icons.tsx b/apps/erp/app/components/Icons.tsx
index e4426494c7..6d798c7d1c 100644
--- a/apps/erp/app/components/Icons.tsx
+++ b/apps/erp/app/components/Icons.tsx
@@ -8,6 +8,7 @@ import {
LuBox,
LuCircle,
LuCircleCheck,
+ LuCircleDashed,
LuCircleX,
LuClipboardCheck,
LuClock,
@@ -35,6 +36,8 @@ import {
import { RxCodesandboxLogo } from "react-icons/rx";
import { TbTargetOff } from "react-icons/tb";
+import type { LinearIssue } from "@carbon/ee/linear";
+import { mapLinearStatusToCarbonStatus } from "@carbon/ee/linear";
import { useMode } from "@carbon/remix";
import { getColor } from "@carbon/utils";
import { Link } from "@remix-run/react";
@@ -201,7 +204,7 @@ export const IssueTaskStatusIcon = ({
}) => {
switch (status) {
case "Pending":
- return <TodoStatusIcon className={cn("text-foreground", className)} />;
+ return <LuCircleDashed className={cn("text-foreground", className)} />;
case "Skipped":
return <LuCircleX className={cn("text-muted-foreground", className)} />;
case "Completed":
@@ -321,3 +324,77 @@ export const TimeTypeIcon = ({
return <LuSquare className={cn("text-muted-foreground", className)} />;
};
+
+export const LinearIcon = (props: React.SVGProps<SVGSVGElement>) => {
+ return (
+ <svg
+ viewBox="0 0 24 24"
+ fill="none"
+ xmlns="http://www.w3.org/2000/svg"
+ stroke="#717ce2"
+ transform="matrix(1, 0, 0, 1, 0, 0)"
+ className={props.className}
+ {...props}
+ >
+ <g id="SVGRepo_bgCarrier" stroke-width="0"></g>
+ <g
+ id="SVGRepo_tracerCarrier"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ ></g>
+ <g id="SVGRepo_iconCarrier">
+ {" "}
+ <path
+ d="M3.03509 12.9431C3.24245 14.9227 4.10472 16.8468 5.62188 18.364C7.13904 19.8811 9.0631 20.7434 11.0428 20.9508L3.03509 12.9431Z"
+ fill="currentColor"
+ ></path>{" "}
+ <path
+ d="M3 11.4938L12.4921 20.9858C13.2976 20.9407 14.0981 20.7879 14.8704 20.5273L3.4585 9.11548C3.19793 9.88771 3.0451 10.6883 3 11.4938Z"
+ fill="currentColor"
+ />{" "}
+ <path
+ d="M3.86722 8.10999L15.8758 20.1186C16.4988 19.8201 17.0946 19.4458 17.6493 18.9956L4.99021 6.33659C4.54006 6.89125 4.16573 7.487 3.86722 8.10999Z"
+ fill="currentColor"
+ />{" "}
+ <path
+ d="M5.66301 5.59517C9.18091 2.12137 14.8488 2.135 18.3498 5.63604C21.8508 9.13708 21.8645 14.8049 18.3907 18.3228L5.66301 5.59517Z"
+ fill="currentColor"
+ />{" "}
+ </g>
+ </svg>
+ );
+};
+
+export const LinearIssueStateBadge = (props: {
+ state: LinearIssue["state"];
+ className?: string;
+}) => {
+ const status = mapLinearStatusToCarbonStatus(props.state.type);
+ let className = props.className;
+
+ let icon: React.ReactNode = (
+ <LuCircleDashed className={cn("text-foreground", className)} />
+ );
+
+ switch (status) {
+ case "Pending":
+ icon = <LuCircleDashed className={cn("text-foreground", className)} />;
+ break;
+ case "Skipped":
+ icon = <LuCircleX className={cn("text-muted-foreground", className)} />;
+ break;
+ case "Completed":
+ icon = <LuCircleCheck className={cn("text-emerald-600", className)} />;
+ break;
+ case "In Progress":
+ icon = <AlmostDoneIcon className={className} />;
+ break;
+ }
+
+ return (
+ <Badge variant={"secondary"} className="py-1 bg-transparent">
+ {icon}
+ <span className="ml-1">{props.state.name}</span>
+ </Badge>
+ );
+};
diff --git a/apps/erp/app/components/Layout/Navigation/GroupedContentSidebar.tsx b/apps/erp/app/components/Layout/Navigation/GroupedContentSidebar.tsx
index ed117acf32..a00a0635bf 100644
--- a/apps/erp/app/components/Layout/Navigation/GroupedContentSidebar.tsx
+++ b/apps/erp/app/components/Layout/Navigation/GroupedContentSidebar.tsx
@@ -103,7 +103,7 @@ const GroupedContentSidebar = ({
className={cn(
"justify-start flex-grow truncate",
!isActive &&
- "hover:bg-active hover:text-active-foreground"
+ "hover:bg-active hover:text-active-foreground hover:scale-100 focus-visible:scale-100"
)}
>
<Link
diff --git a/apps/erp/app/hooks/useAsyncFetcher.tsx b/apps/erp/app/hooks/useAsyncFetcher.tsx
new file mode 100644
index 0000000000..447300baf3
--- /dev/null
+++ b/apps/erp/app/hooks/useAsyncFetcher.tsx
@@ -0,0 +1,56 @@
+import type { Fetcher } from "@remix-run/react";
+import { useFetcher } from "@remix-run/react";
+import { noop } from "@tanstack/react-query";
+import { useCallback, useEffect, useRef } from "react";
+
+type FetcherOptions = {
+ key?: string;
+ onStateChange?: (state: Fetcher["state"]) => Promise<void> | void;
+};
+
+export function useAsyncFetcher<TData>(options?: FetcherOptions) {
+ const onStateChange = options?.onStateChange || noop;
+
+ const fetcher = useFetcher<TData>({
+ key: options?.key,
+ });
+
+ const instance = useRef<PromiseWithResolvers<TData>>();
+
+ if (!instance.current) {
+ instance.current = Promise.withResolvers<TData>();
+ }
+
+ const submit = useCallback(
+ (...args: Parameters<typeof fetcher.submit>) => {
+ fetcher.submit(...args);
+ return instance.current!.promise;
+ },
+ [fetcher, instance]
+ );
+
+ const load = useCallback(
+ (...args: Parameters<typeof fetcher.load>) => {
+ fetcher.load(...args);
+ return instance.current!.promise;
+ },
+ [fetcher, instance]
+ );
+
+ useEffect(() => {
+ onStateChange(fetcher.state);
+ if (fetcher.state === "idle") {
+ if (fetcher.data) {
+ instance.current?.resolve(fetcher.data as TData); // I think we don't need to use SerializeFrom here
+ instance.current = Promise.withResolvers<TData>();
+ }
+ }
+ }, [fetcher.state, fetcher.data, onStateChange]);
+
+ return {
+ ...fetcher,
+ data: fetcher.data as TData,
+ submit,
+ load,
+ };
+}
diff --git a/apps/erp/app/modules/quality/quality.service.ts b/apps/erp/app/modules/quality/quality.service.ts
index 96d61133de..86d93a6f11 100644
--- a/apps/erp/app/modules/quality/quality.service.ts
+++ b/apps/erp/app/modules/quality/quality.service.ts
@@ -370,6 +370,17 @@ export async function getIssueWorkflow(
.single();
}
+export async function getIssueAction(
+ client: SupabaseClient<Database>,
+ id: string
+) {
+ return client
+ .from("nonConformanceActionTask")
+ .select("id, ...nonConformance(nonConformanceId)")
+ .eq("id", id)
+ .single();
+}
+
export async function getIssueActionTasks(
client: SupabaseClient<Database>,
id: string,
@@ -1007,14 +1018,14 @@ export async function updateIssueTaskStatus(
args: {
id: string;
status: "Pending" | "Completed" | "Skipped" | "In Progress";
- type: "action" | "approval" | "review";
+ type: "investigation" | "action" | "approval" | "review";
userId?: string;
assignee?: string | null;
}
) {
const { id, status, type, userId, assignee } = args;
const table =
- type === "action"
+ type === "action" || type === "investigation"
? "nonConformanceActionTask"
: type === "review"
? "nonConformanceReviewer"
@@ -1023,18 +1034,14 @@ export async function updateIssueTaskStatus(
const finalAssignee = assignee || userId;
// Set completedDate to today when status is "Completed"
- const updateData: {
- status: string;
- updatedBy?: string;
- assignee?: string | null;
- completedDate?: string;
- } = {
+ const updateData = {
status,
updatedBy: userId,
assignee: finalAssignee,
};
if (status === "Completed") {
+ // @ts-expect-error
updateData.completedDate = new Date().toISOString().split("T")[0];
}
diff --git a/apps/erp/app/modules/quality/ui/Issue/IssueTask.tsx b/apps/erp/app/modules/quality/ui/Issue/IssueTask.tsx
index fa478891f7..2ff8a194ea 100644
--- a/apps/erp/app/modules/quality/ui/Issue/IssueTask.tsx
+++ b/apps/erp/app/modules/quality/ui/Issue/IssueTask.tsx
@@ -49,6 +49,8 @@ import { useProcesses } from "~/components/Form/Process";
import { IssueTaskStatusIcon } from "~/components/Icons";
import SupplierAvatar from "~/components/SupplierAvatar";
import { usePermissions, useRouteData, useUser } from "~/hooks";
+import { useIntegrations } from "~/hooks/useIntegrations";
+import { useRealtime } from "~/hooks/useRealtime";
import type {
Issue,
IssueActionTask,
@@ -59,6 +61,7 @@ import type {
import { nonConformanceTaskStatus } from "~/modules/quality";
import { useSuppliers } from "~/stores";
import { getPrivateUrl, path } from "~/utils/path";
+import { LinearIssueDialog } from "./Linear/IssueDialog";
export function TaskProgress({
tasks,
@@ -257,20 +260,33 @@ export function TaskItem({
showDragHandle?: boolean;
dragControls?: DragControls;
}) {
+ useRealtime("nonConformanceActionTask", `id=eq.${task.id}`);
+
+ const integrations = useIntegrations();
const permissions = usePermissions();
const disclosure = useDisclosure({
defaultIsOpen: true,
});
+
const { currentStatus, onOperationStatusChange } = useTaskStatus({
task,
type,
disabled: isDisabled,
});
- const statusAction = statusActions[currentStatus];
+ const statusAction =
+ statusActions[currentStatus as keyof typeof statusActions];
+
+ // Check if this action task has a linked Linear issue
+ const hasLinearLink =
+ type === "action" &&
+ !!(task as IssueActionTask & { externalId?: { linear?: unknown } })
+ .externalId?.linear;
+
const { content, setContent, onUpdateContent, onUploadImage } = useTaskNotes({
initialContent: (task.notes ?? {}) as JSONContent,
taskId: task.id!,
type,
+ hasLinearLink,
});
const { id } = useParams();
@@ -304,6 +320,9 @@ export function TaskItem({
<LuGripVertical size={16} />
</button>
)}
+
+ {integrations.has("linear") && <LinearIssueDialog task={task} />}
+
<IconButton
icon={<LuChevronRight />}
variant="ghost"
@@ -353,6 +372,7 @@ export function TaskItem({
)}
</div>
)}
+
<div className="bg-muted/30 border-t px-4 py-2 flex justify-between w-full">
<HStack>
<IssueTaskStatus
@@ -410,10 +430,12 @@ function useTaskNotes({
initialContent,
taskId,
type,
+ hasLinearLink = false,
}: {
initialContent: JSONContent;
taskId: string;
type: "investigation" | "action" | "approval" | "review";
+ hasLinearLink?: boolean;
}) {
const {
id: userId,
@@ -445,13 +467,32 @@ function useTaskNotes({
const onUpdateContent = useDebounce(
async (content: JSONContent) => {
+ // Update notes in Carbon database
await carbon
+ // @ts-expect-error -
?.from(table)
.update({
notes: content,
updatedBy: userId,
})
.eq("id", taskId!);
+
+ // Sync to Linear if this is an action task with a linked Linear issue
+ if (type === "action" && hasLinearLink) {
+ try {
+ await fetch(path.to.api.linearSyncNotes, {
+ method: "POST",
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
+ body: new URLSearchParams({
+ actionId: taskId,
+ notes: JSON.stringify(content),
+ }),
+ });
+ } catch (e) {
+ // Silently fail Linear sync - not critical
+ console.error("Failed to sync notes to Linear:", e);
+ }
+ }
},
2500,
true
diff --git a/apps/erp/app/modules/quality/ui/Issue/Linear/CreateIssue.tsx b/apps/erp/app/modules/quality/ui/Issue/Linear/CreateIssue.tsx
new file mode 100644
index 0000000000..af70b64326
--- /dev/null
+++ b/apps/erp/app/modules/quality/ui/Issue/Linear/CreateIssue.tsx
@@ -0,0 +1,117 @@
+import type { LinearTeam, LinearUser } from "@carbon/ee/linear";
+import {
+ Hidden,
+ Input,
+ Select,
+ Submit,
+ TextArea,
+ ValidatedForm,
+} from "@carbon/form";
+import { Button, ModalFooter, VStack } from "@carbon/react";
+import { useEffect, useId, useMemo, useState } from "react";
+import z from "zod";
+import { useAsyncFetcher } from "~/hooks/useAsyncFetcher";
+import type { IssueActionTask } from "~/modules/quality";
+import { path } from "~/utils/path";
+
+type Props = {
+ task: IssueActionTask;
+ onClose: () => void;
+};
+
+const createIssueValidator = z.object({
+ actionId: z.string(),
+ teamId: z.string(),
+ title: z.string().min(1, "Title is required"),
+ description: z.string().min(1, "Description is required"),
+});
+
+export const CreateIssue = (props: Props) => {
+ const id = useId();
+ const [team, setTeam] = useState<string | undefined>();
+
+ const { teams, members, fetcher } = useLinearTeams(team);
+
+ const teamOptions = useMemo(
+ () => teams.map((el) => ({ label: el.name, value: el.id })),
+ [teams]
+ );
+ const membersOptions = useMemo(
+ () => members.map((el) => ({ label: el.email, value: el.id })),
+ [members]
+ );
+
+ const isSearching = fetcher.state === "loading";
+
+ return (
+ <ValidatedForm
+ id={id}
+ method="post"
+ action={path.to.api.linearCreateIssue}
+ validator={createIssueValidator}
+ fetcher={fetcher}
+ resetAfterSubmit
+ onAfterSubmit={() => props.onClose()}
+ >
+ <VStack spacing={4}>
+ <Hidden name="actionId" value={props.task.id} />
+ <Select
+ isLoading={isSearching}
+ label="Linear Team"
+ name="teamId"
+ placeholder="Select a team"
+ value={team}
+ onChange={(e) => setTeam(e?.value)}
+ options={teamOptions}
+ />
+ <Input label="Title" name="title" placeholder="Issue title" required />
+ <TextArea
+ label="Description"
+ name="description"
+ placeholder="Issue description"
+ required
+ />
+ <Select
+ label="Assign To"
+ name="assignee"
+ placeholder="Select a assignee"
+ isOptional
+ options={membersOptions}
+ />
+ </VStack>
+ <ModalFooter>
+ <Button
+ variant="secondary"
+ onClick={() => {
+ props.onClose();
+ }}
+ >
+ Cancel
+ </Button>
+ <Submit>Create</Submit>
+ </ModalFooter>
+ </ValidatedForm>
+ );
+};
+
+CreateIssue.displayName = "CreateIssue";
+
+const useLinearTeams = (teamId?: string) => {
+ const fetcher = useAsyncFetcher<{
+ teams: LinearTeam[];
+ members: LinearUser[];
+ }>();
+
+ useEffect(() => {
+ fetcher.load(
+ path.to.api.linearCreateIssue + (teamId ? `?teamId=${teamId}` : "")
+ );
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [teamId]);
+
+ return {
+ teams: fetcher.data?.teams || [],
+ members: fetcher.data?.members || [],
+ fetcher,
+ };
+};
diff --git a/apps/erp/app/modules/quality/ui/Issue/Linear/IssueDialog.tsx b/apps/erp/app/modules/quality/ui/Issue/Linear/IssueDialog.tsx
new file mode 100644
index 0000000000..322881f37a
--- /dev/null
+++ b/apps/erp/app/modules/quality/ui/Issue/Linear/IssueDialog.tsx
@@ -0,0 +1,168 @@
+import {
+ Badge,
+ Button,
+ cn,
+ IconButton,
+ Modal,
+ ModalBody,
+ ModalContent,
+ ModalDescription,
+ ModalHeader,
+ ModalTitle,
+ ModalTrigger,
+ Tabs,
+ TabsContent,
+ TabsList,
+ TabsTrigger,
+ useDisclosure,
+} from "@carbon/react";
+import { useState } from "react";
+import type { IssueActionTask } from "~/modules/quality/types";
+
+import { LinearIssueSchema, type LinearIssue } from "@carbon/ee/linear";
+import { Link, useRevalidator } from "@remix-run/react";
+import { LuExternalLink } from "react-icons/lu";
+import { PiLinkBreak } from "react-icons/pi";
+import { LinearIcon, LinearIssueStateBadge } from "~/components/Icons";
+import { useAsyncFetcher } from "~/hooks/useAsyncFetcher";
+import { path } from "~/utils/path";
+import { CreateIssue } from "./CreateIssue";
+import { LinkIssue } from "./LinkIssue";
+
+interface Props {
+ task: IssueActionTask & {
+ externalId: { linear: LinearIssue } | undefined;
+ };
+}
+
+export const LinearIssueDialog = ({ task }: Props) => {
+ const [tab, setTab] = useState("link");
+ const revalidator = useRevalidator();
+
+ const disclosure = useDisclosure({
+ onClose() {
+ revalidator.revalidate();
+ },
+ });
+
+ const { data: linked } = LinearIssueSchema.safeParse(task.externalId?.linear);
+ const fetcher = useAsyncFetcher();
+
+ const onUnlink = async () => {
+ await fetcher.submit(
+ { actionId: task.id },
+ { method: "DELETE", action: path.to.api.linearLinkExistingIssue }
+ );
+ disclosure.onClose();
+ };
+
+ return (
+ <Modal
+ open={disclosure.isOpen}
+ onOpenChange={(open) => {
+ console.log("ON open changed");
+ if (!open) {
+ disclosure.onClose();
+ }
+ }}
+ >
+ <ModalTrigger onClick={() => disclosure.onToggle()}>
+ {linked ? (
+ <Button
+ leftIcon={<LinearIcon className={"size-4"} />}
+ variant="ghost"
+ aria-label="Update Linear issue"
+ >
+ {linked.identifier}
+ </Button>
+ ) : (
+ <IconButton
+ icon={<LinearIcon className={"size-4 grayscale"} />}
+ variant="ghost"
+ aria-label="Connect Linear issue"
+ />
+ )}
+ </ModalTrigger>
+ <ModalContent size={"large"}>
+ <Tabs value={tab} onValueChange={setTab} defaultValue="link">
+ <ModalHeader className="mb-1 flex-row justify-between py-3">
+ <div className="space-y-1">
+ <ModalTitle>Link Linear Issue</ModalTitle>
+ <ModalDescription>
+ Search for an existing issue or create a new one
+ </ModalDescription>
+ </div>
+
+ <TabsList className="max-w-max mb-4">
+ <TabsTrigger value="link">Link Existing</TabsTrigger>
+ <TabsTrigger value="create">Create New</TabsTrigger>
+ </TabsList>
+ </ModalHeader>
+ <ModalBody>
+ {linked && (
+ <div
+ className={cn(
+ "w-full rounded-lg p-3 mb-3 text-left transition-colors block h-auto border border-secondary"
+ )}
+ >
+ <div className="flex items-start justify-between gap-2">
+ <div className="flex-1">
+ <div className="flex items-center gap-2 justify-between">
+ <span className="flex items-center">
+ <span className="mr-2 text-foreground">
+ {linked.title}
+ </span>
+ <Link to={linked.url} target="_blank" rel="noreferrer">
+ <Badge
+ variant={"outline"}
+ className="font-normal text-xs text-muted-foreground flex items-center"
+ >
+ {linked.identifier}
+ <LuExternalLink className="size-3 ml-2" />
+ </Badge>
+ </Link>
+ </span>
+ <LinearIssueStateBadge
+ state={linked.state}
+ className="size-3.5"
+ />
+ </div>
+
+ <div className="mt-2 text-sm text-muted-foreground flex justify-between items-center">
+ <span>
+ {linked.assignee?.email
+ ? `Assigned to ${linked.assignee?.email}`
+ : "Unassigned"}
+ </span>
+
+ <Button
+ onClick={onUnlink}
+ isLoading={fetcher.state === "submitting"}
+ leftIcon={<PiLinkBreak />}
+ size="sm"
+ variant={"destructive"}
+ >
+ Unlink
+ </Button>
+ </div>
+ </div>
+ </div>
+ </div>
+ )}
+
+ <TabsContent value="link" className="relative mt-0">
+ <LinkIssue
+ task={task}
+ onClose={disclosure.onClose}
+ linked={linked}
+ />
+ </TabsContent>
+ <TabsContent value="create" className="relative mt-0">
+ <CreateIssue task={task} onClose={disclosure.onClose} />
+ </TabsContent>
+ </ModalBody>
+ </Tabs>
+ </ModalContent>
+ </Modal>
+ );
+};
diff --git a/apps/erp/app/modules/quality/ui/Issue/Linear/LinkIssue.tsx b/apps/erp/app/modules/quality/ui/Issue/Linear/LinkIssue.tsx
new file mode 100644
index 0000000000..4b03c7c575
--- /dev/null
+++ b/apps/erp/app/modules/quality/ui/Issue/Linear/LinkIssue.tsx
@@ -0,0 +1,167 @@
+import type { LinearIssue } from "@carbon/ee/linear";
+import { Hidden, Submit, ValidatedForm } from "@carbon/form";
+import {
+ Badge,
+ Button,
+ cn,
+ Input,
+ ModalFooter,
+ Spinner,
+ ToggleGroup,
+ ToggleGroupItem,
+ useDebounce,
+ VStack,
+} from "@carbon/react";
+import { Link } from "@remix-run/react";
+import { useId, useState } from "react";
+import { LuExternalLink } from "react-icons/lu";
+import z from "zod";
+import { LinearIssueStateBadge } from "~/components/Icons";
+import { useAsyncFetcher } from "~/hooks/useAsyncFetcher";
+import type { IssueActionTask } from "~/modules/quality";
+import { path } from "~/utils/path";
+
+type Props = {
+ task: IssueActionTask;
+ linked?: LinearIssue;
+ onClose: () => void;
+};
+
+const linkIssueValidator = z.object({
+ actionId: z.string(),
+ issueId: z.string(),
+});
+
+export const LinkIssue = (props: Props) => {
+ const id = useId();
+ const [issueId, setIssueId] = useState<string | undefined>();
+
+ const { issues, fetcher } = useLinearIssues();
+
+ const onSearch = useDebounce((e: React.ChangeEvent<HTMLInputElement>) => {
+ if (!e.target.value || e.target.value.trim().length < 3) return;
+
+ fetcher.load(
+ path.to.api.linearLinkExistingIssue +
+ `?actionId=${props.task.id}&search=${e.target.value}`
+ );
+ }, 300);
+
+ const isSearching = fetcher.state === "loading";
+
+ return (
+ <ValidatedForm
+ id={id}
+ method="post"
+ action={path.to.api.linearLinkExistingIssue}
+ validator={linkIssueValidator}
+ fetcher={fetcher}
+ resetAfterSubmit
+ onAfterSubmit={() => props.onClose()}
+ >
+ <Hidden name="actionId" value={props.task.id} />
+ <Hidden name="issueId" value={issueId} />
+ <VStack spacing={4}>
+ <div className="w-full flex items-center gap-x-2 relative">
+ <Input
+ name="query"
+ type="search"
+ className="w-full"
+ autoComplete="off"
+ placeholder="Search by linear issue title..."
+ onChange={onSearch}
+ disabled={isSearching}
+ />
+ {isSearching && (
+ <Spinner className="w-5 h-5 absolute right-3.5 text-primary animate-spin" />
+ )}
+ </div>
+ <ToggleGroup
+ orientation="vertical"
+ onValueChange={setIssueId}
+ value={issueId}
+ type="single"
+ className="w-full flex-col gap-y-2"
+ >
+ {issues.map((issue) => (
+ <ToggleGroupItem
+ key={issue.id}
+ name="issueId"
+ value={issue.id}
+ disabled={issue.id === props.linked?.id}
+ variant={"outline"}
+ className={cn(
+ "w-full rounded-lg p-3 text-left transition-colors hover:bg-transparent block h-auto data-[state=on]:bg-accent hover:data-[state=on]:bg-accent"
+ )}
+ >
+ <div className="flex items-start justify-between gap-2">
+ <div className="flex-1">
+ <div className="flex items-center gap-2 justify-between">
+ <span className="flex items-center">
+ <span className="mr-2 text-foreground">
+ {issue.title}
+ </span>
+ <Link to={issue.url} target="_blank" rel="noreferrer">
+ <Badge
+ variant={"outline"}
+ className="font-normal text-xs text-muted-foreground flex items-center"
+ >
+ {issue.identifier}
+ <LuExternalLink className="size-3 ml-2" />
+ </Badge>
+ </Link>
+ </span>
+ <LinearIssueStateBadge
+ state={issue.state}
+ className="size-3.5"
+ />
+ </div>
+
+ <div className="mt-2 text-sm text-muted-foreground flex justify-between items-center">
+ <span>
+ {issue.assignee?.email
+ ? `Assigned to ${issue.assignee?.email}`
+ : "Unassigned"}
+ </span>
+ </div>
+ </div>
+ </div>
+ </ToggleGroupItem>
+ ))}
+
+ {issues.length === 0 && !isSearching && (
+ <p className="text-sm text-muted-foreground">
+ No Linear issues found
+ </p>
+ )}
+ </ToggleGroup>
+ </VStack>
+ <ModalFooter>
+ <Button
+ variant="secondary"
+ onClick={() => {
+ props.onClose();
+ }}
+ >
+ Cancel
+ </Button>
+ <Submit>Save</Submit>
+ </ModalFooter>
+ </ValidatedForm>
+ );
+};
+
+LinkIssue.displayName = "LinkIssue";
+
+const useLinearIssues = () => {
+ const fetcher = useAsyncFetcher<{
+ issues: LinearIssue[];
+ linked?: LinearIssue;
+ }>();
+
+ return {
+ issues: fetcher.data?.issues || [],
+ linked: fetcher.data?.linked || null,
+ fetcher,
+ };
+};
diff --git a/apps/erp/app/routes/api+/integrations.linear.issue.create.ts b/apps/erp/app/routes/api+/integrations.linear.issue.create.ts
new file mode 100644
index 0000000000..25112f4312
--- /dev/null
+++ b/apps/erp/app/routes/api+/integrations.linear.issue.create.ts
@@ -0,0 +1,93 @@
+import { getAppUrl } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import {
+ getCompanyEmployees,
+ LinearClient,
+ linkActionToLinearIssue,
+} from "@carbon/ee/linear";
+import { json, type ActionFunction, type LoaderFunction } from "@vercel/remix";
+import { getIssueAction } from "~/modules/quality/quality.service";
+
+const linear = new LinearClient();
+
+export const action: ActionFunction = async ({ request }) => {
+ const data = await request.formData();
+
+ const { companyId, client } = await requirePermissions(request, {});
+
+ const actionId = data.get("actionId") as string;
+ const teamId = data.get("teamId") as string;
+ const title = data.get("title") as string;
+ const description = data.get("description") as string;
+ const assigneeId = data.get("assignee") as string;
+
+ const [carbonIssue, issue] = await Promise.all([
+ getIssueAction(client, actionId),
+ linear.createIssue(companyId, {
+ teamId,
+ title,
+ description: description || undefined,
+ assigneeId: assigneeId || null,
+ }),
+ ]);
+
+ if (!issue) {
+ return { success: false, message: "Issue not found" };
+ }
+
+ const linked = await linkActionToLinearIssue(client, companyId, {
+ actionId,
+ issue: issue,
+ });
+
+ if (!linked || linked.data?.length === 0) {
+ return json({ success: false, message: "Failed to link issue" });
+ }
+
+ const nonConformanceId = linked.data?.[0].nonConformanceId;
+
+ const url = getAppUrl() + `/x/issue/${nonConformanceId}/details`;
+
+ await linear.createAttachmentLink(companyId, {
+ issueId: issue.id,
+ url,
+ title: `Linked Carbon Issue: ${carbonIssue.data?.nonConformanceId ?? ""}`,
+ });
+
+ return new Response("Linear issue created");
+};
+
+export const loader: LoaderFunction = async ({ request }) => {
+ const { companyId, client } = await requirePermissions(request, {});
+
+ const url = new URL(request.url);
+
+ const teamId = url.searchParams.get("teamId") as string;
+ const teams = await linear.listTeams(companyId);
+
+ if (teamId) {
+ const members = teamId
+ ? await linear.listTeamMembers(companyId, teamId)
+ : [];
+ const employees = await getCompanyEmployees(
+ client,
+ companyId,
+ members.map((m) => m.email)
+ );
+
+ // I am sure we can improve this filtering step
+ return {
+ teams,
+ members: members.filter((m) =>
+ employees.some((v) => {
+ if (!v.user?.email || !m.email) {
+ return false;
+ }
+ return v.user.email.toLowerCase() === m.email.toLowerCase();
+ })
+ ),
+ };
+ }
+
+ return { teams };
+};
diff --git a/apps/erp/app/routes/api+/integrations.linear.issue.link.ts b/apps/erp/app/routes/api+/integrations.linear.issue.link.ts
new file mode 100644
index 0000000000..e6b9876139
--- /dev/null
+++ b/apps/erp/app/routes/api+/integrations.linear.issue.link.ts
@@ -0,0 +1,96 @@
+import { getAppUrl } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import {
+ LinearClient,
+ linkActionToLinearIssue,
+ unlinkActionFromLinearIssue,
+} from "@carbon/ee/linear";
+import { type ActionFunction, type LoaderFunction, json } from "@vercel/remix";
+import { getIssueAction } from "~/modules/quality/quality.service";
+
+const linear = new LinearClient();
+
+export const action: ActionFunction = async ({ request }) => {
+ const { companyId, client } = await requirePermissions(request, {});
+ const form = await request.formData();
+
+ const actionId = form.get("actionId") as string;
+
+ if (!actionId) {
+ return { success: false, message: "Missing required fields: actionId" };
+ }
+
+ switch (request.method) {
+ case "POST": {
+ const issueId = form.get("issueId") as string;
+
+ if (!issueId) {
+ return { success: false, message: "Missing required fields: issueId" };
+ }
+
+ const [carbonIssue, issue] = await Promise.all([
+ getIssueAction(client, actionId),
+ linear.getIssueById(companyId, issueId),
+ ]);
+
+ if (!issue) {
+ return { success: false, message: "Issue not found" };
+ }
+
+ const email = issue.assignee?.email ?? "";
+
+ const assignee = await client
+ .from("user")
+ .select("id")
+ .eq("email", email)
+ .single();
+
+ const linked = await linkActionToLinearIssue(client, companyId, {
+ actionId,
+ issue,
+ assignee: assignee.data ? assignee.data.id : null,
+ });
+
+ if (!linked || linked.data?.length === 0) {
+ return json({ success: false, message: "Failed to link issue" });
+ }
+
+ const nonConformanceId = linked.data?.[0].nonConformanceId;
+
+ const url = getAppUrl() + `/x/issue/${nonConformanceId}/details`;
+
+ await linear.createAttachmentLink(companyId, {
+ issueId: issue.id as string,
+ url,
+ title: `Linked Carbon Issue: ${
+ carbonIssue.data?.nonConformanceId ?? ""
+ }`,
+ });
+
+ return json({ success: true, message: "Linked successfully" });
+ }
+
+ case "DELETE": {
+ const unlinked = await unlinkActionFromLinearIssue(client, companyId, {
+ actionId,
+ });
+
+ if (unlinked.error) {
+ return json({ success: false, message: "Failed to unlink issue" });
+ }
+
+ return json({ success: true, message: "Unlinked successfully" });
+ }
+ }
+};
+
+export const loader: LoaderFunction = async ({ request }) => {
+ const { companyId } = await requirePermissions(request, {});
+ const url = new URL(request.url);
+
+ const query = url.searchParams.get("search") as string;
+
+ const issues = await linear.listIssues(companyId, query);
+
+ return json({ issues });
+};
diff --git a/apps/erp/app/routes/api+/integrations.linear.issue.sync-notes.ts b/apps/erp/app/routes/api+/integrations.linear.issue.sync-notes.ts
new file mode 100644
index 0000000000..a62e442495
--- /dev/null
+++ b/apps/erp/app/routes/api+/integrations.linear.issue.sync-notes.ts
@@ -0,0 +1,64 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import {
+ getLinearIssueFromExternalId,
+ LinearClient,
+ tiptapToMarkdown,
+ type TiptapDocument,
+} from "@carbon/ee/linear";
+import { json, type ActionFunction } from "@vercel/remix";
+
+const linear = new LinearClient();
+
+export const action: ActionFunction = async ({ request }) => {
+ const { companyId, client } = await requirePermissions(request, {});
+
+ if (request.method !== "POST") {
+ return json({ success: false, message: "Method not allowed" }, 405);
+ }
+
+ const form = await request.formData();
+ const actionId = form.get("actionId") as string;
+ const notesStr = form.get("notes") as string;
+
+ if (!actionId) {
+ return json({ success: false, message: "Missing actionId" }, 400);
+ }
+
+ // Parse the notes JSON
+ let notes: TiptapDocument | null = null;
+ try {
+ notes = notesStr ? JSON.parse(notesStr) : null;
+ } catch {
+ return json({ success: false, message: "Invalid notes format" }, 400);
+ }
+
+ // Get the linked Linear issue
+ const issue = await getLinearIssueFromExternalId(client, companyId, actionId);
+
+ if (!issue) {
+ // No linked Linear issue, nothing to sync
+ return json({ success: true, message: "No linked Linear issue" });
+ }
+
+ if (!notes) {
+ return json({ success: true, message: "No notes to sync" });
+ }
+
+ try {
+ // Convert Tiptap notes to markdown for Linear
+ const description = tiptapToMarkdown(notes);
+
+ await linear.updateIssue(companyId, {
+ id: issue.id,
+ description,
+ });
+
+ return json({ success: true, message: "Notes synced to Linear" });
+ } catch (error) {
+ console.error("Failed to sync notes to Linear:", error);
+ return json(
+ { success: false, message: "Failed to sync notes to Linear" },
+ 500
+ );
+ }
+};
diff --git a/apps/erp/app/routes/api+/webhook.linear.$companyId.ts b/apps/erp/app/routes/api+/webhook.linear.$companyId.ts
new file mode 100644
index 0000000000..1fdb9aae8b
--- /dev/null
+++ b/apps/erp/app/routes/api+/webhook.linear.$companyId.ts
@@ -0,0 +1,75 @@
+import { getCarbonServiceRole } from "@carbon/auth";
+import { syncIssueFromLinearSchema } from "@carbon/jobs/trigger/linear";
+import { tasks } from "@trigger.dev/sdk";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";
+import { json } from "@vercel/remix";
+import { getIntegration } from "../../modules/settings";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { companyId } = params;
+ if (!companyId) {
+ return json({ success: false }, { status: 400 });
+ }
+
+ return json({
+ success: true,
+ });
+}
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ const { companyId } = params;
+
+ if (!companyId) {
+ return json({ success: false }, { status: 400 });
+ }
+
+ const serviceRole = getCarbonServiceRole();
+ const integration = await getIntegration(serviceRole, "linear", companyId);
+
+ if (integration.error) {
+ console.error(
+ "Linear webhook: integration query failed",
+ integration.error
+ );
+ return json(
+ { success: false, error: "Integration query failed" },
+ { status: 400 }
+ );
+ }
+
+ if (!integration.data) {
+ return json(
+ { success: false, error: "Integration not configured" },
+ { status: 400 }
+ );
+ }
+
+ if (!integration.data.active) {
+ return json(
+ { success: false, error: "Integration not active" },
+ { status: 400 }
+ );
+ }
+
+ const body = await request.json();
+
+ const parsed = syncIssueFromLinearSchema.safeParse({
+ companyId,
+ event: body,
+ });
+
+ if (!parsed.success) {
+ return json(
+ { success: false, error: parsed.error.format() },
+ { status: 400 }
+ );
+ }
+
+ try {
+ await tasks.trigger("sync-issue-from-linear", parsed.data);
+ return json({ success: true });
+ } catch (err) {
+ console.error("Linear webhook: failed to trigger task", err);
+ return json({ success: false }, { status: 500 });
+ }
+}
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index b1442a361d..0405e9364f 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -99,6 +99,9 @@ export const path = {
`${api}/integrations/onshape/d/${documentId}/v/${versionId}/elements`
),
onShapeSync: `${api}/integrations/onshape/sync`,
+ linearCreateIssue: `${api}/integrations/linear/issue/create`,
+ linearLinkExistingIssue: `${api}/integrations/linear/issue/link`,
+ linearSyncNotes: `${api}/integrations/linear/issue/sync-notes`,
outsideOperations: (jobId: string) =>
generatePath(`${api}/production/outside-operations/${jobId}`),
purchasingKpi: (key: string) =>
diff --git a/apps/erp/vite.config.ts b/apps/erp/vite.config.ts
index 796f55dca0..e565ca8b51 100644
--- a/apps/erp/vite.config.ts
+++ b/apps/erp/vite.config.ts
@@ -33,7 +33,7 @@ export default defineConfig({
},
server: {
port: 3000,
- allowedHosts: ["958d8cbb09d3.ngrok-free.app"],
+ allowedHosts: [".ngrok-free.app"],
},
plugins: [
remix({
diff --git a/llm/cache/linear-integration.md b/llm/cache/linear-integration.md
new file mode 100644
index 0000000000..03ad512fd0
--- /dev/null
+++ b/llm/cache/linear-integration.md
@@ -0,0 +1,293 @@
+# Linear Integration
+
+## Overview
+
+The Linear integration allows Carbon to sync Quality Management issues (non-conformances) with Linear issues. It provides two-way synchronization between Carbon action tasks and Linear issues.
+
+## Architecture
+
+### Integration Setup
+
+**Database:**
+- Integration registered in `integration` table with ID `"linear"`
+- Configuration stored in `companyIntegration` table per company
+- Required metadata: `{ apiKey: string }`
+
+**Configuration File:** `/packages/ee/src/linear/config.tsx`
+- Integration name: "Linear"
+- Category: "Project Management"
+- Settings: API Key (required)
+- Setup includes webhook URL generation for webhooks
+
+**Migration:** `/packages/database/supabase/migrations/20251127091215_add_linear_integration.sql`
+
+### Key Components
+
+#### 1. Linear Client (`/packages/ee/src/linear/lib/client.ts`)
+
+GraphQL API client for Linear that provides:
+- `listTeams()` - Get all Linear teams
+- `listIssues(input)` - Search issues by title
+- `getIssueById(issueId)` - Fetch specific issue with full details
+- `createIssue(data)` - Create new Linear issue
+- `updateIssue(data)` - Update issue title, description, assignee, state
+- `listTeamMembers(teamId)` - Get team member list
+- `getUsers(filter)` - Search users by email or ID
+- `createAttachmentLink(input)` - Add attachment/link to issue
+- `getWorkflowState(type)` - Get workflow state by type
+
+**Authentication:**
+- Uses API key from `companyIntegration.metadata.apiKey`
+- Retrieved via `getLinearIntegration()` service function
+
+#### 2. Service Layer (`/packages/ee/src/linear/lib/service.ts`)
+
+**Data Types:**
+```typescript
+LinearIssueSchema = {
+ id: string,
+ title: string,
+ description: string,
+ url: string,
+ state: {
+ name: string,
+ color: string,
+ type: LinearWorkStateType
+ },
+ identifier: string,
+ dueDate: string | null,
+ assignee: { email: string } | null
+}
+```
+
+**Functions:**
+- `linkActionToLinearIssue()` - Links Carbon action task to Linear issue
+ - Stores Linear issue data in `externalId.linear` JSON field
+ - Updates assignee if Linear assignee matches Carbon employee
+ - Syncs status and due date
+ - Returns `nonConformanceId` for creating backlink
+
+- `unlinkActionFromLinearIssue()` - Removes link by clearing `externalId.linear`
+
+- `getLinearIssueFromExternalId()` - Retrieves Linear issue data from action task
+
+- `getCompanyEmployees()` - Finds Carbon employees by email addresses
+
+#### 3. Status Mapping (`/packages/ee/src/linear/lib/utils.ts`)
+
+**Linear State Types:**
+- `triage`, `backlog`, `todo`, `unstarted` → Carbon "Pending"
+- `started` → Carbon "In Progress"
+- `completed` → Carbon "Completed"
+- `canceled` → Carbon "Skipped"
+
+**Reverse Mapping (Carbon → Linear):**
+- "Pending" → `unstarted`
+- "In Progress" → `started`
+- "Completed" → `completed`
+- "Skipped" → `canceled`
+
+### Integration Points
+
+#### A. Carbon to Linear (Outbound)
+
+**1. Link Existing Issue**
+Route: `/api/integrations.linear.issue.link`
+- POST: Links Carbon action task to existing Linear issue
+ - Fetches Linear issue by ID
+ - Maps Linear assignee to Carbon user (by email)
+ - Stores issue data in `nonConformanceActionTask.externalId.linear`
+ - Creates attachment link back to Carbon issue
+- DELETE: Unlinks by clearing `externalId.linear`
+- GET: Search Linear issues by title query
+
+**2. Create New Issue**
+Route: `/api/integrations.linear.issue.create`
+- POST: Creates new Linear issue and links to Carbon action
+ - Requires: teamId, title, description, assigneeId (optional)
+ - Creates issue in Linear
+ - Links to Carbon action task
+ - Creates attachment link back to Carbon
+- GET: Lists Linear teams, optionally filters team members by Carbon employees
+
+**3. Notification Service** (`/packages/ee/src/notifications/services/linear.ts`)
+
+Listens for Carbon events and updates Linear:
+
+**Event: `task.status.changed`**
+- Only processes action/investigation tasks
+- Gets linked Linear issue from `externalId`
+- Maps Carbon status to Linear workflow state
+- Updates Linear issue state via API
+
+**Event: `task.assigned`**
+- Only processes `nonConformanceActionTask` table
+- Gets linked Linear issue
+- Finds Linear user by Carbon employee email
+- Updates Linear issue assignee
+
+#### B. Linear to Carbon (Inbound)
+
+**Webhook Route:** `/api/webhook/linear/:companyId`
+- Receives Linear webhook events
+- Validates company and integration are active
+- Parses event using `syncIssueFromLinearSchema`
+- Triggers Trigger.dev task for async processing
+
+**Trigger.dev Task:** `/packages/jobs/trigger/linear.ts`
+
+`syncIssueFromLinear` task:
+- Accepts event type: `Issue` with action: `update`
+- Finds linked Carbon action by `externalId->linear->>id`
+- Maps Linear assignee to Carbon employee (by email)
+- Updates Carbon action task with:
+ - Latest Linear issue state (title, description, state, url)
+ - Mapped status from Linear state type
+ - Assignee from Linear (if employee exists)
+ - Due date from Linear
+- Returns success/failure message
+
+**Event Schema:**
+```typescript
+{
+ companyId: string,
+ event: {
+ type: "Issue",
+ action: "update",
+ data: {
+ id: string,
+ title: string,
+ description: string,
+ url: string,
+ state: { name, color, type },
+ identifier: string,
+ assigneeId?: string
+ }
+ }
+}
+```
+
+### Data Flow
+
+#### Linking Flow (Carbon → Linear)
+1. User selects Linear issue or creates new one in Carbon UI
+2. Carbon fetches issue details from Linear API
+3. Carbon stores issue in `nonConformanceActionTask.externalId.linear`
+4. Carbon syncs assignee (if Linear assignee email matches Carbon employee)
+5. Carbon creates attachment link in Linear pointing back to Carbon issue
+
+#### Webhook Flow (Linear → Carbon)
+1. User updates issue in Linear (status, assignee, title, etc.)
+2. Linear sends webhook to `/api/webhook/linear/:companyId`
+3. Carbon validates and triggers Trigger.dev task
+4. Task finds linked Carbon action by Linear issue ID
+5. Task updates Carbon action with Linear changes
+6. Assignee synced if Linear user email matches Carbon employee
+
+#### Notification Flow (Carbon → Linear)
+1. User changes task status or assignee in Carbon
+2. Carbon notification pipeline detects change
+3. If Linear integration is active, notification service triggers
+4. Service finds linked Linear issue from `externalId`
+5. Service updates Linear issue via API
+
+### Database Schema
+
+**Storage of Link:**
+```sql
+-- nonConformanceActionTask table
+externalId JSONB
+ Contains: {
+ linear: {
+ id: string,
+ title: string,
+ description: string,
+ url: string,
+ state: { name, color, type },
+ identifier: string,
+ dueDate: string | null,
+ assignee: { email: string } | null
+ }
+ }
+```
+
+**Querying Linked Issues:**
+```typescript
+// Find action by Linear issue ID
+.eq("externalId->linear->>id", linearIssueId)
+
+// Check if action has Linear link
+.not("externalId->linear", "is", null)
+```
+
+### UI Components
+
+Located in `/apps/erp/app/modules/quality/ui/Issue/Linear/`:
+- `LinkIssue.tsx` - Component to search and link existing Linear issues
+- `CreateIssue.tsx` - Form to create new Linear issue
+- `IssueDialog.tsx` - Modal containing link/create options
+
+Display in `/apps/erp/app/modules/quality/ui/Issue/IssueTask.tsx`:
+- Shows Linear badge with issue identifier
+- Links to Linear issue URL
+- Displays on action tasks with `externalId.linear` data
+
+### Notification Pipeline
+
+**Registry:** `/packages/ee/src/notifications/index.ts`
+- Registers `LinearNotificationService` on initialization
+- Service ID: `"linear"`
+
+**Pipeline:** `/packages/ee/src/notifications/pipeline.ts`
+- `NotificationPipeline` class sends events to active integrations
+- Filters integrations by `active: true` and notification service type
+- Sends events in parallel to all active services
+
+**Supported Events:**
+1. `issue.created` - (Slack only currently)
+2. `issue.status.changed` - (Slack only currently)
+3. `task.status.changed` - Slack + **Linear** (updates issue state)
+4. `task.assigned` - Slack + **Linear** (updates issue assignee)
+
+### Setup Instructions (for users)
+
+1. Login to Linear account
+2. Navigate to Settings → Webhooks
+3. Create new webhook with URL: `https://app.carbon.ms/api/webhook/linear/{companyId}`
+4. Go to Settings → Security and access → API
+5. Generate new API key
+6. In Carbon, go to Settings → Integrations → Linear
+7. Paste API key
+8. Save integration
+
+### Important Notes
+
+- Only **action tasks** can be linked to Linear issues (not investigation or approval tasks)
+- Assignee sync requires matching email between Linear user and Carbon employee
+- Two-way sync means changes in either system update the other
+- Linear issue data is cached in Carbon's `externalId` field as JSON
+- Attachment links in Linear point back to Carbon issue details page
+- Webhook processes updates asynchronously via Trigger.dev
+- Integration must be active (`companyIntegration.active = true`) for notifications to flow
+
+### Key Files Reference
+
+**Packages:**
+- `/packages/ee/src/linear/config.tsx` - Integration config
+- `/packages/ee/src/linear/lib/client.ts` - GraphQL API client
+- `/packages/ee/src/linear/lib/service.ts` - Business logic
+- `/packages/ee/src/linear/lib/utils.ts` - Status mapping
+- `/packages/ee/src/notifications/services/linear.ts` - Notification handler
+- `/packages/jobs/trigger/linear.ts` - Webhook handler task
+
+**Routes:**
+- `/apps/erp/app/routes/api+/webhook.linear.$companyId.ts` - Webhook endpoint
+- `/apps/erp/app/routes/api+/integrations.linear.issue.link.ts` - Link/unlink API
+- `/apps/erp/app/routes/api+/integrations.linear.issue.create.ts` - Create issue API
+
+**UI:**
+- `/apps/erp/app/modules/quality/ui/Issue/Linear/*.tsx` - Integration UI components
+- `/apps/erp/app/modules/quality/ui/Issue/IssueTask.tsx` - Task display with Linear badge
+
+**Database:**
+- `/packages/database/supabase/migrations/20251127091215_add_linear_integration.sql` - Integration setup
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index 290687148a..7fed334827 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -6096,6 +6096,9 @@ export default {
{
$ref: "#/parameters/rowFilter.nonConformanceActionTask.supplierId",
},
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceActionTask.externalId",
+ },
{
$ref: "#/parameters/select",
},
@@ -6203,6 +6206,9 @@ export default {
{
$ref: "#/parameters/rowFilter.nonConformanceActionTask.supplierId",
},
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceActionTask.externalId",
+ },
{
$ref: "#/parameters/preferReturn",
},
@@ -6264,6 +6270,9 @@ export default {
{
$ref: "#/parameters/rowFilter.nonConformanceActionTask.supplierId",
},
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceActionTask.externalId",
+ },
{
$ref: "#/parameters/body.nonConformanceActionTask",
},
@@ -27279,6 +27288,9 @@ export default {
{
$ref: "#/parameters/rowFilter.userAttributeCategory.updatedBy",
},
+ {
+ $ref: "#/parameters/rowFilter.userAttributeCategory.emoji",
+ },
{
$ref: "#/parameters/select",
},
@@ -27368,6 +27380,9 @@ export default {
{
$ref: "#/parameters/rowFilter.userAttributeCategory.updatedBy",
},
+ {
+ $ref: "#/parameters/rowFilter.userAttributeCategory.emoji",
+ },
{
$ref: "#/parameters/preferReturn",
},
@@ -27411,6 +27426,9 @@ export default {
{
$ref: "#/parameters/rowFilter.userAttributeCategory.updatedBy",
},
+ {
+ $ref: "#/parameters/rowFilter.userAttributeCategory.emoji",
+ },
{
$ref: "#/parameters/body.userAttributeCategory",
},
@@ -33750,6 +33768,9 @@ export default {
{
$ref: "#/parameters/rowFilter.nonConformanceReviewer.updatedBy",
},
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceReviewer.completedDate",
+ },
{
$ref: "#/parameters/select",
},
@@ -33842,6 +33863,9 @@ export default {
{
$ref: "#/parameters/rowFilter.nonConformanceReviewer.updatedBy",
},
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceReviewer.completedDate",
+ },
{
$ref: "#/parameters/preferReturn",
},
@@ -33888,6 +33912,9 @@ export default {
{
$ref: "#/parameters/rowFilter.nonConformanceReviewer.updatedBy",
},
+ {
+ $ref: "#/parameters/rowFilter.nonConformanceReviewer.completedDate",
+ },
{
$ref: "#/parameters/body.nonConformanceReviewer",
},
@@ -55566,6 +55593,9 @@ export default {
{
$ref: "#/parameters/rowFilter.companySettings.gaugeCalibrationExpiredNotificationGroup",
},
+ {
+ $ref: "#/parameters/rowFilter.companySettings.purchasePriceUpdateTiming",
+ },
{
$ref: "#/parameters/select",
},
@@ -55664,6 +55694,9 @@ export default {
{
$ref: "#/parameters/rowFilter.companySettings.gaugeCalibrationExpiredNotificationGroup",
},
+ {
+ $ref: "#/parameters/rowFilter.companySettings.purchasePriceUpdateTiming",
+ },
{
$ref: "#/parameters/preferReturn",
},
@@ -55716,6 +55749,9 @@ export default {
{
$ref: "#/parameters/rowFilter.companySettings.gaugeCalibrationExpiredNotificationGroup",
},
+ {
+ $ref: "#/parameters/rowFilter.companySettings.purchasePriceUpdateTiming",
+ },
{
$ref: "#/parameters/body.companySettings",
},
@@ -56958,6 +56994,41 @@ export default {
tags: ["(rpc) get_companies_with_any_role"],
},
},
+ "/rpc/get_unscheduled_jobs": {
+ post: {
+ parameters: [
+ {
+ in: "body",
+ name: "args",
+ required: true,
+ schema: {
+ properties: {
+ location_id: {
+ format: "text",
+ type: "string",
+ },
+ },
+ required: ["location_id"],
+ type: "object",
+ },
+ },
+ {
+ $ref: "#/parameters/preferParams",
+ },
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json",
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ },
+ },
+ tags: ["(rpc) get_unscheduled_jobs"],
+ },
+ },
"/rpc/get_direct_ancestors_of_tracked_entity": {
post: {
parameters: [
@@ -62881,6 +62952,9 @@ export default {
format: "text",
type: "string",
},
+ externalId: {
+ format: "json",
+ },
},
type: "object",
},
@@ -65984,6 +66058,7 @@ export default {
"Job Consumption",
"Job Receipt",
"Batch Split",
+ "Purchase Order",
],
format: 'public."itemLedgerDocumentType"',
type: "string",
@@ -72993,6 +73068,10 @@ export default {
format: "text",
type: "string",
},
+ emoji: {
+ format: "text",
+ type: "string",
+ },
},
type: "object",
},
@@ -76011,6 +76090,10 @@ export default {
format: "text",
type: "string",
},
+ completedDate: {
+ format: "timestamp with time zone",
+ type: "string",
+ },
},
type: "object",
},
@@ -77859,6 +77942,7 @@ export default {
"Job Consumption",
"Job Receipt",
"Batch Split",
+ "Purchase Order",
],
format: 'public."itemLedgerDocumentType"',
type: "string",
@@ -86534,6 +86618,7 @@ export default {
"useMetric",
"kanbanOutput",
"gaugeCalibrationExpiredNotificationGroup",
+ "purchasePriceUpdateTiming",
],
properties: {
id: {
@@ -86613,6 +86698,12 @@ export default {
},
type: "array",
},
+ purchasePriceUpdateTiming: {
+ default: "Purchase Invoice Post",
+ enum: ["Purchase Invoice Post", "Purchase Order Finalize"],
+ format: 'public."purchasePriceUpdateTiming"',
+ type: "string",
+ },
},
type: "object",
},
@@ -90045,6 +90136,12 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.nonConformanceActionTask.externalId": {
+ name: "externalId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"body.supplierInteraction": {
name: "supplierInteraction",
description: "supplierInteraction",
@@ -101367,6 +101464,12 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.userAttributeCategory.emoji": {
+ name: "emoji",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"body.trackedActivity": {
name: "trackedActivity",
description: "trackedActivity",
@@ -104838,6 +104941,12 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.nonConformanceReviewer.completedDate": {
+ name: "completedDate",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"body.employee": {
name: "employee",
description: "employee",
@@ -116763,6 +116872,12 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.companySettings.purchasePriceUpdateTiming": {
+ name: "purchasePriceUpdateTiming",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"body.part": {
name: "part",
description: "part",
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index b842bdd3b4..44a018fa84 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -23134,6 +23134,7 @@ export type Database = {
id: string
name: string
status: Database["public"]["Enums"]["qualityDocumentStatus"]
+ tags: string[] | null
updatedAt: string | null
updatedBy: string | null
version: number
@@ -23148,6 +23149,7 @@ export type Database = {
id?: string
name: string
status?: Database["public"]["Enums"]["qualityDocumentStatus"]
+ tags?: string[] | null
updatedAt?: string | null
updatedBy?: string | null
version?: number
@@ -23162,6 +23164,7 @@ export type Database = {
id?: string
name?: string
status?: Database["public"]["Enums"]["qualityDocumentStatus"]
+ tags?: string[] | null
updatedAt?: string | null
updatedBy?: string | null
version?: number
@@ -37757,7 +37760,6 @@ export type Database = {
defaultMethodType: Database["public"]["Enums"]["methodType"] | null
description: string | null
id: string | null
- itemPostingGroupId: string | null
itemTrackingType:
| Database["public"]["Enums"]["itemTrackingType"]
| null
@@ -37944,13 +37946,6 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
- {
- foreignKeyName: "itemCost_itemPostingGroupId_fkey"
- columns: ["itemPostingGroupId"]
- isOneToOne: false
- referencedRelation: "itemPostingGroup"
- referencedColumns: ["id"]
- },
]
}
contractors: {
@@ -41898,7 +41893,6 @@ export type Database = {
defaultMethodType: Database["public"]["Enums"]["methodType"] | null
description: string | null
id: string | null
- itemPostingGroupId: string | null
itemTrackingType:
| Database["public"]["Enums"]["itemTrackingType"]
| null
@@ -42063,13 +42057,6 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
- {
- foreignKeyName: "itemCost_itemPostingGroupId_fkey"
- columns: ["itemPostingGroupId"]
- isOneToOne: false
- referencedRelation: "itemPostingGroup"
- referencedColumns: ["id"]
- },
]
}
procedures: {
@@ -43218,14 +43205,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -43790,6 +43777,7 @@ export type Database = {
id: string | null
name: string | null
status: Database["public"]["Enums"]["qualityDocumentStatus"] | null
+ tags: string[] | null
version: number | null
versions: Json | null
}
@@ -45737,14 +45725,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["invoiceCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["invoiceCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -48404,7 +48392,6 @@ export type Database = {
defaultMethodType: Database["public"]["Enums"]["methodType"] | null
description: string | null
id: string | null
- itemPostingGroupId: string | null
itemTrackingType:
| Database["public"]["Enums"]["itemTrackingType"]
| null
@@ -48569,13 +48556,6 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
- {
- foreignKeyName: "itemCost_itemPostingGroupId_fkey"
- columns: ["itemPostingGroupId"]
- isOneToOne: false
- referencedRelation: "itemPostingGroup"
- referencedColumns: ["id"]
- },
]
}
userDefaults: {
@@ -48961,7 +48941,6 @@ export type Database = {
defaultMethodType: Database["public"]["Enums"]["methodType"]
description: string
id: string
- itemPostingGroupId: string
itemTrackingType: Database["public"]["Enums"]["itemTrackingType"]
modelName: string
modelPath: string
@@ -49354,7 +49333,6 @@ export type Database = {
grade: string
gradeId: string
id: string
- itemPostingGroupId: string
itemTrackingType: Database["public"]["Enums"]["itemTrackingType"]
materialForm: string
materialFormId: string
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index b842bdd3b4..44a018fa84 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -23134,6 +23134,7 @@ export type Database = {
id: string
name: string
status: Database["public"]["Enums"]["qualityDocumentStatus"]
+ tags: string[] | null
updatedAt: string | null
updatedBy: string | null
version: number
@@ -23148,6 +23149,7 @@ export type Database = {
id?: string
name: string
status?: Database["public"]["Enums"]["qualityDocumentStatus"]
+ tags?: string[] | null
updatedAt?: string | null
updatedBy?: string | null
version?: number
@@ -23162,6 +23164,7 @@ export type Database = {
id?: string
name?: string
status?: Database["public"]["Enums"]["qualityDocumentStatus"]
+ tags?: string[] | null
updatedAt?: string | null
updatedBy?: string | null
version?: number
@@ -37757,7 +37760,6 @@ export type Database = {
defaultMethodType: Database["public"]["Enums"]["methodType"] | null
description: string | null
id: string | null
- itemPostingGroupId: string | null
itemTrackingType:
| Database["public"]["Enums"]["itemTrackingType"]
| null
@@ -37944,13 +37946,6 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
- {
- foreignKeyName: "itemCost_itemPostingGroupId_fkey"
- columns: ["itemPostingGroupId"]
- isOneToOne: false
- referencedRelation: "itemPostingGroup"
- referencedColumns: ["id"]
- },
]
}
contractors: {
@@ -41898,7 +41893,6 @@ export type Database = {
defaultMethodType: Database["public"]["Enums"]["methodType"] | null
description: string | null
id: string | null
- itemPostingGroupId: string | null
itemTrackingType:
| Database["public"]["Enums"]["itemTrackingType"]
| null
@@ -42063,13 +42057,6 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
- {
- foreignKeyName: "itemCost_itemPostingGroupId_fkey"
- columns: ["itemPostingGroupId"]
- isOneToOne: false
- referencedRelation: "itemPostingGroup"
- referencedColumns: ["id"]
- },
]
}
procedures: {
@@ -43218,14 +43205,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -43790,6 +43777,7 @@ export type Database = {
id: string | null
name: string | null
status: Database["public"]["Enums"]["qualityDocumentStatus"] | null
+ tags: string[] | null
version: number | null
versions: Json | null
}
@@ -45737,14 +45725,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["invoiceCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["invoiceCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -48404,7 +48392,6 @@ export type Database = {
defaultMethodType: Database["public"]["Enums"]["methodType"] | null
description: string | null
id: string | null
- itemPostingGroupId: string | null
itemTrackingType:
| Database["public"]["Enums"]["itemTrackingType"]
| null
@@ -48569,13 +48556,6 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
- {
- foreignKeyName: "itemCost_itemPostingGroupId_fkey"
- columns: ["itemPostingGroupId"]
- isOneToOne: false
- referencedRelation: "itemPostingGroup"
- referencedColumns: ["id"]
- },
]
}
userDefaults: {
@@ -48961,7 +48941,6 @@ export type Database = {
defaultMethodType: Database["public"]["Enums"]["methodType"]
description: string
id: string
- itemPostingGroupId: string
itemTrackingType: Database["public"]["Enums"]["itemTrackingType"]
modelName: string
modelPath: string
@@ -49354,7 +49333,6 @@ export type Database = {
grade: string
gradeId: string
id: string
- itemPostingGroupId: string
itemTrackingType: Database["public"]["Enums"]["itemTrackingType"]
materialForm: string
materialFormId: string
diff --git a/packages/database/supabase/migrations/20251126192515_add_external_id_to_quality_action.sql b/packages/database/supabase/migrations/20251126192515_add_external_id_to_quality_action.sql
new file mode 100644
index 0000000000..0fddfd4553
--- /dev/null
+++ b/packages/database/supabase/migrations/20251126192515_add_external_id_to_quality_action.sql
@@ -0,0 +1 @@
+ALTER TABLE "nonConformanceActionTask" ADD COLUMN "externalId" JSON;
\ No newline at end of file
diff --git a/packages/database/supabase/migrations/20251127091215_add_linear_integration.sql b/packages/database/supabase/migrations/20251127091215_add_linear_integration.sql
new file mode 100644
index 0000000000..77ed4eb52d
--- /dev/null
+++ b/packages/database/supabase/migrations/20251127091215_add_linear_integration.sql
@@ -0,0 +1,4 @@
+INSERT INTO "integration" (id, jsonschema) VALUES (
+ 'linear',
+ '{"type":"object","properties":{"apiKey":{"type":"string"}},"required":["apiKey"]}'
+);
\ No newline at end of file
diff --git a/packages/database/supabase/migrations/20251207005731_attribute-realtime.sql b/packages/database/supabase/migrations/20251207005731_attribute-realtime.sql
new file mode 100644
index 0000000000..51893a088d
--- /dev/null
+++ b/packages/database/supabase/migrations/20251207005731_attribute-realtime.sql
@@ -0,0 +1 @@
+ALTER publication supabase_realtime ADD TABLE "nonConformanceActionTask";
\ No newline at end of file
diff --git a/packages/ee/package.json b/packages/ee/package.json
index 5c7cc675bd..89dae9a881 100644
--- a/packages/ee/package.json
+++ b/packages/ee/package.json
@@ -7,6 +7,7 @@
"./exchange-rates.server": "./src/exchange-rates/exchange-rates.server.ts",
"./notifications": "./src/notifications/index.ts",
"./onshape": "./src/onshape/lib/index.ts",
+ "./linear": "./src/linear/lib/index.ts",
"./paperless-parts": "./src/paperless-parts/lib/index.ts",
"./slack.server": "./src/slack.server.ts",
"./slack/messages": "./src/slack/lib/messages.ts"
diff --git a/packages/ee/src/index.ts b/packages/ee/src/index.ts
index 8a6f26b78b..4ba69fc1ba 100644
--- a/packages/ee/src/index.ts
+++ b/packages/ee/src/index.ts
@@ -1,4 +1,5 @@
import { ExchangeRates } from "./exchange-rates/config";
+import { Linear } from "./linear/config";
import { Onshape } from "./onshape/config";
import { PaperlessParts } from "./paperless-parts/config";
import { QuickBooks } from "./quickbooks/config";
@@ -13,16 +14,17 @@ export { Resend } from "./resend/config";
export type { IntegrationConfig } from "./types";
export const integrations = [
- ExchangeRates,
- PaperlessParts,
- Onshape,
- QuickBooks,
- Resend,
- // Radan,
- Slack,
- Sage,
- Xero,
- Zapier,
+ ExchangeRates,
+ PaperlessParts,
+ Onshape,
+ Linear,
+ QuickBooks,
+ Resend,
+ // Radan,
+ Slack,
+ Sage,
+ Xero,
+ Zapier,
];
export { Onshape, Logo as OnshapeLogo } from "./onshape/config";
diff --git a/packages/ee/src/linear/config.tsx b/packages/ee/src/linear/config.tsx
new file mode 100644
index 0000000000..89f6c2abdf
--- /dev/null
+++ b/packages/ee/src/linear/config.tsx
@@ -0,0 +1,82 @@
+import { Copy, Input, InputGroup, InputRightElement } from "@carbon/react";
+import { isBrowser } from "@carbon/utils";
+import type { SVGProps } from "react";
+import { z } from "zod/v3";
+import type { IntegrationConfig } from "../types";
+
+export const Linear: IntegrationConfig = {
+ name: "Linear",
+ id: "linear",
+ active: true,
+ category: "Project Management",
+ logo: Logo,
+ description:
+ "Linear is a project management software that allows you to create issues and track project progress seamlessly. With this integration, you can link issues from Carbon to Linear.",
+ shortDescription: "Sync issues from Carbon to Linear.",
+ setupInstructions: SetupInstructions,
+ images: [],
+ settings: [
+ {
+ name: "apiKey",
+ label: "API Key",
+ type: "text",
+ required: true,
+ value: "",
+ },
+ ],
+ schema: z.object({
+ apiKey: z.string().min(1, { message: "API Key is required" }),
+ }),
+};
+
+function SetupInstructions({ companyId }: { companyId: string }) {
+ const webhookUrl = isBrowser
+ ? `${window.location.origin}/api/webhook/${Linear.id}/${companyId}`
+ : "";
+
+ return (
+ <>
+ <p className="text-sm text-muted-foreground">
+ To integrate Linear with Carbon, start by logging into your Linear
+ account and navigating to the API settings page.
+ </p>
+ <p className="text-sm text-muted-foreground">
+ Under the "Webhooks" section, click on "New Webhook" and give it a
+ descriptive label.
+ </p>
+ <p className="text-sm text-muted-foreground">
+ Copy the webhook URL provided below into the "URL" field.
+ </p>
+ <InputGroup className="mb-8">
+ <Input value={webhookUrl} />
+ <InputRightElement>
+ <Copy text={webhookUrl} />
+ </InputRightElement>
+ </InputGroup>
+
+ <p className="text-sm text-muted-foreground">
+ Next, from the sidebar go to "Security and access" page and generate a
+ new API key. Copy the generated API key and paste it into the "API Key"
+ field below.
+ </p>
+ </>
+ );
+}
+
+export function Logo(props: SVGProps<SVGSVGElement>) {
+ return (
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ fill="none"
+ width={200}
+ height={200}
+ viewBox="0 0 100 100"
+ {...props}
+ >
+ <path
+ fill="#fff"
+ d="M1.225 61.523c-.222-.949.908-1.546 1.597-.857l36.512 36.512c.69.69.092 1.82-.857 1.597-18.425-4.323-32.93-18.827-37.252-37.252M.002 46.889a1 1 0 0 0 .29.76L52.35 99.71c.201.2.478.307.76.29 2.37-.149 4.695-.46 6.963-.927.765-.157 1.03-1.096.478-1.648L2.576 39.448c-.552-.551-1.491-.286-1.648.479a50 50 0 0 0-.926 6.962M4.21 29.705a.99.99 0 0 0 .208 1.1l64.776 64.776a.99.99 0 0 0 1.1.208 50 50 0 0 0 5.185-2.684.98.98 0 0 0 .183-1.54L8.436 24.336a.98.98 0 0 0-1.541.183 50 50 0 0 0-2.684 5.185m8.448-11.631a.986.986 0 0 1-.045-1.354C21.78 6.46 35.111 0 49.952 0 77.592 0 100 22.407 100 50.048c0 14.84-6.46 28.172-16.72 37.338a.986.986 0 0 1-1.354-.045z"
+ />
+ </svg>
+ );
+}
diff --git a/packages/ee/src/linear/lib/client.ts b/packages/ee/src/linear/lib/client.ts
new file mode 100644
index 0000000000..ea45b9e75b
--- /dev/null
+++ b/packages/ee/src/linear/lib/client.ts
@@ -0,0 +1,267 @@
+import { getCarbonServiceRole } from "@carbon/auth";
+import axios, { isAxiosError, type AxiosInstance } from "axios";
+import type z from "zod";
+import type { LinearIssueSchema } from "./service";
+import { getLinearIntegration } from "./service";
+import type { LinearWorkStateType } from "./utils";
+
+export type LinearIssue = z.infer<typeof LinearIssueSchema>;
+
+export interface LinearTeam {
+ id: string;
+ name: string;
+}
+
+export interface LinearUser {
+ id: string;
+ email: string;
+ name: string;
+}
+export class LinearClient {
+ instance: AxiosInstance;
+
+ constructor() {
+ this.instance = axios.create({
+ baseURL: "https://api.linear.app/graphql",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ });
+ }
+
+ async getAuthHeaders(companyId: string) {
+ const serviceRole = getCarbonServiceRole();
+
+ const { data } = await getLinearIntegration(serviceRole, companyId);
+
+ const integration = data?.[0];
+
+ if (!integration) {
+ throw new Error("Linear integration not found for company");
+ }
+
+ const metadata = integration.metadata as { apiKey: string };
+
+ return {
+ Authorization: metadata.apiKey,
+ };
+ }
+
+ async listTeams(companyId: string) {
+ const query = `query Teams { teams { nodes { id name } } }`;
+
+ const response = await this.instance.request<{
+ data: { teams: { nodes: LinearTeam[] } };
+ }>({
+ method: "POST",
+ headers: await this.getAuthHeaders(companyId),
+ data: {
+ query,
+ },
+ });
+
+ return response.data.data.teams.nodes.map((el) => el);
+ }
+
+ async listIssues(companyId: string, input: string) {
+ const query = `query SearchIssues($filter: IssueFilter!) { issues( filter: $filter first: 5 orderBy: updatedAt ) { nodes { id identifier title description state { name type color } url assignee { email } } } }`;
+
+ const response = await this.instance.request<{
+ data: { issues: { nodes: LinearIssue[] } };
+ }>({
+ method: "POST",
+ headers: await this.getAuthHeaders(companyId),
+ data: {
+ query,
+ variables: {
+ filter: {
+ title: { containsIgnoreCase: input },
+ },
+ },
+ },
+ });
+
+ return response.data.data.issues.nodes.map((el) => el);
+ }
+
+ async getIssueById(companyId: string, issueId: string) {
+ try {
+ const query = `query SearchIssues($filter: IssueFilter!) { issues( filter: $filter first: 1 orderBy: updatedAt ) { nodes { id identifier title dueDate description state { name type color } url assignee { email } } } }`;
+
+ const response = await this.instance.request<{
+ data: { issues: { nodes: LinearIssue[] } };
+ }>({
+ method: "POST",
+ headers: await this.getAuthHeaders(companyId),
+ data: {
+ query,
+ variables: { filter: { id: { eq: issueId } } },
+ },
+ });
+
+ return response.data.data.issues.nodes.at(0) || null;
+ } catch (error) {
+ if (isAxiosError(error)) {
+ console.dir(error.response.data, { depth: null });
+ console.dir(error.config.data, { depth: null });
+ }
+ }
+ }
+
+ async createAttachmentLink(
+ companyId: string,
+ input: { issueId: string; title: string; url: string }
+ ) {
+ const query = `mutation AttachmentCreate($input: AttachmentCreateInput!) { attachmentCreate(input: $input) { attachment { id } } }`;
+
+ const response = await this.instance.request<{
+ data: { issues: { nodes: LinearIssue[] } };
+ }>({
+ method: "POST",
+ headers: await this.getAuthHeaders(companyId),
+ data: {
+ query,
+ variables: {
+ input,
+ },
+ },
+ });
+
+ return response.data;
+ }
+
+ async listTeamMembers(companyId: string, teamId: string) {
+ const query = `query Team($teamId: String!) { team(id: $teamId) { members { nodes { id email name } } } }`;
+
+ const response = await this.instance.request<{
+ data: { team: { members: { nodes: LinearUser[] } } };
+ }>({
+ method: "POST",
+ headers: await this.getAuthHeaders(companyId),
+ data: {
+ query,
+ variables: { teamId },
+ },
+ });
+
+ return response.data.data.team.members.nodes.map((el) => el);
+ }
+
+ async createIssue(
+ companyId: string,
+ data: {
+ title: string;
+ description?: string;
+ teamId: string;
+ assigneeId?: string | null;
+ }
+ ) {
+ const query = `mutation IssueCreate($input: IssueCreateInput!) { issueCreate(input: $input) { issue { id identifier title dueDate description state { name type color } url assignee { email } } } }`;
+
+ const response = await this.instance.request<{
+ data: {
+ issueCreate: {
+ issue: LinearIssue;
+ };
+ };
+ }>({
+ method: "POST",
+ headers: await this.getAuthHeaders(companyId),
+ data: {
+ query,
+ variables: {
+ input: data,
+ },
+ },
+ });
+
+ return response.data.data.issueCreate.issue;
+ }
+
+ async getUsers(companyId: string, filter: { email?: string; id?: string }) {
+ const query = `query Users($filter: UserFilter) { users(filter: $filter) { edges { node { id email } } } }`;
+
+ const response = await this.instance.request<{
+ data: { users: { edges: Array<{ node: LinearUser }> } };
+ }>({
+ method: "POST",
+ headers: await this.getAuthHeaders(companyId),
+ data: {
+ query,
+ variables: { input: filter },
+ },
+ });
+
+ return response.data.data.users.edges.map((el) => el.node);
+ }
+
+ async updateIssue(
+ companyId: string,
+ data: {
+ id: string;
+ title?: string;
+ description?: string;
+ assigneeId?: string | null;
+ stateId?: string;
+ }
+ ) {
+ try {
+ const query = `mutation IssueUpdate($issueUpdateId: String!, $input: IssueUpdateInput!) { issueUpdate(id: $issueUpdateId, input: $input) { issue { id } } }`;
+ const { id, ...input } = data;
+
+ const response = await this.instance.request<{
+ data: {
+ issueUpdate: {
+ issue: { id: string };
+ };
+ };
+ }>({
+ method: "POST",
+ headers: await this.getAuthHeaders(companyId),
+ data: {
+ query,
+ variables: {
+ issueUpdateId: id,
+ input,
+ },
+ },
+ });
+
+ return response.data.data.issueUpdate.issue;
+ } catch (error) {
+ if (isAxiosError(error)) {
+ console.dir(error.response.data, { depth: null });
+ console.dir(error.config.data, { depth: null });
+ }
+ }
+ }
+
+ async getWorkflowState(companyId: string, type: LinearWorkStateType) {
+ const query = `query GetWorkflowState($filter: WorkflowStateFilter) { workflowStates(filter: $filter ) { nodes { id name color type } } }`;
+ const res = await this.instance.request<{
+ data: {
+ workflowStates: {
+ nodes: Array<{
+ id: string;
+ name: string;
+ color: string;
+ type: string;
+ }>;
+ };
+ };
+ }>({
+ method: "POST",
+ headers: await this.getAuthHeaders(companyId),
+ data: {
+ query,
+ variables: {
+ filter: {
+ type: { eq: type },
+ },
+ },
+ },
+ });
+
+ return res.data.data.workflowStates.nodes.at(0) || null;
+ }
+}
diff --git a/packages/ee/src/linear/lib/index.ts b/packages/ee/src/linear/lib/index.ts
new file mode 100644
index 0000000000..7e92f9ddc4
--- /dev/null
+++ b/packages/ee/src/linear/lib/index.ts
@@ -0,0 +1,4 @@
+export * from "./client";
+export * from "./richtext";
+export * from "./service";
+export * from "./utils";
diff --git a/packages/ee/src/linear/lib/richtext.ts b/packages/ee/src/linear/lib/richtext.ts
new file mode 100644
index 0000000000..b42fc6f7cb
--- /dev/null
+++ b/packages/ee/src/linear/lib/richtext.ts
@@ -0,0 +1,388 @@
+/**
+ * Utilities for bidirectional conversion between Markdown (Linear description format)
+ * and Tiptap JSON (Carbon's rich text format).
+ *
+ * Linear's API uses plain markdown for the `description` field.
+ * Carbon uses Tiptap/ProseMirror JSON for rich text editing.
+ */
+
+// Tiptap (ProseMirror) JSON format
+export type TiptapNode = {
+ type: string;
+ attrs?: Record<string, any>;
+ content?: TiptapNode[];
+ text?: string;
+ marks?: { type: string; attrs?: Record<string, any> }[];
+};
+
+export type TiptapDocument = {
+ type: "doc";
+ content: TiptapNode[];
+};
+
+/**
+ * Convert Markdown to Tiptap JSON format.
+ * This is used when syncing from Linear → Carbon.
+ */
+export function markdownToTiptap(
+ markdown: string | null | undefined
+): TiptapDocument {
+ if (!markdown || !markdown.trim()) {
+ return { type: "doc", content: [{ type: "paragraph" }] };
+ }
+
+ const lines = markdown.split("\n");
+ const content: TiptapNode[] = [];
+ let i = 0;
+
+ while (i < lines.length) {
+ const line = lines[i];
+
+ // Heading
+ const headingMatch = line.match(/^(#{1,6})\s+(.*)$/);
+ if (headingMatch) {
+ const level = headingMatch[1].length as 1 | 2 | 3 | 4 | 5 | 6;
+ content.push({
+ type: "heading",
+ attrs: { level },
+ content: parseInlineMarkdown(headingMatch[2]),
+ });
+ i++;
+ continue;
+ }
+
+ // Horizontal rule
+ if (/^(-{3,}|\*{3,}|_{3,})$/.test(line.trim())) {
+ content.push({ type: "horizontalRule" });
+ i++;
+ continue;
+ }
+
+ // Code block
+ if (line.startsWith("```")) {
+ const language = line.slice(3).trim() || undefined;
+ const codeLines: string[] = [];
+ i++;
+ while (i < lines.length && !lines[i].startsWith("```")) {
+ codeLines.push(lines[i]);
+ i++;
+ }
+ content.push({
+ type: "codeBlock",
+ attrs: language ? { language } : undefined,
+ content:
+ codeLines.length > 0
+ ? [{ type: "text", text: codeLines.join("\n") }]
+ : undefined,
+ });
+ i++; // Skip closing ```
+ continue;
+ }
+
+ // Blockquote
+ if (line.startsWith("> ")) {
+ const quoteLines: string[] = [];
+ while (i < lines.length && lines[i].startsWith("> ")) {
+ quoteLines.push(lines[i].slice(2));
+ i++;
+ }
+ content.push({
+ type: "blockquote",
+ content: [
+ {
+ type: "paragraph",
+ content: parseInlineMarkdown(quoteLines.join("\n")),
+ },
+ ],
+ });
+ continue;
+ }
+
+ // Unordered list
+ if (/^[-*+]\s+/.test(line)) {
+ const listItems: TiptapNode[] = [];
+ while (i < lines.length && /^[-*+]\s+/.test(lines[i])) {
+ const itemText = lines[i].replace(/^[-*+]\s+/, "");
+ listItems.push({
+ type: "listItem",
+ content: [
+ {
+ type: "paragraph",
+ content: parseInlineMarkdown(itemText),
+ },
+ ],
+ });
+ i++;
+ }
+ content.push({
+ type: "bulletList",
+ content: listItems,
+ });
+ continue;
+ }
+
+ // Ordered list
+ if (/^\d+\.\s+/.test(line)) {
+ const listItems: TiptapNode[] = [];
+ while (i < lines.length && /^\d+\.\s+/.test(lines[i])) {
+ const itemText = lines[i].replace(/^\d+\.\s+/, "");
+ listItems.push({
+ type: "listItem",
+ content: [
+ {
+ type: "paragraph",
+ content: parseInlineMarkdown(itemText),
+ },
+ ],
+ });
+ i++;
+ }
+ content.push({
+ type: "orderedList",
+ content: listItems,
+ });
+ continue;
+ }
+
+ // Empty line or regular paragraph
+ if (line.trim() === "") {
+ i++;
+ continue;
+ }
+
+ // Regular paragraph
+ content.push({
+ type: "paragraph",
+ content: parseInlineMarkdown(line),
+ });
+ i++;
+ }
+
+ if (content.length === 0) {
+ return { type: "doc", content: [{ type: "paragraph" }] };
+ }
+
+ return { type: "doc", content };
+}
+
+/**
+ * Parse inline markdown (bold, italic, links, code) into Tiptap nodes.
+ */
+function parseInlineMarkdown(text: string): TiptapNode[] {
+ if (!text) return [];
+
+ const nodes: TiptapNode[] = [];
+ let remaining = text;
+
+ while (remaining.length > 0) {
+ // Link: [text](url)
+ const linkMatch = remaining.match(/^\[([^\]]+)\]\(([^)]+)\)/);
+ if (linkMatch) {
+ nodes.push({
+ type: "text",
+ text: linkMatch[1],
+ marks: [{ type: "link", attrs: { href: linkMatch[2] } }],
+ });
+ remaining = remaining.slice(linkMatch[0].length);
+ continue;
+ }
+
+ // Bold: **text** or __text__
+ const boldMatch = remaining.match(/^(\*\*|__)(.+?)\1/);
+ if (boldMatch) {
+ nodes.push({
+ type: "text",
+ text: boldMatch[2],
+ marks: [{ type: "bold" }],
+ });
+ remaining = remaining.slice(boldMatch[0].length);
+ continue;
+ }
+
+ // Italic: *text* or _text_
+ const italicMatch = remaining.match(/^(\*|_)([^*_]+)\1/);
+ if (italicMatch) {
+ nodes.push({
+ type: "text",
+ text: italicMatch[2],
+ marks: [{ type: "italic" }],
+ });
+ remaining = remaining.slice(italicMatch[0].length);
+ continue;
+ }
+
+ // Strikethrough: ~~text~~
+ const strikeMatch = remaining.match(/^~~(.+?)~~/);
+ if (strikeMatch) {
+ nodes.push({
+ type: "text",
+ text: strikeMatch[1],
+ marks: [{ type: "strike" }],
+ });
+ remaining = remaining.slice(strikeMatch[0].length);
+ continue;
+ }
+
+ // Inline code: `text`
+ const codeMatch = remaining.match(/^`([^`]+)`/);
+ if (codeMatch) {
+ nodes.push({
+ type: "text",
+ text: codeMatch[1],
+ marks: [{ type: "code" }],
+ });
+ remaining = remaining.slice(codeMatch[0].length);
+ continue;
+ }
+
+ // Plain text (find next special character or end)
+ const nextSpecial = remaining.search(/[[*_~`]/);
+ if (nextSpecial === -1) {
+ nodes.push({ type: "text", text: remaining });
+ break;
+ } else if (nextSpecial === 0) {
+ // The special character didn't match a pattern, treat as literal
+ nodes.push({ type: "text", text: remaining[0] });
+ remaining = remaining.slice(1);
+ } else {
+ nodes.push({ type: "text", text: remaining.slice(0, nextSpecial) });
+ remaining = remaining.slice(nextSpecial);
+ }
+ }
+
+ return nodes;
+}
+
+/**
+ * Convert Tiptap JSON to Markdown format.
+ * This is used when syncing from Carbon → Linear.
+ */
+export function tiptapToMarkdown(
+ tiptapDoc: TiptapDocument | null | undefined
+): string {
+ if (!tiptapDoc || !tiptapDoc.content) return "";
+
+ return tiptapDoc.content.map(nodeToMarkdown).join("\n\n");
+}
+
+function nodeToMarkdown(node: TiptapNode): string {
+ switch (node.type) {
+ case "paragraph":
+ return node.content ? node.content.map(inlineToMarkdown).join("") : "";
+
+ case "heading": {
+ const level = node.attrs?.level ?? 1;
+ const prefix = "#".repeat(level);
+ const text = node.content
+ ? node.content.map(inlineToMarkdown).join("")
+ : "";
+ return `${prefix} ${text}`;
+ }
+
+ case "bulletList":
+ return (node.content ?? [])
+ .map((item) => {
+ const itemContent =
+ item.content?.map(nodeToMarkdown).join("\n") ?? "";
+ return `- ${itemContent}`;
+ })
+ .join("\n");
+
+ case "orderedList":
+ return (node.content ?? [])
+ .map((item, index) => {
+ const itemContent =
+ item.content?.map(nodeToMarkdown).join("\n") ?? "";
+ return `${index + 1}. ${itemContent}`;
+ })
+ .join("\n");
+
+ case "blockquote":
+ return (node.content ?? [])
+ .map((child) => `> ${nodeToMarkdown(child)}`)
+ .join("\n");
+
+ case "codeBlock": {
+ const language = node.attrs?.language ?? "";
+ const code = node.content?.[0]?.text ?? "";
+ return `\`\`\`${language}\n${code}\n\`\`\``;
+ }
+
+ case "horizontalRule":
+ return "---";
+
+ case "listItem":
+ return node.content?.map(nodeToMarkdown).join("\n") ?? "";
+
+ default:
+ return node.content ? node.content.map(inlineToMarkdown).join("") : "";
+ }
+}
+
+function inlineToMarkdown(node: TiptapNode): string {
+ if (node.type === "text") {
+ let text = node.text ?? "";
+
+ if (node.marks) {
+ for (const mark of node.marks) {
+ switch (mark.type) {
+ case "bold":
+ text = `**${text}**`;
+ break;
+ case "italic":
+ text = `*${text}*`;
+ break;
+ case "strike":
+ text = `~~${text}~~`;
+ break;
+ case "code":
+ text = `\`${text}\``;
+ break;
+ case "link":
+ text = `[${text}](${mark.attrs?.href ?? ""})`;
+ break;
+ }
+ }
+ }
+
+ return text;
+ }
+
+ if (node.type === "hardBreak") {
+ return "\n";
+ }
+
+ return "";
+}
+
+/**
+ * Check if two Tiptap documents have the same content.
+ * Used to prevent unnecessary syncs when content hasn't changed.
+ */
+export function tiptapDocumentsEqual(
+ a: TiptapDocument | null | undefined,
+ b: TiptapDocument | null | undefined
+): boolean {
+ if (!a && !b) return true;
+ if (!a || !b) return false;
+
+ return JSON.stringify(a) === JSON.stringify(b);
+}
+
+/**
+ * Check if a Tiptap document is empty (no meaningful content).
+ */
+export function isTiptapEmpty(doc: TiptapDocument | null | undefined): boolean {
+ if (!doc || !doc.content) return true;
+
+ const hasContent = doc.content.some((node) => {
+ if (node.type === "paragraph" && node.content) {
+ return node.content.some(
+ (inline) => inline.type === "text" && inline.text?.trim()
+ );
+ }
+ return node.content && node.content.length > 0;
+ });
+
+ return !hasContent;
+}
diff --git a/packages/ee/src/linear/lib/service.ts b/packages/ee/src/linear/lib/service.ts
new file mode 100644
index 0000000000..6faecca349
--- /dev/null
+++ b/packages/ee/src/linear/lib/service.ts
@@ -0,0 +1,140 @@
+import type { Database } from "@carbon/database";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import { z } from "zod";
+import { markdownToTiptap } from "./richtext";
+import { LinearWorkStateType, mapLinearStatusToCarbonStatus } from "./utils";
+
+export const LinearIssueSchema = z.object({
+ id: z.string(),
+ title: z.string(),
+ description: z.string().nullish(),
+ url: z.string(),
+ state: z.object({
+ name: z.string(),
+ color: z.string(),
+ type: z.nativeEnum(LinearWorkStateType),
+ }),
+ identifier: z.string(),
+ dueDate: z.string().nullish(),
+ assignee: z
+ .object({
+ email: z.string(),
+ })
+ .nullish(),
+});
+
+export async function getLinearIntegration(
+ client: SupabaseClient<Database>,
+ companyId: string
+) {
+ return await client
+ .from("companyIntegration")
+ .select("*")
+ .eq("companyId", companyId)
+ .eq("id", "linear")
+ .limit(1);
+}
+
+export function linkActionToLinearIssue(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ input: {
+ actionId: string;
+ issue: z.infer<typeof LinearIssueSchema>;
+ assignee?: string | null;
+ syncNotes?: boolean;
+ }
+) {
+ const { data, success } = LinearIssueSchema.safeParse(input.issue);
+
+ if (!success) return null;
+
+ // Convert Linear description (markdown) to Tiptap format for notes
+ let notes: any = undefined;
+ if (input.syncNotes && data.description) {
+ try {
+ notes = markdownToTiptap(data.description);
+ } catch (e) {
+ console.error("Failed to convert Linear description to Tiptap:", e);
+ }
+ }
+
+ const updateData: Record<string, any> = {
+ externalId: {
+ linear: data,
+ },
+ assignee: input.assignee,
+ status: mapLinearStatusToCarbonStatus(data.state.type!),
+ dueDate: data.dueDate,
+ };
+
+ // Only update notes if we successfully converted the description
+ if (notes !== undefined) {
+ updateData.notes = notes;
+ }
+
+ return client
+ .from("nonConformanceActionTask")
+ .update(updateData)
+ .eq("companyId", companyId)
+ .eq("id", input.actionId)
+ .select("nonConformanceId");
+}
+
+export const getCompanyEmployees = async (
+ client: SupabaseClient<Database>,
+ companyId: string,
+ emails: string[]
+) => {
+ const users = await client
+ .from("userToCompany")
+ .select("userId,user(email)")
+ .eq("companyId", companyId)
+ .eq("role", "employee")
+ .in("user.email", emails);
+
+ return users.data ?? [];
+};
+
+export function unlinkActionFromLinearIssue(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ input: {
+ actionId: string;
+ assignee?: string | null;
+ }
+) {
+ return client
+ .from("nonConformanceActionTask")
+ .update({
+ externalId: {
+ linear: undefined,
+ },
+ })
+ .eq("companyId", companyId)
+ .eq("id", input.actionId)
+ .select("nonConformanceId");
+}
+
+export const getLinearIssueFromExternalId = async (
+ client: SupabaseClient<Database>,
+ companyId: string,
+ actionId: string
+) => {
+ const { data: action } = await client
+ .from("nonConformanceActionTask")
+ .select("externalId")
+ .eq("companyId", companyId)
+ .eq("id", actionId)
+ .maybeSingle();
+
+ if (!action) return null;
+
+ const { data } = LinearIssueSchema.safeParse(
+ (action.externalId as any)?.linear
+ );
+
+ if (!data) return null;
+
+ return data;
+};
diff --git a/packages/ee/src/linear/lib/utils.ts b/packages/ee/src/linear/lib/utils.ts
new file mode 100644
index 0000000000..4f0f8684b6
--- /dev/null
+++ b/packages/ee/src/linear/lib/utils.ts
@@ -0,0 +1,50 @@
+import type { Database } from "@carbon/database";
+
+export enum LinearWorkStateType {
+ Triage = "triage",
+ Backlog = "backlog",
+ Todo = "todo",
+ Unstarted = "unstarted",
+ Started = "started",
+ Completed = "completed",
+ Canceled = "canceled",
+}
+
+type CarbonTaskStatus = Database["public"]["Enums"]["nonConformanceTaskStatus"];
+
+export const mapLinearStatusToCarbonStatus = (
+ status: LinearWorkStateType
+): CarbonTaskStatus => {
+ console.log("status", status);
+ switch (status) {
+ case LinearWorkStateType.Started:
+ return "In Progress";
+ case LinearWorkStateType.Canceled:
+ return "Skipped";
+ case LinearWorkStateType.Completed:
+ return "Completed";
+ case LinearWorkStateType.Triage:
+ case LinearWorkStateType.Unstarted:
+ case LinearWorkStateType.Todo:
+ case LinearWorkStateType.Backlog:
+ default:
+ return "Pending";
+ }
+};
+
+export const mapCarbonStatusToLinearStatus = (
+ status: string
+): LinearWorkStateType => {
+ switch (status) {
+ case "Pending":
+ return LinearWorkStateType.Unstarted;
+ case "In Progress":
+ return LinearWorkStateType.Started;
+ case "Completed":
+ return LinearWorkStateType.Completed;
+ case "Skipped":
+ return LinearWorkStateType.Canceled;
+ default:
+ throw new Error(`Unknown Carbon task status: ${status}`);
+ }
+};
diff --git a/packages/ee/src/notifications/index.ts b/packages/ee/src/notifications/index.ts
index 7d9cfd67c3..a880108216 100644
--- a/packages/ee/src/notifications/index.ts
+++ b/packages/ee/src/notifications/index.ts
@@ -1,7 +1,9 @@
import { notificationRegistry } from "./registry";
+import { LinearNotificationService } from "./services/linear";
import { SlackNotificationService } from "./services/slack";
notificationRegistry.register(new SlackNotificationService());
+notificationRegistry.register(new LinearNotificationService());
export * from "./pipeline";
export * from "./registry";
diff --git a/packages/ee/src/notifications/pipeline.ts b/packages/ee/src/notifications/pipeline.ts
index a8d587457b..1f58a50561 100644
--- a/packages/ee/src/notifications/pipeline.ts
+++ b/packages/ee/src/notifications/pipeline.ts
@@ -48,7 +48,7 @@ export class NotificationPipeline {
}
private isNotificationService(integrationId: string): boolean {
- const notificationServiceIds = ["slack"];
+ const notificationServiceIds = ["slack", "linear"];
return notificationServiceIds.includes(integrationId);
}
}
@@ -172,3 +172,31 @@ export async function notifyTaskAssigned(
integrations
);
}
+
+export async function notifyTaskNotesChanged(
+ context: NotificationContext,
+ integrations: CompanyIntegration[],
+ data: {
+ companyId: string;
+ userId: string;
+ carbonUrl: string;
+ task: {
+ id: string;
+ table: string;
+ notes: any; // Tiptap JSONContent
+ title?: string;
+ };
+ }
+): Promise<void> {
+ const pipeline = createNotificationPipeline(context);
+ await pipeline.send(
+ {
+ type: "task.notes.changed",
+ companyId: data.companyId,
+ userId: data.userId,
+ carbonUrl: data.carbonUrl,
+ data: data.task,
+ },
+ integrations
+ );
+}
diff --git a/packages/ee/src/notifications/services/linear.ts b/packages/ee/src/notifications/services/linear.ts
new file mode 100644
index 0000000000..b15ab7ed66
--- /dev/null
+++ b/packages/ee/src/notifications/services/linear.ts
@@ -0,0 +1,113 @@
+import { getUser } from "@carbon/auth";
+import type { Database } from "@carbon/database";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import {
+ getLinearIssueFromExternalId,
+ LinearClient,
+ mapCarbonStatusToLinearStatus,
+ tiptapToMarkdown,
+ type TiptapDocument,
+} from "../../linear/lib";
+import type { NotificationEvent, NotificationService } from "../types";
+
+const linear = new LinearClient();
+
+/**
+ * Linear Notification Service
+ * Updates Linear issues based on Carbon notification events
+ */
+export class LinearNotificationService implements NotificationService {
+ id = "linear";
+ name = "Linear";
+
+ async send(
+ event: NotificationEvent,
+ context: { serviceRole: SupabaseClient<Database> }
+ ): Promise<void> {
+ switch (event.type) {
+ case "task.status.changed": {
+ if (!["action", "investigation"].includes(event.data.type)) return;
+
+ const issue = await getLinearIssueFromExternalId(
+ context.serviceRole,
+ event.companyId,
+ event.data.id
+ );
+
+ if (!issue) return;
+
+ const state = await linear.getWorkflowState(
+ event.companyId,
+ mapCarbonStatusToLinearStatus(event.data.status)
+ );
+
+ await linear.updateIssue(event.companyId, {
+ id: issue.id,
+ stateId: state.id,
+ });
+
+ break;
+ }
+
+ case "task.assigned": {
+ if (event.data.table !== "nonConformanceActionTask") return;
+
+ const issue = await getLinearIssueFromExternalId(
+ context.serviceRole,
+ event.companyId,
+ event.data.id
+ );
+
+ if (!issue) return; // No linked Linear issue
+
+ const { data: user } = await getUser(
+ context.serviceRole,
+ event.data.assignee
+ );
+
+ if (!user) return; // No assignee user
+
+ const [linearUser] = await linear.getUsers(event.companyId, {
+ email: user.email,
+ });
+
+ if (!linearUser) return;
+
+ await linear.updateIssue(event.companyId, {
+ id: issue.id,
+ assigneeId: linearUser.id,
+ });
+ break;
+ }
+
+ case "task.notes.changed": {
+ if (event.data.table !== "nonConformanceActionTask") return;
+
+ const issue = await getLinearIssueFromExternalId(
+ context.serviceRole,
+ event.companyId,
+ event.data.id
+ );
+
+ if (!issue) return; // No linked Linear issue
+
+ // Convert Tiptap notes to markdown for Linear
+ const notes = event.data.notes as TiptapDocument | null | undefined;
+ if (!notes) return;
+
+ try {
+ const description = tiptapToMarkdown(notes);
+
+ await linear.updateIssue(event.companyId, {
+ id: issue.id,
+ description,
+ });
+ } catch (e) {
+ console.error("Failed to sync notes to Linear:", e);
+ }
+ break;
+ }
+ }
+ return;
+ }
+}
diff --git a/packages/ee/src/notifications/types.ts b/packages/ee/src/notifications/types.ts
index 6064227e83..85d6264f67 100644
--- a/packages/ee/src/notifications/types.ts
+++ b/packages/ee/src/notifications/types.ts
@@ -58,11 +58,22 @@ export interface TaskAssignedEvent extends BaseNotificationEvent {
};
}
+export interface TaskNotesChangedEvent extends BaseNotificationEvent {
+ type: "task.notes.changed";
+ data: {
+ id: string;
+ table: string;
+ notes: any; // Tiptap JSONContent
+ title?: string;
+ };
+}
+
export type NotificationEvent =
| IssueCreatedEvent
| IssueStatusChangedEvent
| TaskStatusChangedEvent
- | TaskAssignedEvent;
+ | TaskAssignedEvent
+ | TaskNotesChangedEvent;
// Notification service interface
export interface NotificationService {
diff --git a/packages/form/src/ValidatedForm.tsx b/packages/form/src/ValidatedForm.tsx
index 7c88e77858..492e320a4c 100644
--- a/packages/form/src/ValidatedForm.tsx
+++ b/packages/form/src/ValidatedForm.tsx
@@ -14,7 +14,7 @@ import React, {
useState,
} from "react";
import * as R from "remeda";
-import type { z } from 'zod/v3';
+import type { z } from "zod/v3";
import { useIsSubmitting, useIsValid } from "./hooks";
import type { MultiValueMap } from "./internal/MultiValueMap";
import { useMultiValueMap } from "./internal/MultiValueMap";
@@ -75,6 +75,12 @@ export type FormProps<DataType, Subaction extends string | undefined> = {
data: DataForSubaction<DataType, Subaction>,
event: React.FormEvent<HTMLFormElement>
) => void | Promise<void>;
+
+ /**
+ * A callback that fires after the promise returned by fetcher completes.
+ * As the default useFetcher doesn't support promises - we have a custom useAsyncFetcher hook.
+ */
+ onAfterSubmit?: () => void | Promise<void>;
/**
* Allows you to provide a `fetcher` from Remix's `useFetcher` hook.
* The form will use the fetcher for loading states, action data, etc
@@ -205,13 +211,16 @@ const useFormId = (providedId?: string): string | symbol => {
const FormResetter = ({
resetAfterSubmit,
formRef,
+ onComplete,
}: {
resetAfterSubmit: boolean;
formRef: RefObject<HTMLFormElement>;
+ onComplete?: () => void;
}) => {
const isSubmitting = useIsSubmitting();
const isValid = useIsValid();
useSubmitComplete(isSubmitting, () => {
+ typeof onComplete === "function" && onComplete();
if (isValid && resetAfterSubmit) {
formRef.current?.reset();
}
@@ -255,6 +264,7 @@ export function ValidatedForm<
>({
validator,
onSubmit,
+ onAfterSubmit,
children,
fetcher,
action,
@@ -420,8 +430,13 @@ export function ValidatedForm<
// 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.
- if (fetcher) fetcher.submit(formData, opts);
- else submit(formData, opts);
+ let value: any = fetcher
+ ? fetcher.submit(formData, opts)
+ : submit(formData, opts);
+
+ if (value instanceof Promise) {
+ await value;
+ }
}
};
@@ -451,7 +466,11 @@ export function ValidatedForm<
>
<InternalFormContext.Provider value={contextValue}>
<>
- <FormResetter formRef={formRef} resetAfterSubmit={resetAfterSubmit} />
+ <FormResetter
+ formRef={formRef}
+ resetAfterSubmit={resetAfterSubmit}
+ onComplete={onAfterSubmit}
+ />
{subaction && (
<input type="hidden" value={subaction} name="subaction" />
)}
diff --git a/packages/jobs/trigger/linear.ts b/packages/jobs/trigger/linear.ts
new file mode 100644
index 0000000000..211afaf4fc
--- /dev/null
+++ b/packages/jobs/trigger/linear.ts
@@ -0,0 +1,115 @@
+import { getCarbonServiceRole } from "@carbon/auth";
+import {
+ getCompanyEmployees,
+ LinearClient,
+ linkActionToLinearIssue,
+} from "@carbon/ee/linear";
+import { task } from "@trigger.dev/sdk";
+import { z } from "zod";
+
+const linear = new LinearClient();
+
+// Schema for webhook payload - we only need the issue ID since we fetch full details from Linear
+export const syncIssueFromLinearSchema = z.object({
+ companyId: z.string(),
+ event: z.discriminatedUnion("type", [
+ z.object({
+ type: z.literal("Issue"),
+ action: z.literal("update"),
+ data: z.object({
+ id: z.string(),
+ assigneeId: z.string().optional(),
+ }),
+ }),
+ ]),
+});
+
+export const syncIssueFromLinear = task({
+ id: "sync-issue-from-linear",
+ retry: {
+ maxAttempts: 1,
+ },
+ maxDuration: 5 * 60,
+ run: async (payload: z.infer<typeof syncIssueFromLinearSchema>) => {
+ console.info(`🔰 Linear webhook received: ${payload}`);
+ console.info(`📦 Payload:`, payload);
+
+ const carbon = getCarbonServiceRole();
+
+ const [company, integration] = await Promise.all([
+ carbon.from("company").select("*").eq("id", payload.companyId).single(),
+ carbon
+ .from("companyIntegration")
+ .select("*")
+ .eq("companyId", payload.companyId)
+ .eq("id", "linear")
+ .single(),
+ ]);
+
+ if (company.error || !company.data) {
+ throw new Error("Failed to fetch company from Carbon");
+ }
+
+ if (integration.error || !integration.data) {
+ throw new Error("Failed to fetch integration from Carbon");
+ }
+
+ const action = await carbon
+ .from("nonConformanceActionTask")
+ .select("id")
+ .eq("externalId->linear->>id", payload.event.data.id)
+ .eq("companyId", payload.companyId)
+ .maybeSingle();
+
+ if (!action.data) {
+ return {
+ success: false,
+ message: `No linked action found for Linear issue ID ${payload.event.data.id}`,
+ };
+ }
+
+ const fullIssue = await linear.getIssueById(
+ payload.companyId,
+ payload.event.data.id
+ );
+
+ if (!fullIssue) {
+ return {
+ success: false,
+ message: `Failed to fetch issue ${payload.event.data.id} from Linear`,
+ };
+ }
+
+ let assignee = null;
+
+ if (payload.event.data.assigneeId) {
+ const [linearUser] = await linear.getUsers(payload.companyId, {
+ id: payload.event.data.assigneeId,
+ });
+
+ const employees = await getCompanyEmployees(carbon, payload.companyId, [
+ linearUser?.email,
+ ]);
+ assignee = employees.length > 0 ? employees[0].userId : null;
+ }
+
+ const updated = await linkActionToLinearIssue(carbon, payload.companyId, {
+ actionId: action.data.id,
+ issue: fullIssue,
+ assignee,
+ syncNotes: true,
+ });
+
+ if (!updated || updated.error) {
+ return {
+ success: false,
+ message: `Failed to update action for Linear issue ID ${payload.event.data.id}`,
+ };
+ }
+
+ return {
+ success: true,
+ message: `Synced Linear issue ${payload.event.data.id}`,
+ };
+ },
+});
diff --git a/packages/jobs/tsconfig.json b/packages/jobs/tsconfig.json
index 82bf6bba2a..a173f9cefc 100644
--- a/packages/jobs/tsconfig.json
+++ b/packages/jobs/tsconfig.json
@@ -5,6 +5,11 @@
"rootDir": "./trigger",
"allowImportingTsExtensions": true
},
+ "references": [
+ {
+ "path": "../ee/tsconfig.json"
+ }
+ ],
"exclude": ["node_modules"],
"extends": "@carbon/tsconfig/base.json",
"include": ["trigger"]
diff --git a/packages/react/src/IconButton.tsx b/packages/react/src/IconButton.tsx
index 0042b9984a..fb0e6b5379 100644
--- a/packages/react/src/IconButton.tsx
+++ b/packages/react/src/IconButton.tsx
@@ -3,6 +3,7 @@ import { cloneElement, forwardRef, isValidElement } from "react";
import type { ButtonProps } from "./Button";
import { Button } from "./Button";
+import { cn } from "./utils/cn";
export interface IconButtonProps
extends Omit<ButtonProps, "leftIcon" | "rightIcon"> {
@@ -30,7 +31,7 @@ const IconButton = forwardRef<HTMLButtonElement, IconButtonProps>(
? cloneElement(element as any, {
"aria-hidden": true,
focusable: false,
- className: iconSizes[size],
+ className: cn(iconSizes[size], icon.props?.className),
})
: null;