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.2 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 { getLogger } from "@carbon/logger";
import { async } from "@carbon/utils";
import type { ActionFunctionArgs } from "react-router";
import { data } from "react-router";
import { batchStepRecordsValidator } from "~/services/models";
import {
  abilityBlockRefusal,
  backflushUntrackedMaterialsOnStepRecord,
  insertBatchStepRecords
} from "~/services/operations.service";

const log = getLogger("mes");

// Records one work-instruction step for several batch members at once — the
// batch view's counterpart of x+/record, with the same per-step backflush.
export async function action({ request, params }: ActionFunctionArgs) {
  assertIsPost(request);
  const { companyId, userId } = await requirePermissions(request, {});
  const { batchId } = params;
  if (!batchId) throw new Error("Batch ID is required");

  const validation = await validator(batchStepRecordsValidator).validate(
    await request.formData()
  );
  if (validation.error) {
    return validationError(validation.error);
  }

  const serviceRole = await getCarbonServiceRole();

  // Every member runs the batch's one process, so one member's check covers
  // the whole batch.
  const member = await serviceRole
    .from("jobOperation")
    .select("id")
    .eq("jobOperationBatchId", batchId)
    .eq("companyId", companyId)
    .limit(1)
    .maybeSingle();
  const abilityRefusal = member.data
    ? await abilityBlockRefusal(serviceRole, {
        operationId: member.data.id,
        employeeId: userId,
        companyId
      })
    : null;
  if (abilityRefusal) {
    return data({}, await flash(request, error(null, abilityRefusal)));
  }

  const inserted = await insertBatchStepRecords(serviceRole, {
    batchId,
    companyId,
    createdBy: userId,
    records: validation.data.records
  });
  if (inserted.error) {
    return data(
      {},
      await flash(request, error(inserted.error, "Failed to record step"))
    );
  }

  // One backflush per recorded step, as if each job had recorded its own.
  // Each backflush is its own transaction on the shared pool: bound them.
  const backflushes = await async.map(
    validation.data.records,
    (record) =>
      backflushUntrackedMaterialsOnStepRecord(serviceRole, {
        jobOperationStepId: record.jobOperationStepId,
        companyId,
        userId
      }),
    { concurrency: 4 }
  );
  for (const [i, backflush] of backflushes.entries()) {
    if (backflush.error) {
      log.error("Backflush on batch step record failed", {
        error: backflush.error,
        jobOperationStepId: validation.data.records[i]?.jobOperationStepId
      });
    }
  }

  return data(
    { success: true },
    await flash(
      request,
      success(`Recorded for ${validation.data.records.length} jobs`)
    )
  );
}