Skip to main content
doc0blade47/dubdocumentation home
Sign in

Quick Start

Last updated Oct 12, 2026
Relevant source files

The following files were used as context for generating this wiki page:

Overview

The Quick Start page documents the local development environment, database seeding pipelines, bulk test data generators, integration emulators, and historical data maintenance scripts used across the monorepo web application apps/web/package.json:1-20. It provides developers with complete orchestration steps for configuring containerized database infrastructure, running deterministic dataset builders, simulating third-party webhook conversions, and executing schema backfills apps/web/docker-compose.yml:1-45. Sources: apps/web/docker-compose.yml:1-45, apps/web/package.json:1-20

Local Environment and Infrastructure Setup

Containerized Infrastructure Services

Local development relies on Docker Compose to provision auxiliary databases, database compatibility proxies, and mail servers required by the web application. The service definitions run on version 3.8 and are intended exclusively for local development apps/web/docker-compose.yml:1-3.

version: "3.8"
 
services:
  ps-mysql:
    image: mysql:8.0
    restart: always
    environment:
      MYSQL_DATABASE: planetscale
      MYSQL_ROOT_HOST: "%"
      MYSQL_ALLOW_EMPTY_PASSWORD: "yes"
    command:
      [
        "--max_connections=1000",
        "--default-authentication-plugin=mysql_native_password",
      ]
    ports:
      - 3306:3306
    volumes:
      - ps-mysql:/var/lib/mysql
 
  planetscale-proxy:
    image: ghcr.io/mattrobenolt/ps-http-sim:latest
    command:
      [
        "-mysql-no-pass",
        "-listen-port=3900",
        "-mysql-dbname=planetscale",
        "-mysql-addr=ps-mysql",
      ]
    depends_on:
      - ps-mysql
    ports:
      - 3900:3900
    links:
      - ps-mysql
 
  mailhog:
    image: "mailhog/mailhog:latest"
    ports:
      - "1025:1025"
      - "8025:8025"
 
volumes:
  ps-mysql:

Sources: apps/web/docker-compose.yml:1-45

Note

The planetscale-proxy service simulates PlanetScale HTTP API interactions by communicating directly with the underlying ps-mysql container on port 3900. Sources: apps/web/docker-compose.yml:22-37

Monorepo Scripts and Web App Configuration

The Turborepo monorepo coordinates task execution across packages using global dependencies defined on root configuration files turbo.json:1-19. The web application package (apps/web) exposes dedicated scripts for Prisma client generation, schema pushing, database management, testing, and starting the local development server apps/web/package.json:1-20.

Script CommandTarget Action & Tooling
devpnpm prisma:generate && concurrently --kill-others "next dev --turbopack --port 8888" apps/web/package.json:6
buildpnpm prisma:generate && next build apps/web/package.json:7
scripttsx ./scripts/run.ts apps/web/package.json:10
testpnpm prisma:generate && vitest -no-file-parallelism --bail=1 apps/web/package.json:11
prisma:generatedotenv-flow -e .env -- prisma generate --schema=./prisma/schema apps/web/package.json:16
prisma:pushdotenv-flow -e .env -- prisma db push --schema=./prisma/schema apps/web/package.json:17
prisma:studiodotenv-flow -e .env -- prisma studio --schema=./prisma/schema --browser none apps/web/package.json:18

Sources: apps/web/package.json:5-20

Warning

Always execute prisma:generate before launching the dev server or running test suites to ensure the Prisma client aligns with the current database schema. Sources: apps/web/package.json:6-11

Baseline Database Seeding Workflow

Fixture Loading and Workspace Initialization

The database seeding workflow relies on structured fixtures defined in JSON format to populate foundational entities via Prisma ORM [[Database Architecture]]. The seeding script reads apps/web/scripts/dev/data.json using Node's filesystem and path modules through parseJSON() apps/web/scripts/dev/seed.ts:137-141. The root workspace fixture provides configuration metadata, quotas, limits, and identifiers for the enterprise test workspace Overview.

const parseJSON = (): SeedData => {
  const jsonPath = path.join(__dirname, "data.json");
  const jsonData = JSON.parse(fs.readFileSync(jsonPath, "utf-8"));
  return jsonData;
};

