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.

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

import type {
  AvailableVariable,
  ValueType,
  VariableRef,
  WorkflowCatalog
} from "@carbon/ee/workflows";
import { canAssign, rendersAsText } from "@carbon/ee/workflows";
import {
  describeVariable,
  nodeNameLabel,
  outputLabel,
  propertyLabelKey
} from "../labelKeys";
import type { RefPart } from "./tokenId";
import { encodeTokenId, refLabel, refLeafLabel } from "./tokenId";

const ITEM_HELPER = "the item in the current loop";

export type VariableMenuItem = {
  id: string;
  label: string;
  helper?: string;
  /** Just the variable's own name. Search rows title themselves with this and show
   * `label` underneath — a full breadcrumb in a narrow menu truncates away the one
   * word the user typed. */
  leaf?: string;
};

/** One row in the drill-down menu. `item` means selectable, `children` means drillable,
 * neither means disabled with `helper` saying why; an entity can be both. */
export type VariableTreeNode = {
  key: string;
  label: string;
  helper?: string;
  /** Plain-English explanation of what this field holds, shown as a tooltip. */
  description?: string;
  /** `Step › output › property`, shown on hover. Only search rows set it: they are
   * the only rows the tree's own breadcrumb does not already place. */
  fullPath?: string;
  item?: VariableMenuItem;
  children?: VariableTreeNode[];
};

/** How many property hops a reference may take. The drill-down picker imports
 * this, so both menus offer exactly the same set. */
export const MAX_PATH = 2;

/** What the menu filters by, which is not always the type the field renders: a clause's
 * left side renders as text but must offer every variable. `undefined` is the "no filter"
 * signal below, so `"any"` is how a caller asks for it. */
export function pickAccepts(
  type: ValueType,
  accepts: ValueType | "any" | undefined
): ValueType | undefined {
  if (accepts === "any") return undefined;
  return accepts ?? type;
}

type Options = {
  /** Omit to accept any type. */
  accepts?: ValueType;
  /** For fields that write into a sentence. A record has no reading as text, so it is
   * not offered; drilling into it still is, which is where its name lives. */
  textOnly?: boolean;
  inLoop?: boolean;
  /** The operation card an inserted item ref should be scoped to (data-node chains). */
  itemCard?: string;
  /** What the current item is, so its fields can be offered. Omitted when the loop's
   * list is not known yet — the item is then offered whole, as a single row. */
  itemType?: ValueType;
  /** The action runs once per item, so a list may fill a single-value input. */
  batching?: boolean;
  /** Resolves a catalog label key to display text. Defaults to the fallback, which is what
   * the tests use — this file must not import the Lingui macro. */
  labelFor?: (key: string, fallback: string) => string;
};

/**
 * A change trigger hands out `record` and `after` as the same row in the same state.
 * Offering both only asks the user to pick between two names for one thing, so the
 * menus show `record`. An existing reference to `after` still resolves and still
 * renders — this hides it from the menu, it does not remove it.
 */
function withoutDuplicateOutputs(
  variables: AvailableVariable[]
): AvailableVariable[] {
  const hasRecord = new Set(
    variables.filter((v) => v.output === "record").map((v) => v.nodeId)
  );
  return variables.filter(
    (v) => v.output !== "after" || !hasRecord.has(v.nodeId)
  );
}

/**
 * What one property is called. The shipped translation first, then the catalog's own
 * label — a custom field lives only there — and the raw column name last.
 */
function propertyLabel(
  catalog: WorkflowCatalog,
  labelFor: (key: string, fallback: string) => string,
  entity: string,
  property: string
): string {
  return labelFor(
    propertyLabelKey(entity, property),
    catalog.getPropertyLabel(entity, property) ?? property
  );
}

/**
 * Flattens the variable list into menu entries, expanding entity properties up to
 * `MAX_PATH` hops. Labels come from `refLabel`, the same function that renders an
 * already-placed token, so a chip reads the same whether it was just inserted or
 * loaded from storage.
 */
