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.

5.6 KB
Raw Blame
CREATE OR REPLACE FUNCTION public.sync_finish_job_operation(p_table text, p_operation text, p_new jsonb, p_old jsonb)
 RETURNS void
 LANGUAGE plpgsql
 SET search_path TO 'public'
AS $function$
DECLARE
  v_job_location_id TEXT;
  v_job_storage_unit_id TEXT;
  v_job_quantity NUMERIC;
  v_sales_order_id TEXT;
  v_quantity_complete NUMERIC;
  v_quantity_lost NUMERIC;
  v_quantity_received NUMERIC;
  v_job_status TEXT;
BEGIN
  IF p_operation != 'UPDATE' THEN RETURN; END IF;
  IF (p_new->>'status') != 'Done' OR (p_old->>'status') = 'Done' THEN RETURN; END IF;

  UPDATE "productionEvent"
  SET "endTime" = NOW()
  WHERE "jobOperationId" = p_new->>'id'
    AND "endTime" IS NULL;

  UPDATE "jobOperation" op
  SET status = 'Ready'
  WHERE EXISTS (
    SELECT 1
    FROM "jobOperationDependency" dep
    WHERE dep."operationId" = op.id
      AND dep."dependsOnId" = p_new->>'id'
      AND op.status = 'Waiting'
  )
  AND NOT EXISTS (
    SELECT 1
    FROM "jobOperationDependency" dep2
    JOIN "jobOperation" jo2 ON jo2.id = dep2."dependsOnId"
    WHERE dep2."operationId" = op.id
      AND jo2.status != 'Done'
      AND jo2.id != p_new->>'id'
  );

  SELECT status INTO v_job_status FROM "job" WHERE id = p_new->>'jobId';
  -- A Draft/Planned job's operation can only reach Done through a released
  -- BATCH (batch release outranks job release for floor visibility), so the
  -- run genuinely happened. Completing the batch must complete those jobs
  -- too: otherwise their output lots exist while their receipts never post,
  -- and a merged output lot carries only the received fraction of its
  -- quantity.
  IF v_job_status NOT IN ('Ready', 'In Progress', 'Paused')
     AND NOT (
       (p_new->>'jobOperationBatchId') IS NOT NULL
       AND v_job_status IN ('Draft', 'Planned')
     ) THEN
    RETURN;
  END IF;

  IF is_last_job_operation(p_new->>'id') THEN
    SELECT "locationId", "storageUnitId", quantity, "salesOrderId", "quantityReceivedToInventory"
    INTO v_job_location_id, v_job_storage_unit_id, v_job_quantity, v_sales_order_id, v_quantity_received
    FROM "job"
    WHERE id = p_new->>'jobId';

    -- The units out of the routing's final operations. Two kinds of final
    -- operation report differently:
    --   * the routing's own (parallel "With Previous" operations at the end)
    --     each see EVERY unit, so a unit is finished once it has come through
    --     all of them: the smallest count. Summing them completed a 3-unit job
    --     at 6, which a serial job then refused for want of units. One closed
    --     with Finish and no quantity reports nothing, so it is left out.
    --   * a rework branch triggered at the final operation (trigger-rework)
    --     carries only the reworked units, which the operation it came from
    --     reports as reworked, not complete: those add on top.
    v_quantity_complete := (
      SELECT COALESCE(MIN(terminal_jo."quantityComplete") FILTER (
               WHERE terminal_jo."reworkId" IS NULL AND terminal_jo."quantityComplete" > 0
             ), 0)
           + COALESCE(SUM(terminal_jo."quantityComplete") FILTER (
               WHERE terminal_jo."reworkId" IS NOT NULL
             ), 0)
      FROM "jobOperation" terminal_jo
      INNER JOIN "jobMakeMethod" terminal_jmm ON terminal_jmm.id = terminal_jo."jobMakeMethodId"
      WHERE terminal_jo."jobId" = p_new->>'jobId'
        AND terminal_jmm."parentMaterialId" IS NULL
        AND terminal_jo.status <> 'Canceled'
        AND NOT EXISTS (
          SELECT 1
          FROM "jobOperationDependency" dep
          INNER JOIN "jobOperation" child_jo ON child_jo.id = dep."operationId"
          INNER JOIN "jobMakeMethod" child_jmm ON child_jmm.id = child_jo."jobMakeMethodId"
          WHERE dep."dependsOnId" = terminal_jo.id
            AND child_jmm."parentMaterialId" IS NULL
        )
    );

    IF COALESCE(v_quantity_complete, 0) = 0 THEN
      -- The zero fallback exists for the quantity-less Finish flow (no
      -- productionQuantity ever recorded). When the job DID record scrap or
      -- rework, zero completions is a real outcome (e.g. a fully-scrapped
      -- lot) — falling back would receive scrapped units into stock.
      SELECT COALESCE(SUM(COALESCE("quantityScrapped", 0) + COALESCE("quantityReworked", 0)), 0)
      INTO v_quantity_lost
      FROM "jobOperation"
      WHERE "jobId" = p_new->>'jobId';

      IF v_quantity_lost = 0 THEN
        v_quantity_complete := v_job_quantity;
      ELSE
        -- Nothing to receive: close the job without posting Assembly Output.
        -- Materials were already consumed by the scrap/complete flows; WIP
        -- cost disposition for fully-scrapped jobs is a costing follow-up.
        UPDATE "job"
        SET status = 'Completed',
            "completedDate" = NOW(),
            "quantityComplete" = 0,
            "updatedBy" = COALESCE(p_new->>'updatedBy', p_new->>'createdBy'),
            "updatedAt" = NOW()
        WHERE id = p_new->>'jobId';
        RETURN;
      END IF;
    END IF;

    -- A reopened job may already have received more than its operations now
    -- report. complete_job_to_inventory refuses a quantity below what was
    -- received, and refusing here would block the Done update itself.
    v_quantity_complete := GREATEST(v_quantity_complete, COALESCE(v_quantity_received, 0));

    PERFORM complete_job_to_inventory(
      p_job_id := p_new->>'jobId',
      p_quantity_complete := v_quantity_complete,
      p_storage_unit_id := v_job_storage_unit_id,
      p_location_id := v_job_location_id,
      p_company_id := p_new->>'companyId',
      p_user_id := COALESCE(p_new->>'updatedBy', p_new->>'createdBy')
    );
  END IF;
END;
$function$;