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.

10.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 { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { rejectCrossSiteNavigation } from "@carbon/auth/middleware/security.server";
import { flash } from "@carbon/auth/session.server";
import { activeJobStatuses } from "@carbon/database";
import { evaluateLinesForSurface, isBlocked } from "@carbon/ee/rules.server";
import { getLogger } from "@carbon/logger";
import { datetime, redirect } from "@carbon/utils";
import type { LoaderFunctionArgs } from "react-router";
import { getDatabaseClient } from "~/services/database.server";
import { getWorkCenterWithBlockingStatus } from "~/services/maintenance.service";
import {
  abilityBlockRefusal,
  getNextIncompleteSerialEntity,
  getTrackedEntitiesByMakeMethodId,
  postEndedProductionEvents,
  startMachineProductionEvent,
  startProductionEvent
} from "~/services/operations.service";
import { assignSerialNumberOnFirstTouch } from "~/services/serial-number.server";
import { OUTSIDE_PROCESSING_REFUSAL } from "~/utils/operationView";
import { path } from "~/utils/path";

const logger = getLogger("mes", "start-operation");

export async function loader({ request, params }: LoaderFunctionArgs) {
  // Writes on GET: a link on another site must not trigger it.
  rejectCrossSiteNavigation(request);
  const { userId, companyId } = await requirePermissions(request, {});
  const { operationId } = params;
  if (!operationId) throw new Error("Operation ID is required");

  const url = new URL(request.url);
  let trackedEntityId = url.searchParams.get("trackedEntityId");

  let type = (url.searchParams.get("type") ?? "Labor") as
    | "Setup"
    | "Labor"
    | "Machine";
  if (!["Setup", "Labor", "Machine"].includes(type)) {
    type = "Labor";
  }

  const serviceRole = await getCarbonServiceRole();
  const jobOperation = await serviceRole
    .from("jobOperation")
    .select("*")
    .eq("id", operationId)
    .eq("companyId", companyId)
    .maybeSingle();

  if (jobOperation.error || !jobOperation.data) {
    throw redirect(
      path.to.operations,
      await flash(
        request,
        error(jobOperation.error, "Failed to fetch job operation")
      )
    );
  }

  if (jobOperation.data?.companyId !== companyId) {
    logger.warn("Job operation does not belong to company", {
      companyId,
      operationId
    });
    throw redirect(
      path.to.operations,
      await flash(
        request,
        error("You are not authorized to start this operation", "Unauthorized")
      )
    );
  }

  // Subcontracted work runs at the supplier and is never startable here. Like
  // the floor rule below, this must run BEFORE the timer re-open.
  if (jobOperation.data.operationType === "Outside Processing") {
    throw redirect(
      path.to.operations,
      await flash(request, error(null, OUTSIDE_PROCESSING_REFUSAL))
    );
  }

  // Floor rule: an operation is startable iff it is floor-visible — a batched
  // op needs its batch released (not Planned); an unbatched op needs its job
  // released (Ready/In Progress/Paused). These guards must run BEFORE the
  // productionEvent re-open below so a not-released op never mutates timers.
  if (jobOperation.data.jobOperationBatchId) {
    const batch = await serviceRole
      .from("jobOperationBatch")
      .select("status")
      .eq("id", jobOperation.data.jobOperationBatchId)
      .eq("companyId", companyId)
      .maybeSingle();
    if (batch.data?.status === "Planned") {
      throw redirect(
        path.to.operations,
        await flash(
          request,
          error(
            null,
            "This operation is part of a batch that has not been released to the floor"
          )
        )
      );
    }
  } else {
    const job = await serviceRole
      .from("job")
      .select("status")
      .eq("id", jobOperation.data.jobId)
      .eq("companyId", companyId)
      .maybeSingle();
    if (
      !job.data?.status ||
      !(activeJobStatuses as readonly string[]).includes(job.data.status)
    ) {
      throw redirect(
        path.to.operations,
        await flash(
          request,
          error(null, "This operation's job has not been released to the floor")
        )
      );
    }
  }

  // Re-open any still-running timers for this operation (touches updatedBy so
  // realtime subscribers refresh).
  await serviceRole
    .from("productionEvent")
    .update({
      endTime: null,
      updatedBy: userId
    })
    .eq("jobOperationId", operationId)
    .is("endTime", null);

  // Check if work center is blocked for maintenance
  if (jobOperation.data.workCenterId) {
    const workCenterStatus = await getWorkCenterWithBlockingStatus(
      serviceRole,
      jobOperation.data.workCenterId
    );

    if (workCenterStatus.data?.isBlocked) {
      throw redirect(
        path.to.operation(operationId),
        await flash(
          request,
          error(
            `Work center is blocked for maintenance (${workCenterStatus.data.blockingDispatchReadableId})`,
            "Work Center Blocked"
          )
        )
      );
    }
  }

  // Refuse when the process requires an ability the operator lacks and its
  // policy is Block
  const abilityRefusal = await abilityBlockRefusal(serviceRole, {
    operationId,
    employeeId: userId,
    companyId
  });
  if (abilityRefusal) {
    throw redirect(
      path.to.operation(operationId),
      await flash(request, error(null, abilityRefusal))
    );
  }

  // Get tracked entities if jobMakeMethodId exists
  if (!trackedEntityId && jobOperation.data.jobMakeMethodId) {
    const trackedEntities = await getTrackedEntitiesByMakeMethodId(
      serviceRole,
      jobOperation.data.jobMakeMethodId,
      companyId
    );

    // Start the next incomplete serial unit for this operation (createdAt asc),
    // falling back to the last entity when every unit is already complete.
    const nextTrackedEntity = getNextIncompleteSerialEntity(
      trackedEntities.data ?? [],
      operationId
    );
    if (nextTrackedEntity) {
      trackedEntityId = nextTrackedEntity.id;
    }
  }

  // Business-rule pre-flight (workCenter target, operationStart surface).
  // Hard errors abort; warnings flash but allow (loader-only flow has no
  // modal to ack against).
  if (jobOperation.data.workCenterId) {
    const acknowledged = url.searchParams.get("acknowledged") === "true";
    const ruleEval = await evaluateLinesForSurface({
      client: serviceRole,
      companyId,
      userId,
      targetType: "workCenter",
      surface: "operationStart",
      lines: [
        {
          lineId: operationId,
          itemId: null,
          workCenterId: jobOperation.data.workCenterId,
          operation: {
            id: operationId,
            itemId: null,
            quantity: jobOperation.data.operationQuantity ?? null,
            workInstructionId:
              (jobOperation.data as { workInstructionId?: string | null })
                .workInstructionId ?? null
          },
          quantity: jobOperation.data.operationQuantity ?? 0
        }
      ]
    });
    if (
      ruleEval.violations.length > 0 &&
      isBlocked(ruleEval.violations, acknowledged)
    ) {
      throw redirect(
        path.to.operation(operationId),
        await flash(
          request,
          error(
            ruleEval.violations[0]?.message ?? "Rule violation",
            "Cannot start operation"
          )
        )
      );
    }
  }

  // A machine has one machine time: a Machine start ends every open Machine
  // event on the work center (from any operator or the sensor) and, with a
  // device, the open unattributed time, in one transaction with the new
  // event. That write skips RLS, so its permission is checked first.
  const machineWorkCenterId =
    type === "Machine" ? jobOperation.data.workCenterId : null;
  if (machineWorkCenterId) {
    await requirePermissions(request, { create: "production" });
  }

  const db = getDatabaseClient();
  const event = {
    type,
    jobOperationId: operationId,
    workCenterId: jobOperation.data.workCenterId!,
    startTime: datetime.timestamp(),
    employeeId: userId,
    companyId,
    createdBy: userId
  };
  const startEvent = machineWorkCenterId
    ? await startMachineProductionEvent(
        db,
        serviceRole,
        { ...event, workCenterId: machineWorkCenterId },
        trackedEntityId || undefined,
        undefined,
        "mes_qr"
      )
    : await startProductionEvent(
        serviceRole,
        event,
        trackedEntityId || undefined,
        undefined,
        "mes_qr"
      );

  if (startEvent.error) {
    throw redirect(
      path.to.operations,
      await flash(request, error(startEvent.error, "Failed to start event"))
    );
  }

  // A Machine start ends this operation's Setup and Labor timers, once the
  // Machine time is running. Every event ended here is posted.
  const ended =
    startEvent.data && "endedEventIds" in startEvent.data
      ? [...startEvent.data.endedEventIds]
      : [];
  if (type === "Machine") {
    const endTime = datetime.timestamp();
    const setupAndLabor = await serviceRole
      .from("productionEvent")
      .update({ endTime, updatedAt: endTime, updatedBy: userId })
      .eq("jobOperationId", operationId)
      .eq("companyId", companyId)
      .in("type", ["Setup", "Labor"])
      .is("endTime", null)
      .select("id");
    if (setupAndLabor.error) {
      logger.error("Failed to end Setup and Labor at a Machine start", {
        companyId,
        operationId,
        error: setupAndLabor.error
      });
    }
    for (const row of setupAndLabor.data ?? []) ended.push(row.id);
  }
  await postEndedProductionEvents(serviceRole, {
    companyId,
    userId,
    ids: ended
  });

  // First touch: number the unit if it has no serial number yet.
  if (trackedEntityId) {
    await assignSerialNumberOnFirstTouch({
      trackedEntityId,
      jobOperationId: operationId,
      companyId
    });
  }

  throw redirect(path.to.operation(operationId));
}