Sources: apps/web/scripts/dev/seed.ts:137-141

The workspace creation function extracts the workspace payload and inserts a new Project record using Prisma Database Architecture, logging the assigned identifier upon successful completion apps/web/scripts/dev/seed.ts:144-152.

const createWorkspace = async (data: SeedData) => {
  const { workspace } = data;
 
  const { id } = await prisma.project.create({
    data: workspace,
  });
 
  console.log(`Created workspace ${id}`);
};

Sources: apps/web/scripts/dev/seed.ts:144-152

Tip

The seed runner enforces safety checks via assertLocalDatabaseEnv before executing mutation operations to prevent running development fixtures against production environments. Sources: apps/web/scripts/dev/seed.ts:22

User and Role Seeding Architecture

User initialization provisions both global user records and workspace-level membership bindings. The createUsers function hashes a standard test password (password) using hashPassword and bulk-inserts user entities via prisma.user.createMany apps/web/scripts/dev/seed.ts:155-173. Each user maps to specific workspace roles defined within the fixture data.

Sources: apps/web/scripts/dev/data.json:26-55

Following user creation, the script establishes project memberships in ProjectUsers and initializes default notification preferences by querying back the inserted relation identifiers apps/web/scripts/dev/seed.ts:177-210.

  const { count: projectUsersCount } = await prisma.projectUsers.createMany({
    data: users.map((user) => ({
      projectId: workspace.id,
      userId: user.id,
      role: user.role,
    })),
  });

Sources: apps/web/scripts/dev/seed.ts:177-184

Warning

Because createMany in Prisma does auto-increment or relational ID generation without returning inserted records on certain database adapters, the seeding script performs an explicit findMany query on ProjectUsers to retrieve generated relation IDs before seeding NotificationPreference records. Sources: apps/web/scripts/dev/seed.ts:187-205

Bulk Partner Dataset Generation

Large-Scale Dataset Generator Configuration

The bulk partner seeding utility generates high-volume partner records for local development and partner-search performance benchmarking apps/web/scripts/dev/seed-100k-partners.ts:1-7. It writes relational models including User, Partner, PartnerUser, ProgramEnrollment, PartnerPlatform, Link, and ProgramPartnerTag in atomic chunks of 2,500 partners apps/web/scripts/dev/seed-100k-partners.ts:4-6, apps/web/scripts/dev/seed-100k-partners.ts:40.

Constant NameValuePurpose
DEFAULT_COUNT100_000 apps/web/scripts/dev/seed-100k-partners.ts:37Default number of partner records generated when no count argument is supplied.
MAX_COUNT1_000_000 apps/web/scripts/dev/seed-100k-partners.ts:38Upper ceiling for bulk partner generation runs.
DEFAULT_SEED"partners-search" apps/web/scripts/dev/seed-100k-partners.ts:39Default deterministic seed string for hash generation.
CHUNK_SIZE2_500 apps/web/scripts/dev/seed-100k-partners.ts:40Number of records processed per atomic database transaction chunk.

Sources: apps/web/scripts/dev/seed-100k-partners.ts:37-40

Caution

The script inserts login-capable users with a known password. It refuses non-local DATABASE_URL connections unless --allowRemoteDatabase is explicitly passed, and halts execution outright if production environment variables (NODE_ENV or VERCEL_ENV) are detected. Sources: apps/web/scripts/dev/seed-100k-partners.ts:18-20

Partner Enrollment and Single-Record Seeding

For targeted testing and single-record validation, the partner enrollment script provisions individual test entities associated with specific program and referrer identifiers apps/web/scripts/dev/seed-partner-enrollment.ts:6-8. It validates target program existence and retrieves default group settings before creating relational binding rows apps/web/scripts/dev/seed-partner-enrollment.ts:10-22.

const suffix = nanoid(3);
const email = `partner-${suffix}@dub-internal-test.com`;
const name = `Partner ${suffix}`;
 
const userId = createId({ prefix: "user_" });
const partnerId = createId({ prefix: "pn_" });
 
