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.

11.4 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.

// Settings → Demo Data (apply an industry demo dataset, keep it or revert).
import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { DATASETS, datasetKeys } from "@carbon/database/datasets";
import { useRevalidator } from "@carbon/query";
import { toast, VStack } from "@carbon/react";
import { msg } from "@lingui/core/macro";
import { Trans } from "@lingui/react/macro";
import { useEffect, useMemo, useRef, useState } from "react";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { data, useFetcher, useLoaderData } from "react-router";
import { SettingsPageHeading } from "~/components/SettingsPage";
import type { CompanyTemplateRun } from "~/modules/settings/backups.service";
import { getCompanyTemplateRun } from "~/modules/settings/backups.service";
import {
  finalizeCompanyTemplate,
  purgeCorruptedRows,
  revertCompanyTemplate,
  startCompanyTemplate
} from "~/modules/settings/settings.service";
import {
  TemplateCards,
  TemplateReviewRow
} from "~/modules/settings/ui/DemoData";
import { getDatabaseClient } from "~/services/database.server";
import { path } from "~/utils/path";

export const handle = {
  breadcrumb: msg`Demo Data`,
  to: path.to.demoData
};

export async function loader({ request }: LoaderFunctionArgs) {
  const { client, companyId } = await requirePermissions(request, {
    update: "settings"
  });

  const run = await getCompanyTemplateRun(client, companyId);

  // Read from DATASETS rather than a hardcoded list, so a new dataset shows up
  // here without a second edit. The loader is server-only, so this import never
  // reaches the browser bundle.
  const datasets = datasetKeys().map((key) => ({
    key,
    label: DATASETS[key].label
  }));

  return { run: run.data, datasets };
}

export async function action({ request }: ActionFunctionArgs) {
  assertIsPost(request);
  const { client, companyId, userId } = await requirePermissions(request, {
    update: "settings"
  });

  const formData = await request.formData();
  const intent = formData.get("intent");
  const templateRunId = String(formData.get("templateRunId") ?? "");

  switch (intent) {
    // Replaces this company's data with a demo dataset. The job snapshots first
    // so it can be reverted; the snapshot is also what makes the wipe safe.
    case "apply": {
      const datasetKey = String(formData.get("datasetKey") ?? "");
      if (!datasetKey || !datasetKeys().includes(datasetKey as never)) {
        return { success: false, message: "Choose a demo dataset" };
      }

      // One change at a time. A second apply while one is still pending review
      // would overwrite the only snapshot of the user's real data.
      const inFlight = await getCompanyTemplateRun(client, companyId);
      if (inFlight.data && inFlight.data.status !== "failed") {
        return {
          success: false,
          message:
            "Finish your current demo data change — keep or revert it — first."
        };
      }

      try {
        const startedRunId = await startCompanyTemplate({
          companyId,
          userId,
          datasetKey
        });
        return {
          success: true,
          message: "Applying demo data",
          templateRunId: startedRunId
        };
      } catch (err) {
        return {
          success: false,
          message:
            err instanceof Error
              ? err.message
              : "Failed to start the demo data change"
        };
      }
    }

    // Keep (a ready run) and Dismiss (a failed one) are the same operation —
    // drop the snapshot, then the marker — and differ only in what the user is
    // told. The job refuses anything that isn't settled.
    case "keep":
    case "dismiss": {
      if (!templateRunId) {
        return { success: false, message: "Nothing to resolve" };
      }
      try {
        await finalizeCompanyTemplate({ companyId, templateRunId });
        return {
          success: true,
          message: intent === "keep" ? "Demo data kept" : "Dismissed"
        };
      } catch (err) {
        return data(
          { success: false },
          await flash(request, error(err, "Failed to resolve the demo data"))
        );
      }
    }

    case "revert": {
      if (!templateRunId) {
        return { success: false, message: "Nothing to revert" };
      }
      try {
        await revertCompanyTemplate({ companyId, userId, templateRunId });
        return { success: true, message: "Reverting demo data" };
      } catch (err) {
        return data(
          { success: false },
          await flash(request, error(err, "Failed to revert the demo data"))
        );
      }
    }

    // Mirrors Backups' purgeAndRestore. No finalize first: apply overwrites a
    // failed marker, and a snapshot-guard failure never recorded a snapshot.
    case "purgeAndApply": {
      const datasetKey = String(formData.get("datasetKey") ?? "");
      const current = await getCompanyTemplateRun(client, companyId);
      const failed = current.data;
      if (
        !failed ||
        !templateRunId ||
        failed.templateRunId !== templateRunId ||
        failed.status !== "failed" ||
        failed.reason !== "scope-violations" ||
        failed.datasetKey !== datasetKey ||
        !datasetKeys().includes(datasetKey as never)
      ) {
        return {
          success: false,
          message: "This demo data change can't be retried this way"
        };
      }

      // The delete commits on its own; the apply is enqueued after. Two steps,
      // not one transaction, so the messages say WHICH half happened.
      let deleted: Array<{ table: string; rows: number }>;
      try {
        ({ deleted } = await purgeCorruptedRows(
          getDatabaseClient(),
          companyId
        ));
      } catch (err) {
        return {
          success: false,
          message:
            err instanceof Error
              ? err.message
              : "Failed to remove corrupted data — nothing was deleted"
        };
      }

      const rows = deleted.reduce((sum, d) => sum + d.rows, 0);
      try {
        const startedRunId = await startCompanyTemplate({
          companyId,
          userId,
          datasetKey
        });
        return {
          success: true,
          message: `Removed ${rows} row${rows === 1 ? "" : "s"} — applying demo data`,
          templateRunId: startedRunId
        };
      } catch (err) {
        return {
          success: false,
          message:
            `Removed ${rows} row${rows === 1 ? "" : "s"}, but the demo data did not start` +
            ` — apply it again. (${
              err instanceof Error ? err.message : "unknown error"
            })`
        };
      }
    }

    default:
      return { success: false, message: "Unknown action" };
  }
}

