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(workspace): migrate to workspace-only scoping

Jonas Kaninda6ef1e435fe5f
diff --git a/cmd/posta/server.go b/cmd/posta/server.go
index 24b797e..7195aa9 100644
--- a/cmd/posta/server.go
+++ b/cmd/posta/server.go
@@ -41,9 +41,11 @@ import (
"github.com/goposta/posta/internal/services/settings"
"github.com/goposta/posta/internal/services/tracking"
"github.com/goposta/posta/internal/services/webhook"
+ "github.com/goposta/posta/internal/services/workspacemigrate"
"github.com/goposta/posta/internal/storage"
"github.com/goposta/posta/internal/storage/blob"
"github.com/goposta/posta/internal/storage/migration"
+ "github.com/goposta/posta/internal/storage/migration/upgrade"
"github.com/goposta/posta/internal/storage/repositories"
"github.com/goposta/posta/internal/worker"
"github.com/hibiken/asynq"
@@ -80,6 +82,15 @@ func runServer(cli *okapicli.CLI) {
logger.Fatal("failed to run migrations", "error", err)
}
+ if err := upgrade.Run(context.Background(), res.db, config.Version, upgrade.Options{
+ AllowDowngrade: cfg.AllowDowngrade,
+ PlanEnforcement: cfg.PlanEnforcement,
+ }); err != nil {
+ logger.Fatal("failed to run upgrade steps", "error", err)
+ }
+
+ checkDefaultPlan(res.db, cfg)
+
// Initialize SMTP password encryption
crypto.Init(cfg.EncryptionKey)
@@ -87,7 +98,7 @@ func runServer(cli *okapicli.CLI) {
logger.Fatal("failed to seed admin user", "error", err)
}
- seedDefaults(res.db, cfg.AdminEmail)
+ seedDefaults(res.db, cfg)
// Initialize blob storage (S3 or filesystem) for attachments
if cfg.BlobProvider != "" {
@@ -113,7 +124,13 @@ func runServer(cli *okapicli.CLI) {
userRepo := repositories.NewUserRepository(res.db)
userSettingRepo := repositories.NewUserSettingRepository(res.db)
appName := "Posta"
- notifier := notification.NewService(cfg.SystemSMTP, appName, cfg.AppWebURL, userRepo, userSettingRepo)
+ notifier := notification.NewService(
+ cfg.SystemSMTP,
+ appName,
+ cfg.AppWebURL,
+ userRepo,
+ userSettingRepo,
+ repositories.NewWorkspaceRepository(res.db))
if notifier.IsConfigured() {
logger.Info("system notification service enabled")
}
@@ -176,10 +193,19 @@ func runServer(cli *okapicli.CLI) {
}
}
-// seedDefaults seeds default templates, stylesheets, and languages for the admin user.
-func seedDefaults(db *gorm.DB, adminEmail string) {
+func checkDefaultPlan(db *gorm.DB, cfg *config.Config) {
+ if !cfg.PlanEnforcement {
+ return
+ }
+ if _, err := repositories.NewPlanRepository(db).FindDefault(); err != nil {
+ logger.Warn("plan enforcement is enabled but no default plan is set — " +
+ "personal-workspace migration will fail until one is configured via PATCH /admin/plans/{id}/default")
+ }
+}
+
+func seedDefaults(db *gorm.DB, cfg *config.Config) {
userRepo := repositories.NewUserRepository(db)
- admin, err := userRepo.FindByEmail(adminEmail)
+ admin, err := userRepo.FindByEmail(cfg.AdminEmail)
if err != nil || admin == nil {
return
}
@@ -190,7 +216,11 @@ func seedDefaults(db *gorm.DB, adminEmail string) {
repositories.NewTemplateLocalizationRepository(db),
repositories.NewLanguageRepository(db),
)
- s.SeedUserDefaults(admin.ID, admin.Name)
+ migrator := workspacemigrate.New(cfg.PlanEnforcement)
+ migrator.SetSeeder(s)
+ if _, err := migrator.MigrateUser(db, admin.ID); err != nil {
+ logger.Error("failed to provision admin personal workspace", "error", err)
+ }
}
// newWebhookDispatcher creates a configured webhook dispatcher with metrics hooks.
@@ -449,7 +479,7 @@ func initCronManager(
retentionJob.SetBlobStore(blobStore)
}
manager.Register(retentionJob)
- manager.Register(jobs.NewDailyReportJob(repositories.NewUserSettingRepository(db)))
+ manager.Register(jobs.NewDailyReportJob(repositories.NewWorkspaceRepository(db)))
manager.Register(jobs.NewAccountCleanupJob(repositories.NewUserRepository(db)))
manager.Register(jobs.NewAPIKeyExpiryJob(db, notifier))
manager.Register(jobs.NewBounceAlertJob(
diff --git a/cmd/posta/worker.go b/cmd/posta/worker.go
index ff2c6aa..bd4680b 100644
--- a/cmd/posta/worker.go
+++ b/cmd/posta/worker.go
@@ -150,6 +150,7 @@ func runWorker() error {
cfg.SystemSMTP, "Posta", cfg.AppWebURL,
repositories.NewUserRepository(db),
repositories.NewUserSettingRepository(db),
+ repositories.NewWorkspaceRepository(db),
)
dailyReportHandler := worker.NewDailyReportHandler(
notifier,
diff --git a/go.mod b/go.mod
index 34b9c0a..8b354a2 100644
--- a/go.mod
+++ b/go.mod
@@ -22,6 +22,7 @@ require (
github.com/robfig/cron/v3 v3.0.1
github.com/vanng822/go-premailer v1.33.0
golang.org/x/crypto v0.52.0
+ golang.org/x/mod v0.36.0
golang.org/x/net v0.55.0
golang.org/x/oauth2 v0.36.0
gorm.io/driver/postgres v1.6.0
diff --git a/go.sum b/go.sum
index 5b28ee4..12112a4 100644
--- a/go.sum
+++ b/go.sum
@@ -208,6 +208,8 @@ golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
+golang.org/x/mod v0.36.0 h1:JJjpVx6myfUsUdAzZuOSTTmRE0PfZeNWzzvKrP7amb4=
+golang.org/x/mod v0.36.0/go.mod h1:moc6ELqsWcOw5Ef3xVprK5ul/MvtVvkIXLziUOICjUQ=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
diff --git a/internal/config/config.go b/internal/config/config.go
index e85a24a..f527081 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -51,13 +51,20 @@ type Config struct {
AdminEmail string
AdminPassword string
OpenAPIDocs bool
- securitySchemes okapi.SecuritySchemes
+ // AllowDowngrade lets the server boot even when the binary's version is
+ // older than the version recorded in the database. Off by default.
+ AllowDowngrade bool
+ securitySchemes okapi.SecuritySchemes
MetricsEnabled bool
- WebDir string
- AppWebURL string
- ApiBaseURL string
- CORSOrigins string
+
+ PlanEnforcement bool
+ WorkspaceOnlyMode bool
+
+ WebDir string
+ AppWebURL string
+ ApiBaseURL string
+ CORSOrigins string
// Worker settings
EmbeddedWorker bool
@@ -183,12 +190,15 @@ func New() *Config {
AdminEmail: goutils.Env("POSTA_ADMIN_EMAIL", "[email protected]"),
AdminPassword: goutils.Env("POSTA_ADMIN_PASSWORD", "admin1234"),
OpenAPIDocs: goutils.EnvBool("POSTA_OPENAPI_DOCS", true),
+ AllowDowngrade: goutils.EnvBool("POSTA_ALLOW_DOWNGRADE", false),
securitySchemes: okapi.SecuritySchemes{},
- MetricsEnabled: goutils.EnvBool("POSTA_METRICS_ENABLED", false),
- WebDir: goutils.Env("POSTA_WEB_DIR", "web/dist"),
- AppWebURL: goutils.Env("POSTA_WEB_URL", ""),
- ApiBaseURL: goutils.Env("POSTA_API_URL", ""),
+ MetricsEnabled: goutils.EnvBool("POSTA_METRICS_ENABLED", false),
+ PlanEnforcement: goutils.EnvBool("POSTA_PLAN_ENFORCEMENT", false),
+ WorkspaceOnlyMode: goutils.EnvBool("POSTA_WORKSPACE_ONLY_MODE", false),
+ WebDir: goutils.Env("POSTA_WEB_DIR", "web/dist"),
+ AppWebURL: goutils.Env("POSTA_WEB_URL", ""),
+ ApiBaseURL: goutils.Env("POSTA_API_URL", ""),
CORSOrigins: goutils.Env("POSTA_CORS_ORIGINS", "*"),
@@ -323,6 +333,7 @@ func (c *Config) Initialize(app *okapi.Okapi) error {
Servers: apiServers,
SecuritySchemes: c.securitySchemes,
UI: okapi.ScalarUI,
+ StrictDocUI: true,
})
}
app.WithErrorHandler(errorhandlers.CustomErrorHandler())
diff --git a/internal/cron/jobs/api_key_expiry.go b/internal/cron/jobs/api_key_expiry.go
index 7ec6cd3..5c69a05 100644
--- a/internal/cron/jobs/api_key_expiry.go
+++ b/internal/cron/jobs/api_key_expiry.go
@@ -29,7 +29,8 @@ import (
"gorm.io/gorm"
)
-// APIKeyExpiryJob checks for API keys expiring within 7 days and notifies users.
+// APIKeyExpiryJob checks for workspace API keys expiring within 7 days and
+// notifies the owning workspace's owners and admins.
type APIKeyExpiryJob struct {
db *gorm.DB
notifier *notification.Service
@@ -52,12 +53,13 @@ func (j *APIKeyExpiryJob) Run(_ context.Context, _ *asynq.Client) error {
return nil
}
- // Find API keys expiring within the next 7 days
+ // Find workspace API keys expiring within the next 7 days. Personal
+ // (user-scoped) keys are excluded: scoping is workspace-only.
now := time.Now().UTC()
deadline := now.AddDate(0, 0, 7)
var keys []models.APIKey
- if err := j.db.Where("expires_at IS NOT NULL AND expires_at > ? AND expires_at <= ? AND revoked = ?", now, deadline, false).
+ if err := j.db.Where("expires_at IS NOT NULL AND expires_at > ? AND expires_at <= ? AND revoked = ? AND workspace_id IS NOT NULL", now, deadline, false).
Find(&keys).Error; err != nil {
logger.Error("api-key-expiry: failed to query", "error", err)
return err
@@ -67,26 +69,29 @@ func (j *APIKeyExpiryJob) Run(_ context.Context, _ *asynq.Client) error {
return nil
}
- // Group by user
- userKeys := make(map[uint][]expiringKey)
+ // Group by workspace
+ workspaceKeys := make(map[uint][]expiringKey)
for _, k := range keys {
- userKeys[k.UserID] = append(userKeys[k.UserID], expiringKey{
+ if k.WorkspaceID == nil {
+ continue
+ }
+ workspaceKeys[*k.WorkspaceID] = append(workspaceKeys[*k.WorkspaceID], expiringKey{
Name: k.Name,
ExpiresAt: k.ExpiresAt.Format("January 2, 2006"),
})
}
sent := 0
- for userID, ks := range userKeys {
+ for workspaceID, ks := range workspaceKeys {
subject := fmt.Sprintf("%d API key(s) expiring soon", len(ks))
if len(ks) == 1 {
subject = "API key expiring soon"
}
- if err := j.notifier.SendToUser(userID, subject, notification.TemplateAPIKeyExpiry, map[string]any{
+ if err := j.notifier.SendToWorkspaceAdmins(workspaceID, subject, notification.TemplateAPIKeyExpiry, map[string]any{
"Keys": ks,
"KeyCount": len(ks),
}); err != nil {
- logger.Error("api-key-expiry: failed to send", "user_id", userID, "error", err)
+ logger.Error("api-key-expiry: failed to send", "workspace_id", workspaceID, "error", err)
continue
}
sent++
diff --git a/internal/cron/jobs/bounce_alert.go b/internal/cron/jobs/bounce_alert.go
index 6e1fd47..b29664d 100644
--- a/internal/cron/jobs/bounce_alert.go
+++ b/internal/cron/jobs/bounce_alert.go
@@ -32,7 +32,8 @@ import (
const bounceRateThreshold = 5.0 // percent
-// BounceAlertJob checks for users with high bounce rates and sends alerts.
+// BounceAlertJob checks for workspaces with high bounce rates and alerts their
+// owners and admins.
type BounceAlertJob struct {
db *gorm.DB
notifier *notification.Service
@@ -65,30 +66,30 @@ func (j *BounceAlertJob) Run(_ context.Context, _ *asynq.Client) error {
now := time.Now().UTC()
from := now.Add(-24 * time.Hour)
- // Find users who sent emails in the last 24 hours
- type userEmailCount struct {
- UserID uint `gorm:"column:user_id"`
- Total int64 `gorm:"column:total"`
+ // Find workspaces that sent emails in the last 24 hours
+ type workspaceEmailCount struct {
+ WorkspaceID uint `gorm:"column:workspace_id"`
+ Total int64 `gorm:"column:total"`
}
- var counts []userEmailCount
+ var counts []workspaceEmailCount
if err := j.db.Model(&models.Email{}).
- Select("user_id, COUNT(*) as total").
- Where("created_at >= ? AND workspace_id IS NULL", from).
- Group("user_id").
- Having("COUNT(*) >= ?", 10). // Only alert for users with meaningful volume
+ Select("workspace_id, COUNT(*) as total").
+ Where("created_at >= ? AND workspace_id IS NOT NULL", from).
+ Group("workspace_id").
+ Having("COUNT(*) >= ?", 10).
Find(&counts).Error; err != nil {
logger.Error("bounce-alert: failed to query email counts", "error", err)
return err
}
sent := 0
- for _, uc := range counts {
- bounceCount, err := j.bounceRepo.CountByUserAndDateRange(uc.UserID, from, now)
+ for _, wc := range counts {
+ bounceCount, err := j.bounceRepo.CountByWorkspaceAndDateRange(wc.WorkspaceID, from, now)
if err != nil {
continue
}
- bounceRate := float64(bounceCount) / float64(uc.Total) * 100
+ bounceRate := float64(bounceCount) / float64(wc.Total) * 100
if bounceRate < bounceRateThreshold {
continue
}
@@ -96,17 +97,17 @@ func (j *BounceAlertJob) Run(_ context.Context, _ *asynq.Client) error {
// Count new suppressions
var suppressionCount int64
j.db.Model(&models.Suppression{}).
- Where("user_id = ? AND created_at >= ?", uc.UserID, from).
+ Where("workspace_id = ? AND created_at >= ?", wc.WorkspaceID, from).
Count(&suppressionCount)
- if err := j.notifier.SendToUser(uc.UserID, "Bounce Rate Alert", notification.TemplateBounceAlert, map[string]any{
+ if err := j.notifier.SendToWorkspaceAdmins(wc.WorkspaceID, "Bounce Rate Alert", notification.TemplateBounceAlert, map[string]any{
"BounceRate": fmt.Sprintf("%.1f", bounceRate),
"Threshold": fmt.Sprintf("%.0f", bounceRateThreshold),
- "TotalEmails": uc.Total,
+ "TotalEmails": wc.Total,
"BounceCount": bounceCount,
"SuppressionCount": suppressionCount,
}); err != nil {
- logger.Error("bounce-alert: failed to send", "user_id", uc.UserID, "error", err)
+ logger.Error("bounce-alert: failed to send", "workspace_id", wc.WorkspaceID, "error", err)
continue
}
sent++
diff --git a/internal/cron/jobs/daily_report.go b/internal/cron/jobs/daily_report.go
index ef296f6..6047cb9 100644
--- a/internal/cron/jobs/daily_report.go
+++ b/internal/cron/jobs/daily_report.go
@@ -29,43 +29,43 @@ import (
const TypeDailyReport = "cron:daily-report"
-// DailyReportPayload is the Asynq task payload for a per-user daily report.
+// DailyReportPayload is the Asynq task payload for a per-workspace daily report.
type DailyReportPayload struct {
- UserID uint `json:"user_id"`
+ WorkspaceID uint `json:"workspace_id"`
}
-// DailyReportJob is a daily report job that enqueues a report task for each user
-// that has daily_report enabled in their settings.
+// DailyReportJob enqueues a report task for each workspace. The processed report
+// is delivered to the workspace's owners and admins.
type DailyReportJob struct {
- userSettingRepo *repositories.UserSettingRepository
+ workspaceRepo *repositories.WorkspaceRepository
}
-// dailyReportTask implements cron.Job for enqueueing a single user's report.
+// dailyReportTask implements cron.Job for enqueueing a single workspace's report.
type dailyReportTask struct {
- userID uint
+ workspaceID uint
}
func (t *dailyReportTask) Type() string { return TypeDailyReport }
-func (t *dailyReportTask) Payload() any { return DailyReportPayload{UserID: t.userID} }
+func (t *dailyReportTask) Payload() any { return DailyReportPayload{WorkspaceID: t.workspaceID} }
-func NewDailyReportJob(userSettingRepo *repositories.UserSettingRepository) *DailyReportJob {
- return &DailyReportJob{userSettingRepo: userSettingRepo}
+func NewDailyReportJob(workspaceRepo *repositories.WorkspaceRepository) *DailyReportJob {
+ return &DailyReportJob{workspaceRepo: workspaceRepo}
}
func (j *DailyReportJob) Name() string { return "daily-report" }
func (j *DailyReportJob) Schedule() string { return "0 7 * * *" } // daily at 07:00 UTC
func (j *DailyReportJob) Run(_ context.Context, client *asynq.Client) error {
- users, err := j.userSettingRepo.FindUsersWithDailyReport()
+ workspaces, err := j.workspaceRepo.FindAll()
if err != nil {
- logger.Error("daily report: failed to find users", "error", err)
+ logger.Error("daily report: failed to find workspaces", "error", err)
return err
}
enqueued := 0
- for _, userID := range users {
- if err := cron.EnqueueJob(client, &dailyReportTask{userID: userID}, asynq.Queue("low")); err != nil {
- logger.Error("daily report: failed to enqueue", "user_id", userID, "error", err)
+ for _, ws := range workspaces {
+ if err := cron.EnqueueJob(client, &dailyReportTask{workspaceID: ws.ID}, asynq.Queue("low")); err != nil {
+ logger.Error("daily report: failed to enqueue", "workspace_id", ws.ID, "error", err)
continue
}
enqueued++
@@ -76,8 +76,8 @@ func (j *DailyReportJob) Run(_ context.Context, client *asynq.Client) error {
}
// NewDailyReportTask creates an Asynq task for processing a daily report.
-func NewDailyReportTask(userID uint, opts ...asynq.Option) (*asynq.Task, error) {
- payload, err := json.Marshal(DailyReportPayload{UserID: userID})
+func NewDailyReportTask(workspaceID uint, opts ...asynq.Option) (*asynq.Task, error) {
+ payload, err := json.Marshal(DailyReportPayload{WorkspaceID: workspaceID})
if err != nil {
return nil, err
}
diff --git a/internal/handlers/admin_handler.go b/internal/handlers/admin_handler.go
index 618e5bd..5440f95 100644
--- a/internal/handlers/admin_handler.go
+++ b/internal/handlers/admin_handler.go
@@ -29,8 +29,10 @@ import (
"github.com/goposta/posta/internal/services/seeder"
"github.com/goposta/posta/internal/services/session"
"github.com/goposta/posta/internal/services/settings"
+ "github.com/goposta/posta/internal/services/workspacemigrate"
"github.com/goposta/posta/internal/storage/repositories"
"github.com/hibiken/asynq"
+ "github.com/jkaninda/logger"
"github.com/jkaninda/okapi"
"golang.org/x/crypto/bcrypt"
"gorm.io/gorm"
@@ -48,11 +50,19 @@ type AdminHandler struct {
inspector *asynq.Inspector
bus *eventbus.EventBus
seeder *seeder.Seeder
+ migrator *workspacemigrate.Service
embeddedWorker bool
emailSettings *settings.Provider
sessionRepo *repositories.SessionRepository
sessionStore *session.Store
}
+
+// SetMigrator wires the personal-workspace migrator used to provision (and seed)
+// a personal workspace for admin-created users. See §4.
+func (h *AdminHandler) SetMigrator(m *workspacemigrate.Service) {
+ h.migrator = m
+}
+
type AdminCreateUserRequest struct {
Body struct {
Name string `json:"name"`
@@ -106,6 +116,10 @@ type PlatformMetrics struct {
FailedLoginsLast24h int64 `json:"failed_logins_last_24h"`
TwoFactorAdoptionRate float64 `json:"two_factor_adoption_rate"`
TwoFactorUsers int64 `json:"two_factor_users"`
+
+ // Workspace-only migration progress
+ UsersUnmigrated int64 `json:"users_unmigrated"`
+ UsersMigrationFailed int64 `json:"users_migration_failed"`
}
// processStartTime records when the process started, for uptime reporting.
@@ -183,9 +197,13 @@ func (h *AdminHandler) CreateUser(c *okapi.Context, req *AdminCreateUserRequest)
return c.AbortConflict("email already registered")
}
- // Seed default templates, stylesheets, and languages for the new user
- if h.seeder != nil {
- go h.seeder.SeedUserDefaults(user.ID, user.Name)
+ // Provision the new user's personal workspace and seed its default content.
+ if h.migrator != nil {
+ go func(id uint) {
+ if _, err := h.migrator.MigrateUser(h.db, id); err != nil {
+ logger.Error("failed to provision personal workspace", "user_id", id, "err", err)
+ }
+ }(user.ID)
}
if h.bus != nil {
@@ -408,6 +426,10 @@ func (h *AdminHandler) Metrics(c *okapi.Context) error {
m.TwoFactorAdoptionRate = float64(m.TwoFactorUsers) / float64(m.TotalUsers) * 100
}
+ // Workspace-only migration progress.
+ h.db.Model(&models.User{}).Where("personal_workspace_id IS NULL").Count(&m.UsersUnmigrated)
+ h.db.Model(&models.User{}).Where("migration_error IS NOT NULL AND migration_error <> ''").Count(&m.UsersMigrationFailed)
+
h.cache.Set(ctx, cacheKey, m, cache.AdminMetricsTTL)
fillRuntimeStats(&m)
diff --git a/internal/handlers/event_handler.go b/internal/handlers/event_handler.go
index 10cde81..887c9a2 100644
--- a/internal/handlers/event_handler.go
+++ b/internal/handlers/event_handler.go
@@ -74,6 +74,18 @@ func (h *EventHandler) UserAuditLog(c *okapi.Context, req *ListEventsRequest) er
return paginated(c, events, total, page, size)
}
+func (h *EventHandler) WorkspaceAuditLog(c *okapi.Context, req *ListEventsRequest) error {
+ wsID := c.GetInt("workspace_id")
+ page, size, offset := normalizePageParams(req.Page, req.Size)
+
+ events, total, err := h.repo.FindByWorkspaceAndCategory(uint(wsID), models.EventCategoryAudit, size, offset)
+ if err != nil {
+ return c.AbortInternalServerError("failed to list audit events")
+ }
+
+ return paginated(c, events, total, page, size)
+}
+
// Stream sends real-time events to the admin via SSE.
func (h *EventHandler) Stream(c *okapi.Context) error {
ctx := c.Request().Context()
diff --git a/internal/handlers/oauth_handler.go b/internal/handlers/oauth_handler.go
index dcda48d..7e5bac9 100644
--- a/internal/handlers/oauth_handler.go
+++ b/internal/handlers/oauth_handler.go
@@ -14,10 +14,12 @@ import (
"github.com/goposta/posta/internal/services/auth"
"github.com/goposta/posta/internal/services/eventbus"
"github.com/goposta/posta/internal/services/seeder"
+ "github.com/goposta/posta/internal/services/workspacemigrate"
"github.com/goposta/posta/internal/storage/repositories"
"github.com/jkaninda/logger"
"github.com/jkaninda/okapi"
"github.com/redis/go-redis/v9"
+ "gorm.io/gorm"
)
type OAuthHandler struct {
@@ -32,6 +34,15 @@ type OAuthHandler struct {
redisClient *redis.Client
callbackBase string // e.g. "http://localhost:9000"
appWebURL string // e.g. "http://localhost:9000"
+ db *gorm.DB
+ migrator *workspacemigrate.Service
+}
+
+// SetMigrator wires the personal-workspace migrator used to provision (and seed)
+// a personal workspace after OAuth user upsert. See §4.
+func (h *OAuthHandler) SetMigrator(db *gorm.DB, m *workspacemigrate.Service) {
+ h.db = db
+ h.migrator = m
}
func NewOAuthHandler(
@@ -230,9 +241,12 @@ func (h *OAuthHandler) Callback(c *okapi.Context) error {
return redirect("account_disabled")
}
- // Seed defaults for new users
- if isNew && h.seeder != nil {
- go h.seeder.SeedUserDefaults(user.ID, user.Name)
+ // Provision the personal workspace (and seed defaults for new users) before
+ // issuing the JWT. Idempotent: a no-op for already-migrated returning users.
+ if h.migrator != nil && h.db != nil {
+ if _, err := h.migrator.MigrateUser(h.db, user.ID); err != nil {
+ logger.Error("failed to provision personal workspace", "user_id", user.ID, "err", err)
+ }
}
// Generate JWT
diff --git a/internal/handlers/setting_handler.go b/internal/handlers/setting_handler.go
index d7f8944..062dcd4 100644
--- a/internal/handlers/setting_handler.go
+++ b/internal/handlers/setting_handler.go
@@ -18,12 +18,30 @@
package handlers
import (
+ "strings"
+
"github.com/goposta/posta/internal/models"
"github.com/goposta/posta/internal/services/audit"
"github.com/goposta/posta/internal/storage/repositories"
"github.com/jkaninda/okapi"
)
+func isReservedSettingKey(key string) bool {
+ return strings.HasPrefix(key, "app.")
+}
+
+// visibleSettings drops reserved internal rows from a settings list.
+func visibleSettings(settings []models.Setting) []models.Setting {
+ out := make([]models.Setting, 0, len(settings))
+ for _, s := range settings {
+ if isReservedSettingKey(s.Key) {
+ continue
+ }
+ out = append(out, s)
+ }
+ return out
+}
+
// SettingHandler handles admin management of platform settings.
type SettingHandler struct {
repo *repositories.SettingRepository
@@ -51,7 +69,7 @@ func (h *SettingHandler) GetSettings(c *okapi.Context) error {
if err != nil {
return c.AbortInternalServerError("failed to load settings", err)
}
- return ok(c, settings)
+ return ok(c, visibleSettings(settings))
}
func (h *SettingHandler) UpdateSettings(c *okapi.Context, req *UpdateSettingsRequest) error {
@@ -59,6 +77,10 @@ func (h *SettingHandler) UpdateSettings(c *okapi.Context, req *UpdateSettingsReq
settings := make([]models.Setting, 0, len(req.Body.Settings))
for _, s := range req.Body.Settings {
+
+ if isReservedSettingKey(s.Key) {
+ continue
+ }
typ := s.Type
if typ == "" {
typ = "string"
@@ -80,5 +102,5 @@ func (h *SettingHandler) UpdateSettings(c *okapi.Context, req *UpdateSettingsReq
if err != nil {
return c.AbortInternalServerError("failed to load settings", err)
}
- return ok(c, updated)
+ return ok(c, visibleSettings(updated))
}
diff --git a/internal/handlers/user_data_handler.go b/internal/handlers/user_data_handler.go
deleted file mode 100644
index f338189..0000000
--- a/internal/handlers/user_data_handler.go
+++ /dev/null
@@ -1,273 +0,0 @@
-/*
- * Copyright 2026 Jonas Kaninda
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package handlers
-
-import (
- "fmt"
- "time"
-
- "github.com/goposta/posta/internal/config"
- "github.com/goposta/posta/internal/models"
- "github.com/goposta/posta/internal/storage/repositories"
- "github.com/jkaninda/okapi"
- "gorm.io/gorm"
-)
-
-type UserDataHandler struct {
- db *gorm.DB
- templateRepo *repositories.TemplateRepository
- versionRepo *repositories.TemplateVersionRepository
- localizationRepo *repositories.TemplateLocalizationRepository
- stylesheetRepo *repositories.StyleSheetRepository
- languageRepo *repositories.LanguageRepository
- contactRepo *repositories.ContactRepository
- webhookRepo *repositories.WebhookRepository
- suppressionRepo *repositories.SuppressionRepository
- userSettingRepo *repositories.UserSettingRepository
-}
-
-func NewUserDataHandler(
- db *gorm.DB,
- templateRepo *repositories.TemplateRepository,
- versionRepo *repositories.TemplateVersionRepository,
- localizationRepo *repositories.TemplateLocalizationRepository,
- stylesheetRepo *repositories.StyleSheetRepository,
- languageRepo *repositories.LanguageRepository,
- contactRepo *repositories.ContactRepository,
- webhookRepo *repositories.WebhookRepository,
- suppressionRepo *repositories.SuppressionRepository,
- userSettingRepo *repositories.UserSettingRepository,
-) *UserDataHandler {
- return &UserDataHandler{
- db: db,
- templateRepo: templateRepo,
- versionRepo: versionRepo,
- localizationRepo: localizationRepo,
- stylesheetRepo: stylesheetRepo,
- languageRepo: languageRepo,
- contactRepo: contactRepo,
- webhookRepo: webhookRepo,
- suppressionRepo: suppressionRepo,
- userSettingRepo: userSettingRepo,
- }
-}
-
-type UserDataExport struct {
- PostaVersion string `json:"posta_version"`
- ExportedAt string `json:"exported_at"`
- Templates []TemplateExport `json:"templates"`
- Stylesheets []ExportStyleSheet `json:"stylesheets"`
- Languages []ExportLanguage `json:"languages"`
- Contacts []ExportContact `json:"contacts"`
- Suppressions []ExportSuppression `json:"suppressions"`
- Webhooks []ExportWebhook `json:"webhooks"`
- Settings *ExportUserSettings `json:"settings,omitempty"`
-}
-
-type ImportUserDataRequest struct {
- Body UserDataExport `json:"body"`
-}
-
-type GDPRDeleteContactsRequest struct {
- Body struct {
- Email string `json:"email"`
- } `json:"body"`
-}
-
-type GDPRDeleteEmailLogsRequest struct {
- Body struct {
- OlderThanDays int `json:"older_than_days"`
- } `json:"body"`
-}
-
-type GDPRDeleteResult struct {
- Deleted int64 `json:"deleted"`
- Message string `json:"message"`
-}
-
-func (h *UserDataHandler) Export(c *okapi.Context) error {
- userID := uint(c.GetInt("user_id"))
- scope := repositories.ResourceScope{UserID: userID}
-
- templates, _, err := h.templateRepo.FindByScope(scope, "", exportLimit, 0)
- if err != nil {
- return c.AbortInternalServerError("failed to load templates")
- }
- tmplExport, err := exportTemplates(templates, h.versionRepo, h.localizationRepo)
- if err != nil {
- return c.AbortInternalServerError("failed to load template details")
- }
-
- stylesheets, _, err := h.stylesheetRepo.FindByScope(scope, exportLimit, 0)
- if err != nil {
- return c.AbortInternalServerError("failed to load stylesheets")
- }
-
- languages, _, err := h.languageRepo.FindByScope(scope, exportLimit, 0)
- if err != nil {
- return c.AbortInternalServerError("failed to load languages")
- }
-
- contacts, _, err := h.contactRepo.FindByScope(scope, "", exportLimit, 0)
- if err != nil {
- return c.AbortInternalServerError("failed to load contacts")
- }
-
- suppressions, _, err := h.suppressionRepo.FindByScope(scope, exportLimit, 0)
- if err != nil {
- return c.AbortInternalServerError("failed to load suppressions")
- }
-
- webhooks, _, err := h.webhookRepo.FindByScope(scope, exportLimit, 0)
- if err != nil {
- return c.AbortInternalServerError("failed to load webhooks")
- }
-
- var settings *ExportUserSettings
- s, err := h.userSettingRepo.FindByUserID(userID)
- if err == nil && s != nil {
- settings = &ExportUserSettings{
- Timezone: s.Timezone,
- DefaultSenderName: s.DefaultSenderName,
- DefaultSenderEmail: s.DefaultSenderEmail,
- EmailNotifications: s.EmailNotifications,
- NotificationEmail: s.NotificationEmail,
- WebhookRetryCount: s.WebhookRetryCount,
- APIKeyExpiryDays: s.APIKeyExpiryDays,
- BounceAutoSuppress: s.BounceAutoSuppress,
- DailyReport: s.DailyReport,
- }
- }
-
- return ok(c, UserDataExport{
- PostaVersion: config.Version,
- ExportedAt: time.Now().UTC().Format(time.RFC3339),
- Templates: tmplExport,
- Stylesheets: exportStylesheets(stylesheets),
- Languages: exportLanguages(languages),
- Contacts: exportContacts(contacts),
- Suppressions: exportSuppressions(suppressions),
- Webhooks: exportWebhooks(webhooks),
- Settings: settings,
- })
-}
-
-func (h *UserDataHandler) Import(c *okapi.Context, req *ImportUserDataRequest) error {
- userID := uint(c.GetInt("user_id"))
- data := req.Body
-
- var total int
- total += importLanguages(data.Languages, userID, nil, h.languageRepo)
- total += importStylesheets(data.Stylesheets, userID, nil, h.stylesheetRepo)
- total += importTemplates(data.Templates, userID, nil, h.templateRepo, h.versionRepo, h.localizationRepo)
- total += importContacts(data.Contacts, userID, nil, h.db)
- total += importSuppressions(data.Suppressions, userID, nil, h.suppressionRepo)
- total += importWebhooks(data.Webhooks, userID, nil, h.db)
-
- // Import settings
- if data.Settings != nil {
- settings, err := h.userSettingRepo.FindByUserID(userID)
- if err == nil && settings != nil {
- settings.Timezone = data.Settings.Timezone
- settings.DefaultSenderName = data.Settings.DefaultSenderName
- settings.DefaultSenderEmail = data.Settings.DefaultSenderEmail
- settings.EmailNotifications = data.Settings.EmailNotifications
- settings.NotificationEmail = data.Settings.NotificationEmail
- settings.WebhookRetryCount = data.Settings.WebhookRetryCount
- settings.APIKeyExpiryDays = data.Settings.APIKeyExpiryDays
- settings.BounceAutoSuppress = data.Settings.BounceAutoSuppress
- settings.DailyReport = data.Settings.DailyReport
- _ = h.userSettingRepo.CreateOrUpdate(settings)
- }
- }
-
- return ok(c, map[string]any{
- "message": "Data imported successfully",
- "imported_count": total,
- })
-}
-
-func (h *UserDataHandler) DeleteContacts(c *okapi.Context, req *GDPRDeleteContactsRequest) error {
- userID := uint(c.GetInt("user_id"))
- email := req.Body.Email
-
- if email == "" {
- result := h.db.Where("user_id = ?", userID).Delete(&models.Contact{})
- if result.Error != nil {
- return c.AbortInternalServerError("failed to delete contacts")
- }
- return ok(c, GDPRDeleteResult{
- Deleted: result.RowsAffected,
- Message: "All contacts deleted",
- })
- }
-
- result := h.db.Where("user_id = ? AND email = ?", userID, email).Delete(&models.Contact{})
- if result.Error != nil {
- return c.AbortInternalServerError("failed to delete contact")
- }
-
- h.db.Where("user_id = ? AND email = ?", userID, email).Delete(&models.Suppression{})
-
- var listIDs []uint
- h.db.Model(&models.ContactList{}).Where("user_id = ?", userID).Pluck("id", &listIDs)
- if len(listIDs) > 0 {
- h.db.Where("list_id IN ? AND email = ?", listIDs, email).Delete(&models.ContactListMember{})
- }
-
- return ok(c, GDPRDeleteResult{
- Deleted: result.RowsAffected,
- Message: fmt.Sprintf("Contact %s and associated data deleted", email),
- })
-}
-
-func (h *UserDataHandler) DeleteEmailLogs(c *okapi.Context, req *GDPRDeleteEmailLogsRequest) error {
- userID := uint(c.GetInt("user_id"))
-
- days := req.Body.OlderThanDays
- if days <= 0 {
- days = 0
- }
-
- query := h.db.Where("user_id = ?", userID)
- if days > 0 {
- before := time.Now().AddDate(0, 0, -days)
- query = query.Where("created_at < ?", before)
- }
-
- var emailIDs []uint
- query.Model(&models.Email{}).Pluck("id", &emailIDs)
- if len(emailIDs) > 0 {
- h.db.Where("email_id IN ?", emailIDs).Delete(&models.Bounce{})
- }
-
- result := query.Delete(&models.Email{})
- if result.Error != nil {
- return c.AbortInternalServerError("failed to delete email logs")
- }
-
- msg := "All email logs deleted"
- if days > 0 {
- msg = fmt.Sprintf("Email logs older than %d days deleted", days)
- }
-
- return ok(c, GDPRDeleteResult{
- Deleted: result.RowsAffected,
- Message: msg,
- })
-}
diff --git a/internal/handlers/user_handler.go b/internal/handlers/user_handler.go
index 1202d45..987b24f 100644
--- a/internal/handlers/user_handler.go
+++ b/internal/handlers/user_handler.go
@@ -33,10 +33,12 @@ import (
"github.com/goposta/posta/internal/services/seeder"
"github.com/goposta/posta/internal/services/settings"
"github.com/goposta/posta/internal/services/twofactor"
+ "github.com/goposta/posta/internal/services/workspacemigrate"
"github.com/goposta/posta/internal/storage/repositories"
"github.com/jkaninda/logger"
"github.com/jkaninda/okapi"
"golang.org/x/crypto/bcrypt"
+ "gorm.io/gorm"
)
type UserHandler struct {
@@ -48,6 +50,8 @@ type UserHandler struct {
settings *settings.Provider
notifier *notification.Service
emailVerifier *emailverify.Service
+ db *gorm.DB
+ migrator *workspacemigrate.Service
}
func NewUserHandler(repo *repositories.UserRepository, jwtSecret string, seeder *seeder.Seeder, bus *eventbus.EventBus) *UserHandler {
@@ -59,6 +63,20 @@ func NewUserHandler(repo *repositories.UserRepository, jwtSecret string, seeder
}
}
+func (h *UserHandler) SetMigrator(db *gorm.DB, m *workspacemigrate.Service) {
+ h.db = db
+ h.migrator = m
+}
+
+func (h *UserHandler) ensurePersonalWorkspace(userID uint) {
+ if h.migrator == nil || h.db == nil {
+ return
+ }
+ if _, err := h.migrator.MigrateUser(h.db, userID); err != nil {
+ logger.Error("failed to provision personal workspace", "user_id", userID, "err", err)
+ }
+}
+
func (h *UserHandler) SetSessionRepo(repo *repositories.SessionRepository) {
h.sessionRepo = repo
}
@@ -196,10 +214,9 @@ func (h *UserHandler) Register(c *okapi.Context, req *RegisterRequest) error {
return c.AbortConflict("email already registered")
}
- // Seed default data for the new user
- if h.seeder != nil {
- go h.seeder.SeedUserDefaults(user.ID, user.Name)
- }
+ // Provision the user's personal workspace (and seed its default content)
+ // before issuing the JWT, so the first authenticated request lands in it.
+ h.ensurePersonalWorkspace(user.ID)
if h.bus != nil {
h.bus.PublishSimple(models.EventCategoryUser, "user.registered", &user.ID, user.Email, c.RealIP(),
@@ -391,8 +408,7 @@ func (h *UserHandler) Login(c *okapi.Context, req *LoginRequest) error {
}
}
- // Seed default data on first login
- go h.seeder.SeedUserDefaults(user.ID, user.Name)
+ h.ensurePersonalWorkspace(user.ID)
// Record last login time
now := time.Now()
diff --git a/internal/handlers/workspace_data_handler.go b/internal/handlers/workspace_data_handler.go
index 493e4b9..9c5ce51 100644
--- a/internal/handlers/workspace_data_handler.go
+++ b/internal/handlers/workspace_data_handler.go
@@ -18,9 +18,11 @@
package handlers
import (
+ "fmt"
"time"
"github.com/goposta/posta/internal/config"
+ "github.com/goposta/posta/internal/models"
"github.com/goposta/posta/internal/storage/repositories"
"github.com/jkaninda/okapi"
"gorm.io/gorm"
@@ -235,3 +237,93 @@ func (h *WorkspaceDataHandler) Import(c *okapi.Context, req *ImportWorkspaceData
"imported_count": total,
})
}
+
+type GDPRDeleteContactsRequest struct {
+ Body struct {
+ Email string `json:"email"`
+ } `json:"body"`
+}
+
+type GDPRDeleteEmailLogsRequest struct {
+ Body struct {
+ OlderThanDays int `json:"older_than_days"`
+ } `json:"body"`
+}
+
+type GDPRDeleteResult struct {
+ Deleted int64 `json:"deleted"`
+ Message string `json:"message"`
+}
+
+// DeleteContacts (GDPR) removes contact data scoped to the active workspace.
+func (h *WorkspaceDataHandler) DeleteContacts(c *okapi.Context, req *GDPRDeleteContactsRequest) error {
+ wsID := uint(c.GetInt("workspace_id"))
+ if wsID == 0 {
+ return c.AbortBadRequest("workspace context required")
+ }
+ email := req.Body.Email
+
+ if email == "" {
+ result := h.db.Where("workspace_id = ?", wsID).Delete(&models.Contact{})
+ if result.Error != nil {
+ return c.AbortInternalServerError("failed to delete contacts")
+ }
+ return ok(c, GDPRDeleteResult{Deleted: result.RowsAffected, Message: "All contacts deleted"})
+ }
+
+ result := h.db.Where("workspace_id = ? AND email = ?", wsID, email).Delete(&models.Contact{})
+ if result.Error != nil {
+ return c.AbortInternalServerError("failed to delete contact")
+ }
+
+ h.db.Where("workspace_id = ? AND email = ?", wsID, email).Delete(&models.Suppression{})
+
+ var listIDs []uint
+ h.db.Model(&models.ContactList{}).Where("workspace_id = ?", wsID).Pluck("id", &listIDs)
+ if len(listIDs) > 0 {
+ h.db.Where("list_id IN ? AND email = ?", listIDs, email).Delete(&models.ContactListMember{})
+ }
+
+ return ok(c, GDPRDeleteResult{
+ Deleted: result.RowsAffected,
+ Message: fmt.Sprintf("Contact %s and associated data deleted", email),
+ })
+}
+
+// DeleteEmailLogs (GDPR) purges email logs scoped to the active workspace.
+// Mirrors UserDataHandler.DeleteEmailLogs but scopes by workspace_id.
+func (h *WorkspaceDataHandler) DeleteEmailLogs(c *okapi.Context, req *GDPRDeleteEmailLogsRequest) error {
+ wsID := uint(c.GetInt("workspace_id"))
+ if wsID == 0 {
+ return c.AbortBadRequest("workspace context required")
+ }
+
+ days := req.Body.OlderThanDays
+ if days < 0 {
+ days = 0
+ }
+
+ query := h.db.Where("workspace_id = ?", wsID)
+ if days > 0 {
+ before := time.Now().AddDate(0, 0, -days)
+ query = query.Where("created_at < ?", before)
+ }
+
+ var emailIDs []uint
+ query.Model(&models.Email{}).Pluck("id", &emailIDs)
+ if len(emailIDs) > 0 {
+ h.db.Where("email_id IN ?", emailIDs).Delete(&models.Bounce{})
+ }
+
+ result := query.Delete(&models.Email{})
+ if result.Error != nil {
+ return c.AbortInternalServerError("failed to delete email logs")
+ }
+
+ msg := "All email logs deleted"
+ if days > 0 {
+ msg = fmt.Sprintf("Email logs older than %d days deleted", days)
+ }
+
+ return ok(c, GDPRDeleteResult{Deleted: result.RowsAffected, Message: msg})
+}
diff --git a/internal/handlers/workspace_handler.go b/internal/handlers/workspace_handler.go
index 23ef1cb..f36f218 100644
--- a/internal/handlers/workspace_handler.go
+++ b/internal/handlers/workspace_handler.go
@@ -109,6 +109,7 @@ type WorkspaceResponse struct {
Description string `json:"description"`
OwnerID uint `json:"owner_id"`
Role string `json:"role"`
+ IsPersonal bool `json:"is_personal"`
CreatedAt time.Time `json:"created_at"`
}
@@ -190,6 +191,7 @@ func (h *WorkspaceHandler) Create(c *okapi.Context, req *CreateWorkspaceRequest)
Description: ws.Description,
OwnerID: ws.OwnerID,
Role: string(models.WorkspaceRoleOwner),
+ IsPersonal: ws.IsPersonal,
CreatedAt: ws.CreatedAt,
})
}
@@ -216,6 +218,7 @@ func (h *WorkspaceHandler) List(c *okapi.Context) error {
Description: ws.Description,
OwnerID: ws.OwnerID,
Role: role,
+ IsPersonal: ws.IsPersonal,
CreatedAt: ws.CreatedAt,
})
}
@@ -240,6 +243,7 @@ func (h *WorkspaceHandler) Get(c *okapi.Context) error {
Description: ws.Description,
OwnerID: ws.OwnerID,
Role: role,
+ IsPersonal: ws.IsPersonal,
CreatedAt: ws.CreatedAt,
})
}
@@ -276,6 +280,7 @@ func (h *WorkspaceHandler) Update(c *okapi.Context, req *UpdateWorkspaceRequest)
Description: ws.Description,
OwnerID: ws.OwnerID,
Role: role,
+ IsPersonal: ws.IsPersonal,
CreatedAt: ws.CreatedAt,
})
}
@@ -682,85 +687,6 @@ func (h *WorkspaceHandler) DeclineInvitation(c *okapi.Context, req *DeclineInvit
return ok(c, okapi.M{"message": "invitation declined"})
}
-type TransferDataRequest struct {
- Body struct {
- Resources []string `json:"resources" required:"true"`
- } `json:"body"`
-}
-
-type TransferResult struct {
- Resource string `json:"resource"`
- Count int64 `json:"count"`
-}
-
-type TransferResponse struct {
- Message string `json:"message"`
- Results []TransferResult `json:"results"`
- Total int64 `json:"total"`
-}
-
-// TransferData moves the current user's personal data into the workspace.
-func (h *WorkspaceHandler) TransferData(c *okapi.Context, req *TransferDataRequest) error {
- userID := c.GetInt("user_id")
- wsID := c.GetInt("workspace_id")
- if wsID == 0 {
- return c.AbortBadRequest("workspace context required")
- }
-
- allowedResources := map[string]string{
- "templates": "templates",
- "stylesheets": "style_sheets",
- "languages": "languages",
- "smtp_servers": "smtp_servers",
- "domains": "domains",
- "webhooks": "webhooks",
- "contacts": "contacts",
- "subscribers": "subscribers",
- "subscriber_lists": "subscriber_lists",
- "suppressions": "suppressions",
- "api_keys": "api_keys",
- "bounces": "bounces",
- "emails": "emails",
- }
-
- var results []TransferResult
- var totalMoved int64
-
- wsIDVal := uint(wsID)
-
- err := h.db.Transaction(func(tx *gorm.DB) error {
- for _, res := range req.Body.Resources {
- table, ok := allowedResources[res]
- if !ok {
- continue
- }
- result := tx.Exec(
- fmt.Sprintf(`UPDATE %s SET workspace_id = ? WHERE user_id = ? AND workspace_id IS NULL`, table),
- wsIDVal, userID,
- )
- if result.Error != nil {
- return result.Error
- }
- results = append(results, TransferResult{
- Resource: res,
- Count: result.RowsAffected,
- })
- totalMoved += result.RowsAffected
- }
- return nil
- })
-
- if err != nil {
- return c.AbortInternalServerError("failed to transfer data: " + err.Error())
- }
-
- return ok(c, TransferResponse{
- Message: fmt.Sprintf("transferred %d records to workspace", totalMoved),
- Results: results,
- Total: totalMoved,
- })
-}
-
var slugRegex = regexp.MustCompile(`^[a-z0-9]+(?:-[a-z0-9]+)*$`)
func isValidSlug(s string) bool {
diff --git a/internal/handlers/workspace_setting_handler.go b/internal/handlers/workspace_setting_handler.go
new file mode 100644
index 0000000..fe49e22
--- /dev/null
+++ b/internal/handlers/workspace_setting_handler.go
@@ -0,0 +1,94 @@
+/*
+ * Copyright 2026 Jonas Kaninda
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package handlers
+
+import (
+ "github.com/goposta/posta/internal/storage/repositories"
+ "github.com/jkaninda/okapi"
+)
+
+type WorkspaceSettingHandler struct {
+ repo *repositories.WorkspaceSettingRepository
+}
+
+func NewWorkspaceSettingHandler(repo *repositories.WorkspaceSettingRepository) *WorkspaceSettingHandler {
+ return &WorkspaceSettingHandler{repo: repo}
+}
+
+type UpdateWorkspaceSettingsRequest struct {
+ Body struct {
+ Timezone *string `json:"timezone"`
+ DefaultSenderName *string `json:"default_sender_name"`
+ DefaultSenderEmail *string `json:"default_sender_email"`
+ WebhookRetryCount *int `json:"webhook_retry_count"`
+ APIKeyExpiryDays *int `json:"api_key_expiry_days"`
+ BounceAutoSuppress *bool `json:"bounce_auto_suppress"`
+ RequireVerifiedDomain *bool `json:"require_verified_domain"`
+ } `json:"body"`
+}
+
+// GetSettings returns the current workspace's operational settings. Any member
+// may read them.
+func (h *WorkspaceSettingHandler) GetSettings(c *okapi.Context) error {
+ wsID := uint(c.GetInt("workspace_id"))
+
+ settings, err := h.repo.FindByWorkspaceID(wsID)
+ if err != nil {
+ return c.AbortInternalServerError("failed to load settings", err)
+ }
+ return ok(c, settings)
+}
+
+// UpdateSettings updates the current workspace's operational settings. Restricted
+// to admin/owner via the RequireWorkspaceRole middleware on the route.
+func (h *WorkspaceSettingHandler) UpdateSettings(c *okapi.Context, req *UpdateWorkspaceSettingsRequest) error {
+ wsID := uint(c.GetInt("workspace_id"))
+
+ settings, err := h.repo.FindByWorkspaceID(wsID)
+ if err != nil {
+ return c.AbortInternalServerError("failed to load settings", err)
+ }
+
+ if req.Body.Timezone != nil {
+ settings.Timezone = *req.Body.Timezone
+ }
+ if req.Body.DefaultSenderName != nil {
+ settings.DefaultSenderName = *req.Body.DefaultSenderName
+ }
+ if req.Body.DefaultSenderEmail != nil {
+ settings.DefaultSenderEmail = *req.Body.DefaultSenderEmail
+ }
+ if req.Body.WebhookRetryCount != nil {
+ settings.WebhookRetryCount = *req.Body.WebhookRetryCount
+ }
+ if req.Body.APIKeyExpiryDays != nil {
+ settings.APIKeyExpiryDays = *req.Body.APIKeyExpiryDays
+ }
+ if req.Body.BounceAutoSuppress != nil {
+ settings.BounceAutoSuppress = *req.Body.BounceAutoSuppress
+ }
+ if req.Body.RequireVerifiedDomain != nil {
+ settings.RequireVerifiedDomain = *req.Body.RequireVerifiedDomain
+ }
+
+ if err := h.repo.CreateOrUpdate(settings); err != nil {
+ return c.AbortInternalServerError("failed to update settings", err)
+ }
+
+ return ok(c, settings)
+}
diff --git a/internal/middlewares/workspace.go b/internal/middlewares/workspace.go
index 9a4fd8f..be98a03 100644
--- a/internal/middlewares/workspace.go
+++ b/internal/middlewares/workspace.go
@@ -25,14 +25,24 @@ import (
"github.com/jkaninda/okapi"
)
-// OptionalWorkspaceMiddleware reads the X-Posta-Workspace-Id header if present.
-// If absent, the request operates in personal mode (workspace_id stays 0).
-// If present, validates membership and sets workspace_id + workspace_role.
-func OptionalWorkspaceMiddleware(workspaceRepo *repositories.WorkspaceRepository) okapi.Middleware {
+func OptionalWorkspaceMiddleware(workspaceRepo *repositories.WorkspaceRepository, userRepo *repositories.UserRepository) okapi.Middleware {
return func(c *okapi.Context) error {
wsHeader := c.Header("X-Posta-Workspace-Id")
if wsHeader == "" {
- // Personal mode — no workspace context
+ if c.GetInt("workspace_id") > 0 {
+ return c.Next()
+ }
+ userID := c.GetInt("user_id")
+ if userID == 0 || userRepo == nil {
+ return c.Next()
+ }
+ personalID, err := userRepo.PersonalWorkspaceID(uint(userID))
+ if err != nil || personalID == nil {
+ // Not migrated yet — legacy personal mode.
+ return c.Next()
+ }
+ c.Set("workspace_id", int(*personalID))
+ c.Set("workspace_role", string(models.WorkspaceRoleOwner))
return c.Next()
}
@@ -58,6 +68,42 @@ func OptionalWorkspaceMiddleware(workspaceRepo *repositories.WorkspaceRepository
}
}
+func WorkspaceFromQueryOrHeader(workspaceRepo *repositories.WorkspaceRepository, userRepo *repositories.UserRepository) okapi.Middleware {
+ return func(c *okapi.Context) error {
+ userID := c.GetInt("user_id")
+ if userID == 0 {
+ return c.AbortUnauthorized("authentication required")
+ }
+
+ raw := c.Header("X-Posta-Workspace-Id")
+ if raw == "" {
+ raw = c.Query("workspace_id")
+ }
+ if raw != "" {
+ wsID, err := strconv.Atoi(raw)
+ if err != nil || wsID <= 0 {
+ return c.AbortBadRequest("invalid workspace id")
+ }
+ member, err := workspaceRepo.FindMember(uint(wsID), uint(userID))
+ if err != nil {
+ return c.AbortForbidden("you are not a member of this workspace")
+ }
+ c.Set("workspace_id", wsID)
+ c.Set("workspace_role", string(member.Role))
+ return c.Next()
+ }
+
+ // Neither header nor query — fall back to the personal workspace.
+ if userRepo != nil {
+ if personalID, err := userRepo.PersonalWorkspaceID(uint(userID)); err == nil && personalID != nil {
+ c.Set("workspace_id", int(*personalID))
+ c.Set("workspace_role", string(models.WorkspaceRoleOwner))
+ }
+ }
+ return c.Next()
+ }
+}
+
// RequireWorkspaceMiddleware is like OptionalWorkspaceMiddleware but requires
// the header to be present (for workspace-only endpoints like member management).
func RequireWorkspaceMiddleware(workspaceRepo *repositories.WorkspaceRepository) okapi.Middleware {
diff --git a/internal/models/subscriber.go b/internal/models/subscriber.go
index 05c1336..9e9784e 100644
--- a/internal/models/subscriber.go
+++ b/internal/models/subscriber.go
@@ -60,7 +60,7 @@ func (cf *CustomFields) Scan(value interface{}) error {
type Subscriber struct {
ID uint `json:"id" gorm:"primaryKey"`
- UserID uint `json:"user_id" gorm:"uniqueIndex:idx_sub_scope_email;not null"`
+ UserID uint `json:"user_id" gorm:"index;not null"`
WorkspaceID *uint `json:"workspace_id,omitempty" gorm:"uniqueIndex:idx_sub_scope_email;index"`
Email string `json:"email" gorm:"uniqueIndex:idx_sub_scope_email;not null"`
Name string `json:"name" gorm:"default:''"`
diff --git a/internal/models/upgrade_step.go b/internal/models/upgrade_step.go
new file mode 100644
index 0000000..d811c6d
--- /dev/null
+++ b/internal/models/upgrade_step.go
@@ -0,0 +1,27 @@
+/*
+ * Copyright 2026 Jonas Kaninda
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package models
+
+import "time"
+
+type UpgradeStep struct {
+ ID string `json:"id" gorm:"primaryKey;size:128"`
+ AppVersion string `json:"app_version" gorm:"size:64;not null"`
+ AppliedAt time.Time `json:"applied_at" gorm:"not null"`
+ DurationMS int64 `json:"duration_ms"`
+}
diff --git a/internal/models/user.go b/internal/models/user.go
index fe81648..0c98385 100644
--- a/internal/models/user.go
+++ b/internal/models/user.go
@@ -44,6 +44,10 @@ type User struct {
CreatedAt time.Time `json:"created_at"`
LastLoginAt *time.Time `json:"last_login_at"`
+ PersonalWorkspaceID *uint `json:"personal_workspace_id" gorm:"index"`
+ MigratedAt *time.Time `json:"migrated_at"`
+ MigrationError string `json:"migration_error,omitempty" gorm:"type:text"`
+
Plan Plan `json:"-" gorm:"foreignKey:PlanID"`
}
diff --git a/internal/models/workspace.go b/internal/models/workspace.go
index fbbf441..de3e532 100644
--- a/internal/models/workspace.go
+++ b/internal/models/workspace.go
@@ -44,6 +44,7 @@ type Workspace struct {
OwnerID uint `json:"owner_id" gorm:"index;not null"`
PlanID *uint `json:"plan_id" gorm:"index"`
DefaultLanguage string `json:"default_language" gorm:"size:10;default:'en'"`
+ IsPersonal bool `json:"is_personal" gorm:"not null;default:false"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
diff --git a/internal/models/workspace_setting.go b/internal/models/workspace_setting.go
new file mode 100644
index 0000000..c62f499
--- /dev/null
+++ b/internal/models/workspace_setting.go
@@ -0,0 +1,34 @@
+/*
+ * Copyright 2026 Jonas Kaninda
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package models
+
+import "time"
+
+type WorkspaceSetting struct {
+ ID uint `json:"id" gorm:"primaryKey"`
+ WorkspaceID uint `json:"workspace_id" gorm:"uniqueIndex;not null"`
+ Timezone string `json:"timezone" gorm:"default:UTC"`
+ DefaultSenderName string `json:"default_sender_name"`
+ DefaultSenderEmail string `json:"default_sender_email"`
+ WebhookRetryCount int `json:"webhook_retry_count" gorm:"default:3"`
+ APIKeyExpiryDays int `json:"api_key_expiry_days" gorm:"default:90"`
+ BounceAutoSuppress bool `json:"bounce_auto_suppress" gorm:"default:true"`
+ RequireVerifiedDomain bool `json:"require_verified_domain" gorm:"default:false"`
+ CreatedAt time.Time `json:"created_at"`
+ UpdatedAt time.Time `json:"updated_at"`
+}
diff --git a/internal/routes/inbound_routes.go b/internal/routes/inbound_routes.go
index 439c9af..0c60619 100644
--- a/internal/routes/inbound_routes.go
+++ b/internal/routes/inbound_routes.go
@@ -26,8 +26,7 @@ import (
"github.com/jkaninda/okapi"
)
-// inboundWebhookRoutes returns public routes for the generic inbound-email webhook
-// and signed attachment downloads. Both are auth'd by opaque secret/token — no JWT.
+// Protected by opaque secret/token — no JWT.
func (r *Router) inboundWebhookRoutes() []okapi.RouteDefinition {
inboundGroup := r.app.Group("/api/v1/inbound").WithTagInfo(okapi.GroupTag{
Name: "Inbound",
@@ -54,17 +53,15 @@ func (r *Router) inboundWebhookRoutes() []okapi.RouteDefinition {
}
}
-// inboundUserRoutes returns authenticated routes for browsing inbound email history.
-func (r *Router) inboundUserRoutes() []okapi.RouteDefinition {
- userGroup := r.v1.Group("/users/me", r.mw.jwtAuth.Middleware, r.mw.optionalWorkspace).WithTagInfo(okapi.GroupTag{
+func (r *Router) inboundWorkspaceRoutes() []okapi.RouteDefinition {
+ userGroup := r.v1.Group("/workspaces/current", r.mw.jwtAuth.Middleware, r.mw.workspaceQuery).WithTagInfo(okapi.GroupTag{
Name: "Inbound",
Description: "Inbound email ingestion and retrieval: receive messages from upstream providers, browse history, and stream live events. Public ingest endpoints use opaque secrets; user endpoints use JWT.",
})
userGroup.WithBearerAuth()
- // SSE endpoints use query-param auth because browsers cannot set custom
- // Authorization headers on EventSource connections.
- streamGroup := r.v1.Group("/users/me", r.mw.jwtQueryAuth.Middleware, r.mw.optionalWorkspace).WithTagInfo(okapi.GroupTag{
+ // SSE endpoints
+ streamGroup := r.v1.Group("/workspaces/current", r.mw.jwtQueryAuth.Middleware, r.mw.workspaceQuery).WithTagInfo(okapi.GroupTag{
Name: "Inbound",
Description: "Inbound email ingestion and retrieval: receive messages from upstream providers, browse history, and stream live events. Public ingest endpoints use opaque secrets; user endpoints use JWT.",
})
diff --git a/internal/routes/routes.go b/internal/routes/routes.go
index 604cb8f..6d552be 100644
--- a/internal/routes/routes.go
+++ b/internal/routes/routes.go
@@ -48,6 +48,7 @@ import (
"github.com/goposta/posta/internal/services/verifier"
"github.com/goposta/posta/internal/services/webhook"
"github.com/goposta/posta/internal/services/workermon"
+ "github.com/goposta/posta/internal/services/workspacemigrate"
"github.com/goposta/posta/internal/storage/blob"
"github.com/goposta/posta/internal/storage/repositories"
"github.com/goposta/posta/internal/worker"
@@ -74,52 +75,56 @@ type routerMiddleware struct {
apiKey okapi.Middleware
workspace okapi.Middleware
optionalWorkspace okapi.Middleware
+ workspaceQuery okapi.Middleware
verifiedEmail okapi.Middleware
}
type routerHandlers struct {
- health *handlers.HealthHandler
- user *handlers.UserHandler
- email *handlers.EmailHandler
- apiKey *handlers.APIKeyHandler
- template *handlers.TemplateHandler
- version *handlers.TemplateVersionHandler
- localization *handlers.TemplateLocalizationHandler
- language *handlers.LanguageHandler
- stylesheet *handlers.StyleSheetHandler
- smtp *handlers.SMTPHandler
- webhook *handlers.WebhookHandler
- webhookDelivery *handlers.WebhookDeliveryHandler
- dashboard *handlers.DashboardHandler
- domain *handlers.DomainHandler
- bounce *handlers.BounceHandler
- suppression *handlers.SuppressionHandler
- unsubscribeList *handlers.UnsubscribeListHandler
- contact *handlers.ContactHandler
- admin *handlers.AdminHandler
- workspace *handlers.WorkspaceHandler
- server *handlers.ServerHandler
- event *handlers.EventHandler
- analytics *handlers.AnalyticsHandler
- setting *handlers.SettingHandler
- userSetting *handlers.UserSettingHandler
- userData *handlers.UserDataHandler
- session *handlers.SessionHandler
- cron *handlers.CronHandler
- oauth *handlers.OAuthHandler
- oauthAdmin *handlers.OAuthAdminHandler
- subscriber *handlers.SubscriberHandler
- subscriberList *handlers.SubscriberListHandler
- campaign *handlers.CampaignHandler
- tracking *handlers.TrackingHandler
- bounceWebhook *handlers.BounceWebhookHandler
- workspaceData *handlers.WorkspaceDataHandler
- plan *handlers.PlanHandler
- inbound *handlers.InboundHandler
- verify *handlers.VerifyHandler
+ health *handlers.HealthHandler
+ user *handlers.UserHandler
+ email *handlers.EmailHandler
+ apiKey *handlers.APIKeyHandler
+ template *handlers.TemplateHandler
+ version *handlers.TemplateVersionHandler
+ localization *handlers.TemplateLocalizationHandler
+ language *handlers.LanguageHandler
+ stylesheet *handlers.StyleSheetHandler
+ smtp *handlers.SMTPHandler
+ webhook *handlers.WebhookHandler
+ webhookDelivery *handlers.WebhookDeliveryHandler
+ dashboard *handlers.DashboardHandler
+ domain *handlers.DomainHandler
+ bounce *handlers.BounceHandler
+ suppression *handlers.SuppressionHandler
+ unsubscribeList *handlers.UnsubscribeListHandler
+ contact *handlers.ContactHandler
+ admin *handlers.AdminHandler
+ workspace *handlers.WorkspaceHandler
+ server *handlers.ServerHandler
+ event *handlers.EventHandler
+ analytics *handlers.AnalyticsHandler
+ setting *handlers.SettingHandler
+ userSetting *handlers.UserSettingHandler
+ workspaceSetting *handlers.WorkspaceSettingHandler
+ session *handlers.SessionHandler
+ cron *handlers.CronHandler
+ oauth *handlers.OAuthHandler
+ oauthAdmin *handlers.OAuthAdminHandler
+ subscriber *handlers.SubscriberHandler
+ subscriberList *handlers.SubscriberListHandler
+ campaign *handlers.CampaignHandler
+ tracking *handlers.TrackingHandler
+ bounceWebhook *handlers.BounceWebhookHandler
+ workspaceData *handlers.WorkspaceDataHandler
+ plan *handlers.PlanHandler
+ inbound *handlers.InboundHandler
+ verify *handlers.VerifyHandler
}
func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *config.Config, producer *worker.Producer, cronManager *cronpkg.Manager, blobStore blob.Store, ctx context.Context, notifier ...*notification.Service) {
+
+ repositories.SetWorkspaceOnlyMode(cfg.WorkspaceOnlyMode)
+
// Repositories
userRepo := repositories.NewUserRepository(db)
apiKeyRepo := repositories.NewAPIKeyRepository(db)
@@ -141,6 +146,7 @@ func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *c
eventRepo := repositories.NewEventRepository(db)
settingRepo := repositories.NewSettingRepository(db)
userSettingRepo := repositories.NewUserSettingRepository(db)
+ workspaceSettingRepo := repositories.NewWorkspaceSettingRepository(db)
sessionRepo := repositories.NewSessionRepository(db)
workspaceRepo := repositories.NewWorkspaceRepository(db)
emailVerifyRepo := repositories.NewUserEmailVerificationRepository(db)
@@ -173,7 +179,7 @@ func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *c
emailService.SetVersionRepos(versionRepo, localizationRepo)
emailService.SetContactRepo(contactRepo)
emailService.SetUnsubscribeListRepo(unsubListRepo)
- emailService.SetDomainVerification(domainRepo, userRepo)
+ emailService.SetDomainVerification(domainRepo, userRepo, workspaceSettingRepo)
if producer != nil {
emailService.SetEnqueuer(producer)
}
@@ -197,8 +203,12 @@ func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *c
// Handlers
userSeeder := seeder.New(templateRepo, stylesheetRepo, versionRepo, localizationRepo, languageRepo)
+
+ migrator := workspacemigrate.New(cfg.PlanEnforcement)
+ migrator.SetSeeder(userSeeder)
userHandler := handlers.NewUserHandler(userRepo, cfg.JWTSecret, userSeeder, bus)
userHandler.SetSettings(settingsProvider)
+ userHandler.SetMigrator(db, migrator)
inspector := asynq.NewInspector(asynq.RedisClientOpt{
Addr: cfg.Redis.Addr,
Password: cfg.Redis.Password,
@@ -224,43 +234,45 @@ func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *c
loginLimiter: loginLimiterMiddleware(cfg, limiter),
apiKey: middlewares.APIKeyAuthMiddleware(apiKeyService, userRepo, apiKeyRepo),
workspace: middlewares.RequireWorkspaceMiddleware(workspaceRepo),
- optionalWorkspace: middlewares.OptionalWorkspaceMiddleware(workspaceRepo),
+ optionalWorkspace: middlewares.OptionalWorkspaceMiddleware(workspaceRepo, userRepo),
+ workspaceQuery: middlewares.WorkspaceFromQueryOrHeader(workspaceRepo, userRepo),
},
h: routerHandlers{
- health: handlers.NewHealthHandler(db, redisClient),
- user: userHandler,
- email: handlers.NewEmailHandler(emailService, emailRepo, bus, statsCache),
- apiKey: handlers.NewAPIKeyHandler(apiKeyService, apiKeyRepo, userSettingRepo, auditLogger),
- template: handlers.NewTemplateHandler(templateRepo, stylesheetRepo, versionRepo, localizationRepo, languageRepo, emailService),
- version: handlers.NewTemplateVersionHandler(templateRepo, versionRepo),
- localization: handlers.NewTemplateLocalizationHandler(templateRepo, versionRepo, localizationRepo, stylesheetRepo),
- language: handlers.NewLanguageHandler(languageRepo),
- stylesheet: handlers.NewStyleSheetHandler(stylesheetRepo),
- smtp: handlers.NewSMTPHandler(smtpRepo, domainRepo, auditLogger),
- webhook: handlers.NewWebhookHandler(webhookRepo, auditLogger),
- webhookDelivery: handlers.NewWebhookDeliveryHandler(webhookDeliveryRepo),
- dashboard: handlers.NewDashboardHandler(db, statsCache, webhookDeliveryRepo),
- domain: handlers.NewDomainHandler(domainRepo),
- bounce: handlers.NewBounceHandler(bounceRepo, suppressionRepo, emailRepo, dispatcher),
- suppression: handlers.NewSuppressionHandler(suppressionRepo, unsubListRepo),
- unsubscribeList: handlers.NewUnsubscribeListHandler(unsubListRepo),
- contact: handlers.NewContactHandler(contactRepo, suppressionRepo),
- admin: handlers.NewAdminHandler(db, statsCache, userRepo, apiKeyRepo, emailRepo, webhookDeliveryRepo, inspector, bus, userSeeder, cfg.EmbeddedWorker),
- workspace: handlers.NewWorkspaceHandler(workspaceRepo, userRepo, db),
- server: handlers.NewServerHandler(serverRepo, auditLogger),
- event: handlers.NewEventHandler(eventRepo, bus),
- analytics: handlers.NewAnalyticsHandler(repositories.NewAnalyticsRepository(db), statsCache),
- setting: handlers.NewSettingHandler(settingRepo, auditLogger),
- userSetting: handlers.NewUserSettingHandler(userSettingRepo),
- userData: handlers.NewUserDataHandler(db, templateRepo, versionRepo, localizationRepo, stylesheetRepo, languageRepo, contactRepo, webhookRepo, suppressionRepo, userSettingRepo),
- session: handlers.NewSessionHandler(sessionRepo, sessionStore),
- verify: handlers.NewVerifyHandler(verifierSvc),
+ health: handlers.NewHealthHandler(db, redisClient),
+ user: userHandler,
+ email: handlers.NewEmailHandler(emailService, emailRepo, bus, statsCache),
+ apiKey: handlers.NewAPIKeyHandler(apiKeyService, apiKeyRepo, userSettingRepo, auditLogger),
+ template: handlers.NewTemplateHandler(templateRepo, stylesheetRepo, versionRepo, localizationRepo, languageRepo, emailService),
+ version: handlers.NewTemplateVersionHandler(templateRepo, versionRepo),
+ localization: handlers.NewTemplateLocalizationHandler(templateRepo, versionRepo, localizationRepo, stylesheetRepo),
+ language: handlers.NewLanguageHandler(languageRepo),
+ stylesheet: handlers.NewStyleSheetHandler(stylesheetRepo),
+ smtp: handlers.NewSMTPHandler(smtpRepo, domainRepo, auditLogger),
+ webhook: handlers.NewWebhookHandler(webhookRepo, auditLogger),
+ webhookDelivery: handlers.NewWebhookDeliveryHandler(webhookDeliveryRepo),
+ dashboard: handlers.NewDashboardHandler(db, statsCache, webhookDeliveryRepo),
+ domain: handlers.NewDomainHandler(domainRepo),
+ bounce: handlers.NewBounceHandler(bounceRepo, suppressionRepo, emailRepo, dispatcher),
+ suppression: handlers.NewSuppressionHandler(suppressionRepo, unsubListRepo),
+ unsubscribeList: handlers.NewUnsubscribeListHandler(unsubListRepo),
+ contact: handlers.NewContactHandler(contactRepo, suppressionRepo),
+ admin: handlers.NewAdminHandler(db, statsCache, userRepo, apiKeyRepo, emailRepo, webhookDeliveryRepo, inspector, bus, userSeeder, cfg.EmbeddedWorker),
+ workspace: handlers.NewWorkspaceHandler(workspaceRepo, userRepo, db),
+ server: handlers.NewServerHandler(serverRepo, auditLogger),
+ event: handlers.NewEventHandler(eventRepo, bus),
+ analytics: handlers.NewAnalyticsHandler(repositories.NewAnalyticsRepository(db), statsCache),
+ setting: handlers.NewSettingHandler(settingRepo, auditLogger),
+ userSetting: handlers.NewUserSettingHandler(userSettingRepo),
+ workspaceSetting: handlers.NewWorkspaceSettingHandler(workspaceSettingRepo),
+ session: handlers.NewSessionHandler(sessionRepo, sessionStore),
+ verify: handlers.NewVerifyHandler(verifierSvc),
},
}
// Session management
r.h.user.SetSessionRepo(sessionRepo)
r.h.admin.SetSessionRepo(sessionRepo, sessionStore)
+ r.h.admin.SetMigrator(migrator)
// Plans
r.h.plan = handlers.NewPlanHandler(planRepo, workspaceRepo, userRepo, planService, auditLogger)
@@ -308,6 +320,7 @@ func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *c
userRepo, sessionRepo, cfg.JWTSecret,
userSeeder, bus, redisClient, callbackBase, cfg.AppWebURL,
)
+ r.h.oauth.SetMigrator(db, migrator)
r.h.oauthAdmin = handlers.NewOAuthAdminHandler(oauthProviderRepo, ssoRepo)
// Subscribers
@@ -418,9 +431,6 @@ func (a *emailPlanAdapter) EffectiveLimits(workspaceID *uint) *email.PlanLimits
// workspaceHeaderRequired is a reusable route option documenting the required workspace header.
var workspaceHeaderRequired = okapi.DocHeader("X-Posta-Workspace-Id", "integer", "Workspace ID (required for workspace-scoped endpoints)", true)
-// workspaceHeaderOptional is a reusable route option documenting the optional workspace header.
-var workspaceHeaderOptional = okapi.DocHeader("X-Posta-Workspace-Id", "integer", "Workspace ID (optional, omit for personal mode)", false)
-
// loginLimiterMiddleware returns the login rate limit middleware when enabled,
// or a pass-through middleware when disabled.
func loginLimiterMiddleware(cfg *config.Config, limiter *ratelimit.RedisLimiter) okapi.Middleware {
@@ -449,13 +459,14 @@ func (r *Router) registerRoutes() {
r.app.Register(r.apiAuthRoutes()...)
r.app.Register(r.userRoutes()...)
r.app.Register(r.workspaceRoutes()...)
+ r.app.Register(r.workspaceResourceRoutes()...)
r.app.Register(r.oauthRoutes()...)
r.app.Register(r.trackingRoutes()...)
r.app.Register(r.trackingAnalyticsRoutes()...)
r.app.Register(r.bounceWebhookRoutes()...)
if r.cfg.InboundEnabled && r.h.inbound != nil {
r.app.Register(r.inboundWebhookRoutes()...)
- r.app.Register(r.inboundUserRoutes()...)
+ r.app.Register(r.inboundWorkspaceRoutes()...)
}
r.app.Register(r.adminRoutes()...)
r.app.Register(r.adminSSERoutes()...)
diff --git a/internal/routes/tracking_routes.go b/internal/routes/tracking_routes.go
index d168931..39e8964 100644
--- a/internal/routes/tracking_routes.go
+++ b/internal/routes/tracking_routes.go
@@ -106,20 +106,21 @@ func (r *Router) bounceWebhookRoutes() []okapi.RouteDefinition {
}
}
-// trackingAnalyticsRoutes returns the authenticated campaign analytics route.
+// trackingAnalyticsRoutes returns the authenticated campaign analytics route,
+// scoped to the active workspace (workspace-only migration §7).
func (r *Router) trackingAnalyticsRoutes() []okapi.RouteDefinition {
- userGroup := r.v1.Group("/users/me", r.mw.jwtAuth.Middleware, r.mw.optionalWorkspace).WithTagInfo(okapi.GroupTag{
+ wsGroup := r.v1.Group("/workspaces/current", r.mw.jwtAuth.Middleware, r.mw.workspace).WithTagInfo(okapi.GroupTag{
Name: "Campaigns",
- Description: "Email campaign analytics — open, click, bounce, and engagement metrics for campaigns you own.",
+ Description: "Email campaign analytics — open, click, bounce, and engagement metrics for campaigns in the active workspace.",
})
- userGroup.WithBearerAuth()
+ wsGroup.WithBearerAuth()
return []okapi.RouteDefinition{
{
Method: http.MethodGet,
Path: "/campaigns/{id:int}/analytics",
Handler: okapi.H(r.h.tracking.CampaignAnalytics),
- Group: userGroup,
+ Group: wsGroup,
Summary: "Get campaign analytics",
Response: &handlers.CampaignAnalyticsResponse{},
Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "Campaign ID")},
diff --git a/internal/routes/user_routes.go b/internal/routes/user_routes.go
index 9cde2b7..231fe3d 100644
--- a/internal/routes/user_routes.go
+++ b/internal/routes/user_routes.go
@@ -23,7 +23,6 @@ import (
"github.com/goposta/posta/internal/dto"
"github.com/goposta/posta/internal/handlers"
"github.com/goposta/posta/internal/models"
- "github.com/goposta/posta/internal/services/email"
"github.com/jkaninda/okapi"
)
@@ -36,7 +35,6 @@ func (r *Router) userRoutes() []okapi.RouteDefinition {
userGroup.WithBearerAuth()
routes := []okapi.RouteDefinition{
- // ==================== Profile ====================
{
Method: http.MethodGet,
Path: "",
@@ -77,8 +75,6 @@ func (r *Router) userRoutes() []okapi.RouteDefinition {
okapi.DocErrorResponse(429, &dto.ErrorResponseBody{}),
},
},
-
- // ==================== Plan ====================
{
Method: http.MethodGet,
Path: "/plan",
@@ -88,8 +84,6 @@ func (r *Router) userRoutes() []okapi.RouteDefinition {
Description: "Get the effective plan for the authenticated user",
Response: &dto.Response[models.Plan]{},
},
-
- // ==================== 2FA ====================
{
Method: http.MethodPost,
Path: "/2fa/setup",
@@ -119,8 +113,6 @@ func (r *Router) userRoutes() []okapi.RouteDefinition {
Request: &handlers.Disable2FARequest{},
Response: &dto.Response[any]{},
},
-
- // ==================== Account Deletion ====================
{
Method: http.MethodPost,
Path: "/delete",
@@ -139,8 +131,6 @@ func (r *Router) userRoutes() []okapi.RouteDefinition {
Description: "Cancel a previously scheduled account deletion and reactivate the account.",
Response: &dto.Response[any]{},
},
-
- // ==================== Sessions ====================
{
Method: http.MethodGet,
Path: "/sessions",
@@ -181,1230 +171,35 @@ func (r *Router) userRoutes() []okapi.RouteDefinition {
Description: "Revoke the current session's JWT token",
Response: &dto.Response[any]{},
},
-
- // ==================== Dashboard & Analytics ====================
- {
- Method: http.MethodGet,
- Path: "/dashboard/stats",
- Handler: r.h.dashboard.Stats,
- Group: userGroup,
- Summary: "Get dashboard statistics",
- Description: "Returns email sending statistics for the authenticated user",
- Response: &dto.Response[handlers.DashboardStats]{},
- },
- {
- Method: http.MethodGet,
- Path: "/analytics",
- Handler: okapi.H(r.h.analytics.UserAnalytics),
- Group: userGroup,
- Summary: "Email analytics",
- Description: "Returns daily email counts and status breakdown for the authenticated user",
- Request: &handlers.AnalyticsRequest{},
- Response: &dto.Response[handlers.AnalyticsResponse]{},
- },
- {
- Method: http.MethodGet,
- Path: "/analytics/dashboard",
- Handler: okapi.H(r.h.analytics.UserDashboardAnalytics),
- Group: userGroup,
- Summary: "Dashboard analytics",
- Description: "Returns delivery rate trends, bounce rate graphs, and latency percentiles",
- Request: &handlers.DashboardAnalyticsRequest{},
- Response: &dto.Response[handlers.DashboardAnalyticsResponse]{},
- },
- {
- Method: http.MethodGet,
- Path: "/analytics/providers",
- Handler: okapi.H(r.h.analytics.UserProviderBreakdown),
- Group: userGroup,
- Summary: "Deliverability by provider",
- Description: "Returns sent/failed counts and delivery rate grouped by recipient mailbox provider (Gmail, Outlook, Yahoo, ...)",
- Request: &handlers.ProviderBreakdownRequest{},
- Response: &dto.Response[handlers.ProviderBreakdownResponse]{},
- },
-
- // ==================== Email Logs ====================
- {
- Method: http.MethodGet,
- Path: "/emails",
- Handler: okapi.H(r.h.email.List),
- Group: userGroup,
- Summary: "List emails",
- Description: "List sent emails with pagination",
- Request: &handlers.ListRequest{},
- Response: &dto.PageableResponse[models.Email]{},
- },
- {
- Method: http.MethodGet,
- Path: "/emails/{id}",
- Handler: okapi.H(r.h.email.Get),
- Group: userGroup,
- Summary: "Get email details",
- Response: &dto.Response[models.Email]{},
- Options: []okapi.RouteOption{
- okapi.DocPathParam("id", "string", "Email UUID"),
- okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
- },
- },
- {
- Method: http.MethodGet,
- Path: "/emails/{id}/status",
- Handler: okapi.H(r.h.email.GetStatus),
- Group: userGroup,
- Summary: "Get email delivery status",
- Description: "Returns a lightweight status view for polling email delivery progress. Only the email owner can access this.",
- Response: &dto.Response[handlers.EmailStatusResponse]{},
- Options: []okapi.RouteOption{
- okapi.DocPathParam("id", "string", "Email UUID"),
- okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
- },
- },
- {
- Method: http.MethodPost,
- Path: "/emails/{id}/retry",
- Handler: okapi.H(r.h.email.Retry),
- Group: userGroup,
- Summary: "Retry failed email",
- Description: "Re-enqueue a failed email for another delivery attempt",
- Response: &dto.Response[email.SendResponse]{},
- Options: []okapi.RouteOption{
- okapi.DocPathParam("id", "string", "Email UUID"),
- okapi.DocErrorResponse(400, &dto.ErrorResponseBody{}),
- okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
- },
- },
-
- // ==================== Email Preview ====================
- {
- Method: http.MethodPost,
- Path: "/emails/preview",
- Handler: okapi.H(r.h.email.Preview),
- Group: userGroup,
- Summary: "Preview email from template",
- Description: "Render a template with variables and return the HTML, text, and subject without sending.",
- Request: &handlers.PreviewEmailRequest{},
- Response: &dto.Response[handlers.PreviewEmailResponse]{},
- Options: []okapi.RouteOption{
- okapi.DocErrorResponse(400, &dto.ErrorResponseBody{}),
- },
- },
-
- // ==================== API Keys ====================
- {
- Method: http.MethodPost,
- Path: "/api-keys",
- Handler: okapi.H(r.h.apiKey.Create),
- Group: userGroup,
- Middlewares: []okapi.Middleware{r.mw.verifiedEmail},
- Summary: "Create API key",
- Description: "Generate a new API key. The raw key is only shown once in the response.",
- Request: &handlers.CreateAPIKeyRequest{},
- Options: []okapi.RouteOption{
- okapi.DocResponse(201, &dto.Response[dto.APIKeyCreatedData]{}),
- okapi.DocErrorResponse(403, &dto.ErrorResponseBody{}),
- },
- },
- {
- Method: http.MethodGet,
- Path: "/api-keys",
- Handler: okapi.H(r.h.apiKey.List),
- Group: userGroup,
- Summary: "List API keys",
- Request: &handlers.ListRequest{},
- Response: &dto.PageableResponse[models.APIKey]{},
- },
- {
- Method: http.MethodPut,
- Path: "/api-keys/{id:int}/revoke",
- Handler: okapi.H(r.h.apiKey.Revoke),
- Group: userGroup,
- Summary: "Revoke API key",
- Response: &dto.Response[dto.MessageData]{},
- Options: []okapi.RouteOption{
- okapi.DocPathParam("id", "integer", "API key ID"),
- okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
- },
- },
- {
- Method: http.MethodDelete,
- Path: "/api-keys/{id:int}",
- Handler: okapi.H(r.h.apiKey.Delete),
- Group: userGroup,
- Summary: "Delete API key",
- Response: &dto.Response[dto.MessageData]{},
- Options: []okapi.RouteOption{
- okapi.DocPathParam("id", "integer", "API key ID"),
- okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
- },
- },
-
- // ==================== Templates ====================
- {
- Method: http.MethodPost,
- Path: "/templates",
- Handler: okapi.H(r.h.template.Create),
- Group: userGroup,
- Tags: []string{"User"},
- Summary: "Create template",
- Request: &handlers.CreateTemplateRequest{},
- Options: []okapi.RouteOption{
- okapi.DocResponse(201, &dto.Response[models.Template]{}),
- okapi.DocErrorResponse(409, &dto.ErrorResponseBody{}),
- },
- },
- {
- Method: http.MethodGet,
- Path: "/templates",
- Handler: okapi.H(r.h.template.List),
- Group: userGroup,
- Summary: "List templates",
- Request: &handlers.ListTemplatesRequest{},
- Response: &dto.PageableResponse[models.Template]{},
- },
- {
- Method: http.MethodPut,
- Path: "/templates/{id:int}",
- Handler: okapi.H(r.h.template.Update),
- Group: userGroup,
- Summary: "Update template",
- Request: &handlers.UpdateTemplateRequest{},
- Response: &dto.Response[models.Template]{},
- Options: []okapi.RouteOption{
- okapi.DocPathParam("id", "integer", "Template ID"),
- okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
- },
- },
- {
- Method: http.MethodDelete,
- Path: "/templates/{id:int}",
- Handler: okapi.H(r.h.template.Delete),
- Group: userGroup,
- Tags: []string{"User"},
- Summary: "Delete template",
- Options: []okapi.RouteOption{
- okapi.DocPathParam("id", "integer", "Template ID"),
- okapi.DocResponse(204, nil),
- okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
- },
- },
- {
- Method: http.MethodPost,
- Path: "/templates/preview",
- Handler: okapi.H(r.h.template.Preview),
- Group: userGroup,
- Summary: "Preview template",
- Description: "Render a template with sample data and return the result",
- Request: &handlers.PreviewTemplateRequest{},
- Response: &dto.Response[handlers.PreviewResult]{},
- },
- {
- Method: http.MethodPost,
- Path: "/templates/{id:int}/send-test",
- Handler: okapi.H(r.h.template.SendTest),
- Group: userGroup,
- Summary: "Send test email",
- Description: "Send a test email using a template with sample data",
- Request: &handlers.SendTestRequest{},
- Response: &dto.Response[email.SendResponse]{},
- Options: []okapi.RouteOption{
- okapi.DocPathParam("id", "integer", "Template ID"),
- okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
- },
- },
-
- // ==================== Template Import/Export ====================
- {
- Method: http.MethodGet,
- Path: "/templates/{id:int}/export",
- Handler: okapi.H(r.h.template.Export),
- Group: userGroup,
- Summary: "Export template",
- Description: "Export a template with all versions and localizations as JSON",
- Response: &dto.Response[handlers.TemplateExport]{},
- Options: []okapi.RouteOption{
- okapi.DocPathParam("id", "integer", "Template ID"),
- okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
- },
- },
- {
- Method: http.MethodPost,
- Path: "/templates/import",
- Handler: okapi.H(r.h.template.Import),
- Group: userGroup,
- Summary: "Import template",
- Description: "Import a template from a previously exported JSON payload",
- Request: &handlers.ImportTemplateRequest{},
- Options: []okapi.RouteOption{
- okapi.DocResponse(201, &dto.Response[models.Template]{}),
- okapi.DocErrorResponse(409, &dto.ErrorResponseBody{}),
- },
- },
-
- {
- Method: http.MethodPost,
- Path: "/templates/import-html",
- Handler: r.h.template.ImportHTML,
- Group: userGroup,
- Tags: []string{"Templates"},
- Summary: "Import HTML template",
- Description: "Upload an .html file to create a template. CSS from <style> blocks is extracted into a separate stylesheet.",
- Options: []okapi.RouteOption{
- okapi.DocResponse(201, &dto.Response[models.Template]{}),
- okapi.DocErrorResponse(409, &dto.ErrorResponseBody{}),
- },
- },
-
- // ==================== Template Versions ====================
- {
- Method: http.MethodGet,
- Path: "/templates/{id:int}/versions",
- Handler: okapi.H(r.h.version.List),
- Group: userGroup,
- Tags: []string{"Template Versions"},
- Summary: "List template versions",
- Response: &dto.Response[[]models.TemplateVersion]{},
- Options: []okapi.RouteOption{
- okapi.DocPathParam("id", "integer", "Template ID"),
- okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
- },
- },
- {
- Method: http.MethodPost,
- Path: "/templates/{id:int}/versions",
- Handler: okapi.H(r.h.version.Create),
- Group: userGroup,
- Tags: []string{"Template Versions"},
- Summary: "Create template version",
- Request: &handlers.CreateVersionRequest{},
- Options: []okapi.RouteOption{
- okapi.DocPathParam("id", "integer", "Template ID"),
- okapi.DocResponse(201, &dto.Response[models.TemplateVersion]{}),
- okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
- },
- },
- {
- Method: http.MethodPut,
- Path: "/templates/{id:int}/versions/{versionId:int}",
- Handler: okapi.H(r.h.version.Update),
- Group: userGroup,
- Tags: []string{"Template Versions"},
- Summary: "Update template version",
- Request: &handlers.UpdateVersionRequest{},
- Response: &dto.Response[models.TemplateVersion]{},
- Options: []okapi.RouteOption{
- okapi.DocPathParam("id", "integer", "Template ID"),
- okapi.DocPathParam("versionId", "integer", "Version ID"),
- okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
- },
- },
- {
- Method: http.MethodPost,
- Path: "/templates/{id:int}/activate/{versionId:int}",
- Handler: okapi.H(r.h.version.Activate),
- Group: userGroup,
- Tags: []string{"Template Versions"},
- Summary: "Activate template version",
- Response: &dto.Response[models.Template]{},
- Options: []okapi.RouteOption{
- okapi.DocPathParam("id", "integer", "Template ID"),
- okapi.DocPathParam("versionId", "integer", "Version ID"),
- okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
- },
- },
- {
- Method: http.MethodDelete,
- Path: "/templates/{id:int}/versions/{versionId:int}",
- Handler: okapi.H(r.h.version.Delete),
- Group: userGroup,
- Tags: []string{"Template Versions"},
- Summary: "Delete template version",
- Options: []okapi.RouteOption{
- okapi.DocPathParam("id", "integer", "Template ID"),
- okapi.DocPathParam("versionId", "integer", "Version ID"),
- okapi.DocResponse(204, nil),
- okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
- },
- },
-
- // ==================== Template Localizations ====================
- {
- Method: http.MethodGet,
- Path: "/templates/{id:int}/versions/{versionId:int}/localizations",
- Handler: okapi.H(r.h.localization.List),
- Group: userGroup,
- Tags: []string{"Template Localizations"},
- Summary: "List localizations for a version",
- Response: &dto.Response[[]models.TemplateLocalization]{},
- Options: []okapi.RouteOption{
- okapi.DocPathParam("id", "integer", "Template ID"),
- okapi.DocPathParam("versionId", "integer", "Version ID"),
- okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
- },
- },
- {
- Method: http.MethodPost,
- Path: "/templates/{id:int}/versions/{versionId:int}/localizations",
- Handler: okapi.H(r.h.localization.Create),
- Group: userGroup,
- Tags: []string{"Template Localizations"},
- Summary: "Create localization",
- Request: &handlers.CreateLocalizationRequest{},
- Options: []okapi.RouteOption{
- okapi.DocPathParam("id", "integer", "Template ID"),
- okapi.DocPathParam("versionId", "integer", "Version ID"),
- okapi.DocResponse(201, &dto.Response[models.TemplateLocalization]{}),
- okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
- okapi.DocErrorResponse(409, &dto.ErrorResponseBody{}),
- },
- },
- {
- Method: http.MethodPut,
- Path: "/localizations/{localizationId:int}",
- Handler: okapi.H(r.h.localization.Update),
- Group: userGroup,
- Tags: []string{"Template Localizations"},
- Summary: "Update localization",
- Request: &handlers.UpdateLocalizationRequest{},
- Response: &dto.Response[models.TemplateLocalization]{},
- Options: []okapi.RouteOption{
- okapi.DocPathParam("localizationId", "integer", "Localization ID"),
- okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
- },
- },
- {
- Method: http.MethodDelete,
- Path: "/localizations/{localizationId:int}",
- Handler: okapi.H(r.h.localization.Delete),
- Group: userGroup,
- Tags: []string{"Template Localizations"},
- Summary: "Delete localization",
- Options: []okapi.RouteOption{
- okapi.DocPathParam("localizationId", "integer", "Localization ID"),
- okapi.DocResponse(204, nil),
- okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
- },
- },
- {
- Method: http.MethodPost,
- Path: "/templates/{id:int}/versions/{versionId:int}/preview",
- Handler: okapi.H(r.h.localization.Preview),
- Group: userGroup,
- Tags: []string{"Template Localizations"},
- Summary: "Preview localized template",
- Description: "Render a specific language version of a template with sample data",
- Request: &handlers.PreviewLocalizationRequest{},
- Response: &dto.Response[handlers.PreviewResult]{},
- Options: []okapi.RouteOption{
- okapi.DocPathParam("id", "integer", "Template ID"),
- okapi.DocPathParam("versionId", "integer", "Version ID"),
- okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
- },
- },
-
- // ==================== Languages ====================
- {
- Method: http.MethodPost,
- Path: "/languages",
- Handler: okapi.H(r.h.language.Create),
- Group: userGroup,
- Tags: []string{"Languages"},
- Summary: "Create language",
- Request: &handlers.CreateLanguageRequest{},
- Options: []okapi.RouteOption{
- okapi.DocResponse(201, &dto.Response[models.Language]{}),
- okapi.DocErrorResponse(409, &dto.ErrorResponseBody{}),
- },
- },
- {
- Method: http.MethodGet,
- Path: "/languages",
- Handler: okapi.H(r.h.language.List),
- Group: userGroup,
- Tags: []string{"Languages"},
- Summary: "List languages",
- Request: &handlers.ListRequest{},
- Response: &dto.PageableResponse[models.Language]{},
- },
- {
- Method: http.MethodPut,
- Path: "/languages/{id:int}",
- Handler: okapi.H(r.h.language.Update),
- Group: userGroup,
- Tags: []string{"Languages"},
- Summary: "Update language",
- Request: &handlers.UpdateLanguageRequest{},
- Response: &dto.Response[models.Language]{},
- Options: []okapi.RouteOption{
- okapi.DocPathParam("id", "integer", "Language ID"),
- okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
- },
- },
- {
- Method: http.MethodDelete,
- Path: "/languages/{id:int}",
- Handler: okapi.H(r.h.language.Delete),
- Group: userGroup,
- Tags: []string{"Languages"},
- Summary: "Delete language",
- Options: []okapi.RouteOption{
- okapi.DocPathParam("id", "integer", "Language ID"),
- okapi.DocResponse(204, nil),
- okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
- },
- },
-
- // ==================== Stylesheets ====================
- {
- Method: http.MethodPost,
- Path: "/stylesheets",
- Handler: okapi.H(r.h.stylesheet.Create),
- Group: userGroup,
- Tags: []string{"User"},
- Summary: "Create stylesheet",
- Request: &handlers.CreateStyleSheetRequest{},
- Options: []okapi.RouteOption{
- okapi.DocResponse(201, &dto.Response[models.StyleSheet]{}),
- okapi.DocErrorResponse(409, &dto.ErrorResponseBody{}),
- },
- },
- {
- Method: http.MethodGet,
- Path: "/stylesheets",
- Handler: okapi.H(r.h.stylesheet.List),
- Group: userGroup,
- Summary: "List stylesheets",
- Request: &handlers.ListRequest{},
- Response: &dto.PageableResponse[models.StyleSheet]{},
- },
- {
- Method: http.MethodPut,
- Path: "/stylesheets/{id:int}",
- Handler: okapi.H(r.h.stylesheet.Update),
- Group: userGroup,
- Summary: "Update stylesheet",
- Request: &handlers.UpdateStyleSheetRequest{},
- Response: &dto.Response[models.StyleSheet]{},
- Options: []okapi.RouteOption{
- okapi.DocPathParam("id", "integer", "StyleSheet ID"),
- okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
- },
- },
- {
- Method: http.MethodDelete,
- Path: "/stylesheets/{id:int}",
- Handler: okapi.H(r.h.stylesheet.Delete),
- Group: userGroup,
- Tags: []string{"User"},
- Summary: "Delete stylesheet",
- Options: []okapi.RouteOption{
- okapi.DocPathParam("id", "integer", "StyleSheet ID"),
- okapi.DocResponse(204, nil),
- okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
- },
- },
-
- // ==================== SMTP Servers ====================
- {
- Method: http.MethodPost,
- Path: "/smtp-servers",
- Handler: okapi.H(r.h.smtp.Create),
- Group: userGroup,
- Tags: []string{"User"},
- Summary: "Add SMTP server",
- Request: &handlers.CreateSMTPRequest{},
- Options: []okapi.RouteOption{
- okapi.DocResponse(201, &dto.Response[models.SMTPServer]{}),
- },
- },
- {
- Method: http.MethodGet,
- Path: "/smtp-servers",
- Handler: okapi.H(r.h.smtp.List),
- Group: userGroup,
- Summary: "List SMTP servers",
- Request: &handlers.ListRequest{},
- Response: &dto.PageableResponse[models.SMTPServer]{},
- },
- {
- Method: http.MethodGet,
- Path: "/smtp-servers/{id:int}",
- Handler: okapi.H(r.h.smtp.Get),
- Group: userGroup,
- Summary: "Get SMTP server",
- Request: &handlers.GetSMTPRequest{},
- Response: &dto.Response[models.SMTPServer]{},
- Options: []okapi.RouteOption{
- okapi.DocPathParam("id", "integer", "SMTP server ID"),
- okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
- },
- },
- {
- Method: http.MethodPut,
- Path: "/smtp-servers/{id:int}",
- Handler: okapi.H(r.h.smtp.Update),
- Group: userGroup,
- Summary: "Update SMTP server",
- Request: &handlers.UpdateSMTPRequest{},
- Response: &dto.Response[models.SMTPServer]{},
- Options: []okapi.RouteOption{
- okapi.DocPathParam("id", "integer", "SMTP server ID"),
- okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
- },
- },
- {
- Method: http.MethodDelete,
- Path: "/smtp-servers/{id:int}",
- Handler: okapi.H(r.h.smtp.Delete),
- Group: userGroup,
- Tags: []string{"User"},
- Summary: "Delete SMTP server",
- Options: []okapi.RouteOption{
- okapi.DocPathParam("id", "integer", "SMTP server ID"),
- okapi.DocResponse(204, nil),
- okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
- },
- },
- {
- Method: http.MethodPost,
- Path: "/smtp-servers/{id:int}/test",
- Handler: okapi.H(r.h.smtp.Test),
- Group: userGroup,
- Summary: "Test SMTP server connection",
- Response: &dto.Response[dto.MessageData]{},
- Options: []okapi.RouteOption{
- okapi.DocPathParam("id", "integer", "SMTP server ID"),
- okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
- },
- },
-
- // ==================== Webhooks ====================
- {
- Method: http.MethodPost,
- Path: "/webhooks",
- Handler: okapi.H(r.h.webhook.Create),
- Group: userGroup,
- Tags: []string{"User"},
- Summary: "Create webhook",
- Request: &handlers.CreateWebhookRequest{},
- Options: []okapi.RouteOption{
- okapi.DocResponse(201, &dto.Response[models.Webhook]{}),
- },
- },
- {
- Method: http.MethodGet,
- Path: "/webhooks",
- Handler: okapi.H(r.h.webhook.List),
- Group: userGroup,
- Summary: "List webhooks",
- Request: &handlers.ListRequest{},
- Response: &dto.PageableResponse[models.Webhook]{},
- },
- {
- Method: http.MethodDelete,
- Path: "/webhooks/{id:int}",
- Handler: okapi.H(r.h.webhook.Delete),
- Group: userGroup,
- Tags: []string{"User"},
- Summary: "Delete webhook",
- Options: []okapi.RouteOption{
- okapi.DocPathParam("id", "integer", "Webhook ID"),
- okapi.DocResponse(204, nil),
- okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
- },
- },
-
- // ==================== Webhook Deliveries ====================
- {
- Method: http.MethodGet,
- Path: "/webhook-deliveries",
- Handler: okapi.H(r.h.webhookDelivery.List),
- Group: userGroup,
- Summary: "List webhook deliveries",
- Request: &handlers.ListRequest{},
- Response: &dto.PageableResponse[models.WebhookDelivery]{},
- },
-
- // ==================== Domains ====================
- {
- Method: http.MethodPost,
- Path: "/domains",
- Handler: okapi.H(r.h.domain.Create),
- Group: userGroup,
- Summary: "Add domain",
- Description: "Register a domain for verification. Returns the DNS records that must be configured.",
- Request: &handlers.CreateDomainRequest{},
- Options: []okapi.RouteOption{
- okapi.DocResponse(201, &dto.Response[handlers.DomainWithRecords]{}),
- okapi.DocErrorResponse(409, &dto.ErrorResponseBody{}),
- },
- },
- {
- Method: http.MethodGet,
- Path: "/domains",
- Handler: okapi.H(r.h.domain.List),
- Group: userGroup,
- Summary: "List domains",
- Request: &handlers.ListRequest{},
- Response: &dto.PageableResponse[models.Domain]{},
- },
- {
- Method: http.MethodGet,
- Path: "/domains/{id:int}",
- Handler: okapi.H(r.h.domain.Get),
- Group: userGroup,
- Summary: "Get domain details",
- Response: &dto.Response[handlers.DomainWithRecords]{},
- Options: []okapi.RouteOption{
- okapi.DocPathParam("id", "integer", "Domain ID"),
- okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
- },
- },
- {
- Method: http.MethodDelete,
- Path: "/domains/{id:int}",
- Handler: okapi.H(r.h.domain.Delete),
- Group: userGroup,
- Tags: []string{"User"},
- Summary: "Delete domain",
- Options: []okapi.RouteOption{
- okapi.DocPathParam("id", "integer", "Domain ID"),
- okapi.DocResponse(204, nil),
- okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
- },
- },
- {
- Method: http.MethodPost,
- Path: "/domains/{id:int}/verify",
- Handler: okapi.H(r.h.domain.Verify),
- Group: userGroup,
- Summary: "Verify domain DNS records",
- Description: "Check DNS records (SPF, DKIM, DMARC) for the domain",
- Response: &dto.Response[any]{},
- Options: []okapi.RouteOption{
- okapi.DocPathParam("id", "integer", "Domain ID"),
- okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
- },
- },
-
- // ==================== Bounces ====================
- {
- Method: http.MethodPost,
- Path: "/bounces",
- Handler: okapi.H(r.h.bounce.Record),
- Group: userGroup,
- Summary: "Record a bounce",
- Description: "Record a bounce or complaint. Hard bounces and complaints auto-suppress the recipient.",
- Request: &handlers.RecordBounceRequest{},
- Options: []okapi.RouteOption{
- okapi.DocResponse(201, &dto.Response[models.Bounce]{}),
- },
- },
- {
- Method: http.MethodGet,
- Path: "/bounces",
- Handler: okapi.H(r.h.bounce.List),
- Group: userGroup,
- Summary: "List bounces",
- Request: &handlers.ListRequest{},
- Response: &dto.PageableResponse[models.Bounce]{},
- },
-
- // ==================== Suppressions ====================
- {
- Method: http.MethodPost,
- Path: "/suppressions",
- Handler: okapi.H(r.h.suppression.Create),
- Group: userGroup,
- Tags: []string{"User"},
- Summary: "Add to suppression list",
- Request: &handlers.CreateSuppressionRequest{},
- Options: []okapi.RouteOption{
- okapi.DocResponse(201, &dto.Response[models.Suppression]{}),
- okapi.DocErrorResponse(409, &dto.ErrorResponseBody{}),
- },
- },
- {
- Method: http.MethodGet,
- Path: "/suppressions",
- Handler: okapi.H(r.h.suppression.List),
- Group: userGroup,
- Summary: "List suppressed emails",
- Request: &handlers.ListSuppressionsRequest{},
- Response: &dto.PageableResponse[models.Suppression]{},
- },
- {
- Method: http.MethodDelete,
- Path: "/suppressions",
- Handler: okapi.H(r.h.suppression.Delete),
- Group: userGroup,
- Tags: []string{"User"},
- Summary: "Remove from suppression list",
- Request: &handlers.DeleteSuppressionRequest{},
- Options: []okapi.RouteOption{
- okapi.DocResponse(204, nil),
- },
- },
-
- // ==================== Unsubscribe Lists ====================
- {
- Method: http.MethodPost,
- Path: "/unsubscribe-lists",
- Handler: okapi.H(r.h.unsubscribeList.Create),
- Group: userGroup,
- Tags: []string{"Unsubscribe Lists"},
- Summary: "Create unsubscribe list",
- Request: &handlers.CreateUnsubscribeListRequest{},
- Options: []okapi.RouteOption{
- okapi.DocResponse(201, &dto.Response[models.UnsubscribeList]{}),
- okapi.DocErrorResponse(409, &dto.ErrorResponseBody{}),
- },
- },
- {
- Method: http.MethodGet,
- Path: "/unsubscribe-lists",
- Handler: okapi.H(r.h.unsubscribeList.List),
- Group: userGroup,
- Tags: []string{"Unsubscribe Lists"},
- Summary: "List unsubscribe lists",
- Request: &handlers.ListRequest{},
- Response: &dto.PageableResponse[models.UnsubscribeList]{},
- },
- {
- Method: http.MethodGet,
- Path: "/unsubscribe-lists/{id:int}",
- Handler: okapi.H(r.h.unsubscribeList.Get),
- Group: userGroup,
- Tags: []string{"Unsubscribe Lists"},
- Summary: "Get unsubscribe list",
- Response: &dto.Response[models.UnsubscribeList]{},
- Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "List ID")},
- },
- {
- Method: http.MethodPut,
- Path: "/unsubscribe-lists/{id:int}",
- Handler: okapi.H(r.h.unsubscribeList.Update),
- Group: userGroup,
- Tags: []string{"Unsubscribe Lists"},
- Summary: "Update unsubscribe list",
- Request: &handlers.UpdateUnsubscribeListRequest{},
- Response: &dto.Response[models.UnsubscribeList]{},
- Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "List ID")},
- },
- {
- Method: http.MethodDelete,
- Path: "/unsubscribe-lists/{id:int}",
- Handler: okapi.H(r.h.unsubscribeList.Delete),
- Group: userGroup,
- Tags: []string{"Unsubscribe Lists"},
- Summary: "Delete unsubscribe list",
- Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "List ID"), okapi.DocResponse(204, nil)},
- },
-
- // ==================== Audit Log ====================
{
Method: http.MethodGet,
Path: "/audit-log",
Handler: okapi.H(r.h.event.UserAuditLog),
Group: userGroup,
- Summary: "List audit log",
- Description: "Returns the authenticated user's audit trail",
+ Summary: "List user audit log",
+ Description: "Returns the authenticated user's security audit trail (login, password, 2FA). Workspace-operational audit lives at /workspaces/current/audit-log.",
Request: &handlers.ListEventsRequest{},
Response: &dto.PageableResponse[models.Event]{},
},
-
- // ==================== Contacts ====================
- {
- Method: http.MethodGet,
- Path: "/contacts",
- Handler: okapi.H(r.h.contact.List),
- Group: userGroup,
- Summary: "List contacts",
- Description: "List all recipient email addresses with sent/failed counts. Use the search query parameter to filter by email or name.",
- Request: &handlers.ListContactsRequest{},
- Response: &dto.PageableResponse[models.Contact]{},
- },
- {
- Method: http.MethodGet,
- Path: "/contacts/{id:int}",
- Handler: okapi.H(r.h.contact.Get),
- Group: userGroup,
- Summary: "Get contact details",
- Description: "Get a single contact by ID with suppression status",
- Request: &handlers.GetByIDRequest{},
- Response: &dto.Response[models.Contact]{},
- },
-
- // ==================== User Data Export/Import ====================
{
Method: http.MethodGet,
- Path: "/data/export",
- Handler: r.h.userData.Export,
- Group: userGroup,
- Summary: "Export all user data",
- Description: "Export all user data including templates, stylesheets, languages, contacts, contact lists, webhooks, suppressions, and settings as JSON",
- Response: &dto.Response[handlers.UserDataExport]{},
- },
- {
- Method: http.MethodPost,
- Path: "/data/import",
- Handler: okapi.H(r.h.userData.Import),
- Group: userGroup,
- Summary: "Import user data",
- Description: "Import user data from a previously exported JSON payload. Duplicates are skipped.",
- Request: &handlers.ImportUserDataRequest{},
- Response: &dto.Response[any]{},
- },
-
- // ==================== GDPR Data Management ====================
- {
- Method: http.MethodPost,
- Path: "/gdpr/delete-contacts",
- Handler: okapi.H(r.h.userData.DeleteContacts),
+ Path: "/settings",
+ Handler: r.h.userSetting.GetSettings,
Group: userGroup,
- Summary: "Delete contact data (GDPR)",
- Description: "Delete a specific contact by email or all contacts. Also removes the contact from suppression lists and contact list memberships.",
- Request: &handlers.GDPRDeleteContactsRequest{},
- Response: &dto.Response[handlers.GDPRDeleteResult]{},
+ Summary: "Get user settings",
+ Description: "Personal notification preferences. Operational settings live at /workspaces/current/settings.",
+ Response: &dto.Response[models.UserSetting]{},
},
{
- Method: http.MethodPost,
- Path: "/gdpr/delete-email-logs",
- Handler: okapi.H(r.h.userData.DeleteEmailLogs),
- Group: userGroup,
- Summary: "Delete email logs (GDPR)",
- Description: "Delete email logs and associated bounces. Specify older_than_days to only delete old logs, or 0 to delete all.",
- Request: &handlers.GDPRDeleteEmailLogsRequest{},
- Response: &dto.Response[handlers.GDPRDeleteResult]{},
- },
-
- // ==================== User Settings ====================
- {
- Method: http.MethodGet,
- Path: "/settings",
- Handler: r.h.userSetting.GetSettings,
- Group: userGroup,
- Summary: "Get user settings",
- Response: &dto.Response[models.UserSetting]{},
- },
- {
- Method: http.MethodPut,
- Path: "/settings",
- Handler: okapi.H(r.h.userSetting.UpdateSettings),
- Group: userGroup,
- Summary: "Update user settings",
- Request: &handlers.UpdateUserSettingsRequest{},
- Response: &dto.Response[models.UserSetting]{},
- },
-
- // ==================== Subscribers ====================
- {
- Method: http.MethodPost,
- Path: "/subscribers",
- Handler: okapi.H(r.h.subscriber.Create),
- Group: userGroup,
- Tags: []string{"Subscribers"},
- Summary: "Create subscriber",
- Request: &handlers.CreateSubscriberRequest{},
- Options: []okapi.RouteOption{okapi.DocResponse(201, &dto.Response[models.Subscriber]{})},
- },
- {
- Method: http.MethodGet,
- Path: "/subscribers",
- Handler: okapi.H(r.h.subscriber.List),
- Group: userGroup,
- Tags: []string{"Subscribers"},
- Summary: "List subscribers",
- Request: &handlers.ListSubscribersRequest{},
- Response: &dto.PageableResponse[models.Subscriber]{},
- },
- {
- Method: http.MethodGet,
- Path: "/subscribers/{id:int}",
- Handler: okapi.H(r.h.subscriber.Get),
- Group: userGroup,
- Tags: []string{"Subscribers"},
- Summary: "Get subscriber",
- Response: &dto.Response[models.Subscriber]{},
- Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "Subscriber ID")},
- },
- {
- Method: http.MethodPut,
- Path: "/subscribers/{id:int}",
- Handler: okapi.H(r.h.subscriber.Update),
- Group: userGroup,
- Tags: []string{"Subscribers"},
- Summary: "Update subscriber",
- Request: &handlers.UpdateSubscriberRequest{},
- Response: &dto.Response[models.Subscriber]{},
- Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "Subscriber ID")},
- },
- {
- Method: http.MethodDelete,
- Path: "/subscribers/{id:int}",
- Handler: okapi.H(r.h.subscriber.Delete),
- Group: userGroup,
- Tags: []string{"Subscribers"},
- Summary: "Delete subscriber",
- Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "Subscriber ID"), okapi.DocResponse(204, nil)},
- },
- {
- Method: http.MethodPost,
- Path: "/subscribers/import/json",
- Handler: okapi.H(r.h.subscriber.BulkImportJSON),
- Group: userGroup,
- Tags: []string{"Subscribers"},
- Summary: "Bulk import subscribers (JSON)",
- Request: &handlers.BulkImportSubscribersRequest{},
- Response: &dto.Response[handlers.BulkImportResult]{},
- },
- {
- Method: http.MethodPost,
- Path: "/subscribers/import/csv",
- Handler: r.h.subscriber.BulkImportCSV,
- Group: userGroup,
- Tags: []string{"Subscribers"},
- Summary: "Bulk import subscribers (CSV)",
- Description: "Upload a CSV file with optional column_mapping JSON field",
- Response: &dto.Response[handlers.BulkImportResult]{},
- },
-
- // ==================== Subscriber Lists ====================
- {
- Method: http.MethodPost,
- Path: "/subscriber-lists",
- Handler: okapi.H(r.h.subscriberList.Create),
- Group: userGroup,
- Tags: []string{"Subscriber Lists"},
- Summary: "Create subscriber list",
- Request: &handlers.CreateSubscriberListRequest{},
- Options: []okapi.RouteOption{okapi.DocResponse(201, &dto.Response[models.SubscriberList]{})},
- },
- {
- Method: http.MethodGet,
- Path: "/subscriber-lists",
- Handler: okapi.H(r.h.subscriberList.List),
- Group: userGroup,
- Tags: []string{"Subscriber Lists"},
- Summary: "List subscriber lists",
- Request: &handlers.ListRequest{},
- Response: &dto.PageableResponse[handlers.SubscriberListWithCount]{},
- },
- {
- Method: http.MethodGet,
- Path: "/subscriber-lists/{id:int}",
- Handler: okapi.H(r.h.subscriberList.Get),
- Group: userGroup,
- Tags: []string{"Subscriber Lists"},
- Summary: "Get subscriber list",
- Response: &dto.Response[handlers.SubscriberListWithCount]{},
- Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "List ID")},
- },
- {
- Method: http.MethodPut,
- Path: "/subscriber-lists/{id:int}",
- Handler: okapi.H(r.h.subscriberList.Update),
- Group: userGroup,
- Tags: []string{"Subscriber Lists"},
- Summary: "Update subscriber list",
- Request: &handlers.UpdateSubscriberListRequest{},
- Response: &dto.Response[models.SubscriberList]{},
- Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "List ID")},
- },
- {
- Method: http.MethodDelete,
- Path: "/subscriber-lists/{id:int}",
- Handler: okapi.H(r.h.subscriberList.Delete),
- Group: userGroup,
- Tags: []string{"Subscriber Lists"},
- Summary: "Delete subscriber list",
- Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "List ID"), okapi.DocResponse(204, nil)},
- },
- {
- Method: http.MethodPost,
- Path: "/subscriber-lists/{id:int}/members",
- Handler: okapi.H(r.h.subscriberList.AddMember),
- Group: userGroup,
- Tags: []string{"Subscriber Lists"},
- Summary: "Add subscriber to list",
- Request: &handlers.AddSubscriberToListRequest{},
- Response: &dto.Response[okapi.M]{},
- Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "List ID")},
- },
- {
- Method: http.MethodDelete,
- Path: "/subscriber-lists/{id:int}/members",
- Handler: okapi.H(r.h.subscriberList.RemoveMember),
- Group: userGroup,
- Tags: []string{"Subscriber Lists"},
- Summary: "Remove subscriber from list",
- Request: &handlers.RemoveSubscriberFromListRequest{},
- Response: &dto.Response[okapi.M]{},
- Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "List ID")},
- },
- {
- Method: http.MethodGet,
- Path: "/subscriber-lists/{id:int}/members",
- Handler: okapi.H(r.h.subscriberList.ListMembers),
- Group: userGroup,
- Tags: []string{"Subscriber Lists"},
- Summary: "List members of subscriber list",
- Request: &handlers.ListSubscriberListMembersRequest{},
- Response: &dto.PageableResponse[models.Subscriber]{},
- Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "List ID")},
- },
- {
- Method: http.MethodPost,
- Path: "/subscriber-lists/preview-segment",
- Handler: okapi.H(r.h.subscriberList.PreviewSegment),
- Group: userGroup,
- Tags: []string{"Subscriber Lists"},
- Summary: "Preview segment count",
- Description: "Evaluate filter rules and return the number of matching subscribers",
- Request: &handlers.PreviewSegmentRequest{},
- Response: &dto.Response[okapi.M]{},
- },
- {
- Method: http.MethodPost,
- Path: "/subscriber-lists/{id:int}/unsubscribe",
- Handler: okapi.H(r.h.subscriberList.UnsubscribeByEmail),
- Group: userGroup,
- Tags: []string{"Subscriber Lists"},
- Summary: "Unsubscribe an email from a list",
- Description: "API-key-accessible list opt-out. Idempotent. Does not change global subscriber status.",
- Request: &handlers.ListUnsubscribeByEmailRequest{},
- Response: &dto.Response[handlers.ListSubscribeResponse]{},
- Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "List ID")},
- },
- {
- Method: http.MethodPost,
- Path: "/subscriber-lists/{id:int}/resubscribe",
- Handler: okapi.H(r.h.subscriberList.ResubscribeByEmail),
+ Method: http.MethodPut,
+ Path: "/settings",
+ Handler: okapi.H(r.h.userSetting.UpdateSettings),
Group: userGroup,
- Tags: []string{"Subscriber Lists"},
- Summary: "Re-subscribe an email to a list",
- Description: "Reverses a list-scoped opt-out and re-adds to the list (static lists). Idempotent.",
- Request: &handlers.ListResubscribeByEmailRequest{},
- Response: &dto.Response[handlers.ListSubscribeResponse]{},
- Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "List ID")},
- },
-
- // ==================== Campaigns ====================
- {
- Method: http.MethodPost,
- Path: "/campaigns",
- Handler: okapi.H(r.h.campaign.Create),
- Group: userGroup,
- Tags: []string{"Campaigns"},
- Summary: "Create campaign",
- Request: &handlers.CreateCampaignRequest{},
- Options: []okapi.RouteOption{okapi.DocResponse(201, &dto.Response[models.Campaign]{})},
- },
- {
- Method: http.MethodGet,
- Path: "/campaigns",
- Handler: okapi.H(r.h.campaign.List),
- Group: userGroup,
- Tags: []string{"Campaigns"},
- Summary: "List campaigns",
- Request: &handlers.ListCampaignsRequest{},
- Response: &dto.PageableResponse[handlers.CampaignWithStats]{},
+ Summary: "Update user settings",
+ Description: "Personal notification preferences. Operational settings live at /workspaces/current/settings.",
+ Request: &handlers.UpdateUserSettingsRequest{},
+ Response: &dto.Response[models.UserSetting]{},
},
- {
- Method: http.MethodGet,
- Path: "/campaigns/{id:int}",
- Handler: okapi.H(r.h.campaign.Get),
- Group: userGroup,
- Tags: []string{"Campaigns"},
- Summary: "Get campaign",
- Response: &dto.Response[handlers.CampaignWithStats]{},
- Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "Campaign ID")},
- },
- {
- Method: http.MethodPut,
- Path: "/campaigns/{id:int}",
- Handler: okapi.H(r.h.campaign.Update),
- Group: userGroup,
- Tags: []string{"Campaigns"},
- Summary: "Update campaign",
- Request: &handlers.UpdateCampaignRequest{},
- Response: &dto.Response[models.Campaign]{},
- Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "Campaign ID")},
- },
- {
- Method: http.MethodDelete,
- Path: "/campaigns/{id:int}",
- Handler: okapi.H(r.h.campaign.Delete),
- Group: userGroup,
- Tags: []string{"Campaigns"},
- Summary: "Delete campaign",
- Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "Campaign ID"), okapi.DocResponse(204, nil)},
- },
- {
- Method: http.MethodPost,
- Path: "/campaigns/{id:int}/send",
- Handler: okapi.H(r.h.campaign.Send),
- Group: userGroup,
- Tags: []string{"Campaigns"},
- Summary: "Send campaign",
- Response: &dto.Response[models.Campaign]{},
- Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "Campaign ID")},
- },
- {
- Method: http.MethodPost,
- Path: "/campaigns/{id:int}/pause",
- Handler: okapi.H(r.h.campaign.Pause),
- Group: userGroup,
- Tags: []string{"Campaigns"},
- Summary: "Pause campaign",
- Response: &dto.Response[models.Campaign]{},
- Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "Campaign ID")},
- },
- {
- Method: http.MethodPost,
- Path: "/campaigns/{id:int}/resume",
- Handler: okapi.H(r.h.campaign.Resume),
- Group: userGroup,
- Tags: []string{"Campaigns"},
- Summary: "Resume campaign",
- Response: &dto.Response[models.Campaign]{},
- Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "Campaign ID")},
- },
- {
- Method: http.MethodPost,
- Path: "/campaigns/{id:int}/cancel",
- Handler: okapi.H(r.h.campaign.Cancel),
- Group: userGroup,
- Tags: []string{"Campaigns"},
- Summary: "Cancel campaign",
- Response: &dto.Response[models.Campaign]{},
- Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "Campaign ID")},
- },
- {
- Method: http.MethodPost,
- Path: "/campaigns/{id:int}/duplicate",
- Handler: okapi.H(r.h.campaign.Duplicate),
- Group: userGroup,
- Tags: []string{"Campaigns"},
- Summary: "Duplicate campaign",
- Response: &dto.Response[models.Campaign]{},
- Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "Campaign ID")},
- },
- {
- Method: http.MethodGet,
- Path: "/campaigns/{id:int}/messages",
- Handler: okapi.H(r.h.campaign.ListMessages),
- Group: userGroup,
- Tags: []string{"Campaigns"},
- Summary: "List campaign messages",
- Request: &handlers.ListCampaignMessagesRequest{},
- Response: &dto.PageableResponse[models.CampaignMessage]{},
- Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "Campaign ID")},
- },
- }
-
- // Append optional workspace header documentation to all user routes
- for i := range routes {
- routes[i].Options = append(routes[i].Options, workspaceHeaderOptional)
}
return routes
diff --git a/internal/routes/workspace_resource_routes.go b/internal/routes/workspace_resource_routes.go
new file mode 100644
index 0000000..60c034d
--- /dev/null
+++ b/internal/routes/workspace_resource_routes.go
@@ -0,0 +1,1143 @@
+/*
+ * Copyright 2026 Jonas Kaninda
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package routes
+
+import (
+ "net/http"
+
+ "github.com/goposta/posta/internal/dto"
+ "github.com/goposta/posta/internal/handlers"
+ "github.com/goposta/posta/internal/models"
+ "github.com/goposta/posta/internal/services/email"
+ "github.com/jkaninda/okapi"
+)
+
+func (r *Router) workspaceResourceRoutes() []okapi.RouteDefinition {
+ opsGroup := r.v1.Group("/workspaces/current", r.mw.jwtAuth.Middleware, r.mw.workspace).WithTagInfo(okapi.GroupTag{
+ Name: "Workspace resources",
+ Description: "Operational resources scoped to the active workspace: sending, templates, stylesheets, languages, API keys, contacts, subscribers, campaigns, domains, SMTP servers, webhooks, suppressions, and workspace analytics.",
+ })
+ opsGroup.WithBearerAuth()
+
+ routes := []okapi.RouteDefinition{
+ {
+ Method: http.MethodGet,
+ Path: "/dashboard/stats",
+ Handler: r.h.dashboard.Stats,
+ Group: opsGroup,
+ Summary: "Get dashboard statistics",
+ Description: "Returns email sending statistics for the authenticated user",
+ Response: &dto.Response[handlers.DashboardStats]{},
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/analytics",
+ Handler: okapi.H(r.h.analytics.UserAnalytics),
+ Group: opsGroup,
+ Summary: "Email analytics",
+ Description: "Returns daily email counts and status breakdown for the authenticated user",
+ Request: &handlers.AnalyticsRequest{},
+ Response: &dto.Response[handlers.AnalyticsResponse]{},
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/analytics/dashboard",
+ Handler: okapi.H(r.h.analytics.UserDashboardAnalytics),
+ Group: opsGroup,
+ Summary: "Dashboard analytics",
+ Description: "Returns delivery rate trends, bounce rate graphs, and latency percentiles",
+ Request: &handlers.DashboardAnalyticsRequest{},
+ Response: &dto.Response[handlers.DashboardAnalyticsResponse]{},
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/analytics/providers",
+ Handler: okapi.H(r.h.analytics.UserProviderBreakdown),
+ Group: opsGroup,
+ Summary: "Deliverability by provider",
+ Description: "Returns sent/failed counts and delivery rate grouped by recipient mailbox provider (Gmail, Outlook, Yahoo, ...)",
+ Request: &handlers.ProviderBreakdownRequest{},
+ Response: &dto.Response[handlers.ProviderBreakdownResponse]{},
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/emails",
+ Handler: okapi.H(r.h.email.List),
+ Group: opsGroup,
+ Summary: "List emails",
+ Description: "List sent emails with pagination",
+ Request: &handlers.ListRequest{},
+ Response: &dto.PageableResponse[models.Email]{},
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/emails/{id}",
+ Handler: okapi.H(r.h.email.Get),
+ Group: opsGroup,
+ Summary: "Get email details",
+ Response: &dto.Response[models.Email]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "string", "Email UUID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/emails/{id}/status",
+ Handler: okapi.H(r.h.email.GetStatus),
+ Group: opsGroup,
+ Summary: "Get email delivery status",
+ Description: "Returns a lightweight status view for polling email delivery progress. Only the email owner can access this.",
+ Response: &dto.Response[handlers.EmailStatusResponse]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "string", "Email UUID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/emails/{id}/retry",
+ Handler: okapi.H(r.h.email.Retry),
+ Group: opsGroup,
+ Summary: "Retry failed email",
+ Description: "Re-enqueue a failed email for another delivery attempt",
+ Response: &dto.Response[email.SendResponse]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "string", "Email UUID"),
+ okapi.DocErrorResponse(400, &dto.ErrorResponseBody{}),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/emails/preview",
+ Handler: okapi.H(r.h.email.Preview),
+ Group: opsGroup,
+ Summary: "Preview email from template",
+ Description: "Render a template with variables and return the HTML, text, and subject without sending.",
+ Request: &handlers.PreviewEmailRequest{},
+ Response: &dto.Response[handlers.PreviewEmailResponse]{},
+ Options: []okapi.RouteOption{
+ okapi.DocErrorResponse(400, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/api-keys",
+ Handler: okapi.H(r.h.apiKey.Create),
+ Group: opsGroup,
+ Middlewares: []okapi.Middleware{r.mw.verifiedEmail},
+ Summary: "Create API key",
+ Description: "Generate a new API key. The raw key is only shown once in the response.",
+ Request: &handlers.CreateAPIKeyRequest{},
+ Options: []okapi.RouteOption{
+ okapi.DocResponse(201, &dto.Response[dto.APIKeyCreatedData]{}),
+ okapi.DocErrorResponse(403, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/api-keys",
+ Handler: okapi.H(r.h.apiKey.List),
+ Group: opsGroup,
+ Summary: "List API keys",
+ Request: &handlers.ListRequest{},
+ Response: &dto.PageableResponse[models.APIKey]{},
+ },
+ {
+ Method: http.MethodPut,
+ Path: "/api-keys/{id:int}/revoke",
+ Handler: okapi.H(r.h.apiKey.Revoke),
+ Group: opsGroup,
+ Summary: "Revoke API key",
+ Response: &dto.Response[dto.MessageData]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "API key ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodDelete,
+ Path: "/api-keys/{id:int}",
+ Handler: okapi.H(r.h.apiKey.Delete),
+ Group: opsGroup,
+ Summary: "Delete API key",
+ Response: &dto.Response[dto.MessageData]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "API key ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/templates",
+ Handler: okapi.H(r.h.template.Create),
+ Group: opsGroup,
+ Tags: []string{"User"},
+ Summary: "Create template",
+ Request: &handlers.CreateTemplateRequest{},
+ Options: []okapi.RouteOption{
+ okapi.DocResponse(201, &dto.Response[models.Template]{}),
+ okapi.DocErrorResponse(409, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/templates",
+ Handler: okapi.H(r.h.template.List),
+ Group: opsGroup,
+ Summary: "List templates",
+ Request: &handlers.ListTemplatesRequest{},
+ Response: &dto.PageableResponse[models.Template]{},
+ },
+ {
+ Method: http.MethodPut,
+ Path: "/templates/{id:int}",
+ Handler: okapi.H(r.h.template.Update),
+ Group: opsGroup,
+ Summary: "Update template",
+ Request: &handlers.UpdateTemplateRequest{},
+ Response: &dto.Response[models.Template]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Template ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodDelete,
+ Path: "/templates/{id:int}",
+ Handler: okapi.H(r.h.template.Delete),
+ Group: opsGroup,
+ Tags: []string{"User"},
+ Summary: "Delete template",
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Template ID"),
+ okapi.DocResponse(204, nil),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/templates/preview",
+ Handler: okapi.H(r.h.template.Preview),
+ Group: opsGroup,
+ Summary: "Preview template",
+ Description: "Render a template with sample data and return the result",
+ Request: &handlers.PreviewTemplateRequest{},
+ Response: &dto.Response[handlers.PreviewResult]{},
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/templates/{id:int}/send-test",
+ Handler: okapi.H(r.h.template.SendTest),
+ Group: opsGroup,
+ Summary: "Send test email",
+ Description: "Send a test email using a template with sample data",
+ Request: &handlers.SendTestRequest{},
+ Response: &dto.Response[email.SendResponse]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Template ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/templates/{id:int}/export",
+ Handler: okapi.H(r.h.template.Export),
+ Group: opsGroup,
+ Summary: "Export template",
+ Description: "Export a template with all versions and localizations as JSON",
+ Response: &dto.Response[handlers.TemplateExport]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Template ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/templates/import",
+ Handler: okapi.H(r.h.template.Import),
+ Group: opsGroup,
+ Summary: "Import template",
+ Description: "Import a template from a previously exported JSON payload",
+ Request: &handlers.ImportTemplateRequest{},
+ Options: []okapi.RouteOption{
+ okapi.DocResponse(201, &dto.Response[models.Template]{}),
+ okapi.DocErrorResponse(409, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/templates/import-html",
+ Handler: r.h.template.ImportHTML,
+ Group: opsGroup,
+ Tags: []string{"Templates"},
+ Summary: "Import HTML template",
+ Description: "Upload an .html file to create a template. CSS from <style> blocks is extracted into a separate stylesheet.",
+ Options: []okapi.RouteOption{
+ okapi.DocResponse(201, &dto.Response[models.Template]{}),
+ okapi.DocErrorResponse(409, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/templates/{id:int}/versions",
+ Handler: okapi.H(r.h.version.List),
+ Group: opsGroup,
+ Tags: []string{"Template Versions"},
+ Summary: "List template versions",
+ Response: &dto.Response[[]models.TemplateVersion]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Template ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/templates/{id:int}/versions",
+ Handler: okapi.H(r.h.version.Create),
+ Group: opsGroup,
+ Tags: []string{"Template Versions"},
+ Summary: "Create template version",
+ Request: &handlers.CreateVersionRequest{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Template ID"),
+ okapi.DocResponse(201, &dto.Response[models.TemplateVersion]{}),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodPut,
+ Path: "/templates/{id:int}/versions/{versionId:int}",
+ Handler: okapi.H(r.h.version.Update),
+ Group: opsGroup,
+ Tags: []string{"Template Versions"},
+ Summary: "Update template version",
+ Request: &handlers.UpdateVersionRequest{},
+ Response: &dto.Response[models.TemplateVersion]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Template ID"),
+ okapi.DocPathParam("versionId", "integer", "Version ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/templates/{id:int}/activate/{versionId:int}",
+ Handler: okapi.H(r.h.version.Activate),
+ Group: opsGroup,
+ Tags: []string{"Template Versions"},
+ Summary: "Activate template version",
+ Response: &dto.Response[models.Template]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Template ID"),
+ okapi.DocPathParam("versionId", "integer", "Version ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodDelete,
+ Path: "/templates/{id:int}/versions/{versionId:int}",
+ Handler: okapi.H(r.h.version.Delete),
+ Group: opsGroup,
+ Tags: []string{"Template Versions"},
+ Summary: "Delete template version",
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Template ID"),
+ okapi.DocPathParam("versionId", "integer", "Version ID"),
+ okapi.DocResponse(204, nil),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/templates/{id:int}/versions/{versionId:int}/localizations",
+ Handler: okapi.H(r.h.localization.List),
+ Group: opsGroup,
+ Tags: []string{"Template Localizations"},
+ Summary: "List localizations for a version",
+ Response: &dto.Response[[]models.TemplateLocalization]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Template ID"),
+ okapi.DocPathParam("versionId", "integer", "Version ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/templates/{id:int}/versions/{versionId:int}/localizations",
+ Handler: okapi.H(r.h.localization.Create),
+ Group: opsGroup,
+ Tags: []string{"Template Localizations"},
+ Summary: "Create localization",
+ Request: &handlers.CreateLocalizationRequest{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Template ID"),
+ okapi.DocPathParam("versionId", "integer", "Version ID"),
+ okapi.DocResponse(201, &dto.Response[models.TemplateLocalization]{}),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ okapi.DocErrorResponse(409, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodPut,
+ Path: "/localizations/{localizationId:int}",
+ Handler: okapi.H(r.h.localization.Update),
+ Group: opsGroup,
+ Tags: []string{"Template Localizations"},
+ Summary: "Update localization",
+ Request: &handlers.UpdateLocalizationRequest{},
+ Response: &dto.Response[models.TemplateLocalization]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("localizationId", "integer", "Localization ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodDelete,
+ Path: "/localizations/{localizationId:int}",
+ Handler: okapi.H(r.h.localization.Delete),
+ Group: opsGroup,
+ Tags: []string{"Template Localizations"},
+ Summary: "Delete localization",
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("localizationId", "integer", "Localization ID"),
+ okapi.DocResponse(204, nil),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/templates/{id:int}/versions/{versionId:int}/preview",
+ Handler: okapi.H(r.h.localization.Preview),
+ Group: opsGroup,
+ Tags: []string{"Template Localizations"},
+ Summary: "Preview localized template",
+ Description: "Render a specific language version of a template with sample data",
+ Request: &handlers.PreviewLocalizationRequest{},
+ Response: &dto.Response[handlers.PreviewResult]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Template ID"),
+ okapi.DocPathParam("versionId", "integer", "Version ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/languages",
+ Handler: okapi.H(r.h.language.Create),
+ Group: opsGroup,
+ Tags: []string{"Languages"},
+ Summary: "Create language",
+ Request: &handlers.CreateLanguageRequest{},
+ Options: []okapi.RouteOption{
+ okapi.DocResponse(201, &dto.Response[models.Language]{}),
+ okapi.DocErrorResponse(409, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/languages",
+ Handler: okapi.H(r.h.language.List),
+ Group: opsGroup,
+ Tags: []string{"Languages"},
+ Summary: "List languages",
+ Request: &handlers.ListRequest{},
+ Response: &dto.PageableResponse[models.Language]{},
+ },
+ {
+ Method: http.MethodPut,
+ Path: "/languages/{id:int}",
+ Handler: okapi.H(r.h.language.Update),
+ Group: opsGroup,
+ Tags: []string{"Languages"},
+ Summary: "Update language",
+ Request: &handlers.UpdateLanguageRequest{},
+ Response: &dto.Response[models.Language]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Language ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodDelete,
+ Path: "/languages/{id:int}",
+ Handler: okapi.H(r.h.language.Delete),
+ Group: opsGroup,
+ Tags: []string{"Languages"},
+ Summary: "Delete language",
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Language ID"),
+ okapi.DocResponse(204, nil),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/stylesheets",
+ Handler: okapi.H(r.h.stylesheet.Create),
+ Group: opsGroup,
+ Tags: []string{"User"},
+ Summary: "Create stylesheet",
+ Request: &handlers.CreateStyleSheetRequest{},
+ Options: []okapi.RouteOption{
+ okapi.DocResponse(201, &dto.Response[models.StyleSheet]{}),
+ okapi.DocErrorResponse(409, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/stylesheets",
+ Handler: okapi.H(r.h.stylesheet.List),
+ Group: opsGroup,
+ Summary: "List stylesheets",
+ Request: &handlers.ListRequest{},
+ Response: &dto.PageableResponse[models.StyleSheet]{},
+ },
+ {
+ Method: http.MethodPut,
+ Path: "/stylesheets/{id:int}",
+ Handler: okapi.H(r.h.stylesheet.Update),
+ Group: opsGroup,
+ Summary: "Update stylesheet",
+ Request: &handlers.UpdateStyleSheetRequest{},
+ Response: &dto.Response[models.StyleSheet]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "StyleSheet ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodDelete,
+ Path: "/stylesheets/{id:int}",
+ Handler: okapi.H(r.h.stylesheet.Delete),
+ Group: opsGroup,
+ Tags: []string{"User"},
+ Summary: "Delete stylesheet",
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "StyleSheet ID"),
+ okapi.DocResponse(204, nil),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/smtp-servers",
+ Handler: okapi.H(r.h.smtp.Create),
+ Group: opsGroup,
+ Tags: []string{"User"},
+ Summary: "Add SMTP server",
+ Request: &handlers.CreateSMTPRequest{},
+ Options: []okapi.RouteOption{
+ okapi.DocResponse(201, &dto.Response[models.SMTPServer]{}),
+ },
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/smtp-servers",
+ Handler: okapi.H(r.h.smtp.List),
+ Group: opsGroup,
+ Summary: "List SMTP servers",
+ Request: &handlers.ListRequest{},
+ Response: &dto.PageableResponse[models.SMTPServer]{},
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/smtp-servers/{id:int}",
+ Handler: okapi.H(r.h.smtp.Get),
+ Group: opsGroup,
+ Summary: "Get SMTP server",
+ Request: &handlers.GetSMTPRequest{},
+ Response: &dto.Response[models.SMTPServer]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "SMTP server ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodPut,
+ Path: "/smtp-servers/{id:int}",
+ Handler: okapi.H(r.h.smtp.Update),
+ Group: opsGroup,
+ Summary: "Update SMTP server",
+ Request: &handlers.UpdateSMTPRequest{},
+ Response: &dto.Response[models.SMTPServer]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "SMTP server ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodDelete,
+ Path: "/smtp-servers/{id:int}",
+ Handler: okapi.H(r.h.smtp.Delete),
+ Group: opsGroup,
+ Tags: []string{"User"},
+ Summary: "Delete SMTP server",
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "SMTP server ID"),
+ okapi.DocResponse(204, nil),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/smtp-servers/{id:int}/test",
+ Handler: okapi.H(r.h.smtp.Test),
+ Group: opsGroup,
+ Summary: "Test SMTP server connection",
+ Response: &dto.Response[dto.MessageData]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "SMTP server ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/webhooks",
+ Handler: okapi.H(r.h.webhook.Create),
+ Group: opsGroup,
+ Tags: []string{"User"},
+ Summary: "Create webhook",
+ Request: &handlers.CreateWebhookRequest{},
+ Options: []okapi.RouteOption{
+ okapi.DocResponse(201, &dto.Response[models.Webhook]{}),
+ },
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/webhooks",
+ Handler: okapi.H(r.h.webhook.List),
+ Group: opsGroup,
+ Summary: "List webhooks",
+ Request: &handlers.ListRequest{},
+ Response: &dto.PageableResponse[models.Webhook]{},
+ },
+ {
+ Method: http.MethodDelete,
+ Path: "/webhooks/{id:int}",
+ Handler: okapi.H(r.h.webhook.Delete),
+ Group: opsGroup,
+ Tags: []string{"User"},
+ Summary: "Delete webhook",
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Webhook ID"),
+ okapi.DocResponse(204, nil),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/webhook-deliveries",
+ Handler: okapi.H(r.h.webhookDelivery.List),
+ Group: opsGroup,
+ Summary: "List webhook deliveries",
+ Request: &handlers.ListRequest{},
+ Response: &dto.PageableResponse[models.WebhookDelivery]{},
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/domains",
+ Handler: okapi.H(r.h.domain.Create),
+ Group: opsGroup,
+ Summary: "Add domain",
+ Description: "Register a domain for verification. Returns the DNS records that must be configured.",
+ Request: &handlers.CreateDomainRequest{},
+ Options: []okapi.RouteOption{
+ okapi.DocResponse(201, &dto.Response[handlers.DomainWithRecords]{}),
+ okapi.DocErrorResponse(409, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/domains",
+ Handler: okapi.H(r.h.domain.List),
+ Group: opsGroup,
+ Summary: "List domains",
+ Request: &handlers.ListRequest{},
+ Response: &dto.PageableResponse[models.Domain]{},
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/domains/{id:int}",
+ Handler: okapi.H(r.h.domain.Get),
+ Group: opsGroup,
+ Summary: "Get domain details",
+ Response: &dto.Response[handlers.DomainWithRecords]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Domain ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodDelete,
+ Path: "/domains/{id:int}",
+ Handler: okapi.H(r.h.domain.Delete),
+ Group: opsGroup,
+ Tags: []string{"User"},
+ Summary: "Delete domain",
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Domain ID"),
+ okapi.DocResponse(204, nil),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/domains/{id:int}/verify",
+ Handler: okapi.H(r.h.domain.Verify),
+ Group: opsGroup,
+ Summary: "Verify domain DNS records",
+ Description: "Check DNS records (SPF, DKIM, DMARC) for the domain",
+ Response: &dto.Response[any]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Domain ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/bounces",
+ Handler: okapi.H(r.h.bounce.Record),
+ Group: opsGroup,
+ Summary: "Record a bounce",
+ Description: "Record a bounce or complaint. Hard bounces and complaints auto-suppress the recipient.",
+ Request: &handlers.RecordBounceRequest{},
+ Options: []okapi.RouteOption{
+ okapi.DocResponse(201, &dto.Response[models.Bounce]{}),
+ },
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/bounces",
+ Handler: okapi.H(r.h.bounce.List),
+ Group: opsGroup,
+ Summary: "List bounces",
+ Request: &handlers.ListRequest{},
+ Response: &dto.PageableResponse[models.Bounce]{},
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/suppressions",
+ Handler: okapi.H(r.h.suppression.Create),
+ Group: opsGroup,
+ Tags: []string{"User"},
+ Summary: "Add to suppression list",
+ Request: &handlers.CreateSuppressionRequest{},
+ Options: []okapi.RouteOption{
+ okapi.DocResponse(201, &dto.Response[models.Suppression]{}),
+ okapi.DocErrorResponse(409, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/suppressions",
+ Handler: okapi.H(r.h.suppression.List),
+ Group: opsGroup,
+ Summary: "List suppressed emails",
+ Request: &handlers.ListSuppressionsRequest{},
+ Response: &dto.PageableResponse[models.Suppression]{},
+ },
+ {
+ Method: http.MethodDelete,
+ Path: "/suppressions",
+ Handler: okapi.H(r.h.suppression.Delete),
+ Group: opsGroup,
+ Tags: []string{"User"},
+ Summary: "Remove from suppression list",
+ Request: &handlers.DeleteSuppressionRequest{},
+ Options: []okapi.RouteOption{
+ okapi.DocResponse(204, nil),
+ },
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/unsubscribe-lists",
+ Handler: okapi.H(r.h.unsubscribeList.Create),
+ Group: opsGroup,
+ Tags: []string{"Unsubscribe Lists"},
+ Summary: "Create unsubscribe list",
+ Request: &handlers.CreateUnsubscribeListRequest{},
+ Options: []okapi.RouteOption{
+ okapi.DocResponse(201, &dto.Response[models.UnsubscribeList]{}),
+ okapi.DocErrorResponse(409, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/unsubscribe-lists",
+ Handler: okapi.H(r.h.unsubscribeList.List),
+ Group: opsGroup,
+ Tags: []string{"Unsubscribe Lists"},
+ Summary: "List unsubscribe lists",
+ Request: &handlers.ListRequest{},
+ Response: &dto.PageableResponse[models.UnsubscribeList]{},
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/unsubscribe-lists/{id:int}",
+ Handler: okapi.H(r.h.unsubscribeList.Get),
+ Group: opsGroup,
+ Tags: []string{"Unsubscribe Lists"},
+ Summary: "Get unsubscribe list",
+ Response: &dto.Response[models.UnsubscribeList]{},
+ Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "List ID")},
+ },
+ {
+ Method: http.MethodPut,
+ Path: "/unsubscribe-lists/{id:int}",
+ Handler: okapi.H(r.h.unsubscribeList.Update),
+ Group: opsGroup,
+ Tags: []string{"Unsubscribe Lists"},
+ Summary: "Update unsubscribe list",
+ Request: &handlers.UpdateUnsubscribeListRequest{},
+ Response: &dto.Response[models.UnsubscribeList]{},
+ Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "List ID")},
+ },
+ {
+ Method: http.MethodDelete,
+ Path: "/unsubscribe-lists/{id:int}",
+ Handler: okapi.H(r.h.unsubscribeList.Delete),
+ Group: opsGroup,
+ Tags: []string{"Unsubscribe Lists"},
+ Summary: "Delete unsubscribe list",
+ Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "List ID"), okapi.DocResponse(204, nil)},
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/contacts",
+ Handler: okapi.H(r.h.contact.List),
+ Group: opsGroup,
+ Summary: "List contacts",
+ Description: "List all recipient email addresses with sent/failed counts. Use the search query parameter to filter by email or name.",
+ Request: &handlers.ListContactsRequest{},
+ Response: &dto.PageableResponse[models.Contact]{},
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/contacts/{id:int}",
+ Handler: okapi.H(r.h.contact.Get),
+ Group: opsGroup,
+ Summary: "Get contact details",
+ Description: "Get a single contact by ID with suppression status",
+ Request: &handlers.GetByIDRequest{},
+ Response: &dto.Response[models.Contact]{},
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/subscribers",
+ Handler: okapi.H(r.h.subscriber.Create),
+ Group: opsGroup,
+ Tags: []string{"Subscribers"},
+ Summary: "Create subscriber",
+ Request: &handlers.CreateSubscriberRequest{},
+ Options: []okapi.RouteOption{okapi.DocResponse(201, &dto.Response[models.Subscriber]{})},
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/subscribers",
+ Handler: okapi.H(r.h.subscriber.List),
+ Group: opsGroup,
+ Tags: []string{"Subscribers"},
+ Summary: "List subscribers",
+ Request: &handlers.ListSubscribersRequest{},
+ Response: &dto.PageableResponse[models.Subscriber]{},
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/subscribers/{id:int}",
+ Handler: okapi.H(r.h.subscriber.Get),
+ Group: opsGroup,
+ Tags: []string{"Subscribers"},
+ Summary: "Get subscriber",
+ Response: &dto.Response[models.Subscriber]{},
+ Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "Subscriber ID")},
+ },
+ {
+ Method: http.MethodPut,
+ Path: "/subscribers/{id:int}",
+ Handler: okapi.H(r.h.subscriber.Update),
+ Group: opsGroup,
+ Tags: []string{"Subscribers"},
+ Summary: "Update subscriber",
+ Request: &handlers.UpdateSubscriberRequest{},
+ Response: &dto.Response[models.Subscriber]{},
+ Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "Subscriber ID")},
+ },
+ {
+ Method: http.MethodDelete,
+ Path: "/subscribers/{id:int}",
+ Handler: okapi.H(r.h.subscriber.Delete),
+ Group: opsGroup,
+ Tags: []string{"Subscribers"},
+ Summary: "Delete subscriber",
+ Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "Subscriber ID"), okapi.DocResponse(204, nil)},
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/subscribers/import/json",
+ Handler: okapi.H(r.h.subscriber.BulkImportJSON),
+ Group: opsGroup,
+ Tags: []string{"Subscribers"},
+ Summary: "Bulk import subscribers (JSON)",
+ Request: &handlers.BulkImportSubscribersRequest{},
+ Response: &dto.Response[handlers.BulkImportResult]{},
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/subscribers/import/csv",
+ Handler: r.h.subscriber.BulkImportCSV,
+ Group: opsGroup,
+ Tags: []string{"Subscribers"},
+ Summary: "Bulk import subscribers (CSV)",
+ Description: "Upload a CSV file with optional column_mapping JSON field",
+ Response: &dto.Response[handlers.BulkImportResult]{},
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/subscriber-lists",
+ Handler: okapi.H(r.h.subscriberList.Create),
+ Group: opsGroup,
+ Tags: []string{"Subscriber Lists"},
+ Summary: "Create subscriber list",
+ Request: &handlers.CreateSubscriberListRequest{},
+ Options: []okapi.RouteOption{okapi.DocResponse(201, &dto.Response[models.SubscriberList]{})},
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/subscriber-lists",
+ Handler: okapi.H(r.h.subscriberList.List),
+ Group: opsGroup,
+ Tags: []string{"Subscriber Lists"},
+ Summary: "List subscriber lists",
+ Request: &handlers.ListRequest{},
+ Response: &dto.PageableResponse[handlers.SubscriberListWithCount]{},
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/subscriber-lists/{id:int}",
+ Handler: okapi.H(r.h.subscriberList.Get),
+ Group: opsGroup,
+ Tags: []string{"Subscriber Lists"},
+ Summary: "Get subscriber list",
+ Response: &dto.Response[handlers.SubscriberListWithCount]{},
+ Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "List ID")},
+ },
+ {
+ Method: http.MethodPut,
+ Path: "/subscriber-lists/{id:int}",
+ Handler: okapi.H(r.h.subscriberList.Update),
+ Group: opsGroup,
+ Tags: []string{"Subscriber Lists"},
+ Summary: "Update subscriber list",
+ Request: &handlers.UpdateSubscriberListRequest{},
+ Response: &dto.Response[models.SubscriberList]{},
+ Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "List ID")},
+ },
+ {
+ Method: http.MethodDelete,
+ Path: "/subscriber-lists/{id:int}",
+ Handler: okapi.H(r.h.subscriberList.Delete),
+ Group: opsGroup,
+ Tags: []string{"Subscriber Lists"},
+ Summary: "Delete subscriber list",
+ Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "List ID"), okapi.DocResponse(204, nil)},
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/subscriber-lists/{id:int}/members",
+ Handler: okapi.H(r.h.subscriberList.AddMember),
+ Group: opsGroup,
+ Tags: []string{"Subscriber Lists"},
+ Summary: "Add subscriber to list",
+ Request: &handlers.AddSubscriberToListRequest{},
+ Response: &dto.Response[okapi.M]{},
+ Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "List ID")},
+ },
+ {
+ Method: http.MethodDelete,
+ Path: "/subscriber-lists/{id:int}/members",
+ Handler: okapi.H(r.h.subscriberList.RemoveMember),
+ Group: opsGroup,
+ Tags: []string{"Subscriber Lists"},
+ Summary: "Remove subscriber from list",
+ Request: &handlers.RemoveSubscriberFromListRequest{},
+ Response: &dto.Response[okapi.M]{},
+ Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "List ID")},
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/subscriber-lists/{id:int}/members",
+ Handler: okapi.H(r.h.subscriberList.ListMembers),
+ Group: opsGroup,
+ Tags: []string{"Subscriber Lists"},
+ Summary: "List members of subscriber list",
+ Request: &handlers.ListSubscriberListMembersRequest{},
+ Response: &dto.PageableResponse[models.Subscriber]{},
+ Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "List ID")},
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/subscriber-lists/preview-segment",
+ Handler: okapi.H(r.h.subscriberList.PreviewSegment),
+ Group: opsGroup,
+ Tags: []string{"Subscriber Lists"},
+ Summary: "Preview segment count",
+ Description: "Evaluate filter rules and return the number of matching subscribers",
+ Request: &handlers.PreviewSegmentRequest{},
+ Response: &dto.Response[okapi.M]{},
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/subscriber-lists/{id:int}/unsubscribe",
+ Handler: okapi.H(r.h.subscriberList.UnsubscribeByEmail),
+ Group: opsGroup,
+ Tags: []string{"Subscriber Lists"},
+ Summary: "Unsubscribe an email from a list",
+ Description: "API-key-accessible list opt-out. Idempotent. Does not change global subscriber status.",
+ Request: &handlers.ListUnsubscribeByEmailRequest{},
+ Response: &dto.Response[handlers.ListSubscribeResponse]{},
+ Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "List ID")},
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/subscriber-lists/{id:int}/resubscribe",
+ Handler: okapi.H(r.h.subscriberList.ResubscribeByEmail),
+ Group: opsGroup,
+ Tags: []string{"Subscriber Lists"},
+ Summary: "Re-subscribe an email to a list",
+ Description: "Reverses a list-scoped opt-out and re-adds to the list (static lists). Idempotent.",
+ Request: &handlers.ListResubscribeByEmailRequest{},
+ Response: &dto.Response[handlers.ListSubscribeResponse]{},
+ Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "List ID")},
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/campaigns",
+ Handler: okapi.H(r.h.campaign.Create),
+ Group: opsGroup,
+ Tags: []string{"Campaigns"},
+ Summary: "Create campaign",
+ Request: &handlers.CreateCampaignRequest{},
+ Options: []okapi.RouteOption{okapi.DocResponse(201, &dto.Response[models.Campaign]{})},
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/campaigns",
+ Handler: okapi.H(r.h.campaign.List),
+ Group: opsGroup,
+ Tags: []string{"Campaigns"},
+ Summary: "List campaigns",
+ Request: &handlers.ListCampaignsRequest{},
+ Response: &dto.PageableResponse[handlers.CampaignWithStats]{},
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/campaigns/{id:int}",
+ Handler: okapi.H(r.h.campaign.Get),
+ Group: opsGroup,
+ Tags: []string{"Campaigns"},
+ Summary: "Get campaign",
+ Response: &dto.Response[handlers.CampaignWithStats]{},
+ Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "Campaign ID")},
+ },
+ {
+ Method: http.MethodPut,
+ Path: "/campaigns/{id:int}",
+ Handler: okapi.H(r.h.campaign.Update),
+ Group: opsGroup,
+ Tags: []string{"Campaigns"},
+ Summary: "Update campaign",
+ Request: &handlers.UpdateCampaignRequest{},
+ Response: &dto.Response[models.Campaign]{},
+ Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "Campaign ID")},
+ },
+ {
+ Method: http.MethodDelete,
+ Path: "/campaigns/{id:int}",
+ Handler: okapi.H(r.h.campaign.Delete),
+ Group: opsGroup,
+ Tags: []string{"Campaigns"},
+ Summary: "Delete campaign",
+ Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "Campaign ID"), okapi.DocResponse(204, nil)},
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/campaigns/{id:int}/send",
+ Handler: okapi.H(r.h.campaign.Send),
+ Group: opsGroup,
+ Tags: []string{"Campaigns"},
+ Summary: "Send campaign",
+ Response: &dto.Response[models.Campaign]{},
+ Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "Campaign ID")},
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/campaigns/{id:int}/pause",
+ Handler: okapi.H(r.h.campaign.Pause),
+ Group: opsGroup,
+ Tags: []string{"Campaigns"},
+ Summary: "Pause campaign",
+ Response: &dto.Response[models.Campaign]{},
+ Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "Campaign ID")},
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/campaigns/{id:int}/resume",
+ Handler: okapi.H(r.h.campaign.Resume),
+ Group: opsGroup,
+ Tags: []string{"Campaigns"},
+ Summary: "Resume campaign",
+ Response: &dto.Response[models.Campaign]{},
+ Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "Campaign ID")},
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/campaigns/{id:int}/cancel",
+ Handler: okapi.H(r.h.campaign.Cancel),
+ Group: opsGroup,
+ Tags: []string{"Campaigns"},
+ Summary: "Cancel campaign",
+ Response: &dto.Response[models.Campaign]{},
+ Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "Campaign ID")},
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/campaigns/{id:int}/duplicate",
+ Handler: okapi.H(r.h.campaign.Duplicate),
+ Group: opsGroup,
+ Tags: []string{"Campaigns"},
+ Summary: "Duplicate campaign",
+ Response: &dto.Response[models.Campaign]{},
+ Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "Campaign ID")},
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/campaigns/{id:int}/messages",
+ Handler: okapi.H(r.h.campaign.ListMessages),
+ Group: opsGroup,
+ Tags: []string{"Campaigns"},
+ Summary: "List campaign messages",
+ Request: &handlers.ListCampaignMessagesRequest{},
+ Response: &dto.PageableResponse[models.CampaignMessage]{},
+ Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "Campaign ID")},
+ },
+ }
+
+ return routes
+}
diff --git a/internal/routes/workspace_routes.go b/internal/routes/workspace_routes.go
index 53c3370..cbd0cf9 100644
--- a/internal/routes/workspace_routes.go
+++ b/internal/routes/workspace_routes.go
@@ -22,6 +22,7 @@ import (
"github.com/goposta/posta/internal/dto"
"github.com/goposta/posta/internal/handlers"
+ "github.com/goposta/posta/internal/middlewares"
"github.com/goposta/posta/internal/models"
"github.com/jkaninda/okapi"
)
@@ -191,16 +192,41 @@ func (r *Router) workspaceRoutes() []okapi.RouteDefinition {
Options: []okapi.RouteOption{workspaceHeaderRequired},
},
- // Data Transfer
+ // Operational settings
{
- Method: http.MethodPost,
- Path: "/transfer",
- Handler: okapi.H(r.h.workspace.TransferData),
+ Method: http.MethodGet,
+ Path: "/settings",
+ Handler: r.h.workspaceSetting.GetSettings,
+ Group: wsGroup,
+ Summary: "Get workspace settings",
+ Description: "Get the operational settings for the current workspace (any member)",
+ Response: &dto.Response[models.WorkspaceSetting]{},
+ Options: []okapi.RouteOption{workspaceHeaderRequired},
+ },
+ {
+ Method: http.MethodPut,
+ Path: "/settings",
+ Handler: okapi.H(r.h.workspaceSetting.UpdateSettings),
+ Group: wsGroup,
+ Middlewares: []okapi.Middleware{middlewares.RequireWorkspaceRole(models.WorkspaceRoleAdmin)},
+ Summary: "Update workspace settings",
+ Description: "Update the operational settings for the current workspace (admin/owner only)",
+ Request: &handlers.UpdateWorkspaceSettingsRequest{},
+ Response: &dto.Response[models.WorkspaceSetting]{},
+ Options: []okapi.RouteOption{workspaceHeaderRequired},
+ },
+
+ // Audit log (workspace-scoped): events WHERE workspace_id = ? AND category = 'audit'.
+ {
+ Method: http.MethodGet,
+ Path: "/audit-log",
+ Handler: okapi.H(r.h.event.WorkspaceAuditLog),
Group: wsGroup,
- Summary: "Transfer personal data to workspace",
- Description: "Move the current user's personal resources into this workspace",
- Request: &handlers.TransferDataRequest{},
- Response: &dto.Response[handlers.TransferResponse]{},
+ Middlewares: []okapi.Middleware{middlewares.RequireWorkspaceRole(models.WorkspaceRoleAdmin)},
+ Summary: "List workspace audit log",
+ Description: "Returns the audit trail for the current workspace (admin/owner only)",
+ Request: &handlers.ListEventsRequest{},
+ Response: &dto.PageableResponse[models.Event]{},
Options: []okapi.RouteOption{workspaceHeaderRequired},
},
@@ -226,6 +252,32 @@ func (r *Router) workspaceRoutes() []okapi.RouteDefinition {
Response: &dto.Response[any]{},
Options: []okapi.RouteOption{workspaceHeaderRequired},
},
+
+ // Data Management (GDPR) — destructive, admin/owner only.
+ {
+ Method: http.MethodPost,
+ Path: "/gdpr/delete-contacts",
+ Handler: okapi.H(r.h.workspaceData.DeleteContacts),
+ Group: wsGroup,
+ Middlewares: []okapi.Middleware{middlewares.RequireWorkspaceRole(models.WorkspaceRoleAdmin)},
+ Summary: "Delete workspace contact data (GDPR)",
+ Description: "Delete a specific contact (by email) or all contacts in the workspace, with associated suppressions and list memberships.",
+ Request: &handlers.GDPRDeleteContactsRequest{},
+ Response: &dto.Response[handlers.GDPRDeleteResult]{},
+ Options: []okapi.RouteOption{workspaceHeaderRequired},
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/gdpr/delete-email-logs",
+ Handler: okapi.H(r.h.workspaceData.DeleteEmailLogs),
+ Group: wsGroup,
+ Middlewares: []okapi.Middleware{middlewares.RequireWorkspaceRole(models.WorkspaceRoleAdmin)},
+ Summary: "Delete workspace email logs (GDPR)",
+ Description: "Purge the workspace's email logs (optionally only those older than a given number of days) and their bounce records.",
+ Request: &handlers.GDPRDeleteEmailLogsRequest{},
+ Response: &dto.Response[handlers.GDPRDeleteResult]{},
+ Options: []okapi.RouteOption{workspaceHeaderRequired},
+ },
}...)
// User-level invitation actions (no workspace context needed)
diff --git a/internal/services/email/service.go b/internal/services/email/service.go
index dee939c..2ff95d6 100644
--- a/internal/services/email/service.go
+++ b/internal/services/email/service.go
@@ -86,6 +86,7 @@ type Service struct {
contactRepo *repositories.ContactRepository
domainRepo *repositories.DomainRepository
userRepo *repositories.UserRepository
+ wsSettingRepo *repositories.WorkspaceSettingRepository
sender *SMTPSender
renderer *TemplateRenderer
limiter *ratelimit.RedisLimiter
@@ -140,10 +141,13 @@ func (s *Service) SetUnsubscribeListRepo(r *repositories.UnsubscribeListReposito
s.unsubRepo = r
}
-// SetDomainVerification sets the domain and user repositories for enforcing verified domain sending.
-func (s *Service) SetDomainVerification(dr *repositories.DomainRepository, ur *repositories.UserRepository) {
+// SetDomainVerification sets the repositories for enforcing verified-domain
+// sending. Strict mode is read from the workspace settings when a workspace is
+// active, falling back to the user's setting in legacy personal mode.
+func (s *Service) SetDomainVerification(dr *repositories.DomainRepository, ur *repositories.UserRepository, wsr *repositories.WorkspaceSettingRepository) {
s.domainRepo = dr
s.userRepo = ur
+ s.wsSettingRepo = wsr
}
// SetSettings sets the platform settings provider for dynamic configuration.
@@ -424,7 +428,7 @@ func (s *Service) ValidateSend(ctx context.Context, userID uint, workspaceID *ui
}
}
- if err := s.checkDomainVerification(userID, req.From); err != nil {
+ if err := s.checkDomainVerification(userID, workspaceID, req.From); err != nil {
return nil, err
}
@@ -598,12 +602,10 @@ func (s *Service) Send(ctx context.Context, userID, apiKeyID uint, workspaceID *
}
}
- // Enforce verified domain when user has strict mode enabled (personal mode only;
- // workspace domain verification is handled at the workspace level).
- if workspaceID == nil {
- if err := s.checkDomainVerification(userID, req.From); err != nil {
- return nil, err
- }
+ // Enforce verified-domain sending. Strict mode is scoped to the active
+ // workspace (or the user in legacy personal mode).
+ if err := s.checkDomainVerification(userID, workspaceID, req.From); err != nil {
+ return nil, err
}
// Resolve + validate the unsubscribe config (Posta-managed list, or caller-managed
@@ -1359,20 +1361,31 @@ func filterCustomHeaders(headers map[string]string) map[string]string {
return filtered
}
-// checkDomainVerification enforces domain ownership verification when the user
-// has RequireVerifiedDomain enabled. It extracts the sender domain and checks
-// that it is registered and ownership-verified via TXT record.
-func (s *Service) checkDomainVerification(userID uint, from string) error {
- if s.domainRepo == nil || s.userRepo == nil {
+// checkDomainVerification enforces domain ownership verification when strict
+// domain mode is enabled. Strict mode and domain ownership are scoped to the
+// active workspace when present, falling back to the user in legacy personal
+// mode. It extracts the sender domain and checks that it is registered and
+// ownership-verified.
+func (s *Service) checkDomainVerification(userID uint, workspaceID *uint, from string) error {
+ if s.domainRepo == nil {
return nil
}
- user, err := s.userRepo.FindByID(userID)
- if err != nil {
- return fmt.Errorf("failed to load user: %w", err)
+ // Resolve whether strict domain mode is on for this scope.
+ strict := false
+ if workspaceID != nil {
+ if s.wsSettingRepo != nil {
+ strict = s.wsSettingRepo.RequireVerifiedDomain(*workspaceID)
+ }
+ } else if s.userRepo != nil {
+ user, err := s.userRepo.FindByID(userID)
+ if err != nil {
+ return fmt.Errorf("failed to load user: %w", err)
+ }
+ strict = user.RequireVerifiedDomain
}
- if !user.RequireVerifiedDomain {
+ if !strict {
return nil
}
@@ -1381,7 +1394,13 @@ func (s *Service) checkDomainVerification(userID uint, from string) error {
return fmt.Errorf("domain_verification: could not extract domain from sender %q", from)
}
- if !s.domainRepo.IsOwnershipVerified(userID, senderDomain) {
+ verified := false
+ if workspaceID != nil {
+ verified = s.domainRepo.IsOwnershipVerifiedInWorkspace(*workspaceID, senderDomain)
+ } else {
+ verified = s.domainRepo.IsOwnershipVerified(userID, senderDomain)
+ }
+ if !verified {
return fmt.Errorf("domain_verification: domain %q is not verified. Add and verify the domain or disable strict domain mode", senderDomain)
}
diff --git a/internal/services/notification/service.go b/internal/services/notification/service.go
index 86fba14..891bcf2 100644
--- a/internal/services/notification/service.go
+++ b/internal/services/notification/service.go
@@ -54,6 +54,7 @@ type Service struct {
sender *email.SMTPSender
userRepo *repositories.UserRepository
userSettingRepo *repositories.UserSettingRepository
+ workspaceRepo *repositories.WorkspaceRepository
templates map[string]*template.Template
}
@@ -63,6 +64,7 @@ func NewService(
appName, appURL string,
userRepo *repositories.UserRepository,
userSettingRepo *repositories.UserSettingRepository,
+ workspaceRepo *repositories.WorkspaceRepository,
) *Service {
s := &Service{
smtpCfg: smtpCfg,
@@ -71,6 +73,7 @@ func NewService(
sender: email.NewSMTPSender(),
userRepo: userRepo,
userSettingRepo: userSettingRepo,
+ workspaceRepo: workspaceRepo,
templates: make(map[string]*template.Template),
}
s.loadTemplates()
@@ -172,6 +175,41 @@ func (s *Service) SendToUser(userID uint, subject, templateName string, data map
return s.Send(to, subject, templateName, data)
}
+func (s *Service) SendToWorkspaceAdmins(workspaceID uint, subject, templateName string, data map[string]any) error {
+ if !s.IsConfigured() {
+ return nil
+ }
+
+ members, err := s.workspaceRepo.ListMembers(workspaceID)
+ if err != nil {
+ return fmt.Errorf("notification: members for workspace %d: %w", workspaceID, err)
+ }
+
+ if data == nil {
+ data = make(map[string]any)
+ }
+ if _, ok := data["WorkspaceName"]; !ok {
+ if ws, err := s.workspaceRepo.FindByID(workspaceID); err == nil {
+ data["WorkspaceName"] = ws.Name
+ }
+ }
+
+ var firstErr error
+ for _, m := range members {
+ if m.Role != models.WorkspaceRoleOwner && m.Role != models.WorkspaceRoleAdmin {
+ continue
+ }
+ if err := s.SendToUser(m.UserID, subject, templateName, data); err != nil {
+ logger.Error("notification: failed to send to workspace admin",
+ "workspace_id", workspaceID, "user_id", m.UserID, "error", err)
+ if firstErr == nil {
+ firstErr = err
+ }
+ }
+ }
+ return firstErr
+}
+
func (s *Service) render(templateName string, data map[string]any) (string, error) {
tmpl, ok := s.templates[templateName]
if !ok {
diff --git a/internal/services/notification/templates/api_key_expiry.tmpl b/internal/services/notification/templates/api_key_expiry.tmpl
index e5ee894..a274921 100644
--- a/internal/services/notification/templates/api_key_expiry.tmpl
+++ b/internal/services/notification/templates/api_key_expiry.tmpl
@@ -1,7 +1,7 @@
{{ define "content" }}
<h2>API Key Expiring Soon</h2>
<p>Hi {{ .UserName }},</p>
-<p>The following API {{ if eq .KeyCount 1 }}key is{{ else }}keys are{{ end }} expiring within the next 7 days:</p>
+<p>The following API {{ if eq .KeyCount 1 }}key is{{ else }}keys are{{ end }} in {{ if .WorkspaceName }}<strong>{{ .WorkspaceName }}</strong>{{ else }}your workspace{{ end }} expiring within the next 7 days:</p>
<table class="stats-table">
<tr>
diff --git a/internal/services/notification/templates/bounce_alert.tmpl b/internal/services/notification/templates/bounce_alert.tmpl
index 9a8c3eb..5e5bfda 100644
--- a/internal/services/notification/templates/bounce_alert.tmpl
+++ b/internal/services/notification/templates/bounce_alert.tmpl
@@ -3,7 +3,7 @@
<p>Hi {{ .UserName }},</p>
<div class="alert-box alert-danger">
- Your bounce rate in the last 24 hours is <strong>{{ .BounceRate }}%</strong>, which exceeds the {{ .Threshold }}% threshold.
+ The bounce rate {{ if .WorkspaceName }}for <strong>{{ .WorkspaceName }}</strong> {{ end }}in the last 24 hours is <strong>{{ .BounceRate }}%</strong>, which exceeds the {{ .Threshold }}% threshold.
</div>
<table class="stats-table">
diff --git a/internal/services/notification/templates/daily_report.tmpl b/internal/services/notification/templates/daily_report.tmpl
index b2794e5..6579be0 100644
--- a/internal/services/notification/templates/daily_report.tmpl
+++ b/internal/services/notification/templates/daily_report.tmpl
@@ -1,6 +1,6 @@
{{ define "content" }}
<h2>Daily Email Report</h2>
-<p>Here's your email activity summary for <strong>{{ .ReportDate }}</strong>.</p>
+<p>Here's the email activity summary{{ if .WorkspaceName }} for <strong>{{ .WorkspaceName }}</strong>{{ end }} on <strong>{{ .ReportDate }}</strong>.</p>
<table class="stats-table">
<tr>
@@ -41,5 +41,5 @@
</p>
{{ end }}
-<p class="muted" style="margin-top: 24px;">You receive this report because you enabled daily reports in your notification settings.</p>
+<p class="muted" style="margin-top: 24px;">You receive this report as an owner or admin of this workspace.</p>
{{ end }}
diff --git a/internal/services/seeder/seeder.go b/internal/services/seeder/seeder.go
index 31662d9..82d065e 100644
--- a/internal/services/seeder/seeder.go
+++ b/internal/services/seeder/seeder.go
@@ -68,12 +68,13 @@ type templateDef struct {
// seedTemplate creates a single template with a version and one localization
// per seedLanguages entry, loading each localized body from the embedded files.
-func (s *Seeder) seedTemplate(userID uint, ssID uint, def templateDef) {
+func (s *Seeder) seedTemplate(workspaceID, userID uint, ssID uint, def templateDef) {
b, _ := json.MarshalIndent(def.SampleData, "", " ")
sampleData := string(b)
tmpl := &models.Template{
UserID: userID,
+ WorkspaceID: workspacePtr(workspaceID),
Name: def.Name,
DefaultLanguage: seedLanguages[0],
Description: def.Description,
@@ -115,8 +116,16 @@ func (s *Seeder) seedTemplate(userID uint, ssID uint, def templateDef) {
}
}
-// SeedUserDefaults creates default stylesheet and templates for a user
-func (s *Seeder) SeedUserDefaults(userID uint, userName string) {
+// workspacePtr returns a pointer to workspaceID, or nil when zero (defensive:
+// seeding always runs against a real personal workspace post-migration).
+func workspacePtr(workspaceID uint) *uint {
+ if workspaceID == 0 {
+ return nil
+ }
+ return &workspaceID
+}
+
+func (s *Seeder) SeedWorkspaceDefaults(workspaceID, userID uint, userName string) {
if userName == "" {
userName = "Jonas"
}
@@ -125,11 +134,14 @@ func (s *Seeder) SeedUserDefaults(userID uint, userName string) {
return
}
+ wsID := workspacePtr(workspaceID)
+
// Create default stylesheet
ss := &models.StyleSheet{
- UserID: userID,
- Name: "default",
- CSS: defaultCSS,
+ UserID: userID,
+ WorkspaceID: wsID,
+ Name: "default",
+ CSS: defaultCSS,
}
if err := s.stylesheetRepo.Create(ss); err != nil {
logger.Error("failed to seed default stylesheet", "user_id", userID, "error", err)
@@ -140,7 +152,7 @@ func (s *Seeder) SeedUserDefaults(userID uint, userName string) {
docsURL := fmt.Sprintf("%s/docs", goutils.Env("POSTA_WEB_URL", ""))
for _, def := range defaultTemplateDefs(userName, year, docsURL) {
- s.seedTemplate(userID, ss.ID, def)
+ s.seedTemplate(workspaceID, userID, ss.ID, def)
}
// Seed default languages
@@ -153,7 +165,7 @@ func (s *Seeder) SeedUserDefaults(userID uint, userName string) {
{"de", "German"},
}
for _, dl := range defaultLanguages {
- lang := &models.Language{UserID: userID, Code: dl.Code, Name: dl.Name}
+ lang := &models.Language{UserID: userID, WorkspaceID: wsID, Code: dl.Code, Name: dl.Name}
if lang.Code == "en" {
lang.IsDefault = true
}
@@ -162,7 +174,8 @@ func (s *Seeder) SeedUserDefaults(userID uint, userName string) {
}
}
- logger.Info("seeded default stylesheet, templates, versions, localizations, and languages", "user_id", userID)
+ logger.Info("seeded default stylesheet, templates, versions, localizations, and languages",
+ "user_id", userID, "workspace_id", workspaceID)
}
// defaultTemplateDefs returns the built-in templates seeded for every new user.
diff --git a/internal/services/workspacemigrate/migrate.go b/internal/services/workspacemigrate/migrate.go
new file mode 100644
index 0000000..5a3b451
--- /dev/null
+++ b/internal/services/workspacemigrate/migrate.go
@@ -0,0 +1,262 @@
+/*
+ * Copyright 2026 Jonas Kaninda
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package workspacemigrate
+
+import (
+ "errors"
+ "fmt"
+ "strings"
+ "time"
+
+ "github.com/goposta/posta/internal/models"
+ "github.com/jkaninda/logger"
+ "gorm.io/gorm"
+)
+
+// operationalTables are the user-scoped resources whose rows are re-scoped to
+// the personal workspace. Each has a `user_id NOT NULL` + nullable `workspace_id`.
+// Order is irrelevant — every table is backfilled by user_id in one pass.
+var operationalTables = []interface{}{
+ &models.APIKey{},
+ &models.Template{},
+ &models.StyleSheet{},
+ &models.Language{},
+ &models.Domain{},
+ &models.SMTPServer{},
+ &models.Webhook{},
+ &models.Contact{},
+ &models.Subscriber{},
+ &models.SubscriberList{},
+ &models.UnsubscribeList{},
+ &models.Suppression{},
+ &models.Bounce{},
+ &models.Email{},
+ &models.InboundEmail{},
+ &models.Campaign{},
+}
+
+// Seeder provisions default content (stylesheet, templates, languages) for a
+// freshly-created personal workspace. Implemented by services/seeder.Seeder.
+// It is only invoked on the per-user hook path (register/login/oauth), not the
+// bulk backfill — existing users already own their content.
+type Seeder interface {
+ SeedWorkspaceDefaults(workspaceID, userID uint, userName string)
+}
+
+// Service performs personal-workspace migrations.
+type Service struct {
+ // planEnforcement mirrors config.PlanEnforcement. When true a default plan
+ // must exist and is assigned to each personal workspace; when false (OSS
+ // default) workspaces get plan_id = NULL. See plan §1.
+ planEnforcement bool
+
+ // seeder, when set, seeds default content into a newly-created personal
+ // workspace after MigrateUser commits. nil on the backfill path.
+ seeder Seeder
+}
+
+// New constructs a migration service.
+func New(planEnforcement bool) *Service {
+ return &Service{planEnforcement: planEnforcement}
+}
+
+// SetSeeder attaches a seeder so MigrateUser provisions default content for new
+// personal workspaces. Folds the old fire-and-forget SeedUserDefaults call into
+// the migration (§4).
+func (s *Service) SetSeeder(seeder Seeder) {
+ s.seeder = seeder
+}
+
+func (s *Service) MigrateUser(db *gorm.DB, userID uint) (uint, error) {
+ var existing models.User
+ if err := db.Select("personal_workspace_id", "name").First(&existing, userID).Error; err == nil &&
+ existing.PersonalWorkspaceID != nil {
+ return *existing.PersonalWorkspaceID, nil
+ }
+
+ var wsID uint
+ err := db.Transaction(func(tx *gorm.DB) error {
+ id, e := s.migrate(tx, userID)
+ wsID = id
+ return e
+ })
+ if err != nil {
+ var u models.User
+ if e := db.First(&u, userID).Error; e == nil && u.PersonalWorkspaceID != nil {
+ return *u.PersonalWorkspaceID, nil
+ }
+ return 0, err
+ }
+
+ // Seed default content after commit so the workspace row is visible. The
+ // seeder is idempotent (skips users who already own templates), so this is a
+ // no-op for users who were re-scoped rather than freshly created.
+ if s.seeder != nil {
+ s.seeder.SeedWorkspaceDefaults(wsID, userID, existing.Name)
+ }
+
+ return wsID, nil
+}
+
+func (s *Service) MigrateAllUnmigrated(tx *gorm.DB) error {
+ var ids []uint
+ if err := tx.Model(&models.User{}).
+ Where("personal_workspace_id IS NULL").
+ Order("id").
+ Pluck("id", &ids).Error; err != nil {
+ return fmt.Errorf("list unmigrated users: %w", err)
+ }
+
+ logger.Info("workspace migration: backfilling personal workspaces", "users", len(ids))
+
+ migrated := 0
+ for _, id := range ids {
+ err := tx.Transaction(func(utx *gorm.DB) error {
+ _, e := s.migrate(utx, id)
+ return e
+ })
+ if err != nil {
+ logger.Error("workspace migration failed for user", "user_id", id, "error", err)
+ if uerr := tx.Model(&models.User{}).Where("id = ?", id).
+ Update("migration_error", err.Error()).Error; uerr != nil {
+ return fmt.Errorf("record migration error for user %d: %w", id, uerr)
+ }
+ continue
+ }
+ migrated++
+ }
+
+ logger.Info("workspace migration: backfill complete", "migrated", migrated, "failed", len(ids)-migrated)
+ return nil
+}
+
+func (s *Service) migrate(tx *gorm.DB, userID uint) (uint, error) {
+ var user models.User
+ if err := tx.First(&user, userID).Error; err != nil {
+ return 0, fmt.Errorf("load user: %w", err)
+ }
+
+ // Already migrated — no-op.
+ if user.PersonalWorkspaceID != nil {
+ return *user.PersonalWorkspaceID, nil
+ }
+
+ // Resolve the plan (NULL in OSS / non-enforcing mode).
+ planID, err := s.resolvePlanID(tx)
+ if err != nil {
+ return 0, err
+ }
+
+ // Create the personal workspace.
+ name := strings.TrimSpace(user.Name)
+ if name == "" {
+ name = "Personal"
+ }
+ ws := &models.Workspace{
+ Name: name,
+ Slug: personalSlug(user.ID),
+ OwnerID: user.ID,
+ IsPersonal: true,
+ PlanID: planID,
+ }
+ if err := tx.Create(ws).Error; err != nil {
+ return 0, fmt.Errorf("create personal workspace: %w", err)
+ }
+
+ // Owner member row
+ member := &models.WorkspaceMember{
+ WorkspaceID: ws.ID,
+ UserID: user.ID,
+ Role: models.WorkspaceRoleOwner,
+ }
+ if err := tx.Create(member).Error; err != nil {
+ return 0, fmt.Errorf("create owner member: %w", err)
+ }
+
+ if err := s.copySettings(tx, user.ID, ws.ID, user.RequireVerifiedDomain); err != nil {
+ return 0, err
+ }
+
+ for _, model := range operationalTables {
+ if err := tx.Model(model).
+ Where("user_id = ? AND workspace_id IS NULL", user.ID).
+ Update("workspace_id", ws.ID).Error; err != nil {
+ return 0, fmt.Errorf("backfill %T: %w", model, err)
+ }
+ }
+
+ // Mark the user migrated and clear any prior error.
+ if err := tx.Model(&models.User{}).Where("id = ?", user.ID).Updates(map[string]interface{}{
+ "personal_workspace_id": ws.ID,
+ "migrated_at": time.Now().UTC(),
+ "migration_error": "",
+ }).Error; err != nil {
+ return 0, fmt.Errorf("mark user migrated: %w", err)
+ }
+
+ return ws.ID, nil
+}
+
+func (s *Service) resolvePlanID(tx *gorm.DB) (*uint, error) {
+ if !s.planEnforcement {
+ return nil, nil
+ }
+ var plan models.Plan
+ if err := tx.Where("is_default = ? AND is_active = ?", true, true).First(&plan).Error; err != nil {
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil, errors.New("plan enforcement is enabled but no default plan is configured")
+ }
+ return nil, fmt.Errorf("resolve default plan: %w", err)
+ }
+ return &plan.ID, nil
+}
+
+func (s *Service) copySettings(tx *gorm.DB, userID, workspaceID uint, requireVerifiedDomain bool) error {
+ var us models.UserSetting
+ err := tx.Where("user_id = ?", userID).First(&us).Error
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ us = models.UserSetting{
+ Timezone: "UTC",
+ WebhookRetryCount: 3,
+ APIKeyExpiryDays: 90,
+ BounceAutoSuppress: true,
+ }
+ } else if err != nil {
+ return fmt.Errorf("load user settings: %w", err)
+ }
+
+ ws := models.WorkspaceSetting{
+ WorkspaceID: workspaceID,
+ Timezone: us.Timezone,
+ DefaultSenderName: us.DefaultSenderName,
+ DefaultSenderEmail: us.DefaultSenderEmail,
+ WebhookRetryCount: us.WebhookRetryCount,
+ APIKeyExpiryDays: us.APIKeyExpiryDays,
+ BounceAutoSuppress: us.BounceAutoSuppress,
+ RequireVerifiedDomain: requireVerifiedDomain,
+ }
+ if err := tx.Create(&ws).Error; err != nil {
+ return fmt.Errorf("create workspace settings: %w", err)
+ }
+ return nil
+}
+
+// personalSlug derives a stable, unique slug for a user's personal workspace.
+func personalSlug(userID uint) string {
+ return fmt.Sprintf("personal-%d", userID)
+}
diff --git a/internal/services/workspacemigrate/migrate_test.go b/internal/services/workspacemigrate/migrate_test.go
new file mode 100644
index 0000000..22c469b
--- /dev/null
+++ b/internal/services/workspacemigrate/migrate_test.go
@@ -0,0 +1,67 @@
+/*
+ * Copyright 2026 Jonas Kaninda
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package workspacemigrate
+
+import (
+ "fmt"
+ "testing"
+
+ "github.com/goposta/posta/internal/models"
+)
+
+// The transactional migration itself is exercised against a live Postgres (it
+// relies on SAVEPOINTs and the partial unique index, which an in-memory engine
+// won't replicate). These unit tests cover the pure pieces that are easy to get
+// wrong without a database.
+
+func TestPersonalSlugIsStableAndUnique(t *testing.T) {
+ if got := personalSlug(42); got != "personal-42" {
+ t.Fatalf("personalSlug(42) = %q, want %q", got, "personal-42")
+ }
+ if personalSlug(1) == personalSlug(2) {
+ t.Fatal("personalSlug must differ per user")
+ }
+}
+
+// TestOperationalTablesMatchPlan guards against silently dropping a table from
+// the backfill — every user-scoped operational resource listed in §3 of the
+// plan must be present, and each must actually carry a workspace_id column.
+func TestOperationalTablesMatchPlan(t *testing.T) {
+ want := []interface{}{
+ &models.APIKey{}, &models.Template{}, &models.StyleSheet{}, &models.Language{},
+ &models.Domain{}, &models.SMTPServer{}, &models.Webhook{}, &models.Contact{},
+ &models.Subscriber{}, &models.SubscriberList{}, &models.UnsubscribeList{},
+ &models.Suppression{}, &models.Bounce{}, &models.Email{}, &models.InboundEmail{},
+ &models.Campaign{},
+ }
+
+ if len(operationalTables) != len(want) {
+ t.Fatalf("operationalTables has %d entries, plan expects %d", len(operationalTables), len(want))
+ }
+
+ got := make(map[string]bool, len(operationalTables))
+ for _, m := range operationalTables {
+ got[fmt.Sprintf("%T", m)] = true
+ }
+ for _, m := range want {
+ key := fmt.Sprintf("%T", m)
+ if !got[key] {
+ t.Errorf("operationalTables is missing %s", key)
+ }
+ }
+}
diff --git a/internal/storage/migration/constraints.go b/internal/storage/migration/constraints.go
index f2f2b76..7d594b9 100644
--- a/internal/storage/migration/constraints.go
+++ b/internal/storage/migration/constraints.go
@@ -56,39 +56,60 @@ func runConstraints(db *gorm.DB) {
EXCEPTION WHEN others THEN NULL;
END $$`)
- // Composite index for fast Message-ID dedup lookups on inbound_emails.
+ // Composite index for fast Message-ID dedup lookups on inbound_emails, scoped
+ // to the workspace (workspace-only migration — replaces the legacy user_id one).
db.Exec(`DO $$ BEGIN
- CREATE INDEX IF NOT EXISTS idx_inbound_user_message_id ON inbound_emails (user_id, message_id) WHERE message_id <> '';
+ DROP INDEX IF EXISTS idx_inbound_user_message_id;
+ CREATE INDEX IF NOT EXISTS idx_inbound_workspace_message_id ON inbound_emails (workspace_id, message_id) WHERE message_id <> '';
+ EXCEPTION WHEN others THEN NULL;
+ END $$`)
+
+ db.Exec(`DO $$ BEGIN
+ CREATE UNIQUE INDEX IF NOT EXISTS one_personal_per_user ON workspaces (owner_id) WHERE is_personal;
EXCEPTION WHEN others THEN NULL;
END $$`)
}
+// rebuildUniqueIndexes re-scopes the per-tenant uniqueness constraints to
+// workspace-only.
func rebuildUniqueIndexes(db *gorm.DB) {
type indexDef struct {
- table string
- name string
- column string
+ table string
+ oldName string // legacy user-scoped index, dropped
+ newName string // workspace-scoped index, created
+ column string
}
indexes := []indexDef{
- {"templates", "idx_user_template", "name"},
- {"style_sheets", "idx_user_stylesheet", "name"},
- {"contacts", "idx_user_email", "email"},
- {"domains", "idx_user_domain", "domain"},
- {"languages", "idx_user_language", "code"},
+ {"templates", "idx_user_template", "idx_workspace_template", "name"},
+ {"style_sheets", "idx_user_stylesheet", "idx_workspace_stylesheet", "name"},
+ {"contacts", "idx_user_email", "idx_workspace_email", "email"},
+ {"domains", "idx_user_domain", "idx_workspace_domain", "domain"},
+ {"languages", "idx_user_language", "idx_workspace_language", "code"},
- {"suppressions", "idx_user_suppression", "email, COALESCE(list_id, 0)"},
- {"unsubscribe_lists", "idx_user_unsub_list", "name"},
+ {"suppressions", "idx_user_suppression", "idx_workspace_suppression", "email, COALESCE(list_id, 0)"},
+ {"unsubscribe_lists", "idx_user_unsub_list", "idx_workspace_unsub_list", "name"},
}
for _, idx := range indexes {
db.Exec(fmt.Sprintf(`
DO $$ BEGIN
DROP INDEX IF EXISTS %s;
- CREATE UNIQUE INDEX %s ON %s (user_id, COALESCE(workspace_id, 0), %s);
+ DROP INDEX IF EXISTS %s;
+ CREATE UNIQUE INDEX %s ON %s (workspace_id, %s) WHERE workspace_id IS NOT NULL;
EXCEPTION WHEN others THEN NULL;
END $$`,
- idx.name, idx.name, idx.table, idx.column,
+ idx.oldName, idx.newName, idx.newName, idx.table, idx.column,
))
}
+
+ // Subscribers carry their unique index from a GORM tag (idx_sub_scope_email,
+ // historically on user_id, workspace_id, email). Re-scope it to workspace-only
+ // here so both fresh and existing databases converge. Recreated under the same
+ // name so AutoMigrate won't re-add the legacy definition.
+ db.Exec(`DO $$ BEGIN
+ DROP INDEX IF EXISTS idx_sub_scope_email;
+ CREATE UNIQUE INDEX idx_sub_scope_email ON subscribers (workspace_id, email) WHERE workspace_id IS NOT NULL;
+ EXCEPTION WHEN others THEN NULL;
+ END $$`)
}
diff --git a/internal/storage/migration/migration.go b/internal/storage/migration/migration.go
index d8adb16..0fb00e0 100644
--- a/internal/storage/migration/migration.go
+++ b/internal/storage/migration/migration.go
@@ -52,9 +52,12 @@ func Run(db *gorm.DB) error {
&models.Suppression{},
&models.UnsubscribeList{},
&models.Contact{},
+ &models.ContactList{},
+ &models.ContactListMember{},
&models.Event{},
&models.Setting{},
&models.UserSetting{},
+ &models.WorkspaceSetting{},
&models.WebhookDelivery{},
&models.Session{},
&models.UserEmailVerification{},
@@ -66,6 +69,7 @@ func Run(db *gorm.DB) error {
&models.CampaignMessage{},
&models.TrackedLink{},
&models.TrackingEvent{},
+ &models.UpgradeStep{},
); err != nil {
return fmt.Errorf("failed to migrate database: %w", err)
}
diff --git a/internal/storage/migration/upgrade/lock.go b/internal/storage/migration/upgrade/lock.go
new file mode 100644
index 0000000..305ede6
--- /dev/null
+++ b/internal/storage/migration/upgrade/lock.go
@@ -0,0 +1,52 @@
+/*
+ * Copyright 2026 Jonas Kaninda
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package upgrade
+
+import (
+ "context"
+ "fmt"
+
+ "gorm.io/gorm"
+)
+
+const advisoryLockKey int64 = 0x506F73746155706C // "PostaUpl"
+
+// withLock acquires a Postgres session-level advisory lock for the upgrade
+// flow, runs fn, then releases the lock. Concurrent boots of multiple
+// replicas serialize through this lock so only one runs the registry.
+func withLock(ctx context.Context, db *gorm.DB, fn func(context.Context) error) error {
+ conn, err := db.DB()
+ if err != nil {
+ return fmt.Errorf("upgrade: acquire raw conn: %w", err)
+ }
+ // Use a single connection so the lock is held for the duration of fn.
+ c, err := conn.Conn(ctx)
+ if err != nil {
+ return fmt.Errorf("upgrade: pin conn: %w", err)
+ }
+ defer func() { _ = c.Close() }()
+
+ if _, err := c.ExecContext(ctx, "SELECT pg_advisory_lock($1)", advisoryLockKey); err != nil {
+ return fmt.Errorf("upgrade: acquire lock: %w", err)
+ }
+ defer func() {
+ _, _ = c.ExecContext(context.Background(), "SELECT pg_advisory_unlock($1)", advisoryLockKey)
+ }()
+
+ return fn(ctx)
+}
diff --git a/internal/storage/migration/upgrade/settings.go b/internal/storage/migration/upgrade/settings.go
new file mode 100644
index 0000000..07aa1d5
--- /dev/null
+++ b/internal/storage/migration/upgrade/settings.go
@@ -0,0 +1,84 @@
+/*
+ * Copyright 2026 Jonas Kaninda
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package upgrade
+
+import (
+ "errors"
+ "time"
+
+ "github.com/goposta/posta/internal/models"
+ "gorm.io/gorm"
+)
+
+// readVersion returns the stored app version. The fresh flag is true when no
+// app.version row exists yet
+func readVersion(db *gorm.DB) (version string, fresh bool, err error) {
+ var s models.Setting
+ err = db.Where("key = ?", KeyAppVersion).First(&s).Error
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return "", true, nil
+ }
+ if err != nil {
+ return "", false, err
+ }
+ return s.Value, false, nil
+}
+
+// writeVersion updates the app.version and app.last_started_at settings rows
+// in a single transaction. It also creates app.first_started_at on first
+// successful boot.
+func writeVersion(db *gorm.DB, version string) error {
+ now := time.Now().UTC().Format(time.RFC3339)
+ return db.Transaction(func(tx *gorm.DB) error {
+ if err := upsertSetting(tx, KeyAppVersion, version); err != nil {
+ return err
+ }
+ if err := upsertSetting(tx, KeyAppLastStartedAt, now); err != nil {
+ return err
+ }
+ return ensureSetting(tx, KeyAppFirstStartedAt, now)
+ })
+}
+
+// upsertSetting writes a string value, replacing any existing row for the key.
+func upsertSetting(tx *gorm.DB, key, value string) error {
+ var existing models.Setting
+ err := tx.Where("key = ?", key).First(&existing).Error
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return tx.Create(&models.Setting{Key: key, Value: value, Type: "string"}).Error
+ }
+ if err != nil {
+ return err
+ }
+ existing.Value = value
+ existing.Type = "string"
+ return tx.Save(&existing).Error
+}
+
+// ensureSetting inserts the row only if it does not already exist.
+func ensureSetting(tx *gorm.DB, key, value string) error {
+ var existing models.Setting
+ err := tx.Where("key = ?", key).First(&existing).Error
+ if err == nil {
+ return nil
+ }
+ if !errors.Is(err, gorm.ErrRecordNotFound) {
+ return err
+ }
+ return tx.Create(&models.Setting{Key: key, Value: value, Type: "string"}).Error
+}
diff --git a/internal/storage/migration/upgrade/step.go b/internal/storage/migration/upgrade/step.go
new file mode 100644
index 0000000..b507507
--- /dev/null
+++ b/internal/storage/migration/upgrade/step.go
@@ -0,0 +1,61 @@
+/*
+ * Copyright 2026 Jonas Kaninda
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package upgrade
+
+import "gorm.io/gorm"
+
+// Step is a one-shot data migration that runs at boot time, exactly once per
+// database. Schema migrations stay in GORM AutoMigrate; this registry is for
+// data backfills, defaults, and cleanup that AutoMigrate cannot express.
+//
+// Rules each step author must follow:
+//
+// 1. ID is permanent. Once a step ships, never rename or delete its ID —
+// that's how the registry knows the step has already been applied.
+// Use a date-prefixed slug, e.g. "2026-05-30-mark-default-plan".
+// 2. Apply must be idempotent in spirit even though the framework guarantees
+// single-run, because a step that crashes mid-way will retry on the next
+// boot. Use INSERT … ON CONFLICT DO NOTHING, WHERE NOT EXISTS, etc.
+// 3. Apply runs inside its own transaction; do not start one yourself.
+// 4. If a step is wrong after it ships, write a follow-up step that fixes
+// forward. Do not retroactively edit a step's Apply.
+type Step struct {
+ ID string
+ Apply func(tx *gorm.DB) error
+}
+
+// registry is the in-tree list of upgrade steps, in the order they should be
+// applied. Append-only: new steps go at the end, old steps never move.
+//
+// To register a step, add an entry here and define its Apply func in a sibling
+// file (e.g. steps_2026_05_30_default_plan.go).
+var registry = []Step{
+ {
+
+ ID: "2026-05-31-personal-workspaces",
+ Apply: applyPersonalWorkspaces,
+ },
+}
+
+// Registry returns a copy of the registered steps so callers (status command,
+// tests) can inspect the list without mutating it.
+func Registry() []Step {
+ out := make([]Step, len(registry))
+ copy(out, registry)
+ return out
+}
diff --git a/internal/storage/migration/upgrade/steps_2026_05_31_personal_workspaces.go b/internal/storage/migration/upgrade/steps_2026_05_31_personal_workspaces.go
new file mode 100644
index 0000000..461eb6d
--- /dev/null
+++ b/internal/storage/migration/upgrade/steps_2026_05_31_personal_workspaces.go
@@ -0,0 +1,30 @@
+/*
+ * Copyright 2026 Jonas Kaninda
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package upgrade
+
+import (
+ "github.com/goposta/posta/internal/services/workspacemigrate"
+ "gorm.io/gorm"
+)
+
+// applyPersonalWorkspaces is the Apply func for the one-shot personal-workspace
+// backfill.
+func applyPersonalWorkspaces(tx *gorm.DB) error {
+ svc := workspacemigrate.New(runOptions.PlanEnforcement)
+ return svc.MigrateAllUnmigrated(tx)
+}
diff --git a/internal/storage/migration/upgrade/upgrade.go b/internal/storage/migration/upgrade/upgrade.go
new file mode 100644
index 0000000..512f4f2
--- /dev/null
+++ b/internal/storage/migration/upgrade/upgrade.go
@@ -0,0 +1,169 @@
+/*
+ * Copyright 2026 Jonas Kaninda
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// Package upgrade tracks the app version stored in the database and applies
+// one-shot data migrations recorded in the in-tree step registry. It runs at
+// server start, after the GORM schema AutoMigrate.
+//
+// Schema migrations live in internal/storage/migration. This package only
+// handles versioned data migrations and the version pin used to refuse
+// downgrades. See step.go for the registry contract.
+package upgrade
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "time"
+
+ "github.com/goposta/posta/internal/models"
+ "github.com/jkaninda/logger"
+ "gorm.io/gorm"
+)
+
+// Settings keys persisted in the platform `settings` table.
+const (
+ KeyAppVersion = "app.version"
+ KeyAppFirstStartedAt = "app.first_started_at"
+ KeyAppLastStartedAt = "app.last_started_at"
+)
+
+// ErrDowngrade is returned when the binary version is older than the version
+// recorded in the database. Callers may choose to allow it via AllowDowngrade.
+var ErrDowngrade = errors.New("upgrade: binary is older than the database version (downgrade)")
+
+// Options tunes the upgrade run. Zero value is the safe default.
+type Options struct {
+ // AllowDowngrade lets the boot proceed even when the binary is older than
+ // the stored version. Intended for emergencies; logs a loud warning.
+ AllowDowngrade bool
+
+ // PlanEnforcement mirrors config.PlanEnforcement. It is consumed by data
+ // steps that provision plan-bearing rows (the personal-workspace backfill).
+ PlanEnforcement bool
+}
+
+// runOptions holds the Options for the in-progress run so registry steps — whose
+// Apply signature takes only a *gorm.DB — can read runtime configuration. Access
+// is safe: Run holds the advisory lock for the entire run, serializing it.
+var runOptions Options
+
+func Run(ctx context.Context, db *gorm.DB, binaryVersion string, opts Options) error {
+ return withLock(ctx, db, func(ctx context.Context) error {
+ return runLocked(ctx, db, binaryVersion, opts)
+ })
+}
+
+func runLocked(ctx context.Context, db *gorm.DB, binaryVersion string, opts Options) error {
+ runOptions = opts
+ stored, fresh, err := readVersion(db)
+ if err != nil {
+ return fmt.Errorf("upgrade: read stored version: %w", err)
+ }
+
+ switch {
+ case fresh:
+ if err := markAllApplied(db, binaryVersion); err != nil {
+ return fmt.Errorf("upgrade: bootstrap fresh install: %w", err)
+ }
+ logger.Info("upgrade: fresh install, sealed step registry", "version", binaryVersion)
+
+ case IsDev(binaryVersion):
+ logger.Warn("upgrade: running dev binary against versioned database — skipping version pin",
+ "stored_version", stored)
+
+ case IsDowngrade(binaryVersion, stored):
+ if !opts.AllowDowngrade {
+ return fmt.Errorf("%w: binary=%s, database=%s", ErrDowngrade, binaryVersion, stored)
+ }
+ logger.Warn("upgrade: downgrade explicitly allowed",
+ "binary_version", binaryVersion, "stored_version", stored)
+ }
+ if err := applyPending(ctx, db, binaryVersion); err != nil {
+ return err
+ }
+
+ if !IsDev(binaryVersion) {
+ if err := writeVersion(db, binaryVersion); err != nil {
+ return fmt.Errorf("upgrade: persist version: %w", err)
+ }
+ }
+ return nil
+}
+
+func applyPending(ctx context.Context, db *gorm.DB, binaryVersion string) error {
+ applied, err := loadAppliedIDs(db)
+ if err != nil {
+ return fmt.Errorf("upgrade: load applied steps: %w", err)
+ }
+
+ for _, step := range registry {
+ if _, ok := applied[step.ID]; ok {
+ continue
+ }
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ start := time.Now()
+ logger.Info("upgrade: applying step", "id", step.ID)
+
+ err := db.Transaction(func(tx *gorm.DB) error {
+ if err := step.Apply(tx); err != nil {
+ return err
+ }
+ return tx.Create(&models.UpgradeStep{
+ ID: step.ID,
+ AppVersion: binaryVersion,
+ AppliedAt: time.Now().UTC(),
+ DurationMS: time.Since(start).Milliseconds(),
+ }).Error
+ })
+ if err != nil {
+ return fmt.Errorf("upgrade: step %q failed: %w", step.ID, err)
+ }
+ logger.Info("upgrade: step applied", "id", step.ID, "duration_ms", time.Since(start).Milliseconds())
+ }
+ return nil
+}
+
+func loadAppliedIDs(db *gorm.DB) (map[string]struct{}, error) {
+ var ids []string
+ if err := db.Model(&models.UpgradeStep{}).Pluck("id", &ids).Error; err != nil {
+ return nil, err
+ }
+ out := make(map[string]struct{}, len(ids))
+ for _, id := range ids {
+ out[id] = struct{}{}
+ }
+ return out, nil
+}
+
+func markAllApplied(db *gorm.DB, binaryVersion string) error {
+ if len(registry) == 0 {
+ return nil
+ }
+ now := time.Now().UTC()
+ rows := make([]models.UpgradeStep, 0, len(registry))
+ for _, s := range registry {
+ rows = append(rows, models.UpgradeStep{
+ ID: s.ID,
+ AppVersion: binaryVersion,
+ AppliedAt: now,
+ })
+ }
+ return db.Create(&rows).Error
+}
diff --git a/internal/storage/migration/upgrade/version.go b/internal/storage/migration/upgrade/version.go
new file mode 100644
index 0000000..160bb62
--- /dev/null
+++ b/internal/storage/migration/upgrade/version.go
@@ -0,0 +1,91 @@
+/*
+ * Copyright 2026 Jonas Kaninda
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package upgrade
+
+import (
+ "regexp"
+ "strings"
+
+ "golang.org/x/mod/semver"
+)
+
+// gitDescribeSuffix matches the trailing "-N-g<sha>" (plus optional "-dirty")
+// that `git describe` appends to commits past a tag. Stripping it lets us
+// treat a developer's branch ahead of v1.2.0 as v1.2.0 for downgrade checks
+// — not as a pre-release of it.
+var gitDescribeSuffix = regexp.MustCompile(`-\d+-g[0-9a-f]+(-dirty)?$`)
+
+// devVersion is the placeholder used by local builds (Makefile fallback).
+const devVersion = "dev"
+
+// IsDev reports whether v is the sentinel value used for local/dev builds.
+func IsDev(v string) bool { return v == devVersion || v == "" }
+
+// canonical converts a `git describe` style version like "v0.6.6-3-gabc1234"
+// or "v0.6.6-3-gabc1234-dirty" into a canonical semver that x/mod/semver can
+// compare. Tag-only versions ("v0.6.6") and pre-releases ("v0.6.5-rc.1") pass
+// through unchanged.
+func canonical(v string) string {
+ v = strings.TrimSpace(v)
+ if v == "" {
+ return ""
+ }
+ if !strings.HasPrefix(v, "v") {
+ v = "v" + v
+ }
+ if c := semver.Canonical(v); c != "" {
+ return c
+ }
+ // Fall back: strip everything after the first '-' (post-tag commit suffix).
+ if idx := strings.Index(v, "-"); idx > 0 {
+ return semver.Canonical(v[:idx])
+ }
+ return ""
+}
+
+// Compare returns -1, 0, or 1 if a is less than, equal to, or greater than b.
+// Invalid or dev versions sort as equal (callers must check IsDev first if
+// they care).
+func Compare(a, b string) int {
+ ca, cb := canonical(a), canonical(b)
+ if ca == "" || cb == "" {
+ return 0
+ }
+ return semver.Compare(ca, cb)
+}
+
+// IsDowngrade reports whether `binary` is strictly older than `stored`. Both
+// arguments are normalized through baseTag so a developer build with commits
+// ahead of a tag (e.g. "v1.2.0-3-gabc1234") is treated as the tag itself and
+// not as a pre-release of it.
+func IsDowngrade(binary, stored string) bool {
+ if IsDev(binary) || IsDev(stored) {
+ return false
+ }
+ return Compare(baseTag(binary), baseTag(stored)) < 0
+}
+
+// baseTag strips a `git describe` post-tag suffix, leaving the underlying
+// release tag. Intentional pre-releases like "v1.0.0-rc.1" pass through.
+func baseTag(v string) string {
+ v = strings.TrimSpace(v)
+ if !strings.HasPrefix(v, "v") {
+ v = "v" + v
+ }
+ return gitDescribeSuffix.ReplaceAllString(v, "")
+}
diff --git a/internal/storage/migration/upgrade/version_test.go b/internal/storage/migration/upgrade/version_test.go
new file mode 100644
index 0000000..105a9a2
--- /dev/null
+++ b/internal/storage/migration/upgrade/version_test.go
@@ -0,0 +1,90 @@
+/*
+ * Copyright 2026 Jonas Kaninda
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package upgrade
+
+import "testing"
+
+func TestCompare(t *testing.T) {
+ cases := []struct {
+ name string
+ a, b string
+ want int
+ }{
+ {"equal canonical", "v1.2.3", "v1.2.3", 0},
+ {"missing v prefix", "1.2.3", "v1.2.3", 0},
+ {"older patch", "v1.2.3", "v1.2.4", -1},
+ {"older minor", "v1.2.0", "v1.3.0", -1},
+ {"older major", "v1.9.9", "v2.0.0", -1},
+ {"newer patch", "v1.2.4", "v1.2.3", 1},
+ // Lexicographic vs numeric: would compare wrong as plain strings.
+ {"numeric vs lexicographic minor", "v0.10.0", "v0.2.0", 1},
+ {"numeric vs lexicographic patch", "v1.0.10", "v1.0.2", 1},
+ // Pre-releases sort below the corresponding release.
+ {"rc below release", "v1.0.0-rc.1", "v1.0.0", -1},
+ {"rc1 before rc2", "v1.0.0-rc.1", "v1.0.0-rc.2", -1},
+ // git describe suffixes — "v0.6.6-3-gabc1234" is post-tag commits.
+ {"post-tag suffix sorts below next release", "v0.6.6-3-gabc1234", "v0.6.7", -1},
+ {"post-tag suffix above older release", "v0.6.6-3-gabc1234", "v0.6.5", 1},
+ {"dirty suffix still comparable", "v0.6.6-3-gabc1234-dirty", "v0.6.5", 1},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got := Compare(tc.a, tc.b)
+ if got != tc.want {
+ t.Fatalf("Compare(%q, %q) = %d, want %d", tc.a, tc.b, got, tc.want)
+ }
+ })
+ }
+}
+
+func TestIsDowngrade(t *testing.T) {
+ cases := []struct {
+ name string
+ binary, stored string
+ want bool
+ }{
+ {"newer binary not a downgrade", "v1.3.0", "v1.2.0", false},
+ {"same version not a downgrade", "v1.3.0", "v1.3.0", false},
+ {"older binary is a downgrade", "v1.2.0", "v1.3.0", true},
+ {"dev binary never a downgrade", "dev", "v1.3.0", false},
+ {"dev stored never a downgrade", "v1.3.0", "dev", false},
+ {"empty binary treated as dev", "", "v1.0.0", false},
+
+ {"post-tag ahead is not a downgrade", "v1.2.0-3-gabc1234", "v1.2.0", false},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := IsDowngrade(tc.binary, tc.stored); got != tc.want {
+ t.Fatalf("IsDowngrade(%q, %q) = %v, want %v", tc.binary, tc.stored, got, tc.want)
+ }
+ })
+ }
+}
+
+func TestIsDev(t *testing.T) {
+ for _, v := range []string{"dev", ""} {
+ if !IsDev(v) {
+ t.Errorf("IsDev(%q) = false, want true", v)
+ }
+ }
+ for _, v := range []string{"v1.0.0", "v0.6.6-3-gabc1234", "1.2.3"} {
+ if IsDev(v) {
+ t.Errorf("IsDev(%q) = true, want false", v)
+ }
+ }
+}
diff --git a/internal/storage/repositories/bounce_repo.go b/internal/storage/repositories/bounce_repo.go
index 14753f8..f87f698 100644
--- a/internal/storage/repositories/bounce_repo.go
+++ b/internal/storage/repositories/bounce_repo.go
@@ -105,3 +105,12 @@ func (r *BounceRepository) CountByUserAndDateRange(userID uint, from, to time.Ti
Count(&count).Error
return count, err
}
+
+// CountByWorkspaceAndDateRange counts bounces for a workspace within a date range.
+func (r *BounceRepository) CountByWorkspaceAndDateRange(workspaceID uint, from, to time.Time) (int64, error) {
+ var count int64
+ err := r.db.Model(&models.Bounce{}).
+ Where("workspace_id = ? AND created_at >= ? AND created_at <= ?", workspaceID, from, to).
+ Count(&count).Error
+ return count, err
+}
diff --git a/internal/storage/repositories/contact_repo.go b/internal/storage/repositories/contact_repo.go
index e87c814..d9a15ca 100644
--- a/internal/storage/repositories/contact_repo.go
+++ b/internal/storage/repositories/contact_repo.go
@@ -42,7 +42,7 @@ func (r *ContactRepository) RecordSent(userID uint, workspaceID *uint, recipient
addr, name := parseRecipient(raw)
r.db.Exec(`INSERT INTO contacts (user_id, workspace_id, email, name, sent_count, fail_count, last_sent_at, created_at)
VALUES (?, ?, ?, ?, 1, 0, ?, ?)
- ON CONFLICT (user_id, COALESCE(workspace_id, 0), email)
+ ON CONFLICT (workspace_id, email) WHERE workspace_id IS NOT NULL
DO UPDATE SET sent_count = contacts.sent_count + 1, last_sent_at = EXCLUDED.last_sent_at`+
nameUpdateClause(name),
userID, workspaceID, addr, name, now, now)
@@ -55,7 +55,7 @@ func (r *ContactRepository) RecordFailed(userID uint, workspaceID *uint, recipie
addr, name := parseRecipient(raw)
r.db.Exec(`INSERT INTO contacts (user_id, workspace_id, email, name, sent_count, fail_count, created_at)
VALUES (?, ?, ?, ?, 0, 1, ?)
- ON CONFLICT (user_id, COALESCE(workspace_id, 0), email)
+ ON CONFLICT (workspace_id, email) WHERE workspace_id IS NOT NULL
DO UPDATE SET fail_count = contacts.fail_count + 1`+
nameUpdateClause(name),
userID, workspaceID, addr, name, time.Now())
diff --git a/internal/storage/repositories/domain_repo.go b/internal/storage/repositories/domain_repo.go
index f91eff8..ae2a63e 100644
--- a/internal/storage/repositories/domain_repo.go
+++ b/internal/storage/repositories/domain_repo.go
@@ -124,3 +124,13 @@ func (r *DomainRepository) IsOwnershipVerified(userID uint, domainName string) b
Count(&count)
return count > 0
}
+
+// IsOwnershipVerifiedInWorkspace checks whether the given domain is registered
+// and ownership-verified within the workspace (any member's verified domain).
+func (r *DomainRepository) IsOwnershipVerifiedInWorkspace(workspaceID uint, domainName string) bool {
+ var count int64
+ r.db.Model(&models.Domain{}).
+ Where("workspace_id = ? AND domain = ? AND ownership_verified = ?", workspaceID, domainName, true).
+ Count(&count)
+ return count > 0
+}
diff --git a/internal/storage/repositories/scope.go b/internal/storage/repositories/scope.go
index ed87daa..48f3fe5 100644
--- a/internal/storage/repositories/scope.go
+++ b/internal/storage/repositories/scope.go
@@ -17,23 +17,29 @@
package repositories
-import "gorm.io/gorm"
+import (
+ "github.com/jkaninda/logger"
+ "gorm.io/gorm"
+)
-// ResourceScope defines the ownership context for a request.
-// If WorkspaceID is nil, the request is in personal mode.
-// If WorkspaceID is set, the request targets that workspace.
type ResourceScope struct {
UserID uint
WorkspaceID *uint
}
-// ApplyScope adds the appropriate WHERE clause to a GORM query.
-// Personal: user_id = ? AND workspace_id IS NULL
-// Workspace: workspace_id = ?
+var workspaceOnlyMode bool
+
+// SetWorkspaceOnlyMode enables or disables the R6 personal-mode lock.
+func SetWorkspaceOnlyMode(enabled bool) { workspaceOnlyMode = enabled }
+
func ApplyScope(db *gorm.DB, scope ResourceScope) *gorm.DB {
if scope.WorkspaceID != nil {
return db.Where("workspace_id = ?", *scope.WorkspaceID)
}
+ if workspaceOnlyMode {
+ logger.Warn("ApplyScope: personal-mode scope rejected (workspace-only mode)", "user_id", scope.UserID)
+ return db.Where("1 = 0")
+ }
return db.Where("user_id = ? AND workspace_id IS NULL", scope.UserID)
}
diff --git a/internal/storage/repositories/user_repo.go b/internal/storage/repositories/user_repo.go
index 06075b8..72b3499 100644
--- a/internal/storage/repositories/user_repo.go
+++ b/internal/storage/repositories/user_repo.go
@@ -52,6 +52,17 @@ func (r *UserRepository) FindByID(id uint) (*models.User, error) {
return &user, nil
}
+func (r *UserRepository) PersonalWorkspaceID(userID uint) (*uint, error) {
+ var user models.User
+ if err := r.db.Model(&models.User{}).
+ Select("personal_workspace_id").
+ Where("id = ?", userID).
+ First(&user).Error; err != nil {
+ return nil, err
+ }
+ return user.PersonalWorkspaceID, nil
+}
+
func (r *UserRepository) FindAll(limit, offset int) ([]models.User, int64, error) {
var users []models.User
var total int64
@@ -93,6 +104,10 @@ func (r *UserRepository) DeleteAllUserData(userID uint) error {
if err := tx.Exec("DELETE FROM subscriber_list_members WHERE list_id IN (SELECT id FROM subscriber_lists WHERE user_id = ?)", userID).Error; err != nil {
return err
}
+ // Delete subscriber_list_unsubscribes via subscriber_lists
+ if err := tx.Exec("DELETE FROM subscriber_list_unsubscribes WHERE list_id IN (SELECT id FROM subscriber_lists WHERE user_id = ?)", userID).Error; err != nil {
+ return err
+ }
// Clear active_version_id FK on templates before deleting versions
if err := tx.Exec("UPDATE templates SET active_version_id = NULL WHERE user_id = ?", userID).Error; err != nil {
return err
@@ -119,12 +134,15 @@ func (r *UserRepository) DeleteAllUserData(userID uint) error {
"style_sheets",
"languages",
"contacts",
+ "unsubscribe_lists",
"emails",
+ "inbound_emails",
"api_keys",
"webhooks",
"domains",
"smtp_servers",
"user_settings",
+ "user_email_verifications",
"o_auth_accounts",
}
diff --git a/internal/storage/repositories/workspace_repo.go b/internal/storage/repositories/workspace_repo.go
index b2426d4..a395ab5 100644
--- a/internal/storage/repositories/workspace_repo.go
+++ b/internal/storage/repositories/workspace_repo.go
@@ -68,6 +68,17 @@ func (r *WorkspaceRepository) FindBySlug(slug string) (*models.Workspace, error)
return &ws, nil
}
+// FindAll returns every workspace, oldest first. Used by platform cron jobs
+// (api-key-expiry, bounce-alert, daily-report) that operate across all
+// workspaces.
+func (r *WorkspaceRepository) FindAll() ([]models.Workspace, error) {
+ var workspaces []models.Workspace
+ if err := r.db.Order("id ASC").Find(&workspaces).Error; err != nil {
+ return nil, err
+ }
+ return workspaces, nil
+}
+
// FindByUserID returns all workspaces the user is a member of.
func (r *WorkspaceRepository) FindByUserID(userID uint) ([]models.Workspace, error) {
var workspaces []models.Workspace
diff --git a/internal/storage/repositories/workspace_setting_repo.go b/internal/storage/repositories/workspace_setting_repo.go
new file mode 100644
index 0000000..a0ba065
--- /dev/null
+++ b/internal/storage/repositories/workspace_setting_repo.go
@@ -0,0 +1,73 @@
+/*
+ * Copyright 2026 Jonas Kaninda
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package repositories
+
+import (
+ "github.com/goposta/posta/internal/models"
+ "gorm.io/gorm"
+)
+
+type WorkspaceSettingRepository struct {
+ db *gorm.DB
+}
+
+func NewWorkspaceSettingRepository(db *gorm.DB) *WorkspaceSettingRepository {
+ return &WorkspaceSettingRepository{db: db}
+}
+
+// FindByWorkspaceID returns the workspace's settings, creating a default row if
+// none exists. Mirrors UserSettingRepository.FindByUserID.
+func (r *WorkspaceSettingRepository) FindByWorkspaceID(workspaceID uint) (*models.WorkspaceSetting, error) {
+ var setting models.WorkspaceSetting
+ result := r.db.Where("workspace_id = ?", workspaceID).First(&setting)
+ if result.Error == nil {
+ return &setting, nil
+ }
+ if result.Error == gorm.ErrRecordNotFound {
+ setting = models.WorkspaceSetting{
+ WorkspaceID: workspaceID,
+ Timezone: "UTC",
+ WebhookRetryCount: 3,
+ APIKeyExpiryDays: 90,
+ BounceAutoSuppress: true,
+ }
+ if err := r.db.Create(&setting).Error; err != nil {
+ return nil, err
+ }
+ return &setting, nil
+ }
+ return nil, result.Error
+}
+
+// CreateOrUpdate saves or updates the workspace's settings row.
+func (r *WorkspaceSettingRepository) CreateOrUpdate(setting *models.WorkspaceSetting) error {
+ return r.db.Save(setting).Error
+}
+
+// RequireVerifiedDomain reports whether strict domain mode is enabled for the
+// workspace. A focused read for the email-send hot path that does not
+// auto-create a settings row; returns false when no row exists.
+func (r *WorkspaceSettingRepository) RequireVerifiedDomain(workspaceID uint) bool {
+ var setting models.WorkspaceSetting
+ if err := r.db.Select("require_verified_domain").
+ Where("workspace_id = ?", workspaceID).
+ First(&setting).Error; err != nil {
+ return false
+ }
+ return setting.RequireVerifiedDomain
+}
diff --git a/internal/worker/campaign_processor.go b/internal/worker/campaign_processor.go
index a1f582c..b81e728 100644
--- a/internal/worker/campaign_processor.go
+++ b/internal/worker/campaign_processor.go
@@ -127,9 +127,6 @@ func (p *CampaignProcessor) HandleCampaignStart(_ context.Context, t *asynq.Task
return nil
}
- // Pull list-scoped opt-outs once. Required for dynamic lists (where the
- // filter rules can re-include a previously-unsubscribed subscriber on the
- // next send) and a defense-in-depth check for static lists.
suppressed, sErr := p.listRepo.SuppressedSubscriberIDs(campaign.ListID)
if sErr != nil {
logger.Warn("campaign: failed to load list suppressions, proceeding without", "list_id", campaign.ListID, "error", sErr)
diff --git a/internal/worker/daily_report_handler.go b/internal/worker/daily_report_handler.go
index 0b4b6f7..f53aa0f 100644
--- a/internal/worker/daily_report_handler.go
+++ b/internal/worker/daily_report_handler.go
@@ -50,15 +50,15 @@ func NewDailyReportHandler(
}
}
-// ProcessTask handles a daily report task for a single user.
+// ProcessTask handles a daily report task for a single workspace.
func (h *DailyReportHandler) ProcessTask(_ context.Context, t *asynq.Task) error {
var payload jobs.DailyReportPayload
if err := json.Unmarshal(t.Payload(), &payload); err != nil {
return fmt.Errorf("daily report: invalid payload: %w", err)
}
- userID := payload.UserID
- logger.Info("daily report: processing", "user_id", userID)
+ workspaceID := payload.WorkspaceID
+ logger.Info("daily report: processing", "workspace_id", workspaceID)
// Yesterday's date range
now := time.Now().UTC()
@@ -67,9 +67,9 @@ func (h *DailyReportHandler) ProcessTask(_ context.Context, t *asynq.Task) error
to := time.Date(yesterday.Year(), yesterday.Month(), yesterday.Day(), 23, 59, 59, 0, time.UTC)
// Gather stats
- breakdown, err := h.analyticsRepo.StatusBreakdown(userID, from, to)
+ breakdown, err := h.analyticsRepo.WorkspaceStatusBreakdown(workspaceID, from, to)
if err != nil {
- logger.Error("daily report: failed to get stats", "user_id", userID, "error", err)
+ logger.Error("daily report: failed to get stats", "workspace_id", workspaceID, "error", err)
return err
}
@@ -89,7 +89,7 @@ func (h *DailyReportHandler) ProcessTask(_ context.Context, t *asynq.Task) error
// Count bounces for the period
var bounced int64
if h.bounceRepo != nil {
- bounced, _ = h.bounceRepo.CountByUserAndDateRange(userID, from, to)
+ bounced, _ = h.bounceRepo.CountByWorkspaceAndDateRange(workspaceID, from, to)
}
var deliveryRate float64
@@ -108,11 +108,11 @@ func (h *DailyReportHandler) ProcessTask(_ context.Context, t *asynq.Task) error
}
subject := fmt.Sprintf("Daily Email Report — %s", yesterday.Format("Jan 2, 2006"))
- if err := h.notifier.SendToUser(userID, subject, notification.TemplateDailyReport, data); err != nil {
- logger.Error("daily report: failed to send", "user_id", userID, "error", err)
+ if err := h.notifier.SendToWorkspaceAdmins(workspaceID, subject, notification.TemplateDailyReport, data); err != nil {
+ logger.Error("daily report: failed to send", "workspace_id", workspaceID, "error", err)
return err
}
- logger.Info("daily report: sent", "user_id", userID)
+ logger.Info("daily report: sent", "workspace_id", workspaceID)
return nil
}
diff --git a/web/src/api/analytics.ts b/web/src/api/analytics.ts
index a01131a..db572dc 100644
--- a/web/src/api/analytics.ts
+++ b/web/src/api/analytics.ts
@@ -7,7 +7,7 @@ export const analyticsApi = {
if (from) params.from = from
if (to) params.to = to
if (status) params.status = status
- return api.get<ApiResponse<AnalyticsResponse>>('/users/me/analytics', { params })
+ return api.get<ApiResponse<AnalyticsResponse>>('/workspaces/current/analytics', { params })
},
admin(from?: string, to?: string, status?: string) {
const params: Record<string, string> = {}
@@ -20,7 +20,7 @@ export const analyticsApi = {
const params: Record<string, string> = {}
if (from) params.from = from
if (to) params.to = to
- return api.get<ApiResponse<DashboardAnalyticsResponse>>('/users/me/analytics/dashboard', { params })
+ return api.get<ApiResponse<DashboardAnalyticsResponse>>('/workspaces/current/analytics/dashboard', { params })
},
adminDashboardAnalytics(from?: string, to?: string) {
const params: Record<string, string> = {}
@@ -32,7 +32,7 @@ export const analyticsApi = {
const params: Record<string, string> = {}
if (from) params.from = from
if (to) params.to = to
- return api.get<ApiResponse<ProviderBreakdownResponse>>('/users/me/analytics/providers', { params })
+ return api.get<ApiResponse<ProviderBreakdownResponse>>('/workspaces/current/analytics/providers', { params })
},
adminProviderBreakdown(from?: string, to?: string) {
const params: Record<string, string> = {}
diff --git a/web/src/api/apikeys.ts b/web/src/api/apikeys.ts
index 85a9410..0fd32fa 100644
--- a/web/src/api/apikeys.ts
+++ b/web/src/api/apikeys.ts
@@ -3,18 +3,18 @@ import type { ApiResponse, PaginatedResponse, ApiKey, ApiKeyCreateResponse } fro
export const apiKeysApi = {
list(page = 0, size = 20) {
- return api.get<PaginatedResponse<ApiKey>>('/users/me/api-keys', { params: { page, size } })
+ return api.get<PaginatedResponse<ApiKey>>('/workspaces/current/api-keys', { params: { page, size } })
},
create(name: string, allowedIPs?: string[], expiresInDays?: number) {
const body: Record<string, any> = { name }
if (allowedIPs && allowedIPs.length > 0) body.allowed_ips = allowedIPs
if (expiresInDays !== undefined) body.expires_in_days = expiresInDays
- return api.post<ApiResponse<ApiKeyCreateResponse>>('/users/me/api-keys', body)
+ return api.post<ApiResponse<ApiKeyCreateResponse>>('/workspaces/current/api-keys', body)
},
revoke(id: number) {
- return api.put(`/users/me/api-keys/${id}/revoke`)
+ return api.put(`/workspaces/current/api-keys/${id}/revoke`)
},
delete(id: number) {
- return api.delete(`/users/me/api-keys/${id}`)
+ return api.delete(`/workspaces/current/api-keys/${id}`)
},
}
diff --git a/web/src/api/audit.ts b/web/src/api/audit.ts
index f180e8a..12ba0b1 100644
--- a/web/src/api/audit.ts
+++ b/web/src/api/audit.ts
@@ -2,9 +2,11 @@ import api from './client'
import type { PaginatedResponse, Event } from './types'
export const auditApi = {
+ // Workspace audit log. The X-Posta-Workspace-Id header (injected by the
+ // workspace store) scopes this to the active workspace.
list(page = 0, size = 20, category?: string) {
const params: Record<string, any> = { page, size }
if (category) params.category = category
- return api.get<PaginatedResponse<Event>>('/users/me/audit-log', { params })
+ return api.get<PaginatedResponse<Event>>('/workspaces/current/audit-log', { params })
},
}
diff --git a/web/src/api/bounces.ts b/web/src/api/bounces.ts
index 220b362..c8c8bf0 100644
--- a/web/src/api/bounces.ts
+++ b/web/src/api/bounces.ts
@@ -3,10 +3,10 @@ import type { PaginatedResponse, Bounce, Suppression, ApiResponse } from './type
export const bouncesApi = {
list(page = 0, size = 20) {
- return api.get<PaginatedResponse<Bounce>>('/users/me/bounces', { params: { page, size } })
+ return api.get<PaginatedResponse<Bounce>>('/workspaces/current/bounces', { params: { page, size } })
},
create(data: { email_id: number; recipient: string; type: string; reason: string }) {
- return api.post<ApiResponse<Bounce>>('/users/me/bounces', data)
+ return api.post<ApiResponse<Bounce>>('/workspaces/current/bounces', data)
},
}
@@ -14,14 +14,14 @@ export const suppressionsApi = {
list(page = 0, size = 20, listId?: number) {
const params: Record<string, number> = { page, size }
if (listId) params.list_id = listId
- return api.get<PaginatedResponse<Suppression>>('/users/me/suppressions', { params })
+ return api.get<PaginatedResponse<Suppression>>('/workspaces/current/suppressions', { params })
},
create(data: { email: string; reason: string; list_id?: number }) {
- return api.post<ApiResponse<Suppression>>('/users/me/suppressions', data)
+ return api.post<ApiResponse<Suppression>>('/workspaces/current/suppressions', data)
},
delete(email: string, listId?: number) {
const body: Record<string, string | number> = { email }
if (listId) body.list_id = listId
- return api.delete('/users/me/suppressions', { data: body })
+ return api.delete('/workspaces/current/suppressions', { data: body })
},
}
diff --git a/web/src/api/campaigns.ts b/web/src/api/campaigns.ts
index c192486..1a501c8 100644
--- a/web/src/api/campaigns.ts
+++ b/web/src/api/campaigns.ts
@@ -3,10 +3,10 @@ import type { ApiResponse, PaginatedResponse, Campaign, CampaignMessage, Campaig
export const campaignsApi = {
list(page = 0, size = 20, status?: string) {
- return api.get<PaginatedResponse<Campaign>>('/users/me/campaigns', { params: { page, size, status } })
+ return api.get<PaginatedResponse<Campaign>>('/workspaces/current/campaigns', { params: { page, size, status } })
},
get(id: number) {
- return api.get<ApiResponse<Campaign>>(`/users/me/campaigns/${id}`)
+ return api.get<ApiResponse<Campaign>>(`/workspaces/current/campaigns/${id}`)
},
create(data: {
name: string
@@ -21,7 +21,7 @@ export const campaignsApi = {
send_rate?: number
scheduled_at?: string
}) {
- return api.post<ApiResponse<Campaign>>('/users/me/campaigns', data)
+ return api.post<ApiResponse<Campaign>>('/workspaces/current/campaigns', data)
},
update(id: number, data: Partial<{
name: string
@@ -36,27 +36,27 @@ export const campaignsApi = {
send_rate: number
scheduled_at: string
}>) {
- return api.put<ApiResponse<Campaign>>(`/users/me/campaigns/${id}`, data)
+ return api.put<ApiResponse<Campaign>>(`/workspaces/current/campaigns/${id}`, data)
},
delete(id: number) {
- return api.delete(`/users/me/campaigns/${id}`)
+ return api.delete(`/workspaces/current/campaigns/${id}`)
},
send(id: number) {
- return api.post<ApiResponse<Campaign>>(`/users/me/campaigns/${id}/send`)
+ return api.post<ApiResponse<Campaign>>(`/workspaces/current/campaigns/${id}/send`)
},
pause(id: number) {
- return api.post<ApiResponse<Campaign>>(`/users/me/campaigns/${id}/pause`)
+ return api.post<ApiResponse<Campaign>>(`/workspaces/current/campaigns/${id}/pause`)
},
resume(id: number) {
- return api.post<ApiResponse<Campaign>>(`/users/me/campaigns/${id}/resume`)
+ return api.post<ApiResponse<Campaign>>(`/workspaces/current/campaigns/${id}/resume`)
},
cancel(id: number) {
- return api.post<ApiResponse<Campaign>>(`/users/me/campaigns/${id}/cancel`)
+ return api.post<ApiResponse<Campaign>>(`/workspaces/current/campaigns/${id}/cancel`)
},
listMessages(id: number, page = 0, size = 20, status?: string) {
- return api.get<PaginatedResponse<CampaignMessage>>(`/users/me/campaigns/${id}/messages`, { params: { page, size, status } })
+ return api.get<PaginatedResponse<CampaignMessage>>(`/workspaces/current/campaigns/${id}/messages`, { params: { page, size, status } })
},
analytics(id: number) {
- return api.get<ApiResponse<CampaignAnalyticsData>>(`/users/me/campaigns/${id}/analytics`)
+ return api.get<ApiResponse<CampaignAnalyticsData>>(`/workspaces/current/campaigns/${id}/analytics`)
},
}
diff --git a/web/src/api/contacts.ts b/web/src/api/contacts.ts
index 9e5fc4b..c853b79 100644
--- a/web/src/api/contacts.ts
+++ b/web/src/api/contacts.ts
@@ -3,9 +3,9 @@ import type { ApiResponse, PaginatedResponse, Contact } from './types'
export const contactsApi = {
list(page = 0, size = 20, search = '') {
- return api.get<PaginatedResponse<Contact>>('/users/me/contacts', { params: { page, size, search: search || undefined } })
+ return api.get<PaginatedResponse<Contact>>('/workspaces/current/contacts', { params: { page, size, search: search || undefined } })
},
get(id: number) {
- return api.get<ApiResponse<Contact>>(`/users/me/contacts/${id}`)
+ return api.get<ApiResponse<Contact>>(`/workspaces/current/contacts/${id}`)
},
}
diff --git a/web/src/api/dashboard.ts b/web/src/api/dashboard.ts
index a9b2682..aa8e1fd 100644
--- a/web/src/api/dashboard.ts
+++ b/web/src/api/dashboard.ts
@@ -3,6 +3,6 @@ import type { ApiResponse, DashboardStats } from './types'
export const dashboardApi = {
getStats() {
- return api.get<ApiResponse<DashboardStats>>('/users/me/dashboard/stats')
+ return api.get<ApiResponse<DashboardStats>>('/workspaces/current/dashboard/stats')
},
}
diff --git a/web/src/api/domains.ts b/web/src/api/domains.ts
index 35aa2bf..8e2a397 100644
--- a/web/src/api/domains.ts
+++ b/web/src/api/domains.ts
@@ -3,18 +3,18 @@ import type { ApiResponse, PaginatedResponse, Domain } from './types'
export const domainsApi = {
list(page = 0, size = 20) {
- return api.get<PaginatedResponse<Domain>>('/users/me/domains', { params: { page, size } })
+ return api.get<PaginatedResponse<Domain>>('/workspaces/current/domains', { params: { page, size } })
},
get(id: number) {
- return api.get<ApiResponse<Domain>>(`/users/me/domains/${id}`)
+ return api.get<ApiResponse<Domain>>(`/workspaces/current/domains/${id}`)
},
create(domain: string) {
- return api.post<ApiResponse<Domain>>('/users/me/domains', { domain })
+ return api.post<ApiResponse<Domain>>('/workspaces/current/domains', { domain })
},
verify(id: number) {
- return api.post<ApiResponse<Domain>>(`/users/me/domains/${id}/verify`)
+ return api.post<ApiResponse<Domain>>(`/workspaces/current/domains/${id}/verify`)
},
delete(id: number) {
- return api.delete(`/users/me/domains/${id}`)
+ return api.delete(`/workspaces/current/domains/${id}`)
},
}
diff --git a/web/src/api/emails.ts b/web/src/api/emails.ts
index 3be6cfd..0d6c8ae 100644
--- a/web/src/api/emails.ts
+++ b/web/src/api/emails.ts
@@ -20,15 +20,15 @@ export interface EmailPreviewResponse {
export const emailsApi = {
list(page = 0, size = 20) {
- return api.get<PaginatedResponse<Email>>('/users/me/emails', { params: { page, size } })
+ return api.get<PaginatedResponse<Email>>('/workspaces/current/emails', { params: { page, size } })
},
get(uuid: string) {
- return api.get<ApiResponse<Email>>(`/users/me/emails/${uuid}`)
+ return api.get<ApiResponse<Email>>(`/workspaces/current/emails/${uuid}`)
},
retry(uuid: string) {
- return api.post<ApiResponse<RetryResponse>>(`/users/me/emails/${uuid}/retry`)
+ return api.post<ApiResponse<RetryResponse>>(`/workspaces/current/emails/${uuid}/retry`)
},
preview(data: EmailPreviewRequest) {
- return api.post<ApiResponse<EmailPreviewResponse>>('/users/me/emails/preview', data)
+ return api.post<ApiResponse<EmailPreviewResponse>>('/workspaces/current/emails/preview', data)
},
}
diff --git a/web/src/api/inbound.ts b/web/src/api/inbound.ts
index ede5a51..ca9146a 100644
--- a/web/src/api/inbound.ts
+++ b/web/src/api/inbound.ts
@@ -15,30 +15,43 @@ export interface InboundRetryResponse {
status: string
}
+const WORKSPACE_KEY = 'posta_workspace_id'
+
+// Browser-direct requests (download links, EventSource) cannot set the
+// X-Posta-Workspace-Id header, so the active workspace travels as a query
+// parameter that the backend's WorkspaceFromQueryOrHeader middleware reads.
+function workspaceParam(): string {
+ const ws = localStorage.getItem(WORKSPACE_KEY)
+ return ws ? `workspace_id=${encodeURIComponent(ws)}` : ''
+}
+
export const inboundApi = {
list(params: InboundListParams = {}) {
- return api.get<PaginatedResponse<InboundEmail>>('/users/me/inbound-emails', {
+ return api.get<PaginatedResponse<InboundEmail>>('/workspaces/current/inbound-emails', {
params: { page: 0, size: 20, ...params },
})
},
get(uuid: string) {
- return api.get<ApiResponse<InboundEmail>>(`/users/me/inbound-emails/${uuid}`)
+ return api.get<ApiResponse<InboundEmail>>(`/workspaces/current/inbound-emails/${uuid}`)
},
delete(uuid: string) {
- return api.delete<ApiResponse<void>>(`/users/me/inbound-emails/${uuid}`)
+ return api.delete<ApiResponse<void>>(`/workspaces/current/inbound-emails/${uuid}`)
},
retry(uuid: string) {
- return api.post<ApiResponse<InboundRetryResponse>>(`/users/me/inbound-emails/${uuid}/retry`)
+ return api.post<ApiResponse<InboundRetryResponse>>(`/workspaces/current/inbound-emails/${uuid}/retry`)
},
rawUrl(uuid: string) {
- return `/api/v1/users/me/inbound-emails/${uuid}/raw`
+ const ws = workspaceParam()
+ return `/api/v1/workspaces/current/inbound-emails/${uuid}/raw${ws ? `?${ws}` : ''}`
},
attachmentUrl(uuid: string, idx: number) {
- return `/api/v1/users/me/inbound-emails/${uuid}/attachments/${idx}`
+ const ws = workspaceParam()
+ return `/api/v1/workspaces/current/inbound-emails/${uuid}/attachments/${idx}${ws ? `?${ws}` : ''}`
},
streamUrl(token?: string) {
const t = token ?? localStorage.getItem('posta_token') ?? ''
- const qs = t ? `?token=${encodeURIComponent(t)}` : ''
- return `/api/v1/users/me/inbound-stream${qs}`
+ const parts = [t ? `token=${encodeURIComponent(t)}` : '', workspaceParam()].filter(Boolean)
+ const qs = parts.length ? `?${parts.join('&')}` : ''
+ return `/api/v1/workspaces/current/inbound-stream${qs}`
},
}
diff --git a/web/src/api/languages.ts b/web/src/api/languages.ts
index 25bda33..0c261f7 100644
--- a/web/src/api/languages.ts
+++ b/web/src/api/languages.ts
@@ -3,15 +3,15 @@ import type { ApiResponse, PaginatedResponse, Language, LanguageInput } from './
export const languagesApi = {
list(page = 0, size = 100) {
- return api.get<PaginatedResponse<Language>>('/users/me/languages', { params: { page, size } })
+ return api.get<PaginatedResponse<Language>>('/workspaces/current/languages', { params: { page, size } })
},
create(data: LanguageInput) {
- return api.post<ApiResponse<Language>>('/users/me/languages', data)
+ return api.post<ApiResponse<Language>>('/workspaces/current/languages', data)
},
update(id: number, data: Partial<LanguageInput>) {
- return api.put<ApiResponse<Language>>(`/users/me/languages/${id}`, data)
+ return api.put<ApiResponse<Language>>(`/workspaces/current/languages/${id}`, data)
},
delete(id: number) {
- return api.delete(`/users/me/languages/${id}`)
+ return api.delete(`/workspaces/current/languages/${id}`)
},
}
diff --git a/web/src/api/settings.ts b/web/src/api/settings.ts
index 545943b..1358ebc 100644
--- a/web/src/api/settings.ts
+++ b/web/src/api/settings.ts
@@ -1,5 +1,5 @@
import api from './client'
-import type { ApiResponse, AdminSetting, AdminSettingInput, UserSettings } from './types'
+import type { ApiResponse, AdminSetting, AdminSettingInput, UserSettings, WorkspaceSettings } from './types'
export const settingsApi = {
// Admin platform settings
@@ -10,11 +10,23 @@ export const settingsApi = {
return api.put<ApiResponse<AdminSetting[]>>('/admin/settings', { settings })
},
- // User settings
+ // User settings — personal notification preferences only after the
+ // workspace-only migration cutover.
getUserSettings() {
return api.get<ApiResponse<UserSettings>>('/users/me/settings')
},
updateUserSettings(data: Partial<Omit<UserSettings, 'id' | 'user_id' | 'created_at' | 'updated_at'>>) {
return api.put<ApiResponse<UserSettings>>('/users/me/settings', data)
},
+
+ // Workspace operational settings (timezone, sender defaults, webhook retries,
+ // API-key expiry, bounce auto-suppress). Scoped via X-Posta-Workspace-Id.
+ getWorkspaceSettings() {
+ return api.get<ApiResponse<WorkspaceSettings>>('/workspaces/current/settings')
+ },
+ updateWorkspaceSettings(
+ data: Partial<Omit<WorkspaceSettings, 'id' | 'workspace_id' | 'created_at' | 'updated_at'>>
+ ) {
+ return api.put<ApiResponse<WorkspaceSettings>>('/workspaces/current/settings', data)
+ },
}
diff --git a/web/src/api/smtp.ts b/web/src/api/smtp.ts
index 555b9bb..507e86f 100644
--- a/web/src/api/smtp.ts
+++ b/web/src/api/smtp.ts
@@ -3,21 +3,21 @@ import type { ApiResponse, PaginatedResponse, SmtpServer, SmtpServerInput } from
export const smtpApi = {
list(page = 0, size = 20) {
- return api.get<PaginatedResponse<SmtpServer>>('/users/me/smtp-servers', { params: { page, size } })
+ return api.get<PaginatedResponse<SmtpServer>>('/workspaces/current/smtp-servers', { params: { page, size } })
},
get(id: number) {
- return api.get<ApiResponse<SmtpServer>>(`/users/me/smtp-servers/${id}`)
+ return api.get<ApiResponse<SmtpServer>>(`/workspaces/current/smtp-servers/${id}`)
},
create(data: SmtpServerInput) {
- return api.post<ApiResponse<SmtpServer>>('/users/me/smtp-servers', data)
+ return api.post<ApiResponse<SmtpServer>>('/workspaces/current/smtp-servers', data)
},
update(id: number, data: Partial<SmtpServerInput>) {
- return api.put<ApiResponse<SmtpServer>>(`/users/me/smtp-servers/${id}`, data)
+ return api.put<ApiResponse<SmtpServer>>(`/workspaces/current/smtp-servers/${id}`, data)
},
delete(id: number) {
- return api.delete(`/users/me/smtp-servers/${id}`)
+ return api.delete(`/workspaces/current/smtp-servers/${id}`)
},
test(id: number) {
- return api.post(`/users/me/smtp-servers/${id}/test`)
+ return api.post(`/workspaces/current/smtp-servers/${id}/test`)
},
}
diff --git a/web/src/api/stylesheets.ts b/web/src/api/stylesheets.ts
index 540adec..58e7adf 100644
--- a/web/src/api/stylesheets.ts
+++ b/web/src/api/stylesheets.ts
@@ -3,15 +3,15 @@ import type { ApiResponse, PaginatedResponse, StyleSheet, StyleSheetInput } from
export const stylesheetsApi = {
list(page = 0, size = 100) {
- return api.get<PaginatedResponse<StyleSheet>>('/users/me/stylesheets', { params: { page, size } })
+ return api.get<PaginatedResponse<StyleSheet>>('/workspaces/current/stylesheets', { params: { page, size } })
},
create(data: StyleSheetInput) {
- return api.post<ApiResponse<StyleSheet>>('/users/me/stylesheets', data)
+ return api.post<ApiResponse<StyleSheet>>('/workspaces/current/stylesheets', data)
},
update(id: number, data: StyleSheetInput) {
- return api.put<ApiResponse<StyleSheet>>(`/users/me/stylesheets/${id}`, data)
+ return api.put<ApiResponse<StyleSheet>>(`/workspaces/current/stylesheets/${id}`, data)
},
delete(id: number) {
- return api.delete(`/users/me/stylesheets/${id}`)
+ return api.delete(`/workspaces/current/stylesheets/${id}`)
},
}
diff --git a/web/src/api/subscriberLists.ts b/web/src/api/subscriberLists.ts
index 21e5f0e..362277d 100644
--- a/web/src/api/subscriberLists.ts
+++ b/web/src/api/subscriberLists.ts
@@ -3,30 +3,30 @@ import type { ApiResponse, PaginatedResponse, SubscriberListItem, Subscriber, Fi
export const subscriberListsApi = {
list(page = 0, size = 20) {
- return api.get<PaginatedResponse<SubscriberListItem>>('/users/me/subscriber-lists', { params: { page, size } })
+ return api.get<PaginatedResponse<SubscriberListItem>>('/workspaces/current/subscriber-lists', { params: { page, size } })
},
get(id: number) {
- return api.get<ApiResponse<SubscriberListItem>>(`/users/me/subscriber-lists/${id}`)
+ return api.get<ApiResponse<SubscriberListItem>>(`/workspaces/current/subscriber-lists/${id}`)
},
create(data: { name: string; description: string; type: string; filter_rules?: FilterRule[] }) {
- return api.post<ApiResponse<SubscriberListItem>>('/users/me/subscriber-lists', data)
+ return api.post<ApiResponse<SubscriberListItem>>('/workspaces/current/subscriber-lists', data)
},
update(id: number, data: { name?: string; description?: string; filter_rules?: FilterRule[] }) {
- return api.put<ApiResponse<SubscriberListItem>>(`/users/me/subscriber-lists/${id}`, data)
+ return api.put<ApiResponse<SubscriberListItem>>(`/workspaces/current/subscriber-lists/${id}`, data)
},
delete(id: number) {
- return api.delete(`/users/me/subscriber-lists/${id}`)
+ return api.delete(`/workspaces/current/subscriber-lists/${id}`)
},
listMembers(id: number, page = 0, size = 20) {
- return api.get<PaginatedResponse<Subscriber>>(`/users/me/subscriber-lists/${id}/members`, { params: { page, size } })
+ return api.get<PaginatedResponse<Subscriber>>(`/workspaces/current/subscriber-lists/${id}/members`, { params: { page, size } })
},
addMember(id: number, subscriberId: number) {
- return api.post<ApiResponse<null>>(`/users/me/subscriber-lists/${id}/members`, { subscriber_id: subscriberId })
+ return api.post<ApiResponse<null>>(`/workspaces/current/subscriber-lists/${id}/members`, { subscriber_id: subscriberId })
},
removeMember(id: number, subscriberId: number) {
- return api.delete(`/users/me/subscriber-lists/${id}/members`, { data: { subscriber_id: subscriberId } })
+ return api.delete(`/workspaces/current/subscriber-lists/${id}/members`, { data: { subscriber_id: subscriberId } })
},
previewSegment(filterRules: FilterRule[]) {
- return api.post<PaginatedResponse<Subscriber>>('/users/me/subscriber-lists/preview', { filter_rules: filterRules })
+ return api.post<PaginatedResponse<Subscriber>>('/workspaces/current/subscriber-lists/preview', { filter_rules: filterRules })
},
}
diff --git a/web/src/api/subscribers.ts b/web/src/api/subscribers.ts
index 3206f35..9e1866d 100644
--- a/web/src/api/subscribers.ts
+++ b/web/src/api/subscribers.ts
@@ -3,24 +3,24 @@ import type { ApiResponse, PaginatedResponse, Subscriber, BulkImportResult, Subs
export const subscribersApi = {
list(page = 0, size = 20, search = '', status?: SubscriberStatus) {
- return api.get<PaginatedResponse<Subscriber>>('/users/me/subscribers', {
+ return api.get<PaginatedResponse<Subscriber>>('/workspaces/current/subscribers', {
params: { page, size, search: search || undefined, status: status || undefined },
})
},
get(id: number) {
- return api.get<ApiResponse<Subscriber>>(`/users/me/subscribers/${id}`)
+ return api.get<ApiResponse<Subscriber>>(`/workspaces/current/subscribers/${id}`)
},
create(data: { email: string; name: string; custom_fields?: Record<string, any> }) {
- return api.post<ApiResponse<Subscriber>>('/users/me/subscribers', data)
+ return api.post<ApiResponse<Subscriber>>('/workspaces/current/subscribers', data)
},
update(id: number, data: { email?: string; name?: string; status?: SubscriberStatus; custom_fields?: Record<string, any> }) {
- return api.put<ApiResponse<Subscriber>>(`/users/me/subscribers/${id}`, data)
+ return api.put<ApiResponse<Subscriber>>(`/workspaces/current/subscribers/${id}`, data)
},
delete(id: number) {
- return api.delete(`/users/me/subscribers/${id}`)
+ return api.delete(`/workspaces/current/subscribers/${id}`)
},
bulkImportJSON(subscribers: { email: string; name?: string; custom_fields?: Record<string, any> }[]) {
- return api.post<ApiResponse<BulkImportResult>>('/users/me/subscribers/import/json', { subscribers })
+ return api.post<ApiResponse<BulkImportResult>>('/workspaces/current/subscribers/import/json', { subscribers })
},
bulkImportCSV(file: File, columnMapping?: Record<string, string>) {
const formData = new FormData()
@@ -28,7 +28,7 @@ export const subscribersApi = {
if (columnMapping) {
formData.append('column_mapping', JSON.stringify(columnMapping))
}
- return api.post<ApiResponse<BulkImportResult>>('/users/me/subscribers/import/csv', formData, {
+ return api.post<ApiResponse<BulkImportResult>>('/workspaces/current/subscribers/import/csv', formData, {
headers: { 'Content-Type': 'multipart/form-data' },
})
},
diff --git a/web/src/api/templates.ts b/web/src/api/templates.ts
index 5096e45..97bc1f8 100644
--- a/web/src/api/templates.ts
+++ b/web/src/api/templates.ts
@@ -16,50 +16,50 @@ import type {
export const templatesApi = {
list(page = 0, size = 20, search = '') {
- return api.get<PaginatedResponse<Template>>('/users/me/templates', { params: { page, size, search } })
+ return api.get<PaginatedResponse<Template>>('/workspaces/current/templates', { params: { page, size, search } })
},
create(data: TemplateInput) {
- return api.post<ApiResponse<Template>>('/users/me/templates', data)
+ return api.post<ApiResponse<Template>>('/workspaces/current/templates', data)
},
update(id: number, data: Partial<TemplateInput>) {
- return api.put<ApiResponse<Template>>(`/users/me/templates/${id}`, data)
+ return api.put<ApiResponse<Template>>(`/workspaces/current/templates/${id}`, data)
},
delete(id: number) {
- return api.delete(`/users/me/templates/${id}`)
+ return api.delete(`/workspaces/current/templates/${id}`)
},
// Versions
listVersions(templateId: number) {
- return api.get<ApiResponse<TemplateVersion[]>>(`/users/me/templates/${templateId}/versions`)
+ return api.get<ApiResponse<TemplateVersion[]>>(`/workspaces/current/templates/${templateId}/versions`)
},
createVersion(templateId: number, data: TemplateVersionInput) {
- return api.post<ApiResponse<TemplateVersion>>(`/users/me/templates/${templateId}/versions`, data)
+ return api.post<ApiResponse<TemplateVersion>>(`/workspaces/current/templates/${templateId}/versions`, data)
},
updateVersion(templateId: number, versionId: number, data: Partial<TemplateVersionInput>) {
- return api.put<ApiResponse<TemplateVersion>>(`/users/me/templates/${templateId}/versions/${versionId}`, data)
+ return api.put<ApiResponse<TemplateVersion>>(`/workspaces/current/templates/${templateId}/versions/${versionId}`, data)
},
activateVersion(templateId: number, versionId: number) {
- return api.post<ApiResponse<Template>>(`/users/me/templates/${templateId}/activate/${versionId}`)
+ return api.post<ApiResponse<Template>>(`/workspaces/current/templates/${templateId}/activate/${versionId}`)
},
deleteVersion(templateId: number, versionId: number) {
- return api.delete(`/users/me/templates/${templateId}/versions/${versionId}`)
+ return api.delete(`/workspaces/current/templates/${templateId}/versions/${versionId}`)
},
// Localizations
listLocalizations(templateId: number, versionId: number) {
- return api.get<ApiResponse<TemplateLocalization[]>>(`/users/me/templates/${templateId}/versions/${versionId}/localizations`)
+ return api.get<ApiResponse<TemplateLocalization[]>>(`/workspaces/current/templates/${templateId}/versions/${versionId}/localizations`)
},
createLocalization(templateId: number, versionId: number, data: TemplateLocalizationInput) {
- return api.post<ApiResponse<TemplateLocalization>>(`/users/me/templates/${templateId}/versions/${versionId}/localizations`, data)
+ return api.post<ApiResponse<TemplateLocalization>>(`/workspaces/current/templates/${templateId}/versions/${versionId}/localizations`, data)
},
updateLocalization(localizationId: number, data: Partial<Omit<TemplateLocalizationInput, 'language'>>) {
- return api.put<ApiResponse<TemplateLocalization>>(`/users/me/localizations/${localizationId}`, data)
+ return api.put<ApiResponse<TemplateLocalization>>(`/workspaces/current/localizations/${localizationId}`, data)
},
deleteLocalization(localizationId: number) {
- return api.delete(`/users/me/localizations/${localizationId}`)
+ return api.delete(`/workspaces/current/localizations/${localizationId}`)
},
previewLocalization(templateId: number, versionId: number, data: { language: string; template_data: Record<string, any> }) {
- return api.post<ApiResponse<TemplatePreview>>(`/users/me/templates/${templateId}/versions/${versionId}/preview`, data)
+ return api.post<ApiResponse<TemplatePreview>>(`/workspaces/current/templates/${templateId}/versions/${versionId}/preview`, data)
},
// Renders raw, unsaved template content so the editor can show a live preview
// without persisting first.
@@ -70,24 +70,24 @@ export const templatesApi = {
stylesheet_id?: number | null
template_data?: Record<string, any>
}) {
- return api.post<ApiResponse<TemplatePreview>>('/users/me/templates/preview', data)
+ return api.post<ApiResponse<TemplatePreview>>('/workspaces/current/templates/preview', data)
},
sendTest(templateId: number, data: SendTestInput) {
- return api.post<ApiResponse<SendTestResponse>>(`/users/me/templates/${templateId}/send-test`, data)
+ return api.post<ApiResponse<SendTestResponse>>(`/workspaces/current/templates/${templateId}/send-test`, data)
},
// Import/Export
exportTemplate(templateId: number) {
- return api.get<ApiResponse<TemplateExport>>(`/users/me/templates/${templateId}/export`)
+ return api.get<ApiResponse<TemplateExport>>(`/workspaces/current/templates/${templateId}/export`)
},
importTemplate(data: TemplateExport) {
- return api.post<ApiResponse<Template>>('/users/me/templates/import', data)
+ return api.post<ApiResponse<Template>>('/workspaces/current/templates/import', data)
},
importHTML(file: File) {
const formData = new FormData()
formData.append('file', file)
- return api.post<ApiResponse<Template>>('/users/me/templates/import-html', formData, {
+ return api.post<ApiResponse<Template>>('/workspaces/current/templates/import-html', formData, {
headers: { 'Content-Type': 'multipart/form-data' },
})
},
diff --git a/web/src/api/types.ts b/web/src/api/types.ts
index 2af736e..d1a65c6 100644
--- a/web/src/api/types.ts
+++ b/web/src/api/types.ts
@@ -680,19 +680,6 @@ export interface UserProfile extends User {
}
// User Data Export/Import
-export interface UserDataExport {
- posta_version?: string
- exported_at?: string
- templates: TemplateExport[]
- stylesheets: ExportStyleSheet[]
- languages: ExportLanguage[]
- contacts: ExportContact[]
- contact_lists: ExportContactList[]
- suppressions: ExportSuppression[]
- webhooks: ExportWebhook[]
- settings?: ExportUserSettings
-}
-
export interface ExportStyleSheet {
name: string
css: string
@@ -813,9 +800,26 @@ export interface Workspace {
description: string
owner_id: number
role: WorkspaceRole
+ is_personal: boolean
created_at: string
}
+// Operational settings that live on the workspace (not the user). Personal
+// notification preferences stay on UserSettings.
+export interface WorkspaceSettings {
+ id: number
+ workspace_id: number
+ timezone: string
+ default_sender_name: string
+ default_sender_email: string
+ webhook_retry_count: number
+ api_key_expiry_days: number
+ bounce_auto_suppress: boolean
+ require_verified_domain: boolean
+ created_at: string
+ updated_at: string
+}
+
export interface WorkspaceInput {
name: string
slug?: string
@@ -847,17 +851,6 @@ export interface InviteMemberInput {
role: WorkspaceRole
}
-export interface TransferResult {
- resource: string
- count: number
-}
-
-export interface TransferResponse {
- message: string
- results: TransferResult[]
- total: number
-}
-
// OAuth
export interface OAuthProviderInfo {
id: number
diff --git a/web/src/api/unsubscribeLists.ts b/web/src/api/unsubscribeLists.ts
index b47c644..74b8443 100644
--- a/web/src/api/unsubscribeLists.ts
+++ b/web/src/api/unsubscribeLists.ts
@@ -3,18 +3,18 @@ import type { ApiResponse, PaginatedResponse, UnsubscribeListItem, UnsubscribeLi
export const unsubscribeListsApi = {
list(page = 0, size = 20) {
- return api.get<PaginatedResponse<UnsubscribeListItem>>('/users/me/unsubscribe-lists', { params: { page, size } })
+ return api.get<PaginatedResponse<UnsubscribeListItem>>('/workspaces/current/unsubscribe-lists', { params: { page, size } })
},
get(id: number) {
- return api.get<ApiResponse<UnsubscribeListItem>>(`/users/me/unsubscribe-lists/${id}`)
+ return api.get<ApiResponse<UnsubscribeListItem>>(`/workspaces/current/unsubscribe-lists/${id}`)
},
create(data: UnsubscribeListInput) {
- return api.post<ApiResponse<UnsubscribeListItem>>('/users/me/unsubscribe-lists', data)
+ return api.post<ApiResponse<UnsubscribeListItem>>('/workspaces/current/unsubscribe-lists', data)
},
update(id: number, data: Partial<UnsubscribeListInput>) {
- return api.put<ApiResponse<UnsubscribeListItem>>(`/users/me/unsubscribe-lists/${id}`, data)
+ return api.put<ApiResponse<UnsubscribeListItem>>(`/workspaces/current/unsubscribe-lists/${id}`, data)
},
delete(id: number) {
- return api.delete(`/users/me/unsubscribe-lists/${id}`)
+ return api.delete(`/workspaces/current/unsubscribe-lists/${id}`)
},
}
diff --git a/web/src/api/userData.ts b/web/src/api/userData.ts
deleted file mode 100644
index bc2fc5e..0000000
--- a/web/src/api/userData.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import api from './client'
-import type { ApiResponse, UserDataExport, GDPRDeleteResult } from './types'
-
-export const userDataApi = {
- exportAll() {
- return api.get<ApiResponse<UserDataExport>>('/users/me/data/export')
- },
- importAll(data: UserDataExport) {
- return api.post<ApiResponse<{ message: string; imported_count: number }>>('/users/me/data/import', data)
- },
- deleteContacts(email?: string) {
- return api.post<ApiResponse<GDPRDeleteResult>>('/users/me/gdpr/delete-contacts', { email: email || '' })
- },
- deleteEmailLogs(olderThanDays: number) {
- return api.post<ApiResponse<GDPRDeleteResult>>('/users/me/gdpr/delete-email-logs', { older_than_days: olderThanDays })
- },
-}
diff --git a/web/src/api/webhooks.ts b/web/src/api/webhooks.ts
index c220e7a..a11960c 100644
--- a/web/src/api/webhooks.ts
+++ b/web/src/api/webhooks.ts
@@ -3,18 +3,18 @@ import type { ApiResponse, PaginatedResponse, Webhook, WebhookDelivery, WebhookI
export const webhooksApi = {
list(page = 0, size = 20) {
- return api.get<PaginatedResponse<Webhook>>('/users/me/webhooks', { params: { page, size } })
+ return api.get<PaginatedResponse<Webhook>>('/workspaces/current/webhooks', { params: { page, size } })
},
create(data: WebhookInput) {
- return api.post<ApiResponse<Webhook>>('/users/me/webhooks', data)
+ return api.post<ApiResponse<Webhook>>('/workspaces/current/webhooks', data)
},
delete(id: number) {
- return api.delete(`/users/me/webhooks/${id}`)
+ return api.delete(`/workspaces/current/webhooks/${id}`)
},
}
export const webhookDeliveriesApi = {
list(page = 0, size = 20) {
- return api.get<PaginatedResponse<WebhookDelivery>>('/users/me/webhook-deliveries', { params: { page, size } })
+ return api.get<PaginatedResponse<WebhookDelivery>>('/workspaces/current/webhook-deliveries', { params: { page, size } })
},
}
diff --git a/web/src/api/workspaces.ts b/web/src/api/workspaces.ts
index 42c4bf8..a8d0c5e 100644
--- a/web/src/api/workspaces.ts
+++ b/web/src/api/workspaces.ts
@@ -7,8 +7,8 @@ import type {
WorkspaceInvitation,
InviteMemberInput,
WorkspaceRole,
- TransferResponse,
WorkspaceDataExport,
+ GDPRDeleteResult,
Plan,
} from './types'
@@ -73,11 +73,6 @@ export const workspaceApi = {
return api.get<ApiResponse<Plan | null>>('/workspaces/current/plan')
},
- // Data Transfer
- transferData(resources: string[]) {
- return api.post<ApiResponse<TransferResponse>>('/workspaces/current/transfer', { resources })
- },
-
// Data Export/Import
exportData() {
return api.get<ApiResponse<WorkspaceDataExport>>('/workspaces/current/data/export')
@@ -85,4 +80,12 @@ export const workspaceApi = {
importData(data: WorkspaceDataExport) {
return api.post<ApiResponse<{ message: string; imported_count: number }>>('/workspaces/current/data/import', data)
},
+
+ // Data Management (GDPR)
+ deleteContacts(email?: string) {
+ return api.post<ApiResponse<GDPRDeleteResult>>('/workspaces/current/gdpr/delete-contacts', { email: email || '' })
+ },
+ deleteEmailLogs(olderThanDays: number) {
+ return api.post<ApiResponse<GDPRDeleteResult>>('/workspaces/current/gdpr/delete-email-logs', { older_than_days: olderThanDays })
+ },
}
diff --git a/web/src/assets/styles.css b/web/src/assets/styles.css
index 11363e8..886a3cf 100644
--- a/web/src/assets/styles.css
+++ b/web/src/assets/styles.css
@@ -366,6 +366,113 @@ tr:hover td { background: var(--bg-hover); }
.badge-neutral { background: var(--bg-tertiary); color: var(--text-tertiary); }
.badge-secondary { background: var(--bg-tertiary); color: var(--text-secondary); }
+/* ─── Banners / Inline notices ─── */
+/* A cohesive inline banner. Set the accent with a variant class
+ (.app-banner--info / --warning / --success / --danger). All colors derive
+ from the accent vars so light/dark themes stay correct. */
+.app-banner {
+ --banner-accent: var(--primary-500);
+ --banner-accent-strong: var(--primary-600);
+ --banner-surface: var(--primary-50);
+ display: flex;
+ align-items: flex-start;
+ gap: 12px;
+ padding: 12px 14px;
+ border-radius: var(--radius);
+ border: 1px solid color-mix(in srgb, var(--banner-accent) 30%, transparent);
+ background: var(--banner-surface);
+ color: var(--text-secondary);
+ font-size: 13px;
+ line-height: 1.45;
+}
+.app-banner--info {
+ --banner-accent: var(--primary-500);
+ --banner-accent-strong: var(--primary-600);
+ --banner-surface: var(--primary-50);
+}
+.app-banner--warning {
+ --banner-accent: var(--warning-500);
+ --banner-accent-strong: var(--warning-600);
+ --banner-surface: var(--warning-50);
+}
+.app-banner--success {
+ --banner-accent: var(--success-500);
+ --banner-accent-strong: var(--success-600);
+ --banner-surface: var(--success-50);
+}
+.app-banner--danger {
+ --banner-accent: var(--danger-500);
+ --banner-accent-strong: var(--danger-600);
+ --banner-surface: var(--danger-50);
+}
+.app-banner-icon {
+ flex-shrink: 0;
+ width: 18px;
+ height: 18px;
+ margin-top: 1px;
+ color: var(--banner-accent-strong);
+}
+.app-banner-content {
+ flex: 1;
+ min-width: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+}
+.app-banner-title {
+ margin: 0;
+ font-size: 13.5px;
+ font-weight: 600;
+ color: var(--text-primary);
+}
+.app-banner-text { margin: 0; color: var(--text-secondary); }
+.app-banner-text strong { color: var(--text-primary); font-weight: 600; }
+.app-banner-actions {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ flex-shrink: 0;
+}
+/* Accent-tinted action button that reads on the banner surface in both themes. */
+.app-banner-btn {
+ padding: 6px 12px;
+ border-radius: var(--radius-sm);
+ border: 1px solid color-mix(in srgb, var(--banner-accent) 40%, transparent);
+ background: color-mix(in srgb, var(--banner-accent) 12%, transparent);
+ color: var(--banner-accent-strong);
+ font-size: 12px;
+ font-weight: 600;
+ cursor: pointer;
+ white-space: nowrap;
+ transition: background var(--transition), border-color var(--transition);
+}
+.app-banner-btn:hover:not(:disabled) {
+ background: color-mix(in srgb, var(--banner-accent) 20%, transparent);
+ border-color: color-mix(in srgb, var(--banner-accent) 55%, transparent);
+}
+.app-banner-btn:disabled { opacity: 0.6; cursor: not-allowed; }
+.app-banner-dismiss {
+ flex-shrink: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 26px;
+ height: 26px;
+ border: none;
+ border-radius: var(--radius-sm);
+ background: transparent;
+ color: var(--text-tertiary);
+ font-size: 18px;
+ line-height: 1;
+ cursor: pointer;
+ transition: background var(--transition), color var(--transition);
+}
+.app-banner-dismiss:hover { background: color-mix(in srgb, var(--banner-accent) 14%, transparent); color: var(--text-primary); }
+@media (max-width: 640px) {
+ .app-banner { flex-wrap: wrap; }
+ .app-banner-actions { width: 100%; justify-content: flex-end; }
+}
+
/* ─── Stats ─── */
.stats-grid {
display: grid;
diff --git a/web/src/components/EmailVerificationBanner.vue b/web/src/components/EmailVerificationBanner.vue
index 5016e12..b06bfbd 100644
--- a/web/src/components/EmailVerificationBanner.vue
+++ b/web/src/components/EmailVerificationBanner.vue
@@ -35,44 +35,30 @@ async function resend() {
</script>
<template>
- <div v-if="unverified" class="verify-banner">
- <span class="verify-banner-text">
- Your email is not verified. Some actions (inviting members, creating API keys) are blocked until you confirm your address.
- </span>
- <button class="verify-banner-btn" :disabled="sending" @click="resend">
- {{ sending ? 'Sending…' : 'Resend email' }}
- </button>
+ <div v-if="unverified" class="app-banner app-banner--warning verify-banner" role="alert">
+ <svg class="app-banner-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
+ stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
+ <path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0Z" />
+ <line x1="12" y1="9" x2="12" y2="13" />
+ <line x1="12" y1="17" x2="12.01" y2="17" />
+ </svg>
+ <div class="app-banner-content">
+ <p class="app-banner-title">Verify your email address</p>
+ <p class="app-banner-text">
+ Some actions — inviting members, creating API keys — stay locked until you confirm your address.
+ </p>
+ </div>
+ <div class="app-banner-actions">
+ <button class="app-banner-btn" :disabled="sending" @click="resend">
+ {{ sending ? 'Sending…' : 'Resend email' }}
+ </button>
+ </div>
</div>
</template>
<style scoped>
+/* Layout-only override; visual styling comes from the shared .app-banner system. */
.verify-banner {
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: 16px;
- padding: 10px 16px;
margin: 12px 16px 0;
- background: var(--warning-50, #fffbeb);
- border: 1px solid var(--warning-200, #fde68a);
- color: var(--warning-900, #78350f);
- border-radius: 6px;
- font-size: 13px;
-}
-.verify-banner-text { flex: 1; }
-.verify-banner-btn {
- padding: 6px 12px;
- border-radius: 4px;
- border: 1px solid var(--warning-400, #fbbf24);
- background: var(--warning-100, #fef3c7);
- color: var(--warning-900, #78350f);
- font-size: 12px;
- font-weight: 500;
- cursor: pointer;
- white-space: nowrap;
-}
-.verify-banner-btn:disabled {
- opacity: 0.6;
- cursor: not-allowed;
}
</style>
diff --git a/web/src/layouts/DashboardLayout.vue b/web/src/layouts/DashboardLayout.vue
index c15acd1..b98b5df 100644
--- a/web/src/layouts/DashboardLayout.vue
+++ b/web/src/layouts/DashboardLayout.vue
@@ -19,6 +19,23 @@ const userMenuOpen = ref(false)
const wsSwitcherOpen = ref(false)
const themeModes = ['light', 'dark', 'system'] as const
+// One-time banner introducing the personal workspace after the workspace-only
+// migration cutover. Dismissal is remembered in localStorage.
+const PERSONAL_BANNER_KEY = 'posta_personal_ws_banner_dismissed'
+const personalBannerDismissed = ref(localStorage.getItem(PERSONAL_BANNER_KEY) === 'true')
+const showPersonalBanner = computed(
+ () => wsStore.currentWorkspaceIsPersonal && !personalBannerDismissed.value
+)
+function dismissPersonalBanner() {
+ personalBannerDismissed.value = true
+ localStorage.setItem(PERSONAL_BANNER_KEY, 'true')
+}
+
+function goWorkspaceSettings() {
+ const id = wsStore.currentWorkspace?.id
+ if (id) router.push(`/workspaces/${id}`)
+}
+
function closeUserMenu(e: MouseEvent) {
const el = document.querySelector('.user-menu')
if (el && !el.contains(e.target as Node)) {
@@ -62,10 +79,14 @@ interface NavItem {
requiresWorkspace?: boolean
/** Only show when the user is an owner or admin of the current workspace. */
requiresWorkspaceAdmin?: boolean
+ /** Hidden when the active workspace is the user's personal one (no team). */
+ hideInPersonal?: boolean
/** Only show when the backend exposes the OpenAPI docs. */
requiresOpenapiDocs?: boolean
/** Deep-link into a WorkspaceSettings tab of the current workspace. */
workspaceTab?: 'members' | 'plan' | 'settings'
+ /** Link to a dedicated workspace sub-page (e.g. /workspaces/:id/members). */
+ workspaceSubpath?: string
/** Additional route path prefixes that should keep this item highlighted (grouped tab pages). */
matchPaths?: string[]
/** Nested items shown indented under this entry. */
@@ -137,19 +158,18 @@ const navSections: NavSection[] = [
{
id: 'developers',
title: 'Developers',
- defaultOpen: false,
+ defaultOpen: true,
items: [
{ name: 'API Keys', path: '/api-keys', icon: 'key' },
{ name: 'Webhooks', path: '/webhooks', icon: 'link' },
{ name: 'Webhook Deliveries', path: '/webhook-deliveries', icon: 'activity' },
{ name: 'API Reference', path: '/docs', icon: 'book-open', external: true, requiresOpenapiDocs: true },
- { name: 'OpenAPI (Swagger)', path: '/swagger', icon: 'code', external: true, requiresOpenapiDocs: true },
],
},
{
id: 'infrastructure',
title: 'Infrastructure',
- defaultOpen: false,
+ defaultOpen: true,
items: [
{ name: 'Domains', path: '/domains', icon: 'globe' },
{ name: 'SMTP Servers', path: '/smtp-servers', icon: 'server' },
@@ -159,10 +179,11 @@ const navSections: NavSection[] = [
id: 'workspace',
title: 'Workspace',
requiresWorkspace: true,
- defaultOpen: false,
+ defaultOpen: true,
items: [
- { name: 'Members', path: '', icon: 'users', workspaceTab: 'members' },
- { name: 'Plan & Billing', path: '', icon: 'credit-card', workspaceTab: 'plan' },
+ { name: 'All Workspaces', path: '/workspaces', icon: 'layers' },
+ { name: 'Members', path: '', icon: 'users', workspaceSubpath: 'members', hideInPersonal: true },
+ { name: 'Plan & Billing', path: '', icon: 'credit-card', workspaceTab: 'plan', hideInPersonal: true },
{ name: 'Settings', path: '', icon: 'settings', workspaceTab: 'settings', requiresWorkspaceAdmin: true },
],
},
@@ -219,6 +240,7 @@ function sectionItems(section: NavSection): NavItem[] {
return section.items.filter((item) => {
if (item.requiresWorkspace && !wsStore.isWorkspaceContext) return false
if (item.requiresWorkspaceAdmin && !wsStore.isWorkspaceAdmin) return false
+ if (item.hideInPersonal && wsStore.currentWorkspaceIsPersonal) return false
if (item.requiresOpenapiDocs && !appInfo.value?.openapi_docs) return false
return true
})
@@ -226,6 +248,9 @@ function sectionItems(section: NavSection): NavItem[] {
/** Resolve the effective target of an item (handles workspace tab deep-links). */
function itemTo(item: NavItem): string {
+ if (item.workspaceSubpath) {
+ return `/workspaces/${wsStore.currentWorkspaceId}/${item.workspaceSubpath}`
+ }
if (item.workspaceTab) {
return `/workspaces/${wsStore.currentWorkspaceId}?tab=${item.workspaceTab}`
}
@@ -238,10 +263,13 @@ function isActive(path: string): boolean {
}
function isItemActive(item: NavItem): boolean {
+ if (item.workspaceSubpath) {
+ return route.path === `/workspaces/${wsStore.currentWorkspaceId}/${item.workspaceSubpath}`
+ }
if (item.workspaceTab) {
return (
route.path === `/workspaces/${wsStore.currentWorkspaceId}` &&
- (route.query.tab || 'members') === item.workspaceTab
+ (route.query.tab || 'settings') === item.workspaceTab
)
}
// "Manage Workspaces…" should only highlight on the list page itself,
@@ -320,13 +348,16 @@ function getIcon(name: string): string {
<aside class="sidebar">
<div class="sidebar-header">
<img src="/logo.png" alt="Posta" class="sidebar-logo" @click="navigate('/')" />
- <span class="sidebar-brand-text" @click="navigate('/')">Posta</span>
+ <span class="sidebar-brand-text" @click="navigate('/')">Posta<span class="sidebar-brand-text-dot">.</span></span>
<button class="sidebar-collapse-btn" @click="toggleSidebar"
- :title="sidebarCollapsed ? 'Expand sidebar' : 'Collapse sidebar'">
- <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
- <path :d="sidebarCollapsed ? 'M6 3l5 5-5 5' : 'M10 3L5 8l5 5'" stroke="currentColor" stroke-width="1.5"
- stroke-linecap="round" stroke-linejoin="round" />
+ :title="sidebarCollapsed ? 'Expand sidebar' : 'Collapse sidebar'"
+ :aria-label="sidebarCollapsed ? 'Expand sidebar' : 'Collapse sidebar'">
+ <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
+ stroke-linecap="round" stroke-linejoin="round">
+ <rect x="3" y="3" width="18" height="18" rx="2" />
+ <path d="M9 3v18" />
+ <path :d="sidebarCollapsed ? 'm14 9 3 3-3 3' : 'm16 15-3-3 3-3'" />
</svg>
</button>
@@ -344,15 +375,11 @@ function getIcon(name: string): string {
</svg>
</div>
<div v-if="wsSwitcherOpen" class="ws-switcher-dropdown">
- <div class="ws-switcher-option" :class="{ active: wsStore.isPersonal }" @click="switchContext(null)">
- <div class="ws-avatar-sm">P</div>
- <span>Personal</span>
- </div>
<div v-for="ws in wsStore.workspaces" :key="ws.id" class="ws-switcher-option"
:class="{ active: wsStore.currentWorkspaceId === ws.id }" @click="switchContext(ws.id)">
<div class="ws-avatar-sm">{{ ws.name.charAt(0).toUpperCase() }}</div>
<span>{{ ws.name }}</span>
- <span class="ws-role-badge">{{ ws.role }}</span>
+ <span class="ws-role-badge">{{ ws.is_personal ? 'personal' : ws.role }}</span>
</div>
<div class="ws-switcher-divider"></div>
<div class="ws-switcher-action" @click="createWorkspace">
@@ -508,6 +535,25 @@ function getIcon(name: string): string {
</header>
<main class="main-content">
<EmailVerificationBanner />
+ <div v-if="showPersonalBanner" class="app-banner app-banner--info personal-ws-banner">
+ <svg class="app-banner-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
+ stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
+ <circle cx="12" cy="12" r="10" />
+ <line x1="12" y1="16" x2="12" y2="12" />
+ <line x1="12" y1="8" x2="12.01" y2="8" />
+ </svg>
+ <div class="app-banner-content">
+ <p class="app-banner-title">Your personal workspace is ready</p>
+ <p class="app-banner-text">
+ Your data now lives in <strong>{{ wsStore.currentWorkspace?.name }}</strong>.
+ Invite collaborators or rename it in workspace settings.
+ </p>
+ </div>
+ <div class="app-banner-actions">
+ <button class="app-banner-btn" @click="goWorkspaceSettings">Workspace settings</button>
+ <button class="app-banner-dismiss" @click="dismissPersonalBanner" aria-label="Dismiss banner">×</button>
+ </div>
+ </div>
<router-view />
</main>
<footer class="main-footer">
@@ -539,7 +585,7 @@ function getIcon(name: string): string {
<aside v-if="mobileOpen" class="sidebar sidebar-mobile">
<div class="sidebar-header">
<img src="/logo.png" alt="Posta" class="sidebar-logo" />
- <span class="sidebar-brand-text">Posta </span>
+ <span class="sidebar-brand-text">Posta<span class="sidebar-brand-text-dot">.</span></span>
<button class="sidebar-collapse-btn" @click="mobileOpen = false">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
stroke-linecap="round" stroke-linejoin="round">
@@ -566,19 +612,13 @@ function getIcon(name: string): string {
<Transition name="dropdown">
<div v-if="wsSwitcherOpen" class="ws-dropdown">
- <div class="ws-option" :class="{ active: wsStore.isPersonal }"
- @click="switchContext(null); mobileOpen = false">
- <span class="ws-avatar">P</span>
- <span>Personal</span>
- </div>
-
<div v-for="ws in wsStore.workspaces" :key="ws.id" class="ws-option"
:class="{ active: wsStore.currentWorkspaceId === ws.id }"
@click="switchContext(ws.id); mobileOpen = false">
<span class="ws-avatar">{{ ws.name?.charAt(0)?.toUpperCase() }}</span>
<div style="display: flex; flex-direction: column;">
<span>{{ ws.name }}</span>
- <small v-if="ws.role" style="font-size: 0.75rem; opacity: 0.7;">{{ ws.role }}</small>
+ <small style="font-size: 0.75rem; opacity: 0.7;">{{ ws.is_personal ? 'personal' : ws.role }}</small>
</div>
</div>
@@ -1255,6 +1295,12 @@ function getIcon(name: string): string {
padding: 28px;
}
+/* ─── Personal workspace intro banner ─── */
+/* Visuals come from the shared .app-banner system; only spacing is local. */
+.personal-ws-banner {
+ margin-bottom: 20px;
+}
+
/* ─── Footer ─── */
.main-footer {
display: flex;
diff --git a/web/src/router/index.ts b/web/src/router/index.ts
index 28a14ec..d6cf152 100644
--- a/web/src/router/index.ts
+++ b/web/src/router/index.ts
@@ -1,5 +1,6 @@
import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '../stores/auth'
+import { useWorkspaceStore } from '../stores/workspace'
const APP_NAME = 'Posta'
const DEFAULT_TITLE = 'Posta — Self-Hosted Email Delivery & Inbound Platform'
@@ -75,6 +76,7 @@ const routes = [
{ path: 'settings', name: 'settings', component: () => import('../views/settings/Settings.vue'), meta: { title: 'Settings' } },
{ path: 'workspaces', name: 'workspaces', component: () => import('../views/workspaces/Workspaces.vue'), meta: { title: 'Workspaces' } },
{ path: 'workspaces/:id', name: 'workspace-detail', component: () => import('../views/workspaces/WorkspaceSettings.vue'), meta: { title: 'Workspace Settings' } },
+ { path: 'workspaces/:id/members', name: 'workspace-members', component: () => import('../views/workspaces/WorkspaceMembers.vue'), meta: { title: 'Workspace Members' } },
{ path: 'about', name: 'about', component: () => import('../views/about/About.vue'), meta: { title: 'About' } },
{ path: 'profile', name: 'profile', component: () => import('../views/auth/Profile.vue'), meta: { title: 'Profile' } },
{ path: 'change-password', redirect: '/profile' },
@@ -105,7 +107,7 @@ const router = createRouter({
routes,
})
-router.beforeEach((to) => {
+router.beforeEach(async (to) => {
const auth = useAuthStore()
if (to.meta.auth && !auth.isAuthenticated) {
@@ -117,6 +119,18 @@ router.beforeEach((to) => {
if (to.meta.admin && !auth.isAdmin) {
return { name: 'dashboard' }
}
+
+ // Resolve the active workspace before any authenticated view mounts, so the
+ // X-Posta-Workspace-Id header is set on its first scoped request. Without
+ // this, on a fresh login the dashboard's stats/emails calls race the
+ // (unawaited) fetchWorkspaces() and go out header-less. Runs once — later
+ // navigations reuse the already-loaded store.
+ if (to.meta.auth && auth.isAuthenticated) {
+ const ws = useWorkspaceStore()
+ if (ws.workspaces.length === 0) {
+ await ws.fetchWorkspaces()
+ }
+ }
})
router.afterEach((to) => {
diff --git a/web/src/stores/workspace.ts b/web/src/stores/workspace.ts
index 4206978..29b4477 100644
--- a/web/src/stores/workspace.ts
+++ b/web/src/stores/workspace.ts
@@ -29,6 +29,12 @@ export const useWorkspaceStore = defineStore('workspace', () => {
return role === 'owner' || role === 'admin' || role === 'editor'
})
+ // The user's auto-provisioned personal workspace (workspace-only migration).
+ const personalWorkspace = computed(() => workspaces.value.find((w) => w.is_personal) ?? null)
+ // True when the active workspace is the user's personal one — used to hide
+ // team-only affordances (Members, Plan & Billing).
+ const currentWorkspaceIsPersonal = computed(() => currentWorkspace.value?.is_personal ?? false)
+
const contextLabel = computed(() => currentWorkspace.value?.name ?? 'Personal')
function setWorkspace(wsId: number | null) {
@@ -44,9 +50,12 @@ export const useWorkspaceStore = defineStore('workspace', () => {
try {
const res = await workspaceApi.list()
workspaces.value = res.data.data ?? []
- // If stored workspace no longer valid, clear it
- if (currentWorkspaceId.value && !workspaces.value.find((w) => w.id === currentWorkspaceId.value)) {
- setWorkspace(null)
+ const valid = currentWorkspaceId.value && workspaces.value.find((w) => w.id === currentWorkspaceId.value)
+ // After the workspace-only migration every user owns a personal workspace.
+ // Land there by default (instead of legacy header-less "personal mode") so
+ // the active context always maps to a real workspace.
+ if (!valid) {
+ setWorkspace(personalWorkspace.value?.id ?? null)
}
} catch {
workspaces.value = []
@@ -67,6 +76,8 @@ export const useWorkspaceStore = defineStore('workspace', () => {
isWorkspaceContext,
isWorkspaceAdmin,
canEdit,
+ personalWorkspace,
+ currentWorkspaceIsPersonal,
contextLabel,
setWorkspace,
fetchWorkspaces,
diff --git a/web/src/views/admin/Settings.vue b/web/src/views/admin/Settings.vue
index 839a1a9..b11c6d0 100644
--- a/web/src/views/admin/Settings.vue
+++ b/web/src/views/admin/Settings.vue
@@ -35,10 +35,10 @@ const settingMeta: Record<string, { label: string; description: string; category
const categories = ['General', 'Security', 'Privacy', 'Limits', 'Retention']
function settingsByCategory(category: string) {
- return settings.value.filter(s => {
- const meta = settingMeta[s.key]
- return meta ? meta.category === category : category === 'General'
- })
+ // Only render known, documented settings. Unknown keys (e.g. the upgrade
+ // framework's internal app.* bookkeeping rows) are never editable platform
+ // settings and must not leak into the UI.
+ return settings.value.filter(s => settingMeta[s.key]?.category === category)
}
// Track edited values separately
diff --git a/web/src/views/apikeys/ApiKeys.vue b/web/src/views/apikeys/ApiKeys.vue
index a662f9f..9ab5a15 100644
--- a/web/src/views/apikeys/ApiKeys.vue
+++ b/web/src/views/apikeys/ApiKeys.vue
@@ -187,7 +187,6 @@ onMounted(() => {
</div>
<div class="api-docs-links">
<a class="btn btn-secondary btn-sm" href="/docs" target="_blank" rel="noopener noreferrer">API Reference</a>
- <a class="btn btn-secondary btn-sm" href="/swagger" target="_blank" rel="noopener noreferrer">OpenAPI (Swagger)</a>
</div>
</div>
diff --git a/web/src/views/campaigns/Campaigns.vue b/web/src/views/campaigns/Campaigns.vue
index 87a7f25..35d50b0 100644
--- a/web/src/views/campaigns/Campaigns.vue
+++ b/web/src/views/campaigns/Campaigns.vue
@@ -75,7 +75,7 @@ async function loadFormData() {
}
try {
const { default: api } = await import('../../api/client')
- const res = await api.get<any>('/users/me/templates', { params: { page: 0, size: 100 } })
+ const res = await api.get<any>('/workspaces/current/templates', { params: { page: 0, size: 100 } })
templates.value = (res.data.data ?? []).map((t: any) => ({ id: t.id, name: t.name }))
} catch {
// non-critical
diff --git a/web/src/views/settings/Settings.vue b/web/src/views/settings/Settings.vue
index 700e40a..0cca98d 100644
--- a/web/src/views/settings/Settings.vue
+++ b/web/src/views/settings/Settings.vue
@@ -1,21 +1,12 @@
<script setup lang="ts">
import { ref, onMounted, watch, nextTick } from 'vue'
import { settingsApi } from '../../api/settings'
-import { authApi } from '../../api/auth'
-import { userDataApi } from '../../api/userData'
-import { workspaceApi } from '../../api/workspaces'
-import { useAuthStore } from '../../stores/auth'
-import { useWorkspaceStore } from '../../stores/workspace'
import { useThemeStore, type ThemeMode } from '../../stores/theme'
import { useNotificationStore } from '../../stores/notification'
-import { useConfirm } from '../../composables/useConfirm'
import type { UserSettings } from '../../api/types'
-const auth = useAuthStore()
-const wsStore = useWorkspaceStore()
const theme = useThemeStore()
const notify = useNotificationStore()
-const { confirm } = useConfirm()
const loading = ref(true)
// Auto-save state. saveStatus drives the header indicator; ready gates the
@@ -30,38 +21,15 @@ const SAVED_INDICATOR_MS = 2000
let debounceTimer: ReturnType<typeof setTimeout> | null = null
let savedClearTimer: ReturnType<typeof setTimeout> | null = null
-// Data management
-const exporting = ref(false)
-const importing = ref(false)
-const deletingContacts = ref(false)
-const deletingEmails = ref(false)
-const gdprEmail = ref('')
-const gdprDays = ref(90)
-const importFileRef = ref<HTMLInputElement | null>(null)
-
+// User settings are personal notification preferences only. Operational settings
+// (sending defaults, webhooks, API-key expiry, domain security, data) live on the
+// workspace — see Workspace Settings (workspace-only migration §2c/§5).
const form = ref<Partial<UserSettings>>({
- timezone: 'UTC',
- default_sender_name: '',
- default_sender_email: '',
email_notifications: true,
notification_email: '',
- webhook_retry_count: 3,
- api_key_expiry_days: 90,
- bounce_auto_suppress: true,
daily_report: false,
})
-const timezones = [
- 'UTC', 'America/New_York', 'America/Chicago', 'America/Denver', 'America/Los_Angeles',
- 'Europe/London', 'Europe/Paris', 'Europe/Berlin', 'Europe/Moscow',
- 'Asia/Tokyo', 'Asia/Shanghai', 'Asia/Kolkata', 'Asia/Dubai',
- 'Australia/Sydney', 'Pacific/Auckland','Africa/Kinshasa', 'Africa/Nairobi', 'Africa/Lagos','Africa/Lubumbashi',
-]
-
-// Domain Security
-const requireVerifiedDomain = ref(false)
-const domainSecurityLoading = ref(false)
-
// Theme
const themeModes: { value: ThemeMode; label: string; icon: string }[] = [
{ value: 'light', label: 'Light', icon: 'sun' },
@@ -71,23 +39,13 @@ const themeModes: { value: ThemeMode; label: string; icon: string }[] = [
onMounted(async () => {
try {
- const [settingsRes, profileRes] = await Promise.all([
- settingsApi.getUserSettings(),
- authApi.me(),
- ])
- const s = settingsRes.data.data
+ const res = await settingsApi.getUserSettings()
+ const u = res.data.data
form.value = {
- timezone: s.timezone || 'UTC',
- default_sender_name: s.default_sender_name || '',
- default_sender_email: s.default_sender_email || '',
- email_notifications: s.email_notifications,
- notification_email: s.notification_email || '',
- webhook_retry_count: s.webhook_retry_count,
- api_key_expiry_days: s.api_key_expiry_days,
- bounce_auto_suppress: s.bounce_auto_suppress,
- daily_report: s.daily_report,
+ email_notifications: u.email_notifications,
+ notification_email: u.notification_email || '',
+ daily_report: u.daily_report,
}
- requireVerifiedDomain.value = profileRes.data.data.require_verified_domain
} catch {
notify.error('Failed to load settings')
} finally {
@@ -139,143 +97,6 @@ async function autoSave() {
}
}
}
-
-async function exportData() {
- exporting.value = true
- try {
- const isWorkspace = wsStore.isWorkspaceContext
- const res = isWorkspace
- ? await workspaceApi.exportData()
- : await userDataApi.exportAll()
- const blob = new Blob([JSON.stringify(res.data.data, null, 2)], { type: 'application/json' })
- const url = URL.createObjectURL(blob)
- const a = document.createElement('a')
- a.href = url
- const prefix = isWorkspace
- ? `posta-workspace-export-${wsStore.currentWorkspace?.slug || 'ws'}`
- : 'posta-export'
- a.download = `${prefix}-${new Date().toISOString().slice(0, 10)}.json`
- a.click()
- URL.revokeObjectURL(url)
- notify.success('Data exported successfully')
- } catch {
- notify.error('Failed to export data')
- } finally {
- exporting.value = false
- }
-}
-
-function triggerImport() {
- importFileRef.value?.click()
-}
-
-async function handleImportFile(event: Event) {
- const file = (event.target as HTMLInputElement).files?.[0]
- if (!file) return
-
- const isWorkspace = wsStore.isWorkspaceContext
- const importMessage = isWorkspace
- ? 'This will import data into the current workspace. Duplicate items will be skipped. SMTP servers will be imported as disabled. Domains will require re-verification. Continue?'
- : 'This will import data from the selected file. Duplicate items will be skipped. Continue?'
-
- const confirmed = await confirm({
- title: isWorkspace ? 'Import Workspace Data' : 'Import Data',
- message: importMessage,
- confirmText: 'Import',
- variant: 'danger',
- })
- if (!confirmed) {
- if (importFileRef.value) importFileRef.value.value = ''
- return
- }
-
- importing.value = true
- try {
- const text = await file.text()
- const data = JSON.parse(text)
- const res = isWorkspace
- ? await workspaceApi.importData(data)
- : await userDataApi.importAll(data)
- notify.success(res.data.data.message || 'Data imported successfully')
- } catch (e: any) {
- if (e instanceof SyntaxError) {
- notify.error('Invalid JSON file')
- } else {
- notify.error(e.response?.data?.error?.message || 'Failed to import data')
- }
- } finally {
- importing.value = false
- if (importFileRef.value) importFileRef.value.value = ''
- }
-}
-
-async function deleteContacts() {
- const target = gdprEmail.value.trim()
- const msg = target
- ? `Delete contact "${target}" and remove from all lists and suppression?`
- : 'Delete ALL contacts? This cannot be undone.'
- const confirmed = await confirm({
- title: 'Delete Contact Data',
- message: msg,
- confirmText: 'Delete',
- variant: 'danger',
- })
- if (!confirmed) return
-
- deletingContacts.value = true
- try {
- const res = await userDataApi.deleteContacts(target || undefined)
- notify.success(res.data.data.message)
- gdprEmail.value = ''
- } catch (e: any) {
- notify.error(e.response?.data?.error?.message || 'Failed to delete contacts')
- } finally {
- deletingContacts.value = false
- }
-}
-
-async function deleteEmailLogs() {
- const days = gdprDays.value
- const msg = days > 0
- ? `Delete all email logs older than ${days} days and their associated bounces?`
- : 'Delete ALL email logs and associated bounces? This cannot be undone.'
- const confirmed = await confirm({
- title: 'Delete Email Logs',
- message: msg,
- confirmText: 'Delete',
- variant: 'danger',
- })
- if (!confirmed) return
-
- deletingEmails.value = true
- try {
- const res = await userDataApi.deleteEmailLogs(days)
- notify.success(res.data.data.message)
- } catch (e: any) {
- notify.error(e.response?.data?.error?.message || 'Failed to delete email logs')
- } finally {
- deletingEmails.value = false
- }
-}
-
-async function toggleDomainSecurity() {
- domainSecurityLoading.value = true
- try {
- const res = await authApi.updateProfile({
- name: auth.user?.name || '',
- require_verified_domain: !requireVerifiedDomain.value,
- })
- auth.user = res.data.data
- localStorage.setItem('posta_user', JSON.stringify(res.data.data))
- requireVerifiedDomain.value = res.data.data.require_verified_domain
- notify.success(requireVerifiedDomain.value ? 'Strict domain mode enabled' : 'Strict domain mode disabled')
- } catch (e: any) {
- const message = e?.response?.data?.error?.message || 'Failed to update setting'
- notify.error(message)
- } finally {
- domainSecurityLoading.value = false
- }
-}
</script>
<template>
@@ -302,32 +123,6 @@ async function toggleDomainSecurity() {
</div>
<div v-else class="settings-grid">
- <!-- General -->
- <div class="card">
- <div class="card-header"><h2>General</h2></div>
- <div class="card-body">
- <div class="settings-form">
- <div class="form-group">
- <label class="form-label">Timezone</label>
- <select v-model="form.timezone" class="form-select">
- <option v-for="tz in timezones" :key="tz" :value="tz">{{ tz }}</option>
- </select>
- <span class="form-hint">Used for displaying timestamps and scheduling emails.</span>
- </div>
- <div class="form-group">
- <label class="form-label">Default Sender Name</label>
- <input v-model="form.default_sender_name" type="text" class="form-input" placeholder="e.g. My Company" />
- <span class="form-hint">Pre-filled sender name when sending emails.</span>
- </div>
- <div class="form-group">
- <label class="form-label">Default Sender Email</label>
- <input v-model="form.default_sender_email" type="email" class="form-input" placeholder="e.g. [email protected]" />
- <span class="form-hint">Pre-filled sender address when sending emails.</span>
- </div>
- </div>
- </div>
- </div>
-
<!-- Notifications -->
<div class="card">
<div class="card-header"><h2>Notifications</h2></div>
@@ -364,138 +159,6 @@ async function toggleDomainSecurity() {
</div>
</div>
- <!-- Email Delivery -->
- <div class="card">
- <div class="card-header"><h2>Email Delivery</h2></div>
- <div class="card-body">
- <div class="form-group">
- <label class="form-label">Webhook Retry Count</label>
- <input v-model.number="form.webhook_retry_count" type="number" class="form-input" min="0" max="10" />
- <span class="form-hint">How many times to retry failed webhook deliveries.</span>
- </div>
- <div class="toggle-row" style="margin-top: 16px">
- <div>
- <label class="toggle-label">Auto-Suppress on Bounce</label>
- <span class="form-hint">Automatically add to suppression list on hard bounce.</span>
- </div>
- <button
- :class="['toggle-btn', { active: form.bounce_auto_suppress }]"
- @click="form.bounce_auto_suppress = !form.bounce_auto_suppress"
- >
- <span class="toggle-slider"></span>
- </button>
- </div>
- </div>
- </div>
-
- <!-- Domain Security -->
- <div class="card">
- <div class="card-header">
- <h2>Domain Security</h2>
- <span v-if="requireVerifiedDomain" class="badge badge-success">Strict</span>
- <span v-else class="badge badge-secondary">Permissive</span>
- </div>
- <div class="card-body">
- <p class="section-description">
- When strict domain mode is enabled, emails can only be sent from domains you have registered and verified via DNS TXT record.
- This prevents sending from unverified domains and protects your sender reputation.
- </p>
- <div class="toggle-row">
- <label class="toggle-label">Require verified domain</label>
- <button
- :class="['toggle-btn', { active: requireVerifiedDomain }]"
- :disabled="domainSecurityLoading"
- @click="toggleDomainSecurity"
- >
- <span class="toggle-slider"></span>
- </button>
- </div>
- </div>
- </div>
-
- <!-- API & Templates -->
- <div class="card">
- <div class="card-header"><h2>API & Templates</h2></div>
- <div class="card-body">
- <div class="form-group">
- <label class="form-label">Default API Key Expiry (days)</label>
- <input v-model.number="form.api_key_expiry_days" type="number" class="form-input" min="1" max="365" />
- <span class="form-hint">Default expiration period for newly created API keys.</span>
- </div>
- </div>
- </div>
-
- <!-- Data Export/Import -->
- <div class="card">
- <div class="card-header">
- <h2>Data Export / Import</h2>
- <span v-if="wsStore.isWorkspaceContext" class="badge badge-primary">{{ wsStore.contextLabel }}</span>
- </div>
- <div class="card-body">
- <p v-if="wsStore.isWorkspaceContext" class="section-description">
- Export all workspace data (settings, templates, stylesheets, languages, contacts, contact lists, webhooks, SMTP servers, domains, subscribers, subscriber lists, and suppressions) as a JSON file.
- You can import this file to restore data on this or another workspace.
- </p>
- <p v-else class="section-description">
- Export all your data (templates, stylesheets, languages, contacts, contact lists, webhooks, suppressions, and settings) as a JSON file.
- You can import this file later to restore your data on this or another Posta instance.
- </p>
- <p v-if="wsStore.isWorkspaceContext" class="section-hint">
- Note: SMTP server passwords are not included in exports. Imported SMTP servers will be disabled until passwords are reconfigured.
- Imported domains will require re-verification.
- </p>
- <div class="flex gap-2">
- <button class="btn btn-primary" :disabled="exporting" @click="exportData">
- {{ exporting ? 'Exporting...' : wsStore.isWorkspaceContext ? 'Export Workspace Data' : 'Export All Data' }}
- </button>
- <button class="btn btn-secondary" :disabled="importing" @click="triggerImport">
- {{ importing ? 'Importing...' : 'Import Data' }}
- </button>
- <input ref="importFileRef" type="file" accept=".json" style="display: none" @change="handleImportFile" />
- </div>
- </div>
- </div>
-
- <!-- GDPR Data Management -->
- <div class="card">
- <div class="card-header">
- <h2>Data Management (GDPR)</h2>
- </div>
- <div class="card-body">
- <p class="section-description">
- Manage personal data for GDPR compliance. Delete specific contacts or purge old email logs.
- </p>
-
- <div class="gdpr-section">
- <h3 class="gdpr-title">Delete Contact Data</h3>
- <p class="section-description">
- Remove a specific contact by email (including suppression list and list memberships), or leave empty to delete all contacts.
- </p>
- <div class="flex gap-2 align-center">
- <input v-model="gdprEmail" type="email" class="form-input" placeholder="[email protected] (or leave empty for all)" style="flex: 1" />
- <button class="btn btn-danger" :disabled="deletingContacts" @click="deleteContacts">
- {{ deletingContacts ? 'Deleting...' : 'Delete' }}
- </button>
- </div>
- </div>
-
- <div class="gdpr-section" style="margin-top: 24px">
- <h3 class="gdpr-title">Delete Email Logs</h3>
- <p class="section-description">
- Delete email logs and associated bounce records. Set days to 0 to delete all logs.
- </p>
- <div class="flex gap-2 align-center">
- <label class="form-label" style="margin: 0; white-space: nowrap">Older than</label>
- <input v-model.number="gdprDays" type="number" class="form-input" min="0" style="width: 100px" />
- <label class="form-label" style="margin: 0">days</label>
- <button class="btn btn-danger" :disabled="deletingEmails" @click="deleteEmailLogs">
- {{ deletingEmails ? 'Deleting...' : 'Delete Logs' }}
- </button>
- </div>
- </div>
- </div>
- </div>
-
<!-- Theme -->
<div class="card">
<div class="card-header"><h2>Theme</h2></div>
@@ -529,11 +192,6 @@ async function toggleDomainSecurity() {
max-width: 640px;
}
-.settings-form {
- display: grid;
- gap: 1rem;
-}
-
.form-hint {
font-size: 12px;
color: var(--text-muted);
@@ -577,11 +235,6 @@ async function toggleDomainSecurity() {
background: var(--primary-600);
}
-.toggle-btn:disabled {
- opacity: 0.5;
- cursor: not-allowed;
-}
-
.toggle-slider {
position: absolute;
top: 2px;
@@ -641,23 +294,6 @@ async function toggleDomainSecurity() {
font-weight: 500;
}
-.align-center {
- align-items: center;
-}
-
-.gdpr-section h3.gdpr-title {
- font-size: 14px;
- font-weight: 600;
- color: var(--text-primary);
- margin: 0 0 4px;
-}
-
-.section-hint {
- font-size: 12px;
- color: var(--text-muted);
- margin-bottom: 16px;
-}
-
.save-status {
display: inline-flex;
align-items: center;
diff --git a/web/src/views/workspaces/WorkspaceMembers.vue b/web/src/views/workspaces/WorkspaceMembers.vue
new file mode 100644
index 0000000..09bc56c
--- /dev/null
+++ b/web/src/views/workspaces/WorkspaceMembers.vue
@@ -0,0 +1,328 @@
+<script setup lang="ts">
+import { ref, onMounted, computed, watch } from 'vue'
+import { useRoute, useRouter } from 'vue-router'
+import { workspaceApi } from '../../api/workspaces'
+import type { Workspace, WorkspaceMember, WorkspaceInvitation, WorkspaceRole } from '../../api/types'
+import { useNotificationStore } from '../../stores/notification'
+import { useWorkspaceStore } from '../../stores/workspace'
+import { useConfirm } from '../../composables/useConfirm'
+
+const route = useRoute()
+const router = useRouter()
+const notify = useNotificationStore()
+const wsStore = useWorkspaceStore()
+const { confirm } = useConfirm()
+
+const wsId = Number(route.params.id)
+const ws = ref<Workspace | null>(null)
+const loading = ref(true)
+
+// Tabs
+type MembersTab = 'members' | 'invitations'
+const validTabs: MembersTab[] = ['members', 'invitations']
+function tabFromQuery(value: unknown): MembersTab {
+ return validTabs.includes(value as MembersTab) ? (value as MembersTab) : 'members'
+}
+const activeTab = ref<MembersTab>(tabFromQuery(route.query.tab))
+watch(() => route.query.tab, (value) => {
+ if (value) activeTab.value = tabFromQuery(value)
+})
+
+const members = ref<WorkspaceMember[]>([])
+const invitations = ref<WorkspaceInvitation[]>([])
+
+// Invite modal
+const showInviteModal = ref(false)
+const inviteEmail = ref('')
+const inviteRole = ref<WorkspaceRole>('editor')
+const inviting = ref(false)
+
+const myRole = computed(() => {
+ const membership = wsStore.workspaces.find(w => w.id === wsId)
+ return membership?.role ?? 'viewer'
+})
+const isAdminOrOwner = computed(() => myRole.value === 'owner' || myRole.value === 'admin')
+
+async function withWorkspace<T>(fn: () => Promise<T>): Promise<T> {
+ const prevWs = wsStore.currentWorkspaceId
+ wsStore.setWorkspace(wsId)
+ try {
+ return await fn()
+ } finally {
+ wsStore.setWorkspace(prevWs)
+ }
+}
+
+async function fetchWorkspace() {
+ loading.value = true
+ try {
+ const res = await withWorkspace(() => workspaceApi.getCurrent())
+ ws.value = res.data.data
+ } catch {
+ notify.error('Failed to load workspace')
+ router.push('/workspaces')
+ } finally {
+ loading.value = false
+ }
+}
+
+async function fetchMembers() {
+ try {
+ const res = await withWorkspace(() => workspaceApi.listMembers())
+ members.value = res.data.data ?? []
+ } catch {
+ notify.error('Failed to load members')
+ }
+}
+
+async function fetchInvitations() {
+ try {
+ const res = await withWorkspace(() => workspaceApi.listInvitations())
+ invitations.value = res.data.data ?? []
+ } catch {
+ notify.error('Failed to load invitations')
+ }
+}
+
+async function inviteMember() {
+ if (!inviteEmail.value.trim()) return
+ inviting.value = true
+ try {
+ await withWorkspace(() => workspaceApi.invite({ email: inviteEmail.value.trim(), role: inviteRole.value }))
+ notify.success('Invitation sent')
+ showInviteModal.value = false
+ inviteEmail.value = ''
+ inviteRole.value = 'editor'
+ await fetchInvitations()
+ } catch (err: any) {
+ notify.error(err.response?.data?.error?.message || 'Failed to invite')
+ } finally {
+ inviting.value = false
+ }
+}
+
+async function updateRole(member: WorkspaceMember, newRole: WorkspaceRole) {
+ try {
+ await withWorkspace(() => workspaceApi.updateMemberRole(member.user_id, newRole))
+ notify.success('Role updated')
+ await fetchMembers()
+ } catch (err: any) {
+ notify.error(err.response?.data?.error?.message || 'Failed to update role')
+ }
+}
+
+async function removeMember(member: WorkspaceMember) {
+ const ok = await confirm({ title: 'Remove Member', message: `Remove ${member.name || member.email} from this workspace?`, confirmText: 'Remove', variant: 'danger' })
+ if (!ok) return
+ try {
+ await withWorkspace(() => workspaceApi.removeMember(member.user_id))
+ notify.success('Member removed')
+ await fetchMembers()
+ } catch (err: any) {
+ notify.error(err.response?.data?.error?.message || 'Failed to remove')
+ }
+}
+
+async function revokeInvitation(inv: WorkspaceInvitation) {
+ const ok = await confirm({ title: 'Revoke Invitation', message: `Revoke the invitation for ${inv.email}?`, confirmText: 'Revoke', variant: 'warning' })
+ if (!ok) return
+ try {
+ await withWorkspace(() => workspaceApi.cancelInvitation(inv.id))
+ notify.success('Invitation revoked')
+ await fetchInvitations()
+ } catch (err: any) {
+ notify.error(err.response?.data?.error?.message || 'Failed to revoke')
+ }
+}
+
+function roleBadgeClass(role: string): string {
+ if (role === 'owner') return 'badge-primary'
+ if (role === 'admin') return 'badge-warning'
+ return 'badge-neutral'
+}
+
+function formatDate(dateStr: string): string {
+ return new Date(dateStr).toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' })
+}
+
+onMounted(async () => {
+ await fetchWorkspace()
+ await Promise.all([fetchMembers(), fetchInvitations()])
+})
+</script>
+
+<template>
+ <div>
+ <div class="page-header">
+ <div>
+ <h1>{{ ws?.name || 'Workspace' }} — Members</h1>
+ <p v-if="ws?.slug" style="color: var(--text-muted); font-size: 13px; margin-top: 2px;">
+ <code>{{ ws.slug }}</code>
+ </p>
+ </div>
+ <div style="display: flex; gap: 8px;">
+ <button class="btn btn-secondary" @click="router.push(`/workspaces/${wsId}`)">Workspace Settings</button>
+ <button class="btn btn-secondary" @click="router.push('/workspaces')">Back</button>
+ </div>
+ </div>
+
+ <div v-if="loading" class="loading-page">
+ <div class="spinner"></div>
+ </div>
+
+ <template v-else>
+ <div class="tabs">
+ <button :class="['tab', { active: activeTab === 'members' }]" @click="activeTab = 'members'">
+ Members ({{ members.length }})
+ </button>
+ <button :class="['tab', { active: activeTab === 'invitations' }]" @click="activeTab = 'invitations'">
+ Invitations ({{ invitations.length }})
+ </button>
+ </div>
+
+ <!-- Members Tab -->
+ <div v-if="activeTab === 'members'" class="card">
+ <div class="card-header">
+ <span>Members</span>
+ <button v-if="isAdminOrOwner" class="btn btn-primary btn-sm" @click="showInviteModal = true">Invite</button>
+ </div>
+ <div class="table-wrapper">
+ <table>
+ <thead>
+ <tr>
+ <th>Name</th>
+ <th>Email</th>
+ <th>Role</th>
+ <th>Joined</th>
+ <th v-if="isAdminOrOwner">Actions</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr v-for="m in members" :key="m.id">
+ <td style="font-weight: 500;">{{ m.name }}</td>
+ <td>{{ m.email }}</td>
+ <td>
+ <select
+ v-if="isAdminOrOwner && m.role !== 'owner'"
+ :value="m.role"
+ class="form-select form-select-sm"
+ @change="updateRole(m, ($event.target as HTMLSelectElement).value as WorkspaceRole)"
+ >
+ <option value="admin">Admin</option>
+ <option value="editor">Editor</option>
+ <option value="viewer">Viewer</option>
+ </select>
+ <span v-else class="badge" :class="roleBadgeClass(m.role)">{{ m.role }}</span>
+ </td>
+ <td>{{ formatDate(m.created_at) }}</td>
+ <td v-if="isAdminOrOwner">
+ <button v-if="m.role !== 'owner'" class="btn btn-danger btn-sm" @click="removeMember(m)">Remove</button>
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ </div>
+
+ <!-- Invitations Tab -->
+ <div v-if="activeTab === 'invitations'" class="card">
+ <div class="card-header">
+ <span>Pending Invitations</span>
+ <button v-if="isAdminOrOwner" class="btn btn-primary btn-sm" @click="showInviteModal = true">Invite</button>
+ </div>
+ <div v-if="invitations.length === 0" class="empty-state">
+ <p>No pending invitations.</p>
+ </div>
+ <div v-else class="table-wrapper">
+ <table>
+ <thead>
+ <tr>
+ <th>Email</th>
+ <th>Role</th>
+ <th>Expires</th>
+ <th>Sent</th>
+ <th v-if="isAdminOrOwner">Actions</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr v-for="inv in invitations" :key="inv.id">
+ <td>{{ inv.email }}</td>
+ <td><span class="badge" :class="roleBadgeClass(inv.role)">{{ inv.role }}</span></td>
+ <td>{{ formatDate(inv.expires_at) }}</td>
+ <td>{{ formatDate(inv.created_at) }}</td>
+ <td v-if="isAdminOrOwner">
+ <button class="btn btn-danger btn-sm" @click="revokeInvitation(inv)">Revoke</button>
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ </div>
+ </template>
+
+ <!-- Invite Modal -->
+ <div v-if="showInviteModal" class="modal-overlay" @click.self="showInviteModal = false">
+ <div class="modal">
+ <div class="modal-header">
+ <h3>Invite Member</h3>
+ </div>
+ <form @submit.prevent="inviteMember">
+ <div class="modal-body">
+ <div class="form-group">
+ <label class="form-label">Email Address</label>
+ <input v-model="inviteEmail" type="email" class="form-input" placeholder="[email protected]" required />
+ </div>
+ <div class="form-group">
+ <label class="form-label">Role</label>
+ <select v-model="inviteRole" class="form-select">
+ <option value="admin">Admin</option>
+ <option value="editor">Editor</option>
+ <option value="viewer">Viewer</option>
+ </select>
+ </div>
+ </div>
+ <div class="modal-footer">
+ <button type="button" class="btn btn-secondary" @click="showInviteModal = false">Cancel</button>
+ <button type="submit" class="btn btn-primary" :disabled="inviting || !inviteEmail.trim()">
+ {{ inviting ? 'Sending...' : 'Send Invitation' }}
+ </button>
+ </div>
+ </form>
+ </div>
+ </div>
+ </div>
+</template>
+
+<style scoped>
+.tabs {
+ display: flex;
+ gap: 0;
+ border-bottom: 1px solid var(--border-primary);
+ margin-bottom: 20px;
+}
+.tab {
+ padding: 10px 20px;
+ font-size: 14px;
+ font-weight: 500;
+ color: var(--text-muted);
+ background: none;
+ border: none;
+ border-bottom: 2px solid transparent;
+ cursor: pointer;
+ transition: all var(--transition);
+}
+.tab:hover { color: var(--text-primary); }
+.tab.active {
+ color: var(--primary-600);
+ border-bottom-color: var(--primary-600);
+}
+.card-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 14px 20px;
+ border-bottom: 1px solid var(--border-primary);
+ font-weight: 600;
+ font-size: 14px;
+}
+</style>
diff --git a/web/src/views/workspaces/WorkspaceSettings.vue b/web/src/views/workspaces/WorkspaceSettings.vue
index 2c0d9e9..e9735f7 100644
--- a/web/src/views/workspaces/WorkspaceSettings.vue
+++ b/web/src/views/workspaces/WorkspaceSettings.vue
@@ -3,7 +3,8 @@ import { ref, onMounted, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { workspaceApi } from '../../api/workspaces'
import { oauthApi } from '../../api/oauth'
-import type { Workspace, WorkspaceMember, WorkspaceInvitation, WorkspaceRole, TransferResult, Plan, OAuthProviderInfo, WorkspaceSSOConfig } from '../../api/types'
+import { settingsApi } from '../../api/settings'
+import type { Workspace, Plan, OAuthProviderInfo, WorkspaceSSOConfig, WorkspaceSettings } from '../../api/types'
import { useNotificationStore } from '../../stores/notification'
import { useWorkspaceStore } from '../../stores/workspace'
import { useConfirm } from '../../composables/useConfirm'
@@ -18,30 +19,27 @@ const wsId = Number(route.params.id)
const ws = ref<Workspace | null>(null)
const loading = ref(true)
-// Tabs
-type WorkspaceTab = 'members' | 'invitations' | 'plan' | 'settings'
-const validTabs: WorkspaceTab[] = ['members', 'invitations', 'plan', 'settings']
-function tabFromQuery(value: unknown): WorkspaceTab {
- // Legacy tabs that were folded into Settings.
- if (value === 'sso' || value === 'transfer') return 'settings'
- return validTabs.includes(value as WorkspaceTab) ? (value as WorkspaceTab) : 'members'
+// Members and invitations now live on a dedicated page; redirect legacy deep-links.
+if (route.query.tab === 'members' || route.query.tab === 'invitations') {
+ router.replace(`/workspaces/${wsId}/members?tab=${route.query.tab}`)
}
-const activeTab = ref<WorkspaceTab>(tabFromQuery(route.query.tab))
-// Keep the active tab in sync when the sidebar deep-links into a different tab
-// of the workspace that is already open.
+// Tabs
+type SettingsTab = 'settings' | 'data' | 'sso' | 'plan'
+const validTabs: SettingsTab[] = ['settings', 'data', 'sso', 'plan']
+function tabFromQuery(value: unknown): SettingsTab {
+ if (value === 'transfer') return 'settings'
+ return validTabs.includes(value as SettingsTab) ? (value as SettingsTab) : 'settings'
+}
+const activeTab = ref<SettingsTab>(tabFromQuery(route.query.tab))
watch(() => route.query.tab, (value) => {
+ if (value === 'members' || value === 'invitations') {
+ router.replace(`/workspaces/${wsId}/members?tab=${value}`)
+ return
+ }
if (value) activeTab.value = tabFromQuery(value)
})
-// Members
-const members = ref<WorkspaceMember[]>([])
-const membersLoading = ref(false)
-
-// Invitations
-const invitations = ref<WorkspaceInvitation[]>([])
-const invitationsLoading = ref(false)
-
// Plan
const currentPlan = ref<Plan | null>(null)
const planLoading = ref(false)
@@ -54,106 +52,78 @@ const ssoLoading = ref(false)
const ssoSaving = ref(false)
const ssoForm = ref({ provider_id: 0, enforce_sso: false, auto_provision: true, allowed_domains: '' })
-// Invite modal
-const showInviteModal = ref(false)
-const inviteEmail = ref('')
-const inviteRole = ref<WorkspaceRole>('editor')
-const inviting = ref(false)
-
// Data Export/Import
const exporting = ref(false)
const importing = ref(false)
const importFileRef = ref<HTMLInputElement | null>(null)
-// Settings
+// Settings (workspace name/description)
const editName = ref('')
const editDescription = ref('')
const saving = ref(false)
-// Data Transfer
-const availableResources = [
- { key: 'templates', label: 'Templates' },
- { key: 'stylesheets', label: 'Stylesheets' },
- { key: 'languages', label: 'Languages' },
- { key: 'smtp_servers', label: 'SMTP Servers' },
- { key: 'domains', label: 'Domains' },
- { key: 'webhooks', label: 'Webhooks' },
- { key: 'contacts', label: 'Contacts' },
- { key: 'subscribers', label: 'Subscribers' },
- { key: 'subscriber_lists', label: 'Lists' },
- { key: 'suppressions', label: 'Suppressions' },
- { key: 'api_keys', label: 'API Keys' },
- { key: 'bounces', label: 'Bounces' },
- { key: 'emails', label: 'Emails' },
+// Operational workspace settings (timezone, sender defaults, webhook retries,
+// API-key expiry, bounce auto-suppress) — backed by /workspaces/current/settings.
+const timezones = [
+ 'UTC', 'America/New_York', 'America/Chicago', 'America/Denver', 'America/Los_Angeles',
+ 'Europe/London', 'Europe/Paris', 'Europe/Berlin', 'Europe/Moscow',
+ 'Asia/Tokyo', 'Asia/Shanghai', 'Asia/Kolkata', 'Asia/Dubai',
+ 'Australia/Sydney', 'Pacific/Auckland', 'Africa/Kinshasa', 'Africa/Nairobi', 'Africa/Lagos', 'Africa/Lubumbashi',
]
-const selectedResources = ref<string[]>([])
-const transferring = ref(false)
-const transferResults = ref<TransferResult[] | null>(null)
-const transferTotal = ref(0)
+const wsSettings = ref<Partial<WorkspaceSettings>>({
+ timezone: 'UTC',
+ default_sender_name: '',
+ default_sender_email: '',
+ webhook_retry_count: 3,
+ api_key_expiry_days: 90,
+ bounce_auto_suppress: true,
+ require_verified_domain: false,
+})
+const wsSettingsLoading = ref(false)
+const wsSettingsSaving = ref(false)
+
+// Data Management (GDPR) — scoped to this workspace.
+const gdprEmail = ref('')
+const gdprDays = ref(90)
+const deletingContacts = ref(false)
+const deletingEmails = ref(false)
const myRole = computed(() => {
const membership = wsStore.workspaces.find(w => w.id === wsId)
return membership?.role ?? 'viewer'
})
-
const isAdminOrOwner = computed(() => myRole.value === 'owner' || myRole.value === 'admin')
const isOwner = computed(() => myRole.value === 'owner')
-async function fetchWorkspace() {
- loading.value = true
- // Temporarily set workspace context for API calls
- const prevWs = wsStore.currentWorkspaceId
- wsStore.setWorkspace(wsId)
- try {
- const res = await workspaceApi.getCurrent()
- ws.value = res.data.data
- editName.value = ws.value.name
- editDescription.value = ws.value.description || ''
- } catch {
- notify.error('Failed to load workspace')
- router.push('/workspaces')
- } finally {
- loading.value = false
- wsStore.setWorkspace(prevWs)
- }
-}
-
-async function fetchMembers() {
+async function withWorkspace<T>(fn: () => Promise<T>): Promise<T> {
const prevWs = wsStore.currentWorkspaceId
wsStore.setWorkspace(wsId)
- membersLoading.value = true
try {
- const res = await workspaceApi.listMembers()
- members.value = res.data.data ?? []
- } catch {
- notify.error('Failed to load members')
+ return await fn()
} finally {
- membersLoading.value = false
wsStore.setWorkspace(prevWs)
}
}
-async function fetchInvitations() {
- const prevWs = wsStore.currentWorkspaceId
- wsStore.setWorkspace(wsId)
- invitationsLoading.value = true
+async function fetchWorkspace() {
+ loading.value = true
try {
- const res = await workspaceApi.listInvitations()
- invitations.value = res.data.data ?? []
+ const res = await withWorkspace(() => workspaceApi.getCurrent())
+ ws.value = res.data.data
+ editName.value = ws.value.name
+ editDescription.value = ws.value.description || ''
} catch {
- notify.error('Failed to load invitations')
+ notify.error('Failed to load workspace')
+ router.push('/workspaces')
} finally {
- invitationsLoading.value = false
- wsStore.setWorkspace(prevWs)
+ loading.value = false
}
}
async function fetchPlan() {
- const prevWs = wsStore.currentWorkspaceId
- wsStore.setWorkspace(wsId)
planLoading.value = true
try {
- const res = await workspaceApi.getPlan()
+ const res = await withWorkspace(() => workspaceApi.getPlan())
const data = res.data.data
if (data && typeof data === 'object' && 'id' in data) {
currentPlan.value = data as Plan
@@ -170,19 +140,86 @@ async function fetchPlan() {
planSource.value = 'global_settings'
} finally {
planLoading.value = false
- wsStore.setWorkspace(prevWs)
+ }
+}
+
+async function fetchWorkspaceSettings() {
+ wsSettingsLoading.value = true
+ try {
+ const res = await withWorkspace(() => settingsApi.getWorkspaceSettings())
+ const s = res.data.data
+ wsSettings.value = {
+ timezone: s.timezone || 'UTC',
+ default_sender_name: s.default_sender_name || '',
+ default_sender_email: s.default_sender_email || '',
+ webhook_retry_count: s.webhook_retry_count,
+ api_key_expiry_days: s.api_key_expiry_days,
+ bounce_auto_suppress: s.bounce_auto_suppress,
+ require_verified_domain: s.require_verified_domain,
+ }
+ } catch {
+ /* settings fall back to defaults */
+ } finally {
+ wsSettingsLoading.value = false
+ }
+}
+
+async function saveWorkspaceSettings() {
+ wsSettingsSaving.value = true
+ try {
+ await withWorkspace(() => settingsApi.updateWorkspaceSettings(wsSettings.value))
+ notify.success('Workspace settings saved')
+ } catch (err: any) {
+ notify.error(err.response?.data?.error?.message || 'Failed to save workspace settings')
+ } finally {
+ wsSettingsSaving.value = false
+ }
+}
+
+async function deleteWorkspaceContacts() {
+ const target = gdprEmail.value.trim()
+ const message = target
+ ? `Delete contact "${target}" and remove it from all lists and suppression in this workspace?`
+ : 'Delete ALL contacts in this workspace? This cannot be undone.'
+ const confirmed = await confirm({ title: 'Delete Contact Data', message, confirmText: 'Delete', variant: 'danger' })
+ if (!confirmed) return
+ deletingContacts.value = true
+ try {
+ const res = await withWorkspace(() => workspaceApi.deleteContacts(target || undefined))
+ notify.success(res.data.data.message)
+ gdprEmail.value = ''
+ } catch (e: any) {
+ notify.error(e.response?.data?.error?.message || 'Failed to delete contacts')
+ } finally {
+ deletingContacts.value = false
+ }
+}
+
+async function deleteWorkspaceEmailLogs() {
+ const days = gdprDays.value
+ const message = days > 0
+ ? `Delete all email logs older than ${days} days and their associated bounces in this workspace?`
+ : 'Delete ALL email logs and associated bounces in this workspace? This cannot be undone.'
+ const confirmed = await confirm({ title: 'Delete Email Logs', message, confirmText: 'Delete', variant: 'danger' })
+ if (!confirmed) return
+ deletingEmails.value = true
+ try {
+ const res = await withWorkspace(() => workspaceApi.deleteEmailLogs(days))
+ notify.success(res.data.data.message)
+ } catch (e: any) {
+ notify.error(e.response?.data?.error?.message || 'Failed to delete email logs')
+ } finally {
+ deletingEmails.value = false
}
}
async function fetchSSO() {
- const prevWs = wsStore.currentWorkspaceId
- wsStore.setWorkspace(wsId)
ssoLoading.value = true
try {
- const [ssoRes, providersRes] = await Promise.all([
+ const [ssoRes, providersRes] = await withWorkspace(() => Promise.all([
oauthApi.getSSO(),
oauthApi.providers(),
- ])
+ ]))
ssoConfig.value = ssoRes.data.data
ssoProviders.value = providersRes.data.data?.providers || []
if (ssoConfig.value) {
@@ -196,7 +233,6 @@ async function fetchSSO() {
} catch { /* ignore */ }
finally {
ssoLoading.value = false
- wsStore.setWorkspace(prevWs)
}
}
@@ -205,35 +241,28 @@ async function saveSSO() {
notify.error('Please select a provider')
return
}
- const prevWs = wsStore.currentWorkspaceId
- wsStore.setWorkspace(wsId)
ssoSaving.value = true
try {
- await oauthApi.setSSO(ssoForm.value)
+ await withWorkspace(() => oauthApi.setSSO(ssoForm.value))
notify.success('SSO configuration saved')
await fetchSSO()
} catch (err: any) {
notify.error(err.response?.data?.error?.message || 'Failed to save SSO config')
} finally {
ssoSaving.value = false
- wsStore.setWorkspace(prevWs)
}
}
async function removeSSO() {
const ok = await confirm({ title: 'Remove SSO', message: 'Remove SSO configuration from this workspace? Members will no longer be required to use SSO.', confirmText: 'Remove SSO', variant: 'danger' })
if (!ok) return
- const prevWs = wsStore.currentWorkspaceId
- wsStore.setWorkspace(wsId)
try {
- await oauthApi.deleteSSO()
+ await withWorkspace(() => oauthApi.deleteSSO())
ssoConfig.value = null
ssoForm.value = { provider_id: 0, enforce_sso: false, auto_provision: true, allowed_domains: '' }
notify.success('SSO configuration removed')
} catch (err: any) {
notify.error(err.response?.data?.error?.message || 'Failed to remove SSO config')
- } finally {
- wsStore.setWorkspace(prevWs)
}
}
@@ -241,151 +270,37 @@ function formatLimit(value: number): string {
return value === 0 ? 'Unlimited' : value.toLocaleString()
}
-async function inviteMember() {
- if (!inviteEmail.value.trim()) return
- inviting.value = true
- const prevWs = wsStore.currentWorkspaceId
- wsStore.setWorkspace(wsId)
- try {
- await workspaceApi.invite({ email: inviteEmail.value.trim(), role: inviteRole.value })
- notify.success('Invitation sent')
- showInviteModal.value = false
- inviteEmail.value = ''
- inviteRole.value = 'editor'
- await fetchInvitations()
- } catch (err: any) {
- notify.error(err.response?.data?.error?.message || 'Failed to invite')
- } finally {
- inviting.value = false
- wsStore.setWorkspace(prevWs)
- }
-}
-
-async function updateRole(member: WorkspaceMember, newRole: WorkspaceRole) {
- const prevWs = wsStore.currentWorkspaceId
- wsStore.setWorkspace(wsId)
- try {
- await workspaceApi.updateMemberRole(member.user_id, newRole)
- notify.success('Role updated')
- await fetchMembers()
- } catch (err: any) {
- notify.error(err.response?.data?.error?.message || 'Failed to update role')
- } finally {
- wsStore.setWorkspace(prevWs)
- }
-}
-
-async function removeMember(member: WorkspaceMember) {
- const ok = await confirm({ title: 'Remove Member', message: `Remove ${member.name || member.email} from this workspace?`, confirmText: 'Remove', variant: 'danger' })
- if (!ok) return
- const prevWs = wsStore.currentWorkspaceId
- wsStore.setWorkspace(wsId)
- try {
- await workspaceApi.removeMember(member.user_id)
- notify.success('Member removed')
- await fetchMembers()
- } catch (err: any) {
- notify.error(err.response?.data?.error?.message || 'Failed to remove')
- } finally {
- wsStore.setWorkspace(prevWs)
- }
-}
-
-async function revokeInvitation(inv: WorkspaceInvitation) {
- const ok = await confirm({ title: 'Revoke Invitation', message: `Revoke the invitation for ${inv.email}?`, confirmText: 'Revoke', variant: 'warning' })
- if (!ok) return
- const prevWs = wsStore.currentWorkspaceId
- wsStore.setWorkspace(wsId)
- try {
- await workspaceApi.cancelInvitation(inv.id)
- notify.success('Invitation revoked')
- await fetchInvitations()
- } catch (err: any) {
- notify.error(err.response?.data?.error?.message || 'Failed to revoke')
- } finally {
- wsStore.setWorkspace(prevWs)
- }
-}
-
async function saveSettings() {
saving.value = true
- const prevWs = wsStore.currentWorkspaceId
- wsStore.setWorkspace(wsId)
try {
- await workspaceApi.update({ name: editName.value.trim(), description: editDescription.value.trim() })
+ await withWorkspace(() => workspaceApi.update({ name: editName.value.trim(), description: editDescription.value.trim() }))
notify.success('Workspace updated')
await wsStore.fetchWorkspaces()
} catch (err: any) {
notify.error(err.response?.data?.error?.message || 'Failed to update')
} finally {
saving.value = false
- wsStore.setWorkspace(prevWs)
}
}
async function deleteWorkspace() {
const ok = await confirm({ title: 'Delete Workspace', message: 'Are you sure you want to delete this workspace? This cannot be undone.', confirmText: 'Delete', variant: 'danger' })
if (!ok) return
- const prevWs = wsStore.currentWorkspaceId
- wsStore.setWorkspace(wsId)
try {
- await workspaceApi.delete()
+ await withWorkspace(() => workspaceApi.delete())
notify.success('Workspace deleted')
wsStore.setWorkspace(null)
await wsStore.fetchWorkspaces()
router.push('/workspaces')
} catch (err: any) {
notify.error(err.response?.data?.error?.message || 'Failed to delete')
- wsStore.setWorkspace(prevWs)
- }
-}
-
-function toggleResource(key: string) {
- const idx = selectedResources.value.indexOf(key)
- if (idx >= 0) {
- selectedResources.value.splice(idx, 1)
- } else {
- selectedResources.value.push(key)
- }
-}
-
-function selectAllResources() {
- if (selectedResources.value.length === availableResources.length) {
- selectedResources.value = []
- } else {
- selectedResources.value = availableResources.map(r => r.key)
- }
-}
-
-async function transferData() {
- if (selectedResources.value.length === 0) return
- const ok = await confirm({ title: 'Transfer Data', message: `Transfer ${selectedResources.value.length} resource type(s) from your personal account to this workspace? This cannot be undone.`, confirmText: 'Transfer', variant: 'warning' })
- if (!ok) return
-
- transferring.value = true
- transferResults.value = null
- const prevWs = wsStore.currentWorkspaceId
- wsStore.setWorkspace(wsId)
- try {
- const res = await workspaceApi.transferData(selectedResources.value)
- transferResults.value = res.data.data.results
- transferTotal.value = res.data.data.total
- notify.success(res.data.data.message)
- selectedResources.value = []
- } catch (err: any) {
- notify.error(err.response?.data?.error?.message || 'Failed to transfer data')
- } finally {
- transferring.value = false
- wsStore.setWorkspace(prevWs)
}
}
async function exportWorkspaceData() {
exporting.value = true
- const prevWs = wsStore.currentWorkspaceId
- wsStore.setWorkspace(wsId)
try {
- const res = await workspaceApi.exportData()
+ const res = await withWorkspace(() => workspaceApi.exportData())
const blob = new Blob([JSON.stringify(res.data.data, null, 2)], { type: 'application/json' })
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
@@ -398,7 +313,6 @@ async function exportWorkspaceData() {
notify.error('Failed to export workspace data')
} finally {
exporting.value = false
- wsStore.setWorkspace(prevWs)
}
}
@@ -422,12 +336,10 @@ async function handleWorkspaceImportFile(event: Event) {
}
importing.value = true
- const prevWs = wsStore.currentWorkspaceId
- wsStore.setWorkspace(wsId)
try {
const text = await file.text()
const data = JSON.parse(text)
- const res = await workspaceApi.importData(data)
+ const res = await withWorkspace(() => workspaceApi.importData(data))
notify.success(res.data.data.message || 'Workspace data imported successfully')
} catch (e: any) {
if (e instanceof SyntaxError) {
@@ -438,27 +350,17 @@ async function handleWorkspaceImportFile(event: Event) {
} finally {
importing.value = false
if (importFileRef.value) importFileRef.value.value = ''
- wsStore.setWorkspace(prevWs)
}
}
-function roleBadgeClass(role: string): string {
- if (role === 'owner') return 'badge-primary'
- if (role === 'admin') return 'badge-warning'
- return 'badge-neutral'
-}
-
-function formatDate(dateStr: string): string {
- return new Date(dateStr).toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' })
-}
-
onMounted(async () => {
await fetchWorkspace()
- await Promise.all([fetchMembers(), fetchInvitations(), fetchPlan()])
+ await fetchPlan()
})
watch(activeTab, (value) => {
- if (value === 'settings' && isOwner.value) fetchSSO()
+ if (value === 'settings' && isAdminOrOwner.value) fetchWorkspaceSettings()
+ if (value === 'sso' && isOwner.value) fetchSSO()
}, { immediate: true })
</script>
@@ -466,12 +368,15 @@ watch(activeTab, (value) => {
<div>
<div class="page-header">
<div>
- <h1>{{ ws?.name || 'Workspace' }}</h1>
+ <h1>{{ ws?.name || 'Workspace' }} — Settings</h1>
<p v-if="ws?.slug" style="color: var(--text-muted); font-size: 13px; margin-top: 2px;">
<code>{{ ws.slug }}</code>
</p>
</div>
- <button class="btn btn-secondary" @click="router.push('/workspaces')">Back</button>
+ <div style="display: flex; gap: 8px;">
+ <button class="btn btn-secondary" @click="router.push(`/workspaces/${wsId}/members`)">Members</button>
+ <button class="btn btn-secondary" @click="router.push('/workspaces')">Back</button>
+ </div>
</div>
<div v-if="loading" class="loading-page">
@@ -481,97 +386,18 @@ watch(activeTab, (value) => {
<template v-else>
<!-- Tabs -->
<div class="tabs">
- <button :class="['tab', { active: activeTab === 'members' }]" @click="activeTab = 'members'">
- Members ({{ members.length }})
+ <button v-if="isAdminOrOwner" :class="['tab', { active: activeTab === 'settings' }]" @click="activeTab = 'settings'">
+ Settings
</button>
- <button :class="['tab', { active: activeTab === 'invitations' }]" @click="activeTab = 'invitations'">
- Invitations ({{ invitations.length }})
+ <button v-if="isAdminOrOwner" :class="['tab', { active: activeTab === 'data' }]" @click="activeTab = 'data'">
+ Data Management
+ </button>
+ <button v-if="isOwner" :class="['tab', { active: activeTab === 'sso' }]" @click="activeTab = 'sso'">
+ SSO
</button>
<button :class="['tab', { active: activeTab === 'plan' }]" @click="activeTab = 'plan'">
Plan
</button>
- <button v-if="isAdminOrOwner" :class="['tab', { active: activeTab === 'settings' }]" @click="activeTab = 'settings'">
- Settings
- </button>
- </div>
-
- <!-- Members Tab -->
- <div v-if="activeTab === 'members'" class="card">
- <div class="card-header">
- <span>Members</span>
- <button v-if="isAdminOrOwner" class="btn btn-primary btn-sm" @click="showInviteModal = true">Invite</button>
- </div>
- <div class="table-wrapper">
- <table>
- <thead>
- <tr>
- <th>Name</th>
- <th>Email</th>
- <th>Role</th>
- <th>Joined</th>
- <th v-if="isAdminOrOwner">Actions</th>
- </tr>
- </thead>
- <tbody>
- <tr v-for="m in members" :key="m.id">
- <td style="font-weight: 500;">{{ m.name }}</td>
- <td>{{ m.email }}</td>
- <td>
- <select
- v-if="isAdminOrOwner && m.role !== 'owner'"
- :value="m.role"
- class="form-select form-select-sm"
- @change="updateRole(m, ($event.target as HTMLSelectElement).value as WorkspaceRole)"
- >
- <option value="admin">Admin</option>
- <option value="editor">Editor</option>
- <option value="viewer">Viewer</option>
- </select>
- <span v-else class="badge" :class="roleBadgeClass(m.role)">{{ m.role }}</span>
- </td>
- <td>{{ formatDate(m.created_at) }}</td>
- <td v-if="isAdminOrOwner">
- <button v-if="m.role !== 'owner'" class="btn btn-danger btn-sm" @click="removeMember(m)">Remove</button>
- </td>
- </tr>
- </tbody>
- </table>
- </div>
- </div>
-
- <!-- Invitations Tab -->
- <div v-if="activeTab === 'invitations'" class="card">
- <div class="card-header">
- <span>Pending Invitations</span>
- <button v-if="isAdminOrOwner" class="btn btn-primary btn-sm" @click="showInviteModal = true">Invite</button>
- </div>
- <div v-if="invitations.length === 0" class="empty-state">
- <p>No pending invitations.</p>
- </div>
- <div v-else class="table-wrapper">
- <table>
- <thead>
- <tr>
- <th>Email</th>
- <th>Role</th>
- <th>Expires</th>
- <th>Sent</th>
- <th v-if="isAdminOrOwner">Actions</th>
- </tr>
- </thead>
- <tbody>
- <tr v-for="inv in invitations" :key="inv.id">
- <td>{{ inv.email }}</td>
- <td><span class="badge" :class="roleBadgeClass(inv.role)">{{ inv.role }}</span></td>
- <td>{{ formatDate(inv.expires_at) }}</td>
- <td>{{ formatDate(inv.created_at) }}</td>
- <td v-if="isAdminOrOwner">
- <button class="btn btn-danger btn-sm" @click="revokeInvitation(inv)">Revoke</button>
- </td>
- </tr>
- </tbody>
- </table>
- </div>
</div>
<!-- Plan Tab -->
@@ -703,12 +529,146 @@ watch(activeTab, (value) => {
</button>
</div>
- <!-- Single Sign-On (SSO) — owners only -->
+ <!-- Sending & Operational Settings -->
+ <div class="card-body" style="border-top: 1px solid var(--border-primary);">
+ <h4 style="font-size: 14px; font-weight: 600; margin-bottom: 8px;">Sending &amp; Operational Settings</h4>
+ <p style="font-size: 13px; color: var(--text-secondary); margin-bottom: 16px;">
+ Defaults applied to this workspace's emails, webhooks, and API keys.
+ </p>
+ <div v-if="wsSettingsLoading" class="loading-page" style="padding: 24px 0;"><div class="spinner"></div></div>
+ <template v-else>
+ <div class="form-group">
+ <label class="form-label">Timezone</label>
+ <select v-model="wsSettings.timezone" class="form-select">
+ <option v-for="tz in timezones" :key="tz" :value="tz">{{ tz }}</option>
+ </select>
+ </div>
+ <div class="form-group">
+ <label class="form-label">Default Sender Name</label>
+ <input v-model="wsSettings.default_sender_name" class="form-input" placeholder="Acme Inc." />
+ </div>
+ <div class="form-group">
+ <label class="form-label">Default Sender Email</label>
+ <input v-model="wsSettings.default_sender_email" type="email" class="form-input" placeholder="[email protected]" />
+ </div>
+ <div class="form-group">
+ <label class="form-label">Webhook Retry Count</label>
+ <input v-model.number="wsSettings.webhook_retry_count" type="number" min="0" max="10" class="form-input" />
+ </div>
+ <div class="form-group">
+ <label class="form-label">API Key Expiry (days)</label>
+ <input v-model.number="wsSettings.api_key_expiry_days" type="number" min="0" class="form-input" />
+ <small style="font-size: 12px; color: var(--text-muted); margin-top: 4px; display: block;">0 means keys never expire by default.</small>
+ </div>
+ <div class="form-group">
+ <label style="display: flex; align-items: center; gap: 8px; cursor: pointer;">
+ <input type="checkbox" v-model="wsSettings.bounce_auto_suppress" />
+ <span>Auto-suppress on hard bounce</span>
+ </label>
+ <small style="font-size: 12px; color: var(--text-muted); margin-top: 4px; display: block;">Automatically add hard-bounced addresses to the suppression list.</small>
+ </div>
+ <button class="btn btn-primary" :disabled="wsSettingsSaving" @click="saveWorkspaceSettings">
+ {{ wsSettingsSaving ? 'Saving...' : 'Save Settings' }}
+ </button>
+ </template>
+ </div>
+
+ <!-- Domain Security -->
+ <div class="card-body" style="border-top: 1px solid var(--border-primary);">
+ <h4 style="font-size: 14px; font-weight: 600; margin-bottom: 8px;">Domain Security</h4>
+ <p style="font-size: 13px; color: var(--text-secondary); margin-bottom: 16px;">
+ When strict domain mode is enabled, this workspace can only send from domains it has
+ added and ownership-verified. Disable it to send from any sender domain.
+ </p>
+ <div v-if="wsSettingsLoading" class="loading-page" style="padding: 24px 0;"><div class="spinner"></div></div>
+ <template v-else>
+ <div class="form-group">
+ <label style="display: flex; align-items: center; gap: 8px; cursor: pointer;">
+ <input type="checkbox" v-model="wsSettings.require_verified_domain" />
+ <span>Require verified sender domain (strict mode)</span>
+ </label>
+ </div>
+ <button class="btn btn-primary" :disabled="wsSettingsSaving" @click="saveWorkspaceSettings">
+ {{ wsSettingsSaving ? 'Saving...' : 'Save' }}
+ </button>
+ </template>
+ </div>
+
+ <div class="card-body" style="border-top: 1px solid var(--border-primary);">
+ <h4 style="font-size: 14px; font-weight: 600; margin-bottom: 8px;">Data Export / Import</h4>
+ <p style="font-size: 13px; color: var(--text-secondary); margin-bottom: 12px;">
+ Export all workspace data (settings, templates, stylesheets, languages, contacts, contact lists, webhooks,
+ SMTP servers, domains, subscribers, subscriber lists, and suppressions) as a JSON file.
+ </p>
+ <p style="font-size: 12px; color: var(--text-muted); margin-bottom: 16px;">
+ SMTP server passwords are not included in exports. Imported SMTP servers will be disabled until reconfigured.
+ Imported domains will require re-verification.
+ </p>
+ <div style="display: flex; gap: 8px; flex-wrap: wrap;">
+ <button class="btn btn-primary" :disabled="exporting" @click="exportWorkspaceData">
+ {{ exporting ? 'Exporting...' : 'Export Workspace Data' }}
+ </button>
+ <button class="btn btn-secondary" :disabled="importing" @click="triggerWorkspaceImport">
+ {{ importing ? 'Importing...' : 'Import Data' }}
+ </button>
+ <input ref="importFileRef" type="file" accept=".json" style="display: none" @change="handleWorkspaceImportFile" />
+ </div>
+ </div>
+
<div v-if="isOwner" class="card-body" style="border-top: 1px solid var(--border-primary);">
- <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 8px;">
- <h4 style="font-size: 14px; font-weight: 600; margin: 0;">Single Sign-On (SSO)</h4>
- <button v-if="ssoConfig" class="btn btn-danger btn-sm" @click="removeSSO">Remove SSO</button>
+ <h4 style="color: var(--danger-600); margin-bottom: 8px;">Danger Zone</h4>
+ <p style="font-size: 13px; color: var(--text-muted); margin-bottom: 12px;">
+ Deleting this workspace will permanently remove all its resources. This cannot be undone.
+ </p>
+ <button class="btn btn-danger" @click="deleteWorkspace">Delete Workspace</button>
+ </div>
+ </div>
+
+ <!-- Data Management (GDPR) Tab — admin/owner only -->
+ <div v-if="activeTab === 'data' && isAdminOrOwner" class="card">
+ <div class="card-header"><span>Data Management (GDPR)</span></div>
+ <div class="card-body">
+ <p style="font-size: 13px; color: var(--text-secondary); margin-bottom: 20px;">
+ Manage this workspace's data for GDPR compliance. Delete specific contacts or purge old email logs.
+ </p>
+
+ <div>
+ <h4 style="font-size: 14px; font-weight: 600; margin-bottom: 4px;">Delete Contact Data</h4>
+ <p style="font-size: 13px; color: var(--text-secondary); margin-bottom: 12px;">
+ Remove a specific contact by email (including suppression list and list memberships), or leave empty to delete all contacts in this workspace.
+ </p>
+ <div style="display: flex; gap: 8px; align-items: center;">
+ <input v-model="gdprEmail" type="email" class="form-input" placeholder="[email protected] (or leave empty for all)" style="flex: 1" />
+ <button class="btn btn-danger" :disabled="deletingContacts" @click="deleteWorkspaceContacts">
+ {{ deletingContacts ? 'Deleting...' : 'Delete' }}
+ </button>
+ </div>
</div>
+
+ <div style="margin-top: 24px;">
+ <h4 style="font-size: 14px; font-weight: 600; margin-bottom: 4px;">Delete Email Logs</h4>
+ <p style="font-size: 13px; color: var(--text-secondary); margin-bottom: 12px;">
+ Delete email logs and associated bounce records. Set days to 0 to delete all logs.
+ </p>
+ <div style="display: flex; gap: 8px; align-items: center;">
+ <label class="form-label" style="margin: 0; white-space: nowrap">Older than</label>
+ <input v-model.number="gdprDays" type="number" class="form-input" min="0" style="width: 100px" />
+ <label class="form-label" style="margin: 0">days</label>
+ <button class="btn btn-danger" :disabled="deletingEmails" @click="deleteWorkspaceEmailLogs">
+ {{ deletingEmails ? 'Deleting...' : 'Delete Logs' }}
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- SSO Tab — owners only -->
+ <div v-if="activeTab === 'sso' && isOwner" class="card">
+ <div class="card-header">
+ <span>Single Sign-On (SSO)</span>
+ <button v-if="ssoConfig" class="btn btn-danger btn-sm" @click="removeSSO">Remove SSO</button>
+ </div>
+ <div class="card-body">
<p style="font-size: 13px; color: var(--text-secondary); margin-bottom: 16px;">
Configure SSO to allow workspace members to authenticate using an OAuth provider.
</p>
@@ -757,139 +717,8 @@ watch(activeTab, (value) => {
</form>
</template>
</div>
-
- <!-- Transfer Personal Data to Workspace -->
- <div class="card-body" style="border-top: 1px solid var(--border-primary);">
- <h4 style="font-size: 14px; font-weight: 600; margin-bottom: 8px;">Transfer Personal Data to Workspace</h4>
- <p style="font-size: 13px; color: var(--text-secondary); margin-bottom: 16px;">
- Move your personal resources into this workspace. Transferred data will no longer appear in your personal account.
- </p>
-
- <div style="margin-bottom: 16px;">
- <label class="form-label" style="margin-bottom: 8px;">Select resources to transfer</label>
- <div style="margin-bottom: 8px;">
- <label style="display: flex; align-items: center; gap: 8px; cursor: pointer; font-size: 13px; font-weight: 600; color: var(--text-primary); padding: 6px 0;">
- <input
- type="checkbox"
- :checked="selectedResources.length === availableResources.length"
- @change="selectAllResources"
- />
- Select All
- </label>
- </div>
- <div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)); gap: 4px;">
- <label
- v-for="res in availableResources"
- :key="res.key"
- style="display: flex; align-items: center; gap: 8px; cursor: pointer; font-size: 13px; color: var(--text-secondary); padding: 6px 8px; border-radius: var(--radius-sm); transition: background var(--transition);"
- :style="{ background: selectedResources.includes(res.key) ? 'var(--primary-50)' : 'transparent' }"
- >
- <input
- type="checkbox"
- :checked="selectedResources.includes(res.key)"
- @change="toggleResource(res.key)"
- />
- {{ res.label }}
- </label>
- </div>
- </div>
-
- <button
- class="btn btn-primary"
- :disabled="transferring || selectedResources.length === 0"
- @click="transferData"
- >
- {{ transferring ? 'Transferring...' : `Transfer ${selectedResources.length} resource type(s)` }}
- </button>
-
- <!-- Transfer Results -->
- <div v-if="transferResults" style="margin-top: 20px; border-top: 1px solid var(--border-primary); padding-top: 16px;">
- <h4 style="font-size: 14px; font-weight: 600; margin-bottom: 12px;">
- Transfer Complete — {{ transferTotal }} record(s) moved
- </h4>
- <div class="table-wrapper">
- <table>
- <thead>
- <tr>
- <th>Resource</th>
- <th>Records Transferred</th>
- </tr>
- </thead>
- <tbody>
- <tr v-for="r in transferResults" :key="r.resource">
- <td style="font-weight: 500; text-transform: capitalize;">{{ r.resource.replace(/_/g, ' ') }}</td>
- <td>
- <span v-if="r.count > 0" class="badge badge-primary">{{ r.count }}</span>
- <span v-else style="color: var(--text-muted);">0</span>
- </td>
- </tr>
- </tbody>
- </table>
- </div>
- </div>
- </div>
-
- <div class="card-body" style="border-top: 1px solid var(--border-primary);">
- <h4 style="font-size: 14px; font-weight: 600; margin-bottom: 8px;">Data Export / Import</h4>
- <p style="font-size: 13px; color: var(--text-secondary); margin-bottom: 12px;">
- Export all workspace data (settings, templates, stylesheets, languages, contacts, contact lists, webhooks,
- SMTP servers, domains, subscribers, subscriber lists, and suppressions) as a JSON file.
- </p>
- <p style="font-size: 12px; color: var(--text-muted); margin-bottom: 16px;">
- SMTP server passwords are not included in exports. Imported SMTP servers will be disabled until reconfigured.
- Imported domains will require re-verification.
- </p>
- <div style="display: flex; gap: 8px; flex-wrap: wrap;">
- <button class="btn btn-primary" :disabled="exporting" @click="exportWorkspaceData">
- {{ exporting ? 'Exporting...' : 'Export Workspace Data' }}
- </button>
- <button class="btn btn-secondary" :disabled="importing" @click="triggerWorkspaceImport">
- {{ importing ? 'Importing...' : 'Import Data' }}
- </button>
- <input ref="importFileRef" type="file" accept=".json" style="display: none" @change="handleWorkspaceImportFile" />
- </div>
- </div>
-
- <div v-if="isOwner" class="card-body" style="border-top: 1px solid var(--border-primary);">
- <h4 style="color: var(--danger-600); margin-bottom: 8px;">Danger Zone</h4>
- <p style="font-size: 13px; color: var(--text-muted); margin-bottom: 12px;">
- Deleting this workspace will permanently remove all its resources. This cannot be undone.
- </p>
- <button class="btn btn-danger" @click="deleteWorkspace">Delete Workspace</button>
- </div>
</div>
</template>
-
- <!-- Invite Modal -->
- <div v-if="showInviteModal" class="modal-overlay" @click.self="showInviteModal = false">
- <div class="modal">
- <div class="modal-header">
- <h3>Invite Member</h3>
- </div>
- <form @submit.prevent="inviteMember">
- <div class="modal-body">
- <div class="form-group">
- <label class="form-label">Email Address</label>
- <input v-model="inviteEmail" type="email" class="form-input" placeholder="[email protected]" required />
- </div>
- <div class="form-group">
- <label class="form-label">Role</label>
- <select v-model="inviteRole" class="form-select">
- <option value="admin">Admin</option>
- <option value="editor">Editor</option>
- <option value="viewer">Viewer</option>
- </select>
- </div>
- </div>
- <div class="modal-footer">
- <button type="button" class="btn btn-secondary" @click="showInviteModal = false">Cancel</button>
- <button type="submit" class="btn btn-primary" :disabled="inviting || !inviteEmail.trim()">
- {{ inviting ? 'Sending...' : 'Send Invitation' }}
- </button>
- </div>
- </form>
- </div>
- </div>
</div>
</template>