Skip to content

armgit / kaneo

Public Imported from GitHub
0

⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.

1.3 KB
Raw Blame
import { count, eq } from "drizzle-orm";
import db from "../../database";
import {
  workspaceBillingTable,
  workspaceUserTable,
} from "../../database/schema";
import type { DbOrTx } from "../../project-access/db-or-tx";
import { isBillingEnabled } from "../config";
import { updateSubscriptionSeats } from "../creem-client";

export async function syncWorkspaceSeats(
  workspaceId: string,
  database: DbOrTx = db,
) {
  if (!isBillingEnabled()) {
    return;
  }

  const [billing] = await database
    .select()
    .from(workspaceBillingTable)
    .where(eq(workspaceBillingTable.workspaceId, workspaceId));

  if (
    !billing?.creemSubscriptionId ||
    !billing.creemProductId ||
    billing.plan !== "team" ||
    (billing.status !== "active" && billing.status !== "trialing")
  ) {
    return;
  }

  const [members] = await database
    .select({ value: count() })
    .from(workspaceUserTable)
    .where(eq(workspaceUserTable.workspaceId, workspaceId));

  const seats = Math.max(1, members?.value ?? 1);
  if (seats === billing.seats) {
    return;
  }

  await updateSubscriptionSeats({
    subscriptionId: billing.creemSubscriptionId,
    productId: billing.creemProductId,
    units: seats,
  });

  await database
    .update(workspaceBillingTable)
    .set({ seats })
    .where(eq(workspaceBillingTable.workspaceId, workspaceId));
}