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 Jira Cloud integration for quality issue tracking (#521)

Brad Barbin4f8eb8a13ccc
diff --git a/apps/erp/app/components/Icons.tsx b/apps/erp/app/components/Icons.tsx
index c3b11d82d0..29f9641715 100644
--- a/apps/erp/app/components/Icons.tsx
+++ b/apps/erp/app/components/Icons.tsx
@@ -478,3 +478,68 @@ export const LinearIssueStateBadge = (props: {
</Badge>
);
};
+
+export const JiraIcon = (props: React.SVGProps<SVGSVGElement>) => {
+ return (
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ viewBox="0 0 65 65"
+ fill="currentColor"
+ className={props.className}
+ {...props}
+ >
+ <defs>
+ <linearGradient id="jira-gradient-1" x1="98.03%" y1="0.16%" x2="58.89%" y2="40.53%">
+ <stop offset="0.18" stopColor="currentColor" stopOpacity="0.4" />
+ <stop offset="1" stopColor="currentColor" />
+ </linearGradient>
+ <linearGradient id="jira-gradient-2" x1="100.17%" y1="0.05%" x2="55.99%" y2="44.23%">
+ <stop offset="0.18" stopColor="currentColor" stopOpacity="0.4" />
+ <stop offset="1" stopColor="currentColor" />
+ </linearGradient>
+ </defs>
+ <path
+ d="M62.75 30.02L35.58 2.85 32.5 0 12.77 19.73 1.25 31.25a1.69 1.69 0 0 0 0 2.39L20 52.11l12.5 12.5 19.73-19.73.62-.62 9.9-9.9a1.69 1.69 0 0 0 0-2.34zM32.5 42.15l-9.65-9.65 9.65-9.65 9.65 9.65z"
+ fill="currentColor"
+ />
+ <path
+ d="M32.5 22.85A13.85 13.85 0 0 1 32.4 3L12.65 22.77l9.85 9.85z"
+ fill="url(#jira-gradient-1)"
+ />
+ <path
+ d="M42.17 32.48L32.5 42.15a13.86 13.86 0 0 1 0 19.6l19.77-19.75z"
+ fill="url(#jira-gradient-2)"
+ />
+ </svg>
+ );
+};
+
+export const JiraIssueStatusBadge = (props: {
+ status: { name: string; category: "new" | "indeterminate" | "done" };
+ className?: string;
+}) => {
+ let className = props.className;
+
+ let icon: React.ReactNode = (
+ <LuCircleDashed className={cn("text-foreground", className)} />
+ );
+
+ switch (props.status.category) {
+ case "new":
+ icon = <LuCircleDashed className={cn("text-foreground", className)} />;
+ break;
+ case "indeterminate":
+ icon = <AlmostDoneIcon className={className} />;
+ break;
+ case "done":
+ icon = <LuCircleCheck className={cn("text-emerald-600", className)} />;
+ break;
+ }
+
+ return (
+ <Badge variant={"secondary"} className="py-1 bg-transparent">
+ {icon}
+ <span className="ml-1">{props.status.name}</span>
+ </Badge>
+ );
+};
diff --git a/apps/erp/app/modules/quality/quality.service.ts b/apps/erp/app/modules/quality/quality.service.ts
index 99ad4ba653..71cf7bcc30 100644
--- a/apps/erp/app/modules/quality/quality.service.ts
+++ b/apps/erp/app/modules/quality/quality.service.ts
@@ -387,7 +387,7 @@ export async function getIssueAction(
) {
return client
.from("nonConformanceActionTask")
- .select("id,nonConformanceId,nonConformance(id,nonConformanceId)")
+ .select("id,notes,nonConformanceId,nonConformance(id,nonConformanceId)")
.eq("id", id)
.single();
}
@@ -416,20 +416,32 @@ export async function getIssueActionTasks(
return result;
}
- // Fetch Linear mappings for all action task IDs
+ // Fetch Linear and Jira mappings for all action task IDs
const taskIds = result.data.map((t) => t.id);
let linearMappings: Map<string, unknown> = new Map();
+ let jiraMappings: Map<string, unknown> = new Map();
if (taskIds.length > 0) {
- const { data: mappings } = await client
- .from("externalIntegrationMapping")
- .select("entityId, metadata")
- .eq("entityType", "nonConformanceActionTask")
- .eq("integration", "linear")
- .in("entityId", taskIds);
+ const [{ data: linearData }, { data: jiraData }] = await Promise.all([
+ client
+ .from("externalIntegrationMapping")
+ .select("entityId, metadata")
+ .eq("entityType", "nonConformanceActionTask")
+ .eq("integration", "linear")
+ .in("entityId", taskIds),
+ client
+ .from("externalIntegrationMapping")
+ .select("entityId, metadata")
+ .eq("entityType", "nonConformanceActionTask")
+ .eq("integration", "jira")
+ .in("entityId", taskIds)
+ ]);
linearMappings = new Map(
- (mappings ?? []).map((m) => [m.entityId, m.metadata])
+ (linearData ?? []).map((m) => [m.entityId, m.metadata])
+ );
+ jiraMappings = new Map(
+ (jiraData ?? []).map((m) => [m.entityId, m.metadata])
);
}
@@ -437,7 +449,8 @@ export async function getIssueActionTasks(
...result,
data: result.data.map((task) => ({
...task,
- linearIssue: linearMappings.get(task.id) ?? null
+ linearIssue: linearMappings.get(task.id) ?? null,
+ jiraIssue: jiraMappings.get(task.id) ?? null
}))
};
}
diff --git a/apps/erp/app/modules/quality/ui/Issue/IssueTask.tsx b/apps/erp/app/modules/quality/ui/Issue/IssueTask.tsx
index 67b59b001e..5d4e0ed17c 100644
--- a/apps/erp/app/modules/quality/ui/Issue/IssueTask.tsx
+++ b/apps/erp/app/modules/quality/ui/Issue/IssueTask.tsx
@@ -60,6 +60,7 @@ import type {
import { nonConformanceTaskStatus } from "~/modules/quality";
import { useSuppliers } from "~/stores";
import { getPrivateUrl, path } from "~/utils/path";
+import { JiraIssueDialog } from "./Jira/IssueDialog";
import { LinearIssueDialog } from "./Linear/IssueDialog";
export function TaskProgress({
@@ -75,7 +76,12 @@ export function TaskProgress({
const progressPercentage = (completedOrSkippedTasks / tasks.length) * 100;
return (
- <div className={cn("flex flex-col items-end gap-2 pt-2 pr-14", className)}>
+ <div
+ className={cn(
+ "flex flex-col items-end gap-2 py-3 pr-14 w-[120px]",
+ className
+ )}
+ >
<BarProgress
gradient
progress={progressPercentage}
@@ -277,15 +283,18 @@ export function TaskItem({
const statusAction =
statusActions[currentStatus as keyof typeof statusActions];
- // Check if this action task has a linked Linear issue
+ // Check if this action task has a linked Linear or Jira issue
const hasLinearLink =
type === "action" && !!(task as IssueActionTask).linearIssue;
+ const hasJiraLink =
+ type === "action" && !!(task as IssueActionTask).jiraIssue;
const { content, setContent, onUpdateContent, onUploadImage } = useTaskNotes({
initialContent: (task.notes ?? {}) as JSONContent,
taskId: task.id!,
type,
- hasLinearLink
+ hasLinearLink,
+ hasJiraLink
});
const { id } = useParams();
@@ -321,6 +330,7 @@ export function TaskItem({
)}
{integrations.has("linear") && <LinearIssueDialog task={task} />}
+ {integrations.has("jira") && <JiraIssueDialog task={task} />}
<IconButton
icon={<LuChevronRight />}
@@ -429,12 +439,14 @@ function useTaskNotes({
initialContent,
taskId,
type,
- hasLinearLink = false
+ hasLinearLink = false,
+ hasJiraLink = false
}: {
initialContent: JSONContent;
taskId: string;
type: "investigation" | "action" | "approval" | "review";
hasLinearLink?: boolean;
+ hasJiraLink?: boolean;
}) {
const {
id: userId,
@@ -492,6 +504,23 @@ function useTaskNotes({
console.error("Failed to sync notes to Linear:", e);
}
}
+
+ // Sync to Jira if this is an action task with a linked Jira issue
+ if (type === "action" && hasJiraLink) {
+ try {
+ await fetch(path.to.api.jiraSyncNotes, {
+ method: "POST",
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
+ body: new URLSearchParams({
+ actionId: taskId,
+ notes: JSON.stringify(content)
+ })
+ });
+ } catch (e) {
+ // Silently fail Jira sync - not critical
+ console.error("Failed to sync notes to Jira:", e);
+ }
+ }
},
2500,
true
diff --git a/apps/erp/app/modules/quality/ui/Issue/Jira/CreateIssue.tsx b/apps/erp/app/modules/quality/ui/Issue/Jira/CreateIssue.tsx
new file mode 100644
index 0000000000..b5c10e74da
--- /dev/null
+++ b/apps/erp/app/modules/quality/ui/Issue/Jira/CreateIssue.tsx
@@ -0,0 +1,141 @@
+import type { JiraIssueType, JiraProject, JiraUser } from "@carbon/ee/jira";
+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(),
+ projectKey: z.string().min(1, "Project is required"),
+ issueTypeId: z.string().min(1, "Issue type is required"),
+ title: z.string().min(1, "Title is required"),
+ description: z.string().optional()
+});
+
+export const CreateIssue = (props: Props) => {
+ const id = useId();
+ const [projectKey, setProjectKey] = useState<string | undefined>();
+
+ const { projects, issueTypes, members, fetcher } =
+ useJiraProjects(projectKey);
+
+ const projectOptions = useMemo(
+ () =>
+ projects.map((p) => ({ label: `${p.key} - ${p.name}`, value: p.key })),
+ [projects]
+ );
+
+ const issueTypeOptions = useMemo(
+ () => issueTypes.map((t) => ({ label: t.name, value: t.id })),
+ [issueTypes]
+ );
+
+ const memberOptions = useMemo(
+ () =>
+ members.map((m) => ({
+ label: m.displayName,
+ value: m.accountId
+ })),
+ [members]
+ );
+
+ const isLoading = fetcher.state === "loading";
+
+ return (
+ <ValidatedForm
+ id={id}
+ method="post"
+ action={path.to.api.jiraCreateIssue}
+ validator={createIssueValidator}
+ fetcher={fetcher}
+ resetAfterSubmit
+ onAfterSubmit={() => props.onClose()}
+ >
+ <VStack spacing={4}>
+ <Hidden name="actionId" value={props.task.id} />
+ <Select
+ isLoading={isLoading}
+ label="Project"
+ name="projectKey"
+ placeholder="Select a project"
+ value={projectKey}
+ onChange={(e) => setProjectKey(e?.value)}
+ options={projectOptions}
+ />
+ <Select
+ isLoading={isLoading}
+ label="Issue Type"
+ name="issueTypeId"
+ placeholder="Select an issue type"
+ options={issueTypeOptions}
+ isDisabled={!projectKey || issueTypes.length === 0}
+ />
+ <Input label="Title" name="title" placeholder="Issue title" required />
+ <TextArea
+ label="Description"
+ name="description"
+ placeholder="Issue description"
+ />
+ <Select
+ label="Assign To"
+ name="assignee"
+ placeholder="Select an assignee"
+ isOptional
+ options={memberOptions}
+ isDisabled={!projectKey || members.length === 0}
+ />
+ </VStack>
+ <ModalFooter className="px-0 pb-0">
+ <Button
+ variant="secondary"
+ onClick={() => {
+ props.onClose();
+ }}
+ >
+ Cancel
+ </Button>
+ <Submit>Create</Submit>
+ </ModalFooter>
+ </ValidatedForm>
+ );
+};
+
+CreateIssue.displayName = "CreateIssue";
+
+const useJiraProjects = (projectKey?: string) => {
+ const fetcher = useAsyncFetcher<{
+ projects: JiraProject[];
+ issueTypes: JiraIssueType[];
+ members: JiraUser[];
+ }>();
+
+ // biome-ignore lint/correctness/useExhaustiveDependencies: not necessary
+ useEffect(() => {
+ fetcher.load(
+ path.to.api.jiraCreateIssue +
+ (projectKey ? `?projectKey=${projectKey}` : "")
+ );
+ }, [projectKey]);
+
+ return {
+ projects: fetcher.data?.projects || [],
+ issueTypes: fetcher.data?.issueTypes || [],
+ members: fetcher.data?.members || [],
+ fetcher
+ };
+};
diff --git a/apps/erp/app/modules/quality/ui/Issue/Jira/IssueDialog.tsx b/apps/erp/app/modules/quality/ui/Issue/Jira/IssueDialog.tsx
new file mode 100644
index 0000000000..b66d7022d0
--- /dev/null
+++ b/apps/erp/app/modules/quality/ui/Issue/Jira/IssueDialog.tsx
@@ -0,0 +1,181 @@
+import { JiraIssueMappingSchema } from "@carbon/ee/jira";
+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 { LuExternalLink } from "react-icons/lu";
+import { PiLinkBreak } from "react-icons/pi";
+import { Link, useRevalidator } from "react-router";
+import { JiraIcon, JiraIssueStatusBadge } from "~/components/Icons";
+import { useAsyncFetcher } from "~/hooks/useAsyncFetcher";
+import type { IssueActionTask } from "~/modules/quality/types";
+import { path } from "~/utils/path";
+import { CreateIssue } from "./CreateIssue";
+import { LinkIssue } from "./LinkIssue";
+
+interface Props {
+ task: IssueActionTask;
+}
+
+export const JiraIssueDialog = ({ task }: Props) => {
+ const [tab, setTab] = useState("link");
+ const revalidator = useRevalidator();
+
+ const disclosure = useDisclosure({
+ onClose() {
+ setTab("link");
+ revalidator.revalidate();
+ }
+ });
+
+ const { data: linked } = JiraIssueMappingSchema.safeParse(task.jiraIssue);
+ const fetcher = useAsyncFetcher();
+
+ const onUnlink = async () => {
+ await fetcher.submit(
+ { actionId: task.id },
+ { method: "DELETE", action: path.to.api.jiraLinkExistingIssue }
+ );
+ disclosure.onClose();
+ };
+
+ const isAlreadyLinked = !!linked?.id;
+
+ return (
+ <Modal
+ open={disclosure.isOpen}
+ onOpenChange={(open) => {
+ if (!open) {
+ disclosure.onClose();
+ }
+ }}
+ >
+ <ModalTrigger onClick={() => disclosure.onToggle()}>
+ {linked ? (
+ <Button
+ leftIcon={<JiraIcon className={"size-4"} />}
+ variant="ghost"
+ aria-label="Update Jira issue"
+ >
+ {linked.key}
+ </Button>
+ ) : (
+ <IconButton
+ icon={<JiraIcon className={"size-4 grayscale"} />}
+ variant="ghost"
+ aria-label="Connect Jira issue"
+ />
+ )}
+ </ModalTrigger>
+ <ModalContent size={"large"}>
+ <Tabs value={tab} onValueChange={setTab} defaultValue="link">
+ <ModalHeader className="mb-1 flex-row justify-between py-3 pr-10">
+ <div className="space-y-1">
+ <ModalTitle>Link Jira Issue</ModalTitle>
+ <ModalDescription>
+ Search for existing or create a new one
+ </ModalDescription>
+ </div>
+
+ <TabsList className="max-w-max mb-4">
+ <TabsTrigger value="link" disabled={isAlreadyLinked}>
+ Link Existing
+ </TabsTrigger>
+ <TabsTrigger value="create" disabled={isAlreadyLinked}>
+ 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">
+ <Link
+ to={linked.url}
+ target="_blank"
+ rel="noreferrer"
+ className="flex items-center"
+ >
+ <span className="mr-2 text-foreground flex items-center">
+ {linked.summary}
+ <LuExternalLink className="size-4 ml-2 text-primary" />
+ </span>
+ </Link>
+
+ <div className="flex items-center gap-2">
+ <Badge
+ variant={"outline"}
+ className="font-normal font-mono text-muted-foreground flex items-center"
+ >
+ {linked.key}
+ </Badge>
+ <JiraIssueStatusBadge
+ status={linked.status}
+ className="size-3.5"
+ />
+ </div>
+ </div>
+
+ <div className="mt-2 text-sm text-muted-foreground flex justify-between items-center">
+ <span>
+ {linked.assignee?.displayName
+ ? `Assigned to ${linked.assignee.displayName}`
+ : "Unassigned"}
+ </span>
+
+ <Button
+ onClick={onUnlink}
+ isLoading={fetcher.state === "submitting"}
+ leftIcon={<PiLinkBreak />}
+ size="sm"
+ variant={"destructive"}
+ >
+ Unlink
+ </Button>
+ </div>
+ </div>
+ </div>
+ </div>
+ )}
+
+ <TabsContent
+ value="link"
+ hidden={isAlreadyLinked}
+ 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/Jira/LinkIssue.tsx b/apps/erp/app/modules/quality/ui/Issue/Jira/LinkIssue.tsx
new file mode 100644
index 0000000000..343d342950
--- /dev/null
+++ b/apps/erp/app/modules/quality/ui/Issue/Jira/LinkIssue.tsx
@@ -0,0 +1,183 @@
+import type { JiraIssueMapping } from "@carbon/ee/jira";
+import { Hidden, Submit, ValidatedForm } from "@carbon/form";
+import {
+ Badge,
+ Button,
+ cn,
+ Input,
+ ModalFooter,
+ Spinner,
+ ToggleGroup,
+ ToggleGroupItem,
+ useDebounce,
+ VStack
+} from "@carbon/react";
+import { useId, useState } from "react";
+import z from "zod";
+import { JiraIssueStatusBadge } from "~/components/Icons";
+import { useAsyncFetcher } from "~/hooks/useAsyncFetcher";
+import type { IssueActionTask } from "~/modules/quality";
+import { path } from "~/utils/path";
+
+type Props = {
+ task: IssueActionTask;
+ linked?: JiraIssueMapping | null;
+ onClose: () => void;
+};
+
+const linkIssueValidator = z.object({
+ actionId: z.string(),
+ issueId: z.string()
+});
+
+// Jira issue shape from search API
+interface JiraSearchIssue {
+ id: string;
+ key: string;
+ fields: {
+ summary: string;
+ status: {
+ name: string;
+ statusCategory: {
+ key: "new" | "indeterminate" | "done";
+ };
+ };
+ assignee: {
+ displayName: string;
+ emailAddress?: string;
+ } | null;
+ };
+}
+
+export const LinkIssue = (props: Props) => {
+ const id = useId();
+ const [issueId, setIssueId] = useState<string | undefined>();
+
+ const { issues, fetcher } = useJiraIssues();
+
+ const onSearch = useDebounce((e: React.ChangeEvent<HTMLInputElement>) => {
+ if (!e.target.value || e.target.value.trim().length < 3) return;
+
+ fetcher.load(
+ path.to.api.jiraLinkExistingIssue +
+ `?actionId=${props.task.id}&search=${e.target.value}`
+ );
+ }, 300);
+
+ const isSearching = fetcher.state === "loading";
+
+ return (
+ <ValidatedForm
+ id={id}
+ method="post"
+ action={path.to.api.jiraLinkExistingIssue}
+ 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 Jira 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-transparent hover:data-[state=on]:bg-transparent data-[state=on]:border-primary hover:data-[state=on]:border-primary"
+ )}
+ >
+ <div className="flex items-start justify-between gap-2">
+ <div className="flex-1">
+ <div className="flex items-center gap-2 justify-between">
+ <span className="mr-2 text-foreground flex items-center">
+ {issue.fields.summary}
+ </span>
+
+ <div className="flex items-center gap-2">
+ <Badge
+ variant={"outline"}
+ className="font-normal font-mono text-muted-foreground flex items-center"
+ >
+ {issue.key}
+ </Badge>
+ <JiraIssueStatusBadge
+ status={{
+ name: issue.fields.status.name,
+ category: issue.fields.status.statusCategory.key
+ }}
+ className="size-3.5"
+ />
+ </div>
+ </div>
+
+ <div className="mt-2 text-sm text-muted-foreground flex justify-between items-center">
+ <span>
+ {issue.fields.assignee?.displayName
+ ? `Assigned to ${issue.fields.assignee.displayName}`
+ : "Unassigned"}
+ </span>
+ </div>
+ </div>
+ </div>
+ </ToggleGroupItem>
+ ))}
+
+ {issues.length === 0 && !isSearching && (
+ <p className="text-sm text-muted-foreground">
+ No Jira issues found
+ </p>
+ )}
+ </ToggleGroup>
+ </VStack>
+ <ModalFooter className="px-0 pb-0">
+ <Button
+ variant="secondary"
+ onClick={() => {
+ props.onClose();
+ }}
+ >
+ Cancel
+ </Button>
+ <Submit>Save</Submit>
+ </ModalFooter>
+ </ValidatedForm>
+ );
+};
+
+LinkIssue.displayName = "LinkIssue";
+
+const useJiraIssues = () => {
+ const fetcher = useAsyncFetcher<{
+ issues: JiraSearchIssue[];
+ }>();
+
+ return {
+ issues: fetcher.data?.issues || [],
+ fetcher
+ };
+};
diff --git a/apps/erp/app/modules/quality/ui/IssueWorkflows/IssueWorkflowForm.tsx b/apps/erp/app/modules/quality/ui/IssueWorkflows/IssueWorkflowForm.tsx
index d3ed977bbf..445923c22b 100644
--- a/apps/erp/app/modules/quality/ui/IssueWorkflows/IssueWorkflowForm.tsx
+++ b/apps/erp/app/modules/quality/ui/IssueWorkflows/IssueWorkflowForm.tsx
@@ -232,37 +232,45 @@ const IssueWorkflowForm = ({
}))}
/>
</div>
- <VStack spacing={2}>
- <label
- htmlFor="requiredActions"
- className="text-xs text-muted-foreground font-medium"
- >
- Required Actions (in order)
- </label>
-
- {orderedActions.length > 0 && (
- <Reorder.Group
- axis="y"
- values={selectedActionIds}
- onReorder={handleReorder}
- className="w-full space-y-2"
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4 w-full">
+ <VStack spacing={2}>
+ <label
+ htmlFor="requiredActions"
+ className="text-xs text-muted-foreground font-medium"
>
- {orderedActions.map((action) => (
- <ReorderableActionItem
- key={action.id}
- action={action}
- onRemove={() => handleRemoveAction(action.id)}
- />
- ))}
- </Reorder.Group>
- )}
+ Required Actions (in order)
+ </label>
+
+ {orderedActions.length > 0 && (
+ <Reorder.Group
+ axis="y"
+ values={selectedActionIds}
+ onReorder={handleReorder}
+ className="w-full space-y-2"
+ >
+ {orderedActions.map((action) => (
+ <ReorderableActionItem
+ key={action.id}
+ action={action}
+ onRemove={() => handleRemoveAction(action.id)}
+ />
+ ))}
+ </Reorder.Group>
+ )}
- {availableActions.length > 0 && (
- <VStack spacing={2} className="mt-2">
- <p className="text-xs text-muted-foreground">
- Available Actions (click to add):
+ {orderedActions.length === 0 && (
+ <p className="text-sm text-muted-foreground italic">
+ No actions selected
</p>
- <div className="grid grid-cols-1 md:grid-cols-2 gap-2">
+ )}
+ </VStack>
+
+ <VStack spacing={2}>
+ <p className="text-xs text-muted-foreground font-medium">
+ Available Actions (click to add)
+ </p>
+ {availableActions.length > 0 ? (
+ <div className="flex flex-col gap-2">
{availableActions.map((action) => (
<button
key={action.id}
@@ -273,21 +281,19 @@ const IssueWorkflowForm = ({
<Checkbox
onClick={(e) => e.preventDefault()}
isChecked={false}
- readOnly
+ disabled
/>
<span>{action.name}</span>
</button>
))}
</div>
- </VStack>
- )}
-
- {orderedActions.length === 0 && availableActions.length === 0 && (
- <p className="text-sm text-muted-foreground italic">
- No required actions available
- </p>
- )}
- </VStack>
+ ) : (
+ <p className="text-sm text-muted-foreground italic">
+ All actions selected
+ </p>
+ )}
+ </VStack>
+ </div>
<MultiSelect
name="approvalRequirements"
diff --git a/apps/erp/app/root.tsx b/apps/erp/app/root.tsx
index 9483056c7a..1c18d903ed 100644
--- a/apps/erp/app/root.tsx
+++ b/apps/erp/app/root.tsx
@@ -63,6 +63,7 @@ export async function loader({ request, context }: LoaderFunctionArgs) {
CLOUDFLARE_TURNSTILE_SITE_KEY,
CONTROLLED_ENVIRONMENT,
GOOGLE_PLACES_API_KEY,
+ JIRA_CLIENT_ID,
NOVU_APPLICATION_ID,
ONSHAPE_CLIENT_ID,
POSTHOG_API_HOST,
@@ -84,6 +85,7 @@ export async function loader({ request, context }: LoaderFunctionArgs) {
CLOUDFLARE_TURNSTILE_SITE_KEY,
CONTROLLED_ENVIRONMENT,
GOOGLE_PLACES_API_KEY,
+ JIRA_CLIENT_ID,
NOVU_APPLICATION_ID,
ONSHAPE_CLIENT_ID,
POSTHOG_API_HOST,
diff --git a/apps/erp/app/routes/api+/integrations.jira.issue.create.ts b/apps/erp/app/routes/api+/integrations.jira.issue.create.ts
new file mode 100644
index 0000000000..e9062c9ca0
--- /dev/null
+++ b/apps/erp/app/routes/api+/integrations.jira.issue.create.ts
@@ -0,0 +1,164 @@
+import { getAppUrl } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import {
+ getCompanyEmployees,
+ getJiraClient,
+ linkActionToJiraIssue,
+ tiptapToAdf
+} from "@carbon/ee/jira";
+import type { ActionFunction, LoaderFunction } from "react-router";
+import { data } from "react-router";
+import { getIssueAction } from "~/modules/quality/quality.service";
+
+const jira = getJiraClient();
+
+export const action: ActionFunction = async ({ request }) => {
+ try {
+ const formData = await request.formData();
+
+ const { companyId, client } = await requirePermissions(request, {});
+
+ const actionId = formData.get("actionId") as string;
+ const projectKey = formData.get("projectKey") as string;
+ const issueTypeId = formData.get("issueTypeId") as string;
+ const summary = formData.get("title") as string;
+ const description = formData.get("description") as string;
+ const assigneeId = formData.get("assignee") as string;
+
+ if (!actionId || !projectKey || !issueTypeId || !summary) {
+ return data(
+ {
+ success: false,
+ message:
+ "Missing required fields: actionId, projectKey, issueTypeId, title"
+ },
+ { status: 400 }
+ );
+ }
+
+ const [carbonIssue, siteUrl] = await Promise.all([
+ getIssueAction(client, actionId),
+ jira.getSiteUrl(companyId)
+ ]);
+
+ // Use the task's notes as the Jira issue description, falling back to form description
+ let adfDescription: any = undefined;
+ const notes = carbonIssue.data?.notes;
+ if (notes && typeof notes === "object") {
+ try {
+ adfDescription = tiptapToAdf(notes as any);
+ } catch (e) {
+ console.error("Failed to convert notes to ADF:", e);
+ }
+ }
+
+ if (!adfDescription && description) {
+ try {
+ const tiptapDoc = JSON.parse(description);
+ adfDescription = tiptapToAdf(tiptapDoc);
+ } catch {
+ adfDescription = {
+ version: 1,
+ type: "doc",
+ content: [
+ {
+ type: "paragraph",
+ content: [{ type: "text", text: description }]
+ }
+ ]
+ };
+ }
+ }
+
+ const issue = await jira.createIssue(companyId, {
+ projectKey,
+ issueTypeId,
+ summary,
+ description: adfDescription,
+ assigneeId: assigneeId || undefined
+ });
+
+ if (!issue) {
+ return data(
+ { success: false, message: "Failed to create Jira issue" },
+ { status: 500 }
+ );
+ }
+
+ const linked = await linkActionToJiraIssue(client, companyId, {
+ actionId,
+ issue,
+ siteUrl
+ });
+
+ if (!linked || linked.data?.length === 0) {
+ return data(
+ { success: false, message: "Failed to link issue" },
+ { status: 500 }
+ );
+ }
+
+ const nonConformanceId = linked.data?.[0].nonConformanceId;
+
+ const url = getAppUrl() + `/x/issue/${nonConformanceId}/details`;
+
+ // Create a remote link in Jira pointing back to Carbon
+ await jira.createRemoteLink(
+ companyId,
+ issue.id,
+ url,
+ `Linked Carbon Issue: ${carbonIssue.data?.nonConformance?.nonConformanceId ?? ""}`
+ );
+
+ return { success: true, message: "Jira issue created" };
+ } catch (error) {
+ console.error("Jira issue action error:", error);
+ return data(
+ { success: false, message: "Failed to create issue" },
+ { status: 400 }
+ );
+ }
+};
+
+export const loader: LoaderFunction = async ({ request }) => {
+ const { companyId, client } = await requirePermissions(request, {});
+
+ const url = new URL(request.url);
+
+ const projectKey = url.searchParams.get("projectKey") as string;
+ const projects = await jira.listProjects(companyId);
+
+ if (projectKey) {
+ const [issueTypes, members] = await Promise.all([
+ jira.getIssueTypes(companyId, projectKey),
+ jira.listProjectUsers(companyId, projectKey)
+ ]);
+
+ // Filter members to only those who are also Carbon employees
+ const memberEmails = members
+ .map((m) => m.emailAddress)
+ .filter((e): e is string => !!e);
+
+ const employees = await getCompanyEmployees(
+ client,
+ companyId,
+ memberEmails
+ );
+
+ // Filter to members who are also Carbon employees
+ const filteredMembers = members.filter((m) =>
+ employees.some((e) => {
+ if (!e.user?.email || !m.emailAddress) return false;
+ return e.user.email.toLowerCase() === m.emailAddress.toLowerCase();
+ })
+ );
+
+ return {
+ projects,
+ issueTypes,
+ members: filteredMembers
+ };
+ }
+
+ return { projects };
+};
diff --git a/apps/erp/app/routes/api+/integrations.jira.issue.link.ts b/apps/erp/app/routes/api+/integrations.jira.issue.link.ts
new file mode 100644
index 0000000000..cd5dbdc4ca
--- /dev/null
+++ b/apps/erp/app/routes/api+/integrations.jira.issue.link.ts
@@ -0,0 +1,166 @@
+import { getAppUrl } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import {
+ getJiraClient,
+ getJiraIssueFromExternalId,
+ linkActionToJiraIssue,
+ tiptapToAdf,
+ unlinkActionFromJiraIssue
+} from "@carbon/ee/jira";
+import type { ActionFunction, LoaderFunction } from "react-router";
+import { data } from "react-router";
+import { getIssueAction } from "~/modules/quality/quality.service";
+
+const jira = getJiraClient();
+
+export const action: ActionFunction = async ({ request }) => {
+ try {
+ 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, siteUrl] = await Promise.all([
+ getIssueAction(client, actionId),
+ jira.getIssue(companyId, issueId),
+ jira.getSiteUrl(companyId)
+ ]);
+
+ if (!issue) {
+ return { success: false, message: "Issue not found" };
+ }
+
+ const email = issue.fields.assignee?.emailAddress ?? "";
+
+ let assigneeId: string | null = null;
+ if (email) {
+ const assignee = await client
+ .from("user")
+ .select("id")
+ .eq("email", email)
+ .single();
+ assigneeId = assignee.data?.id ?? null;
+ }
+
+ const linked = await linkActionToJiraIssue(client, companyId, {
+ actionId,
+ issue,
+ siteUrl,
+ assignee: assigneeId
+ });
+
+ if (!linked || linked.data?.length === 0) {
+ return { success: false, message: "Failed to link issue" };
+ }
+
+ const nonConformanceId = linked.data?.[0].nonConformanceId;
+
+ const url = getAppUrl() + `/x/issue/${nonConformanceId}/details`;
+
+ // Update the Jira issue description with the task's notes
+ const notes = carbonIssue.data?.notes;
+ if (notes && typeof notes === "object") {
+ try {
+ const adfDescription = tiptapToAdf(notes as any);
+ await jira.updateIssue(companyId, issue.id, {
+ description: adfDescription
+ });
+ } catch (e) {
+ console.error("Failed to update Jira issue description:", e);
+ }
+ }
+
+ // Create a remote link in Jira pointing back to Carbon
+ await jira.createRemoteLink(
+ companyId,
+ issue.id,
+ url,
+ `Linked Carbon Issue: ${
+ carbonIssue.data?.nonConformance?.nonConformanceId ?? ""
+ }`
+ );
+
+ return { success: true, message: "Linked successfully" };
+ }
+
+ case "DELETE": {
+ const mapping = await getJiraIssueFromExternalId(
+ client,
+ companyId,
+ actionId
+ );
+
+ // Unlink from Carbon's DB first
+ const unlinked = await unlinkActionFromJiraIssue(client, companyId, {
+ actionId
+ });
+
+ if (unlinked.error) {
+ return { success: false, message: "Failed to unlink issue" };
+ }
+
+ // Best-effort: clean up remote link in Jira
+ if (mapping) {
+ try {
+ const remoteLinks = await jira.getRemoteLinks(
+ companyId,
+ mapping.id
+ );
+ const carbonLink = remoteLinks.find(
+ (link) =>
+ link.application?.name === "Carbon" ||
+ link.globalId.startsWith("carbon-")
+ );
+ if (carbonLink) {
+ await jira.deleteRemoteLink(
+ companyId,
+ mapping.id,
+ carbonLink.globalId
+ );
+ }
+ } catch (e) {
+ console.error("Failed to clean up Jira remote link:", e);
+ }
+ }
+
+ return { success: true, message: "Unlinked successfully" };
+ }
+ }
+ } catch (error) {
+ console.error("Jira issue link action error:", error);
+ return data(
+ { success: false, message: `Failed to process request` },
+ { status: 400 }
+ );
+ }
+};
+
+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;
+
+ if (!query || query.trim().length === 0) {
+ return { issues: [] };
+ }
+
+ const issues = await jira.searchIssues(companyId, query);
+
+ return { issues };
+};
diff --git a/apps/erp/app/routes/api+/integrations.jira.issue.sync-notes.ts b/apps/erp/app/routes/api+/integrations.jira.issue.sync-notes.ts
new file mode 100644
index 0000000000..0de0dfa840
--- /dev/null
+++ b/apps/erp/app/routes/api+/integrations.jira.issue.sync-notes.ts
@@ -0,0 +1,63 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import type { TiptapDocument } from "@carbon/ee/jira";
+import {
+ getJiraClient,
+ getJiraIssueFromExternalId,
+ tiptapToAdf
+} from "@carbon/ee/jira";
+import type { ActionFunction } from "react-router";
+import { data } from "react-router";
+
+const jira = getJiraClient();
+
+export const action: ActionFunction = async ({ request }) => {
+ const { companyId, client } = await requirePermissions(request, {});
+
+ if (request.method !== "POST") {
+ return data({ 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 data({ success: false, message: "Missing actionId" }, 400);
+ }
+
+ // Parse the notes JSON
+ let notes: TiptapDocument | null = null;
+ try {
+ notes = notesStr ? JSON.parse(notesStr) : null;
+ } catch {
+ return data({ success: false, message: "Invalid notes format" }, 400);
+ }
+
+ // Get the linked Jira issue
+ const issue = await getJiraIssueFromExternalId(client, companyId, actionId);
+
+ if (!issue) {
+ return { success: true, message: "No linked Jira issue" };
+ }
+
+ if (!notes) {
+ return { success: true, message: "No notes to sync" };
+ }
+
+ try {
+ // Convert Tiptap notes to ADF for Jira
+ const description = tiptapToAdf(notes);
+
+ await jira.updateIssue(companyId, issue.id, {
+ description
+ });
+
+ return { success: true, message: "Notes synced to Jira" };
+ } catch (error) {
+ console.error("Failed to sync notes to Jira:", error);
+ return data(
+ { success: false, message: "Failed to sync notes to Jira" },
+ 500
+ );
+ }
+};
diff --git a/apps/erp/app/routes/api+/integrations.jira.oauth.ts b/apps/erp/app/routes/api+/integrations.jira.oauth.ts
new file mode 100644
index 0000000000..04929aba04
--- /dev/null
+++ b/apps/erp/app/routes/api+/integrations.jira.oauth.ts
@@ -0,0 +1,108 @@
+import { VERCEL_URL } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { getIntegrationConfigById } from "@carbon/ee";
+import { exchangeCodeForTokens, getAccessibleResources } from "@carbon/ee/jira";
+import type { LoaderFunctionArgs } from "react-router";
+import { data, redirect } from "react-router";
+import { upsertCompanyIntegration } from "~/modules/settings/settings.server";
+import { oAuthCallbackSchema } from "~/modules/shared";
+import { path } from "~/utils/path";
+
+export const config = {
+ runtime: "nodejs"
+};
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, userId, companyId } = await requirePermissions(request, {
+ update: "settings"
+ });
+
+ const url = new URL(request.url);
+ const searchParams = Object.fromEntries(url.searchParams.entries());
+
+ const jiraAuthResponse = oAuthCallbackSchema.safeParse(searchParams);
+
+ if (!jiraAuthResponse.success) {
+ return data({ error: "Invalid Jira auth response" }, { status: 400 });
+ }
+
+ const { data: params } = jiraAuthResponse;
+
+ if (!params.state) {
+ return data({ error: "Invalid state parameter" }, { status: 400 });
+ }
+
+ try {
+ const redirectUri = `${url.origin}/api/integrations/jira/oauth`;
+
+ // Exchange the authorization code for tokens
+ const tokens = await exchangeCodeForTokens(params.code, redirectUri);
+
+ if (!tokens) {
+ return data(
+ { error: "Failed to exchange code for token" },
+ { status: 500 }
+ );
+ }
+
+ // Get accessible resources to find cloudId
+ const resources = await getAccessibleResources(tokens.accessToken);
+
+ if (resources.length === 0) {
+ return data(
+ {
+ error:
+ "No Jira Cloud sites found. Make sure you have access to at least one Jira site."
+ },
+ { status: 400 }
+ );
+ }
+
+ // Use the first available resource
+ const resource = resources[0];
+
+ const createdJiraIntegration = await upsertCompanyIntegration(client, {
+ id: "jira",
+ active: true,
+ metadata: {
+ credentials: {
+ accessToken: tokens.accessToken,
+ refreshToken: tokens.refreshToken,
+ expiresAt: Date.now() + tokens.expiresIn * 1000,
+ cloudId: resource.id,
+ siteUrl: resource.url
+ }
+ },
+ updatedBy: userId,
+ companyId: companyId
+ });
+
+ const config = getIntegrationConfigById("jira");
+
+ typeof config?.onInstall === "function" &&
+ (await config.onInstall(companyId));
+
+ if (createdJiraIntegration?.data?.metadata) {
+ const requestUrl = new URL(request.url);
+
+ if (!VERCEL_URL || VERCEL_URL.includes("localhost")) {
+ requestUrl.protocol = "http";
+ }
+
+ const redirectUrl = `${requestUrl.origin}${path.to.integrations}`;
+
+ return redirect(redirectUrl);
+ } else {
+ return data(
+ { error: "Failed to save Jira integration" },
+ { status: 500 }
+ );
+ }
+ } catch (err) {
+ console.error("Jira OAuth Error:", err);
+ return data(
+ { error: "Failed to exchange code for token" },
+ { status: 500 }
+ );
+ }
+}
diff --git a/apps/erp/app/routes/api+/webhook.jira.$companyId.ts b/apps/erp/app/routes/api+/webhook.jira.$companyId.ts
new file mode 100644
index 0000000000..ba804214ff
--- /dev/null
+++ b/apps/erp/app/routes/api+/webhook.jira.$companyId.ts
@@ -0,0 +1,71 @@
+import { getCarbonServiceRole } from "@carbon/auth";
+import { syncIssueFromJiraSchema } from "@carbon/jobs/trigger/jira";
+import { tasks } from "@trigger.dev/sdk";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
+import { data } from "react-router";
+import { getIntegration } from "../../modules/settings";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { companyId } = params;
+ if (!companyId) {
+ return data({ success: false }, { status: 400 });
+ }
+
+ return {
+ success: true
+ };
+}
+export async function action({ request, params }: ActionFunctionArgs) {
+ const { companyId } = params;
+
+ if (!companyId) {
+ return data({ success: false }, { status: 400 });
+ }
+
+ const serviceRole = getCarbonServiceRole();
+
+ const integration = await getIntegration(serviceRole, "jira", companyId);
+
+ if (integration.error) {
+ return data(
+ { success: false, error: "Integration query failed" },
+ { status: 400 }
+ );
+ }
+
+ if (!integration.data) {
+ return data(
+ { success: false, error: "Integration not configured" },
+ { status: 400 }
+ );
+ }
+
+ if (!integration.data.active) {
+ return data(
+ { success: false, error: "Integration not active" },
+ { status: 400 }
+ );
+ }
+
+ const body = await request.json();
+
+ const parsed = syncIssueFromJiraSchema.safeParse({
+ companyId,
+ event: body
+ });
+
+ if (!parsed.success) {
+ return data(
+ { success: false, error: parsed.error.format() },
+ { status: 400 }
+ );
+ }
+
+ try {
+ await tasks.trigger("sync-issue-from-jira", parsed.data);
+ return { success: true };
+ } catch (err) {
+ console.error(err);
+ return data({ success: false }, { status: 500 });
+ }
+}
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index e0332a6a2c..c87ea27e96 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -116,6 +116,9 @@ export const path = {
linearCreateIssue: `${api}/integrations/linear/issue/create`,
linearLinkExistingIssue: `${api}/integrations/linear/issue/link`,
linearSyncNotes: `${api}/integrations/linear/issue/sync-notes`,
+ jiraCreateIssue: `${api}/integrations/jira/issue/create`,
+ jiraLinkExistingIssue: `${api}/integrations/jira/issue/link`,
+ jiraSyncNotes: `${api}/integrations/jira/issue/sync-notes`,
outsideOperations: (jobId: string) =>
generatePath(`${api}/production/outside-operations/${jobId}`),
purchasingKpi: (key: string) =>
diff --git a/apps/mes/app/components/JobOperation/JobOperation.tsx b/apps/mes/app/components/JobOperation/JobOperation.tsx
index 0e42e15f8e..a11ba6d68d 100644
--- a/apps/mes/app/components/JobOperation/JobOperation.tsx
+++ b/apps/mes/app/components/JobOperation/JobOperation.tsx
@@ -256,7 +256,7 @@ export const JobOperation = ({
if (operation.setupDuration > 0) operations++;
if (operation.laborDuration > 0) operations++;
if (operation.machineDuration > 0) operations++;
- return 60 + operations * 40;
+ return 60 + operations * 36;
}, [
operation.laborDuration,
operation.machineDuration,
diff --git a/packages/auth/src/config/env.ts b/packages/auth/src/config/env.ts
index e5c8fe8d4e..daf7a8bc27 100644
--- a/packages/auth/src/config/env.ts
+++ b/packages/auth/src/config/env.ts
@@ -8,6 +8,7 @@ declare global {
CLOUDFLARE_TURNSTILE_SITE_KEY: string;
CONTROLLED_ENVIRONMENT: string;
ERP_URL: string;
+ JIRA_CLIENT_ID: string;
MES_URL: string;
ONSHAPE_CLIENT_ID: string;
POSTHOG_API_HOST: string;
@@ -30,6 +31,10 @@ declare global {
CLOUDFLARE_TURNSTILE_SECRET_KEY: string;
DOMAIN: string;
ERP_URL: string;
+ JIRA_CLIENT_ID: string;
+ JIRA_CLIENT_SECRET: string;
+ JIRA_OAUTH_REDIRECT_URL: string;
+ JIRA_STATE_SECRET: string;
MES_URL: string;
NOVU_SECRET_KEY: string;
ONSHAPE_CLIENT_ID: string;
@@ -272,6 +277,21 @@ export const XERO_WEBHOOK_SECRET = getEnv("XERO_WEBHOOK_SECRET", {
isSecret: true
});
+export const JIRA_CLIENT_ID = getEnv("JIRA_CLIENT_ID", {
+ isRequired: false
+});
+export const JIRA_CLIENT_SECRET = getEnv("JIRA_CLIENT_SECRET", {
+ isRequired: false,
+ isSecret: true
+});
+export const JIRA_OAUTH_REDIRECT_URL = getEnv("JIRA_OAUTH_REDIRECT_URL", {
+ isRequired: false
+});
+export const JIRA_STATE_SECRET = getEnv("JIRA_STATE_SECRET", {
+ isRequired: false,
+ isSecret: true
+});
+
/**
* Shared envs
*/
@@ -337,6 +357,7 @@ export function getBrowserEnv() {
CONTROLLED_ENVIRONMENT,
CLOUDFLARE_TURNSTILE_SITE_KEY,
GOOGLE_PLACES_API_KEY,
+ JIRA_CLIENT_ID,
POSTHOG_API_HOST,
POSTHOG_PROJECT_PUBLIC_KEY,
NODE_ENV,
diff --git a/packages/database/src/seed-dev.ts b/packages/database/src/seed-dev.ts
index 33a9b07a38..f68e64f7c4 100644
--- a/packages/database/src/seed-dev.ts
+++ b/packages/database/src/seed-dev.ts
@@ -304,7 +304,7 @@ async function seedDev() {
for (const nct of nonConformanceTypes) {
await client.query(
`INSERT INTO "nonConformanceType" (name, "companyId", "createdBy") VALUES ($1, $2, 'system')`,
- [nct, companyId]
+ [nct.name, companyId]
);
}
@@ -312,7 +312,7 @@ async function seedDev() {
for (const nca of nonConformanceRequiredActions) {
await client.query(
`INSERT INTO "nonConformanceRequiredAction" (name, "companyId", "createdBy") VALUES ($1, $2, 'system')`,
- [nca, companyId]
+ [nca.name, companyId]
);
}
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index c415da4a61..d16c78f09a 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -51891,14 +51891,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"]
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index c415da4a61..d16c78f09a 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -51891,14 +51891,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"]
diff --git a/packages/database/supabase/migrations/20260215000000_add_jira_integration.sql b/packages/database/supabase/migrations/20260215000000_add_jira_integration.sql
new file mode 100644
index 0000000000..9159890a6b
--- /dev/null
+++ b/packages/database/supabase/migrations/20260215000000_add_jira_integration.sql
@@ -0,0 +1,3 @@
+INSERT INTO "integration" ("id", "jsonschema")
+VALUES
+ ('jira', '{"type": "object", "properties": {}}'::json);
diff --git a/packages/ee/package.json b/packages/ee/package.json
index 34094be367..1d26af8a2e 100644
--- a/packages/ee/package.json
+++ b/packages/ee/package.json
@@ -6,9 +6,10 @@
".": "./src/index.ts",
"./accounting": "./src/accounting/index.ts",
"./exchange-rates.server": "./src/exchange-rates/exchange-rates.server.ts",
+ "./jira": "./src/jira/lib/index.ts",
+ "./linear": "./src/linear/lib/index.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 924ac61666..6e34289220 100644
--- a/packages/ee/src/index.ts
+++ b/packages/ee/src/index.ts
@@ -1,4 +1,5 @@
import { ExchangeRates } from "./exchange-rates/config";
+import { Jira } from "./jira/config";
import { Linear } from "./linear/config";
import { Onshape } from "./onshape/config";
import { PaperlessParts } from "./paperless-parts/config";
@@ -27,19 +28,21 @@ export type {
} from "./types";
export const integrations = [
+ // Radan,
ExchangeRates,
- PaperlessParts,
- Onshape,
+ Jira,
Linear,
+ Onshape,
+ PaperlessParts,
QuickBooks,
Resend,
- // Radan,
- Slack,
Sage,
+ Slack,
Xero,
Zapier
];
+export { Jira } from "./jira/config";
export { Logo as OnshapeLogo, Onshape } from "./onshape/config";
// TODO: export as @carbon/ee/paperless
export { PaperlessPartsClient } from "./paperless-parts/lib/client";
diff --git a/packages/ee/src/jira/config.tsx b/packages/ee/src/jira/config.tsx
new file mode 100644
index 0000000000..a477a659bb
--- /dev/null
+++ b/packages/ee/src/jira/config.tsx
@@ -0,0 +1,86 @@
+import { JIRA_CLIENT_ID } from "@carbon/auth";
+import { Copy, Input, InputGroup, InputRightElement } from "@carbon/react";
+import { isBrowser } from "@carbon/utils";
+import type { SVGProps } from "react";
+import { z } from "zod";
+import { defineIntegration } from "../fns";
+import { getJiraClient } from "./lib";
+
+export const Jira = defineIntegration({
+ name: "Jira",
+ id: "jira",
+ active: !!JIRA_CLIENT_ID,
+ category: "Project Management",
+ logo: Logo,
+ description:
+ "Jira is a project management and issue tracking tool by Atlassian. With this integration, you can link quality issues from Carbon to Jira for tracking and collaboration.",
+ shortDescription: "Sync quality issues from Carbon to Jira.",
+ setupInstructions: SetupInstructions,
+ images: [],
+ settings: [],
+ oauth: {
+ authUrl: "https://auth.atlassian.com/authorize",
+ clientId: JIRA_CLIENT_ID!,
+ redirectUri: "/api/integrations/jira/oauth",
+ scopes: [
+ "read:jira-user",
+ "read:jira-work",
+ "write:jira-work",
+ "offline_access"
+ ],
+ tokenUrl: "https://auth.atlassian.com/oauth/token"
+ },
+ onHealthcheck: healthcheck,
+ schema: z.object({})
+});
+
+function SetupInstructions({ companyId }: { companyId: string }) {
+ const webhookUrl = isBrowser
+ ? `${window.location.origin}/api/webhook/jira/${companyId}`
+ : "";
+
+ return (
+ <>
+ <p className="text-sm text-muted-foreground">
+ To integrate Jira with Carbon, click the "Connect" button above to
+ authorize Carbon with your Atlassian account.
+ </p>
+ <p className="text-sm text-muted-foreground">
+ After connecting, you can optionally set up a webhook in Jira to receive
+ real-time updates when issues change. Go to your Jira settings, then
+ System → WebHooks, and create a new webhook with the URL below.
+ </p>
+ <InputGroup className="mb-8">
+ <Input value={webhookUrl} readOnly />
+ <InputRightElement>
+ <Copy text={webhookUrl} />
+ </InputRightElement>
+ </InputGroup>
+ <p className="text-sm text-muted-foreground">
+ Select the following events: Issue updated, Issue deleted.
+ </p>
+ </>
+ );
+}
+
+export function Logo(props: SVGProps<SVGSVGElement>) {
+ return (
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ {...props}
+ width="40"
+ height="40"
+ viewBox="0 0 24 24"
+ fill="currentColor"
+ >
+ <title>atlassian_jira</title>
+ <rect width="24" height="24" fill="none" />
+ <path d="M11.53,2a4.37,4.37,0,0,0,4.35,4.35h1.78v1.7A4.35,4.35,0,0,0,22,12.4V2.84A.85.85,0,0,0,21.16,2H11.53M6.77,6.8a4.36,4.36,0,0,0,4.34,4.34h1.8v1.72a4.36,4.36,0,0,0,4.34,4.34V7.63a.84.84,0,0,0-.83-.83H6.77M2,11.6a4.34,4.34,0,0,0,4.35,4.34H8.13v1.72A4.36,4.36,0,0,0,12.47,22V12.43a.85.85,0,0,0-.84-.84H2Z" />
+ </svg>
+ );
+}
+
+async function healthcheck(companyId: string, _: Record<string, unknown>) {
+ const jira = getJiraClient();
+ return await jira.healthcheck(companyId);
+}
diff --git a/packages/ee/src/jira/lib/client.ts b/packages/ee/src/jira/lib/client.ts
new file mode 100644
index 0000000000..99792727c7
--- /dev/null
+++ b/packages/ee/src/jira/lib/client.ts
@@ -0,0 +1,613 @@
+import {
+ getCarbonServiceRole,
+ JIRA_CLIENT_ID,
+ JIRA_CLIENT_SECRET
+} from "@carbon/auth";
+import { getJiraIntegration, updateJiraCredentials } from "./service";
+import type {
+ CreateJiraIssueInput,
+ JiraAccessibleResource,
+ JiraCredentials,
+ JiraIssue,
+ JiraIssueType,
+ JiraProject,
+ JiraRemoteLink,
+ JiraStatusCategory,
+ JiraTransition,
+ JiraUser,
+ UpdateJiraIssueInput
+} from "./types";
+
+const ATLASSIAN_AUTH_URL = "https://auth.atlassian.com";
+const ATLASSIAN_API_URL = "https://api.atlassian.com";
+
+/**
+ * Exchange authorization code for access and refresh tokens.
+ */
+export async function exchangeCodeForTokens(
+ code: string,
+ redirectUri: string
+): Promise<{
+ accessToken: string;
+ refreshToken: string;
+ expiresIn: number;
+} | null> {
+ try {
+ const response = await fetch(`${ATLASSIAN_AUTH_URL}/oauth/token`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json"
+ },
+ body: JSON.stringify({
+ grant_type: "authorization_code",
+ client_id: JIRA_CLIENT_ID,
+ client_secret: JIRA_CLIENT_SECRET,
+ code,
+ redirect_uri: redirectUri
+ })
+ });
+
+ if (!response.ok) {
+ console.error(
+ "Failed to exchange code for tokens:",
+ response.status,
+ await response.text()
+ );
+ return null;
+ }
+
+ const data = (await response.json()) as {
+ access_token: string;
+ refresh_token: string;
+ expires_in: number;
+ };
+
+ return {
+ accessToken: data.access_token,
+ refreshToken: data.refresh_token,
+ expiresIn: data.expires_in
+ };
+ } catch (e) {
+ console.error("Error exchanging code for tokens:", e);
+ return null;
+ }
+}
+
+/**
+ * Refresh access token using refresh token.
+ */
+export async function refreshAccessToken(refreshToken: string): Promise<{
+ accessToken: string;
+ refreshToken: string;
+ expiresIn: number;
+} | null> {
+ try {
+ const response = await fetch(`${ATLASSIAN_AUTH_URL}/oauth/token`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json"
+ },
+ body: JSON.stringify({
+ grant_type: "refresh_token",
+ client_id: JIRA_CLIENT_ID,
+ client_secret: JIRA_CLIENT_SECRET,
+ refresh_token: refreshToken
+ })
+ });
+
+ if (!response.ok) {
+ console.error(
+ "Failed to refresh token:",
+ response.status,
+ await response.text()
+ );
+ return null;
+ }
+
+ const data = (await response.json()) as {
+ access_token: string;
+ refresh_token: string;
+ expires_in: number;
+ };
+
+ return {
+ accessToken: data.access_token,
+ refreshToken: data.refresh_token,
+ expiresIn: data.expires_in
+ };
+ } catch (e) {
+ console.error("Error refreshing token:", e);
+ return null;
+ }
+}
+
+/**
+ * Get accessible Jira Cloud resources for the authenticated user.
+ * This is called during OAuth to get the cloudId.
+ */
+export async function getAccessibleResources(
+ accessToken: string
+): Promise<JiraAccessibleResource[]> {
+ try {
+ const response = await fetch(
+ `${ATLASSIAN_API_URL}/oauth/token/accessible-resources`,
+ {
+ headers: {
+ Authorization: `Bearer ${accessToken}`,
+ Accept: "application/json"
+ }
+ }
+ );
+
+ if (!response.ok) {
+ console.error(
+ "Failed to get accessible resources:",
+ response.status,
+ await response.text()
+ );
+ return [];
+ }
+
+ return (await response.json()) as JiraAccessibleResource[];
+ } catch (e) {
+ console.error("Error getting accessible resources:", e);
+ return [];
+ }
+}
+
+/**
+ * Jira Cloud REST API client.
+ */
+export class JiraClient {
+ /**
+ * Get authentication headers, refreshing token if needed.
+ */
+ async getAuthHeaders(companyId: string): Promise<Record<string, string>> {
+ const serviceRole = getCarbonServiceRole();
+ const { data } = await getJiraIntegration(serviceRole, companyId);
+ const integration = data?.[0];
+
+ if (!integration) {
+ throw new Error("Jira integration not found for company");
+ }
+
+ const metadata = integration.metadata as { credentials: JiraCredentials };
+ const credentials = metadata.credentials;
+
+ // Check if token needs refresh (5 min buffer)
+ const now = Date.now();
+ if (credentials.expiresAt - now < 5 * 60 * 1000) {
+ const refreshed = await refreshAccessToken(credentials.refreshToken);
+ if (refreshed) {
+ const newCredentials: JiraCredentials = {
+ ...credentials,
+ accessToken: refreshed.accessToken,
+ refreshToken: refreshed.refreshToken,
+ expiresAt: now + refreshed.expiresIn * 1000
+ };
+
+ // Update stored credentials
+ await updateJiraCredentials(serviceRole, companyId, newCredentials);
+
+ return {
+ Authorization: `Bearer ${refreshed.accessToken}`,
+ Accept: "application/json",
+ "Content-Type": "application/json"
+ };
+ }
+ }
+
+ return {
+ Authorization: `Bearer ${credentials.accessToken}`,
+ Accept: "application/json",
+ "Content-Type": "application/json"
+ };
+ }
+
+ /**
+ * Get the cloud ID for API requests.
+ */
+ async getCloudId(companyId: string): Promise<string> {
+ const serviceRole = getCarbonServiceRole();
+ const { data } = await getJiraIntegration(serviceRole, companyId);
+ const integration = data?.[0];
+
+ if (!integration) {
+ throw new Error("Jira integration not found for company");
+ }
+
+ const metadata = integration.metadata as { credentials: JiraCredentials };
+ return metadata.credentials.cloudId;
+ }
+
+ /**
+ * Get the site URL for linking.
+ */
+ async getSiteUrl(companyId: string): Promise<string> {
+ const serviceRole = getCarbonServiceRole();
+ const { data } = await getJiraIntegration(serviceRole, companyId);
+ const integration = data?.[0];
+
+ if (!integration) {
+ throw new Error("Jira integration not found for company");
+ }
+
+ const metadata = integration.metadata as { credentials: JiraCredentials };
+ return metadata.credentials.siteUrl;
+ }
+
+ /**
+ * Make an API request to Jira Cloud.
+ */
+ async request<T>(
+ companyId: string,
+ path: string,
+ options?: RequestInit
+ ): Promise<T> {
+ const headers = await this.getAuthHeaders(companyId);
+ const cloudId = await this.getCloudId(companyId);
+
+ const response = await fetch(
+ `${ATLASSIAN_API_URL}/ex/jira/${cloudId}/rest/api/3${path}`,
+ {
+ ...options,
+ headers: {
+ ...headers,
+ ...(options?.headers || {})
+ }
+ }
+ );
+
+ if (!response.ok) {
+ const errorText = await response.text();
+ console.error(`Jira API error (${path}):`, response.status, errorText);
+ throw new Error(`Jira API error: ${response.status}`);
+ }
+
+ // Handle 204 No Content
+ if (response.status === 204) {
+ return {} as T;
+ }
+
+ return response.json();
+ }
+
+ /**
+ * Health check - verify the integration is working.
+ */
+ async healthcheck(companyId: string): Promise<boolean> {
+ try {
+ await this.request(companyId, "/myself");
+ return true;
+ } catch {
+ return false;
+ }
+ }
+
+ /**
+ * List all projects accessible to the user.
+ */
+ async listProjects(companyId: string): Promise<JiraProject[]> {
+ try {
+ const response = await this.request<{ values: JiraProject[] }>(
+ companyId,
+ "/project/search?maxResults=50"
+ );
+ return response.values || [];
+ } catch (e) {
+ console.error("Error listing Jira projects:", e);
+ return [];
+ }
+ }
+
+ /**
+ * Get issue types for a project.
+ */
+ async getIssueTypes(
+ companyId: string,
+ projectKey: string
+ ): Promise<JiraIssueType[]> {
+ try {
+ const response = await this.request<{ issueTypes: JiraIssueType[] }>(
+ companyId,
+ `/project/${projectKey}`
+ );
+ return (response.issueTypes || []).filter((t) => !t.subtask);
+ } catch (e) {
+ console.error("Error getting Jira issue types:", e);
+ return [];
+ }
+ }
+
+ /**
+ * Get users assignable to a project.
+ */
+ async listProjectUsers(
+ companyId: string,
+ projectKey: string
+ ): Promise<JiraUser[]> {
+ try {
+ return await this.request<JiraUser[]>(
+ companyId,
+ `/user/assignable/search?project=${projectKey}&maxResults=50`
+ );
+ } catch (e) {
+ console.error("Error listing Jira project users:", e);
+ return [];
+ }
+ }
+
+ /**
+ * Search for issues using JQL.
+ */
+ async searchIssues(companyId: string, query: string): Promise<JiraIssue[]> {
+ try {
+ // Escape special characters in query for JQL text search
+ const escapedQuery = query.replace(/['"\\]/g, "\\$&");
+ const jql = `text ~ "${escapedQuery}" ORDER BY updated DESC`;
+
+ const response = await this.request<{ issues: JiraIssue[] }>(
+ companyId,
+ `/search/jql?jql=${encodeURIComponent(
+ jql
+ )}&maxResults=10&fields=summary,description,status,assignee,duedate,issuetype,project,priority`
+ );
+ return response.issues || [];
+ } catch (e) {
+ console.error("Error searching Jira issues:", e);
+ return [];
+ }
+ }
+
+ /**
+ * Get a single issue by ID or key.
+ */
+ async getIssue(
+ companyId: string,
+ issueIdOrKey: string
+ ): Promise<JiraIssue | null> {
+ try {
+ return await this.request<JiraIssue>(
+ companyId,
+ `/issue/${issueIdOrKey}?fields=summary,description,status,assignee,duedate,issuetype,project,priority`
+ );
+ } catch (e) {
+ console.error("Error getting Jira issue:", e);
+ return null;
+ }
+ }
+
+ /**
+ * Create a new issue.
+ */
+ async createIssue(
+ companyId: string,
+ input: CreateJiraIssueInput
+ ): Promise<JiraIssue | null> {
+ try {
+ const fields: Record<string, any> = {
+ project: { key: input.projectKey },
+ issuetype: { id: input.issueTypeId },
+ summary: input.summary
+ };
+
+ if (input.description) {
+ fields.description = input.description;
+ }
+
+ if (input.assigneeId) {
+ fields.assignee = { accountId: input.assigneeId };
+ }
+
+ if (input.priority) {
+ fields.priority = { name: input.priority };
+ }
+
+ const response = await this.request<{ id: string; key: string }>(
+ companyId,
+ "/issue",
+ {
+ method: "POST",
+ body: JSON.stringify({ fields })
+ }
+ );
+
+ // Fetch the full issue details
+ return this.getIssue(companyId, response.key);
+ } catch (e) {
+ console.error("Error creating Jira issue:", e);
+ return null;
+ }
+ }
+
+ /**
+ * Update an existing issue.
+ */
+ async updateIssue(
+ companyId: string,
+ issueId: string,
+ input: UpdateJiraIssueInput
+ ): Promise<void> {
+ try {
+ const fields: Record<string, any> = {};
+
+ if (input.summary !== undefined) {
+ fields.summary = input.summary;
+ }
+
+ if (input.description !== undefined) {
+ fields.description = input.description;
+ }
+
+ if (input.assigneeId !== undefined) {
+ fields.assignee = input.assigneeId
+ ? { accountId: input.assigneeId }
+ : null;
+ }
+
+ if (input.priority !== undefined) {
+ fields.priority = { name: input.priority };
+ }
+
+ await this.request(companyId, `/issue/${issueId}`, {
+ method: "PUT",
+ body: JSON.stringify({ fields })
+ });
+ } catch (e) {
+ console.error("Error updating Jira issue:", e);
+ }
+ }
+
+ /**
+ * Get available transitions for an issue.
+ */
+ async getTransitions(
+ companyId: string,
+ issueId: string
+ ): Promise<JiraTransition[]> {
+ try {
+ const response = await this.request<{ transitions: JiraTransition[] }>(
+ companyId,
+ `/issue/${issueId}/transitions`
+ );
+ return response.transitions || [];
+ } catch (e) {
+ console.error("Error getting Jira transitions:", e);
+ return [];
+ }
+ }
+
+ /**
+ * Transition an issue to a status matching the target category.
+ */
+ async transitionIssue(
+ companyId: string,
+ issueId: string,
+ targetCategory: JiraStatusCategory
+ ): Promise<boolean> {
+ try {
+ const transitions = await this.getTransitions(companyId, issueId);
+
+ // Find a transition that leads to the target status category
+ const transition = transitions.find(
+ (t) => t.to.statusCategory.key === targetCategory
+ );
+
+ if (!transition) {
+ console.warn(
+ `No transition found to ${targetCategory} for issue ${issueId}`
+ );
+ return false;
+ }
+
+ await this.request(companyId, `/issue/${issueId}/transitions`, {
+ method: "POST",
+ body: JSON.stringify({ transition: { id: transition.id } })
+ });
+
+ return true;
+ } catch (e) {
+ console.error("Error transitioning Jira issue:", e);
+ return false;
+ }
+ }
+
+ /**
+ * Create a remote link (backlink to Carbon).
+ */
+ async createRemoteLink(
+ companyId: string,
+ issueId: string,
+ url: string,
+ title: string
+ ): Promise<JiraRemoteLink | null> {
+ try {
+ return await this.request<JiraRemoteLink>(
+ companyId,
+ `/issue/${issueId}/remotelink`,
+ {
+ method: "POST",
+ body: JSON.stringify({
+ globalId: `carbon-${url}`,
+ application: {
+ type: "com.carbon.ms",
+ name: "Carbon"
+ },
+ object: {
+ url,
+ title
+ }
+ })
+ }
+ );
+ } catch (e) {
+ console.error("Error creating Jira remote link:", e);
+ return null;
+ }
+ }
+
+ /**
+ * Get remote links for an issue.
+ */
+ async getRemoteLinks(
+ companyId: string,
+ issueId: string
+ ): Promise<JiraRemoteLink[]> {
+ try {
+ return await this.request<JiraRemoteLink[]>(
+ companyId,
+ `/issue/${issueId}/remotelink`
+ );
+ } catch (e) {
+ console.error("Error getting Jira remote links:", e);
+ return [];
+ }
+ }
+
+ /**
+ * Delete a remote link by global ID.
+ */
+ async deleteRemoteLink(
+ companyId: string,
+ issueId: string,
+ globalId: string
+ ): Promise<boolean> {
+ try {
+ await this.request(
+ companyId,
+ `/issue/${issueId}/remotelink?globalId=${encodeURIComponent(globalId)}`,
+ { method: "DELETE" }
+ );
+ return true;
+ } catch (e) {
+ console.error("Error deleting Jira remote link:", e);
+ return false;
+ }
+ }
+
+ /**
+ * Find users by email.
+ */
+ async findUserByEmail(
+ companyId: string,
+ email: string
+ ): Promise<JiraUser | null> {
+ try {
+ const users = await this.request<JiraUser[]>(
+ companyId,
+ `/user/search?query=${encodeURIComponent(email)}&maxResults=1`
+ );
+ return users.length > 0 ? users[0] : null;
+ } catch (e) {
+ console.error("Error finding Jira user:", e);
+ return null;
+ }
+ }
+}
+
+let instance: JiraClient | null = null;
+
+export const getJiraClient = () => {
+ if (!instance) instance = new JiraClient();
+ return instance;
+};
diff --git a/packages/ee/src/jira/lib/index.ts b/packages/ee/src/jira/lib/index.ts
new file mode 100644
index 0000000000..fe4bbfd4b1
--- /dev/null
+++ b/packages/ee/src/jira/lib/index.ts
@@ -0,0 +1,5 @@
+export * from "./client";
+export * from "./richtext";
+export * from "./service";
+export * from "./types";
+export * from "./utils";
diff --git a/packages/ee/src/jira/lib/richtext.ts b/packages/ee/src/jira/lib/richtext.ts
new file mode 100644
index 0000000000..a0a437193a
--- /dev/null
+++ b/packages/ee/src/jira/lib/richtext.ts
@@ -0,0 +1,344 @@
+/**
+ * Utilities for bidirectional conversion between Atlassian Document Format (ADF)
+ * and Tiptap JSON (Carbon's rich text format).
+ *
+ * Jira Cloud uses ADF for rich text fields like description.
+ * Carbon uses Tiptap/ProseMirror JSON for rich text editing.
+ *
+ * ADF documentation: https://developer.atlassian.com/cloud/jira/platform/apis/document/structure/
+ */
+
+// 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[];
+};
+
+// ADF (Atlassian Document Format) types
+export type ADFNode = {
+ type: string;
+ attrs?: Record<string, any>;
+ content?: ADFNode[];
+ text?: string;
+ marks?: { type: string; attrs?: Record<string, any> }[];
+};
+
+export type ADFDocument = {
+ version: 1;
+ type: "doc";
+ content: ADFNode[];
+};
+
+/**
+ * Convert ADF (Atlassian Document Format) to Tiptap JSON.
+ * Used when syncing from Jira → Carbon.
+ */
+export function adfToTiptap(adf: ADFDocument | null | undefined): TiptapDocument {
+ if (!adf || !adf.content || adf.content.length === 0) {
+ return { type: "doc", content: [{ type: "paragraph" }] };
+ }
+
+ const content = adf.content.map(convertADFNodeToTiptap).filter(Boolean) as TiptapNode[];
+
+ if (content.length === 0) {
+ return { type: "doc", content: [{ type: "paragraph" }] };
+ }
+
+ return { type: "doc", content };
+}
+
+function convertADFNodeToTiptap(node: ADFNode): TiptapNode | null {
+ switch (node.type) {
+ case "paragraph":
+ return {
+ type: "paragraph",
+ content: node.content?.map(convertADFNodeToTiptap).filter(Boolean) as TiptapNode[] || []
+ };
+
+ case "heading":
+ return {
+ type: "heading",
+ attrs: { level: node.attrs?.level ?? 1 },
+ content: node.content?.map(convertADFNodeToTiptap).filter(Boolean) as TiptapNode[] || []
+ };
+
+ case "bulletList":
+ return {
+ type: "bulletList",
+ content: node.content?.map(convertADFNodeToTiptap).filter(Boolean) as TiptapNode[] || []
+ };
+
+ case "orderedList":
+ return {
+ type: "orderedList",
+ content: node.content?.map(convertADFNodeToTiptap).filter(Boolean) as TiptapNode[] || []
+ };
+
+ case "listItem":
+ return {
+ type: "listItem",
+ content: node.content?.map(convertADFNodeToTiptap).filter(Boolean) as TiptapNode[] || []
+ };
+
+ case "blockquote":
+ return {
+ type: "blockquote",
+ content: node.content?.map(convertADFNodeToTiptap).filter(Boolean) as TiptapNode[] || []
+ };
+
+ case "codeBlock":
+ return {
+ type: "codeBlock",
+ attrs: node.attrs?.language ? { language: node.attrs.language } : undefined,
+ content: node.content?.map(convertADFNodeToTiptap).filter(Boolean) as TiptapNode[] || []
+ };
+
+ case "rule":
+ return { type: "horizontalRule" };
+
+ case "hardBreak":
+ return { type: "hardBreak" };
+
+ case "text":
+ return {
+ type: "text",
+ text: node.text ?? "",
+ marks: node.marks?.map(convertADFMarkToTiptap).filter(Boolean) as TiptapNode["marks"]
+ };
+
+ case "mention":
+ // Convert Jira mentions to plain text
+ return {
+ type: "text",
+ text: node.attrs?.text || "@mention"
+ };
+
+ case "emoji":
+ return {
+ type: "text",
+ text: node.attrs?.shortName || node.attrs?.text || ""
+ };
+
+ case "inlineCard":
+ case "blockCard":
+ // Convert Jira cards to links
+ return {
+ type: "text",
+ text: node.attrs?.url || "",
+ marks: node.attrs?.url
+ ? [{ type: "link", attrs: { href: node.attrs.url } }]
+ : undefined
+ };
+
+ case "mediaGroup":
+ case "mediaSingle":
+ // Skip media for now - could be enhanced to handle attachments
+ return null;
+
+ case "table":
+ case "tableRow":
+ case "tableCell":
+ case "tableHeader":
+ // Tables are complex - skip for now
+ return null;
+
+ default:
+ // For unknown types, try to extract text content
+ if (node.content) {
+ return {
+ type: "paragraph",
+ content: node.content.map(convertADFNodeToTiptap).filter(Boolean) as TiptapNode[]
+ };
+ }
+ return null;
+ }
+}
+
+function convertADFMarkToTiptap(
+ mark: NonNullable<ADFNode["marks"]>[number]
+): NonNullable<TiptapNode["marks"]>[number] | null {
+ switch (mark.type) {
+ case "strong":
+ return { type: "bold" };
+ case "em":
+ return { type: "italic" };
+ case "strike":
+ return { type: "strike" };
+ case "code":
+ return { type: "code" };
+ case "link":
+ return { type: "link", attrs: { href: mark.attrs?.href } };
+ case "underline":
+ return { type: "underline" };
+ case "textColor":
+ return { type: "textStyle", attrs: { color: mark.attrs?.color } };
+ case "subsup":
+ // Subscript/superscript - map to appropriate type or skip
+ return null;
+ default:
+ return null;
+ }
+}
+
+/**
+ * Convert Tiptap JSON to ADF (Atlassian Document Format).
+ * Used when syncing from Carbon → Jira.
+ */
+export function tiptapToAdf(tiptapDoc: TiptapDocument | null | undefined): ADFDocument {
+ if (!tiptapDoc || !tiptapDoc.content || tiptapDoc.content.length === 0) {
+ return {
+ version: 1,
+ type: "doc",
+ content: [{ type: "paragraph", content: [] }]
+ };
+ }
+
+ const content = tiptapDoc.content.map(convertTiptapNodeToADF).filter(Boolean) as ADFNode[];
+
+ if (content.length === 0) {
+ return {
+ version: 1,
+ type: "doc",
+ content: [{ type: "paragraph", content: [] }]
+ };
+ }
+
+ return { version: 1, type: "doc", content };
+}
+
+function convertTiptapNodeToADF(node: TiptapNode): ADFNode | null {
+ switch (node.type) {
+ case "paragraph":
+ return {
+ type: "paragraph",
+ content: node.content?.map(convertTiptapNodeToADF).filter(Boolean) as ADFNode[] || []
+ };
+
+ case "heading":
+ return {
+ type: "heading",
+ attrs: { level: node.attrs?.level ?? 1 },
+ content: node.content?.map(convertTiptapNodeToADF).filter(Boolean) as ADFNode[] || []
+ };
+
+ case "bulletList":
+ return {
+ type: "bulletList",
+ content: node.content?.map(convertTiptapNodeToADF).filter(Boolean) as ADFNode[] || []
+ };
+
+ case "orderedList":
+ return {
+ type: "orderedList",
+ content: node.content?.map(convertTiptapNodeToADF).filter(Boolean) as ADFNode[] || []
+ };
+
+ case "listItem":
+ return {
+ type: "listItem",
+ content: node.content?.map(convertTiptapNodeToADF).filter(Boolean) as ADFNode[] || []
+ };
+
+ case "blockquote":
+ return {
+ type: "blockquote",
+ content: node.content?.map(convertTiptapNodeToADF).filter(Boolean) as ADFNode[] || []
+ };
+
+ case "codeBlock":
+ return {
+ type: "codeBlock",
+ attrs: node.attrs?.language ? { language: node.attrs.language } : {},
+ content: node.content?.map(convertTiptapNodeToADF).filter(Boolean) as ADFNode[] || []
+ };
+
+ case "horizontalRule":
+ return { type: "rule" };
+
+ case "hardBreak":
+ return { type: "hardBreak" };
+
+ case "text":
+ return {
+ type: "text",
+ text: node.text ?? "",
+ marks: node.marks?.map(convertTiptapMarkToADF).filter(Boolean) as ADFNode["marks"]
+ };
+
+ default:
+ // For unknown types, try to extract text content
+ if (node.content) {
+ return {
+ type: "paragraph",
+ content: node.content.map(convertTiptapNodeToADF).filter(Boolean) as ADFNode[]
+ };
+ }
+ return null;
+ }
+}
+
+function convertTiptapMarkToADF(
+ mark: NonNullable<TiptapNode["marks"]>[number]
+): NonNullable<ADFNode["marks"]>[number] | null {
+ switch (mark.type) {
+ case "bold":
+ return { type: "strong" };
+ case "italic":
+ return { type: "em" };
+ case "strike":
+ return { type: "strike" };
+ case "code":
+ return { type: "code" };
+ case "link":
+ return { type: "link", attrs: { href: mark.attrs?.href } };
+ case "underline":
+ return { type: "underline" };
+ case "textStyle":
+ if (mark.attrs?.color) {
+ return { type: "textColor", attrs: { color: mark.attrs.color } };
+ }
+ return null;
+ default:
+ return null;
+ }
+}
+
+/**
+ * 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/jira/lib/service.ts b/packages/ee/src/jira/lib/service.ts
new file mode 100644
index 0000000000..8d5e5655d3
--- /dev/null
+++ b/packages/ee/src/jira/lib/service.ts
@@ -0,0 +1,234 @@
+import { getCarbonServiceRole } from "@carbon/auth";
+import type { Database } from "@carbon/database";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import { adfToTiptap } from "./richtext";
+import type { JiraCredentials, JiraIssue, JiraIssueMapping } from "./types";
+import { JiraIssueMappingSchema } from "./types";
+import { mapJiraStatusToCarbonStatus } from "./utils";
+
+/**
+ * Get the Jira integration for a company.
+ */
+export async function getJiraIntegration(
+ client: SupabaseClient<Database>,
+ companyId: string
+) {
+ return await client
+ .from("companyIntegration")
+ .select("*")
+ .eq("companyId", companyId)
+ .eq("id", "jira")
+ .limit(1);
+}
+
+/**
+ * Update Jira credentials in the integration metadata.
+ */
+export async function updateJiraCredentials(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ credentials: JiraCredentials
+) {
+ const { data: current } = await getJiraIntegration(client, companyId);
+ const integration = current?.[0];
+
+ if (!integration) {
+ throw new Error("Jira integration not found");
+ }
+
+ const metadata = integration.metadata as Record<string, any>;
+
+ return await client
+ .from("companyIntegration")
+ .update({
+ metadata: {
+ ...metadata,
+ credentials
+ }
+ })
+ .eq("companyId", companyId)
+ .eq("id", "jira");
+}
+
+/**
+ * Convert a Jira issue to the mapping format for storage.
+ */
+export function issueToMapping(
+ issue: JiraIssue,
+ siteUrl: string
+): JiraIssueMapping {
+ return {
+ id: issue.id,
+ key: issue.key,
+ summary: issue.fields.summary,
+ url: `${siteUrl}/browse/${issue.key}`,
+ status: {
+ name: issue.fields.status.name,
+ category: issue.fields.status.statusCategory.key
+ },
+ assignee: issue.fields.assignee
+ ? {
+ emailAddress: issue.fields.assignee.emailAddress,
+ displayName: issue.fields.assignee.displayName
+ }
+ : null
+ };
+}
+
+/**
+ * Link an action task to a Jira issue.
+ */
+export async function linkActionToJiraIssue(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ input: {
+ actionId: string;
+ issue: JiraIssue;
+ siteUrl: string;
+ assignee?: string | null;
+ syncNotes?: boolean;
+ }
+) {
+ const mapping = issueToMapping(input.issue, input.siteUrl);
+
+ // Convert Jira description (ADF) to Tiptap format for notes
+ let notes: any = undefined;
+ if (input.syncNotes && input.issue.fields.description) {
+ try {
+ notes = adfToTiptap(input.issue.fields.description);
+ } catch (e) {
+ console.error("Failed to convert Jira description to Tiptap:", e);
+ }
+ }
+
+ const updateData: Record<string, any> = {
+ assignee: input.assignee,
+ status: mapJiraStatusToCarbonStatus(
+ input.issue.fields.status.statusCategory.key
+ ),
+ dueDate: input.issue.fields.duedate
+ };
+
+ // Only update notes if we successfully converted the description
+ if (notes !== undefined) {
+ updateData.notes = notes;
+ }
+
+ // Update the task fields
+ const result = await client
+ .from("nonConformanceActionTask")
+ .update(updateData)
+ .eq("companyId", companyId)
+ .eq("id", input.actionId)
+ .select("nonConformanceId");
+
+ // Delete any existing Jira mapping for this action
+ await client
+ .from("externalIntegrationMapping")
+ .delete()
+ .eq("entityType", "nonConformanceActionTask")
+ .eq("entityId", input.actionId)
+ .eq("integration", "jira");
+
+ // Create the new mapping
+ await client.from("externalIntegrationMapping").insert({
+ entityType: "nonConformanceActionTask",
+ entityId: input.actionId,
+ integration: "jira",
+ externalId: input.issue.id,
+ metadata: mapping as any,
+ companyId
+ });
+
+ return result;
+}
+
+/**
+ * Unlink an action task from a Jira issue.
+ */
+export async function unlinkActionFromJiraIssue(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ input: {
+ actionId: string;
+ assignee?: string | null;
+ }
+) {
+ // Delete the Jira mapping using service role to bypass RLS
+ const serviceRole = getCarbonServiceRole();
+ await serviceRole
+ .from("externalIntegrationMapping")
+ .delete()
+ .eq("entityType", "nonConformanceActionTask")
+ .eq("entityId", input.actionId)
+ .eq("integration", "jira");
+
+ // Return the nonConformanceId for the action task
+ return client
+ .from("nonConformanceActionTask")
+ .select("nonConformanceId")
+ .eq("companyId", companyId)
+ .eq("id", input.actionId);
+}
+
+/**
+ * Get Jira issue metadata from the external integration mapping.
+ */
+export const getJiraIssueFromExternalId = async (
+ client: SupabaseClient<Database>,
+ companyId: string,
+ actionId: string
+): Promise<JiraIssueMapping | null> => {
+ const { data: mapping } = await client
+ .from("externalIntegrationMapping")
+ .select("metadata")
+ .eq("entityType", "nonConformanceActionTask")
+ .eq("entityId", actionId)
+ .eq("integration", "jira")
+ .eq("companyId", companyId)
+ .maybeSingle();
+
+ if (!mapping) return null;
+
+ const { data } = JiraIssueMappingSchema.safeParse(mapping.metadata);
+
+ if (!data) return null;
+
+ return data;
+};
+
+/**
+ * Get employees that match email addresses.
+ */
+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 ?? [];
+};
+
+/**
+ * Update the cached Jira issue metadata in the mapping.
+ */
+export async function updateJiraIssueMapping(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ actionId: string,
+ mapping: JiraIssueMapping
+) {
+ return await client
+ .from("externalIntegrationMapping")
+ .update({ metadata: mapping as any })
+ .eq("entityType", "nonConformanceActionTask")
+ .eq("entityId", actionId)
+ .eq("integration", "jira")
+ .eq("companyId", companyId);
+}
diff --git a/packages/ee/src/jira/lib/types.ts b/packages/ee/src/jira/lib/types.ts
new file mode 100644
index 0000000000..ac09652a33
--- /dev/null
+++ b/packages/ee/src/jira/lib/types.ts
@@ -0,0 +1,233 @@
+import { z } from "zod";
+
+/**
+ * Jira status category - used for status mapping
+ * Jira organizes statuses into these three categories
+ */
+export type JiraStatusCategory = "new" | "indeterminate" | "done";
+
+/**
+ * Jira issue status
+ */
+export const JiraStatusSchema = z.object({
+ id: z.string(),
+ name: z.string(),
+ statusCategory: z.object({
+ id: z.number(),
+ key: z.enum(["new", "indeterminate", "done"]),
+ name: z.string()
+ })
+});
+
+export type JiraStatus = z.infer<typeof JiraStatusSchema>;
+
+/**
+ * Jira user (assignee)
+ */
+export const JiraUserSchema = z.object({
+ accountId: z.string(),
+ emailAddress: z.string().optional(),
+ displayName: z.string(),
+ avatarUrls: z
+ .object({
+ "48x48": z.string().optional()
+ })
+ .optional()
+});
+
+export type JiraUser = z.infer<typeof JiraUserSchema>;
+
+/**
+ * Jira issue - the main entity we work with
+ */
+export const JiraIssueSchema = z.object({
+ id: z.string(),
+ key: z.string(),
+ self: z.string().optional(),
+ fields: z.object({
+ summary: z.string(),
+ description: z.any().nullable(), // ADF format
+ status: JiraStatusSchema,
+ assignee: JiraUserSchema.nullable(),
+ duedate: z.string().nullable().optional(),
+ issuetype: z
+ .object({
+ id: z.string(),
+ name: z.string(),
+ iconUrl: z.string().optional()
+ })
+ .optional(),
+ project: z
+ .object({
+ id: z.string(),
+ key: z.string(),
+ name: z.string()
+ })
+ .optional(),
+ priority: z
+ .object({
+ id: z.string(),
+ name: z.string()
+ })
+ .optional()
+ })
+});
+
+export type JiraIssue = z.infer<typeof JiraIssueSchema>;
+
+/**
+ * Simplified Jira issue for external mapping storage
+ */
+export const JiraIssueMappingSchema = z.object({
+ id: z.string(),
+ key: z.string(),
+ summary: z.string(),
+ url: z.string(),
+ status: z.object({
+ name: z.string(),
+ category: z.enum(["new", "indeterminate", "done"])
+ }),
+ assignee: z
+ .object({
+ emailAddress: z.string().optional(),
+ displayName: z.string()
+ })
+ .nullable()
+});
+
+export type JiraIssueMapping = z.infer<typeof JiraIssueMappingSchema>;
+
+/**
+ * Jira project
+ */
+export const JiraProjectSchema = z.object({
+ id: z.string(),
+ key: z.string(),
+ name: z.string(),
+ avatarUrls: z
+ .object({
+ "48x48": z.string().optional()
+ })
+ .optional()
+});
+
+export type JiraProject = z.infer<typeof JiraProjectSchema>;
+
+/**
+ * Jira issue type (Task, Bug, Story, etc.)
+ */
+export const JiraIssueTypeSchema = z.object({
+ id: z.string(),
+ name: z.string(),
+ description: z.string().optional(),
+ iconUrl: z.string().optional(),
+ subtask: z.boolean()
+});
+
+export type JiraIssueType = z.infer<typeof JiraIssueTypeSchema>;
+
+/**
+ * Jira transition (for changing issue status)
+ */
+export const JiraTransitionSchema = z.object({
+ id: z.string(),
+ name: z.string(),
+ to: JiraStatusSchema
+});
+
+export type JiraTransition = z.infer<typeof JiraTransitionSchema>;
+
+/**
+ * Jira OAuth credentials stored in companyIntegration.metadata
+ */
+export interface JiraCredentials {
+ accessToken: string;
+ refreshToken: string;
+ expiresAt: number;
+ cloudId: string;
+ siteUrl: string;
+}
+
+/**
+ * Jira accessible resource (returned from OAuth flow)
+ */
+export const JiraAccessibleResourceSchema = z.object({
+ id: z.string(),
+ url: z.string(),
+ name: z.string(),
+ scopes: z.array(z.string()),
+ avatarUrl: z.string().optional()
+});
+
+export type JiraAccessibleResource = z.infer<
+ typeof JiraAccessibleResourceSchema
+>;
+
+/**
+ * Jira remote link (for backlinks from Jira to Carbon)
+ */
+export const JiraRemoteLinkSchema = z.object({
+ id: z.number(),
+ self: z.string(),
+ globalId: z.string(),
+ application: z.object({
+ type: z.string().optional(),
+ name: z.string().optional()
+ }),
+ object: z.object({
+ url: z.string(),
+ title: z.string()
+ })
+});
+
+export type JiraRemoteLink = z.infer<typeof JiraRemoteLinkSchema>;
+
+/**
+ * Jira webhook event payload
+ */
+export const JiraWebhookEventSchema = z.object({
+ timestamp: z.number(),
+ webhookEvent: z.string(),
+ issue: JiraIssueSchema.optional(),
+ changelog: z
+ .object({
+ id: z.string(),
+ items: z.array(
+ z.object({
+ field: z.string(),
+ fieldtype: z.string(),
+ fieldId: z.string().optional(),
+ from: z.string().nullable(),
+ fromString: z.string().nullable(),
+ to: z.string().nullable(),
+ toString: z.string().nullable()
+ })
+ )
+ })
+ .optional(),
+ user: JiraUserSchema.optional()
+});
+
+export type JiraWebhookEvent = z.infer<typeof JiraWebhookEventSchema>;
+
+/**
+ * Input for creating a Jira issue
+ */
+export interface CreateJiraIssueInput {
+ projectKey: string;
+ issueTypeId: string;
+ summary: string;
+ description?: any; // ADF format
+ assigneeId?: string;
+ priority?: string;
+}
+
+/**
+ * Input for updating a Jira issue
+ */
+export interface UpdateJiraIssueInput {
+ summary?: string;
+ description?: any; // ADF format
+ assigneeId?: string | null;
+ priority?: string;
+}
diff --git a/packages/ee/src/jira/lib/utils.ts b/packages/ee/src/jira/lib/utils.ts
new file mode 100644
index 0000000000..a2c55b4943
--- /dev/null
+++ b/packages/ee/src/jira/lib/utils.ts
@@ -0,0 +1,50 @@
+import type { Database } from "@carbon/database";
+import type { JiraStatusCategory } from "./types";
+
+type CarbonTaskStatus = Database["public"]["Enums"]["nonConformanceTaskStatus"];
+
+/**
+ * Maps Jira status category to Carbon task status.
+ *
+ * Jira organizes all statuses into three categories:
+ * - "new" (To Do, Backlog, Open, etc.) → Pending
+ * - "indeterminate" (In Progress, In Review, etc.) → In Progress
+ * - "done" (Done, Closed, Resolved, etc.) → Completed
+ */
+export const mapJiraStatusToCarbonStatus = (
+ statusCategory: JiraStatusCategory
+): CarbonTaskStatus => {
+ switch (statusCategory) {
+ case "new":
+ return "Pending";
+ case "indeterminate":
+ return "In Progress";
+ case "done":
+ return "Completed";
+ default:
+ return "Pending";
+ }
+};
+
+/**
+ * Maps Carbon task status to target Jira status category.
+ *
+ * Note: Jira uses transitions to change status, not direct status updates.
+ * The caller must find an available transition that leads to a status
+ * in the target category.
+ */
+export const mapCarbonStatusToJiraCategory = (
+ status: CarbonTaskStatus
+): JiraStatusCategory => {
+ switch (status) {
+ case "Pending":
+ return "new";
+ case "In Progress":
+ return "indeterminate";
+ case "Completed":
+ case "Skipped":
+ return "done";
+ 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 a880108216..9daa992b43 100644
--- a/packages/ee/src/notifications/index.ts
+++ b/packages/ee/src/notifications/index.ts
@@ -1,11 +1,14 @@
import { notificationRegistry } from "./registry";
+import { JiraNotificationService } from "./services/jira";
import { LinearNotificationService } from "./services/linear";
import { SlackNotificationService } from "./services/slack";
notificationRegistry.register(new SlackNotificationService());
notificationRegistry.register(new LinearNotificationService());
+notificationRegistry.register(new JiraNotificationService());
export * from "./pipeline";
export * from "./registry";
export * from "./types";
+export { JiraNotificationService };
export { SlackNotificationService };
diff --git a/packages/ee/src/notifications/services/jira.ts b/packages/ee/src/notifications/services/jira.ts
new file mode 100644
index 0000000000..ca14395716
--- /dev/null
+++ b/packages/ee/src/notifications/services/jira.ts
@@ -0,0 +1,107 @@
+import { getUser } from "@carbon/auth";
+import type { Database } from "@carbon/database";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import type { TiptapDocument } from "../../jira/lib/richtext";
+import {
+ getJiraClient,
+ getJiraIssueFromExternalId,
+ mapCarbonStatusToJiraCategory,
+ tiptapToAdf
+} from "../../jira/lib";
+import type { NotificationEvent, NotificationService } from "../types";
+
+const jira = getJiraClient();
+
+/**
+ * Jira Notification Service
+ * Updates Jira issues based on Carbon notification events
+ */
+export class JiraNotificationService implements NotificationService {
+ id = "jira";
+ name = "Jira";
+
+ 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 getJiraIssueFromExternalId(
+ context.serviceRole,
+ event.companyId,
+ event.data.id
+ );
+
+ if (!issue) return;
+
+ const targetCategory = mapCarbonStatusToJiraCategory(event.data.status);
+
+ await jira.transitionIssue(event.companyId, issue.id, targetCategory);
+
+ break;
+ }
+
+ case "task.assigned": {
+ if (event.data.table !== "nonConformanceActionTask") return;
+
+ const issue = await getJiraIssueFromExternalId(
+ context.serviceRole,
+ event.companyId,
+ event.data.id
+ );
+
+ if (!issue) return; // No linked Jira issue
+
+ const { data: user } = await getUser(
+ context.serviceRole,
+ event.data.assignee
+ );
+
+ if (!user) return; // No assignee user
+
+ // Find the Jira user by email
+ const jiraUser = await jira.findUserByEmail(
+ event.companyId,
+ user.email
+ );
+
+ if (!jiraUser) return;
+
+ await jira.updateIssue(event.companyId, issue.id, {
+ assigneeId: jiraUser.accountId
+ });
+ break;
+ }
+
+ case "task.notes.changed": {
+ if (event.data.table !== "nonConformanceActionTask") return;
+
+ const issue = await getJiraIssueFromExternalId(
+ context.serviceRole,
+ event.companyId,
+ event.data.id
+ );
+
+ if (!issue) return; // No linked Jira issue
+
+ // Convert Tiptap notes to ADF for Jira
+ const notes = event.data.notes as TiptapDocument | null | undefined;
+ if (!notes) return;
+
+ try {
+ const description = tiptapToAdf(notes);
+
+ await jira.updateIssue(event.companyId, issue.id, {
+ description
+ });
+ } catch (e) {
+ console.error("Failed to sync notes to Jira:", e);
+ }
+ break;
+ }
+ }
+ return;
+ }
+}
diff --git a/packages/form/src/components/Select.tsx b/packages/form/src/components/Select.tsx
index 9cfadb5713..d8ef362e4f 100644
--- a/packages/form/src/components/Select.tsx
+++ b/packages/form/src/components/Select.tsx
@@ -179,7 +179,7 @@ export const SelectBase = forwardRef<HTMLButtonElement, SelectBaseProps>(
<SelectValue placeholder={placeholder} />
{isLoading && (
<div className="absolute top-3 right-2">
- <Spinner />
+ <Spinner className="size-3" />
</div>
)}
</div>
diff --git a/packages/jobs/trigger/jira.ts b/packages/jobs/trigger/jira.ts
new file mode 100644
index 0000000000..53c5141add
--- /dev/null
+++ b/packages/jobs/trigger/jira.ts
@@ -0,0 +1,177 @@
+import { getCarbonServiceRole } from "@carbon/auth";
+import {
+ getCompanyEmployees,
+ getJiraClient,
+ linkActionToJiraIssue
+} from "@carbon/ee/jira";
+import { task } from "@trigger.dev/sdk";
+import { z } from "zod";
+
+const jira = getJiraClient();
+
+// Schema for Jira webhook payload
+export const syncIssueFromJiraSchema = z.object({
+ companyId: z.string(),
+ event: z.object({
+ timestamp: z.number().optional(),
+ webhookEvent: z.string(),
+ issue: z
+ .object({
+ id: z.string(),
+ key: z.string(),
+ fields: z.object({
+ summary: z.string().optional(),
+ description: z.any().nullable().optional(),
+ status: z
+ .object({
+ name: z.string().optional(),
+ statusCategory: z
+ .object({
+ key: z.string()
+ })
+ .optional()
+ })
+ .optional(),
+ assignee: z
+ .object({
+ accountId: z.string().optional(),
+ emailAddress: z.string().optional(),
+ displayName: z.string().optional()
+ })
+ .nullable()
+ .optional(),
+ duedate: z.string().nullable().optional()
+ })
+ })
+ .optional(),
+ changelog: z
+ .object({
+ items: z.array(
+ z.object({
+ field: z.string(),
+ fieldtype: z.string().optional(),
+ from: z.string().nullable().optional(),
+ fromString: z.string().nullable().optional(),
+ to: z.string().nullable().optional(),
+ toString: z.string().nullable().optional()
+ })
+ )
+ })
+ .optional()
+ })
+});
+
+export const syncIssueFromJira = task({
+ id: "sync-issue-from-jira",
+ retry: {
+ maxAttempts: 1
+ },
+ maxDuration: 5 * 60,
+ run: async (payload: z.infer<typeof syncIssueFromJiraSchema>) => {
+ console.info(`🔰 Jira webhook received`);
+ console.info(`📦 Event type: ${payload.event.webhookEvent}`);
+
+ // Only handle issue_updated events
+ if (
+ payload.event.webhookEvent !== "jira:issue_updated" &&
+ payload.event.webhookEvent !== "issue_updated"
+ ) {
+ return {
+ success: true,
+ message: `Ignoring event type: ${payload.event.webhookEvent}`
+ };
+ }
+
+ if (!payload.event.issue) {
+ return {
+ success: false,
+ message: "No issue data in webhook 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", "jira")
+ .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 issueId = payload.event.issue.id;
+
+ // Look up the action task via the mapping table
+ const mapping = await carbon
+ .from("externalIntegrationMapping")
+ .select("entityId")
+ .eq("entityType", "nonConformanceActionTask")
+ .eq("integration", "jira")
+ .eq("externalId", issueId)
+ .eq("companyId", payload.companyId)
+ .maybeSingle();
+
+ if (!mapping.data) {
+ return {
+ success: false,
+ message: `No linked action found for Jira issue ID ${issueId}`
+ };
+ }
+
+ const actionId = mapping.data.entityId;
+
+ // Fetch the full issue from Jira
+ const fullIssue = await jira.getIssue(payload.companyId, issueId);
+
+ if (!fullIssue) {
+ return {
+ success: false,
+ message: `Failed to fetch issue ${issueId} from Jira`
+ };
+ }
+
+ // Get the site URL for the mapping
+ const siteUrl = await jira.getSiteUrl(payload.companyId);
+
+ // Resolve assignee if present
+ let assignee: string | null = null;
+
+ if (fullIssue.fields.assignee?.emailAddress) {
+ const employees = await getCompanyEmployees(carbon, payload.companyId, [
+ fullIssue.fields.assignee.emailAddress
+ ]);
+ assignee = employees.length > 0 ? employees[0].userId : null;
+ }
+
+ // Update the linked action task
+ const updated = await linkActionToJiraIssue(carbon, payload.companyId, {
+ actionId,
+ issue: fullIssue,
+ siteUrl,
+ assignee,
+ syncNotes: true
+ });
+
+ if (!updated || updated.error) {
+ return {
+ success: false,
+ message: `Failed to update action for Jira issue ID ${issueId}`
+ };
+ }
+
+ return {
+ success: true,
+ message: `Synced Jira issue ${fullIssue.key}`
+ };
+ }
+});
diff --git a/packages/react/src/BarProgress.tsx b/packages/react/src/BarProgress.tsx
index e599d2a54c..9c09e234d8 100644
--- a/packages/react/src/BarProgress.tsx
+++ b/packages/react/src/BarProgress.tsx
@@ -119,7 +119,7 @@ export function BarProgress({
return (
<div className={cn("w-full", className)}>
{hasHeader && (
- <div className="mb-1.5 flex items-baseline justify-between">
+ <div className="mb-0.5 flex items-baseline justify-between">
{label ? (
<span className="text-sm font-medium text-foreground">{label}</span>
) : (
diff --git a/packages/react/src/Combobox.tsx b/packages/react/src/Combobox.tsx
index 1cda716c8b..c1cd751d27 100644
--- a/packages/react/src/Combobox.tsx
+++ b/packages/react/src/Combobox.tsx
@@ -97,7 +97,7 @@ const Combobox = forwardRef<HTMLButtonElement, ComboboxProps>(
"min-w-[160px]",
!value && "text-muted-foreground"
)}
- icon={isLoading ? <Spinner /> : undefined}
+ icon={isLoading ? <Spinner className="size-3" /> : undefined}
ref={ref}
{...props}
onClick={() => setOpen(true)}
diff --git a/packages/react/src/Modal.tsx b/packages/react/src/Modal.tsx
index 92f4467da2..bd2b6d1553 100644
--- a/packages/react/src/Modal.tsx
+++ b/packages/react/src/Modal.tsx
@@ -44,7 +44,7 @@ ModalOverlay.displayName = DialogPrimitive.Overlay.displayName;
const ModalContentVariants = cva(
cn(
"p-0",
- "relative z-50 flex flex-col w-full shadow-button-base duration-200",
+ "relative z-50 flex flex-col w-full max-h-[85vh] shadow-button-base duration-200",
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
"data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95",
"data-[state=closed]:slide-out-to-left-[0%] data-[state=closed]:slide-out-to-top-[0%",
@@ -119,7 +119,7 @@ ModalHeader.displayName = "ModalHeader";
const ModalBody = ({ className, ...props }: HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
- "w-full p-6 rounded-2xl border border-border bg-card dark:bg-muted/40",
+ "w-full p-6 rounded-2xl border border-border bg-card dark:bg-muted/40 overflow-y-auto",
className
)}
{...props}