Skip to content

armgit / posta

Public Imported from GitHub
0

Self-hosted email delivery platform that enables applications to send emails via HTTP APIs while handling SMTP delivery, templates, storage, security, and analytics. Fully self-hostable alternative to services like SendGrid or Mailgun.

feat(admin): add workspaces list and detail pages

Jonas Kaninda13110d1e23f6
diff --git a/internal/handlers/admin_workspace_handler.go b/internal/handlers/admin_workspace_handler.go
new file mode 100644
index 0000000..714b390
--- /dev/null
+++ b/internal/handlers/admin_workspace_handler.go
@@ -0,0 +1,273 @@
+// Copyright (c) 2026 Jonas Kaninda.
+//
+// This file is part of Posta.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+//
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package handlers
+
+import (
+ "time"
+
+ "github.com/goposta/posta/internal/models"
+ "github.com/goposta/posta/internal/storage/repositories"
+ "github.com/jkaninda/okapi"
+ "gorm.io/gorm"
+)
+
+type AdminWorkspaceHandler struct {
+ db *gorm.DB
+ repo *repositories.WorkspaceRepository
+}
+
+func NewAdminWorkspaceHandler(db *gorm.DB, repo *repositories.WorkspaceRepository) *AdminWorkspaceHandler {
+ return &AdminWorkspaceHandler{db: db, repo: repo}
+}
+
+// AdminWorkspaceRow is one line of the platform-wide workspace table.
+type AdminWorkspaceRow struct {
+ ID uint `json:"id"`
+ Name string `json:"name"`
+ Slug string `json:"slug"`
+ System bool `json:"system"`
+ OwnerID uint `json:"owner_id"`
+ OwnerName string `json:"owner_name"`
+ OwnerEmail string `json:"owner_email"`
+ PlanID *uint `json:"plan_id"`
+ PlanName string `json:"plan_name"`
+ MemberCount int64 `json:"member_count"`
+ CreatedAt time.Time `json:"created_at"`
+}
+
+// AdminWorkspaceMember is a workspace member with the account details an
+// administrator needs to follow up on them.
+type AdminWorkspaceMember struct {
+ UserID uint `json:"user_id"`
+ Name string `json:"name"`
+ Email string `json:"email"`
+ Active bool `json:"active"`
+ Role models.WorkspaceRole `json:"role"`
+ JoinedAt time.Time `json:"joined_at"`
+}
+
+// AdminWorkspaceUsage counts the resources a workspace holds.
+type AdminWorkspaceUsage struct {
+ Emails int64 `json:"emails"`
+ Templates int64 `json:"templates"`
+ Contacts int64 `json:"contacts"`
+ Subscribers int64 `json:"subscribers"`
+ Campaigns int64 `json:"campaigns"`
+ Domains int64 `json:"domains"`
+ SMTPServers int64 `json:"smtp_servers"`
+ APIKeys int64 `json:"api_keys"`
+ Webhooks int64 `json:"webhooks"`
+}
+
+// AdminWorkspaceDetail adds membership, pending invitations and resource usage.
+type AdminWorkspaceDetail struct {
+ AdminWorkspaceRow
+ Description string `json:"description"`
+ DefaultLanguage string `json:"default_language"`
+ UpdatedAt time.Time `json:"updated_at"`
+ Members []AdminWorkspaceMember `json:"members"`
+ PendingInvitations int64 `json:"pending_invitations"`
+ Usage AdminWorkspaceUsage `json:"usage"`
+}
+
+type AdminListWorkspacesRequest struct {
+ Page int `query:"page" default:"0"`
+ Size int `query:"size" default:"20"`
+ Search string `query:"search" doc:"Match part of the workspace name or slug"`
+ Owner int `query:"owner" doc:"Restrict to workspaces owned by this user id"`
+ Plan int `query:"plan" doc:"Restrict to workspaces assigned this plan id"`
+}
+
+type AdminWorkspaceIDRequest struct {
+ ID int `param:"id"`
+}
+
+func (h *AdminWorkspaceHandler) List(c *okapi.Context, req *AdminListWorkspacesRequest) error {
+ page, size, offset := normalizePageParams(req.Page, req.Size)
+
+ filter := repositories.AdminWorkspaceFilter{Search: req.Search}
+ if req.Owner > 0 {
+ owner := uint(req.Owner)
+ filter.OwnerID = &owner
+ }
+ if req.Plan > 0 {
+ plan := uint(req.Plan)
+ filter.PlanID = &plan
+ }
+
+ workspaces, total, err := h.repo.FindAllFiltered(filter, size, offset)
+ if err != nil {
+ return c.AbortInternalServerError("failed to list workspaces")
+ }
+
+ owners := h.owners(workspaces)
+ plans := h.planNames(workspaces)
+ members := h.memberCounts(workspaces)
+
+ rows := make([]AdminWorkspaceRow, 0, len(workspaces))
+ for i := range workspaces {
+ rows = append(rows, h.row(&workspaces[i], owners, plans, members))
+ }
+ return paginated(c, rows, total, page, size)
+}
+
+func (h *AdminWorkspaceHandler) Get(c *okapi.Context, req *AdminWorkspaceIDRequest) error {
+ ws, err := h.repo.FindByID(uint(req.ID))
+ if err != nil {
+ return c.AbortNotFound("workspace not found")
+ }
+ one := []models.Workspace{*ws}
+
+ members, err := h.repo.ListMembers(ws.ID)
+ if err != nil {
+ return c.AbortInternalServerError("failed to list workspace members")
+ }
+ memberRows := make([]AdminWorkspaceMember, 0, len(members))
+ for i := range members {
+ m := &members[i]
+ memberRows = append(memberRows, AdminWorkspaceMember{
+ UserID: m.UserID,
+ Name: m.User.Name,
+ Email: m.User.Email,
+ Active: m.User.Active,
+ Role: m.Role,
+ JoinedAt: m.CreatedAt,
+ })
+ }
+
+ detail := AdminWorkspaceDetail{
+ AdminWorkspaceRow: h.row(ws, h.owners(one), h.planNames(one), map[uint]int64{ws.ID: int64(len(members))}),
+ Description: ws.Description,
+ DefaultLanguage: ws.DefaultLanguage,
+ UpdatedAt: ws.UpdatedAt,
+ Members: memberRows,
+ Usage: h.usage(ws.ID),
+ }
+ h.db.Model(&models.WorkspaceInvitation{}).
+ Where("workspace_id = ? AND status = ? AND expires_at > ?", ws.ID, models.InvitationStatusPending, time.Now()).
+ Count(&detail.PendingInvitations)
+
+ return ok(c, detail)
+}
+
+func (h *AdminWorkspaceHandler) row(ws *models.Workspace, owners map[uint]models.User, plans map[uint]string, members map[uint]int64) AdminWorkspaceRow {
+ row := AdminWorkspaceRow{
+ ID: ws.ID,
+ Name: ws.Name,
+ Slug: ws.Slug,
+ System: ws.System,
+ OwnerID: ws.OwnerID,
+ OwnerName: owners[ws.OwnerID].Name,
+ OwnerEmail: owners[ws.OwnerID].Email,
+ PlanID: ws.PlanID,
+ MemberCount: members[ws.ID],
+ CreatedAt: ws.CreatedAt,
+ }
+ if ws.PlanID != nil {
+ row.PlanName = plans[*ws.PlanID]
+ }
+ return row
+}
+
+// usage counts each resource type through its model so soft-deleted rows are
+// left out the same way the workspace's own views leave them out.
+func (h *AdminWorkspaceHandler) usage(workspaceID uint) AdminWorkspaceUsage {
+ var u AdminWorkspaceUsage
+ count := func(model any, dst *int64) {
+ h.db.Model(model).Where("workspace_id = ?", workspaceID).Count(dst)
+ }
+ count(&models.Email{}, &u.Emails)
+ count(&models.Template{}, &u.Templates)
+ count(&models.Contact{}, &u.Contacts)
+ count(&models.Subscriber{}, &u.Subscribers)
+ count(&models.Campaign{}, &u.Campaigns)
+ count(&models.Domain{}, &u.Domains)
+ count(&models.SMTPServer{}, &u.SMTPServers)
+ count(&models.APIKey{}, &u.APIKeys)
+ count(&models.Webhook{}, &u.Webhooks)
+ return u
+}
+
+// owners resolves the owning accounts for a page of workspaces in one query.
+func (h *AdminWorkspaceHandler) owners(workspaces []models.Workspace) map[uint]models.User {
+ out := map[uint]models.User{}
+ if len(workspaces) == 0 {
+ return out
+ }
+ ids := make([]uint, 0, len(workspaces))
+ for i := range workspaces {
+ ids = append(ids, workspaces[i].OwnerID)
+ }
+ var rows []models.User
+ if err := h.db.Select("id", "name", "email").Where("id IN ?", ids).Find(&rows).Error; err != nil {
+ return out
+ }
+ for i := range rows {
+ out[rows[i].ID] = rows[i]
+ }
+ return out
+}
+
+func (h *AdminWorkspaceHandler) planNames(workspaces []models.Workspace) map[uint]string {
+ out := map[uint]string{}
+ ids := make([]uint, 0, len(workspaces))
+ for i := range workspaces {
+ if workspaces[i].PlanID != nil {
+ ids = append(ids, *workspaces[i].PlanID)
+ }
+ }
+ if len(ids) == 0 {
+ return out
+ }
+ var rows []models.Plan
+ if err := h.db.Select("id", "name").Where("id IN ?", ids).Find(&rows).Error; err != nil {
+ return out
+ }
+ for i := range rows {
+ out[rows[i].ID] = rows[i].Name
+ }
+ return out
+}
+
+func (h *AdminWorkspaceHandler) memberCounts(workspaces []models.Workspace) map[uint]int64 {
+ out := map[uint]int64{}
+ if len(workspaces) == 0 {
+ return out
+ }
+ ids := make([]uint, 0, len(workspaces))
+ for i := range workspaces {
+ ids = append(ids, workspaces[i].ID)
+ }
+ var rows []struct {
+ WorkspaceID uint
+ Count int64
+ }
+ if err := h.db.Model(&models.WorkspaceMember{}).
+ Select("workspace_id, COUNT(*) AS count").
+ Where("workspace_id IN ?", ids).
+ Group("workspace_id").
+ Scan(&rows).Error; err != nil {
+ return out
+ }
+ for _, r := range rows {
+ out[r.WorkspaceID] = r.Count
+ }
+ return out
+}
diff --git a/internal/routes/admin_routes.go b/internal/routes/admin_routes.go
index fc3f1ea..b133614 100644
--- a/internal/routes/admin_routes.go
+++ b/internal/routes/admin_routes.go
@@ -393,6 +393,31 @@ func (r *Router) adminRoutes() []okapi.RouteDefinition {
},
},
+ // ==================== Workspaces ====================
+ {
+ Method: http.MethodGet,
+ Path: pathWorkspaces,
+ Handler: okapi.H(r.h.adminWorkspace.List),
+ Group: adminGroup,
+ Summary: "List all workspaces",
+ Description: "Platform-wide workspace list with owner, plan and member count, filterable by name/slug, owner, and plan.",
+ Request: &handlers.AdminListWorkspacesRequest{},
+ Response: &dto.PageableResponse[handlers.AdminWorkspaceRow]{},
+ },
+ {
+ Method: http.MethodGet,
+ Path: pathWorkspaceByID,
+ Handler: okapi.H(r.h.adminWorkspace.Get),
+ Group: adminGroup,
+ Summary: "Get a workspace",
+ Description: "Returns the workspace with its members, pending invitation count, and resource usage.",
+ Response: &dto.Response[handlers.AdminWorkspaceDetail]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Workspace ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+
// ==================== Plans ====================
{
Method: http.MethodPost,
diff --git a/internal/routes/paths.go b/internal/routes/paths.go
index 1793d99..c14f3ac 100644
--- a/internal/routes/paths.go
+++ b/internal/routes/paths.go
@@ -34,6 +34,7 @@ const (
pathSettings = "/settings"
pathSuppressions = "/suppressions"
pathWebhooks = "/webhooks"
+ pathWorkspaces = "/workspaces"
pathAnnouncementByID = "/announcements/{id:int}"
pathCampaignByID = "/campaigns/{id:int}"
@@ -46,4 +47,5 @@ const (
pathSubscriberListByID = "/subscriber-lists/{id:int}"
pathSubscriberListMembers = "/subscriber-lists/{id:int}/members"
pathUnsubscribeListByID = "/unsubscribe-lists/{id:int}"
+ pathWorkspaceByID = "/workspaces/{id:int}"
)
diff --git a/internal/routes/routes.go b/internal/routes/routes.go
index 3f47fb7..adb1c8f 100644
--- a/internal/routes/routes.go
+++ b/internal/routes/routes.go
@@ -115,6 +115,7 @@ type routerHandlers struct {
event *handlers.EventHandler
analytics *handlers.AnalyticsHandler
adminDomain *handlers.AdminDomainHandler
+ adminWorkspace *handlers.AdminWorkspaceHandler
notification *handlers.NotificationHandler
announcement *handlers.AdminAnnouncementHandler
setting *handlers.SettingHandler
@@ -275,6 +276,7 @@ func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *c
dashboard: handlers.NewDashboardHandler(db, statsCache, webhookDeliveryRepo),
domain: handlers.NewDomainHandler(domainRepo),
adminDomain: handlers.NewAdminDomainHandler(db, domainRepo, auditLogger),
+ adminWorkspace: handlers.NewAdminWorkspaceHandler(db, workspaceRepo),
notification: handlers.NewNotificationHandler(notificationRepo, inboxService),
announcement: handlers.NewAdminAnnouncementHandler(db, inboxService, auditLogger),
bounce: handlers.NewBounceHandler(bounceRepo, suppressionRepo, emailRepo, dispatcher),
diff --git a/internal/storage/repositories/workspace_repo.go b/internal/storage/repositories/workspace_repo.go
index cdb9d08..18d7d56 100644
--- a/internal/storage/repositories/workspace_repo.go
+++ b/internal/storage/repositories/workspace_repo.go
@@ -20,6 +20,7 @@
package repositories
import (
+ "strings"
"time"
"github.com/goposta/posta/internal/models"
@@ -81,6 +82,46 @@ func (r *WorkspaceRepository) FindAll() ([]models.Workspace, error) {
return workspaces, nil
}
+// AdminWorkspaceFilter narrows the platform-wide workspace list.
+type AdminWorkspaceFilter struct {
+ Search string
+ OwnerID *uint
+ PlanID *uint
+}
+
+// FindAllFiltered pages through every workspace for the admin console. The
+// system workspace sorts first so it is easy to find, then newest first.
+func (r *WorkspaceRepository) FindAllFiltered(f AdminWorkspaceFilter, limit, offset int) ([]models.Workspace, int64, error) {
+ var items []models.Workspace
+ var total int64
+
+ apply := func(q *gorm.DB) *gorm.DB {
+ if s := strings.TrimSpace(f.Search); s != "" {
+ like := "%" + strings.ToLower(s) + "%"
+ q = q.Where("LOWER(name) LIKE ? OR LOWER(slug) LIKE ?", like, like)
+ }
+ if f.OwnerID != nil {
+ q = q.Where("owner_id = ?", *f.OwnerID)
+ }
+ if f.PlanID != nil {
+ q = q.Where("plan_id = ?", *f.PlanID)
+ }
+ return q
+ }
+
+ if err := apply(r.db.Model(&models.Workspace{})).Count(&total).Error; err != nil {
+ return nil, 0, err
+ }
+
+ if err := apply(r.db).
+ Order("system DESC, created_at DESC").
+ Limit(limit).Offset(offset).
+ Find(&items).Error; err != nil {
+ return nil, 0, err
+ }
+ return items, total, nil
+}
+
// FindByUserID returns all workspaces the user is a member of. The system
// workspace sorts last so it never displaces a real one at the top of a list.
func (r *WorkspaceRepository) FindByUserID(userID uint) ([]models.Workspace, error) {
diff --git a/web/src/api/admin.ts b/web/src/api/admin.ts
index 6873178..354ae66 100644
--- a/web/src/api/admin.ts
+++ b/web/src/api/admin.ts
@@ -3,6 +3,7 @@ import type {
ApiResponse, PaginatedResponse, User, ApiKey, Email, Event, AdminMetrics,
UserDetailMetrics, CronJob, AdminWorkspace, UpdateInfo,
Domain, AdminDomainRow, AdminDomainDetail, AdminDomainVerifyResult,
+ AdminWorkspaceRow, AdminWorkspaceDetail,
} from './types'
import type { Announcement, AnnouncementInput } from './inbox'
@@ -45,6 +46,22 @@ export const adminApi = {
})
},
+ // ---- Workspaces (platform-wide) ----
+ listWorkspaces(page = 0, size = 20, search = '', plan = 0, owner = 0) {
+ return api.get<PaginatedResponse<AdminWorkspaceRow>>('/admin/workspaces', {
+ params: {
+ page,
+ size,
+ search: search || undefined,
+ plan: plan || undefined,
+ owner: owner || undefined,
+ },
+ })
+ },
+ getWorkspace(id: number) {
+ return api.get<ApiResponse<AdminWorkspaceDetail>>(`/admin/workspaces/${id}`)
+ },
+
createUser(name: string, email: string, password: string, role: string) {
return api.post<ApiResponse<User>>('/admin/users', { name, email, password, role })
},
diff --git a/web/src/api/types.ts b/web/src/api/types.ts
index b592bb3..9106606 100644
--- a/web/src/api/types.ts
+++ b/web/src/api/types.ts
@@ -441,6 +441,48 @@ export interface AdminDomainDetail extends AdminDomainRow {
conflict_workspace_name?: string
}
+export interface AdminWorkspaceRow {
+ id: number
+ name: string
+ slug: string
+ system: boolean
+ owner_id: number
+ owner_name: string
+ owner_email: string
+ plan_id: number | null
+ plan_name: string
+ member_count: number
+ created_at: string
+}
+
+export interface AdminWorkspaceMember {
+ user_id: number
+ name: string
+ email: string
+ active: boolean
+ role: WorkspaceRole
+ joined_at: string
+}
+
+export interface AdminWorkspaceDetail extends AdminWorkspaceRow {
+ description: string
+ default_language: string
+ updated_at: string
+ members: AdminWorkspaceMember[]
+ pending_invitations: number
+ usage: {
+ emails: number
+ templates: number
+ contacts: number
+ subscribers: number
+ campaigns: number
+ domains: number
+ smtp_servers: number
+ api_keys: number
+ webhooks: number
+ }
+}
+
export interface AdminDomainVerifyResult {
domain: Domain
verification: {
diff --git a/web/src/layouts/DashboardLayout.vue b/web/src/layouts/DashboardLayout.vue
index 1462b88..0bf16a7 100644
--- a/web/src/layouts/DashboardLayout.vue
+++ b/web/src/layouts/DashboardLayout.vue
@@ -226,6 +226,7 @@ const navSections: NavSection[] = [
// The dashboard is the landing page for this section, so it leads.
{ name: 'Dashboard', path: '/admin/dashboard', icon: 'pie-chart' },
{ name: 'Users', path: '/admin/users', icon: 'users' },
+ { name: 'Workspaces', path: '/admin/workspaces', icon: 'briefcase' },
{ name: 'Plans', path: '/admin/plans', icon: 'layers' },
{ name: 'Shared Servers', path: '/admin/servers', icon: 'server' },
{ name: 'Domains', path: '/admin/domains', icon: 'globe' },
diff --git a/web/src/router/index.ts b/web/src/router/index.ts
index cf61ef9..4ae5893 100644
--- a/web/src/router/index.ts
+++ b/web/src/router/index.ts
@@ -109,6 +109,8 @@ const routes = [
// links; keep the old path working for bookmarks and muscle memory.
{ path: 'admin/metrics', redirect: '/admin/dashboard' },
{ path: 'admin/announcements', name: 'admin-announcements', component: () => import('../views/admin/Announcements.vue'), meta: { admin: true, title: 'Admin · Announcements' } },
+ { path: 'admin/workspaces', name: 'admin-workspaces', component: () => import('../views/admin/Workspaces.vue'), meta: { admin: true, title: 'Admin · Workspaces' } },
+ { path: 'admin/workspaces/:id', name: 'admin-workspace-detail', component: () => import('../views/admin/WorkspaceDetail.vue'), meta: { admin: true, title: 'Admin · Workspace' } },
{ path: 'admin/domains', name: 'admin-domains', component: () => import('../views/admin/Domains.vue'), meta: { admin: true, title: 'Admin · Domains' } },
{ path: 'admin/domains/:id', name: 'admin-domain-detail', component: () => import('../views/admin/DomainDetail.vue'), meta: { admin: true, title: 'Admin · Domain' } },
{ path: 'admin/events', name: 'admin-events', component: () => import('../views/admin/Events.vue'), meta: { admin: true, title: 'Admin · Events' } },
diff --git a/web/src/views/admin/UserDetail.vue b/web/src/views/admin/UserDetail.vue
index df44eeb..490e716 100644
--- a/web/src/views/admin/UserDetail.vue
+++ b/web/src/views/admin/UserDetail.vue
@@ -480,7 +480,7 @@ function formatDate(date: string) {
</thead>
<tbody>
<tr v-for="ws in workspaces" :key="ws.id">
- <td>{{ ws.name }}</td>
+ <td><router-link :to="`/admin/workspaces/${ws.id}`">{{ ws.name }}</router-link></td>
<td><code>{{ ws.slug }}</code></td>
<td>
<select
diff --git a/web/src/views/admin/WorkspaceDetail.vue b/web/src/views/admin/WorkspaceDetail.vue
new file mode 100644
index 0000000..13e6f98
--- /dev/null
+++ b/web/src/views/admin/WorkspaceDetail.vue
@@ -0,0 +1,267 @@
+<script setup lang="ts">
+import { computed, onMounted, ref } from "vue";
+import { useRoute, useRouter } from "vue-router";
+import { adminApi } from "../../api/admin";
+import { plansApi } from "../../api/plans";
+import { useNotificationStore } from "../../stores/notification";
+import { apiMessage } from "../../composables/apiError";
+import type { AdminWorkspaceDetail, Plan } from "../../api/types";
+
+const route = useRoute();
+const router = useRouter();
+const notify = useNotificationStore();
+
+const id = Number(route.params.id);
+const workspace = ref<AdminWorkspaceDetail | null>(null);
+const plans = ref<Plan[]>([]);
+const loading = ref(true);
+const loadFailed = ref(false);
+const changingPlan = ref(false);
+
+async function load() {
+ loading.value = true;
+ try {
+ const [wsRes, plansRes] = await Promise.all([
+ adminApi.getWorkspace(id),
+ plansApi.list(0, 100).catch(() => null),
+ ]);
+ workspace.value = wsRes.data.data;
+ if (plansRes) plans.value = plansRes.data.data;
+ } catch (e: any) {
+ loadFailed.value = true;
+ notify.error(apiMessage(e, "Failed to load the workspace"));
+ } finally {
+ loading.value = false;
+ }
+}
+
+// The API only assigns plans; it cannot return a workspace to the default.
+// Inactive plans are refused server-side, so they are only listed when one is
+// already assigned and has to show as the current value.
+const planOptions = computed(() =>
+ plans.value.filter((p) => p.is_active || p.id === workspace.value?.plan_id)
+);
+
+async function changePlan(event: Event) {
+ const ws = workspace.value;
+ const planId = Number((event.target as HTMLSelectElement).value);
+ if (!ws || !planId || planId === ws.plan_id) return;
+ changingPlan.value = true;
+ try {
+ await plansApi.assignToWorkspace(ws.id, planId);
+ ws.plan_id = planId;
+ ws.plan_name = plans.value.find((p) => p.id === planId)?.name || "";
+ notify.success(`Plan updated for workspace "${ws.name}"`);
+ } catch (e: any) {
+ notify.error(apiMessage(e, "Failed to update the workspace plan"));
+ (event.target as HTMLSelectElement).value = String(ws.plan_id ?? "");
+ } finally {
+ changingPlan.value = false;
+ }
+}
+
+const usageCards = computed(() => {
+ const u = workspace.value?.usage;
+ if (!u) return [];
+ return [
+ { label: "Emails", value: u.emails },
+ { label: "Templates", value: u.templates },
+ { label: "Contacts", value: u.contacts },
+ { label: "Subscribers", value: u.subscribers },
+ { label: "Campaigns", value: u.campaigns },
+ { label: "Domains", value: u.domains },
+ { label: "SMTP Servers", value: u.smtp_servers },
+ { label: "API Keys", value: u.api_keys },
+ { label: "Webhooks", value: u.webhooks },
+ ];
+});
+
+function roleBadge(role: string) {
+ switch (role) {
+ case "owner":
+ return "badge badge-info";
+ case "admin":
+ return "badge badge-success";
+ default:
+ return "badge badge-neutral";
+ }
+}
+
+function formatDate(value?: string) {
+ return value ? new Date(value).toLocaleString() : "—";
+}
+
+onMounted(load);
+</script>
+
+<template>
+ <div>
+ <div class="page-header">
+ <div>
+ <h1>
+ {{ workspace?.name || "Workspace" }}
+ <span v-if="workspace?.system" class="badge badge-info" style="margin-left: 8px; vertical-align: middle">
+ system
+ </span>
+ </h1>
+ <p v-if="workspace" class="page-subtitle">
+ <code>{{ workspace.slug }}</code> · created {{ formatDate(workspace.created_at) }}
+ </p>
+ </div>
+ <div class="header-actions">
+ <button class="btn btn-secondary" @click="router.push('/admin/workspaces')">Back</button>
+ </div>
+ </div>
+
+ <div v-if="loading" class="loading-page"><div class="spinner"></div></div>
+
+ <div v-else-if="loadFailed || !workspace" class="card">
+ <div class="empty-state">
+ <h3>Workspace not found</h3>
+ <button class="btn btn-secondary" @click="router.push('/admin/workspaces')">Back to workspaces</button>
+ </div>
+ </div>
+
+ <template v-else>
+ <div class="card" style="margin-bottom: 20px">
+ <div class="card-header"><h2>Overview</h2></div>
+ <div class="card-body">
+ <table>
+ <tbody>
+ <tr>
+ <td class="label-cell">Owner</td>
+ <td>
+ <router-link :to="`/admin/users/${workspace.owner_id}`">
+ {{ workspace.owner_name || workspace.owner_email || `#${workspace.owner_id}` }}
+ </router-link>
+ <span v-if="workspace.owner_name && workspace.owner_email" class="muted">
+ {{ workspace.owner_email }}
+ </span>
+ </td>
+ </tr>
+ <tr>
+ <td class="label-cell">Description</td>
+ <td>{{ workspace.description || "—" }}</td>
+ </tr>
+ <tr>
+ <td class="label-cell">Default language</td>
+ <td>{{ workspace.default_language || "—" }}</td>
+ </tr>
+ <tr>
+ <td class="label-cell">Plan</td>
+ <td>
+ <select
+ class="form-select form-select-sm plan-select"
+ :value="workspace.plan_id ?? ''"
+ :disabled="changingPlan"
+ @change="changePlan"
+ >
+ <option value="" disabled>No plan (uses default)</option>
+ <option v-for="plan in planOptions" :key="plan.id" :value="plan.id">
+ {{ plan.name }}{{ !plan.is_active ? " (inactive)" : "" }}{{ plan.is_default ? " (default)" : "" }}
+ </option>
+ </select>
+ </td>
+ </tr>
+ <tr>
+ <td class="label-cell">Pending invitations</td>
+ <td>{{ workspace.pending_invitations }}</td>
+ </tr>
+ <tr>
+ <td class="label-cell">Last updated</td>
+ <td>{{ formatDate(workspace.updated_at) }}</td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ </div>
+
+ <div class="card" style="margin-bottom: 20px">
+ <div class="card-header"><h2>Usage</h2></div>
+ <div class="card-body">
+ <div class="stats-grid">
+ <div v-for="card in usageCards" :key="card.label" class="stat-card">
+ <div class="stat-label">{{ card.label }}</div>
+ <div class="stat-value">{{ card.value }}</div>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <div class="card">
+ <div class="card-header">
+ <h2>Members ({{ workspace.members.length }})</h2>
+ </div>
+ <div v-if="!workspace.members.length" class="empty-state">
+ <p>This workspace has no members.</p>
+ </div>
+ <div v-else class="table-wrapper">
+ <table>
+ <thead>
+ <tr>
+ <th>Name</th>
+ <th>Email</th>
+ <th>Role</th>
+ <th>Status</th>
+ <th>Joined</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr
+ v-for="m in workspace.members"
+ :key="m.user_id"
+ style="cursor: pointer"
+ @click="router.push(`/admin/users/${m.user_id}`)"
+ >
+ <td>{{ m.name || "—" }}</td>
+ <td class="muted-cell">{{ m.email }}</td>
+ <td><span :class="roleBadge(m.role)">{{ m.role }}</span></td>
+ <td>
+ <span :class="m.active ? 'badge badge-success' : 'badge badge-warning'">
+ {{ m.active ? "active" : "disabled" }}
+ </span>
+ </td>
+ <td class="muted-cell">{{ formatDate(m.joined_at) }}</td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ </div>
+ </template>
+ </div>
+</template>
+
+<style scoped>
+.page-subtitle {
+ font-size: 13px;
+ color: var(--text-tertiary);
+ margin-top: 4px;
+}
+
+.header-actions {
+ display: flex;
+ gap: 8px;
+ flex-wrap: wrap;
+}
+
+.label-cell {
+ font-weight: 600;
+ width: 190px;
+ color: var(--text-secondary);
+}
+
+.muted {
+ margin-left: 8px;
+ color: var(--text-tertiary);
+ font-size: 13px;
+}
+
+.muted-cell {
+ color: var(--text-tertiary);
+ font-size: 13px;
+}
+
+.plan-select {
+ max-width: 300px;
+}
+</style>
diff --git a/web/src/views/admin/Workspaces.vue b/web/src/views/admin/Workspaces.vue
new file mode 100644
index 0000000..4546c05
--- /dev/null
+++ b/web/src/views/admin/Workspaces.vue
@@ -0,0 +1,172 @@
+<script setup lang="ts">
+import { onMounted, ref } from "vue";
+import { useRouter } from "vue-router";
+import { adminApi } from "../../api/admin";
+import { plansApi } from "../../api/plans";
+import { useNotificationStore } from "../../stores/notification";
+import { apiMessage } from "../../composables/apiError";
+import { usePagination } from "../../composables/usePagination";
+import Pagination from "../../components/Pagination.vue";
+import type { AdminWorkspaceRow, Plan } from "../../api/types";
+
+const router = useRouter();
+const notify = useNotificationStore();
+
+const workspaces = ref<AdminWorkspaceRow[]>([]);
+const plans = ref<Plan[]>([]);
+const loading = ref(true);
+const search = ref("");
+const planFilter = ref(0);
+
+let searchTimer: ReturnType<typeof setTimeout> | undefined;
+
+const { pageable, goToPage } = usePagination(async (page) => {
+ loading.value = true;
+ try {
+ const res = await adminApi.listWorkspaces(page, pageable.value.size, search.value.trim(), planFilter.value);
+ workspaces.value = res.data.data;
+ pageable.value = res.data.pageable;
+ } catch (e: any) {
+ notify.error(apiMessage(e, "Failed to load workspaces"));
+ } finally {
+ loading.value = false;
+ }
+});
+
+function onSearchInput() {
+ if (searchTimer) clearTimeout(searchTimer);
+ searchTimer = setTimeout(() => goToPage(0), 300);
+}
+
+function formatDate(value: string) {
+ return new Date(value).toLocaleDateString(undefined, {
+ year: "numeric",
+ month: "short",
+ day: "numeric",
+ });
+}
+
+onMounted(async () => {
+ try {
+ plans.value = (await plansApi.list(0, 100)).data.data;
+ } catch {
+ // The plan filter is optional; the list still works without it.
+ }
+});
+</script>
+
+<template>
+ <div>
+ <div class="page-header">
+ <div>
+ <h1>Workspaces</h1>
+ <p class="page-subtitle">Every workspace on the platform, with its owner, plan and members</p>
+ </div>
+ </div>
+
+ <div class="card">
+ <div class="card-body toolbar">
+ <input
+ v-model="search"
+ class="form-input search"
+ placeholder="Search by name or slug…"
+ @input="onSearchInput"
+ />
+ <select v-model.number="planFilter" class="form-select plan-filter" @change="goToPage(0)">
+ <option :value="0">All plans</option>
+ <option v-for="plan in plans" :key="plan.id" :value="plan.id">{{ plan.name }}</option>
+ </select>
+ <span class="count">
+ {{ pageable.total_elements }} workspace{{ pageable.total_elements === 1 ? "" : "s" }}
+ </span>
+ </div>
+
+ <div v-if="loading && !workspaces.length" class="card-body">
+ <div class="spinner"></div>
+ </div>
+
+ <div v-else-if="!workspaces.length" class="empty-state">
+ <h3>{{ search.trim() || planFilter ? "No workspaces match these filters" : "No workspaces yet" }}</h3>
+ </div>
+
+ <template v-else>
+ <div class="table-wrapper">
+ <table>
+ <thead>
+ <tr>
+ <th>Name</th>
+ <th>Slug</th>
+ <th>Owner</th>
+ <th>Plan</th>
+ <th>Members</th>
+ <th>Created</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr
+ v-for="ws in workspaces"
+ :key="ws.id"
+ style="cursor: pointer"
+ @click="router.push(`/admin/workspaces/${ws.id}`)"
+ >
+ <td>
+ {{ ws.name }}
+ <span v-if="ws.system" class="badge badge-info" style="margin-left: 6px">system</span>
+ </td>
+ <td class="mono">{{ ws.slug }}</td>
+ <td class="muted-cell">{{ ws.owner_email || `#${ws.owner_id}` }}</td>
+ <td>
+ <span v-if="ws.plan_name" class="badge badge-neutral">{{ ws.plan_name }}</span>
+ <span v-else class="muted-cell">Default</span>
+ </td>
+ <td>{{ ws.member_count }}</td>
+ <td class="muted-cell">{{ formatDate(ws.created_at) }}</td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ <Pagination :pageable="pageable" @page="goToPage" />
+ </template>
+ </div>
+ </div>
+</template>
+
+<style scoped>
+.page-subtitle {
+ font-size: 13px;
+ color: var(--text-tertiary);
+ margin-top: 4px;
+}
+
+.toolbar {
+ display: flex;
+ align-items: center;
+ gap: 16px;
+ flex-wrap: wrap;
+}
+
+.search {
+ flex: 1 1 260px;
+ max-width: 360px;
+}
+
+.plan-filter {
+ max-width: 200px;
+}
+
+.count {
+ margin-left: auto;
+ font-size: 12px;
+ color: var(--text-tertiary);
+}
+
+.mono {
+ font-family: "SFMono-Regular", Consolas, monospace;
+ font-size: 13px;
+}
+
+.muted-cell {
+ color: var(--text-tertiary);
+ font-size: 13px;
+}
+</style>