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.

fix: add batching to graph api

Sidwebworksea53327f46fa
diff --git a/apps/erp/app/modules/inventory/lineage.server.ts b/apps/erp/app/modules/inventory/lineage.server.ts
index ebb3030dfb..9c5b9efcd0 100644
--- a/apps/erp/app/modules/inventory/lineage.server.ts
+++ b/apps/erp/app/modules/inventory/lineage.server.ts
@@ -136,41 +136,38 @@ async function runLineageBfs(
if (frontier.length === 0) break;
if (entities.size >= MAX_ENTITIES) break;
- const descendantsResults: {
- id: string;
+ type BatchRow = {
+ sourceEntityId: string;
trackedActivityId: string;
- quantity: number;
- }[][] = [];
- const ancestorsResults: {
id: string;
- trackedActivityId: string;
quantity: number;
- }[][] = [];
+ };
const calls: Promise<void>[] = [];
- for (const id of frontier) {
- if (direction === "down" || direction === "both") {
- calls.push(
- (async () => {
- const res = await client.rpc(
- "get_direct_descendants_of_tracked_entity_strict",
- { p_tracked_entity_id: id }
- );
- descendantsResults.push((res.data ?? []) as any);
- })()
- );
- }
- if (direction === "up" || direction === "both") {
- calls.push(
- (async () => {
- const res = await client.rpc(
- "get_direct_ancestors_of_tracked_entity_strict",
- { p_tracked_entity_id: id }
- );
- ancestorsResults.push((res.data ?? []) as any);
- })()
- );
- }
+ let descendantsBatch: BatchRow[] = [];
+ let ancestorsBatch: BatchRow[] = [];
+
+ if (direction === "down" || direction === "both") {
+ calls.push(
+ (async () => {
+ const res = await client.rpc(
+ "get_direct_descendants_of_tracked_entities_strict",
+ { p_tracked_entity_ids: frontier }
+ );
+ descendantsBatch = (res.data ?? []) as BatchRow[];
+ })()
+ );
+ }
+ if (direction === "up" || direction === "both") {
+ calls.push(
+ (async () => {
+ const res = await client.rpc(
+ "get_direct_ancestors_of_tracked_entities_strict",
+ { p_tracked_entity_ids: frontier }
+ );
+ ancestorsBatch = (res.data ?? []) as BatchRow[];
+ })()
+ );
}
await Promise.all(calls);
@@ -179,60 +176,57 @@ async function runLineageBfs(
const newEntityIds = new Set<string>();
const activityIds = new Set<string>();
- for (let i = 0; i < frontier.length; i++) {
- const sourceId = frontier[i];
- const desc = descendantsResults[i] ?? [];
- for (const row of desc) {
- if (!row?.id) continue;
- activityIds.add(row.trackedActivityId);
- const outputKey = `${row.trackedActivityId}:${sourceId}`;
- if (!outputs.has(outputKey)) {
- outputs.set(outputKey, {
- trackedActivityId: row.trackedActivityId,
- trackedEntityId: sourceId,
- quantity: row.quantity
- });
- }
- if (!visited.has(row.id)) {
- visited.add(row.id);
- newEntityIds.add(row.id);
- nextFrontier.add(row.id);
- }
- const inputKey = `${row.trackedActivityId}:${row.id}`;
- if (!inputs.has(inputKey)) {
- inputs.set(inputKey, {
- trackedActivityId: row.trackedActivityId,
- trackedEntityId: row.id,
- quantity: row.quantity
- });
- }
+ for (let i = 0; i < descendantsBatch.length; i++) {
+ const row = descendantsBatch[i];
+ if (!row?.id) continue;
+ activityIds.add(row.trackedActivityId);
+ const outputKey = `${row.trackedActivityId}:${row.sourceEntityId}`;
+ if (!outputs.has(outputKey)) {
+ outputs.set(outputKey, {
+ trackedActivityId: row.trackedActivityId,
+ trackedEntityId: row.sourceEntityId,
+ quantity: row.quantity
+ });
+ }
+ if (!visited.has(row.id)) {
+ visited.add(row.id);
+ newEntityIds.add(row.id);
+ nextFrontier.add(row.id);
}
+ const inputKey = `${row.trackedActivityId}:${row.id}`;
+ if (!inputs.has(inputKey)) {
+ inputs.set(inputKey, {
+ trackedActivityId: row.trackedActivityId,
+ trackedEntityId: row.id,
+ quantity: row.quantity
+ });
+ }
+ }
- const anc = ancestorsResults[i] ?? [];
- for (const row of anc) {
- if (!row?.id) continue;
- activityIds.add(row.trackedActivityId);
- const inputKey = `${row.trackedActivityId}:${sourceId}`;
- if (!inputs.has(inputKey)) {
- inputs.set(inputKey, {
- trackedActivityId: row.trackedActivityId,
- trackedEntityId: sourceId,
- quantity: row.quantity
- });
- }
- if (!visited.has(row.id)) {
- visited.add(row.id);
- newEntityIds.add(row.id);
- nextFrontier.add(row.id);
- }
- const outputKey = `${row.trackedActivityId}:${row.id}`;
- if (!outputs.has(outputKey)) {
- outputs.set(outputKey, {
- trackedActivityId: row.trackedActivityId,
- trackedEntityId: row.id,
- quantity: row.quantity
- });
- }
+ for (let i = 0; i < ancestorsBatch.length; i++) {
+ const row = ancestorsBatch[i];
+ if (!row?.id) continue;
+ activityIds.add(row.trackedActivityId);
+ const inputKey = `${row.trackedActivityId}:${row.sourceEntityId}`;
+ if (!inputs.has(inputKey)) {
+ inputs.set(inputKey, {
+ trackedActivityId: row.trackedActivityId,
+ trackedEntityId: row.sourceEntityId,
+ quantity: row.quantity
+ });
+ }
+ if (!visited.has(row.id)) {
+ visited.add(row.id);
+ newEntityIds.add(row.id);
+ nextFrontier.add(row.id);
+ }
+ const outputKey = `${row.trackedActivityId}:${row.id}`;
+ if (!outputs.has(outputKey)) {
+ outputs.set(outputKey, {
+ trackedActivityId: row.trackedActivityId,
+ trackedEntityId: row.id,
+ quantity: row.quantity
+ });
}
}
@@ -320,38 +314,36 @@ export async function fetchContainmentsForEntities(
): Promise<IssueContainment[]> {
if (entityIds.length === 0) return [];
- const linkRes = await client
+ // Single round-trip: PostgREST embed pulls the linked issue inline and
+ // filters server-side to only Contained/Uncontained statuses.
+ const res = await client
.from("nonConformanceTrackedEntity")
- .select("nonConformanceId, trackedEntityId")
- .in("trackedEntityId", entityIds);
- const links = linkRes.data ?? [];
- if (links.length === 0) return [];
-
- const issueIds = Array.from(new Set(links.map((l) => l.nonConformanceId)));
-
- const issuesRes = await client
- .from("issues")
- .select("id, nonConformanceId, status, priority, containmentStatus")
- .in("id", issueIds);
- type IssueRow = NonNullable<typeof issuesRes.data>[number];
- const issuesById = new Map<string, IssueRow>();
- for (const row of issuesRes.data ?? []) {
- if (row.id) issuesById.set(row.id, row);
- }
+ .select(
+ `trackedEntityId,
+ nonConformanceId,
+ issue:issues!inner(id, status, priority, containmentStatus)`
+ )
+ .in("trackedEntityId", entityIds)
+ .in("issue.containmentStatus", ["Contained", "Uncontained"]);
const containments: IssueContainment[] = [];
- for (const link of links) {
- const issue = issuesById.get(link.nonConformanceId);
+ for (const row of res.data ?? []) {
+ const issue = row.issue as {
+ id: string | null;
+ status: string | null;
+ priority: string | null;
+ containmentStatus: string | null;
+ } | null;
if (!issue) continue;
const status = issue.containmentStatus;
if (status !== "Contained" && status !== "Uncontained") continue;
containments.push({
- id: issue.id ?? link.nonConformanceId,
- readableId: issue.nonConformanceId,
+ id: issue.id ?? row.nonConformanceId,
+ readableId: row.nonConformanceId,
containmentStatus: status as IssueContainmentStatus,
status: issue.status ?? "",
priority: issue.priority ?? null,
- trackedEntityId: link.trackedEntityId
+ trackedEntityId: row.trackedEntityId
});
}
return containments;
@@ -395,17 +387,16 @@ export async function fetchJobScopedLineage(
);
}
- const [stepRecords, containments] = await Promise.all([
- fetchJobStepRecords(client, jobId),
- fetchContainmentsForEntities(client, Array.from(state.entities.keys()))
- ]);
+ const containments = await fetchContainmentsForEntities(
+ client,
+ Array.from(state.entities.keys())
+ );
return {
entities: Array.from(state.entities.values()),
inputs: Array.from(state.inputs.values()),
outputs: Array.from(state.outputs.values()),
activities: Array.from(state.activities.values()),
- stepRecords,
containments
};
}
diff --git a/apps/erp/app/modules/inventory/ui/Traceability/TraceabilityGraph.tsx b/apps/erp/app/modules/inventory/ui/Traceability/TraceabilityGraph.tsx
index 98ee004f2e..f8e1e2d105 100644
--- a/apps/erp/app/modules/inventory/ui/Traceability/TraceabilityGraph.tsx
+++ b/apps/erp/app/modules/inventory/ui/Traceability/TraceabilityGraph.tsx
@@ -72,7 +72,6 @@ type Props = {
activities: Activity[];
inputs: ActivityInput[];
outputs: ActivityOutput[];
- stepRecords?: import("./utils").StepRecord[];
containments?: import("./utils").IssueContainment[];
rootId: string;
rootType: "entity" | "activity" | "job";
@@ -89,7 +88,6 @@ function TraceabilityGraphInner({
activities,
inputs,
outputs,
- stepRecords,
containments,
rootId,
rootType,
@@ -108,10 +106,9 @@ function TraceabilityGraphInner({
activities,
inputs,
outputs,
- stepRecords,
containments
}),
- [entities, activities, inputs, outputs, stepRecords, containments]
+ [entities, activities, inputs, outputs, containments]
);
const expansions = useTraceabilityStore((s) => s.expansions);
diff --git a/apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx b/apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx
index 34ba75eacc..a6323e1d27 100644
--- a/apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx
+++ b/apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx
@@ -2,12 +2,13 @@ import {
Badge,
Button,
cn,
+ Skeleton,
Tooltip,
TooltipContent,
TooltipTrigger
} from "@carbon/react";
import { useLingui } from "@lingui/react/macro";
-import { useMemo } from "react";
+import { useEffect, useMemo, useRef } from "react";
import {
LuChevronLeft,
LuChevronRight,
@@ -15,7 +16,7 @@ import {
LuExternalLink,
LuLink
} from "react-icons/lu";
-import { Link } from "react-router";
+import { Link, useFetcher } from "react-router";
import type { Activity, TrackedEntity } from "~/modules/inventory";
import { capitalize, copyToClipboard } from "~/utils/string";
import { AttributeList, hasRenderedAttributes } from "./attributeRenderers";
@@ -27,6 +28,7 @@ import {
activityHeadline,
entityHeadline,
type LineagePayload,
+ type StepRecord,
sourceLinkHref
} from "./utils";
@@ -112,14 +114,28 @@ export function TraceabilitySidebar({
return { producedBy, consumedBy, inputs, outputs };
}, [payload, entity, activity]);
+ const stepRecordsFetcher = useFetcher<{ stepRecords: StepRecord[] }>();
+ const lastLoadedActivityIdRef = useRef<string | null>(null);
+ const stepRecordsLoad = stepRecordsFetcher.load;
+ const activityId = activity?.id ?? null;
+ useEffect(() => {
+ if (!activityId) return;
+ if (lastLoadedActivityIdRef.current === activityId) return;
+ lastLoadedActivityIdRef.current = activityId;
+ stepRecordsLoad(
+ `/api/traceability/sidebar?activityId=${encodeURIComponent(activityId)}`
+ );
+ }, [activityId, stepRecordsLoad]);
+
const stepRecordsForActivity = useMemo(() => {
- if (!activity || !payload?.stepRecords?.length) return [];
+ const list = stepRecordsFetcher.data?.stepRecords ?? [];
+ if (!activity || list.length === 0) return [];
const opId = (activity.attributes as Record<string, any> | null)?.[
"Job Operation"
];
if (!opId) return [];
- return payload.stepRecords.filter((r) => r.operationId === opId);
- }, [activity, payload?.stepRecords]);
+ return list.filter((r) => r.operationId === opId);
+ }, [activity, stepRecordsFetcher.data]);
const containmentsForEntity = useMemo(() => {
if (!entity || !payload?.containments?.length) return [];
@@ -332,17 +348,23 @@ export function TraceabilitySidebar({
</Section>
)}
- {stepRecordsForActivity.length > 0 && (
- <Section title="Step records" count={stepRecordsForActivity.length}>
- <StepRecordsList
- records={stepRecordsForActivity}
- jobId={
- (activity?.attributes as Record<string, any> | null)?.Job ??
- null
- }
- />
- </Section>
- )}
+ {activity &&
+ (stepRecordsFetcher.state === "loading" &&
+ stepRecordsFetcher.data === undefined ? (
+ <Section title="Step records">
+ <StepRecordsSkeleton />
+ </Section>
+ ) : stepRecordsForActivity.length > 0 ? (
+ <Section title="Step records" count={stepRecordsForActivity.length}>
+ <StepRecordsList
+ records={stepRecordsForActivity}
+ jobId={
+ (activity?.attributes as Record<string, any> | null)?.Job ??
+ null
+ }
+ />
+ </Section>
+ ) : null)}
{hasRenderedAttributes(selectedNodeAttributes) && (
<Section title="Attributes">
@@ -513,3 +535,20 @@ function RelatedEntityRow({
</li>
);
}
+
+function StepRecordsSkeleton() {
+ return (
+ <ul className="divide-y divide-border/30">
+ {[0, 1, 2].map((i) => (
+ <li key={i} className="px-2 py-1.5 flex items-center gap-2">
+ <Skeleton className="h-6 w-6 rounded-full shrink-0" />
+ <div className="flex-1 min-w-0 flex flex-col gap-1.5">
+ <Skeleton className="h-3 w-32" />
+ <Skeleton className="h-2.5 w-20 opacity-70" />
+ </div>
+ <Skeleton className="h-3 w-10 shrink-0" />
+ </li>
+ ))}
+ </ul>
+ );
+}
diff --git a/apps/erp/app/routes/api+/traceability.sidebar.ts b/apps/erp/app/routes/api+/traceability.sidebar.ts
new file mode 100644
index 0000000000..b9d9bf07ec
--- /dev/null
+++ b/apps/erp/app/routes/api+/traceability.sidebar.ts
@@ -0,0 +1,34 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import type { LoaderFunctionArgs } from "react-router";
+import { fetchJobStepRecords } from "~/modules/inventory/lineage.server";
+import type { StepRecord } from "~/modules/inventory/ui/Traceability/utils";
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "inventory",
+ bypassRls: true
+ });
+
+ const url = new URL(request.url);
+ const activityId = url.searchParams.get("activityId");
+
+ if (!activityId) {
+ return Response.json({ stepRecords: [] as StepRecord[] });
+ }
+
+ const activityRes = await client
+ .from("trackedActivity")
+ .select("attributes")
+ .eq("id", activityId)
+ .maybeSingle();
+
+ const jobId = (activityRes.data?.attributes as Record<string, unknown> | null)
+ ?.Job;
+
+ if (typeof jobId !== "string" || !jobId) {
+ return Response.json({ stepRecords: [] as StepRecord[] });
+ }
+
+ const stepRecords = await fetchJobStepRecords(client, jobId);
+ return Response.json({ stepRecords });
+}
diff --git a/apps/erp/app/routes/x+/traceability+/graph.tsx b/apps/erp/app/routes/x+/traceability+/graph.tsx
index bff7da1920..ec5067ea60 100644
--- a/apps/erp/app/routes/x+/traceability+/graph.tsx
+++ b/apps/erp/app/routes/x+/traceability+/graph.tsx
@@ -12,13 +12,11 @@ import type { Activity, TrackedEntity } from "~/modules/inventory";
import {
fetchContainmentsForEntities,
fetchJobScopedLineage,
- fetchJobStepRecords,
fetchLineageSubgraph
} from "~/modules/inventory/lineage.server";
import { clampDepth } from "~/modules/inventory/ui/Traceability/constants";
import { TraceabilityGraph } from "~/modules/inventory/ui/Traceability/TraceabilityGraph";
import { TraceabilitySidebar } from "~/modules/inventory/ui/Traceability/TraceabilitySidebar";
-import type { StepRecord } from "~/modules/inventory/ui/Traceability/utils";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
@@ -49,8 +47,6 @@ export async function loader({ request }: LoaderFunctionArgs) {
const payload = await fetchJobScopedLineage(client, jobId, depth);
return {
...payload,
- stepRecords: payload.stepRecords ?? [],
- containments: payload.containments ?? [],
rootId: jobId,
rootType: "job" as const,
depth
@@ -64,16 +60,12 @@ export async function loader({ request }: LoaderFunctionArgs) {
depth,
"both"
);
- const [containments, stepRecords] = await Promise.all([
- fetchContainmentsForEntities(
- client,
- payload.entities.map((e) => e.id)
- ),
- collectStepRecordsForActivities(client, payload.activities)
- ]);
+ const containments = await fetchContainmentsForEntities(
+ client,
+ payload.entities.map((e) => e.id)
+ );
return {
...payload,
- stepRecords,
containments,
rootId: trackedEntityId,
rootType: "entity" as const,
@@ -139,13 +131,10 @@ export async function loader({ request }: LoaderFunctionArgs) {
...((additionalActivities?.data || []) as unknown as Activity[])
];
- const [containments, stepRecords] = await Promise.all([
- fetchContainmentsForEntities(
- client,
- allEntities.map((e) => e.id)
- ),
- collectStepRecordsForActivities(client, allActivities)
- ]);
+ const containments = await fetchContainmentsForEntities(
+ client,
+ allEntities.map((e) => e.id)
+ );
return {
entities: allEntities,
@@ -155,7 +144,6 @@ export async function loader({ request }: LoaderFunctionArgs) {
...(additionalOutputs?.data || [])
],
activities: allActivities,
- stepRecords,
containments,
rootId: trackedActivityId!,
rootType: "activity" as const,
@@ -163,22 +151,6 @@ export async function loader({ request }: LoaderFunctionArgs) {
};
}
-async function collectStepRecordsForActivities(
- client: Parameters<typeof fetchJobStepRecords>[0],
- activities: Activity[]
-): Promise<StepRecord[]> {
- const jobIds = new Set<string>();
- for (const a of activities) {
- const jobId = (a.attributes as Record<string, unknown> | null)?.Job;
- if (typeof jobId === "string" && jobId) jobIds.add(jobId);
- }
- if (jobIds.size === 0) return [];
- const results = await Promise.all(
- Array.from(jobIds).map((jobId) => fetchJobStepRecords(client, jobId))
- );
- return results.flat();
-}
-
export default function TraceabilityRoute() {
return (
<ReactFlowProvider>
@@ -193,7 +165,6 @@ function TraceabilityRouteInner() {
inputs,
outputs,
activities,
- stepRecords,
containments,
rootId,
rootType
@@ -270,7 +241,6 @@ function TraceabilityRouteInner() {
activities={activities as Activity[]}
inputs={inputs}
outputs={outputs}
- stepRecords={stepRecords}
containments={containments}
rootId={rootId}
rootType={rootType}
@@ -294,7 +264,6 @@ function TraceabilityRouteInner() {
activities: activities as Activity[],
inputs,
outputs,
- stepRecords,
containments
}}
onSelect={selectNode}
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 03a56cfe94..3c714dc374 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -35436,6 +35436,48 @@ export type Database = {
},
]
}
+ searchIndex_YMRLEKuAtGbyVG5HRUD7k9: {
+ Row: {
+ createdAt: string
+ description: string | null
+ entityId: string
+ entityType: string
+ id: number
+ link: string
+ metadata: Json | null
+ searchVector: unknown
+ tags: string[] | null
+ title: string
+ updatedAt: string | null
+ }
+ Insert: {
+ createdAt?: string
+ description?: string | null
+ entityId: string
+ entityType: string
+ id?: number
+ link: string
+ metadata?: Json | null
+ searchVector?: unknown
+ tags?: string[] | null
+ title: string
+ updatedAt?: string | null
+ }
+ Update: {
+ createdAt?: string
+ description?: string | null
+ entityId?: string
+ entityType?: string
+ id?: number
+ link?: string
+ metadata?: Json | null
+ searchVector?: unknown
+ tags?: string[] | null
+ title?: string
+ updatedAt?: string | null
+ }
+ Relationships: []
+ }
searchIndexRegistry: {
Row: {
companyId: string
@@ -55029,14 +55071,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["invoiceCountryCode"]
+ columns: ["shipmentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["shipmentCountryCode"]
+ columns: ["invoiceCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -59209,6 +59251,22 @@ export type Database = {
Args: { permission: string }
Returns: string[]
}
+ get_direct_ancestors_of_tracked_entities_strict: {
+ Args: { p_tracked_entity_ids: string[] }
+ Returns: {
+ activityAttributes: Json
+ attributes: Json
+ id: string
+ quantity: number
+ readableId: string
+ sourceDocument: string
+ sourceDocumentId: string
+ sourceDocumentReadableId: string
+ sourceEntityId: string
+ status: Database["public"]["Enums"]["trackedEntityStatus"]
+ trackedActivityId: string
+ }[]
+ }
get_direct_ancestors_of_tracked_entity: {
Args: { p_tracked_entity_id: string }
Returns: {
@@ -59239,6 +59297,22 @@ export type Database = {
trackedActivityId: string
}[]
}
+ get_direct_descendants_of_tracked_entities_strict: {
+ Args: { p_tracked_entity_ids: string[] }
+ Returns: {
+ activityAttributes: Json
+ attributes: Json
+ id: string
+ quantity: number
+ readableId: string
+ sourceDocument: string
+ sourceDocumentId: string
+ sourceDocumentReadableId: string
+ sourceEntityId: string
+ status: Database["public"]["Enums"]["trackedEntityStatus"]
+ trackedActivityId: string
+ }[]
+ }
get_direct_descendants_of_tracked_entity: {
Args: { p_tracked_entity_id: string }
Returns: {
diff --git a/packages/database/supabase/migrations/20260430090114_lineage-batch-rpcs.sql b/packages/database/supabase/migrations/20260430090114_lineage-batch-rpcs.sql
new file mode 100644
index 0000000000..5d90ebf342
--- /dev/null
+++ b/packages/database/supabase/migrations/20260430090114_lineage-batch-rpcs.sql
@@ -0,0 +1,84 @@
+-- Batch variants of the existing per-entity strict traversal RPCs.
+-- Saves N round-trips per BFS hop where N = frontier size.
+
+DROP FUNCTION IF EXISTS get_direct_descendants_of_tracked_entities_strict;
+CREATE OR REPLACE FUNCTION get_direct_descendants_of_tracked_entities_strict(p_tracked_entity_ids TEXT[])
+RETURNS TABLE (
+ "sourceEntityId" TEXT,
+ "trackedActivityId" TEXT,
+ "id" TEXT,
+ "readableId" TEXT,
+ "quantity" NUMERIC,
+ "status" "trackedEntityStatus",
+ "sourceDocument" TEXT,
+ "sourceDocumentId" TEXT,
+ "sourceDocumentReadableId" TEXT,
+ "activityAttributes" JSONB,
+ "attributes" JSONB
+) AS $$
+BEGIN
+ RETURN QUERY
+ SELECT
+ seed.id AS "sourceEntityId",
+ ta."id" AS "trackedActivityId",
+ te."id",
+ te."readableId",
+ te."quantity",
+ te."status",
+ te."sourceDocument",
+ te."sourceDocumentId",
+ te."sourceDocumentReadableId",
+ ta."attributes" AS "activityAttributes",
+ te."attributes" AS "attributes"
+ FROM unnest(p_tracked_entity_ids) AS seed(id)
+ JOIN "trackedActivityOutput" tao ON tao."trackedEntityId" = seed.id
+ JOIN "trackedActivityInput" tai ON tai."trackedActivityId" = tao."trackedActivityId"
+ LEFT JOIN "trackedActivityInput" tai2
+ ON tai2."trackedActivityId" = tao."trackedActivityId"
+ AND tai2."trackedEntityId" = seed.id
+ JOIN "trackedEntity" te ON te."id" = tai."trackedEntityId"
+ JOIN "trackedActivity" ta ON ta."id" = tai."trackedActivityId"
+ WHERE tai2."trackedEntityId" IS NULL;
+END;
+$$ LANGUAGE plpgsql;
+
+DROP FUNCTION IF EXISTS get_direct_ancestors_of_tracked_entities_strict;
+CREATE OR REPLACE FUNCTION get_direct_ancestors_of_tracked_entities_strict(p_tracked_entity_ids TEXT[])
+RETURNS TABLE (
+ "sourceEntityId" TEXT,
+ "trackedActivityId" TEXT,
+ "id" TEXT,
+ "readableId" TEXT,
+ "quantity" NUMERIC,
+ "status" "trackedEntityStatus",
+ "sourceDocument" TEXT,
+ "sourceDocumentId" TEXT,
+ "sourceDocumentReadableId" TEXT,
+ "activityAttributes" JSONB,
+ "attributes" JSONB
+) AS $$
+BEGIN
+ RETURN QUERY
+ SELECT
+ seed.id AS "sourceEntityId",
+ ta."id" AS "trackedActivityId",
+ te."id",
+ te."readableId",
+ te."quantity",
+ te."status",
+ te."sourceDocument",
+ te."sourceDocumentId",
+ te."sourceDocumentReadableId",
+ ta."attributes" AS "activityAttributes",
+ te."attributes" AS "attributes"
+ FROM unnest(p_tracked_entity_ids) AS seed(id)
+ JOIN "trackedActivityInput" tai ON tai."trackedEntityId" = seed.id
+ JOIN "trackedActivityOutput" tao ON tao."trackedActivityId" = tai."trackedActivityId"
+ LEFT JOIN "trackedActivityOutput" tao2
+ ON tao2."trackedActivityId" = tai."trackedActivityId"
+ AND tao2."trackedEntityId" = seed.id
+ JOIN "trackedEntity" te ON te."id" = tao."trackedEntityId"
+ JOIN "trackedActivity" ta ON ta."id" = tao."trackedActivityId"
+ WHERE tao2."trackedEntityId" IS NULL;
+END;
+$$ LANGUAGE plpgsql;
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index 7648d4b0d3..b42cdab0a7 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -1492,7 +1492,7 @@ msgstr "Zurück"
msgid "Back to home"
msgstr "Zurück zur Startseite"
-#: apps/erp/app/routes/x+/traceability+/graph.tsx:257
+#: apps/erp/app/routes/x+/traceability+/graph.tsx:228
msgid "Back to traceability"
msgstr "Zurück zur Rückverfolgbarkeit"
@@ -2689,7 +2689,7 @@ msgstr "Dokumentnamen kopieren"
msgid "Copy document unique identifier"
msgstr "Eindeutige Dokumentkennung kopieren"
-#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:218
+#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:234
msgid "Copy ID"
msgstr ""
@@ -2705,7 +2705,7 @@ msgstr "Eindeutige Kennung des Problems kopieren"
msgid "Copy Job number"
msgstr "Job-Nummer kopieren"
-#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:204
+#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:220
msgid "Copy link"
msgstr ""
@@ -13767,7 +13767,7 @@ msgstr "Summe"
#: apps/erp/app/modules/inventory/ui/useInventorySubmodules.tsx:76
#: apps/erp/app/routes/x+/traceability+/_index.tsx:25
#: apps/erp/app/routes/x+/traceability+/_index.tsx:152
-#: apps/erp/app/routes/x+/traceability+/graph.tsx:26
+#: apps/erp/app/routes/x+/traceability+/graph.tsx:24
msgid "Traceability"
msgstr "Rückverfolgbarkeit"
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index 80e70798bc..7779c90cd0 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -1492,7 +1492,7 @@ msgstr "Back"
msgid "Back to home"
msgstr "Back to home"
-#: apps/erp/app/routes/x+/traceability+/graph.tsx:257
+#: apps/erp/app/routes/x+/traceability+/graph.tsx:228
msgid "Back to traceability"
msgstr "Back to traceability"
@@ -2689,7 +2689,7 @@ msgstr "Copy document name"
msgid "Copy document unique identifier"
msgstr "Copy document unique identifier"
-#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:218
+#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:234
msgid "Copy ID"
msgstr "Copy ID"
@@ -2705,7 +2705,7 @@ msgstr "Copy issue unique identifier"
msgid "Copy Job number"
msgstr "Copy Job number"
-#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:204
+#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:220
msgid "Copy link"
msgstr "Copy link"
@@ -13767,7 +13767,7 @@ msgstr "Totaling"
#: apps/erp/app/modules/inventory/ui/useInventorySubmodules.tsx:76
#: apps/erp/app/routes/x+/traceability+/_index.tsx:25
#: apps/erp/app/routes/x+/traceability+/_index.tsx:152
-#: apps/erp/app/routes/x+/traceability+/graph.tsx:26
+#: apps/erp/app/routes/x+/traceability+/graph.tsx:24
msgid "Traceability"
msgstr "Traceability"
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index 1db33d0879..fd6c524371 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -1492,7 +1492,7 @@ msgstr "Atrás"
msgid "Back to home"
msgstr "Volver al inicio"
-#: apps/erp/app/routes/x+/traceability+/graph.tsx:257
+#: apps/erp/app/routes/x+/traceability+/graph.tsx:228
msgid "Back to traceability"
msgstr "Volver a trazabilidad"
@@ -2689,7 +2689,7 @@ msgstr "Copiar nombre del documento"
msgid "Copy document unique identifier"
msgstr "Copiar identificador único del documento"
-#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:218
+#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:234
msgid "Copy ID"
msgstr ""
@@ -2705,7 +2705,7 @@ msgstr "Copiar identificador único del problema"
msgid "Copy Job number"
msgstr "Copiar número de trabajo"
-#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:204
+#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:220
msgid "Copy link"
msgstr ""
@@ -13767,7 +13767,7 @@ msgstr "Totalización"
#: apps/erp/app/modules/inventory/ui/useInventorySubmodules.tsx:76
#: apps/erp/app/routes/x+/traceability+/_index.tsx:25
#: apps/erp/app/routes/x+/traceability+/_index.tsx:152
-#: apps/erp/app/routes/x+/traceability+/graph.tsx:26
+#: apps/erp/app/routes/x+/traceability+/graph.tsx:24
msgid "Traceability"
msgstr "Trazabilidad"
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index 77a1c2fb17..4bca267e06 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -1492,7 +1492,7 @@ msgstr "Retour"
msgid "Back to home"
msgstr "Retour à l'accueil"
-#: apps/erp/app/routes/x+/traceability+/graph.tsx:257
+#: apps/erp/app/routes/x+/traceability+/graph.tsx:228
msgid "Back to traceability"
msgstr "Retour à la traçabilité"
@@ -2689,7 +2689,7 @@ msgstr "Copier le nom du document"
msgid "Copy document unique identifier"
msgstr "Copier l'identifiant unique du document"
-#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:218
+#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:234
msgid "Copy ID"
msgstr ""
@@ -2705,7 +2705,7 @@ msgstr "Copier l'identifiant unique du problème"
msgid "Copy Job number"
msgstr "Copier le numéro de travail"
-#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:204
+#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:220
msgid "Copy link"
msgstr ""
@@ -13767,7 +13767,7 @@ msgstr "Totalisation"
#: apps/erp/app/modules/inventory/ui/useInventorySubmodules.tsx:76
#: apps/erp/app/routes/x+/traceability+/_index.tsx:25
#: apps/erp/app/routes/x+/traceability+/_index.tsx:152
-#: apps/erp/app/routes/x+/traceability+/graph.tsx:26
+#: apps/erp/app/routes/x+/traceability+/graph.tsx:24
msgid "Traceability"
msgstr "Traçabilité"
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index 2ad61f7685..c880ab2067 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -1492,7 +1492,7 @@ msgstr "वापस"
msgid "Back to home"
msgstr "घर वापस जाएं"
-#: apps/erp/app/routes/x+/traceability+/graph.tsx:257
+#: apps/erp/app/routes/x+/traceability+/graph.tsx:228
msgid "Back to traceability"
msgstr "ट्रेसेबिलिटी पर वापस जाएं"
@@ -2689,7 +2689,7 @@ msgstr "दस्तावेज़ का नाम कॉपी करें"
msgid "Copy document unique identifier"
msgstr "दस्तावेज़ की अद्वितीय पहचान की प्रतिलिपि बनाएँ"
-#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:218
+#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:234
msgid "Copy ID"
msgstr ""
@@ -2705,7 +2705,7 @@ msgstr "समस्या की अद्वितीय पहचान क
msgid "Copy Job number"
msgstr "जॉब नंबर कॉपी करें"
-#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:204
+#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:220
msgid "Copy link"
msgstr ""
@@ -13767,7 +13767,7 @@ msgstr "कुल"
#: apps/erp/app/modules/inventory/ui/useInventorySubmodules.tsx:76
#: apps/erp/app/routes/x+/traceability+/_index.tsx:25
#: apps/erp/app/routes/x+/traceability+/_index.tsx:152
-#: apps/erp/app/routes/x+/traceability+/graph.tsx:26
+#: apps/erp/app/routes/x+/traceability+/graph.tsx:24
msgid "Traceability"
msgstr "ट्रेसेबिलिटी"
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index bd66d7c4e4..e10c11ab86 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -1492,7 +1492,7 @@ msgstr "Indietro"
msgid "Back to home"
msgstr "Torna alla home"
-#: apps/erp/app/routes/x+/traceability+/graph.tsx:257
+#: apps/erp/app/routes/x+/traceability+/graph.tsx:228
msgid "Back to traceability"
msgstr "Torna alla tracciabilità"
@@ -2689,7 +2689,7 @@ msgstr "Copia nome documento"
msgid "Copy document unique identifier"
msgstr "Copia identificatore univoco documento"
-#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:218
+#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:234
msgid "Copy ID"
msgstr ""
@@ -2705,7 +2705,7 @@ msgstr "Copia identificatore univoco del problema"
msgid "Copy Job number"
msgstr "Copia numero lavoro"
-#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:204
+#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:220
msgid "Copy link"
msgstr ""
@@ -13767,7 +13767,7 @@ msgstr "Totalizzazione"
#: apps/erp/app/modules/inventory/ui/useInventorySubmodules.tsx:76
#: apps/erp/app/routes/x+/traceability+/_index.tsx:25
#: apps/erp/app/routes/x+/traceability+/_index.tsx:152
-#: apps/erp/app/routes/x+/traceability+/graph.tsx:26
+#: apps/erp/app/routes/x+/traceability+/graph.tsx:24
msgid "Traceability"
msgstr "Tracciabilità"
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index b08b750883..555ef9b19b 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -1492,7 +1492,7 @@ msgstr "戻る"
msgid "Back to home"
msgstr "ホームに戻る"
-#: apps/erp/app/routes/x+/traceability+/graph.tsx:257
+#: apps/erp/app/routes/x+/traceability+/graph.tsx:228
msgid "Back to traceability"
msgstr "トレーサビリティに戻る"
@@ -2689,7 +2689,7 @@ msgstr "ドキュメント名をコピー"
msgid "Copy document unique identifier"
msgstr "ドキュメントの一意の識別子をコピー"
-#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:218
+#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:234
msgid "Copy ID"
msgstr ""
@@ -2705,7 +2705,7 @@ msgstr "問題の一意の識別子をコピー"
msgid "Copy Job number"
msgstr "ジョブ番号をコピー"
-#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:204
+#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:220
msgid "Copy link"
msgstr ""
@@ -13767,7 +13767,7 @@ msgstr "合計"
#: apps/erp/app/modules/inventory/ui/useInventorySubmodules.tsx:76
#: apps/erp/app/routes/x+/traceability+/_index.tsx:25
#: apps/erp/app/routes/x+/traceability+/_index.tsx:152
-#: apps/erp/app/routes/x+/traceability+/graph.tsx:26
+#: apps/erp/app/routes/x+/traceability+/graph.tsx:24
msgid "Traceability"
msgstr "トレーサビリティ"
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index 7491cd189c..dd928e5e2e 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -1492,7 +1492,7 @@ msgstr "Wstecz"
msgid "Back to home"
msgstr "Powrót do strony głównej"
-#: apps/erp/app/routes/x+/traceability+/graph.tsx:257
+#: apps/erp/app/routes/x+/traceability+/graph.tsx:228
msgid "Back to traceability"
msgstr "Wróć do śledzenia"
@@ -2689,7 +2689,7 @@ msgstr "Skopiuj nazwę dokumentu"
msgid "Copy document unique identifier"
msgstr "Skopiuj unikalny identyfikator dokumentu"
-#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:218
+#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:234
msgid "Copy ID"
msgstr ""
@@ -2705,7 +2705,7 @@ msgstr "Skopiuj unikalny identyfikator problemu"
msgid "Copy Job number"
msgstr "Skopiuj numer zadania"
-#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:204
+#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:220
msgid "Copy link"
msgstr ""
@@ -13767,7 +13767,7 @@ msgstr "Razem"
#: apps/erp/app/modules/inventory/ui/useInventorySubmodules.tsx:76
#: apps/erp/app/routes/x+/traceability+/_index.tsx:25
#: apps/erp/app/routes/x+/traceability+/_index.tsx:152
-#: apps/erp/app/routes/x+/traceability+/graph.tsx:26
+#: apps/erp/app/routes/x+/traceability+/graph.tsx:24
msgid "Traceability"
msgstr "Możliwość śledzenia"
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index 98d031e3bb..2d3c5aedcf 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -1492,7 +1492,7 @@ msgstr "Voltar"
msgid "Back to home"
msgstr "Voltar para casa"
-#: apps/erp/app/routes/x+/traceability+/graph.tsx:257
+#: apps/erp/app/routes/x+/traceability+/graph.tsx:228
msgid "Back to traceability"
msgstr "Voltar para rastreabilidade"
@@ -2689,7 +2689,7 @@ msgstr "Copiar nome do documento"
msgid "Copy document unique identifier"
msgstr "Copiar identificador único do documento"
-#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:218
+#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:234
msgid "Copy ID"
msgstr ""
@@ -2705,7 +2705,7 @@ msgstr "Copiar identificador único do problema"
msgid "Copy Job number"
msgstr "Copiar número do trabalho"
-#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:204
+#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:220
msgid "Copy link"
msgstr ""
@@ -13767,7 +13767,7 @@ msgstr "Totalização"
#: apps/erp/app/modules/inventory/ui/useInventorySubmodules.tsx:76
#: apps/erp/app/routes/x+/traceability+/_index.tsx:25
#: apps/erp/app/routes/x+/traceability+/_index.tsx:152
-#: apps/erp/app/routes/x+/traceability+/graph.tsx:26
+#: apps/erp/app/routes/x+/traceability+/graph.tsx:24
msgid "Traceability"
msgstr "Rastreabilidade"
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index 20d5b3a207..cfb001c53f 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -1492,7 +1492,7 @@ msgstr "Назад"
msgid "Back to home"
msgstr "Вернуться на главную"
-#: apps/erp/app/routes/x+/traceability+/graph.tsx:257
+#: apps/erp/app/routes/x+/traceability+/graph.tsx:228
msgid "Back to traceability"
msgstr "Вернуться к отслеживанию"
@@ -2689,7 +2689,7 @@ msgstr "Копировать имя документа"
msgid "Copy document unique identifier"
msgstr "Скопировать уникальный идентификатор документа"
-#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:218
+#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:234
msgid "Copy ID"
msgstr ""
@@ -2705,7 +2705,7 @@ msgstr "Скопировать уникальный идентификатор
msgid "Copy Job number"
msgstr "Скопировать номер задания"
-#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:204
+#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:220
msgid "Copy link"
msgstr ""
@@ -13767,7 +13767,7 @@ msgstr "Итого"
#: apps/erp/app/modules/inventory/ui/useInventorySubmodules.tsx:76
#: apps/erp/app/routes/x+/traceability+/_index.tsx:25
#: apps/erp/app/routes/x+/traceability+/_index.tsx:152
-#: apps/erp/app/routes/x+/traceability+/graph.tsx:26
+#: apps/erp/app/routes/x+/traceability+/graph.tsx:24
msgid "Traceability"
msgstr "Отслеживаемость"
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index 0037476c29..61e677f5d8 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -1492,7 +1492,7 @@ msgstr "返回"
msgid "Back to home"
msgstr "返回主页"
-#: apps/erp/app/routes/x+/traceability+/graph.tsx:257
+#: apps/erp/app/routes/x+/traceability+/graph.tsx:228
msgid "Back to traceability"
msgstr "返回可追溯性"
@@ -2689,7 +2689,7 @@ msgstr "复制文档名称"
msgid "Copy document unique identifier"
msgstr "复制文档唯一标识符"
-#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:218
+#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:234
msgid "Copy ID"
msgstr ""
@@ -2705,7 +2705,7 @@ msgstr "复制问题唯一标识符"
msgid "Copy Job number"
msgstr "复制工作单号"
-#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:204
+#: apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx:220
msgid "Copy link"
msgstr ""
@@ -13767,7 +13767,7 @@ msgstr "合计"
#: apps/erp/app/modules/inventory/ui/useInventorySubmodules.tsx:76
#: apps/erp/app/routes/x+/traceability+/_index.tsx:25
#: apps/erp/app/routes/x+/traceability+/_index.tsx:152
-#: apps/erp/app/routes/x+/traceability+/graph.tsx:26
+#: apps/erp/app/routes/x+/traceability+/graph.tsx:24
msgid "Traceability"
msgstr "可追溯性"