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.

feat: traceability graph

Brad Barbin3ef0004b7a4e
diff --git a/apps/erp/app/components/index.ts b/apps/erp/app/components/index.ts
index 6ade0a6cc0..4cf02e6a75 100644
--- a/apps/erp/app/components/index.ts
+++ b/apps/erp/app/components/index.ts
@@ -4,7 +4,6 @@ import AvatarMenu from "./AvatarMenu";
import { BreadcrumbItem, BreadcrumbLink, Breadcrumbs } from "./Breadcrumb";
import CadModel from "./CadModel";
import Contact from "./Contact";
-import Copy from "./Copy";
import CustomerAvatar from "./CustomerAvatar";
import { DirectionAwareTabs } from "./DirectionAwareTabs";
import DocumentPreview from "./DocumentPreview";
@@ -41,7 +40,6 @@ export {
Breadcrumbs,
CadModel,
Contact,
- Copy,
CustomerAvatar,
DirectionAwareTabs,
DocumentPreview,
diff --git a/apps/erp/app/integrations/paperless-parts/config.tsx b/apps/erp/app/integrations/paperless-parts/config.tsx
index 35e9164843..df4f4fa0d2 100644
--- a/apps/erp/app/integrations/paperless-parts/config.tsx
+++ b/apps/erp/app/integrations/paperless-parts/config.tsx
@@ -1,8 +1,7 @@
-import { cn, Input, InputGroup, InputRightElement } from "@carbon/react";
+import { cn, Copy, Input, InputGroup, InputRightElement } from "@carbon/react";
import { isBrowser } from "@carbon/utils";
import type { SVGProps } from "react";
import { z } from "zod";
-import { Copy } from "~/components";
import type { IntegrationConfig } from "../types";
export const PaperlessParts: IntegrationConfig = {
diff --git a/apps/erp/app/modules/inventory/types.ts b/apps/erp/app/modules/inventory/types.ts
index 1221f2373e..f40e6c64be 100644
--- a/apps/erp/app/modules/inventory/types.ts
+++ b/apps/erp/app/modules/inventory/types.ts
@@ -64,3 +64,56 @@ export type ShippingMethod = NonNullable<
export type ShipmentSourceDocument =
Database["public"]["Enums"]["shipmentSourceDocument"];
+
+export interface TrackedEntity {
+ id: string;
+ quantity: number;
+ sourceDocument: string;
+ sourceDocumentId: string;
+ sourceDocumentReadableId: string;
+ attributes: Record<string, any>;
+}
+
+export interface Activity {
+ id: string;
+ type: string;
+ sourceDocument?: string;
+ sourceDocumentId?: string;
+ sourceDocumentReadableId?: string;
+ attributes: Record<string, any>;
+}
+
+export interface ActivityInput {
+ trackedActivityId: string;
+ trackedEntityId: string;
+ quantity: number;
+ entityType: string;
+}
+
+export interface ActivityOutput {
+ trackedActivityId: string;
+ trackedEntityId: string;
+ quantity: number;
+}
+
+export interface GraphNode {
+ id: string;
+ type: "entity" | "activity";
+ data: TrackedEntity | Activity;
+ x?: number;
+ y?: number;
+ depth?: number;
+ parentId: string | null;
+}
+
+export interface GraphLink {
+ source: string;
+ target: string;
+ type: "input" | "output";
+ quantity: number;
+}
+
+export interface GraphData {
+ nodes: GraphNode[];
+ links: GraphLink[];
+}
diff --git a/apps/erp/app/modules/inventory/ui/Inventory/InventoryShelves.tsx b/apps/erp/app/modules/inventory/ui/Inventory/InventoryShelves.tsx
index 1c33ca9581..66ed5bc262 100644
--- a/apps/erp/app/modules/inventory/ui/Inventory/InventoryShelves.tsx
+++ b/apps/erp/app/modules/inventory/ui/Inventory/InventoryShelves.tsx
@@ -7,6 +7,7 @@ import {
CardDescription,
CardHeader,
CardTitle,
+ Copy,
HStack,
Modal,
ModalBody,
@@ -35,7 +36,6 @@ import { path } from "~/utils/path";
import { inventoryAdjustmentValidator } from "../../inventory.models";
import { useUnitOfMeasure } from "~/components/Form/UnitOfMeasure";
import { LuQrCode } from "react-icons/lu";
-import { Copy } from "~/components";
type InventoryShelvesProps = {
pickMethod: z.infer<typeof pickMethodValidator>;
diff --git a/apps/erp/app/modules/inventory/ui/useInventorySubmodules.tsx b/apps/erp/app/modules/inventory/ui/useInventorySubmodules.tsx
index 10d1438be7..255916201a 100644
--- a/apps/erp/app/modules/inventory/ui/useInventorySubmodules.tsx
+++ b/apps/erp/app/modules/inventory/ui/useInventorySubmodules.tsx
@@ -1,4 +1,4 @@
-import { LuHandCoins, LuTally5, LuTruck } from "react-icons/lu";
+import { LuHandCoins, LuNetwork, LuTally5, LuTruck } from "react-icons/lu";
import { usePermissions } from "~/hooks";
import { useSavedViews } from "~/hooks/useSavedViews";
import type { AuthenticatedRouteGroup } from "~/types";
@@ -6,7 +6,7 @@ import { path } from "~/utils/path";
const inventoryRoutes: AuthenticatedRouteGroup[] = [
{
- name: "Track",
+ name: "Traceability",
routes: [
{
name: "Quantities",
@@ -15,6 +15,12 @@ const inventoryRoutes: AuthenticatedRouteGroup[] = [
icon: <LuTally5 />,
table: "inventory",
},
+ {
+ name: "Traceability",
+ to: path.to.traceability,
+ role: "employee",
+ icon: <LuNetwork />,
+ },
],
},
{
diff --git a/apps/erp/app/modules/items/ui/Consumables/ConsumableHeader.tsx b/apps/erp/app/modules/items/ui/Consumables/ConsumableHeader.tsx
index 3158d0e588..bf709b8c95 100644
--- a/apps/erp/app/modules/items/ui/Consumables/ConsumableHeader.tsx
+++ b/apps/erp/app/modules/items/ui/Consumables/ConsumableHeader.tsx
@@ -1,7 +1,6 @@
-import { HStack, Heading, VStack } from "@carbon/react";
+import { Copy, HStack, Heading, VStack } from "@carbon/react";
import { Link, useParams } from "@remix-run/react";
-import { Copy } from "~/components";
import { DetailsTopbar } from "~/components/Layout";
import { useRouteData } from "~/hooks";
import { path } from "~/utils/path";
diff --git a/apps/erp/app/modules/items/ui/Item/BoMExplorer.tsx b/apps/erp/app/modules/items/ui/Item/BoMExplorer.tsx
index 7756eb24a0..d1ade53081 100644
--- a/apps/erp/app/modules/items/ui/Item/BoMExplorer.tsx
+++ b/apps/erp/app/modules/items/ui/Item/BoMExplorer.tsx
@@ -1,5 +1,6 @@
import {
Badge,
+ Copy,
HStack,
HoverCard,
HoverCardContent,
@@ -14,7 +15,7 @@ import {
import { useNavigate, useParams } from "@remix-run/react";
import { useRef, useState } from "react";
import { LuChevronDown, LuChevronRight, LuSearch } from "react-icons/lu";
-import { Copy, MethodIcon, MethodItemTypeIcon } from "~/components";
+import { MethodIcon, MethodItemTypeIcon } from "~/components";
import type { FlatTreeItem } from "~/components/TreeView";
import { LevelLine, TreeView, useTree } from "~/components/TreeView";
import type { MethodItemType } from "~/modules/shared";
diff --git a/apps/erp/app/modules/items/ui/Item/ItemForm.tsx b/apps/erp/app/modules/items/ui/Item/ItemForm.tsx
index a825525829..55c7a61fab 100644
--- a/apps/erp/app/modules/items/ui/Item/ItemForm.tsx
+++ b/apps/erp/app/modules/items/ui/Item/ItemForm.tsx
@@ -8,6 +8,7 @@ import {
CardFooter,
CardHeader,
CardTitle,
+ Copy,
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
@@ -19,7 +20,7 @@ import { Link, useFetcher } from "@remix-run/react";
import { useState } from "react";
import { LuEllipsisVertical } from "react-icons/lu";
import type { z } from "zod";
-import { Copy, TrackingTypeIcon } from "~/components";
+import { TrackingTypeIcon } from "~/components";
import {
Boolean,
DefaultMethodType,
diff --git a/apps/erp/app/modules/items/ui/Materials/MaterialHeader.tsx b/apps/erp/app/modules/items/ui/Materials/MaterialHeader.tsx
index 99c7a3b2a5..f9fed87054 100644
--- a/apps/erp/app/modules/items/ui/Materials/MaterialHeader.tsx
+++ b/apps/erp/app/modules/items/ui/Materials/MaterialHeader.tsx
@@ -1,7 +1,6 @@
-import { HStack, Heading, VStack } from "@carbon/react";
+import { Copy, HStack, Heading, VStack } from "@carbon/react";
import { Link, useParams } from "@remix-run/react";
-import { Copy } from "~/components";
import { DetailsTopbar } from "~/components/Layout";
import { useRouteData } from "~/hooks";
import { path } from "~/utils/path";
diff --git a/apps/erp/app/modules/items/ui/Parts/PartHeader.tsx b/apps/erp/app/modules/items/ui/Parts/PartHeader.tsx
index cf4efdbf43..8699d6d28f 100644
--- a/apps/erp/app/modules/items/ui/Parts/PartHeader.tsx
+++ b/apps/erp/app/modules/items/ui/Parts/PartHeader.tsx
@@ -1,7 +1,6 @@
-import { HStack, Heading, VStack } from "@carbon/react";
+import { Copy, HStack, Heading, VStack } from "@carbon/react";
import { Link, useParams } from "@remix-run/react";
-import { Copy } from "~/components";
import { DetailsTopbar } from "~/components/Layout";
import { useRouteData } from "~/hooks";
import { path } from "~/utils/path";
diff --git a/apps/erp/app/modules/items/ui/Tools/ToolHeader.tsx b/apps/erp/app/modules/items/ui/Tools/ToolHeader.tsx
index 1e370a7ebc..65c6462e5a 100644
--- a/apps/erp/app/modules/items/ui/Tools/ToolHeader.tsx
+++ b/apps/erp/app/modules/items/ui/Tools/ToolHeader.tsx
@@ -1,7 +1,6 @@
-import { HStack, Heading, VStack } from "@carbon/react";
+import { Copy, HStack, Heading, VStack } from "@carbon/react";
import { Link, useParams } from "@remix-run/react";
-import { Copy } from "~/components";
import { DetailsTopbar } from "~/components/Layout";
import { useRouteData } from "~/hooks";
import { path } from "~/utils/path";
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobBoMExplorer.tsx b/apps/erp/app/modules/production/ui/Jobs/JobBoMExplorer.tsx
index 319fb04c3d..bc968e644f 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobBoMExplorer.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobBoMExplorer.tsx
@@ -1,5 +1,6 @@
import {
Badge,
+ Copy,
HStack,
HoverCard,
HoverCardContent,
@@ -17,7 +18,7 @@ import {
import { useFetchers, useNavigate } from "@remix-run/react";
import { useRef, useState } from "react";
import { LuChevronDown, LuChevronRight, LuSearch } from "react-icons/lu";
-import { Copy, MethodIcon, MethodItemTypeIcon } from "~/components";
+import { MethodIcon, MethodItemTypeIcon } from "~/components";
import type { FlatTree, FlatTreeItem } from "~/components/TreeView";
import { LevelLine, TreeView, useTree } from "~/components/TreeView";
import { useOptimisticLocation } from "~/hooks";
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobMaterialForm.tsx b/apps/erp/app/modules/production/ui/Jobs/JobMaterialForm.tsx
index 77cb263065..461386ceb1 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobMaterialForm.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobMaterialForm.tsx
@@ -5,6 +5,7 @@ import {
CardFooter,
CardHeader,
CardTitle,
+ Copy,
toast,
VStack,
} from "@carbon/react";
@@ -19,7 +20,6 @@ import { useCarbon } from "@carbon/auth";
import { ValidatedForm } from "@carbon/form";
import { useEffect, useState } from "react";
import type { z } from "zod";
-import { Copy } from "~/components";
import {
DefaultMethodType,
Hidden,
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteBoMExplorer.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteBoMExplorer.tsx
index 52ccc9b9fa..218a715fac 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteBoMExplorer.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteBoMExplorer.tsx
@@ -1,5 +1,6 @@
import {
Badge,
+ Copy,
HStack,
HoverCard,
HoverCardContent,
@@ -17,7 +18,7 @@ import {
import { useFetchers, useNavigate } from "@remix-run/react";
import { useRef, useState } from "react";
import { LuChevronDown, LuChevronRight, LuSearch } from "react-icons/lu";
-import { Copy, MethodIcon, MethodItemTypeIcon } from "~/components";
+import { MethodIcon, MethodItemTypeIcon } from "~/components";
import type { FlatTree, FlatTreeItem } from "~/components/TreeView";
import { LevelLine, TreeView, useTree } from "~/components/TreeView";
import { useOptimisticLocation } from "~/hooks";
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteHeader.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteHeader.tsx
index 569273e3f2..31ab2e4f09 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteHeader.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteHeader.tsx
@@ -1,5 +1,6 @@
import {
Button,
+ Copy,
DropdownMenu,
DropdownMenuContent,
DropdownMenuIcon,
@@ -39,7 +40,6 @@ import {
LuShare,
LuTrophy,
} from "react-icons/lu";
-import { Copy } from "~/components";
import { usePanels } from "~/components/Layout";
import { usePermissions, useRouteData } from "~/hooks";
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteMaterialForm.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteMaterialForm.tsx
index 4f239b995b..672a9b0ce4 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteMaterialForm.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteMaterialForm.tsx
@@ -5,6 +5,7 @@ import {
CardFooter,
CardHeader,
CardTitle,
+ Copy,
toast,
VStack,
} from "@carbon/react";
@@ -19,7 +20,6 @@ import { useCarbon } from "@carbon/auth";
import { ValidatedForm } from "@carbon/form";
import { useEffect, useState } from "react";
import type { z } from "zod";
-import { Copy } from "~/components";
import {
DefaultMethodType,
Hidden,
diff --git a/apps/erp/app/routes/x+/inventory+/traceability.tsx b/apps/erp/app/routes/x+/inventory+/traceability.tsx
new file mode 100644
index 0000000000..56b7099c5d
--- /dev/null
+++ b/apps/erp/app/routes/x+/inventory+/traceability.tsx
@@ -0,0 +1,725 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { HStack, Heading, VStack } from "@carbon/react";
+import { useUrlParams } from "@carbon/remix";
+import { useLoaderData } from "@remix-run/react";
+import { json, LoaderFunctionArgs } from "@vercel/remix";
+import { ParentSize } from "@visx/responsive";
+import * as d3 from "d3";
+import { useRef, useState, useEffect } from "react";
+import { CollapsibleSidebarTrigger } from "~/components/Layout/Navigation";
+import {
+ GraphData,
+ GraphNode,
+ GraphLink,
+ TrackedEntity,
+ ActivityInput,
+ ActivityOutput,
+ Activity,
+} from "~/modules/inventory";
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId, userId } = await requirePermissions(request, {
+ view: "inventory",
+ bypassRls: true,
+ });
+
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ const trackedEntityId = searchParams.get("trackedEntityId");
+
+ if (!trackedEntityId) {
+ throw new Error("No tracked entity id provided");
+ }
+
+ const [entity, descendants, ancestors] = await Promise.all([
+ client.from("trackedEntity").select("*").eq("id", trackedEntityId).single(),
+ client.rpc("get_direct_descendants_of_tracked_entity_strict", {
+ p_tracked_entity_id: trackedEntityId,
+ }),
+ client.rpc("get_direct_ancestors_of_tracked_entity_strict", {
+ p_tracked_entity_id: trackedEntityId,
+ }),
+ ]);
+
+ const [inputs, outputs] = await Promise.all([
+ client
+ .from("trackedActivityInput")
+ .select("*")
+ .in(
+ "trackedEntityId",
+ Array.from(
+ new Set([
+ ...(descendants?.data?.map((descendant) => descendant.id) || []),
+ trackedEntityId,
+ ])
+ )
+ ),
+ client
+ .from("trackedActivityOutput")
+ .select("*")
+ .in(
+ "trackedEntityId",
+ Array.from(
+ new Set([
+ trackedEntityId,
+ ...(ancestors?.data?.map((ancestor) => ancestor.id) || []),
+ ])
+ )
+ ),
+ ]);
+
+ const uniqueActivityIds = Array.from(
+ new Set([
+ ...(inputs?.data?.map((input) => input.trackedActivityId) || []),
+ ...(outputs?.data?.map((output) => output.trackedActivityId) || []),
+ ])
+ );
+
+ const activities = await client
+ .from("trackedActivity")
+ .select("*")
+ .in("id", uniqueActivityIds);
+
+ return json({
+ trackedEntityId,
+ entities: [
+ entity?.data,
+ ...(descendants?.data ?? []),
+ ...(ancestors?.data ?? []),
+ ],
+ inputs: inputs?.data ?? [],
+ outputs: outputs?.data ?? [],
+ activities: activities?.data ?? [],
+ });
+}
+
+export default function TraceabilityRoute() {
+ const [params, setParams] = useUrlParams();
+ const selectedId =
+ params.get("trackedEntityId") ?? params.get("trackedActivityId");
+
+ const { entities, inputs, outputs, activities } =
+ useLoaderData<typeof loader>();
+ const [graphData, setGraphData] = useState<GraphData>({
+ nodes: [],
+ links: [],
+ });
+
+ useEffect(() => {
+ // Cast the data from the loader to the correct types
+ const validEntities = entities.filter(
+ Boolean
+ ) as unknown as TrackedEntity[];
+ const validActivities = activities.filter(Boolean) as unknown as Activity[];
+
+ // Show all nodes and links
+ const allNodes = getAllNodes(validEntities, validActivities);
+ const allLinks = getAllLinks(inputs, outputs);
+ setGraphData({ nodes: allNodes, links: allLinks });
+ }, [entities, activities, inputs, outputs]);
+
+ const handleNodeClick = (node: GraphNode) => {
+ if (node.type === "entity") {
+ setParams({
+ trackedEntityId: node.data.id,
+ trackedActivityId: null,
+ });
+ } else {
+ setParams({
+ trackedEntityId: null,
+ trackedActivityId: node.data.id,
+ });
+ }
+ };
+
+ return (
+ <div className="bg-card h-[calc(100dvh-49px)] w-full overflow-hidden scrollbar-hide">
+ <VStack className="flex-1 w-full h-full">
+ <HStack className="px-4 py-6 justify-between w-full relative">
+ <HStack spacing={1}>
+ <CollapsibleSidebarTrigger />
+ <Heading size={"h2"}>Traceability</Heading>
+ </HStack>
+ </HStack>
+ <div className="flex flex-1 w-full h-full overflow-y-auto scrollbar-hide p-4">
+ <div className="w-full max-w-full overflow-x-auto text-muted-foreground">
+ <ParentSize>
+ {({ width, height }) => (
+ <TraceabilityGraph
+ key={`${selectedId}`}
+ data={graphData}
+ onNodeClick={handleNodeClick}
+ selectedId={selectedId}
+ width={width}
+ height={height}
+ />
+ )}
+ </ParentSize>
+ </div>
+ </div>
+ </VStack>
+ </div>
+ );
+}
+
+type TraceabilityGraphProps = {
+ data: GraphData;
+ selectedId: string | null;
+ onNodeClick: (node: GraphNode) => void;
+ width: number;
+ height: number;
+};
+
+function TraceabilityGraph({
+ data,
+ onNodeClick,
+ width,
+ height,
+ selectedId,
+}: TraceabilityGraphProps) {
+ const svgRef = useRef<SVGSVGElement>(null);
+
+ useEffect(() => {
+ if (!svgRef.current || !data.nodes.length) return;
+
+ const svg = d3.select(svgRef.current);
+ svg.selectAll("*").remove();
+
+ // Add definitions for filters and markers
+ const defs = svg.append("defs");
+
+ // Arrow marker - increased size for bigger arrowheads
+ defs
+ .append("marker")
+ .attr("id", "arrow")
+ .attr("viewBox", "0 -4 8 8") // Increased viewBox size
+ .attr("refX", 24) // Adjusted refX to account for larger size
+ .attr("refY", 0)
+ .attr("markerWidth", 6) // Increased from 4 to 6
+ .attr("markerHeight", 6) // Increased from 4 to 6
+ .attr("orient", "auto")
+ .append("path")
+ .attr("d", "M0,-4L8,0L0,4") // Increased path size
+ .attr("fill", "currentColor"); // Use text-foreground color
+
+ // Calculate node depths and assign radial positions
+ const calculateNodeDepths = () => {
+ // Create a map to store node depths
+ const nodeDepths = new Map<string, number>();
+ const nodeParents = new Map<string, string>();
+
+ // Find root nodes (typically activities without incoming links)
+ const rootNodes = data.nodes.filter((node) => {
+ return (
+ node.type === "activity" &&
+ !data.links.some((link) => link.target === node.id)
+ );
+ });
+
+ // If no clear root nodes, use the first activity
+ const startNodes =
+ rootNodes.length > 0
+ ? rootNodes
+ : data.nodes.filter((node) => node.type === "activity").slice(0, 1);
+
+ // Initialize queue with root nodes at depth 0
+ const queue: [string, number, string | null][] = startNodes.map(
+ (node) => [node.id, 0, null]
+ );
+
+ // BFS to assign depths
+ while (queue.length > 0) {
+ const [nodeId, depth, parentId] = queue.shift()!;
+
+ // Skip if we've already processed this node with a shorter path
+ if (nodeDepths.has(nodeId) && nodeDepths.get(nodeId)! <= depth) {
+ continue;
+ }
+
+ // Assign depth and parent
+ nodeDepths.set(nodeId, depth);
+ if (parentId) nodeParents.set(nodeId, parentId);
+
+ // Find all connected nodes
+ const outgoingLinks = data.links.filter(
+ (link) => link.source === nodeId
+ );
+ for (const link of outgoingLinks) {
+ queue.push([link.target, depth + 1, nodeId]);
+ }
+
+ // Also consider incoming links for non-root nodes
+ if (depth > 0) {
+ const incomingLinks = data.links.filter(
+ (link) => link.target === nodeId && link.source !== parentId
+ );
+ for (const link of incomingLinks) {
+ queue.push([link.source, depth + 1, nodeId]);
+ }
+ }
+ }
+
+ return { nodeDepths, nodeParents };
+ };
+
+ const { nodeDepths, nodeParents } = calculateNodeDepths();
+
+ // Enhance nodes with depth information
+ data.nodes.forEach((node) => {
+ node.depth = nodeDepths.get(node.id) || 0;
+ node.parentId = nodeParents.get(node.id) || null;
+ });
+
+ // Create a force simulation with improved forces
+ const simulation = d3
+ .forceSimulation<d3.SimulationNodeDatum & GraphNode>(data.nodes as any)
+ .force(
+ "link",
+ d3
+ .forceLink<
+ d3.SimulationNodeDatum & GraphNode,
+ d3.SimulationLinkDatum<d3.SimulationNodeDatum & GraphNode> &
+ GraphLink
+ >(data.links as any)
+ .id((d) => (d as any).id)
+ .distance((d) => {
+ // Increase distance based on the depth of connected nodes
+ const sourceNode = data.nodes.find(
+ (n) => n.id === (d as any).source.id
+ );
+ const targetNode = data.nodes.find(
+ (n) => n.id === (d as any).target.id
+ );
+ if (sourceNode && targetNode) {
+ const depthDiff = Math.abs(
+ (sourceNode.depth || 0) - (targetNode.depth || 0)
+ );
+ return 150 + depthDiff * 50; // Base distance + additional for depth difference
+ }
+ return 150;
+ })
+ )
+ .force("charge", d3.forceManyBody().strength(-800)) // Stronger repulsion
+ .force("center", d3.forceCenter(width / 2, height / 2))
+ .force(
+ "collision",
+ d3.forceCollide().radius((d) => {
+ // Larger collision radius for nodes with higher depth
+ const node = d as GraphNode;
+ return 60 + (node.depth || 0) * 5;
+ })
+ )
+ .force("x", d3.forceX(width / 2).strength(0.1))
+ .force(
+ "y",
+ d3
+ .forceY()
+ .y((d) => {
+ // Position nodes vertically based on their level or type
+ const node = d as GraphNode;
+ if (node.type === "activity") {
+ return height * 0.4; // Activities in the middle
+ } else {
+ // For entities, check if they're inputs or outputs
+ const isInput = data.links.some(
+ (link) => link.target === node.id
+ );
+ const isOutput = data.links.some(
+ (link) => link.source === node.id
+ );
+
+ if (isInput && !isOutput) {
+ return height * 0.2; // Inputs at the top
+ } else if (isOutput && !isInput) {
+ return height * 0.6; // Outputs at the bottom
+ } else {
+ return height * 0.4; // Both input and output in the middle
+ }
+ }
+ })
+ .strength(0.3)
+ )
+ // Add radial force to push nodes outward based on depth
+ .force(
+ "radial",
+ d3
+ .forceRadial<d3.SimulationNodeDatum & GraphNode>(
+ (d) => {
+ const node = d as GraphNode;
+ // Radius increases with depth
+ return 100 + (node.depth || 0) * 120;
+ },
+ width / 2,
+ height / 2
+ )
+ .strength(0.8)
+ );
+
+ // Create curved links with uniform size
+ const link = svg
+ .append("g")
+ .attr("class", "links")
+ .selectAll("path")
+ .data(data.links)
+ .enter()
+ .append("path")
+ .attr("stroke-width", 1.5)
+ .attr("stroke", "currentColor") // Use text-foreground color
+ .attr("marker-end", "url(#arrow)")
+ .attr("fill", "none")
+ .style("opacity", 0.8); // Increased opacity for better visibility
+
+ // Create the nodes group
+ const node = svg
+ .append("g")
+ .attr("class", "nodes")
+ .selectAll("g")
+ .data(data.nodes)
+ .enter()
+ .append("g")
+ .call(
+ d3
+ .drag<SVGGElement, GraphNode>()
+ .on("start", dragstarted)
+ .on("drag", dragged)
+ .on("end", dragended) as any
+ );
+
+ // Add circles for the nodes with shadow and glow
+ node
+ .append("circle")
+ .attr("r", (d) => 20 + (d.depth || 0) * 2) // Slightly larger circles for deeper nodes
+ .attr("fill", (d) =>
+ d.data.id === selectedId
+ ? "#2DD4BF"
+ : d.type === "entity"
+ ? "#2563EB"
+ : "#7C3AED"
+ ) // blue-600 for entities, rose-600 for activities
+ .attr("filter", "url(#drop-shadow)")
+ .style("filter", "url(#glow)")
+ .on("click", (event, d) => {
+ event.stopPropagation();
+ onNodeClick(d);
+ });
+
+ // Add labels to the nodes
+ node
+ .append("text")
+ .text((d) => {
+ if (d.type === "entity") {
+ const entity = d.data as TrackedEntity;
+ return entity.sourceDocumentReadableId || entity.id.substring(0, 8);
+ } else {
+ const activity = d.data as Activity;
+ // Use optional chaining for properties that might not exist
+ return activity.type || activity.id?.substring(0, 8) || "Unknown";
+ }
+ })
+ .attr("text-anchor", "middle")
+ .attr("dy", (d) => 30 + (d.depth || 0) * 2) // Adjust label position for larger circles
+ .attr("font-size", "12px")
+ .attr("fill", "hsl(var(--foreground))") // Use white in dark mode and black in light mode
+ .attr("font-weight", "bold")
+ .attr("font-family", "Geist");
+
+ // Add title for hover tooltip
+ node.append("title").text((d) => {
+ if (d.type === "entity") {
+ const entity = d.data as TrackedEntity;
+ return `Entity: ${
+ entity.sourceDocumentReadableId || entity.id
+ }\nQuantity: ${entity.quantity}`;
+ } else {
+ const activity = d.data as Activity;
+ return `Activity: ${activity.type || "Unknown"}\nID: ${
+ activity.id || "Unknown"
+ }\nDepth: ${d.depth || 0}`;
+ }
+ });
+
+ // Update positions on each tick of the simulation
+ simulation.on("tick", () => {
+ // Keep nodes within bounds
+ data.nodes.forEach((d: any) => {
+ d.x = Math.max(30, Math.min(width - 30, d.x));
+ d.y = Math.max(30, Math.min(height - 30, d.y));
+ });
+
+ // Update curved links
+ link.attr("d", (d: any) => {
+ const dx = d.target.x - d.source.x;
+ const dy = d.target.y - d.source.y;
+ const dr = Math.sqrt(dx * dx + dy * dy) * 1.5;
+ return `M${d.source.x},${d.source.y}A${dr},${dr} 0 0,1 ${d.target.x},${d.target.y}`;
+ });
+
+ node.attr("transform", (d) => `translate(${d.x},${d.y})`);
+ });
+
+ // Drag functions
+ function dragstarted(event: d3.D3DragEvent<SVGGElement, GraphNode, any>) {
+ if (!event.active) simulation.alphaTarget(0.3).restart();
+ event.subject.fx = event.subject.x;
+ event.subject.fy = event.subject.y;
+ }
+
+ function dragged(event: d3.D3DragEvent<SVGGElement, GraphNode, any>) {
+ event.subject.fx = event.x;
+ event.subject.fy = event.y;
+ }
+
+ function dragended(event: d3.D3DragEvent<SVGGElement, GraphNode, any>) {
+ if (!event.active) simulation.alphaTarget(0);
+ // Don't reset fx and fy to null to keep nodes in place after dragging
+ // This allows nodes to stay where they were dragged to
+ }
+
+ return () => {
+ simulation.stop();
+ };
+ }, [data, width, height, onNodeClick, selectedId]);
+
+ return (
+ <div className="relative">
+ <svg ref={svgRef} width={width} height={height} />
+ </div>
+ );
+}
+
+// Function to filter graph data based on selected node
+export const filterGraphByNode = (
+ allEntities: TrackedEntity[],
+ allActivities: Activity[],
+ allInputs: ActivityInput[],
+ allOutputs: ActivityOutput[],
+ selectedNode: GraphNode | null
+): GraphData => {
+ if (!selectedNode) {
+ // Return empty graph if no node is selected
+ return { nodes: [], links: [] };
+ }
+
+ const nodes: GraphNode[] = [];
+ const links: GraphLink[] = [];
+ const nodeIds = new Set<string>();
+
+ // Add the selected node with depth 0
+ nodes.push({
+ ...selectedNode,
+ depth: 0,
+ parentId: null,
+ });
+ nodeIds.add(selectedNode.id);
+
+ if (selectedNode.type === "entity") {
+ // For entity nodes, show direct parents (activities that output this entity)
+ // and direct children (activities that use this entity as input)
+
+ // Find activities that output this entity
+ const parentActivities = allOutputs
+ .filter((output) => output.trackedEntityId === selectedNode.id)
+ .map((output) => {
+ const activity = allActivities.find(
+ (a) => a.id === output.trackedActivityId
+ );
+ if (activity && !nodeIds.has(activity.id)) {
+ nodeIds.add(activity.id);
+ return {
+ id: activity.id,
+ type: "activity" as const,
+ data: activity,
+ depth: -1, // Parent activities are at depth -1
+ parentId: selectedNode.id,
+ } as GraphNode;
+ }
+ return null;
+ })
+ .filter((node): node is NonNullable<typeof node> => node !== null);
+
+ nodes.push(...parentActivities);
+
+ // Add links from parent activities to this entity
+ parentActivities.forEach((activity) => {
+ if (activity) {
+ links.push({
+ source: activity.id,
+ target: selectedNode.id,
+ type: "output",
+ quantity:
+ allOutputs.find(
+ (o) =>
+ o.trackedActivityId === activity.id &&
+ o.trackedEntityId === selectedNode.id
+ )?.quantity || 1,
+ });
+ }
+ });
+
+ // Find activities that use this entity as input
+ const childActivities = allInputs
+ .filter((input) => input.trackedEntityId === selectedNode.id)
+ .map((input) => {
+ const activity = allActivities.find(
+ (a) => a.id === input.trackedActivityId
+ );
+ if (activity && !nodeIds.has(activity.id)) {
+ nodeIds.add(activity.id);
+ return {
+ id: activity.id,
+ type: "activity" as const,
+ data: activity,
+ depth: 1, // Child activities are at depth 1
+ parentId: selectedNode.id,
+ } as GraphNode;
+ }
+ return null;
+ })
+ .filter((node): node is NonNullable<typeof node> => node !== null);
+
+ nodes.push(...childActivities);
+
+ // Add links from this entity to child activities
+ childActivities.forEach((activity) => {
+ if (activity) {
+ links.push({
+ source: selectedNode.id,
+ target: activity.id,
+ type: "input",
+ quantity:
+ allInputs.find(
+ (i) =>
+ i.trackedActivityId === activity.id &&
+ i.trackedEntityId === selectedNode.id
+ )?.quantity || 1,
+ });
+ }
+ });
+ } else if (selectedNode.type === "activity") {
+ // For activity nodes, show all input entities and all output entities
+
+ // Find all input entities for this activity
+ const inputEntities = allInputs
+ .filter((input) => input.trackedActivityId === selectedNode.id)
+ .map((input) => {
+ const entity = allEntities.find((e) => e.id === input.trackedEntityId);
+ if (entity && !nodeIds.has(entity.id)) {
+ nodeIds.add(entity.id);
+ return {
+ id: entity.id,
+ type: "entity" as const,
+ data: entity,
+ depth: -1, // Input entities are at depth -1
+ parentId: selectedNode.id,
+ } as GraphNode;
+ }
+ return null;
+ })
+ .filter((node): node is NonNullable<typeof node> => node !== null);
+
+ nodes.push(...inputEntities);
+
+ // Add links from input entities to this activity
+ inputEntities.forEach((entity) => {
+ if (entity) {
+ links.push({
+ source: entity.id,
+ target: selectedNode.id,
+ type: "input",
+ quantity:
+ allInputs.find(
+ (i) =>
+ i.trackedActivityId === selectedNode.id &&
+ i.trackedEntityId === entity.id
+ )?.quantity || 1,
+ });
+ }
+ });
+
+ // Find all output entities for this activity
+ const outputEntities = allOutputs
+ .filter((output) => output.trackedActivityId === selectedNode.id)
+ .map((output) => {
+ const entity = allEntities.find((e) => e.id === output.trackedEntityId);
+ if (entity && !nodeIds.has(entity.id)) {
+ nodeIds.add(entity.id);
+ return {
+ id: entity.id,
+ type: "entity" as const,
+ data: entity,
+ depth: 1, // Output entities are at depth 1
+ parentId: selectedNode.id,
+ } as GraphNode;
+ }
+ return null;
+ })
+ .filter((node): node is NonNullable<typeof node> => node !== null);
+
+ nodes.push(...outputEntities);
+
+ // Add links from this activity to output entities
+ outputEntities.forEach((entity) => {
+ if (entity) {
+ links.push({
+ source: selectedNode.id,
+ target: entity.id,
+ type: "output",
+ quantity:
+ allOutputs.find(
+ (o) =>
+ o.trackedActivityId === selectedNode.id &&
+ o.trackedEntityId === entity.id
+ )?.quantity || 1,
+ });
+ }
+ });
+ }
+
+ return { nodes, links };
+};
+
+// Function to get all nodes for initial display
+export const getAllNodes = (
+ entities: TrackedEntity[],
+ activities: Activity[]
+): GraphNode[] => {
+ const entityNodes: GraphNode[] = entities.map((entity) => ({
+ id: entity.id,
+ type: "entity",
+ data: entity,
+ depth: 0,
+ parentId: null,
+ }));
+
+ const activityNodes: GraphNode[] = activities.map((activity) => ({
+ id: activity.id,
+ type: "activity",
+ data: activity,
+ depth: 0,
+ parentId: null,
+ }));
+
+ return [...entityNodes, ...activityNodes];
+};
+
+// Function to get all links
+export const getAllLinks = (
+ inputs: ActivityInput[],
+ outputs: ActivityOutput[]
+): GraphLink[] => {
+ const inputLinks: GraphLink[] = inputs.map((input) => ({
+ source: input.trackedEntityId,
+ target: input.trackedActivityId,
+ type: "input",
+ quantity: input.quantity,
+ }));
+
+ const outputLinks: GraphLink[] = outputs.map((output) => ({
+ source: output.trackedActivityId,
+ target: output.trackedEntityId,
+ type: "output",
+ quantity: output.quantity,
+ }));
+
+ return [...inputLinks, ...outputLinks];
+};
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index af743e1aa3..b44921729e 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -1053,7 +1053,7 @@ export const path = {
generatePath(
`${x}/tool/${itemId}/manufacturing/${makeMethodId}/${methodMaterialId}`
),
-
+
toolPlanning: (id: string) => generatePath(`${x}/tool/${id}/planning`),
toolPlanningLocation: (id: string, locationId: string) =>
generatePath(`${x}/tool/${id}/planning?location=${locationId}`),
@@ -1064,6 +1064,7 @@ export const path = {
generatePath(`${x}/tool/${itemId}/suppliers/${id}`),
toolSuppliers: (id: string) => generatePath(`${x}/tool/${id}/suppliers`),
tools: `${x}/items/tools`,
+ traceability: `${x}/inventory/traceability`,
uom: (id: string) => generatePath(`${x}/items/uom/${id}`),
uoms: `${x}/items/uom`,
userAttribute: (id: string) => generatePath(`${x}/account/${id}/attribute`),
diff --git a/apps/erp/package.json b/apps/erp/package.json
index 585a527b96..e362b84846 100644
--- a/apps/erp/package.json
+++ b/apps/erp/package.json
@@ -43,10 +43,12 @@
"@trigger.dev/sdk": "3.3.12",
"@vercel/analytics": "^1.2.2",
"@vercel/remix": "2.11.2",
+ "@visx/responsive": "^2.1.0",
"ai": "3.4.9",
"assert-never": "^1.2.1",
"clsx": "^2.1.0",
"cookie": "^0.6.0",
+ "d3": "^7.8.5",
"d3-array": "^3.2.4",
"framer-motion": "^11.1.7",
"isbot": "3.6.13",
@@ -82,6 +84,7 @@
"@carbon/tailwind": "*",
"@carbon/tsconfig": "*",
"@trigger.dev/build": "3.3.12",
+ "@types/d3": "^7.4.0",
"@types/nprogress": "^0.2.0",
"@types/papaparse": "^5.3.14",
"@types/react": "^18.2.74",
diff --git a/apps/erp/tsconfig.json b/apps/erp/tsconfig.json
index 6be6e78d8d..a3209f8d54 100644
--- a/apps/erp/tsconfig.json
+++ b/apps/erp/tsconfig.json
@@ -5,7 +5,8 @@
"**/*.tsx",
"app/modules/documents/documents.service.ts",
"app/types/global.d.ts",
- "trigger.config.ts"
+ "trigger.config.ts",
+ "../../packages/react/src/Copy.tsx"
],
"compilerOptions": {
"lib": ["dom", "dom.iterable", "ESNext"],
diff --git a/apps/mes/app/components/JobOperation.tsx b/apps/mes/app/components/JobOperation.tsx
index 50c7058d36..c413561db5 100644
--- a/apps/mes/app/components/JobOperation.tsx
+++ b/apps/mes/app/components/JobOperation.tsx
@@ -62,6 +62,8 @@ import {
NumberInput,
NumberInputGroup,
NumberInputStepper,
+ Copy,
+ Switch,
} from "@carbon/react";
import { generateHTML } from "@carbon/react/Editor";
import {
@@ -218,13 +220,11 @@ export const JobOperation = ({
const [params, setParams] = useUrlParams();
const trackedEntityParam = params.get("trackedEntityId");
- const trackedEntityId =
- trackedEntityParam ?? trackedEntities[0]?.id;
+ const trackedEntityId = trackedEntityParam ?? trackedEntities[0]?.id;
const trackedEntity = trackedEntities.find(
(entity) => entity.id === trackedEntityId
);
-
const navigate = useNavigate();
const parentIsSerial = method?.requiresSerialTracking;
@@ -308,8 +308,6 @@ export const JobOperation = ({
attributeRecordDeleteModal.onClose();
};
-
-
return (
<>
<Tabs
@@ -449,8 +447,8 @@ export const JobOperation = ({
<Heading size="h2">
{/* @ts-ignore */}
{trackedEntity?.attributes?.[`Operation ${operationId}`] ??
- 1}
- {" "}of {operation.operationQuantity}
+ 1}{" "}
+ of {operation.operationQuantity}
</Heading>
) : (
<Heading size="h2">{operation.operationQuantity}</Heading>
@@ -948,18 +946,21 @@ export const JobOperation = ({
</Td>
<Td className="text-right">
- <Button
- variant="secondary"
- size="sm"
- isDisabled={entity.id === trackedEntityId}
- onClick={() => {
- setParams({
- trackedEntityId: entity.id,
- });
- }}
- >
- Select
- </Button>
+ <div className="flex justify-end gap-2">
+ <Copy text={entity.id} />
+ <Button
+ variant="secondary"
+ size="sm"
+ isDisabled={entity.id === trackedEntityId}
+ onClick={() => {
+ setParams({
+ trackedEntityId: entity.id,
+ });
+ }}
+ >
+ Select
+ </Button>
+ </div>
</Td>
</Tr>
))
@@ -1211,6 +1212,11 @@ export const JobOperation = ({
laborProductionEvent={laborProductionEvent}
machineProductionEvent={machineProductionEvent}
hasActiveEvents={hasActiveEvents}
+ isTrackedActivity={
+ method?.requiresSerialTracking === true ||
+ method?.requiresBatchTracking === true
+ }
+ trackedEntityId={trackedEntityId}
/>
<div className="flex flex-row md:flex-col items-center gap-2 justify-center">
{/* <IconButtonWithTooltip
@@ -1222,7 +1228,15 @@ export const JobOperation = ({
/>
*/}
<IconButtonWithTooltip
- disabled={parentIsSerial && trackedEntities.some(entity => entity.id === trackedEntityId && `Operation ${operationId}` in (entity.attributes as TrackedEntityAttributes))}
+ disabled={
+ parentIsSerial &&
+ trackedEntities.some(
+ (entity) =>
+ entity.id === trackedEntityId &&
+ `Operation ${operationId}` in
+ (entity.attributes as TrackedEntityAttributes)
+ )
+ }
icon={
<FaTrash className="text-accent-foreground group-hover:text-accent-foreground/80" />
}
@@ -1231,7 +1245,15 @@ export const JobOperation = ({
/>
<IconButtonWithTooltip
- disabled={parentIsSerial && trackedEntities.some(entity => entity.id === trackedEntityId && `Operation ${operationId}` in (entity.attributes as TrackedEntityAttributes))}
+ disabled={
+ parentIsSerial &&
+ trackedEntities.some(
+ (entity) =>
+ entity.id === trackedEntityId &&
+ `Operation ${operationId}` in
+ (entity.attributes as TrackedEntityAttributes)
+ )
+ }
icon={
<FaPlus className="text-accent-foreground group-hover:text-accent-foreground/80" />
}
@@ -1939,14 +1961,21 @@ function useOperation(
);
const { operationId } = useParams();
- const [availableEntities, setAvailableEntities] = useState<TrackedEntity[]>([]);
+ const [availableEntities, setAvailableEntities] = useState<TrackedEntity[]>(
+ []
+ );
// show the serial selector with the remaining serial numbers for the operation
useEffect(() => {
if (trackedEntityParam) return;
- const uncompletedEntities = trackedEntities.filter((entity) => !(`Operation ${operationId}` in (entity.attributes as TrackedEntityAttributes ?? {})));
- if(uncompletedEntities.length > 0) serialModal.onOpen();
+ const uncompletedEntities = trackedEntities.filter(
+ (entity) =>
+ !(
+ `Operation ${operationId}` in
+ ((entity.attributes as TrackedEntityAttributes) ?? {})
+ )
+ );
+ if (uncompletedEntities.length > 0) serialModal.onOpen();
setAvailableEntities(uncompletedEntities);
-
}, [trackedEntities, operationId, trackedEntityParam]);
return {
@@ -2146,7 +2175,11 @@ function IconButtonWithTooltip({
tooltip,
disabled,
...props
-}: ComponentProps<"button"> & { icon: ReactNode; tooltip: string; disabled?: boolean }) {
+}: ComponentProps<"button"> & {
+ icon: ReactNode;
+ tooltip: string;
+ disabled?: boolean;
+}) {
return (
<ButtonWithTooltip
{...props}
@@ -2260,6 +2293,8 @@ function StartStopButton({
laborProductionEvent,
machineProductionEvent,
hasActiveEvents,
+ isTrackedActivity,
+ trackedEntityId,
...props
}: ComponentProps<"button"> & {
eventType: (typeof productionEventType)[number];
@@ -2269,7 +2304,10 @@ function StartStopButton({
laborProductionEvent: ProductionEvent | undefined;
machineProductionEvent: ProductionEvent | undefined;
hasActiveEvents: boolean;
+ isTrackedActivity: boolean;
+ trackedEntityId: string | undefined;
}) {
+ console.log(isTrackedActivity);
const fetcher = useFetcher<ProductionEvent>();
const isActive = useMemo(() => {
if (fetcher.formData?.get("action") === "End") {
@@ -2334,6 +2372,9 @@ function StartStopButton({
fetcher={fetcher}
>
<Hidden name="id" value={id} />
+ {isTrackedActivity && (
+ <Hidden name="trackedEntityId" value={trackedEntityId} />
+ )}
<Hidden name="jobOperationId" value={operation.id} />
<Hidden name="timezone" />
<Hidden
@@ -2445,7 +2486,9 @@ function QuantityModal({
return (
parentIsSerial &&
materials.some(
- (material) => material.jobOperationId === operation.id && (material?.quantityIssued ?? 0) < material.quantity
+ (material) =>
+ material.jobOperationId === operation.id &&
+ (material?.quantityIssued ?? 0) < material.quantity
)
);
}, [materials, parentIsSerial, operation.id]);
@@ -2589,7 +2632,7 @@ function SerialSelectorModal({
onSelect: (entity: TrackedEntity) => void;
}) {
const [serial, setSerial] = useState("");
-
+
return (
<Modal
open
@@ -2607,7 +2650,7 @@ function SerialSelectorModal({
</ModalDescription>
</ModalHeader>
<ModalBody>
- <Tabs defaultValue="scan">
+ <Tabs defaultValue="scan">
<TabsList className="grid w-full grid-cols-2 mb-4">
<TabsTrigger value="scan">
<LuQrCode className="mr-2" />
@@ -2628,13 +2671,15 @@ function SerialSelectorModal({
) : (
availableEntities.map((entity) => {
return (
- <HStack key={entity.id} className="w-full justify-between p-4 border rounded-md">
+ <HStack
+ key={entity.id}
+ className="w-full justify-between p-4 border rounded-md"
+ >
<VStack spacing={1} className="w-full items-start">
<p className="text-sm">{entity.id}</p>
-
</VStack>
- <Button
- size="sm"
+ <Button
+ size="sm"
variant="secondary"
onClick={() => onSelect(entity)}
>
@@ -2650,13 +2695,13 @@ function SerialSelectorModal({
<TabsContent value="scan" className="mt-4">
<VStack spacing={4}>
<InputGroup>
- <Input
+ <Input
autoFocus
- placeholder="Scan or enter serial number"
+ placeholder="Scan or enter serial number"
onKeyDown={(e) => {
- if (e.key === 'Enter') {
+ if (e.key === "Enter") {
const entity = availableEntities.find(
- entity => entity.id === e.currentTarget.value
+ (entity) => entity.id === e.currentTarget.value
);
if (entity) {
onSelect(entity);
@@ -2667,17 +2712,16 @@ function SerialSelectorModal({
onChange={(e) => setSerial(e.target.value)}
/>
<InputRightElement>
- {serial && (
- availableEntities.some(entity => entity.id === serial) ? (
+ {serial &&
+ (availableEntities.some(
+ (entity) => entity.id === serial
+ ) ? (
<LuCheck className="text-green-500" />
) : (
<LuX className="text-red-500" />
- )
- )}
-
+ ))}
</InputRightElement>
</InputGroup>
-
</VStack>
</TabsContent>
</Tabs>
@@ -2690,7 +2734,6 @@ function SerialSelectorModal({
</ModalContent>
</Modal>
);
-
}
function SerialIssueModal({
@@ -3913,6 +3956,10 @@ function RecordModal({
}
}, [fetcher.data?.success, onClose]);
+ const [booleanControlled, setBooleanControlled] = useState(
+ attribute?.jobOperationAttributeRecord?.booleanValue ?? false
+ );
+
return (
<Modal
open
@@ -3936,8 +3983,6 @@ function RecordModal({
numericValue:
attribute?.jobOperationAttributeRecord?.numericValue ?? 0,
userValue: attribute?.jobOperationAttributeRecord?.userValue ?? "",
- booleanValue:
- attribute?.jobOperationAttributeRecord?.booleanValue ?? false,
}}
fetcher={fetcher}
>
@@ -3947,6 +3992,12 @@ function RecordModal({
</ModalHeader>
<ModalBody>
<Hidden name="jobOperationAttributeId" />
+ {attribute.type === "Checkbox" && (
+ <Hidden
+ name="booleanValue"
+ value={booleanControlled ? "true" : "false"}
+ />
+ )}
{attribute.type === "File" && (
<Hidden name="value" value={filePath ?? ""} />
)}
@@ -3961,7 +4012,10 @@ function RecordModal({
<DateTimePicker name="value" label="" />
)}
{attribute.type === "Checkbox" && (
- <Boolean name="booleanValue" label="" />
+ <Switch
+ checked={booleanControlled}
+ onCheckedChange={(checked) => setBooleanControlled(!!checked)}
+ />
)}
{attribute.type === "Person" && (
<Combobox name="userValue" label="" options={employeeOptions} />
diff --git a/apps/mes/app/routes/x+/event.tsx b/apps/mes/app/routes/x+/event.tsx
index 1b5c52dc5a..1c58d77360 100644
--- a/apps/mes/app/routes/x+/event.tsx
+++ b/apps/mes/app/routes/x+/event.tsx
@@ -34,17 +34,22 @@ export async function action({ request }: ActionFunctionArgs) {
action: productionAction,
timezone,
hasActiveEvents,
+ trackedEntityId,
...data
} = validation.data;
if (productionAction === "Start") {
- const startEvent = await startProductionEvent(client, {
- ...data,
- startTime: now(timezone ?? getLocalTimeZone()).toAbsoluteString(),
- employeeId: userId,
- companyId,
- createdBy: userId,
- });
+ const startEvent = await startProductionEvent(
+ client,
+ {
+ ...data,
+ startTime: now(timezone ?? getLocalTimeZone()).toAbsoluteString(),
+ employeeId: userId,
+ companyId,
+ createdBy: userId,
+ },
+ trackedEntityId
+ );
if (startEvent.error) {
return json(
diff --git a/apps/mes/app/services/models.ts b/apps/mes/app/services/models.ts
index aa2a102ed3..c23348f6bf 100644
--- a/apps/mes/app/services/models.ts
+++ b/apps/mes/app/services/models.ts
@@ -40,31 +40,15 @@ export const jobOperationStatus = [
"Canceled",
] as const;
-export const attributeRecordValidator = z
- .object({
- jobOperationAttributeId: z.string(),
- value: zfd.text(z.string().optional()),
- numericValue: zfd.numeric(z.number().optional()),
- booleanValue: zfd.checkbox().optional(),
- userValue: zfd.text(z.string().optional()),
- })
- .refine(
- (data) => {
- if (
- data.value === undefined &&
- data.numericValue === undefined &&
- data.booleanValue === undefined &&
- data.userValue === undefined
- ) {
- return false;
- }
- return true;
- },
- {
- path: ["value", "numericValue"],
- message: "Value is required",
- }
- );
+export const attributeRecordValidator = z.object({
+ jobOperationAttributeId: z.string(),
+ value: zfd.text(z.string().optional()),
+ numericValue: zfd.numeric(z.number().optional()),
+ booleanValue: zfd
+ .text(z.enum(["true", "false"]).transform((val) => val === "true"))
+ .optional(),
+ userValue: zfd.text(z.string().optional()),
+});
export const issueValidator = z.object({
itemId: z.string().min(1, { message: "Item is required" }),
@@ -106,6 +90,7 @@ export const productionEventValidator = z.object({
}),
workCenterId: zfd.text(z.string().optional()),
hasActiveEvents: z.enum(["true", "false"]),
+ trackedEntityId: zfd.text(z.string().optional()),
});
export const finishValidator = z.object({
diff --git a/apps/mes/app/services/operations.service.ts b/apps/mes/app/services/operations.service.ts
index 28830af561..1fe6e59d79 100644
--- a/apps/mes/app/services/operations.service.ts
+++ b/apps/mes/app/services/operations.service.ts
@@ -9,12 +9,9 @@ import type {
productionEventValidator,
scrapQuantityValidator,
} from "./models";
-import type {
- BaseOperationWithDetails,
- Job,
- StorageItem,
-} from "./types";
+import type { BaseOperationWithDetails, Job, StorageItem } from "./types";
import { TrackedActivityAttributes } from "@carbon/utils";
+import { nanoid } from "nanoid";
export async function deleteAttributeRecord(
client: SupabaseClient<Database>,
@@ -263,7 +260,8 @@ export async function getJobMaterialsByOperationId(
return (
materials.data?.map((material) => {
- if (!material.requiresSerialTracking) return material;
+ if (!material.requiresSerialTracking && !material.requiresBatchTracking)
+ return material;
const issuedForTrackedParent =
trackedInputs.data
?.filter(
@@ -580,7 +578,66 @@ export async function startProductionEvent(
employeeId: string;
companyId: string;
createdBy: string;
+ },
+ trackedEntityId: string | undefined
+) {
+ if (trackedEntityId) {
+ const activityId = nanoid();
+
+ const [eventInsert, operation] = await Promise.all([
+ client.from("productionEvent").insert(data).select("id").single(),
+ client
+ .from("jobOperation")
+ .select("*")
+ .eq("id", data.jobOperationId)
+ .single(),
+ ]);
+
+ if (eventInsert.error) return eventInsert;
+ if (operation.error) return operation;
+
+ const trackedActivityInsert = await client
+ .from("trackedActivity")
+ .insert({
+ id: activityId,
+ type: `${operation.data?.description} (${data.type})`,
+ sourceDocument: "Production Event",
+ sourceDocumentId: eventInsert.data?.id,
+ attributes: {
+ "Production Event": eventInsert.data?.id,
+ "Work Center": data.workCenterId,
+ "Job Operation": data.jobOperationId,
+ Employee: data.employeeId,
+ },
+ companyId: data.companyId,
+ createdBy: data.createdBy,
+ })
+ .select("id")
+ .single();
+
+ if (trackedActivityInsert.error) {
+ console.error(trackedActivityInsert.error);
+ return trackedActivityInsert;
+ }
+
+ const trackedActivityOutputInsert = await client
+ .from("trackedActivityOutput")
+ .insert({
+ trackedActivityId: activityId,
+ trackedEntityId,
+ quantity: 1,
+ companyId: data.companyId,
+ createdBy: data.createdBy,
+ entityType: "Production Event",
+ });
+
+ if (trackedActivityOutputInsert.error) {
+ console.error(trackedActivityOutputInsert.error);
+ return trackedActivityOutputInsert;
+ }
+
+ return eventInsert;
}
-) {
+
return client.from("productionEvent").insert(data).select("*");
}
diff --git a/package-lock.json b/package-lock.json
index 42f336245b..c60686b9e4 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -71,10 +71,12 @@
"@trigger.dev/sdk": "3.3.12",
"@vercel/analytics": "^1.2.2",
"@vercel/remix": "2.11.2",
+ "@visx/responsive": "^2.1.0",
"ai": "3.4.9",
"assert-never": "^1.2.1",
"clsx": "^2.1.0",
"cookie": "^0.6.0",
+ "d3": "^7.8.5",
"d3-array": "^3.2.4",
"framer-motion": "^11.1.7",
"isbot": "3.6.13",
@@ -110,6 +112,7 @@
"@carbon/tailwind": "*",
"@carbon/tsconfig": "*",
"@trigger.dev/build": "3.3.12",
+ "@types/d3": "^7.4.0",
"@types/nprogress": "^0.2.0",
"@types/papaparse": "^5.3.14",
"@types/react": "^18.2.74",
@@ -10980,21 +10983,99 @@
"resolved": "https://registry.npmjs.org/@types/cookie/-/cookie-0.6.0.tgz",
"integrity": "sha512-4Kh9a6B2bQciAhf7FSuMRRkUWecJgJu9nPnx3yzpsfXX/c50REIqpHY4C82bXP90qrLtXtkDxTZosYO3UpOwlA=="
},
+ "node_modules/@types/d3": {
+ "version": "7.4.3",
+ "resolved": "https://registry.npmjs.org/@types/d3/-/d3-7.4.3.tgz",
+ "integrity": "sha512-lZXZ9ckh5R8uiFVt8ogUNf+pIrK4EsWrx2Np75WvF/eTpJ0FMHNhjXk8CKEx/+gpHbNQyJWehbFaTvqmHWB3ww==",
+ "dev": true,
+ "dependencies": {
+ "@types/d3-array": "*",
+ "@types/d3-axis": "*",
+ "@types/d3-brush": "*",
+ "@types/d3-chord": "*",
+ "@types/d3-color": "*",
+ "@types/d3-contour": "*",
+ "@types/d3-delaunay": "*",
+ "@types/d3-dispatch": "*",
+ "@types/d3-drag": "*",
+ "@types/d3-dsv": "*",
+ "@types/d3-ease": "*",
+ "@types/d3-fetch": "*",
+ "@types/d3-force": "*",
+ "@types/d3-format": "*",
+ "@types/d3-geo": "*",
+ "@types/d3-hierarchy": "*",
+ "@types/d3-interpolate": "*",
+ "@types/d3-path": "*",
+ "@types/d3-polygon": "*",
+ "@types/d3-quadtree": "*",
+ "@types/d3-random": "*",
+ "@types/d3-scale": "*",
+ "@types/d3-scale-chromatic": "*",
+ "@types/d3-selection": "*",
+ "@types/d3-shape": "*",
+ "@types/d3-time": "*",
+ "@types/d3-time-format": "*",
+ "@types/d3-timer": "*",
+ "@types/d3-transition": "*",
+ "@types/d3-zoom": "*"
+ }
+ },
"node_modules/@types/d3-array": {
"version": "3.2.1",
"resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.2.1.tgz",
"integrity": "sha512-Y2Jn2idRrLzUfAKV2LyRImR+y4oa2AntrgID95SHJxuMUrkNXmanDSed71sRNZysveJVt1hLLemQZIady0FpEg=="
},
+ "node_modules/@types/d3-axis": {
+ "version": "3.0.6",
+ "resolved": "https://registry.npmjs.org/@types/d3-axis/-/d3-axis-3.0.6.tgz",
+ "integrity": "sha512-pYeijfZuBd87T0hGn0FO1vQ/cgLk6E1ALJjfkC0oJ8cbwkZl3TpgS8bVBLZN+2jjGgg38epgxb2zmoGtSfvgMw==",
+ "dev": true,
+ "dependencies": {
+ "@types/d3-selection": "*"
+ }
+ },
+ "node_modules/@types/d3-brush": {
+ "version": "3.0.6",
+ "resolved": "https://registry.npmjs.org/@types/d3-brush/-/d3-brush-3.0.6.tgz",
+ "integrity": "sha512-nH60IZNNxEcrh6L1ZSMNA28rj27ut/2ZmI3r96Zd+1jrZD++zD3LsMIjWlvg4AYrHn/Pqz4CF3veCxGjtbqt7A==",
+ "dev": true,
+ "dependencies": {
+ "@types/d3-selection": "*"
+ }
+ },
+ "node_modules/@types/d3-chord": {
+ "version": "3.0.6",
+ "resolved": "https://registry.npmjs.org/@types/d3-chord/-/d3-chord-3.0.6.tgz",
+ "integrity": "sha512-LFYWWd8nwfwEmTZG9PfQxd17HbNPksHBiJHaKuY1XeqscXacsS2tyoo6OdRsjf+NQYeB6XrNL3a25E3gH69lcg==",
+ "dev": true
+ },
"node_modules/@types/d3-color": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/@types/d3-color/-/d3-color-3.1.3.tgz",
"integrity": "sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A=="
},
+ "node_modules/@types/d3-contour": {
+ "version": "3.0.6",
+ "resolved": "https://registry.npmjs.org/@types/d3-contour/-/d3-contour-3.0.6.tgz",
+ "integrity": "sha512-BjzLgXGnCWjUSYGfH1cpdo41/hgdWETu4YxpezoztawmqsvCeep+8QGfiY6YbDvfgHz/DkjeIkkZVJavB4a3rg==",
+ "dev": true,
+ "dependencies": {
+ "@types/d3-array": "*",
+ "@types/geojson": "*"
+ }
+ },
"node_modules/@types/d3-delaunay": {
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/@types/d3-delaunay/-/d3-delaunay-6.0.1.tgz",
"integrity": "sha512-tLxQ2sfT0p6sxdG75c6f/ekqxjyYR0+LwPrsO1mbC9YDBzPJhs2HbJJRrn8Ez1DBoHRo2yx7YEATI+8V1nGMnQ=="
},
+ "node_modules/@types/d3-dispatch": {
+ "version": "3.0.6",
+ "resolved": "https://registry.npmjs.org/@types/d3-dispatch/-/d3-dispatch-3.0.6.tgz",
+ "integrity": "sha512-4fvZhzMeeuBJYZXRXrRIQnvUYfyXwYmLsdiN7XXmVNQKKw1cM8a5WdID0g1hVFZDqT9ZqZEY5pD44p24VS7iZQ==",
+ "dev": true
+ },
"node_modules/@types/d3-drag": {
"version": "3.0.7",
"resolved": "https://registry.npmjs.org/@types/d3-drag/-/d3-drag-3.0.7.tgz",
@@ -11003,11 +11084,32 @@
"@types/d3-selection": "*"
}
},
+ "node_modules/@types/d3-dsv": {
+ "version": "3.0.7",
+ "resolved": "https://registry.npmjs.org/@types/d3-dsv/-/d3-dsv-3.0.7.tgz",
+ "integrity": "sha512-n6QBF9/+XASqcKK6waudgL0pf/S5XHPPI8APyMLLUHd8NqouBGLsU8MgtO7NINGtPBtk9Kko/W4ea0oAspwh9g==",
+ "dev": true
+ },
"node_modules/@types/d3-ease": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/@types/d3-ease/-/d3-ease-3.0.2.tgz",
"integrity": "sha512-NcV1JjO5oDzoK26oMzbILE6HW7uVXOHLQvHshBUW4UMdZGfiY6v5BeQwh9a9tCzv+CeefZQHJt5SRgK154RtiA=="
},
+ "node_modules/@types/d3-fetch": {
+ "version": "3.0.7",
+ "resolved": "https://registry.npmjs.org/@types/d3-fetch/-/d3-fetch-3.0.7.tgz",
+ "integrity": "sha512-fTAfNmxSb9SOWNB9IoG5c8Hg6R+AzUHDRlsXsDZsNp6sxAEOP0tkP3gKkNSO/qmHPoBFTxNrjDprVHDQDvo5aA==",
+ "dev": true,
+ "dependencies": {
+ "@types/d3-dsv": "*"
+ }
+ },
+ "node_modules/@types/d3-force": {
+ "version": "3.0.10",
+ "resolved": "https://registry.npmjs.org/@types/d3-force/-/d3-force-3.0.10.tgz",
+ "integrity": "sha512-ZYeSaCF3p73RdOKcjj+swRlZfnYpK1EbaDiYICEEp5Q6sUiqFaFQ9qgoshp5CzIyyb/yD09kD9o2zEltCexlgw==",
+ "dev": true
+ },
"node_modules/@types/d3-format": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/@types/d3-format/-/d3-format-3.0.1.tgz",
@@ -11021,6 +11123,12 @@
"@types/geojson": "*"
}
},
+ "node_modules/@types/d3-hierarchy": {
+ "version": "3.1.7",
+ "resolved": "https://registry.npmjs.org/@types/d3-hierarchy/-/d3-hierarchy-3.1.7.tgz",
+ "integrity": "sha512-tJFtNoYBtRtkNysX1Xq4sxtjK8YgoWUNpIiUee0/jHGRwqvzYxkq0hGVbbOGSz+JgFxxRu4K8nb3YpG3CMARtg==",
+ "dev": true
+ },
"node_modules/@types/d3-interpolate": {
"version": "3.0.4",
"resolved": "https://registry.npmjs.org/@types/d3-interpolate/-/d3-interpolate-3.0.4.tgz",
@@ -11034,6 +11142,24 @@
"resolved": "https://registry.npmjs.org/@types/d3-path/-/d3-path-3.1.0.tgz",
"integrity": "sha512-P2dlU/q51fkOc/Gfl3Ul9kicV7l+ra934qBFXCFhrZMOL6du1TM0pm1ThYvENukyOn5h9v+yMJ9Fn5JK4QozrQ=="
},
+ "node_modules/@types/d3-polygon": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/@types/d3-polygon/-/d3-polygon-3.0.2.tgz",
+ "integrity": "sha512-ZuWOtMaHCkN9xoeEMr1ubW2nGWsp4nIql+OPQRstu4ypeZ+zk3YKqQT0CXVe/PYqrKpZAi+J9mTs05TKwjXSRA==",
+ "dev": true
+ },
+ "node_modules/@types/d3-quadtree": {
+ "version": "3.0.6",
+ "resolved": "https://registry.npmjs.org/@types/d3-quadtree/-/d3-quadtree-3.0.6.tgz",
+ "integrity": "sha512-oUzyO1/Zm6rsxKRHA1vH0NEDG58HrT5icx/azi9MF1TWdtttWl0UIUsjEQBBh+SIkrpd21ZjEv7ptxWys1ncsg==",
+ "dev": true
+ },
+ "node_modules/@types/d3-random": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/@types/d3-random/-/d3-random-3.0.3.tgz",
+ "integrity": "sha512-Imagg1vJ3y76Y2ea0871wpabqp613+8/r0mCLEBfdtqC7xMSfj9idOnmBYyMoULfHePJyxMAw3nWhJxzc+LFwQ==",
+ "dev": true
+ },
"node_modules/@types/d3-scale": {
"version": "4.0.8",
"resolved": "https://registry.npmjs.org/@types/d3-scale/-/d3-scale-4.0.8.tgz",
@@ -11042,6 +11168,12 @@
"@types/d3-time": "*"
}
},
+ "node_modules/@types/d3-scale-chromatic": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/@types/d3-scale-chromatic/-/d3-scale-chromatic-3.1.0.tgz",
+ "integrity": "sha512-iWMJgwkK7yTRmWqRB5plb1kadXyQ5Sj8V/zYlFGMUBbIPKQScw+Dku9cAAMgJG+z5GYDoMjWGLVOvjghDEFnKQ==",
+ "dev": true
+ },
"node_modules/@types/d3-selection": {
"version": "3.0.11",
"resolved": "https://registry.npmjs.org/@types/d3-selection/-/d3-selection-3.0.11.tgz",
@@ -15358,6 +15490,46 @@
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.3.tgz",
"integrity": "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw=="
},
+ "node_modules/d3": {
+ "version": "7.9.0",
+ "resolved": "https://registry.npmjs.org/d3/-/d3-7.9.0.tgz",
+ "integrity": "sha512-e1U46jVP+w7Iut8Jt8ri1YsPOvFpg46k+K8TpCb0P+zjCkjkPnV7WzfDJzMHy1LnA+wj5pLT1wjO901gLXeEhA==",
+ "dependencies": {
+ "d3-array": "3",
+ "d3-axis": "3",
+ "d3-brush": "3",
+ "d3-chord": "3",
+ "d3-color": "3",
+ "d3-contour": "4",
+ "d3-delaunay": "6",
+ "d3-dispatch": "3",
+ "d3-drag": "3",
+ "d3-dsv": "3",
+ "d3-ease": "3",
+ "d3-fetch": "3",
+ "d3-force": "3",
+ "d3-format": "3",
+ "d3-geo": "3",
+ "d3-hierarchy": "3",
+ "d3-interpolate": "3",
+ "d3-path": "3",
+ "d3-polygon": "3",
+ "d3-quadtree": "3",
+ "d3-random": "3",
+ "d3-scale": "4",
+ "d3-scale-chromatic": "3",
+ "d3-selection": "3",
+ "d3-shape": "3",
+ "d3-time": "3",
+ "d3-time-format": "4",
+ "d3-timer": "3",
+ "d3-transition": "3",
+ "d3-zoom": "3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
"node_modules/d3-array": {
"version": "3.2.4",
"resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.4.tgz",
@@ -15369,6 +15541,40 @@
"node": ">=12"
}
},
+ "node_modules/d3-axis": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/d3-axis/-/d3-axis-3.0.0.tgz",
+ "integrity": "sha512-IH5tgjV4jE/GhHkRV0HiVYPDtvfjHQlQfJHs0usq7M30XcSBvOotpmH1IgkcXsO/5gEQZD43B//fc7SRT5S+xw==",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-brush": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/d3-brush/-/d3-brush-3.0.0.tgz",
+ "integrity": "sha512-ALnjWlVYkXsVIGlOsuWH1+3udkYFI48Ljihfnh8FZPF2QS9o+PzGLBslO0PjzVoHLZ2KCVgAM8NVkXPJB2aNnQ==",
+ "dependencies": {
+ "d3-dispatch": "1 - 3",
+ "d3-drag": "2 - 3",
+ "d3-interpolate": "1 - 3",
+ "d3-selection": "3",
+ "d3-transition": "3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-chord": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/d3-chord/-/d3-chord-3.0.1.tgz",
+ "integrity": "sha512-VE5S6TNa+j8msksl7HwjxMHDM2yNK3XCkusIlpX5kwauBfXuyLAtNg9jCp/iHH61tgI4sb6R/EIMWCqEIdjT/g==",
+ "dependencies": {
+ "d3-path": "1 - 3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
"node_modules/d3-color": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/d3-color/-/d3-color-3.1.0.tgz",
@@ -15377,6 +15583,17 @@
"node": ">=12"
}
},
+ "node_modules/d3-contour": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/d3-contour/-/d3-contour-4.0.2.tgz",
+ "integrity": "sha512-4EzFTRIikzs47RGmdxbeUvLWtGedDUNkTcmzoeyg4sP/dvCexO47AaQL7VKy/gul85TOxw+IBgA8US2xwbToNA==",
+ "dependencies": {
+ "d3-array": "^3.2.0"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
"node_modules/d3-delaunay": {
"version": "6.0.2",
"resolved": "https://registry.npmjs.org/d3-delaunay/-/d3-delaunay-6.0.2.tgz",
@@ -15408,6 +15625,49 @@
"node": ">=12"
}
},
+ "node_modules/d3-dsv": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/d3-dsv/-/d3-dsv-3.0.1.tgz",
+ "integrity": "sha512-UG6OvdI5afDIFP9w4G0mNq50dSOsXHJaRE8arAS5o9ApWnIElp8GZw1Dun8vP8OyHOZ/QJUKUJwxiiCCnUwm+Q==",
+ "dependencies": {
+ "commander": "7",
+ "iconv-lite": "0.6",
+ "rw": "1"
+ },
+ "bin": {
+ "csv2json": "bin/dsv2json.js",
+ "csv2tsv": "bin/dsv2dsv.js",
+ "dsv2dsv": "bin/dsv2dsv.js",
+ "dsv2json": "bin/dsv2json.js",
+ "json2csv": "bin/json2dsv.js",
+ "json2dsv": "bin/json2dsv.js",
+ "json2tsv": "bin/json2dsv.js",
+ "tsv2csv": "bin/dsv2dsv.js",
+ "tsv2json": "bin/dsv2json.js"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-dsv/node_modules/commander": {
+ "version": "7.2.0",
+ "resolved": "https://registry.npmjs.org/commander/-/commander-7.2.0.tgz",
+ "integrity": "sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw==",
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/d3-dsv/node_modules/iconv-lite": {
+ "version": "0.6.3",
+ "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz",
+ "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==",
+ "dependencies": {
+ "safer-buffer": ">= 2.1.2 < 3.0.0"
+ },
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
"node_modules/d3-ease": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/d3-ease/-/d3-ease-3.0.1.tgz",
@@ -15416,6 +15676,30 @@
"node": ">=12"
}
},
+ "node_modules/d3-fetch": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/d3-fetch/-/d3-fetch-3.0.1.tgz",
+ "integrity": "sha512-kpkQIM20n3oLVBKGg6oHrUchHM3xODkTzjMoj7aWQFq5QEM+R6E4WkzT5+tojDY7yjez8KgCBRoj4aEr99Fdqw==",
+ "dependencies": {
+ "d3-dsv": "1 - 3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-force": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/d3-force/-/d3-force-3.0.0.tgz",
+ "integrity": "sha512-zxV/SsA+U4yte8051P4ECydjD/S+qeYtnaIyAs9tgHCqfguma/aAQDjo85A9Z6EKhBirHRJHXIgJUlffT4wdLg==",
+ "dependencies": {
+ "d3-dispatch": "1 - 3",
+ "d3-quadtree": "1 - 3",
+ "d3-timer": "1 - 3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
"node_modules/d3-format": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/d3-format/-/d3-format-3.1.0.tgz",
@@ -15435,6 +15719,14 @@
"node": ">=12"
}
},
+ "node_modules/d3-hierarchy": {
+ "version": "3.1.2",
+ "resolved": "https://registry.npmjs.org/d3-hierarchy/-/d3-hierarchy-3.1.2.tgz",
+ "integrity": "sha512-FX/9frcub54beBdugHjDCdikxThEqjnR93Qt7PvQTOHxyiNCAlvMrHhclk3cD5VeAaq9fxmfRp+CnWw9rEMBuA==",
+ "engines": {
+ "node": ">=12"
+ }
+ },
"node_modules/d3-interpolate": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-3.0.1.tgz",
@@ -15454,6 +15746,30 @@
"node": ">=12"
}
},
+ "node_modules/d3-polygon": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/d3-polygon/-/d3-polygon-3.0.1.tgz",
+ "integrity": "sha512-3vbA7vXYwfe1SYhED++fPUQlWSYTTGmFmQiany/gdbiWgU/iEyQzyymwL9SkJjFFuCS4902BSzewVGsHHmHtXg==",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-quadtree": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/d3-quadtree/-/d3-quadtree-3.0.1.tgz",
+ "integrity": "sha512-04xDrxQTDTCFwP5H6hRhsRcb9xxv2RzkcsygFzmkSIOJy3PeRJP7sNk3VRIbKXcog561P9oU0/rVH6vDROAgUw==",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-random": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/d3-random/-/d3-random-3.0.1.tgz",
+ "integrity": "sha512-FXMe9GfxTxqd5D6jFsQ+DJ8BJS4E/fT5mqqdjovykEB2oFbTMDVdg1MGFxfQW+FBOGoB++k8swBrgwSHT1cUXQ==",
+ "engines": {
+ "node": ">=12"
+ }
+ },
"node_modules/d3-scale": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/d3-scale/-/d3-scale-4.0.2.tgz",
@@ -15469,6 +15785,18 @@
"node": ">=12"
}
},
+ "node_modules/d3-scale-chromatic": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/d3-scale-chromatic/-/d3-scale-chromatic-3.1.0.tgz",
+ "integrity": "sha512-A3s5PWiZ9YCXFye1o246KoscMWqf8BsD9eRiJ3He7C9OBaxKhAd5TFCdEx/7VbKtxxTsu//1mMJFrEt572cEyQ==",
+ "dependencies": {
+ "d3-color": "1 - 3",
+ "d3-interpolate": "1 - 3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
"node_modules/d3-selection": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/d3-selection/-/d3-selection-3.0.0.tgz",
@@ -29329,6 +29657,11 @@
"resolved": "https://registry.npmjs.org/rusha/-/rusha-0.8.14.tgz",
"integrity": "sha512-cLgakCUf6PedEu15t8kbsjnwIFFR2D4RfL+W3iWFJ4iac7z4B0ZI8fxy4R3J956kAI68HclCFGL8MPoUVC3qVA=="
},
+ "node_modules/rw": {
+ "version": "1.3.3",
+ "resolved": "https://registry.npmjs.org/rw/-/rw-1.3.3.tgz",
+ "integrity": "sha512-PdhdWy89SiZogBLaw42zdeqtRJ//zFd2PgQavcICDUgJT5oW10QCRKbJ6bg4r0/UY2M6BWd5tkxuGFRvCkgfHQ=="
+ },
"node_modules/rxjs": {
"version": "7.8.1",
"resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.1.tgz",
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 7209572834..0f19378887 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -30368,14 +30368,14 @@ export type Database = {
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["id"]
+ columns: ["supplierLocationId"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["supplierLocationId"]
+ columns: ["id"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
@@ -31672,14 +31672,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -33330,14 +33330,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["paymentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["paymentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -35738,16 +35738,52 @@ export type Database = {
}
Returns: string[]
}
+ get_direct_ancestors_of_tracked_entity: {
+ Args: {
+ p_tracked_entity_id: string
+ }
+ Returns: {
+ trackedActivityId: string
+ id: string
+ quantity: number
+ status: Database["public"]["Enums"]["trackedEntityStatus"]
+ sourceDocument: string
+ sourceDocumentId: string
+ sourceDocumentReadableId: string
+ activityAttributes: Json
+ attributes: Json
+ }[]
+ }
+ get_direct_ancestors_of_tracked_entity_strict: {
+ Args: {
+ p_tracked_entity_id: string
+ }
+ Returns: {
+ trackedActivityId: string
+ id: string
+ quantity: number
+ status: Database["public"]["Enums"]["trackedEntityStatus"]
+ sourceDocument: string
+ sourceDocumentId: string
+ sourceDocumentReadableId: string
+ activityAttributes: Json
+ attributes: Json
+ }[]
+ }
get_direct_descendants_of_tracked_entity: {
Args: {
p_tracked_entity_id: string
}
Returns: {
- trackedEntityId: string
+ trackedActivityId: string
+ id: string
quantity: number
status: Database["public"]["Enums"]["trackedEntityStatus"]
+ sourceDocument: string
+ sourceDocumentId: string
+ sourceDocumentReadableId: string
activityAttributes: Json
- entityAttributes: Json
+ attributes: Json
}[]
}
get_direct_descendants_of_tracked_entity_strict: {
@@ -35755,11 +35791,15 @@ export type Database = {
p_tracked_entity_id: string
}
Returns: {
- trackedEntityId: string
+ trackedActivityId: string
+ id: string
quantity: number
status: Database["public"]["Enums"]["trackedEntityStatus"]
+ sourceDocument: string
+ sourceDocumentId: string
+ sourceDocumentReadableId: string
activityAttributes: Json
- entityAttributes: Json
+ attributes: Json
}[]
}
get_inventory_quantities: {
diff --git a/packages/database/supabase/functions/issue/index.ts b/packages/database/supabase/functions/issue/index.ts
index 0adce498a4..80d3605e0b 100644
--- a/packages/database/supabase/functions/issue/index.ts
+++ b/packages/database/supabase/functions/issue/index.ts
@@ -287,9 +287,9 @@ serve(async (req: Request) => {
const relatedTrackedEntities = trackedEntities.data.filter(
(trackedEntity) =>
- `Operation ${row.jobOperationId}` in (trackedEntity.attributes as TrackedEntityAttributes)
+ `Operation ${row.jobOperationId}` in
+ (trackedEntity.attributes as TrackedEntityAttributes)
);
-
let newEntityId: string | undefined;
await db.transaction().execute(async (trx) => {
@@ -314,33 +314,33 @@ serve(async (req: Request) => {
}
if (trackedEntity.status !== "Consumed") {
- const activityId = nanoid();
- await trx
- .insertInto("trackedActivity")
- .values({
- id: activityId,
- type: "Complete",
- sourceDocument: "Job Operation",
- sourceDocumentId: row.jobOperationId,
- attributes: {
- "Job Operation": row.jobOperationId,
- Employee: userId,
- },
- companyId,
- createdBy: userId,
- })
- .execute();
-
- await trx
- .insertInto("trackedActivityOutput")
- .values({
- trackedActivityId: activityId,
- trackedEntityId: trackedEntityId,
- quantity: 1,
- companyId,
- createdBy: userId,
- })
- .execute();
+ // const activityId = nanoid();
+ // await trx
+ // .insertInto("trackedActivity")
+ // .values({
+ // id: activityId,
+ // type: "Complete",
+ // sourceDocument: "Job Operation",
+ // sourceDocumentId: row.jobOperationId,
+ // attributes: {
+ // "Job Operation": row.jobOperationId,
+ // Employee: userId,
+ // },
+ // companyId,
+ // createdBy: userId,
+ // })
+ // .execute();
+
+ // await trx
+ // .insertInto("trackedActivityOutput")
+ // .values({
+ // trackedActivityId: activityId,
+ // trackedEntityId: trackedEntityId,
+ // quantity: 1,
+ // companyId,
+ // createdBy: userId,
+ // })
+ // .execute();
// Update the current trackedEntity to Complete
await trx
.updateTable("trackedEntity")
@@ -704,6 +704,7 @@ serve(async (req: Request) => {
"Original Quantity": Number(trackedEntity.quantity),
"Consumed Quantity": quantity,
"Remaining Quantity": remainingQuantity,
+ "Split Entity ID": newTrackedEntityId,
},
companyId,
createdBy: userId,
@@ -751,7 +752,7 @@ serve(async (req: Request) => {
"Split Entity ID": newTrackedEntityId,
},
})
- .where("id", "=", parentTrackedEntityId)
+ .where("id", "=", trackedEntityId)
.execute();
// Record outputs from split
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 7209572834..0f19378887 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -30368,14 +30368,14 @@ export type Database = {
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["id"]
+ columns: ["supplierLocationId"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["supplierLocationId"]
+ columns: ["id"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
@@ -31672,14 +31672,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -33330,14 +33330,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["paymentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["paymentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -35738,16 +35738,52 @@ export type Database = {
}
Returns: string[]
}
+ get_direct_ancestors_of_tracked_entity: {
+ Args: {
+ p_tracked_entity_id: string
+ }
+ Returns: {
+ trackedActivityId: string
+ id: string
+ quantity: number
+ status: Database["public"]["Enums"]["trackedEntityStatus"]
+ sourceDocument: string
+ sourceDocumentId: string
+ sourceDocumentReadableId: string
+ activityAttributes: Json
+ attributes: Json
+ }[]
+ }
+ get_direct_ancestors_of_tracked_entity_strict: {
+ Args: {
+ p_tracked_entity_id: string
+ }
+ Returns: {
+ trackedActivityId: string
+ id: string
+ quantity: number
+ status: Database["public"]["Enums"]["trackedEntityStatus"]
+ sourceDocument: string
+ sourceDocumentId: string
+ sourceDocumentReadableId: string
+ activityAttributes: Json
+ attributes: Json
+ }[]
+ }
get_direct_descendants_of_tracked_entity: {
Args: {
p_tracked_entity_id: string
}
Returns: {
- trackedEntityId: string
+ trackedActivityId: string
+ id: string
quantity: number
status: Database["public"]["Enums"]["trackedEntityStatus"]
+ sourceDocument: string
+ sourceDocumentId: string
+ sourceDocumentReadableId: string
activityAttributes: Json
- entityAttributes: Json
+ attributes: Json
}[]
}
get_direct_descendants_of_tracked_entity_strict: {
@@ -35755,11 +35791,15 @@ export type Database = {
p_tracked_entity_id: string
}
Returns: {
- trackedEntityId: string
+ trackedActivityId: string
+ id: string
quantity: number
status: Database["public"]["Enums"]["trackedEntityStatus"]
+ sourceDocument: string
+ sourceDocumentId: string
+ sourceDocumentReadableId: string
activityAttributes: Json
- entityAttributes: Json
+ attributes: Json
}[]
}
get_inventory_quantities: {
diff --git a/packages/database/supabase/migrations/20250301125444_tracked-materials.sql b/packages/database/supabase/migrations/20250301125444_tracked-materials.sql
index 28e7d106b8..e9f6a11410 100644
--- a/packages/database/supabase/migrations/20250301125444_tracked-materials.sql
+++ b/packages/database/supabase/migrations/20250301125444_tracked-materials.sql
@@ -331,20 +331,28 @@ EXECUTE FUNCTION delete_tracked_entity_on_job_make_method_delete();
DROP FUNCTION IF EXISTS get_direct_descendants_of_tracked_entity;
CREATE OR REPLACE FUNCTION get_direct_descendants_of_tracked_entity(p_tracked_entity_id TEXT)
RETURNS TABLE (
- "trackedEntityId" TEXT,
+ "trackedActivityId" TEXT,
+ "id" TEXT,
"quantity" NUMERIC,
"status" "trackedEntityStatus",
+ "sourceDocument" TEXT,
+ "sourceDocumentId" TEXT,
+ "sourceDocumentReadableId" TEXT,
"activityAttributes" JSONB,
- "entityAttributes" JSONB
+ "attributes" JSONB
) AS $$
BEGIN
RETURN QUERY
SELECT
- ai."trackedEntityId",
+ ta."id" AS "trackedActivityId",
+ te."id",
te."quantity",
te."status",
+ te."sourceDocument",
+ te."sourceDocumentId",
+ te."sourceDocumentReadableId",
ta."attributes" AS "activityAttributes",
- te."attributes" AS "entityAttributes"
+ te."attributes" AS "attributes"
FROM "trackedActivityInput" ai
INNER JOIN "trackedEntity" te
ON ai."trackedEntityId" = te."id"
@@ -360,20 +368,28 @@ $$ LANGUAGE plpgsql;
DROP FUNCTION IF EXISTS get_direct_descendants_of_tracked_entity_strict;
CREATE OR REPLACE FUNCTION get_direct_descendants_of_tracked_entity_strict(p_tracked_entity_id TEXT)
RETURNS TABLE (
- "trackedEntityId" TEXT,
+ "trackedActivityId" TEXT,
+ "id" TEXT,
"quantity" NUMERIC,
"status" "trackedEntityStatus",
+ "sourceDocument" TEXT,
+ "sourceDocumentId" TEXT,
+ "sourceDocumentReadableId" TEXT,
"activityAttributes" JSONB,
- "entityAttributes" JSONB
+ "attributes" JSONB
) AS $$
BEGIN
RETURN QUERY
SELECT
- tai."trackedEntityId",
+ ta."id" AS "trackedActivityId",
+ te."id",
te."quantity",
te."status",
+ te."sourceDocument",
+ te."sourceDocumentId",
+ te."sourceDocumentReadableId",
ta."attributes" AS "activityAttributes",
- te."attributes" AS "entityAttributes"
+ te."attributes" AS "attributes"
FROM "trackedActivityInput" tai
INNER JOIN "trackedEntity" te
ON tai."trackedEntityId" = te."id"
@@ -391,4 +407,82 @@ BEGIN
END;
$$ LANGUAGE plpgsql;
-ALTER TABLE "trackedEntity" ADD COLUMN "currentOperationIds" TEXT[] DEFAULT ARRAY[]::TEXT[];
+-- Function to get direct ancestors of tracked entity
+DROP FUNCTION IF EXISTS get_direct_ancestors_of_tracked_entity;
+CREATE OR REPLACE FUNCTION get_direct_ancestors_of_tracked_entity(p_tracked_entity_id TEXT)
+RETURNS TABLE (
+ "trackedActivityId" TEXT,
+ "id" TEXT,
+ "quantity" NUMERIC,
+ "status" "trackedEntityStatus",
+ "sourceDocument" TEXT,
+ "sourceDocumentId" TEXT,
+ "sourceDocumentReadableId" TEXT,
+ "activityAttributes" JSONB,
+ "attributes" JSONB
+) AS $$
+BEGIN
+ RETURN QUERY
+ SELECT
+ ta."id" AS "trackedActivityId",
+ te."id",
+ te."quantity",
+ te."status",
+ te."sourceDocument",
+ te."sourceDocumentId",
+ te."sourceDocumentReadableId",
+ ta."attributes" AS "activityAttributes",
+ te."attributes" AS "attributes"
+ FROM "trackedActivityOutput" ao
+ INNER JOIN "trackedEntity" te
+ ON ao."trackedEntityId" = te."id"
+ INNER JOIN "trackedActivity" ta
+ ON ao."trackedActivityId" = ta."id"
+ JOIN "trackedActivityInput" ai
+ ON ao."trackedActivityId" = ai."trackedActivityId"
+ WHERE ai."trackedEntityId" = p_tracked_entity_id;
+END;
+$$ LANGUAGE plpgsql;
+
+-- Function to get direct ancestors with strict filtering
+DROP FUNCTION IF EXISTS get_direct_ancestors_of_tracked_entity_strict;
+CREATE OR REPLACE FUNCTION get_direct_ancestors_of_tracked_entity_strict(p_tracked_entity_id TEXT)
+RETURNS TABLE (
+ "trackedActivityId" TEXT,
+ "id" TEXT,
+ "quantity" NUMERIC,
+ "status" "trackedEntityStatus",
+ "sourceDocument" TEXT,
+ "sourceDocumentId" TEXT,
+ "sourceDocumentReadableId" TEXT,
+ "activityAttributes" JSONB,
+ "attributes" JSONB
+) AS $$
+BEGIN
+ RETURN QUERY
+ SELECT
+ ta."id" AS "trackedActivityId",
+ te."id",
+ te."quantity",
+ te."status",
+ te."sourceDocument",
+ te."sourceDocumentId",
+ te."sourceDocumentReadableId",
+ ta."attributes" AS "activityAttributes",
+ te."attributes" AS "attributes"
+ FROM "trackedActivityOutput" tao
+ INNER JOIN "trackedEntity" te
+ ON tao."trackedEntityId" = te."id"
+ INNER JOIN "trackedActivity" ta
+ ON tao."trackedActivityId" = ta."id"
+ WHERE tao."trackedActivityId" IN (
+ SELECT tai."trackedActivityId"
+ FROM "trackedActivityInput" tai
+ LEFT JOIN "trackedActivityOutput" tao2
+ ON tai."trackedActivityId" = tao2."trackedActivityId"
+ AND tao2."trackedEntityId" = p_tracked_entity_id
+ WHERE tai."trackedEntityId" = p_tracked_entity_id
+ AND tao2."trackedEntityId" IS NULL
+ );
+END;
+$$ LANGUAGE plpgsql;
\ No newline at end of file
diff --git a/apps/erp/app/components/Copy.tsx b/packages/react/src/Copy.tsx
similarity index 87%
rename from apps/erp/app/components/Copy.tsx
rename to packages/react/src/Copy.tsx
index 2696351f51..7e5cd043f4 100644
--- a/apps/erp/app/components/Copy.tsx
+++ b/packages/react/src/Copy.tsx
@@ -1,14 +1,10 @@
-import {
- Button,
- cn,
- Tooltip,
- TooltipContent,
- TooltipTrigger,
-} from "@carbon/react";
import type { ReactNode } from "react";
import { useState } from "react";
import { LuCheck, LuCopy } from "react-icons/lu";
-import { copyToClipboard } from "~/utils/string";
+import { copyToClipboard } from "./utils/dom";
+import { cn } from "./utils/cn";
+import { Button } from "./Button";
+import { Tooltip, TooltipContent, TooltipTrigger } from "./Tooltip";
const Copy = ({
text,
diff --git a/packages/react/src/index.tsx b/packages/react/src/index.tsx
index a97285fb29..6e578df3e8 100644
--- a/packages/react/src/index.tsx
+++ b/packages/react/src/index.tsx
@@ -293,6 +293,7 @@ import type {
} from "./hooks/useShortcutKeys";
import { cn } from "./utils/cn";
import { getValidChildren, reactNodeToString } from "./utils/react";
+import Copy from "./Copy";
export * from "./hooks";
export {
@@ -359,6 +360,7 @@ export {
ContextMenuSubContent,
ContextMenuSubTrigger,
ContextMenuTrigger,
+ Copy,
Count,
CreatableCombobox,
CreatableMultiSelect,
diff --git a/packages/react/src/utils/dom.ts b/packages/react/src/utils/dom.ts
index 9ba3fa2133..911f78f150 100644
--- a/packages/react/src/utils/dom.ts
+++ b/packages/react/src/utils/dom.ts
@@ -5,3 +5,34 @@ export const dataAttr = (condition: boolean | undefined) =>
export const ariaAttr = (condition: boolean | undefined) =>
condition ? true : undefined;
+
+/**
+ * Copy text content (string or Promise<string>) into Clipboard.
+ * Safari doesn't support write text into clipboard async, so if you need to load
+ * text content async before coping, please use Promise<string> for the 1st arg.
+ */
+export const copyToClipboard = async (
+ str: string | Promise<string>,
+ callback = () => {}
+) => {
+ const focused = window.document.hasFocus();
+ if (focused) {
+ if (
+ navigator.clipboard &&
+ typeof navigator.clipboard.writeText === "function"
+ ) {
+ const text = await Promise.resolve(str);
+ Promise.resolve(window.navigator?.clipboard?.writeText(text)).then(
+ callback
+ );
+
+ return;
+ }
+
+ Promise.resolve(str)
+ .then((text) => window.navigator?.clipboard?.writeText(text))
+ .then(callback);
+ } else {
+ console.warn("Unable to copy to clipboard");
+ }
+};
diff --git a/packages/utils/src/types.ts b/packages/utils/src/types.ts
index c4564b7e3a..046aebdca4 100644
--- a/packages/utils/src/types.ts
+++ b/packages/utils/src/types.ts
@@ -24,6 +24,7 @@ export interface TrackedActivityAttributes {
"Job Make Method"?: string;
"Job Material"?: string;
"Job Operation"?: string;
+ "Production Event"?: string;
Job?: string;
"Original Quantity"?: number;
"Remaining Quantity"?: number;