export function variableMenuItems(
  variables: AvailableVariable[],
  catalog: WorkflowCatalog,
  {
    accepts,
    textOnly,
    inLoop,
    itemCard,
    itemType,
    batching,
    labelFor = (_key, fallback) => fallback
  }: Options = {}
): VariableMenuItem[] {
  const items: VariableMenuItem[] = [];
  const fits = (type: ValueType) =>
    (!textOnly || rendersAsText(type)) &&
    (!accepts || canAssign(type, accepts, { batching }));

  /** Adds the root and every property under it, up to `MAX_PATH` hops. */
  const walk = (
    type: ValueType,
    makeRef: (path: string[]) => RefPart,
    describe: (type: ValueType, path: string[]) => string,
    nodeName?: string
  ) => {
    const add = (path: string[], labels: string[], type: ValueType) => {
      if (!fits(type)) return;
      const ref = makeRef(path);
      items.push({
        id: encodeTokenId(ref),
        // Named as the tree names them: search matches what the customer can see, which
        // for a custom field is the only name they have ever been shown.
        label: refLabel(ref, nodeName, labels),
        leaf: refLeafLabel(ref, labels),
        helper: describe(type, path)
      });
    };

    const expand = (type: ValueType, path: string[], labels: string[]) => {
      if (path.length >= MAX_PATH) return;

      // An object carries its own fields, so it needs no catalog lookup — and its
      // field names are the vendor's own data, never translated, exactly as a
      // customer's custom field names are not.
      if (type.kind === "record") {
        for (const [field, fieldType] of Object.entries(type.fields)) {
          const nextPath = [...path, field];
          const nextLabels = [...labels, field];
          add(nextPath, nextLabels, fieldType);
          expand(fieldType, nextPath, nextLabels);
        }
        return;
      }

      if (type.kind !== "entity") return;
      const entity = catalog.getEntity(type.of);
      if (!entity) return;
      for (const [property, propertyType] of Object.entries(
        entity.properties
      )) {
        const nextPath = [...path, property];
        const nextLabels = [
          ...labels,
          propertyLabel(catalog, labelFor, type.of, property)
        ];
        add(nextPath, nextLabels, propertyType);
        expand(propertyType, nextPath, nextLabels);
      }
    };

    add([], [], type);
    expand(type, [], []);
  };

  for (const variable of withoutDuplicateOutputs(variables)) {
    walk(
      variable.type,
      (path): VariableRef => ({
        kind: "ref",
        nodeId: variable.nodeId,
        output: variable.output,
        path
      }),
      (type) => describeVariable(type, variable.guaranteed, labelFor),
      variable.nodeName
    );
  }

  if (inLoop) {
    const makeItemRef = (path: string[]): RefPart => ({
      kind: "item",
      path,
      ...(itemCard ? { card: itemCard } : {})
    });
    if (itemType) {
      walk(itemType, makeItemRef, (type, path) =>
        path.length === 0 ? ITEM_HELPER : describeVariable(type, true, labelFor)
      );
    } else {
      const ref = makeItemRef([]);
      items.push({
        id: encodeTokenId(ref),
        label: refLabel(ref),
        leaf: refLeafLabel(ref),
        helper: ITEM_HELPER
      });
    }
  }

  return items;
}

/** Where a branch of the tree starts: a step's output, or the current item. */
type TreeRoot = {
  key: string;
  makeRef: (path: string[]) => RefPart;
  nodeName?: string;
  guaranteed: boolean;
  /** Replaces the type description on the root row only. */
  helper?: string;
};

/** The same variables as `variableMenuItems`, as a tree so the menu can show one level at
 * a time. Search still comes off the flat list — it matches the whole breadcrumb. */