await prisma.user.create({
  data: {
    id: userId,
    email,
    name,
    emailVerified: new Date(),
    defaultPartnerId: partnerId,
  },
});

Sources: apps/web/scripts/dev/seed-partner-enrollment.ts:24-39

Note

Single-record enrollment seeding automatically generates a ProgramApplicationEvent recording direct referral source parameters, visit timestamps, and immediate approval states for the newly provisioned partner. Sources: apps/web/scripts/dev/seed-partner-enrollment.ts:72-83

Partner Programs and Commission Simulation

Commission Seeding and Referral Batch Testing

The development scripts for partner programs provide utilities to populate test commission records and trigger referral batch processing jobs. The commission seeding script targets the ACME partner program identifier (prog_1K2J9DRWPPJ2F1RX53N92TSGA) and a specific partner identifier (pn_1K2J9DRWPPJ2F1RX53N92TSGG) to insert referral commission rows via Prisma's createMany operation with skipDuplicates enabled.

Variable NameValuePurpose
programId"prog_1K2J9DRWPPJ2F1RX53N92TSGA" apps/web/scripts/dev/seed-commissions.ts:7Target program identifier for seed commissions.
partnerId"pn_1K2J9DRWPPJ2F1RX53N92TSGG" apps/web/scripts/dev/seed-commissions.ts:8Target partner identifier receiving the simulated earnings.

Sources: apps/web/scripts/dev/seed-commissions.ts:7-8

const commissions: Prisma.CommissionCreateManyInput[] = [
  {
    id: createId({ prefix: "cm_" }),
    programId,
    partnerId,
    type: "referral",
    amount: 0,
    quantity: 1,
    earnings: 10000,
    createdAt: new Date(),
  },
  {
    id: createId({ prefix: "cm_" }),
    programId,
    partnerId,
    type: "referral",
    amount: 0,
    quantity: 1,
    earnings: 20000,
    createdAt: new Date(),
  },
];
 
const response = await prisma.commission.createMany({
  data: commissions,
  skipDuplicates: true,
});

Sources: apps/web/scripts/dev/seed-commissions.ts:10-36

Note

Simulated commissions are created with explicit integer earnings values representing minor currency units (such as $100.00 and $200.00) alongside prefixed IDs generated by createId with the cm_ prefix. Sources: apps/web/scripts/dev/seed-commissions.ts:10-31

To simulate end-to-end referral processing, the referral testing utility queries existing payout records for the program and dispatches queue jobs to the commission referral endpoint.

const payouts = await prisma.payout.findMany({
  where: {
    programId: "prog_1K2J9DRWPPJ2F1RX53N92TSGA",
  },
});
 
await enqueueBatchJobs(
  payouts.map(({ id }) => ({
    queueName: "create-referral-commissions",
    url: `${APP_DOMAIN_WITH_NGROK}/api/cron/commissions/referrals/queue`,
    body: {
      payoutId: id,
    },
  })),
);

Sources: apps/web/scripts/dev/test-partner-referrals.ts:8-22

Tip

The partner referral testing utility uses APP_DOMAIN_WITH_NGROK to construct local endpoint URLs, allowing queued cron requests to reach local development servers via tunnel adapters. Sources: apps/web/scripts/dev/test-partner-referrals.ts:5-18

Application Lifecycle Event Seeding

The application event seeding utility populates ProgramApplicationEvent records for partners enrolled in the ACME program (ACME_PROGRAM_ID). It simulates the complete funnel from initial site visit to final program decision.

const programId = ACME_PROGRAM_ID;
const referredByPartnerIds = ["pn_1K2J9DRWPPJ2F1RX53N92TSGH"];
 
const programEnrollments = await prisma.programEnrollment.findMany({
  where: {
    programId,
    partnerId: {
      notIn: referredByPartnerIds,
    },
  },
  orderBy: {
    createdAt: "asc",
  },
  select: {
    partnerId: true,
    partner: {
      select: {
        country: true,
      },
    },
  },
  take: 1,
});
 
if (programEnrollments.length === 0) {
  console.log(`No enrollments found for program ${programId}`);
  return;
}

Sources: apps/web/scripts/dev/seed-application-events.ts:28-55

