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(templates): track creator and last editor

Jonas Kaninda7288d6786452
diff --git a/internal/handlers/template_handler.go b/internal/handlers/template_handler.go
index 22d30bb..6347bc0 100644
--- a/internal/handlers/template_handler.go
+++ b/internal/handlers/template_handler.go
@@ -41,7 +41,7 @@ type TemplateHandler struct {
type CreateTemplateRequest struct {
Body struct {
Name string `json:"name" required:"true"`
- SampleData string `json:"sample_data"`
+ SampleData string `json:"sample_data" default:"{}"`
DefaultLanguage string `json:"default_language"`
Description string `json:"description"`
} `json:"body"`
@@ -50,11 +50,14 @@ type UpdateTemplateRequest struct {
ID int `param:"id"`
Body struct {
Name string `json:"name"`
- SampleData *string `json:"sample_data"`
+ SampleData *string `json:"sample_data" default:"{}"`
DefaultLanguage string `json:"default_language"`
Description *string `json:"description"`
} `json:"body"`
}
+type GetTemplateRequest struct {
+ ID int `param:"id"`
+}
type DeleteTemplateRequest struct {
ID int `param:"id"`
}
@@ -109,6 +112,7 @@ func (h *TemplateHandler) Create(c *okapi.Context, req *CreateTemplateRequest) e
DefaultLanguage: defaultLang,
Description: req.Body.Description,
SampleData: req.Body.SampleData,
+ LastEditedByID: &scope.UserID,
}
if err := h.repo.Create(tmpl); err != nil {
@@ -157,11 +161,18 @@ func (h *TemplateHandler) Update(c *okapi.Context, req *UpdateTemplateRequest) e
now := time.Now()
tmpl.UpdatedAt = &now
+ editorID := getScope(c).UserID
+ tmpl.LastEditedByID = &editorID
if err := h.repo.Update(tmpl); err != nil {
return c.AbortInternalServerError("failed to update template")
}
+ // Reload so the response carries the populated CreatedBy / LastEditedBy refs.
+ if updated, ferr := h.repo.FindByIDWithActors(tmpl.ID); ferr == nil {
+ tmpl = updated
+ }
+
return ok(c, tmpl)
}
@@ -176,6 +187,14 @@ func (h *TemplateHandler) List(c *okapi.Context, req *ListTemplatesRequest) erro
return paginated(c, templates, total, page, size)
}
+func (h *TemplateHandler) Get(c *okapi.Context, req *GetTemplateRequest) error {
+ tmpl, err := h.repo.FindByIDWithActors(uint(req.ID))
+ if err != nil || !ownsResource(c, tmpl.UserID, tmpl.WorkspaceID) {
+ return c.AbortNotFound("template not found")
+ }
+ return ok(c, tmpl)
+}
+
func (h *TemplateHandler) Delete(c *okapi.Context, req *DeleteTemplateRequest) error {
if err := requireEdit(c); err != nil {
return c.AbortForbidden("Insufficient workspace permissions", err)
diff --git a/internal/handlers/template_localization_handler.go b/internal/handlers/template_localization_handler.go
index c34c0bf..68f3354 100644
--- a/internal/handlers/template_localization_handler.go
+++ b/internal/handlers/template_localization_handler.go
@@ -127,6 +127,7 @@ func (h *TemplateLocalizationHandler) Create(c *okapi.Context, req *CreateLocali
if err := h.localizationRepo.Create(l); err != nil {
return c.AbortConflict("localization for this language already exists")
}
+ _ = h.templateRepo.TouchEditor(tmpl.ID, getScope(c).UserID)
return created(c, l)
}
@@ -169,6 +170,7 @@ func (h *TemplateLocalizationHandler) Update(c *okapi.Context, req *UpdateLocali
if err := h.localizationRepo.Update(l); err != nil {
return c.AbortInternalServerError("failed to update localization")
}
+ _ = h.templateRepo.TouchEditor(tmpl.ID, getScope(c).UserID)
return ok(c, l)
}
@@ -194,6 +196,7 @@ func (h *TemplateLocalizationHandler) Delete(c *okapi.Context, req *DeleteLocali
if err := h.localizationRepo.Delete(l.ID); err != nil {
return c.AbortInternalServerError("failed to delete localization")
}
+ _ = h.templateRepo.TouchEditor(tmpl.ID, getScope(c).UserID)
return noContent(c)
}
diff --git a/internal/handlers/template_version_handler.go b/internal/handlers/template_version_handler.go
index 9cbcded..4693232 100644
--- a/internal/handlers/template_version_handler.go
+++ b/internal/handlers/template_version_handler.go
@@ -121,6 +121,7 @@ func (h *TemplateVersionHandler) Create(c *okapi.Context, req *CreateVersionRequ
if err := h.versionRepo.Create(v); err != nil {
return c.AbortInternalServerError("failed to create version")
}
+ _ = h.templateRepo.TouchEditor(tmpl.ID, getScope(c).UserID)
v, _ = h.versionRepo.FindByID(v.ID)
return created(c, v)
@@ -149,6 +150,7 @@ func (h *TemplateVersionHandler) Update(c *okapi.Context, req *UpdateVersionRequ
if err := h.versionRepo.Update(v); err != nil {
return c.AbortInternalServerError("failed to update version")
}
+ _ = h.templateRepo.TouchEditor(tmpl.ID, getScope(c).UserID)
// Reload to get the stylesheet association
v, _ = h.versionRepo.FindByID(v.ID)
@@ -173,11 +175,17 @@ func (h *TemplateVersionHandler) Activate(c *okapi.Context, req *ActivateVersion
tmpl.ActiveVersionID = &vID
now := time.Now()
tmpl.UpdatedAt = &now
+ editorID := getScope(c).UserID
+ tmpl.LastEditedByID = &editorID
if err := h.templateRepo.Update(tmpl); err != nil {
return c.AbortInternalServerError("failed to activate version")
}
+ if updated, ferr := h.templateRepo.FindByIDWithActors(tmpl.ID); ferr == nil {
+ tmpl = updated
+ }
+
return ok(c, tmpl)
}
@@ -203,6 +211,7 @@ func (h *TemplateVersionHandler) Delete(c *okapi.Context, req *DeleteVersionRequ
if err := h.versionRepo.Delete(v.ID); err != nil {
return c.AbortInternalServerError("failed to delete version")
}
+ _ = h.templateRepo.TouchEditor(tmpl.ID, getScope(c).UserID)
return noContent(c)
}
diff --git a/internal/models/actor.go b/internal/models/actor.go
new file mode 100644
index 0000000..feaf976
--- /dev/null
+++ b/internal/models/actor.go
@@ -0,0 +1,25 @@
+/*
+ * Copyright 2026 Jonas Kaninda
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package models
+
+type ActorRef struct {
+ ID uint `json:"id"`
+ Name string `json:"name"`
+}
+
+func (ActorRef) TableName() string { return "users" }
diff --git a/internal/models/template.go b/internal/models/template.go
index d4c7221..3acc41e 100644
--- a/internal/models/template.go
+++ b/internal/models/template.go
@@ -28,9 +28,12 @@ type Template struct {
ActiveVersionID *uint `json:"active_version_id,omitempty" gorm:"uniqueIndex"`
Description string `json:"description"`
SampleData string `json:"sample_data"`
+ LastEditedByID *uint `json:"last_edited_by_id,omitempty" gorm:"index"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt *time.Time `json:"updated_at,omitempty"`
User User `json:"-" gorm:"foreignKey:UserID"`
ActiveVersion *TemplateVersion `json:"active_version,omitempty" gorm:"foreignKey:ActiveVersionID;constraint:false"`
+ CreatedBy *ActorRef `json:"created_by,omitempty" gorm:"foreignKey:UserID;references:ID;constraint:false"`
+ LastEditedBy *ActorRef `json:"last_edited_by,omitempty" gorm:"foreignKey:LastEditedByID;references:ID;constraint:false"`
}
diff --git a/internal/routes/workspace_resource_routes.go b/internal/routes/workspace_resource_routes.go
index 60c034d..755e5da 100644
--- a/internal/routes/workspace_resource_routes.go
+++ b/internal/routes/workspace_resource_routes.go
@@ -205,9 +205,22 @@ func (r *Router) workspaceResourceRoutes() []okapi.RouteDefinition {
Request: &handlers.ListTemplatesRequest{},
Response: &dto.PageableResponse[models.Template]{},
},
+ {
+ Method: http.MethodGet,
+ Path: "/templates/{id}",
+ Handler: okapi.H(r.h.template.Get),
+ Group: opsGroup,
+ Summary: "Get template",
+ Request: &handlers.GetTemplateRequest{},
+ Response: &dto.Response[models.Template]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Template ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
{
Method: http.MethodPut,
- Path: "/templates/{id:int}",
+ Path: "/templates/{id}",
Handler: okapi.H(r.h.template.Update),
Group: opsGroup,
Summary: "Update template",
diff --git a/internal/storage/repositories/template_attribution_test.go b/internal/storage/repositories/template_attribution_test.go
new file mode 100644
index 0000000..79f4e74
--- /dev/null
+++ b/internal/storage/repositories/template_attribution_test.go
@@ -0,0 +1,86 @@
+/*
+ * Copyright 2026 Jonas Kaninda
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package repositories
+
+import (
+ "testing"
+
+ "github.com/goposta/posta/internal/models"
+)
+
+func TestTemplateAttribution(t *testing.T) {
+ db := testDB(t)
+ if err := db.AutoMigrate(&models.Template{}); err != nil {
+ t.Skipf("skipping: cannot migrate templates: %v", err)
+ }
+ tx := db.Begin()
+ defer tx.Rollback()
+
+ creator := createUser(t, tx, "[email protected]")
+ editor := createUser(t, tx, "[email protected]")
+ repo := &TemplateRepository{db: tx}
+
+ tmpl := &models.Template{UserID: creator, Name: "Attr", LastEditedByID: &creator}
+ if err := repo.Create(tmpl); err != nil {
+ t.Fatalf("create template: %v", err)
+ }
+
+ // Initially both creator and last editor are the creator.
+ got, err := repo.FindByIDWithActors(tmpl.ID)
+ if err != nil {
+ t.Fatalf("find by id: %v", err)
+ }
+ if got.CreatedBy == nil || got.CreatedBy.ID != creator {
+ t.Fatalf("CreatedBy = %+v, want id %d", got.CreatedBy, creator)
+ }
+ if got.CreatedBy.Name != "test" {
+ t.Errorf("CreatedBy.Name = %q, want %q", got.CreatedBy.Name, "test")
+ }
+ if got.LastEditedBy == nil || got.LastEditedBy.ID != creator {
+ t.Fatalf("LastEditedBy = %+v, want id %d", got.LastEditedBy, creator)
+ }
+
+ if err := repo.TouchEditor(tmpl.ID, editor); err != nil {
+ t.Fatalf("touch editor: %v", err)
+ }
+ got, err = repo.FindByIDWithActors(tmpl.ID)
+ if err != nil {
+ t.Fatalf("find by id after touch: %v", err)
+ }
+ if got.CreatedBy.ID != creator {
+ t.Errorf("CreatedBy.ID = %d, want %d (creator must not change)", got.CreatedBy.ID, creator)
+ }
+ if got.LastEditedBy == nil || got.LastEditedBy.ID != editor {
+ t.Fatalf("LastEditedBy = %+v, want id %d", got.LastEditedBy, editor)
+ }
+
+ got.Name = "Attr Renamed"
+ if err := repo.Update(got); err != nil {
+ t.Fatalf("update preloaded template: %v", err)
+ }
+ reloaded, err := repo.FindByIDWithActors(tmpl.ID)
+ 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.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 b0c4351..93f1bd2 100644
--- a/internal/storage/repositories/template_repo.go
+++ b/internal/storage/repositories/template_repo.go
@@ -18,8 +18,11 @@
package repositories
import (
+ "time"
+
"github.com/goposta/posta/internal/models"
"gorm.io/gorm"
+ "gorm.io/gorm/clause"
)
type TemplateRepository struct {
@@ -35,7 +38,7 @@ func (r *TemplateRepository) Create(tmpl *models.Template) error {
}
func (r *TemplateRepository) Update(tmpl *models.Template) error {
- return r.db.Save(tmpl).Error
+ return r.db.Omit(clause.Associations).Save(tmpl).Error
}
func (r *TemplateRepository) Delete(id uint) error {
@@ -50,6 +53,19 @@ func (r *TemplateRepository) FindByID(id uint) (*models.Template, error) {
return &tmpl, nil
}
+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 {
+ return nil, err
+ }
+ return &tmpl, nil
+}
+
+func (r *TemplateRepository) TouchEditor(id, editorID uint) error {
+ return r.db.Model(&models.Template{}).Where("id = ?", id).
+ 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 {
diff --git a/web/src/api/templates.ts b/web/src/api/templates.ts
index 97bc1f8..565137c 100644
--- a/web/src/api/templates.ts
+++ b/web/src/api/templates.ts
@@ -18,6 +18,9 @@ export const templatesApi = {
list(page = 0, size = 20, search = '') {
return api.get<PaginatedResponse<Template>>('/workspaces/current/templates', { params: { page, size, search } })
},
+ get(id: number) {
+ return api.get<ApiResponse<Template>>(`/workspaces/current/templates/${id}`)
+ },
create(data: TemplateInput) {
return api.post<ApiResponse<Template>>('/workspaces/current/templates', data)
},
diff --git a/web/src/api/types.ts b/web/src/api/types.ts
index 4ffa4d7..918c1e8 100644
--- a/web/src/api/types.ts
+++ b/web/src/api/types.ts
@@ -141,6 +141,11 @@ export interface ApiKeyCreateResponse {
message: string
}
+export interface ActorRef {
+ id: number
+ name: string
+}
+
export interface Template {
id: number
user_id: number
@@ -150,6 +155,9 @@ export interface Template {
description: string
active_version?: TemplateVersion | null
sample_data: string
+ last_edited_by_id?: number | null
+ created_by?: ActorRef | null
+ last_edited_by?: ActorRef | null
created_at: string
updated_at?: string
}
diff --git a/web/src/views/templates/TemplateDetail.vue b/web/src/views/templates/TemplateDetail.vue
index 9453d9c..6e5fcd6 100644
--- a/web/src/views/templates/TemplateDetail.vue
+++ b/web/src/views/templates/TemplateDetail.vue
@@ -101,12 +101,12 @@ async function loadAll() {
loading.value = true;
try {
const [tmplRes, versionsRes, ssRes, langRes] = await Promise.all([
- templatesApi.list(0, 100),
+ templatesApi.get(templateId),
templatesApi.listVersions(templateId),
stylesheetsApi.list(0, 100),
languagesApi.list(0, 100),
]);
- template.value = tmplRes.data.data.find((t: Template) => t.id === templateId) || null;
+ template.value = tmplRes.data.data || null;
versions.value = versionsRes.data.data || [];
stylesheets.value = ssRes.data.data || [];
languages.value = langRes.data.data || [];
@@ -520,6 +520,18 @@ onMounted(loadAll);
<td class="info-label">Created</td>
<td>{{ formatDate(template.created_at) }}</td>
</tr>
+ <tr v-if="template.created_by">
+ <td class="info-label">Created by</td>
+ <td>{{ template.created_by.name }}</td>
+ </tr>
+ <tr v-if="template.last_edited_by">
+ <td class="info-label">Last edited by</td>
+ <td>
+ {{ template.last_edited_by.name }}
+ <span v-if="template.updated_at" class="text-muted">
+ · {{ formatDate(template.updated_at) }}</span>
+ </td>
+ </tr>
</tbody>
</table>
</div>