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.

6.5 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 { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
import { redirect } from "@carbon/utils";
import type { ActionFunctionArgs } from "react-router";
import { inspectionCompletePassedValidator } from "~/services/models";
import {
  abilityBlockRefusal,
  returnPickedRemainders
} from "~/services/operations.service";
import {
  checkStrictBackflush,
  getInspectionOutcomeState,
  getSerialCompletionCandidates,
  postBulkCompletion,
  postSerialCompletions
} from "~/services/quality.server";
import { readOrigin, withOrigin } from "~/utils/origin";
import { path } from "~/utils/path";

// Completions posted here insert productionQuantity rows, whose SQL interceptor
// can auto-flip the operation to 'Done' (and complete the job) inside the DB —
// no app hook fires on that path, so the picked-material return sweep is
// orchestrated here after the postings land.
async function sweepIfOperationDone(
  serviceRole: Awaited<ReturnType<typeof getCarbonServiceRole>>,
  args: { jobOperationId: string; userId: string; companyId: string }
) {
  const op = await serviceRole
    .from("jobOperation")
    .select("status")
    .eq("id", args.jobOperationId)
    .eq("companyId", args.companyId)
    .maybeSingle();
  if (op.data?.status !== "Done") return;
  await returnPickedRemainders(serviceRole, args);
}

// Progressive completion while the lot stays open: any unit that passed
// inspection can move on immediately, without waiting for the disposition.
// Explicit (a button, not auto-on-pass) so a verdict typo doesn't need a
// compensating transaction — un-posted verdicts stay editable.
export async function action({ request, params }: ActionFunctionArgs) {
  assertIsPost(request);
  const { client, companyId, userId } = await requirePermissions(request, {
    update: "quality"
  });
  const { id } = params;
  if (!id) throw new Error("id is required");

  const formData = await request.formData();
  const validation = await validator(
    inspectionCompletePassedValidator
  ).validate(formData);
  if (validation.error) {
    return validationError(validation.error);
  }
  const {
    operationId,
    setupProductionEventId,
    laborProductionEventId,
    machineProductionEventId
  } = validation.data;
  const eventIds = {
    setupProductionEventId,
    laborProductionEventId,
    machineProductionEventId
  };
  // The page the inspection was opened from; Back keeps returning there.
  const origin = readOrigin(formData);
  const returnTo = withOrigin(path.to.inspection(operationId), origin);
  const fail = async (err: unknown, message: string): Promise<never> => {
    throw redirect(returnTo, await flash(request, error(err, message)));
  };

  const serviceRole = await getCarbonServiceRole();
  const stateResult = await getInspectionOutcomeState(serviceRole, {
    inspectionId: id,
    companyId
  });
  if (stateResult.error !== null || !stateResult.data) {
    return fail(stateResult.error, stateResult.message ?? "Failed to load lot");
  }
  const state = stateResult.data;
  if (state.jobOperationId !== operationId) {
    return fail(null, "Operation does not match the inspection lot");
  }
  const refusal = await abilityBlockRefusal(serviceRole, {
    operationId: state.jobOperationId,
    employeeId: userId,
    companyId
  });
  if (refusal) {
    return fail(null, refusal);
  }
  if (["Passed", "Failed", "Partial"].includes(state.inspection.status)) {
    return fail(null, "Inspection is closed — the disposition already ran");
  }

  if (state.requiresSerialTracking) {
    const candidates = getSerialCompletionCandidates(state, {
      includePending: false,
      includeSampleless: false
    });
    if (candidates.length === 0) {
      return fail(null, "No passed units to complete");
    }
    if (candidates.length > state.opRemaining) {
      return fail(
        null,
        `Passed units (${candidates.length}) exceed the operation's remaining quantity (${state.opRemaining}) — quantities were already recorded from the actions menu`
      );
    }
    const backflushCheck = await checkStrictBackflush({
      jobOperationId: state.jobOperationId,
      quantity: candidates.length,
      companyId,
      userId
    });
    if (backflushCheck.error) {
      return fail(backflushCheck.error, backflushCheck.message!);
    }
    const completions = await postSerialCompletions(serviceRole, {
      candidates,
      jobOperationId: state.jobOperationId,
      jobMakeMethodId: state.operation.jobMakeMethodId,
      workCenterId: state.operation.workCenterId,
      inspectionId: id,
      eventIds,
      companyId,
      userId
    });
    if (completions.error) {
      return fail(
        completions.error,
        `Completing units failed after ${completions.completed} of ${candidates.length}`
      );
    }
    await sweepIfOperationDone(serviceRole, {
      jobOperationId: state.jobOperationId,
      userId,
      companyId
    });
    throw redirect(
      returnTo,
      await flash(
        request,
        success(
          `${completions.completed} unit${completions.completed === 1 ? "" : "s"} completed`
        )
      )
    );
  }

  const passedCount = state.samples.filter((s) => s.status === "Passed").length;
  const quantity = Math.min(
    Math.max(0, passedCount - state.linkedProductionQuantity),
    state.opRemaining
  );
  if (quantity <= 0) {
    return fail(null, "No passed units to complete");
  }

  const backflushCheck = await checkStrictBackflush({
    jobOperationId: state.jobOperationId,
    quantity,
    companyId,
    userId
  });
  if (backflushCheck.error) {
    return fail(backflushCheck.error, backflushCheck.message!);
  }

  const completion = await postBulkCompletion(serviceRole, client, state, {
    quantity,
    eventIds,
    companyId,
    userId
  });
  if (completion.error) {
    return fail(
      completion.error,
      completion.message ?? "Failed to complete units"
    );
  }

  await sweepIfOperationDone(serviceRole, {
    jobOperationId: state.jobOperationId,
    userId,
    companyId
  });

  throw redirect(
    returnTo,
    await flash(
      request,
      success(`${quantity} unit${quantity === 1 ? "" : "s"} completed`)
    )
  );
}