cloudaxe-opencode/packages/console/core/src/workspace.ts

77 lines
2 KiB
TypeScript
Raw Permalink Normal View History

2025-08-08 17:22:54 +00:00
import { z } from "zod"
import { fn } from "./util/fn"
import { Actor } from "./actor"
2025-10-02 21:55:54 +00:00
import { Database } from "./drizzle"
2025-08-08 17:22:54 +00:00
import { Identifier } from "./identifier"
import { UserTable } from "./schema/user.sql"
import { BillingTable } from "./schema/billing.sql"
import { WorkspaceTable } from "./schema/workspace.sql"
2025-08-29 23:56:14 +00:00
import { Key } from "./key"
2025-10-07 03:57:52 +00:00
import { eq, sql } from "drizzle-orm"
2025-08-08 17:22:54 +00:00
export namespace Workspace {
2025-10-06 20:15:10 +00:00
export const create = fn(
z.object({
2025-10-06 21:17:02 +00:00
name: z.string().min(1),
2025-10-06 20:15:10 +00:00
}),
async ({ name }) => {
const account = Actor.assert("account")
const workspaceID = Identifier.create("workspace")
const userID = Identifier.create("user")
await Database.transaction(async (tx) => {
await tx.insert(WorkspaceTable).values({
id: workspaceID,
name,
})
await tx.insert(UserTable).values({
workspaceID,
id: userID,
accountID: account.properties.accountID,
name: "",
role: "admin",
})
await tx.insert(BillingTable).values({
workspaceID,
id: Identifier.create("billing"),
balance: 0,
})
2025-08-08 17:22:54 +00:00
})
2025-10-06 20:15:10 +00:00
await Actor.provide(
"system",
{
workspaceID,
},
() => Key.create({ userID, name: "Default API Key" }),
)
return workspaceID
},
)
2025-10-06 21:13:15 +00:00
export const update = fn(
z.object({
name: z.string().min(1).max(255),
}),
async ({ name }) => {
2025-10-10 23:49:59 +00:00
Actor.assertAdmin()
2025-10-06 21:13:15 +00:00
const workspaceID = Actor.workspace()
return await Database.use((tx) =>
tx
.update(WorkspaceTable)
.set({
name,
})
.where(eq(WorkspaceTable.id, workspaceID)),
)
},
)
2025-10-07 03:57:52 +00:00
export const remove = fn(z.void(), async () => {
await Database.use((tx) =>
tx
.update(WorkspaceTable)
.set({ timeDeleted: sql`now()` })
.where(eq(WorkspaceTable.id, Actor.workspace())),
)
})
2025-08-08 17:22:54 +00:00
}