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: rename slug to name and name to display_name across resources

Jonas Kaninda3fe236d480b6
diff --git a/cmd/posta/doctor.go b/cmd/posta/doctor.go
index 41b2e21..c5447cb 100644
--- a/cmd/posta/doctor.go
+++ b/cmd/posta/doctor.go
@@ -120,7 +120,7 @@ func runDoctorWorkspaces() error {
fmt.Println(strings.Repeat("-", 60))
if blocked {
fmt.Println("NOT SAFE TO UPGRADE — resolve the blocking rows above first.")
- fmt.Printf("Reserved system slug: %q\n", workspacesvc.SystemSlug)
+ fmt.Printf("Reserved system workspace name: %q\n", workspacesvc.SystemName)
os.Exit(1)
}
fmt.Println("Safe to upgrade.")
diff --git a/docs/docs/admin/oauth-providers.md b/docs/docs/admin/oauth-providers.md
index 7740a5d..e00f93e 100644
--- a/docs/docs/admin/oauth-providers.md
+++ b/docs/docs/admin/oauth-providers.md
@@ -36,8 +36,8 @@ POST /api/v1/admin/oauth/providers
```json
{
- "name": "Google",
- "slug": "google",
+ "name": "google",
+ "display_name": "Google",
"type": "google",
"client_id": "your-google-client-id",
"client_secret": "your-google-client-secret",
@@ -50,8 +50,8 @@ POST /api/v1/admin/oauth/providers
```json
{
- "name": "Keycloak",
- "slug": "keycloak",
+ "name": "keycloak",
+ "display_name": "Keycloak",
"type": "oidc",
"client_id": "posta",
"client_secret": "your-client-secret",
@@ -68,8 +68,8 @@ POST /api/v1/admin/oauth/providers
| Field | Required | Default | Description |
|-------|----------|---------|-------------|
-| `name` | Yes | — | Display name |
-| `slug` | Yes | — | URL-safe identifier (must be unique) |
+| `name` | No | from `display_name` | Identifier in the sign-in URLs (`/auth/oauth/{name}/authorize`): lowercase letters, digits and hyphens, unique. Cannot change later. |
+| `display_name` | No | `name` | Shown on the sign-in button. One of `name` and `display_name` is required. |
| `type` | Yes | — | `google` or `oidc` |
| `client_id` | Yes | — | OAuth client ID |
| `client_secret` | Yes | — | OAuth client secret |
diff --git a/docs/docs/messages/creating-a-form.md b/docs/docs/messages/creating-a-form.md
index 2e53218..24d09a8 100644
--- a/docs/docs/messages/creating-a-form.md
+++ b/docs/docs/messages/creating-a-form.md
@@ -14,7 +14,8 @@ curl -X POST https://posta.example.com/api/v1/workspaces/current/forms \
-H "X-Posta-Workspace-Id: 1" \
-H "Content-Type: application/json" \
-d '{
- "name": "Contact form",
+ "name": "contact",
+ "display_name": "Contact form",
"allowed_origins": ["https://example.com", "https://www.example.com"],
"notify_emails": ["[email protected]"],
"reply_from": "[email protected]"
@@ -23,6 +24,8 @@ curl -X POST https://posta.example.com/api/v1/workspaces/current/forms \
The response includes `public_key` — the unguessable 22-character string that appears in your embed URL.
+`name` identifies the form in the API: lowercase letters, digits and hyphens, unique in the workspace. `display_name` is its label. Send either; the other is derived. Before 0.18 these were `slug` and `name`; requests in the old shape are still read the old way until 0.19.
+
## Example forms
Every new workspace starts with three example forms you can use as they are, edit or delete:
diff --git a/docs/docs/templates/creating-templates.md b/docs/docs/templates/creating-templates.md
index dc5d7a9..de9c422 100644
--- a/docs/docs/templates/creating-templates.md
+++ b/docs/docs/templates/creating-templates.md
@@ -6,6 +6,19 @@ description: Create and manage email templates
# Creating Templates
+## Names
+
+A template has two names:
+
+- **`name`**: its identifier, like `welcome-email`. It is what you send as `template` and is unique in the workspace: up to 63 lowercase letters, digits and hyphens.
+- **`display_name`**: its label in the dashboard, like `Welcome Email`.
+
+When you create a template you can send either. A missing `name` is derived from the display name, and a missing display name is the name.
+
+:::caution Changed in 0.18
+Before 0.18 a template had only `name`, which was both its label and what you sent. Upgrading keeps every label as the `display_name` and gives each template a `name` derived from it: `Welcome Email` becomes `welcome-email`. Sending by the old label still works until 0.19 and logs a deprecation warning; switch to the new names. Stylesheets, forms, workspaces and OAuth providers follow the same scheme.
+:::
+
## Create a Template
```
@@ -21,6 +34,7 @@ curl -X POST http://localhost:9000/api/v1/workspaces/current/templates \
-H "Content-Type: application/json" \
-d '{
"name": "welcome",
+ "display_name": "Welcome",
"description": "Welcome email for new users",
"html": "<h1>Welcome, {{name}}!</h1><p>Thanks for joining.</p>",
"text": "Welcome, {{name}}! Thanks for joining.",
@@ -38,6 +52,7 @@ Response:
"data": {
"id": "uuid",
"name": "welcome",
+ "display_name": "Welcome",
"description": "Welcome email for new users",
"active_version_id": "version-uuid",
"created_at": "2026-01-01T00:00:00Z"
@@ -63,12 +78,14 @@ PUT /api/v1/workspaces/current/templates/{id}
```json
{
- "name": "welcome-v2",
+ "display_name": "Welcome (v2)",
"description": "Updated welcome email",
"default_language": "en"
}
```
+Changing `name` renames the template for sending: callers that send the old name stop finding it.
+
## Delete a Template
```
diff --git a/docs/docs/templates/import-export.md b/docs/docs/templates/import-export.md
index e5748cd..c2a3932 100644
--- a/docs/docs/templates/import-export.md
+++ b/docs/docs/templates/import-export.md
@@ -58,3 +58,30 @@ curl -X POST http://localhost:9000/api/v1/workspaces/current/templates/import \
:::note
If a template with the same name already exists, the import will fail with `409 Conflict`. Rename the template in the JSON before importing, or delete the existing template first.
:::
+
+## Import an HTML File
+
+```
+POST /api/v1/workspaces/current/templates/import-html
+```
+
+Upload an `.html` or `.htm` file (up to 2 MB) as `multipart/form-data` under `file`. CSS in `<style>` blocks becomes a stylesheet; a `<link rel="stylesheet" href="brand.css">` attaches the workspace stylesheet named `brand` instead. Returns `201 Created` with the new template.
+
+Every other form field is optional and overrides a default:
+
+| Field | Default |
+|-------|---------|
+| `name` | Derived from `display_name` |
+| `display_name` | The filename without its extension |
+| `subject` | The document's `<title>`, or else the display name |
+| `language` | The workspace's default language |
+| `description` | `Imported from <filename>` |
+
+```bash
+curl -X POST http://localhost:9000/api/v1/workspaces/current/templates/import-html \
+ -H "Authorization: Bearer <jwt-token>" \
+ -H "X-Posta-Workspace-Id: 1" \
+ -F display_name="Spring sale" \
+ -F subject="20% off this week"
+```
diff --git a/docs/docs/templates/stylesheets.md b/docs/docs/templates/stylesheets.md
index b7bdfbe..7aeb81e 100644
--- a/docs/docs/templates/stylesheets.md
+++ b/docs/docs/templates/stylesheets.md
@@ -21,10 +21,13 @@ POST /api/v1/workspaces/current/stylesheets
```json
{
"name": "brand-styles",
+ "display_name": "Brand styles",
"css": "h1 { color: #333; font-family: Arial, sans-serif; } .btn { background-color: #7c3aed; color: white; padding: 12px 24px; border-radius: 6px; text-decoration: none; }"
}
```
+`name` is the stylesheet's identifier (lowercase letters, digits and hyphens, unique in the workspace); imported HTML templates link stylesheets by it. `display_name` is its label. Send either; the other is derived.
+
## List Stylesheets
```
diff --git a/docs/docs/workspaces/overview.md b/docs/docs/workspaces/overview.md
index c8c5bdf..1705f41 100644
--- a/docs/docs/workspaces/overview.md
+++ b/docs/docs/workspaces/overview.md
@@ -42,7 +42,7 @@ A server you add to the system workspace yourself is left alone: the provisioned
A workspace is an isolated environment where team members collaborate. Resources created within a workspace are only visible to members of that workspace. Each workspace has:
-- A unique **name** and **slug** (a URL-friendly identifier)
+- A unique **name**, its identifier (`acme`), and a **display name**, its label (`Acme Inc`)
- An **owner** (the creator)
- **Members**, each with a role
- A **default language**
@@ -147,15 +147,15 @@ Request body:
```json
{
- "name": "Acme Inc",
- "slug": "acme",
+ "name": "acme",
+ "display_name": "Acme Inc",
"description": "Marketing and transactional mail",
"default_language": "en",
"seed_defaults": true
}
```
-Only `name` is required. If `slug` is omitted it is derived from the name; slugs must contain only lowercase letters, numbers, and hyphens, and must be unique. `default_language` defaults to `en`. The caller becomes the workspace **owner**.
+Send `name`, `display_name` or both. A missing `name` is derived from the display name, and a missing display name is the name. A name is up to 63 lowercase letters, digits and hyphens, unique on the platform, and cannot change after creation; `display_name` can. `default_language` defaults to `en`. The caller becomes the workspace **owner**.
`seed_defaults` controls whether the new workspace starts with content: a welcome template in English, French and German, a default stylesheet, and the matching languages. It defaults to `true`, so omitting it gives you a workspace you can send from immediately. Send `false` when you intend to populate the workspace from an [export](../gdpr/data-export-import.md) or the API and do not want the starter template in the way.
@@ -165,7 +165,7 @@ Seeding is best effort and runs after the workspace exists, so a workspace is ne
curl -X POST http://localhost:9000/api/v1/workspaces \
-H "Authorization: Bearer <jwt>" \
-H "Content-Type: application/json" \
- -d '{"name": "Acme Inc", "slug": "acme"}'
+ -d '{"name": "acme", "display_name": "Acme Inc"}'
```
Response (`201`):
@@ -174,8 +174,8 @@ Response (`201`):
{
"data": {
"id": 1,
- "name": "Acme Inc",
- "slug": "acme",
+ "name": "acme",
+ "display_name": "Acme Inc",
"description": "",
"owner_id": 42,
"role": "owner",
@@ -185,7 +185,7 @@ Response (`201`):
}
```
-Creating a workspace is subject to your plan's workspace quota; exceeding it returns `403`. Creating a duplicate slug returns `409`.
+Creating a workspace is subject to your plan's workspace quota; exceeding it returns `403`. Creating a workspace with a name that is taken returns `409`.
## Listing workspaces
diff --git a/internal/cron/jobs/message_digest.go b/internal/cron/jobs/message_digest.go
index 8ee04c0..69310a7 100644
--- a/internal/cron/jobs/message_digest.go
+++ b/internal/cron/jobs/message_digest.go
@@ -155,7 +155,7 @@ func (j *MessageDigestJob) runMode(mode models.NotifyMode, since time.Time, labe
workspaceName := ""
if ws, err := j.workspaceRepo.FindByID(*form.WorkspaceID); err == nil {
- workspaceName = ws.Name
+ workspaceName = ws.DisplayName
}
noun := "message(s)"
if form.IsCollect() {
@@ -167,7 +167,7 @@ func (j *MessageDigestJob) runMode(mode models.NotifyMode, since time.Time, labe
items := groups[target]
data := map[string]any{
"Period": label,
- "FormName": form.Name,
+ "FormName": form.DisplayName,
"Collect": form.IsCollect(),
"Total": len(items),
"Items": items,
@@ -179,7 +179,7 @@ func (j *MessageDigestJob) runMode(mode models.NotifyMode, since time.Time, labe
if workspaceName != "" {
data["WorkspaceName"] = workspaceName
}
- subject := fmt.Sprintf("%s digest: %d new %s on %s", label, len(items), noun, form.Name)
+ subject := fmt.Sprintf("%s digest: %d new %s on %s", label, len(items), noun, form.DisplayName)
if err := j.send(form, target, subject, data); err != nil {
logger.Error("message-digest: failed to send", "form_id", form.ID, "error", err)
failed = true
diff --git a/internal/handlers/admin_domain_handler.go b/internal/handlers/admin_domain_handler.go
index 3af5bca..a6bfb7b 100644
--- a/internal/handlers/admin_domain_handler.go
+++ b/internal/handlers/admin_domain_handler.go
@@ -268,11 +268,11 @@ func (h *AdminDomainHandler) workspaceNames(domains []models.Domain) map[uint]st
return out
}
var rows []models.Workspace
- if err := h.db.Select("id", "name").Where("id IN ?", ids).Find(&rows).Error; err != nil {
+ if err := h.db.Select("id", "display_name").Where("id IN ?", ids).Find(&rows).Error; err != nil {
return out
}
for i := range rows {
- out[rows[i].ID] = rows[i].Name
+ out[rows[i].ID] = rows[i].DisplayName
}
return out
}
@@ -282,10 +282,10 @@ func (h *AdminDomainHandler) workspaceName(id *uint) string {
return ""
}
var ws models.Workspace
- if err := h.db.Select("id", "name").First(&ws, *id).Error; err != nil {
+ if err := h.db.Select("id", "display_name").First(&ws, *id).Error; err != nil {
return ""
}
- return ws.Name
+ return ws.DisplayName
}
func (h *AdminDomainHandler) ownerEmails(domains []models.Domain) map[uint]string {
diff --git a/internal/handlers/admin_handler.go b/internal/handlers/admin_handler.go
index 416a9f8..000f77a 100644
--- a/internal/handlers/admin_handler.go
+++ b/internal/handlers/admin_handler.go
@@ -507,14 +507,14 @@ func (h *AdminHandler) UserMetrics(c *okapi.Context, req *AdminGetUserRequest) e
// AdminWorkspace is a workspace with its plan name for admin views.
type AdminWorkspace struct {
- ID uint `json:"id"`
- Name string `json:"name"`
- Slug string `json:"slug"`
- OwnerID uint `json:"owner_id"`
- PlanID *uint `json:"plan_id"`
- PlanName string `json:"plan_name"`
- CreatedAt time.Time `json:"created_at"`
- UpdatedAt time.Time `json:"updated_at"`
+ ID uint `json:"id"`
+ DisplayName string `json:"display_name"`
+ Name string `json:"name"`
+ OwnerID uint `json:"owner_id"`
+ PlanID *uint `json:"plan_id"`
+ PlanName string `json:"plan_name"`
+ CreatedAt time.Time `json:"created_at"`
+ UpdatedAt time.Time `json:"updated_at"`
}
// UserWorkspaces returns workspaces for a specific user (admin only).
@@ -549,13 +549,13 @@ func (h *AdminHandler) UserWorkspaces(c *okapi.Context, req *AdminGetUserRequest
result := make([]AdminWorkspace, len(workspaces))
for i, ws := range workspaces {
result[i] = AdminWorkspace{
- ID: ws.ID,
- Name: ws.Name,
- Slug: ws.Slug,
- OwnerID: ws.OwnerID,
- PlanID: ws.PlanID,
- CreatedAt: ws.CreatedAt,
- UpdatedAt: ws.UpdatedAt,
+ ID: ws.ID,
+ DisplayName: ws.DisplayName,
+ Name: ws.Name,
+ OwnerID: ws.OwnerID,
+ PlanID: ws.PlanID,
+ CreatedAt: ws.CreatedAt,
+ UpdatedAt: ws.UpdatedAt,
}
if ws.PlanID != nil {
result[i].PlanName = planNames[*ws.PlanID]
diff --git a/internal/handlers/admin_workspace_handler.go b/internal/handlers/admin_workspace_handler.go
index 58d5fec..9e9654b 100644
--- a/internal/handlers/admin_workspace_handler.go
+++ b/internal/handlers/admin_workspace_handler.go
@@ -42,8 +42,8 @@ func NewAdminWorkspaceHandler(db *gorm.DB, repo *repositories.WorkspaceRepositor
// AdminWorkspaceRow is one line of the platform-wide workspace table.
type AdminWorkspaceRow struct {
ID uint `json:"id"`
+ DisplayName string `json:"display_name"`
Name string `json:"name"`
- Slug string `json:"slug"`
System bool `json:"system"`
OwnerID uint `json:"owner_id"`
OwnerName string `json:"owner_name"`
@@ -95,7 +95,7 @@ type AdminWorkspaceDetail struct {
type AdminListWorkspacesRequest struct {
Page int `query:"page" default:"0"`
Size int `query:"size" default:"20"`
- Search string `query:"search" doc:"Match part of the workspace name or slug"`
+ Search string `query:"search" doc:"Match part of the workspace name or display name"`
Owner int `query:"owner" doc:"Restrict to workspaces owned by this user id"`
Plan int `query:"plan" doc:"Restrict to workspaces assigned this plan id"`
}
@@ -128,9 +128,9 @@ func (h *AdminWorkspaceHandler) SetHostedForms(c *okapi.Context, req *AdminSetHo
}
ws.HostedFormsDisabled = disabled
if h.audit != nil {
- action, message := "workspace.hosted_forms_enabled", "Hosted form pages turned back on: "+ws.Name
+ action, message := "workspace.hosted_forms_enabled", "Hosted form pages turned back on: "+ws.DisplayName
if disabled {
- action, message = "workspace.hosted_forms_disabled", "Hosted form pages taken offline: "+ws.Name
+ action, message = "workspace.hosted_forms_disabled", "Hosted form pages taken offline: "+ws.DisplayName
}
h.audit.LogCtxScoped(c, ws.ID, action, message, map[string]any{"workspace_id": ws.ID})
}
@@ -210,8 +210,8 @@ func (h *AdminWorkspaceHandler) Get(c *okapi.Context, req *AdminWorkspaceIDReque
func (h *AdminWorkspaceHandler) row(ws *models.Workspace, owners map[uint]models.User, plans map[uint]string, members map[uint]int64) AdminWorkspaceRow {
row := AdminWorkspaceRow{
ID: ws.ID,
+ DisplayName: ws.DisplayName,
Name: ws.Name,
- Slug: ws.Slug,
System: ws.System,
OwnerID: ws.OwnerID,
OwnerName: owners[ws.OwnerID].Name,
diff --git a/internal/handlers/data_export.go b/internal/handlers/data_export.go
index 0d03cf2..b1abfda 100644
--- a/internal/handlers/data_export.go
+++ b/internal/handlers/data_export.go
@@ -29,8 +29,9 @@ import (
const exportLimit = 10000
type ExportStyleSheet struct {
- Name string `json:"name"`
- CSS string `json:"css,omitempty"`
+ Name string `json:"name"`
+ DisplayName string `json:"display_name,omitempty"`
+ CSS string `json:"css,omitempty"`
}
type ExportLanguage struct {
@@ -156,6 +157,7 @@ func exportTemplates(
result = append(result, TemplateExport{
Name: tmpl.Name,
+ DisplayName: tmpl.DisplayName,
Description: tmpl.Description,
DefaultLanguage: tmpl.DefaultLanguage,
SampleData: tmpl.SampleData,
@@ -169,7 +171,7 @@ func exportVersionStyleSheet(ss *models.StyleSheet, includeCSS bool) *ExportStyl
if ss == nil {
return nil
}
- es := &ExportStyleSheet{Name: ss.Name}
+ es := &ExportStyleSheet{Name: ss.Name, DisplayName: ss.DisplayName}
if includeCSS {
es.CSS = ss.CSS
}
@@ -177,10 +179,11 @@ func exportVersionStyleSheet(ss *models.StyleSheet, includeCSS bool) *ExportStyl
}
func findOrCreateStyleSheet(es *ExportStyleSheet, scope repositories.ResourceScope, repo *repositories.StyleSheetRepository) *uint {
- if es == nil || es.Name == "" {
+ if es == nil || (es.Name == "" && es.DisplayName == "") {
return nil
}
- if existing, err := repo.FindByNameInScope(scope, es.Name); err == nil && existing != nil {
+ name, displayName := importNames(es.Name, es.DisplayName, "stylesheet")
+ if existing, err := repo.FindByNameInScope(scope, name); err == nil && existing != nil {
return &existing.ID
}
if es.CSS == "" {
@@ -189,7 +192,8 @@ func findOrCreateStyleSheet(es *ExportStyleSheet, scope repositories.ResourceSco
ss := &models.StyleSheet{
UserID: scope.UserID,
WorkspaceID: scope.WorkspaceID,
- Name: es.Name,
+ Name: name,
+ DisplayName: displayName,
CSS: es.CSS,
}
if err := repo.Create(ss); err != nil {
@@ -201,7 +205,7 @@ func findOrCreateStyleSheet(es *ExportStyleSheet, scope repositories.ResourceSco
func exportStylesheets(stylesheets []models.StyleSheet) []ExportStyleSheet {
result := make([]ExportStyleSheet, 0, len(stylesheets))
for _, ss := range stylesheets {
- result = append(result, ExportStyleSheet{Name: ss.Name, CSS: ss.CSS})
+ result = append(result, ExportStyleSheet{Name: ss.Name, DisplayName: ss.DisplayName, CSS: ss.CSS})
}
return result
}
@@ -316,9 +320,10 @@ func importTemplates(
scope := repositories.ResourceScope{UserID: userID, WorkspaceID: workspaceID}
var count int
for _, tmplData := range data {
- if tmplData.Name == "" {
+ if tmplData.Name == "" && tmplData.DisplayName == "" {
continue
}
+ name, displayName := importNames(tmplData.Name, tmplData.DisplayName, "template")
defaultLang := tmplData.DefaultLanguage
if defaultLang == "" {
@@ -328,7 +333,8 @@ func importTemplates(
tmpl := &models.Template{
UserID: userID,
WorkspaceID: workspaceID,
- Name: tmplData.Name,
+ Name: name,
+ DisplayName: displayName,
DefaultLanguage: defaultLang,
Description: tmplData.Description,
SampleData: tmplData.SampleData,
@@ -404,12 +410,13 @@ func importLanguages(data []ExportLanguage, userID uint, workspaceID *uint, repo
func importStylesheets(data []ExportStyleSheet, userID uint, workspaceID *uint, repo *repositories.StyleSheetRepository) int {
var count int
for _, ss := range data {
- if ss.Name == "" {
+ if ss.Name == "" && ss.DisplayName == "" {
continue
}
+ name, displayName := importNames(ss.Name, ss.DisplayName, "stylesheet")
if err := repo.Create(&models.StyleSheet{
UserID: userID, WorkspaceID: workspaceID,
- Name: ss.Name, CSS: ss.CSS,
+ Name: name, DisplayName: displayName, CSS: ss.CSS,
}); err != nil {
continue
}
diff --git a/internal/handlers/form_handler.go b/internal/handlers/form_handler.go
index 49a22c8..8a9663d 100644
--- a/internal/handlers/form_handler.go
+++ b/internal/handlers/form_handler.go
@@ -39,13 +39,11 @@ import (
"github.com/jkaninda/okapi"
)
-const metaSlug = "slug"
+const metaName = "name"
const publicKeyAlphabet = models.FormPublicKeyAlphabet
const publicKeyLength = models.FormPublicKeyLength
-var formSlugPattern = regexp.MustCompile(`[^a-z0-9]+`)
-
type FormHandler struct {
repo *repositories.FormRepository
// hostedSettings and workspaces tell the snippet whether the share link works.
@@ -97,8 +95,9 @@ func NewFormHandler(
type CreateFormRequest struct {
Body struct {
- Name string `json:"name" required:"true"`
- Slug string `json:"slug"`
+ Name string `json:"name" doc:"Identifier, like contact-form: lowercase letters, digits and hyphens. Derived from display_name when empty."`
+ DisplayName string `json:"display_name" doc:"The form's label. Defaults to name."`
+ Slug string `json:"slug,omitempty" doc:"Deprecated: the identifier before 0.18, now name."`
Description string `json:"description"`
Mode string `json:"mode" enum:"inbox,collect" doc:"inbox (default): submissions are conversations to answer. collect: responses read as a table, kept out of the inbox."`
AllowedOrigins []string `json:"allowed_origins"`
@@ -128,8 +127,9 @@ type CreateFormRequest struct {
type UpdateFormRequest struct {
ID int `param:"id"`
Body struct {
- Name string `json:"name"`
- Slug string `json:"slug"`
+ Name string `json:"name" doc:"Identifier, like contact-form"`
+ DisplayName string `json:"display_name"`
+ Slug string `json:"slug,omitempty" doc:"Deprecated: the identifier before 0.18, now name."`
Description string `json:"description"`
Status string `json:"status" enum:"active,paused,archived"`
Mode *string `json:"mode" doc:"inbox or collect"`
@@ -198,20 +198,12 @@ func (h *FormHandler) Create(c *okapi.Context, req *CreateFormRequest) error {
return c.AbortBadRequest("a workspace is required to create a form")
}
- name := strings.TrimSpace(req.Body.Name)
- if name == "" {
- return c.AbortBadRequest("name is required")
- }
-
- slug := formSlug(req.Body.Slug)
- if slug == "" {
- slug = formSlug(name)
- }
- if slug == "" {
- return c.AbortBadRequest("could not derive a slug from the name")
+ name, displayName, err := resolveNames(req.Body.Name, req.Body.DisplayName, req.Body.Slug)
+ if err != nil {
+ return c.AbortBadRequest(err.Error())
}
- if h.repo.SlugExists(*scope.WorkspaceID, slug, 0) {
- return c.AbortConflict("a form with that slug already exists")
+ if h.repo.NameExists(*scope.WorkspaceID, name, 0) {
+ return c.AbortConflict("a form named \"" + name + "\" already exists")
}
origins, err := normalizeOrigins(req.Body.AllowedOrigins)
@@ -251,7 +243,7 @@ func (h *FormHandler) Create(c *okapi.Context, req *CreateFormRequest) error {
form := &models.Form{
WorkspaceID: scope.WorkspaceID,
Name: name,
- Slug: slug,
+ DisplayName: displayName,
Description: strings.TrimSpace(req.Body.Description),
PublicKey: key,
Status: models.FormStatusActive,
@@ -300,8 +292,8 @@ func (h *FormHandler) Create(c *okapi.Context, req *CreateFormRequest) error {
return c.AbortConflict("failed to create form")
}
- h.log(c, "form.created", fmt.Sprintf("Form %s created", form.Name), map[string]any{
- metaFormID: form.ID, metaSlug: form.Slug,
+ h.log(c, "form.created", fmt.Sprintf("Form %s created", form.DisplayName), map[string]any{
+ metaFormID: form.ID, metaName: form.Name,
})
return created(c, form)
}
@@ -334,18 +326,18 @@ func (h *FormHandler) Update(c *okapi.Context, req *UpdateFormRequest) error {
}
b := req.Body
- if strings.TrimSpace(b.Name) != "" {
- form.Name = strings.TrimSpace(b.Name)
+ name, displayName, err := resolveRenames(b.Name, b.DisplayName, b.Slug)
+ if err != nil {
+ return c.AbortBadRequest(err.Error())
}
- if strings.TrimSpace(b.Slug) != "" {
- slug := formSlug(b.Slug)
- if slug == "" {
- return c.AbortBadRequest("invalid slug")
- }
- if h.repo.SlugExists(*scope.WorkspaceID, slug, form.ID) {
- return c.AbortConflict("a form with that slug already exists")
+ if displayName != "" {
+ form.DisplayName = displayName
+ }
+ if name != "" && name != form.Name {
+ if h.repo.NameExists(*scope.WorkspaceID, name, form.ID) {
+ return c.AbortConflict("a form named \"" + name + "\" already exists")
}
- form.Slug = slug
+ form.Name = name
}
if strings.TrimSpace(b.Description) != "" {
form.Description = strings.TrimSpace(b.Description)
@@ -478,7 +470,7 @@ func (h *FormHandler) Update(c *okapi.Context, req *UpdateFormRequest) error {
}
h.invalidate(form.PublicKey)
- h.log(c, "form.updated", fmt.Sprintf("Form %s updated", form.Name), map[string]any{metaFormID: form.ID})
+ h.log(c, "form.updated", fmt.Sprintf("Form %s updated", form.DisplayName), map[string]any{metaFormID: form.ID})
return ok(c, form)
}
@@ -494,7 +486,7 @@ func (h *FormHandler) Delete(c *okapi.Context, req *FormIDRequest) error {
return c.AbortInternalServerError("failed to delete form")
}
h.invalidate(form.PublicKey)
- h.log(c, "form.deleted", fmt.Sprintf("Form %s deleted", form.Name), map[string]any{metaFormID: form.ID})
+ h.log(c, "form.deleted", fmt.Sprintf("Form %s deleted", form.DisplayName), map[string]any{metaFormID: form.ID})
return noContent(c)
}
@@ -518,7 +510,7 @@ func (h *FormHandler) RotateKey(c *okapi.Context, req *FormIDRequest) error {
return c.AbortInternalServerError("failed to rotate form key")
}
h.invalidate(oldKey, key)
- h.log(c, "form.key_rotated", fmt.Sprintf("Form %s key rotated", form.Name), map[string]any{metaFormID: form.ID})
+ h.log(c, "form.key_rotated", fmt.Sprintf("Form %s key rotated", form.DisplayName), map[string]any{metaFormID: form.ID})
return ok(c, form)
}
@@ -573,16 +565,6 @@ func (h *FormHandler) log(c *okapi.Context, action, message string, meta map[str
h.audit.LogCtx(c, action, message, meta)
}
-func formSlug(v string) string {
- v = strings.ToLower(strings.TrimSpace(v))
- v = formSlugPattern.ReplaceAllString(v, "-")
- v = strings.Trim(v, "-")
- if len(v) > 60 {
- v = strings.Trim(v[:60], "-")
- }
- return v
-}
-
func generatePublicKey() (string, error) { return models.NewFormPublicKey() }
func normalizeOrigins(in []string) ([]string, error) {
diff --git a/internal/handlers/form_handler_test.go b/internal/handlers/form_handler_test.go
index 73355ed..344e6b5 100644
--- a/internal/handlers/form_handler_test.go
+++ b/internal/handlers/form_handler_test.go
@@ -26,7 +26,7 @@ import (
"github.com/goposta/posta/internal/models"
)
-func TestFormSlug(t *testing.T) {
+func TestToIdentifier(t *testing.T) {
cases := map[string]string{
"Contact Form": "contact-form",
" Support!! ": "support",
@@ -34,11 +34,11 @@ func TestFormSlug(t *testing.T) {
"already-a-slug": "already-a-slug",
"!!!": "",
"": "",
- strings.Repeat("a", 100): strings.Repeat("a", 60),
+ strings.Repeat("a", 100): strings.Repeat("a", models.MaxIdentifierLength),
}
for in, want := range cases {
- if got := formSlug(in); got != want {
- t.Fatalf("formSlug(%q) = %q, want %q", in, got, want)
+ if got := models.ToIdentifier(in); got != want {
+ t.Fatalf("models.ToIdentifier(%q) = %q, want %q", in, got, want)
}
}
}
@@ -133,7 +133,7 @@ func TestIsHTTPURL(t *testing.T) {
}
func TestBuildHTMLSnippetIncludesHoneypot(t *testing.T) {
- form := &models.Form{Name: "Contact", HoneypotField: "_trap"}
+ form := &models.Form{DisplayName: "Contact", HoneypotField: "_trap"}
snippet := buildHTMLSnippet("https://posta.test/api/v1/f/abc", form)
if !strings.Contains(snippet, `name="_trap"`) {
t.Fatalf("snippet is missing the honeypot field:\n%s", snippet)
diff --git a/internal/handlers/form_page_handler.go b/internal/handlers/form_page_handler.go
index c7e0ee7..685d33c 100644
--- a/internal/handlers/form_page_handler.go
+++ b/internal/handlers/form_page_handler.go
@@ -114,7 +114,7 @@ func (h *FormIngestHandler) HostedPage(c *okapi.Context) error {
}
data := hostedPageData{
- Title: form.Name,
+ Title: form.DisplayName,
Description: form.Description,
Key: form.PublicKey,
Theme: form.Appearance.Theme,
diff --git a/internal/handlers/form_rule_handler.go b/internal/handlers/form_rule_handler.go
index a1c1433..33db394 100644
--- a/internal/handlers/form_rule_handler.go
+++ b/internal/handlers/form_rule_handler.go
@@ -208,7 +208,7 @@ func (h *FormRuleHandler) Create(c *okapi.Context, req *CreateFormRuleRequest) e
if err := h.repo.Create(rule); err != nil {
return c.AbortInternalServerError("failed to create rule")
}
- h.log(c, "form.rule_created", fmt.Sprintf("Rule %q created on form %s", rule.Name, form.Name), form, rule)
+ h.log(c, "form.rule_created", fmt.Sprintf("Rule %q created on form %s", rule.Name, form.DisplayName), form, rule)
return created(c, rule)
}
@@ -236,7 +236,7 @@ func (h *FormRuleHandler) Update(c *okapi.Context, req *UpdateFormRuleRequest) e
if err := h.repo.Update(existing); err != nil {
return c.AbortInternalServerError("failed to update rule")
}
- h.log(c, "form.rule_updated", fmt.Sprintf("Rule %q updated on form %s", existing.Name, form.Name), form, existing)
+ h.log(c, "form.rule_updated", fmt.Sprintf("Rule %q updated on form %s", existing.Name, form.DisplayName), form, existing)
return ok(c, existing)
}
@@ -255,7 +255,7 @@ func (h *FormRuleHandler) Delete(c *okapi.Context, req *FormRuleIDRequest) error
if err := h.repo.Delete(rule.ID); err != nil {
return c.AbortInternalServerError("failed to delete rule")
}
- h.log(c, "form.rule_deleted", fmt.Sprintf("Rule %q deleted from form %s", rule.Name, form.Name), form, rule)
+ h.log(c, "form.rule_deleted", fmt.Sprintf("Rule %q deleted from form %s", rule.Name, form.DisplayName), form, rule)
return noContent(c)
}
@@ -274,7 +274,7 @@ func (h *FormRuleHandler) Reorder(c *okapi.Context, req *ReorderFormRulesRequest
if err != nil {
return c.AbortInternalServerError("failed to list rules")
}
- h.log(c, "form.rules_reordered", fmt.Sprintf("Rules reordered on form %s", form.Name), form, nil)
+ h.log(c, "form.rules_reordered", fmt.Sprintf("Rules reordered on form %s", form.DisplayName), form, nil)
return ok(c, rules)
}
diff --git a/internal/handlers/form_submission_handler.go b/internal/handlers/form_submission_handler.go
index 9b2b384..601e1b5 100644
--- a/internal/handlers/form_submission_handler.go
+++ b/internal/handlers/form_submission_handler.go
@@ -326,11 +326,11 @@ func (h *MessageHandler) ExportSubmissions(c *okapi.Context, req *SubmissionQuer
known[f.Key] = true
}
- slug := form.Slug
- if slug == "" {
- slug = "form"
+ base := form.Name
+ if base == "" {
+ base = "form"
}
- filename := fmt.Sprintf("%s-responses-%s.%s", slug, time.Now().UTC().Format("20060102"), format)
+ filename := fmt.Sprintf("%s-responses-%s.%s", base, time.Now().UTC().Format("20060102"), format)
hdr := c.ResponseWriter().Header()
if format == formatCSV {
hdr.Set("Content-Type", "text/csv; charset=utf-8")
@@ -471,7 +471,7 @@ func (h *MessageHandler) ExportSubmissions(c *okapi.Context, req *SubmissionQuer
piiIncluded = piiIncluded || f.PII
}
h.audit.LogCtxScoped(c, *scope.WorkspaceID, "form.submissions_exported",
- fmt.Sprintf("Exported %d responses of form %q as %s", rows, form.Name, strings.ToUpper(format)),
+ fmt.Sprintf("Exported %d responses of form %q as %s", rows, form.DisplayName, strings.ToUpper(format)),
map[string]any{"form_id": form.ID, "format": format, "rows": rows, "pii": piiIncluded, "withheld_fields": withheld, "truncated": truncated})
}
}
diff --git a/internal/handlers/identifier.go b/internal/handlers/identifier.go
new file mode 100644
index 0000000..bf40211
--- /dev/null
+++ b/internal/handlers/identifier.go
@@ -0,0 +1,108 @@
+// Copyright (c) 2026 Jonas Kaninda.
+//
+// This file is part of Posta.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+//
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package handlers
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/goposta/posta/internal/models"
+)
+
+// Workspaces, forms, OAuth providers, templates and stylesheets share one
+// naming scheme: name is the identifier the API and URLs use, like
+// "contact-form"; display_name is the label people read.
+
+// legacyNames reads a request made before 0.18, when name was the label:
+// with a slug and no display_name, the slug is the identifier; with no
+// display_name and a name that is not an identifier, that name is the
+// label. Deprecated, until 0.19.
+func legacyNames(name, displayName, legacySlug string) (string, string) {
+ name, displayName, legacySlug = strings.TrimSpace(name), strings.TrimSpace(displayName), strings.TrimSpace(legacySlug)
+ switch {
+ case displayName != "":
+ return name, displayName
+ case legacySlug != "":
+ return legacySlug, name
+ case name != "" && models.CheckIdentifier(name) != nil:
+ return "", name
+ }
+ return name, displayName
+}
+
+// resolveNames settles the name and display name of a resource being
+// created. A missing name is derived from the display name, and a missing
+// display name is the name. legacySlug is the slug field of requests made
+// before the rename, read by legacyNames.
+func resolveNames(name, displayName, legacySlug string) (string, string, error) {
+ name, displayName = legacyNames(name, displayName, legacySlug)
+ if name == "" {
+ name = models.ToIdentifier(displayName)
+ }
+ if name == "" {
+ return "", "", fmt.Errorf("name or display_name is required")
+ }
+ if err := models.CheckIdentifier(name); err != nil {
+ return "", "", err
+ }
+ if displayName == "" {
+ displayName = name
+ }
+ return name, displayName, nil
+}
+
+// resolveRenames settles the name and display name an update asks for;
+// an empty result leaves that value as it is. legacySlug is read by
+// legacyNames.
+func resolveRenames(name, displayName, legacySlug string) (string, string, error) {
+ name, displayName = legacyNames(name, displayName, legacySlug)
+ if name != "" {
+ if err := models.CheckIdentifier(name); err != nil {
+ return "", "", err
+ }
+ }
+ return name, displayName, nil
+}
+
+// importNames settles the names of a resource read from an export or a
+// file, where a missing or malformed identifier must not fail the import:
+// it is derived from the display name, or fallback.
+func importNames(name, displayName, fallback string) (string, string) {
+ name, displayName = legacyNames(name, displayName, "")
+ if name == "" || models.CheckIdentifier(name) != nil {
+ name = models.ToIdentifier(firstNonEmpty(name, displayName))
+ }
+ if name == "" {
+ name = fallback
+ }
+ if displayName == "" {
+ displayName = name
+ }
+ return name, displayName
+}
+
+func firstNonEmpty(values ...string) string {
+ for _, v := range values {
+ if strings.TrimSpace(v) != "" {
+ return v
+ }
+ }
+ return ""
+}
diff --git a/internal/handlers/identifier_test.go b/internal/handlers/identifier_test.go
new file mode 100644
index 0000000..a0fe752
--- /dev/null
+++ b/internal/handlers/identifier_test.go
@@ -0,0 +1,77 @@
+// Copyright (c) 2026 Jonas Kaninda.
+//
+// This file is part of Posta.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+//
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package handlers
+
+import "testing"
+
+func TestResolveNames(t *testing.T) {
+ cases := []struct {
+ label string
+ name, displayName, slug string
+ wantName, wantDisplay string
+ wantErr bool
+ }{
+ {"both", "contact", "Contact form", "", "contact", "Contact form", false},
+ {"display only", "", "Contact form", "", "contact-form", "Contact form", false},
+ {"name only", "contact", "", "", "contact", "contact", false},
+ {"legacy label in name", "Contact form", "", "", "contact-form", "Contact form", false},
+ {"legacy name and slug", "Contact form", "", "contact", "contact", "Contact form", false},
+ {"slug ignored with display_name", "contact", "Contact form", "other", "contact", "Contact form", false},
+ {"bad name with display_name", "Contact form", "Contact", "", "", "", true},
+ {"nothing", "", "", "", "", "", true},
+ {"label without letters", "", "!!!", "", "", "", true},
+ }
+ for _, tc := range cases {
+ t.Run(tc.label, func(t *testing.T) {
+ name, display, err := resolveNames(tc.name, tc.displayName, tc.slug)
+ if (err != nil) != tc.wantErr {
+ t.Fatalf("err = %v, want error %v", err, tc.wantErr)
+ }
+ if !tc.wantErr && (name != tc.wantName || display != tc.wantDisplay) {
+ t.Fatalf("got (%q, %q), want (%q, %q)", name, display, tc.wantName, tc.wantDisplay)
+ }
+ })
+ }
+}
+
+func TestResolveRenames(t *testing.T) {
+ // An old client renaming the label sent it as name.
+ if name, display, err := resolveRenames("New label", "", ""); err != nil || name != "" || display != "New label" {
+ t.Fatalf("legacy label rename = (%q, %q, %v)", name, display, err)
+ }
+ if name, display, err := resolveRenames("new-id", "", ""); err != nil || name != "new-id" || display != "" {
+ t.Fatalf("identifier rename = (%q, %q, %v)", name, display, err)
+ }
+ if _, _, err := resolveRenames("Bad Id", "Label", ""); err == nil {
+ t.Fatal("a malformed name with a display name must be refused")
+ }
+}
+
+func TestImportNames(t *testing.T) {
+ if n, d := importNames("Welcome Email", "", "template"); n != "welcome-email" || d != "Welcome Email" {
+ t.Fatalf("old export = (%q, %q)", n, d)
+ }
+ if n, d := importNames("welcome", "Welcome", "template"); n != "welcome" || d != "Welcome" {
+ t.Fatalf("new export = (%q, %q)", n, d)
+ }
+ if n, d := importNames("", "!!!", "template"); n != "template" || d != "!!!" {
+ t.Fatalf("no letters = (%q, %q)", n, d)
+ }
+}
diff --git a/internal/handlers/ldap_admin_handler.go b/internal/handlers/ldap_admin_handler.go
index 8079a62..fbb441c 100644
--- a/internal/handlers/ldap_admin_handler.go
+++ b/internal/handlers/ldap_admin_handler.go
@@ -279,7 +279,7 @@ func (h *LDAPAdminHandler) apply(c *okapi.Context, cfg *models.LDAPConfig, b LDA
// uniqueName derives the directory's handle from its display name.
func (h *LDAPAdminHandler) uniqueName(displayName string) string {
- base := slugify(displayName)
+ base := models.ToIdentifier(displayName)
if base == "" {
base = "directory"
}
diff --git a/internal/handlers/oauth_admin_handler.go b/internal/handlers/oauth_admin_handler.go
index ce423f6..05eaa78 100644
--- a/internal/handlers/oauth_admin_handler.go
+++ b/internal/handlers/oauth_admin_handler.go
@@ -20,7 +20,6 @@
package handlers
import (
- "strings"
"time"
"github.com/goposta/posta/internal/enterprise"
@@ -48,8 +47,9 @@ func NewOAuthAdminHandler(providerRepo *repositories.OAuthProviderRepository, ss
type CreateOAuthProviderRequest struct {
Body struct {
- Name string `json:"name" required:"true"`
- Slug string `json:"slug" required:"true"`
+ Name string `json:"name" doc:"Identifier used in the sign-in URLs, like google: lowercase letters, digits and hyphens. Derived from display_name when empty."`
+ DisplayName string `json:"display_name" doc:"Shown on the sign-in button. Defaults to name."`
+ Slug string `json:"slug,omitempty" doc:"Deprecated: the identifier before 0.18, now name."`
Type string `json:"type" required:"true"`
ClientID string `json:"client_id" required:"true"`
ClientSecret string `json:"client_secret" required:"true"`
@@ -67,7 +67,8 @@ type CreateOAuthProviderRequest struct {
type UpdateOAuthProviderRequest struct {
ID int `param:"id"`
Body struct {
- Name string `json:"name"`
+ Name string `json:"name" doc:"A provider's name is in its sign-in URLs and cannot change; only accepted when it is the current one."`
+ DisplayName string `json:"display_name"`
ClientID string `json:"client_id"`
ClientSecret string `json:"client_secret"`
Issuer string `json:"issuer"`
@@ -88,8 +89,8 @@ type DeleteOAuthProviderRequest struct {
type OAuthProviderResponse struct {
ID uint `json:"id"`
+ DisplayName string `json:"display_name"`
Name string `json:"name"`
- Slug string `json:"slug"`
Type string `json:"type"`
Issuer string `json:"issuer"`
Scopes string `json:"scopes"`
@@ -133,15 +134,18 @@ func (h *OAuthAdminHandler) CreateProvider(c *okapi.Context, req *CreateOAuthPro
return licenseAbort(c, err)
}
}
- slug := strings.ToLower(strings.TrimSpace(req.Body.Slug))
+ name, displayName, err := resolveNames(req.Body.Name, req.Body.DisplayName, req.Body.Slug)
+ if err != nil {
+ return c.AbortBadRequest(err.Error())
+ }
providerType := models.OAuthProviderType(req.Body.Type)
if providerType != models.OAuthProviderGoogle && providerType != models.OAuthProviderOIDC {
return c.AbortBadRequest("type must be 'google' or 'oidc'")
}
provider := &models.OAuthProvider{
- Name: strings.TrimSpace(req.Body.Name),
- Slug: slug,
+ Name: name,
+ DisplayName: displayName,
Type: providerType,
ClientID: req.Body.ClientID,
ClientSecret: req.Body.ClientSecret,
@@ -165,7 +169,7 @@ func (h *OAuthAdminHandler) CreateProvider(c *okapi.Context, req *CreateOAuthPro
}
if err := h.providerRepo.Create(provider); err != nil {
- return c.AbortConflict("provider slug already exists")
+ return c.AbortConflict("a provider named \"" + name + "\" already exists")
}
return created(c, toProviderResponse(provider))
@@ -190,8 +194,15 @@ func (h *OAuthAdminHandler) UpdateProvider(c *okapi.Context, req *UpdateOAuthPro
return c.AbortNotFound("provider not found")
}
- if req.Body.Name != "" {
- provider.Name = req.Body.Name
+ name, displayName, err := resolveRenames(req.Body.Name, req.Body.DisplayName, "")
+ if err != nil {
+ return c.AbortBadRequest(err.Error())
+ }
+ if name != "" && name != provider.Name {
+ return c.AbortBadRequest("a provider's name is in its sign-in URLs and cannot change; set display_name to rename it")
+ }
+ if displayName != "" {
+ provider.DisplayName = displayName
}
if req.Body.ClientID != "" {
provider.ClientID = req.Body.ClientID
@@ -255,7 +266,7 @@ func (h *OAuthAdminHandler) GetWorkspaceSSO(c *okapi.Context) error {
return ok(c, WorkspaceSSOResponse{
ProviderID: config.ProviderID,
- ProviderName: config.Provider.Name,
+ ProviderName: config.Provider.DisplayName,
EnforceSSO: config.EnforceSSO,
AutoProvision: config.AutoProvision,
AllowedDomains: config.AllowedDomains,
@@ -299,8 +310,8 @@ func (h *OAuthAdminHandler) DeleteWorkspaceSSO(c *okapi.Context) error {
func toProviderResponse(p *models.OAuthProvider) OAuthProviderResponse {
return OAuthProviderResponse{
ID: p.ID,
+ DisplayName: p.DisplayName,
Name: p.Name,
- Slug: p.Slug,
Type: string(p.Type),
Issuer: p.Issuer,
Scopes: p.Scopes,
diff --git a/internal/handlers/oauth_handler.go b/internal/handlers/oauth_handler.go
index 71f82be..addf119 100644
--- a/internal/handlers/oauth_handler.go
+++ b/internal/handlers/oauth_handler.go
@@ -94,10 +94,10 @@ func NewOAuthHandler(
}
type OAuthProviderInfo struct {
- ID uint `json:"id"`
- Slug string `json:"slug"`
- Name string `json:"name"`
- Type string `json:"type"`
+ ID uint `json:"id"`
+ Name string `json:"name"`
+ DisplayName string `json:"display_name"`
+ Type string `json:"type"`
}
type OAuthLinkedAccount struct {
@@ -120,9 +120,9 @@ type DiscoverSSORequest struct {
}
type DiscoverSSOResponse struct {
- Slug string `json:"slug"`
- Name string `json:"name"`
- Type string `json:"type"`
+ Name string `json:"name"`
+ DisplayName string `json:"display_name"`
+ Type string `json:"type"`
}
// ListProviders returns enabled OAuth providers for the login page
@@ -135,10 +135,10 @@ func (h *OAuthHandler) ListProviders(c *okapi.Context) error {
var result []OAuthProviderInfo
for _, p := range providers {
result = append(result, OAuthProviderInfo{
- ID: p.ID,
- Slug: p.Slug,
- Name: p.Name,
- Type: string(p.Type),
+ ID: p.ID,
+ Name: p.Name,
+ DisplayName: p.DisplayName,
+ Type: string(p.Type),
})
}
@@ -163,16 +163,16 @@ func (h *OAuthHandler) DiscoverSSO(c *okapi.Context, req *DiscoverSSORequest) er
}
return ok(c, DiscoverSSOResponse{
- Slug: provider.Slug,
- Name: provider.Name,
- Type: string(provider.Type),
+ Name: provider.Name,
+ DisplayName: provider.DisplayName,
+ Type: string(provider.Type),
})
}
// Authorize redirects the user to the OAuth provider's authorization page.
func (h *OAuthHandler) Authorize(c *okapi.Context) error {
- providerSlug := c.Param("provider")
- provider, err := h.providerRepo.FindBySlug(providerSlug)
+ providerName := c.Param("provider")
+ provider, err := h.providerRepo.FindByName(providerName)
if err != nil {
return c.AbortNotFound("OAuth provider not found")
}
@@ -186,12 +186,12 @@ func (h *OAuthHandler) Authorize(c *okapi.Context) error {
// Store state in Redis with 10-minute TTL
stateData, _ := json.Marshal(map[string]string{
- "provider_slug": provider.Slug,
+ "provider_slug": provider.Name,
"created_at": time.Now().UTC().Format(time.RFC3339),
})
h.redisClient.Set(c.Request().Context(), "oauth:state:"+state, string(stateData), 10*time.Minute)
- redirectURI := fmt.Sprintf("%s/api/v1/auth/oauth/%s/callback", h.callbackBase, provider.Slug)
+ redirectURI := fmt.Sprintf("%s/api/v1/auth/oauth/%s/callback", h.callbackBase, provider.Name)
oauthCfg, err := h.oauthService.GetOAuthConfig(provider, redirectURI)
if err != nil {
return c.AbortBadRequest("OAuth provider misconfigured: " + err.Error())
@@ -204,7 +204,7 @@ func (h *OAuthHandler) Authorize(c *okapi.Context) error {
// Callback handles the OAuth provider's redirect with authorization code.
func (h *OAuthHandler) Callback(c *okapi.Context) error {
- providerSlug := c.Param("provider")
+ providerName := c.Param("provider")
code := c.Query("code")
state := c.Query("state")
oauthError := c.Query("error")
@@ -232,28 +232,28 @@ func (h *OAuthHandler) Callback(c *okapi.Context) error {
// Verify state matches provider
var stateData map[string]string
- if err := json.Unmarshal([]byte(stateVal.Val()), &stateData); err != nil || stateData["provider_slug"] != providerSlug {
+ if err := json.Unmarshal([]byte(stateVal.Val()), &stateData); err != nil || stateData["provider_slug"] != providerName {
return redirect("state_mismatch")
}
- provider, err := h.providerRepo.FindBySlug(providerSlug)
+ provider, err := h.providerRepo.FindByName(providerName)
if err != nil {
return redirect("provider_not_found")
}
- redirectURI := fmt.Sprintf("%s/api/v1/auth/oauth/%s/callback", h.callbackBase, provider.Slug)
+ redirectURI := fmt.Sprintf("%s/api/v1/auth/oauth/%s/callback", h.callbackBase, provider.Name)
// Exchange code for tokens + user info
userInfo, token, err := h.oauthService.ExchangeCode(ctx, provider, code, redirectURI)
if err != nil {
- logger.Error("OAuth exchange failed for provider %s: %v", provider.Slug, err)
+ logger.Error("OAuth exchange failed for provider %s: %v", provider.Name, err)
return redirect("exchange_failed")
}
// Find or create user
user, isNew, err := h.oauthService.FindOrCreateUser(provider, userInfo, token)
if err != nil {
- logger.Error("OAuth account resolution failed for provider %s: %v", provider.Slug, err)
+ logger.Error("OAuth account resolution failed for provider %s: %v", provider.Name, err)
return redirect("account_error")
}
@@ -282,7 +282,7 @@ func (h *OAuthHandler) Callback(c *okapi.Context) error {
action = "user.oauth_registered"
}
h.bus.PublishSimple(models.EventCategoryUser, action, &user.ID, user.Email, c.RealIP(),
- fmt.Sprintf("User %q authenticated via %s", user.Email, provider.Name), nil)
+ fmt.Sprintf("User %q authenticated via %s", user.Email, provider.DisplayName), nil)
}
// Update last login
@@ -312,7 +312,7 @@ func (h *OAuthHandler) ListLinkedAccounts(c *okapi.Context) error {
result = append(result, OAuthLinkedAccount{
ID: a.ID,
ProviderID: a.ProviderID,
- ProviderName: a.Provider.Name,
+ ProviderName: a.Provider.DisplayName,
ProviderType: string(a.Provider.Type),
Email: a.Email,
CreatedAt: a.CreatedAt.Format(time.RFC3339),
diff --git a/internal/handlers/plan_handler.go b/internal/handlers/plan_handler.go
index aef2302..87dcbed 100644
--- a/internal/handlers/plan_handler.go
+++ b/internal/handlers/plan_handler.go
@@ -360,9 +360,9 @@ func (h *PlanHandler) AssignToWorkspace(c *okapi.Context, req *AssignWorkspacePl
}
h.audit.Log(userID, c.GetString("email"), c.RealIP(), "plan.assigned",
- fmt.Sprintf("Plan '%s' assigned to workspace '%s'", plan.Name, ws.Name), nil)
+ fmt.Sprintf("Plan '%s' assigned to workspace '%s'", plan.Name, ws.DisplayName), nil)
- return ok(c, dto.MessageData{Message: fmt.Sprintf("plan '%s' assigned to workspace '%s'", plan.Name, ws.Name)})
+ return ok(c, dto.MessageData{Message: fmt.Sprintf("plan '%s' assigned to workspace '%s'", plan.Name, ws.DisplayName)})
}
// GetWorkspacePlan returns the effective plan for a workspace.
diff --git a/internal/handlers/stylesheet_handler.go b/internal/handlers/stylesheet_handler.go
index 05d9c98..8d4d490 100644
--- a/internal/handlers/stylesheet_handler.go
+++ b/internal/handlers/stylesheet_handler.go
@@ -32,15 +32,17 @@ type StyleSheetHandler struct {
}
type CreateStyleSheetRequest struct {
Body struct {
- Name string `json:"name" required:"true"`
- CSS string `json:"css"`
+ Name string `json:"name" doc:"Identifier, like brand: lowercase letters, digits and hyphens. Derived from display_name when empty."`
+ DisplayName string `json:"display_name" doc:"The stylesheet's label. Defaults to name."`
+ CSS string `json:"css"`
} `json:"body"`
}
type UpdateStyleSheetRequest struct {
ID int `param:"id"`
Body struct {
- Name string `json:"name"`
- CSS string `json:"css"`
+ Name string `json:"name"`
+ DisplayName string `json:"display_name"`
+ CSS string `json:"css"`
} `json:"body"`
}
type DeleteStyleSheetRequest struct {
@@ -57,15 +59,20 @@ func (h *StyleSheetHandler) Create(c *okapi.Context, req *CreateStyleSheetReques
}
scope := getScope(c)
+ name, displayName, err := resolveNames(req.Body.Name, req.Body.DisplayName, "")
+ if err != nil {
+ return c.AbortBadRequest(err.Error())
+ }
ss := &models.StyleSheet{
UserID: scope.UserID,
WorkspaceID: scope.WorkspaceID,
- Name: req.Body.Name,
+ Name: name,
+ DisplayName: displayName,
CSS: req.Body.CSS,
}
if err := h.repo.Create(ss); err != nil {
- return c.AbortConflict("stylesheet name already exists")
+ return c.AbortConflict("a stylesheet named \"" + name + "\" already exists")
}
return created(c, ss)
@@ -80,8 +87,15 @@ func (h *StyleSheetHandler) Update(c *okapi.Context, req *UpdateStyleSheetReques
return c.AbortNotFound("stylesheet not found")
}
- if req.Body.Name != "" {
- ss.Name = req.Body.Name
+ name, displayName, err := resolveRenames(req.Body.Name, req.Body.DisplayName, "")
+ if err != nil {
+ return c.AbortBadRequest(err.Error())
+ }
+ if name != "" {
+ ss.Name = name
+ }
+ if displayName != "" {
+ ss.DisplayName = displayName
}
if req.Body.CSS != "" {
ss.CSS = req.Body.CSS
@@ -91,6 +105,9 @@ func (h *StyleSheetHandler) Update(c *okapi.Context, req *UpdateStyleSheetReques
ss.UpdatedAt = &now
if err := h.repo.Update(ss); err != nil {
+ if repositories.IsDuplicateName(err) {
+ return c.AbortConflict("a stylesheet named \"" + ss.Name + "\" already exists")
+ }
return c.AbortInternalServerError("failed to update stylesheet")
}
diff --git a/internal/handlers/template_handler.go b/internal/handlers/template_handler.go
index b37ad51..64c71d4 100644
--- a/internal/handlers/template_handler.go
+++ b/internal/handlers/template_handler.go
@@ -43,7 +43,8 @@ type TemplateHandler struct {
}
type CreateTemplateRequest struct {
Body struct {
- Name string `json:"name" required:"true"`
+ Name string `json:"name" doc:"Identifier used to send with this template, like welcome-email: lowercase letters, digits and hyphens. Derived from display_name when empty."`
+ DisplayName string `json:"display_name" doc:"The template's label. Defaults to name."`
SampleData string `json:"sample_data" default:"{}"`
DefaultLanguage string `json:"default_language"`
Description string `json:"description"`
@@ -52,7 +53,8 @@ type CreateTemplateRequest struct {
type UpdateTemplateRequest struct {
ID int `param:"id"`
Body struct {
- Name string `json:"name"`
+ Name string `json:"name" doc:"Identifier used to send with this template. Renaming it breaks callers that send by the old name."`
+ DisplayName string `json:"display_name"`
SampleData *string `json:"sample_data" default:"{}"`
DefaultLanguage string `json:"default_language"`
Description *string `json:"description"`
@@ -108,17 +110,22 @@ func (h *TemplateHandler) Create(c *okapi.Context, req *CreateTemplateRequest) e
}
}
+ name, displayName, err := resolveNames(req.Body.Name, req.Body.DisplayName, "")
+ if err != nil {
+ return c.AbortBadRequest(err.Error())
+ }
tmpl := &models.Template{
UserID: scope.UserID,
WorkspaceID: scope.WorkspaceID,
- Name: req.Body.Name,
+ Name: name,
+ DisplayName: displayName,
DefaultLanguage: defaultLang,
Description: req.Body.Description,
SampleData: req.Body.SampleData,
LastEditedByID: &scope.UserID,
}
- err := h.repo.CreateWithVersions(tmpl, []repositories.ImportVersion{
+ err = h.repo.CreateWithVersions(tmpl, []repositories.ImportVersion{
{SampleData: req.Body.SampleData, IsActive: true},
})
if repositories.IsDuplicateName(err) {
@@ -140,8 +147,15 @@ func (h *TemplateHandler) Update(c *okapi.Context, req *UpdateTemplateRequest) e
return c.AbortNotFound("template not found")
}
- if req.Body.Name != "" {
- tmpl.Name = req.Body.Name
+ name, displayName, err := resolveRenames(req.Body.Name, req.Body.DisplayName, "")
+ if err != nil {
+ return c.AbortBadRequest(err.Error())
+ }
+ if name != "" {
+ tmpl.Name = name
+ }
+ if displayName != "" {
+ tmpl.DisplayName = displayName
}
if req.Body.SampleData != nil {
tmpl.SampleData = *req.Body.SampleData
@@ -314,6 +328,7 @@ type TemplateExport struct {
PostaVersion string `json:"posta_version,omitempty"`
ExportedAt string `json:"exported_at,omitempty"`
Name string `json:"name"`
+ DisplayName string `json:"display_name,omitempty"`
Description string `json:"description"`
DefaultLanguage string `json:"default_language"`
SampleData string `json:"sample_data"`
@@ -367,6 +382,7 @@ func (h *TemplateHandler) Export(c *okapi.Context, req *ExportTemplateRequest) e
PostaVersion: config.Version,
ExportedAt: time.Now().UTC().Format(time.RFC3339),
Name: tmpl.Name,
+ DisplayName: tmpl.DisplayName,
Description: tmpl.Description,
DefaultLanguage: tmpl.DefaultLanguage,
SampleData: tmpl.SampleData,
@@ -383,9 +399,10 @@ func (h *TemplateHandler) Import(c *okapi.Context, req *ImportTemplateRequest) e
scope := getScope(c)
data := req.Body
- if data.Name == "" {
+ if data.Name == "" && data.DisplayName == "" {
return c.AbortBadRequest("template name is required")
}
+ name, displayName := importNames(data.Name, data.DisplayName, "template")
defaultLang := data.DefaultLanguage
if defaultLang == "" {
@@ -399,7 +416,8 @@ func (h *TemplateHandler) Import(c *okapi.Context, req *ImportTemplateRequest) e
tmpl := &models.Template{
UserID: scope.UserID,
WorkspaceID: scope.WorkspaceID,
- Name: data.Name,
+ Name: name,
+ DisplayName: displayName,
DefaultLanguage: defaultLang,
Description: data.Description,
SampleData: data.SampleData,
@@ -477,28 +495,51 @@ func (h *TemplateHandler) ImportHTML(c *okapi.Context) error {
return c.AbortBadRequest("file is empty")
}
- // Derive the template name from the filename, keeping its capitalisation:
- // the lowercased copy is only there to match the extension.
- name := filename[:len(filename)-len(filepath.Ext(filename))]
- name = strings.TrimSpace(name)
- if name == "" {
- return c.AbortBadRequest("could not derive template name from filename")
+ // Optional form fields override what is otherwise derived from the
+ // filename and the document: name, display_name, description, subject
+ // and language.
+ form := func(key string) string { return strings.TrimSpace(c.Request().FormValue(key)) }
+
+ // Without a name or display name, the template is named after the
+ // filename, keeping its capitalisation: the lowercased copy is only
+ // there to match the extension.
+ name := form("display_name")
+ if name == "" && form("name") == "" {
+ name = strings.TrimSpace(filename[:len(filename)-len(filepath.Ext(filename))])
+ if name == "" || models.ToIdentifier(name) == "" {
+ return c.AbortBadRequest("could not derive template name from filename")
+ }
}
+ identifier, displayName, err := resolveNames(form("name"), name, "")
+ if err != nil {
+ return c.AbortBadRequest(err.Error())
+ }
+ name = displayName
// Extract CSS and HTML body, plus any <link rel="stylesheet"> references
css, body := extractStyleAndBody(htmlContent)
linkNames := extractStyleSheetLinks(htmlContent)
// Try to extract a subject from <title>
- subject := extractTitle(htmlContent)
+ subject := form("subject")
+ if subject == "" {
+ subject = extractTitle(htmlContent)
+ }
if subject == "" {
subject = name
}
// Resolve default language from scope
- defaultLang := "en"
- if defLang, err := h.languageRepo.FindDefault(scope); err == nil {
- defaultLang = defLang.Code
+ defaultLang := form("language")
+ if defaultLang == "" {
+ defaultLang = "en"
+ if defLang, err := h.languageRepo.FindDefault(scope); err == nil {
+ defaultLang = defLang.Code
+ }
+ }
+ description := form("description")
+ if description == "" {
+ description = fmt.Sprintf("Imported from %s", filename)
}
stylesheetID := h.resolveImportedStyleSheet(scope, name, css, linkNames)
@@ -506,9 +547,10 @@ func (h *TemplateHandler) ImportHTML(c *okapi.Context) error {
tmpl := &models.Template{
UserID: scope.UserID,
WorkspaceID: scope.WorkspaceID,
- Name: name,
+ Name: identifier,
+ DisplayName: displayName,
DefaultLanguage: defaultLang,
- Description: fmt.Sprintf("Imported from %s", filename),
+ Description: description,
SampleData: "{}",
LastEditedByID: &scope.UserID,
}
@@ -524,7 +566,7 @@ func (h *TemplateHandler) ImportHTML(c *okapi.Context) error {
}},
}})
if repositories.IsDuplicateName(err) {
- return c.AbortConflict("a template named \"" + name + "\" already exists in this workspace")
+ return c.AbortConflict("a template named \"" + tmpl.Name + "\" already exists in this workspace")
}
if err != nil {
return c.AbortInternalServerError("failed to import template")
@@ -551,17 +593,19 @@ func (h *TemplateHandler) resolveImportedStyleSheet(scope repositories.ResourceS
}
if strings.TrimSpace(inlineCSS) != "" {
- return findOrCreateStyleSheet(&ExportStyleSheet{Name: baseName + "-styles", CSS: inlineCSS}, scope, h.stylesheetRepo)
+ return findOrCreateStyleSheet(&ExportStyleSheet{Name: models.ToIdentifier(baseName) + "-styles", DisplayName: baseName + " styles", CSS: inlineCSS}, scope, h.stylesheetRepo)
}
return nil
}
func (h *TemplateHandler) createStyleSheet(scope repositories.ResourceScope, name, css string) *uint {
+ id, displayName := importNames(name, "", "stylesheet")
ss := &models.StyleSheet{
UserID: scope.UserID,
WorkspaceID: scope.WorkspaceID,
- Name: name,
+ Name: id,
+ DisplayName: displayName,
CSS: css,
}
if err := h.stylesheetRepo.Create(ss); err != nil {
diff --git a/internal/handlers/workspace_data_handler.go b/internal/handlers/workspace_data_handler.go
index 1d64006..7bb1eb1 100644
--- a/internal/handlers/workspace_data_handler.go
+++ b/internal/handlers/workspace_data_handler.go
@@ -187,7 +187,7 @@ func (h *WorkspaceDataHandler) Export(c *okapi.Context) error {
PostaVersion: config.Version,
ExportedAt: time.Now().UTC().Format(time.RFC3339),
WorkspaceSettings: ExportWorkspaceSettings{
- Name: ws.Name,
+ Name: ws.DisplayName,
Description: ws.Description,
DefaultLanguage: ws.DefaultLanguage,
},
@@ -218,7 +218,7 @@ func (h *WorkspaceDataHandler) Import(c *okapi.Context, req *ImportWorkspaceData
ws, err := h.workspaceRepo.FindByID(wsID)
if err == nil {
if data.WorkspaceSettings.Name != "" {
- ws.Name = data.WorkspaceSettings.Name
+ ws.DisplayName = data.WorkspaceSettings.Name
}
if data.WorkspaceSettings.Description != "" {
ws.Description = data.WorkspaceSettings.Description
diff --git a/internal/handlers/workspace_handler.go b/internal/handlers/workspace_handler.go
index 026e78e..6e1234b 100644
--- a/internal/handlers/workspace_handler.go
+++ b/internal/handlers/workspace_handler.go
@@ -23,7 +23,6 @@ import (
"crypto/rand"
"encoding/hex"
"fmt"
- "regexp"
"strings"
"time"
@@ -73,8 +72,9 @@ func (h *WorkspaceHandler) SetSeeder(s workspaceSeeder) { h.seeder = s }
type CreateWorkspaceRequest struct {
Body struct {
- Name string `json:"name" required:"true" minLength:"1"`
- Slug string `json:"slug"`
+ Name string `json:"name" doc:"Identifier, like acme: lowercase letters, digits and hyphens, unique on the platform. Derived from display_name when empty."`
+ DisplayName string `json:"display_name" doc:"The workspace's label. Defaults to name."`
+ Slug string `json:"slug,omitempty" doc:"Deprecated: the identifier before 0.18, now name."`
Description string `json:"description"`
DefaultLanguage string `json:"default_language"`
// SeedDefaults fills the new workspace with starter templates, a
@@ -88,7 +88,8 @@ type CreateWorkspaceRequest struct {
type UpdateWorkspaceRequest struct {
Body struct {
- Name string `json:"name"`
+ Name string `json:"name" doc:"A workspace's name cannot change; only accepted when it is the current one. Set display_name to rename it."`
+ DisplayName string `json:"display_name"`
Description string `json:"description"`
DefaultLanguage string `json:"default_language"`
} `json:"body"`
@@ -126,8 +127,8 @@ type DeclineInvitationRequest struct {
type WorkspaceResponse struct {
ID uint `json:"id"`
+ DisplayName string `json:"display_name"`
Name string `json:"name"`
- Slug string `json:"slug"`
Description string `json:"description"`
OwnerID uint `json:"owner_id"`
Role string `json:"role"`
@@ -167,22 +168,15 @@ func (h *WorkspaceHandler) Create(c *okapi.Context, req *CreateWorkspaceRequest)
}
}
- slug := req.Body.Slug
- if slug == "" {
- slug = slugify(req.Body.Name)
- }
-
- // Validate slug format
- if !isValidSlug(slug) {
- return c.AbortBadRequest("slug must contain only lowercase letters, numbers, and hyphens")
+ name, displayName, err := resolveNames(req.Body.Name, req.Body.DisplayName, req.Body.Slug)
+ if err != nil {
+ return c.AbortBadRequest(err.Error())
}
- if workspace.IsReservedSlug(slug) {
- return c.AbortConflict("that slug is reserved by the platform")
+ if workspace.IsReservedName(name) {
+ return c.AbortConflict("the name \"" + name + "\" is reserved by the platform")
}
-
- // Check slug uniqueness
- if _, err := h.workspaceRepo.FindBySlug(slug); err == nil {
- return c.AbortConflict("workspace slug already exists")
+ if _, err := h.workspaceRepo.FindByName(name); err == nil {
+ return c.AbortConflict("a workspace named \"" + name + "\" already exists")
}
defaultLang := strings.TrimSpace(req.Body.DefaultLanguage)
@@ -191,8 +185,8 @@ func (h *WorkspaceHandler) Create(c *okapi.Context, req *CreateWorkspaceRequest)
}
ws := &models.Workspace{
- Name: strings.TrimSpace(req.Body.Name),
- Slug: slug,
+ Name: name,
+ DisplayName: displayName,
Description: req.Body.Description,
DefaultLanguage: defaultLang,
OwnerID: uint(userID),
@@ -220,14 +214,14 @@ func (h *WorkspaceHandler) Create(c *okapi.Context, req *CreateWorkspaceRequest)
h.seeder.SeedWorkspaceDefaults(ws.ID, uint(userID), h.ownerName(uint(userID)))
}
- h.logAudit(c, ws.ID, "workspace.created", "Workspace created: "+ws.Name, map[string]any{
- metaSlug: ws.Slug, "seeded": seeded,
+ h.logAudit(c, ws.ID, "workspace.created", "Workspace created: "+ws.DisplayName, map[string]any{
+ metaName: ws.Name, "seeded": seeded,
})
return created(c, WorkspaceResponse{
ID: ws.ID,
+ DisplayName: ws.DisplayName,
Name: ws.Name,
- Slug: ws.Slug,
Description: ws.Description,
OwnerID: ws.OwnerID,
Role: string(models.WorkspaceRoleOwner),
@@ -274,8 +268,8 @@ func (h *WorkspaceHandler) List(c *okapi.Context) error {
}
result = append(result, WorkspaceResponse{
ID: ws.ID,
+ DisplayName: ws.DisplayName,
Name: ws.Name,
- Slug: ws.Slug,
Description: ws.Description,
OwnerID: ws.OwnerID,
Role: role,
@@ -299,8 +293,8 @@ func (h *WorkspaceHandler) Get(c *okapi.Context) error {
return ok(c, WorkspaceResponse{
ID: ws.ID,
+ DisplayName: ws.DisplayName,
Name: ws.Name,
- Slug: ws.Slug,
Description: ws.Description,
OwnerID: ws.OwnerID,
Role: role,
@@ -317,11 +311,18 @@ func (h *WorkspaceHandler) Update(c *okapi.Context, req *UpdateWorkspaceRequest)
return c.AbortNotFound("workspace not found")
}
- if ws.System && req.Body.Name != "" && strings.TrimSpace(req.Body.Name) != ws.Name {
+ name, displayName, err := resolveRenames(req.Body.Name, req.Body.DisplayName, "")
+ if err != nil {
+ return c.AbortBadRequest(err.Error())
+ }
+ if name != "" && name != ws.Name {
+ return c.AbortBadRequest("a workspace's name cannot change; set display_name to rename it")
+ }
+ if ws.System && displayName != "" && displayName != ws.DisplayName {
return c.AbortConflict("the system workspace cannot be renamed")
}
- if req.Body.Name != "" {
- ws.Name = strings.TrimSpace(req.Body.Name)
+ if displayName != "" {
+ ws.DisplayName = displayName
}
if req.Body.Description != "" {
ws.Description = req.Body.Description
@@ -335,14 +336,14 @@ func (h *WorkspaceHandler) Update(c *okapi.Context, req *UpdateWorkspaceRequest)
return c.AbortInternalServerError("failed to update workspace")
}
- h.logAudit(c, ws.ID, "workspace.updated", "Workspace updated: "+ws.Name, nil)
+ h.logAudit(c, ws.ID, "workspace.updated", "Workspace updated: "+ws.DisplayName, nil)
role := c.GetString("workspace_role")
return ok(c, WorkspaceResponse{
ID: ws.ID,
+ DisplayName: ws.DisplayName,
Name: ws.Name,
- Slug: ws.Slug,
Description: ws.Description,
OwnerID: ws.OwnerID,
Role: role,
@@ -370,7 +371,7 @@ func (h *WorkspaceHandler) Delete(c *okapi.Context) error {
return c.AbortInternalServerError("failed to delete workspace")
}
- h.logAudit(c, ws.ID, "workspace.deleted", "Workspace deleted: "+ws.Name, map[string]any{metaSlug: ws.Slug})
+ h.logAudit(c, ws.ID, "workspace.deleted", "Workspace deleted: "+ws.DisplayName, map[string]any{metaName: ws.Name})
return noContent(c)
}
@@ -432,7 +433,7 @@ func (h *WorkspaceHandler) UpdateMemberRole(c *okapi.Context, req *UpdateMemberR
wsName := ""
changerName := "An administrator"
if ws != nil {
- wsName = ws.Name
+ wsName = ws.DisplayName
}
if changer != nil {
changerName = changer.Name
@@ -525,7 +526,7 @@ func (h *WorkspaceHandler) InviteMember(c *okapi.Context, req *InviteMemberReque
wsName := ""
inviterName := "A team member"
if ws != nil {
- wsName = ws.Name
+ wsName = ws.DisplayName
}
if inviter != nil {
inviterName = inviter.Name
@@ -627,7 +628,7 @@ func (h *WorkspaceHandler) MyInvitations(c *okapi.Context) error {
result = append(result, InvitationResponse{
ID: inv.ID,
WorkspaceID: inv.WorkspaceID,
- Workspace: inv.Workspace.Name,
+ Workspace: inv.Workspace.DisplayName,
Email: inv.Email,
Role: string(inv.Role),
Status: string(inv.Status),
@@ -685,11 +686,11 @@ func (h *WorkspaceHandler) AcceptInvitation(c *okapi.Context, req *AcceptInvitat
inv.Status = models.InvitationStatusAccepted
_ = h.workspaceRepo.UpdateInvitation(inv)
- h.logAudit(c, inv.WorkspaceID, "member.joined", "Joined workspace "+inv.Workspace.Name,
+ h.logAudit(c, inv.WorkspaceID, "member.joined", "Joined workspace "+inv.Workspace.DisplayName,
map[string]any{"role": string(inv.Role)})
return ok(c, okapi.M{
- "message": fmt.Sprintf("joined workspace %q", inv.Workspace.Name),
+ "message": fmt.Sprintf("joined workspace %q", inv.Workspace.DisplayName),
"workspace_id": inv.WorkspaceID,
})
}
@@ -748,11 +749,11 @@ func (h *WorkspaceHandler) AcceptInvitationByID(c *okapi.Context, req *AcceptInv
inv.Status = models.InvitationStatusAccepted
_ = h.workspaceRepo.UpdateInvitation(inv)
- h.logAudit(c, inv.WorkspaceID, "member.joined", "Joined workspace "+inv.Workspace.Name,
+ h.logAudit(c, inv.WorkspaceID, "member.joined", "Joined workspace "+inv.Workspace.DisplayName,
map[string]any{"role": string(inv.Role)})
return ok(c, okapi.M{
- "message": fmt.Sprintf("joined workspace %q", inv.Workspace.Name),
+ "message": fmt.Sprintf("joined workspace %q", inv.Workspace.DisplayName),
"workspace_id": inv.WorkspaceID,
})
}
@@ -801,23 +802,6 @@ func (h *WorkspaceHandler) DeclineInvitation(c *okapi.Context, req *DeclineInvit
return ok(c, okapi.M{"message": "invitation declined"})
}
-var slugRegex = regexp.MustCompile(`^[a-z0-9]+(?:-[a-z0-9]+)*$`)
-
-func isValidSlug(s string) bool {
- return slugRegex.MatchString(s)
-}
-
-func slugify(name string) string {
- s := strings.ToLower(strings.TrimSpace(name))
- s = regexp.MustCompile(`[^a-z0-9\s-]`).ReplaceAllString(s, "")
- s = regexp.MustCompile(`[\s]+`).ReplaceAllString(s, "-")
- s = strings.Trim(s, "-")
- if s == "" {
- s = "workspace"
- }
- return s
-}
-
func generateToken() (string, error) {
b := make([]byte, 32)
if _, err := rand.Read(b); err != nil {
diff --git a/internal/models/form.go b/internal/models/form.go
index 0da07c9..23acceb 100644
--- a/internal/models/form.go
+++ b/internal/models/form.go
@@ -86,7 +86,7 @@ type Form struct {
UUID string `json:"uuid" gorm:"type:uuid;default:gen_random_uuid();uniqueIndex;not null"`
WorkspaceID *uint `json:"workspace_id,omitempty" gorm:"index;not null"`
Name string `json:"name" gorm:"not null"`
- Slug string `json:"slug" gorm:"not null"`
+ DisplayName string `json:"display_name" gorm:"not null;default:''"`
Description string `json:"description"`
PublicKey string `json:"public_key" gorm:"uniqueIndex;not null"`
Status FormStatus `json:"status" gorm:"type:varchar(20);default:'active';index;not null"`
diff --git a/internal/models/identifier.go b/internal/models/identifier.go
new file mode 100644
index 0000000..2bcc1d0
--- /dev/null
+++ b/internal/models/identifier.go
@@ -0,0 +1,55 @@
+// Copyright (c) 2026 Jonas Kaninda.
+//
+// This file is part of Posta.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+//
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package models
+
+import (
+ "fmt"
+ "regexp"
+ "strings"
+)
+
+// Workspaces, forms, OAuth providers, templates and stylesheets share one
+// naming scheme: Name is the identifier the API and URLs use, like
+// "contact-form"; DisplayName is the label people read.
+
+var identifierPattern = regexp.MustCompile(`^[a-z0-9]+(?:-[a-z0-9]+)*$`)
+
+var identifierSeparators = regexp.MustCompile(`[^a-z0-9]+`)
+
+const MaxIdentifierLength = 63
+
+// ToIdentifier derives an identifier from a label: "Contact form" becomes
+// "contact-form". It is empty when the label has no letters or digits.
+func ToIdentifier(label string) string {
+ v := identifierSeparators.ReplaceAllString(strings.ToLower(strings.TrimSpace(label)), "-")
+ v = strings.Trim(v, "-")
+ if len(v) > MaxIdentifierLength {
+ v = strings.Trim(v[:MaxIdentifierLength], "-")
+ }
+ return v
+}
+
+// CheckIdentifier explains why name cannot be an identifier.
+func CheckIdentifier(name string) error {
+ if len(name) > MaxIdentifierLength || !identifierPattern.MatchString(name) {
+ return fmt.Errorf("name %q must be up to %d lowercase letters, digits and hyphens, like \"contact-form\"; put the label in display_name", name, MaxIdentifierLength)
+ }
+ return nil
+}
diff --git a/internal/models/oauth_provider.go b/internal/models/oauth_provider.go
index cd55f85..b0498cf 100644
--- a/internal/models/oauth_provider.go
+++ b/internal/models/oauth_provider.go
@@ -32,8 +32,8 @@ const (
type OAuthProvider struct {
ID uint `json:"id" gorm:"primaryKey"`
WorkspaceID *uint `json:"workspace_id,omitempty" gorm:"index"`
- Name string `json:"name" gorm:"not null"`
- Slug string `json:"slug" gorm:"uniqueIndex;not null"`
+ Name string `json:"name" gorm:"uniqueIndex;not null"`
+ DisplayName string `json:"display_name" gorm:"not null;default:''"`
Type OAuthProviderType `json:"type" gorm:"not null"`
ClientID string `json:"-" gorm:"not null"`
ClientSecret string `json:"-" gorm:"not null"`
diff --git a/internal/models/stylesheet.go b/internal/models/stylesheet.go
index e56d92d..2b861f2 100644
--- a/internal/models/stylesheet.go
+++ b/internal/models/stylesheet.go
@@ -26,6 +26,7 @@ type StyleSheet struct {
UserID uint `json:"user_id" gorm:"index;not null"`
WorkspaceID *uint `json:"workspace_id,omitempty" gorm:"index"`
Name string `json:"name" gorm:"not null"`
+ DisplayName string `json:"display_name" gorm:"not null;default:''"`
CSS string `json:"css"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt *time.Time `json:"updated_at,omitempty"`
diff --git a/internal/models/template.go b/internal/models/template.go
index 1230f1c..4443084 100644
--- a/internal/models/template.go
+++ b/internal/models/template.go
@@ -26,6 +26,7 @@ type Template struct {
UserID uint `json:"user_id" gorm:"index;not null"`
WorkspaceID *uint `json:"workspace_id,omitempty" gorm:"index"`
Name string `json:"name" gorm:"not null"`
+ DisplayName string `json:"display_name" gorm:"not null;default:''"`
DefaultLanguage string `json:"default_language" gorm:"default:en;not null"`
ActiveVersionID *uint `json:"active_version_id,omitempty" gorm:"uniqueIndex"`
Description string `json:"description"`
diff --git a/internal/models/workspace.go b/internal/models/workspace.go
index 8209634..ead04d2 100644
--- a/internal/models/workspace.go
+++ b/internal/models/workspace.go
@@ -40,8 +40,8 @@ const (
type Workspace struct {
ID uint `json:"id" gorm:"primaryKey"`
- Name string `json:"name" gorm:"not null"`
- Slug string `json:"slug" gorm:"uniqueIndex;not null"`
+ Name string `json:"name" gorm:"uniqueIndex;not null"`
+ DisplayName string `json:"display_name" gorm:"not null;default:''"`
Description string `json:"description"`
OwnerID uint `json:"owner_id" gorm:"index;not null"`
PlanID *uint `json:"plan_id" gorm:"index"`
diff --git a/internal/routes/admin_routes.go b/internal/routes/admin_routes.go
index aeaaa1d..19e0292 100644
--- a/internal/routes/admin_routes.go
+++ b/internal/routes/admin_routes.go
@@ -402,7 +402,7 @@ func (r *Router) adminRoutes() []okapi.RouteDefinition {
Handler: okapi.H(r.h.adminWorkspace.List),
Group: adminGroup,
Summary: "List all workspaces",
- Description: "Platform-wide workspace list with owner, plan and member count, filterable by name/slug, owner, and plan.",
+ Description: "Platform-wide workspace list with owner, plan and member count, filterable by name or display name, owner, and plan.",
Request: &handlers.AdminListWorkspacesRequest{},
Response: &dto.PageableResponse[handlers.AdminWorkspaceRow]{},
},
diff --git a/internal/routes/oauth_routes.go b/internal/routes/oauth_routes.go
index 5f79c63..5960fb4 100644
--- a/internal/routes/oauth_routes.go
+++ b/internal/routes/oauth_routes.go
@@ -54,7 +54,7 @@ func (r *Router) oauthRoutes() []okapi.RouteDefinition {
Handler: okapi.H(r.h.oauth.DiscoverSSO),
Group: oauthPublic,
Summary: "Discover SSO provider by email",
- Description: "Returns the OAuth provider slug whose allowed domains match the given email's domain. Used for email-first SSO login.",
+ Description: "Returns the name of the OAuth provider whose allowed domains match the given email's domain. Used for email-first SSO login.",
Request: &handlers.DiscoverSSORequest{},
Response: &dto.Response[handlers.DiscoverSSOResponse]{},
},
@@ -66,7 +66,7 @@ func (r *Router) oauthRoutes() []okapi.RouteDefinition {
Summary: "Initiate OAuth flow",
Description: "Redirects to the OAuth provider's authorization page",
Options: []okapi.RouteOption{
- okapi.DocPathParam("provider", "string", "Provider slug"),
+ okapi.DocPathParam("provider", "string", "Provider name"),
},
},
{
@@ -77,7 +77,7 @@ func (r *Router) oauthRoutes() []okapi.RouteDefinition {
Summary: "OAuth callback",
Description: "Handles the OAuth provider's redirect after authorization",
Options: []okapi.RouteOption{
- okapi.DocPathParam("provider", "string", "Provider slug"),
+ okapi.DocPathParam("provider", "string", "Provider name"),
okapi.DocHide(),
},
},
diff --git a/internal/routes/routes.go b/internal/routes/routes.go
index 59a23fd..de601c9 100644
--- a/internal/routes/routes.go
+++ b/internal/routes/routes.go
@@ -543,10 +543,10 @@ func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *c
// Auto-seed Google provider if configured
if cfg.GoogleOAuthClientID != "" {
- if _, err := oauthProviderRepo.FindBySlug("google"); err != nil {
+ if _, err := oauthProviderRepo.FindByName("google"); err != nil {
_ = oauthProviderRepo.Create(&models.OAuthProvider{
- Name: "Google",
- Slug: "google",
+ DisplayName: "Google",
+ Name: "google",
Type: models.OAuthProviderGoogle,
ClientID: cfg.GoogleOAuthClientID,
ClientSecret: cfg.GoogleOAuthClientSecret,
diff --git a/internal/routes/workspace_resource_routes.go b/internal/routes/workspace_resource_routes.go
index 7160818..ee105b9 100644
--- a/internal/routes/workspace_resource_routes.go
+++ b/internal/routes/workspace_resource_routes.go
@@ -389,7 +389,7 @@ func (r *Router) workspaceResourceRoutes() []okapi.RouteDefinition {
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.",
+ Description: "Upload an .html file as multipart/form-data under \"file\" to create a template. CSS from <style> blocks is extracted into a separate stylesheet. Optional form fields: name and display_name (default: from the filename), subject (default: the document's <title>), language (default: the workspace's default language) and description.",
Options: []okapi.RouteOption{
okapi.DocResponse(201, &dto.Response[models.Template]{}),
okapi.DocResponse(409, &dto.ErrorResponseBody{}),
diff --git a/internal/services/auth/oauth.go b/internal/services/auth/oauth.go
index 2716315..0f8a017 100644
--- a/internal/services/auth/oauth.go
+++ b/internal/services/auth/oauth.go
@@ -92,7 +92,7 @@ func (s *OAuthService) GetOAuthConfig(provider *models.OAuthProvider, redirectUR
}
if provider.AuthURL == "" || provider.TokenURL == "" {
- return nil, fmt.Errorf("OIDC provider %q has no issuer for auto-discovery and no explicit auth_url/token_url configured", provider.Name)
+ return nil, fmt.Errorf("OIDC provider %q has no issuer for auto-discovery and no explicit auth_url/token_url configured", provider.DisplayName)
}
cfg.Endpoint = oauth2.Endpoint{
@@ -119,7 +119,7 @@ func (s *OAuthService) ExchangeCode(ctx context.Context, provider *models.OAuthP
if idErr == nil {
return info, token, nil
}
- fmt.Printf("[oauth] ID token parse failed for %s: %v, falling back to userinfo\n", provider.Slug, idErr)
+ fmt.Printf("[oauth] ID token parse failed for %s: %v, falling back to userinfo\n", provider.Name, idErr)
}
// Fall back to userinfo endpoint (use OIDC discovery for correct URL)
diff --git a/internal/services/email/service.go b/internal/services/email/service.go
index 60d434f..473bace 100644
--- a/internal/services/email/service.go
+++ b/internal/services/email/service.go
@@ -1222,7 +1222,8 @@ func (s *Service) RenderTemplate(userID uint, workspaceID *uint, templateID *uin
// findTemplate looks up the template ref names, or the deprecated templateID
// when ref is empty. A ref is matched by name in the workspace first; one that
// is all digits and matches no name is then looked up as an ID, so a template
-// named "2024" still wins over the template whose ID is 2024.
+// named "2024" still wins over the template whose ID is 2024. Until 0.19 a ref
+// matching nothing else is tried as a display name, with a warning.
func (s *Service) findTemplate(userID uint, workspaceID *uint, templateID *uint, ref TemplateRef) (*models.Template, error) {
if ref == "" {
if templateID != nil && *templateID != 0 {
@@ -1241,6 +1242,14 @@ func (s *Service) findTemplate(userID uint, workspaceID *uint, templateID *uint,
return tmpl, nil
}
}
+ if workspaceID != nil {
+ // Before 0.18 a template's name was its label, and callers sent that.
+ if tmpl, err := s.templateRepo.FindByWorkspaceDisplayName(*workspaceID, ref.String()); err == nil {
+ logger.Warn("template sent by its display name, which is deprecated: send its name instead",
+ "display_name", ref.String(), "name", tmpl.Name, "workspace_id", *workspaceID)
+ return tmpl, nil
+ }
+ }
if workspaceID == nil {
return nil, fmt.Errorf("template %q not found: no active workspace", ref)
}
@@ -1269,7 +1278,7 @@ func (s *Service) findTemplateByID(userID uint, workspaceID *uint, id uint) (*mo
// and renders it with the given data.
func (s *Service) resolveAndRender(tmpl *models.Template, language string, data map[string]any) (*RenderedTemplate, error) {
if tmpl.ActiveVersionID == nil {
- return nil, fmt.Errorf("template %q has no active version", tmpl.Name)
+ return nil, fmt.Errorf("template %q has no active version", tmpl.DisplayName)
}
v, err := s.versionRepo.FindByID(*tmpl.ActiveVersionID)
@@ -1279,7 +1288,7 @@ func (s *Service) resolveAndRender(tmpl *models.Template, language string, data
l := s.resolveLocalization(v.ID, language, tmpl.DefaultLanguage)
if l == nil {
- return nil, fmt.Errorf("no localization found for template %q", tmpl.Name)
+ return nil, fmt.Errorf("no localization found for template %q", tmpl.DisplayName)
}
var css string
diff --git a/internal/services/messages/service.go b/internal/services/messages/service.go
index 1bb60d2..dcc7a1b 100644
--- a/internal/services/messages/service.go
+++ b/internal/services/messages/service.go
@@ -498,7 +498,7 @@ func newMessageID(messageUUID, from string) string {
}
func defaultSubject(form *models.Form) string {
- return fmt.Sprintf("New submission on %s", form.Name)
+ return fmt.Sprintf("New submission on %s", form.DisplayName)
}
func replySubject(subject string) string {
diff --git a/internal/services/notification/service.go b/internal/services/notification/service.go
index 572223a..d7a4186 100644
--- a/internal/services/notification/service.go
+++ b/internal/services/notification/service.go
@@ -240,7 +240,7 @@ func (s *Service) SendToWorkspaceAdmins(workspaceID uint, subject, templateName
}
if _, ok := data["WorkspaceName"]; !ok {
if ws, err := s.workspaceRepo.FindByID(workspaceID); err == nil {
- data["WorkspaceName"] = ws.Name
+ data["WorkspaceName"] = ws.DisplayName
}
}
diff --git a/internal/services/seeder/forms.go b/internal/services/seeder/forms.go
index 8a7cceb..54b921f 100644
--- a/internal/services/seeder/forms.go
+++ b/internal/services/seeder/forms.go
@@ -26,8 +26,8 @@ import (
)
type formDef struct {
+ DisplayName string
Name string
- Slug string
Description string
Mode models.FormMode
Confirmation string
@@ -41,8 +41,8 @@ type formDef struct {
func defaultFormDefs() []formDef {
return []formDef{
{
- Name: "Contact form",
- Slug: "contact",
+ DisplayName: "Contact form",
+ Name: "contact",
Description: "Questions and requests from your website, answered from Messages.",
Mode: models.FormModeInbox,
Confirmation: "Thanks for getting in touch. We'll reply by email soon.",
@@ -54,8 +54,8 @@ func defaultFormDefs() []formDef {
},
},
{
- Name: "Customer feedback",
- Slug: "customer-feedback",
+ DisplayName: "Customer feedback",
+ Name: "customer-feedback",
Description: "A short survey. Its responses are summarised per question and can be exported.",
Mode: models.FormModeCollect,
Confirmation: "Thank you, your feedback helps us improve.",
@@ -88,8 +88,8 @@ func defaultFormDefs() []formDef {
},
},
{
- Name: "Event registration",
- Slug: "event-registration",
+ DisplayName: "Event registration",
+ Name: "event-registration",
Description: "A registration form over three pages, one section each.",
Mode: models.FormModeCollect,
Confirmation: "You're registered. We'll send the details before the event.",
@@ -138,7 +138,7 @@ func (s *Seeder) seedForms(workspaceID, userID uint) {
for _, def := range defaultFormDefs() {
key, err := models.NewFormPublicKey()
if err != nil {
- logger.Error("failed to generate form key", "name", def.Name, "error", err)
+ logger.Error("failed to generate form key", "name", def.DisplayName, "error", err)
return
}
notifyMode := models.NotifyModeImmediate
@@ -149,7 +149,7 @@ func (s *Seeder) seedForms(workspaceID, userID uint) {
form := &models.Form{
WorkspaceID: workspacePtr(workspaceID),
Name: def.Name,
- Slug: def.Slug,
+ DisplayName: def.DisplayName,
Description: def.Description,
PublicKey: key,
Status: models.FormStatusActive,
@@ -172,7 +172,7 @@ func (s *Seeder) seedForms(workspaceID, userID uint) {
LastEditedByID: &userID,
}
if err := s.formRepo.Create(form); err != nil {
- logger.Error("failed to seed form", "name", def.Name, "workspace_id", workspaceID, "error", err)
+ logger.Error("failed to seed form", "name", def.DisplayName, "workspace_id", workspaceID, "error", err)
}
}
}
diff --git a/internal/services/seeder/seeder.go b/internal/services/seeder/seeder.go
index 1ad58d8..bcac94c 100644
--- a/internal/services/seeder/seeder.go
+++ b/internal/services/seeder/seeder.go
@@ -65,7 +65,7 @@ func New(
var seedLanguages = []string{"en", "fr", "de"}
type templateDef struct {
- Name string
+ DisplayName string
Description string
Base string // template file base name, e.g. "welcome"
SampleData okapi.M
@@ -85,13 +85,14 @@ func (s *Seeder) seedTemplate(workspaceID, userID uint, ssID uint, def templateD
tmpl := &models.Template{
UserID: userID,
WorkspaceID: workspacePtr(workspaceID),
- Name: def.Name,
+ Name: models.ToIdentifier(def.DisplayName),
+ DisplayName: def.DisplayName,
DefaultLanguage: seedLanguages[0],
Description: def.Description,
SampleData: sampleData,
}
if err := s.templateRepo.Create(tmpl); err != nil {
- logger.Error("failed to seed template", "name", def.Name, "user_id", userID, "error", err)
+ logger.Error("failed to seed template", "name", def.DisplayName, "user_id", userID, "error", err)
return
}
@@ -102,7 +103,7 @@ func (s *Seeder) seedTemplate(workspaceID, userID uint, ssID uint, def templateD
SampleData: sampleData,
}
if err := s.versionRepo.Create(v); err != nil {
- logger.Error("failed to seed template version", "name", def.Name, "user_id", userID, "error", err)
+ logger.Error("failed to seed template version", "name", def.DisplayName, "user_id", userID, "error", err)
return
}
@@ -115,14 +116,14 @@ func (s *Seeder) seedTemplate(workspaceID, userID uint, ssID uint, def templateD
TextTemplate: textTmpl(def.Base, lang),
}
if err := s.localizationRepo.Create(loc); err != nil {
- logger.Error("failed to seed localization", "name", def.Name, "lang", lang, "user_id", userID, "error", err)
+ logger.Error("failed to seed localization", "name", def.DisplayName, "lang", lang, "user_id", userID, "error", err)
}
}
vID := v.ID
tmpl.ActiveVersionID = &vID
if err := s.templateRepo.Update(tmpl); err != nil {
- logger.Error("failed to activate template version", "name", def.Name, "user_id", userID, "error", err)
+ logger.Error("failed to activate template version", "name", def.DisplayName, "user_id", userID, "error", err)
}
}
@@ -161,6 +162,7 @@ func (s *Seeder) SeedWorkspaceDefaults(workspaceID, userID uint, userName string
UserID: userID,
WorkspaceID: wsID,
Name: "default",
+ DisplayName: "Default",
CSS: defaultCSS,
}
if err := s.stylesheetRepo.Create(ss); err != nil {
@@ -207,7 +209,7 @@ func defaultTemplateDefs(userName string, year int, docsURL string) []templateDe
return []templateDef{
// 1. Welcome
{
- Name: "Welcome Email",
+ DisplayName: "Welcome Email",
Description: "Welcome email introducing Posta and its features",
SampleData: okapi.M{
"name": userName,
@@ -247,7 +249,7 @@ func defaultTemplateDefs(userName string, year int, docsURL string) []templateDe
},
// 2. Password Reset
{
- Name: "Password Reset",
+ DisplayName: "Password Reset",
Description: "Transactional email for password reset requests",
SampleData: okapi.M{
"name": userName,
@@ -265,7 +267,7 @@ func defaultTemplateDefs(userName string, year int, docsURL string) []templateDe
},
// 3. Order Confirmation
{
- Name: "Order Confirmation",
+ DisplayName: "Order Confirmation",
Description: "Order confirmation email with item details and total",
SampleData: okapi.M{
"name": userName,
@@ -288,7 +290,7 @@ func defaultTemplateDefs(userName string, year int, docsURL string) []templateDe
},
// 4. Newsletter
{
- Name: "Monthly Newsletter",
+ DisplayName: "Monthly Newsletter",
Description: "Monthly newsletter with articles and unsubscribe link",
SampleData: okapi.M{
"name": userName,
@@ -323,7 +325,7 @@ func defaultTemplateDefs(userName string, year int, docsURL string) []templateDe
},
// 5. Email Verification
{
- Name: "Email Verification",
+ DisplayName: "Email Verification",
Description: "Confirm a new account's email address with a link and code",
SampleData: okapi.M{
"name": userName,
@@ -342,7 +344,7 @@ func defaultTemplateDefs(userName string, year int, docsURL string) []templateDe
},
// 6. Sign-in Code (OTP)
{
- Name: "Sign-in Code",
+ DisplayName: "Sign-in Code",
Description: "One-time passcode / magic-link login email",
SampleData: okapi.M{
"name": userName,
@@ -361,7 +363,7 @@ func defaultTemplateDefs(userName string, year int, docsURL string) []templateDe
},
// 7. Invoice / Receipt
{
- Name: "Invoice Receipt",
+ DisplayName: "Invoice Receipt",
Description: "Payment receipt with line items, subtotal, tax, and total",
SampleData: okapi.M{
"name": userName,
@@ -387,7 +389,7 @@ func defaultTemplateDefs(userName string, year int, docsURL string) []templateDe
},
// 8. Team Invitation
{
- Name: "Team Invitation",
+ DisplayName: "Team Invitation",
Description: "Invite a user to a workspace with an accept link and role",
SampleData: okapi.M{
"name": userName,
diff --git a/internal/services/seeder/seeder_forms_test.go b/internal/services/seeder/seeder_forms_test.go
index 7a4787a..3044a56 100644
--- a/internal/services/seeder/seeder_forms_test.go
+++ b/internal/services/seeder/seeder_forms_test.go
@@ -44,11 +44,11 @@ func TestDefaultFormsAreValid(t *testing.T) {
slugs := map[string]bool{}
var sawCollect, sawSections bool
for _, def := range defs {
- t.Run(def.Slug, func(t *testing.T) {
- if slugs[def.Slug] {
- t.Fatalf("slug %q is used twice", def.Slug)
+ t.Run(def.Name, func(t *testing.T) {
+ if slugs[def.Name] {
+ t.Fatalf("slug %q is used twice", def.Name)
}
- slugs[def.Slug] = true
+ slugs[def.Name] = true
fields := append(models.FieldDefs{}, def.Fields...)
if err := messages.CheckSchema(fields, nil, models.DefaultHoneypotField); err != nil {
@@ -102,7 +102,7 @@ func TestSeedWorkspaceDefaultsCreatesForms(t *testing.T) {
if err := tx.Create(user).Error; err != nil {
t.Skipf("skipping: cannot create user: %v", err)
}
- ws := &models.Workspace{Name: "seed test", Slug: fmt.Sprintf("seed-%d", suffix), OwnerID: user.ID}
+ ws := &models.Workspace{DisplayName: "seed test", Name: fmt.Sprintf("seed-%d", suffix), OwnerID: user.ID}
if err := tx.Create(ws).Error; err != nil {
t.Fatalf("create workspace: %v", err)
}
@@ -128,7 +128,7 @@ func TestSeedWorkspaceDefaultsCreatesForms(t *testing.T) {
}
for _, f := range forms {
if len(f.PublicKey) != models.FormPublicKeyLength || len(f.Fields) == 0 || f.Status != models.FormStatusActive {
- t.Fatalf("run %d: form %q seeded incompletely: %+v", run, f.Slug, f)
+ t.Fatalf("run %d: form %q seeded incompletely: %+v", run, f.Name, f)
}
}
}
diff --git a/internal/services/seeder/seeder_templates_test.go b/internal/services/seeder/seeder_templates_test.go
index b17b149..f1b7398 100644
--- a/internal/services/seeder/seeder_templates_test.go
+++ b/internal/services/seeder/seeder_templates_test.go
@@ -39,11 +39,11 @@ func TestDefaultTemplatesRender(t *testing.T) {
renderer := email.NewTemplateRenderer() // defaults to missingkey=error
for _, def := range defs {
- t.Run(def.Name, func(t *testing.T) {
+ t.Run(def.DisplayName, func(t *testing.T) {
for _, lang := range seedLanguages {
subject, ok := def.Subjects[lang]
if !ok || strings.TrimSpace(subject) == "" {
- t.Fatalf("%s/%s: missing subject", def.Name, lang)
+ t.Fatalf("%s/%s: missing subject", def.DisplayName, lang)
}
// WithSystemVars injects the reserved posta_* variables (as
@@ -57,22 +57,22 @@ func TestDefaultTemplatesRender(t *testing.T) {
CSS: defaultCSS,
}, data)
if err != nil {
- t.Fatalf("%s/%s: render failed: %v", def.Name, lang, err)
+ t.Fatalf("%s/%s: render failed: %v", def.DisplayName, lang, err)
}
if strings.TrimSpace(out.Subject) == "" {
- t.Errorf("%s/%s: empty subject", def.Name, lang)
+ t.Errorf("%s/%s: empty subject", def.DisplayName, lang)
}
if strings.TrimSpace(out.HTML) == "" {
- t.Errorf("%s/%s: empty HTML", def.Name, lang)
+ t.Errorf("%s/%s: empty HTML", def.DisplayName, lang)
}
if strings.TrimSpace(out.Text) == "" {
- t.Errorf("%s/%s: empty text", def.Name, lang)
+ t.Errorf("%s/%s: empty text", def.DisplayName, lang)
}
// Every seeded template links the hosted web view, so a reserved
// system sentinel must survive into the rendered HTML.
if !email.HasSystemSentinels(out.HTML) {
- t.Errorf("%s/%s: expected a posta_* system link in rendered HTML", def.Name, lang)
+ t.Errorf("%s/%s: expected a posta_* system link in rendered HTML", def.DisplayName, lang)
}
}
})
diff --git a/internal/services/workspace/system.go b/internal/services/workspace/system.go
index 82910c0..c1f8f4e 100644
--- a/internal/services/workspace/system.go
+++ b/internal/services/workspace/system.go
@@ -30,8 +30,8 @@ import (
)
const (
- SystemSlug = "system"
- SystemName = "Posta System"
+ SystemName = "system"
+ SystemDisplayName = "Posta System"
SystemDescription = "Built-in workspace for platform-managed resources. Managed by platform administrators."
)
@@ -71,14 +71,14 @@ func EnsureSystem(db *gorm.DB, smtp config.SystemSMTPConfig) (*models.Workspace,
return nil, fmt.Errorf("resolve system workspace owner: %w", err)
}
- slug, err := availableSlug(db, SystemSlug)
+ name, err := availableName(db, SystemName)
if err != nil {
return nil, err
}
ws := &models.Workspace{
- Name: SystemName,
- Slug: slug,
+ DisplayName: SystemDisplayName,
+ Name: name,
Description: SystemDescription,
OwnerID: owner.ID,
System: true,
@@ -120,7 +120,7 @@ func EnsureSystem(db *gorm.DB, smtp config.SystemSMTPConfig) (*models.Workspace,
return nil, err
}
- logger.Info("platform system workspace ready", "workspace_id", ws.ID, "slug", ws.Slug, "owner_id", owner.ID)
+ logger.Info("platform system workspace ready", "workspace_id", ws.ID, "name", ws.Name, "owner_id", owner.ID)
return ws, nil
}
@@ -161,20 +161,20 @@ func SyncMembers(db *gorm.DB) error {
Delete(&models.WorkspaceMember{}).Error
}
-// IsReservedSlug reports whether slug is claimable only by the system workspace.
-func IsReservedSlug(slug string) bool { return slug == SystemSlug }
+// IsReservedName reports whether name is claimable only by the system workspace.
+func IsReservedName(name string) bool { return name == SystemName }
-func availableSlug(db *gorm.DB, base string) (string, error) {
- slug := base
+func availableName(db *gorm.DB, base string) (string, error) {
+ name := base
for i := 2; i < 100; i++ {
var count int64
- if err := db.Model(&models.Workspace{}).Where("slug = ?", slug).Count(&count).Error; err != nil {
+ if err := db.Model(&models.Workspace{}).Where("name = ?", name).Count(&count).Error; err != nil {
return "", err
}
if count == 0 {
- return slug, nil
+ return name, nil
}
- slug = fmt.Sprintf("%s-%d", base, i)
+ name = fmt.Sprintf("%s-%d", base, i)
}
- return "", fmt.Errorf("could not find an available slug for %q", base)
+ return "", fmt.Errorf("could not find an available name for %q", base)
}
diff --git a/internal/services/workspace/system_test.go b/internal/services/workspace/system_test.go
index 546524c..b356dbd 100644
--- a/internal/services/workspace/system_test.go
+++ b/internal/services/workspace/system_test.go
@@ -21,13 +21,13 @@ package workspace
import "testing"
-func TestIsReservedSlug(t *testing.T) {
- if !IsReservedSlug(SystemSlug) {
- t.Fatalf("IsReservedSlug(%q) = false, want true", SystemSlug)
+func TestIsReservedName(t *testing.T) {
+ if !IsReservedName(SystemName) {
+ t.Fatalf("IsReservedName(%q) = false, want true", SystemName)
}
for _, slug := range []string{"acme", "system-2", "systems", "", "System"} {
- if IsReservedSlug(slug) {
- t.Fatalf("IsReservedSlug(%q) = true, want false", slug)
+ if IsReservedName(slug) {
+ t.Fatalf("IsReservedName(%q) = true, want false", slug)
}
}
}
diff --git a/internal/services/workspaceprovision/provision.go b/internal/services/workspaceprovision/provision.go
index 0c521de..0ed71a1 100644
--- a/internal/services/workspaceprovision/provision.go
+++ b/internal/services/workspaceprovision/provision.go
@@ -153,10 +153,10 @@ func (s *Service) provision(tx *gorm.DB, userID uint) (uint, error) {
}
ws := &models.Workspace{
- Name: workspaceName(user.Name),
- Slug: workspaceSlug(user.ID),
- OwnerID: user.ID,
- PlanID: planID,
+ DisplayName: workspaceDisplayName(user.Name),
+ Name: workspaceName(user.ID),
+ OwnerID: user.ID,
+ PlanID: planID,
}
if err := tx.Create(ws).Error; err != nil {
return 0, fmt.Errorf("create workspace: %w", err)
@@ -239,9 +239,9 @@ func (s *Service) copySettings(tx *gorm.DB, userID, workspaceID uint, requireVer
return nil
}
-// workspaceName labels a user's first workspace after them, so a switcher with
+// workspaceDisplayName labels a user's first workspace after them, so a switcher with
// several entries reads as names rather than as "Workspace 1, Workspace 2".
-func workspaceName(userName string) string {
+func workspaceDisplayName(userName string) string {
first := strings.TrimSpace(userName)
if idx := strings.IndexAny(first, " \t"); idx > 0 {
first = first[:idx]
@@ -252,7 +252,7 @@ func workspaceName(userName string) string {
return first + "'s workspace"
}
-// workspaceSlug derives a stable, unique slug for a user's first workspace.
-func workspaceSlug(userID uint) string {
+// workspaceName derives a stable, unique name for a user's first workspace.
+func workspaceName(userID uint) string {
return fmt.Sprintf("workspace-%d", userID)
}
diff --git a/internal/services/workspaceprovision/provision_test.go b/internal/services/workspaceprovision/provision_test.go
index 8fd2a42..fb47aec 100644
--- a/internal/services/workspaceprovision/provision_test.go
+++ b/internal/services/workspaceprovision/provision_test.go
@@ -26,12 +26,12 @@ import (
"github.com/goposta/posta/internal/models"
)
-func TestWorkspaceSlugIsStableAndUnique(t *testing.T) {
- if got := workspaceSlug(42); got != "workspace-42" {
- t.Fatalf("workspaceSlug(42) = %q, want %q", got, "workspace-42")
+func TestWorkspaceNameIsStableAndUnique(t *testing.T) {
+ if got := workspaceName(42); got != "workspace-42" {
+ t.Fatalf("workspaceName(42) = %q, want %q", got, "workspace-42")
}
- if workspaceSlug(1) == workspaceSlug(2) {
- t.Fatal("workspaceSlug must differ per user")
+ if workspaceName(1) == workspaceName(2) {
+ t.Fatal("workspaceName must differ per user")
}
}
@@ -44,8 +44,8 @@ func TestWorkspaceName(t *testing.T) {
" ": "My workspace",
}
for in, want := range cases {
- if got := workspaceName(in); got != want {
- t.Fatalf("workspaceName(%q) = %q, want %q", in, got, want)
+ if got := workspaceDisplayName(in); got != want {
+ t.Fatalf("workspaceDisplayName(%q) = %q, want %q", in, got, want)
}
}
}
diff --git a/internal/storage/migration/constraints.go b/internal/storage/migration/constraints.go
index 5cb606e..0e0f748 100644
--- a/internal/storage/migration/constraints.go
+++ b/internal/storage/migration/constraints.go
@@ -104,7 +104,8 @@ func runConstraints(db *gorm.DB) {
END $$`)
db.Exec(`DO $$ BEGIN
- CREATE UNIQUE INDEX IF NOT EXISTS idx_workspace_form_slug ON forms (workspace_id, slug) WHERE workspace_id IS NOT NULL AND deleted_at IS NULL;
+ DROP INDEX IF EXISTS idx_workspace_form_slug;
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_workspace_form_name ON forms (workspace_id, name) WHERE workspace_id IS NOT NULL AND deleted_at IS NULL;
EXCEPTION WHEN others THEN NULL;
END $$`)
diff --git a/internal/storage/migration/identifiers.go b/internal/storage/migration/identifiers.go
new file mode 100644
index 0000000..c2be5dc
--- /dev/null
+++ b/internal/storage/migration/identifiers.go
@@ -0,0 +1,101 @@
+// Copyright (c) 2026 Jonas Kaninda.
+//
+// This file is part of Posta.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+//
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package migration
+
+import (
+ "fmt"
+
+ "github.com/jkaninda/logger"
+ "gorm.io/gorm"
+)
+
+// renameIdentifiers moves workspaces, forms, OAuth providers, templates and
+// stylesheets to one naming scheme before AutoMigrate sees the new models:
+// name is the identifier used in the API, display_name the label people
+// read. It runs before AutoMigrate because AutoMigrate would otherwise add
+// an empty display_name and build the unique index on name while name still
+// holds labels, which need not be unique. Each table is moved once; on a
+// fresh database there is nothing to move.
+func renameIdentifiers(db *gorm.DB) error {
+ return db.Transaction(func(tx *gorm.DB) error {
+ // name was the label and slug the identifier.
+ for _, table := range []string{"workspaces", "forms", "o_auth_providers"} {
+ if !columnExists(tx, table, "slug") {
+ continue
+ }
+ for _, stmt := range []string{
+ fmt.Sprintf("ALTER TABLE %s ADD COLUMN IF NOT EXISTS display_name text NOT NULL DEFAULT ''", table),
+ fmt.Sprintf("UPDATE %s SET display_name = name, name = slug", table),
+ fmt.Sprintf("ALTER TABLE %s DROP COLUMN slug", table),
+ } {
+ if err := tx.Exec(stmt).Error; err != nil {
+ return fmt.Errorf("rename %s identifiers: %w", table, err)
+ }
+ }
+ logger.Info("identifiers renamed: slug is now name, name is now display_name", "table", table)
+ }
+
+ // name was a free-form label that also identified the row. It becomes
+ // the label, and name becomes a slug of it; a second row with the
+ // same slug in a workspace gets its id appended. The unique index
+ // is dropped while names change and rebuilt by runConstraints.
+ for _, t := range []struct{ table, index, fallback string }{
+ {"templates", "idx_workspace_template", "template"},
+ {"style_sheets", "idx_workspace_stylesheet", "stylesheet"},
+ } {
+ if !tableExists(tx, t.table) || columnExists(tx, t.table, "display_name") {
+ continue
+ }
+ for _, stmt := range []string{
+ fmt.Sprintf("DROP INDEX IF EXISTS %s", t.index),
+ fmt.Sprintf("ALTER TABLE %s ADD COLUMN display_name text NOT NULL DEFAULT ''", t.table),
+ fmt.Sprintf("UPDATE %s SET display_name = name", t.table),
+ fmt.Sprintf(`
+ WITH s AS (
+ SELECT id, workspace_id,
+ COALESCE(NULLIF(trim(both '-' from regexp_replace(lower(name), '[^a-z0-9]+', '-', 'g')), ''), '%s') AS base
+ FROM %s
+ ), r AS (
+ SELECT id, base, row_number() OVER (PARTITION BY workspace_id, base ORDER BY id) AS n FROM s
+ )
+ UPDATE %s t SET name = CASE WHEN r.n = 1 THEN r.base ELSE r.base || '-' || t.id END
+ FROM r WHERE r.id = t.id`, t.fallback, t.table, t.table),
+ } {
+ if err := tx.Exec(stmt).Error; err != nil {
+ return fmt.Errorf("rename %s identifiers: %w", t.table, err)
+ }
+ }
+ logger.Info("identifiers renamed: name is now display_name, name is a slug of it", "table", t.table)
+ }
+ return nil
+ })
+}
+
+func tableExists(tx *gorm.DB, table string) bool {
+ var n int64
+ tx.Raw("SELECT count(*) FROM information_schema.tables WHERE table_schema = current_schema() AND table_name = ?", table).Scan(&n)
+ return n > 0
+}
+
+func columnExists(tx *gorm.DB, table, column string) bool {
+ var n int64
+ tx.Raw("SELECT count(*) FROM information_schema.columns WHERE table_schema = current_schema() AND table_name = ? AND column_name = ?", table, column).Scan(&n)
+ return n > 0
+}
diff --git a/internal/storage/migration/identifiers_test.go b/internal/storage/migration/identifiers_test.go
new file mode 100644
index 0000000..538f933
--- /dev/null
+++ b/internal/storage/migration/identifiers_test.go
@@ -0,0 +1,84 @@
+// Copyright (c) 2026 Jonas Kaninda.
+//
+// This file is part of Posta.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+//
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package migration
+
+import (
+ "os"
+ "testing"
+
+ "github.com/goposta/posta/internal/models"
+ "gorm.io/driver/postgres"
+ "gorm.io/gorm"
+ gl "gorm.io/gorm/logger"
+)
+
+// TestIdentifiersAfterMigration runs the full migration against a scratch
+// database, ideally a copy of one made before 0.18, and checks that every
+// workspace, form, OAuth provider, template and stylesheet ends with an
+// identifier for a name and a label for a display name. It is skipped
+// unless MIGRATION_SMOKE_DSN is set. Running it twice checks the move is
+// done once.
+func TestIdentifiersAfterMigration(t *testing.T) {
+ dsn := os.Getenv("MIGRATION_SMOKE_DSN")
+ if dsn == "" {
+ t.Skip("set MIGRATION_SMOKE_DSN to run")
+ }
+ db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{Logger: gl.Default.LogMode(gl.Silent)})
+ if err != nil {
+ t.Fatalf("open: %v", err)
+ }
+ for run := 1; run <= 2; run++ {
+ if err := Run(db); err != nil {
+ t.Fatalf("run %d: migrate: %v", run, err)
+ }
+ }
+
+ for _, table := range []string{"workspaces", "forms", "o_auth_providers"} {
+ if columnExists(db, table, "slug") {
+ t.Errorf("%s still has a slug column", table)
+ }
+ }
+ for _, table := range []string{"workspaces", "forms", "o_auth_providers", "templates", "style_sheets"} {
+ var rows []struct {
+ ID uint
+ Name string
+ DisplayName string
+ }
+ if err := db.Table(table).Select("id, name, display_name").Scan(&rows).Error; err != nil {
+ t.Fatalf("%s: %v", table, err)
+ }
+ for _, r := range rows {
+ if err := models.CheckIdentifier(r.Name); err != nil && table != "workspaces" {
+ t.Errorf("%s %d: %v", table, r.ID, err)
+ }
+ if r.DisplayName == "" {
+ t.Errorf("%s %d (%q) has no display name", table, r.ID, r.Name)
+ }
+ }
+ t.Logf("%s: %d rows", table, len(rows))
+ }
+ for _, idx := range []string{"idx_workspace_template", "idx_workspace_stylesheet", "idx_workspace_form_name", "idx_workspaces_name", "idx_o_auth_providers_name"} {
+ var n int64
+ db.Raw("SELECT count(*) FROM pg_indexes WHERE indexname = ?", idx).Scan(&n)
+ if n == 0 {
+ t.Errorf("unique index %s is missing", idx)
+ }
+ }
+}
diff --git a/internal/storage/migration/migration.go b/internal/storage/migration/migration.go
index 1882ab2..ab63036 100644
--- a/internal/storage/migration/migration.go
+++ b/internal/storage/migration/migration.go
@@ -29,6 +29,9 @@ import (
// Run executes all schema migrations and adds FK constraints.
func Run(db *gorm.DB) error {
+ if err := renameIdentifiers(db); err != nil {
+ return err
+ }
if err := db.AutoMigrate(
&models.User{},
&models.Plan{},
diff --git a/internal/storage/repositories/actor_cascade_test.go b/internal/storage/repositories/actor_cascade_test.go
index f35d6d5..68ce1e2 100644
--- a/internal/storage/repositories/actor_cascade_test.go
+++ b/internal/storage/repositories/actor_cascade_test.go
@@ -37,7 +37,7 @@ func seedActor(t *testing.T, tx *gorm.DB, email string) uint {
func seedWorkspace(t *testing.T, tx *gorm.DB, ownerID uint, slug string) uint {
t.Helper()
- ws := &models.Workspace{Name: "Acme", Slug: slug, OwnerID: ownerID}
+ ws := &models.Workspace{DisplayName: "Acme", Name: slug, OwnerID: ownerID}
if err := tx.Create(ws).Error; err != nil {
t.Fatalf("create workspace: %v", err)
}
@@ -57,7 +57,7 @@ func TestFormUpdateDoesNotCascadeIntoUsers(t *testing.T) {
repo := NewFormRepository(tx)
form := &models.Form{
- WorkspaceID: &wsID, Name: "Contact", Slug: "contact",
+ WorkspaceID: &wsID, DisplayName: "Contact", Name: "contact",
PublicKey: "form-cascade-key", Status: models.FormStatusActive,
LastEditedByID: &userID,
}
@@ -74,7 +74,7 @@ func TestFormUpdateDoesNotCascadeIntoUsers(t *testing.T) {
t.Fatal("expected LastEditedBy to be preloaded; this test proves nothing without it")
}
- loaded.Name = "Contact form"
+ loaded.DisplayName = "Contact form"
if err := repo.Update(loaded); err != nil {
t.Fatalf("update form must not cascade into users: %v", err)
}
@@ -96,7 +96,7 @@ func TestMessageUpdateDoesNotCascadeIntoUsers(t *testing.T) {
formRepo := NewFormRepository(tx)
form := &models.Form{
- WorkspaceID: &wsID, Name: "Contact", Slug: "contact",
+ WorkspaceID: &wsID, DisplayName: "Contact", Name: "contact",
PublicKey: "msg-cascade-key", Status: models.FormStatusActive,
}
if err := formRepo.Create(form); err != nil {
diff --git a/internal/storage/repositories/form_repo.go b/internal/storage/repositories/form_repo.go
index bf328eb..fa64e53 100644
--- a/internal/storage/repositories/form_repo.go
+++ b/internal/storage/repositories/form_repo.go
@@ -93,9 +93,9 @@ func (r *FormRepository) Delete(id uint) error {
return r.db.Delete(&models.Form{}, id).Error
}
-func (r *FormRepository) SlugExists(workspaceID uint, slug string, excludeID uint) bool {
+func (r *FormRepository) NameExists(workspaceID uint, name string, excludeID uint) bool {
var count int64
- q := r.db.Model(&models.Form{}).Where("workspace_id = ? AND slug = ?", workspaceID, slug)
+ q := r.db.Model(&models.Form{}).Where("workspace_id = ? AND name = ?", workspaceID, name)
if excludeID > 0 {
q = q.Where("id <> ?", excludeID)
}
diff --git a/internal/storage/repositories/form_rule_repo.go b/internal/storage/repositories/form_rule_repo.go
index 41083b4..252c9f3 100644
--- a/internal/storage/repositories/form_rule_repo.go
+++ b/internal/storage/repositories/form_rule_repo.go
@@ -135,10 +135,10 @@ type RuleUsingTeam struct {
func (r *FormRuleRepository) RulesUsingTeam(workspaceID, teamID uint) ([]RuleUsingTeam, error) {
var out []RuleUsingTeam
err := r.db.Table("form_rules").
- Select("form_rules.id, form_rules.name, form_rules.enabled, form_rules.form_id, forms.name AS form_name").
+ Select("form_rules.id, form_rules.name, form_rules.enabled, form_rules.form_id, forms.display_name AS form_name").
Joins("JOIN forms ON forms.id = form_rules.form_id AND forms.deleted_at IS NULL").
Where("form_rules.workspace_id = ? AND form_rules.actions @> ?::jsonb", workspaceID, fmt.Sprintf(`[{"team_id":%d}]`, teamID)).
- Order("LOWER(forms.name), form_rules.position").
+ Order("LOWER(forms.display_name), form_rules.position").
Scan(&out).Error
return out, err
}
diff --git a/internal/storage/repositories/message_repo_db_test.go b/internal/storage/repositories/message_repo_db_test.go
index 51fad4c..27cf040 100644
--- a/internal/storage/repositories/message_repo_db_test.go
+++ b/internal/storage/repositories/message_repo_db_test.go
@@ -77,11 +77,11 @@ func newFixture(t *testing.T, tx *gorm.DB, tag string) fixture {
if err := tx.Create(user).Error; err != nil {
t.Fatalf("user: %v", err)
}
- ws := &models.Workspace{Name: tag, Slug: tag + fmt.Sprint(time.Now().UnixNano()), OwnerID: user.ID}
+ ws := &models.Workspace{DisplayName: tag, Name: tag + fmt.Sprint(time.Now().UnixNano()), OwnerID: user.ID}
if err := tx.Create(ws).Error; err != nil {
t.Fatalf("workspace: %v", err)
}
- form := &models.Form{WorkspaceID: &ws.ID, Name: tag, Slug: tag, PublicKey: tag + fmt.Sprint(time.Now().UnixNano())}
+ form := &models.Form{WorkspaceID: &ws.ID, DisplayName: tag, Name: tag, PublicKey: tag + fmt.Sprint(time.Now().UnixNano())}
if err := tx.Create(form).Error; err != nil {
t.Fatalf("form: %v", err)
}
diff --git a/internal/storage/repositories/oauth_provider_repo.go b/internal/storage/repositories/oauth_provider_repo.go
index 066b2af..7067420 100644
--- a/internal/storage/repositories/oauth_provider_repo.go
+++ b/internal/storage/repositories/oauth_provider_repo.go
@@ -53,9 +53,9 @@ func (r *OAuthProviderRepository) FindByID(id uint) (*models.OAuthProvider, erro
return &p, nil
}
-func (r *OAuthProviderRepository) FindBySlug(slug string) (*models.OAuthProvider, error) {
+func (r *OAuthProviderRepository) FindByName(name string) (*models.OAuthProvider, error) {
var p models.OAuthProvider
- if err := r.db.Where("slug = ? AND enabled = true", slug).First(&p).Error; err != nil {
+ if err := r.db.Where("name = ? AND enabled = true", name).First(&p).Error; err != nil {
return nil, err
}
return &p, nil
@@ -65,7 +65,7 @@ func (r *OAuthProviderRepository) FindBySlug(slug string) (*models.OAuthProvider
func (r *OAuthProviderRepository) FindEnabled() ([]models.OAuthProvider, error) {
var providers []models.OAuthProvider
if err := r.db.Where("enabled = true AND hidden = false AND workspace_id IS NULL").
- Order("name ASC").Find(&providers).Error; err != nil {
+ Order("display_name ASC").Find(&providers).Error; err != nil {
return nil, err
}
return providers, nil
@@ -75,7 +75,7 @@ func (r *OAuthProviderRepository) FindEnabled() ([]models.OAuthProvider, error)
func (r *OAuthProviderRepository) FindEnabledForWorkspace(wsID uint) ([]models.OAuthProvider, error) {
var providers []models.OAuthProvider
if err := r.db.Where("enabled = true AND hidden = false AND (workspace_id IS NULL OR workspace_id = ?)", wsID).
- Order("name ASC").Find(&providers).Error; err != nil {
+ Order("display_name ASC").Find(&providers).Error; err != nil {
return nil, err
}
return providers, nil
diff --git a/internal/storage/repositories/stylesheet_repo.go b/internal/storage/repositories/stylesheet_repo.go
index a805170..95188a4 100644
--- a/internal/storage/repositories/stylesheet_repo.go
+++ b/internal/storage/repositories/stylesheet_repo.go
@@ -22,6 +22,7 @@ package repositories
import (
"github.com/goposta/posta/internal/models"
"gorm.io/gorm"
+ "gorm.io/gorm/clause"
)
type StyleSheetRepository struct {
@@ -90,9 +91,14 @@ func (r *StyleSheetRepository) FindByIDInScope(scope ResourceScope, id uint) (*m
return &ss, nil
}
+// FindByNameInScope finds a stylesheet by name or, for exports and HTML
+// files made before 0.18, when a stylesheet's name was its label, by
+// display name.
func (r *StyleSheetRepository) FindByNameInScope(scope ResourceScope, name string) (*models.StyleSheet, error) {
var ss models.StyleSheet
- if err := ApplyScope(r.db, scope).Where("name = ?", name).First(&ss).Error; err != nil {
+ if err := ApplyScope(r.db, scope).Where("name = ? OR display_name = ?", name, name).
+ Order(clause.OrderBy{Expression: clause.Expr{SQL: "name = ? DESC, id", Vars: []any{name}}}).
+ First(&ss).Error; err != nil {
return nil, err
}
return &ss, nil
diff --git a/internal/storage/repositories/template_attribution_test.go b/internal/storage/repositories/template_attribution_test.go
index 9d33b8e..ded2d88 100644
--- a/internal/storage/repositories/template_attribution_test.go
+++ b/internal/storage/repositories/template_attribution_test.go
@@ -37,7 +37,7 @@ func TestTemplateAttribution(t *testing.T) {
editor := createUser(t, tx, "[email protected]")
repo := &TemplateRepository{db: tx}
- tmpl := &models.Template{UserID: creator, Name: "Attr", LastEditedByID: &creator}
+ tmpl := &models.Template{UserID: creator, Name: "attr", LastEditedByID: &creator}
if err := repo.Create(tmpl); err != nil {
t.Fatalf("create template: %v", err)
}
@@ -71,7 +71,7 @@ func TestTemplateAttribution(t *testing.T) {
t.Fatalf("LastEditedBy = %+v, want id %d", got.LastEditedBy, editor)
}
- got.Name = "Attr Renamed"
+ got.DisplayName = "Attr Renamed"
if err := repo.Update(got); err != nil {
t.Fatalf("update preloaded template: %v", err)
}
@@ -79,8 +79,8 @@ func TestTemplateAttribution(t *testing.T) {
if err != nil {
t.Fatalf("find by id after update: %v", err)
}
- if reloaded.Name != "Attr Renamed" {
- t.Errorf("Name = %q, want %q", reloaded.Name, "Attr Renamed")
+ if reloaded.DisplayName != "Attr Renamed" {
+ t.Errorf("Name = %q, want %q", reloaded.DisplayName, "Attr Renamed")
}
if reloaded.LastEditedBy == nil || reloaded.LastEditedBy.ID != editor {
t.Errorf("LastEditedBy after update = %+v, want id %d", reloaded.LastEditedBy, editor)
diff --git a/internal/storage/repositories/template_repo.go b/internal/storage/repositories/template_repo.go
index 4060d14..aaa1757 100644
--- a/internal/storage/repositories/template_repo.go
+++ b/internal/storage/repositories/template_repo.go
@@ -101,7 +101,7 @@ func (r *TemplateRepository) FindByScope(scope ResourceScope, search string, lim
filter := func(q *gorm.DB) *gorm.DB {
q = ApplyScope(q, scope)
if search != "" {
- q = q.Where("name ILIKE ? OR description ILIKE ?", "%"+search+"%", "%"+search+"%")
+ q = q.Where("name ILIKE ? OR display_name ILIKE ? OR description ILIKE ?", "%"+search+"%", "%"+search+"%", "%"+search+"%")
}
return q
}
@@ -122,6 +122,17 @@ func (r *TemplateRepository) FindByScope(scope ResourceScope, search string, lim
return items, total, nil
}
+// FindByWorkspaceDisplayName finds a template by its label, for callers that
+// still send what a template's name was before 0.18. The oldest one wins
+// when two share a label.
+func (r *TemplateRepository) FindByWorkspaceDisplayName(workspaceID uint, displayName string) (*models.Template, error) {
+ var tmpl models.Template
+ if err := r.db.Where("workspace_id = ? AND display_name = ?", workspaceID, displayName).Order("id").First(&tmpl).Error; err != nil {
+ return nil, err
+ }
+ return &tmpl, nil
+}
+
func (r *TemplateRepository) FindByWorkspaceName(workspaceID uint, name string) (*models.Template, error) {
var tmpl models.Template
if err := r.db.Where("workspace_id = ? AND name = ?", workspaceID, name).First(&tmpl).Error; err != nil {
diff --git a/internal/storage/repositories/template_repo_test.go b/internal/storage/repositories/template_repo_test.go
index b34e452..edde776 100644
--- a/internal/storage/repositories/template_repo_test.go
+++ b/internal/storage/repositories/template_repo_test.go
@@ -41,7 +41,7 @@ func templateDB(t *testing.T) *gorm.DB {
func seedTemplateWorkspace(t *testing.T, tx *gorm.DB, slug string) (uint, uint) {
t.Helper()
userID := createUser(t, tx, slug+"@test.local")
- ws := &models.Workspace{Name: "Acme", Slug: slug, OwnerID: userID}
+ ws := &models.Workspace{DisplayName: "Acme", Name: slug, OwnerID: userID}
if err := tx.Create(ws).Error; err != nil {
t.Fatalf("workspace: %v", err)
}
@@ -58,7 +58,7 @@ func TestFindByScopePreloadsActiveVersion(t *testing.T) {
userID, wsID := seedTemplateWorkspace(t, tx, "tmpl-preload")
repo := &TemplateRepository{db: tx}
- tmpl := &models.Template{UserID: userID, WorkspaceID: &wsID, Name: "Welcome", DefaultLanguage: "en"}
+ tmpl := &models.Template{UserID: userID, WorkspaceID: &wsID, Name: "welcome", DefaultLanguage: "en"}
if err := repo.CreateWithVersions(tmpl, []ImportVersion{
{SampleData: "{}"},
{SampleData: "{}", IsActive: true},
@@ -93,7 +93,7 @@ func TestCreateWithVersionsIsAtomic(t *testing.T) {
// Two localizations for the same language violate idx_version_language, so
// the second version fails after the template and first version are written.
- tmpl := &models.Template{UserID: userID, WorkspaceID: &wsID, Name: "Broken", DefaultLanguage: "en"}
+ tmpl := &models.Template{UserID: userID, WorkspaceID: &wsID, Name: "broken", DefaultLanguage: "en"}
err := repo.CreateWithVersions(tmpl, []ImportVersion{
{Localizations: []ImportLocalization{
{Language: "en", SubjectTemplate: "Hi"},
@@ -133,7 +133,7 @@ func TestCreateAlwaysActivatesAVersion(t *testing.T) {
repo := &TemplateRepository{db: tx}
// No version is marked active, as an older export would be.
- tmpl := &models.Template{UserID: userID, WorkspaceID: &wsID, Name: "Fallback", DefaultLanguage: "en"}
+ tmpl := &models.Template{UserID: userID, WorkspaceID: &wsID, Name: "fallback", DefaultLanguage: "en"}
if err := repo.CreateWithVersions(tmpl, []ImportVersion{{SampleData: "{}"}, {SampleData: "{}"}}); err != nil {
t.Fatalf("create: %v", err)
}
@@ -163,7 +163,7 @@ func TestImportedVersionsAreNumberedInOrder(t *testing.T) {
userID, wsID := seedTemplateWorkspace(t, tx, "tmpl-order")
repo := &TemplateRepository{db: tx}
- tmpl := &models.Template{UserID: userID, WorkspaceID: &wsID, Name: "Ordered", DefaultLanguage: "en"}
+ tmpl := &models.Template{UserID: userID, WorkspaceID: &wsID, Name: "ordered", DefaultLanguage: "en"}
if err := repo.CreateWithVersions(tmpl, []ImportVersion{{}, {}, {IsActive: true}}); err != nil {
t.Fatalf("create: %v", err)
}
@@ -194,7 +194,7 @@ func TestBuilderJSONSurvivesCreate(t *testing.T) {
repo := &TemplateRepository{db: tx}
const doc = `{"pages":[{"component":"hero"}]}`
- tmpl := &models.Template{UserID: userID, WorkspaceID: &wsID, Name: "Designed", DefaultLanguage: "en"}
+ tmpl := &models.Template{UserID: userID, WorkspaceID: &wsID, Name: "designed", DefaultLanguage: "en"}
if err := repo.CreateWithVersions(tmpl, []ImportVersion{{
IsActive: true,
Localizations: []ImportLocalization{
@@ -223,7 +223,7 @@ func TestDuplicateNameIsDetectable(t *testing.T) {
userID, wsID := seedTemplateWorkspace(t, tx, "tmpl-dupe")
repo := &TemplateRepository{db: tx}
- first := &models.Template{UserID: userID, WorkspaceID: &wsID, Name: "Welcome", DefaultLanguage: "en"}
+ first := &models.Template{UserID: userID, WorkspaceID: &wsID, Name: "welcome", DefaultLanguage: "en"}
if err := repo.CreateWithVersions(first, []ImportVersion{{IsActive: true}}); err != nil {
t.Fatalf("first create: %v", err)
}
@@ -235,7 +235,7 @@ func TestDuplicateNameIsDetectable(t *testing.T) {
t.Skipf("cannot create the unique index: %v", err)
}
- second := &models.Template{UserID: userID, WorkspaceID: &wsID, Name: "Welcome", DefaultLanguage: "en"}
+ second := &models.Template{UserID: userID, WorkspaceID: &wsID, Name: "welcome", DefaultLanguage: "en"}
err := repo.CreateWithVersions(second, []ImportVersion{{IsActive: true}})
if err == nil {
t.Fatal("expected the duplicate name to be rejected")
@@ -256,7 +256,7 @@ func TestLanguagesForActiveVersions(t *testing.T) {
userID, wsID := seedTemplateWorkspace(t, tx, "tmpl-langs")
repo := &TemplateRepository{db: tx}
- tmpl := &models.Template{UserID: userID, WorkspaceID: &wsID, Name: "Multi", DefaultLanguage: "en"}
+ tmpl := &models.Template{UserID: userID, WorkspaceID: &wsID, Name: "multi", DefaultLanguage: "en"}
if err := repo.CreateWithVersions(tmpl, []ImportVersion{
{Localizations: []ImportLocalization{{Language: "ja", SubjectTemplate: "old"}}},
{IsActive: true, Localizations: []ImportLocalization{
@@ -267,7 +267,7 @@ func TestLanguagesForActiveVersions(t *testing.T) {
t.Fatalf("create: %v", err)
}
- empty := &models.Template{UserID: userID, WorkspaceID: &wsID, Name: "Empty", DefaultLanguage: "en"}
+ empty := &models.Template{UserID: userID, WorkspaceID: &wsID, Name: "empty", DefaultLanguage: "en"}
if err := repo.CreateWithVersions(empty, []ImportVersion{{IsActive: true}}); err != nil {
t.Fatalf("create empty: %v", err)
}
diff --git a/internal/storage/repositories/workspace_repo.go b/internal/storage/repositories/workspace_repo.go
index 7a5da09..b351ea4 100644
--- a/internal/storage/repositories/workspace_repo.go
+++ b/internal/storage/repositories/workspace_repo.go
@@ -63,9 +63,9 @@ func (r *WorkspaceRepository) FindByID(id uint) (*models.Workspace, error) {
return &ws, nil
}
-func (r *WorkspaceRepository) FindBySlug(slug string) (*models.Workspace, error) {
+func (r *WorkspaceRepository) FindByName(name string) (*models.Workspace, error) {
var ws models.Workspace
- if err := r.db.Where("slug = ?", slug).First(&ws).Error; err != nil {
+ if err := r.db.Where("name = ?", name).First(&ws).Error; err != nil {
return nil, err
}
return &ws, nil
@@ -98,7 +98,7 @@ func (r *WorkspaceRepository) FindAllFiltered(f AdminWorkspaceFilter, limit, off
apply := func(q *gorm.DB) *gorm.DB {
if s := strings.TrimSpace(f.Search); s != "" {
like := "%" + strings.ToLower(s) + "%"
- q = q.Where("LOWER(name) LIKE ? OR LOWER(slug) LIKE ?", like, like)
+ q = q.Where("LOWER(display_name) LIKE ? OR LOWER(name) LIKE ?", like, like)
}
if f.OwnerID != nil {
q = q.Where("owner_id = ?", *f.OwnerID)
@@ -145,10 +145,10 @@ func (r *WorkspaceRepository) FindSystem() (*models.Workspace, error) {
return &ws, nil
}
-// SlugExists reports whether slug is taken by a workspace other than excludeID.
-func (r *WorkspaceRepository) SlugExists(slug string, excludeID uint) bool {
+// NameExists reports whether name is taken by a workspace other than excludeID.
+func (r *WorkspaceRepository) NameExists(name string, excludeID uint) bool {
var count int64
- q := r.db.Model(&models.Workspace{}).Where("slug = ?", slug)
+ q := r.db.Model(&models.Workspace{}).Where("name = ?", name)
if excludeID > 0 {
q = q.Where("id <> ?", excludeID)
}
@@ -285,11 +285,11 @@ func (r *WorkspaceRepository) DeleteInvitation(id uint) error {
}
// CreateDefaultWorkspace creates a default workspace for a user during registration.
-func (r *WorkspaceRepository) CreateDefaultWorkspace(userID uint, name, slug string) (*models.Workspace, error) {
+func (r *WorkspaceRepository) CreateDefaultWorkspace(userID uint, displayName, name string) (*models.Workspace, error) {
ws := &models.Workspace{
- Name: name,
- Slug: slug,
- OwnerID: userID,
+ Name: name,
+ DisplayName: displayName,
+ OwnerID: userID,
}
if err := r.db.Create(ws).Error; err != nil {
return nil, err
diff --git a/internal/worker/message_handler.go b/internal/worker/message_handler.go
index 4eb2d1b..a5ce953 100644
--- a/internal/worker/message_handler.go
+++ b/internal/worker/message_handler.go
@@ -379,7 +379,7 @@ func (h *MessageProcessHandler) dispatch(msg *models.Message, form *models.Form,
Timestamp: time.Now().UTC().Format(time.RFC3339),
MessageID: msg.UUID,
FormID: form.UUID,
- FormName: form.Name,
+ FormName: form.DisplayName,
SenderEmail: msg.SenderEmail,
SenderName: msg.SenderName,
SenderPhone: msg.SenderPhone,
@@ -433,9 +433,9 @@ func (h *MessageProcessHandler) notify(msg *models.Message, form *models.Form, o
if form.IsCollect() {
noun = "response"
}
- subject := fmt.Sprintf("New %s on %s", noun, form.Name)
+ subject := fmt.Sprintf("New %s on %s", noun, form.DisplayName)
if msg.Status == models.MessageStatusFlagged {
- subject = fmt.Sprintf("Flagged %s on %s", noun, form.Name)
+ subject = fmt.Sprintf("Flagged %s on %s", noun, form.DisplayName)
}
// Answers to personal-data questions stay out of email: inboxes are
@@ -446,7 +446,7 @@ func (h *MessageProcessHandler) notify(msg *models.Message, form *models.Form, o
phone = "" // the Phone row in Fields shows it as hidden
}
data := map[string]any{
- "FormName": form.Name,
+ "FormName": form.DisplayName,
"Collect": form.IsCollect(),
"SenderPhone": phone,
"Fields": notifiableFields(msg, fields, mask),
@@ -525,8 +525,8 @@ func (h *MessageProcessHandler) addWorkspaceName(msg *models.Message, data map[s
return
}
if _, ok := data["WorkspaceName"]; !ok {
- if ws, err := h.workspaceRepo.FindByID(*msg.WorkspaceID); err == nil && ws.Name != "" {
- data["WorkspaceName"] = ws.Name
+ if ws, err := h.workspaceRepo.FindByID(*msg.WorkspaceID); err == nil && ws.DisplayName != "" {
+ data["WorkspaceName"] = ws.DisplayName
}
}
}
@@ -636,7 +636,7 @@ func (h *MessageProcessHandler) dispatchReply(msg *models.Message, form *models.
MessageID: msg.UUID,
ReplyID: reply.UUID,
FormID: form.UUID,
- FormName: form.Name,
+ FormName: form.DisplayName,
Kind: string(reply.Kind),
From: reply.FromAddr,
To: reply.ToAddr,
@@ -676,9 +676,9 @@ func (h *MessageProcessHandler) notifyReply(msg *models.Message, form *models.Fo
if h.notifier == nil || !h.notifier.IsConfigured() {
return nil
}
- subject := fmt.Sprintf("New reply on %s", form.Name)
+ subject := fmt.Sprintf("New reply on %s", form.DisplayName)
data := map[string]any{
- "FormName": form.Name,
+ "FormName": form.DisplayName,
"Reply": true,
"SenderMismatch": reply.SenderMismatch,
"Fields": []models.MessageField{
diff --git a/internal/worker/message_process_test.go b/internal/worker/message_process_test.go
index 7a43bea..9167da8 100644
--- a/internal/worker/message_process_test.go
+++ b/internal/worker/message_process_test.go
@@ -134,7 +134,7 @@ func processTask(t *testing.T) *asynq.Task {
}
func immediateForm() *models.Form {
- return &models.Form{ID: 1, Name: "Contact", NotifyEnabled: true, NotifyMode: models.NotifyModeImmediate, NotifyOnFlagged: true}
+ return &models.Form{ID: 1, DisplayName: "Contact", NotifyEnabled: true, NotifyMode: models.NotifyModeImmediate, NotifyOnFlagged: true}
}
func TestProcessTaskReturnsNotifyErrorSoAsynqRetries(t *testing.T) {
diff --git a/web/src/api/messages.ts b/web/src/api/messages.ts
index 9d02944..ffa84c6 100644
--- a/web/src/api/messages.ts
+++ b/web/src/api/messages.ts
@@ -31,8 +31,8 @@ function workspaceParam(): string {
}
export interface FormPayload {
+ display_name?: string
name?: string
- slug?: string
description?: string
status?: string
mode?: FormMode
diff --git a/web/src/api/types.ts b/web/src/api/types.ts
index 61f21bb..afea81f 100644
--- a/web/src/api/types.ts
+++ b/web/src/api/types.ts
@@ -183,6 +183,7 @@ export interface Template {
id: number
user_id: number
name: string
+ display_name: string
default_language: string
active_version_id?: number | null
description: string
@@ -196,12 +197,16 @@ export interface Template {
}
export interface TemplateInput {
- name: string
+ name?: string
+ display_name?: string
sample_data?: string
default_language?: string
description?: string
}
+/** A template being created or edited in the dashboard: both names are set. */
+export type TemplateDraft = TemplateInput & { name: string; display_name: string }
+
export interface TemplateExportLocalization {
language: string
subject_template: string
@@ -320,13 +325,15 @@ export interface StyleSheet {
id: number
user_id: number
name: string
+ display_name: string
css: string
created_at: string
updated_at?: string
}
export interface StyleSheetInput {
- name: string
+ name?: string
+ display_name?: string
css: string
}
@@ -444,8 +451,8 @@ export interface AdminDomainDetail extends AdminDomainRow {
export interface AdminWorkspaceRow {
id: number
+ display_name: string
name: string
- slug: string
system: boolean
owner_id: number
owner_name: string
@@ -967,8 +974,8 @@ export type WorkspaceRole = 'owner' | 'admin' | 'editor' | 'viewer'
export interface Workspace {
id: number
+ display_name: string
name: string
- slug: string
description: string
owner_id: number
role: WorkspaceRole
@@ -993,8 +1000,8 @@ export interface WorkspaceSettings {
}
export interface WorkspaceInput {
- name: string
- slug?: string
+ display_name?: string
+ name?: string
description?: string
/** Starter templates, stylesheet and languages. Omitted means true. */
seed_defaults?: boolean
@@ -1028,8 +1035,8 @@ export interface InviteMemberInput {
// OAuth
export interface OAuthProviderInfo {
id: number
- slug: string
name: string
+ display_name: string
type: 'google' | 'oidc'
}
@@ -1044,8 +1051,8 @@ export interface OAuthLinkedAccount {
export interface OAuthProviderAdmin {
id: number
+ display_name: string
name: string
- slug: string
type: string
issuer: string
scopes: string
@@ -1057,8 +1064,8 @@ export interface OAuthProviderAdmin {
}
export interface OAuthProviderInput {
+ display_name?: string
name: string
- slug: string
type: string
client_id: string
client_secret: string
@@ -1073,8 +1080,8 @@ export interface OAuthProviderInput {
}
export interface SSODiscovery {
- slug: string
name: string
+ display_name: string
type: string
}
@@ -1197,8 +1204,8 @@ export interface Plan {
export interface AdminWorkspace {
id: number
+ display_name: string
name: string
- slug: string
owner_id: number
plan_id: number | null
plan_name: string
@@ -1247,8 +1254,8 @@ export interface Form {
id: number
uuid: string
workspace_id?: number | null
+ display_name: string
name: string
- slug: string
description: string
public_key: string
status: FormStatus
diff --git a/web/src/api/workspaces.ts b/web/src/api/workspaces.ts
index 5ccd42e..68df7b5 100644
--- a/web/src/api/workspaces.ts
+++ b/web/src/api/workspaces.ts
@@ -22,7 +22,7 @@ export const workspaceApi = {
getCurrent() {
return api.get<ApiResponse<Workspace>>('/workspaces/current')
},
- update(data: { name?: string; description?: string }) {
+ update(data: { display_name?: string; description?: string }) {
return api.put<ApiResponse<Workspace>>('/workspaces/current', data)
},
delete() {
diff --git a/web/src/assets/styles.css b/web/src/assets/styles.css
index d992e5c..62163ac 100644
--- a/web/src/assets/styles.css
+++ b/web/src/assets/styles.css
@@ -331,8 +331,15 @@ option::checkmark {
font-size: 13px;
}
+/* An identifier field: a resource's name, as the API and URLs use it. */
+.form-input.mono {
+ font-family: 'JetBrains Mono', 'Fira Code', 'Cascadia Code', monospace;
+ font-size: 13px;
+}
+
.form-hint { font-size: 12px; color: var(--text-muted); margin-top: 4px; }
.form-error { font-size: 12px; color: var(--danger-500); margin-top: 4px; }
+.form-hint-warning { color: var(--warning-600); }
/* ─── Cards ─── */
.card {
diff --git a/web/src/components/TemplateModal.vue b/web/src/components/TemplateModal.vue
index e79dd96..23eed35 100644
--- a/web/src/components/TemplateModal.vue
+++ b/web/src/components/TemplateModal.vue
@@ -1,11 +1,12 @@
<script setup lang="ts">
import { languagesApi } from '@/api/languages';
-import { Language, Template, TemplateInput } from '@/api/types';
+import { Language, Template, TemplateDraft } from '@/api/types';
+import { IDENTIFIER_HINT, toIdentifier } from '@/composables/identifier';
import { useModalSafeClose } from '@/composables/useModalSafeClose';
-import { onMounted, ref } from 'vue';
+import { onMounted, ref, watch } from 'vue';
interface Props {
- form: TemplateInput
+ form: TemplateDraft
isVisible?: boolean
saving?: boolean
editing?: Template | null
@@ -38,6 +39,16 @@ const { watchClickStart, confirmClickEnd } = useModalSafeClose(() => {
onMounted(() => {
loadLanguages();
});
+
+// A new template's name follows its display name until edited by hand; an
+// existing one keeps its name, which callers send.
+const nameEdited = ref(false)
+watch(() => props.isVisible, (visible) => {
+ if (visible) nameEdited.value = !!props.editing
+})
+function syncName() {
+ if (!nameEdited.value) props.form.name = toIdentifier(props.form.display_name)
+}
</script>
<template>
@@ -48,9 +59,18 @@ onMounted(() => {
</div>
<div class="modal-body">
+ <div class="form-group">
+ <label class="form-label">Display name</label>
+ <input v-model="form.display_name" class="form-input" placeholder="e.g. Welcome Email" @input="syncName" />
+ </div>
<div class="form-group">
<label class="form-label">Name</label>
- <input v-model="form.name" class="form-input" placeholder="e.g. Welcome Email" />
+ <input v-model="form.name" class="form-input mono" placeholder="welcome-email" :title="IDENTIFIER_HINT"
+ @input="nameEdited = true" />
+ <span v-if="editing && form.name !== editing.name" class="form-hint form-hint-warning">
+ Callers that send with <code>{{ editing.name }}</code> stop finding this template.
+ </span>
+ <span v-else class="form-hint">What you send as <code>template</code> in the API. {{ IDENTIFIER_HINT }}</span>
</div>
<div class="form-group">
<label class="form-label">Description</label>
@@ -75,7 +95,7 @@ onMounted(() => {
<div class="modal-footer">
<button class="btn btn-secondary" @click="emit('close')">Cancel</button>
- <button class="btn btn-primary" :disabled="saving || !form.name.trim()" @click="emit('save')">
+ <button class="btn btn-primary" :disabled="saving || !form.display_name.trim() || !form.name.trim()" @click="emit('save')">
{{ saving ? "Saving..." : editing ? "Update" : "Create" }}
</button>
</div>
diff --git a/web/src/composables/identifier.ts b/web/src/composables/identifier.ts
new file mode 100644
index 0000000..f661734
--- /dev/null
+++ b/web/src/composables/identifier.ts
@@ -0,0 +1,22 @@
+// Workspaces, forms, OAuth providers, templates and stylesheets share one
+// naming scheme: name is the identifier the API and URLs use, like
+// "contact-form"; display_name is the label people read. These mirror the
+// server's rules in internal/models/identifier.go.
+
+export const MAX_IDENTIFIER_LENGTH = 63
+
+const IDENTIFIER = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
+
+/** Derives an identifier from a label: "Contact form" becomes "contact-form". */
+export function toIdentifier(label: string): string {
+ let v = label.trim().toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '')
+ if (v.length > MAX_IDENTIFIER_LENGTH) v = v.slice(0, MAX_IDENTIFIER_LENGTH).replace(/-+$/, '')
+ return v
+}
+
+/** Whether name can be an identifier. */
+export function isIdentifier(name: string): boolean {
+ return name.length <= MAX_IDENTIFIER_LENGTH && IDENTIFIER.test(name)
+}
+
+export const IDENTIFIER_HINT = 'Lowercase letters, digits and hyphens.'
diff --git a/web/src/layouts/DashboardLayout.vue b/web/src/layouts/DashboardLayout.vue
index 4688121..8facaf1 100644
--- a/web/src/layouts/DashboardLayout.vue
+++ b/web/src/layouts/DashboardLayout.vue
@@ -545,7 +545,7 @@ function getIcon(name: string): string {
<div class="ws-switcher-toggle" @click="wsSwitcherOpen = !wsSwitcherOpen">
<div class="ws-switcher-current">
<div v-if="isAdminConsole" class="ws-avatar ws-avatar-admin" v-html="getIcon('shield-admin')"></div>
- <div v-else class="ws-avatar">{{ wsStore.currentWorkspace?.name?.charAt(0)?.toUpperCase() || 'P' }}</div>
+ <div v-else class="ws-avatar">{{ wsStore.currentWorkspace?.display_name?.charAt(0)?.toUpperCase() || 'P' }}</div>
<span v-if="!sidebarCollapsed" class="ws-switcher-name">
{{ isAdminConsole ? 'Platform' : wsStore.contextLabel }}
<span v-if="isAdminConsole" class="ws-admin-badge">Admin</span>
@@ -559,8 +559,8 @@ function getIcon(name: string): string {
<div v-if="wsSwitcherOpen" class="ws-switcher-dropdown">
<div v-for="ws in wsStore.workspaces" :key="ws.id" class="ws-switcher-option"
:class="{ active: !isAdminConsole && wsStore.currentWorkspaceId === ws.id }" @click="switchContext(ws.id)">
- <div class="ws-avatar-sm">{{ ws.name.charAt(0).toUpperCase() }}</div>
- <span>{{ ws.name }}</span>
+ <div class="ws-avatar-sm">{{ ws.display_name.charAt(0).toUpperCase() }}</div>
+ <span>{{ ws.display_name }}</span>
<span class="ws-role-badge" :class="{ 'ws-role-badge--system': ws.system }">{{ ws.system ? 'system' : ws.role }}</span>
</div>
<div class="ws-switcher-divider"></div>
@@ -808,7 +808,7 @@ function getIcon(name: string): string {
<div style="display: flex; align-items: center; gap: 8px; overflow: hidden;">
<span v-if="isAdminConsole" class="ws-avatar ws-avatar-admin" v-html="getIcon('shield-admin')"></span>
<span v-else class="ws-avatar">
- {{ wsStore.currentWorkspace?.name?.charAt(0)?.toUpperCase() || 'P' }}
+ {{ wsStore.currentWorkspace?.display_name?.charAt(0)?.toUpperCase() || 'P' }}
</span>
<span class="ws-name">
{{ isAdminConsole ? 'Platform' : wsStore.contextLabel }}
@@ -826,9 +826,9 @@ function getIcon(name: string): string {
<div v-for="ws in wsStore.workspaces" :key="ws.id" class="ws-option"
:class="{ active: !isAdminConsole && wsStore.currentWorkspaceId === ws.id }"
@click="switchContext(ws.id); mobileOpen = false">
- <span class="ws-avatar">{{ ws.name?.charAt(0)?.toUpperCase() }}</span>
+ <span class="ws-avatar">{{ ws.display_name?.charAt(0)?.toUpperCase() }}</span>
<div style="display: flex; flex-direction: column;">
- <span>{{ ws.name }}</span>
+ <span>{{ ws.display_name }}</span>
<small style="font-size: 0.75rem; opacity: 0.7;">{{ ws.system ? 'system' : ws.role }}</small>
</div>
</div>
diff --git a/web/src/stores/workspace.ts b/web/src/stores/workspace.ts
index b49d20d..783df64 100644
--- a/web/src/stores/workspace.ts
+++ b/web/src/stores/workspace.ts
@@ -37,7 +37,7 @@ export const useWorkspaceStore = defineStore('workspace', () => {
const currentWorkspaceIsSystem = computed(() => currentWorkspace.value?.system ?? false)
const hasWorkspace = computed(() => ownWorkspaces.value.length > 0)
- const contextLabel = computed(() => currentWorkspace.value?.name ?? 'No workspace')
+ const contextLabel = computed(() => currentWorkspace.value?.display_name ?? 'No workspace')
function setWorkspace(wsId: number | null) {
currentWorkspaceId.value = wsId
diff --git a/web/src/views/admin/LdapDirectories.vue b/web/src/views/admin/LdapDirectories.vue
index b28198d..2462c17 100644
--- a/web/src/views/admin/LdapDirectories.vue
+++ b/web/src/views/admin/LdapDirectories.vue
@@ -22,7 +22,7 @@ const directories = ref<LDAPDirectory[]>([])
const workspaces = ref<AdminWorkspaceRow[]>([])
const tests = ref<Record<number, LDAPTestResult | 'running'>>({})
-const workspaceName = computed(() => Object.fromEntries(workspaces.value.map((w) => [w.id, w.name])))
+const workspaceName = computed(() => Object.fromEntries(workspaces.value.map((w) => [w.id, w.display_name])))
async function load() {
loading.value = true
@@ -319,7 +319,7 @@ onMounted(async () => {
</label>
<select v-model="mappingDraft(dir.id).workspace_id" class="form-select" aria-label="Workspace">
<option value="">No workspace</option>
- <option v-for="w in workspaces" :key="w.id" :value="w.id">{{ w.name }}</option>
+ <option v-for="w in workspaces" :key="w.id" :value="w.id">{{ w.display_name }}</option>
</select>
<select
v-model="mappingDraft(dir.id).workspace_role"
diff --git a/web/src/views/admin/OAuthProviders.vue b/web/src/views/admin/OAuthProviders.vue
index e13f083..b491893 100644
--- a/web/src/views/admin/OAuthProviders.vue
+++ b/web/src/views/admin/OAuthProviders.vue
@@ -6,6 +6,7 @@ import { useNotificationStore } from '../../stores/notification'
import { useConfirm } from '../../composables/useConfirm'
import { useLicenseStore } from '../../stores/license'
import { ENTERPRISE_URL } from '../../api/license'
+import { IDENTIFIER_HINT, toIdentifier } from '../../composables/identifier'
const notify = useNotificationStore()
const { confirm } = useConfirm()
@@ -20,8 +21,15 @@ const loading = ref(true)
const showCreateModal = ref(false)
const creating = ref(false)
+const emptyForm = () => ({
+ display_name: '', name: '', type: 'oidc',
+ client_id: '', client_secret: '', issuer: '',
+ auth_url: '', token_url: '', userinfo_url: '',
+ scopes: 'openid email profile',
+ auto_register: true, hidden: false, allowed_domains: '',
+})
const form = ref({
- name: '', slug: '', type: 'oidc',
+ display_name: '', name: '', type: 'oidc',
client_id: '', client_secret: '', issuer: '',
auth_url: '', token_url: '', userinfo_url: '',
scopes: 'openid email profile',
@@ -33,7 +41,7 @@ const showEditModal = ref(false)
const editing = ref(false)
const editingProvider = ref<OAuthProviderAdmin | null>(null)
const editForm = ref({
- name: '', client_id: '', client_secret: '', issuer: '',
+ display_name: '', client_id: '', client_secret: '', issuer: '',
auth_url: '', token_url: '', userinfo_url: '',
scopes: '', auto_register: true, hidden: false, allowed_domains: '',
})
@@ -50,18 +58,21 @@ async function fetchProviders() {
}
}
-function autoSlug() {
- form.value.slug = form.value.name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')
+// The name follows the display name until it is edited by hand.
+const nameEdited = ref(false)
+function syncName() {
+ if (!nameEdited.value) form.value.name = toIdentifier(form.value.display_name)
}
async function createProvider() {
- if (!form.value.name || !form.value.slug || !form.value.client_id || !form.value.client_secret) return
+ if (!form.value.display_name || !form.value.name || !form.value.client_id || !form.value.client_secret) return
creating.value = true
try {
await oauthApi.adminCreate(form.value)
notify.success('Provider created')
showCreateModal.value = false
- form.value = { name: '', slug: '', type: 'oidc', client_id: '', client_secret: '', issuer: '', auth_url: '', token_url: '', userinfo_url: '', scopes: 'openid email profile', auto_register: true, hidden: false, allowed_domains: '' }
+ form.value = emptyForm()
+ nameEdited.value = false
await fetchProviders()
} catch (err: any) {
notify.error(err.response?.data?.error?.message || 'Failed to create provider')
@@ -73,7 +84,7 @@ async function createProvider() {
function openEdit(p: OAuthProviderAdmin) {
editingProvider.value = p
editForm.value = {
- name: p.name,
+ display_name: p.display_name,
client_id: '',
client_secret: '',
issuer: p.issuer || '',
@@ -93,7 +104,7 @@ async function updateProvider() {
editing.value = true
try {
const data: Record<string, any> = {}
- if (editForm.value.name) data.name = editForm.value.name
+ if (editForm.value.display_name) data.display_name = editForm.value.display_name
if (editForm.value.client_id) data.client_id = editForm.value.client_id
if (editForm.value.client_secret) data.client_secret = editForm.value.client_secret
if (editForm.value.issuer) data.issuer = editForm.value.issuer
@@ -123,7 +134,7 @@ async function toggleEnabled(p: OAuthProviderAdmin) {
}
async function deleteProvider(p: OAuthProviderAdmin) {
- const ok = await confirm({ title: 'Delete Provider', message: `Delete "${p.name}"? Users won't be able to sign in with this provider.`, confirmText: 'Delete', variant: 'danger' })
+ const ok = await confirm({ title: 'Delete Provider', message: `Delete "${p.display_name}"? Users won't be able to sign in with this provider.`, confirmText: 'Delete', variant: 'danger' })
if (!ok) return
try {
await oauthApi.adminDelete(p.id)
@@ -180,8 +191,8 @@ onMounted(() => {
<table>
<thead>
<tr>
+ <th>Display name</th>
<th>Name</th>
- <th>Slug</th>
<th>Type</th>
<th>Status</th>
<th>Visibility</th>
@@ -192,8 +203,8 @@ onMounted(() => {
</thead>
<tbody>
<tr v-for="p in providers" :key="p.id">
- <td style="font-weight: 500;">{{ p.name }}</td>
- <td><code>{{ p.slug }}</code></td>
+ <td style="font-weight: 500;">{{ p.display_name }}</td>
+ <td><code>{{ p.name }}</code></td>
<td><span class="badge badge-neutral">{{ p.type }}</span></td>
<td><span class="badge" :class="p.enabled ? 'badge-primary' : 'badge-neutral'">{{ p.enabled ? 'enabled' : 'disabled' }}</span></td>
<td><span class="badge" :class="p.hidden ? 'badge-neutral' : 'badge-primary'">{{ p.hidden ? 'hidden' : 'visible' }}</span></td>
@@ -222,12 +233,15 @@ onMounted(() => {
<div class="modal-body">
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
<div class="form-group">
- <label class="form-label">Name</label>
- <input v-model="form.name" class="form-input" placeholder="Google" required @input="autoSlug" />
+ <label class="form-label">Display name</label>
+ <input v-model="form.display_name" class="form-input" placeholder="Google" required @input="syncName" />
+ <span class="form-hint">Shown on the sign-in button.</span>
</div>
<div class="form-group">
- <label class="form-label">Slug</label>
- <input v-model="form.slug" class="form-input" placeholder="google" required />
+ <label class="form-label">Name</label>
+ <input v-model="form.name" class="form-input mono" placeholder="google" required pattern="[a-z0-9]+(-[a-z0-9]+)*"
+ :title="IDENTIFIER_HINT" @input="nameEdited = true" />
+ <span class="form-hint">In the sign-in URLs. It cannot change later.</span>
</div>
</div>
<div class="form-group">
@@ -285,12 +299,13 @@ onMounted(() => {
<!-- Edit Modal -->
<div v-if="showEditModal && editingProvider" class="modal-overlay" @click.self="showEditModal = false">
<div class="modal" style="max-width: 560px;">
- <div class="modal-header"><h3>Edit {{ editingProvider.name }}</h3></div>
+ <div class="modal-header"><h3>Edit {{ editingProvider.display_name }}</h3></div>
<form @submit.prevent="updateProvider">
<div class="modal-body">
<div class="form-group">
- <label class="form-label">Name</label>
- <input v-model="editForm.name" class="form-input" required />
+ <label class="form-label">Display name</label>
+ <input v-model="editForm.display_name" class="form-input" required />
+ <span class="form-hint">Its name, <code>{{ editingProvider.name }}</code>, is in the sign-in URLs and stays the same.</span>
</div>
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
<div class="form-group">
diff --git a/web/src/views/admin/UserDetail.vue b/web/src/views/admin/UserDetail.vue
index 490e716..4391dea 100644
--- a/web/src/views/admin/UserDetail.vue
+++ b/web/src/views/admin/UserDetail.vue
@@ -198,7 +198,7 @@ async function handleChangePlan(workspace: AdminWorkspace, planId: number | null
const plan = plans.value.find(p => p.id === planId)
workspace.plan_id = planId
workspace.plan_name = plan?.name || ''
- notification.success(`Plan updated for workspace "${workspace.name}".`)
+ notification.success(`Plan updated for workspace "${workspace.display_name}".`)
}
} catch {
notification.error('Failed to update workspace plan.')
@@ -472,16 +472,16 @@ function formatDate(date: string) {
<table v-else class="table">
<thead>
<tr>
+ <th>Display name</th>
<th>Name</th>
- <th>Slug</th>
<th>Plan</th>
<th>Created</th>
</tr>
</thead>
<tbody>
<tr v-for="ws in workspaces" :key="ws.id">
- <td><router-link :to="`/admin/workspaces/${ws.id}`">{{ ws.name }}</router-link></td>
- <td><code>{{ ws.slug }}</code></td>
+ <td><router-link :to="`/admin/workspaces/${ws.id}`">{{ ws.display_name }}</router-link></td>
+ <td><code>{{ ws.name }}</code></td>
<td>
<select
class="form-select form-select-sm"
diff --git a/web/src/views/admin/WorkspaceDetail.vue b/web/src/views/admin/WorkspaceDetail.vue
index 25034c9..ce279b0 100644
--- a/web/src/views/admin/WorkspaceDetail.vue
+++ b/web/src/views/admin/WorkspaceDetail.vue
@@ -30,8 +30,8 @@ async function toggleHostedForms() {
const ok = await confirm({
title: enable ? "Turn hosted form pages back on?" : "Take hosted form pages offline?",
message: enable
- ? `The share links of "${ws.name}" forms work again.`
- : `Every share link of "${ws.name}" forms answers "not found" at once, and forms can no longer be loaded or submitted from this Posta's domain. Forms embedded on the workspace's own websites, its submissions and its data are not affected. Use this when hosted forms are abused, for example for phishing.`,
+ ? `The share links of "${ws.display_name}" forms work again.`
+ : `Every share link of "${ws.display_name}" forms answers "not found" at once, and forms can no longer be loaded or submitted from this Posta's domain. Forms embedded on the workspace's own websites, its submissions and its data are not affected. Use this when hosted forms are abused, for example for phishing.`,
confirmText: enable ? "Turn back on" : "Take offline",
variant: enable ? "info" : "danger",
});
@@ -81,7 +81,7 @@ async function changePlan(event: Event) {
await plansApi.assignToWorkspace(ws.id, planId);
ws.plan_id = planId;
ws.plan_name = plans.value.find((p) => p.id === planId)?.name || "";
- notify.success(`Plan updated for workspace "${ws.name}"`);
+ notify.success(`Plan updated for workspace "${ws.display_name}"`);
} catch (e: any) {
notify.error(apiMessage(e, "Failed to update the workspace plan"));
(event.target as HTMLSelectElement).value = String(ws.plan_id ?? "");
@@ -129,13 +129,13 @@ onMounted(load);
<div class="page-header">
<div>
<h1>
- {{ workspace?.name || "Workspace" }}
+ {{ workspace?.display_name || "Workspace" }}
<span v-if="workspace?.system" class="badge badge-info" style="margin-left: 8px; vertical-align: middle">
system
</span>
</h1>
<p v-if="workspace" class="page-subtitle">
- <code>{{ workspace.slug }}</code> · created {{ formatDate(workspace.created_at) }}
+ <code>{{ workspace.name }}</code> · created {{ formatDate(workspace.created_at) }}
</p>
</div>
<div class="header-actions">
diff --git a/web/src/views/admin/Workspaces.vue b/web/src/views/admin/Workspaces.vue
index 4546c05..9fe53c4 100644
--- a/web/src/views/admin/Workspaces.vue
+++ b/web/src/views/admin/Workspaces.vue
@@ -69,7 +69,7 @@ onMounted(async () => {
<input
v-model="search"
class="form-input search"
- placeholder="Search by name or slug…"
+ placeholder="Search by display name or name…"
@input="onSearchInput"
/>
<select v-model.number="planFilter" class="form-select plan-filter" @change="goToPage(0)">
@@ -94,8 +94,8 @@ onMounted(async () => {
<table>
<thead>
<tr>
+ <th>Display name</th>
<th>Name</th>
- <th>Slug</th>
<th>Owner</th>
<th>Plan</th>
<th>Members</th>
@@ -110,10 +110,10 @@ onMounted(async () => {
@click="router.push(`/admin/workspaces/${ws.id}`)"
>
<td>
- {{ ws.name }}
+ {{ ws.display_name }}
<span v-if="ws.system" class="badge badge-info" style="margin-left: 6px">system</span>
</td>
- <td class="mono">{{ ws.slug }}</td>
+ <td class="mono">{{ ws.name }}</td>
<td class="muted-cell">{{ ws.owner_email || `#${ws.owner_id}` }}</td>
<td>
<span v-if="ws.plan_name" class="badge badge-neutral">{{ ws.plan_name }}</span>
diff --git a/web/src/views/auth/Login.vue b/web/src/views/auth/Login.vue
index 018aa12..cde93db 100644
--- a/web/src/views/auth/Login.vue
+++ b/web/src/views/auth/Login.vue
@@ -77,9 +77,9 @@ watch(twoFactorCode, (val) => {
if (digits.length === 6 && !loading.value) handleLogin()
})
-function oauthLogin(slug: string) {
+function oauthLogin(provider: string) {
// Full page navigation to the backend OAuth authorize endpoint
- window.location.href = `/api/v1/auth/oauth/${slug}/authorize`
+ window.location.href = `/api/v1/auth/oauth/${provider}/authorize`
}
const ssoChecking = ref(false)
@@ -99,9 +99,9 @@ async function submitSSO() {
ssoChecking.value = true
try {
const res = await oauthApi.discoverSSO(email.value)
- const slug = res.data.data?.slug
- if (slug) {
- oauthLogin(slug)
+ const provider = res.data.data?.name
+ if (provider) {
+ oauthLogin(provider)
return
}
notification.info('No SSO configured for this email.')
@@ -283,13 +283,13 @@ function resetLogin() {
<div class="oauth-buttons">
<button
v-for="p in oauthProviders"
- :key="p.slug"
+ :key="p.name"
class="btn btn-secondary auth-btn oauth-btn"
- @click="oauthLogin(p.slug)"
+ @click="oauthLogin(p.name)"
>
<svg v-if="p.type === 'google'" width="18" height="18" viewBox="0 0 24 24"><path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92a5.06 5.06 0 01-2.2 3.32v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.1z" fill="#4285F4"/><path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853"/><path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18A10.97 10.97 0 001 12c0 1.77.42 3.45 1.18 4.93l3.66-2.84z" fill="#FBBC05"/><path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335"/></svg>
<svg v-else width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0110 0v4"/></svg>
- Sign in with {{ p.name }}
+ Sign in with {{ p.display_name }}
</button>
</div>
</div>
diff --git a/web/src/views/auth/Profile.vue b/web/src/views/auth/Profile.vue
index f9bf54b..b0681a0 100644
--- a/web/src/views/auth/Profile.vue
+++ b/web/src/views/auth/Profile.vue
@@ -33,7 +33,7 @@ const unlinkingAccount = ref<number | null>(null)
const availableProviders = computed(() => {
const linkedNames = new Set(linkedAccounts.value.map(a => a.provider_name))
- return oauthProviders.value.filter(p => !linkedNames.has(p.name))
+ return oauthProviders.value.filter(p => !linkedNames.has(p.display_name))
})
function formatLimit(val: number): string {
@@ -114,8 +114,8 @@ async function unlinkOAuthAccount(account: OAuthLinkedAccount) {
}
}
-function linkOAuthProvider(slug: string) {
- window.location.href = `/api/v1/auth/oauth/${slug}/authorize`
+function linkOAuthProvider(provider: string) {
+ window.location.href = `/api/v1/auth/oauth/${provider}/authorize`
}
// Password
@@ -557,11 +557,11 @@ onMounted(() => { loadSessions() })
<div style="display: flex; gap: 8px; flex-wrap: wrap">
<button
v-for="provider in availableProviders"
- :key="provider.slug"
+ :key="provider.name"
class="btn btn-secondary"
- @click="linkOAuthProvider(provider.slug)"
+ @click="linkOAuthProvider(provider.name)"
>
- Link {{ provider.name }}
+ Link {{ provider.display_name }}
</button>
</div>
</div>
diff --git a/web/src/views/emails/EmailPreview.vue b/web/src/views/emails/EmailPreview.vue
index e0346f0..0491efb 100644
--- a/web/src/views/emails/EmailPreview.vue
+++ b/web/src/views/emails/EmailPreview.vue
@@ -118,7 +118,7 @@ async function renderPreview() {
<label class="form-label">Template</label>
<select v-model="selectedTemplate" class="form-select">
<option value="" disabled>Select a template</option>
- <option v-for="t in templates" :key="t.id" :value="t.name">{{ t.name }}</option>
+ <option v-for="t in templates" :key="t.id" :value="t.name">{{ t.display_name }}</option>
</select>
</div>
<div class="form-group">
diff --git a/web/src/views/forms/FormDetail.vue b/web/src/views/forms/FormDetail.vue
index 015f9d9..37f2b39 100644
--- a/web/src/views/forms/FormDetail.vue
+++ b/web/src/views/forms/FormDetail.vue
@@ -1,5 +1,6 @@
<script setup lang="ts">
import { computed, onMounted, ref, watch } from "vue";
+import { IDENTIFIER_HINT } from "../../composables/identifier";
import { useRoute, useRouter } from "vue-router";
import { formsApi } from "../../api/messages";
import { useNotificationStore } from "../../stores/notification";
@@ -112,6 +113,7 @@ async function save() {
saving.value = true;
try {
const res = await formsApi.update(id, {
+ display_name: form.value.display_name,
name: form.value.name,
description: form.value.description,
status: form.value.status,
@@ -254,7 +256,7 @@ onMounted(load);
<template>
<div>
<div class="page-header">
- <h1>{{ form?.name || "Form" }}</h1>
+ <h1>{{ form?.display_name || "Form" }}</h1>
<div style="display: flex; gap: 8px">
<router-link
v-if="form && form.mode !== 'collect'"
@@ -307,9 +309,16 @@ onMounted(load);
<div v-show="tab === 'setup'" class="card" style="margin-bottom: 20px">
<div class="card-header"><h2>Setup</h2></div>
<div class="card-body">
- <div class="form-group">
- <label class="form-label">Name</label>
- <input v-model="form.name" class="form-input" />
+ <div class="name-row">
+ <div class="form-group">
+ <label class="form-label">Display name</label>
+ <input v-model="form.display_name" class="form-input" />
+ </div>
+ <div class="form-group">
+ <label class="form-label">Name</label>
+ <input v-model="form.name" class="form-input mono" pattern="[a-z0-9]+(-[a-z0-9]+)*" :title="IDENTIFIER_HINT" />
+ <span class="form-hint">Identifies the form in the API. The embed and share links use its key, so they keep working if it changes.</span>
+ </div>
</div>
<div class="form-group">
<label class="form-label">Description</label>
@@ -701,6 +710,12 @@ onMounted(load);
</template>
<style scoped>
+.name-row {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
+ gap: 0 16px;
+}
+
.mode-choice {
border: 0;
padding: 0;
diff --git a/web/src/views/forms/FormFields.vue b/web/src/views/forms/FormFields.vue
index 2e93e8b..060485c 100644
--- a/web/src/views/forms/FormFields.vue
+++ b/web/src/views/forms/FormFields.vue
@@ -457,7 +457,7 @@ function renderPreview() {
}
watch(
- () => [drafts.value, props.form.name, props.form.description, props.form.appearance],
+ () => [drafts.value, props.form.display_name, props.form.description, props.form.appearance],
renderPreview,
{ deep: true },
);
@@ -828,7 +828,7 @@ onBeforeUnmount(() => {
The preview needs the widget script at <code>/widget/v1/posta-form.js</code>, which could not be loaded.
</p>
<p v-else-if="previewState === 'loading'" class="muted" style="font-size: 13px">Loading preview…</p>
- <div ref="previewEl" :data-title="form.name" :data-description="form.description || null"></div>
+ <div ref="previewEl" :data-title="form.display_name" :data-description="form.description || null"></div>
</aside>
</div>
</template>
diff --git a/web/src/views/forms/Forms.vue b/web/src/views/forms/Forms.vue
index dbbe466..628da3b 100644
--- a/web/src/views/forms/Forms.vue
+++ b/web/src/views/forms/Forms.vue
@@ -1,5 +1,6 @@
<script setup lang="ts">
import { ref } from "vue";
+import { IDENTIFIER_HINT, toIdentifier } from "../../composables/identifier";
import { useRouter } from "vue-router";
import { formsApi } from "../../api/messages";
import { useNotificationStore } from "../../stores/notification";
@@ -16,7 +17,10 @@ const forms = ref<Form[]>([]);
const showCreate = ref(false);
const creating = ref(false);
+const newDisplayName = ref("");
const newName = ref("");
+// The name follows the display name until it is edited by hand.
+const nameEdited = ref(false);
const newOrigins = ref("");
const newNotify = ref("");
const newMode = ref<FormMode>("inbox");
@@ -39,8 +43,14 @@ const { pageable, goToPage } = usePagination(async (page) => {
}
});
+function syncName() {
+ if (!nameEdited.value) newName.value = toIdentifier(newDisplayName.value);
+}
+
function openCreate() {
+ newDisplayName.value = "";
newName.value = "";
+ nameEdited.value = false;
newOrigins.value = "";
newNotify.value = "";
newMode.value = "inbox";
@@ -48,11 +58,12 @@ function openCreate() {
}
async function createForm() {
- if (!newName.value.trim()) return;
+ if (!newDisplayName.value.trim()) return;
creating.value = true;
try {
const res = await formsApi.create({
- name: newName.value.trim(),
+ display_name: newDisplayName.value.trim(),
+ name: newName.value.trim() || undefined,
mode: newMode.value,
allowed_origins: splitList(newOrigins.value),
notify_emails: splitList(newNotify.value),
@@ -142,7 +153,7 @@ function formatDate(date: string | null | undefined) {
style="cursor: pointer"
@click="router.push(`/forms/${form.id}`)"
>
- <td>{{ form.name }}</td>
+ <td>{{ form.display_name }}</td>
<td><code style="font-size: 12px">{{ form.public_key }}</code></td>
<td><span :class="statusBadgeClass(form.status)">{{ form.status }}</span></td>
<td>{{ form.mode === "collect" ? "Responses" : "Messages" }}</td>
@@ -163,9 +174,15 @@ function formatDate(date: string | null | undefined) {
<h3>New form</h3>
</div>
<div class="modal-body">
+ <div class="form-group">
+ <label class="form-label">Display name</label>
+ <input v-model="newDisplayName" class="form-input" placeholder="Contact form" @input="syncName" />
+ </div>
<div class="form-group">
<label class="form-label">Name</label>
- <input v-model="newName" class="form-input" placeholder="Contact form" />
+ <input v-model="newName" class="form-input mono" placeholder="contact-form" :title="IDENTIFIER_HINT"
+ @input="nameEdited = true" />
+ <span class="form-hint">Identifies the form in the API. {{ IDENTIFIER_HINT }}</span>
</div>
<div class="form-group">
<label class="form-label">Submissions are</label>
@@ -201,7 +218,7 @@ function formatDate(date: string | null | undefined) {
</div>
<div class="modal-footer">
<button class="btn btn-secondary" @click="showCreate = false">Cancel</button>
- <button class="btn btn-primary" :disabled="creating || !newName.trim()" @click="createForm">
+ <button class="btn btn-primary" :disabled="creating || !newDisplayName.trim()" @click="createForm">
{{ creating ? "Creating..." : "Create form" }}
</button>
</div>
diff --git a/web/src/views/messages/MessageDetail.vue b/web/src/views/messages/MessageDetail.vue
index 5fd9607..1e93feb 100644
--- a/web/src/views/messages/MessageDetail.vue
+++ b/web/src/views/messages/MessageDetail.vue
@@ -371,7 +371,7 @@ onBeforeUnmount(() => {
<td style="font-weight: 600">Form</td>
<td>
<router-link v-if="message.form" :to="`/forms/${message.form.id}`">
- {{ message.form.name }}
+ {{ message.form.display_name }}
</router-link>
<span v-else>-</span>
</td>
diff --git a/web/src/views/messages/MessageFilters.vue b/web/src/views/messages/MessageFilters.vue
index ac77255..35010f6 100644
--- a/web/src/views/messages/MessageFilters.vue
+++ b/web/src/views/messages/MessageFilters.vue
@@ -123,7 +123,7 @@ async function remove(filter: MessageFilterRule) {
function formName(formId: number | null | undefined) {
if (!formId) return "All forms";
- return forms.value.find((f) => f.id === formId)?.name || `Form ${formId}`;
+ return forms.value.find((f) => f.id === formId)?.display_name || `Form ${formId}`;
}
function actionBadgeClass(action: string) {
@@ -233,7 +233,7 @@ load();
<label class="form-label">Applies to</label>
<select v-model.number="draft.form_id" class="form-select">
<option :value="0">All forms</option>
- <option v-for="f in forms" :key="f.id" :value="f.id">{{ f.name }}</option>
+ <option v-for="f in forms" :key="f.id" :value="f.id">{{ f.display_name }}</option>
</select>
</div>
<div class="form-group">
diff --git a/web/src/views/messages/Messages.vue b/web/src/views/messages/Messages.vue
index 8fe3a3c..ed65987 100644
--- a/web/src/views/messages/Messages.vue
+++ b/web/src/views/messages/Messages.vue
@@ -221,7 +221,7 @@ function formatDate(date: string | null | undefined) {
<label class="form-label">Form</label>
<select v-model.number="formId" class="form-select" @change="applyFilters">
<option :value="0">All forms</option>
- <option v-for="f in forms" :key="f.id" :value="f.id">{{ f.name }}</option>
+ <option v-for="f in forms" :key="f.id" :value="f.id">{{ f.display_name }}</option>
</select>
</div>
@@ -306,7 +306,7 @@ function formatDate(date: string | null | undefined) {
<p v-if="!formId && collectForms.length" class="collect-note">
Responses to
<template v-for="(f, i) in collectForms.slice(0, 3)" :key="f.id">
- <router-link :to="`/forms/${f.id}?tab=responses`">{{ f.name }}</router-link
+ <router-link :to="`/forms/${f.id}?tab=responses`">{{ f.display_name }}</router-link
>{{ i < Math.min(collectForms.length, 3) - 1 ? ", " : "" }}
</template>
<template v-if="collectForms.length > 3"> and {{ collectForms.length - 3 }} more</template>
@@ -365,7 +365,7 @@ function formatDate(date: string | null | undefined) {
</span>
</td>
<td>
- {{ message.form?.name || "-" }}
+ {{ message.form?.display_name || "-" }}
<div v-if="message.team || message.assigned_to" class="route-line">
{{ [message.team?.name, message.assigned_to?.name].filter(Boolean).join(" · ") }}
</div>
diff --git a/web/src/views/settings/Settings.vue b/web/src/views/settings/Settings.vue
index a1bcad4..1edf4f8 100644
--- a/web/src/views/settings/Settings.vue
+++ b/web/src/views/settings/Settings.vue
@@ -276,7 +276,7 @@ async function autoSave() {
>
<option v-if="savedWorkspaceId === null" :value="null" disabled>Not set</option>
<option v-for="ws in workspaceChoices" :key="ws.id" :value="ws.id">
- {{ ws.name }}
+ {{ ws.display_name }}
</option>
</select>
<span class="form-hint">
diff --git a/web/src/views/stylesheets/Stylesheets.vue b/web/src/views/stylesheets/Stylesheets.vue
index 1222434..9e27b9b 100644
--- a/web/src/views/stylesheets/Stylesheets.vue
+++ b/web/src/views/stylesheets/Stylesheets.vue
@@ -1,5 +1,6 @@
<script setup lang="ts">
import { ref, onMounted } from 'vue'
+import { IDENTIFIER_HINT, toIdentifier } from '../../composables/identifier'
import { stylesheetsApi } from '../../api/stylesheets'
import type { StyleSheet, StyleSheetInput, Pageable } from '../../api/types'
import { useNotificationStore } from '../../stores/notification'
@@ -21,13 +22,22 @@ const showModal = ref(false)
const editing = ref<StyleSheet | null>(null)
const saving = ref(false)
- const form = ref<StyleSheetInput>({
+ const form = ref<Required<StyleSheetInput>>({
name: '',
+ display_name: '',
css: '',
})
+// A new stylesheet's name follows its display name until edited by hand;
+// an existing one keeps its name.
+const nameEdited = ref(false)
+
+function syncName() {
+ if (!nameEdited.value) form.value.name = toIdentifier(form.value.display_name)
+}
function resetForm() {
- form.value = { name: '', css: '' }
+ form.value = { name: '', display_name: '', css: '' }
+ nameEdited.value = false
editing.value = null
}
@@ -40,8 +50,10 @@ function openEdit(sheet: StyleSheet) {
editing.value = sheet
form.value = {
name: sheet.name,
+ display_name: sheet.display_name,
css: sheet.css,
}
+ nameEdited.value = true
showModal.value = true
}
@@ -64,7 +76,7 @@ const { pageable, goToPage } = usePagination(async (page) => {
async function saveStylesheet() {
- if (!form.value.name.trim()) return
+ if (!form.value.display_name.trim() || !form.value.name.trim()) return
saving.value = true
try {
if (editing.value) {
@@ -76,8 +88,8 @@ async function saveStylesheet() {
}
closeModal()
await goToPage(pageable.value.current_page)
- } catch {
- notify.error(editing.value ? 'Failed to update stylesheet' : 'Failed to create stylesheet')
+ } catch (e: any) {
+ notify.error(e?.response?.data?.error?.message || (editing.value ? 'Failed to update stylesheet' : 'Failed to create stylesheet'))
} finally {
saving.value = false
}
@@ -86,7 +98,7 @@ async function saveStylesheet() {
async function deleteStylesheet(sheet: StyleSheet) {
const confirmed = await confirm({
title: 'Delete Stylesheet',
- message: `Are you sure you want to delete "${sheet.name}"? Templates using this stylesheet will lose their styling.`,
+ message: `Are you sure you want to delete "${sheet.display_name}"? Templates using this stylesheet will lose their styling.`,
confirmText: 'Delete',
variant: 'danger',
})
@@ -133,6 +145,7 @@ const { watchClickStart, confirmClickEnd } = useModalSafeClose(() => {
<table>
<thead>
<tr>
+ <th>Display name</th>
<th>Name</th>
<th>Created</th>
<th>Updated</th>
@@ -141,7 +154,8 @@ const { watchClickStart, confirmClickEnd } = useModalSafeClose(() => {
</thead>
<tbody>
<tr v-for="sheet in stylesheets" :key="sheet.id">
- <td>{{ sheet.name }}</td>
+ <td>{{ sheet.display_name }}</td>
+ <td><code>{{ sheet.name }}</code></td>
<td>{{ formatDate(sheet.created_at) }}</td>
<td>
<span v-if="sheet.updated_at">{{ formatDate(sheet.updated_at) }}</span>
@@ -171,9 +185,15 @@ const { watchClickStart, confirmClickEnd } = useModalSafeClose(() => {
<h3>{{ editing ? 'Edit Stylesheet' : 'Create Stylesheet' }}</h3>
</div>
<div class="modal-body">
+ <div class="form-group">
+ <label class="form-label">Display name</label>
+ <input v-model="form.display_name" class="form-input" placeholder="e.g. Brand Styles" @input="syncName" />
+ </div>
<div class="form-group">
<label class="form-label">Name</label>
- <input v-model="form.name" class="form-input" placeholder="e.g. Brand Styles" />
+ <input v-model="form.name" class="form-input mono" placeholder="brand-styles" :title="IDENTIFIER_HINT"
+ @input="nameEdited = true" />
+ <span class="form-hint">Imported HTML templates link stylesheets by this name. {{ IDENTIFIER_HINT }}</span>
</div>
<div class="form-group">
<label class="form-label">CSS</label>
@@ -185,7 +205,7 @@ const { watchClickStart, confirmClickEnd } = useModalSafeClose(() => {
<button class="btn btn-secondary" @click="closeModal">Cancel</button>
<button
class="btn btn-primary"
- :disabled="saving || !form.name.trim()"
+ :disabled="saving || !form.display_name.trim() || !form.name.trim()"
@click="saveStylesheet"
>
{{ saving ? 'Saving...' : (editing ? 'Update' : 'Create') }}
diff --git a/web/src/views/templates/EmailBuilder.vue b/web/src/views/templates/EmailBuilder.vue
index 802fedd..306d9c5 100644
--- a/web/src/views/templates/EmailBuilder.vue
+++ b/web/src/views/templates/EmailBuilder.vue
@@ -199,7 +199,7 @@ onBeforeUnmount(() => {
<span class="mdi mdi-arrow-left"></span> Back
</button>
<div class="builder-title">
- <h2>{{ template?.name || 'Template' }}</h2>
+ <h2>{{ template?.display_name || 'Template' }}</h2>
<div class="builder-meta">
<span class="badge badge-accent">Visual Builder</span>
<span class="badge badge-info">{{ localization?.language }}</span>
diff --git a/web/src/views/templates/TemplateDetail.vue b/web/src/views/templates/TemplateDetail.vue
index 2486d4a..dd1354b 100644
--- a/web/src/views/templates/TemplateDetail.vue
+++ b/web/src/views/templates/TemplateDetail.vue
@@ -8,7 +8,7 @@ import type {
Language,
StyleSheet,
Template,
- TemplateInput,
+ TemplateDraft,
TemplateLocalization,
TemplateLocalizationInput,
TemplatePreview,
@@ -83,8 +83,9 @@ const savingVersionStylesheet = ref(false);
const savingTemplate = ref(false);
const showTemplateEditModal = ref(false);
-const templateForm = ref<TemplateInput>({
+const templateForm = ref<TemplateDraft>({
name: "",
+ display_name: "",
sample_data: "",
default_language: "en",
description: "",
@@ -377,6 +378,7 @@ function openEditTemplate() {
if (!template.value) return;
templateForm.value = {
name: template.value.name,
+ display_name: template.value.display_name,
sample_data: template.value.sample_data || "",
default_language: template.value.default_language || "en",
description: template.value.description || "",
@@ -385,7 +387,7 @@ function openEditTemplate() {
}
async function saveTemplate() {
- if (!template.value || !templateForm.value.name.trim()) return;
+ if (!template.value || !templateForm.value.display_name.trim() || !templateForm.value.name.trim()) return;
savingTemplate.value = true;
try {
await templatesApi.update(template.value.id, templateForm.value);
@@ -416,11 +418,11 @@ onMounted(loadAll);
<div>
<div class="page-header">
<div>
- <h1>{{ template?.name || "Template" }}</h1>
+ <h1>{{ template?.display_name || "Template" }}</h1>
<p class="crumb">
<RouterLink to="/templates">Templates</RouterLink>
<span aria-hidden="true"> / </span>
- <span>{{ template?.name || "…" }}</span>
+ <span>{{ template?.display_name || "…" }}</span>
</p>
</div>
<div class="header-actions">
diff --git a/web/src/views/templates/TemplateEditor.vue b/web/src/views/templates/TemplateEditor.vue
index f1211f9..1c441d1 100644
--- a/web/src/views/templates/TemplateEditor.vue
+++ b/web/src/views/templates/TemplateEditor.vue
@@ -307,7 +307,7 @@ function switchToVisualBuilder() {
<span class="mdi mdi-arrow-left"></span> Back
</button>
<div class="editor-title">
- <h2>{{ template?.name || 'Template' }}</h2>
+ <h2>{{ template?.display_name || 'Template' }}</h2>
<div class="editor-meta">
<span class="badge badge-info">{{ localization?.language }}</span>
<span class="badge badge-neutral">v{{ version?.version }}</span>
diff --git a/web/src/views/templates/TemplatePreview.vue b/web/src/views/templates/TemplatePreview.vue
index 855f4ae..13c2541 100644
--- a/web/src/views/templates/TemplatePreview.vue
+++ b/web/src/views/templates/TemplatePreview.vue
@@ -77,7 +77,7 @@ async function loadTemplate(id: number) {
return
}
- search.value = template.value.name
+ search.value = template.value.display_name
if (template.value.sample_data) sampleData.value = template.value.sample_data
@@ -183,7 +183,7 @@ function formatDate(dateStr: string): string {
:class="{ active: t.id === template?.id }"
@mousedown.prevent="selectTemplate(t)"
>
- <span class="template-search-name">{{ t.name }}</span>
+ <span class="template-search-name">{{ t.display_name }}</span>
<span v-if="t.description" class="template-search-desc">{{ t.description }}</span>
</button>
</div>
@@ -203,7 +203,7 @@ function formatDate(dateStr: string): string {
<!-- Template Info -->
<div class="card" style="margin-bottom: 24px;">
<div class="card-header">
- <h2>{{ template.name }}</h2>
+ <h2>{{ template.display_name }}</h2>
<div class="flex gap-2">
<span v-if="localization" class="badge badge-success">{{ localization.language }}</span>
<span v-if="version" class="badge badge-neutral">v{{ version.version }}</span>
@@ -222,7 +222,7 @@ function formatDate(dateStr: string): string {
</tr>
<tr v-if="version?.stylesheet">
<td class="info-label">Stylesheet</td>
- <td><span class="badge badge-neutral">{{ version.stylesheet.name }}</span></td>
+ <td><span class="badge badge-neutral">{{ version.stylesheet.display_name }}</span></td>
</tr>
<tr>
<td class="info-label">Created</td>
@@ -325,7 +325,7 @@ function formatDate(dateStr: string): string {
<pre class="code-block">{{ localization.text_template }}</pre>
</div>
<div v-if="version?.stylesheet" style="margin-bottom: 16px;">
- <div class="source-label">Stylesheet: {{ version.stylesheet.name }}</div>
+ <div class="source-label">Stylesheet: {{ version.stylesheet.display_name }}</div>
<pre class="code-block">{{ version.stylesheet.css }}</pre>
</div>
<div v-if="!localization.html_template && !localization.text_template" class="text-muted text-sm">
diff --git a/web/src/views/templates/Templates.vue b/web/src/views/templates/Templates.vue
index 8ce3bbc..0d87773 100644
--- a/web/src/views/templates/Templates.vue
+++ b/web/src/views/templates/Templates.vue
@@ -6,7 +6,7 @@ import { languagesApi } from "../../api/languages";
import type {
Template,
TemplateListItem,
- TemplateInput,
+ TemplateDraft,
TemplateExport,
Language,
Pageable,
@@ -36,8 +36,9 @@ const saving = ref(false);
const languages = ref<Language[]>([]);
-const form = ref<TemplateInput>({
+const form = ref<TemplateDraft>({
name: "",
+ display_name: "",
sample_data: "",
default_language: "en",
description: "",
@@ -53,7 +54,7 @@ async function loadLanguages() {
}
function resetForm() {
- form.value = { name: "", sample_data: "", default_language : languages.value.find(l => l.is_default)?.code || 'en', description: "" };
+ form.value = { name: "", display_name: "", sample_data: "", default_language : languages.value.find(l => l.is_default)?.code || 'en', description: "" };
editing.value = null;
}
@@ -66,6 +67,7 @@ function openEdit(template: Template) {
editing.value = template;
form.value = {
name: template.name,
+ display_name: template.display_name,
sample_data: template.sample_data || "",
default_language: template.default_language || "en",
description: template.description || "",
@@ -96,7 +98,7 @@ function onSearchInput() {
}
async function saveTemplate() {
- if (!form.value.name.trim()) return;
+ if (!form.value.display_name.trim() || !form.value.name.trim()) return;
saving.value = true;
try {
if (editing.value) {
@@ -120,7 +122,7 @@ async function saveTemplate() {
async function deleteTemplate(template: Template) {
const confirmed = await confirm({
title: "Delete Template",
- message: `Are you sure you want to delete "${template.name}"? This action cannot be undone.`,
+ message: `Are you sure you want to delete "${template.display_name}"? This action cannot be undone.`,
confirmText: "Delete",
variant: "danger",
});
@@ -278,7 +280,7 @@ onMounted(() => {
"
>
<td>
- <div>{{ tmpl.name }}</div>
+ <div>{{ tmpl.display_name }} <code class="tmpl-name">{{ tmpl.name }}</code></div>
<div v-if="tmpl.description" class="text-muted text-sm">
{{ tmpl.description }}
</div>
@@ -367,6 +369,12 @@ onMounted(() => {
</template>
<style scoped>
+.tmpl-name {
+ margin-left: 6px;
+ font-size: 12px;
+ color: var(--text-muted);
+}
+
.langs {
display: flex;
gap: 4px;
diff --git a/web/src/views/templates/detail/VersionList.vue b/web/src/views/templates/detail/VersionList.vue
index ee9af85..34ac7b4 100644
--- a/web/src/views/templates/detail/VersionList.vue
+++ b/web/src/views/templates/detail/VersionList.vue
@@ -37,7 +37,7 @@ function formatDate(value: string) {
<div v-if="canEdit" class="new-version">
<select v-model="newStylesheetId" class="form-select select-sm" aria-label="Stylesheet for the new version">
<option :value="null">No stylesheet</option>
- <option v-for="ss in stylesheets" :key="ss.id" :value="ss.id">{{ ss.name }}</option>
+ <option v-for="ss in stylesheets" :key="ss.id" :value="ss.id">{{ ss.display_name }}</option>
</select>
<button class="btn btn-primary btn-sm" :disabled="creating" @click="emit('create', newStylesheetId)">
{{ creating ? "Creating…" : "New version" }}
@@ -79,7 +79,7 @@ function formatDate(value: string) {
<span v-if="selectedId === v.id" class="viewing">Showing content below</span>
</td>
<td>
- <span v-if="v.stylesheet" class="badge badge-neutral">{{ v.stylesheet.name }}</span>
+ <span v-if="v.stylesheet" class="badge badge-neutral">{{ v.stylesheet.display_name }}</span>
<span v-else class="muted">&mdash;</span>
</td>
<td>{{ v.localizations?.length || 0 }}</td>
diff --git a/web/src/views/templates/detail/VersionStylesheetModal.vue b/web/src/views/templates/detail/VersionStylesheetModal.vue
index 5936ba2..fc01018 100644
--- a/web/src/views/templates/detail/VersionStylesheetModal.vue
+++ b/web/src/views/templates/detail/VersionStylesheetModal.vue
@@ -17,7 +17,7 @@ const stylesheetId = defineModel<number | null>("stylesheetId", { default: null
<label class="form-label" for="version-stylesheet">Stylesheet</label>
<select id="version-stylesheet" v-model="stylesheetId" class="form-select">
<option :value="null">No stylesheet</option>
- <option v-for="ss in stylesheets" :key="ss.id" :value="ss.id">{{ ss.name }}</option>
+ <option v-for="ss in stylesheets" :key="ss.id" :value="ss.id">{{ ss.display_name }}</option>
</select>
<span class="form-hint">
Its CSS is inlined into every send from this version. Each version carries its own, so a
diff --git a/web/src/views/workspaces/WorkspaceMembers.vue b/web/src/views/workspaces/WorkspaceMembers.vue
index 09bc56c..a3abb9b 100644
--- a/web/src/views/workspaces/WorkspaceMembers.vue
+++ b/web/src/views/workspaces/WorkspaceMembers.vue
@@ -155,9 +155,9 @@ onMounted(async () => {
<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>
+ <h1>{{ ws?.display_name || 'Workspace' }} — Members</h1>
+ <p v-if="ws?.name" style="color: var(--text-muted); font-size: 13px; margin-top: 2px;">
+ <code>{{ ws.name }}</code>
</p>
</div>
<div style="display: flex; gap: 8px;">
diff --git a/web/src/views/workspaces/WorkspaceSettings.vue b/web/src/views/workspaces/WorkspaceSettings.vue
index 739de16..2c79d3d 100644
--- a/web/src/views/workspaces/WorkspaceSettings.vue
+++ b/web/src/views/workspaces/WorkspaceSettings.vue
@@ -59,7 +59,7 @@ const importing = ref(false)
const importFileRef = ref<HTMLInputElement | null>(null)
// Settings (workspace name/description)
-const editName = ref('')
+const editDisplayName = ref('')
const editDescription = ref('')
const saving = ref(false)
@@ -113,7 +113,7 @@ async function fetchWorkspace() {
try {
const res = await withWorkspace(() => workspaceApi.getCurrent())
ws.value = res.data.data
- editName.value = ws.value.name
+ editDisplayName.value = ws.value.display_name
editDescription.value = ws.value.description || ''
} catch {
notify.error('Failed to load workspace')
@@ -298,7 +298,7 @@ function formatLimit(value: number): string {
async function saveSettings() {
saving.value = true
try {
- await withWorkspace(() => workspaceApi.update({ name: editName.value.trim(), description: editDescription.value.trim() }))
+ await withWorkspace(() => workspaceApi.update({ display_name: editDisplayName.value.trim(), description: editDescription.value.trim() }))
notify.success('Workspace updated')
await wsStore.fetchWorkspaces()
} catch (err: any) {
@@ -330,7 +330,7 @@ async function exportWorkspaceData() {
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
- a.download = `posta-workspace-export-${ws.value?.slug || wsId}-${new Date().toISOString().slice(0, 10)}.json`
+ a.download = `posta-workspace-export-${ws.value?.name || wsId}-${new Date().toISOString().slice(0, 10)}.json`
a.click()
URL.revokeObjectURL(url)
notify.success('Workspace data exported successfully')
@@ -393,9 +393,9 @@ watch(activeTab, (value) => {
<div>
<div class="page-header">
<div>
- <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>
+ <h1>{{ ws?.display_name || 'Workspace' }} — Settings</h1>
+ <p v-if="ws?.name" style="color: var(--text-muted); font-size: 13px; margin-top: 2px;">
+ <code>{{ ws.name }}</code>
</p>
</div>
<div style="display: flex; gap: 8px;">
@@ -537,17 +537,17 @@ watch(activeTab, (value) => {
<div class="card-header"><span>Workspace Settings</span></div>
<div class="card-body">
<div class="form-group">
- <label class="form-label">Name</label>
- <input v-model="editName" class="form-input" />
+ <label class="form-label">Display name</label>
+ <input v-model="editDisplayName" class="form-input" />
</div>
<div class="form-group">
<label class="form-label">Description</label>
<input v-model="editDescription" class="form-input" placeholder="Optional description" />
</div>
<div class="form-group">
- <label class="form-label">Slug</label>
- <input :value="ws?.slug" class="form-input" disabled />
- <small style="font-size: 12px; color: var(--text-muted); margin-top: 4px; display: block;">Slug cannot be changed after creation.</small>
+ <label class="form-label">Name</label>
+ <input :value="ws?.name" class="form-input mono" disabled />
+ <span class="form-hint">The workspace's identifier. It cannot change after creation.</span>
</div>
<button class="btn btn-primary" :disabled="saving" @click="saveSettings">
{{ saving ? 'Saving...' : 'Save Changes' }}
@@ -733,7 +733,7 @@ watch(activeTab, (value) => {
<label class="form-label">OAuth Provider</label>
<select v-model.number="ssoForm.provider_id" class="form-select" required>
<option :value="0" disabled>Select a provider</option>
- <option v-for="p in ssoProviders" :key="p.slug" :value="p.id">{{ p.name }} ({{ p.type }})</option>
+ <option v-for="p in ssoProviders" :key="p.name" :value="p.id">{{ p.display_name }} ({{ p.type }})</option>
</select>
</div>
diff --git a/web/src/views/workspaces/Workspaces.vue b/web/src/views/workspaces/Workspaces.vue
index c046629..520cd6b 100644
--- a/web/src/views/workspaces/Workspaces.vue
+++ b/web/src/views/workspaces/Workspaces.vue
@@ -1,5 +1,6 @@
<script setup lang="ts">
import { ref, onMounted } from 'vue'
+import { IDENTIFIER_HINT, toIdentifier } from '../../composables/identifier'
import { useRouter, useRoute } from 'vue-router'
import { workspaceApi } from '../../api/workspaces'
import type { Workspace, WorkspaceInvitation } from '../../api/types'
@@ -16,8 +17,10 @@ const invitations = ref<WorkspaceInvitation[]>([])
const loading = ref(true)
const showCreateModal = ref(false)
+const newDisplayName = ref('')
const newName = ref('')
-const newSlug = ref('')
+// The name follows the display name until it is edited by hand.
+const nameEdited = ref(false)
const newDescription = ref('')
// On by default: an empty workspace has nothing to send and nothing to look at.
const newSeedDefaults = ref(true)
@@ -39,27 +42,25 @@ async function fetchData() {
}
}
-function autoSlug() {
- newSlug.value = newName.value
- .toLowerCase()
- .replace(/[^a-z0-9]+/g, '-')
- .replace(/^-|-$/g, '')
+function syncName() {
+ if (!nameEdited.value) newName.value = toIdentifier(newDisplayName.value)
}
async function createWorkspace() {
- if (!newName.value.trim() || !newSlug.value.trim()) return
+ if (!newDisplayName.value.trim() || !newName.value.trim()) return
creating.value = true
try {
await workspaceApi.create({
+ display_name: newDisplayName.value.trim(),
name: newName.value.trim(),
- slug: newSlug.value.trim(),
description: newDescription.value.trim(),
seed_defaults: newSeedDefaults.value,
})
notify.success('Workspace created')
showCreateModal.value = false
+ newDisplayName.value = ''
newName.value = ''
- newSlug.value = ''
+ nameEdited.value = false
newDescription.value = ''
newSeedDefaults.value = true
await fetchData()
@@ -175,8 +176,8 @@ if (route.query.create !== undefined) {
<table>
<thead>
<tr>
+ <th>Display name</th>
<th>Name</th>
- <th>Slug</th>
<th>Your Role</th>
<th>Created</th>
<th>Actions</th>
@@ -184,8 +185,8 @@ if (route.query.create !== undefined) {
</thead>
<tbody>
<tr v-for="ws in workspaces" :key="ws.id">
- <td style="font-weight: 500;">{{ ws.name }}</td>
- <td><code>{{ ws.slug }}</code></td>
+ <td style="font-weight: 500;">{{ ws.display_name }}</td>
+ <td><code>{{ ws.name }}</code></td>
<td>
<span class="badge" :class="roleBadgeClass(ws.role)">{{ ws.role }}</span>
</td>
@@ -224,27 +225,27 @@ if (route.query.create !== undefined) {
<form @submit.prevent="createWorkspace">
<div class="modal-body">
<div class="form-group">
- <label class="form-label">Name</label>
+ <label class="form-label">Display name</label>
<input
- v-model="newName"
+ v-model="newDisplayName"
class="form-input"
placeholder="My Team"
required
- @input="autoSlug"
+ @input="syncName"
/>
</div>
<div class="form-group">
- <label class="form-label">Slug</label>
+ <label class="form-label">Name</label>
<input
- v-model="newSlug"
- class="form-input"
+ v-model="newName"
+ class="form-input mono"
placeholder="my-team"
pattern="[a-z0-9]+(-[a-z0-9]+)*"
+ :title="IDENTIFIER_HINT"
required
+ @input="nameEdited = true"
/>
- <small style="font-size: 12px; color: var(--text-muted); margin-top: 4px; display: block;">
- URL-friendly identifier. Lowercase letters, numbers, and hyphens only.
- </small>
+ <span class="form-hint">Unique on this Posta. {{ IDENTIFIER_HINT }} It cannot change later.</span>
</div>
<div class="form-group">
<label class="form-label">Description (optional)</label>
@@ -268,7 +269,7 @@ if (route.query.create !== undefined) {
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" @click="showCreateModal = false">Cancel</button>
- <button type="submit" class="btn btn-primary" :disabled="creating || !newName.trim() || !newSlug.trim()">
+ <button type="submit" class="btn btn-primary" :disabled="creating || !newDisplayName.trim() || !newName.trim()">
{{ creating ? 'Creating...' : 'Create' }}
</button>
</div>