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.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 { existsSync } from "node:fs";
import path from "node:path";
import process from "node:process";
import { fileURLToPath } from "node:url";
import { parseArgs } from "node:util";
import * as dotenv from "dotenv";

// SUPABASE_DB_URL lives in the repo-root .env.local (not .env) — load both.
export function loadEnv() {
  const here = path.dirname(fileURLToPath(import.meta.url));
  const repoRoot = path.resolve(here, "..", "..", "..", "..");
  // Caller-supplied vars win: `crbn up` passes localhost URLs, while .env.local
  // holds portless hosts that don't resolve until aliases are registered.
  const preset = { ...process.env };
  dotenv.config();
  for (const file of [".env", ".env.local"]) {
    const envPath = path.join(repoRoot, file);
    if (existsSync(envPath)) dotenv.config({ path: envPath, override: true });
  }
  for (const [key, value] of Object.entries(preset)) {
    if (value !== undefined) process.env[key] = value;
  }
}

export type SeedArgs = {
  email: string;
  dataset: string;
  tiers: number[] | null;
  skipWipe: boolean;
  skipPlan: boolean;
};

function printUsage(datasets: string[]) {
  console.log(`
Usage: pnpm run db:seed:dev -- --email <email> [--dataset <key>] [--tiers 1,2,3] [--skip-wipe] [--skip-plan]

Arguments:
  --email, -e    Required. Seeds the company this user belongs to.
                 Unknown emails bootstrap a brand new user + company.
  --dataset      Which industry story to seed (default: satellite).
                 Available: ${datasets.join(", ")}
  --tiers        Dev only. Comma-separated tier numbers to run (default: all).
  --skip-wipe    Dev only. Leave existing business data in place.
  --skip-plan    Skip the MRP + scheduler run that follows the seed.

Example:
  pnpm run db:seed:dev -- --email [email protected] --dataset satellite
`);
}

export function parseSeedArgs(datasets: string[]): SeedArgs {
  // The root script forwards a bare `--`, which strict parseArgs rejects.
  const { values } = parseArgs({
    args: process.argv.slice(2).filter((a) => a !== "--"),
    options: {
      email: { type: "string", short: "e" },
      dataset: { type: "string", default: "satellite" },
      tiers: { type: "string" },
      "skip-wipe": { type: "boolean", default: false },
      "skip-plan": { type: "boolean", default: false }
    },
    strict: true
  });

  const email = values.email?.trim();
  if (!email) {
    console.error("Error: --email is required\n");
    printUsage(datasets);
    process.exit(1);
  }

  const dataset = values.dataset?.trim() ?? "satellite";
  if (!datasets.includes(dataset)) {
    console.error(
      `Error: no such dataset "${dataset}" — available: ${datasets.join(", ")}\n`
    );
    process.exit(1);
  }
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
    console.error("Error: Invalid email format\n");
    process.exit(1);
  }

  let tiers: number[] | null = null;
  if (values.tiers) {
    tiers = values.tiers
      .split(",")
      .map((t) => Number(t.trim()))
      .filter((n) => Number.isInteger(n));
    if (tiers.length === 0) {
      console.error(`Error: could not parse --tiers "${values.tiers}"\n`);
      process.exit(1);
    }
  }

  return {
    email,
    dataset,
    tiers,
    skipWipe: values["skip-wipe"] ?? false,
    skipPlan: values["skip-plan"] ?? false
  };
}