The script computes randomized milestone timestamps across a thirty-day sliding window, assigning referral sources from a predefined array and determining approval states probabilistically.

Referral SourceDescription / Origin
"direct" apps/web/scripts/dev/seed-application-events.ts:19Direct traffic arrival without an intermediary referrer domain.
"linkedin.com" apps/web/scripts/dev/seed-application-events.ts:20Professional network referral traffic.
"twitter.com" apps/web/scripts/dev/seed-application-events.ts:21Social media platform referral traffic.
"marketplace" apps/web/scripts/dev/seed-application-events.ts:22Partner marketplace discovery channel.
"acme.com" apps/web/scripts/dev/seed-application-events.ts:23Internal property referral source.
"google.com" apps/web/scripts/dev/seed-application-events.ts:24Search engine referral traffic.

Sources: apps/web/scripts/dev/seed-application-events.ts:18-25

const { count } = await prisma.programApplicationEvent.createMany({
  data: programEnrollments.map((programEnrollment) => {
    const visitedAt = randomDateBetween(thirtyDaysAgo, now);
 
    const startedAt = new Date(
      visitedAt.getTime() + randomInt(1, 30) * 60 * 1000,
    );
 
    const submittedAt = new Date(
      startedAt.getTime() + randomInt(1, 90) * 60 * 1000,
    );
 
    const decidedAt = new Date(
      submittedAt.getTime() + randomInt(5, 72) * 60 * 60 * 1000,
    );
 
    const isApproved = Math.random() < 0.7;
 
    return {
      programId,
      partnerId: programEnrollment.partnerId,
      visitedAt,
      startedAt,
      submittedAt,
      approvedAt: isApproved ? decidedAt : null,
      rejectedAt: isApproved ? null : decidedAt,
      referralSource: sample(referralSources),
      country: programEnrollment.partner.country ?? null,
      referredByPartnerId: sample(referredByPartnerIds),
    };
  }),
  skipDuplicates: true,
});

Sources: apps/web/scripts/dev/seed-application-events.ts:60-92

Warning

Application event seeding applies a 70% approval probability (Math.random() < 0.7) to populate either approvedAt or rejectedAt timestamps exclusively based on the decision outcome. Sources: apps/web/scripts/dev/seed-application-events.ts:76-85

Integration Seeding and Event Emulation

Third-Party Integration Fixtures

Development environments configure third-party application integrations using database upsert utilities. The integration seeding script targets the ACME workspace (ACME_WORKSPACE_ID) to provision an Intercom integration installation (INTERCOM_INTEGRATION_ID) associated with user cl7p1s07k000687rbuhpwqkqa.

async function main() {
  await prisma.installedIntegration.upsert({
    where: {
      userId_integrationId_projectId: {
        userId: "cl7p1s07k000687rbuhpwqkqa",
        integrationId: INTERCOM_INTEGRATION_ID,
        projectId: ACME_WORKSPACE_ID,
      },
    },
    create: {
      userId: "cl7p1s07k000687rbuhpwqkqa",
      integrationId: INTERCOM_INTEGRATION_ID,
      projectId: ACME_WORKSPACE_ID,
      credentials: {
        appId: "xxx",
        accessToken: encrypt("xxx"),
      },
    },
    update: {
      //
    },
  });
}

Sources: apps/web/scripts/dev/seed-integration.ts:7-29

Tip

Intercom integration credentials are encrypted via the encrypt utility before storage in the InstalledIntegration table, ensuring sensitive tokens and application identifiers remain protected at rest. Sources: apps/web/scripts/dev/seed-integration.ts:1-24

Global platform integrations are registered using integration creation scripts. For instance, the Google Ads integration definition upserts descriptive metadata, verification flags, and developer ownership under the DUB workspace (DUB_WORKSPACE_ID).

