Skip to main content
The Workspace service provides functions for creating, querying, and managing workspaces within OneGlance. It handles workspace creation, member management, settings updates, and account deletion.

Core Functions

Workspace Creation

createWorkspaceForTenant

Creates a new workspace within an organization and automatically adds the creator as an owner.
import { createWorkspaceForTenant } from "@oneglanse/services";

const workspace = await createWorkspaceForTenant({
  name: "Marketing Team",
  slug: "marketing-team",
  domain: "example.com",
  tenantId: "org_abc123",
  userId: "user_xyz789"
});
args
CreateWorkspaceForTenantArgs
required
Configuration object for workspace creation
workspace
Workspace
The created workspace object containing:
  • id: Unique workspace identifier (format: workspace_*)
  • name: Workspace display name
  • slug: URL-friendly slug
  • domain: Associated domain
  • tenantId: Parent organization ID
  • schedule: Cron schedule (null initially)
  • enabledProviders: JSON array of enabled AI providers
  • createdAt: Timestamp of creation
  • deletedAt: Soft deletion timestamp (null for active workspaces)

addWorkspaceToExistingOrg

Adds a new workspace to an existing organization. Verifies user membership before creating the workspace.
import { addWorkspaceToExistingOrg } from "@oneglanse/services";

const { workspace } = await addWorkspaceToExistingOrg({
  name: "Sales Team",
  slug: "sales-team",
  domain: "example.com",
  userId: "user_xyz789",
  tenantId: "org_abc123"
});
args
object
required
workspace
Workspace
The newly created workspace object
Throws:
  • ValidationError if user is not a member of the organization

checkIsFirstWorkspace

Checks if this is the user’s first workspace (used for onboarding flows).
import { checkIsFirstWorkspace } from "@oneglanse/services";

const isFirst = await checkIsFirstWorkspace({ 
  userId: "user_xyz789" 
});

if (isFirst) {
  // Show onboarding tour
}
args.userId
string
required
User ID to check
isFirst
boolean
true if the user has no active workspace memberships, false otherwise

Workspace Queries

getWorkspaceById

Retrieves a workspace by its ID. Only returns active (non-deleted) workspaces.
import { getWorkspaceById } from "@oneglanse/services";

const workspace = await getWorkspaceById({
  workspaceId: "workspace_abc123"
});

console.log(workspace.name); // "Marketing Team"
console.log(workspace.domain); // "example.com"
args.workspaceId
string
required
Workspace ID to retrieve
workspace
Workspace
Complete workspace object with all fields
Throws:
  • ValidationError if workspaceId is empty or undefined
  • NotFoundError if workspace doesn’t exist or is deleted

getWorkspacesForUser

Fetches all workspaces within a specific organization that the user is a member of.
import { getWorkspacesForUser } from "@oneglanse/services";

const workspaces = await getWorkspacesForUser({
  tenantId: "org_abc123",
  userId: "user_xyz789"
});

workspaces.forEach(ws => {
  console.log(`${ws.name} - ${ws.domain}`);
});
args
GetWorkspacesForUserArgs
required
workspaces
Workspace[]
Array of workspaces where the user is an active member

getAllWorkspacesForUser

Retrieves all workspaces across all organizations for a user, grouped by organization.
import { getAllWorkspacesForUser } from "@oneglanse/services";

const orgGroups = await getAllWorkspacesForUser({
  userId: "user_xyz789"
});

orgGroups.forEach(group => {
  console.log(`Organization: ${group.organization.name}`);
  group.workspaces.forEach(ws => {
    console.log(`  - ${ws.name}`);
  });
});
args.userId
string
required
User ID
groups
OrganizationWorkspaceGroup[]
Array of objects, each containing:
  • organization: Organization metadata (id, name, slug)
  • workspaces: Array of workspaces in that organization

getWorkspaceMembersWithUsers

Fetches all members of a workspace with their user details.
import { getWorkspaceMembersWithUsers } from "@oneglanse/services";

const members = await getWorkspaceMembersWithUsers({
  workspaceId: "workspace_abc123"
});

