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.

3.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 } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { getLogger } from "@carbon/logger";
import { RecordOutlet, useMount, VStack } from "@carbon/react";
import { redirect } from "@carbon/utils";
import type { LoaderFunctionArgs } from "react-router";
import { useLoaderData } from "react-router";
import { usePanels } from "~/components/Layout";
import {
  getJobOperationsList,
  getProductionEvents,
  PRODUCTION_EVENTS_PAGING
} from "~/modules/production/production.service";
import { ProductionEventsTable } from "~/modules/production/ui/Jobs";
import { getWorkCentersList } from "~/modules/resources/resources.service";
import { toPage } from "~/utils/cursor";
import { listErrorPage } from "~/utils/list-registry/load.server";
import { path, requestReferrer } from "~/utils/path";
import { getGenericQueryFilters } from "~/utils/query";

const logger = getLogger("erp", "job-events");

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

  const { jobId } = params;
  if (!jobId) throw new Error("Could not find jobId");

  const url = new URL(request.url);
  const searchParams = new URLSearchParams(url.search);
  const search = searchParams.get("search");
  const { limit, cursor, sorts, filters } =
    getGenericQueryFilters(searchParams);

  const operations = await getJobOperationsList(client, jobId);
  if (operations.error) {
    throw redirect(
      requestReferrer(request) ?? path.to.job(jobId),
      await flash(
        request,
        error(operations.error, "Failed to fetch job operations")
      )
    );
  }

  if (operations.data?.length === 0) {
    return {
      count: 0,
      events: [],
      nextCursor: null,
      workCenters: [],
      operations: []
    };
  }

  // A later page (`?after=`) is read for its rows only: skip the work centers.
  const [events, workCenters] = await Promise.all([
    getProductionEvents(client, operations.data?.map((o) => o.id) ?? [], {
      search,
      limit,
      cursor,
      sorts,
      filters
    }),
    cursor ? null : getWorkCentersList(client, companyId)
  ]);

  if (events.error) {
    if (cursor) {
      logger.error("Failed to load a later page of production events", {
        companyId,
        error: events.error
      });
      return listErrorPage("events");
    }
    throw redirect(
      path.to.production,
      await flash(request, error(events.error, "Failed to fetch job events"))
    );
  }

  const page = toPage(
    events.data ?? [],
    { limit, sorts },
    PRODUCTION_EVENTS_PAGING
  );

  return {
    count: events.count ?? 0,
    events: page.rows,
    nextCursor: page.nextCursor,
    workCenters: workCenters?.data ?? [],
    operations: operations.data ?? []
  };
}

export default function ProductionEventsRoute() {
  const { count, events, nextCursor, operations, workCenters } =
    useLoaderData<typeof loader>();

  const { setIsExplorerCollapsed } = usePanels();

  useMount(() => {
    setIsExplorerCollapsed(true);
  });

  return (
    <>
      <VStack
        spacing={0}
        className="h-[calc(100dvh-var(--topbar-height)-var(--header-height)-var(--content-inset))]"
      >
        <ProductionEventsTable
          data={events}
          count={count}
          nextCursor={nextCursor}
          operations={operations}
          workCenters={workCenters}
        />
      </VStack>
      <RecordOutlet />
    </>
  );
}