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.
Go email-relayemail-routinghttp-to-smtpmail-deliverymailchimp-alternativemailgun-alternativemailsendermailservermailtemplatemailtestpostmark-alternativesend-emailsendgrid-alternativesendmailtransactional-emailtransactional-outbox
fix(templates): repair the list, make creation atomic, stop losing builder designs
Jonas Kaninda3dbdc6a59816
diff --git a/go.mod b/go.modindex 5e57118..6b7a0df 100644--- a/go.mod+++ b/go.mod@@ -12,6 +12,7 @@ require (github.com/golang-jwt/jwt/v5 v5.3.1github.com/google/uuid v1.6.0github.com/hibiken/asynq v0.26.0+ github.com/jackc/pgx/v5 v5.10.0github.com/jkaninda/go-utils v0.1.4github.com/jkaninda/logger v0.0.5github.com/jkaninda/okapi v0.11.0@@ -59,7 +60,6 @@ require (github.com/inbucket/html2text v1.0.0 // indirectgithub.com/jackc/pgpassfile v1.0.0 // indirectgithub.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect- github.com/jackc/pgx/v5 v5.10.0 // indirectgithub.com/jackc/puddle/v2 v2.2.2 // indirectgithub.com/jinzhu/inflection v1.0.0 // indirectgithub.com/jinzhu/now v1.1.5 // indirectdiff --git a/internal/handlers/template_handler.go b/internal/handlers/template_handler.goindex 7116832..9599abe 100644--- a/internal/handlers/template_handler.go+++ b/internal/handlers/template_handler.go@@ -6,6 +6,7 @@ package handlersimport ("fmt""io"+ "path/filepath""strings""time"@@ -101,23 +102,14 @@ func (h *TemplateHandler) Create(c *okapi.Context, req *CreateTemplateRequest) eLastEditedByID: &scope.UserID,}- if err := h.repo.Create(tmpl); err != nil {- return c.AbortConflict("template name already exists")- }-- // Create default version v1 and set it as active- v := &models.TemplateVersion{- TemplateID: tmpl.ID,- Version: 1,- SampleData: req.Body.SampleData,- }- if err := h.versionRepo.Create(v); err != nil {- return c.AbortInternalServerError("failed to create default version")+ err := h.repo.CreateWithVersions(tmpl, []repositories.ImportVersion{+ {SampleData: req.Body.SampleData, IsActive: true},+ })+ if repositories.IsDuplicateName(err) {+ return c.AbortConflict("a template named \"" + tmpl.Name + "\" already exists in this workspace")}-- tmpl.ActiveVersionID = &v.ID- if err := h.repo.Update(tmpl); err != nil {- return c.AbortInternalServerError("failed to activate default version")+ if err != nil {+ return c.AbortInternalServerError("failed to create template")}return created(c, tmpl)@@ -151,6 +143,9 @@ func (h *TemplateHandler) Update(c *okapi.Context, req *UpdateTemplateRequest) etmpl.LastEditedByID = &editorIDif err := h.repo.Update(tmpl); err != nil {+ if repositories.IsDuplicateName(err) {+ return c.AbortConflict("a template named \"" + tmpl.Name + "\" already exists in this workspace")+ }return c.AbortInternalServerError("failed to update template")}@@ -162,6 +157,11 @@ func (h *TemplateHandler) Update(c *okapi.Context, req *UpdateTemplateRequest) ereturn ok(c, tmpl)}+type TemplateListItem struct {+ models.Template+ Languages []string `json:"languages"`+}+func (h *TemplateHandler) List(c *okapi.Context, req *ListTemplatesRequest) error {page, size, offset := normalizePageParams(req.Page, req.Size)@@ -170,7 +170,26 @@ func (h *TemplateHandler) List(c *okapi.Context, req *ListTemplatesRequest) erroreturn c.AbortInternalServerError("failed to list templates")}- return paginated(c, templates, total, page, size)+ ids := make([]uint, 0, len(templates))+ for i := range templates {+ ids = append(ids, templates[i].ID)+ }+ // One aggregate for the page rather than a query per row.+ languages, err := h.repo.LanguagesForActiveVersions(ids)+ if err != nil {+ return c.AbortInternalServerError("failed to list templates")+ }++ items := make([]TemplateListItem, 0, len(templates))+ for i := range templates {+ langs := languages[templates[i].ID]+ if langs == nil {+ langs = []string{}+ }+ items = append(items, TemplateListItem{Template: templates[i], Languages: langs})+ }++ return paginated(c, items, total, page, size)}func (h *TemplateHandler) Get(c *okapi.Context, req *GetTemplateRequest) error {@@ -264,6 +283,7 @@ type ExportLocalization struct {SubjectTemplate string `json:"subject_template"`HTMLTemplate string `json:"html_template"`TextTemplate string `json:"text_template"`+ BuilderJSON string `json:"builder_json,omitempty"`}type ExportVersion struct {@@ -313,6 +333,7 @@ func (h *TemplateHandler) Export(c *okapi.Context, req *ExportTemplateRequest) eSubjectTemplate: l.SubjectTemplate,HTMLTemplate: l.HTMLTemplate,TextTemplate: l.TextTemplate,+ BuilderJSON: l.BuilderJSON,})}@@ -366,66 +387,38 @@ func (h *TemplateHandler) Import(c *okapi.Context, req *ImportTemplateRequest) eDefaultLanguage: defaultLang,Description: data.Description,SampleData: data.SampleData,+ LastEditedByID: &scope.UserID,}- if err := h.repo.Create(tmpl); err != nil {- return c.AbortConflict("template name already exists")- }-- var activeVersionDBID *uint-+ versions := make([]repositories.ImportVersion, 0, len(data.Versions))for _, ev := range data.Versions {- nextVersion, err := h.versionRepo.NextVersion(tmpl.ID)- if err != nil {- return c.AbortInternalServerError("failed to determine next version")- }-- v := &models.TemplateVersion{- TemplateID: tmpl.ID,- Version: nextVersion,- SampleData: ev.SampleData,- StyleSheetID: findOrCreateStyleSheet(ev.StyleSheet, scope, h.stylesheetRepo),- }- if err := h.versionRepo.Create(v); err != nil {- return c.AbortInternalServerError(fmt.Sprintf("failed to create version %d", ev.Version))- }-- if ev.IsActive {- activeVersionDBID = &v.ID- }-+ locs := make([]repositories.ImportLocalization, 0, len(ev.Localizations))for _, el := range ev.Localizations {- l := &models.TemplateLocalization{- VersionID: v.ID,+ locs = append(locs, repositories.ImportLocalization{Language: el.Language,SubjectTemplate: el.SubjectTemplate,HTMLTemplate: el.HTMLTemplate,TextTemplate: el.TextTemplate,- }- if err := h.localizationRepo.Create(l); err != nil {- return c.AbortInternalServerError(fmt.Sprintf("failed to create localization %s for version %d", el.Language, ev.Version))- }+ BuilderJSON: el.BuilderJSON,+ })}+ versions = append(versions, repositories.ImportVersion{+ SampleData: ev.SampleData,+ StyleSheetID: findOrCreateStyleSheet(ev.StyleSheet, scope, h.stylesheetRepo),+ IsActive: ev.IsActive,+ Localizations: locs,+ })}-- // If no versions were imported, create a default v1- if len(data.Versions) == 0 {- v := &models.TemplateVersion{- TemplateID: tmpl.ID,- Version: 1,- SampleData: data.SampleData,- }- if err := h.versionRepo.Create(v); err != nil {- return c.AbortInternalServerError("failed to create default version")- }- activeVersionDBID = &v.ID+ if len(versions) == 0 {+ versions = append(versions, repositories.ImportVersion{SampleData: data.SampleData, IsActive: true})}- if activeVersionDBID != nil {- tmpl.ActiveVersionID = activeVersionDBID- if err := h.repo.Update(tmpl); err != nil {- return c.AbortInternalServerError("failed to activate version")- }+ err := h.repo.CreateWithVersions(tmpl, versions)+ if repositories.IsDuplicateName(err) {+ return c.AbortConflict("a template named \"" + tmpl.Name + "\" already exists in this workspace")+ }+ if err != nil {+ return c.AbortInternalServerError("failed to import template")}return created(c, tmpl)@@ -468,9 +461,9 @@ func (h *TemplateHandler) ImportHTML(c *okapi.Context) error {return c.AbortBadRequest("file is empty")}- // Derive template name from filename- name := strings.TrimSuffix(lower, ".html")- name = strings.TrimSuffix(name, ".htm")+ // 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")@@ -492,7 +485,8 @@ func (h *TemplateHandler) ImportHTML(c *okapi.Context) error {defaultLang = defLang.Code}- // Create template+ stylesheetID := h.resolveImportedStyleSheet(scope, name, css, linkNames)+tmpl := &models.Template{UserID: scope.UserID,WorkspaceID: scope.WorkspaceID,@@ -500,39 +494,24 @@ func (h *TemplateHandler) ImportHTML(c *okapi.Context) error {DefaultLanguage: defaultLang,Description: fmt.Sprintf("Imported from %s", filename),SampleData: "{}",- }- if err := h.repo.Create(tmpl); err != nil {- return c.AbortConflict("template with this name already exists")+ LastEditedByID: &scope.UserID,}- stylesheetID := h.resolveImportedStyleSheet(scope, name, css, linkNames)-- // Create version v1- v := &models.TemplateVersion{- TemplateID: tmpl.ID,- Version: 1,+ err = h.repo.CreateWithVersions(tmpl, []repositories.ImportVersion{{SampleData: "{}",StyleSheetID: stylesheetID,+ IsActive: true,+ Localizations: []repositories.ImportLocalization{{+ Language: defaultLang,+ SubjectTemplate: subject,+ HTMLTemplate: body,+ }},+ }})+ if repositories.IsDuplicateName(err) {+ return c.AbortConflict("a template named \"" + name + "\" already exists in this workspace")}- if err := h.versionRepo.Create(v); err != nil {- return c.AbortInternalServerError("failed to create template version")- }-- // Set active version- tmpl.ActiveVersionID = &v.ID- if err := h.repo.Update(tmpl); err != nil {- return c.AbortInternalServerError("failed to activate version")- }-- // Create default localization- loc := &models.TemplateLocalization{- VersionID: v.ID,- Language: defaultLang,- SubjectTemplate: subject,- HTMLTemplate: body,- }- if err := h.localizationRepo.Create(loc); err != nil {- return c.AbortInternalServerError("failed to create localization")+ if err != nil {+ return c.AbortInternalServerError("failed to import template")}return created(c, tmpl)diff --git a/internal/routes/workspace_resource_routes.go b/internal/routes/workspace_resource_routes.goindex 56f4e13..5093ff1 100644--- a/internal/routes/workspace_resource_routes.go+++ b/internal/routes/workspace_resource_routes.go@@ -270,7 +270,7 @@ func (r *Router) workspaceResourceRoutes() []okapi.RouteDefinition {Group: opsGroup,Summary: "List templates",Request: &handlers.ListTemplatesRequest{},- Response: &dto.PageableResponse[models.Template]{},+ Response: &dto.PageableResponse[handlers.TemplateListItem]{},},{Method: http.MethodGet,diff --git a/internal/services/email/service.go b/internal/services/email/service.goindex 2607c57..7114c46 100644--- a/internal/services/email/service.go+++ b/internal/services/email/service.go@@ -1223,13 +1223,14 @@ func (s *Service) findTemplate(userID uint, workspaceID *uint, templateID *uint,return nil, fmt.Errorf("template_id or template name is required")}- if workspaceID != nil {- tmpl, err := s.templateRepo.FindByWorkspaceName(*workspaceID, name)- if err == nil {- return tmpl, nil- }+ if workspaceID == nil {+ return nil, fmt.Errorf("template %q not found: no active workspace", name)+ }+ tmpl, err := s.templateRepo.FindByWorkspaceName(*workspaceID, name)+ if err != nil {+ return nil, fmt.Errorf("template %q not found", name)}- return s.templateRepo.FindByName(userID, name)+ return tmpl, nil}// resolveAndRender resolves the template content using versioned localizationsdiff --git a/internal/storage/repositories/template_repo.go b/internal/storage/repositories/template_repo.goindex 1232033..3afc3fe 100644--- a/internal/storage/repositories/template_repo.go+++ b/internal/storage/repositories/template_repo.go@@ -4,9 +4,11 @@package repositoriesimport (+ "errors""time""github.com/goposta/posta/internal/models"+ "github.com/jackc/pgx/v5/pgconn""gorm.io/gorm""gorm.io/gorm/clause")@@ -41,7 +43,11 @@ func (r *TemplateRepository) FindByID(id uint) (*models.Template, error) {func (r *TemplateRepository) FindByIDWithActors(id uint) (*models.Template, error) {var tmpl models.Template- if err := r.db.Preload("CreatedBy").Preload("LastEditedBy").First(&tmpl, id).Error; err != nil {+ if err := r.db.+ Preload("ActiveVersion").+ Preload("CreatedBy").+ Preload("LastEditedBy").+ First(&tmpl, id).Error; err != nil {return nil, err}return &tmpl, nil@@ -52,29 +58,6 @@ func (r *TemplateRepository) TouchEditor(id, editorID uint) error {Updates(map[string]any{"last_edited_by_id": editorID, "updated_at": time.Now()}).Error}-func (r *TemplateRepository) FindByName(userID uint, name string) (*models.Template, error) {- var tmpl models.Template- if err := r.db.Where("user_id = ? AND name = ? AND workspace_id IS NULL", userID, name).First(&tmpl).Error; err != nil {- return nil, err- }- return &tmpl, nil-}--func (r *TemplateRepository) FindByUserID(userID uint, limit, offset int) ([]models.Template, int64, error) {- var templates []models.Template- var total int64-- r.db.Model(&models.Template{}).Where("user_id = ? AND workspace_id IS NULL", userID).Count(&total)-- if err := r.db.Where("user_id = ? AND workspace_id IS NULL", userID).- Order("created_at DESC").- Limit(limit).Offset(offset).- Find(&templates).Error; err != nil {- return nil, 0, err- }- return templates, total, nil-}-func (r *TemplateRepository) FindByWorkspaceID(workspaceID uint, limit, offset int) ([]models.Template, int64, error) {var templates []models.Templatevar total int64@@ -90,21 +73,31 @@ func (r *TemplateRepository) FindByWorkspaceID(workspaceID uint, limit, offset ireturn templates, total, nil}+// FindByScope lists a workspace's templates.+//+// ActiveVersion and the actor refs are preloaded because the list renders all+// three. Without the preload the version column had nothing to show and printed+// "v?" against every template that had an active version.func (r *TemplateRepository) FindByScope(scope ResourceScope, search string, limit, offset int) ([]models.Template, int64, error) {var items []models.Templatevar total int64- q := ApplyScope(r.db.Model(&models.Template{}), scope)- if search != "" {- q = q.Where("name ILIKE ? OR description ILIKE ?", "%"+search+"%", "%"+search+"%")+ filter := func(q *gorm.DB) *gorm.DB {+ q = ApplyScope(q, scope)+ if search != "" {+ q = q.Where("name ILIKE ? OR description ILIKE ?", "%"+search+"%", "%"+search+"%")+ }+ return q}- q.Count(&total)- qItems := ApplyScope(r.db, scope)- if search != "" {- qItems = qItems.Where("name ILIKE ? OR description ILIKE ?", "%"+search+"%", "%"+search+"%")+ if err := filter(r.db.Model(&models.Template{})).Count(&total).Error; err != nil {+ return nil, 0, err}- if err := qItems.++ if err := filter(r.db.Model(&models.Template{})).+ Preload("ActiveVersion").+ Preload("CreatedBy").+ Preload("LastEditedBy").Order("created_at DESC").Limit(limit).Offset(offset).Find(&items).Error; err != nil {@@ -120,3 +113,127 @@ func (r *TemplateRepository) FindByWorkspaceName(workspaceID uint, name string)}return &tmpl, nil}++// ImportLocalization is one language's content for a template being created.+type ImportLocalization struct {+ Language string+ SubjectTemplate string+ HTMLTemplate string+ TextTemplate string+ BuilderJSON string+}++// ImportVersion is one version of a template being created, with its content.+type ImportVersion struct {+ SampleData string+ StyleSheetID *uint+ IsActive bool+ Localizations []ImportLocalization+}++// CreateWithVersions writes a template, its versions, their localizations and+// the active-version pointer as one unit.+//+// Creating these separately left wreckage behind whenever a later step failed:+// a template with no active version can never be sent, and a partially imported+// one silently lost languages. Both looked fine in the list.+//+// Versions are numbered from 1 in the order given, so an import reproduces the+// source's ordering rather than depending on what already exists.+func (r *TemplateRepository) CreateWithVersions(tmpl *models.Template, versions []ImportVersion) error {+ return r.db.Transaction(func(tx *gorm.DB) error {+ if err := tx.Create(tmpl).Error; err != nil {+ return err+ }++ var activeID *uint+ for i, in := range versions {+ v := &models.TemplateVersion{+ TemplateID: tmpl.ID,+ Version: i + 1,+ SampleData: in.SampleData,+ StyleSheetID: in.StyleSheetID,+ }+ if err := tx.Create(v).Error; err != nil {+ return err+ }+ // The first version is activated by default so the template is+ // usable the moment it exists; an explicitly active one wins.+ if in.IsActive || i == 0 {+ id := v.ID+ activeID = &id+ }++ for _, l := range in.Localizations {+ loc := &models.TemplateLocalization{+ VersionID: v.ID,+ Language: l.Language,+ SubjectTemplate: l.SubjectTemplate,+ HTMLTemplate: l.HTMLTemplate,+ TextTemplate: l.TextTemplate,+ BuilderJSON: l.BuilderJSON,+ }+ if err := tx.Create(loc).Error; err != nil {+ return err+ }+ }+ }++ if activeID == nil {+ return nil+ }+ tmpl.ActiveVersionID = activeID+ return tx.Model(tmpl).Update("active_version_id", *activeID).Error+ })+}++// IsDuplicateName reports whether an error is a unique-constraint violation —+// for templates, the index on (workspace_id, name) rejecting a second template+// with the same name. The caller can then answer with a conflict naming the+// problem instead of a generic failure.+//+// It reads the driver error directly rather than gorm.ErrDuplicatedKey, which+// only exists when the connection is opened with TranslateError.+func IsDuplicateName(err error) bool {+ var pgErr *pgconn.PgError+ if errors.As(err, &pgErr) {+ return pgErr.Code == uniqueViolationCode+ }+ return false+}++const uniqueViolationCode = "23505"++// LanguagesForActiveVersions returns the languages each template is actually+// translated into, keyed by template id.+//+// It is a single aggregate rather than a preload of the localizations+// themselves: the list only needs the codes, and loading every localization+// would pull each language's full HTML body across for nothing. Returning+// partially-selected localization rows instead would put objects on the wire+// whose empty subject and body mean "not loaded" rather than "empty".+func (r *TemplateRepository) LanguagesForActiveVersions(templateIDs []uint) (map[uint][]string, error) {+ out := make(map[uint][]string, len(templateIDs))+ if len(templateIDs) == 0 {+ return out, nil+ }++ var rows []struct {+ TemplateID uint+ Language string+ }+ err := r.db.Table("templates t").+ Select("t.id as template_id, l.language").+ Joins("JOIN template_localizations l ON l.version_id = t.active_version_id").+ Where("t.id IN ?", templateIDs).+ Order("t.id, l.language").+ Scan(&rows).Error+ if err != nil {+ return nil, err+ }++ for _, row := range rows {+ out[row.TemplateID] = append(out[row.TemplateID], row.Language)+ }+ return out, nil+}diff --git a/internal/storage/repositories/template_repo_test.go b/internal/storage/repositories/template_repo_test.gonew file mode 100644index 0000000..3f87c1e--- /dev/null+++ b/internal/storage/repositories/template_repo_test.go@@ -0,0 +1,283 @@+// SPDX-FileCopyrightText: 2026 Jonas Kaninda+// SPDX-License-Identifier: AGPL-3.0-or-later++package repositories++import (+ "testing"++ "github.com/goposta/posta/internal/models"+ "gorm.io/gorm"+)++func templateDB(t *testing.T) *gorm.DB {+ t.Helper()+ db := testDB(t)+ if err := db.AutoMigrate(+ &models.User{}, &models.Workspace{}, &models.Template{},+ &models.TemplateVersion{}, &models.TemplateLocalization{},+ ); err != nil {+ t.Skipf("skipping: cannot migrate schema: %v", err)+ }+ return 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}+ if err := tx.Create(ws).Error; err != nil {+ t.Fatalf("workspace: %v", err)+ }+ return userID, ws.ID+}++// The list renders the active version number. Without the preload it had+// nothing to read and printed "v?" against every template that had one.+func TestFindByScopePreloadsActiveVersion(t *testing.T) {+ db := templateDB(t)+ tx := db.Begin()+ t.Cleanup(func() { tx.Rollback() })++ userID, wsID := seedTemplateWorkspace(t, tx, "tmpl-preload")+ repo := &TemplateRepository{db: tx}++ tmpl := &models.Template{UserID: userID, WorkspaceID: &wsID, Name: "Welcome", DefaultLanguage: "en"}+ if err := repo.CreateWithVersions(tmpl, []ImportVersion{+ {SampleData: "{}"},+ {SampleData: "{}", IsActive: true},+ }); err != nil {+ t.Fatalf("create: %v", err)+ }++ items, total, err := repo.FindByScope(ResourceScope{UserID: userID, WorkspaceID: &wsID}, "", 20, 0)+ if err != nil {+ t.Fatalf("list: %v", err)+ }+ if total != 1 || len(items) != 1 {+ t.Fatalf("expected 1 template, got %d (total %d)", len(items), total)+ }+ if items[0].ActiveVersion == nil {+ t.Fatal("active version was not preloaded; the list can only render \"v?\"")+ }+ if items[0].ActiveVersion.Version != 2 {+ t.Errorf("expected the explicitly active version 2, got v%d", items[0].ActiveVersion.Version)+ }+}++// A template with no active version can never be sent. Creating the rows+// separately left exactly that behind whenever a later step failed.+func TestCreateWithVersionsIsAtomic(t *testing.T) {+ db := templateDB(t)+ tx := db.Begin()+ t.Cleanup(func() { tx.Rollback() })++ userID, wsID := seedTemplateWorkspace(t, tx, "tmpl-atomic")+ repo := &TemplateRepository{db: tx}++ // 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"}+ err := repo.CreateWithVersions(tmpl, []ImportVersion{+ {Localizations: []ImportLocalization{+ {Language: "en", SubjectTemplate: "Hi"},+ {Language: "en", SubjectTemplate: "Hi again"},+ }},+ })+ if err == nil {+ t.Fatal("expected the duplicate language to be rejected")+ }++ var templates int64+ tx.Model(&models.Template{}).Where("workspace_id = ?", wsID).Count(&templates)+ if templates != 0 {+ t.Errorf("a failed create left %d template(s) behind", templates)+ }+ var versions int64+ tx.Model(&models.TemplateVersion{}).Where("template_id = ?", tmpl.ID).Count(&versions)+ if versions != 0 {+ t.Errorf("a failed create left %d version(s) behind", versions)+ }+ var locs int64+ tx.Model(&models.TemplateLocalization{}).+ Where("version_id IN (SELECT id FROM template_versions WHERE template_id = ?)", tmpl.ID).+ Count(&locs)+ if locs != 0 {+ t.Errorf("a failed create left %d localization(s) behind", locs)+ }+}++// Every successful create must leave the template immediately usable.+func TestCreateAlwaysActivatesAVersion(t *testing.T) {+ db := templateDB(t)+ tx := db.Begin()+ t.Cleanup(func() { tx.Rollback() })++ userID, wsID := seedTemplateWorkspace(t, tx, "tmpl-active")+ 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"}+ if err := repo.CreateWithVersions(tmpl, []ImportVersion{{SampleData: "{}"}, {SampleData: "{}"}}); err != nil {+ t.Fatalf("create: %v", err)+ }+ if tmpl.ActiveVersionID == nil {+ t.Fatal("no version was activated; the template could never be sent")+ }++ stored, err := repo.FindByIDWithActors(tmpl.ID)+ if err != nil {+ t.Fatalf("reload: %v", err)+ }+ if stored.ActiveVersionID == nil || *stored.ActiveVersionID != *tmpl.ActiveVersionID {+ t.Error("the activation pointer was not persisted")+ }+ if stored.ActiveVersion == nil || stored.ActiveVersion.Version != 1 {+ t.Error("expected the first version to be activated by default")+ }+}++// Versions are numbered from 1 in source order, so an import reproduces the+// ordering it was given.+func TestImportedVersionsAreNumberedInOrder(t *testing.T) {+ db := templateDB(t)+ tx := db.Begin()+ t.Cleanup(func() { tx.Rollback() })++ userID, wsID := seedTemplateWorkspace(t, tx, "tmpl-order")+ repo := &TemplateRepository{db: tx}++ 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)+ }++ var versions []models.TemplateVersion+ tx.Where("template_id = ?", tmpl.ID).Order("version ASC").Find(&versions)+ if len(versions) != 3 {+ t.Fatalf("expected 3 versions, got %d", len(versions))+ }+ for i, v := range versions {+ if v.Version != i+1 {+ t.Errorf("version %d numbered %d", i, v.Version)+ }+ }+ if tmpl.ActiveVersionID == nil || *tmpl.ActiveVersionID != versions[2].ID {+ t.Error("the explicitly active version should win over the first")+ }+}++// The builder document has to survive creation, or a template designed visually+// comes back editable only as raw HTML.+func TestBuilderJSONSurvivesCreate(t *testing.T) {+ db := templateDB(t)+ tx := db.Begin()+ t.Cleanup(func() { tx.Rollback() })++ userID, wsID := seedTemplateWorkspace(t, tx, "tmpl-builder")+ repo := &TemplateRepository{db: tx}++ const doc = `{"pages":[{"component":"hero"}]}`+ tmpl := &models.Template{UserID: userID, WorkspaceID: &wsID, Name: "Designed", DefaultLanguage: "en"}+ if err := repo.CreateWithVersions(tmpl, []ImportVersion{{+ IsActive: true,+ Localizations: []ImportLocalization{+ {Language: "en", SubjectTemplate: "Hello", HTMLTemplate: "<p>hi</p>", BuilderJSON: doc},+ },+ }}); err != nil {+ t.Fatalf("create: %v", err)+ }++ var loc models.TemplateLocalization+ if err := tx.Where("version_id = ?", *tmpl.ActiveVersionID).First(&loc).Error; err != nil {+ t.Fatalf("localization: %v", err)+ }+ if loc.BuilderJSON != doc {+ t.Errorf("builder document lost: got %q", loc.BuilderJSON)+ }+}++// A duplicate name has to be recognisable so the API can answer with a conflict+// naming the problem instead of a generic failure.+func TestDuplicateNameIsDetectable(t *testing.T) {+ db := templateDB(t)+ tx := db.Begin()+ t.Cleanup(func() { tx.Rollback() })++ userID, wsID := seedTemplateWorkspace(t, tx, "tmpl-dupe")+ repo := &TemplateRepository{db: tx}++ 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)+ }++ // The unique index lives in constraints.go, not the model, so AutoMigrate+ // alone does not create it; add it here to exercise the real behaviour.+ if err := tx.Exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_workspace_template+ ON templates (workspace_id, name) WHERE workspace_id IS NOT NULL`).Error; err != nil {+ t.Skipf("cannot create the unique index: %v", err)+ }++ 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")+ }+ if !IsDuplicateName(err) {+ t.Errorf("IsDuplicateName did not recognise the violation: %v", err)+ }+}++// The list shows which languages a template is actually translated into. It has+// to read the active version only: languages from an older version would claim+// coverage the template no longer sends.+func TestLanguagesForActiveVersions(t *testing.T) {+ db := templateDB(t)+ tx := db.Begin()+ t.Cleanup(func() { tx.Rollback() })++ userID, wsID := seedTemplateWorkspace(t, tx, "tmpl-langs")+ repo := &TemplateRepository{db: tx}++ 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{+ {Language: "fr", SubjectTemplate: "Bonjour"},+ {Language: "en", SubjectTemplate: "Hello"},+ }},+ }); err != nil {+ t.Fatalf("create: %v", err)+ }++ 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)+ }++ got, err := repo.LanguagesForActiveVersions([]uint{tmpl.ID, empty.ID})+ if err != nil {+ t.Fatalf("languages: %v", err)+ }++ langs := got[tmpl.ID]+ if len(langs) != 2 || langs[0] != "en" || langs[1] != "fr" {+ t.Errorf("expected [en fr] sorted, got %v", langs)+ }+ if _, ok := got[empty.ID]; ok {+ t.Errorf("a template with no localizations should have no languages, got %v", got[empty.ID])+ }+}++func TestLanguagesForNoTemplates(t *testing.T) {+ db := templateDB(t)+ repo := &TemplateRepository{db: db}+ got, err := repo.LanguagesForActiveVersions(nil)+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if len(got) != 0 {+ t.Errorf("expected an empty map, got %v", got)+ }+}diff --git a/web/src/api/templates.ts b/web/src/api/templates.tsindex 565137c..d275d89 100644--- a/web/src/api/templates.ts+++ b/web/src/api/templates.ts@@ -3,6 +3,7 @@ import type {ApiResponse,PaginatedResponse,Template,+ TemplateListItem,TemplateInput,TemplateExport,TemplatePreview,@@ -16,7 +17,7 @@ import type {export const templatesApi = {list(page = 0, size = 20, search = '') {- return api.get<PaginatedResponse<Template>>('/workspaces/current/templates', { params: { page, size, search } })+ return api.get<PaginatedResponse<TemplateListItem>>('/workspaces/current/templates', { params: { page, size, search } })},get(id: number) {return api.get<ApiResponse<Template>>(`/workspaces/current/templates/${id}`)diff --git a/web/src/api/types.ts b/web/src/api/types.tsindex 7aab17a..5e08854 100644--- a/web/src/api/types.ts+++ b/web/src/api/types.ts@@ -168,6 +168,11 @@ export interface SMTPCredentialCreateResponse {message: string}+/** A template as the list returns it: the record plus the languages it is translated into. */+export interface TemplateListItem extends Template {+ languages: string[]+}+export interface ActorRef {id: numbername: stringdiff --git a/web/src/composables/apiError.ts b/web/src/composables/apiError.tsindex d2c3ce8..07dfc1d 100644--- a/web/src/composables/apiError.ts+++ b/web/src/composables/apiError.ts@@ -1,5 +1,42 @@+// Status phrases the server sends as `error.message` when it has nothing more+// specific to say. Showing one of these to a user is no better than showing+// nothing, so the more detailed `error.error` is preferred whenever the message+// is only the status text — that is where a bind or validation failure explains+// itself.+const GENERIC = new Set([+ 'bad request',+ 'unauthorized',+ 'forbidden',+ 'not found',+ 'method not allowed',+ 'conflict',+ 'unprocessable entity',+ 'too many requests',+ 'internal server error',+ 'bad gateway',+ 'service unavailable',+ 'error',+])++function usable(value: unknown): string {+ return typeof value === 'string' && value.trim() ? value.trim() : ''+}++function specific(value: unknown): string {+ const text = usable(value)+ return text && !GENERIC.has(text.toLowerCase()) ? text : ''+}+export function apiMessage(e: any, fallback: string): string {const data = e?.response?.data- const message = data?.error?.message || data?.error?.error || data?.message- return typeof message === 'string' && message.trim() ? message : fallback++ // A message the handler wrote itself wins; the status phrase is a last resort+ // ahead of the caller's fallback only because it at least names the failure.+ return (+ specific(data?.error?.message) ||+ specific(data?.error?.error) ||+ specific(data?.message) ||+ specific(data?.details) ||+ fallback+ )}diff --git a/web/src/views/templates/TemplateDetail.vue b/web/src/views/templates/TemplateDetail.vueindex 6e5fcd6..e2fd1a6 100644--- a/web/src/views/templates/TemplateDetail.vue+++ b/web/src/views/templates/TemplateDetail.vue@@ -18,6 +18,7 @@ import { useNotificationStore } from "../../stores/notification";import { useConfirm } from "../../composables/useConfirm";import { useModalSafeClose } from "../../composables/useModalSafeClose";import { useWorkspaceStore } from "../../stores/workspace";+import { apiMessage } from "../../composables/apiError";import TemplateModal from "@/components/TemplateModal.vue";const route = useRoute();@@ -123,8 +124,8 @@ async function loadAll() {);selectVersion(active || versions.value[0]);}- } catch {- notify.error("Failed to load template");+ } catch (e: any) {+ notify.error(apiMessage(e, "Failed to load template"));} finally {loading.value = false;}@@ -153,8 +154,8 @@ async function createVersion() {selectVersion(res.data.data);notify.success(`Version ${res.data.data.version} created`);newVersionStylesheetId.value = null;- } catch {- notify.error("Failed to create version");+ } catch (e: any) {+ notify.error(apiMessage(e, "Failed to create version"));} finally {creatingVersion.value = false;}@@ -180,8 +181,8 @@ async function saveVersionStylesheet() {}notify.success("Version stylesheet updated");showVersionStylesheetModal.value = false;- } catch {- notify.error("Failed to update version stylesheet");+ } catch (e: any) {+ notify.error(apiMessage(e, "Failed to update version stylesheet"));} finally {savingVersionStylesheet.value = false;}@@ -192,8 +193,8 @@ async function activateVersion(v: TemplateVersion) {const res = await templatesApi.activateVersion(templateId, v.id);template.value = res.data.data;notify.success(`Version ${v.version} activated`);- } catch {- notify.error("Failed to activate version");+ } catch (e: any) {+ notify.error(apiMessage(e, "Failed to activate version"));}}@@ -218,8 +219,8 @@ async function deleteVersion(v: TemplateVersion) {else localizations.value = [];}notify.success("Version deleted");- } catch {- notify.error("Failed to delete version");+ } catch (e: any) {+ notify.error(apiMessage(e, "Failed to delete version"));}}@@ -269,11 +270,12 @@ async function saveLoc() {}syncLocalizationsToVersion();showLocModal.value = false;- } catch {+ } catch (e: any) {notify.error(- editingLoc.value- ? "Failed to update localization"- : "Language already exists for this version"+ apiMessage(+ e,+ editingLoc.value ? "Failed to update localization" : "Failed to add the localization"+ ));} finally {savingLoc.value = false;@@ -293,8 +295,8 @@ async function deleteLoc(l: TemplateLocalization) {localizations.value = localizations.value.filter((x) => x.id !== l.id);syncLocalizationsToVersion();notify.success("Localization deleted");- } catch {- notify.error("Failed to delete localization");+ } catch (e: any) {+ notify.error(apiMessage(e, "Failed to delete localization"));}}@@ -324,7 +326,7 @@ async function renderPreview() {);preview.value = res.data.data;} catch (e: any) {- previewError.value = e.response?.data?.error?.message || "Failed to render preview";+ previewError.value = apiMessage(e, "Failed to render preview");} finally {previewLoading.value = false;}@@ -370,7 +372,7 @@ async function sendTest() {notify.success("Test email sent");showSendTest.value = false;} catch (e: any) {- notify.error(e.response?.data?.error?.message || "Failed to send test email");+ notify.error(apiMessage(e, "Failed to send test email"));} finally {sendingTest.value = false;}@@ -410,10 +412,8 @@ async function saveTemplate() {closeActiveModal();loadAll()- } catch {- notify.error(- "Failed to update template"- );+ } catch (e: any) {+ notify.error(apiMessage(e, "Failed to update template"));} finally {savingTemplate.value = false;}diff --git a/web/src/views/templates/Templates.vue b/web/src/views/templates/Templates.vueindex f52c8c6..8ce3bbc 100644--- a/web/src/views/templates/Templates.vue+++ b/web/src/views/templates/Templates.vue@@ -5,6 +5,7 @@ import { templatesApi } from "../../api/templates";import { languagesApi } from "../../api/languages";import type {Template,+ TemplateListItem,TemplateInput,TemplateExport,Language,@@ -14,6 +15,7 @@ import { useNotificationStore } from "../../stores/notification";import { useConfirm } from "../../composables/useConfirm";import { useModalSafeClose } from "../../composables/useModalSafeClose";import { useWorkspaceStore } from "../../stores/workspace";+import { apiMessage } from "../../composables/apiError";import { usePagination } from '@/composables/usePagination'import Pagination from '@/components/Pagination.vue'import TemplateModal from "@/components/TemplateModal.vue";@@ -23,7 +25,7 @@ const notify = useNotificationStore();const wsStore = useWorkspaceStore();const { confirm } = useConfirm();-const templates = ref<Template[]>([]);+const templates = ref<TemplateListItem[]>([]);const loading = ref(true);const search = ref("");let searchTimeout: ReturnType<typeof setTimeout> | null = null;@@ -82,8 +84,8 @@ const { pageable, goToPage } = usePagination(async (page) => {const res = await templatesApi.list(page, pageable.value.size, search.value);templates.value = res.data.data;pageable.value = res.data.pageable;- } catch (e) {- console.error('Failed to load templates', e)+ } catch (e: any) {+ notify.error(apiMessage(e, 'Failed to load templates'))} finally {loading.value = false}@@ -106,9 +108,9 @@ async function saveTemplate() {}closeModal();await goToPage(pageable.value.current_page);- } catch {+ } catch (e: any) {notify.error(- editing.value ? "Failed to update template" : "Failed to create template"+ apiMessage(e, editing.value ? "Failed to update template" : "Failed to create template"));} finally {saving.value = false;@@ -127,8 +129,8 @@ async function deleteTemplate(template: Template) {await templatesApi.delete(template.id);notify.success("Template deleted");await goToPage(pageable.value.current_page);- } catch {- notify.error("Failed to delete template");+ } catch (e: any) {+ notify.error(apiMessage(e, "Failed to delete template"));}}@@ -144,8 +146,8 @@ async function exportTemplate(template: Template) {a.click();URL.revokeObjectURL(url);notify.success("Template exported");- } catch {- notify.error("Failed to export template");+ } catch (e: any) {+ notify.error(apiMessage(e, "Failed to export template"));}}@@ -175,10 +177,7 @@ async function handleImportFile(event: Event) {}await goToPage(pageable.value.current_page);} catch (e: any) {- const msg =- e?.response?.data?.message ||- "Failed to import template. Please check the file format.";- notify.error(msg);+ notify.error(apiMessage(e, "Failed to import template. Check the file format."));} finally {importing.value = false;input.value = "";@@ -263,9 +262,9 @@ onMounted(() => {<thead><tr><th>Name</th>- <th>Language</th>- <th>Active Version</th>- <th>Created</th>+ <th>Languages</th>+ <th>Version</th>+ <th>Last edited</th><th>Actions</th></tr></thead>@@ -285,28 +284,37 @@ onMounted(() => {</div></td><td>- <span class="badge badge-neutral">{{ tmpl.default_language }}</span>+ <div class="langs">+ <span+ v-for="lang in tmpl.languages"+ :key="lang"+ class="badge"+ :class="lang === tmpl.default_language ? 'badge-success' : 'badge-neutral'"+ :title="lang === tmpl.default_language ? 'Default language' : ''"+ >+ {{ lang }}+ </span>+ <span v-if="!tmpl.languages.length" class="text-muted text-sm">+ No content yet+ </span>+ </div>+ </td>+ <td>+ <span v-if="tmpl.active_version" class="badge badge-neutral">+ v{{ tmpl.active_version.version }}+ </span>+ <span v-else class="text-muted" title="This template cannot be sent until a version is active">+ —+ </span></td><td>- <span v-if="tmpl.active_version_id" class="badge badge-success"- >v{{ tmpl.active_version?.version || "?" }}</span- >- <span v-else class="text-muted">—</span>+ <div>{{ formatDate(tmpl.updated_at || tmpl.created_at) }}</div>+ <div v-if="tmpl.last_edited_by?.name" class="text-muted text-sm">+ by {{ tmpl.last_edited_by.name }}+ </div></td>- <td>{{ formatDate(tmpl.created_at) }}</td><td><div class="flex gap-2">- <button- class="btn btn-primary btn-sm"- @click.stop="- router.push({- name: 'template-detail',- params: { id: tmpl.id },- })- "- >- Versions- </button><buttonclass="btn btn-secondary btn-sm"@click.stop="@@ -357,3 +365,12 @@ onMounted(() => {</div></template>++<style scoped>+.langs {+ display: flex;+ gap: 4px;+ flex-wrap: wrap;+ max-width: 220px;+}+</style>