members.forEach(member => {
  console.log(`${member.userName} (${member.role})`);
});
args.workspaceId
string
required
Workspace ID
members
WorkspaceMemberWithUser[]
Array of member objects with:
  • memberId: Workspace member record ID
  • userId: User ID
  • role: “owner” or “member”
  • joinedAt: Membership creation timestamp
  • userName: User’s display name
  • userEmail: User’s email address
  • userImage: User’s profile image URL

getWorkspaceJoinInfo

Generates join codes and metadata for inviting users to a workspace.
import { getWorkspaceJoinInfo } from "@oneglanse/services";

const joinInfo = await getWorkspaceJoinInfo({
  workspaceId: "workspace_abc123"
});

console.log(`Org code: ${joinInfo.orgCode}`);
console.log(`Workspace code: ${joinInfo.workspaceCode}`);
args.workspaceId
string
required
Workspace ID
joinInfo
WorkspaceJoinInfo
Contains:
  • orgCode: Organization slug or ID for joining
  • workspaceCode: Workspace ID (globally unique)
  • organization: Organization metadata
  • workspace: Workspace metadata

Member Management

addMemberToWorkspace

Adds a user to a workspace with a specified role.
import { addMemberToWorkspace } from "@oneglanse/services";

const result = await addMemberToWorkspace({
  workspaceId: "workspace_abc123",
  userId: "user_xyz789",
  role: "member" // or "owner"
});
args
AddMemberToWorkspaceArgs
required
result
AddMemberToWorkspaceResult
Contains workspaceId, userId, and assigned role
Throws:
  • ValidationError if user is already a member

removeMemberFromWorkspace

Removes a member from a workspace (soft delete). Prevents removing the last owner.
import { removeMemberFromWorkspace } from "@oneglanse/services";

await removeMemberFromWorkspace({
  workspaceId: "workspace_abc123",
  userId: "user_xyz789"
});
args
RemoveMemberFromWorkspaceArgs
required
Throws:
  • NotFoundError if member not found
  • ValidationError if attempting to remove the last owner

addMemberToWorkspaceByEmail

Adds a user to a workspace by their email address. Creates organization membership if needed.
import { addMemberToWorkspaceByEmail } from "@oneglanse/services";

const result = await addMemberToWorkspaceByEmail({
  workspaceId: "workspace_abc123",
  email: "[email protected]",
  role: "member"
});

if (result.status === "added") {
  console.log("User added successfully");
} else if (result.status === "not-found") {
  console.log("User doesn't exist - send invite");
}
args
object
required
result
object
Union type with one of:
  • { status: "added", workspaceId, userId, role } - User was added
  • { status: "already-member", workspaceId, userId } - Already a member
  • { status: "not-found" } - User account doesn’t exist

joinWorkspaceByCode

Join a workspace using an invite code. Supports organization codes, workspace codes, or combined codes.
import { joinWorkspaceByCode } from "@oneglanse/services";

const result = await joinWorkspaceByCode({
  code: "workspace_abc123", // or org slug, or "org/workspace" format
  userId: "user_xyz789"
});

if (result.status === "joined") {
  console.log(`Joined ${result.workspace.name}`);
} else if (result.status === "select-workspace") {
  // Show workspace selection UI
  console.log(`Select from ${result.workspaces.length} workspaces`);
}
args
object
required
result
object
Union type:
  • { status: "joined", organization, workspace } - Successfully joined
  • { status: "select-workspace", organization, workspaces[] } - Multiple workspaces available
Code Format Support:
  • Direct workspace ID: workspace_abc123
  • Organization slug: acme-corp (prompts workspace selection if multiple exist)
  • Combined format: acme-corp/marketing-team

Workspace Settings

updateWorkspaceDetails

Updates workspace name and domain. Automatically resets analysis if branding changes.
import { updateWorkspaceDetails } from "@oneglanse/services";

const { workspace, analysisReset } = await updateWorkspaceDetails({
  workspaceId: "workspace_abc123",
  name: "Marketing & Sales Team",
  domain: "newdomain.com"
});

if (analysisReset) {
  console.log("Analysis data reset due to brand change");
}
args
object
required
result
object
  • workspace: Updated workspace object
  • analysisReset: boolean indicating if analysis was cleared

updateOrganizationName

Updates the organization name and generates a new slug scoped to the workspace.
import { updateOrganizationName } from "@oneglanse/services";

