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: add Email preview endpoint, render template with variables, return HTML without sending add user Data Export/Import feat: add session management feat: add daily sent/failed counts with delivery rate %, filling all days in range

Jonas Kaninda8888d6da3589
diff --git a/internal/handlers/analytics_handler.go b/internal/handlers/analytics_handler.go
index 764fd6d..4bffd3d 100644
--- a/internal/handlers/analytics_handler.go
+++ b/internal/handlers/analytics_handler.go
@@ -52,6 +52,17 @@ type AnalyticsResponse struct {
StatusBreakdown []repositories.StatusBreakdown `json:"status_breakdown"`
}
+type DashboardAnalyticsRequest struct {
+ From string `query:"from"`
+ To string `query:"to"`
+}
+
+type DashboardAnalyticsResponse struct {
+ DeliveryRateTrends []repositories.DeliveryRatePoint `json:"delivery_rate_trends"`
+ BounceRateTrends []repositories.BounceRatePoint `json:"bounce_rate_trends"`
+ LatencyPercentiles *repositories.LatencyPercentiles `json:"latency_percentiles"`
+}
+
func (h *AnalyticsHandler) UserAnalytics(c *okapi.Context, req *AnalyticsRequest) error {
userID := c.GetInt("user_id")
ctx := c.Request().Context()
@@ -115,6 +126,75 @@ func (h *AnalyticsHandler) AdminAnalytics(c *okapi.Context, req *AnalyticsReques
return ok(c, resp)
}
+func (h *AnalyticsHandler) UserDashboardAnalytics(c *okapi.Context, req *DashboardAnalyticsRequest) error {
+ userID := c.GetInt("user_id")
+ ctx := c.Request().Context()
+
+ cacheKey := cache.DashboardAnalyticsKey(userID, req.From, req.To)
+ var resp DashboardAnalyticsResponse
+ if h.cache.Get(ctx, cacheKey, &resp) {
+ return ok(c, resp)
+ }
+
+ from, to := parseTimeRange(req.From, req.To)
+
+ delivery, err := h.repo.DeliveryRateTrends(uint(userID), from, to)
+ if err != nil {
+ return c.AbortInternalServerError("failed to fetch delivery rate trends")
+ }
+ bounces, err := h.repo.BounceRateTrends(uint(userID), from, to)
+ if err != nil {
+ return c.AbortInternalServerError("failed to fetch bounce rate trends")
+ }
+ latency, err := h.repo.LatencyPercentilesForUser(uint(userID), from, to)
+ if err != nil {
+ return c.AbortInternalServerError("failed to fetch latency percentiles")
+ }
+
+ resp = DashboardAnalyticsResponse{
+ DeliveryRateTrends: delivery,
+ BounceRateTrends: bounces,
+ LatencyPercentiles: latency,
+ }
+
+ h.cache.Set(ctx, cacheKey, resp, cache.AnalyticsTTL)
+ return ok(c, resp)
+}
+
+func (h *AnalyticsHandler) AdminDashboardAnalytics(c *okapi.Context, req *DashboardAnalyticsRequest) error {
+ ctx := c.Request().Context()
+
+ cacheKey := cache.AdminDashboardAnalyticsKey(req.From, req.To)
+ var resp DashboardAnalyticsResponse
+ if h.cache.Get(ctx, cacheKey, &resp) {
+ return ok(c, resp)
+ }
+
+ from, to := parseTimeRange(req.From, req.To)
+
+ delivery, err := h.repo.AdminDeliveryRateTrends(from, to)
+ if err != nil {
+ return c.AbortInternalServerError("failed to fetch delivery rate trends")
+ }
+ bounces, err := h.repo.AdminBounceRateTrends(from, to)
+ if err != nil {
+ return c.AbortInternalServerError("failed to fetch bounce rate trends")
+ }
+ latency, err := h.repo.AdminLatencyPercentiles(from, to)
+ if err != nil {
+ return c.AbortInternalServerError("failed to fetch latency percentiles")
+ }
+
+ resp = DashboardAnalyticsResponse{
+ DeliveryRateTrends: delivery,
+ BounceRateTrends: bounces,
+ LatencyPercentiles: latency,
+ }
+
+ h.cache.Set(ctx, cacheKey, resp, cache.AnalyticsTTL)
+ return ok(c, resp)
+}
+
func parseTimeRange(fromStr, toStr string) (time.Time, time.Time) {
to := time.Now()
from := to.AddDate(0, 0, -30) // default: last 30 days
diff --git a/internal/handlers/email_handler.go b/internal/handlers/email_handler.go
index c9c4461..a033da9 100644
--- a/internal/handlers/email_handler.go
+++ b/internal/handlers/email_handler.go
@@ -86,6 +86,35 @@ func (h *EmailHandler) redactContent() bool {
return true
}
+type PreviewEmailRequest struct {
+ Body struct {
+ Template string `json:"template" required:"true" doc:"Template name"`
+ Language string `json:"language" doc:"Language code for localization"`
+ TemplateData map[string]any `json:"template_data" doc:"Variables to inject into the template"`
+ } `json:"body"`
+}
+
+type PreviewEmailResponse struct {
+ Subject string `json:"subject"`
+ HTML string `json:"html"`
+ Text string `json:"text"`
+}
+
+func (h *EmailHandler) Preview(c *okapi.Context, req *PreviewEmailRequest) error {
+ userID := c.GetInt("user_id")
+
+ rendered, err := h.service.RenderTemplate(uint(userID), req.Body.Template, req.Body.Language, req.Body.TemplateData)
+ if err != nil {
+ return c.AbortBadRequest(err.Error())
+ }
+
+ return ok(c, PreviewEmailResponse{
+ Subject: rendered.Subject,
+ HTML: rendered.HTML,
+ Text: rendered.Text,
+ })
+}
+
const redactedPlaceholder = "[redacted]"
func redactEmail(em *models.Email) {
diff --git a/internal/handlers/session_handler.go b/internal/handlers/session_handler.go
new file mode 100644
index 0000000..ccbfdaa
--- /dev/null
+++ b/internal/handlers/session_handler.go
@@ -0,0 +1,149 @@
+/*
+ * MIT License
+ *
+ * Copyright (c) 2026 Jonas Kaninda
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+package handlers
+
+import (
+ "fmt"
+
+ "github.com/jkaninda/okapi"
+ "github.com/jkaninda/posta/internal/services/session"
+ "github.com/jkaninda/posta/internal/storage/repositories"
+)
+
+type SessionHandler struct {
+ repo *repositories.SessionRepository
+ store *session.Store
+}
+
+func NewSessionHandler(repo *repositories.SessionRepository, store *session.Store) *SessionHandler {
+ return &SessionHandler{repo: repo, store: store}
+}
+
+// SessionResponse is the API representation of a session.
+type SessionResponse struct {
+ ID uint `json:"id"`
+ IPAddress string `json:"ip_address"`
+ UserAgent string `json:"user_agent"`
+ Current bool `json:"current"`
+ CreatedAt string `json:"created_at"`
+ ExpiresAt string `json:"expires_at"`
+}
+
+type RevokeSessionRequest struct {
+ ID int `param:"id"`
+}
+
+// List returns all active sessions for the current user.
+func (h *SessionHandler) List(c *okapi.Context) error {
+ userID := uint(c.GetInt("user_id"))
+ currentJTI := c.GetString("jti")
+
+ sessions, err := h.repo.FindActiveByUserID(userID)
+ if err != nil {
+ return c.AbortInternalServerError("failed to load sessions")
+ }
+
+ result := make([]SessionResponse, 0, len(sessions))
+ for _, s := range sessions {
+ result = append(result, SessionResponse{
+ ID: s.ID,
+ IPAddress: s.IPAddress,
+ UserAgent: s.UserAgent,
+ Current: s.JTI == currentJTI,
+ CreatedAt: s.CreatedAt.Format("2006-01-02T15:04:05Z"),
+ ExpiresAt: s.ExpiresAt.Format("2006-01-02T15:04:05Z"),
+ })
+ }
+
+ return ok(c, result)
+}
+
+// Revoke terminates a specific session by ID.
+func (h *SessionHandler) Revoke(c *okapi.Context, req *RevokeSessionRequest) error {
+ userID := uint(c.GetInt("user_id"))
+
+ sess, err := h.repo.FindByID(uint(req.ID))
+ if err != nil || sess.UserID != userID {
+ return c.AbortNotFound("session not found")
+ }
+
+ if sess.Revoked {
+ return c.AbortBadRequest("session already revoked")
+ }
+
+ if err := h.repo.Revoke(sess.ID); err != nil {
+ return c.AbortInternalServerError("failed to revoke session")
+ }
+
+ // Add to Redis blacklist for immediate effect
+ h.store.MarkRevoked(c.Request().Context(), sess.JTI, sess.ExpiresAt)
+
+ return ok(c, okapi.M{"message": fmt.Sprintf("Session %d revoked", sess.ID)})
+}
+
+// RevokeOthers revokes all sessions except the current one.
+func (h *SessionHandler) RevokeOthers(c *okapi.Context) error {
+ userID := uint(c.GetInt("user_id"))
+ currentJTI := c.GetString("jti")
+
+ // Get all active sessions first (need JTIs for Redis blacklist)
+ sessions, err := h.repo.FindActiveByUserID(userID)
+ if err != nil {
+ return c.AbortInternalServerError("failed to load sessions")
+ }
+
+ count, err := h.repo.RevokeOthersByUserID(userID, currentJTI)
+ if err != nil {
+ return c.AbortInternalServerError("failed to revoke sessions")
+ }
+
+ // Blacklist each revoked session in Redis
+ for _, s := range sessions {
+ if s.JTI != currentJTI {
+ h.store.MarkRevoked(c.Request().Context(), s.JTI, s.ExpiresAt)
+ }
+ }
+
+ return ok(c, okapi.M{
+ "message": fmt.Sprintf("%d other session(s) revoked", count),
+ "revoked": count,
+ })
+}
+
+// Logout revokes the current session.
+func (h *SessionHandler) Logout(c *okapi.Context) error {
+ currentJTI := c.GetString("jti")
+ if currentJTI == "" {
+ return ok(c, okapi.M{"message": "logged out"})
+ }
+
+ sess, err := h.repo.FindByJTI(currentJTI)
+ if err == nil && sess != nil && !sess.Revoked {
+ _ = h.repo.Revoke(sess.ID)
+ h.store.MarkRevoked(c.Request().Context(), sess.JTI, sess.ExpiresAt)
+ }
+
+ return ok(c, okapi.M{"message": "logged out"})
+}
diff --git a/internal/handlers/user_data_handler.go b/internal/handlers/user_data_handler.go
new file mode 100644
index 0000000..6fd966b
--- /dev/null
+++ b/internal/handlers/user_data_handler.go
@@ -0,0 +1,637 @@
+/*
+ * MIT License
+ *
+ * Copyright (c) 2026 Jonas Kaninda
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+package handlers
+
+import (
+ "fmt"
+ "time"
+
+ "github.com/jkaninda/okapi"
+ "github.com/jkaninda/posta/internal/config"
+ "github.com/jkaninda/posta/internal/models"
+ "github.com/jkaninda/posta/internal/storage/repositories"
+ "gorm.io/gorm"
+)
+
+type UserDataHandler struct {
+ db *gorm.DB
+ templateRepo *repositories.TemplateRepository
+ versionRepo *repositories.TemplateVersionRepository
+ localizationRepo *repositories.TemplateLocalizationRepository
+ stylesheetRepo *repositories.StyleSheetRepository
+ languageRepo *repositories.LanguageRepository
+ contactRepo *repositories.ContactRepository
+ contactListRepo *repositories.ContactListRepository
+ webhookRepo *repositories.WebhookRepository
+ suppressionRepo *repositories.SuppressionRepository
+ userSettingRepo *repositories.UserSettingRepository
+}
+
+func NewUserDataHandler(
+ db *gorm.DB,
+ templateRepo *repositories.TemplateRepository,
+ versionRepo *repositories.TemplateVersionRepository,
+ localizationRepo *repositories.TemplateLocalizationRepository,
+ stylesheetRepo *repositories.StyleSheetRepository,
+ languageRepo *repositories.LanguageRepository,
+ contactRepo *repositories.ContactRepository,
+ contactListRepo *repositories.ContactListRepository,
+ webhookRepo *repositories.WebhookRepository,
+ suppressionRepo *repositories.SuppressionRepository,
+ userSettingRepo *repositories.UserSettingRepository,
+) *UserDataHandler {
+ return &UserDataHandler{
+ db: db,
+ templateRepo: templateRepo,
+ versionRepo: versionRepo,
+ localizationRepo: localizationRepo,
+ stylesheetRepo: stylesheetRepo,
+ languageRepo: languageRepo,
+ contactRepo: contactRepo,
+ contactListRepo: contactListRepo,
+ webhookRepo: webhookRepo,
+ suppressionRepo: suppressionRepo,
+ userSettingRepo: userSettingRepo,
+ }
+}
+
+// --- Export / Import types ---
+
+type UserDataExport struct {
+ PostaVersion string `json:"posta_version"`
+ ExportedAt string `json:"exported_at"`
+ Templates []TemplateExport `json:"templates"`
+ Stylesheets []ExportStyleSheet `json:"stylesheets"`
+ Languages []ExportLanguage `json:"languages"`
+ Contacts []ExportContact `json:"contacts"`
+ ContactLists []ExportContactList `json:"contact_lists"`
+ Suppressions []ExportSuppression `json:"suppressions"`
+ Webhooks []ExportWebhook `json:"webhooks"`
+ Settings *ExportUserSettings `json:"settings,omitempty"`
+}
+
+type ExportStyleSheet struct {
+ Name string `json:"name"`
+ CSS string `json:"css"`
+}
+
+type ExportLanguage struct {
+ Code string `json:"code"`
+ Name string `json:"name"`
+}
+
+type ExportContact struct {
+ Email string `json:"email"`
+ Name string `json:"name"`
+ SentCount int64 `json:"sent_count"`
+ FailCount int64 `json:"fail_count"`
+}
+
+type ExportContactList struct {
+ Name string `json:"name"`
+ Description string `json:"description"`
+ Members []ExportContactMember `json:"members"`
+}
+
+type ExportContactMember struct {
+ Email string `json:"email"`
+ Name string `json:"name"`
+ Data string `json:"data,omitempty"`
+}
+
+type ExportSuppression struct {
+ Email string `json:"email"`
+ Reason string `json:"reason"`
+}
+
+type ExportWebhook struct {
+ URL string `json:"url"`
+ Events []string `json:"events"`
+ Filters []string `json:"filters,omitempty"`
+}
+
+type ExportUserSettings struct {
+ Timezone string `json:"timezone"`
+ DefaultSenderName string `json:"default_sender_name"`
+ DefaultSenderEmail string `json:"default_sender_email"`
+ EmailNotifications bool `json:"email_notifications"`
+ NotificationEmail string `json:"notification_email"`
+ WebhookRetryCount int `json:"webhook_retry_count"`
+ APIKeyExpiryDays int `json:"api_key_expiry_days"`
+ BounceAutoSuppress bool `json:"bounce_auto_suppress"`
+ DailyReport bool `json:"daily_report"`
+}
+
+type ImportUserDataRequest struct {
+ Body UserDataExport `json:"body"`
+}
+
+// --- GDPR types ---
+
+type GDPRDeleteContactsRequest struct {
+ Body struct {
+ Email string `json:"email"`
+ } `json:"body"`
+}
+
+type GDPRDeleteEmailLogsRequest struct {
+ Body struct {
+ OlderThanDays int `json:"older_than_days"`
+ } `json:"body"`
+}
+
+type GDPRDeleteResult struct {
+ Deleted int64 `json:"deleted"`
+ Message string `json:"message"`
+}
+
+// --- Export handler ---
+
+func (h *UserDataHandler) Export(c *okapi.Context) error {
+ userID := uint(c.GetInt("user_id"))
+
+ // Templates (reuse existing TemplateExport struct)
+ templates, _, err := h.templateRepo.FindByUserID(userID, 10000, 0)
+ if err != nil {
+ return c.AbortInternalServerError("failed to load templates")
+ }
+
+ exportTemplates := make([]TemplateExport, 0, len(templates))
+ for _, tmpl := range templates {
+ versions, err := h.versionRepo.FindByTemplateID(tmpl.ID)
+ if err != nil {
+ return c.AbortInternalServerError("failed to load template versions")
+ }
+
+ exportVersions := make([]ExportVersion, 0, len(versions))
+ for _, v := range versions {
+ localizations, err := h.localizationRepo.FindByVersionID(v.ID)
+ if err != nil {
+ return c.AbortInternalServerError("failed to load localizations")
+ }
+
+ exportLocs := make([]ExportLocalization, 0, len(localizations))
+ for _, l := range localizations {
+ exportLocs = append(exportLocs, ExportLocalization{
+ Language: l.Language,
+ SubjectTemplate: l.SubjectTemplate,
+ HTMLTemplate: l.HTMLTemplate,
+ TextTemplate: l.TextTemplate,
+ })
+ }
+
+ isActive := tmpl.ActiveVersionID != nil && *tmpl.ActiveVersionID == v.ID
+ exportVersions = append(exportVersions, ExportVersion{
+ Version: v.Version,
+ SampleData: v.SampleData,
+ IsActive: isActive,
+ Localizations: exportLocs,
+ })
+ }
+
+ exportTemplates = append(exportTemplates, TemplateExport{
+ Name: tmpl.Name,
+ Description: tmpl.Description,
+ DefaultLanguage: tmpl.DefaultLanguage,
+ SampleData: tmpl.SampleData,
+ Versions: exportVersions,
+ })
+ }
+
+ // Stylesheets
+ stylesheets, _, err := h.stylesheetRepo.FindByUserID(userID, 10000, 0)
+ if err != nil {
+ return c.AbortInternalServerError("failed to load stylesheets")
+ }
+ exportStylesheets := make([]ExportStyleSheet, 0, len(stylesheets))
+ for _, ss := range stylesheets {
+ exportStylesheets = append(exportStylesheets, ExportStyleSheet{
+ Name: ss.Name,
+ CSS: ss.CSS,
+ })
+ }
+
+ // Languages
+ languages, _, err := h.languageRepo.FindByUserID(userID, 10000, 0)
+ if err != nil {
+ return c.AbortInternalServerError("failed to load languages")
+ }
+ exportLanguages := make([]ExportLanguage, 0, len(languages))
+ for _, lang := range languages {
+ exportLanguages = append(exportLanguages, ExportLanguage{
+ Code: lang.Code,
+ Name: lang.Name,
+ })
+ }
+
+ // Contacts
+ contacts, _, err := h.contactRepo.FindByUserID(userID, "", 10000, 0)
+ if err != nil {
+ return c.AbortInternalServerError("failed to load contacts")
+ }
+ exportContacts := make([]ExportContact, 0, len(contacts))
+ for _, ct := range contacts {
+ exportContacts = append(exportContacts, ExportContact{
+ Email: ct.Email,
+ Name: ct.Name,
+ SentCount: ct.SentCount,
+ FailCount: ct.FailCount,
+ })
+ }
+
+ // Contact Lists with members
+ contactLists, _, err := h.contactListRepo.FindByUserID(userID, 10000, 0)
+ if err != nil {
+ return c.AbortInternalServerError("failed to load contact lists")
+ }
+ exportContactLists := make([]ExportContactList, 0, len(contactLists))
+ for _, cl := range contactLists {
+ members, _, err := h.contactListRepo.ListMembers(cl.ID, 100000, 0)
+ if err != nil {
+ return c.AbortInternalServerError("failed to load contact list members")
+ }
+ exportMembers := make([]ExportContactMember, 0, len(members))
+ for _, m := range members {
+ exportMembers = append(exportMembers, ExportContactMember{
+ Email: m.Email,
+ Name: m.Name,
+ Data: m.Data,
+ })
+ }
+ exportContactLists = append(exportContactLists, ExportContactList{
+ Name: cl.Name,
+ Description: cl.Description,
+ Members: exportMembers,
+ })
+ }
+
+ // Suppressions
+ suppressions, _, err := h.suppressionRepo.FindByUserID(userID, 10000, 0)
+ if err != nil {
+ return c.AbortInternalServerError("failed to load suppressions")
+ }
+ exportSuppressions := make([]ExportSuppression, 0, len(suppressions))
+ for _, s := range suppressions {
+ exportSuppressions = append(exportSuppressions, ExportSuppression{
+ Email: s.Email,
+ Reason: s.Reason,
+ })
+ }
+
+ // Webhooks
+ webhooks, _, err := h.webhookRepo.FindByUserID(userID, 10000, 0)
+ if err != nil {
+ return c.AbortInternalServerError("failed to load webhooks")
+ }
+ exportWebhooks := make([]ExportWebhook, 0, len(webhooks))
+ for _, wh := range webhooks {
+ exportWebhooks = append(exportWebhooks, ExportWebhook{
+ URL: wh.URL,
+ Events: wh.Events,
+ Filters: wh.Filters,
+ })
+ }
+
+ // User settings
+ var exportSettings *ExportUserSettings
+ settings, err := h.userSettingRepo.FindByUserID(userID)
+ if err == nil && settings != nil {
+ exportSettings = &ExportUserSettings{
+ Timezone: settings.Timezone,
+ DefaultSenderName: settings.DefaultSenderName,
+ DefaultSenderEmail: settings.DefaultSenderEmail,
+ EmailNotifications: settings.EmailNotifications,
+ NotificationEmail: settings.NotificationEmail,
+ WebhookRetryCount: settings.WebhookRetryCount,
+ APIKeyExpiryDays: settings.APIKeyExpiryDays,
+ BounceAutoSuppress: settings.BounceAutoSuppress,
+ DailyReport: settings.DailyReport,
+ }
+ }
+
+ export := UserDataExport{
+ PostaVersion: config.Version,
+ ExportedAt: time.Now().UTC().Format(time.RFC3339),
+ Templates: exportTemplates,
+ Stylesheets: exportStylesheets,
+ Languages: exportLanguages,
+ Contacts: exportContacts,
+ ContactLists: exportContactLists,
+ Suppressions: exportSuppressions,
+ Webhooks: exportWebhooks,
+ Settings: exportSettings,
+ }
+
+ return ok(c, export)
+}
+
+// Import
+
+func (h *UserDataHandler) Import(c *okapi.Context, req *ImportUserDataRequest) error {
+ userID := uint(c.GetInt("user_id"))
+ data := req.Body
+
+ var importedCount int
+
+ for _, lang := range data.Languages {
+ if lang.Code == "" || lang.Name == "" {
+ continue
+ }
+ l := &models.Language{
+ UserID: userID,
+ Code: lang.Code,
+ Name: lang.Name,
+ }
+ if err := h.languageRepo.Create(l); err != nil {
+ continue // skip duplicates
+ }
+ importedCount++
+ }
+
+ // Import stylesheets
+ stylesheetMap := make(map[string]uint) // name -> id for template reference
+ for _, ss := range data.Stylesheets {
+ if ss.Name == "" {
+ continue
+ }
+ s := &models.StyleSheet{
+ UserID: userID,
+ Name: ss.Name,
+ CSS: ss.CSS,
+ }
+ if err := h.stylesheetRepo.Create(s); err != nil {
+ continue // skip duplicates
+ }
+ stylesheetMap[s.Name] = s.ID
+ importedCount++
+ }
+
+ // Import templates (reuse template import logic)
+ for _, tmplData := range data.Templates {
+ if tmplData.Name == "" {
+ continue
+ }
+
+ defaultLang := tmplData.DefaultLanguage
+ if defaultLang == "" {
+ defaultLang = "en"
+ }
+
+ tmpl := &models.Template{
+ UserID: userID,
+ Name: tmplData.Name,
+ DefaultLanguage: defaultLang,
+ Description: tmplData.Description,
+ SampleData: tmplData.SampleData,
+ }
+
+ if err := h.templateRepo.Create(tmpl); err != nil {
+ continue // skip duplicates
+ }
+
+ var activeVersionDBID *uint
+
+ for _, ev := range tmplData.Versions {
+ nextVersion, err := h.versionRepo.NextVersion(tmpl.ID)
+ if err != nil {
+ continue
+ }
+
+ v := &models.TemplateVersion{
+ TemplateID: tmpl.ID,
+ Version: nextVersion,
+ SampleData: ev.SampleData,
+ }
+ if err := h.versionRepo.Create(v); err != nil {
+ continue
+ }
+
+ if ev.IsActive {
+ activeVersionDBID = &v.ID
+ }
+
+ for _, el := range ev.Localizations {
+ l := &models.TemplateLocalization{
+ VersionID: v.ID,
+ Language: el.Language,
+ SubjectTemplate: el.SubjectTemplate,
+ HTMLTemplate: el.HTMLTemplate,
+ TextTemplate: el.TextTemplate,
+ }
+ h.localizationRepo.Create(l)
+ }
+ }
+
+ if len(tmplData.Versions) == 0 {
+ v := &models.TemplateVersion{
+ TemplateID: tmpl.ID,
+ Version: 1,
+ SampleData: tmplData.SampleData,
+ }
+ if err := h.versionRepo.Create(v); err == nil {
+ activeVersionDBID = &v.ID
+ }
+ }
+
+ if activeVersionDBID != nil {
+ tmpl.ActiveVersionID = activeVersionDBID
+ h.templateRepo.Update(tmpl)
+ }
+
+ importedCount++
+ }
+
+ // Import contacts
+ for _, ct := range data.Contacts {
+ if ct.Email == "" {
+ continue
+ }
+ contact := &models.Contact{
+ UserID: userID,
+ Email: ct.Email,
+ Name: ct.Name,
+ SentCount: ct.SentCount,
+ FailCount: ct.FailCount,
+ }
+ if err := h.db.Create(contact).Error; err != nil {
+ continue // skip duplicates
+ }
+ importedCount++
+ }
+
+ // Import contact lists
+ for _, cl := range data.ContactLists {
+ if cl.Name == "" {
+ continue
+ }
+ list := &models.ContactList{
+ UserID: userID,
+ Name: cl.Name,
+ Description: cl.Description,
+ }
+ if err := h.contactListRepo.Create(list); err != nil {
+ continue
+ }
+ for _, m := range cl.Members {
+ member := &models.ContactListMember{
+ ListID: list.ID,
+ Email: m.Email,
+ Name: m.Name,
+ Data: m.Data,
+ }
+ h.contactListRepo.AddMember(member)
+ }
+ importedCount++
+ }
+
+ // Import suppressions
+ for _, s := range data.Suppressions {
+ if s.Email == "" {
+ continue
+ }
+ sup := &models.Suppression{
+ UserID: userID,
+ Email: s.Email,
+ Reason: s.Reason,
+ }
+ h.suppressionRepo.Create(sup)
+ }
+
+ // Import webhooks
+ for _, wh := range data.Webhooks {
+ if wh.URL == "" {
+ continue
+ }
+ webhook := &models.Webhook{
+ UserID: userID,
+ URL: wh.URL,
+ Events: wh.Events,
+ Filters: wh.Filters,
+ }
+ h.db.Create(webhook)
+ }
+
+ // Import settings
+ if data.Settings != nil {
+ settings, err := h.userSettingRepo.FindByUserID(userID)
+ if err == nil && settings != nil {
+ settings.Timezone = data.Settings.Timezone
+ settings.DefaultSenderName = data.Settings.DefaultSenderName
+ settings.DefaultSenderEmail = data.Settings.DefaultSenderEmail
+ settings.EmailNotifications = data.Settings.EmailNotifications
+ settings.NotificationEmail = data.Settings.NotificationEmail
+ settings.WebhookRetryCount = data.Settings.WebhookRetryCount
+ settings.APIKeyExpiryDays = data.Settings.APIKeyExpiryDays
+ settings.BounceAutoSuppress = data.Settings.BounceAutoSuppress
+ settings.DailyReport = data.Settings.DailyReport
+ h.userSettingRepo.CreateOrUpdate(settings)
+ }
+ }
+
+ return ok(c, map[string]any{
+ "message": "Data imported successfully",
+ "imported_count": importedCount,
+ })
+}
+
+// GDPR Delete Contacts
+
+func (h *UserDataHandler) DeleteContacts(c *okapi.Context, req *GDPRDeleteContactsRequest) error {
+ userID := uint(c.GetInt("user_id"))
+ email := req.Body.Email
+
+ if email == "" {
+ // Delete all contacts
+ result := h.db.Where("user_id = ?", userID).Delete(&models.Contact{})
+ if result.Error != nil {
+ return c.AbortInternalServerError("failed to delete contacts")
+ }
+ return ok(c, GDPRDeleteResult{
+ Deleted: result.RowsAffected,
+ Message: "All contacts deleted",
+ })
+ }
+
+ // Delete specific contact by email
+ result := h.db.Where("user_id = ? AND email = ?", userID, email).Delete(&models.Contact{})
+ if result.Error != nil {
+ return c.AbortInternalServerError("failed to delete contact")
+ }
+
+ // Also remove from suppression list
+ h.db.Where("user_id = ? AND email = ?", userID, email).Delete(&models.Suppression{})
+
+ // Also remove from contact list memberships
+ var listIDs []uint
+ h.db.Model(&models.ContactList{}).Where("user_id = ?", userID).Pluck("id", &listIDs)
+ if len(listIDs) > 0 {
+ h.db.Where("list_id IN ? AND email = ?", listIDs, email).Delete(&models.ContactListMember{})
+ }
+
+ return ok(c, GDPRDeleteResult{
+ Deleted: result.RowsAffected,
+ Message: fmt.Sprintf("Contact %s and associated data deleted", email),
+ })
+}
+
+// GDPR Delete Email Logs
+
+func (h *UserDataHandler) DeleteEmailLogs(c *okapi.Context, req *GDPRDeleteEmailLogsRequest) error {
+ userID := uint(c.GetInt("user_id"))
+
+ days := req.Body.OlderThanDays
+ if days <= 0 {
+ days = 0 // delete all
+ }
+
+ query := h.db.Where("user_id = ?", userID)
+ if days > 0 {
+ before := time.Now().AddDate(0, 0, -days)
+ query = query.Where("created_at < ?", before)
+ }
+
+ // Delete bounces for matching emails first
+ var emailIDs []uint
+ query.Model(&models.Email{}).Pluck("id", &emailIDs)
+ if len(emailIDs) > 0 {
+ h.db.Where("email_id IN ?", emailIDs).Delete(&models.Bounce{})
+ }
+
+ // Delete the emails
+ result := query.Delete(&models.Email{})
+ if result.Error != nil {
+ return c.AbortInternalServerError("failed to delete email logs")
+ }
+
+ msg := "All email logs deleted"
+ if days > 0 {
+ msg = fmt.Sprintf("Email logs older than %d days deleted", days)
+ }
+
+ return ok(c, GDPRDeleteResult{
+ Deleted: result.RowsAffected,
+ Message: msg,
+ })
+}
diff --git a/internal/handlers/user_handler.go b/internal/handlers/user_handler.go
index 05d73db..c6b3a9b 100644
--- a/internal/handlers/user_handler.go
+++ b/internal/handlers/user_handler.go
@@ -31,6 +31,7 @@ import (
"strings"
+ "github.com/google/uuid"
"github.com/jkaninda/okapi"
"github.com/jkaninda/posta/internal/dto"
"github.com/jkaninda/posta/internal/models"
@@ -43,11 +44,12 @@ import (
)
type UserHandler struct {
- repo *repositories.UserRepository
- jwtSecret []byte
- seeder *seeder.Seeder
- bus *eventbus.EventBus
- settings *settings.Provider
+ repo *repositories.UserRepository
+ sessionRepo *repositories.SessionRepository
+ jwtSecret []byte
+ seeder *seeder.Seeder
+ bus *eventbus.EventBus
+ settings *settings.Provider
}
func NewUserHandler(repo *repositories.UserRepository, jwtSecret string, seeder *seeder.Seeder, bus *eventbus.EventBus) *UserHandler {
@@ -59,6 +61,12 @@ func NewUserHandler(repo *repositories.UserRepository, jwtSecret string, seeder
}
}
+func (h *UserHandler) SetSessionRepo(repo *repositories.SessionRepository) {
+ h.sessionRepo = repo
+}
+
+const jwtTokenTTL = 24 * time.Hour
+
func (h *UserHandler) SetSettings(s *settings.Provider) {
h.settings = s
}
@@ -188,12 +196,7 @@ func (h *UserHandler) Register(c *okapi.Context, req *RegisterRequest) error {
}
// Auto-login: generate JWT token
- token, err := okapi.GenerateJwtToken(h.jwtSecret, map[string]any{
- "sub": user.ID,
- "email": user.Email,
- "role": string(user.Role),
- "aud": "posta",
- }, 24*time.Hour)
+ token, _, err := h.generateTokenWithSession(c, user)
if err != nil {
return c.AbortInternalServerError("failed to generate token", err)
}
@@ -310,15 +313,11 @@ func (h *UserHandler) Login(c *okapi.Context, req *LoginRequest) error {
fmt.Sprintf("User %q logged in", user.Email), nil)
}
- token, err := okapi.GenerateJwtToken(h.jwtSecret, map[string]any{
- "sub": user.ID,
- "email": user.Email,
- "role": string(user.Role),
- "aud": "posta",
- }, 24*time.Hour)
+ token, jti, err := h.generateTokenWithSession(c, user)
if err != nil {
return c.AbortInternalServerError("failed to generate token", err)
}
+ _ = jti
return ok(c, AuthResponse{
Token: token,
@@ -427,3 +426,37 @@ func (h *UserHandler) Disable2FA(c *okapi.Context, req *Disable2FARequest) error
return ok(c, okapi.M{"message": "2FA disabled successfully"})
}
+
+// generateTokenWithSession creates a JWT with a jti claim and records the session.
+func (h *UserHandler) generateTokenWithSession(c *okapi.Context, user *models.User) (string, string, error) {
+ jti := uuid.NewString()
+
+ token, err := okapi.GenerateJwtToken(h.jwtSecret, map[string]any{
+ "sub": user.ID,
+ "email": user.Email,
+ "role": string(user.Role),
+ "aud": "posta",
+ "jti": jti,
+ }, jwtTokenTTL)
+ if err != nil {
+ return "", "", err
+ }
+
+ // Track session in database
+ if h.sessionRepo != nil {
+ ua := c.Header("User-Agent")
+ if len(ua) > 512 {
+ ua = ua[:512]
+ }
+ session := &models.Session{
+ UserID: user.ID,
+ JTI: jti,
+ IPAddress: c.RealIP(),
+ UserAgent: ua,
+ ExpiresAt: time.Now().Add(jwtTokenTTL),
+ }
+ _ = h.sessionRepo.Create(session)
+ }
+
+ return token, jti, nil
+}
diff --git a/internal/middlewares/middleware.go b/internal/middlewares/middleware.go
index a94f144..b56b777 100644
--- a/internal/middlewares/middleware.go
+++ b/internal/middlewares/middleware.go
@@ -25,13 +25,16 @@
package middlewares
import (
+ "errors"
"net"
"strings"
+ "github.com/golang-jwt/jwt/v5"
"github.com/jkaninda/okapi"
"github.com/jkaninda/posta/internal/config"
"github.com/jkaninda/posta/internal/services/auth"
"github.com/jkaninda/posta/internal/services/ratelimit"
+ sessionpkg "github.com/jkaninda/posta/internal/services/session"
"github.com/jkaninda/posta/internal/storage/repositories"
)
@@ -44,27 +47,56 @@ func baseJWTAuth(cfg *config.Config) okapi.JWTAuth {
"user_id": "sub",
"email": "email",
"role": "role",
+ "jti": "jti",
},
}
}
-// User
-func JWTAuth(cfg *config.Config) okapi.JWTAuth {
- return baseJWTAuth(cfg)
+// sessionValidator returns a ValidateClaims function that checks the Redis blacklist.
+func sessionValidator(store *sessionpkg.Store) func(c *okapi.Context, claims jwt.Claims) error {
+ return func(c *okapi.Context, claims jwt.Claims) error {
+ mapClaims, ok := claims.(jwt.MapClaims)
+ if !ok {
+ return nil // no claims to check
+ }
+ jti, _ := mapClaims["jti"].(string)
+ if jti == "" {
+ return nil // legacy token without jti, allow through
+ }
+ if store.IsRevoked(c.Request().Context(), jti) {
+ return errors.New("session has been revoked")
+ }
+ return nil
+ }
}
-// Admin
-func JWTAdminAuth(cfg *config.Config) okapi.JWTAuth {
+// JWTAuth creates user JWT auth middleware. If sessionStore is non-nil, revoked sessions are rejected.
+func JWTAuth(cfg *config.Config, sessionStore ...*sessionpkg.Store) okapi.JWTAuth {
+ auth := baseJWTAuth(cfg)
+ if len(sessionStore) > 0 && sessionStore[0] != nil {
+ auth.ValidateClaims = sessionValidator(sessionStore[0])
+ }
+ return auth
+}
+
+// JWTAdminAuth creates admin JWT auth middleware.
+func JWTAdminAuth(cfg *config.Config, sessionStore ...*sessionpkg.Store) okapi.JWTAuth {
auth := baseJWTAuth(cfg)
auth.ClaimsExpression = "Equals(`role`,`admin`)"
+ if len(sessionStore) > 0 && sessionStore[0] != nil {
+ auth.ValidateClaims = sessionValidator(sessionStore[0])
+ }
return auth
}
-// Admin via Query for SSE
-func JWTAdminQueryAuth(cfg *config.Config) okapi.JWTAuth {
+// JWTAdminQueryAuth creates admin JWT auth via query param (for SSE).
+func JWTAdminQueryAuth(cfg *config.Config, sessionStore ...*sessionpkg.Store) okapi.JWTAuth {
auth := baseJWTAuth(cfg)
auth.ClaimsExpression = "Equals(`role`,`admin`)"
auth.TokenLookup = "query:token"
+ if len(sessionStore) > 0 && sessionStore[0] != nil {
+ auth.ValidateClaims = sessionValidator(sessionStore[0])
+ }
return auth
}
diff --git a/internal/models/session.go b/internal/models/session.go
new file mode 100644
index 0000000..d6f047e
--- /dev/null
+++ b/internal/models/session.go
@@ -0,0 +1,51 @@
+/*
+ * MIT License
+ *
+ * Copyright (c) 2026 Jonas Kaninda
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+package models
+
+import "time"
+
+// Session tracks an active JWT session for a user.
+type Session struct {
+ ID uint `json:"id" gorm:"primaryKey"`
+ UserID uint `json:"user_id" gorm:"index;not null"`
+ JTI string `json:"jti" gorm:"uniqueIndex;not null;size:36"` // JWT ID (UUID)
+ IPAddress string `json:"ip_address"`
+ UserAgent string `json:"user_agent"`
+ Revoked bool `json:"revoked" gorm:"default:false;not null"`
+ CreatedAt time.Time `json:"created_at"`
+ ExpiresAt time.Time `json:"expires_at"`
+
+ User User `json:"-" gorm:"foreignKey:UserID"`
+}
+
+// IsExpired returns true if the session has passed its expiry time.
+func (s *Session) IsExpired() bool {
+ return time.Now().After(s.ExpiresAt)
+}
+
+// IsActive returns true if the session is neither revoked nor expired.
+func (s *Session) IsActive() bool {
+ return !s.Revoked && !s.IsExpired()
+}
diff --git a/internal/routes/admin_routes.go b/internal/routes/admin_routes.go
index 403cbf7..204e44b 100644
--- a/internal/routes/admin_routes.go
+++ b/internal/routes/admin_routes.go
@@ -185,6 +185,16 @@ func (r *Router) adminRoutes() []okapi.RouteDefinition {
Request: &handlers.AnalyticsRequest{},
Response: &dto.Response[handlers.AnalyticsResponse]{},
},
+ {
+ Method: http.MethodGet,
+ Path: "/analytics/dashboard",
+ Handler: okapi.H(r.h.analytics.AdminDashboardAnalytics),
+ Group: adminGroup,
+ Summary: "Platform dashboard analytics",
+ Description: "Returns platform-wide delivery rate trends, bounce rate graphs, and latency percentiles",
+ Request: &handlers.DashboardAnalyticsRequest{},
+ Response: &dto.Response[handlers.DashboardAnalyticsResponse]{},
+ },
// ==================== Platform Settings ====================
{
diff --git a/internal/routes/auth_routes.go b/internal/routes/auth_routes.go
index bc75135..79aaba3 100644
--- a/internal/routes/auth_routes.go
+++ b/internal/routes/auth_routes.go
@@ -162,6 +162,19 @@ func (r *Router) apiAuthRoutes() []okapi.RouteDefinition {
okapi.DocErrorResponse(429, &dto.ErrorResponseBody{}),
},
},
+ {
+ Method: http.MethodPost,
+ Path: "/emails/preview",
+ Handler: okapi.H(r.h.email.Preview),
+ Group: apiAuth,
+ Summary: "Preview email from template",
+ Description: "Render a template with variables and return the HTML, text, and subject without sending.",
+ Request: &handlers.PreviewEmailRequest{},
+ Response: &dto.Response[handlers.PreviewEmailResponse]{},
+ Options: []okapi.RouteOption{
+ okapi.DocErrorResponse(400, &dto.ErrorResponseBody{}),
+ },
+ },
{
Method: http.MethodGet,
Path: "/emails/{id}/status",
diff --git a/internal/routes/routes.go b/internal/routes/routes.go
index 8fffba0..c44272f 100644
--- a/internal/routes/routes.go
+++ b/internal/routes/routes.go
@@ -46,6 +46,7 @@ import (
"github.com/jkaninda/posta/internal/services/eventbus"
"github.com/jkaninda/posta/internal/services/ratelimit"
"github.com/jkaninda/posta/internal/services/seeder"
+ sessionpkg "github.com/jkaninda/posta/internal/services/session"
"github.com/jkaninda/posta/internal/services/settings"
"github.com/jkaninda/posta/internal/services/webhook"
"github.com/jkaninda/posta/internal/services/workermon"
@@ -96,6 +97,8 @@ type routerHandlers struct {
analytics *handlers.AnalyticsHandler
setting *handlers.SettingHandler
userSetting *handlers.UserSettingHandler
+ userData *handlers.UserDataHandler
+ session *handlers.SessionHandler
cron *handlers.CronHandler
}
@@ -120,6 +123,10 @@ func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *c
eventRepo := repositories.NewEventRepository(db)
settingRepo := repositories.NewSettingRepository(db)
userSettingRepo := repositories.NewUserSettingRepository(db)
+ sessionRepo := repositories.NewSessionRepository(db)
+
+ // Session store (Redis-backed blacklist)
+ sessionStore := sessionpkg.NewStore(redisClient)
// Services
bus := eventbus.New(eventRepo)
@@ -174,9 +181,9 @@ func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *c
cfg: cfg,
v1: app.Group("/api/v1"),
mw: routerMiddleware{
- jwtAuth: middlewares.JWTAuth(cfg),
- jwtAdminAuth: middlewares.JWTAdminAuth(cfg),
- jwtAdminQueryAuth: middlewares.JWTAdminQueryAuth(cfg),
+ jwtAuth: middlewares.JWTAuth(cfg, sessionStore),
+ jwtAdminAuth: middlewares.JWTAdminAuth(cfg, sessionStore),
+ jwtAdminQueryAuth: middlewares.JWTAdminQueryAuth(cfg, sessionStore),
loginLimiter: middlewares.LoginRateLimitMiddleware(limiter),
apiKey: middlewares.APIKeyAuthMiddleware(apiKeyService, userRepo, apiKeyRepo),
},
@@ -205,9 +212,14 @@ func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *c
analytics: handlers.NewAnalyticsHandler(repositories.NewAnalyticsRepository(db), statsCache),
setting: handlers.NewSettingHandler(settingRepo, auditLogger),
userSetting: handlers.NewUserSettingHandler(userSettingRepo),
+ userData: handlers.NewUserDataHandler(db, templateRepo, versionRepo, localizationRepo, stylesheetRepo, languageRepo, contactRepo, contactListRepo, webhookRepo, suppressionRepo, userSettingRepo),
+ session: handlers.NewSessionHandler(sessionRepo, sessionStore),
},
}
+ // Session management
+ r.h.user.SetSessionRepo(sessionRepo)
+
// Email content privacy
r.h.email.SetSettings(settingsProvider)
r.h.admin.SetEmailSettings(settingsProvider)
diff --git a/internal/routes/user_routes.go b/internal/routes/user_routes.go
index 3a02d23..daf99da 100644
--- a/internal/routes/user_routes.go
+++ b/internal/routes/user_routes.go
@@ -101,6 +101,48 @@ func (r *Router) userRoutes() []okapi.RouteDefinition {
Response: &dto.Response[any]{},
},
+ // ==================== Sessions ====================
+ {
+ Method: http.MethodGet,
+ Path: "/sessions",
+ Handler: r.h.session.List,
+ Group: userGroup,
+ Summary: "List active sessions",
+ Description: "Returns all active (non-revoked, non-expired) sessions for the current user",
+ Response: &dto.Response[[]handlers.SessionResponse]{},
+ },
+ {
+ Method: http.MethodDelete,
+ Path: "/sessions/{id:int}",
+ Handler: okapi.H(r.h.session.Revoke),
+ Group: userGroup,
+ Summary: "Revoke session",
+ Description: "Force logout a specific session by ID",
+ Response: &dto.Response[any]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Session ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/sessions/revoke-others",
+ Handler: r.h.session.RevokeOthers,
+ Group: userGroup,
+ Summary: "Revoke all other sessions",
+ Description: "Force logout all sessions except the current one",
+ Response: &dto.Response[any]{},
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/sessions/logout",
+ Handler: r.h.session.Logout,
+ Group: userGroup,
+ Summary: "Logout current session",
+ Description: "Revoke the current session's JWT token",
+ Response: &dto.Response[any]{},
+ },
+
// ==================== Dashboard & Analytics ====================
{
Method: http.MethodGet,
@@ -121,6 +163,16 @@ func (r *Router) userRoutes() []okapi.RouteDefinition {
Request: &handlers.AnalyticsRequest{},
Response: &dto.Response[handlers.AnalyticsResponse]{},
},
+ {
+ Method: http.MethodGet,
+ Path: "/analytics/dashboard",
+ Handler: okapi.H(r.h.analytics.UserDashboardAnalytics),
+ Group: userGroup,
+ Summary: "Dashboard analytics",
+ Description: "Returns delivery rate trends, bounce rate graphs, and latency percentiles",
+ Request: &handlers.DashboardAnalyticsRequest{},
+ Response: &dto.Response[handlers.DashboardAnalyticsResponse]{},
+ },
// ==================== Email Logs ====================
{
@@ -173,6 +225,21 @@ func (r *Router) userRoutes() []okapi.RouteDefinition {
},
},
+ // ==================== Email Preview ====================
+ {
+ Method: http.MethodPost,
+ Path: "/emails/preview",
+ Handler: okapi.H(r.h.email.Preview),
+ Group: userGroup,
+ Summary: "Preview email from template",
+ Description: "Render a template with variables and return the HTML, text, and subject without sending.",
+ Request: &handlers.PreviewEmailRequest{},
+ Response: &dto.Response[handlers.PreviewEmailResponse]{},
+ Options: []okapi.RouteOption{
+ okapi.DocErrorResponse(400, &dto.ErrorResponseBody{}),
+ },
+ },
+
// ==================== API Keys ====================
{
Method: http.MethodPost,
@@ -941,6 +1008,49 @@ func (r *Router) userRoutes() []okapi.RouteDefinition {
},
},
+ // ==================== User Data Export/Import ====================
+ {
+ Method: http.MethodGet,
+ Path: "/data/export",
+ Handler: r.h.userData.Export,
+ Group: userGroup,
+ Summary: "Export all user data",
+ Description: "Export all user data including templates, stylesheets, languages, contacts, contact lists, webhooks, suppressions, and settings as JSON",
+ Response: &dto.Response[handlers.UserDataExport]{},
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/data/import",
+ Handler: okapi.H(r.h.userData.Import),
+ Group: userGroup,
+ Summary: "Import user data",
+ Description: "Import user data from a previously exported JSON payload. Duplicates are skipped.",
+ Request: &handlers.ImportUserDataRequest{},
+ Response: &dto.Response[any]{},
+ },
+
+ // ==================== GDPR Data Management ====================
+ {
+ Method: http.MethodPost,
+ Path: "/gdpr/delete-contacts",
+ Handler: okapi.H(r.h.userData.DeleteContacts),
+ Group: userGroup,
+ Summary: "Delete contact data (GDPR)",
+ Description: "Delete a specific contact by email or all contacts. Also removes the contact from suppression lists and contact list memberships.",
+ Request: &handlers.GDPRDeleteContactsRequest{},
+ Response: &dto.Response[handlers.GDPRDeleteResult]{},
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/gdpr/delete-email-logs",
+ Handler: okapi.H(r.h.userData.DeleteEmailLogs),
+ Group: userGroup,
+ Summary: "Delete email logs (GDPR)",
+ Description: "Delete email logs and associated bounces. Specify older_than_days to only delete old logs, or 0 to delete all.",
+ Request: &handlers.GDPRDeleteEmailLogsRequest{},
+ Response: &dto.Response[handlers.GDPRDeleteResult]{},
+ },
+
// ==================== User Settings ====================
{
Method: http.MethodGet,
diff --git a/internal/services/cache/cache.go b/internal/services/cache/cache.go
index ccf0922..36f1383 100644
--- a/internal/services/cache/cache.go
+++ b/internal/services/cache/cache.go
@@ -44,7 +44,9 @@ const (
prefixAdminMetrics = "cache:admin:metrics"
prefixUserMetrics = "cache:admin:user_metrics:"
prefixUserAnalytics = "cache:analytics:user:"
- prefixAdminAnalytics = "cache:analytics:admin"
+ prefixAdminAnalytics = "cache:analytics:admin"
+ prefixDashAnalytics = "cache:dash_analytics:user:"
+ prefixAdminDashAnalytics = "cache:dash_analytics:admin"
)
// Cache provides Redis-backed caching for dashboard stats and metrics.
@@ -103,6 +105,14 @@ func AdminAnalyticsKey(from, to, status string) string {
return fmt.Sprintf("%s:%s:%s:%s", prefixAdminAnalytics, from, to, status)
}
+func DashboardAnalyticsKey(userID int, from, to string) string {
+ return fmt.Sprintf("%s%d:%s:%s", prefixDashAnalytics, userID, from, to)
+}
+
+func AdminDashboardAnalyticsKey(from, to string) string {
+ return fmt.Sprintf("%s:%s:%s", prefixAdminDashAnalytics, from, to)
+}
+
// InvalidateUser removes all cached data scoped to a specific user.
func (c *Cache) InvalidateUser(ctx context.Context, userID int) {
c.Delete(ctx, DashboardKey(userID))
diff --git a/internal/services/email/service.go b/internal/services/email/service.go
index 0520c3e..244866d 100644
--- a/internal/services/email/service.go
+++ b/internal/services/email/service.go
@@ -775,6 +775,16 @@ func (s *Service) RetryEmail(emailUUID string, userID uint) (*SendResponse, erro
})
}
+// RenderTemplate resolves a template by name and renders it with the given data,
+// returning the rendered subject, HTML, and text without sending.
+func (s *Service) RenderTemplate(userID uint, templateName, language string, data map[string]any) (*RenderedTemplate, error) {
+ tmpl, err := s.templateRepo.FindByName(userID, templateName)
+ if err != nil {
+ return nil, fmt.Errorf("template not found: %s", templateName)
+ }
+ return s.resolveAndRender(tmpl, language, data)
+}
+
// resolveAndRender resolves the template content using versioned localizations
// and renders it with the given data.
func (s *Service) resolveAndRender(tmpl *models.Template, language string, data map[string]any) (*RenderedTemplate, error) {
diff --git a/internal/services/session/session.go b/internal/services/session/session.go
new file mode 100644
index 0000000..741a444
--- /dev/null
+++ b/internal/services/session/session.go
@@ -0,0 +1,68 @@
+/*
+ * MIT License
+ *
+ * Copyright (c) 2026 Jonas Kaninda
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+package session
+
+import (
+ "context"
+ "fmt"
+ "time"
+
+ "github.com/redis/go-redis/v9"
+)
+
+const revokedPrefix = "session:revoked:"
+
+// Store provides Redis-backed session revocation checking.
+type Store struct {
+ redis *redis.Client
+}
+
+// NewStore creates a new session store backed by Redis.
+func NewStore(client *redis.Client) *Store {
+ return &Store{redis: client}
+}
+
+// MarkRevoked adds a JTI to the Redis blacklist with a TTL matching the token's remaining lifetime.
+func (s *Store) MarkRevoked(ctx context.Context, jti string, expiresAt time.Time) {
+ ttl := time.Until(expiresAt)
+ if ttl <= 0 {
+ return // already expired, no need to blacklist
+ }
+ s.redis.Set(ctx, revokedPrefix+jti, "1", ttl)
+}
+
+// IsRevoked checks if a JTI is in the Redis blacklist.
+func (s *Store) IsRevoked(ctx context.Context, jti string) bool {
+ val, err := s.redis.Exists(ctx, revokedPrefix+jti).Result()
+ if err != nil {
+ return false // fail open to avoid locking everyone out on Redis errors
+ }
+ return val > 0
+}
+
+// RevokedKey returns the Redis key for a revoked session.
+func RevokedKey(jti string) string {
+ return fmt.Sprintf("%s%s", revokedPrefix, jti)
+}
diff --git a/internal/storage/migration/migration.go b/internal/storage/migration/migration.go
index cd73edb..4a22446 100644
--- a/internal/storage/migration/migration.go
+++ b/internal/storage/migration/migration.go
@@ -56,6 +56,7 @@ func Run(db *gorm.DB) error {
&models.Setting{},
&models.UserSetting{},
&models.WebhookDelivery{},
+ &models.Session{},
); err != nil {
return fmt.Errorf("failed to migrate database: %w", err)
}
diff --git a/internal/storage/repositories/analytics_repo.go b/internal/storage/repositories/analytics_repo.go
index 209f2b5..60d47a8 100644
--- a/internal/storage/repositories/analytics_repo.go
+++ b/internal/storage/repositories/analytics_repo.go
@@ -107,3 +107,196 @@ func (r *AnalyticsRepository) AdminStatusBreakdown(from, to time.Time) ([]Status
Find(&results).Error
return results, err
}
+
+type deliveryRow struct {
+ Date string
+ Status string
+ Count int64
+}
+
+type bounceRow struct {
+ Date string
+ Type string
+ Count int64
+}
+
+// DeliveryRatePoint represents a single day's delivery rate.
+type DeliveryRatePoint struct {
+ Date string `json:"date"`
+ Sent int64 `json:"sent"`
+ Failed int64 `json:"failed"`
+ Total int64 `json:"total"`
+ DeliveryRate float64 `json:"delivery_rate"`
+}
+
+// BounceRatePoint represents a single day's bounce counts by type.
+type BounceRatePoint struct {
+ Date string `json:"date"`
+ Hard int64 `json:"hard"`
+ Soft int64 `json:"soft"`
+ Complaint int64 `json:"complaint"`
+ Total int64 `json:"total"`
+}
+
+// LatencyPercentiles represents email delivery latency percentiles.
+type LatencyPercentiles struct {
+ P50 float64 `json:"p50"`
+ P75 float64 `json:"p75"`
+ P90 float64 `json:"p90"`
+ P99 float64 `json:"p99"`
+ Avg float64 `json:"avg"`
+}
+
+// DeliveryRateTrends returns daily delivery rate for a user within a date range.
+func (r *AnalyticsRepository) DeliveryRateTrends(userID uint, from, to time.Time) ([]DeliveryRatePoint, error) {
+ var rows []deliveryRow
+ err := r.db.Table("emails").
+ Select("TO_CHAR(created_at, 'YYYY-MM-DD') as date, status, COUNT(*) as count").
+ Where("user_id = ? AND created_at >= ? AND created_at <= ? AND status IN ?", userID, from, to, []string{"sent", "failed"}).
+ Group("date, status").Order("date ASC").
+ Find(&rows).Error
+ if err != nil {
+ return nil, err
+ }
+ return buildDeliveryRatePoints(rows, from, to), nil
+}
+
+// AdminDeliveryRateTrends returns daily delivery rate across all users.
+func (r *AnalyticsRepository) AdminDeliveryRateTrends(from, to time.Time) ([]DeliveryRatePoint, error) {
+ var rows []deliveryRow
+ err := r.db.Table("emails").
+ Select("TO_CHAR(created_at, 'YYYY-MM-DD') as date, status, COUNT(*) as count").
+ Where("created_at >= ? AND created_at <= ? AND status IN ?", from, to, []string{"sent", "failed"}).
+ Group("date, status").Order("date ASC").
+ Find(&rows).Error
+ if err != nil {
+ return nil, err
+ }
+ return buildDeliveryRatePoints(rows, from, to), nil
+}
+
+func buildDeliveryRatePoints(rows []deliveryRow, from, to time.Time) []DeliveryRatePoint {
+ m := make(map[string]*DeliveryRatePoint)
+ start := from.Truncate(24 * time.Hour)
+ end := to.Truncate(24 * time.Hour)
+ for d := start; !d.After(end); d = d.AddDate(0, 0, 1) {
+ key := d.Format("2006-01-02")
+ m[key] = &DeliveryRatePoint{Date: key}
+ }
+ for _, r := range rows {
+ p, ok := m[r.Date]
+ if !ok {
+ p = &DeliveryRatePoint{Date: r.Date}
+ m[r.Date] = p
+ }
+ if r.Status == "sent" {
+ p.Sent = r.Count
+ } else if r.Status == "failed" {
+ p.Failed = r.Count
+ }
+ }
+ result := make([]DeliveryRatePoint, 0, len(m))
+ for d := start; !d.After(end); d = d.AddDate(0, 0, 1) {
+ key := d.Format("2006-01-02")
+ p := m[key]
+ p.Total = p.Sent + p.Failed
+ if p.Total > 0 {
+ p.DeliveryRate = float64(p.Sent) / float64(p.Total) * 100
+ }
+ result = append(result, *p)
+ }
+ return result
+}
+
+// BounceRateTrends returns daily bounce counts by type for a user.
+func (r *AnalyticsRepository) BounceRateTrends(userID uint, from, to time.Time) ([]BounceRatePoint, error) {
+ var rows []bounceRow
+ err := r.db.Table("bounces").
+ Select("TO_CHAR(created_at, 'YYYY-MM-DD') as date, type, COUNT(*) as count").
+ Where("user_id = ? AND created_at >= ? AND created_at <= ?", userID, from, to).
+ Group("date, type").Order("date ASC").
+ Find(&rows).Error
+ if err != nil {
+ return nil, err
+ }
+ return buildBounceRatePoints(rows, from, to), nil
+}
+
+// AdminBounceRateTrends returns daily bounce counts by type across all users.
+func (r *AnalyticsRepository) AdminBounceRateTrends(from, to time.Time) ([]BounceRatePoint, error) {
+ var rows []bounceRow
+ err := r.db.Table("bounces").
+ Select("TO_CHAR(created_at, 'YYYY-MM-DD') as date, type, COUNT(*) as count").
+ Where("created_at >= ? AND created_at <= ?", from, to).
+ Group("date, type").Order("date ASC").
+ Find(&rows).Error
+ if err != nil {
+ return nil, err
+ }
+ return buildBounceRatePoints(rows, from, to), nil
+}
+
+func buildBounceRatePoints(rows []bounceRow, from, to time.Time) []BounceRatePoint {
+ m := make(map[string]*BounceRatePoint)
+ start := from.Truncate(24 * time.Hour)
+ end := to.Truncate(24 * time.Hour)
+ for d := start; !d.After(end); d = d.AddDate(0, 0, 1) {
+ key := d.Format("2006-01-02")
+ m[key] = &BounceRatePoint{Date: key}
+ }
+ for _, r := range rows {
+ p, ok := m[r.Date]
+ if !ok {
+ p = &BounceRatePoint{Date: r.Date}
+ m[r.Date] = p
+ }
+ switch r.Type {
+ case "hard":
+ p.Hard = r.Count
+ case "soft":
+ p.Soft = r.Count
+ case "complaint":
+ p.Complaint = r.Count
+ }
+ }
+ result := make([]BounceRatePoint, 0, len(m))
+ for d := start; !d.After(end); d = d.AddDate(0, 0, 1) {
+ key := d.Format("2006-01-02")
+ p := m[key]
+ p.Total = p.Hard + p.Soft + p.Complaint
+ result = append(result, *p)
+ }
+ return result
+}
+
+// LatencyPercentilesForUser returns delivery latency percentiles for a user.
+func (r *AnalyticsRepository) LatencyPercentilesForUser(userID uint, from, to time.Time) (*LatencyPercentiles, error) {
+ var result LatencyPercentiles
+ err := r.db.Table("emails").
+ Select(`
+ COALESCE(PERCENTILE_CONT(0.50) WITHIN GROUP (ORDER BY EXTRACT(EPOCH FROM (sent_at - created_at))), 0) as p50,
+ COALESCE(PERCENTILE_CONT(0.75) WITHIN GROUP (ORDER BY EXTRACT(EPOCH FROM (sent_at - created_at))), 0) as p75,
+ COALESCE(PERCENTILE_CONT(0.90) WITHIN GROUP (ORDER BY EXTRACT(EPOCH FROM (sent_at - created_at))), 0) as p90,
+ COALESCE(PERCENTILE_CONT(0.99) WITHIN GROUP (ORDER BY EXTRACT(EPOCH FROM (sent_at - created_at))), 0) as p99,
+ COALESCE(AVG(EXTRACT(EPOCH FROM (sent_at - created_at))), 0) as avg
+ `).
+ Where("user_id = ? AND status = 'sent' AND sent_at IS NOT NULL AND created_at >= ? AND created_at <= ?", userID, from, to).
+ Scan(&result).Error
+ return &result, err
+}
+
+// AdminLatencyPercentiles returns delivery latency percentiles across all users.
+func (r *AnalyticsRepository) AdminLatencyPercentiles(from, to time.Time) (*LatencyPercentiles, error) {
+ var result LatencyPercentiles
+ err := r.db.Table("emails").
+ Select(`
+ COALESCE(PERCENTILE_CONT(0.50) WITHIN GROUP (ORDER BY EXTRACT(EPOCH FROM (sent_at - created_at))), 0) as p50,
+ COALESCE(PERCENTILE_CONT(0.75) WITHIN GROUP (ORDER BY EXTRACT(EPOCH FROM (sent_at - created_at))), 0) as p75,
+ COALESCE(PERCENTILE_CONT(0.90) WITHIN GROUP (ORDER BY EXTRACT(EPOCH FROM (sent_at - created_at))), 0) as p90,
+ COALESCE(PERCENTILE_CONT(0.99) WITHIN GROUP (ORDER BY EXTRACT(EPOCH FROM (sent_at - created_at))), 0) as p99,
+ COALESCE(AVG(EXTRACT(EPOCH FROM (sent_at - created_at))), 0) as avg
+ `).
+ Where("status = 'sent' AND sent_at IS NOT NULL AND created_at >= ? AND created_at <= ?", from, to).
+ Scan(&result).Error
+ return &result, err
+}
diff --git a/internal/storage/repositories/session_repo.go b/internal/storage/repositories/session_repo.go
new file mode 100644
index 0000000..870938f
--- /dev/null
+++ b/internal/storage/repositories/session_repo.go
@@ -0,0 +1,112 @@
+/*
+ * MIT License
+ *
+ * Copyright (c) 2026 Jonas Kaninda
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+package repositories
+
+import (
+ "time"
+
+ "github.com/jkaninda/posta/internal/models"
+ "gorm.io/gorm"
+)
+
+type SessionRepository struct {
+ db *gorm.DB
+}
+
+func NewSessionRepository(db *gorm.DB) *SessionRepository {
+ return &SessionRepository{db: db}
+}
+
+func (r *SessionRepository) Create(session *models.Session) error {
+ return r.db.Create(session).Error
+}
+
+// FindActiveByUserID returns non-revoked, non-expired sessions for a user.
+func (r *SessionRepository) FindActiveByUserID(userID uint) ([]models.Session, error) {
+ var sessions []models.Session
+ if err := r.db.Where("user_id = ? AND revoked = false AND expires_at > ?", userID, time.Now()).
+ Order("created_at DESC").
+ Find(&sessions).Error; err != nil {
+ return nil, err
+ }
+ return sessions, nil
+}
+
+func (r *SessionRepository) FindByID(id uint) (*models.Session, error) {
+ var session models.Session
+ if err := r.db.First(&session, id).Error; err != nil {
+ return nil, err
+ }
+ return &session, nil
+}
+
+func (r *SessionRepository) FindByJTI(jti string) (*models.Session, error) {
+ var session models.Session
+ if err := r.db.Where("jti = ?", jti).First(&session).Error; err != nil {
+ return nil, err
+ }
+ return &session, nil
+}
+
+// Revoke marks a session as revoked.
+func (r *SessionRepository) Revoke(id uint) error {
+ return r.db.Model(&models.Session{}).Where("id = ?", id).Update("revoked", true).Error
+}
+
+// RevokeByJTI marks a session as revoked by JTI.
+func (r *SessionRepository) RevokeByJTI(jti string) error {
+ return r.db.Model(&models.Session{}).Where("jti = ?", jti).Update("revoked", true).Error
+}
+
+// RevokeAllByUserID revokes all active sessions for a user.
+func (r *SessionRepository) RevokeAllByUserID(userID uint) (int64, error) {
+ result := r.db.Model(&models.Session{}).
+ Where("user_id = ? AND revoked = false AND expires_at > ?", userID, time.Now()).
+ Update("revoked", true)
+ return result.RowsAffected, result.Error
+}
+
+// RevokeOthersByUserID revokes all active sessions except the given JTI.
+func (r *SessionRepository) RevokeOthersByUserID(userID uint, exceptJTI string) (int64, error) {
+ result := r.db.Model(&models.Session{}).
+ Where("user_id = ? AND jti != ? AND revoked = false AND expires_at > ?", userID, exceptJTI, time.Now()).
+ Update("revoked", true)
+ return result.RowsAffected, result.Error
+}
+
+// CleanExpired removes expired sessions from the database.
+func (r *SessionRepository) CleanExpired() (int64, error) {
+ result := r.db.Where("expires_at < ?", time.Now()).Delete(&models.Session{})
+ return result.RowsAffected, result.Error
+}
+
+// IsRevoked checks if a session with the given JTI is revoked.
+func (r *SessionRepository) IsRevoked(jti string) (bool, error) {
+ var count int64
+ err := r.db.Model(&models.Session{}).
+ Where("jti = ? AND revoked = true", jti).
+ Count(&count).Error
+ return count > 0, err
+}
diff --git a/web/package-lock.json b/web/package-lock.json
index 8a56cab..1e76386 100644
--- a/web/package-lock.json
+++ b/web/package-lock.json
@@ -8,8 +8,14 @@
"name": "dashboard",
"version": "0.0.0",
"dependencies": {
+ "@codemirror/lang-html": "^6.4.11",
+ "@codemirror/lang-json": "^6.0.2",
+ "@codemirror/state": "^6.6.0",
+ "@codemirror/theme-one-dark": "^6.1.3",
+ "@codemirror/view": "^6.40.0",
"@mdi/font": "^7.4.47",
"axios": "^1.13.6",
+ "codemirror": "^6.0.2",
"pinia": "^3.0.4",
"vue": "^3.5.25",
"vue-router": "^4.6.4"
@@ -68,6 +74,154 @@
"node": ">=6.9.0"
}
},
+ "node_modules/@codemirror/autocomplete": {
+ "version": "6.20.1",
+ "resolved": "https://registry.npmjs.org/@codemirror/autocomplete/-/autocomplete-6.20.1.tgz",
+ "integrity": "sha512-1cvg3Vz1dSSToCNlJfRA2WSI4ht3K+WplO0UMOgmUYPivCyy2oueZY6Lx7M9wThm7SDUBViRmuT+OG/i8+ON9A==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/language": "^6.0.0",
+ "@codemirror/state": "^6.0.0",
+ "@codemirror/view": "^6.17.0",
+ "@lezer/common": "^1.0.0"
+ }
+ },
+ "node_modules/@codemirror/commands": {
+ "version": "6.10.3",
+ "resolved": "https://registry.npmjs.org/@codemirror/commands/-/commands-6.10.3.tgz",
+ "integrity": "sha512-JFRiqhKu+bvSkDLI+rUhJwSxQxYb759W5GBezE8Uc8mHLqC9aV/9aTC7yJSqCtB3F00pylrLCwnyS91Ap5ej4Q==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/language": "^6.0.0",
+ "@codemirror/state": "^6.6.0",
+ "@codemirror/view": "^6.27.0",
+ "@lezer/common": "^1.1.0"
+ }
+ },
+ "node_modules/@codemirror/lang-css": {
+ "version": "6.3.1",
+ "resolved": "https://registry.npmjs.org/@codemirror/lang-css/-/lang-css-6.3.1.tgz",
+ "integrity": "sha512-kr5fwBGiGtmz6l0LSJIbno9QrifNMUusivHbnA1H6Dmqy4HZFte3UAICix1VuKo0lMPKQr2rqB+0BkKi/S3Ejg==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/autocomplete": "^6.0.0",
+ "@codemirror/language": "^6.0.0",
+ "@codemirror/state": "^6.0.0",
+ "@lezer/common": "^1.0.2",
+ "@lezer/css": "^1.1.7"
+ }
+ },
+ "node_modules/@codemirror/lang-html": {
+ "version": "6.4.11",
+ "resolved": "https://registry.npmjs.org/@codemirror/lang-html/-/lang-html-6.4.11.tgz",
+ "integrity": "sha512-9NsXp7Nwp891pQchI7gPdTwBuSuT3K65NGTHWHNJ55HjYcHLllr0rbIZNdOzas9ztc1EUVBlHou85FFZS4BNnw==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/autocomplete": "^6.0.0",
+ "@codemirror/lang-css": "^6.0.0",
+ "@codemirror/lang-javascript": "^6.0.0",
+ "@codemirror/language": "^6.4.0",
+ "@codemirror/state": "^6.0.0",
+ "@codemirror/view": "^6.17.0",
+ "@lezer/common": "^1.0.0",
+ "@lezer/css": "^1.1.0",
+ "@lezer/html": "^1.3.12"
+ }
+ },
+ "node_modules/@codemirror/lang-javascript": {
+ "version": "6.2.5",
+ "resolved": "https://registry.npmjs.org/@codemirror/lang-javascript/-/lang-javascript-6.2.5.tgz",
+ "integrity": "sha512-zD4e5mS+50htS7F+TYjBPsiIFGanfVqg4HyUz6WNFikgOPf2BgKlx+TQedI1w6n/IqRBVBbBWmGFdLB/7uxO4A==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/autocomplete": "^6.0.0",
+ "@codemirror/language": "^6.6.0",
+ "@codemirror/lint": "^6.0.0",
+ "@codemirror/state": "^6.0.0",
+ "@codemirror/view": "^6.17.0",
+ "@lezer/common": "^1.0.0",
+ "@lezer/javascript": "^1.0.0"
+ }
+ },
+ "node_modules/@codemirror/lang-json": {
+ "version": "6.0.2",
+ "resolved": "https://registry.npmjs.org/@codemirror/lang-json/-/lang-json-6.0.2.tgz",
+ "integrity": "sha512-x2OtO+AvwEHrEwR0FyyPtfDUiloG3rnVTSZV1W8UteaLL8/MajQd8DpvUb2YVzC+/T18aSDv0H9mu+xw0EStoQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/language": "^6.0.0",
+ "@lezer/json": "^1.0.0"
+ }
+ },
+ "node_modules/@codemirror/language": {
+ "version": "6.12.2",
+ "resolved": "https://registry.npmjs.org/@codemirror/language/-/language-6.12.2.tgz",
+ "integrity": "sha512-jEPmz2nGGDxhRTg3lTpzmIyGKxz3Gp3SJES4b0nAuE5SWQoKdT5GoQ69cwMmFd+wvFUhYirtDTr0/DRHpQAyWg==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/state": "^6.0.0",
+ "@codemirror/view": "^6.23.0",
+ "@lezer/common": "^1.5.0",
+ "@lezer/highlight": "^1.0.0",
+ "@lezer/lr": "^1.0.0",
+ "style-mod": "^4.0.0"
+ }
+ },
+ "node_modules/@codemirror/lint": {
+ "version": "6.9.5",
+ "resolved": "https://registry.npmjs.org/@codemirror/lint/-/lint-6.9.5.tgz",
+ "integrity": "sha512-GElsbU9G7QT9xXhpUg1zWGmftA/7jamh+7+ydKRuT0ORpWS3wOSP0yT1FOlIZa7mIJjpVPipErsyvVqB9cfTFA==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/state": "^6.0.0",
+ "@codemirror/view": "^6.35.0",
+ "crelt": "^1.0.5"
+ }
+ },
+ "node_modules/@codemirror/search": {
+ "version": "6.6.0",
+ "resolved": "https://registry.npmjs.org/@codemirror/search/-/search-6.6.0.tgz",
+ "integrity": "sha512-koFuNXcDvyyotWcgOnZGmY7LZqEOXZaaxD/j6n18TCLx2/9HieZJ5H6hs1g8FiRxBD0DNfs0nXn17g872RmYdw==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/state": "^6.0.0",
+ "@codemirror/view": "^6.37.0",
+ "crelt": "^1.0.5"
+ }
+ },
+ "node_modules/@codemirror/state": {
+ "version": "6.6.0",
+ "resolved": "https://registry.npmjs.org/@codemirror/state/-/state-6.6.0.tgz",
+ "integrity": "sha512-4nbvra5R5EtiCzr9BTHiTLc+MLXK2QGiAVYMyi8PkQd3SR+6ixar/Q/01Fa21TBIDOZXgeWV4WppsQolSreAPQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@marijn/find-cluster-break": "^1.0.0"
+ }
+ },
+ "node_modules/@codemirror/theme-one-dark": {
+ "version": "6.1.3",
+ "resolved": "https://registry.npmjs.org/@codemirror/theme-one-dark/-/theme-one-dark-6.1.3.tgz",
+ "integrity": "sha512-NzBdIvEJmx6fjeremiGp3t/okrLPYT0d9orIc7AFun8oZcRk58aejkqhv6spnz4MLAevrKNPMQYXEWMg4s+sKA==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/language": "^6.0.0",
+ "@codemirror/state": "^6.0.0",
+ "@codemirror/view": "^6.0.0",
+ "@lezer/highlight": "^1.0.0"
+ }
+ },
+ "node_modules/@codemirror/view": {
+ "version": "6.40.0",
+ "resolved": "https://registry.npmjs.org/@codemirror/view/-/view-6.40.0.tgz",
+ "integrity": "sha512-WA0zdU7xfF10+5I3HhUUq3kqOx3KjqmtQ9lqZjfK7jtYk4G72YW9rezcSywpaUMCWOMlq+6E0pO1IWg1TNIhtg==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/state": "^6.6.0",
+ "crelt": "^1.0.6",
+ "style-mod": "^4.1.0",
+ "w3c-keyname": "^2.2.4"
+ }
+ },
"node_modules/@esbuild/aix-ppc64": {
"version": "0.27.3",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.3.tgz",
@@ -516,6 +670,80 @@
"integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==",
"license": "MIT"
},
+ "node_modules/@lezer/common": {
+ "version": "1.5.1",
+ "resolved": "https://registry.npmjs.org/@lezer/common/-/common-1.5.1.tgz",
+ "integrity": "sha512-6YRVG9vBkaY7p1IVxL4s44n5nUnaNnGM2/AckNgYOnxTG2kWh1vR8BMxPseWPjRNpb5VtXnMpeYAEAADoRV1Iw==",
+ "license": "MIT"
+ },
+ "node_modules/@lezer/css": {
+ "version": "1.3.1",
+ "resolved": "https://registry.npmjs.org/@lezer/css/-/css-1.3.1.tgz",
+ "integrity": "sha512-PYAKeUVBo3HFThruRyp/iK91SwiZJnzXh8QzkQlwijB5y+N5iB28+iLk78o2zmKqqV0uolNhCwFqB8LA7b0Svg==",
+ "license": "MIT",
+ "dependencies": {
+ "@lezer/common": "^1.2.0",
+ "@lezer/highlight": "^1.0.0",
+ "@lezer/lr": "^1.3.0"
+ }
+ },
+ "node_modules/@lezer/highlight": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/@lezer/highlight/-/highlight-1.2.3.tgz",
+ "integrity": "sha512-qXdH7UqTvGfdVBINrgKhDsVTJTxactNNxLk7+UMwZhU13lMHaOBlJe9Vqp907ya56Y3+ed2tlqzys7jDkTmW0g==",
+ "license": "MIT",
+ "dependencies": {
+ "@lezer/common": "^1.3.0"
+ }
+ },
+ "node_modules/@lezer/html": {
+ "version": "1.3.13",
+ "resolved": "https://registry.npmjs.org/@lezer/html/-/html-1.3.13.tgz",
+ "integrity": "sha512-oI7n6NJml729m7pjm9lvLvmXbdoMoi2f+1pwSDJkl9d68zGr7a9Btz8NdHTGQZtW2DA25ybeuv/SyDb9D5tseg==",
+ "license": "MIT",
+ "dependencies": {
+ "@lezer/common": "^1.2.0",
+ "@lezer/highlight": "^1.0.0",
+ "@lezer/lr": "^1.0.0"
+ }
+ },
+ "node_modules/@lezer/javascript": {
+ "version": "1.5.4",
+ "resolved": "https://registry.npmjs.org/@lezer/javascript/-/javascript-1.5.4.tgz",
+ "integrity": "sha512-vvYx3MhWqeZtGPwDStM2dwgljd5smolYD2lR2UyFcHfxbBQebqx8yjmFmxtJ/E6nN6u1D9srOiVWm3Rb4tmcUA==",
+ "license": "MIT",
+ "dependencies": {
+ "@lezer/common": "^1.2.0",
+ "@lezer/highlight": "^1.1.3",
+ "@lezer/lr": "^1.3.0"
+ }
+ },
+ "node_modules/@lezer/json": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/@lezer/json/-/json-1.0.3.tgz",
+ "integrity": "sha512-BP9KzdF9Y35PDpv04r0VeSTKDeox5vVr3efE7eBbx3r4s3oNLfunchejZhjArmeieBH+nVOpgIiBJpEAv8ilqQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@lezer/common": "^1.2.0",
+ "@lezer/highlight": "^1.0.0",
+ "@lezer/lr": "^1.0.0"
+ }
+ },
+ "node_modules/@lezer/lr": {
+ "version": "1.4.8",
+ "resolved": "https://registry.npmjs.org/@lezer/lr/-/lr-1.4.8.tgz",
+ "integrity": "sha512-bPWa0Pgx69ylNlMlPvBPryqeLYQjyJjqPx+Aupm5zydLIF3NE+6MMLT8Yi23Bd9cif9VS00aUebn+6fDIGBcDA==",
+ "license": "MIT",
+ "dependencies": {
+ "@lezer/common": "^1.0.0"
+ }
+ },
+ "node_modules/@marijn/find-cluster-break": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/@marijn/find-cluster-break/-/find-cluster-break-1.0.2.tgz",
+ "integrity": "sha512-l0h88YhZFyKdXIFNfSWpyjStDjGHwZ/U7iobcK1cQQD8sejsONdQtTVU+1wVN1PBw40PiiHB1vA5S7VTfQiP9g==",
+ "license": "MIT"
+ },
"node_modules/@mdi/font": {
"version": "7.4.47",
"resolved": "https://registry.npmjs.org/@mdi/font/-/font-7.4.47.tgz",
@@ -1134,6 +1362,21 @@
"node": ">= 0.4"
}
},
+ "node_modules/codemirror": {
+ "version": "6.0.2",
+ "resolved": "https://registry.npmjs.org/codemirror/-/codemirror-6.0.2.tgz",
+ "integrity": "sha512-VhydHotNW5w1UGK0Qj96BwSk/Zqbp9WbnyK2W/eVMv4QyF41INRGpjUhFJY7/uDNuudSc33a/PKr4iDqRduvHw==",
+ "license": "MIT",
+ "dependencies": {
+ "@codemirror/autocomplete": "^6.0.0",
+ "@codemirror/commands": "^6.0.0",
+ "@codemirror/language": "^6.0.0",
+ "@codemirror/lint": "^6.0.0",
+ "@codemirror/search": "^6.0.0",
+ "@codemirror/state": "^6.0.0",
+ "@codemirror/view": "^6.0.0"
+ }
+ },
"node_modules/combined-stream": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
@@ -1161,6 +1404,12 @@
"url": "https://github.com/sponsors/mesqueeb"
}
},
+ "node_modules/crelt": {
+ "version": "1.0.6",
+ "resolved": "https://registry.npmjs.org/crelt/-/crelt-1.0.6.tgz",
+ "integrity": "sha512-VQ2MBenTq1fWZUH9DJNGti7kKv6EeAuYr3cLwxUWhIu1baTaXh4Ib5W2CqHVqib4/MqbYGJqiL3Zb8GJZr3l4g==",
+ "license": "MIT"
+ },
"node_modules/csstype": {
"version": "3.2.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
@@ -1705,6 +1954,12 @@
"node": ">=0.10.0"
}
},
+ "node_modules/style-mod": {
+ "version": "4.1.3",
+ "resolved": "https://registry.npmjs.org/style-mod/-/style-mod-4.1.3.tgz",
+ "integrity": "sha512-i/n8VsZydrugj3Iuzll8+x/00GH2vnYsk1eomD8QiRrSAeW6ItbCQDtfXCeJHd0iwiNagqjQkvpvREEPtW3IoQ==",
+ "license": "MIT"
+ },
"node_modules/superjson": {
"version": "2.2.6",
"resolved": "https://registry.npmjs.org/superjson/-/superjson-2.2.6.tgz",
@@ -1888,6 +2143,12 @@
"peerDependencies": {
"typescript": ">=5.0.0"
}
+ },
+ "node_modules/w3c-keyname": {
+ "version": "2.2.8",
+ "resolved": "https://registry.npmjs.org/w3c-keyname/-/w3c-keyname-2.2.8.tgz",
+ "integrity": "sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==",
+ "license": "MIT"
}
}
}
diff --git a/web/package.json b/web/package.json
index 8c524d5..2bc5a92 100644
--- a/web/package.json
+++ b/web/package.json
@@ -9,8 +9,14 @@
"preview": "vite preview"
},
"dependencies": {
+ "@codemirror/lang-html": "^6.4.11",
+ "@codemirror/lang-json": "^6.0.2",
+ "@codemirror/state": "^6.6.0",
+ "@codemirror/theme-one-dark": "^6.1.3",
+ "@codemirror/view": "^6.40.0",
"@mdi/font": "^7.4.47",
"axios": "^1.13.6",
+ "codemirror": "^6.0.2",
"pinia": "^3.0.4",
"vue": "^3.5.25",
"vue-router": "^4.6.4"
diff --git a/web/src/api/analytics.ts b/web/src/api/analytics.ts
index fda41c5..ef7b662 100644
--- a/web/src/api/analytics.ts
+++ b/web/src/api/analytics.ts
@@ -1,5 +1,5 @@
import api from './client'
-import type { ApiResponse, AnalyticsResponse } from './types'
+import type { ApiResponse, AnalyticsResponse, DashboardAnalyticsResponse } from './types'
export const analyticsApi = {
user(from?: string, to?: string, status?: string) {
@@ -16,4 +16,16 @@ export const analyticsApi = {
if (status) params.status = status
return api.get<ApiResponse<AnalyticsResponse>>('/admin/analytics', { params })
},
+ dashboardAnalytics(from?: string, to?: string) {
+ const params: Record<string, string> = {}
+ if (from) params.from = from
+ if (to) params.to = to
+ return api.get<ApiResponse<DashboardAnalyticsResponse>>('/users/me/analytics/dashboard', { params })
+ },
+ adminDashboardAnalytics(from?: string, to?: string) {
+ const params: Record<string, string> = {}
+ if (from) params.from = from
+ if (to) params.to = to
+ return api.get<ApiResponse<DashboardAnalyticsResponse>>('/admin/analytics/dashboard', { params })
+ },
}
diff --git a/web/src/api/emails.ts b/web/src/api/emails.ts
index c558105..3be6cfd 100644
--- a/web/src/api/emails.ts
+++ b/web/src/api/emails.ts
@@ -6,6 +6,18 @@ export interface RetryResponse {
status: string
}
+export interface EmailPreviewRequest {
+ template: string
+ language?: string
+ template_data?: Record<string, any>
+}
+
+export interface EmailPreviewResponse {
+ subject: string
+ html: string
+ text: string
+}
+
export const emailsApi = {
list(page = 0, size = 20) {
return api.get<PaginatedResponse<Email>>('/users/me/emails', { params: { page, size } })
@@ -16,4 +28,7 @@ export const emailsApi = {
retry(uuid: string) {
return api.post<ApiResponse<RetryResponse>>(`/users/me/emails/${uuid}/retry`)
},
+ preview(data: EmailPreviewRequest) {
+ return api.post<ApiResponse<EmailPreviewResponse>>('/users/me/emails/preview', data)
+ },
}
diff --git a/web/src/api/sessions.ts b/web/src/api/sessions.ts
new file mode 100644
index 0000000..4beb6ab
--- /dev/null
+++ b/web/src/api/sessions.ts
@@ -0,0 +1,26 @@
+import api from './client'
+import type { ApiResponse } from './types'
+
+export interface Session {
+ id: number
+ ip_address: string
+ user_agent: string
+ current: boolean
+ created_at: string
+ expires_at: string
+}
+
+export const sessionsApi = {
+ list() {
+ return api.get<ApiResponse<Session[]>>('/users/me/sessions')
+ },
+ revoke(id: number) {
+ return api.delete<ApiResponse<{ message: string }>>(`/users/me/sessions/${id}`)
+ },
+ revokeOthers() {
+ return api.post<ApiResponse<{ message: string; revoked: number }>>('/users/me/sessions/revoke-others')
+ },
+ logout() {
+ return api.post<ApiResponse<{ message: string }>>('/users/me/sessions/logout')
+ },
+}
diff --git a/web/src/api/types.ts b/web/src/api/types.ts
index f279844..6664c21 100644
--- a/web/src/api/types.ts
+++ b/web/src/api/types.ts
@@ -464,6 +464,36 @@ export interface AnalyticsResponse {
status_breakdown: StatusBreakdown[]
}
+export interface DeliveryRatePoint {
+ date: string
+ sent: number
+ failed: number
+ total: number
+ delivery_rate: number
+}
+
+export interface BounceRatePoint {
+ date: string
+ hard: number
+ soft: number
+ complaint: number
+ total: number
+}
+
+export interface LatencyPercentiles {
+ p50: number
+ p75: number
+ p90: number
+ p99: number
+ avg: number
+}
+
+export interface DashboardAnalyticsResponse {
+ delivery_rate_trends: DeliveryRatePoint[]
+ bounce_rate_trends: BounceRatePoint[]
+ latency_percentiles: LatencyPercentiles
+}
+
// Contact Lists
export interface ContactList {
id: number
@@ -545,3 +575,74 @@ export interface UserProfile {
require_verified_domain: boolean
created_at: string
}
+
+// User Data Export/Import
+export interface UserDataExport {
+ posta_version?: string
+ exported_at?: string
+ templates: TemplateExport[]
+ stylesheets: ExportStyleSheet[]
+ languages: ExportLanguage[]
+ contacts: ExportContact[]
+ contact_lists: ExportContactList[]
+ suppressions: ExportSuppression[]
+ webhooks: ExportWebhook[]
+ settings?: ExportUserSettings
+}
+
+export interface ExportStyleSheet {
+ name: string
+ css: string
+}
+
+export interface ExportLanguage {
+ code: string
+ name: string
+}
+
+export interface ExportContact {
+ email: string
+ name: string
+ sent_count: number
+ fail_count: number
+}
+
+export interface ExportContactList {
+ name: string
+ description: string
+ members: ExportContactMember[]
+}
+
+export interface ExportContactMember {
+ email: string
+ name: string
+ data?: string
+}
+
+export interface ExportSuppression {
+ email: string
+ reason: string
+}
+
+export interface ExportWebhook {
+ url: string
+ events: string[]
+ filters?: string[]
+}
+
+export interface ExportUserSettings {
+ timezone: string
+ default_sender_name: string
+ default_sender_email: string
+ email_notifications: boolean
+ notification_email: string
+ webhook_retry_count: number
+ api_key_expiry_days: number
+ bounce_auto_suppress: boolean
+ daily_report: boolean
+}
+
+export interface GDPRDeleteResult {
+ deleted: number
+ message: string
+}
diff --git a/web/src/api/userData.ts b/web/src/api/userData.ts
new file mode 100644
index 0000000..bc2fc5e
--- /dev/null
+++ b/web/src/api/userData.ts
@@ -0,0 +1,17 @@
+import api from './client'
+import type { ApiResponse, UserDataExport, GDPRDeleteResult } from './types'
+
+export const userDataApi = {
+ exportAll() {
+ return api.get<ApiResponse<UserDataExport>>('/users/me/data/export')
+ },
+ importAll(data: UserDataExport) {
+ return api.post<ApiResponse<{ message: string; imported_count: number }>>('/users/me/data/import', data)
+ },
+ deleteContacts(email?: string) {
+ return api.post<ApiResponse<GDPRDeleteResult>>('/users/me/gdpr/delete-contacts', { email: email || '' })
+ },
+ deleteEmailLogs(olderThanDays: number) {
+ return api.post<ApiResponse<GDPRDeleteResult>>('/users/me/gdpr/delete-email-logs', { older_than_days: olderThanDays })
+ },
+}
diff --git a/web/src/router/index.ts b/web/src/router/index.ts
index 2584c99..9e656b1 100644
--- a/web/src/router/index.ts
+++ b/web/src/router/index.ts
@@ -22,10 +22,12 @@ const routes = [
{ path: '', name: 'dashboard', component: () => import('../views/dashboard/Dashboard.vue') },
{ path: 'api-keys', name: 'api-keys', component: () => import('../views/apikeys/ApiKeys.vue') },
{ path: 'emails', name: 'emails', component: () => import('../views/emails/Emails.vue') },
+ { path: 'emails/preview', name: 'email-preview', component: () => import('../views/emails/EmailPreview.vue') },
{ path: 'emails/:id', name: 'email-detail', component: () => import('../views/emails/EmailDetail.vue') },
{ path: 'templates', name: 'templates', component: () => import('../views/templates/Templates.vue') },
{ path: 'templates/:id/preview', name: 'template-preview', component: () => import('../views/templates/TemplatePreview.vue') },
{ path: 'templates/:id/versions', name: 'template-detail', component: () => import('../views/templates/TemplateDetail.vue') },
+ { path: 'templates/:id/versions/:versionId/localizations/:localizationId/edit', name: 'template-editor', component: () => import('../views/templates/TemplateEditor.vue') },
{ path: 'languages', name: 'languages', component: () => import('../views/languages/Languages.vue') },
{ path: 'stylesheets', name: 'stylesheets', component: () => import('../views/stylesheets/Stylesheets.vue') },
{ path: 'smtp-servers', name: 'smtp-servers', component: () => import('../views/smtp/SmtpServers.vue') },
diff --git a/web/src/views/admin/Metrics.vue b/web/src/views/admin/Metrics.vue
index 013c1a9..dc218f5 100644
--- a/web/src/views/admin/Metrics.vue
+++ b/web/src/views/admin/Metrics.vue
@@ -3,23 +3,26 @@ import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { adminApi } from '../../api/admin'
import { analyticsApi } from '../../api/analytics'
import { useAuthStore } from '../../stores/auth'
-import type { AdminMetrics, WorkerStatus, AnalyticsResponse } from '../../api/types'
+import type { AdminMetrics, WorkerStatus, AnalyticsResponse, DashboardAnalyticsResponse } from '../../api/types'
const auth = useAuthStore()
const loading = ref(true)
const metrics = ref<AdminMetrics | null>(null)
const workerStatus = ref<WorkerStatus | null>(null)
const analytics = ref<AnalyticsResponse | null>(null)
+const dashAnalytics = ref<DashboardAnalyticsResponse | null>(null)
let workerSSE: EventSource | null = null
onMounted(async () => {
try {
- const [metricsRes, analyticsRes] = await Promise.all([
+ const [metricsRes, analyticsRes, dashRes] = await Promise.all([
adminApi.getMetrics(),
analyticsApi.admin(),
+ analyticsApi.adminDashboardAnalytics(),
])
metrics.value = metricsRes.data.data
analytics.value = analyticsRes.data.data
+ dashAnalytics.value = dashRes.data.data
} catch (e) {
console.error('Failed to load metrics', e)
} finally {
@@ -108,6 +111,47 @@ function statusColor(status: string): string {
}
const totalBreakdown = computed(() => analytics.value?.status_breakdown?.reduce((s, b) => s + b.count, 0) || 0)
+
+// Dashboard analytics helpers
+const deliveryRateMax = computed(() => {
+ if (!dashAnalytics.value) return 1
+ return Math.max(...dashAnalytics.value.delivery_rate_trends.map(d => d.total), 1)
+})
+
+function deliveryBarHeight(value: number): string {
+ const pct = (value / deliveryRateMax.value) * 100
+ return `${Math.max(pct, value > 0 ? 2 : 0)}%`
+}
+
+const bounceMax = computed(() => {
+ if (!dashAnalytics.value) return 1
+ return Math.max(...dashAnalytics.value.bounce_rate_trends.map(d => d.total), 1)
+})
+
+function bounceBarHeight(value: number): string {
+ const pct = (value / bounceMax.value) * 100
+ return `${Math.max(pct, value > 0 ? 2 : 0)}%`
+}
+
+const totalBounces = computed(() => {
+ if (!dashAnalytics.value) return 0
+ return dashAnalytics.value.bounce_rate_trends.reduce((sum, d) => sum + d.total, 0)
+})
+
+function formatLatency(seconds: number): string {
+ if (seconds < 1) return `${Math.round(seconds * 1000)}ms`
+ if (seconds < 60) return `${seconds.toFixed(1)}s`
+ return `${(seconds / 60).toFixed(1)}m`
+}
+
+const avgDeliveryRate = computed(() => {
+ if (!dashAnalytics.value) return 0
+ const points = dashAnalytics.value.delivery_rate_trends.filter(d => d.total > 0)
+ if (points.length === 0) return 0
+ const totalSent = points.reduce((sum, d) => sum + d.sent, 0)
+ const totalAll = points.reduce((sum, d) => sum + d.total, 0)
+ return totalAll > 0 ? (totalSent / totalAll) * 100 : 0
+})
</script>
<template>
@@ -389,6 +433,95 @@ const totalBreakdown = computed(() => analytics.value?.status_breakdown?.reduce(
</div>
</template>
+ <!-- Dashboard Analytics: Delivery Rate, Bounce Rate, Latency -->
+ <template v-if="dashAnalytics">
+ <div class="metrics-section-label">Delivery Rate Trends <span class="metrics-section-sub">{{ avgDeliveryRate.toFixed(1) }}% avg</span></div>
+ <div class="card" style="margin-bottom: 28px;">
+ <div class="card-body">
+ <div v-if="dashAnalytics.delivery_rate_trends.length === 0" style="text-align: center; color: var(--text-muted); padding: 24px;">No data</div>
+ <div v-else>
+ <div class="da-chart">
+ <div
+ v-for="day in dashAnalytics.delivery_rate_trends"
+ :key="day.date"
+ class="da-bar-group"
+ :title="`${formatShortDate(day.date)}: ${day.sent} sent, ${day.failed} failed (${day.delivery_rate.toFixed(1)}%)`"
+ >
+ <div class="da-bar-stack">
+ <div class="da-bar da-bar-failed" :style="{ height: deliveryBarHeight(day.failed) }"></div>
+ <div class="da-bar da-bar-sent" :style="{ height: deliveryBarHeight(day.sent) }"></div>
+ </div>
+ <div class="da-rate-label" :class="{ 'da-rate-warning': day.delivery_rate < 90 && day.total > 0, 'da-rate-danger': day.delivery_rate < 75 && day.total > 0 }">
+ {{ day.total > 0 ? day.delivery_rate.toFixed(0) + '%' : '' }}
+ </div>
+ <div class="da-bar-date">{{ formatShortDate(day.date) }}</div>
+ </div>
+ </div>
+ <div class="da-legend">
+ <span class="legend-item"><span class="legend-dot delivery-sent"></span> Sent</span>
+ <span class="legend-item"><span class="legend-dot delivery-failed"></span> Failed</span>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <div class="metrics-section-label">Bounce Rate <span class="metrics-section-sub">{{ totalBounces }} total</span></div>
+ <div class="card" style="margin-bottom: 28px;">
+ <div class="card-body">
+ <div v-if="totalBounces === 0" style="text-align: center; color: var(--text-muted); padding: 24px;">No bounces</div>
+ <div v-else>
+ <div class="da-chart">
+ <div
+ v-for="day in dashAnalytics.bounce_rate_trends"
+ :key="day.date"
+ class="da-bar-group"
+ :title="`${formatShortDate(day.date)}: ${day.hard} hard, ${day.soft} soft, ${day.complaint} complaint`"
+ >
+ <div class="da-bar-stack">
+ <div class="da-bar da-bounce-complaint" :style="{ height: bounceBarHeight(day.complaint) }"></div>
+ <div class="da-bar da-bounce-soft" :style="{ height: bounceBarHeight(day.soft) }"></div>
+ <div class="da-bar da-bounce-hard" :style="{ height: bounceBarHeight(day.hard) }"></div>
+ </div>
+ <div class="da-bar-date">{{ formatShortDate(day.date) }}</div>
+ </div>
+ </div>
+ <div class="da-legend">
+ <span class="legend-item"><span class="legend-dot da-bounce-hard"></span> Hard</span>
+ <span class="legend-item"><span class="legend-dot da-bounce-soft"></span> Soft</span>
+ <span class="legend-item"><span class="legend-dot da-bounce-complaint"></span> Complaint</span>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <div class="metrics-section-label">Delivery Latency</div>
+ <div v-if="dashAnalytics.latency_percentiles.p50 === 0 && dashAnalytics.latency_percentiles.avg === 0" class="card" style="margin-bottom: 28px;">
+ <div class="card-body" style="text-align: center; color: var(--text-muted); padding: 24px;">No latency data</div>
+ </div>
+ <div v-else class="stats-grid" style="margin-bottom: 28px;">
+ <div class="stat-card">
+ <div class="stat-header"><div class="stat-label">Average</div></div>
+ <div class="stat-value">{{ formatLatency(dashAnalytics.latency_percentiles.avg) }}</div>
+ </div>
+ <div class="stat-card">
+ <div class="stat-header"><div class="stat-label">p50 (Median)</div></div>
+ <div class="stat-value">{{ formatLatency(dashAnalytics.latency_percentiles.p50) }}</div>
+ </div>
+ <div class="stat-card">
+ <div class="stat-header"><div class="stat-label">p75</div></div>
+ <div class="stat-value">{{ formatLatency(dashAnalytics.latency_percentiles.p75) }}</div>
+ </div>
+ <div class="stat-card">
+ <div class="stat-header"><div class="stat-label">p90</div></div>
+ <div class="stat-value">{{ formatLatency(dashAnalytics.latency_percentiles.p90) }}</div>
+ </div>
+ <div class="stat-card">
+ <div class="stat-header"><div class="stat-label">p99</div></div>
+ <div class="stat-value" style="color: var(--warning-600, #ca8a04)">{{ formatLatency(dashAnalytics.latency_percentiles.p99) }}</div>
+ </div>
+ </div>
+ </template>
+
<!-- API Keys & Reputation -->
<div class="metrics-section-label">API Keys & Reputation</div>
<div class="stats-grid">
@@ -586,4 +719,84 @@ const totalBreakdown = computed(() => analytics.value?.status_breakdown?.reduce(
font-size: 13px;
font-weight: 600;
}
+
+.metrics-section-sub {
+ font-weight: 400;
+ text-transform: none;
+ letter-spacing: 0;
+ font-size: 12px;
+ color: var(--text-muted);
+}
+
+/* Dashboard analytics charts */
+.da-chart {
+ display: flex;
+ align-items: flex-end;
+ gap: 3px;
+ height: 160px;
+ padding-bottom: 44px;
+ position: relative;
+ overflow-x: auto;
+}
+
+.da-bar-group {
+ flex: 1;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ height: 100%;
+ min-width: 24px;
+ max-width: 42px;
+ position: relative;
+}
+
+.da-bar-stack {
+ flex: 1;
+ width: 100%;
+ max-width: 32px;
+ display: flex;
+ flex-direction: column;
+ justify-content: flex-end;
+}
+
+.da-bar {
+ width: 100%;
+ min-width: 0;
+ transition: height 0.3s ease;
+}
+
+.da-bar-sent { background: var(--success-500, #22c55e); border-radius: 3px 3px 0 0; }
+.da-bar-failed { background: var(--danger-400, #f87171); }
+.da-bar-stack .da-bar:first-child { border-radius: 3px 3px 0 0; }
+
+.da-rate-label {
+ font-size: 10px;
+ color: var(--success-600, #16a34a);
+ font-weight: 600;
+ margin-top: 2px;
+ white-space: nowrap;
+}
+.da-rate-warning { color: var(--warning-600, #ca8a04); }
+.da-rate-danger { color: var(--danger-600, #dc2626); }
+
+.da-bar-date {
+ position: absolute;
+ bottom: -38px;
+ font-size: 9px;
+ color: var(--text-muted);
+ white-space: nowrap;
+ transform: rotate(-45deg);
+ transform-origin: top center;
+}
+
+.da-legend {
+ display: flex;
+ gap: 16px;
+ justify-content: center;
+ margin-top: 12px;
+}
+
+.da-bounce-hard { background: var(--danger-500, #ef4444); }
+.da-bounce-soft { background: var(--warning-500, #f59e0b); }
+.da-bounce-complaint { background: var(--purple-500, #a855f7); }
</style>
diff --git a/web/src/views/analytics/Analytics.vue b/web/src/views/analytics/Analytics.vue
index 9be788f..3bc320d 100644
--- a/web/src/views/analytics/Analytics.vue
+++ b/web/src/views/analytics/Analytics.vue
@@ -1,11 +1,12 @@
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { analyticsApi } from '../../api/analytics'
-import type { DailyCount, StatusBreakdown } from '../../api/types'
+import type { DailyCount, StatusBreakdown, DashboardAnalyticsResponse } from '../../api/types'
const loading = ref(true)
const dailyCounts = ref<DailyCount[]>([])
const statusBreakdown = ref<StatusBreakdown[]>([])
+const dashAnalytics = ref<DashboardAnalyticsResponse | null>(null)
const fromDate = ref('')
const toDate = ref('')
@@ -21,9 +22,13 @@ toDate.value = now.toISOString().slice(0, 10)
async function loadAnalytics() {
loading.value = true
try {
- const res = await analyticsApi.user(fromDate.value, toDate.value, statusFilter.value || undefined)
+ const [res, dashRes] = await Promise.all([
+ analyticsApi.user(fromDate.value, toDate.value, statusFilter.value || undefined),
+ analyticsApi.dashboardAnalytics(fromDate.value, toDate.value),
+ ])
dailyCounts.value = res.data.data.daily_counts || []
statusBreakdown.value = res.data.data.status_breakdown || []
+ dashAnalytics.value = dashRes.data.data
} catch (e) {
console.error('Failed to load analytics', e)
} finally {
@@ -64,6 +69,50 @@ function breakdownPercent(count: number): string {
if (totalBreakdown.value === 0) return '0'
return ((count / totalBreakdown.value) * 100).toFixed(1)
}
+
+// Delivery rate chart helpers
+const deliveryRateMax = computed(() => {
+ if (!dashAnalytics.value) return 1
+ return Math.max(...dashAnalytics.value.delivery_rate_trends.map(d => d.total), 1)
+})
+
+function deliveryBarHeight(value: number): string {
+ const pct = (value / deliveryRateMax.value) * 100
+ return `${Math.max(pct, value > 0 ? 2 : 0)}%`
+}
+
+// Bounce rate chart helpers
+const bounceMax = computed(() => {
+ if (!dashAnalytics.value) return 1
+ return Math.max(...dashAnalytics.value.bounce_rate_trends.map(d => d.total), 1)
+})
+
+function bounceBarHeight(value: number): string {
+ const pct = (value / bounceMax.value) * 100
+ return `${Math.max(pct, value > 0 ? 2 : 0)}%`
+}
+
+const totalBounces = computed(() => {
+ if (!dashAnalytics.value) return 0
+ return dashAnalytics.value.bounce_rate_trends.reduce((sum, d) => sum + d.total, 0)
+})
+
+// Latency formatting
+function formatLatency(seconds: number): string {
+ if (seconds < 1) return `${Math.round(seconds * 1000)}ms`
+ if (seconds < 60) return `${seconds.toFixed(1)}s`
+ return `${(seconds / 60).toFixed(1)}m`
+}
+
+// Average delivery rate
+const avgDeliveryRate = computed(() => {
+ if (!dashAnalytics.value) return 0
+ const points = dashAnalytics.value.delivery_rate_trends.filter(d => d.total > 0)
+ if (points.length === 0) return 0
+ const totalSent = points.reduce((sum, d) => sum + d.sent, 0)
+ const totalAll = points.reduce((sum, d) => sum + d.total, 0)
+ return totalAll > 0 ? (totalSent / totalAll) * 100 : 0
+})
</script>
<template>
@@ -178,6 +227,119 @@ function breakdownPercent(count: number): string {
</div>
</div>
</div>
+
+ <!-- Dashboard Analytics: Delivery Rate, Bounce Rate, Latency -->
+ <template v-if="dashAnalytics">
+ <!-- Delivery Rate Trends -->
+ <div class="card" style="margin-top: 24px">
+ <div class="card-header">
+ <h2>Delivery Rate Trends <span class="card-header-sub">{{ avgDeliveryRate.toFixed(1) }}% avg</span></h2>
+ </div>
+ <div class="card-body">
+ <div v-if="dashAnalytics.delivery_rate_trends.length === 0" class="empty-state">
+ <h3>No data</h3>
+ <p>No delivery data in the selected range.</p>
+ </div>
+ <div v-else>
+ <div class="trend-chart">
+ <div class="trend-chart-bars">
+ <div
+ v-for="day in dashAnalytics.delivery_rate_trends"
+ :key="day.date"
+ class="trend-bar-group"
+ :title="`${formatDate(day.date)}: ${day.sent} sent, ${day.failed} failed (${day.delivery_rate.toFixed(1)}%)`"
+ >
+ <div class="trend-bar-stack">
+ <div class="trend-bar trend-bar-failed" :style="{ height: deliveryBarHeight(day.failed) }"></div>
+ <div class="trend-bar trend-bar-sent" :style="{ height: deliveryBarHeight(day.sent) }"></div>
+ </div>
+ <div class="trend-rate-label" :class="{ 'rate-warning': day.delivery_rate < 90 && day.total > 0, 'rate-danger': day.delivery_rate < 75 && day.total > 0 }">
+ {{ day.total > 0 ? day.delivery_rate.toFixed(0) + '%' : '' }}
+ </div>
+ <div class="trend-bar-date">{{ formatDate(day.date) }}</div>
+ </div>
+ </div>
+ <div class="trend-chart-legend">
+ <span class="trend-legend-item"><span class="trend-legend-dot trend-legend-sent"></span> Sent</span>
+ <span class="trend-legend-item"><span class="trend-legend-dot trend-legend-failed"></span> Failed</span>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Bounce Rate Graph -->
+ <div class="card" style="margin-top: 24px">
+ <div class="card-header">
+ <h2>Bounce Rate <span class="card-header-sub">{{ totalBounces }} total bounces</span></h2>
+ </div>
+ <div class="card-body">
+ <div v-if="totalBounces === 0" class="empty-state">
+ <h3>No bounces</h3>
+ <p>No bounces recorded in the selected range.</p>
+ </div>
+ <div v-else>
+ <div class="trend-chart">
+ <div class="trend-chart-bars">
+ <div
+ v-for="day in dashAnalytics.bounce_rate_trends"
+ :key="day.date"
+ class="trend-bar-group"
+ :title="`${formatDate(day.date)}: ${day.hard} hard, ${day.soft} soft, ${day.complaint} complaint`"
+ >
+ <div class="trend-bar-stack">
+ <div class="trend-bar bounce-bar-complaint" :style="{ height: bounceBarHeight(day.complaint) }"></div>
+ <div class="trend-bar bounce-bar-soft" :style="{ height: bounceBarHeight(day.soft) }"></div>
+ <div class="trend-bar bounce-bar-hard" :style="{ height: bounceBarHeight(day.hard) }"></div>
+ </div>
+ <div class="trend-bar-date">{{ formatDate(day.date) }}</div>
+ </div>
+ </div>
+ <div class="trend-chart-legend">
+ <span class="trend-legend-item"><span class="trend-legend-dot bounce-legend-hard"></span> Hard</span>
+ <span class="trend-legend-item"><span class="trend-legend-dot bounce-legend-soft"></span> Soft</span>
+ <span class="trend-legend-item"><span class="trend-legend-dot bounce-legend-complaint"></span> Complaint</span>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Latency Percentiles -->
+ <div class="card" style="margin-top: 24px">
+ <div class="card-header">
+ <h2>Delivery Latency</h2>
+ </div>
+ <div class="card-body">
+ <div v-if="dashAnalytics.latency_percentiles.p50 === 0 && dashAnalytics.latency_percentiles.avg === 0" class="empty-state">
+ <h3>No data</h3>
+ <p>No delivered emails in the selected range.</p>
+ </div>
+ <div v-else class="latency-grid">
+ <div class="latency-card">
+ <div class="latency-value">{{ formatLatency(dashAnalytics.latency_percentiles.avg) }}</div>
+ <div class="latency-label">Average</div>
+ </div>
+ <div class="latency-card">
+ <div class="latency-value">{{ formatLatency(dashAnalytics.latency_percentiles.p50) }}</div>
+ <div class="latency-label">p50 (Median)</div>
+ </div>
+ <div class="latency-card">
+ <div class="latency-value">{{ formatLatency(dashAnalytics.latency_percentiles.p75) }}</div>
+ <div class="latency-label">p75</div>
+ </div>
+ <div class="latency-card">
+ <div class="latency-value">{{ formatLatency(dashAnalytics.latency_percentiles.p90) }}</div>
+ <div class="latency-label">p90</div>
+ </div>
+ <div class="latency-card">
+ <div class="latency-value latency-value-tail">{{ formatLatency(dashAnalytics.latency_percentiles.p99) }}</div>
+ <div class="latency-label">p99</div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </template>
</template>
</div>
</template>
@@ -306,4 +468,166 @@ function breakdownPercent(count: number): string {
font-weight: 400;
color: var(--text-muted);
}
+
+/* Card header subtitle */
+.card-header-sub {
+ font-weight: 400;
+ font-size: 13px;
+ color: var(--text-muted);
+}
+
+/* Delivery rate & bounce trend charts */
+.trend-chart {
+ padding: 8px 0;
+}
+
+.trend-chart-bars {
+ display: flex;
+ align-items: flex-end;
+ gap: 3px;
+ height: 160px;
+ padding-bottom: 44px;
+ position: relative;
+ overflow-x: auto;
+}
+
+.trend-bar-group {
+ flex: 1;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ height: 100%;
+ min-width: 24px;
+ max-width: 42px;
+ position: relative;
+}
+
+.trend-bar-stack {
+ flex: 1;
+ width: 100%;
+ max-width: 32px;
+ display: flex;
+ flex-direction: column;
+ justify-content: flex-end;
+ position: relative;
+}
+
+.trend-bar {
+ width: 100%;
+ min-width: 0;
+ transition: height 0.3s ease;
+}
+
+.trend-bar-sent {
+ background: var(--success-500, #22c55e);
+ border-radius: 3px 3px 0 0;
+}
+
+.trend-bar-failed {
+ background: var(--danger-400, #f87171);
+}
+
+.trend-bar-stack .trend-bar:first-child {
+ border-radius: 3px 3px 0 0;
+}
+
+.trend-rate-label {
+ font-size: 10px;
+ color: var(--success-600, #16a34a);
+ font-weight: 600;
+ margin-top: 2px;
+ white-space: nowrap;
+}
+
+.trend-rate-label.rate-warning {
+ color: var(--warning-600, #ca8a04);
+}
+
+.trend-rate-label.rate-danger {
+ color: var(--danger-600, #dc2626);
+}
+
+.trend-bar-date {
+ position: absolute;
+ bottom: -38px;
+ font-size: 10px;
+ color: var(--text-muted);
+ white-space: nowrap;
+ transform: rotate(-45deg);
+ transform-origin: top center;
+}
+
+.trend-chart-legend {
+ display: flex;
+ gap: 16px;
+ justify-content: center;
+ margin-top: 12px;
+}
+
+.trend-legend-item {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ font-size: 12px;
+ color: var(--text-muted);
+}
+
+.trend-legend-dot {
+ width: 10px;
+ height: 10px;
+ border-radius: 2px;
+}
+
+.trend-legend-sent { background: var(--success-500, #22c55e); }
+.trend-legend-failed { background: var(--danger-400, #f87171); }
+
+/* Bounce type colors */
+.bounce-bar-hard { background: var(--danger-500, #ef4444); }
+.bounce-bar-soft { background: var(--warning-500, #f59e0b); }
+.bounce-bar-complaint { background: var(--purple-500, #a855f7); }
+.bounce-legend-hard { background: var(--danger-500, #ef4444); }
+.bounce-legend-soft { background: var(--warning-500, #f59e0b); }
+.bounce-legend-complaint { background: var(--purple-500, #a855f7); }
+
+/* Latency percentiles */
+.latency-grid {
+ display: grid;
+ grid-template-columns: repeat(5, 1fr);
+ gap: 12px;
+}
+
+@media (max-width: 768px) {
+ .latency-grid {
+ grid-template-columns: repeat(3, 1fr);
+ }
+}
+
+@media (max-width: 480px) {
+ .latency-grid {
+ grid-template-columns: repeat(2, 1fr);
+ }
+}
+
+.latency-card {
+ text-align: center;
+ padding: 16px 8px;
+ background: var(--bg-secondary);
+ border-radius: 8px;
+}
+
+.latency-value {
+ font-size: 22px;
+ font-weight: 700;
+ color: var(--text-primary);
+}
+
+.latency-value-tail {
+ color: var(--warning-600, #ca8a04);
+}
+
+.latency-label {
+ font-size: 12px;
+ color: var(--text-muted);
+ margin-top: 4px;
+}
</style>
diff --git a/web/src/views/auth/Profile.vue b/web/src/views/auth/Profile.vue
index 86f1c32..53e853c 100644
--- a/web/src/views/auth/Profile.vue
+++ b/web/src/views/auth/Profile.vue
@@ -1,10 +1,13 @@
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { authApi } from '../../api/auth'
+import { sessionsApi, type Session } from '../../api/sessions'
import { useAuthStore } from '../../stores/auth'
import { useNotificationStore } from '../../stores/notification'
+import { useConfirm } from '../../composables/useConfirm'
const auth = useAuthStore()
const notify = useNotificationStore()
+const { confirm } = useConfirm()
// Profile
const name = ref('')
@@ -149,6 +152,87 @@ function cancel2FASetup() {
tfaSecret.value = ''
tfaURL.value = ''
}
+
+// Sessions
+const sessions = ref<Session[]>([])
+const sessionsLoading = ref(false)
+const revokingSession = ref<number | null>(null)
+const revokingOthers = ref(false)
+
+async function loadSessions() {
+ sessionsLoading.value = true
+ try {
+ const res = await sessionsApi.list()
+ sessions.value = res.data.data || []
+ } catch {
+ // silently fail — sessions card still shows
+ } finally {
+ sessionsLoading.value = false
+ }
+}
+
+async function revokeSession(s: Session) {
+ const confirmed = await confirm({
+ title: 'Revoke Session',
+ message: `Force logout the session from ${s.ip_address}?`,
+ confirmText: 'Revoke',
+ variant: 'danger',
+ })
+ if (!confirmed) return
+
+ revokingSession.value = s.id
+ try {
+ await sessionsApi.revoke(s.id)
+ sessions.value = sessions.value.filter(x => x.id !== s.id)
+ notify.success('Session revoked')
+ } catch (e: any) {
+ notify.error(e.response?.data?.error?.message || 'Failed to revoke session')
+ } finally {
+ revokingSession.value = null
+ }
+}
+
+async function revokeOtherSessions() {
+ const confirmed = await confirm({
+ title: 'Revoke All Other Sessions',
+ message: 'This will force logout all other devices and browsers. Continue?',
+ confirmText: 'Revoke All Others',
+ variant: 'danger',
+ })
+ if (!confirmed) return
+
+ revokingOthers.value = true
+ try {
+ const res = await sessionsApi.revokeOthers()
+ notify.success(res.data.data.message)
+ await loadSessions()
+ } catch (e: any) {
+ notify.error(e.response?.data?.error?.message || 'Failed to revoke sessions')
+ } finally {
+ revokingOthers.value = false
+ }
+}
+
+function parseUserAgent(ua: string): string {
+ if (!ua) return 'Unknown'
+ // Extract browser name
+ if (ua.includes('Firefox')) return 'Firefox'
+ if (ua.includes('Edg/')) return 'Edge'
+ if (ua.includes('Chrome')) return 'Chrome'
+ if (ua.includes('Safari')) return 'Safari'
+ if (ua.includes('curl')) return 'curl'
+ return ua.slice(0, 30) + (ua.length > 30 ? '...' : '')
+}
+
+function formatSessionDate(dateStr: string): string {
+ return new Date(dateStr).toLocaleDateString(undefined, {
+ year: 'numeric', month: 'short', day: 'numeric',
+ hour: '2-digit', minute: '2-digit',
+ })
+}
+
+// Load sessions on mount
+onMounted(() => { loadSessions() })
</script>
<template>
@@ -265,6 +349,56 @@ function cancel2FASetup() {
</div>
</div>
+ <!-- Active Sessions -->
+ <div class="card">
+ <div class="card-header">
+ <h2>Active Sessions</h2>
+ <button
+ v-if="sessions.length > 1"
+ class="btn btn-danger btn-sm"
+ :disabled="revokingOthers"
+ @click="revokeOtherSessions"
+ >
+ {{ revokingOthers ? 'Revoking...' : 'Revoke All Others' }}
+ </button>
+ </div>
+ <div class="card-body">
+ <p class="tfa-description">
+ These are the devices and browsers currently logged in to your account.
+ </p>
+
+ <div v-if="sessionsLoading" style="text-align: center; padding: 20px 0">
+ <div class="spinner"></div>
+ </div>
+
+ <div v-else-if="sessions.length === 0" class="text-muted" style="text-align: center; padding: 16px 0">
+ No active sessions found.
+ </div>
+
+ <div v-else class="session-list">
+ <div v-for="s in sessions" :key="s.id" class="session-item" :class="{ 'session-current': s.current }">
+ <div class="session-info">
+ <div class="session-browser">
+ {{ parseUserAgent(s.user_agent) }}
+ <span v-if="s.current" class="badge badge-success" style="margin-left: 6px">Current</span>
+ </div>
+ <div class="session-meta">
+ {{ s.ip_address }} &middot; Created {{ formatSessionDate(s.created_at) }} &middot; Expires {{ formatSessionDate(s.expires_at) }}
+ </div>
+ </div>
+ <button
+ v-if="!s.current"
+ class="btn btn-danger btn-sm"
+ :disabled="revokingSession === s.id"
+ @click="revokeSession(s)"
+ >
+ {{ revokingSession === s.id ? 'Revoking...' : 'Revoke' }}
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+
<!-- Change Password -->
<div class="card">
<div class="card-header"><h2>Change Password</h2></div>
@@ -356,4 +490,42 @@ function cancel2FASetup() {
font-family: 'JetBrains Mono', 'Fira Code', monospace;
max-width: 220px;
}
+
+.session-list {
+ display: grid;
+ gap: 8px;
+}
+
+.session-item {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 12px 14px;
+ border: 1px solid var(--border-primary);
+ border-radius: var(--radius);
+ background: var(--bg-secondary);
+}
+
+.session-current {
+ border-color: var(--primary-300);
+ background: var(--primary-50, rgba(147, 51, 234, 0.04));
+}
+
+.session-info {
+ min-width: 0;
+}
+
+.session-browser {
+ font-size: 14px;
+ font-weight: 500;
+ color: var(--text-primary);
+ display: flex;
+ align-items: center;
+}
+
+.session-meta {
+ font-size: 12px;
+ color: var(--text-muted);
+ margin-top: 2px;
+}
</style>
diff --git a/web/src/views/emails/EmailPreview.vue b/web/src/views/emails/EmailPreview.vue
new file mode 100644
index 0000000..6482585
--- /dev/null
+++ b/web/src/views/emails/EmailPreview.vue
@@ -0,0 +1,207 @@
+<script setup lang="ts">
+import { ref, onMounted, watch } from 'vue'
+import { useRouter } from 'vue-router'
+import { emailsApi } from '../../api/emails'
+import type { EmailPreviewResponse } from '../../api/emails'
+import { templatesApi } from '../../api/templates'
+import type { Template } from '../../api/types'
+import { useNotificationStore } from '../../stores/notification'
+
+const router = useRouter()
+const notify = useNotificationStore()
+
+const templates = ref<Template[]>([])
+const selectedTemplate = ref('')
+const language = ref('')
+const sampleData = ref('{\n \n}')
+const preview = ref<EmailPreviewResponse | null>(null)
+const loading = ref(true)
+const previewLoading = ref(false)
+const previewError = ref('')
+const activeTab = ref<'html' | 'text'>('html')
+
+onMounted(async () => {
+ try {
+ const res = await templatesApi.list(0, 100)
+ templates.value = res.data.data || []
+ } catch {
+ notify.error('Failed to load templates')
+ } finally {
+ loading.value = false
+ }
+})
+
+watch(selectedTemplate, (name) => {
+ const tmpl = templates.value.find(t => t.name === name)
+ if (tmpl) {
+ language.value = tmpl.default_language || ''
+ if (tmpl.sample_data) sampleData.value = tmpl.sample_data
+ }
+ preview.value = null
+ previewError.value = ''
+})
+
+async function renderPreview() {
+ if (!selectedTemplate.value) {
+ previewError.value = 'Select a template first'
+ return
+ }
+
+ previewLoading.value = true
+ previewError.value = ''
+ preview.value = null
+
+ let data: Record<string, any> = {}
+ try {
+ const trimmed = sampleData.value.trim()
+ if (trimmed) data = JSON.parse(trimmed)
+ } catch {
+ previewError.value = 'Invalid JSON in template data'
+ previewLoading.value = false
+ return
+ }
+
+ try {
+ const res = await emailsApi.preview({
+ template: selectedTemplate.value,
+ language: language.value || undefined,
+ template_data: Object.keys(data).length > 0 ? data : undefined,
+ })
+ preview.value = res.data.data
+ } catch (e: any) {
+ previewError.value = e.response?.data?.error?.message || 'Failed to render preview'
+ } finally {
+ previewLoading.value = false
+ }
+}
+</script>
+
+<template>
+ <div>
+ <div class="page-header">
+ <h1>Email Preview</h1>
+ <button class="btn btn-secondary" @click="router.push('/emails')">Back to Emails</button>
+ </div>
+
+ <div v-if="loading" class="loading-page">
+ <div class="spinner"></div>
+ </div>
+
+ <template v-else>
+ <!-- Template Selection -->
+ <div class="card" style="margin-bottom: 24px;">
+ <div class="card-header">
+ <h2>Configuration</h2>
+ <button
+ class="btn btn-primary btn-sm"
+ :disabled="previewLoading || !selectedTemplate"
+ @click="renderPreview"
+ >
+ {{ previewLoading ? 'Rendering...' : 'Render Preview' }}
+ </button>
+ </div>
+ <div class="card-body">
+ <div class="form-grid">
+ <div class="form-group">
+ <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>
+ </select>
+ </div>
+ <div class="form-group">
+ <label class="form-label">Language</label>
+ <input v-model="language" type="text" class="form-input" placeholder="e.g. en, fr, de" />
+ <span class="form-hint">Leave empty to use the template default.</span>
+ </div>
+ </div>
+ <div class="form-group" style="margin-top: 16px;">
+ <label class="form-label">Template Data (JSON)</label>
+ <textarea
+ v-model="sampleData"
+ class="form-textarea"
+ rows="5"
+ placeholder='{"name": "John", "company": "Acme"}'
+ @keydown.ctrl.enter="renderPreview"
+ @keydown.meta.enter="renderPreview"
+ ></textarea>
+ <span class="form-hint">JSON variables to inject into the template. Press Ctrl+Enter to render.</span>
+ </div>
+ </div>
+ </div>
+
+ <!-- Error -->
+ <div v-if="previewError" class="preview-error" style="margin-bottom: 24px;">
+ {{ previewError }}
+ </div>
+
+ <!-- Rendered Preview -->
+ <template v-if="preview">
+ <div class="card" style="margin-bottom: 24px;">
+ <div class="card-header"><h2>Rendered Subject</h2></div>
+ <div class="card-body">
+ <div style="font-size: 16px; font-weight: 500; color: var(--text-primary);">{{ preview.subject }}</div>
+ </div>
+ </div>
+
+ <div class="card">
+ <div class="card-header">
+ <div class="tabs" style="margin-bottom: 0;">
+ <button class="tab" :class="{ active: activeTab === 'html' }" @click="activeTab = 'html'">HTML Preview</button>
+ <button class="tab" :class="{ active: activeTab === 'text' }" @click="activeTab = 'text'">Plain Text</button>
+ </div>
+ </div>
+ <div class="card-body">
+ <div v-if="activeTab === 'html'">
+ <div v-if="preview.html" class="preview-html-frame">
+ <iframe :srcdoc="preview.html" sandbox="" class="preview-iframe"></iframe>
+ </div>
+ <div v-else class="text-muted" style="text-align: center; padding: 20px 0;">
+ No HTML content rendered.
+ </div>
+ </div>
+ <pre
+ v-else
+ style="white-space: pre-wrap; word-wrap: break-word; font-size: 14px; color: var(--text-secondary); line-height: 1.6; margin: 0;"
+ >{{ preview.text || 'No text content rendered.' }}</pre>
+ </div>
+ </div>
+ </template>
+ </template>
+ </div>
+</template>
+
+<style scoped>
+.form-grid {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 16px;
+}
+
+.preview-error {
+ padding: 12px 16px;
+ background: var(--danger-50);
+ color: var(--danger-600);
+ border-radius: var(--radius);
+ font-size: 13px;
+}
+
+.preview-html-frame {
+ border: 1px solid var(--border-primary);
+ border-radius: var(--radius);
+ overflow: hidden;
+}
+
+.preview-iframe {
+ width: 100%;
+ min-height: 400px;
+ border: none;
+ background: #fff;
+}
+
+@media (max-width: 640px) {
+ .form-grid {
+ grid-template-columns: 1fr;
+ }
+}
+</style>
diff --git a/web/src/views/emails/Emails.vue b/web/src/views/emails/Emails.vue
index e04c437..3c4df3e 100644
--- a/web/src/views/emails/Emails.vue
+++ b/web/src/views/emails/Emails.vue
@@ -46,6 +46,7 @@ function formatDate(date: string | null) {
<div>
<div class="page-header">
<h1>Email Logs</h1>
+ <button class="btn btn-secondary" @click="router.push('/emails/preview')">Preview Template</button>
</div>
<div v-if="loading" class="loading-page">
diff --git a/web/src/views/settings/Settings.vue b/web/src/views/settings/Settings.vue
index fed1a3e..73c1aca 100644
--- a/web/src/views/settings/Settings.vue
+++ b/web/src/views/settings/Settings.vue
@@ -2,17 +2,29 @@
import { ref, onMounted } from 'vue'
import { settingsApi } from '../../api/settings'
import { authApi } from '../../api/auth'
+import { userDataApi } from '../../api/userData'
import { useAuthStore } from '../../stores/auth'
import { useThemeStore, type ThemeMode } from '../../stores/theme'
import { useNotificationStore } from '../../stores/notification'
+import { useConfirm } from '../../composables/useConfirm'
import type { UserSettings } from '../../api/types'
const auth = useAuthStore()
const theme = useThemeStore()
const notify = useNotificationStore()
+const { confirm } = useConfirm()
const loading = ref(true)
const saving = ref(false)
+// Data management
+const exporting = ref(false)
+const importing = ref(false)
+const deletingContacts = ref(false)
+const deletingEmails = ref(false)
+const gdprEmail = ref('')
+const gdprDays = ref(90)
+const importFileRef = ref<HTMLInputElement | null>(null)
+
const form = ref<Partial<UserSettings>>({
timezone: 'UTC',
default_sender_name: '',
@@ -93,6 +105,111 @@ async function save() {
}
}
+async function exportData() {
+ exporting.value = true
+ try {
+ const res = await userDataApi.exportAll()
+ const blob = new Blob([JSON.stringify(res.data.data, null, 2)], { type: 'application/json' })
+ const url = URL.createObjectURL(blob)
+ const a = document.createElement('a')
+ a.href = url
+ a.download = `posta-export-${new Date().toISOString().slice(0, 10)}.json`
+ a.click()
+ URL.revokeObjectURL(url)
+ notify.success('Data exported successfully')
+ } catch {
+ notify.error('Failed to export data')
+ } finally {
+ exporting.value = false
+ }
+}
+
+function triggerImport() {
+ importFileRef.value?.click()
+}
+
+async function handleImportFile(event: Event) {
+ const file = (event.target as HTMLInputElement).files?.[0]
+ if (!file) return
+
+ const confirmed = await confirm({
+ title: 'Import Data',
+ message: 'This will import data from the selected file. Duplicate items will be skipped. Continue?',
+ confirmText: 'Import',
+ variant: 'danger',
+ })
+ if (!confirmed) {
+ if (importFileRef.value) importFileRef.value.value = ''
+ return
+ }
+
+ importing.value = true
+ try {
+ const text = await file.text()
+ const data = JSON.parse(text)
+ const res = await userDataApi.importAll(data)
+ notify.success(res.data.data.message || 'Data imported successfully')
+ } catch (e: any) {
+ if (e instanceof SyntaxError) {
+ notify.error('Invalid JSON file')
+ } else {
+ notify.error(e.response?.data?.error?.message || 'Failed to import data')
+ }
+ } finally {
+ importing.value = false
+ if (importFileRef.value) importFileRef.value.value = ''
+ }
+}
+
+async function deleteContacts() {
+ const target = gdprEmail.value.trim()
+ const msg = target
+ ? `Delete contact "${target}" and remove from all lists and suppression?`
+ : 'Delete ALL contacts? This cannot be undone.'
+ const confirmed = await confirm({
+ title: 'Delete Contact Data',
+ message: msg,
+ confirmText: 'Delete',
+ variant: 'danger',
+ })
+ if (!confirmed) return
+
+ deletingContacts.value = true
+ try {
+ const res = await userDataApi.deleteContacts(target || undefined)
+ notify.success(res.data.data.message)
+ gdprEmail.value = ''
+ } catch (e: any) {
+ notify.error(e.response?.data?.error?.message || 'Failed to delete contacts')
+ } finally {
+ deletingContacts.value = false
+ }
+}
+
+async function deleteEmailLogs() {
+ const days = gdprDays.value
+ const msg = days > 0
+ ? `Delete all email logs older than ${days} days and their associated bounces?`
+ : 'Delete ALL email logs and associated bounces? This cannot be undone.'
+ const confirmed = await confirm({
+ title: 'Delete Email Logs',
+ message: msg,
+ confirmText: 'Delete',
+ variant: 'danger',
+ })
+ if (!confirmed) return
+
+ deletingEmails.value = true
+ try {
+ const res = await userDataApi.deleteEmailLogs(days)
+ notify.success(res.data.data.message)
+ } catch (e: any) {
+ notify.error(e.response?.data?.error?.message || 'Failed to delete email logs')
+ } finally {
+ deletingEmails.value = false
+ }
+}
+
async function toggleDomainSecurity() {
domainSecurityLoading.value = true
try {
@@ -250,6 +367,66 @@ async function toggleDomainSecurity() {
</div>
</div>
+ <!-- Data Export/Import -->
+ <div class="card">
+ <div class="card-header"><h2>Data Export / Import</h2></div>
+ <div class="card-body">
+ <p class="section-description">
+ Export all your data (templates, stylesheets, languages, contacts, contact lists, webhooks, suppressions, and settings) as a JSON file.
+ You can import this file later to restore your data on this or another Posta instance.
+ </p>
+ <div class="flex gap-2">
+ <button class="btn btn-primary" :disabled="exporting" @click="exportData">
+ {{ exporting ? 'Exporting...' : 'Export All Data' }}
+ </button>
+ <button class="btn btn-secondary" :disabled="importing" @click="triggerImport">
+ {{ importing ? 'Importing...' : 'Import Data' }}
+ </button>
+ <input ref="importFileRef" type="file" accept=".json" style="display: none" @change="handleImportFile" />
+ </div>
+ </div>
+ </div>
+
+ <!-- GDPR Data Management -->
+ <div class="card">
+ <div class="card-header">
+ <h2>Data Management (GDPR)</h2>
+ </div>
+ <div class="card-body">
+ <p class="section-description">
+ Manage personal data for GDPR compliance. Delete specific contacts or purge old email logs.
+ </p>
+
+ <div class="gdpr-section">
+ <h3 class="gdpr-title">Delete Contact Data</h3>
+ <p class="section-description">
+ Remove a specific contact by email (including suppression list and list memberships), or leave empty to delete all contacts.
+ </p>
+ <div class="flex gap-2 align-center">
+ <input v-model="gdprEmail" type="email" class="form-input" placeholder="[email protected] (or leave empty for all)" style="flex: 1" />
+ <button class="btn btn-danger" :disabled="deletingContacts" @click="deleteContacts">
+ {{ deletingContacts ? 'Deleting...' : 'Delete' }}
+ </button>
+ </div>
+ </div>
+
+ <div class="gdpr-section" style="margin-top: 24px">
+ <h3 class="gdpr-title">Delete Email Logs</h3>
+ <p class="section-description">
+ Delete email logs and associated bounce records. Set days to 0 to delete all logs.
+ </p>
+ <div class="flex gap-2 align-center">
+ <label class="form-label" style="margin: 0; white-space: nowrap">Older than</label>
+ <input v-model.number="gdprDays" type="number" class="form-input" min="0" style="width: 100px" />
+ <label class="form-label" style="margin: 0">days</label>
+ <button class="btn btn-danger" :disabled="deletingEmails" @click="deleteEmailLogs">
+ {{ deletingEmails ? 'Deleting...' : 'Delete Logs' }}
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+
<!-- Theme -->
<div class="card">
<div class="card-header"><h2>Theme</h2></div>
@@ -394,4 +571,15 @@ async function toggleDomainSecurity() {
font-size: 13px;
font-weight: 500;
}
+
+.align-center {
+ align-items: center;
+}
+
+.gdpr-section h3.gdpr-title {
+ font-size: 14px;
+ font-weight: 600;
+ color: var(--text-primary);
+ margin: 0 0 4px;
+}
</style>
diff --git a/web/src/views/templates/TemplateDetail.vue b/web/src/views/templates/TemplateDetail.vue
index c8f5542..c644aad 100644
--- a/web/src/views/templates/TemplateDetail.vue
+++ b/web/src/views/templates/TemplateDetail.vue
@@ -584,8 +584,14 @@ onMounted(loadAll);
>
Preview
</button>
+ <button
+ class="btn btn-secondary btn-sm"
+ @click="router.push(`/templates/${templateId}/versions/${selectedVersion?.id}/localizations/${l.id}/edit`)"
+ >
+ Editor
+ </button>
<button class="btn btn-secondary btn-sm" @click="openEditLoc(l)">
- Edit
+ Quick Edit
</button>
<button class="btn btn-danger btn-sm" @click="deleteLoc(l)">
Delete
diff --git a/web/src/views/templates/TemplateEditor.vue b/web/src/views/templates/TemplateEditor.vue
new file mode 100644
index 0000000..868078c
--- /dev/null
+++ b/web/src/views/templates/TemplateEditor.vue
@@ -0,0 +1,625 @@
+<script setup lang="ts">
+import { ref, onMounted, onBeforeUnmount, shallowRef } from 'vue'
+import { useRoute, useRouter } from 'vue-router'
+import { templatesApi } from '../../api/templates'
+import type {
+ Template,
+ TemplateVersion,
+ TemplateLocalization,
+ TemplatePreview,
+} from '../../api/types'
+import { useNotificationStore } from '../../stores/notification'
+
+// CodeMirror
+import { EditorView, placeholder as cmPlaceholder } from '@codemirror/view'
+import { EditorState } from '@codemirror/state'
+import { html } from '@codemirror/lang-html'
+import { json } from '@codemirror/lang-json'
+import { oneDark } from '@codemirror/theme-one-dark'
+import { basicSetup } from 'codemirror'
+
+const route = useRoute()
+const router = useRouter()
+const notify = useNotificationStore()
+
+const templateId = Number(route.params.id)
+const versionId = Number(route.params.versionId)
+const localizationId = Number(route.params.localizationId)
+
+const template = ref<Template | null>(null)
+const version = ref<TemplateVersion | null>(null)
+const localization = ref<TemplateLocalization | null>(null)
+const loading = ref(true)
+const saving = ref(false)
+const hasChanges = ref(false)
+
+// Editor state
+const activeTab = ref<'html' | 'text' | 'subject'>('html')
+const subjectValue = ref('')
+const htmlValue = ref('')
+const textValue = ref('')
+const sampleDataValue = ref('{\n "name": "John",\n "company": "Acme"\n}')
+
+// Preview
+const preview = ref<TemplatePreview | null>(null)
+const previewLoading = ref(false)
+const previewError = ref('')
+const previewTab = ref<'html' | 'text'>('html')
+const showPreviewPanel = ref(true)
+
+// CodeMirror editor refs
+const htmlEditorRef = ref<HTMLElement | null>(null)
+const textEditorRef = ref<HTMLElement | null>(null)
+const subjectEditorRef = ref<HTMLElement | null>(null)
+const sampleDataEditorRef = ref<HTMLElement | null>(null)
+
+const htmlEditor = shallowRef<EditorView | null>(null)
+const textEditor = shallowRef<EditorView | null>(null)
+const subjectEditor = shallowRef<EditorView | null>(null)
+const sampleDataEditor = shallowRef<EditorView | null>(null)
+
+function createEditor(
+ container: HTMLElement,
+ content: string,
+ lang: 'html' | 'json' | 'text',
+ onChange: (value: string) => void,
+ placeholderText?: string,
+): EditorView {
+ const extensions = [
+ basicSetup,
+ EditorView.lineWrapping,
+ EditorView.updateListener.of((update) => {
+ if (update.docChanged) {
+ onChange(update.state.doc.toString())
+ }
+ }),
+ ]
+
+ if (lang === 'html') extensions.push(html())
+ if (lang === 'json') extensions.push(json())
+ if (placeholderText) extensions.push(cmPlaceholder(placeholderText))
+
+ // Always use dark theme for code editors — looks better for code
+ extensions.push(oneDark)
+ extensions.push(editorTheme)
+
+ const state = EditorState.create({
+ doc: content,
+ extensions,
+ })
+
+ return new EditorView({ state, parent: container })
+}
+
+const editorTheme = EditorView.theme({
+ '&': {
+ fontSize: '13px',
+ height: '100%',
+ },
+ '.cm-scroller': {
+ fontFamily: '"JetBrains Mono", "Fira Code", "Cascadia Code", monospace',
+ },
+ '.cm-content': {
+ minHeight: '100px',
+ },
+})
+
+let debounceTimer: ReturnType<typeof setTimeout> | null = null
+
+function schedulePreview() {
+ if (debounceTimer) clearTimeout(debounceTimer)
+ debounceTimer = setTimeout(() => renderPreview(), 600)
+}
+
+async function renderPreview() {
+ if (!template.value) return
+ previewLoading.value = true
+ previewError.value = ''
+
+ let data: Record<string, any> = {}
+ try {
+ data = JSON.parse(sampleDataValue.value)
+ } catch {
+ previewError.value = 'Invalid JSON in sample data'
+ previewLoading.value = false
+ return
+ }
+
+ try {
+ const res = await templatesApi.previewLocalization(templateId, versionId, {
+ language: localization.value?.language || template.value.default_language,
+ template_data: data,
+ })
+ preview.value = res.data.data
+ } catch (e: any) {
+ previewError.value = e.response?.data?.error?.message || 'Failed to render preview'
+ } finally {
+ previewLoading.value = false
+ }
+}
+
+async function save() {
+ if (!localization.value) return
+ saving.value = true
+ try {
+ const res = await templatesApi.updateLocalization(localizationId, {
+ subject_template: subjectValue.value,
+ html_template: htmlValue.value,
+ text_template: textValue.value,
+ })
+ localization.value = res.data.data
+ hasChanges.value = false
+ notify.success('Localization saved')
+ renderPreview()
+ } catch (e: any) {
+ notify.error(e.response?.data?.error?.message || 'Failed to save')
+ } finally {
+ saving.value = false
+ }
+}
+
+function handleKeydown(e: KeyboardEvent) {
+ if ((e.metaKey || e.ctrlKey) && e.key === 's') {
+ e.preventDefault()
+ save()
+ }
+}
+
+function initEditors() {
+ if (htmlEditorRef.value) {
+ htmlEditor.value = createEditor(htmlEditorRef.value, htmlValue.value, 'html', (val) => {
+ htmlValue.value = val
+ hasChanges.value = true
+ schedulePreview()
+ }, '<html>...</html>')
+ }
+ if (textEditorRef.value) {
+ textEditor.value = createEditor(textEditorRef.value, textValue.value, 'text', (val) => {
+ textValue.value = val
+ hasChanges.value = true
+ schedulePreview()
+ }, 'Plain text version...')
+ }
+ if (subjectEditorRef.value) {
+ subjectEditor.value = createEditor(subjectEditorRef.value, subjectValue.value, 'text', (val) => {
+ subjectValue.value = val
+ hasChanges.value = true
+ schedulePreview()
+ }, 'e.g. Welcome {{name}}!')
+ }
+ if (sampleDataEditorRef.value) {
+ sampleDataEditor.value = createEditor(sampleDataEditorRef.value, sampleDataValue.value, 'json', (val) => {
+ sampleDataValue.value = val
+ schedulePreview()
+ }, '{"key": "value"}')
+ }
+}
+
+function destroyEditors() {
+ htmlEditor.value?.destroy()
+ textEditor.value?.destroy()
+ subjectEditor.value?.destroy()
+ sampleDataEditor.value?.destroy()
+}
+
+onMounted(async () => {
+ document.addEventListener('keydown', handleKeydown)
+
+ try {
+ const [tmplRes, versionsRes, locsRes] = await Promise.all([
+ templatesApi.list(0, 100),
+ templatesApi.listVersions(templateId),
+ templatesApi.listLocalizations(templateId, versionId),
+ ])
+
+ template.value = tmplRes.data.data.find((t: Template) => t.id === templateId) || null
+ version.value = (versionsRes.data.data || []).find((v: TemplateVersion) => v.id === versionId) || null
+
+ const locs: TemplateLocalization[] = locsRes.data.data || []
+ localization.value = locs.find((l) => l.id === localizationId) || null
+
+ if (!template.value || !version.value || !localization.value) {
+ notify.error('Template, version, or localization not found')
+ loading.value = false
+ return
+ }
+
+ // Populate editor values
+ subjectValue.value = localization.value.subject_template
+ htmlValue.value = localization.value.html_template
+ textValue.value = localization.value.text_template
+
+ if (template.value.sample_data) {
+ sampleDataValue.value = template.value.sample_data
+ } else if (version.value.sample_data) {
+ sampleDataValue.value = version.value.sample_data
+ }
+
+ loading.value = false
+
+ // Initialize editors after DOM update
+ setTimeout(() => {
+ initEditors()
+ renderPreview()
+ }, 0)
+ } catch {
+ notify.error('Failed to load template data')
+ loading.value = false
+ }
+})
+
+onBeforeUnmount(() => {
+ document.removeEventListener('keydown', handleKeydown)
+ destroyEditors()
+ if (debounceTimer) clearTimeout(debounceTimer)
+})
+
+function goBack() {
+ router.push(`/templates/${templateId}/versions`)
+}
+</script>
+
+<template>
+ <div class="editor-page">
+ <!-- Header -->
+ <div class="editor-header">
+ <div class="editor-header-left">
+ <button class="btn btn-secondary btn-sm" @click="goBack">
+ <span class="mdi mdi-arrow-left"></span> Back
+ </button>
+ <div class="editor-title">
+ <h2>{{ template?.name || 'Template' }}</h2>
+ <div class="editor-meta">
+ <span class="badge badge-info">{{ localization?.language }}</span>
+ <span class="badge badge-neutral">v{{ version?.version }}</span>
+ <span v-if="hasChanges" class="badge badge-warning">Unsaved</span>
+ </div>
+ </div>
+ </div>
+ <div class="editor-header-right">
+ <button
+ class="btn btn-secondary btn-sm"
+ @click="showPreviewPanel = !showPreviewPanel"
+ >
+ {{ showPreviewPanel ? 'Hide Preview' : 'Show Preview' }}
+ </button>
+ <button
+ class="btn btn-primary btn-sm"
+ :disabled="saving || !hasChanges"
+ @click="save"
+ >
+ {{ saving ? 'Saving...' : 'Save' }}
+ </button>
+ </div>
+ </div>
+
+ <!-- Loading -->
+ <div v-if="loading" class="loading-page">
+ <div class="spinner"></div>
+ </div>
+
+ <!-- Editor Layout -->
+ <div v-else-if="template && localization" class="editor-layout" :class="{ 'preview-hidden': !showPreviewPanel }">
+ <!-- Left: Code Editor -->
+ <div class="editor-pane">
+ <!-- Tabs -->
+ <div class="editor-tabs">
+ <button
+ class="editor-tab"
+ :class="{ active: activeTab === 'html' }"
+ @click="activeTab = 'html'"
+ >
+ HTML
+ </button>
+ <button
+ class="editor-tab"
+ :class="{ active: activeTab === 'text' }"
+ @click="activeTab = 'text'"
+ >
+ Plain Text
+ </button>
+ <button
+ class="editor-tab"
+ :class="{ active: activeTab === 'subject' }"
+ @click="activeTab = 'subject'"
+ >
+ Subject
+ </button>
+ </div>
+
+ <!-- Editor panels -->
+ <div class="editor-content">
+ <div v-show="activeTab === 'html'" ref="htmlEditorRef" class="cm-container"></div>
+ <div v-show="activeTab === 'text'" ref="textEditorRef" class="cm-container"></div>
+ <div v-show="activeTab === 'subject'" ref="subjectEditorRef" class="cm-container"></div>
+ </div>
+
+ <!-- Sample Data (collapsible) -->
+ <details class="sample-data-section">
+ <summary class="sample-data-header">
+ Sample Data (JSON)
+ </summary>
+ <div ref="sampleDataEditorRef" class="cm-container cm-container-sm"></div>
+ </details>
+ </div>
+
+ <!-- Right: Preview -->
+ <div v-if="showPreviewPanel" class="preview-pane">
+ <div class="preview-header">
+ <div class="preview-tabs">
+ <button
+ class="editor-tab"
+ :class="{ active: previewTab === 'html' }"
+ @click="previewTab = 'html'"
+ >
+ HTML
+ </button>
+ <button
+ class="editor-tab"
+ :class="{ active: previewTab === 'text' }"
+ @click="previewTab = 'text'"
+ >
+ Text
+ </button>
+ </div>
+ <button
+ class="btn btn-secondary btn-sm"
+ :disabled="previewLoading"
+ @click="renderPreview"
+ >
+ {{ previewLoading ? 'Rendering...' : 'Refresh' }}
+ </button>
+ </div>
+
+ <!-- Preview subject -->
+ <div v-if="preview?.subject" class="preview-subject">
+ <span class="preview-subject-label">Subject:</span>
+ {{ preview.subject }}
+ </div>
+
+ <!-- Preview error -->
+ <div v-if="previewError" class="preview-error">{{ previewError }}</div>
+
+ <!-- Preview content -->
+ <div class="preview-content">
+ <div v-if="previewTab === 'html'">
+ <iframe
+ v-if="preview?.html"
+ :srcdoc="preview.html"
+ sandbox=""
+ class="preview-iframe"
+ ></iframe>
+ <div v-else class="preview-empty">
+ {{ previewLoading ? 'Rendering...' : 'No HTML preview available' }}
+ </div>
+ </div>
+ <pre v-else class="preview-text">{{ preview?.text || (previewLoading ? 'Rendering...' : 'No text preview available') }}</pre>
+ </div>
+ </div>
+ </div>
+
+ <!-- Not found -->
+ <div v-else class="empty-state">
+ <h3>Not found</h3>
+ <p>The template, version, or localization was not found.</p>
+ <button class="btn btn-secondary" @click="goBack">Go Back</button>
+ </div>
+ </div>
+</template>
+
+<style scoped>
+.editor-page {
+ display: flex;
+ flex-direction: column;
+ height: calc(100vh - 60px);
+ margin: -24px;
+ overflow: hidden;
+}
+
+.editor-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 10px 16px;
+ border-bottom: 1px solid var(--border-primary);
+ background: var(--bg-primary);
+ flex-shrink: 0;
+}
+
+.editor-header-left {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+}
+
+.editor-header-right {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+}
+
+.editor-title h2 {
+ font-size: 15px;
+ font-weight: 600;
+ margin: 0;
+ color: var(--text-primary);
+}
+
+.editor-meta {
+ display: flex;
+ gap: 6px;
+ margin-top: 2px;
+}
+
+.editor-layout {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ flex: 1;
+ overflow: hidden;
+}
+
+.editor-layout.preview-hidden {
+ grid-template-columns: 1fr;
+}
+
+.editor-pane {
+ display: flex;
+ flex-direction: column;
+ overflow: hidden;
+ border-right: 1px solid var(--border-primary);
+}
+
+.editor-tabs {
+ display: flex;
+ border-bottom: 1px solid var(--border-primary);
+ background: var(--bg-secondary);
+ flex-shrink: 0;
+}
+
+.editor-tab {
+ padding: 8px 16px;
+ font-size: 13px;
+ font-weight: 500;
+ color: var(--text-secondary);
+ background: none;
+ border: none;
+ border-bottom: 2px solid transparent;
+ cursor: pointer;
+ transition: color 0.15s, border-color 0.15s;
+}
+
+.editor-tab:hover {
+ color: var(--text-primary);
+}
+
+.editor-tab.active {
+ color: var(--primary-600);
+ border-bottom-color: var(--primary-600);
+}
+
+.editor-content {
+ flex: 1;
+ overflow: hidden;
+}
+
+.cm-container {
+ height: 100%;
+ overflow: auto;
+}
+
+.cm-container :deep(.cm-editor) {
+ height: 100%;
+}
+
+.cm-container-sm {
+ height: 150px;
+}
+
+.cm-container-sm :deep(.cm-editor) {
+ height: 150px;
+}
+
+.sample-data-section {
+ border-top: 1px solid var(--border-primary);
+ flex-shrink: 0;
+}
+
+.sample-data-header {
+ padding: 8px 16px;
+ font-size: 12px;
+ font-weight: 600;
+ text-transform: uppercase;
+ letter-spacing: 0.05em;
+ color: var(--text-muted);
+ background: var(--bg-secondary);
+ cursor: pointer;
+ user-select: none;
+}
+
+.sample-data-header:hover {
+ color: var(--text-secondary);
+}
+
+/* Preview pane */
+.preview-pane {
+ display: flex;
+ flex-direction: column;
+ overflow: hidden;
+ background: var(--bg-primary);
+}
+
+.preview-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ border-bottom: 1px solid var(--border-primary);
+ background: var(--bg-secondary);
+ flex-shrink: 0;
+ padding-right: 12px;
+}
+
+.preview-tabs {
+ display: flex;
+}
+
+.preview-subject {
+ padding: 8px 16px;
+ font-size: 13px;
+ color: var(--text-primary);
+ background: var(--bg-tertiary);
+ border-bottom: 1px solid var(--border-primary);
+ flex-shrink: 0;
+}
+
+.preview-subject-label {
+ font-weight: 600;
+ color: var(--text-secondary);
+ margin-right: 6px;
+}
+
+.preview-error {
+ padding: 8px 16px;
+ background: var(--danger-50);
+ color: var(--danger-600);
+ font-size: 13px;
+ flex-shrink: 0;
+}
+
+.preview-content {
+ flex: 1;
+ overflow: auto;
+}
+
+.preview-iframe {
+ width: 100%;
+ height: 100%;
+ min-height: 400px;
+ border: none;
+ background: #fff;
+}
+
+.preview-text {
+ padding: 16px;
+ margin: 0;
+ font-family: 'JetBrains Mono', 'Fira Code', monospace;
+ font-size: 13px;
+ color: var(--text-secondary);
+ white-space: pre-wrap;
+ word-wrap: break-word;
+ line-height: 1.6;
+}
+
+.preview-empty {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ height: 200px;
+ color: var(--text-muted);
+ font-size: 14px;
+}
+
+.badge-warning {
+ background: var(--warning-50);
+ color: var(--warning-600);
+}
+</style>
diff --git a/web/vite.config.ts b/web/vite.config.ts
index a93c139..4336fe0 100644
--- a/web/vite.config.ts
+++ b/web/vite.config.ts
@@ -4,6 +4,15 @@ import { resolve } from 'path'
export default defineConfig({
plugins: [vue()],
+ build: {
+ rollupOptions: {
+ output: {
+ manualChunks: {
+ codemirror: ['codemirror', '@codemirror/lang-html', '@codemirror/lang-json', '@codemirror/theme-one-dark', '@codemirror/view', '@codemirror/state'],
+ },
+ },
+ },
+ },
resolve: {
alias: {
'@': resolve(__dirname, 'src'),