async function main() {
  const integration = await prisma.integration.upsert({
    where: {
      id: GOOGLE_ADS_INTEGRATION_ID,
    },
    create: {
      id: GOOGLE_ADS_INTEGRATION_ID,
      name: "Google Ads",
      slug: "google-ads",
      description:
        "Upload offline click conversions to Google Ads to optimize ad performance.",
      developer: "Dub",
      website: "https://ads.google.com",
      verified: true,
      projectId: DUB_WORKSPACE_ID,
      category: "Analytics",
    },
    update: {
      name: "Google Ads",
      slug: "google-ads",
      description:
        "Upload offline click conversions to Google Ads to optimize ad performance.",
      verified: true,
      category: "Analytics",
    },
  });

Sources: apps/web/scripts/create-integration.ts:6-31

Shopify Conversion and Webhook Simulation

End-to-end e-commerce conversion testing is handled by simulation scripts that emulate Shopify pixel tracking and signed order webhook payloads against local server endpoints.

async function main() {
  const clickId = "RZjkGhi04FGxWjcK";
  const checkoutToken = nanoid(10);
  const storeId = "store.dub.co";
  const existingCustomerId = null;
  const discountCode = null;
 
  await trackPixel({
    clickId,
    checkoutToken,
  });
 
  await sleep(4000);
 
  await trackOrderPaid({
    checkoutToken,
    storeId,
    existingCustomerId,
    discountCode,
  });
}

Sources: apps/web/scripts/dev/simulate-shopify-conversion.ts:6-26

The simulation workflow executes in two sequential stages: first posting a click identifier and checkout token to the pixel tracking endpoint, pausing for four seconds using sleep(4000), and subsequently dispatching a paid order webhook request with HMAC signature verification headers.

async function trackPixel({
  clickId,
  checkoutToken,
}: {
  clickId: string;
  checkoutToken: string;
}) {
  const response = await fetch("http://localhost:8888/api/shopify/pixel", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      clickId,
      checkoutToken,
    }),
  });
 
  const data = await response.json();
 
  console.log("trackPixel", data);
}
 
async function trackOrderPaid({
  checkoutToken,
  storeId,
  existingCustomerId,
  discountCode,
}: {
  checkoutToken: string;
  storeId: string;
  existingCustomerId?: string | null;
  discountCode?: string | null;
}) {
  const payload = shopifyOrderPayload({
    checkoutToken,
    ...(existingCustomerId && {
      customer: { id: existingCustomerId },
    }),
    ...(discountCode && {
      discount_codes: [{ code: discountCode }],
    }),
  });
 
  const body = JSON.stringify(payload);
  const signature = shopifyWebhookSignature(body);
 
  const response = await fetch(
    "http://localhost:8888/api/shopify/integration/webhook",
    {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "x-shopify-topic": "orders/paid",
        "x-shopify-shop-domain": storeId,
        ...(signature && { "x-shopify-hmac-sha256": signature }),
      },
      body,
    },
  );
 
  const data = await response.text();
 
  console.log("trackOrderPaid", data);
}

Sources: apps/web/scripts/dev/simulate-shopify-conversion.ts:28-92

Header NameSource Value / ExpressionPurpose
"Content-Type""application/json" apps/web/scripts/dev/simulate-shopify-conversion.ts:80Specifies JSON payload encoding for the webhook body.
"x-shopify-topic""orders/paid" apps/web/scripts/dev/simulate-shopify-conversion.ts:81Identifies the e-commerce event type for handler routing.
"x-shopify-shop-domain"storeId ("store.dub.co") apps/web/scripts/dev/simulate-shopify-conversion.ts:9, 82Specifies the originating merchant store domain.
"x-shopify-hmac-sha256"signature (Base64 HMAC) apps/web/scripts/dev/simulate-shopify-conversion.ts:73, 83Authenticates webhook payload integrity using SHOPIFY_WEBHOOK_SECRET.

Sources: apps/web/scripts/dev/simulate-shopify-conversion.ts:75-87

Warning

Webhook signature generation requires the SHOPIFY_WEBHOOK_SECRET environment variable; if unset, signature generation returns undefined, which omits the x-shopify-hmac-sha256 header from the simulation request. Sources: apps/web/scripts/dev/simulate-shopify-conversion.ts:94-102

Data Maintenance and Schema Backfills

Historical Migration Scripts

