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.6 KB
Raw Blame
-- Generated by `pnpm --filter @carbon/database authz migration` from packages/database/src/authz. Do not edit.

-- Ships these rules to databases where `authz sync` does not run after migrations yet.

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$;

CREATE OR REPLACE FUNCTION public.sync_update_job_operation_quantities(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_operation_id TEXT;
  v_job_id TEXT;
  v_user_id TEXT;
  v_is_last_top_level_operation BOOLEAN := FALSE;
BEGIN
  v_user_id := COALESCE(
    p_new->>'updatedBy', p_new->>'createdBy',
    p_old->>'updatedBy', p_old->>'createdBy'
  );

  IF p_operation = 'INSERT' THEN
    v_job_operation_id := p_new->>'jobOperationId';

    UPDATE "jobOperation"
    SET
      "quantityComplete" = "quantityComplete" +
        CASE WHEN (p_new->>'type') = 'Production' THEN (p_new->>'quantity')::numeric ELSE 0 END,
      "quantityReworked" = "quantityReworked" +
        CASE WHEN (p_new->>'type') = 'Rework' THEN (p_new->>'quantity')::numeric ELSE 0 END,
      "quantityScrapped" = "quantityScrapped" +
        CASE WHEN (p_new->>'type') = 'Scrap' THEN (p_new->>'quantity')::numeric ELSE 0 END
    WHERE id = v_job_operation_id;

  ELSIF p_operation = 'UPDATE' THEN
    v_job_operation_id := p_new->>'jobOperationId';

    UPDATE "jobOperation"
    SET
      "quantityComplete" = "quantityComplete"
        - CASE WHEN (p_old->>'type') = 'Production' THEN (p_old->>'quantity')::numeric ELSE 0 END
        + CASE WHEN (p_new->>'type') = 'Production' THEN (p_new->>'quantity')::numeric ELSE 0 END,
      "quantityReworked" = "quantityReworked"
        - CASE WHEN (p_old->>'type') = 'Rework' THEN (p_old->>'quantity')::numeric ELSE 0 END
        + CASE WHEN (p_new->>'type') = 'Rework' THEN (p_new->>'quantity')::numeric ELSE 0 END,
      "quantityScrapped" = "quantityScrapped"
        - CASE WHEN (p_old->>'type') = 'Scrap' THEN (p_old->>'quantity')::numeric ELSE 0 END
        + CASE WHEN (p_new->>'type') = 'Scrap' THEN (p_new->>'quantity')::numeric ELSE 0 END
    WHERE id = v_job_operation_id;

  ELSIF p_operation = 'DELETE' THEN
    v_job_operation_id := p_old->>'jobOperationId';

    UPDATE "jobOperation"
    SET
      "quantityComplete" = "quantityComplete" -
        CASE WHEN (p_old->>'type') = 'Production' THEN (p_old->>'quantity')::numeric ELSE 0 END,
      "quantityReworked" = "quantityReworked" -
        CASE WHEN (p_old->>'type') = 'Rework' THEN (p_old->>'quantity')::numeric ELSE 0 END,
      "quantityScrapped" = "quantityScrapped" -
        CASE WHEN (p_old->>'type') = 'Scrap' THEN (p_old->>'quantity')::numeric ELSE 0 END
    WHERE id = v_job_operation_id;
  END IF;

  UPDATE "jobOperation"
  SET "status" = 'Done',
      "updatedBy" = COALESCE(v_user_id, "updatedBy", "createdBy"),
      "updatedAt" = NOW()
  WHERE id = v_job_operation_id
    AND "status" NOT IN ('Done', 'Canceled')
    AND "targetQuantity" > 0
    AND ("quantityComplete" + "quantityReworked") >= "targetQuantity";

  SELECT jo."jobId" INTO v_job_id
  FROM "jobOperation" jo
  WHERE jo.id = v_job_operation_id;

  SELECT EXISTS (
    SELECT 1
    FROM "jobOperation" jo
    INNER JOIN "jobMakeMethod" jmm ON jmm.id = jo."jobMakeMethodId"
    WHERE jo.id = v_job_operation_id
      AND jmm."parentMaterialId" IS NULL
      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" = jo.id
          AND child_jmm."parentMaterialId" IS NULL
      )
  ) INTO v_is_last_top_level_operation;

  IF v_job_id IS NOT NULL AND v_is_last_top_level_operation THEN
    UPDATE "job"
    -- Counted as sync_finish_job_operation counts the receipt: the smallest of
    -- the routing's own final operations (parallel ones each see every unit)
    -- plus what rework branches completed.
    SET "quantityComplete" = (
      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" = v_job_id
        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
        )
    )
    WHERE id = v_job_id
      AND status NOT IN ('Completed', 'Cancelled');
  END IF;
END;
$function$;