export default function DemoDataRoute() {
  const { run, datasets } = useLoaderData<typeof loader>();
  const revalidator = useRevalidator();

  // Keep/Dismiss clear the marker through a job, so the row is hidden the moment
  // the user acts rather than a poll later. A REVERT is not resolved here — it
  // keeps running, and the row is the only thing reporting that it is.
  const [resolvedRunIds, setResolvedRunIds] = useState<string[]>([]);

  // Apply only ENQUEUES the job, so its fetcher goes idle a moment later with no
  // marker written yet — without this the button's spinner vanishes and the page
  // looks like nothing happened. Stands in until the loader sees a real run.
  const [pendingApplyKey, setPendingApplyKey] = useState<string | null>(null);
  // A run the user already resolved (a failed run being purged and re-applied)
  // doesn't count — the optimistic row stands in until the NEW run appears.
  const hasLiveRun =
    run !== null && !resolvedRunIds.includes(run.templateRunId);
  useEffect(() => {
    if (hasLiveRun) setPendingApplyKey(null);
  }, [hasLiveRun]);

  const optimisticRun: CompanyTemplateRun | null =
    !hasLiveRun && pendingApplyKey !== null
      ? {
          templateRunId: "",
          status: "running",
          datasetKey: pendingApplyKey,
          startedAt: null,
          error: null,
          progress: null,
          hasSnapshot: false,
          reason: null,
          violations: [],
          violationRowsByTable: []
        }
      : null;

  const active =
    (run !== null && run.status !== "failed") || pendingApplyKey !== null;
  const pending =
    (run !== null && !resolvedRunIds.includes(run.templateRunId)
      ? run
      : null) ?? optimisticRun;

  // The loader is the only source of run state — this revalidate is what moves
  // the row from "applying…" to Keep/Revert. The job throttles its own marker
  // writes, so a faster poll would only re-read the same row.
  useEffect(() => {
    if (!active) return;
    const id = setInterval(() => revalidator.revalidate(), 2500);
    return () => clearInterval(id);
  }, [active, revalidator]);

  const purgeFetcher = useFetcher<{ success: boolean; message: string }>();
  const [purgingRun, setPurgingRun] = useState<CompanyTemplateRun | null>(null);
  // The response a previous purge left on the fetcher — ignored, so a retry
  // doesn't settle on the old result before its own arrives.
  const staleResult = useRef<typeof purgeFetcher.data>(undefined);
  const purgeAndApply = (failed: CompanyTemplateRun) => {
    staleResult.current = purgeFetcher.data;
    setPurgingRun(failed);
    setResolvedRunIds((prev) => [...prev, failed.templateRunId]);
    setPendingApplyKey(failed.datasetKey);
    purgeFetcher.submit(
      {
        intent: "purgeAndApply",
        templateRunId: failed.templateRunId,
        datasetKey: failed.datasetKey ?? ""
      },
      { method: "post", action: path.to.demoData }
    );
  };
  const purgeResult =
    purgeFetcher.state === "idle" && purgeFetcher.data !== staleResult.current
      ? purgeFetcher.data
      : null;
  useEffect(() => {
    if (!purgeResult || !purgingRun) return;
    if (purgeResult.success) {
      toast.success(purgeResult.message);
    } else {
      toast.error(purgeResult.message);
      setResolvedRunIds((prev) =>
        prev.filter((id) => id !== purgingRun.templateRunId)
      );
      setPendingApplyKey(null);
    }
    setPurgingRun(null);
  }, [purgeResult, purgingRun]);

  const datasetLabel = useMemo(
    () => datasets.find((d) => d.key === pending?.datasetKey)?.label ?? null,
    [datasets, pending]
  );

  return (
    <VStack spacing={4} className="p-8 w-full max-w-4xl mx-auto max-md:p-4">
      <VStack spacing={1}>
        <SettingsPageHeading>
          <Trans>Demo Data</Trans>
        </SettingsPageHeading>
        <p className="text-muted-foreground text-sm">
          <Trans>
            Fill this company with a realistic industry story so every screen
            has something in it. You can put back what was here before.
          </Trans>
        </p>
      </VStack>

      {pending && (
        <TemplateReviewRow
          run={pending}
          datasetLabel={datasetLabel}
          onResolve={(id) => setResolvedRunIds((prev) => [...prev, id])}
          onPurgeAndApply={() => purgeAndApply(pending)}
        />
      )}

      <TemplateCards
        datasets={datasets}
        disabled={active}
        onApply={setPendingApplyKey}
      />
    </VStack>
  );
}