Data maintenance operations often require running standalone migration scripts to backfill historical data or align database records with updated schema requirements. For instance, the application event backfill script scans ProgramApplication records lacking application events in batches of 250, inferring referral sources, timestamps, and review milestones.

while (true) {
  const programApplications = await prisma.programApplication.findMany({
    where: {
      programApplicationEvents: {
        none: {},
      },
    },
    include: {
      enrollment: {
        include: {
          partner: true,
          links: {
            orderBy: {
              createdAt: "asc",
            },
            take: 1,
          },
        },
      },
    },
    take: 250,
  });

Sources: apps/web/scripts/migrations/backfill-application-events.ts:10-31

When backfilling events created after the program marketplace launch date of 2025-12-09, if the associated enrollment was created within five seconds of the application, the script classifies the referral source as "marketplace"; otherwise, it defaults to "direct". Visited timestamps are simulated by subtracting between 300 and 600 seconds from the application creation time, while application start times are offset by an additional 15 to 45 seconds.

// for applications created after 2025-12-09 (program marketplace launch),
// if the enrollment was created within 5 seconds of the application, it's a marketplace referral
const referralSource =
  enrollment &&
  programApplication.createdAt > new Date("2025-12-09") &&
  differenceInSeconds(
    enrollment.createdAt,
    programApplication.createdAt,
  ) < 5
    ? "marketplace"
    : "direct";
 
// average time from view -> submission is 5-10 mins so let's do 5 min + random seconds between 0-300
const visitedAt = subSeconds(
  programApplication.createdAt,
  300 + randomInt(0, 300),
);
// assume starts application after 15-45 seconds
const startedAt = addSeconds(visitedAt, randomInt(15, 45));
 

Sources: apps/web/scripts/migrations/backfill-application-events.ts:42-61

Warning

Program application event backfilling uses randomized time offsets (randomInt) to estimate visitor behavior durations; running the script multiple times without transaction isolation against active production data can result in non-deterministic event history. Sources: apps/web/scripts/migrations/backfill-application-events.ts:54-61

Event Metadata and Schema Consistency Verification

Backfilling metadata across systems involves querying analytical data stores like Tinybird pipes to populate relational columns. The commission metadata backfill script connects to Tinybird via internal_get_events_metadata to retrieve event metadata, filtering out internal webhook payloads from Stripe or Shopify before updating Prisma records.

const getEventsMetadata = tb.buildPipe({
  pipe: "internal_get_events_metadata",
  parameters: z.object({
    eventIds: z.string().array(),
  }),
  data: z.object({
    event_id: z.string(),
    metadata: z.string(),
  }),
});

Sources: apps/web/scripts/migrations/backfill-commissions-metadata.ts:31-40

To ensure relational integrity between migrated entities, verification scripts perform read-only comparisons across tables. The program application status verification script scans enrollments created before 2026-10-01T00:00:00.000Z in batches of 100, checking for status, partner ID, and program ID mismatches.

const BATCH_SIZE = 100;
const CREATED_BEFORE = new Date("2026-10-01T00:00:00.000Z");
 
function getApplicationStatusFromEnrollment(
  enrollmentStatus: ProgramEnrollmentStatus,
): ProgramApplicationStatus {

Sources: apps/web/scripts/migrations/verify-backfill-program-application-status.ts:8-13

Enrollment Status (ProgramEnrollmentStatus)Expected Application Status (ProgramApplicationStatus)Purpose
pendingpending apps/web/scripts/migrations/verify-backfill-program-application-status.ts:14-16Preserves unreviewed application states during verification.
rejectedrejected apps/web/scripts/migrations/verify-backfill-program-application-status.ts:18-20Maintains denial consistency across enrollment records.
All other active statusesapproved apps/web/scripts/migrations/verify-backfill-program-application-status.ts:22Maps successful or active enrollments to approved applications.

Sources: apps/web/scripts/migrations/verify-backfill-program-application-status.ts:11-23

Tip

The commission metadata backfill script supports a DRY_RUN constant flag set to true by default, allowing operators to preview updates and inspect parsed JSON payloads before executing raw SQL updates against the Commission table. Sources: apps/web/scripts/migrations/backfill-commissions-metadata.ts:25-28, 195-226

Was this page helpful?