export function variableTree(
  variables: AvailableVariable[],
  catalog: WorkflowCatalog,
  {
    accepts,
    textOnly,
    inLoop,
    itemCard,
    itemType,
    batching,
    labelFor = (_key, fallback) => fallback
  }: Options = {}
): VariableTreeNode[] {
  const fits = (type: ValueType) =>
    (!textOnly || rendersAsText(type)) &&
    (!accepts || canAssign(type, accepts, { batching }));

  /** Null for a branch with nothing pickable inside — a row you cannot use is a row
   * that should not be there. An entity with usable properties survives even when the
   * record itself does not fit. */
  function build(
    root: TreeRoot,
    type: ValueType,
    path: string[],
    pathLabels: string[],
    label: string,
    description?: string
  ): VariableTreeNode | null {
    const compatible = fits(type);
    const ref = root.makeRef(path);
    const helper =
      path.length === 0 && root.helper !== undefined
        ? root.helper
        : describeVariable(type, root.guaranteed, labelFor);
    const node: VariableTreeNode = {
      key: `${root.key}:${path.join(".")}`,
      label,
      helper,
      description,
      item: compatible
        ? {
            id: encodeTokenId(ref),
            label: refLabel(ref, root.nodeName, pathLabels),
            // The row's own label IS the leaf, so a search scoped to this level names
            // its hits exactly as the level it drilled out of did.
            leaf: label,
            helper
          }
        : undefined
    };

    // An object's fields are on the type itself; there is nothing to look up, and
    // the field name IS the label — it is the vendor's word, not ours to translate.
    if (path.length < MAX_PATH && type.kind === "record") {
      const children = Object.entries(type.fields)
        .map(([field, fieldType]) =>
          build(
            root,
            fieldType,
            [...path, field],
            [...pathLabels, field],
            field
          )
        )
        .filter((child): child is VariableTreeNode => child !== null);
      if (children.length) node.children = children;
      if (!node.item && !children.length) return null;
    }

    if (path.length < MAX_PATH && type.kind === "entity") {
      const entity = catalog.getEntity(type.of);
      const children = entity
        ? Object.entries(entity.properties)
            .map(([property, propertyType]) => {
              // Property labels are catalog-driven; the raw column name is the fallback.
              const propertyName = propertyLabel(
                catalog,
                labelFor,
                type.of,
                property
              );
              return build(
                root,
                propertyType,
                [...path, property],
                [...pathLabels, propertyName],
                propertyName,
                entity.descriptions?.[property]
              );
            })
            .filter((child): child is VariableTreeNode => child !== null)
        : [];
      if (children.length) node.children = children;
      // Nothing to pick here and nothing worth opening — never offer a dead end.
      if (!node.item && !children.length) return null;
    }

    // A leaf that does not fit has nothing to offer and nothing to open.
    if (!node.item && !node.children?.length) return null;

    return node;
  }

  const byNode = new Map<string, VariableTreeNode>();
  for (const variable of withoutDuplicateOutputs(variables)) {
    let step = byNode.get(variable.nodeId);
    if (!step) {
      step = {
        key: variable.nodeId,
        label: nodeNameLabel(variable.nodeName),
        children: []
      };
      byNode.set(variable.nodeId, step);
    }
    const output = build(
      {
        key: `${variable.nodeId}:${variable.output}`,
        makeRef: (path) => ({
          kind: "ref",
          nodeId: variable.nodeId,
          output: variable.output,
          path
        }),
        nodeName: variable.nodeName,
        guaranteed: variable.guaranteed
      },
      variable.type,
      [],
      [],
      outputLabel(variable.output)
    );
    if (output) step.children!.push(output);
  }

  // A lone output is not hoisted into its step's row: the chip names the output, so the
  // row the user clicks has to name it too.
  const roots = [...byNode.values()].filter(
    (step) => step.item || step.children?.length
  );

  if (inLoop) {
    const makeRef = (path: string[]): RefPart => ({
      kind: "item",
      path,
      ...(itemCard ? { card: itemCard } : {})
    });
    if (itemType) {
      // Its fields hang under it like an output's, so a clause can compare one of them.
      const item = build(
        { key: "item", makeRef, guaranteed: true, helper: ITEM_HELPER },
        itemType,
        [],
        [],
        "Current item"
      );
      if (item) roots.push(item);
    } else {
      const ref = makeRef([]);
      roots.push({
        key: "item",
        label: "Current item",
        helper: ITEM_HELPER,
        item: {
          id: encodeTokenId(ref),
          label: refLabel(ref),
          leaf: refLeafLabel(ref),
          helper: ITEM_HELPER
        }
      });
    }
  }

  return roots;
}