const org = await updateOrganizationName({
  workspaceId: "workspace_abc123",
  organizationName: "Acme Corporation"
});
args
object
required
organization
Organization
Updated organization object with new name and slug

setWorkspaceEnabledProviders

Configures which AI providers are enabled for prompt execution.
import { setWorkspaceEnabledProviders } from "@oneglanse/services";
import type { Provider } from "@oneglanse/types";

const { providers } = await setWorkspaceEnabledProviders({
  workspaceId: "workspace_abc123",
  providers: ["perplexity", "chatgpt", "gemini"]
});
args
object
required
providers
Provider[]
The updated array of enabled providers

updateWorkspaceSchedule

Sets or clears the cron schedule for automatic prompt execution.
import { updateWorkspaceSchedule } from "@oneglanse/services";

// Set daily schedule at 9 AM
const { schedule } = await updateWorkspaceSchedule({
  workspaceId: "workspace_abc123",
  userId: "user_xyz789",
  schedule: "0 9 * * *" // cron expression
});

// Clear schedule
await updateWorkspaceSchedule({
  workspaceId: "workspace_abc123",
  userId: "user_xyz789",
  schedule: null
});
args
object
required
schedule
string | null
The updated schedule value
Note: Uses PostgreSQL pg_cron extension. Failures to configure cron are non-fatal and logged as warnings.

Account Management

deleteUserAccount

Permanently deletes a user account and cleans up associated workspaces and organizations.
import { deleteUserAccount } from "@oneglanse/services";

await deleteUserAccount({
  userId: "user_xyz789"
});
args.userId
string
required
User ID to delete
Behavior:
  • If user is the sole owner of an organization:
    • Soft-deletes all workspaces in that org
    • Soft-deletes all workspace members
    • Deletes the organization (cascades member and invitation rows)
  • If user is one of multiple owners:
    • Only removes the user’s membership
    • Leaves organization and workspaces intact
  • Soft-deletes remaining workspace memberships
  • Deletes user account (cascades sessions and auth records)

Usage in tRPC Routers

Example from apps/web/src/server/api/routers/workspace/_routes/protectedRoutes.ts:
import { 
  createWorkspaceForTenant,
  checkIsFirstWorkspace,
  getAllWorkspacesForUser 
} from "@oneglanse/services";
import { protectedProcedure } from "../../../procedures";

export const protectedWorkspaceRoutes = {
  create: protectedProcedure
    .input(createWorkspaceInputSchema)
    .mutation(async ({ input, ctx }) => {
      const { user: { id: userId } } = ctx;
      const { organizationName, name, slug, domain } = input;

      const isFirstWorkspace = await checkIsFirstWorkspace({ userId });
      
      // Create organization via auth API
      const org = await auth.api.createOrganization({
        body: { name: organizationName || name, slug },
        headers: ctx.headers,
      });

      // Create workspace
      const workspace = await createWorkspaceForTenant({
        name, slug, domain,
        tenantId: org.id,
        userId,
      });

      return { workspace, org, isFirstWorkspace };
    }),

  listAllForUser: protectedProcedure.query(async ({ ctx }) => {
    return getAllWorkspacesForUser({ userId: ctx.user.id });
  }),
};

Type Definitions

All types are exported from @oneglanse/types:
import type {
  Workspace,
  CreateWorkspaceForTenantArgs,
  GetWorkspaceByIdArgs,
  GetWorkspacesForUserArgs,
  GetWorkspaceMembersWithUsersArgs,
  WorkspaceMemberWithUser,
  AddMemberToWorkspaceArgs,
  RemoveMemberFromWorkspaceArgs,
  WorkspaceJoinInfo,
  Provider,
} from "@oneglanse/types";

Source Files

Workspace service functions are implemented in:
  • packages/services/src/workspace/create.ts - Workspace creation functions
  • packages/services/src/workspace/query.ts - Query and retrieval functions
  • packages/services/src/workspace/members.ts - Member management functions
  • packages/services/src/workspace/settings.ts - Settings and configuration
  • packages/services/src/workspace/account.ts - Account deletion logic
All exports are re-exported through packages/services/src/workspace/index.ts.

Build docs developers (and LLMs) love