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.

7.7 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 { error, notFound } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import type { JSONContent } from "@carbon/react";
import { VStack } from "@carbon/react";
import { isUniqueViolation, pluckUnique, redirect } from "@carbon/utils";
import type { LoaderFunctionArgs } from "react-router";
import { useLoaderData } from "react-router";
import { useStorageUnits } from "~/components/Form/StorageUnit";
import { getTrackedEntityExpirations } from "~/modules/inventory/inventory.service";
import { InventoryDetails } from "~/modules/inventory/ui";
import {
  getItem,
  getItemQuantities,
  getItemShelfLife,
  getMakeMethodById,
  getMakeMethods,
  getMethodMaterialsByMakeMethod,
  getMethodOperationsByMakeMethodId,
  getPickMethod,
  upsertPickMethod
} from "~/modules/items/items.service";
import { getItemStorageUnitQuantities } from "~/modules/items/items.utils";
import { getLocationsList } from "~/modules/resources/resources.service";
import { getTagsList } from "~/modules/shared/shared.service";
import type { MethodItemType, MethodType } from "~/modules/shared/types";
import { getUserDefaults } from "~/modules/users/users.service";
import { useItems } from "~/stores/items";
import { path } from "~/utils/path";

export async function loader({ request, params }: LoaderFunctionArgs) {
  const { client, companyId, userId } = await requirePermissions(request, {
    view: "inventory"
  });

  const { itemId } = params;
  if (!itemId) throw notFound("itemId not found");

  const url = new URL(request.url);
  const searchParams = new URLSearchParams(url.search);
  let locationId = searchParams.get("location");

  // Three waits at most: what needs no location is read while the default
  // location is, and everything else is read together.
  const [userDefaults, item, itemShelfLife, makeMethods] = await Promise.all([
    locationId ? null : getUserDefaults(client, userId, companyId),
    getItem(client, itemId),
    getItemShelfLife(client, itemId),
    getMakeMethods(client, itemId, companyId)
  ]);

  if (userDefaults) {
    if (userDefaults.error) {
      throw redirect(
        path.to.inventory,
        await flash(
          request,
          error(userDefaults.error, "Failed to load default location")
        )
      );
    }

    locationId = userDefaults.data?.locationId ?? null;
  }

  if (!locationId) {
    const locations = await getLocationsList(client, companyId);
    if (locations.error || !locations.data?.length) {
      throw redirect(
        path.to.inventory,
        await flash(
          request,
          error(locations.error, "Failed to load any locations")
        )
      );
    }
    locationId = locations.data?.[0].id as string;
  }

  // Manufacturing data, for manufactured parts only
  const makeMethod =
    item.data && item.data.replenishmentSystem !== "Buy"
      ? (makeMethods.data?.find((m) => m.status === "Active") ??
        makeMethods.data?.[0])
      : undefined;

  let [
    pickMethod,
    quantities,
    itemStorageUnitQuantities,
    fullMethod,
    methodMaterials,
    methodOperations,
    operationTags
  ] = await Promise.all([
    getPickMethod(client, itemId, companyId, locationId),
    getItemQuantities(client, itemId, companyId, locationId),
    getItemStorageUnitQuantities(client, itemId, companyId, locationId),
    makeMethod ? getMakeMethodById(client, makeMethod.id, companyId) : null,
    makeMethod ? getMethodMaterialsByMakeMethod(client, makeMethod.id) : null,
    makeMethod
      ? getMethodOperationsByMakeMethodId(client, makeMethod.id)
      : null,
    makeMethod ? getTagsList(client, companyId, "operation") : null
  ]);

  if (pickMethod.error || !pickMethod.data) {
    const insertPickMethod = await upsertPickMethod(client, {
      itemId,
      companyId,
      locationId,
      customFields: {},
      createdBy: userId
    });

    if (insertPickMethod.error && !isUniqueViolation(insertPickMethod.error)) {
      throw redirect(
        path.to.inventory,
        await flash(
          request,
          error(insertPickMethod.error, "Failed to insert part inventory")
        )
      );
    }

    pickMethod = await getPickMethod(client, itemId, companyId, locationId);
    if (pickMethod.error || !pickMethod.data) {
      throw redirect(
        path.to.inventory,
        await flash(
          request,
          error(pickMethod.error, "Failed to load part inventory")
        )
      );
    }
  }

  if (quantities.error) {
    throw redirect(
      path.to.inventory,
      await flash(request, error(quantities, "Failed to load part quantities"))
    );
  }

  if (item.error || !item.data) {
    throw redirect(
      path.to.inventory,
      await flash(request, error(item.error, "Failed to load item"))
    );
  }

  if (itemStorageUnitQuantities.error || !itemStorageUnitQuantities.data) {
    throw redirect(
      path.to.inventory,
      await flash(
        request,
        error(
          itemStorageUnitQuantities.error,
          "Failed to load item storage unit quantities"
        )
      )
    );
  }

  // Pull shelf-life policy + current expiration dates so the adjustment modal
  // can pre-fill / surface the existing value when the user edits a batch.
  const trackedEntityIds = pluckUnique(
    itemStorageUnitQuantities.data,
    (row) => row.trackedEntityId
  );
  const trackedEntityExpirations = await getTrackedEntityExpirations(
    client,
    trackedEntityIds
  );

  let methodData = null;
  let tags: { name: string }[] = [];

  if (fullMethod && !fullMethod.error && fullMethod.data) {
    methodData = {
      makeMethod: fullMethod.data,
      methodMaterials:
        methodMaterials?.data?.map((m) => ({
          ...m,
          description: m.item?.name ?? "",
          methodType: m.methodType as MethodType,
          itemType: m.itemType as MethodItemType
        })) ?? [],
      methodOperations:
        methodOperations?.data?.map((operation) => ({
          ...operation,
          workCenterId: operation.workCenterId ?? undefined,
          operationSupplierProcessId:
            operation.operationSupplierProcessId ?? undefined,
          workInstruction: operation.workInstruction as JSONContent | null
        })) ?? []
    };
    tags = operationTags?.data ?? [];
  }

  return {
    pickMethod: pickMethod.data,
    quantities: quantities.data,
    itemStorageUnitQuantities: itemStorageUnitQuantities.data,
    item: item.data,
    itemShelfLife: itemShelfLife.data ?? null,
    trackedEntityExpirations,
    methodData,
    tags
  };
}

export default function ItemInventoryRoute() {
  const {
    pickMethod,
    quantities,
    itemStorageUnitQuantities,
    item,
    itemShelfLife,
    trackedEntityExpirations
  } = useLoaderData<typeof loader>();

  const [items] = useItems();
  const itemTrackingType = items.find(
    (i) => i.id === item.id
  )?.itemTrackingType;

  const storageUnits = useStorageUnits(pickMethod?.locationId);

  return (
    <VStack spacing={2}>
      <InventoryDetails
        itemStorageUnitQuantities={itemStorageUnitQuantities}
        itemUnitOfMeasureCode={item.unitOfMeasureCode ?? "EA"}
        itemTrackingType={itemTrackingType ?? "Inventory"}
        itemShelfLife={itemShelfLife}
        trackedEntityExpirations={trackedEntityExpirations}
        pickMethod={{
          ...pickMethod,
          defaultStorageUnitId: pickMethod.defaultStorageUnitId ?? undefined
        }}
        quantities={quantities}
        storageUnits={storageUnits.options}
        variant="quantity"
      />
    </VStack>
  );
}