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.

Initial commit

Jonas Kanindaa723c55ffc21
diff --git a/.dockerignore b/.dockerignore
new file mode 100644
index 0000000..ff2f392
--- /dev/null
+++ b/.dockerignore
@@ -0,0 +1,11 @@
+.git
+.github
+.gitignore
+.dockerignore
+Dockerfile
+compose.yml
+Makefile
+README.md
+LICENSE
+web/node_modules
+web/dist
diff --git a/.env.example b/.env.example
new file mode 100644
index 0000000..314bd13
--- /dev/null
+++ b/.env.example
@@ -0,0 +1,28 @@
+POSTA_PORT=9000
+POSTA_DB_HOST=localhost
+POSTA_DB_USER=posta
+POSTA_DB_PASSWORD=posta
+POSTA_DB_NAME=posta
+POSTA_DB_PORT=5432
+POSTA_DB_SSL_MODE=disable
+POSTA_DB_URL=
+POSTA_REDIS_ADDR=localhost:6379
+POSTA_REDIS_PASSWORD=
+POSTA_JWT_SECRET=change-me-in-production
+POSTA_DEV_MODE=false
+POSTA_RATE_LIMIT_HOURLY=100
+POSTA_RATE_LIMIT_DAILY=1000
+POSTA_ADMIN_PASSWORD=admin1234
+POSTA_OPENAPI_DOCS=true
+POSTA_METRICS_ENABLED=false
+# POSTA_WEB_DIR=web/dist # For develoment
+POSTA_WEB_URL=https://posta.example.com
+POSTA_CORS_ORIGINS=*
+POSTA_EMBEDDED_WORKER=false
+POSTA_WORKER_CONCURRENCY=10
+POSTA_WORKER_MAX_RETRIES=5
+POSTA_WEBHOOK_MAX_RETRIES=3
+POSTA_WEBHOOK_TIMEOUT_SECS=10
+POSTA_ENV=production
+
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 0000000..c75cbf3
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,65 @@
+name: CI
+
+on:
+ push:
+ branches: [main, dev]
+ pull_request:
+ branches: [main, dev]
+
+jobs:
+ backend:
+ runs-on: ubuntu-latest
+ services:
+ postgres:
+ image: postgres:17-alpine
+ env:
+ POSTGRES_USER: posta
+ POSTGRES_PASSWORD: posta
+ POSTGRES_DB: posta
+ ports: ['5432:5432']
+ options: >-
+ --health-cmd pg_isready
+ --health-interval 10s
+ --health-timeout 5s
+ --health-retries 5
+ redis:
+ image: redis:7-alpine
+ ports: ['6379:6379']
+ options: >-
+ --health-cmd "redis-cli ping"
+ --health-interval 10s
+ --health-timeout 5s
+ --health-retries 5
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-go@v5
+ with:
+ go-version: '1.26'
+ - run: go vet ./...
+ - run: go test ./...
+ - run: go build -o posta ./cmd/posta
+
+ frontend:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-node@v4
+ with:
+ node-version: '20'
+ cache: 'npm'
+ cache-dependency-path: web/package-lock.json
+ - run: cd web && npm ci && npm run build
+
+ docker:
+ needs: [backend, frontend]
+ if: github.event_name == 'push' && github.ref == 'refs/heads/main'
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: docker/setup-buildx-action@v3
+ - uses: docker/build-push-action@v6
+ with:
+ context: .
+ file: "./docker/Dockerfile"
+ push: false
+ tags: posta:latest
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
new file mode 100644
index 0000000..0fbffcf
--- /dev/null
+++ b/.github/workflows/release.yml
@@ -0,0 +1,48 @@
+name: Release
+on:
+ push:
+ tags:
+ - v0.**
+jobs:
+ docker:
+ #if: "!contains(github.ref, '-rc')"
+ runs-on: ubuntu-latest
+ permissions:
+ packages: write
+ contents: read
+ steps:
+ -
+ name: Set up QEMU
+ uses: docker/setup-qemu-action@v3
+ -
+ name: Set up Docker Buildx
+ uses: docker/setup-buildx-action@v3
+ -
+ name: Login to DockerHub
+ uses: docker/login-action@v3
+ with:
+ username: ${{ secrets.DOCKERHUB_USERNAME }}
+ password: ${{ secrets.DOCKERHUB_TOKEN }}
+ -
+ name: Get the tag name
+ id: get_tag_name
+ run: |
+ # Extract tag name and remove "v" if present
+ TAG_NAME="${GITHUB_REF#refs/tags/}"
+ VERSION="${TAG_NAME#v}"
+ echo "VERSION=${VERSION}" >> $GITHUB_ENV
+ echo BUILD_TIME=$(date) >> ${GITHUB_ENV}
+ -
+ name: Build and push
+ uses: docker/build-push-action@v6
+ with:
+ push: true
+ file: "./docker/Dockerfile"
+ platforms: linux/amd64,linux/arm64,linux/arm/v7
+ build-args: |
+ VERSION=${{ env.VERSION }}
+ BUILD_DATE=${{ env.BUILD_TIME }}
+ COMMIT=${{ github.sha }}
+ tags: |
+ "${{vars.BUILDKIT_IMAGE}}:${{ env.VERSION }}"
+ "${{vars.BUILDKIT_IMAGE}}:latest"
\ No newline at end of file
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..35f3da1
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,4 @@
+.env
+bin/
+.history
+.DS_Store
\ No newline at end of file
diff --git a/.golangci.yml b/.golangci.yml
new file mode 100644
index 0000000..4cbc498
--- /dev/null
+++ b/.golangci.yml
@@ -0,0 +1,59 @@
+version: "2"
+run:
+ allow-parallel-runners: true
+linters:
+ default: none
+ enable:
+ - copyloopvar
+ - dupl
+ - errcheck
+ - ginkgolinter
+ - goconst
+ - gocyclo
+ - govet
+ - ineffassign
+ - lll
+ - misspell
+ - nakedret
+ - prealloc
+ - revive
+ - staticcheck
+ - unconvert
+ - unparam
+ - unused
+ settings:
+ gocyclo:
+ min-complexity: 75
+ revive:
+ rules:
+ - name: comment-spacings
+ exclusions:
+ generated: lax
+ rules:
+ - linters:
+ - dupl
+ - lll
+ path: pkg/*
+ - linters:
+ - dupl
+ - lll
+ path: internal/*
+ - linters:
+ - goconst
+ path: _test\.go
+ - linters:
+ - misspell
+ path: internal/services/seeder/constants\.go
+ paths:
+ - third_party$
+ - builtin$
+ - examples$
+formatters:
+ enable:
+ - gofmt
+ exclusions:
+ generated: lax
+ paths:
+ - third_party$
+ - builtin$
+ - examples$
\ No newline at end of file
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..d803269
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
+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.
\ No newline at end of file
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..834f835
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,67 @@
+.PHONY: build build-ui build-all run run-worker dev dev-worker dev-deps test vet fmt lint clean
+
+BINARY := posta
+BUILD_DIR := bin
+UI_DIR := web
+VERSION ?= $(shell git describe --tags --always --dirty 2>/dev/null || echo "dev")
+COMMIT ?= $(shell git rev-parse --short HEAD 2>/dev/null || echo "unknown")
+LDFLAGS := -X github.com/jkaninda/posta/internal/config.Version=$(VERSION) -X github.com/jkaninda/posta/internal/config.CommitID=$(COMMIT)
+build:
+ go build -ldflags "$(LDFLAGS)" -o $(BUILD_DIR)/$(BINARY) ./cmd/posta
+
+build-ui:
+ cd $(UI_DIR) && npm install && npm run build
+
+build-all: build-ui build
+
+run: build
+ ./$(BUILD_DIR)/$(BINARY) server
+
+run-worker: build
+ ./$(BUILD_DIR)/$(BINARY) worker
+
+run-ui:
+ cd $(UI_DIR) && npm run dev
+
+dev: build
+ ./$(BUILD_DIR)/$(BINARY) server
+
+dev-worker: build
+ ./$(BUILD_DIR)/$(BINARY) worker
+
+dev-ui:
+ cd $(UI_DIR) && npm run dev
+
+dev-deps:
+ docker run -d --name posta-postgres \
+ -e POSTGRES_USER=posta \
+ -e POSTGRES_PASSWORD=posta \
+ -e POSTGRES_DB=posta \
+ -p 5432:5432 \
+ postgres:17-alpine
+ docker run -d --name posta-redis \
+ -p 6379:6379 \
+ redis:7-alpine
+
+dev-deps-stop:
+ docker stop posta-postgres posta-redis || true
+ docker rm posta-postgres posta-redis || true
+
+test:
+ go test ./...
+
+vet:
+ go vet ./...
+
+fmt:
+ gofmt -w .
+
+clean:
+ rm -rf $(BUILD_DIR)
+ rm -rf $(UI_DIR)/dist
+
+tidy:
+ go mod tidy
+
+lint:
+ golangci-lint run
\ No newline at end of file
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..b36bea7
--- /dev/null
+++ b/README.md
@@ -0,0 +1,431 @@
+# Posta
+
+<p align="center">
+ <img src="logo.png" alt="Posta" width="120" />
+</p>
+
+[![CI](https://github.com/jkaninda/posta/actions/workflows/ci.yml/badge.svg)](https://github.com/jkaninda/posta/actions/workflows/ci.yml)
+[![Go Report Card](https://goreportcard.com/badge/github.com/jkaninda/posta)](https://goreportcard.com/report/github.com/jkaninda/posta)
+[![Go](https://img.shields.io/github/go-mod/go-version/jkaninda/posta)](https://go.dev/)
+[![Go Reference](https://pkg.go.dev/badge/github.com/jkaninda/posta.svg)](https://pkg.go.dev/github.com/jkaninda/posta)
+[![GitHub Release](https://img.shields.io/github/v/release/jkaninda/posta)](https://github.com/jkaninda/posta/releases)
+![Docker Image Size (latest by date)](https://img.shields.io/docker/image-size/jkaninda/posta?style=flat-square)
+![Docker Pulls](https://img.shields.io/docker/pulls/jkaninda/posta?style=flat-square)
+
+**Posta** is a self-hosted email delivery platform that allows applications to send emails through HTTP APIs while Posta manages SMTP delivery, templates, storage, security, and analytics.
+
+It provides a developer-friendly and fully self-hostable alternative to services such as SendGrid, and Mailgun.
+
+---
+
+# Why Posta
+
+Posta provides a complete email delivery platform that you can run in your own infrastructure.
+
+* HTTP API for sending emails
+* Template engine with versioning and localization
+* Background job processing with Redis and Asynq
+* Multiple SMTP servers and shared SMTP pools
+* Domain verification with SPF, DKIM, and DMARC checks
+* Contact management and bounce suppression
+* Webhooks and event streaming
+* Prometheus metrics and health probes
+* Admin dashboard and API documentation
+
+Posta is designed for developers who want full control over their email infrastructure without relying on third-party services.
+
+---
+
+# Send Your First Email
+
+Example request:
+
+```bash
+curl -X POST http://localhost:9000/api/v1/emails/send \
+ -H "Authorization: Bearer YOUR_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "from": "[email protected]",
+ "to": ["[email protected]"],
+ "subject": "Hello from Posta",
+ "html": "<h1>Hello!</h1>"
+ }'
+```
+
+Response:
+
+```json
+{
+ "id": "email_01J8C8E5W3",
+ "status": "queued"
+}
+```
+
+---
+
+# Features
+
+## Email Delivery
+
+* **HTTP Email API**
+ Send single, batch, or template-based emails via REST endpoints.
+
+* **Scheduled Delivery**
+ Queue emails for delivery at a specified time.
+
+* **Asynchronous Processing**
+ Background workers process email queues using Redis and Asynq with priority tiers (transactional, bulk, and low-priority).
+
+* **Automatic Retry**
+ Failed emails are retried automatically with configurable retry limits per SMTP server.
+
+* **Development Mode**
+ Store and preview emails in the dashboard without sending them.
+
+---
+
+## Templates
+
+* **Versioned Templates**
+ Create multiple template versions with a selectable active version.
+
+* **Multi-language Support**
+ Templates support language-specific versions with variable substitution.
+
+* **Managed Stylesheets**
+ Stylesheets are automatically inlined for email client compatibility.
+
+* **Template Preview**
+ Render and preview templates directly from the dashboard.
+
+* **Template Import / Export**
+ Export templates as JSON and import them across environments.
+
+---
+
+## SMTP and Domain Management
+
+* **Multiple SMTP Servers**
+ Configure multiple SMTP servers per user with SSL or STARTTLS support.
+
+* **Shared SMTP Pool**
+ Administrators can define shared SMTP servers available to all users.
+
+* **Domain Verification**
+ Verify domain ownership via DNS records including SPF, DKIM, and DMARC.
+
+* **Verified Sending Enforcement**
+ Optionally restrict sending to verified domains only.
+
+---
+
+## Security and Authentication
+
+* **API Key Authentication**
+ Secure API keys with hashing, prefix identification, expiration, IP allowlisting, and revocation.
+
+* **Dashboard Authentication**
+ JWT-based authentication with role-based access control.
+
+* **Two-Factor Authentication**
+ TOTP-based 2FA setup and verification.
+
+* **Rate Limiting**
+ Redis-backed hourly and daily email limits per user.
+
+---
+
+## Contacts and Suppression
+
+* **Contact Management**
+ Automatically track recipients with send and failure statistics.
+
+* **Contact Lists**
+ Organize recipients into reusable mailing lists.
+
+* **Bounce Tracking**
+ Track hard bounces, soft bounces, and complaints.
+
+* **Automatic Suppression**
+ Automatically suppress recipients based on bounce behavior.
+
+---
+
+## Events and Webhooks
+
+* **Webhooks**
+ Subscribe to events such as `email.sent` and `email.failed`.
+
+* **Audit Logs**
+ Track platform and user activity with filtering and real-time streaming using Server-Sent Events.
+
+---
+
+## Analytics and Monitoring
+
+* **Email Analytics**
+ View daily email volume and status breakdown with date filtering.
+
+* **Dashboard Statistics**
+ Overview of delivery metrics and recent activity.
+
+* **Prometheus Metrics**
+ Export metrics including request counts, latencies, and email delivery counters.
+
+* **Health Probes**
+ Liveness (`/healthz`) and readiness (`/readyz`) endpoints.
+
+---
+
+## Admin Panel
+
+* **User Management**
+ Create, deactivate, and manage users and roles.
+
+* **Platform Metrics**
+ Aggregate statistics across the entire platform.
+
+* **Shared SMTP Servers**
+ Manage SMTP servers available to all users.
+
+* **Platform Email Logs**
+ View and search emails across all users.
+
+* **Job Monitoring**
+ Track scheduled cron jobs such as retention cleanup and reports.
+
+* **Platform Settings**
+ Configure registration, retention policies, and bounce handling.
+
+* **Real-time Event Streaming**
+ Live audit log updates via Server-Sent Events.
+
+---
+
+## Dashboard
+
+* **Vue.js Web Interface**
+ Manage templates, SMTP servers, domains, API keys, contacts, webhooks, and email logs.
+
+* **User Settings**
+ Configure timezone, default sender, notification preferences, API key expiration, bounce handling, and daily reports.
+
+---
+
+## API Documentation
+
+* **Swagger UI** — `/docs`
+* **ReDoc** — `/redoc`
+
+---
+
+# Requirements
+
+* Go 1.25+
+* PostgreSQL
+* Redis
+
+---
+
+# Quick Start
+
+## Local Development
+
+```bash
+git clone https://github.com/jkaninda/posta.git
+cd posta
+
+make dev-deps
+make dev
+make dev-worker
+```
+
+---
+
+## Docker Compose
+
+```bash
+docker compose up -d
+```
+
+This starts:
+
+* Posta API server
+* Background worker
+* PostgreSQL
+* Redis
+
+Dashboard:
+
+```
+http://localhost:9000
+```
+
+Default admin credentials:
+
+```
+Password: admin1234
+```
+
+---
+
+# Configuration
+
+Configuration is provided through environment variables.
+
+| Variable | Default | Description |
+| -------------------------- | ----------------------- | ------------------------------------ |
+| POSTA_PORT | 9000 | HTTP server port |
+| POSTA_DB_HOST | localhost | PostgreSQL host |
+| POSTA_DB_USER | posta | PostgreSQL user |
+| POSTA_DB_PASSWORD | posta | PostgreSQL password |
+| POSTA_DB_NAME | posta | PostgreSQL database name |
+| POSTA_DB_PORT | 5432 | PostgreSQL port |
+| POSTA_DB_SSL_MODE | disable | PostgreSQL SSL mode |
+| POSTA_DB_URL | | PostgreSQL connection string (overrides individual DB settings) |
+| POSTA_REDIS_ADDR | localhost:6379 | Redis address |
+| POSTA_REDIS_PASSWORD | | Redis password |
+| POSTA_JWT_SECRET | change-me-in-production | JWT signing secret |
+| POSTA_DEV_MODE | false | Store emails without sending |
+| POSTA_RATE_LIMIT_HOURLY | 100 | Hourly email limit per user |
+| POSTA_RATE_LIMIT_DAILY | 1000 | Daily email limit per user |
+| POSTA_ADMIN_EMAIL | [email protected] | Default admin email |
+| POSTA_ADMIN_PASSWORD | admin1234 | Default admin password |
+| POSTA_OPENAPI_DOCS | true | Enable Swagger UI and ReDoc |
+| POSTA_METRICS_ENABLED | false | Enable Prometheus metrics |
+| POSTA_WEB_DIR | web/dist | Vue build directory |
+| POSTA_WEB_URL | | Public URL |
+| POSTA_CORS_ORIGINS | * | Allowed CORS origins (comma-separated) |
+| POSTA_EMBEDDED_WORKER | false | Run worker in server process |
+| POSTA_WORKER_CONCURRENCY | 10 | Worker concurrency |
+| POSTA_WORKER_MAX_RETRIES | 5 | Email retry attempts |
+| POSTA_WEBHOOK_MAX_RETRIES | 3 | Webhook delivery retry attempts |
+| POSTA_WEBHOOK_TIMEOUT_SECS | 10 | Webhook request timeout in seconds |
+
+---
+# Dashboard
+
+Posta includes a web dashboard for managing templates, SMTP servers, domains, contacts, API keys, and analytics.
+
+<p align="center">
+ <img src="docs/screenshots/dashboard.png" alt="Posta Dashboard" width="900"/>
+</p>
+
+### Email Analytics
+
+<p align="center">
+ <img src="docs/screenshots/analytics.png" alt="Email Analytics" width="900"/>
+</p>
+
+### Email Logs
+
+<p align="center">
+ <img src="docs/screenshots/email-logs.png" alt="Email Logs" width="900"/>
+</p>
+
+### Email Detail
+
+<p align="center">
+ <img src="docs/screenshots/email-detail.png" alt="Email Detail" width="900"/>
+</p>
+
+### Template Detail
+
+<p align="center">
+ <img src="docs/screenshots/template-detail.png" alt="Template Detail" width="900"/>
+</p>
+
+### Template Preview
+
+<p align="center">
+ <img src="docs/screenshots/template-preview.png" alt="Template Preview" width="900"/>
+</p>
+
+### Admin Platform Metrics
+
+<p align="center">
+ <img src="docs/screenshots/admin-platform-metrics.png" alt="Admin Platform Metrics" width="900"/>
+</p>
+
+### Admin Metrics (Light)
+
+<p align="center">
+ <img src="docs/screenshots/admin-metrics-light.png" alt="Admin Metrics Light" width="900"/>
+</p>
+
+### Admin Metrics (Dark)
+
+<p align="center">
+ <img src="docs/screenshots/admin-metrics-dark.png" alt="Admin Metrics Dark" width="900"/>
+</p>
+
+---
+## Official Clients
+
+- Go: https://github.com/jkaninda/posta-go
+- Php: https://github.com/jkaninda/posta-php
+- Java: https://github.com/jkaninda/posta-java
+
+### Go Client SDK
+
+An official Go client is available:
+
+
+Install:
+
+```bash
+go get github.com/jkaninda/posta-go
+```
+
+Example:
+
+```go
+package main
+
+import (
+ "fmt"
+ "log"
+
+ posta "github.com/jkaninda/posta-go"
+)
+
+func main() {
+ client := posta.New("https://posta.example.com", "your-api-key")
+
+ resp, err := client.SendEmail(&posta.SendEmailRequest{
+ To: []string{"[email protected]"},
+ Subject: "Hello from Posta",
+ HTML: "<h1>Hello!</h1>",
+ })
+
+ if err != nil {
+ log.Fatal(err)
+ }
+
+ fmt.Printf("Email sent: id=%s status=%s\n", resp.ID, resp.Status)
+}
+```
+
+---
+
+## Contributing
+
+Contributions are welcome! Please open an issue to discuss proposed changes before submitting a pull request.
+
+## License
+
+This project is licensed under the MIT License. See [LICENSE](LICENSE) for details.
+
+---
+
+<div align="center">
+
+**Made with ❤️ for the developer community**
+
+⭐ **Star us on GitHub** — it motivates us to keep improving!
+
+Copyright © 2026 Jonas Kaninda
+
+</div>
\ No newline at end of file
diff --git a/cmd/posta/main.go b/cmd/posta/main.go
new file mode 100644
index 0000000..b60f993
--- /dev/null
+++ b/cmd/posta/main.go
@@ -0,0 +1,63 @@
+/*
+ * 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 main
+
+import (
+ "github.com/jkaninda/logger"
+ "github.com/jkaninda/okapi"
+ "github.com/jkaninda/okapi/okapicli"
+)
+
+type ServerConfig struct {
+ Port int `cli:"port" short:"p" desc:"HTTP server port" env:"POSTA_PORT" default:"9000"`
+ Debug bool `cli:"debug" short:"d" desc:"Enable debug mode" env:"POSTA_DEV_MODE" default:"false"`
+}
+
+func main() {
+ app := okapi.New()
+ cli := okapicli.New(app, "Posta")
+
+ serveCfg := &ServerConfig{}
+ cli.Command("server", "Start Posta server", func(cmd *okapicli.Command) error {
+ app.WithPort(serveCfg.Port)
+ if serveCfg.Debug {
+ app.WithDebug()
+ }
+ runServer(cli)
+ return nil
+ }).FromStruct(serveCfg)
+
+ cli.Command("worker", "Start Posta worker", func(cmd *okapicli.Command) error {
+ if err := runWorker(); err != nil {
+ logger.Fatal("worker server error", "error", err)
+ }
+ return nil
+ })
+ cli.DefaultCommand("server")
+
+ if err := cli.Execute(); err != nil {
+ logger.Fatal(err.Error())
+ }
+}
diff --git a/cmd/posta/server.go b/cmd/posta/server.go
new file mode 100644
index 0000000..6b43ed6
--- /dev/null
+++ b/cmd/posta/server.go
@@ -0,0 +1,261 @@
+/*
+ * 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 main
+
+import (
+ "context"
+ "time"
+
+ "github.com/hibiken/asynq"
+ "github.com/jkaninda/logger"
+ "github.com/jkaninda/okapi/okapicli"
+ "github.com/jkaninda/posta/internal/config"
+ cronpkg "github.com/jkaninda/posta/internal/cron"
+ "github.com/jkaninda/posta/internal/cron/jobs"
+ "github.com/jkaninda/posta/internal/metrics"
+ "github.com/jkaninda/posta/internal/routes"
+ "github.com/jkaninda/posta/internal/services/retry"
+ "github.com/jkaninda/posta/internal/services/seeder"
+ "github.com/jkaninda/posta/internal/services/settings"
+ "github.com/jkaninda/posta/internal/services/webhook"
+ "github.com/jkaninda/posta/internal/storage"
+ "github.com/jkaninda/posta/internal/storage/migration"
+ "github.com/jkaninda/posta/internal/storage/repositories"
+ "github.com/jkaninda/posta/internal/worker"
+ "github.com/redis/go-redis/v9"
+ "gorm.io/gorm"
+)
+
+type serverResources struct {
+ producer *worker.Producer
+ cronManager *cronpkg.Manager
+ db *gorm.DB
+ redis *redis.Client
+}
+
+func runServer(cli *okapicli.CLI) {
+ cfg := config.New()
+ app := cli.Okapi()
+ if err := cfg.Initialize(app); err != nil {
+ logger.Fatal("Failed to initialize Posta", "error", err)
+ }
+
+ res := &serverResources{}
+
+ if err := cli.RunServer(&okapicli.RunOptions{
+ ShutdownTimeout: 30 * time.Second,
+ OnStart: func() {
+ cfg.InitStorage()
+ res.db = cfg.Database.DB
+ res.redis = cfg.Redis.Client
+
+ if err := migration.Run(res.db); err != nil {
+ logger.Fatal("failed to run migrations", "error", err)
+ }
+
+ if err := storage.SeedAdmin(res.db, cfg.AdminEmail, cfg.AdminPassword); err != nil {
+ logger.Fatal("failed to seed admin user", "error", err)
+ }
+
+ seedDefaults(res.db, cfg.AdminEmail)
+
+ if cfg.EmbeddedWorker && !cfg.DevMode {
+ res.producer = worker.NewProducer(cfg.Redis.Addr, cfg.Redis.Password, cfg.WorkerMaxRetries)
+ startEmbeddedWorker(res.db, cfg)
+ }
+
+ if !cfg.DevMode {
+ res.cronManager = initCronManager(res.db, cfg)
+ }
+
+ routes.InitRoutes(app, res.db, res.redis, cfg, res.producer, res.cronManager, context.Background())
+
+ if res.cronManager != nil {
+ res.cronManager.Start(context.Background())
+ }
+
+ if !cfg.DevMode {
+ startRetryWorker(res.db, cfg, res.producer)
+ }
+
+ if cfg.DevMode {
+ logger.Info("running in development mode - emails will NOT be sent")
+ }
+ },
+ OnStarted: func() {
+ logger.Info("Posta Server started", "version", config.Version, "port", cli.GetInt("port"))
+ },
+ OnShutdown: func() {
+ shutdownServer(res)
+ },
+ }); err != nil {
+ logger.Fatal("server error", "error", err)
+ }
+}
+
+// seedDefaults seeds default templates, stylesheets, and languages for the admin user.
+func seedDefaults(db *gorm.DB, adminEmail string) {
+ userRepo := repositories.NewUserRepository(db)
+ admin, err := userRepo.FindByEmail(adminEmail)
+ if err != nil || admin == nil {
+ return
+ }
+ s := seeder.New(
+ repositories.NewTemplateRepository(db),
+ repositories.NewStyleSheetRepository(db),
+ repositories.NewTemplateVersionRepository(db),
+ repositories.NewTemplateLocalizationRepository(db),
+ repositories.NewLanguageRepository(db),
+ )
+ s.SeedUserDefaults(admin.ID, admin.Name)
+}
+
+// newWebhookDispatcher creates a configured webhook dispatcher with metrics hooks.
+func newWebhookDispatcher(db *gorm.DB, cfg *config.Config) *webhook.Dispatcher {
+ webhookRepo := repositories.NewWebhookRepository(db)
+ whDeliveryRepo := repositories.NewWebhookDeliveryRepository(db)
+ dispatcher := webhook.NewDispatcher(webhookRepo)
+ dispatcher.SetDeliveryRepo(whDeliveryRepo)
+ dispatcher.SetConfig(webhookConfig(cfg))
+ dispatcher.OnDeliverySuccess(func() { metrics.IncrementWebhookDelivery("success") })
+ dispatcher.OnDeliveryFailed(func() { metrics.IncrementWebhookDelivery("failed") })
+ dispatcher.OnDeliveryDone(metrics.ObserveWebhookDeliveryDuration)
+ return dispatcher
+}
+
+// startEmbeddedWorker starts an in-process asynq worker for email delivery.
+func startEmbeddedWorker(db *gorm.DB, cfg *config.Config) {
+ dispatcher := newWebhookDispatcher(db, cfg)
+
+ handler := worker.NewEmailSendHandler(
+ repositories.NewEmailRepository(db),
+ repositories.NewSMTPRepository(db),
+ repositories.NewServerRepository(db),
+ repositories.NewDomainRepository(db),
+ repositories.NewContactRepository(db),
+ dispatcher,
+ )
+ handler.OnSent(metrics.IncrementEmailSent)
+ handler.OnFailed(metrics.IncrementEmailFailed)
+
+ exhaustedHandler := worker.NewExhaustedErrorHandler(
+ repositories.NewEmailRepository(db), dispatcher, metrics.IncrementEmailFailed,
+ )
+
+ srv := asynq.NewServer(
+ asynq.RedisClientOpt{Addr: cfg.Redis.Addr, Password: cfg.Redis.Password},
+ asynq.Config{
+ Concurrency: cfg.WorkerConcurrency,
+ Queues: map[string]int{
+ worker.QueueTransactional: 6,
+ worker.QueueBulk: 3,
+ worker.QueueLow: 1,
+ },
+ ErrorHandler: exhaustedHandler,
+ },
+ )
+
+ mux := asynq.NewServeMux()
+ mux.HandleFunc(worker.TypeEmailSend, handler.ProcessTask)
+
+ go func() {
+ if err := srv.Run(mux); err != nil {
+ logger.Error("embedded worker error", "error", err)
+ }
+ }()
+
+ logger.Info("async email delivery enabled (embedded worker)")
+}
+
+// initCronManager creates and registers scheduled jobs.
+func initCronManager(db *gorm.DB, cfg *config.Config) *cronpkg.Manager {
+ cronClient := asynq.NewClient(asynq.RedisClientOpt{
+ Addr: cfg.Redis.Addr,
+ Password: cfg.Redis.Password,
+ })
+ settingsProvider := settings.NewProvider(repositories.NewSettingRepository(db))
+
+ manager := cronpkg.NewManager(cronClient)
+ manager.Register(jobs.NewRetentionCleanupJob(
+ repositories.NewEmailRepository(db),
+ repositories.NewEventRepository(db),
+ repositories.NewWebhookDeliveryRepository(db),
+ settingsProvider,
+ ))
+ manager.Register(jobs.NewDailyReportJob(repositories.NewUserSettingRepository(db)))
+ return manager
+}
+
+// startRetryWorker starts the background worker that retries failed emails.
+func startRetryWorker(db *gorm.DB, cfg *config.Config, producer *worker.Producer) {
+ dispatcher := newWebhookDispatcher(db, cfg)
+ retryWorker := retry.NewWorker(
+ repositories.NewEmailRepository(db),
+ repositories.NewSMTPRepository(db),
+ dispatcher,
+ 5*time.Minute,
+ )
+ if producer != nil {
+ retryWorker.SetEnqueuer(producer)
+ }
+ retryWorker.OnSent(metrics.IncrementEmailSent)
+ retryWorker.OnFailed(metrics.IncrementEmailFailed)
+ retryWorker.OnRetry(metrics.IncrementEmailRetry)
+ retryWorker.Start(context.Background())
+}
+
+// shutdownServer gracefully closes all server resources.
+func shutdownServer(res *serverResources) {
+ logger.Info("Posta Server shutting down gracefully...")
+
+ if res.cronManager != nil {
+ res.cronManager.Stop()
+ }
+ if res.producer != nil {
+ if err := res.producer.Close(); err != nil {
+ logger.Error("failed to close producer", "error", err)
+ }
+ }
+ if res.redis != nil {
+ if err := res.redis.Close(); err != nil {
+ logger.Error("failed to close Redis", "error", err)
+ }
+ }
+ if res.db != nil {
+ if sqlDB, err := res.db.DB(); err == nil {
+ _ = sqlDB.Close()
+ }
+ }
+
+ logger.Info("Posta Server shut down complete")
+}
+
+// webhookConfig builds a webhook.Config from the application configuration.
+func webhookConfig(cfg *config.Config) webhook.Config {
+ return webhook.Config{
+ MaxRetries: cfg.WebhookMaxRetries,
+ Timeout: time.Duration(cfg.WebhookTimeoutSecs) * time.Second,
+ }
+}
diff --git a/cmd/posta/worker.go b/cmd/posta/worker.go
new file mode 100644
index 0000000..beca33c
--- /dev/null
+++ b/cmd/posta/worker.go
@@ -0,0 +1,87 @@
+/*
+ * 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 main
+
+import (
+ "github.com/hibiken/asynq"
+ "github.com/jkaninda/logger"
+ "github.com/jkaninda/posta/internal/config"
+ "github.com/jkaninda/posta/internal/metrics"
+ "github.com/jkaninda/posta/internal/storage/repositories"
+ "github.com/jkaninda/posta/internal/worker"
+)
+
+func runWorker() error {
+ cfg := config.New()
+ _ = cfg.InitWorker()
+ cfg.InitStorage()
+
+ db := cfg.Database.DB
+ defer func() {
+ if sqlDB, err := db.DB(); err == nil {
+ _ = sqlDB.Close()
+ }
+ }()
+
+ dispatcher := newWebhookDispatcher(db, cfg)
+
+ handler := worker.NewEmailSendHandler(
+ repositories.NewEmailRepository(db),
+ repositories.NewSMTPRepository(db),
+ repositories.NewServerRepository(db),
+ repositories.NewDomainRepository(db),
+ repositories.NewContactRepository(db),
+ dispatcher,
+ )
+ handler.OnSent(metrics.IncrementEmailSent)
+ handler.OnFailed(metrics.IncrementEmailFailed)
+
+ exhaustedHandler := worker.NewExhaustedErrorHandler(
+ repositories.NewEmailRepository(db), dispatcher, metrics.IncrementEmailFailed,
+ )
+
+ srv := asynq.NewServer(
+ asynq.RedisClientOpt{Addr: cfg.Redis.Addr, Password: cfg.Redis.Password},
+ asynq.Config{
+ Concurrency: cfg.WorkerConcurrency,
+ Queues: map[string]int{
+ worker.QueueTransactional: 6,
+ worker.QueueBulk: 3,
+ worker.QueueLow: 1,
+ },
+ ErrorHandler: exhaustedHandler,
+ },
+ )
+
+ mux := asynq.NewServeMux()
+ mux.HandleFunc(worker.TypeEmailSend, handler.ProcessTask)
+
+ logger.Info("Posta worker started",
+ "version", config.Version,
+ "concurrency", cfg.WorkerConcurrency,
+ )
+
+ return srv.Run(mux)
+}
diff --git a/compose.yml b/compose.yml
new file mode 100644
index 0000000..33e98a9
--- /dev/null
+++ b/compose.yml
@@ -0,0 +1,64 @@
+services:
+ posta:
+ build:
+ context: .
+ dockerfile: docker/Dockerfile
+ ports:
+ - "9000:9000"
+ environment:
+ POSTA_DB_URL: "host=posta-db user=posta password=posta dbname=posta port=5432 sslmode=disable"
+ POSTA_REDIS_ADDR: "posta-redis:6379"
+ POSTA_JWT_SECRET: "change-me-in-production"
+ POSTA_ADMIN_EMAIL: "[email protected]"
+ POSTA_ADMIN_PASSWORD: "admin1234"
+ depends_on:
+ posta-db:
+ condition: service_healthy
+ posta-redis:
+ condition: service_healthy
+ restart: unless-stopped
+
+ worker:
+ build:
+ context: .
+ dockerfile: docker/Dockerfile
+ command: ["worker"]
+ environment:
+ POSTA_DB_URL: "host=posta-db user=posta password=posta dbname=posta port=5432 sslmode=disable"
+ POSTA_REDIS_ADDR: "posta-redis:6379"
+ POSTA_WORKER_CONCURRENCY: "10"
+ POSTA_WORKER_MAX_RETRIES: "5"
+ depends_on:
+ posta-db:
+ condition: service_healthy
+ posta-redis:
+ condition: service_healthy
+ restart: unless-stopped
+
+ posta-db:
+ image: postgres:17-alpine
+ environment:
+ POSTGRES_USER: posta
+ POSTGRES_PASSWORD: posta
+ POSTGRES_DB: posta
+ volumes:
+ - postgres_data:/var/lib/postgresql/data
+ healthcheck:
+ test: ["CMD-SHELL", "pg_isready -U posta"]
+ interval: 5s
+ timeout: 5s
+ retries: 5
+
+ posta-redis:
+ image: redis:7-alpine
+ volumes:
+ - redis_data:/data
+ healthcheck:
+ test: ["CMD", "redis-cli", "ping"]
+ interval: 5s
+ timeout: 5s
+ retries: 5
+
+volumes:
+ postgres_data:
+ redis_data:
diff --git a/docker/Dockerfile b/docker/Dockerfile
new file mode 100644
index 0000000..c9a6462
--- /dev/null
+++ b/docker/Dockerfile
@@ -0,0 +1,56 @@
+# UI build stage
+FROM node:22-alpine AS ui-builder
+
+WORKDIR /app/web
+COPY web/package.json web/package-lock.json ./
+RUN npm ci
+COPY web/ .
+RUN npm run build
+
+# Go build stage
+FROM golang:1.26-alpine AS builder
+
+ARG VERSION=dev
+ARG COMMIT=unknown
+ARG BUILD_DATE=2026-03-15
+
+WORKDIR /app
+COPY go.mod go.sum ./
+RUN go mod download
+
+COPY cmd/ cmd/
+COPY internal/ internal/
+RUN CGO_ENABLED=0 go build \
+ -ldflags "-s -w -X 'github.com/jkaninda/posta/internal/config.Version=${VERSION}' -X 'github.com/jkaninda/posta/internal/config.CommitID=${COMMIT}' -X 'github.com/jkaninda/posta/internal/config.BuildDate=${BUILD_DATE}'" \
+ -o /bin/posta ./cmd/posta
+
+# Runtime stage
+FROM alpine:3.21
+
+ARG VERSION=dev
+ARG COMMIT=unknown
+
+LABEL org.opencontainers.image.title="posta" \
+ org.opencontainers.image.description="Posta is a self-hosted email delivery platform" \
+ org.opencontainers.image.licenses="Apache" \
+ org.opencontainers.image.authors="Jonas Kaninda" \
+ org.opencontainers.image.version="${VERSION}" \
+ org.opencontainers.image.source="https://github.com/jkaninda/posta" \
+ org.opencontainers.image.revision="${COMMIT}"
+
+RUN apk add --no-cache ca-certificates tzdata \
+ && addgroup -S posta && adduser -S posta -G posta
+
+COPY --from=builder /bin/posta /bin/posta
+RUN ln -s /bin/posta /posta
+COPY --from=ui-builder /app/web/dist /app/web/dist
+
+ENV POSTA_WEB_DIR=/app/web/dist
+
+HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
+ CMD wget -qO- http://localhost:${POSTA_PORT:-9000}/healthz || exit 1
+
+USER posta
+EXPOSE 9000
+
+ENTRYPOINT ["/bin/posta"]
diff --git a/docs/screenshots/admin-metrics-dark.png b/docs/screenshots/admin-metrics-dark.png
new file mode 100644
index 0000000..98ce348
Binary files /dev/null and b/docs/screenshots/admin-metrics-dark.png differ
diff --git a/docs/screenshots/admin-metrics-light.png b/docs/screenshots/admin-metrics-light.png
new file mode 100644
index 0000000..3144cf1
Binary files /dev/null and b/docs/screenshots/admin-metrics-light.png differ
diff --git a/docs/screenshots/admin-platform-metrics.png b/docs/screenshots/admin-platform-metrics.png
new file mode 100644
index 0000000..1ea72c9
Binary files /dev/null and b/docs/screenshots/admin-platform-metrics.png differ
diff --git a/docs/screenshots/analytics.png b/docs/screenshots/analytics.png
new file mode 100644
index 0000000..93af106
Binary files /dev/null and b/docs/screenshots/analytics.png differ
diff --git a/docs/screenshots/dashboard.png b/docs/screenshots/dashboard.png
new file mode 100644
index 0000000..9767d97
Binary files /dev/null and b/docs/screenshots/dashboard.png differ
diff --git a/docs/screenshots/email-detail.png b/docs/screenshots/email-detail.png
new file mode 100644
index 0000000..e1badb9
Binary files /dev/null and b/docs/screenshots/email-detail.png differ
diff --git a/docs/screenshots/email-logs.png b/docs/screenshots/email-logs.png
new file mode 100644
index 0000000..413c3b7
Binary files /dev/null and b/docs/screenshots/email-logs.png differ
diff --git a/docs/screenshots/template-detail.png b/docs/screenshots/template-detail.png
new file mode 100644
index 0000000..2523962
Binary files /dev/null and b/docs/screenshots/template-detail.png differ
diff --git a/docs/screenshots/template-preview.png b/docs/screenshots/template-preview.png
new file mode 100644
index 0000000..4e3121f
Binary files /dev/null and b/docs/screenshots/template-preview.png differ
diff --git a/examples/compose.yml b/examples/compose.yml
new file mode 100644
index 0000000..ca7a994
--- /dev/null
+++ b/examples/compose.yml
@@ -0,0 +1,58 @@
+# Posta Deployment (Single container Worker Setup)
+# ==================================================
+# This configuration runs Posta with the embedded worker enabled.
+# The email processing worker runs inside the main Posta server process,
+# so no separate worker container is required. This setup is ideal for
+# simple deployments, development environments, or small installations.
+
+services:
+ posta:
+ image: jkaninda/posta:latest
+ ports:
+ - "9000:9000"
+ environment:
+ POSTA_DB_HOST: posta-db
+ POSTA_DB_NAME: posta
+ POSTA_DB_USER: posta
+ POSTA_DB_PASSWORD: posta
+ POSTA_DB_PORT: 5432
+ POSTA_DB_SSL_MODE: disable
+ POSTA_REDIS_ADDR: "posta-redis:6379"
+ POSTA_JWT_SECRET: "change-me-in-production"
+ POSTA_ADMIN_EMAIL: "[email protected]"
+ POSTA_ADMIN_PASSWORD: "admin1234"
+ POSTA_EMBEDDED_WORKER: "true"
+ depends_on:
+ posta-db:
+ condition: service_healthy
+ posta-redis:
+ condition: service_healthy
+ restart: unless-stopped
+
+ posta-db:
+ image: postgres:17-alpine
+ environment:
+ POSTGRES_USER: posta
+ POSTGRES_PASSWORD: posta
+ POSTGRES_DB: posta
+ volumes:
+ - postgres_data:/var/lib/postgresql/data
+ healthcheck:
+ test: ["CMD-SHELL", "pg_isready -U posta"]
+ interval: 5s
+ timeout: 5s
+ retries: 5
+
+ posta-redis:
+ image: redis:7-alpine
+ volumes:
+ - redis_data:/data
+ healthcheck:
+ test: ["CMD", "redis-cli", "ping"]
+ interval: 5s
+ timeout: 5s
+ retries: 5
+
+volumes:
+ postgres_data:
+ redis_data:
diff --git a/examples/docker-compose-full.yml b/examples/docker-compose-full.yml
new file mode 100644
index 0000000..a44dc77
--- /dev/null
+++ b/examples/docker-compose-full.yml
@@ -0,0 +1,84 @@
+# Posta Deployment (Server + Dedicated Worker)
+# ============================================
+# This configuration runs Posta with a separate worker process.
+#
+# - The `posta` service runs the HTTP API and web interface.
+# - The `worker` service processes background jobs such as:
+# • email delivery
+# • retrying failed messages
+# • scheduled tasks
+#
+# Using a dedicated worker is recommended for production environments
+# because it allows the API server and background processing to scale
+# independently.
+
+services:
+ posta:
+ image: jkaninda/posta:latest
+ ports:
+ - "9000:9000"
+ environment:
+ POSTA_DB_HOST: posta-db
+ POSTA_DB_NAME: posta
+ POSTA_DB_USER: posta
+ POSTA_DB_PASSWORD: posta
+ POSTA_DB_PORT: 5432
+ POSTA_DB_SSL_MODE: disable
+ POSTA_REDIS_ADDR: "posta-redis:6379"
+ POSTA_JWT_SECRET: "change-me-in-production"
+ POSTA_ADMIN_EMAIL: "[email protected]"
+ POSTA_ADMIN_PASSWORD: "admin1234"
+ depends_on:
+ posta-db:
+ condition: service_healthy
+ posta-redis:
+ condition: service_healthy
+ restart: unless-stopped
+
+ worker:
+ image: jkaninda/posta:latest
+ command: ["worker"]
+ environment:
+ POSTA_DB_HOST: posta-db
+ POSTA_DB_NAME: posta
+ POSTA_DB_USER: posta
+ POSTA_DB_PASSWORD: posta
+ POSTA_DB_PORT: 5432
+ POSTA_DB_SSL_MODE: disable
+ POSTA_REDIS_ADDR: "posta-redis:6379"
+ POSTA_WORKER_CONCURRENCY: "10"
+ POSTA_WORKER_MAX_RETRIES: "5"
+ depends_on:
+ posta-db:
+ condition: service_healthy
+ posta-redis:
+ condition: service_healthy
+ restart: unless-stopped
+
+ posta-db:
+ image: postgres:17-alpine
+ environment:
+ POSTGRES_USER: posta
+ POSTGRES_PASSWORD: posta
+ POSTGRES_DB: posta
+ volumes:
+ - db_data:/var/lib/postgresql/data
+ healthcheck:
+ test: ["CMD-SHELL", "pg_isready -U posta"]
+ interval: 5s
+ timeout: 5s
+ retries: 5
+
+ posta-redis:
+ image: redis:7-alpine
+ volumes:
+ - redis_data:/data
+ healthcheck:
+ test: ["CMD", "redis-cli", "ping"]
+ interval: 5s
+ timeout: 5s
+ retries: 5
+
+volumes:
+ db_data:
+ redis_data:
diff --git a/go.mod b/go.mod
new file mode 100644
index 0000000..311e94f
--- /dev/null
+++ b/go.mod
@@ -0,0 +1,77 @@
+module github.com/jkaninda/posta
+
+go 1.26.1
+
+require (
+ github.com/hibiken/asynq v0.26.0
+ github.com/jkaninda/go-utils v0.1.4
+ github.com/jkaninda/logger v0.0.5
+ github.com/jkaninda/okapi v0.5.0
+ github.com/joho/godotenv v1.5.1
+ github.com/lib/pq v1.11.2
+ github.com/pquerna/otp v1.5.0
+ github.com/prometheus/client_golang v1.23.2
+ github.com/redis/go-redis/v9 v9.18.0
+ github.com/robfig/cron/v3 v3.0.1
+ github.com/vanng822/go-premailer v1.32.0
+ golang.org/x/crypto v0.48.0
+ gorm.io/driver/postgres v1.6.0
+ gorm.io/gorm v1.31.1
+)
+
+require (
+ github.com/PuerkitoBio/goquery v1.11.0 // indirect
+ github.com/andybalholm/cascadia v1.3.3 // indirect
+ github.com/beorn7/perks v1.0.1 // indirect
+ github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc // indirect
+ github.com/cespare/xxhash/v2 v2.3.0 // indirect
+ github.com/clipperhouse/uax29/v2 v2.2.0 // indirect
+ github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
+ github.com/fatih/color v1.18.0 // indirect
+ github.com/getkin/kin-openapi v0.133.0 // indirect
+ github.com/go-openapi/jsonpointer v0.22.5 // indirect
+ github.com/go-openapi/swag/jsonname v0.25.5 // indirect
+ github.com/golang-jwt/jwt/v5 v5.3.1 // indirect
+ github.com/google/uuid v1.6.0 // indirect
+ github.com/gorilla/css v1.0.1 // indirect
+ github.com/gorilla/mux v1.8.1 // indirect
+ github.com/inbucket/html2text v1.0.0 // indirect
+ github.com/jackc/pgpassfile v1.0.0 // indirect
+ github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
+ github.com/jackc/pgx/v5 v5.8.0 // indirect
+ github.com/jackc/puddle/v2 v2.2.2 // indirect
+ github.com/jinzhu/inflection v1.0.0 // indirect
+ github.com/jinzhu/now v1.1.5 // indirect
+ github.com/josharian/intern v1.0.0 // indirect
+ github.com/mailru/easyjson v0.9.1 // indirect
+ github.com/mattn/go-colorable v0.1.14 // indirect
+ github.com/mattn/go-isatty v0.0.20 // indirect
+ github.com/mattn/go-runewidth v0.0.19 // indirect
+ github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 // indirect
+ github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
+ github.com/oasdiff/yaml v0.0.0-20250309154309-f31be36b4037 // indirect
+ github.com/oasdiff/yaml3 v0.0.0-20250309153720-d2182401db90 // indirect
+ github.com/olekukonko/errors v1.1.0 // indirect
+ github.com/olekukonko/ll v0.0.9 // indirect
+ github.com/olekukonko/tablewriter v1.0.7 // indirect
+ github.com/perimeterx/marshmallow v1.1.5 // indirect
+ github.com/prometheus/client_model v0.6.2 // indirect
+ github.com/prometheus/common v0.67.5 // indirect
+ github.com/prometheus/procfs v0.20.1 // indirect
+ github.com/rivo/uniseg v0.4.7 // indirect
+ github.com/spf13/cast v1.10.0 // indirect
+ github.com/spf13/pflag v1.0.10 // indirect
+ github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect
+ github.com/vanng822/css v1.0.1 // indirect
+ github.com/woodsbury/decimal128 v1.4.0 // indirect
+ go.uber.org/atomic v1.11.0 // indirect
+ go.yaml.in/yaml/v2 v2.4.4 // indirect
+ golang.org/x/net v0.51.0 // indirect
+ golang.org/x/sync v0.20.0 // indirect
+ golang.org/x/sys v0.42.0 // indirect
+ golang.org/x/text v0.34.0 // indirect
+ golang.org/x/time v0.15.0 // indirect
+ google.golang.org/protobuf v1.36.11 // indirect
+ gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
+ gopkg.in/yaml.v3 v3.0.1 // indirect
+)
diff --git a/go.sum b/go.sum
new file mode 100644
index 0000000..304d179
--- /dev/null
+++ b/go.sum
@@ -0,0 +1,246 @@
+github.com/PuerkitoBio/goquery v1.11.0 h1:jZ7pwMQXIITcUXNH83LLk+txlaEy6NVOfTuP43xxfqw=
+github.com/PuerkitoBio/goquery v1.11.0/go.mod h1:wQHgxUOU3JGuj3oD/QFfxUdlzW6xPHfqyHre6VMY4DQ=
+github.com/andybalholm/cascadia v1.3.3 h1:AG2YHrzJIm4BZ19iwJ/DAua6Btl3IwJX+VI4kktS1LM=
+github.com/andybalholm/cascadia v1.3.3/go.mod h1:xNd9bqTn98Ln4DwST8/nG+H0yuB8Hmgu1YHNnWw0GeA=
+github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
+github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
+github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc h1:biVzkmvwrH8WK8raXaxBx6fRVTlJILwEwQGL1I/ByEI=
+github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc/go.mod h1:paBWMcWSl3LHKBqUq+rly7CNSldXjb2rDl3JlRe0mD8=
+github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
+github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
+github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
+github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
+github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
+github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
+github.com/clipperhouse/uax29/v2 v2.2.0 h1:ChwIKnQN3kcZteTXMgb1wztSgaU+ZemkgWdohwgs8tY=
+github.com/clipperhouse/uax29/v2 v2.2.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM=
+github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
+github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
+github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
+github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM=
+github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU=
+github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
+github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
+github.com/getkin/kin-openapi v0.133.0 h1:pJdmNohVIJ97r4AUFtEXRXwESr8b0bD721u/Tz6k8PQ=
+github.com/getkin/kin-openapi v0.133.0/go.mod h1:boAciF6cXk5FhPqe/NQeBTeenbjqU4LhWBf09ILVvWE=
+github.com/go-openapi/jsonpointer v0.22.5 h1:8on/0Yp4uTb9f4XvTrM2+1CPrV05QPZXu+rvu2o9jcA=
+github.com/go-openapi/jsonpointer v0.22.5/go.mod h1:gyUR3sCvGSWchA2sUBJGluYMbe1zazrYWIkWPjjMUY0=
+github.com/go-openapi/swag/jsonname v0.25.5 h1:8p150i44rv/Drip4vWI3kGi9+4W9TdI3US3uUYSFhSo=
+github.com/go-openapi/swag/jsonname v0.25.5/go.mod h1:jNqqikyiAK56uS7n8sLkdaNY/uq6+D2m2LANat09pKU=
+github.com/go-openapi/testify/v2 v2.4.0 h1:8nsPrHVCWkQ4p8h1EsRVymA2XABB4OT40gcvAu+voFM=
+github.com/go-openapi/testify/v2 v2.4.0/go.mod h1:HCPmvFFnheKK2BuwSA0TbbdxJ3I16pjwMkYkP4Ywn54=
+github.com/go-test/deep v1.0.8 h1:TDsG77qcSprGbC6vTN8OuXp5g+J+b5Pcguhf7Zt61VM=
+github.com/go-test/deep v1.0.8/go.mod h1:5C2ZWiW0ErCdrYzpqxLbTX7MG14M9iiw8DgHncVwcsE=
+github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
+github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
+github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
+github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
+github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
+github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
+github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
+github.com/gorilla/css v1.0.1 h1:ntNaBIghp6JmvWnxbZKANoLyuXTPZ4cAMlo6RyhlbO8=
+github.com/gorilla/css v1.0.1/go.mod h1:BvnYkspnSzMmwRK+b8/xgNPLiIuNZr6vbZBTPQ2A3b0=
+github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=
+github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ=
+github.com/hibiken/asynq v0.26.0 h1:1Zxr92MlDnb1Zt/QR5g2vSCqUS03i95lUfqx5X7/wrw=
+github.com/hibiken/asynq v0.26.0/go.mod h1:Qk4e57bTnWDoyJ67VkchuV6VzSM9IQW2nPvAGuDyw58=
+github.com/inbucket/html2text v1.0.0 h1:N5kza++4uBBDJ2Z3KUnTRyPNoBcW+YfOgNiNmNB+sgs=
+github.com/inbucket/html2text v1.0.0/go.mod h1:5TrhXQKGU+LXurODaSm55Y9eXoPBRnYiOz4x2XfUoJU=
+github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
+github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
+github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
+github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
+github.com/jackc/pgx/v5 v5.8.0 h1:TYPDoleBBme0xGSAX3/+NujXXtpZn9HBONkQC7IEZSo=
+github.com/jackc/pgx/v5 v5.8.0/go.mod h1:QVeDInX2m9VyzvNeiCJVjCkNFqzsNb43204HshNSZKw=
+github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
+github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
+github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
+github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
+github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
+github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
+github.com/jkaninda/go-utils v0.1.4 h1:ZdNlI+yLWc4/S0qKcCNQIPj+6lHSdJcGaxtRADAifAU=
+github.com/jkaninda/go-utils v0.1.4/go.mod h1:Aa54jEAcDykc3CnOdreqZG80UfSZOvrYecyusu+oPb4=
+github.com/jkaninda/logger v0.0.5 h1:fTHKgDsHtuN8rkSBvwe6QStfi8yIdm8O3r0g99dRDTY=
+github.com/jkaninda/logger v0.0.5/go.mod h1:ZUXJ2BdxDPG6e8t6mbKhc2ZFaFi2Iuy/4ukquFrPkFE=
+github.com/jkaninda/okapi v0.5.0 h1:b8qSmclCOUADXJoe6JQanJ3ZXIvGrSeVnjhyDqwlOs0=
+github.com/jkaninda/okapi v0.5.0/go.mod h1:6d2hfxk7yDyzUdjUElOeLYk1XpqnhZGQm/mPz4Bz4Vc=
+github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
+github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
+github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=
+github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
+github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
+github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
+github.com/klauspost/cpuid/v2 v2.0.9 h1:lgaqFMSdTdQYdZ04uHyN2d/eKdOMyi2YLSvlQIBFYa4=
+github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
+github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
+github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
+github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
+github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
+github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
+github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
+github.com/lib/pq v1.11.2 h1:x6gxUeu39V0BHZiugWe8LXZYZ+Utk7hSJGThs8sdzfs=
+github.com/lib/pq v1.11.2/go.mod h1:/p+8NSbOcwzAEI7wiMXFlgydTwcgTr3OSKMsD2BitpA=
+github.com/mailru/easyjson v0.9.1 h1:LbtsOm5WAswyWbvTEOqhypdPeZzHavpZx96/n553mR8=
+github.com/mailru/easyjson v0.9.1/go.mod h1:1+xMtQp2MRNVL/V1bOzuP3aP8VNwRW55fQUto+XFtTU=
+github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
+github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
+github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
+github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
+github.com/mattn/go-runewidth v0.0.19 h1:v++JhqYnZuu5jSKrk9RbgF5v4CGUjqRfBm05byFGLdw=
+github.com/mattn/go-runewidth v0.0.19/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=
+github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 h1:RWengNIwukTxcDr9M+97sNutRR1RKhG96O6jWumTTnw=
+github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826/go.mod h1:TaXosZuwdSHYgviHp1DAtfrULt5eUgsSMsZf+YrPgl8=
+github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
+github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
+github.com/oasdiff/yaml v0.0.0-20250309154309-f31be36b4037 h1:G7ERwszslrBzRxj//JalHPu/3yz+De2J+4aLtSRlHiY=
+github.com/oasdiff/yaml v0.0.0-20250309154309-f31be36b4037/go.mod h1:2bpvgLBZEtENV5scfDFEtB/5+1M4hkQhDQrccEJ/qGw=
+github.com/oasdiff/yaml3 v0.0.0-20250309153720-d2182401db90 h1:bQx3WeLcUWy+RletIKwUIt4x3t8n2SxavmoclizMb8c=
+github.com/oasdiff/yaml3 v0.0.0-20250309153720-d2182401db90/go.mod h1:y5+oSEHCPT/DGrS++Wc/479ERge0zTFxaF8PbGKcg2o=
+github.com/olekukonko/errors v1.1.0 h1:RNuGIh15QdDenh+hNvKrJkmxxjV4hcS50Db478Ou5sM=
+github.com/olekukonko/errors v1.1.0/go.mod h1:ppzxA5jBKcO1vIpCXQ9ZqgDh8iwODz6OXIGKU8r5m4Y=
+github.com/olekukonko/ll v0.0.9 h1:Y+1YqDfVkqMWuEQMclsF9HUR5+a82+dxJuL1HHSRpxI=
+github.com/olekukonko/ll v0.0.9/go.mod h1:En+sEW0JNETl26+K8eZ6/W4UQ7CYSrrgg/EdIYT2H8g=
+github.com/olekukonko/tablewriter v1.0.7 h1:HCC2e3MM+2g72M81ZcJU11uciw6z/p82aEnm4/ySDGw=
+github.com/olekukonko/tablewriter v1.0.7/go.mod h1:H428M+HzoUXC6JU2Abj9IT9ooRmdq9CxuDmKMtrOCMs=
+github.com/perimeterx/marshmallow v1.1.5 h1:a2LALqQ1BlHM8PZblsDdidgv1mWi1DgC2UmX50IvK2s=
+github.com/perimeterx/marshmallow v1.1.5/go.mod h1:dsXbUu8CRzfYP5a87xpp0xq9S3u0Vchtcl8we9tYaXw=
+github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
+github.com/pquerna/otp v1.5.0 h1:NMMR+WrmaqXU4EzdGJEE1aUUI0AMRzsp96fFFWNPwxs=
+github.com/pquerna/otp v1.5.0/go.mod h1:dkJfzwRKNiegxyNb54X/3fLwhCynbMspSyWKnvi1AEg=
+github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o=
+github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg=
+github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
+github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
+github.com/prometheus/common v0.67.5 h1:pIgK94WWlQt1WLwAC5j2ynLaBRDiinoAb86HZHTUGI4=
+github.com/prometheus/common v0.67.5/go.mod h1:SjE/0MzDEEAyrdr5Gqc6G+sXI67maCxzaT3A2+HqjUw=
+github.com/prometheus/procfs v0.20.1 h1:XwbrGOIplXW/AU3YhIhLODXMJYyC1isLFfYCsTEycfc=
+github.com/prometheus/procfs v0.20.1/go.mod h1:o9EMBZGRyvDrSPH1RqdxhojkuXstoe4UlK79eF5TGGo=
+github.com/redis/go-redis/v9 v9.18.0 h1:pMkxYPkEbMPwRdenAzUNyFNrDgHx9U+DrBabWNfSRQs=
+github.com/redis/go-redis/v9 v9.18.0/go.mod h1:k3ufPphLU5YXwNTUcCRXGxUoF1fqxnhFQmscfkCoDA0=
+github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
+github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
+github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
+github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=
+github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8=
+github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4=
+github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY=
+github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo=
+github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=
+github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
+github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf h1:pvbZ0lM0XWPBqUKqFU8cmavspvIl9nulOYwdy6IFRRo=
+github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf/go.mod h1:RJID2RhlZKId02nZ62WenDCkgHFerpIOmW0iT7GKmXM=
+github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
+github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
+github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
+github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
+github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
+github.com/ugorji/go/codec v1.2.7 h1:YPXUKf7fYbp/y8xloBqZOw2qaVggbfwMlI8WM3wZUJ0=
+github.com/ugorji/go/codec v1.2.7/go.mod h1:WGN1fab3R1fzQlVQTkfxVtIBhWDRqOviHU95kRgeqEY=
+github.com/vanng822/css v1.0.1 h1:10yiXc4e8NI8ldU6mSrWmSWMuyWgPr9DZ63RSlsgDw8=
+github.com/vanng822/css v1.0.1/go.mod h1:tcnB1voG49QhCrwq1W0w5hhGasvOg+VQp9i9H1rCM1w=
+github.com/vanng822/go-premailer v1.32.0 h1:dW1y2IKSBQyYIwMc9comDA2e+00/pJ1kVXf3v4sqAJo=
+github.com/vanng822/go-premailer v1.32.0/go.mod h1:4gVC6Hs+ESjSSfB1ohMwLqwuGoJ76cc0c2VM7DYqr0s=
+github.com/woodsbury/decimal128 v1.4.0 h1:xJATj7lLu4f2oObouMt2tgGiElE5gO6mSWUjQsBgUlc=
+github.com/woodsbury/decimal128 v1.4.0/go.mod h1:BP46FUrVjVhdTbKT+XuQh2xfQaGki9LMIRJSFuh6THU=
+github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
+github.com/zeebo/xxh3 v1.0.2 h1:xZmwmqxHZA8AI603jOQ0tMqmBr9lPeFwGg6d+xy9DC0=
+github.com/zeebo/xxh3 v1.0.2/go.mod h1:5NWz9Sef7zIDm2JHfFlcQvNekmcEl9ekUZQQKCYaDcA=
+go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
+go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
+go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
+go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
+go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ=
+go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
+golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
+golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
+golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc=
+golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
+golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
+golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
+golang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts=
+golang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos=
+golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
+golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
+golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
+golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
+golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
+golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
+golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
+golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
+golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
+golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
+golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk=
+golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
+golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
+golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4=
+golang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=
+golang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=
+golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=
+golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
+golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
+golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
+golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
+golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
+golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
+golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
+golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
+golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
+golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
+golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
+golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE=
+golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
+golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
+golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
+golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
+golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU=
+golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=
+golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY=
+golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM=
+golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
+golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
+golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
+golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
+golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
+golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
+golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
+golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
+golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
+golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=
+golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=
+golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
+golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
+golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
+golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
+golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
+golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
+golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58=
+golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
+golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
+google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
+gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
+gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc=
+gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc=
+gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+gorm.io/driver/postgres v1.6.0 h1:2dxzU8xJ+ivvqTRph34QX+WrRaJlmfyPqXmoGVjMBa4=
+gorm.io/driver/postgres v1.6.0/go.mod h1:vUw0mrGgrTK+uPHEhAdV4sfFELrByKVGnaVRkXDhtWo=
+gorm.io/gorm v1.31.1 h1:7CA8FTFz/gRfgqgpeKIBcervUn3xSyPUmr6B2WXJ7kg=
+gorm.io/gorm v1.31.1/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs=
diff --git a/internal/config/config.go b/internal/config/config.go
new file mode 100644
index 0000000..461192b
--- /dev/null
+++ b/internal/config/config.go
@@ -0,0 +1,198 @@
+/*
+ * 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 config
+
+import (
+ "fmt"
+ "strings"
+
+ goutils "github.com/jkaninda/go-utils"
+ "github.com/jkaninda/logger"
+ "github.com/jkaninda/okapi"
+ errorhandlers "github.com/jkaninda/posta/internal/error_handlers"
+ "github.com/jkaninda/posta/internal/storage"
+ "github.com/joho/godotenv"
+ "github.com/redis/go-redis/v9"
+ "gorm.io/gorm"
+)
+
+type Config struct {
+ Database DatabaseConfig
+ Redis RedisConfig
+ JWTSecret string
+ DevMode bool
+ RateLimitHourly int
+ RateLimitDaily int
+ AdminEmail string
+ AdminPassword string
+ OpenAPIDocs bool
+ MetricsEnabled bool
+ WebDir string
+ AppWebURL string
+ CORSOrigins string
+
+ // Worker settings
+ EmbeddedWorker bool
+ WorkerConcurrency int
+ WorkerMaxRetries int
+
+ // Webhook settings
+ WebhookMaxRetries int
+ WebhookTimeoutSecs int
+}
+type DatabaseConfig struct {
+ DB *gorm.DB
+ host string
+ user string
+ password string
+ name string
+ port int
+ sslMode string
+ url string
+}
+type RedisConfig struct {
+ Client *redis.Client
+ Addr string
+ Password string
+}
+type JWTConfig struct {
+ Secret string
+ Issuer string
+ Audience string
+}
+
+type LogConfig struct {
+ Level string
+}
+
+func New() *Config {
+ if err := godotenv.Load(); err != nil {
+ logger.Debug("no .env file found, using environment variables")
+ }
+ return &Config{
+ Database: DatabaseConfig{
+ host: goutils.Env("POSTA_DB_HOST", "localhost"),
+ user: goutils.Env("POSTA_DB_USER", "posta"),
+ password: goutils.Env("POSTA_DB_PASSWORD", "posta"),
+ name: goutils.Env("POSTA_DB_NAME", "posta"),
+ port: goutils.EnvInt("POSTA_DB_PORT", 5432),
+ sslMode: goutils.Env("POSTA_DB_SSL_MODE", "disable"),
+ url: goutils.Env("POSTA_DB_URL", ""),
+ },
+ Redis: RedisConfig{
+ Addr: goutils.Env("POSTA_REDIS_ADDR", "localhost:6379"),
+ Password: goutils.Env("POSTA_REDIS_PASSWORD", ""),
+ },
+ JWTSecret: goutils.Env("POSTA_JWT_SECRET", "change-me-in-production"),
+ DevMode: goutils.EnvBool("POSTA_DEV_MODE", false),
+ RateLimitHourly: goutils.EnvInt("POSTA_RATE_LIMIT_HOURLY", 100),
+ RateLimitDaily: goutils.EnvInt("POSTA_RATE_LIMIT_DAILY", 1000),
+ AdminEmail: goutils.Env("POSTA_ADMIN_EMAIL", "[email protected]"),
+ AdminPassword: goutils.Env("POSTA_ADMIN_PASSWORD", "admin1234"),
+ OpenAPIDocs: goutils.EnvBool("POSTA_OPENAPI_DOCS", true),
+ MetricsEnabled: goutils.EnvBool("POSTA_METRICS_ENABLED", false),
+ WebDir: goutils.Env("POSTA_WEB_DIR", "web/dist"),
+ AppWebURL: goutils.Env("POSTA_WEB_URL", ""),
+
+ CORSOrigins: goutils.Env("POSTA_CORS_ORIGINS", "*"),
+
+ EmbeddedWorker: goutils.EnvBool("POSTA_EMBEDDED_WORKER", false),
+ WorkerConcurrency: goutils.EnvInt("POSTA_WORKER_CONCURRENCY", 10),
+ WorkerMaxRetries: goutils.EnvInt("POSTA_WORKER_MAX_RETRIES", 5),
+
+ WebhookMaxRetries: goutils.EnvInt("POSTA_WEBHOOK_MAX_RETRIES", 3),
+ WebhookTimeoutSecs: goutils.EnvInt("POSTA_WEBHOOK_TIMEOUT_SECS", 10),
+ }
+}
+func (c *Config) validate() error {
+
+ return nil
+}
+func (c *Config) validateWorker() error {
+
+ return nil
+}
+func (c *Config) Initialize(app *okapi.Okapi) error {
+ if err := c.validate(); err != nil {
+ return err
+ }
+ // Initialize global logger
+ l := c.initLogger()
+ app.WithLogger(l.Logger)
+
+ corsOrigins := strings.Split(c.CORSOrigins, ",")
+ for i := range corsOrigins {
+ corsOrigins[i] = strings.TrimSpace(corsOrigins[i])
+ }
+ app.WithCORS(okapi.Cors{
+ AllowedOrigins: corsOrigins,
+ AllowedHeaders: []string{"Content-Type", "Authorization", "X-Request-ID"},
+ AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
+ AllowCredentials: true,
+ })
+ if c.OpenAPIDocs {
+ app.WithOpenAPIDocs(okapi.OpenAPI{
+ Title: "Posta API",
+ Version: "v1",
+ })
+ }
+ app.WithErrorHandler(errorhandlers.CustomErrorHandler())
+ return nil
+}
+func (c *Config) InitWorker() error {
+ // Initialize global logger
+ c.initLogger()
+ if err := c.validateWorker(); err != nil {
+ return err
+ }
+ return nil
+}
+func (c *Config) initLogger() *logger.Logger {
+ if c.DevMode {
+ return logger.New(logger.WithDebugLevel())
+ }
+ return logger.New(logger.WithJSONFormat(), logger.WithInfoLevel())
+}
+
+func (c *Config) InitStorage() {
+ var dsn string
+ if c.Database.url != "" {
+ dsn = c.Database.url
+ } else {
+ dsn = fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%d sslmode=%s", c.Database.host, c.Database.user, c.Database.password, c.Database.name, c.Database.port, c.Database.sslMode)
+ }
+ dbConn, err := storage.ConnectPostgres(dsn)
+ if err != nil {
+ logger.Fatal("failed to connect to database", "error", err)
+ }
+ c.Database.DB = dbConn
+
+ redisClient, err := storage.NewRedis(c.Redis.Addr, c.Redis.Password)
+ if err != nil {
+ logger.Fatal("failed to connect to redis", "error", err)
+ }
+ c.Redis.Client = redisClient
+
+}
diff --git a/internal/config/version.go b/internal/config/version.go
new file mode 100644
index 0000000..955babe
--- /dev/null
+++ b/internal/config/version.go
@@ -0,0 +1,31 @@
+/*
+ * 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 config
+
+var (
+ BuildDate = "2026-03-15"
+ Version = "dev"
+ CommitID = "unknown"
+)
diff --git a/internal/cron/cronjob.go b/internal/cron/cronjob.go
new file mode 100644
index 0000000..ca0d62f
--- /dev/null
+++ b/internal/cron/cronjob.go
@@ -0,0 +1,39 @@
+/*
+ * 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 cron
+
+import (
+ "context"
+
+ "github.com/hibiken/asynq"
+)
+
+// CronJob defines a recurring job that enqueues work on a cron schedule.
+type CronJob interface {
+ Name() string
+ // cron expression
+ Schedule() string
+ Run(ctx context.Context, client *asynq.Client) error
+}
diff --git a/internal/cron/job.go b/internal/cron/job.go
new file mode 100644
index 0000000..5a7d23c
--- /dev/null
+++ b/internal/cron/job.go
@@ -0,0 +1,48 @@
+/*
+ * 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 cron
+
+import (
+ "encoding/json"
+
+ "github.com/hibiken/asynq"
+)
+
+// Job represents a unit of work that can be enqueued as an Asynq task.
+type Job interface {
+ Type() string
+ Payload() any
+}
+
+// EnqueueJob converts a Job into an Asynq task and enqueues it.
+func EnqueueJob(client *asynq.Client, job Job, opts ...asynq.Option) error {
+ payload, err := json.Marshal(job.Payload())
+ if err != nil {
+ return err
+ }
+ task := asynq.NewTask(job.Type(), payload, opts...)
+ _, err = client.Enqueue(task)
+ return err
+}
diff --git a/internal/cron/jobs/daily_report.go b/internal/cron/jobs/daily_report.go
new file mode 100644
index 0000000..fea31c6
--- /dev/null
+++ b/internal/cron/jobs/daily_report.go
@@ -0,0 +1,92 @@
+/*
+ * 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 jobs
+
+import (
+ "context"
+ "encoding/json"
+
+ "github.com/hibiken/asynq"
+ "github.com/jkaninda/logger"
+ "github.com/jkaninda/posta/internal/cron"
+ "github.com/jkaninda/posta/internal/storage/repositories"
+)
+
+const TypeDailyReport = "cron:daily-report"
+
+// DailyReportPayload is the Asynq task payload for a per-user daily report.
+type DailyReportPayload struct {
+ UserID uint `json:"user_id"`
+}
+
+// DailyReportJob is a daily report job that enqueues a report task for each user
+// that has daily_report enabled in their settings.
+type DailyReportJob struct {
+ userSettingRepo *repositories.UserSettingRepository
+}
+
+// dailyReportTask implements cron.Job for enqueueing a single user's report.
+type dailyReportTask struct {
+ userID uint
+}
+
+func (t *dailyReportTask) Type() string { return TypeDailyReport }
+func (t *dailyReportTask) Payload() any { return DailyReportPayload{UserID: t.userID} }
+
+func NewDailyReportJob(userSettingRepo *repositories.UserSettingRepository) *DailyReportJob {
+ return &DailyReportJob{userSettingRepo: userSettingRepo}
+}
+
+func (j *DailyReportJob) Name() string { return "daily-report" }
+func (j *DailyReportJob) Schedule() string { return "0 7 * * *" } // daily at 07:00 UTC
+
+func (j *DailyReportJob) Run(_ context.Context, client *asynq.Client) error {
+ users, err := j.userSettingRepo.FindUsersWithDailyReport()
+ if err != nil {
+ logger.Error("daily report: failed to find users", "error", err)
+ return err
+ }
+
+ enqueued := 0
+ for _, userID := range users {
+ if err := cron.EnqueueJob(client, &dailyReportTask{userID: userID}, asynq.Queue("low")); err != nil {
+ logger.Error("daily report: failed to enqueue", "user_id", userID, "error", err)
+ continue
+ }
+ enqueued++
+ }
+
+ logger.Info("daily report: enqueued tasks", "count", enqueued)
+ return nil
+}
+
+// NewDailyReportTask creates an Asynq task for processing a daily report.
+func NewDailyReportTask(userID uint, opts ...asynq.Option) (*asynq.Task, error) {
+ payload, err := json.Marshal(DailyReportPayload{UserID: userID})
+ if err != nil {
+ return nil, err
+ }
+ return asynq.NewTask(TypeDailyReport, payload, opts...), nil
+}
diff --git a/internal/cron/jobs/retention.go b/internal/cron/jobs/retention.go
new file mode 100644
index 0000000..f6d1990
--- /dev/null
+++ b/internal/cron/jobs/retention.go
@@ -0,0 +1,101 @@
+/*
+ * 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 jobs
+
+import (
+ "context"
+ "time"
+
+ "github.com/hibiken/asynq"
+ "github.com/jkaninda/logger"
+ "github.com/jkaninda/posta/internal/services/settings"
+ "github.com/jkaninda/posta/internal/storage/repositories"
+)
+
+// RetentionCleanupJob purges old email logs, audit events, and webhook
+// delivery records based on platform retention settings.
+type RetentionCleanupJob struct {
+ emailRepo *repositories.EmailRepository
+ eventRepo *repositories.EventRepository
+ whDeliveryRepo *repositories.WebhookDeliveryRepository
+ settings *settings.Provider
+}
+
+func NewRetentionCleanupJob(
+ emailRepo *repositories.EmailRepository,
+ eventRepo *repositories.EventRepository,
+ whDeliveryRepo *repositories.WebhookDeliveryRepository,
+ sp *settings.Provider,
+) *RetentionCleanupJob {
+ return &RetentionCleanupJob{
+ emailRepo: emailRepo,
+ eventRepo: eventRepo,
+ whDeliveryRepo: whDeliveryRepo,
+ settings: sp,
+ }
+}
+
+func (j *RetentionCleanupJob) Name() string { return "retention-cleanup" }
+func (j *RetentionCleanupJob) Schedule() string { return "0 3 * * *" } // daily at 03:00 UTC
+
+func (j *RetentionCleanupJob) Run(_ context.Context, _ *asynq.Client) error {
+ // Clean up email logs
+ emailRetention := j.settings.RetentionDays()
+ if emailRetention > 0 {
+ before := time.Now().AddDate(0, 0, -emailRetention)
+ deleted, err := j.emailRepo.DeleteOlderThan(before)
+ if err != nil {
+ logger.Error("retention cleanup: failed to delete old emails", "error", err)
+ } else if deleted > 0 {
+ logger.Info("retention cleanup: deleted old emails", "count", deleted, "older_than_days", emailRetention)
+ }
+ }
+
+ // Clean up audit/event logs
+ auditRetention := j.settings.AuditLogRetentionDays()
+ if auditRetention > 0 {
+ before := time.Now().AddDate(0, 0, -auditRetention)
+ deleted, err := j.eventRepo.DeleteOlderThan(before)
+ if err != nil {
+ logger.Error("retention cleanup: failed to delete old events", "error", err)
+ } else if deleted > 0 {
+ logger.Info("retention cleanup: deleted old events", "count", deleted, "older_than_days", auditRetention)
+ }
+ }
+
+ // Clean up webhook delivery logs
+ whRetention := j.settings.WebhookDeliveryRetentionDays()
+ if whRetention > 0 {
+ before := time.Now().AddDate(0, 0, -whRetention)
+ deleted, err := j.whDeliveryRepo.DeleteOlderThan(before)
+ if err != nil {
+ logger.Error("retention cleanup: failed to delete old webhook deliveries", "error", err)
+ } else if deleted > 0 {
+ logger.Info("retention cleanup: deleted old webhook deliveries", "count", deleted, "older_than_days", whRetention)
+ }
+ }
+
+ return nil
+}
diff --git a/internal/cron/manager.go b/internal/cron/manager.go
new file mode 100644
index 0000000..bb13662
--- /dev/null
+++ b/internal/cron/manager.go
@@ -0,0 +1,171 @@
+/*
+ * 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 cron
+
+import (
+ "context"
+ "sync"
+ "time"
+
+ "github.com/hibiken/asynq"
+ "github.com/jkaninda/logger"
+ "github.com/robfig/cron/v3"
+)
+
+// JobStatus holds runtime state for a registered cron job.
+type JobStatus struct {
+ Name string `json:"name"`
+ Schedule string `json:"schedule"`
+ Running bool `json:"running"`
+ LastRunAt *time.Time `json:"last_run_at"`
+ LastError string `json:"last_error,omitempty"`
+ NextRunAt *time.Time `json:"next_run_at"`
+}
+
+// Manager is responsible for registering cron jobs, triggering them based
+// on cron expressions, and enqueueing Asynq jobs.
+type Manager struct {
+ client *asynq.Client
+ jobs []CronJob
+ cron *cron.Cron
+ mu sync.Mutex
+ running bool
+ statuses map[string]*jobState
+}
+
+type jobState struct {
+ running bool
+ lastRunAt *time.Time
+ lastError string
+}
+
+// NewManager creates a new cron manager backed by the given Asynq client.
+func NewManager(client *asynq.Client) *Manager {
+ return &Manager{
+ client: client,
+ cron: cron.New(cron.WithLocation(time.UTC)),
+ statuses: make(map[string]*jobState),
+ }
+}
+
+// Register adds a cron job to the manager.
+func (m *Manager) Register(job CronJob) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ m.jobs = append(m.jobs, job)
+ m.statuses[job.Name()] = &jobState{}
+}
+
+// Start begins running all registered cron jobs.
+func (m *Manager) Start(ctx context.Context) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if m.running {
+ return
+ }
+
+ for _, j := range m.jobs {
+ job := j // capture for closure
+ _, err := m.cron.AddFunc(job.Schedule(), func() {
+ m.setRunning(job.Name(), true)
+ defer m.setRunning(job.Name(), false)
+
+ now := time.Now().UTC()
+ if err := job.Run(ctx, m.client); err != nil {
+ m.recordRun(job.Name(), now, err.Error())
+ logger.Error("cron job failed", "name", job.Name(), "error", err)
+ } else {
+ m.recordRun(job.Name(), now, "")
+ logger.Debug("cron job completed", "name", job.Name())
+ }
+ })
+ if err != nil {
+ logger.Error("failed to register cron job", "name", job.Name(), "schedule", job.Schedule(), "error", err)
+ continue
+ }
+ logger.Info("registered cron job", "name", job.Name(), "schedule", job.Schedule())
+ }
+
+ m.cron.Start()
+ m.running = true
+ logger.Info("cron manager started", "jobs", len(m.jobs))
+}
+
+// Stop gracefully shuts down the cron scheduler.
+func (m *Manager) Stop() {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if !m.running {
+ return
+ }
+ m.cron.Stop()
+ m.running = false
+ logger.Info("cron manager stopped")
+}
+
+// Jobs returns the current status of all registered cron jobs.
+func (m *Manager) Jobs() []JobStatus {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+
+ entries := m.cron.Entries()
+
+ result := make([]JobStatus, 0, len(m.jobs))
+ for i, job := range m.jobs {
+ st := m.statuses[job.Name()]
+ js := JobStatus{
+ Name: job.Name(),
+ Schedule: job.Schedule(),
+ Running: st.running,
+ LastRunAt: st.lastRunAt,
+ LastError: st.lastError,
+ }
+ if m.running && i < len(entries) {
+ next := entries[i].Next
+ if !next.IsZero() {
+ js.NextRunAt = &next
+ }
+ }
+ result = append(result, js)
+ }
+ return result
+}
+
+func (m *Manager) setRunning(name string, running bool) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if st, ok := m.statuses[name]; ok {
+ st.running = running
+ }
+}
+
+func (m *Manager) recordRun(name string, at time.Time, errMsg string) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if st, ok := m.statuses[name]; ok {
+ st.lastRunAt = &at
+ st.lastError = errMsg
+ }
+}
diff --git a/internal/dto/types.go b/internal/dto/types.go
new file mode 100644
index 0000000..b6d9a4d
--- /dev/null
+++ b/internal/dto/types.go
@@ -0,0 +1,73 @@
+/*
+ * 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 dto
+
+// Response is the standard API response envelope with a generic data field.
+type Response[T any] struct {
+ Success bool `json:"success"`
+ Data T `json:"data,omitempty"`
+}
+
+// PageableResponse is the paginated API response envelope.
+type PageableResponse[T any] struct {
+ Success bool `json:"success"`
+ Data []T `json:"data"`
+ Pageable Pageable `json:"pageable"`
+}
+
+// Pageable holds pagination metadata.
+type Pageable struct {
+ CurrentPage int `json:"current_page"`
+ Size int `json:"size"`
+ TotalPages int `json:"total_pages"`
+ TotalElements int64 `json:"total_elements"`
+ Empty bool `json:"empty"`
+}
+
+// ErrorResponseBody is the error envelope returned by the custom error handler.
+type ErrorResponseBody struct {
+ Success bool `json:"success"`
+ Data any `json:"data"`
+ Error *ErrorInfo `json:"error"`
+}
+
+// ErrorInfo holds error details.
+type ErrorInfo struct {
+ Code string `json:"code"`
+ Message string `json:"message"`
+ Error string `json:"error"`
+}
+
+type APIKeyCreatedData struct {
+ Key string `json:"key"`
+ ID uint `json:"id"`
+ Name string `json:"name"`
+ Prefix string `json:"prefix"`
+ Message string `json:"message"`
+}
+
+type MessageData struct {
+ Message string `json:"message"`
+}
diff --git a/internal/error_handlers/errors.go b/internal/error_handlers/errors.go
new file mode 100644
index 0000000..ede8bd4
--- /dev/null
+++ b/internal/error_handlers/errors.go
@@ -0,0 +1,74 @@
+/*
+ * 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 errorhandlers
+
+import (
+ "github.com/jkaninda/okapi"
+ "github.com/jkaninda/posta/internal/dto"
+)
+
+// CustomErrorHandler returns an okapi.ErrorHandler that formats errors
+func CustomErrorHandler() okapi.ErrorHandler {
+ return func(c *okapi.Context, code int, message string, err error) error {
+ return c.JSON(code, dto.ErrorResponseBody{
+ Success: false,
+ Data: nil,
+ Error: &dto.ErrorInfo{
+ Code: httpStatusToCode(code),
+ Error: err.Error(),
+ Message: message,
+ },
+ })
+ }
+}
+
+func httpStatusToCode(status int) string {
+ switch status {
+ case 400:
+ return "BAD_REQUEST"
+ case 401:
+ return "UNAUTHORIZED"
+ case 403:
+ return "FORBIDDEN"
+ case 404:
+ return "NOT_FOUND"
+ case 405:
+ return "METHOD_NOT_ALLOWED"
+ case 409:
+ return "CONFLICT"
+ case 422:
+ return "UNPROCESSABLE_ENTITY"
+ case 429:
+ return "TOO_MANY_REQUESTS"
+ case 500:
+ return "INTERNAL_SERVER_ERROR"
+ case 502:
+ return "BAD_GATEWAY"
+ case 503:
+ return "SERVICE_UNAVAILABLE"
+ default:
+ return "ERROR"
+ }
+}
diff --git a/internal/handlers/admin_handler.go b/internal/handlers/admin_handler.go
new file mode 100644
index 0000000..c3df23b
--- /dev/null
+++ b/internal/handlers/admin_handler.go
@@ -0,0 +1,471 @@
+/*
+ * 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"
+ "os"
+ "time"
+
+ "github.com/hibiken/asynq"
+ "github.com/jkaninda/okapi"
+ "github.com/jkaninda/posta/internal/models"
+ "github.com/jkaninda/posta/internal/services/cache"
+ "github.com/jkaninda/posta/internal/services/eventbus"
+ "github.com/jkaninda/posta/internal/services/seeder"
+ "github.com/jkaninda/posta/internal/storage/repositories"
+ "golang.org/x/crypto/bcrypt"
+ "gorm.io/gorm"
+)
+
+type AdminHandler struct {
+ db *gorm.DB
+ cache *cache.Cache
+ userRepo *repositories.UserRepository
+ keyRepo *repositories.APIKeyRepository
+ emailRepo *repositories.EmailRepository
+ whDeliveryRepo *repositories.WebhookDeliveryRepository
+ inspector *asynq.Inspector
+ bus *eventbus.EventBus
+ seeder *seeder.Seeder
+ embeddedWorker bool
+}
+type AdminCreateUserRequest struct {
+ Body struct {
+ Name string `json:"name"`
+ Email string `json:"email" required:"true" format:"email"`
+ Password string `json:"password" required:"true" minLength:"8"`
+ Role string `json:"role" enum:"admin,user" required:"true"`
+ } `json:"body"`
+}
+type AdminUpdateUserRequest struct {
+ ID int `param:"id"`
+ Body struct {
+ Role string `json:"role" enum:"admin,user"`
+ Active *bool `json:"active"`
+ } `json:"body"`
+}
+type AdminDeleteUserRequest struct {
+ ID int `param:"id"`
+}
+
+// PlatformMetrics holds aggregate platform metrics.
+type PlatformMetrics struct {
+ TotalUsers int64 `json:"total_users"`
+ TotalEmails int64 `json:"total_emails"`
+ QueuedEmails int64 `json:"queued_emails"`
+ ProcessingEmails int64 `json:"processing_emails"`
+ SentEmails int64 `json:"sent_emails"`
+ FailedEmails int64 `json:"failed_emails"`
+ SuppressedEmails int64 `json:"suppressed_emails"`
+ FailureRate float64 `json:"failure_rate"`
+ TotalAPIKeys int64 `json:"total_api_keys"`
+ ActiveAPIKeys int64 `json:"active_api_keys"`
+ TotalBounces int64 `json:"total_bounces"`
+ TotalSuppressions int64 `json:"total_suppressions"`
+ ActiveWorkers int `json:"active_workers"`
+ SharedSmtpServers int64 `json:"shared_smtp_servers"`
+ TotalDomains int64 `json:"total_domains"`
+ WebhookDeliveries *repositories.WebhookDeliveryStats `json:"webhook_deliveries"`
+}
+
+type AdminRevokeKeyRequest struct {
+ ID int `param:"id"`
+}
+
+type AdminGetUserRequest struct {
+ ID int `param:"id"`
+}
+
+// UserDetailMetrics holds per-user metrics.
+type UserDetailMetrics struct {
+ User *models.User `json:"user"`
+ TotalEmails int64 `json:"total_emails"`
+ SentEmails int64 `json:"sent_emails"`
+ FailedEmails int64 `json:"failed_emails"`
+ SuppressedEmails int64 `json:"suppressed_emails"`
+ FailureRate float64 `json:"failure_rate"`
+ TotalAPIKeys int64 `json:"total_api_keys"`
+ ActiveAPIKeys int64 `json:"active_api_keys"`
+ TotalContacts int64 `json:"total_contacts"`
+ TotalBounces int64 `json:"total_bounces"`
+ TotalSuppressions int64 `json:"total_suppressions"`
+ TotalDomains int64 `json:"total_domains"`
+ TotalSmtpServers int64 `json:"total_smtp_servers"`
+ WebhookDeliveries *repositories.WebhookDeliveryStats `json:"webhook_deliveries"`
+}
+
+func NewAdminHandler(db *gorm.DB, c *cache.Cache, userRepo *repositories.UserRepository, keyRepo *repositories.APIKeyRepository, emailRepo *repositories.EmailRepository, whDeliveryRepo *repositories.WebhookDeliveryRepository, inspector *asynq.Inspector, bus *eventbus.EventBus, seeder *seeder.Seeder, embeddedWorker bool) *AdminHandler {
+ return &AdminHandler{db: db, cache: c, userRepo: userRepo, keyRepo: keyRepo, emailRepo: emailRepo, whDeliveryRepo: whDeliveryRepo, inspector: inspector, bus: bus, seeder: seeder, embeddedWorker: embeddedWorker}
+}
+
+// CreateUser allows admins to create a new user.
+func (h *AdminHandler) CreateUser(c *okapi.Context, req *AdminCreateUserRequest) error {
+ role := models.UserRole(req.Body.Role)
+ if role != models.UserRoleAdmin && role != models.UserRoleUser {
+ role = models.UserRoleUser
+ }
+
+ hash, err := bcrypt.GenerateFromPassword([]byte(req.Body.Password), bcrypt.DefaultCost)
+ if err != nil {
+ return c.AbortInternalServerError("failed to hash password", err)
+ }
+
+ user := &models.User{
+ Name: req.Body.Name,
+ Email: req.Body.Email,
+ PasswordHash: string(hash),
+ Role: role,
+ }
+
+ if err := h.userRepo.Create(user); err != nil {
+ return c.AbortConflict("email already registered")
+ }
+
+ // Seed default templates, stylesheets, and languages for the new user
+ if h.seeder != nil {
+ go h.seeder.SeedUserDefaults(user.ID, user.Name)
+ }
+
+ if h.bus != nil {
+ adminID := uint(c.GetInt("user_id"))
+ h.bus.PublishSimple(models.EventCategoryUser, "user.created", &adminID, c.GetString("email"), c.RealIP(),
+ fmt.Sprintf("User %q created", user.Email), map[string]any{"user_id": user.ID, "role": string(user.Role)})
+ }
+
+ return created(c, user)
+}
+
+// ListUsers returns all users.
+func (h *AdminHandler) ListUsers(c *okapi.Context, req *ListRequest) error {
+ page, size, offset := normalizePageParams(req.Page, req.Size)
+
+ users, total, err := h.userRepo.FindAll(size, offset)
+ if err != nil {
+ return c.AbortInternalServerError("failed to list users")
+ }
+
+ return paginated(c, users, total, page, size)
+}
+
+// UpdateUser allows admins to change a user's role and active status.
+func (h *AdminHandler) UpdateUser(c *okapi.Context, req *AdminUpdateUserRequest) error {
+ user, err := h.userRepo.FindByID(uint(req.ID))
+ if err != nil {
+ return c.AbortNotFound("user not found")
+ }
+
+ if req.Body.Role != "" {
+ user.Role = models.UserRole(req.Body.Role)
+ }
+ if req.Body.Active != nil {
+ if !*req.Body.Active && user.ID == uint(c.GetInt("user_id")) {
+ return c.AbortBadRequest("cannot disable your own account")
+ }
+ user.Active = *req.Body.Active
+ }
+ if err := h.userRepo.Update(user); err != nil {
+ return c.AbortInternalServerError("failed to update user")
+ }
+
+ if h.bus != nil {
+ adminID := uint(c.GetInt("user_id"))
+ h.bus.PublishSimple(models.EventCategoryUser, "user.updated", &adminID, c.GetString("email"), c.RealIP(),
+ fmt.Sprintf("User %q updated", user.Email), map[string]any{"user_id": user.ID})
+ }
+
+ return ok(c, user)
+}
+
+// DeleteUser deletes a user (admin only).
+func (h *AdminHandler) DeleteUser(c *okapi.Context, req *AdminDeleteUserRequest) error {
+ currentUserID := c.GetInt("user_id")
+ if req.ID == currentUserID {
+ return c.AbortBadRequest("cannot delete your own account")
+ }
+
+ _, err := h.userRepo.FindByID(uint(req.ID))
+ if err != nil {
+ return c.AbortNotFound("user not found")
+ }
+
+ if err := h.userRepo.Delete(uint(req.ID)); err != nil {
+ return c.AbortInternalServerError("failed to delete user")
+ }
+
+ if h.bus != nil {
+ adminID := uint(c.GetInt("user_id"))
+ h.bus.PublishSimple(models.EventCategoryUser, "user.deleted", &adminID, c.GetString("email"), c.RealIP(),
+ fmt.Sprintf("User ID %d deleted", req.ID), map[string]any{"deleted_user_id": req.ID})
+ }
+
+ return noContent(c)
+}
+
+// ListAllEmails returns all emails across all users (admin only).
+func (h *AdminHandler) ListAllEmails(c *okapi.Context, req *ListRequest) error {
+ page, size, offset := normalizePageParams(req.Page, req.Size)
+
+ emails, total, err := h.emailRepo.FindAll(size, offset)
+ if err != nil {
+ return c.AbortInternalServerError("failed to list emails")
+ }
+
+ return paginated(c, emails, total, page, size)
+}
+
+// ListAllAPIKeys returns all API keys across all users (admin only).
+func (h *AdminHandler) ListAllAPIKeys(c *okapi.Context, req *ListRequest) error {
+ page, size, offset := normalizePageParams(req.Page, req.Size)
+
+ keys, total, err := h.keyRepo.FindAll(size, offset)
+ if err != nil {
+ return c.AbortInternalServerError("failed to list API keys")
+ }
+
+ return paginated(c, keys, total, page, size)
+}
+
+// RevokeAPIKey allows admins to revoke any API key.
+func (h *AdminHandler) RevokeAPIKey(c *okapi.Context, req *AdminRevokeKeyRequest) error {
+ _, err := h.keyRepo.FindByID(uint(req.ID))
+ if err != nil {
+ return c.AbortNotFound("API key not found")
+ }
+
+ if err := h.keyRepo.Revoke(uint(req.ID)); err != nil {
+ return c.AbortInternalServerError("failed to revoke API key")
+ }
+
+ if h.bus != nil {
+ adminID := uint(c.GetInt("user_id"))
+ h.bus.PublishSimple(models.EventCategoryUser, "apikey.revoked", &adminID, c.GetString("email"), c.RealIP(),
+ fmt.Sprintf("API key ID %d revoked", req.ID), map[string]any{"api_key_id": req.ID})
+ }
+
+ return ok(c, okapi.M{"message": "API key revoked"})
+}
+
+// Metrics returns platform-wide metrics (admin only).
+func (h *AdminHandler) Metrics(c *okapi.Context) error {
+ ctx := c.Request().Context()
+
+ // Try cache first
+ cacheKey := cache.AdminMetricsKey()
+ var m PlatformMetrics
+ if h.cache.Get(ctx, cacheKey, &m) {
+ // Always fetch live worker count since it's cheap and real-time.
+ if h.inspector != nil {
+ if servers, err := h.inspector.Servers(); err == nil {
+ m.ActiveWorkers = len(servers)
+ }
+ }
+ return ok(c, m)
+ }
+
+ h.db.Model(&models.User{}).Count(&m.TotalUsers)
+ h.db.Model(&models.Email{}).Count(&m.TotalEmails)
+ h.db.Model(&models.Email{}).Where("status = ?", models.EmailStatusQueued).Count(&m.QueuedEmails)
+ h.db.Model(&models.Email{}).Where("status = ?", models.EmailStatusProcessing).Count(&m.ProcessingEmails)
+ h.db.Model(&models.Email{}).Where("status = ?", models.EmailStatusSent).Count(&m.SentEmails)
+ h.db.Model(&models.Email{}).Where("status = ?", models.EmailStatusFailed).Count(&m.FailedEmails)
+ h.db.Model(&models.Email{}).Where("status = ?", models.EmailStatusSuppressed).Count(&m.SuppressedEmails)
+ h.db.Model(&models.APIKey{}).Count(&m.TotalAPIKeys)
+ h.db.Model(&models.APIKey{}).Where("revoked = false").Count(&m.ActiveAPIKeys)
+ h.db.Model(&models.Bounce{}).Count(&m.TotalBounces)
+ h.db.Model(&models.Suppression{}).Count(&m.TotalSuppressions)
+ h.db.Model(&models.Server{}).Count(&m.SharedSmtpServers)
+ h.db.Model(&models.Domain{}).Count(&m.TotalDomains)
+
+ if m.TotalEmails > 0 {
+ m.FailureRate = float64(m.FailedEmails) / float64(m.TotalEmails) * 100
+ }
+
+ if h.inspector != nil {
+ if servers, err := h.inspector.Servers(); err == nil {
+ m.ActiveWorkers = len(servers)
+ }
+ }
+
+ // Webhook delivery stats (platform-wide)
+ if whStats, err := h.whDeliveryRepo.StatsAll(); err == nil {
+ m.WebhookDeliveries = whStats
+ }
+
+ h.cache.Set(ctx, cacheKey, m, cache.AdminMetricsTTL)
+
+ return ok(c, m)
+}
+
+// UserMetrics returns detailed metrics for a specific user (admin only).
+func (h *AdminHandler) UserMetrics(c *okapi.Context, req *AdminGetUserRequest) error {
+ ctx := c.Request().Context()
+
+ // Try cache first
+ cacheKey := cache.UserMetricsKey(req.ID)
+ var m UserDetailMetrics
+ if h.cache.Get(ctx, cacheKey, &m) {
+ return ok(c, m)
+ }
+
+ user, err := h.userRepo.FindByID(uint(req.ID))
+ if err != nil {
+ return c.AbortNotFound("user not found")
+ }
+
+ m.User = user
+
+ h.db.Model(&models.Email{}).Where("user_id = ?", req.ID).Count(&m.TotalEmails)
+ h.db.Model(&models.Email{}).Where("user_id = ? AND status = ?", req.ID, models.EmailStatusSent).Count(&m.SentEmails)
+ h.db.Model(&models.Email{}).Where("user_id = ? AND status = ?", req.ID, models.EmailStatusFailed).Count(&m.FailedEmails)
+ h.db.Model(&models.Email{}).Where("user_id = ? AND status = ?", req.ID, models.EmailStatusSuppressed).Count(&m.SuppressedEmails)
+ h.db.Model(&models.APIKey{}).Where("user_id = ?", req.ID).Count(&m.TotalAPIKeys)
+ h.db.Model(&models.APIKey{}).Where("user_id = ? AND revoked = false", req.ID).Count(&m.ActiveAPIKeys)
+ h.db.Model(&models.Contact{}).Where("user_id = ?", req.ID).Count(&m.TotalContacts)
+ h.db.Model(&models.Bounce{}).Where("user_id = ?", req.ID).Count(&m.TotalBounces)
+ h.db.Model(&models.Suppression{}).Where("user_id = ?", req.ID).Count(&m.TotalSuppressions)
+ h.db.Model(&models.Domain{}).Where("user_id = ?", req.ID).Count(&m.TotalDomains)
+ h.db.Model(&models.SMTPServer{}).Where("user_id = ?", req.ID).Count(&m.TotalSmtpServers)
+
+ if m.TotalEmails > 0 {
+ m.FailureRate = float64(m.FailedEmails) / float64(m.TotalEmails) * 100
+ }
+
+ // Webhook delivery stats for this user
+ if whStats, err := h.whDeliveryRepo.StatsByUserID(uint(req.ID)); err == nil {
+ m.WebhookDeliveries = whStats
+ }
+
+ h.cache.Set(ctx, cacheKey, m, cache.UserMetricsTTL)
+
+ return ok(c, m)
+}
+
+// Disable2FA allows admins to disable 2FA for a user.
+func (h *AdminHandler) Disable2FA(c *okapi.Context, req *AdminGetUserRequest) error {
+ user, err := h.userRepo.FindByID(uint(req.ID))
+ if err != nil {
+ return c.AbortNotFound("user not found")
+ }
+
+ if !user.TwoFactorEnabled {
+ return c.AbortBadRequest("2FA is not enabled for this user")
+ }
+
+ user.TwoFactorEnabled = false
+ user.TwoFactorSecret = ""
+ if err := h.userRepo.Update(user); err != nil {
+ return c.AbortInternalServerError("failed to disable 2FA")
+ }
+
+ if h.bus != nil {
+ adminID := uint(c.GetInt("user_id"))
+ h.bus.PublishSimple(models.EventCategoryUser, "user.2fa_disabled", &adminID, c.GetString("email"), c.RealIP(),
+ fmt.Sprintf("2FA disabled for user %q by admin", user.Email), map[string]any{"user_id": user.ID})
+ }
+
+ return ok(c, okapi.M{"message": "2FA disabled"})
+}
+
+// WorkerStatus is sent over SSE with the current worker count and details.
+type WorkerStatus struct {
+ ActiveWorkers int `json:"active_workers"`
+ Workers []WorkerDetail `json:"workers"`
+}
+
+// WorkerDetail holds info about a single connected worker.
+type WorkerDetail struct {
+ Host string `json:"host"`
+ PID int `json:"pid"`
+ Queues map[string]int `json:"queues"`
+ Type string `json:"type"` // "embedded" or "standalone"
+}
+
+// WorkerStream sends real-time worker status updates via SSE.
+func (h *AdminHandler) WorkerStream(c *okapi.Context) error {
+ ctx := c.Request().Context()
+
+ w := c.ResponseWriter()
+
+ sendStatus := func() error {
+ status := h.buildWorkerStatus()
+ msg := okapi.Message{
+ Event: "worker.status",
+ Data: status,
+ Serializer: &okapi.JSONSerializer{},
+ }
+ if _, err := msg.Send(w); err != nil {
+ return err
+ }
+ return nil
+ }
+
+ // Send initial status immediately.
+ if err := sendStatus(); err != nil {
+ return nil
+ }
+
+ ticker := time.NewTicker(10 * time.Second)
+ defer ticker.Stop()
+
+ for {
+ select {
+ case <-ctx.Done():
+ return nil
+ case <-ticker.C:
+ if err := sendStatus(); err != nil {
+ return nil
+ }
+ }
+ }
+}
+
+func (h *AdminHandler) buildWorkerStatus() WorkerStatus {
+ var status WorkerStatus
+ if h.inspector == nil {
+ return status
+ }
+ servers, err := h.inspector.Servers()
+ if err != nil {
+ return status
+ }
+ selfPID := os.Getpid()
+ selfHost, _ := os.Hostname()
+ status.ActiveWorkers = len(servers)
+ status.Workers = make([]WorkerDetail, 0, len(servers))
+ for _, s := range servers {
+ wType := "standalone"
+ if h.embeddedWorker && s.PID == selfPID && s.Host == selfHost {
+ wType = "embedded"
+ }
+ status.Workers = append(status.Workers, WorkerDetail{
+ Host: s.Host,
+ PID: s.PID,
+ Queues: s.Queues,
+ Type: wType,
+ })
+ }
+ return status
+}
diff --git a/internal/handlers/analytics_handler.go b/internal/handlers/analytics_handler.go
new file mode 100644
index 0000000..764fd6d
--- /dev/null
+++ b/internal/handlers/analytics_handler.go
@@ -0,0 +1,133 @@
+/*
+ * 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 (
+ "time"
+
+ "github.com/jkaninda/okapi"
+ "github.com/jkaninda/posta/internal/services/cache"
+ "github.com/jkaninda/posta/internal/storage/repositories"
+)
+
+type AnalyticsHandler struct {
+ repo *repositories.AnalyticsRepository
+ cache *cache.Cache
+}
+
+func NewAnalyticsHandler(repo *repositories.AnalyticsRepository, c *cache.Cache) *AnalyticsHandler {
+ return &AnalyticsHandler{repo: repo, cache: c}
+}
+
+type AnalyticsRequest struct {
+ From string `query:"from"`
+ To string `query:"to"`
+ Status string `query:"status"`
+}
+
+type AnalyticsResponse struct {
+ DailyCounts []repositories.DailyCount `json:"daily_counts"`
+ StatusBreakdown []repositories.StatusBreakdown `json:"status_breakdown"`
+}
+
+func (h *AnalyticsHandler) UserAnalytics(c *okapi.Context, req *AnalyticsRequest) error {
+ userID := c.GetInt("user_id")
+ ctx := c.Request().Context()
+
+ // Try cache first
+ cacheKey := cache.UserAnalyticsKey(userID, req.From, req.To, req.Status)
+ var resp AnalyticsResponse
+ if h.cache.Get(ctx, cacheKey, &resp) {
+ return ok(c, resp)
+ }
+
+ from, to := parseTimeRange(req.From, req.To)
+
+ daily, err := h.repo.DailyCounts(uint(userID), from, to, req.Status)
+ if err != nil {
+ return c.AbortInternalServerError("failed to fetch analytics")
+ }
+ breakdown, err := h.repo.StatusBreakdown(uint(userID), from, to)
+ if err != nil {
+ return c.AbortInternalServerError("failed to fetch analytics")
+ }
+
+ resp = AnalyticsResponse{
+ DailyCounts: daily,
+ StatusBreakdown: breakdown,
+ }
+
+ h.cache.Set(ctx, cacheKey, resp, cache.AnalyticsTTL)
+
+ return ok(c, resp)
+}
+
+func (h *AnalyticsHandler) AdminAnalytics(c *okapi.Context, req *AnalyticsRequest) error {
+ ctx := c.Request().Context()
+
+ // Try cache first
+ cacheKey := cache.AdminAnalyticsKey(req.From, req.To, req.Status)
+ var resp AnalyticsResponse
+ if h.cache.Get(ctx, cacheKey, &resp) {
+ return ok(c, resp)
+ }
+
+ from, to := parseTimeRange(req.From, req.To)
+
+ daily, err := h.repo.AdminDailyCounts(from, to, req.Status)
+ if err != nil {
+ return c.AbortInternalServerError("failed to fetch analytics")
+ }
+ breakdown, err := h.repo.AdminStatusBreakdown(from, to)
+ if err != nil {
+ return c.AbortInternalServerError("failed to fetch analytics")
+ }
+
+ resp = AnalyticsResponse{
+ DailyCounts: daily,
+ StatusBreakdown: breakdown,
+ }
+
+ 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
+
+ if fromStr != "" {
+ if t, err := time.Parse("2006-01-02", fromStr); err == nil {
+ from = t
+ }
+ }
+ if toStr != "" {
+ if t, err := time.Parse("2006-01-02", toStr); err == nil {
+ to = t.Add(24*time.Hour - time.Second) // end of day
+ }
+ }
+ return from, to
+}
diff --git a/internal/handlers/api_key_handler.go b/internal/handlers/api_key_handler.go
new file mode 100644
index 0000000..9b7a028
--- /dev/null
+++ b/internal/handlers/api_key_handler.go
@@ -0,0 +1,158 @@
+/*
+ * 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 (
+ "time"
+
+ "github.com/jkaninda/okapi"
+ "github.com/jkaninda/posta/internal/services/audit"
+ "github.com/jkaninda/posta/internal/services/auth"
+ "github.com/jkaninda/posta/internal/storage/repositories"
+)
+
+type APIKeyHandler struct {
+ service *auth.APIKeyService
+ repo *repositories.APIKeyRepository
+ userSettingRepo *repositories.UserSettingRepository
+ audit *audit.Logger
+}
+type CreateAPIKeyRequest struct {
+ Body struct {
+ Name string `json:"name" required:"true"`
+ AllowedIPs []string `json:"allowed_ips"`
+ ExpiresInDays *int `json:"expires_in_days"`
+ } `json:"body"`
+}
+type RevokeAPIKeyRequest struct {
+ ID int `param:"id"`
+}
+type DeleteAPIKeyRequest struct {
+ ID int `param:"id"`
+}
+
+func NewAPIKeyHandler(service *auth.APIKeyService, repo *repositories.APIKeyRepository, userSettingRepo *repositories.UserSettingRepository, audit *audit.Logger) *APIKeyHandler {
+ return &APIKeyHandler{
+ service: service,
+ repo: repo,
+ userSettingRepo: userSettingRepo,
+ audit: audit,
+ }
+}
+
+func (h *APIKeyHandler) Create(c *okapi.Context, req *CreateAPIKeyRequest) error {
+ userID := c.GetInt("user_id")
+
+ // Determine expiration: use provided value, fall back to user setting default
+ var expiresAt *time.Time
+ if req.Body.ExpiresInDays != nil {
+ days := *req.Body.ExpiresInDays
+ if days > 0 {
+ t := time.Now().AddDate(0, 0, days)
+ expiresAt = &t
+ }
+ // days == 0 means never expires (expiresAt stays nil)
+ } else {
+ // Use default from user settings
+ setting, err := h.userSettingRepo.FindByUserID(uint(userID))
+ if err == nil && setting.APIKeyExpiryDays > 0 {
+ t := time.Now().AddDate(0, 0, setting.APIKeyExpiryDays)
+ expiresAt = &t
+ }
+ }
+
+ rawKey, key, err := h.service.GenerateKey(uint(userID), req.Body.Name, req.Body.AllowedIPs, expiresAt)
+ if err != nil {
+ return c.AbortInternalServerError("failed to create API key", err)
+ }
+
+ h.audit.Log(uint(userID), c.GetString("email"), c.RealIP(), "apikey.created", "API key created: "+req.Body.Name, nil)
+
+ return created(c, okapi.M{
+ "key": rawKey,
+ "id": key.ID,
+ "name": key.Name,
+ "prefix": key.KeyPrefix,
+ "expires_at": key.ExpiresAt,
+ "message": "Save this key securely. It will not be shown again.",
+ })
+}
+
+func (h *APIKeyHandler) List(c *okapi.Context, req *ListRequest) error {
+ userID := c.GetInt("user_id")
+ page, size, offset := normalizePageParams(req.Page, req.Size)
+
+ keys, total, err := h.repo.FindByUserID(uint(userID), size, offset)
+ if err != nil {
+ return c.AbortInternalServerError("failed to list API keys")
+ }
+
+ return paginated(c, keys, total, page, size)
+}
+
+func (h *APIKeyHandler) Revoke(c *okapi.Context, req *RevokeAPIKeyRequest) error {
+ userID := c.GetInt("user_id")
+
+ key, err := h.repo.FindByID(uint(req.ID))
+ if err != nil {
+ return c.AbortNotFound("API key not found")
+ }
+ if key.UserID != uint(userID) {
+ return c.AbortNotFound("API key not found")
+ }
+
+ if err := h.repo.Revoke(key.ID); err != nil {
+ return c.AbortInternalServerError("failed to revoke API key")
+ }
+
+ h.audit.Log(uint(userID), c.GetString("email"), c.RealIP(), "apikey.revoked", "API key revoked: "+key.Name, nil)
+
+ return ok(c, okapi.M{"message": "API key revoked"})
+}
+
+func (h *APIKeyHandler) Delete(c *okapi.Context, req *DeleteAPIKeyRequest) error {
+ userID := c.GetInt("user_id")
+
+ key, err := h.repo.FindByID(uint(req.ID))
+ if err != nil {
+ return c.AbortNotFound("API key not found")
+ }
+ if key.UserID != uint(userID) {
+ return c.AbortNotFound("API key not found")
+ }
+
+ // Only allow deletion of expired or revoked keys
+ if key.IsValid() {
+ return c.AbortBadRequest("active API keys cannot be deleted — revoke it first")
+ }
+
+ if err := h.repo.Delete(key.ID); err != nil {
+ return c.AbortInternalServerError("failed to delete API key")
+ }
+
+ h.audit.Log(uint(userID), c.GetString("email"), c.RealIP(), "apikey.deleted", "API key deleted: "+key.Name, nil)
+
+ return ok(c, okapi.M{"message": "API key deleted"})
+}
diff --git a/internal/handlers/bounce_handler.go b/internal/handlers/bounce_handler.go
new file mode 100644
index 0000000..630c4dd
--- /dev/null
+++ b/internal/handlers/bounce_handler.go
@@ -0,0 +1,105 @@
+/*
+ * 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 (
+ "github.com/jkaninda/okapi"
+ "github.com/jkaninda/posta/internal/metrics"
+ "github.com/jkaninda/posta/internal/models"
+ "github.com/jkaninda/posta/internal/storage/repositories"
+)
+
+type BounceHandler struct {
+ bounceRepo *repositories.BounceRepository
+ suppressionRepo *repositories.SuppressionRepository
+ emailRepo *repositories.EmailRepository
+}
+type RecordBounceRequest struct {
+ Body struct {
+ EmailID string `json:"email_id" required:"true"`
+ Recipient string `json:"recipient" required:"true" format:"email"`
+ Type string `json:"type" required:"true"`
+ Reason string `json:"reason"`
+ } `json:"body"`
+}
+
+func NewBounceHandler(bounceRepo *repositories.BounceRepository, suppressionRepo *repositories.SuppressionRepository, emailRepo *repositories.EmailRepository) *BounceHandler {
+ return &BounceHandler{bounceRepo: bounceRepo, suppressionRepo: suppressionRepo, emailRepo: emailRepo}
+}
+
+func (h *BounceHandler) Record(c *okapi.Context, req *RecordBounceRequest) error {
+ userID := c.GetInt("user_id")
+
+ validTypes := map[string]bool{"hard": true, "soft": true, "complaint": true}
+ if !validTypes[req.Body.Type] {
+ return c.AbortBadRequest("invalid bounce type. Valid types: hard, soft, complaint")
+ }
+
+ em, err := h.emailRepo.FindByUUID(req.Body.EmailID)
+ if err != nil {
+ return c.AbortNotFound("email not found")
+ }
+
+ bounce := &models.Bounce{
+ UserID: uint(userID),
+ EmailID: em.ID,
+ Recipient: req.Body.Recipient,
+ Type: models.BounceType(req.Body.Type),
+ Reason: req.Body.Reason,
+ }
+
+ if err := h.bounceRepo.Create(bounce); err != nil {
+ return c.AbortInternalServerError("failed to record bounce")
+ }
+
+ metrics.IncrementBounce(req.Body.Type)
+
+ // Auto-suppress on hard bounce or complaint
+ if req.Body.Type == "hard" || req.Body.Type == "complaint" {
+ suppression := &models.Suppression{
+ UserID: uint(userID),
+ Email: req.Body.Recipient,
+ Reason: "auto-suppressed: " + req.Body.Type + " bounce",
+ }
+ // Ignore error if already suppressed
+ if err := h.suppressionRepo.Create(suppression); err == nil {
+ metrics.IncrementSuppression()
+ }
+ }
+
+ return created(c, bounce)
+}
+
+func (h *BounceHandler) List(c *okapi.Context, req *ListRequest) error {
+ userID := c.GetInt("user_id")
+ page, size, offset := normalizePageParams(req.Page, req.Size)
+
+ bounces, total, err := h.bounceRepo.FindByUserID(uint(userID), size, offset)
+ if err != nil {
+ return c.AbortInternalServerError("failed to list bounces")
+ }
+
+ return paginated(c, bounces, total, page, size)
+}
diff --git a/internal/handlers/contact_handler.go b/internal/handlers/contact_handler.go
new file mode 100644
index 0000000..82b10e0
--- /dev/null
+++ b/internal/handlers/contact_handler.go
@@ -0,0 +1,114 @@
+/*
+ * 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 (
+ "github.com/jkaninda/okapi"
+ "github.com/jkaninda/posta/internal/models"
+ "github.com/jkaninda/posta/internal/storage/repositories"
+)
+
+type ContactHandler struct {
+ repo *repositories.ContactRepository
+ suppressionRepo *repositories.SuppressionRepository
+}
+
+func NewContactHandler(repo *repositories.ContactRepository, suppressionRepo *repositories.SuppressionRepository) *ContactHandler {
+ return &ContactHandler{repo: repo, suppressionRepo: suppressionRepo}
+}
+
+type ContactWithSuppressed struct {
+ models.Contact
+ Suppressed bool `json:"suppressed"`
+}
+
+type ListContactsRequest struct {
+ Page int `query:"page" default:"0"`
+ Size int `query:"size" default:"20"`
+ Search string `query:"search"`
+}
+
+func (h *ContactHandler) List(c *okapi.Context, req *ListContactsRequest) error {
+ userID := c.GetInt("user_id")
+ page, size, offset := normalizePageParams(req.Page, req.Size)
+
+ contacts, total, err := h.repo.FindByUserID(uint(userID), req.Search, size, offset)
+ if err != nil {
+ return c.AbortInternalServerError("failed to list contacts")
+ }
+
+ // Collect emails to batch-check suppression status
+ emails := make([]string, len(contacts))
+ for i, ct := range contacts {
+ emails[i] = ct.Email
+ }
+
+ suppressedSet := make(map[string]bool)
+ if len(emails) > 0 {
+ unsuppressed, err := h.suppressionRepo.FilterSuppressed(uint(userID), emails)
+ if err == nil {
+ unsuppressedSet := make(map[string]bool, len(unsuppressed))
+ for _, e := range unsuppressed {
+ unsuppressedSet[e] = true
+ }
+ for _, e := range emails {
+ if !unsuppressedSet[e] {
+ suppressedSet[e] = true
+ }
+ }
+ }
+ }
+
+ result := make([]ContactWithSuppressed, len(contacts))
+ for i, ct := range contacts {
+ result[i] = ContactWithSuppressed{
+ Contact: ct,
+ Suppressed: suppressedSet[ct.Email],
+ }
+ }
+
+ return paginated(c, result, total, page, size)
+}
+
+func (h *ContactHandler) Get(c *okapi.Context, req *GetByIDRequest) error {
+ userID := c.GetInt("user_id")
+
+ contact, err := h.repo.FindByID(uint(req.ID))
+ if err != nil || contact.UserID != uint(userID) {
+ return c.AbortNotFound("contact not found")
+ }
+
+ // Check suppression status
+ suppressed := false
+ unsuppressed, err := h.suppressionRepo.FilterSuppressed(uint(userID), []string{contact.Email})
+ if err == nil {
+ suppressed = len(unsuppressed) == 0
+ }
+
+ return ok(c, ContactWithSuppressed{
+ Contact: *contact,
+ Suppressed: suppressed,
+ })
+}
diff --git a/internal/handlers/contact_list_handler.go b/internal/handlers/contact_list_handler.go
new file mode 100644
index 0000000..16b9f36
--- /dev/null
+++ b/internal/handlers/contact_list_handler.go
@@ -0,0 +1,182 @@
+/*
+ * 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 (
+ "github.com/jkaninda/okapi"
+ "github.com/jkaninda/posta/internal/models"
+ "github.com/jkaninda/posta/internal/storage/repositories"
+)
+
+type ContactListHandler struct {
+ repo *repositories.ContactListRepository
+}
+
+func NewContactListHandler(repo *repositories.ContactListRepository) *ContactListHandler {
+ return &ContactListHandler{repo: repo}
+}
+
+type CreateContactListRequest struct {
+ Body struct {
+ Name string `json:"name" required:"true"`
+ Description string `json:"description"`
+ } `json:"body"`
+}
+
+type UpdateContactListRequest struct {
+ ID int `param:"id"`
+ Body struct {
+ Name string `json:"name" required:"true"`
+ Description string `json:"description"`
+ } `json:"body"`
+}
+
+type AddMemberRequest struct {
+ ID int `param:"id"`
+ Body struct {
+ Email string `json:"email" required:"true" format:"email"`
+ Name string `json:"name"`
+ } `json:"body"`
+}
+
+type RemoveMemberRequest struct {
+ ID int `param:"id"`
+ Body struct {
+ Email string `json:"email" required:"true" format:"email"`
+ } `json:"body"`
+}
+
+type ListMembersRequest struct {
+ ID int `param:"id"`
+ Page int `query:"page" default:"0"`
+ Size int `query:"size" default:"20"`
+}
+
+type ContactListWithCount struct {
+ models.ContactList
+ MemberCount int64 `json:"member_count"`
+}
+
+func (h *ContactListHandler) Create(c *okapi.Context, req *CreateContactListRequest) error {
+ userID := c.GetInt("user_id")
+ list := &models.ContactList{
+ UserID: uint(userID),
+ Name: req.Body.Name,
+ Description: req.Body.Description,
+ }
+ if err := h.repo.Create(list); err != nil {
+ return c.AbortInternalServerError("failed to create contact list")
+ }
+ return created(c, list)
+}
+
+func (h *ContactListHandler) List(c *okapi.Context, req *ListRequest) error {
+ userID := c.GetInt("user_id")
+ page, size, offset := normalizePageParams(req.Page, req.Size)
+ lists, total, err := h.repo.FindByUserID(uint(userID), size, offset)
+ if err != nil {
+ return c.AbortInternalServerError("failed to list contact lists")
+ }
+
+ // Add member counts
+ result := make([]ContactListWithCount, len(lists))
+ for i, l := range lists {
+ result[i] = ContactListWithCount{
+ ContactList: l,
+ MemberCount: h.repo.MemberCount(l.ID),
+ }
+ }
+
+ return paginated(c, result, total, page, size)
+}
+
+func (h *ContactListHandler) Update(c *okapi.Context, req *UpdateContactListRequest) error {
+ userID := c.GetInt("user_id")
+ list, err := h.repo.FindByID(uint(req.ID))
+ if err != nil || list.UserID != uint(userID) {
+ return c.AbortNotFound("contact list not found")
+ }
+ list.Name = req.Body.Name
+ list.Description = req.Body.Description
+ if err := h.repo.Update(list); err != nil {
+ return c.AbortInternalServerError("failed to update contact list")
+ }
+ return ok(c, list)
+}
+
+func (h *ContactListHandler) Delete(c *okapi.Context, req *GetByIDRequest) error {
+ userID := c.GetInt("user_id")
+ list, err := h.repo.FindByID(uint(req.ID))
+ if err != nil || list.UserID != uint(userID) {
+ return c.AbortNotFound("contact list not found")
+ }
+ if err := h.repo.Delete(list.ID); err != nil {
+ return c.AbortInternalServerError("failed to delete contact list")
+ }
+ return noContent(c)
+}
+
+func (h *ContactListHandler) AddMember(c *okapi.Context, req *AddMemberRequest) error {
+ userID := c.GetInt("user_id")
+ list, err := h.repo.FindByID(uint(req.ID))
+ if err != nil || list.UserID != uint(userID) {
+ return c.AbortNotFound("contact list not found")
+ }
+ member := &models.ContactListMember{
+ ListID: list.ID,
+ Email: req.Body.Email,
+ Name: req.Body.Name,
+ }
+ if err := h.repo.AddMember(member); err != nil {
+ return c.AbortConflict("member already exists in list")
+ }
+ return created(c, member)
+}
+
+func (h *ContactListHandler) RemoveMember(c *okapi.Context, req *RemoveMemberRequest) error {
+ userID := c.GetInt("user_id")
+ list, err := h.repo.FindByID(uint(req.ID))
+ if err != nil || list.UserID != uint(userID) {
+ return c.AbortNotFound("contact list not found")
+ }
+ if err := h.repo.RemoveMember(list.ID, req.Body.Email); err != nil {
+ return c.AbortInternalServerError("failed to remove member")
+ }
+ return noContent(c)
+}
+
+func (h *ContactListHandler) ListMembers(c *okapi.Context, req *ListMembersRequest) error {
+ userID := c.GetInt("user_id")
+ list, err := h.repo.FindByID(uint(req.ID))
+ if err != nil || list.UserID != uint(userID) {
+ return c.AbortNotFound("contact list not found")
+ }
+ page, size, offset := normalizePageParams(req.Page, req.Size)
+ members, total, err := h.repo.ListMembers(list.ID, size, offset)
+ if err != nil {
+ return c.AbortInternalServerError("failed to list members")
+ }
+ return paginated(c, members, total, page, size)
+}
diff --git a/internal/handlers/cron_handler.go b/internal/handlers/cron_handler.go
new file mode 100644
index 0000000..65331f3
--- /dev/null
+++ b/internal/handlers/cron_handler.go
@@ -0,0 +1,44 @@
+/*
+ * 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 (
+ "github.com/jkaninda/okapi"
+ "github.com/jkaninda/posta/internal/cron"
+)
+
+// CronHandler exposes cron job status to admin users.
+type CronHandler struct {
+ manager *cron.Manager
+}
+
+func NewCronHandler(manager *cron.Manager) *CronHandler {
+ return &CronHandler{manager: manager}
+}
+
+func (h *CronHandler) List(c *okapi.Context) error {
+ jobs := h.manager.Jobs()
+ return ok(c, jobs)
+}
diff --git a/internal/handlers/dashboard_handler.go b/internal/handlers/dashboard_handler.go
new file mode 100644
index 0000000..2e637a1
--- /dev/null
+++ b/internal/handlers/dashboard_handler.go
@@ -0,0 +1,162 @@
+/*
+ * 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 (
+ "time"
+
+ "github.com/jkaninda/okapi"
+ "github.com/jkaninda/posta/internal/models"
+ "github.com/jkaninda/posta/internal/services/cache"
+ "github.com/jkaninda/posta/internal/storage/repositories"
+ "gorm.io/gorm"
+)
+
+type DashboardHandler struct {
+ db *gorm.DB
+ cache *cache.Cache
+ whDeliveryRepo *repositories.WebhookDeliveryRepository
+}
+
+type DashboardStats struct {
+ TotalEmails int64 `json:"total_emails"`
+ QueuedEmails int64 `json:"queued_emails"`
+ ProcessingEmails int64 `json:"processing_emails"`
+ SentEmails int64 `json:"sent_emails"`
+ FailedEmails int64 `json:"failed_emails"`
+ SuppressedEmails int64 `json:"suppressed_emails"`
+ FailureRate float64 `json:"failure_rate"`
+ TotalDomains int64 `json:"total_domains"`
+ TotalSmtpServers int64 `json:"total_smtp_servers"`
+ TotalAPIKeys int64 `json:"total_api_keys"`
+ ActiveAPIKeys int64 `json:"active_api_keys"`
+ TotalContacts int64 `json:"total_contacts"`
+ TotalBounces int64 `json:"total_bounces"`
+ TotalSuppressions int64 `json:"total_suppressions"`
+ TotalWebhooks int64 `json:"total_webhooks"`
+ TotalContactLists int64 `json:"total_contact_lists"`
+ DailyVolume []DailyVolume `json:"daily_volume"`
+
+ // Webhook delivery stats
+ WebhookDeliveries *repositories.WebhookDeliveryStats `json:"webhook_deliveries"`
+}
+
+type DailyVolume struct {
+ Date string `json:"date"`
+ Sent int64 `json:"sent"`
+ Failed int64 `json:"failed"`
+}
+
+func NewDashboardHandler(db *gorm.DB, c *cache.Cache, whDeliveryRepo *repositories.WebhookDeliveryRepository) *DashboardHandler {
+ return &DashboardHandler{db: db, cache: c, whDeliveryRepo: whDeliveryRepo}
+}
+
+func (h *DashboardHandler) Stats(c *okapi.Context) error {
+ userID := c.GetInt("user_id")
+ ctx := c.Request().Context()
+
+ // Try cache first
+ cacheKey := cache.DashboardKey(userID)
+ var stats DashboardStats
+ if h.cache.Get(ctx, cacheKey, &stats) {
+ return ok(c, stats)
+ }
+
+ // Email counts by status
+ h.db.Model(&models.Email{}).Where("user_id = ?", userID).Count(&stats.TotalEmails)
+ h.db.Model(&models.Email{}).Where("user_id = ? AND status = ?", userID, models.EmailStatusQueued).Count(&stats.QueuedEmails)
+ h.db.Model(&models.Email{}).Where("user_id = ? AND status = ?", userID, models.EmailStatusProcessing).Count(&stats.ProcessingEmails)
+ h.db.Model(&models.Email{}).Where("user_id = ? AND status = ?", userID, models.EmailStatusSent).Count(&stats.SentEmails)
+ h.db.Model(&models.Email{}).Where("user_id = ? AND status = ?", userID, models.EmailStatusFailed).Count(&stats.FailedEmails)
+ h.db.Model(&models.Email{}).Where("user_id = ? AND status = ?", userID, models.EmailStatusSuppressed).Count(&stats.SuppressedEmails)
+
+ // Infrastructure counts
+ h.db.Model(&models.Domain{}).Where("user_id = ?", userID).Count(&stats.TotalDomains)
+ h.db.Model(&models.SMTPServer{}).Where("user_id = ?", userID).Count(&stats.TotalSmtpServers)
+
+ // API keys
+ h.db.Model(&models.APIKey{}).Where("user_id = ?", userID).Count(&stats.TotalAPIKeys)
+ h.db.Model(&models.APIKey{}).Where("user_id = ? AND revoked = false AND (expires_at IS NULL OR expires_at > ?)", userID, time.Now()).Count(&stats.ActiveAPIKeys)
+
+ // Contacts & deliverability
+ h.db.Model(&models.Contact{}).Where("user_id = ?", userID).Count(&stats.TotalContacts)
+ h.db.Model(&models.Bounce{}).Where("user_id = ?", userID).Count(&stats.TotalBounces)
+ h.db.Model(&models.Suppression{}).Where("user_id = ?", userID).Count(&stats.TotalSuppressions)
+ h.db.Model(&models.Webhook{}).Where("user_id = ?", userID).Count(&stats.TotalWebhooks)
+ h.db.Model(&models.ContactList{}).Where("user_id = ?", userID).Count(&stats.TotalContactLists)
+
+ // Failure rate
+ if stats.TotalEmails > 0 {
+ stats.FailureRate = float64(stats.FailedEmails) / float64(stats.TotalEmails) * 100
+ }
+
+ // Webhook delivery stats
+ if whStats, err := h.whDeliveryRepo.StatsByUserID(uint(userID)); err == nil {
+ stats.WebhookDeliveries = whStats
+ }
+
+ // Daily send volume (last 14 days)
+ since := time.Now().AddDate(0, 0, -13).Truncate(24 * time.Hour)
+ type dailyRow struct {
+ Date string
+ Status string
+ Count int64
+ }
+ var rows []dailyRow
+ h.db.Model(&models.Email{}).
+ Select("TO_CHAR(created_at, 'YYYY-MM-DD') as date, status, COUNT(*) as count").
+ Where("user_id = ? AND created_at >= ? AND status IN ?", userID, since, []string{string(models.EmailStatusSent), string(models.EmailStatusFailed)}).
+ Group("date, status").
+ Order("date").
+ Find(&rows)
+
+ // Build a map for easy lookup and fill all 14 days
+ volumeMap := make(map[string]*DailyVolume)
+ for i := 0; i < 14; i++ {
+ d := since.AddDate(0, 0, i).Format("2006-01-02")
+ volumeMap[d] = &DailyVolume{Date: d}
+ }
+ for _, r := range rows {
+ v, ok := volumeMap[r.Date]
+ if !ok {
+ continue
+ }
+ if r.Status == string(models.EmailStatusSent) {
+ v.Sent = r.Count
+ } else if r.Status == string(models.EmailStatusFailed) {
+ v.Failed = r.Count
+ }
+ }
+ stats.DailyVolume = make([]DailyVolume, 0, 14)
+ for i := 0; i < 14; i++ {
+ d := since.AddDate(0, 0, i).Format("2006-01-02")
+ stats.DailyVolume = append(stats.DailyVolume, *volumeMap[d])
+ }
+
+ // Store in cache
+ h.cache.Set(ctx, cacheKey, stats, cache.DashboardStatsTTL)
+
+ return ok(c, stats)
+}
diff --git a/internal/handlers/domain_handler.go b/internal/handlers/domain_handler.go
new file mode 100644
index 0000000..5c4668c
--- /dev/null
+++ b/internal/handlers/domain_handler.go
@@ -0,0 +1,163 @@
+/*
+ * 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 (
+ "crypto/rand"
+ "encoding/hex"
+
+ "github.com/jkaninda/okapi"
+ "github.com/jkaninda/posta/internal/models"
+ "github.com/jkaninda/posta/internal/services/domain"
+ "github.com/jkaninda/posta/internal/storage/repositories"
+)
+
+type DomainHandler struct {
+ repo *repositories.DomainRepository
+}
+type CreateDomainRequest struct {
+ Body struct {
+ Domain string `json:"domain" required:"true"`
+ } `json:"body"`
+}
+type DomainWithRecords struct {
+ models.Domain
+ DNSRecords *domain.DNSRecords `json:"dns_records"`
+}
+type GetDomainRequest struct {
+ ID int `param:"id"`
+}
+type DeleteDomainRequest struct {
+ ID int `param:"id"`
+}
+type VerifyDomainRequest struct {
+ ID int `param:"id"`
+}
+
+func NewDomainHandler(repo *repositories.DomainRepository) *DomainHandler {
+ return &DomainHandler{repo: repo}
+}
+
+func (h *DomainHandler) Create(c *okapi.Context, req *CreateDomainRequest) error {
+ userID := c.GetInt("user_id")
+
+ token, err := generateVerificationToken()
+ if err != nil {
+ return c.AbortInternalServerError("failed to generate verification token")
+ }
+
+ d := &models.Domain{
+ UserID: uint(userID),
+ Domain: req.Body.Domain,
+ VerificationToken: token,
+ }
+
+ if err := h.repo.Create(d); err != nil {
+ return c.AbortConflict("domain already exists")
+ }
+
+ return created(c, DomainWithRecords{
+ Domain: *d,
+ DNSRecords: domain.RequiredRecords(d),
+ })
+}
+
+func (h *DomainHandler) List(c *okapi.Context, req *ListRequest) error {
+ userID := c.GetInt("user_id")
+ page, size, offset := normalizePageParams(req.Page, req.Size)
+
+ domains, total, err := h.repo.FindByUserID(uint(userID), size, offset)
+ if err != nil {
+ return c.AbortInternalServerError("failed to list domains")
+ }
+
+ return paginated(c, domains, total, page, size)
+}
+
+func (h *DomainHandler) Get(c *okapi.Context, req *GetDomainRequest) error {
+ userID := c.GetInt("user_id")
+
+ d, err := h.repo.FindByID(uint(req.ID))
+ if err != nil || d.UserID != uint(userID) {
+ return c.AbortNotFound("domain not found")
+ }
+
+ return ok(c, DomainWithRecords{
+ Domain: *d,
+ DNSRecords: domain.RequiredRecords(d),
+ })
+}
+
+func (h *DomainHandler) Delete(c *okapi.Context, req *DeleteDomainRequest) error {
+ userID := c.GetInt("user_id")
+
+ d, err := h.repo.FindByID(uint(req.ID))
+ if err != nil || d.UserID != uint(userID) {
+ return c.AbortNotFound("domain not found")
+ }
+
+ if err := h.repo.Delete(d.ID); err != nil {
+ return c.AbortInternalServerError("failed to delete domain")
+ }
+
+ return noContent(c)
+}
+
+func (h *DomainHandler) Verify(c *okapi.Context, req *VerifyDomainRequest) error {
+ userID := c.GetInt("user_id")
+
+ d, err := h.repo.FindByID(uint(req.ID))
+ if err != nil || d.UserID != uint(userID) {
+ return c.AbortNotFound("domain not found")
+ }
+
+ result, err := domain.Verify(d)
+ if err != nil {
+ return c.AbortInternalServerError("DNS verification failed")
+ }
+
+ d.OwnershipVerified = result.OwnershipVerified
+ d.SPFVerified = result.SPFVerified
+ d.DKIMVerified = result.DKIMVerified
+ d.DMARCVerified = result.DMARCVerified
+
+ if err := h.repo.Update(d); err != nil {
+ return c.AbortInternalServerError("failed to update domain")
+ }
+
+ return ok(c, okapi.M{
+ "domain": d,
+ "verification": result,
+ "fully_verified": d.IsFullyVerified(),
+ })
+}
+
+func generateVerificationToken() (string, error) {
+ b := make([]byte, 16)
+ if _, err := rand.Read(b); err != nil {
+ return "", err
+ }
+ return hex.EncodeToString(b), nil
+}
diff --git a/internal/handlers/email_handler.go b/internal/handlers/email_handler.go
new file mode 100644
index 0000000..504e938
--- /dev/null
+++ b/internal/handlers/email_handler.go
@@ -0,0 +1,278 @@
+/*
+ * 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"
+ "strings"
+
+ "github.com/jkaninda/okapi"
+ "github.com/jkaninda/posta/internal/models"
+ "github.com/jkaninda/posta/internal/services/cache"
+ "github.com/jkaninda/posta/internal/services/email"
+ "github.com/jkaninda/posta/internal/services/eventbus"
+ "github.com/jkaninda/posta/internal/storage/repositories"
+)
+
+type EmailHandler struct {
+ service *email.Service
+ emailRepo *repositories.EmailRepository
+ bus *eventbus.EventBus
+ cache *cache.Cache
+}
+type SendEmailRequest struct {
+ Body email.SendRequest `json:"body"`
+}
+type SendTemplateEmailRequest struct {
+ Body email.SendTemplateRequest `json:"body"`
+}
+type SendBatchEmailRequest struct {
+ Body email.BatchRequest `json:"body"`
+}
+type ListRequest struct {
+ Page int `query:"page" default:"0"`
+ Size int `query:"size" default:"20"`
+}
+type GetByIDRequest struct {
+ ID int `param:"id"`
+}
+type GetEmailRequest struct {
+ ID string `param:"id"`
+}
+
+func NewEmailHandler(service *email.Service, emailRepo *repositories.EmailRepository, bus *eventbus.EventBus, c *cache.Cache) *EmailHandler {
+ return &EmailHandler{
+ service: service,
+ emailRepo: emailRepo,
+ bus: bus,
+ cache: c,
+ }
+}
+
+func (h *EmailHandler) Send(c *okapi.Context, req *SendEmailRequest) error {
+ userID := c.GetInt("user_id")
+ apiKeyID := c.GetInt("api_key_id")
+ userEmail := c.GetString("user_email")
+
+ resp, err := h.service.Send(c.Request().Context(), uint(userID), uint(apiKeyID), userEmail, &req.Body)
+ if err != nil {
+ if isRateLimitError(err) {
+ return c.AbortTooManyRequests(err.Error())
+ }
+ if isDomainVerificationError(err) {
+ return c.AbortForbidden(err.Error())
+ }
+ return c.AbortInternalServerError(err.Error())
+ }
+
+ // Invalidate dashboard and metrics caches after queuing
+ h.cache.InvalidateUser(c.Request().Context(), userID)
+ h.cache.InvalidateAnalytics(c.Request().Context())
+
+ if h.bus != nil {
+ uid := uint(userID)
+ h.bus.PublishSimple(models.EventCategoryEmail, "email.queued", &uid, userEmail, c.RealIP(),
+ fmt.Sprintf("Email queued to %v", req.Body.To), map[string]any{"email_uuid": resp.ID})
+ }
+
+ return ok(c, resp)
+}
+
+func (h *EmailHandler) SendWithTemplate(c *okapi.Context, req *SendTemplateEmailRequest) error {
+ userID := c.GetInt("user_id")
+ apiKeyID := c.GetInt("api_key_id")
+ userEmail := c.GetString("user_email")
+
+ resp, err := h.service.SendWithTemplate(c.Request().Context(), uint(userID), uint(apiKeyID), userEmail, &req.Body)
+ if err != nil {
+ if isRateLimitError(err) {
+ return c.AbortTooManyRequests(err.Error())
+ }
+ if isDomainVerificationError(err) {
+ return c.AbortForbidden(err.Error())
+ }
+ return c.AbortInternalServerError(err.Error())
+ }
+
+ h.cache.InvalidateUser(c.Request().Context(), userID)
+ h.cache.InvalidateAnalytics(c.Request().Context())
+
+ if h.bus != nil {
+ uid := uint(userID)
+ h.bus.PublishSimple(models.EventCategoryEmail, "email.queued", &uid, userEmail, c.RealIP(),
+ fmt.Sprintf("Template email queued to %v", req.Body.To), map[string]any{"email_uuid": resp.ID, "template": req.Body.Template})
+ }
+
+ return ok(c, resp)
+}
+
+func (h *EmailHandler) SendBatch(c *okapi.Context, req *SendBatchEmailRequest) error {
+ userID := c.GetInt("user_id")
+ apiKeyID := c.GetInt("api_key_id")
+ userEmail := c.GetString("user_email")
+
+ resp, err := h.service.SendBatch(c.Request().Context(), uint(userID), uint(apiKeyID), userEmail, &req.Body)
+ if err != nil {
+ if isRateLimitError(err) {
+ return c.AbortTooManyRequests(err.Error())
+ }
+ if isDomainVerificationError(err) {
+ return c.AbortForbidden(err.Error())
+ }
+ return c.AbortInternalServerError(err.Error())
+ }
+
+ h.cache.InvalidateUser(c.Request().Context(), userID)
+ h.cache.InvalidateAnalytics(c.Request().Context())
+
+ if h.bus != nil {
+ uid := uint(userID)
+ h.bus.PublishSimple(models.EventCategoryEmail, "email.batch_queued", &uid, userEmail, c.RealIP(),
+ fmt.Sprintf("Batch of %d emails queued", len(resp.Results)), map[string]any{"count": len(resp.Results)})
+ }
+
+ return ok(c, resp)
+}
+
+func normalizePageParams(page, size int) (int, int, int) {
+ if size <= 0 || size > 100 {
+ size = 20
+ }
+ if page < 0 {
+ page = 0
+ }
+ offset := page * size
+ return page, size, offset
+}
+
+func (h *EmailHandler) List(c *okapi.Context, req *ListRequest) error {
+ userID := c.GetInt("user_id")
+ page, size, offset := normalizePageParams(req.Page, req.Size)
+
+ emails, total, err := h.emailRepo.FindByUserID(uint(userID), size, offset)
+ if err != nil {
+ return c.AbortInternalServerError("failed to list emails")
+ }
+
+ return paginated(c, emails, total, page, size)
+}
+
+func (h *EmailHandler) Get(c *okapi.Context, req *GetEmailRequest) error {
+ em, err := h.emailRepo.FindByUUID(req.ID)
+ if err != nil {
+ return c.AbortNotFound("email not found")
+ }
+
+ userID := c.GetInt("user_id")
+ if em.UserID != uint(userID) {
+ return c.AbortNotFound("email not found")
+ }
+
+ return ok(c, em)
+}
+
+// EmailStatusResponse is a lightweight view of an email's delivery status.
+type EmailStatusResponse struct {
+ ID string `json:"id"`
+ Status models.EmailStatus `json:"status"`
+ ErrorMessage string `json:"error_message,omitempty"`
+ RetryCount int `json:"retry_count"`
+ CreatedAt string `json:"created_at"`
+ SentAt *string `json:"sent_at,omitempty"`
+}
+
+// GetStatus returns only the delivery status of an email (owner only).
+func (h *EmailHandler) GetStatus(c *okapi.Context, req *GetEmailRequest) error {
+ em, err := h.emailRepo.FindByUUID(req.ID)
+ if err != nil {
+ return c.AbortNotFound("email not found")
+ }
+
+ userID := c.GetInt("user_id")
+ if em.UserID != uint(userID) {
+ return c.AbortNotFound("email not found")
+ }
+
+ resp := EmailStatusResponse{
+ ID: em.UUID,
+ Status: em.Status,
+ ErrorMessage: em.ErrorMessage,
+ RetryCount: em.RetryCount,
+ CreatedAt: em.CreatedAt.Format("2006-01-02T15:04:05Z07:00"),
+ }
+ if em.SentAt != nil {
+ s := em.SentAt.Format("2006-01-02T15:04:05Z07:00")
+ resp.SentAt = &s
+ }
+
+ return ok(c, resp)
+}
+
+// Retry re-enqueues a failed email for another delivery attempt.
+func (h *EmailHandler) Retry(c *okapi.Context, req *GetEmailRequest) error {
+ userID := c.GetInt("user_id")
+ resp, err := h.service.RetryEmail(req.ID, uint(userID))
+ if err != nil {
+ if err.Error() == "email not found" {
+ return c.AbortNotFound(err.Error())
+ }
+ return c.AbortBadRequest(err.Error())
+ }
+ return ok(c, resp)
+}
+
+// Dev mode handlers
+func (h *EmailHandler) DevList(c *okapi.Context, req *ListRequest) error {
+ page, size, offset := normalizePageParams(req.Page, req.Size)
+
+ emails, total, err := h.emailRepo.FindAll(size, offset)
+ if err != nil {
+ return c.AbortInternalServerError("failed to list emails")
+ }
+
+ return paginated(c, emails, total, page, size)
+}
+
+func (h *EmailHandler) DevGet(c *okapi.Context) error {
+ uuid := c.PathParam("id")
+ if uuid == "" {
+ return c.AbortBadRequest("invalid email id")
+ }
+
+ em, err := h.emailRepo.FindByUUID(uuid)
+ if err != nil {
+ return c.AbortNotFound("email not found")
+ }
+
+ return ok(c, em)
+}
+
+func isRateLimitError(err error) bool {
+ return err != nil && len(err.Error()) > 11 && err.Error()[:11] == "rate_limit:"
+}
+
+func isDomainVerificationError(err error) bool {
+ return err != nil && strings.HasPrefix(err.Error(), "domain_verification:")
+}
diff --git a/internal/handlers/event_handler.go b/internal/handlers/event_handler.go
new file mode 100644
index 0000000..ffacb70
--- /dev/null
+++ b/internal/handlers/event_handler.go
@@ -0,0 +1,115 @@
+/*
+ * 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 (
+ "time"
+
+ "github.com/jkaninda/okapi"
+ "github.com/jkaninda/posta/internal/models"
+ "github.com/jkaninda/posta/internal/services/eventbus"
+ "github.com/jkaninda/posta/internal/storage/repositories"
+)
+
+type EventHandler struct {
+ repo *repositories.EventRepository
+ bus *eventbus.EventBus
+}
+
+type ListEventsRequest struct {
+ Page int `query:"page" default:"0"`
+ Size int `query:"size" default:"20"`
+ Category string `query:"category"`
+}
+
+func NewEventHandler(repo *repositories.EventRepository, bus *eventbus.EventBus) *EventHandler {
+ return &EventHandler{repo: repo, bus: bus}
+}
+
+// List returns paginated historical events.
+func (h *EventHandler) List(c *okapi.Context, req *ListEventsRequest) error {
+ page, size, offset := normalizePageParams(req.Page, req.Size)
+
+ var events []models.Event
+ var total int64
+ var err error
+
+ if req.Category != "" {
+ events, total, err = h.repo.FindByCategory(models.EventCategory(req.Category), size, offset)
+ } else {
+ events, total, err = h.repo.FindAll(size, offset)
+ }
+ if err != nil {
+ return c.AbortInternalServerError("failed to list events")
+ }
+
+ return paginated(c, events, total, page, size)
+}
+
+// UserAuditLog returns paginated audit events for the authenticated user.
+func (h *EventHandler) UserAuditLog(c *okapi.Context, req *ListEventsRequest) error {
+ userID := c.GetInt("user_id")
+ page, size, offset := normalizePageParams(req.Page, req.Size)
+
+ events, total, err := h.repo.FindByActorAndCategory(uint(userID), models.EventCategoryAudit, size, offset)
+ if err != nil {
+ return c.AbortInternalServerError("failed to list audit events")
+ }
+
+ return paginated(c, events, total, page, size)
+}
+
+// Stream sends real-time events to the admin via SSE.
+func (h *EventHandler) Stream(c *okapi.Context) error {
+ ctx := c.Request().Context()
+
+ ch, unsub := h.bus.Subscribe()
+ defer unsub()
+
+ msgCh := make(chan okapi.Message)
+ go func() {
+ defer close(msgCh)
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case evt, ok := <-ch:
+ if !ok {
+ return
+ }
+ select {
+ case msgCh <- okapi.Message{Event: evt.Type, Data: evt}:
+ case <-ctx.Done():
+ return
+ }
+ }
+ }
+ }()
+
+ return c.SSEStreamWithOptions(ctx, msgCh, &okapi.StreamOptions{
+ Serializer: &okapi.JSONSerializer{},
+ PingInterval: 30 * time.Second,
+ })
+}
diff --git a/internal/handlers/health_handler.go b/internal/handlers/health_handler.go
new file mode 100644
index 0000000..b2b73c4
--- /dev/null
+++ b/internal/handlers/health_handler.go
@@ -0,0 +1,94 @@
+/*
+ * 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 (
+ "context"
+ "time"
+
+ "github.com/jkaninda/okapi"
+ "github.com/redis/go-redis/v9"
+ "gorm.io/gorm"
+)
+
+const statusNotReady = "not ready"
+
+type HealthHandler struct {
+ db *gorm.DB
+ redis *redis.Client
+}
+
+func NewHealthHandler(db *gorm.DB, redis *redis.Client) *HealthHandler {
+ return &HealthHandler{db: db, redis: redis}
+}
+
+type HealthResponse struct {
+ Status string `json:"status" example:"ok"`
+}
+
+type ReadyResponse struct {
+ Status string `json:"status" example:"ready"`
+ Database string `json:"database" example:"ok"`
+ Redis string `json:"redis" example:"ok"`
+}
+
+// Healthz is a lightweight liveness probe.
+func (h *HealthHandler) Healthz(c *okapi.Context) error {
+ return c.OK(HealthResponse{Status: "ok"})
+}
+
+// Readyz checks that all dependencies are reachable.
+func (h *HealthHandler) Readyz(c *okapi.Context) error {
+ resp := ReadyResponse{
+ Status: "ready",
+ Database: "ok",
+ Redis: "ok",
+ }
+
+ sqlDB, err := h.db.DB()
+ if err != nil {
+ resp.Status = statusNotReady
+ resp.Database = err.Error()
+ } else {
+ ctx, cancel := context.WithTimeout(c.Request().Context(), 2*time.Second)
+ defer cancel()
+ if err := sqlDB.PingContext(ctx); err != nil {
+ resp.Status = statusNotReady
+ resp.Database = err.Error()
+ }
+ }
+
+ ctx, cancel := context.WithTimeout(c.Request().Context(), 2*time.Second)
+ defer cancel()
+ if err := h.redis.Ping(ctx).Err(); err != nil {
+ resp.Status = statusNotReady
+ resp.Redis = err.Error()
+ }
+
+ if resp.Status != "ready" {
+ return c.JSON(503, resp)
+ }
+ return c.OK(resp)
+}
diff --git a/internal/handlers/helper.go b/internal/handlers/helper.go
new file mode 100644
index 0000000..4f8d2f7
--- /dev/null
+++ b/internal/handlers/helper.go
@@ -0,0 +1,70 @@
+/*
+ * 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 (
+ "net/http"
+
+ "github.com/jkaninda/okapi"
+ "github.com/jkaninda/posta/internal/dto"
+)
+
+func ok[T any](c *okapi.Context, data T) error {
+ return c.JSON(http.StatusOK, dto.Response[T]{
+ Success: true,
+ Data: data,
+ })
+}
+
+func created[T any](c *okapi.Context, data T) error {
+ return c.JSON(http.StatusCreated, dto.Response[T]{
+ Success: true,
+ Data: data,
+ })
+}
+
+func noContent(c *okapi.Context) error {
+ return c.JSON(http.StatusNoContent, dto.Response[any]{
+ Success: true,
+ })
+}
+
+func paginated[T any](c *okapi.Context, items []T, total int64, page, size int) error {
+ totalPages := 0
+ if size > 0 {
+ totalPages = int((total + int64(size) - 1) / int64(size))
+ }
+ return c.JSON(http.StatusOK, dto.PageableResponse[T]{
+ Success: true,
+ Data: items,
+ Pageable: dto.Pageable{
+ CurrentPage: page,
+ Size: size,
+ TotalPages: totalPages,
+ TotalElements: total,
+ Empty: len(items) == 0,
+ },
+ })
+}
diff --git a/internal/handlers/info_handler.go b/internal/handlers/info_handler.go
new file mode 100644
index 0000000..148745f
--- /dev/null
+++ b/internal/handlers/info_handler.go
@@ -0,0 +1,47 @@
+/*
+ * 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 (
+ "github.com/jkaninda/okapi"
+ "github.com/jkaninda/posta/internal/config"
+)
+
+type AppInfo struct {
+ Name string `json:"name" example:"Posta"`
+ Version string `json:"version" example:"v1.0.0"`
+ CommitID string `json:"commit_id" example:"abc1234"`
+ OpenAPIDocs bool `json:"openapi_docs" example:"true"`
+}
+
+func Info(c *okapi.Context) error {
+ cfg := config.New()
+ return ok(c, AppInfo{
+ Name: "Posta",
+ Version: config.Version,
+ CommitID: config.CommitID,
+ OpenAPIDocs: cfg.OpenAPIDocs,
+ })
+}
diff --git a/internal/handlers/language_handler.go b/internal/handlers/language_handler.go
new file mode 100644
index 0000000..7990d3b
--- /dev/null
+++ b/internal/handlers/language_handler.go
@@ -0,0 +1,120 @@
+/*
+ * 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 (
+ "github.com/jkaninda/okapi"
+ "github.com/jkaninda/posta/internal/models"
+ "github.com/jkaninda/posta/internal/storage/repositories"
+)
+
+type LanguageHandler struct {
+ repo *repositories.LanguageRepository
+}
+type CreateLanguageRequest struct {
+ Body struct {
+ Code string `json:"code" required:"true"`
+ Name string `json:"name" required:"true"`
+ } `json:"body"`
+}
+type UpdateLanguageRequest struct {
+ ID int `param:"id"`
+ Body struct {
+ Code string `json:"code"`
+ Name string `json:"name"`
+ } `json:"body"`
+}
+type DeleteLanguageRequest struct {
+ ID int `param:"id"`
+}
+
+func NewLanguageHandler(repo *repositories.LanguageRepository) *LanguageHandler {
+ return &LanguageHandler{repo: repo}
+}
+
+func (h *LanguageHandler) Create(c *okapi.Context, req *CreateLanguageRequest) error {
+ userID := c.GetInt("user_id")
+
+ l := &models.Language{
+ UserID: uint(userID),
+ Code: req.Body.Code,
+ Name: req.Body.Name,
+ }
+
+ if err := h.repo.Create(l); err != nil {
+ return c.AbortConflict("language code already exists")
+ }
+
+ return created(c, l)
+}
+
+func (h *LanguageHandler) Update(c *okapi.Context, req *UpdateLanguageRequest) error {
+ userID := c.GetInt("user_id")
+
+ l, err := h.repo.FindByID(uint(req.ID))
+ if err != nil || l.UserID != uint(userID) {
+ return c.AbortNotFound("language not found")
+ }
+
+ if req.Body.Code != "" {
+ l.Code = req.Body.Code
+ }
+ if req.Body.Name != "" {
+ l.Name = req.Body.Name
+ }
+
+ if err := h.repo.Update(l); err != nil {
+ return c.AbortInternalServerError("failed to update language")
+ }
+
+ return ok(c, l)
+}
+
+func (h *LanguageHandler) Delete(c *okapi.Context, req *DeleteLanguageRequest) error {
+ userID := c.GetInt("user_id")
+
+ l, err := h.repo.FindByID(uint(req.ID))
+ if err != nil || l.UserID != uint(userID) {
+ return c.AbortNotFound("language not found")
+ }
+
+ if err := h.repo.Delete(l.ID); err != nil {
+ return c.AbortInternalServerError("failed to delete language")
+ }
+
+ return noContent(c)
+}
+
+func (h *LanguageHandler) List(c *okapi.Context, req *ListRequest) error {
+ userID := c.GetInt("user_id")
+ page, size, offset := normalizePageParams(req.Page, req.Size)
+
+ languages, total, err := h.repo.FindByUserID(uint(userID), size, offset)
+ if err != nil {
+ return c.AbortInternalServerError("failed to list languages")
+ }
+
+ return paginated(c, languages, total, page, size)
+}
diff --git a/internal/handlers/server_handler.go b/internal/handlers/server_handler.go
new file mode 100644
index 0000000..22777d7
--- /dev/null
+++ b/internal/handlers/server_handler.go
@@ -0,0 +1,339 @@
+/*
+ * 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 (
+ "net/http"
+ "time"
+
+ "github.com/jkaninda/okapi"
+ "github.com/jkaninda/posta/internal/dto"
+ "github.com/jkaninda/posta/internal/models"
+ "github.com/jkaninda/posta/internal/services/audit"
+ "github.com/jkaninda/posta/internal/services/email"
+ "github.com/jkaninda/posta/internal/storage/repositories"
+)
+
+// ServerHandler handles admin management of shared SMTP servers.
+type ServerHandler struct {
+ repo *repositories.ServerRepository
+ sender *email.SMTPSender
+ audit *audit.Logger
+}
+
+func NewServerHandler(repo *repositories.ServerRepository, audit *audit.Logger) *ServerHandler {
+ return &ServerHandler{repo: repo, sender: email.NewSMTPSender(), audit: audit}
+}
+
+// --- Request types ---
+
+type CreateServerRequest struct {
+ Body struct {
+ Name string `json:"name" required:"true"`
+ Host string `json:"host" required:"true"`
+ Port int `json:"port" required:"true"`
+ Username string `json:"username"`
+ Password string `json:"password"`
+ Encryption string `json:"encryption"`
+ MaxRetries int `json:"max_retries"`
+ AllowedDomains []string `json:"allowed_domains"`
+ SecurityMode string `json:"security_mode" enum:"permissive,strict"`
+ } `json:"body"`
+}
+
+type UpdateServerRequest struct {
+ ID int `param:"id"`
+ Body struct {
+ Name string `json:"name"`
+ Host string `json:"host"`
+ Port int `json:"port"`
+ Username string `json:"username"`
+ Password string `json:"password"`
+ Encryption string `json:"encryption"`
+ MaxRetries *int `json:"max_retries"`
+ Status string `json:"status"`
+ AllowedDomains []string `json:"allowed_domains"`
+ SecurityMode string `json:"security_mode" enum:"permissive,strict"`
+ } `json:"body"`
+}
+
+type DeleteServerRequest struct {
+ ID int `param:"id"`
+}
+
+type ServerIDRequest struct {
+ ID int `param:"id"`
+}
+
+// --- Handlers ---
+
+func (h *ServerHandler) Create(c *okapi.Context, req *CreateServerRequest) error {
+ userID := uint(c.GetInt("user_id"))
+
+ encryption := req.Body.Encryption
+ if encryption == "" {
+ encryption = models.EncryptionNone
+ }
+
+ securityMode := req.Body.SecurityMode
+ if securityMode != models.ServerSecurityModeStrict {
+ securityMode = models.ServerSecurityModePermissive
+ }
+
+ server := &models.Server{
+ Name: req.Body.Name,
+ Host: req.Body.Host,
+ Port: req.Body.Port,
+ Username: req.Body.Username,
+ Password: req.Body.Password,
+ Encryption: encryption,
+ MaxRetries: req.Body.MaxRetries,
+ AllowedDomains: req.Body.AllowedDomains,
+ SecurityMode: securityMode,
+ }
+
+ // Validate SMTP connection before saving
+ now := time.Now()
+ server.ValidatedAt = &now
+ smtpTest := server.ToSMTPServer()
+ smtpTest.Password = server.Password // ensure raw password is used for test
+ if err := h.sender.TestConnection(smtpTest); err != nil {
+ server.Status = models.SMTPStatusInvalid
+ server.ValidationError = err.Error()
+ } else {
+ server.Status = models.SMTPStatusEnabled
+ server.ValidationError = ""
+ }
+
+ if err := h.repo.Create(server); err != nil {
+ return c.AbortInternalServerError("failed to create server", err)
+ }
+
+ h.audit.Log(userID, c.GetString("email"), c.RealIP(), "server.created", "Shared SMTP server created: "+req.Body.Host, nil)
+
+ return created(c, server)
+}
+
+func (h *ServerHandler) Get(c *okapi.Context, req *ServerIDRequest) error {
+ server, err := h.repo.FindByID(uint(req.ID))
+ if err != nil {
+ return c.AbortNotFound("server not found")
+ }
+ return ok(c, server)
+}
+
+func (h *ServerHandler) List(c *okapi.Context, req *ListRequest) error {
+ page, size, offset := normalizePageParams(req.Page, req.Size)
+
+ servers, total, err := h.repo.FindAll(size, offset)
+ if err != nil {
+ return c.AbortInternalServerError("failed to list servers")
+ }
+
+ return paginated(c, servers, total, page, size)
+}
+
+func (h *ServerHandler) Update(c *okapi.Context, req *UpdateServerRequest) error {
+ userID := uint(c.GetInt("user_id"))
+
+ server, err := h.repo.FindByID(uint(req.ID))
+ if err != nil {
+ return c.AbortNotFound("server not found")
+ }
+
+ connectionChanged := false
+
+ if req.Body.Name != "" {
+ server.Name = req.Body.Name
+ }
+ if req.Body.Host != "" && req.Body.Host != server.Host {
+ server.Host = req.Body.Host
+ connectionChanged = true
+ }
+ if req.Body.Port != 0 && req.Body.Port != server.Port {
+ server.Port = req.Body.Port
+ connectionChanged = true
+ }
+ if req.Body.Username != "" && req.Body.Username != server.Username {
+ server.Username = req.Body.Username
+ connectionChanged = true
+ }
+ if req.Body.Password != "" {
+ server.Password = req.Body.Password
+ connectionChanged = true
+ }
+ if req.Body.Encryption != "" && req.Body.Encryption != server.Encryption {
+ server.Encryption = req.Body.Encryption
+ connectionChanged = true
+ }
+ if req.Body.MaxRetries != nil {
+ server.MaxRetries = *req.Body.MaxRetries
+ }
+ if req.Body.AllowedDomains != nil {
+ server.AllowedDomains = req.Body.AllowedDomains
+ }
+ switch req.Body.SecurityMode {
+ case models.ServerSecurityModeStrict:
+ server.SecurityMode = models.ServerSecurityModeStrict
+ case models.ServerSecurityModePermissive:
+ server.SecurityMode = models.ServerSecurityModePermissive
+ }
+
+ // Handle status changes
+ if req.Body.Status != "" {
+ switch req.Body.Status {
+ case models.SMTPStatusDisabled:
+ server.Status = models.SMTPStatusDisabled
+ server.ValidationError = ""
+ case models.SMTPStatusEnabled:
+ // Re-validate before enabling
+ now := time.Now()
+ server.ValidatedAt = &now
+ if err := h.sender.TestConnection(server.ToSMTPServer()); err != nil {
+ server.Status = models.SMTPStatusInvalid
+ server.ValidationError = err.Error()
+ } else {
+ server.Status = models.SMTPStatusEnabled
+ server.ValidationError = ""
+ }
+ }
+ } else if connectionChanged {
+ // Connection fields changed — re-validate automatically
+ now := time.Now()
+ server.ValidatedAt = &now
+ if err := h.sender.TestConnection(server.ToSMTPServer()); err != nil {
+ server.Status = models.SMTPStatusInvalid
+ server.ValidationError = err.Error()
+ } else {
+ server.Status = models.SMTPStatusEnabled
+ server.ValidationError = ""
+ }
+ }
+
+ if err := h.repo.Update(server); err != nil {
+ return c.AbortInternalServerError("failed to update server")
+ }
+
+ h.audit.Log(userID, c.GetString("email"), c.RealIP(), "server.updated", "Shared SMTP server updated: "+server.Host, nil)
+
+ return ok(c, server)
+}
+
+func (h *ServerHandler) Delete(c *okapi.Context, req *DeleteServerRequest) error {
+ userID := uint(c.GetInt("user_id"))
+
+ server, err := h.repo.FindByID(uint(req.ID))
+ if err != nil {
+ return c.AbortNotFound("server not found")
+ }
+
+ if err := h.repo.Delete(server.ID); err != nil {
+ return c.AbortInternalServerError("failed to delete server")
+ }
+
+ h.audit.Log(userID, c.GetString("email"), c.RealIP(), "server.deleted", "Shared SMTP server deleted: "+server.Host, nil)
+
+ return noContent(c)
+}
+
+func (h *ServerHandler) Enable(c *okapi.Context, req *ServerIDRequest) error {
+ userID := uint(c.GetInt("user_id"))
+
+ server, err := h.repo.FindByID(uint(req.ID))
+ if err != nil {
+ return c.AbortNotFound("server not found")
+ }
+
+ // Re-validate before enabling
+ now := time.Now()
+ if err := h.sender.TestConnection(server.ToSMTPServer()); err != nil {
+ _ = h.repo.SetStatus(server.ID, models.SMTPStatusInvalid, err.Error())
+ server.Status = models.SMTPStatusInvalid
+ server.ValidationError = err.Error()
+ server.ValidatedAt = &now
+ return ok(c, server)
+ }
+
+ _ = h.repo.SetStatus(server.ID, models.SMTPStatusEnabled, "")
+ h.audit.Log(userID, c.GetString("email"), c.RealIP(), "server.enabled", "Shared SMTP server enabled: "+server.Host, nil)
+
+ server.Status = models.SMTPStatusEnabled
+ server.ValidationError = ""
+ server.ValidatedAt = &now
+ return ok(c, server)
+}
+
+func (h *ServerHandler) Disable(c *okapi.Context, req *ServerIDRequest) error {
+ userID := uint(c.GetInt("user_id"))
+
+ server, err := h.repo.FindByID(uint(req.ID))
+ if err != nil {
+ return c.AbortNotFound("server not found")
+ }
+
+ if err := h.repo.SetStatus(server.ID, models.SMTPStatusDisabled, ""); err != nil {
+ return c.AbortInternalServerError("failed to disable server")
+ }
+
+ h.audit.Log(userID, c.GetString("email"), c.RealIP(), "server.disabled", "Shared SMTP server disabled: "+server.Host, nil)
+
+ server.Status = models.SMTPStatusDisabled
+ server.ValidationError = ""
+ return ok(c, server)
+}
+
+func (h *ServerHandler) Test(c *okapi.Context, req *ServerIDRequest) error {
+ server, err := h.repo.FindByID(uint(req.ID))
+ if err != nil {
+ return c.AbortNotFound("server not found")
+ }
+
+ now := time.Now()
+ if err := h.sender.TestConnection(server.ToSMTPServer()); err != nil {
+ _ = h.repo.SetStatus(server.ID, models.SMTPStatusInvalid, err.Error())
+ return c.JSON(http.StatusOK, dto.Response[okapi.M]{
+ Success: false,
+ Data: okapi.M{
+ "message": err.Error(),
+ "status": models.SMTPStatusInvalid,
+ "validated_at": now,
+ },
+ })
+ }
+
+ // Only set to enabled if not manually disabled
+ if server.Status != models.SMTPStatusDisabled {
+ _ = h.repo.SetStatus(server.ID, models.SMTPStatusEnabled, "")
+ } else {
+ // Still clear validation error even if disabled
+ _ = h.repo.SetStatus(server.ID, models.SMTPStatusDisabled, "")
+ }
+
+ return ok(c, okapi.M{
+ "message": "connection successful",
+ "status": server.Status,
+ "validated_at": now,
+ })
+}
diff --git a/internal/handlers/setting_handler.go b/internal/handlers/setting_handler.go
new file mode 100644
index 0000000..fe92dbf
--- /dev/null
+++ b/internal/handlers/setting_handler.go
@@ -0,0 +1,95 @@
+/*
+ * 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 (
+ "github.com/jkaninda/okapi"
+ "github.com/jkaninda/posta/internal/models"
+ "github.com/jkaninda/posta/internal/services/audit"
+ "github.com/jkaninda/posta/internal/storage/repositories"
+)
+
+// SettingHandler handles admin management of platform settings.
+type SettingHandler struct {
+ repo *repositories.SettingRepository
+ audit *audit.Logger
+}
+
+func NewSettingHandler(repo *repositories.SettingRepository, audit *audit.Logger) *SettingHandler {
+ return &SettingHandler{repo: repo, audit: audit}
+}
+
+// --- Request types ---
+
+type UpdateSettingsRequest struct {
+ Body struct {
+ Settings []SettingInput `json:"settings" required:"true"`
+ } `json:"body"`
+}
+
+type SettingInput struct {
+ Key string `json:"key"`
+ Value string `json:"value"`
+ Type string `json:"type"`
+}
+
+// --- Handlers ---
+
+func (h *SettingHandler) GetSettings(c *okapi.Context) error {
+ settings, err := h.repo.FindAll()
+ if err != nil {
+ return c.AbortInternalServerError("failed to load settings", err)
+ }
+ return ok(c, settings)
+}
+
+func (h *SettingHandler) UpdateSettings(c *okapi.Context, req *UpdateSettingsRequest) error {
+ userID := uint(c.GetInt("user_id"))
+
+ settings := make([]models.Setting, 0, len(req.Body.Settings))
+ for _, s := range req.Body.Settings {
+ typ := s.Type
+ if typ == "" {
+ typ = "string"
+ }
+ settings = append(settings, models.Setting{
+ Key: s.Key,
+ Value: s.Value,
+ Type: typ,
+ })
+ }
+
+ if err := h.repo.BulkUpsert(settings); err != nil {
+ return c.AbortInternalServerError("failed to update settings", err)
+ }
+
+ h.audit.Log(userID, c.GetString("email"), c.RealIP(), "settings.updated", "Platform settings updated", nil)
+
+ updated, err := h.repo.FindAll()
+ if err != nil {
+ return c.AbortInternalServerError("failed to load settings", err)
+ }
+ return ok(c, updated)
+}
diff --git a/internal/handlers/smtp_handler.go b/internal/handlers/smtp_handler.go
new file mode 100644
index 0000000..0d8e07e
--- /dev/null
+++ b/internal/handlers/smtp_handler.go
@@ -0,0 +1,310 @@
+/*
+ * 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"
+ "strings"
+ "time"
+
+ "github.com/jkaninda/okapi"
+ "github.com/jkaninda/posta/internal/models"
+ "github.com/jkaninda/posta/internal/services/audit"
+ "github.com/jkaninda/posta/internal/services/email"
+ "github.com/jkaninda/posta/internal/storage/repositories"
+)
+
+type SMTPHandler struct {
+ repo *repositories.SMTPRepository
+ domainRepo *repositories.DomainRepository
+ sender *email.SMTPSender
+ audit *audit.Logger
+}
+type CreateSMTPRequest struct {
+ Body struct {
+ Host string `json:"host" required:"true"`
+ Port int `json:"port" required:"true"`
+ Username string `json:"username"`
+ Password string `json:"password"`
+ Encryption string `json:"encryption"`
+ MaxRetries int `json:"max_retries"`
+ AllowedEmails []string `json:"allowed_emails"`
+ } `json:"body"`
+}
+type UpdateSMTPRequest struct {
+ ID int `param:"id"`
+ Body struct {
+ Host string `json:"host"`
+ Port int `json:"port"`
+ Username string `json:"username"`
+ Password string `json:"password"`
+ Encryption string `json:"encryption"`
+ MaxRetries *int `json:"max_retries"`
+ AllowedEmails []string `json:"allowed_emails"`
+ Status string `json:"status"`
+ } `json:"body"`
+}
+type GetSMTPRequest struct {
+ ID int `param:"id"`
+}
+type DeleteSMTPRequest struct {
+ ID int `param:"id"`
+}
+type TestSMTPRequest struct {
+ ID int `param:"id"`
+}
+
+func NewSMTPHandler(repo *repositories.SMTPRepository, domainRepo *repositories.DomainRepository, audit *audit.Logger) *SMTPHandler {
+ return &SMTPHandler{repo: repo, domainRepo: domainRepo, sender: email.NewSMTPSender(), audit: audit}
+}
+
+// validateAllowedEmails checks that each allowed email's domain belongs to the user's domains.
+// If the user has no domains configured, all emails are allowed.
+func (h *SMTPHandler) validateAllowedEmails(userID uint, emails []string) error {
+ if len(emails) == 0 {
+ return nil
+ }
+
+ domains, _, err := h.domainRepo.FindByUserID(userID, 1000, 0)
+ if err != nil {
+ return fmt.Errorf("failed to load domains")
+ }
+
+ // If user has no domains, skip validation
+ if len(domains) == 0 {
+ return nil
+ }
+
+ domainSet := make(map[string]bool, len(domains))
+ for _, d := range domains {
+ domainSet[strings.ToLower(d.Domain)] = true
+ }
+
+ for _, addr := range emails {
+ parts := strings.SplitN(addr, "@", 2)
+ if len(parts) != 2 {
+ return fmt.Errorf("invalid email address: %s", addr)
+ }
+ domain := strings.ToLower(parts[1])
+ if !domainSet[domain] {
+ return fmt.Errorf("domain %q is not in your verified domains", domain)
+ }
+ }
+ return nil
+}
+
+func (h *SMTPHandler) Create(c *okapi.Context, req *CreateSMTPRequest) error {
+ userID := c.GetInt("user_id")
+
+ if err := h.validateAllowedEmails(uint(userID), req.Body.AllowedEmails); err != nil {
+ return c.AbortBadRequest(err.Error())
+ }
+
+ encryption := req.Body.Encryption
+ if encryption == "" {
+ encryption = models.EncryptionNone
+ }
+
+ server := &models.SMTPServer{
+ UserID: uint(userID),
+ Host: req.Body.Host,
+ Port: req.Body.Port,
+ Username: req.Body.Username,
+ Password: req.Body.Password,
+ Encryption: encryption,
+ MaxRetries: req.Body.MaxRetries,
+ AllowedEmails: req.Body.AllowedEmails,
+ }
+
+ // Validate SMTP connection before saving
+ now := time.Now()
+ server.ValidatedAt = &now
+ if err := h.sender.TestConnection(server); err != nil {
+ server.Status = models.SMTPStatusInvalid
+ server.ValidationError = err.Error()
+ } else {
+ server.Status = models.SMTPStatusEnabled
+ server.ValidationError = ""
+ }
+
+ if err := h.repo.Create(server); err != nil {
+ return c.AbortInternalServerError("failed to create SMTP server", err)
+ }
+
+ h.audit.Log(uint(userID), c.GetString("email"), c.RealIP(), "smtp.created", "SMTP server created: "+req.Body.Host, nil)
+
+ return created(c, server)
+}
+
+func (h *SMTPHandler) Get(c *okapi.Context, req *GetSMTPRequest) error {
+ userID := c.GetInt("user_id")
+
+ server, err := h.repo.FindByID(uint(req.ID))
+ if err != nil || server.UserID != uint(userID) {
+ return c.AbortNotFound("SMTP server not found")
+ }
+
+ return ok(c, server)
+}
+
+func (h *SMTPHandler) Update(c *okapi.Context, req *UpdateSMTPRequest) error {
+ userID := c.GetInt("user_id")
+
+ server, err := h.repo.FindByID(uint(req.ID))
+ if err != nil || server.UserID != uint(userID) {
+ return c.AbortNotFound("SMTP server not found")
+ }
+
+ // Track whether connection-related fields changed
+ connectionChanged := false
+
+ if req.Body.Host != "" && req.Body.Host != server.Host {
+ server.Host = req.Body.Host
+ connectionChanged = true
+ }
+ if req.Body.Port != 0 && req.Body.Port != server.Port {
+ server.Port = req.Body.Port
+ connectionChanged = true
+ }
+ if req.Body.Username != "" && req.Body.Username != server.Username {
+ server.Username = req.Body.Username
+ connectionChanged = true
+ }
+ if req.Body.Password != "" {
+ server.Password = req.Body.Password
+ connectionChanged = true
+ }
+ if req.Body.Encryption != "" && req.Body.Encryption != server.Encryption {
+ server.Encryption = req.Body.Encryption
+ connectionChanged = true
+ }
+ if req.Body.MaxRetries != nil {
+ server.MaxRetries = *req.Body.MaxRetries
+ }
+ if req.Body.AllowedEmails != nil {
+ if err := h.validateAllowedEmails(uint(userID), req.Body.AllowedEmails); err != nil {
+ return c.AbortBadRequest(err.Error())
+ }
+ server.AllowedEmails = req.Body.AllowedEmails
+ }
+
+ // Handle status changes
+ if req.Body.Status != "" {
+ switch req.Body.Status {
+ case models.SMTPStatusDisabled:
+ server.Status = models.SMTPStatusDisabled
+ server.ValidationError = ""
+ case models.SMTPStatusEnabled:
+ // Re-validate before enabling
+ now := time.Now()
+ server.ValidatedAt = &now
+ if err := h.sender.TestConnection(server); err != nil {
+ server.Status = models.SMTPStatusInvalid
+ server.ValidationError = err.Error()
+ } else {
+ server.Status = models.SMTPStatusEnabled
+ server.ValidationError = ""
+ }
+ }
+ } else if connectionChanged {
+ // Connection fields changed — re-validate automatically
+ now := time.Now()
+ server.ValidatedAt = &now
+ if err := h.sender.TestConnection(server); err != nil {
+ server.Status = models.SMTPStatusInvalid
+ server.ValidationError = err.Error()
+ } else {
+ server.Status = models.SMTPStatusEnabled
+ server.ValidationError = ""
+ }
+ }
+
+ if err := h.repo.Update(server); err != nil {
+ return c.AbortInternalServerError("failed to update SMTP server")
+ }
+
+ h.audit.Log(uint(userID), c.GetString("email"), c.RealIP(), "smtp.updated", "SMTP server updated: "+server.Host, nil)
+
+ return ok(c, server)
+}
+
+func (h *SMTPHandler) List(c *okapi.Context, req *ListRequest) error {
+ userID := c.GetInt("user_id")
+ page, size, offset := normalizePageParams(req.Page, req.Size)
+
+ servers, total, err := h.repo.FindByUserID(uint(userID), size, offset)
+ if err != nil {
+ return c.AbortInternalServerError("failed to list SMTP servers")
+ }
+
+ return paginated(c, servers, total, page, size)
+}
+
+func (h *SMTPHandler) Delete(c *okapi.Context, req *DeleteSMTPRequest) error {
+ userID := c.GetInt("user_id")
+
+ server, err := h.repo.FindByID(uint(req.ID))
+ if err != nil || server.UserID != uint(userID) {
+ return c.AbortNotFound("SMTP server not found")
+ }
+
+ if err := h.repo.Delete(server.ID); err != nil {
+ return c.AbortInternalServerError("failed to delete SMTP server")
+ }
+
+ h.audit.Log(uint(userID), c.GetString("email"), c.RealIP(), "smtp.deleted", "SMTP server deleted: "+server.Host, nil)
+
+ return noContent(c)
+}
+
+func (h *SMTPHandler) Test(c *okapi.Context, req *TestSMTPRequest) error {
+ userID := c.GetInt("user_id")
+
+ server, err := h.repo.FindByID(uint(req.ID))
+ if err != nil || server.UserID != uint(userID) {
+ return c.AbortNotFound("SMTP server not found")
+ }
+
+ now := time.Now()
+ if err := h.sender.TestConnection(server); err != nil {
+ // Update validation state on test failure
+ _ = h.repo.SetStatus(server.ID, models.SMTPStatusInvalid, err.Error())
+ return ok(c, okapi.M{
+ "success": false,
+ "message": err.Error(),
+ "status": models.SMTPStatusInvalid,
+ "validated_at": now,
+ })
+ }
+
+ // Update validation state on test success
+ _ = h.repo.SetStatus(server.ID, models.SMTPStatusEnabled, "")
+ return ok(c, okapi.M{
+ "success": true,
+ "message": "connection successful",
+ "status": models.SMTPStatusEnabled,
+ "validated_at": now,
+ })
+}
diff --git a/internal/handlers/stylesheet_handler.go b/internal/handlers/stylesheet_handler.go
new file mode 100644
index 0000000..59959a9
--- /dev/null
+++ b/internal/handlers/stylesheet_handler.go
@@ -0,0 +1,125 @@
+/*
+ * 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 (
+ "time"
+
+ "github.com/jkaninda/okapi"
+ "github.com/jkaninda/posta/internal/models"
+ "github.com/jkaninda/posta/internal/storage/repositories"
+)
+
+type StyleSheetHandler struct {
+ repo *repositories.StyleSheetRepository
+}
+type CreateStyleSheetRequest struct {
+ Body struct {
+ Name string `json:"name" required:"true"`
+ CSS string `json:"css"`
+ } `json:"body"`
+}
+type UpdateStyleSheetRequest struct {
+ ID int `param:"id"`
+ Body struct {
+ Name string `json:"name"`
+ CSS string `json:"css"`
+ } `json:"body"`
+}
+type DeleteStyleSheetRequest struct {
+ ID int `param:"id"`
+}
+
+func NewStyleSheetHandler(repo *repositories.StyleSheetRepository) *StyleSheetHandler {
+ return &StyleSheetHandler{repo: repo}
+}
+
+func (h *StyleSheetHandler) Create(c *okapi.Context, req *CreateStyleSheetRequest) error {
+ userID := c.GetInt("user_id")
+
+ ss := &models.StyleSheet{
+ UserID: uint(userID),
+ Name: req.Body.Name,
+ CSS: req.Body.CSS,
+ }
+
+ if err := h.repo.Create(ss); err != nil {
+ return c.AbortConflict("stylesheet name already exists")
+ }
+
+ return created(c, ss)
+}
+
+func (h *StyleSheetHandler) Update(c *okapi.Context, req *UpdateStyleSheetRequest) error {
+ userID := c.GetInt("user_id")
+
+ ss, err := h.repo.FindByID(uint(req.ID))
+ if err != nil || ss.UserID != uint(userID) {
+ return c.AbortNotFound("stylesheet not found")
+ }
+
+ if req.Body.Name != "" {
+ ss.Name = req.Body.Name
+ }
+ if req.Body.CSS != "" {
+ ss.CSS = req.Body.CSS
+ }
+
+ now := time.Now()
+ ss.UpdatedAt = &now
+
+ if err := h.repo.Update(ss); err != nil {
+ return c.AbortInternalServerError("failed to update stylesheet")
+ }
+
+ return ok(c, ss)
+}
+
+func (h *StyleSheetHandler) Delete(c *okapi.Context, req *DeleteStyleSheetRequest) error {
+ userID := c.GetInt("user_id")
+
+ ss, err := h.repo.FindByID(uint(req.ID))
+ if err != nil || ss.UserID != uint(userID) {
+ return c.AbortNotFound("stylesheet not found")
+ }
+
+ if err := h.repo.Delete(ss.ID); err != nil {
+ return c.AbortInternalServerError("failed to delete stylesheet")
+ }
+
+ return noContent(c)
+}
+
+func (h *StyleSheetHandler) List(c *okapi.Context, req *ListRequest) error {
+ userID := c.GetInt("user_id")
+ page, size, offset := normalizePageParams(req.Page, req.Size)
+
+ sheets, total, err := h.repo.FindByUserID(uint(userID), size, offset)
+ if err != nil {
+ return c.AbortInternalServerError("failed to list stylesheets")
+ }
+
+ return paginated(c, sheets, total, page, size)
+}
diff --git a/internal/handlers/suppression_handler.go b/internal/handlers/suppression_handler.go
new file mode 100644
index 0000000..edf0578
--- /dev/null
+++ b/internal/handlers/suppression_handler.go
@@ -0,0 +1,88 @@
+/*
+ * 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 (
+ "github.com/jkaninda/okapi"
+ "github.com/jkaninda/posta/internal/models"
+ "github.com/jkaninda/posta/internal/storage/repositories"
+)
+
+type SuppressionHandler struct {
+ repo *repositories.SuppressionRepository
+}
+type CreateSuppressionRequest struct {
+ Body struct {
+ Email string `json:"email" required:"true" format:"email"`
+ Reason string `json:"reason"`
+ } `json:"body"`
+}
+type DeleteSuppressionRequest struct {
+ Body struct {
+ Email string `json:"email" required:"true" format:"email"`
+ } `json:"body"`
+}
+
+func NewSuppressionHandler(repo *repositories.SuppressionRepository) *SuppressionHandler {
+ return &SuppressionHandler{repo: repo}
+}
+
+func (h *SuppressionHandler) Create(c *okapi.Context, req *CreateSuppressionRequest) error {
+ userID := c.GetInt("user_id")
+
+ suppression := &models.Suppression{
+ UserID: uint(userID),
+ Email: req.Body.Email,
+ Reason: req.Body.Reason,
+ }
+
+ if err := h.repo.Create(suppression); err != nil {
+ return c.AbortConflict("email already in suppression list")
+ }
+
+ return created(c, suppression)
+}
+
+func (h *SuppressionHandler) List(c *okapi.Context, req *ListRequest) error {
+ userID := c.GetInt("user_id")
+ page, size, offset := normalizePageParams(req.Page, req.Size)
+
+ suppressions, total, err := h.repo.FindByUserID(uint(userID), size, offset)
+ if err != nil {
+ return c.AbortInternalServerError("failed to list suppressions")
+ }
+
+ return paginated(c, suppressions, total, page, size)
+}
+
+func (h *SuppressionHandler) Delete(c *okapi.Context, req *DeleteSuppressionRequest) error {
+ userID := c.GetInt("user_id")
+
+ if err := h.repo.Delete(uint(userID), req.Body.Email); err != nil {
+ return c.AbortInternalServerError("failed to remove from suppression list")
+ }
+
+ return noContent(c)
+}
diff --git a/internal/handlers/template_handler.go b/internal/handlers/template_handler.go
new file mode 100644
index 0000000..d740ab2
--- /dev/null
+++ b/internal/handlers/template_handler.go
@@ -0,0 +1,403 @@
+/*
+ * 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/services/email"
+ "github.com/jkaninda/posta/internal/storage/repositories"
+)
+
+type TemplateHandler struct {
+ repo *repositories.TemplateRepository
+ stylesheetRepo *repositories.StyleSheetRepository
+ versionRepo *repositories.TemplateVersionRepository
+ localizationRepo *repositories.TemplateLocalizationRepository
+ emailService *email.Service
+}
+type CreateTemplateRequest struct {
+ Body struct {
+ Name string `json:"name" required:"true"`
+ SampleData string `json:"sample_data"`
+ DefaultLanguage string `json:"default_language"`
+ Description string `json:"description"`
+ } `json:"body"`
+}
+type UpdateTemplateRequest struct {
+ ID int `param:"id"`
+ Body struct {
+ Name string `json:"name"`
+ SampleData *string `json:"sample_data"`
+ DefaultLanguage string `json:"default_language"`
+ Description *string `json:"description"`
+ } `json:"body"`
+}
+type DeleteTemplateRequest struct {
+ ID int `param:"id"`
+}
+type PreviewTemplateRequest struct {
+ Body struct {
+ SubjectTemplate string `json:"subject_template" required:"true"`
+ HTMLTemplate string `json:"html_template"`
+ TextTemplate string `json:"text_template"`
+ StyleSheetID *uint `json:"stylesheet_id"`
+ TemplateData map[string]any `json:"template_data"`
+ } `json:"body"`
+}
+type PreviewResult struct {
+ Subject string `json:"subject"`
+ HTML string `json:"html"`
+ Text string `json:"text"`
+}
+type SendTestRequest struct {
+ ID int `param:"id"`
+ Body email.SendTestRequest `json:"body"`
+}
+
+func NewTemplateHandler(repo *repositories.TemplateRepository, ssRepo *repositories.StyleSheetRepository, versionRepo *repositories.TemplateVersionRepository, localizationRepo *repositories.TemplateLocalizationRepository, emailService *email.Service) *TemplateHandler {
+ return &TemplateHandler{repo: repo, stylesheetRepo: ssRepo, versionRepo: versionRepo, localizationRepo: localizationRepo, emailService: emailService}
+}
+
+func (h *TemplateHandler) Create(c *okapi.Context, req *CreateTemplateRequest) error {
+ userID := c.GetInt("user_id")
+
+ defaultLang := req.Body.DefaultLanguage
+ if defaultLang == "" {
+ defaultLang = "en"
+ }
+
+ tmpl := &models.Template{
+ UserID: uint(userID),
+ Name: req.Body.Name,
+ DefaultLanguage: defaultLang,
+ Description: req.Body.Description,
+ SampleData: req.Body.SampleData,
+ }
+
+ if err := h.repo.Create(tmpl); err != nil {
+ return c.AbortConflict("template name already exists")
+ }
+
+ // Create default version v1 and set it as active
+ v := &models.TemplateVersion{
+ TemplateID: tmpl.ID,
+ Version: 1,
+ SampleData: req.Body.SampleData,
+ }
+ if err := h.versionRepo.Create(v); err != nil {
+ return c.AbortInternalServerError("failed to create default version")
+ }
+
+ tmpl.ActiveVersionID = &v.ID
+ if err := h.repo.Update(tmpl); err != nil {
+ return c.AbortInternalServerError("failed to activate default version")
+ }
+
+ return created(c, tmpl)
+}
+
+func (h *TemplateHandler) Update(c *okapi.Context, req *UpdateTemplateRequest) error {
+ userID := c.GetInt("user_id")
+
+ tmpl, err := h.repo.FindByID(uint(req.ID))
+ if err != nil || tmpl.UserID != uint(userID) {
+ return c.AbortNotFound("template not found")
+ }
+
+ if req.Body.Name != "" {
+ tmpl.Name = req.Body.Name
+ }
+ if req.Body.SampleData != nil {
+ tmpl.SampleData = *req.Body.SampleData
+ }
+ if req.Body.DefaultLanguage != "" {
+ tmpl.DefaultLanguage = req.Body.DefaultLanguage
+ }
+ if req.Body.Description != nil {
+ tmpl.Description = *req.Body.Description
+ }
+
+ now := time.Now()
+ tmpl.UpdatedAt = &now
+
+ if err := h.repo.Update(tmpl); err != nil {
+ return c.AbortInternalServerError("failed to update template")
+ }
+
+ return ok(c, tmpl)
+}
+
+func (h *TemplateHandler) List(c *okapi.Context, req *ListRequest) error {
+ userID := c.GetInt("user_id")
+ page, size, offset := normalizePageParams(req.Page, req.Size)
+
+ templates, total, err := h.repo.FindByUserID(uint(userID), size, offset)
+ if err != nil {
+ return c.AbortInternalServerError("failed to list templates")
+ }
+
+ return paginated(c, templates, total, page, size)
+}
+
+func (h *TemplateHandler) Delete(c *okapi.Context, req *DeleteTemplateRequest) error {
+ userID := c.GetInt("user_id")
+
+ tmpl, err := h.repo.FindByID(uint(req.ID))
+ if err != nil || tmpl.UserID != uint(userID) {
+ return c.AbortNotFound("template not found")
+ }
+
+ if err := h.repo.Delete(tmpl.ID); err != nil {
+ return c.AbortInternalServerError("failed to delete template")
+ }
+
+ return noContent(c)
+}
+
+func (h *TemplateHandler) Preview(c *okapi.Context, req *PreviewTemplateRequest) error {
+ renderer := email.NewTemplateRenderer()
+
+ data := req.Body.TemplateData
+ if data == nil {
+ data = map[string]any{}
+ }
+
+ input := &email.RenderInput{
+ SubjectTemplate: req.Body.SubjectTemplate,
+ HTMLTemplate: req.Body.HTMLTemplate,
+ TextTemplate: req.Body.TextTemplate,
+ }
+
+ // Resolve the linked stylesheet for preview
+ if req.Body.StyleSheetID != nil && *req.Body.StyleSheetID > 0 {
+ ss, err := h.stylesheetRepo.FindByID(*req.Body.StyleSheetID)
+ if err != nil {
+ return c.AbortNotFound("stylesheet not found")
+ }
+ input.CSS = ss.CSS
+ }
+
+ rendered, err := renderer.Render(input, data)
+ if err != nil {
+ return c.AbortBadRequest("template render error: " + err.Error())
+ }
+
+ return ok(c, PreviewResult{
+ Subject: rendered.Subject,
+ HTML: rendered.HTML,
+ Text: rendered.Text,
+ })
+}
+
+func (h *TemplateHandler) SendTest(c *okapi.Context, req *SendTestRequest) error {
+ userID := c.GetInt("user_id")
+ userEmail := c.GetString("email")
+
+ tmpl, err := h.repo.FindByID(uint(req.ID))
+ if err != nil || tmpl.UserID != uint(userID) {
+ return c.AbortNotFound("template not found")
+ }
+
+ resp, err := h.emailService.SendTestByTemplateID(c.Request().Context(), uint(userID), userEmail, tmpl.ID, &req.Body)
+ if err != nil {
+ return c.AbortBadRequest(err.Error())
+ }
+
+ return ok(c, resp)
+}
+
+// --- Export / Import ---
+
+type ExportTemplateRequest struct {
+ ID int `param:"id"`
+}
+
+type ExportLocalization struct {
+ Language string `json:"language"`
+ SubjectTemplate string `json:"subject_template"`
+ HTMLTemplate string `json:"html_template"`
+ TextTemplate string `json:"text_template"`
+}
+
+type ExportVersion struct {
+ Version int `json:"version"`
+ SampleData string `json:"sample_data"`
+ IsActive bool `json:"is_active"`
+ Localizations []ExportLocalization `json:"localizations"`
+}
+
+type TemplateExport struct {
+ PostaVersion string `json:"posta_version"`
+ ExportedAt string `json:"exported_at"`
+ Name string `json:"name"`
+ Description string `json:"description"`
+ DefaultLanguage string `json:"default_language"`
+ SampleData string `json:"sample_data"`
+ Versions []ExportVersion `json:"versions"`
+}
+
+type ImportTemplateRequest struct {
+ Body TemplateExport `json:"body"`
+}
+
+func (h *TemplateHandler) Export(c *okapi.Context, req *ExportTemplateRequest) error {
+ userID := c.GetInt("user_id")
+
+ tmpl, err := h.repo.FindByID(uint(req.ID))
+ if err != nil || tmpl.UserID != uint(userID) {
+ return c.AbortNotFound("template not found")
+ }
+
+ versions, err := h.versionRepo.FindByTemplateID(tmpl.ID)
+ if err != nil {
+ return c.AbortInternalServerError("failed to load 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,
+ })
+ }
+
+ export := TemplateExport{
+ PostaVersion: config.Version,
+ ExportedAt: time.Now().UTC().Format(time.RFC3339),
+ Name: tmpl.Name,
+ Description: tmpl.Description,
+ DefaultLanguage: tmpl.DefaultLanguage,
+ SampleData: tmpl.SampleData,
+ Versions: exportVersions,
+ }
+
+ return ok(c, export)
+}
+
+func (h *TemplateHandler) Import(c *okapi.Context, req *ImportTemplateRequest) error {
+ userID := c.GetInt("user_id")
+ data := req.Body
+
+ if data.Name == "" {
+ return c.AbortBadRequest("template name is required")
+ }
+
+ defaultLang := data.DefaultLanguage
+ if defaultLang == "" {
+ defaultLang = "en"
+ }
+
+ tmpl := &models.Template{
+ UserID: uint(userID),
+ Name: data.Name,
+ DefaultLanguage: defaultLang,
+ Description: data.Description,
+ SampleData: data.SampleData,
+ }
+
+ if err := h.repo.Create(tmpl); err != nil {
+ return c.AbortConflict("template name already exists")
+ }
+
+ var activeVersionDBID *uint
+
+ for _, ev := range data.Versions {
+ nextVersion, err := h.versionRepo.NextVersion(tmpl.ID)
+ if err != nil {
+ return c.AbortInternalServerError("failed to determine next version")
+ }
+
+ v := &models.TemplateVersion{
+ TemplateID: tmpl.ID,
+ Version: nextVersion,
+ SampleData: ev.SampleData,
+ }
+ if err := h.versionRepo.Create(v); err != nil {
+ return c.AbortInternalServerError(fmt.Sprintf("failed to create version %d", ev.Version))
+ }
+
+ if ev.IsActive {
+ activeVersionDBID = &v.ID
+ }
+
+ for _, el := range ev.Localizations {
+ l := &models.TemplateLocalization{
+ VersionID: v.ID,
+ Language: el.Language,
+ SubjectTemplate: el.SubjectTemplate,
+ HTMLTemplate: el.HTMLTemplate,
+ TextTemplate: el.TextTemplate,
+ }
+ if err := h.localizationRepo.Create(l); err != nil {
+ return c.AbortInternalServerError(fmt.Sprintf("failed to create localization %s for version %d", el.Language, ev.Version))
+ }
+ }
+ }
+
+ // If no versions were imported, create a default v1
+ if len(data.Versions) == 0 {
+ v := &models.TemplateVersion{
+ TemplateID: tmpl.ID,
+ Version: 1,
+ SampleData: data.SampleData,
+ }
+ if err := h.versionRepo.Create(v); err != nil {
+ return c.AbortInternalServerError("failed to create default version")
+ }
+ activeVersionDBID = &v.ID
+ }
+
+ if activeVersionDBID != nil {
+ tmpl.ActiveVersionID = activeVersionDBID
+ if err := h.repo.Update(tmpl); err != nil {
+ return c.AbortInternalServerError("failed to activate version")
+ }
+ }
+
+ return created(c, tmpl)
+}
diff --git a/internal/handlers/template_localization_handler.go b/internal/handlers/template_localization_handler.go
new file mode 100644
index 0000000..222aaba
--- /dev/null
+++ b/internal/handlers/template_localization_handler.go
@@ -0,0 +1,251 @@
+/*
+ * 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 (
+ "time"
+
+ "github.com/jkaninda/okapi"
+ "github.com/jkaninda/posta/internal/models"
+ "github.com/jkaninda/posta/internal/services/email"
+ "github.com/jkaninda/posta/internal/storage/repositories"
+)
+
+type TemplateLocalizationHandler struct {
+ templateRepo *repositories.TemplateRepository
+ versionRepo *repositories.TemplateVersionRepository
+ localizationRepo *repositories.TemplateLocalizationRepository
+ stylesheetRepo *repositories.StyleSheetRepository
+}
+type ListLocalizationsRequest struct {
+ TemplateID int `param:"id"`
+ VersionID int `param:"versionId"`
+}
+type CreateLocalizationRequest struct {
+ TemplateID int `param:"id"`
+ VersionID int `param:"versionId"`
+ Body struct {
+ Language string `json:"language" required:"true"`
+ SubjectTemplate string `json:"subject_template" required:"true"`
+ HTMLTemplate string `json:"html_template"`
+ TextTemplate string `json:"text_template"`
+ } `json:"body"`
+}
+type UpdateLocalizationRequest struct {
+ ID int `param:"localizationId"`
+ Body struct {
+ SubjectTemplate *string `json:"subject_template"`
+ HTMLTemplate *string `json:"html_template"`
+ TextTemplate *string `json:"text_template"`
+ } `json:"body"`
+}
+type DeleteLocalizationRequest struct {
+ ID int `param:"localizationId"`
+}
+type PreviewLocalizationRequest struct {
+ TemplateID int `param:"id"`
+ VersionID int `param:"versionId"`
+ Body struct {
+ Language string `json:"language" required:"true"`
+ TemplateData map[string]any `json:"template_data"`
+ } `json:"body"`
+}
+
+func NewTemplateLocalizationHandler(
+ templateRepo *repositories.TemplateRepository,
+ versionRepo *repositories.TemplateVersionRepository,
+ localizationRepo *repositories.TemplateLocalizationRepository,
+ stylesheetRepo *repositories.StyleSheetRepository,
+) *TemplateLocalizationHandler {
+ return &TemplateLocalizationHandler{
+ templateRepo: templateRepo,
+ versionRepo: versionRepo,
+ localizationRepo: localizationRepo,
+ stylesheetRepo: stylesheetRepo,
+ }
+}
+
+func (h *TemplateLocalizationHandler) List(c *okapi.Context, req *ListLocalizationsRequest) error {
+ userID := c.GetInt("user_id")
+
+ tmpl, err := h.templateRepo.FindByID(uint(req.TemplateID))
+ if err != nil || tmpl.UserID != uint(userID) {
+ return c.AbortNotFound("template not found")
+ }
+
+ v, err := h.versionRepo.FindByID(uint(req.VersionID))
+ if err != nil || v.TemplateID != tmpl.ID {
+ return c.AbortNotFound("version not found")
+ }
+
+ localizations, err := h.localizationRepo.FindByVersionID(v.ID)
+ if err != nil {
+ return c.AbortInternalServerError("failed to list localizations")
+ }
+
+ return ok(c, localizations)
+}
+
+func (h *TemplateLocalizationHandler) Create(c *okapi.Context, req *CreateLocalizationRequest) error {
+ userID := c.GetInt("user_id")
+
+ tmpl, err := h.templateRepo.FindByID(uint(req.TemplateID))
+ if err != nil || tmpl.UserID != uint(userID) {
+ return c.AbortNotFound("template not found")
+ }
+
+ v, err := h.versionRepo.FindByID(uint(req.VersionID))
+ if err != nil || v.TemplateID != tmpl.ID {
+ return c.AbortNotFound("version not found")
+ }
+
+ l := &models.TemplateLocalization{
+ VersionID: v.ID,
+ Language: req.Body.Language,
+ SubjectTemplate: req.Body.SubjectTemplate,
+ HTMLTemplate: req.Body.HTMLTemplate,
+ TextTemplate: req.Body.TextTemplate,
+ }
+
+ if err := h.localizationRepo.Create(l); err != nil {
+ return c.AbortConflict("localization for this language already exists")
+ }
+
+ return created(c, l)
+}
+
+func (h *TemplateLocalizationHandler) Update(c *okapi.Context, req *UpdateLocalizationRequest) error {
+ l, err := h.localizationRepo.FindByID(uint(req.ID))
+ if err != nil {
+ return c.AbortNotFound("localization not found")
+ }
+
+ // Verify ownership through the version → template chain
+ v, err := h.versionRepo.FindByID(l.VersionID)
+ if err != nil {
+ return c.AbortNotFound("version not found")
+ }
+ tmpl, err := h.templateRepo.FindByID(v.TemplateID)
+ if err != nil {
+ return c.AbortNotFound("template not found")
+ }
+ userID := c.GetInt("user_id")
+ if tmpl.UserID != uint(userID) {
+ return c.AbortNotFound("localization not found")
+ }
+
+ if req.Body.SubjectTemplate != nil {
+ l.SubjectTemplate = *req.Body.SubjectTemplate
+ }
+ if req.Body.HTMLTemplate != nil {
+ l.HTMLTemplate = *req.Body.HTMLTemplate
+ }
+ if req.Body.TextTemplate != nil {
+ l.TextTemplate = *req.Body.TextTemplate
+ }
+
+ now := time.Now()
+ l.UpdatedAt = &now
+
+ if err := h.localizationRepo.Update(l); err != nil {
+ return c.AbortInternalServerError("failed to update localization")
+ }
+
+ return ok(c, l)
+}
+
+func (h *TemplateLocalizationHandler) Delete(c *okapi.Context, req *DeleteLocalizationRequest) error {
+ l, err := h.localizationRepo.FindByID(uint(req.ID))
+ if err != nil {
+ return c.AbortNotFound("localization not found")
+ }
+
+ v, err := h.versionRepo.FindByID(l.VersionID)
+ if err != nil {
+ return c.AbortNotFound("version not found")
+ }
+ tmpl, err := h.templateRepo.FindByID(v.TemplateID)
+ if err != nil {
+ return c.AbortNotFound("template not found")
+ }
+ userID := c.GetInt("user_id")
+ if tmpl.UserID != uint(userID) {
+ return c.AbortNotFound("localization not found")
+ }
+
+ if err := h.localizationRepo.Delete(l.ID); err != nil {
+ return c.AbortInternalServerError("failed to delete localization")
+ }
+
+ return noContent(c)
+}
+
+func (h *TemplateLocalizationHandler) Preview(c *okapi.Context, req *PreviewLocalizationRequest) error {
+ userID := c.GetInt("user_id")
+
+ tmpl, err := h.templateRepo.FindByID(uint(req.TemplateID))
+ if err != nil || tmpl.UserID != uint(userID) {
+ return c.AbortNotFound("template not found")
+ }
+
+ v, err := h.versionRepo.FindByID(uint(req.VersionID))
+ if err != nil || v.TemplateID != tmpl.ID {
+ return c.AbortNotFound("version not found")
+ }
+
+ l, err := h.localizationRepo.FindByVersionAndLanguage(v.ID, req.Body.Language)
+ if err != nil {
+ return c.AbortNotFound("localization not found for language: " + req.Body.Language)
+ }
+
+ data := req.Body.TemplateData
+ if data == nil {
+ data = map[string]any{}
+ }
+
+ // Build render input from the localization
+ var css string
+ if v.StyleSheet != nil {
+ css = v.StyleSheet.CSS
+ }
+ input := &email.RenderInput{
+ SubjectTemplate: l.SubjectTemplate,
+ HTMLTemplate: l.HTMLTemplate,
+ TextTemplate: l.TextTemplate,
+ CSS: css,
+ }
+
+ renderer := email.NewTemplateRenderer()
+ rendered, err := renderer.Render(input, data)
+ if err != nil {
+ return c.AbortBadRequest("template render error: " + err.Error())
+ }
+
+ return ok(c, PreviewResult{
+ Subject: rendered.Subject,
+ HTML: rendered.HTML,
+ Text: rendered.Text,
+ })
+}
diff --git a/internal/handlers/template_version_handler.go b/internal/handlers/template_version_handler.go
new file mode 100644
index 0000000..511d909
--- /dev/null
+++ b/internal/handlers/template_version_handler.go
@@ -0,0 +1,190 @@
+/*
+ * 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 (
+ "time"
+
+ "github.com/jkaninda/okapi"
+ "github.com/jkaninda/posta/internal/models"
+ "github.com/jkaninda/posta/internal/storage/repositories"
+)
+
+type TemplateVersionHandler struct {
+ templateRepo *repositories.TemplateRepository
+ versionRepo *repositories.TemplateVersionRepository
+}
+type ListVersionsRequest struct {
+ TemplateID int `param:"id"`
+}
+type CreateVersionRequest struct {
+ TemplateID int `param:"id"`
+ Body struct {
+ StyleSheetID *uint `json:"stylesheet_id"`
+ SampleData string `json:"sample_data"`
+ } `json:"body"`
+}
+type UpdateVersionRequest struct {
+ TemplateID int `param:"id"`
+ VersionID int `param:"versionId"`
+ Body struct {
+ StyleSheetID *uint `json:"stylesheet_id"`
+ } `json:"body"`
+}
+type ActivateVersionRequest struct {
+ TemplateID int `param:"id"`
+ VersionID int `param:"versionId"`
+}
+type DeleteVersionRequest struct {
+ TemplateID int `param:"id"`
+ VersionID int `param:"versionId"`
+}
+
+func NewTemplateVersionHandler(
+ templateRepo *repositories.TemplateRepository,
+ versionRepo *repositories.TemplateVersionRepository,
+) *TemplateVersionHandler {
+ return &TemplateVersionHandler{
+ templateRepo: templateRepo,
+ versionRepo: versionRepo,
+ }
+}
+
+func (h *TemplateVersionHandler) List(c *okapi.Context, req *ListVersionsRequest) error {
+ userID := c.GetInt("user_id")
+
+ tmpl, err := h.templateRepo.FindByID(uint(req.TemplateID))
+ if err != nil || tmpl.UserID != uint(userID) {
+ return c.AbortNotFound("template not found")
+ }
+
+ versions, err := h.versionRepo.FindByTemplateID(tmpl.ID)
+ if err != nil {
+ return c.AbortInternalServerError("failed to list versions")
+ }
+
+ return ok(c, versions)
+}
+
+func (h *TemplateVersionHandler) Create(c *okapi.Context, req *CreateVersionRequest) error {
+ userID := c.GetInt("user_id")
+
+ tmpl, err := h.templateRepo.FindByID(uint(req.TemplateID))
+ if err != nil || tmpl.UserID != uint(userID) {
+ return c.AbortNotFound("template not found")
+ }
+
+ nextVersion, err := h.versionRepo.NextVersion(tmpl.ID)
+ if err != nil {
+ return c.AbortInternalServerError("failed to determine next version")
+ }
+
+ v := &models.TemplateVersion{
+ TemplateID: tmpl.ID,
+ Version: nextVersion,
+ StyleSheetID: req.Body.StyleSheetID,
+ SampleData: req.Body.SampleData,
+ }
+
+ if err := h.versionRepo.Create(v); err != nil {
+ return c.AbortInternalServerError("failed to create version")
+ }
+
+ return created(c, v)
+}
+
+func (h *TemplateVersionHandler) Update(c *okapi.Context, req *UpdateVersionRequest) error {
+ userID := c.GetInt("user_id")
+
+ tmpl, err := h.templateRepo.FindByID(uint(req.TemplateID))
+ if err != nil || tmpl.UserID != uint(userID) {
+ return c.AbortNotFound("template not found")
+ }
+
+ v, err := h.versionRepo.FindByID(uint(req.VersionID))
+ if err != nil || v.TemplateID != tmpl.ID {
+ return c.AbortNotFound("version not found")
+ }
+
+ v.StyleSheetID = req.Body.StyleSheetID
+
+ if err := h.versionRepo.Update(v); err != nil {
+ return c.AbortInternalServerError("failed to update version")
+ }
+
+ // Reload to get the stylesheet association
+ v, _ = h.versionRepo.FindByID(v.ID)
+ return ok(c, v)
+}
+
+func (h *TemplateVersionHandler) Activate(c *okapi.Context, req *ActivateVersionRequest) error {
+ userID := c.GetInt("user_id")
+
+ tmpl, err := h.templateRepo.FindByID(uint(req.TemplateID))
+ if err != nil || tmpl.UserID != uint(userID) {
+ return c.AbortNotFound("template not found")
+ }
+
+ v, err := h.versionRepo.FindByID(uint(req.VersionID))
+ if err != nil || v.TemplateID != tmpl.ID {
+ return c.AbortNotFound("version not found")
+ }
+
+ vID := v.ID
+ tmpl.ActiveVersionID = &vID
+ now := time.Now()
+ tmpl.UpdatedAt = &now
+
+ if err := h.templateRepo.Update(tmpl); err != nil {
+ return c.AbortInternalServerError("failed to activate version")
+ }
+
+ return ok(c, tmpl)
+}
+
+func (h *TemplateVersionHandler) Delete(c *okapi.Context, req *DeleteVersionRequest) error {
+ userID := c.GetInt("user_id")
+
+ tmpl, err := h.templateRepo.FindByID(uint(req.TemplateID))
+ if err != nil || tmpl.UserID != uint(userID) {
+ return c.AbortNotFound("template not found")
+ }
+
+ v, err := h.versionRepo.FindByID(uint(req.VersionID))
+ if err != nil || v.TemplateID != tmpl.ID {
+ return c.AbortNotFound("version not found")
+ }
+
+ // Prevent deleting the active version
+ if tmpl.ActiveVersionID != nil && *tmpl.ActiveVersionID == v.ID {
+ return c.AbortBadRequest("cannot delete the active version")
+ }
+
+ if err := h.versionRepo.Delete(v.ID); err != nil {
+ return c.AbortInternalServerError("failed to delete version")
+ }
+
+ return noContent(c)
+}
diff --git a/internal/handlers/user_handler.go b/internal/handlers/user_handler.go
new file mode 100644
index 0000000..97480dd
--- /dev/null
+++ b/internal/handlers/user_handler.go
@@ -0,0 +1,429 @@
+/*
+ * 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"
+ "net/http"
+ "time"
+
+ "strings"
+
+ "github.com/jkaninda/okapi"
+ "github.com/jkaninda/posta/internal/dto"
+ "github.com/jkaninda/posta/internal/models"
+ "github.com/jkaninda/posta/internal/services/eventbus"
+ "github.com/jkaninda/posta/internal/services/seeder"
+ "github.com/jkaninda/posta/internal/services/settings"
+ "github.com/jkaninda/posta/internal/services/twofactor"
+ "github.com/jkaninda/posta/internal/storage/repositories"
+ "golang.org/x/crypto/bcrypt"
+)
+
+type UserHandler struct {
+ repo *repositories.UserRepository
+ 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 {
+ return &UserHandler{
+ repo: repo,
+ jwtSecret: []byte(jwtSecret),
+ seeder: seeder,
+ bus: bus,
+ }
+}
+
+func (h *UserHandler) SetSettings(s *settings.Provider) {
+ h.settings = s
+}
+
+type LoginRequest struct {
+ Body struct {
+ Email string `json:"email" required:"true" format:"email"`
+ Password string `json:"password" required:"true"`
+ TwoFactorCode string `json:"two_factor_code"`
+ } `json:"body"`
+}
+
+type AuthResponse struct {
+ Token string `json:"token"`
+ User struct {
+ ID uint `json:"id"`
+ Name string `json:"name"`
+ Email string `json:"email"`
+ Role models.UserRole `json:"role"`
+ } `json:"user"`
+}
+
+type UserProfile struct {
+ ID uint `json:"id"`
+ Name string `json:"name"`
+ Email string `json:"email"`
+ Role models.UserRole `json:"role"`
+ TwoFactorEnabled bool `json:"two_factor_enabled"`
+ RequireVerifiedDomain bool `json:"require_verified_domain"`
+ CreatedAt time.Time `json:"created_at"`
+}
+
+type Enable2FAResponse struct {
+ Secret string `json:"secret"`
+ URL string `json:"url"` // otpauth:// URL for QR code
+}
+
+type Verify2FARequest struct {
+ Body struct {
+ Code string `json:"code" required:"true" minLength:"6" maxLength:"6"`
+ } `json:"body"`
+}
+
+type Disable2FARequest struct {
+ Body struct {
+ Code string `json:"code" required:"true" minLength:"6" maxLength:"6"`
+ } `json:"body"`
+}
+
+type UpdateProfileRequest struct {
+ Body struct {
+ Name string `json:"name" required:"true" minLength:"1"`
+ RequireVerifiedDomain *bool `json:"require_verified_domain"`
+ } `json:"body"`
+}
+
+type ChangePasswordRequest struct {
+ Body struct {
+ CurrentPassword string `json:"current_password" required:"true"`
+ NewPassword string `json:"new_password" required:"true" minLength:"8"`
+ } `json:"body"`
+}
+
+type RegisterRequest struct {
+ Body struct {
+ Name string `json:"name" required:"true" minLength:"1"`
+ Email string `json:"email" required:"true" format:"email"`
+ Password string `json:"password" required:"true" minLength:"8"`
+ } `json:"body"`
+}
+
+// Register allows new users to self-register when registration is enabled.
+func (h *UserHandler) Register(c *okapi.Context, req *RegisterRequest) error {
+ if h.settings == nil || !h.settings.RegistrationEnabled() {
+ return c.AbortForbidden("registration is disabled")
+ }
+
+ email := strings.TrimSpace(strings.ToLower(req.Body.Email))
+ if email == "" {
+ return c.AbortBadRequest("email is required")
+ }
+
+ // Check allowed signup domains
+ allowedDomains := h.settings.GetString("allowed_signup_domains", "")
+ if allowedDomains != "" {
+ parts := strings.SplitN(email, "@", 2)
+ if len(parts) != 2 {
+ return c.AbortBadRequest("invalid email address")
+ }
+ domain := parts[1]
+ allowed := false
+ for _, d := range strings.Split(allowedDomains, ",") {
+ if strings.TrimSpace(d) == domain {
+ allowed = true
+ break
+ }
+ }
+ if !allowed {
+ return c.AbortForbidden("registration is not allowed for this email domain")
+ }
+ }
+
+ hash, err := bcrypt.GenerateFromPassword([]byte(req.Body.Password), bcrypt.DefaultCost)
+ if err != nil {
+ return c.AbortInternalServerError("failed to hash password", err)
+ }
+
+ user := &models.User{
+ Name: strings.TrimSpace(req.Body.Name),
+ Email: email,
+ PasswordHash: string(hash),
+ Role: models.UserRoleUser,
+ }
+
+ if err := h.repo.Create(user); err != nil {
+ return c.AbortConflict("email already registered")
+ }
+
+ // Seed default data for the new user
+ if h.seeder != nil {
+ go h.seeder.SeedUserDefaults(user.ID, user.Name)
+ }
+
+ if h.bus != nil {
+ h.bus.PublishSimple(models.EventCategoryUser, "user.registered", &user.ID, user.Email, c.RealIP(),
+ fmt.Sprintf("User %q registered", user.Email), nil)
+ }
+
+ // 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)
+ if err != nil {
+ return c.AbortInternalServerError("failed to generate token", err)
+ }
+
+ return created(c, AuthResponse{
+ Token: token,
+ User: struct {
+ ID uint `json:"id"`
+ Name string `json:"name"`
+ Email string `json:"email"`
+ Role models.UserRole `json:"role"`
+ }{ID: user.ID, Name: user.Name, Email: user.Email, Role: user.Role},
+ })
+}
+
+// RegistrationStatus returns whether registration is enabled (public endpoint).
+func (h *UserHandler) RegistrationStatus(c *okapi.Context) error {
+ enabled := h.settings != nil && h.settings.RegistrationEnabled()
+ return ok(c, okapi.M{"registration_enabled": enabled})
+}
+
+// UpdateProfile allows authenticated users to update their profile (name).
+func (h *UserHandler) UpdateProfile(c *okapi.Context, req *UpdateProfileRequest) error {
+ userID := c.GetInt("user_id")
+ user, err := h.repo.FindByID(uint(userID))
+ if err != nil {
+ return c.AbortNotFound("user not found")
+ }
+
+ user.Name = req.Body.Name
+ if req.Body.RequireVerifiedDomain != nil {
+ user.RequireVerifiedDomain = *req.Body.RequireVerifiedDomain
+ }
+ if err := h.repo.Update(user); err != nil {
+ return c.AbortInternalServerError("failed to update profile")
+ }
+
+ return ok(c, UserProfile{
+ ID: user.ID,
+ Name: user.Name,
+ Email: user.Email,
+ Role: user.Role,
+ TwoFactorEnabled: user.TwoFactorEnabled,
+ RequireVerifiedDomain: user.RequireVerifiedDomain,
+ CreatedAt: user.CreatedAt,
+ })
+}
+
+// ChangePassword allows authenticated users to change their own password.
+func (h *UserHandler) ChangePassword(c *okapi.Context, req *ChangePasswordRequest) error {
+ userID := c.GetInt("user_id")
+ user, err := h.repo.FindByID(uint(userID))
+ if err != nil {
+ return c.AbortNotFound("user not found")
+ }
+
+ if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(req.Body.CurrentPassword)); err != nil {
+ return c.AbortBadRequest("current password is incorrect")
+ }
+
+ hash, err := bcrypt.GenerateFromPassword([]byte(req.Body.NewPassword), bcrypt.DefaultCost)
+ if err != nil {
+ return c.AbortInternalServerError("failed to hash password", err)
+ }
+
+ user.PasswordHash = string(hash)
+ if err := h.repo.Update(user); err != nil {
+ return c.AbortInternalServerError("failed to update password")
+ }
+
+ return ok(c, okapi.M{"message": "password updated successfully"})
+}
+
+func (h *UserHandler) Login(c *okapi.Context, req *LoginRequest) error {
+ user, err := h.repo.FindByEmail(req.Body.Email)
+ if err != nil {
+ return c.AbortUnauthorized("invalid credentials")
+ }
+
+ if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(req.Body.Password)); err != nil {
+ return c.AbortUnauthorized("invalid credentials")
+ }
+
+ if !user.Active {
+ return c.AbortForbidden("account is disabled")
+ }
+
+ // Check 2FA
+ if user.TwoFactorEnabled {
+ if req.Body.TwoFactorCode == "" {
+ return c.JSON(http.StatusUnauthorized, dto.Response[any]{
+ Success: false,
+ Data: map[string]any{
+ "requires_2fa": true,
+ "message": "2FA code required",
+ },
+ })
+ }
+ if !twofactor.ValidateCode(user.TwoFactorSecret, req.Body.TwoFactorCode) {
+ return c.AbortUnauthorized("invalid 2FA code")
+ }
+ }
+
+ // Seed default data on first login
+ go h.seeder.SeedUserDefaults(user.ID, user.Name)
+
+ // Record last login time
+ now := time.Now()
+ user.LastLoginAt = &now
+ _ = h.repo.Update(user)
+
+ if h.bus != nil {
+ h.bus.PublishSimple(models.EventCategoryUser, "user.login", &user.ID, user.Email, c.RealIP(),
+ 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)
+ if err != nil {
+ return c.AbortInternalServerError("failed to generate token", err)
+ }
+
+ return ok(c, AuthResponse{
+ Token: token,
+ User: struct {
+ ID uint `json:"id"`
+ Name string `json:"name"`
+ Email string `json:"email"`
+ Role models.UserRole `json:"role"`
+ }{ID: user.ID, Name: user.Name, Email: user.Email, Role: user.Role},
+ })
+}
+
+// Me returns the current user's profile.
+func (h *UserHandler) Me(c *okapi.Context) error {
+ userID := c.GetInt("user_id")
+ user, err := h.repo.FindByID(uint(userID))
+ if err != nil {
+ return c.AbortNotFound("user not found")
+ }
+
+ return ok(c, UserProfile{
+ ID: user.ID,
+ Name: user.Name,
+ Email: user.Email,
+ Role: user.Role,
+ TwoFactorEnabled: user.TwoFactorEnabled,
+ RequireVerifiedDomain: user.RequireVerifiedDomain,
+ CreatedAt: user.CreatedAt,
+ })
+}
+
+// Setup2FA generates a TOTP secret for the user (doesn't enable yet).
+func (h *UserHandler) Setup2FA(c *okapi.Context) error {
+ userID := c.GetInt("user_id")
+ user, err := h.repo.FindByID(uint(userID))
+ if err != nil {
+ return c.AbortNotFound("user not found")
+ }
+ if user.TwoFactorEnabled {
+ return c.AbortBadRequest("2FA is already enabled")
+ }
+
+ secret, url, err := twofactor.GenerateSecret(user.Email)
+ if err != nil {
+ return c.AbortInternalServerError("failed to generate 2FA secret")
+ }
+
+ // Store secret temporarily (not enabled yet)
+ user.TwoFactorSecret = secret
+ if err := h.repo.Update(user); err != nil {
+ return c.AbortInternalServerError("failed to save 2FA secret")
+ }
+
+ return ok(c, Enable2FAResponse{
+ Secret: secret,
+ URL: url,
+ })
+}
+
+// Verify2FA verifies a TOTP code and enables 2FA.
+func (h *UserHandler) Verify2FA(c *okapi.Context, req *Verify2FARequest) error {
+ userID := c.GetInt("user_id")
+ user, err := h.repo.FindByID(uint(userID))
+ if err != nil {
+ return c.AbortNotFound("user not found")
+ }
+ if user.TwoFactorEnabled {
+ return c.AbortBadRequest("2FA is already enabled")
+ }
+ if user.TwoFactorSecret == "" {
+ return c.AbortBadRequest("2FA setup not initiated, call setup first")
+ }
+
+ if !twofactor.ValidateCode(user.TwoFactorSecret, req.Body.Code) {
+ return c.AbortBadRequest("invalid 2FA code")
+ }
+
+ user.TwoFactorEnabled = true
+ if err := h.repo.Update(user); err != nil {
+ return c.AbortInternalServerError("failed to enable 2FA")
+ }
+
+ return ok(c, okapi.M{"message": "2FA enabled successfully"})
+}
+
+// Disable2FA disables 2FA after verifying a code.
+func (h *UserHandler) Disable2FA(c *okapi.Context, req *Disable2FARequest) error {
+ userID := c.GetInt("user_id")
+ user, err := h.repo.FindByID(uint(userID))
+ if err != nil {
+ return c.AbortNotFound("user not found")
+ }
+ if !user.TwoFactorEnabled {
+ return c.AbortBadRequest("2FA is not enabled")
+ }
+
+ if !twofactor.ValidateCode(user.TwoFactorSecret, req.Body.Code) {
+ return c.AbortBadRequest("invalid 2FA code")
+ }
+
+ user.TwoFactorEnabled = false
+ user.TwoFactorSecret = ""
+ if err := h.repo.Update(user); err != nil {
+ return c.AbortInternalServerError("failed to disable 2FA")
+ }
+
+ return ok(c, okapi.M{"message": "2FA disabled successfully"})
+}
diff --git a/internal/handlers/user_setting_handler.go b/internal/handlers/user_setting_handler.go
new file mode 100644
index 0000000..2454429
--- /dev/null
+++ b/internal/handlers/user_setting_handler.go
@@ -0,0 +1,114 @@
+/*
+ * 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 (
+ "github.com/jkaninda/okapi"
+ "github.com/jkaninda/posta/internal/storage/repositories"
+)
+
+// UserSettingHandler handles per-user settings.
+type UserSettingHandler struct {
+ repo *repositories.UserSettingRepository
+}
+
+func NewUserSettingHandler(repo *repositories.UserSettingRepository) *UserSettingHandler {
+ return &UserSettingHandler{repo: repo}
+}
+
+// --- Request types ---
+
+type UpdateUserSettingsRequest struct {
+ Body 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"`
+ DefaultTemplateID *uint `json:"default_template_id"`
+ APIKeyExpiryDays *int `json:"api_key_expiry_days"`
+ BounceAutoSuppress *bool `json:"bounce_auto_suppress"`
+ DailyReport *bool `json:"daily_report"`
+ } `json:"body"`
+}
+
+// --- Handlers ---
+
+func (h *UserSettingHandler) GetSettings(c *okapi.Context) error {
+ userID := uint(c.GetInt("user_id"))
+
+ settings, err := h.repo.FindByUserID(userID)
+ if err != nil {
+ return c.AbortInternalServerError("failed to load settings", err)
+ }
+ return ok(c, settings)
+}
+
+func (h *UserSettingHandler) UpdateSettings(c *okapi.Context, req *UpdateUserSettingsRequest) error {
+ userID := uint(c.GetInt("user_id"))
+
+ settings, err := h.repo.FindByUserID(userID)
+ if err != nil {
+ return c.AbortInternalServerError("failed to load settings", err)
+ }
+
+ if req.Body.Timezone != nil {
+ settings.Timezone = *req.Body.Timezone
+ }
+ if req.Body.DefaultSenderName != nil {
+ settings.DefaultSenderName = *req.Body.DefaultSenderName
+ }
+ if req.Body.DefaultSenderEmail != nil {
+ settings.DefaultSenderEmail = *req.Body.DefaultSenderEmail
+ }
+ if req.Body.EmailNotifications != nil {
+ settings.EmailNotifications = *req.Body.EmailNotifications
+ }
+ if req.Body.NotificationEmail != nil {
+ settings.NotificationEmail = *req.Body.NotificationEmail
+ }
+ if req.Body.WebhookRetryCount != nil {
+ settings.WebhookRetryCount = *req.Body.WebhookRetryCount
+ }
+ if req.Body.DefaultTemplateID != nil {
+ settings.DefaultTemplateID = req.Body.DefaultTemplateID
+ }
+ if req.Body.APIKeyExpiryDays != nil {
+ settings.APIKeyExpiryDays = *req.Body.APIKeyExpiryDays
+ }
+ if req.Body.BounceAutoSuppress != nil {
+ settings.BounceAutoSuppress = *req.Body.BounceAutoSuppress
+ }
+ if req.Body.DailyReport != nil {
+ settings.DailyReport = *req.Body.DailyReport
+ }
+
+ if err := h.repo.CreateOrUpdate(settings); err != nil {
+ return c.AbortInternalServerError("failed to update settings", err)
+ }
+
+ return ok(c, settings)
+}
diff --git a/internal/handlers/webhook_delivery_handler.go b/internal/handlers/webhook_delivery_handler.go
new file mode 100644
index 0000000..0235ca8
--- /dev/null
+++ b/internal/handlers/webhook_delivery_handler.go
@@ -0,0 +1,50 @@
+/*
+ * 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 (
+ "github.com/jkaninda/okapi"
+ "github.com/jkaninda/posta/internal/storage/repositories"
+)
+
+type WebhookDeliveryHandler struct {
+ repo *repositories.WebhookDeliveryRepository
+}
+
+func NewWebhookDeliveryHandler(repo *repositories.WebhookDeliveryRepository) *WebhookDeliveryHandler {
+ return &WebhookDeliveryHandler{repo: repo}
+}
+
+func (h *WebhookDeliveryHandler) List(c *okapi.Context, req *ListRequest) error {
+ userID := c.GetInt("user_id")
+ page, size, offset := normalizePageParams(req.Page, req.Size)
+
+ deliveries, total, err := h.repo.FindByUserID(uint(userID), size, offset)
+ if err != nil {
+ return c.AbortInternalServerError("failed to list webhook deliveries")
+ }
+
+ return paginated(c, deliveries, total, page, size)
+}
diff --git a/internal/handlers/webhook_handler.go b/internal/handlers/webhook_handler.go
new file mode 100644
index 0000000..77c700f
--- /dev/null
+++ b/internal/handlers/webhook_handler.go
@@ -0,0 +1,118 @@
+/*
+ * 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 (
+ "crypto/rand"
+ "encoding/hex"
+
+ "github.com/jkaninda/okapi"
+ "github.com/jkaninda/posta/internal/models"
+ "github.com/jkaninda/posta/internal/services/audit"
+ "github.com/jkaninda/posta/internal/storage/repositories"
+)
+
+type WebhookHandler struct {
+ repo *repositories.WebhookRepository
+ audit *audit.Logger
+}
+type CreateWebhookRequest struct {
+ Body struct {
+ URL string `json:"url" required:"true" format:"uri"`
+ Events []string `json:"events" required:"true" minItems:"1"`
+ Filters []string `json:"filters"`
+ } `json:"body"`
+}
+type DeleteWebhookRequest struct {
+ ID int `param:"id"`
+}
+
+func NewWebhookHandler(repo *repositories.WebhookRepository, audit *audit.Logger) *WebhookHandler {
+ return &WebhookHandler{repo: repo, audit: audit}
+}
+
+func (h *WebhookHandler) Create(c *okapi.Context, req *CreateWebhookRequest) error {
+ userID := c.GetInt("user_id")
+
+ // Validate event names
+ validEvents := map[string]bool{"email.sent": true, "email.failed": true}
+ for _, event := range req.Body.Events {
+ if !validEvents[event] {
+ return c.AbortBadRequest("invalid event: " + event + ". Valid events: email.sent, email.failed")
+ }
+ }
+
+ // Generate a random signing secret for HMAC webhook signatures
+ secretBytes := make([]byte, 32)
+ if _, err := rand.Read(secretBytes); err != nil {
+ return c.AbortInternalServerError("failed to generate webhook secret", err)
+ }
+ secret := hex.EncodeToString(secretBytes)
+
+ wh := &models.Webhook{
+ UserID: uint(userID),
+ URL: req.Body.URL,
+ Events: req.Body.Events,
+ Filters: req.Body.Filters,
+ Secret: secret,
+ }
+
+ if err := h.repo.Create(wh); err != nil {
+ return c.AbortInternalServerError("failed to create webhook", err)
+ }
+
+ h.audit.Log(uint(userID), c.GetString("email"), c.RealIP(), "webhook.created", "Webhook created: "+req.Body.URL, nil)
+
+ return created(c, wh)
+}
+
+func (h *WebhookHandler) List(c *okapi.Context, req *ListRequest) error {
+ userID := c.GetInt("user_id")
+ page, size, offset := normalizePageParams(req.Page, req.Size)
+
+ webhooks, total, err := h.repo.FindByUserID(uint(userID), size, offset)
+ if err != nil {
+ return c.AbortInternalServerError("failed to list webhooks")
+ }
+
+ return paginated(c, webhooks, total, page, size)
+}
+
+func (h *WebhookHandler) Delete(c *okapi.Context, req *DeleteWebhookRequest) error {
+ userID := c.GetInt("user_id")
+
+ wh, err := h.repo.FindByID(uint(req.ID))
+ if err != nil || wh.UserID != uint(userID) {
+ return c.AbortNotFound("webhook not found")
+ }
+
+ if err := h.repo.Delete(wh.ID); err != nil {
+ return c.AbortInternalServerError("failed to delete webhook")
+ }
+
+ h.audit.Log(uint(userID), c.GetString("email"), c.RealIP(), "webhook.deleted", "Webhook deleted: "+wh.URL, nil)
+
+ return noContent(c)
+}
diff --git a/internal/metrics/metrics.go b/internal/metrics/metrics.go
new file mode 100644
index 0000000..e787265
--- /dev/null
+++ b/internal/metrics/metrics.go
@@ -0,0 +1,195 @@
+/*
+ * 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 metrics
+
+import (
+ "net/http"
+ "strconv"
+ "time"
+
+ "github.com/jkaninda/okapi"
+ "github.com/prometheus/client_golang/prometheus"
+ "github.com/prometheus/client_golang/prometheus/promhttp"
+)
+
+var (
+ httpRequestsTotal = prometheus.NewCounterVec(
+ prometheus.CounterOpts{
+ Name: "posta_http_requests_total",
+ Help: "Total number of HTTP requests",
+ },
+ []string{"method", "path", "status"},
+ )
+
+ httpRequestDuration = prometheus.NewHistogramVec(
+ prometheus.HistogramOpts{
+ Name: "posta_http_request_duration_seconds",
+ Help: "HTTP request duration in seconds",
+ Buckets: prometheus.DefBuckets,
+ },
+ []string{"method", "path"},
+ )
+
+ emailsSentTotal = prometheus.NewCounter(
+ prometheus.CounterOpts{
+ Name: "posta_emails_sent_total",
+ Help: "Total number of emails sent successfully",
+ },
+ )
+
+ emailsFailedTotal = prometheus.NewCounter(
+ prometheus.CounterOpts{
+ Name: "posta_emails_failed_total",
+ Help: "Total number of emails that failed to send",
+ },
+ )
+
+ emailsQueuedTotal = prometheus.NewCounter(
+ prometheus.CounterOpts{
+ Name: "posta_emails_queued_total",
+ Help: "Total number of emails enqueued for delivery",
+ },
+ )
+
+ emailRetriesTotal = prometheus.NewCounter(
+ prometheus.CounterOpts{
+ Name: "posta_email_retries_total",
+ Help: "Total number of email retry attempts",
+ },
+ )
+
+ webhookDeliveriesTotal = prometheus.NewCounterVec(
+ prometheus.CounterOpts{
+ Name: "posta_webhook_deliveries_total",
+ Help: "Total number of webhook delivery attempts by status",
+ },
+ []string{"status"},
+ )
+
+ webhookDeliveryDuration = prometheus.NewHistogram(
+ prometheus.HistogramOpts{
+ Name: "posta_webhook_delivery_duration_seconds",
+ Help: "Duration of webhook delivery attempts in seconds",
+ Buckets: prometheus.DefBuckets,
+ },
+ )
+
+ bouncesTotal = prometheus.NewCounterVec(
+ prometheus.CounterOpts{
+ Name: "posta_bounces_total",
+ Help: "Total number of bounces recorded by type",
+ },
+ []string{"type"},
+ )
+
+ suppressionsTotal = prometheus.NewCounter(
+ prometheus.CounterOpts{
+ Name: "posta_suppressions_total",
+ Help: "Total number of email suppressions added",
+ },
+ )
+)
+
+func init() {
+ prometheus.MustRegister(httpRequestsTotal)
+ prometheus.MustRegister(httpRequestDuration)
+ prometheus.MustRegister(emailsSentTotal)
+ prometheus.MustRegister(emailsFailedTotal)
+ prometheus.MustRegister(emailsQueuedTotal)
+ prometheus.MustRegister(emailRetriesTotal)
+ prometheus.MustRegister(webhookDeliveriesTotal)
+ prometheus.MustRegister(webhookDeliveryDuration)
+ prometheus.MustRegister(bouncesTotal)
+ prometheus.MustRegister(suppressionsTotal)
+}
+
+// IncrementEmailSent increments the emails sent counter.
+func IncrementEmailSent() {
+ emailsSentTotal.Inc()
+}
+
+// IncrementEmailFailed increments the emails failed counter.
+func IncrementEmailFailed() {
+ emailsFailedTotal.Inc()
+}
+
+// IncrementEmailQueued increments the emails queued counter.
+func IncrementEmailQueued() {
+ emailsQueuedTotal.Inc()
+}
+
+// IncrementEmailRetry increments the email retries counter.
+func IncrementEmailRetry() {
+ emailRetriesTotal.Inc()
+}
+
+// IncrementWebhookDelivery increments the webhook delivery counter for the given status.
+func IncrementWebhookDelivery(status string) {
+ webhookDeliveriesTotal.WithLabelValues(status).Inc()
+}
+
+// ObserveWebhookDeliveryDuration records a webhook delivery duration.
+func ObserveWebhookDeliveryDuration(seconds float64) {
+ webhookDeliveryDuration.Observe(seconds)
+}
+
+// IncrementBounce increments the bounce counter for the given type (hard, soft, complaint).
+func IncrementBounce(bounceType string) {
+ bouncesTotal.WithLabelValues(bounceType).Inc()
+}
+
+// IncrementSuppression increments the suppression counter.
+func IncrementSuppression() {
+ suppressionsTotal.Inc()
+}
+
+// PrometheusMiddleware records HTTP request metrics.
+func PrometheusMiddleware() okapi.Middleware {
+ return func(c *okapi.Context) error {
+ start := time.Now()
+
+ err := c.Next()
+
+ duration := time.Since(start).Seconds()
+ method := c.Request().Method
+ path := c.Path()
+ status := strconv.Itoa(c.Response().StatusCode())
+
+ httpRequestsTotal.WithLabelValues(method, path, status).Inc()
+ httpRequestDuration.WithLabelValues(method, path).Observe(duration)
+
+ return err
+ }
+
+}
+
+// MetricsHandler returns the Prometheus metrics handler.
+func MetricsHandler() okapi.HandlerFunc {
+ handler := promhttp.Handler()
+ return func(c *okapi.Context) error {
+ handler.ServeHTTP(c.Response().(http.ResponseWriter), c.Request())
+ return nil
+ }
+}
diff --git a/internal/middlewares/middleware.go b/internal/middlewares/middleware.go
new file mode 100644
index 0000000..a94f144
--- /dev/null
+++ b/internal/middlewares/middleware.go
@@ -0,0 +1,142 @@
+/*
+ * 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 middlewares
+
+import (
+ "net"
+ "strings"
+
+ "github.com/jkaninda/okapi"
+ "github.com/jkaninda/posta/internal/config"
+ "github.com/jkaninda/posta/internal/services/auth"
+ "github.com/jkaninda/posta/internal/services/ratelimit"
+ "github.com/jkaninda/posta/internal/storage/repositories"
+)
+
+func baseJWTAuth(cfg *config.Config) okapi.JWTAuth {
+ return okapi.JWTAuth{
+ SigningSecret: []byte(cfg.JWTSecret),
+ Audience: "posta",
+ ContextKey: "jwt_user",
+ ForwardClaims: map[string]string{
+ "user_id": "sub",
+ "email": "email",
+ "role": "role",
+ },
+ }
+}
+
+// User
+func JWTAuth(cfg *config.Config) okapi.JWTAuth {
+ return baseJWTAuth(cfg)
+}
+
+// Admin
+func JWTAdminAuth(cfg *config.Config) okapi.JWTAuth {
+ auth := baseJWTAuth(cfg)
+ auth.ClaimsExpression = "Equals(`role`,`admin`)"
+ return auth
+}
+
+// Admin via Query for SSE
+func JWTAdminQueryAuth(cfg *config.Config) okapi.JWTAuth {
+ auth := baseJWTAuth(cfg)
+ auth.ClaimsExpression = "Equals(`role`,`admin`)"
+ auth.TokenLookup = "query:token"
+ return auth
+}
+
+// LoginRateLimitMiddleware limits login attempts per IP address using Redis.
+func LoginRateLimitMiddleware(limiter *ratelimit.RedisLimiter) okapi.Middleware {
+ return func(c *okapi.Context) error {
+ ip := c.RealIP()
+ if err := limiter.AllowLogin(c.Request().Context(), ip); err != nil {
+ return c.AbortTooManyRequests(err.Error())
+ }
+ return c.Next()
+
+ }
+}
+
+// APIKeyAuthMiddleware validates API key from Authorization header and sets user context.
+func APIKeyAuthMiddleware(keyService *auth.APIKeyService, userRepo *repositories.UserRepository, keyRepo *repositories.APIKeyRepository) okapi.Middleware {
+ return func(c *okapi.Context) error {
+ authHeader := c.Header("Authorization")
+ if authHeader == "" {
+ return c.AbortUnauthorized("missing Authorization header")
+ }
+
+ rawKey := strings.TrimPrefix(authHeader, "Bearer ")
+ if rawKey == authHeader {
+ return c.AbortUnauthorized("invalid Authorization format, expected: Bearer <API_KEY>")
+ }
+
+ apiKey, err := keyService.ValidateKey(rawKey)
+ if err != nil {
+ return c.AbortUnauthorized(err.Error())
+ }
+
+ user, err := userRepo.FindByID(apiKey.UserID)
+ if err != nil {
+ return c.AbortUnauthorized("user not found")
+ }
+
+ if !user.Active {
+ return c.AbortForbidden("account is disabled")
+ }
+
+ // Check IP allowlist
+ if len(apiKey.AllowedIPs) > 0 {
+ clientIP := c.RealIP()
+ allowed := false
+ for _, ip := range apiKey.AllowedIPs {
+ if ip == clientIP {
+ allowed = true
+ break
+ }
+ // Support CIDR notation
+ if strings.Contains(ip, "/") {
+ _, network, err := net.ParseCIDR(ip)
+ if err == nil && network.Contains(net.ParseIP(clientIP)) {
+ allowed = true
+ break
+ }
+ }
+ }
+ if !allowed {
+ return c.AbortForbidden("IP address not allowed for this API key")
+ }
+ }
+
+ c.Set("user_id", int(apiKey.UserID))
+ c.Set("api_key_id", int(apiKey.ID))
+ c.Set("user_email", user.Email)
+
+ go func() { _ = keyRepo.UpdateLastUsed(apiKey.ID) }()
+
+ return c.Next()
+
+ }
+}
diff --git a/internal/models/api_key.go b/internal/models/api_key.go
new file mode 100644
index 0000000..38d52a7
--- /dev/null
+++ b/internal/models/api_key.go
@@ -0,0 +1,57 @@
+/*
+ * 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"
+
+ "github.com/lib/pq"
+)
+
+type APIKey struct {
+ ID uint `json:"id" gorm:"primaryKey"`
+ UserID uint `json:"user_id" gorm:"index;not null"`
+ Name string `json:"name" gorm:"not null"`
+ KeyHash string `json:"-" gorm:"not null"`
+ KeyPrefix string `json:"key_prefix" gorm:"not null"`
+ CreatedAt time.Time `json:"created_at"`
+ ExpiresAt *time.Time `json:"expires_at"`
+ LastUsedAt *time.Time `json:"last_used_at"`
+ Revoked bool `json:"revoked" gorm:"default:false"`
+ AllowedIPs pq.StringArray `json:"allowed_ips" gorm:"type:text[]"`
+
+ User User `json:"-" gorm:"foreignKey:UserID"`
+}
+
+func (k *APIKey) IsExpired() bool {
+ if k.ExpiresAt == nil {
+ return false
+ }
+ return time.Now().After(*k.ExpiresAt)
+}
+
+func (k *APIKey) IsValid() bool {
+ return !k.Revoked && !k.IsExpired()
+}
diff --git a/internal/models/bounce.go b/internal/models/bounce.go
new file mode 100644
index 0000000..4cd4ef4
--- /dev/null
+++ b/internal/models/bounce.go
@@ -0,0 +1,48 @@
+/*
+ * 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"
+
+type BounceType string
+
+const (
+ BounceTypeHard BounceType = "hard"
+ BounceTypeSoft BounceType = "soft"
+ BounceTypeComplaint BounceType = "complaint"
+)
+
+type Bounce struct {
+ ID uint `json:"id" gorm:"primaryKey"`
+ UserID uint `json:"user_id" gorm:"index;not null"`
+ EmailID uint `json:"email_id" gorm:"index;not null"`
+ Recipient string `json:"recipient" gorm:"not null"`
+ Type BounceType `json:"type" gorm:"not null"`
+ Reason string `json:"reason"`
+ CreatedAt time.Time `json:"created_at"`
+
+ User User `json:"-" gorm:"foreignKey:UserID"`
+ Email Email `json:"-" gorm:"foreignKey:EmailID"`
+}
diff --git a/internal/models/contact.go b/internal/models/contact.go
new file mode 100644
index 0000000..ceaeebe
--- /dev/null
+++ b/internal/models/contact.go
@@ -0,0 +1,38 @@
+/*
+ * 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"
+
+type Contact struct {
+ ID uint `json:"id" gorm:"primaryKey"`
+ UserID uint `json:"user_id" gorm:"uniqueIndex:idx_user_email;not null"`
+ Email string `json:"email" gorm:"uniqueIndex:idx_user_email;not null"`
+ Name string `json:"name" gorm:"default:''"`
+ SentCount int64 `json:"sent_count" gorm:"default:0;not null"`
+ FailCount int64 `json:"fail_count" gorm:"default:0;not null"`
+ LastSentAt *time.Time `json:"last_sent_at"`
+ CreatedAt time.Time `json:"created_at"`
+}
diff --git a/internal/models/contact_list.go b/internal/models/contact_list.go
new file mode 100644
index 0000000..75169db
--- /dev/null
+++ b/internal/models/contact_list.go
@@ -0,0 +1,50 @@
+/*
+ * 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"
+
+type ContactList struct {
+ ID uint `json:"id" gorm:"primaryKey"`
+ UserID uint `json:"user_id" gorm:"index;not null"`
+ Name string `json:"name" gorm:"not null"`
+ Description string `json:"description"`
+ CreatedAt time.Time `json:"created_at"`
+ UpdatedAt *time.Time `json:"updated_at"`
+
+ User User `json:"-" gorm:"foreignKey:UserID"`
+ Members []ContactListMember `json:"-" gorm:"foreignKey:ListID"`
+}
+
+type ContactListMember struct {
+ ID uint `json:"id" gorm:"primaryKey"`
+ ListID uint `json:"list_id" gorm:"uniqueIndex:idx_list_email;not null"`
+ Email string `json:"email" gorm:"uniqueIndex:idx_list_email;not null"`
+ Name string `json:"name"`
+ Data string `json:"data" gorm:"type:text"` // JSON metadata
+ CreatedAt time.Time `json:"created_at"`
+
+ List ContactList `json:"-" gorm:"foreignKey:ListID"`
+}
diff --git a/internal/models/domain.go b/internal/models/domain.go
new file mode 100644
index 0000000..ebfad5b
--- /dev/null
+++ b/internal/models/domain.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"
+
+type Domain struct {
+ ID uint `json:"id" gorm:"primaryKey"`
+ UserID uint `json:"user_id" gorm:"uniqueIndex:idx_user_domain;not null"`
+ Domain string `json:"domain" gorm:"uniqueIndex:idx_user_domain;not null"`
+ OwnershipVerified bool `json:"ownership_verified" gorm:"default:false"`
+ SPFVerified bool `json:"spf_verified" gorm:"default:false"`
+ DKIMVerified bool `json:"dkim_verified" gorm:"default:false"`
+ DMARCVerified bool `json:"dmarc_verified" gorm:"default:false"`
+ VerificationToken string `json:"verification_token" gorm:"not null"`
+ CreatedAt time.Time `json:"created_at"`
+
+ User User `json:"-" gorm:"foreignKey:UserID"`
+}
+
+// IsOwnershipVerified returns true when domain ownership has been confirmed via TXT record.
+func (d *Domain) IsOwnershipVerified() bool {
+ return d.OwnershipVerified
+}
+
+// IsFullyVerified returns true when ownership is confirmed and all DNS checks pass.
+func (d *Domain) IsFullyVerified() bool {
+ return d.OwnershipVerified && d.SPFVerified && d.DKIMVerified && d.DMARCVerified
+}
diff --git a/internal/models/email.go b/internal/models/email.go
new file mode 100644
index 0000000..1ca1327
--- /dev/null
+++ b/internal/models/email.go
@@ -0,0 +1,77 @@
+/*
+ * 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"
+
+ "github.com/lib/pq"
+)
+
+type EmailStatus string
+
+const (
+ EmailStatusPending EmailStatus = "pending"
+ EmailStatusQueued EmailStatus = "queued"
+ EmailStatusProcessing EmailStatus = "processing"
+ EmailStatusSent EmailStatus = "sent"
+ EmailStatusFailed EmailStatus = "failed"
+ EmailStatusSuppressed EmailStatus = "suppressed"
+ EmailStatusScheduled EmailStatus = "scheduled"
+)
+
+type Email struct {
+ ID uint `json:"id" gorm:"primaryKey"`
+ UUID string `json:"uuid" gorm:"type:uuid;default:gen_random_uuid();uniqueIndex;not null"`
+ UserID uint `json:"user_id" gorm:"index;not null"`
+ APIKeyID *uint `json:"api_key_id" gorm:"index"`
+ Sender string `json:"sender" gorm:"not null"`
+ Recipients pq.StringArray `json:"recipients" gorm:"type:text[];not null"`
+ Subject string `json:"subject" gorm:"not null"`
+ HTMLBody string `json:"html_body"`
+ TextBody string `json:"text_body"`
+ AttachmentsJSON string `json:"attachments_json,omitempty" gorm:"type:text"`
+ HeadersJSON string `json:"headers_json,omitempty" gorm:"type:text"`
+ ListUnsubscribeURL string `json:"list_unsubscribe_url,omitempty" gorm:"type:text"`
+ ListUnsubscribePost bool `json:"list_unsubscribe_post,omitempty"`
+ Status EmailStatus `json:"status" gorm:"default:pending;not null"`
+ ErrorMessage string `json:"error_message"`
+ RetryCount int `json:"retry_count" gorm:"default:0;not null"`
+ CreatedAt time.Time `json:"created_at"`
+ SentAt *time.Time `json:"sent_at"`
+ ScheduledAt *time.Time `json:"scheduled_at"`
+
+ SMTPHostname string `json:"smtp_hostname,omitempty"`
+
+ User User `json:"-" gorm:"foreignKey:UserID"`
+ APIKey APIKey `json:"-" gorm:"foreignKey:APIKeyID"`
+}
+
+// Attachment represents a file attachment in an email.
+type Attachment struct {
+ Filename string `json:"filename"`
+ Content string `json:"content"`
+ ContentType string `json:"content_type"`
+}
diff --git a/internal/models/event.go b/internal/models/event.go
new file mode 100644
index 0000000..f2a1922
--- /dev/null
+++ b/internal/models/event.go
@@ -0,0 +1,48 @@
+/*
+ * 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"
+
+type EventCategory string
+
+const (
+ EventCategoryUser EventCategory = "user"
+ EventCategoryEmail EventCategory = "email"
+ EventCategorySystem EventCategory = "system"
+ EventCategoryAudit EventCategory = "audit"
+)
+
+type Event struct {
+ ID uint `json:"id" gorm:"primaryKey"`
+ Category EventCategory `json:"category" gorm:"index;not null"`
+ Type string `json:"type" gorm:"index;not null"`
+ ActorID *uint `json:"actor_id" gorm:"index"`
+ ActorName string `json:"actor_name"`
+ ClientIP string `json:"client_ip,omitempty" gorm:"size:45"`
+ Message string `json:"message" gorm:"not null"`
+ Metadata string `json:"metadata" gorm:"type:text"`
+ CreatedAt time.Time `json:"created_at" gorm:"index"`
+}
diff --git a/internal/models/language.go b/internal/models/language.go
new file mode 100644
index 0000000..bf57043
--- /dev/null
+++ b/internal/models/language.go
@@ -0,0 +1,37 @@
+/*
+ * 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"
+
+type Language struct {
+ ID uint `json:"id" gorm:"primaryKey"`
+ UserID uint `json:"user_id" gorm:"uniqueIndex:idx_user_language;not null"`
+ Code string `json:"code" gorm:"uniqueIndex:idx_user_language;not null;size:10"`
+ Name string `json:"name" gorm:"not null"`
+ CreatedAt time.Time `json:"created_at"`
+
+ User User `json:"-" gorm:"foreignKey:UserID"`
+}
diff --git a/internal/models/server.go b/internal/models/server.go
new file mode 100644
index 0000000..cf08dea
--- /dev/null
+++ b/internal/models/server.go
@@ -0,0 +1,105 @@
+/*
+ * 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 (
+ "encoding/base64"
+ "time"
+
+ "github.com/lib/pq"
+ "gorm.io/gorm"
+)
+
+const (
+ // ServerSecurityModePermissive allows any user whose sender domain matches
+ // allowed_domains to use this server, regardless of domain ownership.
+ ServerSecurityModePermissive = "permissive"
+
+ // ServerSecurityModeStrict requires the user to have verified ownership of
+ // the sender domain (via TXT record) before the server is available to them.
+ ServerSecurityModeStrict = "strict"
+)
+
+// Server represents a shared SMTP server managed by platform administrators.
+// Unlike per-user SMTPServer records, a Server is available across multiple
+// user accounts based on the sender domain.
+type Server struct {
+ ID uint `json:"id" gorm:"primaryKey"`
+ Name string `json:"name" gorm:"not null"`
+ Host string `json:"host" gorm:"not null"`
+ Port int `json:"port" gorm:"not null"`
+ Username string `json:"username"`
+ Password string `json:"-"`
+ Encryption string `json:"encryption" gorm:"default:none;not null"`
+ MaxRetries int `json:"max_retries" gorm:"default:0;not null"`
+ Status string `json:"status" gorm:"default:enabled;not null"`
+ AllowedDomains pq.StringArray `json:"allowed_domains" gorm:"type:text[]"`
+ SecurityMode string `json:"security_mode" gorm:"default:permissive;not null"`
+ SentCount int64 `json:"sent_count" gorm:"default:0;not null"`
+ FailedCount int64 `json:"failed_count" gorm:"default:0;not null"`
+ ValidationError string `json:"validation_error" gorm:"type:text"`
+ ValidatedAt *time.Time `json:"validated_at"`
+ CreatedAt time.Time `json:"created_at"`
+ UpdatedAt time.Time `json:"updated_at"`
+}
+
+// IsEnabled returns true when the server can be used for delivery.
+func (s *Server) IsEnabled() bool {
+ return s.Status == SMTPStatusEnabled
+}
+
+// BeforeSave encodes the password to base64 before writing to the database.
+func (s *Server) BeforeSave(tx *gorm.DB) error {
+ if s.Password != "" {
+ s.Password = base64.StdEncoding.EncodeToString([]byte(s.Password))
+ }
+ return nil
+}
+
+// AfterFind decodes the base64-encoded password after reading from the database.
+func (s *Server) AfterFind(tx *gorm.DB) error {
+ if s.Password != "" {
+ decoded, err := base64.StdEncoding.DecodeString(s.Password)
+ if err != nil {
+ return nil
+ }
+ s.Password = string(decoded)
+ }
+ return nil
+}
+
+// ToSMTPServer converts this shared Server into the SMTPServer format used
+// by the SMTP sender, so existing send logic can be reused without modification.
+func (s *Server) ToSMTPServer() *SMTPServer {
+ return &SMTPServer{
+ ID: s.ID,
+ Host: s.Host,
+ Port: s.Port,
+ Username: s.Username,
+ Password: s.Password,
+ Encryption: s.Encryption,
+ MaxRetries: s.MaxRetries,
+ }
+}
diff --git a/internal/models/setting.go b/internal/models/setting.go
new file mode 100644
index 0000000..09817f6
--- /dev/null
+++ b/internal/models/setting.go
@@ -0,0 +1,38 @@
+/*
+ * 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"
+
+// Setting represents a platform-wide configuration entry managed by admins.
+// Settings are stored as key-value pairs with a type hint for the frontend.
+type Setting struct {
+ ID uint `json:"id" gorm:"primaryKey"`
+ Key string `json:"key" gorm:"uniqueIndex;not null"`
+ Value string `json:"value" gorm:"type:text"`
+ Type string `json:"type" gorm:"default:string;not null"`
+ CreatedAt time.Time `json:"created_at"`
+ UpdatedAt time.Time `json:"updated_at"`
+}
diff --git a/internal/models/smtp_server.go b/internal/models/smtp_server.go
new file mode 100644
index 0000000..01c7d70
--- /dev/null
+++ b/internal/models/smtp_server.go
@@ -0,0 +1,90 @@
+/*
+ * 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 (
+ "encoding/base64"
+ "time"
+
+ "github.com/lib/pq"
+ "gorm.io/gorm"
+)
+
+// Encryption modes for SMTP connections.
+const (
+ EncryptionNone = "none" // Plain text (port 25)
+ EncryptionSTARTTLS = "starttls" // Upgrade via STARTTLS (port 587)
+ EncryptionSSL = "ssl" // Implicit TLS (port 465)
+)
+
+// SMTP server status values.
+const (
+ SMTPStatusEnabled = "enabled" // Valid and available for sending
+ SMTPStatusDisabled = "disabled" // Manually disabled by user
+ SMTPStatusInvalid = "invalid" // Validation failed (bad credentials, connection error)
+)
+
+type SMTPServer struct {
+ ID uint `json:"id" gorm:"primaryKey"`
+ UserID uint `json:"user_id" gorm:"index;not null"`
+ Host string `json:"host" gorm:"not null"`
+ Port int `json:"port" gorm:"not null"`
+ Username string `json:"username"`
+ Password string `json:"-"`
+ Encryption string `json:"encryption" gorm:"default:none;not null"`
+ MaxRetries int `json:"max_retries" gorm:"default:0;not null"`
+ AllowedEmails pq.StringArray `json:"allowed_emails" gorm:"type:text[]"`
+ Status string `json:"status" gorm:"default:enabled;not null"`
+ ValidationError string `json:"validation_error" gorm:"type:text"`
+ ValidatedAt *time.Time `json:"validated_at"`
+ CreatedAt time.Time `json:"created_at"`
+
+ User User `json:"-" gorm:"foreignKey:UserID"`
+}
+
+// IsEnabled returns true when the server can be used for delivery.
+func (s *SMTPServer) IsEnabled() bool {
+ return s.Status == SMTPStatusEnabled
+}
+
+// BeforeSave encodes the password to base64 before writing to the database.
+func (s *SMTPServer) BeforeSave(tx *gorm.DB) error {
+ if s.Password != "" {
+ s.Password = base64.StdEncoding.EncodeToString([]byte(s.Password))
+ }
+ return nil
+}
+
+// AfterFind decodes the base64-encoded password after reading from the database.
+func (s *SMTPServer) AfterFind(tx *gorm.DB) error {
+ if s.Password != "" {
+ decoded, err := base64.StdEncoding.DecodeString(s.Password)
+ if err != nil {
+ return nil
+ }
+ s.Password = string(decoded)
+ }
+ return nil
+}
diff --git a/internal/models/stylesheet.go b/internal/models/stylesheet.go
new file mode 100644
index 0000000..5cd895d
--- /dev/null
+++ b/internal/models/stylesheet.go
@@ -0,0 +1,38 @@
+/*
+ * 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"
+
+type StyleSheet struct {
+ ID uint `json:"id" gorm:"primaryKey"`
+ UserID uint `json:"user_id" gorm:"uniqueIndex:idx_user_stylesheet;not null"`
+ Name string `json:"name" gorm:"uniqueIndex:idx_user_stylesheet;not null"`
+ CSS string `json:"css"`
+ CreatedAt time.Time `json:"created_at"`
+ UpdatedAt *time.Time `json:"updated_at,omitempty"`
+
+ User User `json:"-" gorm:"foreignKey:UserID"`
+}
diff --git a/internal/models/suppression.go b/internal/models/suppression.go
new file mode 100644
index 0000000..fe89f0d
--- /dev/null
+++ b/internal/models/suppression.go
@@ -0,0 +1,37 @@
+/*
+ * 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"
+
+type Suppression struct {
+ ID uint `json:"id" gorm:"primaryKey"`
+ UserID uint `json:"user_id" gorm:"uniqueIndex:idx_user_suppression;not null"`
+ Email string `json:"email" gorm:"uniqueIndex:idx_user_suppression;not null"`
+ Reason string `json:"reason"`
+ CreatedAt time.Time `json:"created_at"`
+
+ User User `json:"-" gorm:"foreignKey:UserID"`
+}
diff --git a/internal/models/template.go b/internal/models/template.go
new file mode 100644
index 0000000..2b9e510
--- /dev/null
+++ b/internal/models/template.go
@@ -0,0 +1,42 @@
+/*
+ * 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"
+
+type Template struct {
+ ID uint `json:"id" gorm:"primaryKey"`
+ UserID uint `json:"user_id" gorm:"uniqueIndex:idx_user_template;not null"`
+ Name string `json:"name" gorm:"uniqueIndex:idx_user_template;not null"`
+ DefaultLanguage string `json:"default_language" gorm:"default:en;not null"`
+ ActiveVersionID *uint `json:"active_version_id,omitempty" gorm:"uniqueIndex"`
+ Description string `json:"description"`
+ SampleData string `json:"sample_data"`
+ CreatedAt time.Time `json:"created_at"`
+ UpdatedAt *time.Time `json:"updated_at,omitempty"`
+
+ User User `json:"-" gorm:"foreignKey:UserID"`
+ ActiveVersion *TemplateVersion `json:"active_version,omitempty" gorm:"foreignKey:ActiveVersionID;constraint:false"`
+}
diff --git a/internal/models/template_localization.go b/internal/models/template_localization.go
new file mode 100644
index 0000000..bf925a3
--- /dev/null
+++ b/internal/models/template_localization.go
@@ -0,0 +1,40 @@
+/*
+ * 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"
+
+type TemplateLocalization struct {
+ ID uint `json:"id" gorm:"primaryKey"`
+ VersionID uint `json:"version_id" gorm:"uniqueIndex:idx_version_language;not null"`
+ Language string `json:"language" gorm:"uniqueIndex:idx_version_language;not null;size:10"`
+ SubjectTemplate string `json:"subject_template" gorm:"not null"`
+ HTMLTemplate string `json:"html_template"`
+ TextTemplate string `json:"text_template"`
+ CreatedAt time.Time `json:"created_at"`
+ UpdatedAt *time.Time `json:"updated_at,omitempty"`
+
+ Version TemplateVersion `json:"-" gorm:"foreignKey:VersionID;constraint:OnDelete:CASCADE"`
+}
diff --git a/internal/models/template_version.go b/internal/models/template_version.go
new file mode 100644
index 0000000..1636534
--- /dev/null
+++ b/internal/models/template_version.go
@@ -0,0 +1,38 @@
+/*
+ * 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"
+
+type TemplateVersion struct {
+ ID uint `json:"id" gorm:"primaryKey"`
+ TemplateID uint `json:"template_id" gorm:"index;not null"`
+ Version int `json:"version" gorm:"not null"`
+ StyleSheetID *uint `json:"stylesheet_id,omitempty" gorm:"index"`
+ SampleData string `json:"sample_data"`
+ CreatedAt time.Time `json:"created_at"`
+
+ StyleSheet *StyleSheet `json:"stylesheet,omitempty" gorm:"foreignKey:StyleSheetID;constraint:OnDelete:SET NULL"`
+}
diff --git a/internal/models/user.go b/internal/models/user.go
new file mode 100644
index 0000000..45773ed
--- /dev/null
+++ b/internal/models/user.go
@@ -0,0 +1,52 @@
+/*
+ * 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"
+
+type UserRole string
+
+const (
+ UserRoleAdmin UserRole = "admin"
+ UserRoleUser UserRole = "user"
+)
+
+type User struct {
+ ID uint `json:"id" gorm:"primaryKey"`
+ Name string `json:"name" gorm:"not null;default:''"`
+ Email string `json:"email" gorm:"uniqueIndex;not null"`
+ PasswordHash string `json:"-" gorm:"not null"`
+ Role UserRole `json:"role" gorm:"default:user;not null"`
+ TwoFactorSecret string `json:"-" gorm:"type:text"`
+ TwoFactorEnabled bool `json:"two_factor_enabled" gorm:"default:false"`
+ Active bool `json:"active" gorm:"default:true;not null"`
+ RequireVerifiedDomain bool `json:"require_verified_domain" gorm:"default:false"`
+ CreatedAt time.Time `json:"created_at"`
+ LastLoginAt *time.Time `json:"last_login_at"`
+}
+
+func (u *User) IsAdmin() bool {
+ return u.Role == UserRoleAdmin
+}
diff --git a/internal/models/user_setting.go b/internal/models/user_setting.go
new file mode 100644
index 0000000..13b6a3b
--- /dev/null
+++ b/internal/models/user_setting.go
@@ -0,0 +1,45 @@
+/*
+ * 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"
+
+// UserSetting stores per-user preferences. Each user has at most one row.
+type UserSetting struct {
+ ID uint `json:"id" gorm:"primaryKey"`
+ UserID uint `json:"user_id" gorm:"uniqueIndex;not null"`
+ Timezone string `json:"timezone" gorm:"default:UTC"`
+ DefaultSenderName string `json:"default_sender_name"`
+ DefaultSenderEmail string `json:"default_sender_email"`
+ EmailNotifications bool `json:"email_notifications" gorm:"default:true"`
+ NotificationEmail string `json:"notification_email"`
+ WebhookRetryCount int `json:"webhook_retry_count" gorm:"default:3"`
+ DefaultTemplateID *uint `json:"default_template_id"`
+ APIKeyExpiryDays int `json:"api_key_expiry_days" gorm:"default:90"`
+ BounceAutoSuppress bool `json:"bounce_auto_suppress" gorm:"default:true"`
+ DailyReport bool `json:"daily_report" gorm:"default:false"`
+ CreatedAt time.Time `json:"created_at"`
+ UpdatedAt time.Time `json:"updated_at"`
+}
diff --git a/internal/models/webhook.go b/internal/models/webhook.go
new file mode 100644
index 0000000..d65de2a
--- /dev/null
+++ b/internal/models/webhook.go
@@ -0,0 +1,43 @@
+/*
+ * 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"
+
+ "github.com/lib/pq"
+)
+
+type Webhook struct {
+ ID uint `json:"id" gorm:"primaryKey"`
+ UserID uint `json:"user_id" gorm:"index;not null"`
+ URL string `json:"url" gorm:"not null"`
+ Events pq.StringArray `json:"events" gorm:"type:text[];not null"`
+ Filters pq.StringArray `json:"filters" gorm:"type:text[]"`
+ Secret string `json:"secret,omitempty" gorm:"type:varchar(64);not null;default:''"`
+ CreatedAt time.Time `json:"created_at"`
+
+ User User `json:"-" gorm:"foreignKey:UserID"`
+}
diff --git a/internal/models/webhook_delivery.go b/internal/models/webhook_delivery.go
new file mode 100644
index 0000000..210b3ec
--- /dev/null
+++ b/internal/models/webhook_delivery.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"
+
+// WebhookDeliveryStatus represents the outcome of a webhook delivery attempt.
+type WebhookDeliveryStatus string
+
+const (
+ WebhookDeliverySuccess WebhookDeliveryStatus = "success"
+ WebhookDeliveryFailed WebhookDeliveryStatus = "failed"
+)
+
+// WebhookDelivery records the result of delivering a webhook notification.
+type WebhookDelivery struct {
+ ID uint `json:"id" gorm:"primaryKey"`
+ WebhookID uint `json:"webhook_id" gorm:"index;not null"`
+ UserID uint `json:"user_id" gorm:"index;not null"`
+ Event string `json:"event" gorm:"not null"`
+ Status WebhookDeliveryStatus `json:"status" gorm:"type:varchar(16);not null;index"`
+ HTTPStatusCode int `json:"http_status_code"`
+ ErrorMessage string `json:"error_message,omitempty"`
+ Attempt int `json:"attempt" gorm:"not null;default:1"`
+ CreatedAt time.Time `json:"created_at"`
+
+ Webhook Webhook `json:"-" gorm:"foreignKey:WebhookID"`
+ User User `json:"-" gorm:"foreignKey:UserID"`
+}
diff --git a/internal/routes/admin_routes.go b/internal/routes/admin_routes.go
new file mode 100644
index 0000000..517f6cf
--- /dev/null
+++ b/internal/routes/admin_routes.go
@@ -0,0 +1,377 @@
+/*
+ * 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 routes
+
+import (
+ "net/http"
+
+ "github.com/jkaninda/okapi"
+ cronpkg "github.com/jkaninda/posta/internal/cron"
+ "github.com/jkaninda/posta/internal/dto"
+ "github.com/jkaninda/posta/internal/handlers"
+ "github.com/jkaninda/posta/internal/models"
+)
+
+// adminRoutes returns route definitions for admin endpoints.
+func (r *Router) adminRoutes() []okapi.RouteDefinition {
+ adminGroup := r.v1.Group("/admin", r.mw.jwtAdminAuth.Middleware).WithTags([]string{"Admin"})
+ adminGroup.WithBearerAuth()
+
+ routes := []okapi.RouteDefinition{
+ // ==================== Users ====================
+ {
+ Method: http.MethodPost,
+ Path: "/users",
+ Handler: okapi.H(r.h.admin.CreateUser),
+ Group: adminGroup,
+ Summary: "Create a new user",
+ Description: "Create a new user account (admin only)",
+ Request: &handlers.AdminCreateUserRequest{},
+ Options: []okapi.RouteOption{
+ okapi.DocResponse(201, &dto.Response[models.User]{}),
+ okapi.DocErrorResponse(409, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/users",
+ Handler: okapi.H(r.h.admin.ListUsers),
+ Group: adminGroup,
+ Summary: "List all users",
+ Request: &handlers.ListRequest{},
+ Response: &dto.PageableResponse[models.User]{},
+ },
+ {
+ Method: http.MethodPut,
+ Path: "/users/{id:int}",
+ Handler: okapi.H(r.h.admin.UpdateUser),
+ Group: adminGroup,
+ Summary: "Update user",
+ Description: "Update a user's name, email, and/or role",
+ Request: &handlers.AdminUpdateUserRequest{},
+ Response: &dto.Response[models.User]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "User ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ okapi.DocErrorResponse(409, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/users/{id:int}/metrics",
+ Handler: okapi.H(r.h.admin.UserMetrics),
+ Group: adminGroup,
+ Summary: "Get user metrics",
+ Description: "Returns detailed metrics for a specific user",
+ Response: &dto.Response[handlers.UserDetailMetrics]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "User ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodDelete,
+ Path: "/users/{id:int}",
+ Handler: okapi.H(r.h.admin.DeleteUser),
+ Group: adminGroup,
+ Tags: []string{"Admin"},
+ Summary: "Delete user",
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "User ID"),
+ okapi.DocResponse(204, nil),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodDelete,
+ Path: "/users/{id:int}/2fa",
+ Handler: okapi.H(r.h.admin.Disable2FA),
+ Group: adminGroup,
+ Summary: "Disable 2FA for user",
+ Description: "Disable two-factor authentication for a user (admin only)",
+ Response: &dto.Response[okapi.M]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "User ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+
+ // ==================== All API Keys ====================
+ {
+ Method: http.MethodGet,
+ Path: "/api-keys",
+ Handler: okapi.H(r.h.admin.ListAllAPIKeys),
+ Group: adminGroup,
+ Summary: "List all API keys",
+ Request: &handlers.ListRequest{},
+ Response: &dto.PageableResponse[models.APIKey]{},
+ },
+ {
+ Method: http.MethodDelete,
+ Path: "/api-keys/{id:int}",
+ Handler: okapi.H(r.h.admin.RevokeAPIKey),
+ Group: adminGroup,
+ Summary: "Revoke any API key",
+ Response: &dto.Response[dto.MessageData]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "API key ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+
+ // ==================== All Emails ====================
+ {
+ Method: http.MethodGet,
+ Path: "/emails",
+ Handler: okapi.H(r.h.admin.ListAllEmails),
+ Group: adminGroup,
+ Summary: "List all emails",
+ Description: "List all emails across all users",
+ Request: &handlers.ListRequest{},
+ Response: &dto.PageableResponse[models.Email]{},
+ },
+
+ // ==================== Events ====================
+ {
+ Method: http.MethodGet,
+ Path: "/events",
+ Handler: okapi.H(r.h.event.List),
+ Group: adminGroup,
+ Summary: "List events",
+ Description: "List platform activity and system events with optional category filter",
+ Request: &handlers.ListEventsRequest{},
+ Response: &dto.PageableResponse[models.Event]{},
+ },
+
+ // ==================== Metrics & Analytics ====================
+ {
+ Method: http.MethodGet,
+ Path: "/metrics",
+ Handler: r.h.admin.Metrics,
+ Group: adminGroup,
+ Summary: "Platform metrics",
+ Description: "Returns platform-wide metrics: users, emails, bounces, suppressions, API keys",
+ Response: &dto.Response[handlers.PlatformMetrics]{},
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/analytics",
+ Handler: okapi.H(r.h.analytics.AdminAnalytics),
+ Group: adminGroup,
+ Summary: "Platform analytics",
+ Description: "Returns platform-wide daily email counts and status breakdown",
+ Request: &handlers.AnalyticsRequest{},
+ Response: &dto.Response[handlers.AnalyticsResponse]{},
+ },
+
+ // ==================== Platform Settings ====================
+ {
+ Method: http.MethodGet,
+ Path: "/settings",
+ Handler: r.h.setting.GetSettings,
+ Group: adminGroup,
+ Summary: "Get platform settings",
+ Response: &dto.Response[[]models.Setting]{},
+ },
+ {
+ Method: http.MethodPut,
+ Path: "/settings",
+ Handler: okapi.H(r.h.setting.UpdateSettings),
+ Group: adminGroup,
+ Summary: "Update platform settings",
+ Request: &handlers.UpdateSettingsRequest{},
+ Response: &dto.Response[[]models.Setting]{},
+ },
+
+ // ==================== Shared SMTP Servers ====================
+ {
+ Method: http.MethodPost,
+ Path: "/servers",
+ Handler: okapi.H(r.h.server.Create),
+ Group: adminGroup,
+ Summary: "Create shared SMTP server",
+ Description: "Add a new shared SMTP server to the pool",
+ Request: &handlers.CreateServerRequest{},
+ Options: []okapi.RouteOption{
+ okapi.DocResponse(201, &dto.Response[models.Server]{}),
+ },
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/servers",
+ Handler: okapi.H(r.h.server.List),
+ Group: adminGroup,
+ Summary: "List shared SMTP servers",
+ Request: &handlers.ListRequest{},
+ Response: &dto.PageableResponse[models.Server]{},
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/servers/{id:int}",
+ Handler: okapi.H(r.h.server.Get),
+ Group: adminGroup,
+ Summary: "Get shared SMTP server",
+ Response: &dto.Response[models.Server]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Server ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodPut,
+ Path: "/servers/{id:int}",
+ Handler: okapi.H(r.h.server.Update),
+ Group: adminGroup,
+ Summary: "Update shared SMTP server",
+ Request: &handlers.UpdateServerRequest{},
+ Response: &dto.Response[models.Server]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Server ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodDelete,
+ Path: "/servers/{id:int}",
+ Handler: okapi.H(r.h.server.Delete),
+ Group: adminGroup,
+ Tags: []string{"Admin"},
+ Summary: "Delete shared SMTP server",
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Server ID"),
+ okapi.DocResponse(204, nil),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/servers/{id:int}/enable",
+ Handler: okapi.H(r.h.server.Enable),
+ Group: adminGroup,
+ Summary: "Enable shared SMTP server",
+ Response: &dto.Response[models.Server]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Server ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/servers/{id:int}/disable",
+ Handler: okapi.H(r.h.server.Disable),
+ Group: adminGroup,
+ Summary: "Disable shared SMTP server",
+ Response: &dto.Response[models.Server]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Server ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/servers/{id:int}/test",
+ Handler: okapi.H(r.h.server.Test),
+ Group: adminGroup,
+ Summary: "Test shared SMTP server connection",
+ Response: &dto.Response[dto.MessageData]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Server ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ }
+
+ // Cron jobs (only if cron manager is configured)
+ if r.h.cron != nil {
+ routes = append(routes, okapi.RouteDefinition{
+ Method: http.MethodGet,
+ Path: "/jobs",
+ Handler: r.h.cron.List,
+ Group: adminGroup,
+ Summary: "List scheduled jobs",
+ Description: "Returns all registered cron jobs with their schedule and last execution status.",
+ Response: &dto.Response[[]cronpkg.JobStatus]{},
+ })
+ }
+
+ return routes
+}
+
+// adminSSERoutes returns route definitions for admin SSE (Server-Sent Events) endpoints.
+func (r *Router) adminSSERoutes() []okapi.RouteDefinition {
+ adminSSE := r.v1.Group("/admin", r.mw.jwtAdminQueryAuth.Middleware).WithTags([]string{"Admin"})
+
+ return []okapi.RouteDefinition{
+ {
+ Method: http.MethodGet,
+ Path: "/events/stream",
+ Handler: r.h.event.Stream,
+ Group: adminSSE,
+ Summary: "Stream events (SSE)",
+ Description: "Real-time event stream via Server-Sent Events. Pass JWT token as ?token= query parameter.",
+ Options: []okapi.RouteOption{okapi.DocHide()},
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/workers/stream",
+ Handler: r.h.admin.WorkerStream,
+ Group: adminSSE,
+ Summary: "Stream worker status (SSE)",
+ Description: "Real-time worker count and details via Server-Sent Events. Pass JWT token as ?token= query parameter.",
+ Options: []okapi.RouteOption{okapi.DocHide()},
+ },
+ }
+}
+
+// devRoutes returns route definitions for development-only endpoints.
+func (r *Router) devRoutes() []okapi.RouteDefinition {
+ devGroup := r.v1.Group("/dev").WithTags([]string{"Dev"})
+
+ return []okapi.RouteDefinition{
+ {
+ Method: http.MethodGet,
+ Path: "/emails",
+ Handler: okapi.H(r.h.email.DevList),
+ Group: devGroup,
+ Summary: "List all emails (dev)",
+ Description: "List all stored emails across all users. Only available in development mode.",
+ Request: &handlers.ListRequest{},
+ Response: &dto.PageableResponse[models.Email]{},
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/emails/{id}",
+ Handler: r.h.email.DevGet,
+ Group: devGroup,
+ Summary: "Get email (dev)",
+ Description: "Get email details by UUID. Only available in development mode.",
+ Response: &dto.Response[models.Email]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "string", "Email UUID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ }
+}
diff --git a/internal/routes/auth_routes.go b/internal/routes/auth_routes.go
new file mode 100644
index 0000000..bc75135
--- /dev/null
+++ b/internal/routes/auth_routes.go
@@ -0,0 +1,179 @@
+/*
+ * 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 routes
+
+import (
+ "net/http"
+
+ "github.com/jkaninda/okapi"
+ "github.com/jkaninda/posta/internal/dto"
+ "github.com/jkaninda/posta/internal/handlers"
+ "github.com/jkaninda/posta/internal/services/email"
+)
+
+// healthRoutes returns route definitions for health check endpoints.
+func (r *Router) healthRoutes() []okapi.RouteDefinition {
+ return []okapi.RouteDefinition{
+ {
+ Method: http.MethodGet,
+ Path: "/healthz",
+ Handler: r.h.health.Healthz,
+ Tags: []string{"Health"},
+ Summary: "Liveness probe",
+ Response: &handlers.HealthResponse{},
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/readyz",
+ Handler: r.h.health.Readyz,
+ Tags: []string{"Health"},
+ Summary: "Readiness probe",
+ Response: &handlers.ReadyResponse{},
+ },
+ }
+}
+
+// infoRoute returns the route definition for the application info endpoint.
+func (r *Router) infoRoute() okapi.RouteDefinition {
+ return okapi.RouteDefinition{
+ Method: http.MethodGet,
+ Path: "/info",
+ Handler: handlers.Info,
+ Group: r.v1,
+ Tags: []string{"Info"},
+ Summary: "Application info",
+ Description: "Returns app name, version, and commit ID",
+ Response: &dto.Response[handlers.AppInfo]{},
+ }
+}
+
+// authRoutes returns route definitions for authentication endpoints.
+func (r *Router) authRoutes() []okapi.RouteDefinition {
+ authGroup := r.v1.Group("/auth", r.mw.loginLimiter).WithTags([]string{"Auth"})
+
+ return []okapi.RouteDefinition{
+ {
+ Method: http.MethodPost,
+ Path: "/login",
+ Handler: okapi.H(r.h.user.Login),
+ Group: authGroup,
+ Summary: "Login",
+ Description: "Authenticate with email and password to receive a JWT token",
+ Request: &handlers.LoginRequest{},
+ Response: &dto.Response[handlers.AuthResponse]{},
+ Options: []okapi.RouteOption{
+ okapi.DocErrorResponse(401, &dto.ErrorResponseBody{}),
+ okapi.DocErrorResponse(429, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/register",
+ Handler: okapi.H(r.h.user.Register),
+ Group: authGroup,
+ Summary: "Register",
+ Description: "Create a new user account (when registration is enabled)",
+ Request: &handlers.RegisterRequest{},
+ Options: []okapi.RouteOption{
+ okapi.DocResponse(201, &dto.Response[handlers.AuthResponse]{}),
+ okapi.DocErrorResponse(403, &dto.ErrorResponseBody{}),
+ okapi.DocErrorResponse(409, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/registration-status",
+ Handler: r.h.user.RegistrationStatus,
+ Group: authGroup,
+ Summary: "Registration status",
+ Description: "Check whether user self-registration is enabled",
+ Response: &dto.Response[any]{},
+ },
+ }
+}
+
+// apiAuthRoutes returns route definitions for API-key authenticated endpoints.
+func (r *Router) apiAuthRoutes() []okapi.RouteDefinition {
+ apiAuth := r.v1.Group("", r.mw.apiKey).WithTags([]string{"Emails"})
+ apiAuth.WithBearerAuth()
+
+ return []okapi.RouteDefinition{
+ {
+ Method: http.MethodPost,
+ Path: "/emails/send",
+ Handler: okapi.H(r.h.email.Send),
+ Group: apiAuth,
+ Summary: "Send an email",
+ Description: "Send an email via configured SMTP server. Supports file attachments via base64-encoded content.",
+ Request: &handlers.SendEmailRequest{},
+ Response: &dto.Response[email.SendResponse]{},
+ Options: []okapi.RouteOption{
+ okapi.DocErrorResponse(401, &dto.ErrorResponseBody{}),
+ okapi.DocErrorResponse(429, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/emails/send-template",
+ Handler: okapi.H(r.h.email.SendWithTemplate),
+ Group: apiAuth,
+ Summary: "Send email using template",
+ Description: "Send an email using a pre-defined template with variable substitution. Supports attachments.",
+ Request: &handlers.SendTemplateEmailRequest{},
+ Response: &dto.Response[email.SendResponse]{},
+ Options: []okapi.RouteOption{
+ okapi.DocErrorResponse(401, &dto.ErrorResponseBody{}),
+ okapi.DocErrorResponse(429, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/emails/batch",
+ Handler: okapi.H(r.h.email.SendBatch),
+ Group: apiAuth,
+ Summary: "Send batch emails",
+ Description: "Send emails to multiple recipients using a template with per-recipient variable substitution.",
+ Request: &handlers.SendBatchEmailRequest{},
+ Response: &dto.Response[email.BatchResponse]{},
+ Options: []okapi.RouteOption{
+ okapi.DocErrorResponse(401, &dto.ErrorResponseBody{}),
+ okapi.DocErrorResponse(429, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/emails/{id}/status",
+ Handler: okapi.H(r.h.email.GetStatus),
+ Group: apiAuth,
+ Summary: "Get email delivery status",
+ Description: "Returns a lightweight status view for polling email delivery progress. Only the email owner can access this.",
+ Response: &dto.Response[handlers.EmailStatusResponse]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "string", "Email UUID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ }
+}
diff --git a/internal/routes/routes.go b/internal/routes/routes.go
new file mode 100644
index 0000000..d5fcda3
--- /dev/null
+++ b/internal/routes/routes.go
@@ -0,0 +1,261 @@
+/*
+ * 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 routes
+
+import (
+ "context"
+ "net/http"
+ "os"
+ "path/filepath"
+ "strings"
+ "time"
+
+ "github.com/hibiken/asynq"
+ "github.com/jkaninda/okapi"
+ "github.com/jkaninda/posta/internal/config"
+ cronpkg "github.com/jkaninda/posta/internal/cron"
+ "github.com/jkaninda/posta/internal/handlers"
+ "github.com/jkaninda/posta/internal/metrics"
+ "github.com/jkaninda/posta/internal/middlewares"
+ "github.com/jkaninda/posta/internal/services/audit"
+ "github.com/jkaninda/posta/internal/services/auth"
+ "github.com/jkaninda/posta/internal/services/cache"
+ "github.com/jkaninda/posta/internal/services/email"
+ "github.com/jkaninda/posta/internal/services/eventbus"
+ "github.com/jkaninda/posta/internal/services/ratelimit"
+ "github.com/jkaninda/posta/internal/services/seeder"
+ "github.com/jkaninda/posta/internal/services/settings"
+ "github.com/jkaninda/posta/internal/services/webhook"
+ "github.com/jkaninda/posta/internal/services/workermon"
+ "github.com/jkaninda/posta/internal/storage/repositories"
+ "github.com/jkaninda/posta/internal/worker"
+ "github.com/redis/go-redis/v9"
+ "gorm.io/gorm"
+)
+
+type Router struct {
+ app *okapi.Okapi
+ cfg *config.Config
+ v1 *okapi.Group
+ mw routerMiddleware
+ h routerHandlers
+}
+
+type routerMiddleware struct {
+ jwtAuth okapi.JWTAuth
+ jwtAdminAuth okapi.JWTAuth
+ jwtAdminQueryAuth okapi.JWTAuth
+ loginLimiter okapi.Middleware
+ apiKey okapi.Middleware
+}
+
+type routerHandlers struct {
+ health *handlers.HealthHandler
+ user *handlers.UserHandler
+ email *handlers.EmailHandler
+ apiKey *handlers.APIKeyHandler
+ template *handlers.TemplateHandler
+ version *handlers.TemplateVersionHandler
+ localization *handlers.TemplateLocalizationHandler
+ language *handlers.LanguageHandler
+ stylesheet *handlers.StyleSheetHandler
+ smtp *handlers.SMTPHandler
+ webhook *handlers.WebhookHandler
+ webhookDelivery *handlers.WebhookDeliveryHandler
+ dashboard *handlers.DashboardHandler
+ domain *handlers.DomainHandler
+ bounce *handlers.BounceHandler
+ suppression *handlers.SuppressionHandler
+ contact *handlers.ContactHandler
+ contactList *handlers.ContactListHandler
+ admin *handlers.AdminHandler
+ server *handlers.ServerHandler
+ event *handlers.EventHandler
+ analytics *handlers.AnalyticsHandler
+ setting *handlers.SettingHandler
+ userSetting *handlers.UserSettingHandler
+ cron *handlers.CronHandler
+}
+
+func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *config.Config, producer *worker.Producer, cronManager *cronpkg.Manager, ctx context.Context) {
+ // Repositories
+ userRepo := repositories.NewUserRepository(db)
+ apiKeyRepo := repositories.NewAPIKeyRepository(db)
+ emailRepo := repositories.NewEmailRepository(db)
+ templateRepo := repositories.NewTemplateRepository(db)
+ smtpRepo := repositories.NewSMTPRepository(db)
+ serverRepo := repositories.NewServerRepository(db)
+ webhookRepo := repositories.NewWebhookRepository(db)
+ domainRepo := repositories.NewDomainRepository(db)
+ bounceRepo := repositories.NewBounceRepository(db)
+ suppressionRepo := repositories.NewSuppressionRepository(db)
+ stylesheetRepo := repositories.NewStyleSheetRepository(db)
+ versionRepo := repositories.NewTemplateVersionRepository(db)
+ localizationRepo := repositories.NewTemplateLocalizationRepository(db)
+ languageRepo := repositories.NewLanguageRepository(db)
+ contactRepo := repositories.NewContactRepository(db)
+ contactListRepo := repositories.NewContactListRepository(db)
+ eventRepo := repositories.NewEventRepository(db)
+ settingRepo := repositories.NewSettingRepository(db)
+ userSettingRepo := repositories.NewUserSettingRepository(db)
+
+ // Services
+ bus := eventbus.New(eventRepo)
+ auditLogger := audit.NewLogger(bus)
+ apiKeyService := auth.NewAPIKeyService(apiKeyRepo)
+ settingsProvider := settings.NewProvider(settingRepo)
+ limiter := ratelimit.NewRedisLimiter(redisClient, cfg.RateLimitHourly, cfg.RateLimitDaily)
+ limiter.SetSettings(settingsProvider)
+ webhookDeliveryRepo := repositories.NewWebhookDeliveryRepository(db)
+ dispatcher := webhook.NewDispatcher(webhookRepo)
+ dispatcher.SetDeliveryRepo(webhookDeliveryRepo)
+ dispatcher.SetConfig(webhook.Config{
+ MaxRetries: cfg.WebhookMaxRetries,
+ Timeout: time.Duration(cfg.WebhookTimeoutSecs) * time.Second,
+ })
+ dispatcher.OnDeliverySuccess(func() { metrics.IncrementWebhookDelivery("success") })
+ dispatcher.OnDeliveryFailed(func() { metrics.IncrementWebhookDelivery("failed") })
+ dispatcher.OnDeliveryDone(metrics.ObserveWebhookDeliveryDuration)
+ emailService := email.NewService(emailRepo, smtpRepo, templateRepo, suppressionRepo, limiter, dispatcher, cfg.DevMode)
+ emailService.SetSettings(settingsProvider)
+ emailService.SetVersionRepos(versionRepo, localizationRepo)
+ emailService.SetContactRepo(contactRepo)
+ emailService.SetDomainVerification(domainRepo, userRepo)
+ if producer != nil {
+ emailService.SetEnqueuer(producer)
+ }
+ emailService.OnSent(metrics.IncrementEmailSent)
+ emailService.OnFailed(metrics.IncrementEmailFailed)
+ emailService.OnQueued(metrics.IncrementEmailQueued)
+
+ // Cache
+ statsCache := cache.New(redisClient)
+
+ // Handlers
+ userSeeder := seeder.New(templateRepo, stylesheetRepo, versionRepo, localizationRepo, languageRepo)
+ userHandler := handlers.NewUserHandler(userRepo, cfg.JWTSecret, userSeeder, bus)
+ userHandler.SetSettings(settingsProvider)
+ inspector := asynq.NewInspector(asynq.RedisClientOpt{
+ Addr: cfg.Redis.Addr,
+ Password: cfg.Redis.Password,
+ })
+
+ // Seed default platform settings
+ go seeder.SeedDefaultSettings(settingRepo)
+
+ // Start worker connection monitor
+ wm := workermon.New(inspector, bus, 15*time.Second)
+ wm.Start(ctx)
+
+ r := &Router{
+ app: app,
+ cfg: cfg,
+ v1: app.Group("/api/v1"),
+ mw: routerMiddleware{
+ jwtAuth: middlewares.JWTAuth(cfg),
+ jwtAdminAuth: middlewares.JWTAdminAuth(cfg),
+ jwtAdminQueryAuth: middlewares.JWTAdminQueryAuth(cfg),
+ loginLimiter: middlewares.LoginRateLimitMiddleware(limiter),
+ apiKey: middlewares.APIKeyAuthMiddleware(apiKeyService, userRepo, apiKeyRepo),
+ },
+ h: routerHandlers{
+ health: handlers.NewHealthHandler(db, redisClient),
+ user: userHandler,
+ email: handlers.NewEmailHandler(emailService, emailRepo, bus, statsCache),
+ apiKey: handlers.NewAPIKeyHandler(apiKeyService, apiKeyRepo, userSettingRepo, auditLogger),
+ template: handlers.NewTemplateHandler(templateRepo, stylesheetRepo, versionRepo, localizationRepo, emailService),
+ version: handlers.NewTemplateVersionHandler(templateRepo, versionRepo),
+ localization: handlers.NewTemplateLocalizationHandler(templateRepo, versionRepo, localizationRepo, stylesheetRepo),
+ language: handlers.NewLanguageHandler(languageRepo),
+ stylesheet: handlers.NewStyleSheetHandler(stylesheetRepo),
+ smtp: handlers.NewSMTPHandler(smtpRepo, domainRepo, auditLogger),
+ webhook: handlers.NewWebhookHandler(webhookRepo, auditLogger),
+ webhookDelivery: handlers.NewWebhookDeliveryHandler(webhookDeliveryRepo),
+ dashboard: handlers.NewDashboardHandler(db, statsCache, webhookDeliveryRepo),
+ domain: handlers.NewDomainHandler(domainRepo),
+ bounce: handlers.NewBounceHandler(bounceRepo, suppressionRepo, emailRepo),
+ suppression: handlers.NewSuppressionHandler(suppressionRepo),
+ contact: handlers.NewContactHandler(contactRepo, suppressionRepo),
+ contactList: handlers.NewContactListHandler(contactListRepo),
+ admin: handlers.NewAdminHandler(db, statsCache, userRepo, apiKeyRepo, emailRepo, webhookDeliveryRepo, inspector, bus, userSeeder, cfg.EmbeddedWorker),
+ server: handlers.NewServerHandler(serverRepo, auditLogger),
+ event: handlers.NewEventHandler(eventRepo, bus),
+ analytics: handlers.NewAnalyticsHandler(repositories.NewAnalyticsRepository(db), statsCache),
+ setting: handlers.NewSettingHandler(settingRepo, auditLogger),
+ userSetting: handlers.NewUserSettingHandler(userSettingRepo),
+ },
+ }
+
+ if cronManager != nil {
+ r.h.cron = handlers.NewCronHandler(cronManager)
+ }
+
+ r.registerRoutes()
+}
+
+func (r *Router) registerRoutes() {
+ // Request ID middleware
+ r.app.Use(okapi.RequestID())
+
+ // Prometheus metrics
+ if r.cfg.MetricsEnabled {
+ r.app.Use(metrics.PrometheusMiddleware())
+ r.app.Get("/metrics", metrics.MetricsHandler(), okapi.DocHide())
+ }
+
+ // Register all route definitions
+ r.app.Register(r.healthRoutes()...)
+ r.app.Register(r.infoRoute())
+ r.app.Register(r.authRoutes()...)
+ r.app.Register(r.apiAuthRoutes()...)
+ r.app.Register(r.userRoutes()...)
+ r.app.Register(r.adminRoutes()...)
+ r.app.Register(r.adminSSERoutes()...)
+
+ if r.cfg.DevMode {
+ r.app.Register(r.devRoutes()...)
+ }
+
+ // Dashboard UI (static files + SPA fallback)
+ webDir := r.cfg.WebDir
+ if info, err := os.Stat(webDir); err == nil && info.IsDir() {
+ r.app.Static("/assets", filepath.Join(webDir, "assets"))
+
+ indexPath := filepath.Join(webDir, "index.html")
+ r.app.NoRoute(func(c *okapi.Context) error {
+ path := c.Request().URL.Path
+ if strings.HasPrefix(path, "/api/v1/") || strings.HasPrefix(path, "/healthz") || strings.HasPrefix(path, "/readyz") || strings.HasPrefix(path, "/metrics") || strings.HasPrefix(path, "/docs") {
+ return c.AbortNotFound("not found")
+ }
+ filePath := filepath.Join(webDir, filepath.Clean(path))
+ if stat, err := os.Stat(filePath); err == nil && !stat.IsDir() {
+ http.ServeFile(c.ResponseWriter(), c.Request(), filePath)
+ return nil
+ }
+ http.ServeFile(c.ResponseWriter(), c.Request(), indexPath)
+ return nil
+ })
+ }
+}
diff --git a/internal/routes/user_routes.go b/internal/routes/user_routes.go
new file mode 100644
index 0000000..3a02d23
--- /dev/null
+++ b/internal/routes/user_routes.go
@@ -0,0 +1,963 @@
+/*
+ * 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 routes
+
+import (
+ "net/http"
+
+ "github.com/jkaninda/okapi"
+ "github.com/jkaninda/posta/internal/dto"
+ "github.com/jkaninda/posta/internal/handlers"
+ "github.com/jkaninda/posta/internal/models"
+ "github.com/jkaninda/posta/internal/services/email"
+)
+
+// userRoutes returns route definitions for all authenticated user endpoints.
+func (r *Router) userRoutes() []okapi.RouteDefinition {
+ userGroup := r.v1.Group("/users/me", r.mw.jwtAuth.Middleware).WithTags([]string{"User"})
+ userGroup.WithBearerAuth()
+
+ return []okapi.RouteDefinition{
+ // ==================== Profile ====================
+ {
+ Method: http.MethodGet,
+ Path: "",
+ Handler: r.h.user.Me,
+ Group: userGroup,
+ Summary: "Get current user profile",
+ Response: &dto.Response[handlers.UserProfile]{},
+ },
+ {
+ Method: http.MethodPut,
+ Path: "",
+ Handler: okapi.H(r.h.user.UpdateProfile),
+ Group: userGroup,
+ Summary: "Update profile",
+ Description: "Update the current user's profile",
+ Request: &handlers.UpdateProfileRequest{},
+ Response: &dto.Response[handlers.UserProfile]{},
+ },
+ {
+ Method: http.MethodPut,
+ Path: "/password",
+ Handler: okapi.H(r.h.user.ChangePassword),
+ Group: userGroup,
+ Summary: "Change password",
+ Description: "Change the current user's password",
+ Request: &handlers.ChangePasswordRequest{},
+ Response: &dto.Response[dto.MessageData]{},
+ },
+
+ // ==================== 2FA ====================
+ {
+ Method: http.MethodPost,
+ Path: "/2fa/setup",
+ Handler: r.h.user.Setup2FA,
+ Group: userGroup,
+ Summary: "Setup 2FA",
+ Description: "Generate a TOTP secret for enabling 2FA. Returns secret and otpauth URL for QR code.",
+ Response: &dto.Response[handlers.Enable2FAResponse]{},
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/2fa/verify",
+ Handler: okapi.H(r.h.user.Verify2FA),
+ Group: userGroup,
+ Summary: "Verify and enable 2FA",
+ Description: "Verify a TOTP code to confirm 2FA setup",
+ Request: &handlers.Verify2FARequest{},
+ Response: &dto.Response[any]{},
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/2fa/disable",
+ Handler: okapi.H(r.h.user.Disable2FA),
+ Group: userGroup,
+ Summary: "Disable 2FA",
+ Description: "Disable 2FA after verifying a TOTP code",
+ Request: &handlers.Disable2FARequest{},
+ Response: &dto.Response[any]{},
+ },
+
+ // ==================== Dashboard & Analytics ====================
+ {
+ Method: http.MethodGet,
+ Path: "/dashboard/stats",
+ Handler: r.h.dashboard.Stats,
+ Group: userGroup,
+ Summary: "Get dashboard statistics",
+ Description: "Returns email sending statistics for the authenticated user",
+ Response: &dto.Response[handlers.DashboardStats]{},
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/analytics",
+ Handler: okapi.H(r.h.analytics.UserAnalytics),
+ Group: userGroup,
+ Summary: "Email analytics",
+ Description: "Returns daily email counts and status breakdown for the authenticated user",
+ Request: &handlers.AnalyticsRequest{},
+ Response: &dto.Response[handlers.AnalyticsResponse]{},
+ },
+
+ // ==================== Email Logs ====================
+ {
+ Method: http.MethodGet,
+ Path: "/emails",
+ Handler: okapi.H(r.h.email.List),
+ Group: userGroup,
+ Summary: "List emails",
+ Description: "List sent emails with pagination",
+ Request: &handlers.ListRequest{},
+ Response: &dto.PageableResponse[models.Email]{},
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/emails/{id}",
+ Handler: okapi.H(r.h.email.Get),
+ Group: userGroup,
+ Summary: "Get email details",
+ Response: &dto.Response[models.Email]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "string", "Email UUID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/emails/{id}/status",
+ Handler: okapi.H(r.h.email.GetStatus),
+ Group: userGroup,
+ Summary: "Get email delivery status",
+ Description: "Returns a lightweight status view for polling email delivery progress. Only the email owner can access this.",
+ Response: &dto.Response[handlers.EmailStatusResponse]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "string", "Email UUID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/emails/{id}/retry",
+ Handler: okapi.H(r.h.email.Retry),
+ Group: userGroup,
+ Summary: "Retry failed email",
+ Description: "Re-enqueue a failed email for another delivery attempt",
+ Response: &dto.Response[email.SendResponse]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "string", "Email UUID"),
+ okapi.DocErrorResponse(400, &dto.ErrorResponseBody{}),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+
+ // ==================== API Keys ====================
+ {
+ Method: http.MethodPost,
+ Path: "/api-keys",
+ Handler: okapi.H(r.h.apiKey.Create),
+ Group: userGroup,
+ Summary: "Create API key",
+ Description: "Generate a new API key. The raw key is only shown once in the response.",
+ Request: &handlers.CreateAPIKeyRequest{},
+ Options: []okapi.RouteOption{
+ okapi.DocResponse(201, &dto.Response[dto.APIKeyCreatedData]{}),
+ },
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/api-keys",
+ Handler: okapi.H(r.h.apiKey.List),
+ Group: userGroup,
+ Summary: "List API keys",
+ Request: &handlers.ListRequest{},
+ Response: &dto.PageableResponse[models.APIKey]{},
+ },
+ {
+ Method: http.MethodPut,
+ Path: "/api-keys/{id:int}/revoke",
+ Handler: okapi.H(r.h.apiKey.Revoke),
+ Group: userGroup,
+ Summary: "Revoke API key",
+ Response: &dto.Response[dto.MessageData]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "API key ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodDelete,
+ Path: "/api-keys/{id:int}",
+ Handler: okapi.H(r.h.apiKey.Delete),
+ Group: userGroup,
+ Summary: "Delete API key",
+ Response: &dto.Response[dto.MessageData]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "API key ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+
+ // ==================== Templates ====================
+ {
+ Method: http.MethodPost,
+ Path: "/templates",
+ Handler: okapi.H(r.h.template.Create),
+ Group: userGroup,
+ Tags: []string{"User"},
+ Summary: "Create template",
+ Request: &handlers.CreateTemplateRequest{},
+ Options: []okapi.RouteOption{
+ okapi.DocResponse(201, &dto.Response[models.Template]{}),
+ okapi.DocErrorResponse(409, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/templates",
+ Handler: okapi.H(r.h.template.List),
+ Group: userGroup,
+ Summary: "List templates",
+ Request: &handlers.ListRequest{},
+ Response: &dto.PageableResponse[models.Template]{},
+ },
+ {
+ Method: http.MethodPut,
+ Path: "/templates/{id:int}",
+ Handler: okapi.H(r.h.template.Update),
+ Group: userGroup,
+ Summary: "Update template",
+ Request: &handlers.UpdateTemplateRequest{},
+ Response: &dto.Response[models.Template]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Template ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodDelete,
+ Path: "/templates/{id:int}",
+ Handler: okapi.H(r.h.template.Delete),
+ Group: userGroup,
+ Tags: []string{"User"},
+ Summary: "Delete template",
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Template ID"),
+ okapi.DocResponse(204, nil),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/templates/preview",
+ Handler: okapi.H(r.h.template.Preview),
+ Group: userGroup,
+ Summary: "Preview template",
+ Description: "Render a template with sample data and return the result",
+ Request: &handlers.PreviewTemplateRequest{},
+ Response: &dto.Response[handlers.PreviewResult]{},
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/templates/{id:int}/send-test",
+ Handler: okapi.H(r.h.template.SendTest),
+ Group: userGroup,
+ Summary: "Send test email",
+ Description: "Send a test email using a template with sample data",
+ Request: &handlers.SendTestRequest{},
+ Response: &dto.Response[email.SendResponse]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Template ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+
+ // ==================== Template Import/Export ====================
+ {
+ Method: http.MethodGet,
+ Path: "/templates/{id:int}/export",
+ Handler: okapi.H(r.h.template.Export),
+ Group: userGroup,
+ Summary: "Export template",
+ Description: "Export a template with all versions and localizations as JSON",
+ Response: &dto.Response[handlers.TemplateExport]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Template ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/templates/import",
+ Handler: okapi.H(r.h.template.Import),
+ Group: userGroup,
+ Summary: "Import template",
+ Description: "Import a template from a previously exported JSON payload",
+ Request: &handlers.ImportTemplateRequest{},
+ Options: []okapi.RouteOption{
+ okapi.DocResponse(201, &dto.Response[models.Template]{}),
+ okapi.DocErrorResponse(409, &dto.ErrorResponseBody{}),
+ },
+ },
+
+ // ==================== Template Versions ====================
+ {
+ Method: http.MethodGet,
+ Path: "/templates/{id:int}/versions",
+ Handler: okapi.H(r.h.version.List),
+ Group: userGroup,
+ Tags: []string{"Template Versions"},
+ Summary: "List template versions",
+ Response: &dto.Response[[]models.TemplateVersion]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Template ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/templates/{id:int}/versions",
+ Handler: okapi.H(r.h.version.Create),
+ Group: userGroup,
+ Tags: []string{"Template Versions"},
+ Summary: "Create template version",
+ Request: &handlers.CreateVersionRequest{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Template ID"),
+ okapi.DocResponse(201, &dto.Response[models.TemplateVersion]{}),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodPut,
+ Path: "/templates/{id:int}/versions/{versionId:int}",
+ Handler: okapi.H(r.h.version.Update),
+ Group: userGroup,
+ Tags: []string{"Template Versions"},
+ Summary: "Update template version",
+ Request: &handlers.UpdateVersionRequest{},
+ Response: &dto.Response[models.TemplateVersion]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Template ID"),
+ okapi.DocPathParam("versionId", "integer", "Version ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/templates/{id:int}/activate/{versionId:int}",
+ Handler: okapi.H(r.h.version.Activate),
+ Group: userGroup,
+ Tags: []string{"Template Versions"},
+ Summary: "Activate template version",
+ Response: &dto.Response[models.Template]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Template ID"),
+ okapi.DocPathParam("versionId", "integer", "Version ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodDelete,
+ Path: "/templates/{id:int}/versions/{versionId:int}",
+ Handler: okapi.H(r.h.version.Delete),
+ Group: userGroup,
+ Tags: []string{"Template Versions"},
+ Summary: "Delete template version",
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Template ID"),
+ okapi.DocPathParam("versionId", "integer", "Version ID"),
+ okapi.DocResponse(204, nil),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+
+ // ==================== Template Localizations ====================
+ {
+ Method: http.MethodGet,
+ Path: "/templates/{id:int}/versions/{versionId:int}/localizations",
+ Handler: okapi.H(r.h.localization.List),
+ Group: userGroup,
+ Tags: []string{"Template Localizations"},
+ Summary: "List localizations for a version",
+ Response: &dto.Response[[]models.TemplateLocalization]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Template ID"),
+ okapi.DocPathParam("versionId", "integer", "Version ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/templates/{id:int}/versions/{versionId:int}/localizations",
+ Handler: okapi.H(r.h.localization.Create),
+ Group: userGroup,
+ Tags: []string{"Template Localizations"},
+ Summary: "Create localization",
+ Request: &handlers.CreateLocalizationRequest{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Template ID"),
+ okapi.DocPathParam("versionId", "integer", "Version ID"),
+ okapi.DocResponse(201, &dto.Response[models.TemplateLocalization]{}),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ okapi.DocErrorResponse(409, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodPut,
+ Path: "/localizations/{localizationId:int}",
+ Handler: okapi.H(r.h.localization.Update),
+ Group: userGroup,
+ Tags: []string{"Template Localizations"},
+ Summary: "Update localization",
+ Request: &handlers.UpdateLocalizationRequest{},
+ Response: &dto.Response[models.TemplateLocalization]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("localizationId", "integer", "Localization ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodDelete,
+ Path: "/localizations/{localizationId:int}",
+ Handler: okapi.H(r.h.localization.Delete),
+ Group: userGroup,
+ Tags: []string{"Template Localizations"},
+ Summary: "Delete localization",
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("localizationId", "integer", "Localization ID"),
+ okapi.DocResponse(204, nil),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/templates/{id:int}/versions/{versionId:int}/preview",
+ Handler: okapi.H(r.h.localization.Preview),
+ Group: userGroup,
+ Tags: []string{"Template Localizations"},
+ Summary: "Preview localized template",
+ Description: "Render a specific language version of a template with sample data",
+ Request: &handlers.PreviewLocalizationRequest{},
+ Response: &dto.Response[handlers.PreviewResult]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Template ID"),
+ okapi.DocPathParam("versionId", "integer", "Version ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+
+ // ==================== Languages ====================
+ {
+ Method: http.MethodPost,
+ Path: "/languages",
+ Handler: okapi.H(r.h.language.Create),
+ Group: userGroup,
+ Tags: []string{"Languages"},
+ Summary: "Create language",
+ Request: &handlers.CreateLanguageRequest{},
+ Options: []okapi.RouteOption{
+ okapi.DocResponse(201, &dto.Response[models.Language]{}),
+ okapi.DocErrorResponse(409, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/languages",
+ Handler: okapi.H(r.h.language.List),
+ Group: userGroup,
+ Tags: []string{"Languages"},
+ Summary: "List languages",
+ Request: &handlers.ListRequest{},
+ Response: &dto.PageableResponse[models.Language]{},
+ },
+ {
+ Method: http.MethodPut,
+ Path: "/languages/{id:int}",
+ Handler: okapi.H(r.h.language.Update),
+ Group: userGroup,
+ Tags: []string{"Languages"},
+ Summary: "Update language",
+ Request: &handlers.UpdateLanguageRequest{},
+ Response: &dto.Response[models.Language]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Language ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodDelete,
+ Path: "/languages/{id:int}",
+ Handler: okapi.H(r.h.language.Delete),
+ Group: userGroup,
+ Tags: []string{"Languages"},
+ Summary: "Delete language",
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Language ID"),
+ okapi.DocResponse(204, nil),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+
+ // ==================== Stylesheets ====================
+ {
+ Method: http.MethodPost,
+ Path: "/stylesheets",
+ Handler: okapi.H(r.h.stylesheet.Create),
+ Group: userGroup,
+ Tags: []string{"User"},
+ Summary: "Create stylesheet",
+ Request: &handlers.CreateStyleSheetRequest{},
+ Options: []okapi.RouteOption{
+ okapi.DocResponse(201, &dto.Response[models.StyleSheet]{}),
+ okapi.DocErrorResponse(409, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/stylesheets",
+ Handler: okapi.H(r.h.stylesheet.List),
+ Group: userGroup,
+ Summary: "List stylesheets",
+ Request: &handlers.ListRequest{},
+ Response: &dto.PageableResponse[models.StyleSheet]{},
+ },
+ {
+ Method: http.MethodPut,
+ Path: "/stylesheets/{id:int}",
+ Handler: okapi.H(r.h.stylesheet.Update),
+ Group: userGroup,
+ Summary: "Update stylesheet",
+ Request: &handlers.UpdateStyleSheetRequest{},
+ Response: &dto.Response[models.StyleSheet]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "StyleSheet ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodDelete,
+ Path: "/stylesheets/{id:int}",
+ Handler: okapi.H(r.h.stylesheet.Delete),
+ Group: userGroup,
+ Tags: []string{"User"},
+ Summary: "Delete stylesheet",
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "StyleSheet ID"),
+ okapi.DocResponse(204, nil),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+
+ // ==================== SMTP Servers ====================
+ {
+ Method: http.MethodPost,
+ Path: "/smtp-servers",
+ Handler: okapi.H(r.h.smtp.Create),
+ Group: userGroup,
+ Tags: []string{"User"},
+ Summary: "Add SMTP server",
+ Request: &handlers.CreateSMTPRequest{},
+ Options: []okapi.RouteOption{
+ okapi.DocResponse(201, &dto.Response[models.SMTPServer]{}),
+ },
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/smtp-servers",
+ Handler: okapi.H(r.h.smtp.List),
+ Group: userGroup,
+ Summary: "List SMTP servers",
+ Request: &handlers.ListRequest{},
+ Response: &dto.PageableResponse[models.SMTPServer]{},
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/smtp-servers/{id:int}",
+ Handler: okapi.H(r.h.smtp.Get),
+ Group: userGroup,
+ Summary: "Get SMTP server",
+ Request: &handlers.GetSMTPRequest{},
+ Response: &dto.Response[models.SMTPServer]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "SMTP server ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodPut,
+ Path: "/smtp-servers/{id:int}",
+ Handler: okapi.H(r.h.smtp.Update),
+ Group: userGroup,
+ Summary: "Update SMTP server",
+ Request: &handlers.UpdateSMTPRequest{},
+ Response: &dto.Response[models.SMTPServer]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "SMTP server ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodDelete,
+ Path: "/smtp-servers/{id:int}",
+ Handler: okapi.H(r.h.smtp.Delete),
+ Group: userGroup,
+ Tags: []string{"User"},
+ Summary: "Delete SMTP server",
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "SMTP server ID"),
+ okapi.DocResponse(204, nil),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/smtp-servers/{id:int}/test",
+ Handler: okapi.H(r.h.smtp.Test),
+ Group: userGroup,
+ Summary: "Test SMTP server connection",
+ Response: &dto.Response[dto.MessageData]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "SMTP server ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+
+ // ==================== Webhooks ====================
+ {
+ Method: http.MethodPost,
+ Path: "/webhooks",
+ Handler: okapi.H(r.h.webhook.Create),
+ Group: userGroup,
+ Tags: []string{"User"},
+ Summary: "Create webhook",
+ Request: &handlers.CreateWebhookRequest{},
+ Options: []okapi.RouteOption{
+ okapi.DocResponse(201, &dto.Response[models.Webhook]{}),
+ },
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/webhooks",
+ Handler: okapi.H(r.h.webhook.List),
+ Group: userGroup,
+ Summary: "List webhooks",
+ Request: &handlers.ListRequest{},
+ Response: &dto.PageableResponse[models.Webhook]{},
+ },
+ {
+ Method: http.MethodDelete,
+ Path: "/webhooks/{id:int}",
+ Handler: okapi.H(r.h.webhook.Delete),
+ Group: userGroup,
+ Tags: []string{"User"},
+ Summary: "Delete webhook",
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Webhook ID"),
+ okapi.DocResponse(204, nil),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+
+ // ==================== Webhook Deliveries ====================
+ {
+ Method: http.MethodGet,
+ Path: "/webhook-deliveries",
+ Handler: okapi.H(r.h.webhookDelivery.List),
+ Group: userGroup,
+ Summary: "List webhook deliveries",
+ Request: &handlers.ListRequest{},
+ Response: &dto.PageableResponse[models.WebhookDelivery]{},
+ },
+
+ // ==================== Domains ====================
+ {
+ Method: http.MethodPost,
+ Path: "/domains",
+ Handler: okapi.H(r.h.domain.Create),
+ Group: userGroup,
+ Summary: "Add domain",
+ Description: "Register a domain for verification. Returns the DNS records that must be configured.",
+ Request: &handlers.CreateDomainRequest{},
+ Options: []okapi.RouteOption{
+ okapi.DocResponse(201, &dto.Response[handlers.DomainWithRecords]{}),
+ okapi.DocErrorResponse(409, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/domains",
+ Handler: okapi.H(r.h.domain.List),
+ Group: userGroup,
+ Summary: "List domains",
+ Request: &handlers.ListRequest{},
+ Response: &dto.PageableResponse[models.Domain]{},
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/domains/{id:int}",
+ Handler: okapi.H(r.h.domain.Get),
+ Group: userGroup,
+ Summary: "Get domain details",
+ Response: &dto.Response[handlers.DomainWithRecords]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Domain ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodDelete,
+ Path: "/domains/{id:int}",
+ Handler: okapi.H(r.h.domain.Delete),
+ Group: userGroup,
+ Tags: []string{"User"},
+ Summary: "Delete domain",
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Domain ID"),
+ okapi.DocResponse(204, nil),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/domains/{id:int}/verify",
+ Handler: okapi.H(r.h.domain.Verify),
+ Group: userGroup,
+ Summary: "Verify domain DNS records",
+ Description: "Check DNS records (SPF, DKIM, DMARC) for the domain",
+ Response: &dto.Response[any]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Domain ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+
+ // ==================== Bounces ====================
+ {
+ Method: http.MethodPost,
+ Path: "/bounces",
+ Handler: okapi.H(r.h.bounce.Record),
+ Group: userGroup,
+ Summary: "Record a bounce",
+ Description: "Record a bounce or complaint. Hard bounces and complaints auto-suppress the recipient.",
+ Request: &handlers.RecordBounceRequest{},
+ Options: []okapi.RouteOption{
+ okapi.DocResponse(201, &dto.Response[models.Bounce]{}),
+ },
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/bounces",
+ Handler: okapi.H(r.h.bounce.List),
+ Group: userGroup,
+ Summary: "List bounces",
+ Request: &handlers.ListRequest{},
+ Response: &dto.PageableResponse[models.Bounce]{},
+ },
+
+ // ==================== Suppressions ====================
+ {
+ Method: http.MethodPost,
+ Path: "/suppressions",
+ Handler: okapi.H(r.h.suppression.Create),
+ Group: userGroup,
+ Tags: []string{"User"},
+ Summary: "Add to suppression list",
+ Request: &handlers.CreateSuppressionRequest{},
+ Options: []okapi.RouteOption{
+ okapi.DocResponse(201, &dto.Response[models.Suppression]{}),
+ okapi.DocErrorResponse(409, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/suppressions",
+ Handler: okapi.H(r.h.suppression.List),
+ Group: userGroup,
+ Summary: "List suppressed emails",
+ Request: &handlers.ListRequest{},
+ Response: &dto.PageableResponse[models.Suppression]{},
+ },
+ {
+ Method: http.MethodDelete,
+ Path: "/suppressions",
+ Handler: okapi.H(r.h.suppression.Delete),
+ Group: userGroup,
+ Tags: []string{"User"},
+ Summary: "Remove from suppression list",
+ Request: &handlers.DeleteSuppressionRequest{},
+ Options: []okapi.RouteOption{
+ okapi.DocResponse(204, nil),
+ },
+ },
+
+ // ==================== Audit Log ====================
+ {
+ Method: http.MethodGet,
+ Path: "/audit-log",
+ Handler: okapi.H(r.h.event.UserAuditLog),
+ Group: userGroup,
+ Summary: "List audit log",
+ Description: "Returns the authenticated user's audit trail",
+ Request: &handlers.ListEventsRequest{},
+ Response: &dto.PageableResponse[models.Event]{},
+ },
+
+ // ==================== Contacts ====================
+ {
+ Method: http.MethodGet,
+ Path: "/contacts",
+ Handler: okapi.H(r.h.contact.List),
+ Group: userGroup,
+ Summary: "List contacts",
+ Description: "List all recipient email addresses with sent/failed counts. Use the search query parameter to filter by email or name.",
+ Request: &handlers.ListContactsRequest{},
+ Response: &dto.PageableResponse[models.Contact]{},
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/contacts/{id:int}",
+ Handler: okapi.H(r.h.contact.Get),
+ Group: userGroup,
+ Summary: "Get contact details",
+ Description: "Get a single contact by ID with suppression status",
+ Request: &handlers.GetByIDRequest{},
+ Response: &dto.Response[models.Contact]{},
+ },
+
+ // ==================== Contact Lists ====================
+ {
+ Method: http.MethodPost,
+ Path: "/contact-lists",
+ Handler: okapi.H(r.h.contactList.Create),
+ Group: userGroup,
+ Tags: []string{"Contact Lists"},
+ Summary: "Create contact list",
+ Request: &handlers.CreateContactListRequest{},
+ Options: []okapi.RouteOption{
+ okapi.DocResponse(201, &dto.Response[models.ContactList]{}),
+ },
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/contact-lists",
+ Handler: okapi.H(r.h.contactList.List),
+ Group: userGroup,
+ Tags: []string{"Contact Lists"},
+ Summary: "List contact lists",
+ Request: &handlers.ListRequest{},
+ Response: &dto.PageableResponse[handlers.ContactListWithCount]{},
+ },
+ {
+ Method: http.MethodPut,
+ Path: "/contact-lists/{id:int}",
+ Handler: okapi.H(r.h.contactList.Update),
+ Group: userGroup,
+ Tags: []string{"Contact Lists"},
+ Summary: "Update contact list",
+ Request: &handlers.UpdateContactListRequest{},
+ Response: &dto.Response[models.ContactList]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Contact list ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodDelete,
+ Path: "/contact-lists/{id:int}",
+ Handler: okapi.H(r.h.contactList.Delete),
+ Group: userGroup,
+ Tags: []string{"Contact Lists"},
+ Summary: "Delete contact list",
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Contact list ID"),
+ okapi.DocResponse(204, nil),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/contact-lists/{id:int}/members",
+ Handler: okapi.H(r.h.contactList.AddMember),
+ Group: userGroup,
+ Tags: []string{"Contact Lists"},
+ Summary: "Add member to list",
+ Request: &handlers.AddMemberRequest{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Contact list ID"),
+ okapi.DocResponse(201, &dto.Response[models.ContactListMember]{}),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ okapi.DocErrorResponse(409, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodDelete,
+ Path: "/contact-lists/{id:int}/members",
+ Handler: okapi.H(r.h.contactList.RemoveMember),
+ Group: userGroup,
+ Tags: []string{"Contact Lists"},
+ Summary: "Remove member from list",
+ Request: &handlers.RemoveMemberRequest{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Contact list ID"),
+ okapi.DocResponse(204, nil),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/contact-lists/{id:int}/members",
+ Handler: okapi.H(r.h.contactList.ListMembers),
+ Group: userGroup,
+ Tags: []string{"Contact Lists"},
+ Summary: "List members in contact list",
+ Request: &handlers.ListMembersRequest{},
+ Response: &dto.PageableResponse[models.ContactListMember]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Contact list ID"),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+
+ // ==================== User Settings ====================
+ {
+ Method: http.MethodGet,
+ Path: "/settings",
+ Handler: r.h.userSetting.GetSettings,
+ Group: userGroup,
+ Summary: "Get user settings",
+ Response: &dto.Response[models.UserSetting]{},
+ },
+ {
+ Method: http.MethodPut,
+ Path: "/settings",
+ Handler: okapi.H(r.h.userSetting.UpdateSettings),
+ Group: userGroup,
+ Summary: "Update user settings",
+ Request: &handlers.UpdateUserSettingsRequest{},
+ Response: &dto.Response[models.UserSetting]{},
+ },
+ }
+}
diff --git a/internal/services/audit/audit.go b/internal/services/audit/audit.go
new file mode 100644
index 0000000..3736a05
--- /dev/null
+++ b/internal/services/audit/audit.go
@@ -0,0 +1,45 @@
+/*
+ * 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 audit
+
+import (
+ "github.com/jkaninda/posta/internal/models"
+ "github.com/jkaninda/posta/internal/services/eventbus"
+)
+
+// Logger records audit trail events via the existing event bus.
+type Logger struct {
+ bus *eventbus.EventBus
+}
+
+// NewLogger creates an audit logger backed by the given event bus.
+func NewLogger(bus *eventbus.EventBus) *Logger {
+ return &Logger{bus: bus}
+}
+
+// Log records an audit event with the given actor, action type, message, and optional metadata.
+func (l *Logger) Log(actorID uint, actorEmail, clientIP, action, message string, metadata map[string]any) {
+ l.bus.PublishSimple(models.EventCategoryAudit, action, &actorID, actorEmail, clientIP, message, metadata)
+}
diff --git a/internal/services/auth/api_key.go b/internal/services/auth/api_key.go
new file mode 100644
index 0000000..3d5bf37
--- /dev/null
+++ b/internal/services/auth/api_key.go
@@ -0,0 +1,104 @@
+/*
+ * 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 auth
+
+import (
+ "crypto/rand"
+ "crypto/sha256"
+ "encoding/hex"
+ "fmt"
+ "strings"
+ "time"
+
+ "github.com/jkaninda/posta/internal/models"
+ "github.com/jkaninda/posta/internal/storage/repositories"
+)
+
+const apiKeyPrefix = "psk_"
+
+type APIKeyService struct {
+ repo *repositories.APIKeyRepository
+}
+
+func NewAPIKeyService(repo *repositories.APIKeyRepository) *APIKeyService {
+ return &APIKeyService{repo: repo}
+}
+
+// GenerateKey creates a new API key and returns the raw key (only shown once).
+// If expiresAt is nil the key never expires.
+func (s *APIKeyService) GenerateKey(userID uint, name string, allowedIPs []string, expiresAt *time.Time) (string, *models.APIKey, error) {
+ rawBytes := make([]byte, 32)
+ if _, err := rand.Read(rawBytes); err != nil {
+ return "", nil, fmt.Errorf("failed to generate key: %w", err)
+ }
+
+ rawKey := apiKeyPrefix + hex.EncodeToString(rawBytes)
+ hash := hashKey(rawKey)
+
+ key := &models.APIKey{
+ UserID: userID,
+ Name: name,
+ KeyHash: hash,
+ KeyPrefix: rawKey[:len(apiKeyPrefix)+8],
+ AllowedIPs: allowedIPs,
+ ExpiresAt: expiresAt,
+ }
+
+ if err := s.repo.Create(key); err != nil {
+ return "", nil, err
+ }
+
+ return rawKey, key, nil
+}
+
+// ValidateKey checks if a raw API key is valid and returns the matching APIKey.
+func (s *APIKeyService) ValidateKey(rawKey string) (*models.APIKey, error) {
+ if !strings.HasPrefix(rawKey, apiKeyPrefix) {
+ return nil, fmt.Errorf("invalid key format")
+ }
+
+ prefix := rawKey[:len(apiKeyPrefix)+8]
+ candidates, err := s.repo.FindByPrefix(prefix)
+ if err != nil {
+ return nil, fmt.Errorf("key not found")
+ }
+
+ hash := hashKey(rawKey)
+ for i := range candidates {
+ if candidates[i].KeyHash == hash {
+ if !candidates[i].IsValid() {
+ return nil, fmt.Errorf("key is expired or revoked")
+ }
+ return &candidates[i], nil
+ }
+ }
+
+ return nil, fmt.Errorf("key not found")
+}
+
+func hashKey(key string) string {
+ h := sha256.Sum256([]byte(key))
+ return hex.EncodeToString(h[:])
+}
diff --git a/internal/services/cache/cache.go b/internal/services/cache/cache.go
new file mode 100644
index 0000000..ccf0922
--- /dev/null
+++ b/internal/services/cache/cache.go
@@ -0,0 +1,135 @@
+/*
+ * 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 cache
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "time"
+
+ "github.com/redis/go-redis/v9"
+)
+
+const (
+ // Default TTLs for cached data.
+ DashboardStatsTTL = 60 * time.Second
+ AdminMetricsTTL = 60 * time.Second
+ UserMetricsTTL = 60 * time.Second
+ AnalyticsTTL = 120 * time.Second
+
+ prefixDashboard = "cache:dashboard:"
+ prefixAdminMetrics = "cache:admin:metrics"
+ prefixUserMetrics = "cache:admin:user_metrics:"
+ prefixUserAnalytics = "cache:analytics:user:"
+ prefixAdminAnalytics = "cache:analytics:admin"
+)
+
+// Cache provides Redis-backed caching for dashboard stats and metrics.
+type Cache struct {
+ client *redis.Client
+}
+
+// New creates a new Cache backed by the given Redis client.
+func New(client *redis.Client) *Cache {
+ return &Cache{client: client}
+}
+
+// Get retrieves a cached value and unmarshals it into dest.
+// Returns false if the key does not exist or on error.
+func (c *Cache) Get(ctx context.Context, key string, dest any) bool {
+ data, err := c.client.Get(ctx, key).Bytes()
+ if err != nil {
+ return false
+ }
+ return json.Unmarshal(data, dest) == nil
+}
+
+// Set marshals value and stores it with the given TTL.
+func (c *Cache) Set(ctx context.Context, key string, value any, ttl time.Duration) {
+ data, err := json.Marshal(value)
+ if err != nil {
+ return
+ }
+ c.client.Set(ctx, key, data, ttl)
+}
+
+// Delete removes a cached key.
+func (c *Cache) Delete(ctx context.Context, key string) {
+ c.client.Del(ctx, key)
+}
+
+// --- Key builders ---
+
+func DashboardKey(userID int) string {
+ return fmt.Sprintf("%s%d", prefixDashboard, userID)
+}
+
+func AdminMetricsKey() string {
+ return prefixAdminMetrics
+}
+
+func UserMetricsKey(userID int) string {
+ return fmt.Sprintf("%s%d", prefixUserMetrics, userID)
+}
+
+func UserAnalyticsKey(userID int, from, to, status string) string {
+ return fmt.Sprintf("%s%d:%s:%s:%s", prefixUserAnalytics, userID, from, to, status)
+}
+
+func AdminAnalyticsKey(from, to, status string) string {
+ return fmt.Sprintf("%s:%s:%s:%s", prefixAdminAnalytics, from, to, status)
+}
+
+// InvalidateUser removes all cached data scoped to a specific user.
+func (c *Cache) InvalidateUser(ctx context.Context, userID int) {
+ c.Delete(ctx, DashboardKey(userID))
+ c.Delete(ctx, UserMetricsKey(userID))
+ // Invalidate admin-level caches too, since user data affects them.
+ c.Delete(ctx, AdminMetricsKey())
+}
+
+// InvalidateAdmin removes admin-level cached metrics.
+func (c *Cache) InvalidateAdmin(ctx context.Context) {
+ c.Delete(ctx, AdminMetricsKey())
+}
+
+// InvalidateByPattern removes keys matching a pattern using SCAN (non-blocking).
+func (c *Cache) InvalidateByPattern(ctx context.Context, pattern string) {
+ iter := c.client.Scan(ctx, 0, pattern, 100).Iterator()
+ for iter.Next(ctx) {
+ c.client.Del(ctx, iter.Val())
+ }
+}
+
+// InvalidateAnalytics removes all cached analytics data.
+func (c *Cache) InvalidateAnalytics(ctx context.Context) {
+ c.InvalidateByPattern(ctx, "cache:analytics:*")
+}
+
+// InvalidateAll removes all cache keys (dashboard + metrics + analytics).
+func (c *Cache) InvalidateAll(ctx context.Context) {
+ c.InvalidateByPattern(ctx, "cache:*")
+}
diff --git a/internal/services/domain/verifier.go b/internal/services/domain/verifier.go
new file mode 100644
index 0000000..0f98882
--- /dev/null
+++ b/internal/services/domain/verifier.go
@@ -0,0 +1,141 @@
+/*
+ * 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 domain
+
+import (
+ "net"
+ "strings"
+
+ "github.com/jkaninda/posta/internal/models"
+)
+
+// VerificationResult holds the outcome of DNS record checks.
+type VerificationResult struct {
+ OwnershipVerified bool `json:"ownership_verified"`
+ SPFVerified bool `json:"spf_verified"`
+ DKIMVerified bool `json:"dkim_verified"`
+ DMARCVerified bool `json:"dmarc_verified"`
+ SPFRecord string `json:"spf_record,omitempty"`
+ DKIMRecord string `json:"dkim_record,omitempty"`
+ DMARCRecord string `json:"dmarc_record,omitempty"`
+}
+
+// DNSRecords returns the DNS records a user needs to configure for a domain.
+type DNSRecords struct {
+ Verification DNSRecord `json:"verification"`
+ SPF DNSRecord `json:"spf"`
+ DKIM DNSRecord `json:"dkim"`
+ DMARC DNSRecord `json:"dmarc"`
+}
+
+type DNSRecord struct {
+ Type string `json:"type"`
+ Host string `json:"host"`
+ Value string `json:"value"`
+}
+
+// RequiredRecords returns the DNS records the user must add.
+func RequiredRecords(d *models.Domain) *DNSRecords {
+ return &DNSRecords{
+ Verification: DNSRecord{
+ Type: "TXT",
+ Host: d.Domain,
+ Value: "posta-verification=" + d.VerificationToken,
+ },
+ SPF: DNSRecord{
+ Type: "TXT",
+ Host: d.Domain,
+ Value: "v=spf1 include:_spf.posta ~all",
+ },
+ DKIM: DNSRecord{
+ Type: "CNAME",
+ Host: "posta._domainkey." + d.Domain,
+ Value: "posta._domainkey.posta",
+ },
+ DMARC: DNSRecord{
+ Type: "TXT",
+ Host: "_dmarc." + d.Domain,
+ Value: "v=DMARC1; p=none; rua=mailto:dmarc@" + d.Domain,
+ },
+ }
+}
+
+// Verify performs DNS lookups to check SPF, DKIM, and DMARC records.
+// It also checks the verification TXT record for domain ownership.
+func Verify(d *models.Domain) (*VerificationResult, error) {
+ result := &VerificationResult{}
+
+ // Check domain ownership via TXT record
+ ownershipVerified := false
+ txtRecords, err := net.LookupTXT(d.Domain)
+ if err == nil {
+ expectedToken := "posta-verification=" + d.VerificationToken
+ for _, txt := range txtRecords {
+ if strings.TrimSpace(txt) == expectedToken {
+ ownershipVerified = true
+ }
+ if strings.HasPrefix(strings.TrimSpace(txt), "v=spf1") {
+ result.SPFVerified = true
+ result.SPFRecord = txt
+ }
+ }
+ }
+
+ result.OwnershipVerified = ownershipVerified
+ if !ownershipVerified {
+ return result, nil
+ }
+
+ // Check DKIM
+ dkimHost := "posta._domainkey." + d.Domain
+ dkimRecords, err := net.LookupTXT(dkimHost)
+ if err == nil && len(dkimRecords) > 0 {
+ result.DKIMVerified = true
+ result.DKIMRecord = dkimRecords[0]
+ }
+ // Also check CNAME
+ if !result.DKIMVerified {
+ cname, err := net.LookupCNAME(dkimHost)
+ if err == nil && cname != "" {
+ result.DKIMVerified = true
+ result.DKIMRecord = cname
+ }
+ }
+
+ // Check DMARC
+ dmarcHost := "_dmarc." + d.Domain
+ dmarcRecords, err := net.LookupTXT(dmarcHost)
+ if err == nil {
+ for _, txt := range dmarcRecords {
+ if strings.HasPrefix(strings.TrimSpace(txt), "v=DMARC1") {
+ result.DMARCVerified = true
+ result.DMARCRecord = txt
+ break
+ }
+ }
+ }
+
+ return result, nil
+}
diff --git a/internal/services/email/html2text.go b/internal/services/email/html2text.go
new file mode 100644
index 0000000..b1b313b
--- /dev/null
+++ b/internal/services/email/html2text.go
@@ -0,0 +1,82 @@
+/*
+ * 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 email
+
+import (
+ "html"
+ "regexp"
+ "strings"
+)
+
+// HTMLToText converts an HTML string to readable plain text.
+// It strips tags, converts common block elements to appropriate whitespace,
+// extracts link URLs, and decodes HTML entities.
+func HTMLToText(input string) string {
+ if input == "" {
+ return ""
+ }
+
+ s := input
+
+ // Convert <br>, <br/>, <br /> to newlines
+ brRe := regexp.MustCompile(`(?i)<br\s*/?>`)
+ s = brRe.ReplaceAllString(s, "\n")
+
+ // Convert </p> to double newlines
+ closePRe := regexp.MustCompile(`(?i)</p\s*>`)
+ s = closePRe.ReplaceAllString(s, "\n\n")
+
+ // Convert <p ...> to double newlines (except the very first one)
+ openPRe := regexp.MustCompile(`(?i)<p[^>]*>`)
+ s = openPRe.ReplaceAllString(s, "\n\n")
+
+ // Convert <li> to "- " prefix
+ liRe := regexp.MustCompile(`(?i)<li[^>]*>`)
+ s = liRe.ReplaceAllString(s, "\n- ")
+
+ // Convert <a href="url">text</a> to "text (url)"
+ linkRe := regexp.MustCompile(`(?i)<a\s[^>]*href\s*=\s*["']([^"']*)["'][^>]*>(.*?)</a>`)
+ s = linkRe.ReplaceAllString(s, "$2 ($1)")
+
+ // Strip all remaining HTML tags
+ tagRe := regexp.MustCompile(`<[^>]*>`)
+ s = tagRe.ReplaceAllString(s, "")
+
+ // Decode HTML entities (handles &amp;, &lt;, &gt;, &nbsp;, &#xxxx; etc.)
+ s = strings.ReplaceAll(s, "&nbsp;", " ")
+ s = html.UnescapeString(s)
+
+ // Collapse runs of spaces/tabs on each line (preserve newlines)
+ spaceRe := regexp.MustCompile(`[^\S\n]+`)
+ s = spaceRe.ReplaceAllString(s, " ")
+
+ // Collapse 3+ consecutive newlines into 2
+ nlRe := regexp.MustCompile(`\n{3,}`)
+ s = nlRe.ReplaceAllString(s, "\n\n")
+
+ s = strings.TrimSpace(s)
+
+ return s
+}
diff --git a/internal/services/email/service.go b/internal/services/email/service.go
new file mode 100644
index 0000000..f39c09a
--- /dev/null
+++ b/internal/services/email/service.go
@@ -0,0 +1,815 @@
+/*
+ * 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 email
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/mail"
+ "strings"
+ "time"
+
+ "github.com/jkaninda/logger"
+ "github.com/jkaninda/posta/internal/models"
+ "github.com/jkaninda/posta/internal/services/ratelimit"
+ "github.com/jkaninda/posta/internal/services/settings"
+ "github.com/jkaninda/posta/internal/services/webhook"
+ "github.com/jkaninda/posta/internal/storage/repositories"
+)
+
+const (
+ DefaultMaxAttachmentSize int64 = 10 * 1024 * 1024 // 10MB per attachment
+ DefaultMaxTotalSize int64 = 25 * 1024 * 1024 // 25MB total
+
+ defaultFromAddress = "noreply@localhost"
+)
+
+// EmailEnqueuer enqueues an email for background delivery.
+// When set on the Service, emails are sent asynchronously via a worker.
+type EmailEnqueuer interface {
+ EnqueueEmailSend(emailID uint, queue string) error
+ EnqueueEmailSendAt(emailID uint, queue string, sendAt time.Time) error
+}
+
+type Service struct {
+ emailRepo *repositories.EmailRepository
+ smtpRepo *repositories.SMTPRepository
+ templateRepo *repositories.TemplateRepository
+ suppressionRepo *repositories.SuppressionRepository
+ versionRepo *repositories.TemplateVersionRepository
+ localizationRepo *repositories.TemplateLocalizationRepository
+ contactRepo *repositories.ContactRepository
+ domainRepo *repositories.DomainRepository
+ userRepo *repositories.UserRepository
+ sender *SMTPSender
+ renderer *TemplateRenderer
+ limiter *ratelimit.RedisLimiter
+ dispatcher *webhook.Dispatcher
+ enqueuer EmailEnqueuer
+ settings *settings.Provider
+ devMode bool
+ onSent func()
+ onFailed func()
+ onQueued func()
+}
+
+func NewService(
+ emailRepo *repositories.EmailRepository,
+ smtpRepo *repositories.SMTPRepository,
+ templateRepo *repositories.TemplateRepository,
+ suppressionRepo *repositories.SuppressionRepository,
+ limiter *ratelimit.RedisLimiter,
+ dispatcher *webhook.Dispatcher,
+ devMode bool,
+) *Service {
+ return &Service{
+ emailRepo: emailRepo,
+ smtpRepo: smtpRepo,
+ templateRepo: templateRepo,
+ suppressionRepo: suppressionRepo,
+ sender: NewSMTPSender(),
+ renderer: NewTemplateRenderer(),
+ limiter: limiter,
+ dispatcher: dispatcher,
+ devMode: devMode,
+ }
+}
+
+// SetVersionRepos sets the version and localization repositories for multi-language support.
+func (s *Service) SetVersionRepos(vr *repositories.TemplateVersionRepository, lr *repositories.TemplateLocalizationRepository) {
+ s.versionRepo = vr
+ s.localizationRepo = lr
+}
+
+// SetContactRepo sets the contact repository for tracking recipient stats.
+func (s *Service) SetContactRepo(cr *repositories.ContactRepository) {
+ s.contactRepo = cr
+}
+
+// SetDomainVerification sets the domain and user repositories for enforcing verified domain sending.
+func (s *Service) SetDomainVerification(dr *repositories.DomainRepository, ur *repositories.UserRepository) {
+ s.domainRepo = dr
+ s.userRepo = ur
+}
+
+// SetSettings sets the platform settings provider for dynamic configuration.
+func (s *Service) SetSettings(sp *settings.Provider) {
+ s.settings = sp
+}
+
+// SetEnqueuer sets the email enqueuer for asynchronous delivery.
+// When set, emails are enqueued to a background worker instead of being sent synchronously.
+func (s *Service) SetEnqueuer(eq EmailEnqueuer) {
+ s.enqueuer = eq
+}
+
+// OnSent sets a callback invoked after each successful email send.
+func (s *Service) OnSent(fn func()) { s.onSent = fn }
+
+// OnFailed sets a callback invoked after each failed email send.
+func (s *Service) OnFailed(fn func()) { s.onFailed = fn }
+
+// OnQueued sets a callback invoked after each email is enqueued for delivery.
+func (s *Service) OnQueued(fn func()) { s.onQueued = fn }
+
+type SendRequest struct {
+ From string `json:"from" required:"true"`
+ To []string `json:"to" required:"true" minItems:"1"`
+ Subject string `json:"subject" required:"true"`
+ HTML string `json:"html"`
+ Text string `json:"text"`
+ Attachments []models.Attachment `json:"attachments,omitempty"`
+ Headers map[string]string `json:"headers,omitempty"`
+ ListUnsubscribeURL string `json:"list_unsubscribe_url,omitempty"`
+ ListUnsubscribePost bool `json:"list_unsubscribe_post,omitempty"`
+ SendAt *time.Time `json:"send_at,omitempty"`
+}
+
+type SendTemplateRequest struct {
+ Template string `json:"template" required:"true"`
+ Language string `json:"language"`
+ From string `json:"from"`
+ To []string `json:"to" required:"true" minItems:"1"`
+ TemplateData map[string]any `json:"template_data"`
+ Attachments []models.Attachment `json:"attachments,omitempty"`
+}
+
+type SendResponse struct {
+ ID string `json:"id"`
+ Status models.EmailStatus `json:"status"`
+}
+
+type BatchRequest struct {
+ Template string `json:"template" required:"true"`
+ Language string `json:"language"`
+ From string `json:"from"`
+ Recipients []BatchRecipient `json:"recipients" required:"true" minItems:"1"`
+}
+
+type BatchRecipient struct {
+ Email string `json:"email" required:"true" format:"email"`
+ Language string `json:"language"`
+ TemplateData map[string]any `json:"template_data"`
+}
+
+type BatchResponse struct {
+ Total int `json:"total"`
+ Sent int `json:"sent"`
+ Failed int `json:"failed"`
+ Skipped int `json:"skipped"`
+ Results []BatchResult `json:"results"`
+}
+
+type BatchResult struct {
+ Email string `json:"email"`
+ ID string `json:"id,omitempty"`
+ Status models.EmailStatus `json:"status"`
+ Error string `json:"error,omitempty"`
+}
+
+func (s *Service) Send(ctx context.Context, userID, apiKeyID uint, userEmail string, req *SendRequest) (*SendResponse, error) {
+ // Enforce maintenance mode
+ if s.settings != nil && s.settings.MaintenanceMode() {
+ return nil, fmt.Errorf("maintenance: email sending is temporarily disabled")
+ }
+
+ if err := s.limiter.Allow(ctx, userEmail); err != nil {
+ return nil, fmt.Errorf("rate_limit: %w", err)
+ }
+
+ // Validate attachments if present
+ if len(req.Attachments) > 0 {
+ maxSize := DefaultMaxAttachmentSize
+ if s.settings != nil {
+ maxSize = int64(s.settings.MaxAttachmentSizeMB()) * 1024 * 1024
+ }
+ if err := ValidateAttachments(req.Attachments, maxSize, DefaultMaxTotalSize); err != nil {
+ return nil, fmt.Errorf("attachment validation: %w", err)
+ }
+ }
+
+ // Enforce verified domain when user has strict mode enabled
+ if err := s.checkDomainVerification(userID, req.From); err != nil {
+ return nil, err
+ }
+
+ // Filter out suppressed recipients
+ if s.suppressionRepo != nil {
+ filtered, err := s.suppressionRepo.FilterSuppressed(userID, req.To)
+ if err != nil {
+ return nil, fmt.Errorf("failed to check suppression list: %w", err)
+ }
+ if len(filtered) == 0 {
+ // Log the suppressed email attempt
+ var apiKeyPtr *uint
+ if apiKeyID > 0 {
+ apiKeyPtr = &apiKeyID
+ }
+ em := &models.Email{
+ UserID: userID,
+ APIKeyID: apiKeyPtr,
+ Sender: req.From,
+ Recipients: req.To,
+ Subject: req.Subject,
+ HTMLBody: req.HTML,
+ TextBody: req.Text,
+ Status: models.EmailStatusSuppressed,
+ ErrorMessage: "all recipients are suppressed",
+ }
+ _ = s.emailRepo.Create(em)
+ return &SendResponse{ID: em.UUID, Status: em.Status}, nil
+ }
+ // Log suppressed recipients individually if some were filtered out
+ if len(filtered) < len(req.To) {
+ suppressed := diffRecipients(req.To, filtered)
+ var apiKeyPtr *uint
+ if apiKeyID > 0 {
+ apiKeyPtr = &apiKeyID
+ }
+ for _, addr := range suppressed {
+ em := &models.Email{
+ UserID: userID,
+ APIKeyID: apiKeyPtr,
+ Sender: req.From,
+ Recipients: []string{addr},
+ Subject: req.Subject,
+ Status: models.EmailStatusSuppressed,
+ ErrorMessage: "recipient is suppressed",
+ }
+ _ = s.emailRepo.Create(em)
+ }
+ }
+ req.To = filtered
+ }
+
+ // Serialize attachments metadata for storage
+ var attachmentsJSON string
+ if len(req.Attachments) > 0 {
+ type attachMeta struct {
+ Filename string `json:"filename"`
+ ContentType string `json:"content_type"`
+ }
+ meta := make([]attachMeta, len(req.Attachments))
+ for i, a := range req.Attachments {
+ meta[i] = attachMeta{Filename: a.Filename, ContentType: a.ContentType}
+ }
+ b, _ := json.Marshal(meta)
+ attachmentsJSON = string(b)
+ }
+
+ // Auto-generate plain text from HTML when text body is not provided
+ if req.Text == "" && req.HTML != "" {
+ req.Text = HTMLToText(req.HTML)
+ }
+
+ // Serialize custom headers for storage
+ var headersJSON string
+ if len(req.Headers) > 0 {
+ filtered := filterCustomHeaders(req.Headers)
+ if len(filtered) > 0 {
+ b, _ := json.Marshal(filtered)
+ headersJSON = string(b)
+ }
+ }
+
+ var apiKeyPtr *uint
+ if apiKeyID > 0 {
+ apiKeyPtr = &apiKeyID
+ }
+
+ em := &models.Email{
+ UserID: userID,
+ APIKeyID: apiKeyPtr,
+ Sender: req.From,
+ Recipients: req.To,
+ Subject: req.Subject,
+ HTMLBody: req.HTML,
+ TextBody: req.Text,
+ AttachmentsJSON: attachmentsJSON,
+ HeadersJSON: headersJSON,
+ ListUnsubscribeURL: req.ListUnsubscribeURL,
+ ListUnsubscribePost: req.ListUnsubscribePost,
+ Status: models.EmailStatusPending,
+ }
+
+ if err := s.emailRepo.Create(em); err != nil {
+ return nil, fmt.Errorf("failed to store email: %w", err)
+ }
+
+ if s.devMode {
+ em.Status = models.EmailStatusSent
+ now := time.Now()
+ em.SentAt = &now
+ _ = s.emailRepo.Update(em)
+ if s.onSent != nil {
+ s.onSent()
+ }
+ logger.Info("dev mode: email stored but not sent", "id", em.UUID)
+ return &SendResponse{ID: em.UUID, Status: em.Status}, nil
+ }
+
+ // Scheduled sending
+ if req.SendAt != nil && req.SendAt.After(time.Now()) && s.enqueuer != nil {
+ em.Status = models.EmailStatusScheduled
+ em.ScheduledAt = req.SendAt
+ _ = s.emailRepo.Update(em)
+ if err := s.enqueuer.EnqueueEmailSendAt(em.ID, "", *req.SendAt); err != nil {
+ em.Status = models.EmailStatusFailed
+ em.ErrorMessage = fmt.Sprintf("failed to schedule: %v", err)
+ _ = s.emailRepo.Update(em)
+ return nil, fmt.Errorf("failed to schedule email: %w", err)
+ }
+ return &SendResponse{ID: em.UUID, Status: em.Status}, nil
+ }
+
+ // Asynchronous path: enqueue the email for background delivery
+ if s.enqueuer != nil {
+ em.Status = models.EmailStatusQueued
+ _ = s.emailRepo.Update(em)
+ if err := s.enqueuer.EnqueueEmailSend(em.ID, ""); err != nil {
+ em.Status = models.EmailStatusFailed
+ em.ErrorMessage = fmt.Sprintf("failed to enqueue: %v", err)
+ _ = s.emailRepo.Update(em)
+ if s.onFailed != nil {
+ s.onFailed()
+ }
+ return nil, fmt.Errorf("failed to enqueue email: %w", err)
+ }
+ if s.onQueued != nil {
+ s.onQueued()
+ }
+ logger.Debug("email enqueued for background delivery", "id", em.UUID)
+ return &SendResponse{ID: em.UUID, Status: em.Status}, nil
+ }
+
+ // Synchronous fallback: send email directly (no worker configured)
+ return s.sendSync(em, userID, req)
+}
+
+// sendSync performs synchronous SMTP delivery (used when no enqueuer is configured).
+func (s *Service) sendSync(em *models.Email, userID uint, req *SendRequest) (*SendResponse, error) {
+ smtpServer, err := s.smtpRepo.FindFirstByUserID(userID)
+ if err != nil {
+ em.Status = models.EmailStatusFailed
+ em.ErrorMessage = "no SMTP server configured"
+ _ = s.emailRepo.Update(em)
+ s.dispatcher.Dispatch(userID, "email.failed", em.UUID, req.From)
+ if s.onFailed != nil {
+ s.onFailed()
+ }
+ return nil, fmt.Errorf("no SMTP server configured")
+ }
+
+ if len(smtpServer.AllowedEmails) > 0 {
+ bareFrom := extractEmail(req.From)
+ allowed := false
+ for _, e := range smtpServer.AllowedEmails {
+ if e == bareFrom {
+ allowed = true
+ break
+ }
+ }
+ if !allowed {
+ em.Status = models.EmailStatusFailed
+ em.ErrorMessage = fmt.Sprintf("sender %q is not in the allowed emails list", req.From)
+ _ = s.emailRepo.Update(em)
+ s.dispatcher.Dispatch(userID, "email.failed", em.UUID, req.From)
+ if s.onFailed != nil {
+ s.onFailed()
+ }
+ return nil, fmt.Errorf("sender %q is not in the allowed emails list", req.From)
+ }
+ }
+
+ em.SMTPHostname = smtpServer.Host
+ _ = s.emailRepo.Update(em)
+
+ if err := s.sender.Send(smtpServer, req.From, req.To, req.Subject, req.HTML, req.Text, req.Attachments, req.Headers, req.ListUnsubscribeURL, req.ListUnsubscribePost); err != nil {
+ em.Status = models.EmailStatusFailed
+ em.ErrorMessage = err.Error()
+ _ = s.emailRepo.Update(em)
+ s.dispatcher.Dispatch(userID, "email.failed", em.UUID, req.From)
+ if s.onFailed != nil {
+ s.onFailed()
+ }
+ if s.contactRepo != nil {
+ go s.contactRepo.RecordFailed(userID, req.To)
+ }
+ return nil, fmt.Errorf("failed to send email: %w", err)
+ }
+
+ now := time.Now()
+ em.Status = models.EmailStatusSent
+ em.SentAt = &now
+ _ = s.emailRepo.Update(em)
+ s.dispatcher.Dispatch(userID, "email.sent", em.UUID, req.From)
+ if s.onSent != nil {
+ s.onSent()
+ }
+ if s.contactRepo != nil {
+ go s.contactRepo.RecordSent(userID, req.To)
+ }
+
+ return &SendResponse{ID: em.UUID, Status: em.Status}, nil
+}
+
+func (s *Service) SendWithTemplate(ctx context.Context, userID, apiKeyID uint, userEmail string, req *SendTemplateRequest) (*SendResponse, error) {
+ tmpl, err := s.templateRepo.FindByName(userID, req.Template)
+ if err != nil {
+ return nil, fmt.Errorf("template not found: %s", req.Template)
+ }
+
+ rendered, err := s.resolveAndRender(tmpl, req.Language, req.TemplateData)
+ if err != nil {
+ return nil, fmt.Errorf("failed to render template: %w", err)
+ }
+
+ from := req.From
+ if from == "" {
+ from = defaultFromAddress
+ }
+
+ return s.Send(ctx, userID, apiKeyID, userEmail, &SendRequest{
+ From: from,
+ To: req.To,
+ Subject: rendered.Subject,
+ HTML: rendered.HTML,
+ Text: rendered.Text,
+ Attachments: req.Attachments,
+ })
+}
+
+func (s *Service) SendBatch(ctx context.Context, userID, apiKeyID uint, userEmail string, req *BatchRequest) (*BatchResponse, error) {
+ // Enforce max batch size from platform settings
+ if s.settings != nil {
+ maxBatch := s.settings.MaxBatchSize()
+ if maxBatch > 0 && len(req.Recipients) > maxBatch {
+ return nil, fmt.Errorf("batch size %d exceeds maximum allowed (%d)", len(req.Recipients), maxBatch)
+ }
+ }
+
+ tmpl, err := s.templateRepo.FindByName(userID, req.Template)
+ if err != nil {
+ return nil, fmt.Errorf("template not found: %s", req.Template)
+ }
+
+ from := req.From
+ if from == "" {
+ from = defaultFromAddress
+ }
+
+ resp := &BatchResponse{
+ Total: len(req.Recipients),
+ Results: make([]BatchResult, 0, len(req.Recipients)),
+ }
+
+ for _, recipient := range req.Recipients {
+ // Check suppression
+ if s.suppressionRepo != nil {
+ suppressed, err := s.suppressionRepo.IsSuppressed(userID, recipient.Email)
+ if err == nil && suppressed {
+ // Log the suppressed email
+ var apiKeyPtr *uint
+ if apiKeyID > 0 {
+ apiKeyPtr = &apiKeyID
+ }
+ em := &models.Email{
+ UserID: userID,
+ APIKeyID: apiKeyPtr,
+ Sender: from,
+ Recipients: []string{recipient.Email},
+ Subject: req.Template,
+ Status: models.EmailStatusSuppressed,
+ ErrorMessage: "recipient is suppressed",
+ }
+ _ = s.emailRepo.Create(em)
+
+ resp.Skipped++
+ resp.Results = append(resp.Results, BatchResult{
+ Email: recipient.Email,
+ ID: em.UUID,
+ Status: models.EmailStatusSuppressed,
+ Error: "recipient is suppressed",
+ })
+ continue
+ }
+ }
+
+ // Use per-recipient language, fall back to batch-level language
+ lang := recipient.Language
+ if lang == "" {
+ lang = req.Language
+ }
+
+ rendered, err := s.resolveAndRender(tmpl, lang, recipient.TemplateData)
+ if err != nil {
+ resp.Failed++
+ resp.Results = append(resp.Results, BatchResult{
+ Email: recipient.Email,
+ Status: models.EmailStatusFailed,
+ Error: fmt.Sprintf("template render failed: %v", err),
+ })
+ continue
+ }
+
+ sendResp, err := s.Send(ctx, userID, apiKeyID, userEmail, &SendRequest{
+ From: from,
+ To: []string{recipient.Email},
+ Subject: rendered.Subject,
+ HTML: rendered.HTML,
+ Text: rendered.Text,
+ })
+ if err != nil {
+ resp.Failed++
+ resp.Results = append(resp.Results, BatchResult{
+ Email: recipient.Email,
+ Status: models.EmailStatusFailed,
+ Error: err.Error(),
+ })
+ continue
+ }
+
+ resp.Sent++
+ resp.Results = append(resp.Results, BatchResult{
+ Email: recipient.Email,
+ ID: sendResp.ID,
+ Status: sendResp.Status,
+ })
+ }
+
+ return resp, nil
+}
+
+// SendTestByTemplateID sends a test email using a template looked up by ID.
+// It uses apiKeyID=0 since test sends come from the dashboard, not an API key.
+func (s *Service) SendTestByTemplateID(ctx context.Context, userID uint, userEmail string, templateID uint, req *SendTestRequest) (*SendResponse, error) {
+ tmpl, err := s.templateRepo.FindByID(templateID)
+ if err != nil || tmpl.UserID != userID {
+ return nil, fmt.Errorf("template not found")
+ }
+
+ rendered, err := s.resolveAndRender(tmpl, req.Language, req.TemplateData)
+ if err != nil {
+ return nil, fmt.Errorf("failed to render template: %w", err)
+ }
+
+ from := req.From
+ if from == "" {
+ from = defaultFromAddress
+ }
+
+ return s.Send(ctx, userID, 0, userEmail, &SendRequest{
+ From: from,
+ To: req.To,
+ Subject: rendered.Subject,
+ HTML: rendered.HTML,
+ Text: rendered.Text,
+ })
+}
+
+type SendTestRequest struct {
+ To []string `json:"to" required:"true" minItems:"1"`
+ From string `json:"from"`
+ Language string `json:"language"`
+ TemplateData map[string]any `json:"template_data"`
+}
+
+// RetryEmail re-enqueues a failed email for another delivery attempt.
+// Only emails with status "failed" can be retried.
+func (s *Service) RetryEmail(emailUUID string, userID uint) (*SendResponse, error) {
+ em, err := s.emailRepo.FindByUUID(emailUUID)
+ if err != nil {
+ return nil, fmt.Errorf("email not found")
+ }
+ if em.UserID != userID {
+ return nil, fmt.Errorf("email not found")
+ }
+ if em.Status != models.EmailStatusFailed {
+ return nil, fmt.Errorf("only failed emails can be retried")
+ }
+
+ if s.enqueuer != nil {
+ em.Status = models.EmailStatusQueued
+ em.ErrorMessage = ""
+ _ = s.emailRepo.Update(em)
+ if err := s.enqueuer.EnqueueEmailSend(em.ID, ""); err != nil {
+ em.Status = models.EmailStatusFailed
+ em.ErrorMessage = fmt.Sprintf("failed to enqueue: %v", err)
+ _ = s.emailRepo.Update(em)
+ return nil, fmt.Errorf("failed to enqueue email: %w", err)
+ }
+ return &SendResponse{ID: em.UUID, Status: em.Status}, nil
+ }
+
+ // Synchronous fallback
+ return s.sendSync(em, userID, &SendRequest{
+ From: em.Sender,
+ To: em.Recipients,
+ Subject: em.Subject,
+ HTML: em.HTMLBody,
+ Text: em.TextBody,
+ ListUnsubscribeURL: em.ListUnsubscribeURL,
+ ListUnsubscribePost: em.ListUnsubscribePost,
+ })
+}
+
+// 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) {
+ if tmpl.ActiveVersionID == nil {
+ return nil, fmt.Errorf("template %q has no active version", tmpl.Name)
+ }
+
+ v, err := s.versionRepo.FindByID(*tmpl.ActiveVersionID)
+ if err != nil {
+ return nil, fmt.Errorf("failed to load active version: %w", err)
+ }
+
+ l := s.resolveLocalization(v.ID, language, tmpl.DefaultLanguage)
+ if l == nil {
+ return nil, fmt.Errorf("no localization found for template %q", tmpl.Name)
+ }
+
+ var css string
+ if v.StyleSheet != nil {
+ css = v.StyleSheet.CSS
+ }
+ input := &RenderInput{
+ SubjectTemplate: l.SubjectTemplate,
+ HTMLTemplate: l.HTMLTemplate,
+ TextTemplate: l.TextTemplate,
+ CSS: css,
+ }
+ return s.renderer.Render(input, data)
+}
+
+// resolveLocalization implements the language fallback strategy:
+// requested language → base language (e.g. fr-CA → fr) → template default → "en"
+func (s *Service) resolveLocalization(versionID uint, language, defaultLang string) *models.TemplateLocalization {
+ if language == "" {
+ language = defaultLang
+ }
+ if language == "" {
+ language = "en"
+ }
+
+ // Try exact match
+ l, err := s.localizationRepo.FindByVersionAndLanguage(versionID, language)
+ if err == nil {
+ return l
+ }
+
+ // Try base language (e.g. fr-CA → fr)
+ if idx := strings.Index(language, "-"); idx > 0 {
+ base := language[:idx]
+ l, err = s.localizationRepo.FindByVersionAndLanguage(versionID, base)
+ if err == nil {
+ return l
+ }
+ }
+
+ // Try template default language
+ if language != defaultLang && defaultLang != "" {
+ l, err = s.localizationRepo.FindByVersionAndLanguage(versionID, defaultLang)
+ if err == nil {
+ return l
+ }
+ }
+
+ // Try "en" as final fallback
+ if language != "en" && defaultLang != "en" {
+ l, err = s.localizationRepo.FindByVersionAndLanguage(versionID, "en")
+ if err == nil {
+ return l
+ }
+ }
+
+ return nil
+}
+
+// diffRecipients returns elements in original that are not in filtered.
+func diffRecipients(original, filtered []string) []string {
+ set := make(map[string]struct{}, len(filtered))
+ for _, e := range filtered {
+ set[e] = struct{}{}
+ }
+ var diff []string
+ for _, e := range original {
+ if _, ok := set[e]; !ok {
+ diff = append(diff, e)
+ }
+ }
+ return diff
+}
+
+// filterCustomHeaders removes headers that could conflict with system-set
+// headers or be used for spoofing. It returns a sanitized copy.
+func filterCustomHeaders(headers map[string]string) map[string]string {
+ // Headers that are set by the system and must not be overridden.
+ reserved := map[string]bool{
+ "from": true,
+ "to": true,
+ "subject": true,
+ "mime-version": true,
+ "content-type": true,
+ }
+
+ // Prefixes that must not appear in custom headers.
+ blockedPrefixes := []string{
+ "x-posta-",
+ "dkim-",
+ "arc-",
+ }
+
+ filtered := make(map[string]string, len(headers))
+ for key, value := range headers {
+ lower := strings.ToLower(key)
+ if reserved[lower] {
+ continue
+ }
+ blocked := false
+ for _, prefix := range blockedPrefixes {
+ if strings.HasPrefix(lower, prefix) {
+ blocked = true
+ break
+ }
+ }
+ if blocked {
+ continue
+ }
+ filtered[key] = value
+ }
+ return filtered
+}
+
+// checkDomainVerification enforces domain ownership verification when the user
+// has RequireVerifiedDomain enabled. It extracts the sender domain and checks
+// that it is registered and ownership-verified via TXT record.
+func (s *Service) checkDomainVerification(userID uint, from string) error {
+ if s.domainRepo == nil || s.userRepo == nil {
+ return nil
+ }
+
+ user, err := s.userRepo.FindByID(userID)
+ if err != nil {
+ return fmt.Errorf("failed to load user: %w", err)
+ }
+
+ if !user.RequireVerifiedDomain {
+ return nil
+ }
+
+ senderDomain := extractSenderDomain(from)
+ if senderDomain == "" {
+ return fmt.Errorf("domain_verification: could not extract domain from sender %q", from)
+ }
+
+ if !s.domainRepo.IsOwnershipVerified(userID, senderDomain) {
+ return fmt.Errorf("domain_verification: domain %q is not verified. Add and verify the domain or disable strict domain mode", senderDomain)
+ }
+
+ return nil
+}
+
+// extractSenderDomain returns the domain part of a sender address.
+func extractSenderDomain(from string) string {
+ bare := extractEmail(from)
+ parts := strings.SplitN(bare, "@", 2)
+ if len(parts) != 2 {
+ return ""
+ }
+ return strings.ToLower(parts[1])
+}
+
+// extractEmail extracts the bare email address from a string that may be in
+// RFC 5322 format like "Display Name <[email protected]>" or just "[email protected]".
+func extractEmail(from string) string {
+ addr, err := mail.ParseAddress(from)
+ if err != nil {
+ return from
+ }
+ return addr.Address
+}
diff --git a/internal/services/email/smtp_sender.go b/internal/services/email/smtp_sender.go
new file mode 100644
index 0000000..6ccb4a8
--- /dev/null
+++ b/internal/services/email/smtp_sender.go
@@ -0,0 +1,303 @@
+/*
+ * 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 email
+
+import (
+ "crypto/tls"
+ "encoding/base64"
+ "fmt"
+ "net/mail"
+ "net/smtp"
+ "strings"
+
+ "github.com/jkaninda/posta/internal/models"
+)
+
+type SMTPSender struct{}
+
+func NewSMTPSender() *SMTPSender {
+ return &SMTPSender{}
+}
+
+// TestConnection verifies that a connection to the SMTP server can be
+// established and, when credentials are provided, that authentication succeeds.
+func (s *SMTPSender) TestConnection(server *models.SMTPServer) error {
+ addr := fmt.Sprintf("%s:%d", server.Host, server.Port)
+ tlsConfig := &tls.Config{ServerName: server.Host}
+
+ var client *smtp.Client
+ var err error
+
+ switch server.Encryption {
+ case models.EncryptionSSL:
+ conn, dialErr := tls.Dial("tcp", addr, tlsConfig)
+ if dialErr != nil {
+ return fmt.Errorf("SSL dial failed: %w", dialErr)
+ }
+ defer func() { _ = conn.Close() }()
+ client, err = smtp.NewClient(conn, server.Host)
+ if err != nil {
+ return fmt.Errorf("SMTP client creation failed: %w", err)
+ }
+
+ case models.EncryptionSTARTTLS:
+ client, err = smtp.Dial(addr)
+ if err != nil {
+ return fmt.Errorf("SMTP dial failed: %w", err)
+ }
+ if err = client.StartTLS(tlsConfig); err != nil {
+ _ = client.Close()
+ return fmt.Errorf("STARTTLS failed: %w", err)
+ }
+
+ default: // none
+ client, err = smtp.Dial(addr)
+ if err != nil {
+ return fmt.Errorf("SMTP dial failed: %w", err)
+ }
+ }
+ defer func() { _ = client.Close() }()
+
+ if server.Username != "" {
+ if err := client.Auth(smtp.PlainAuth("", server.Username, server.Password, server.Host)); err != nil {
+ return fmt.Errorf("SMTP auth failed: %w", err)
+ }
+ }
+ return client.Quit()
+}
+
+func (s *SMTPSender) Send(server *models.SMTPServer, from string, to []string, subject, htmlBody, textBody string, attachments []models.Attachment, headers map[string]string, listUnsubscribeURL string, listUnsubscribePost bool) error {
+ addr := fmt.Sprintf("%s:%d", server.Host, server.Port)
+
+ var auth smtp.Auth
+ if server.Username != "" {
+ auth = smtp.PlainAuth("", server.Username, server.Password, server.Host)
+ }
+
+ msg := buildMessage(from, to, subject, htmlBody, textBody, attachments, headers, listUnsubscribeURL, listUnsubscribePost)
+
+ // Extract bare email for SMTP envelope (MAIL FROM), keep full format for headers
+ envelopeFrom := envelopeAddress(from)
+
+ switch server.Encryption {
+ case models.EncryptionSSL:
+ return sendWithImplicitTLS(addr, auth, server.Host, envelopeFrom, to, msg)
+ case models.EncryptionSTARTTLS:
+ return sendWithSTARTTLS(addr, auth, server.Host, envelopeFrom, to, msg)
+ default:
+ return smtp.SendMail(addr, auth, envelopeFrom, to, msg)
+ }
+}
+
+// envelopeAddress extracts the bare email from an RFC 5322 address like
+// "Display Name <[email protected]>", returning just "[email protected]".
+// If parsing fails, it returns the input unchanged.
+func envelopeAddress(from string) string {
+ addr, err := mail.ParseAddress(from)
+ if err != nil {
+ return from
+ }
+ return addr.Address
+}
+
+func sendWithImplicitTLS(addr string, auth smtp.Auth, host string, from string, to []string, msg []byte) error {
+ tlsConfig := &tls.Config{ServerName: host}
+
+ conn, err := tls.Dial("tcp", addr, tlsConfig)
+ if err != nil {
+ return fmt.Errorf("SSL dial failed: %w", err)
+ }
+
+ client, err := smtp.NewClient(conn, host)
+ if err != nil {
+ return fmt.Errorf("SMTP client creation failed: %w", err)
+ }
+ defer func() { _ = client.Close() }()
+
+ return sendViaClient(client, auth, from, to, msg)
+}
+
+func sendWithSTARTTLS(addr string, auth smtp.Auth, host string, from string, to []string, msg []byte) error {
+ client, err := smtp.Dial(addr)
+ if err != nil {
+ return fmt.Errorf("SMTP dial failed: %w", err)
+ }
+ defer func() { _ = client.Close() }()
+
+ tlsConfig := &tls.Config{ServerName: host}
+ if err := client.StartTLS(tlsConfig); err != nil {
+ return fmt.Errorf("STARTTLS failed: %w", err)
+ }
+
+ return sendViaClient(client, auth, from, to, msg)
+}
+
+func sendViaClient(client *smtp.Client, auth smtp.Auth, from string, to []string, msg []byte) error {
+ if auth != nil {
+ if err := client.Auth(auth); err != nil {
+ return fmt.Errorf("SMTP auth failed: %w", err)
+ }
+ }
+
+ if err := client.Mail(from); err != nil {
+ return fmt.Errorf("SMTP MAIL FROM failed: %w", err)
+ }
+ for _, addr := range to {
+ if err := client.Rcpt(envelopeAddress(addr)); err != nil {
+ return fmt.Errorf("SMTP RCPT TO failed: %w", err)
+ }
+ }
+
+ w, err := client.Data()
+ if err != nil {
+ return fmt.Errorf("SMTP DATA failed: %w", err)
+ }
+ if _, err := w.Write(msg); err != nil {
+ return fmt.Errorf("SMTP write failed: %w", err)
+ }
+ if err := w.Close(); err != nil {
+ return fmt.Errorf("SMTP close failed: %w", err)
+ }
+
+ return client.Quit()
+}
+
+func buildMessage(from string, to []string, subject, htmlBody, textBody string, attachments []models.Attachment, headers map[string]string, listUnsubscribeURL string, listUnsubscribePost bool) []byte {
+ var b strings.Builder
+
+ fmt.Fprintf(&b, "From: %s\r\n", from)
+ fmt.Fprintf(&b, "To: %s\r\n", strings.Join(to, ", "))
+ fmt.Fprintf(&b, "Subject: %s\r\n", subject)
+ b.WriteString("MIME-Version: 1.0\r\n")
+
+ // RFC 8058: List-Unsubscribe headers
+ if listUnsubscribeURL != "" {
+ fmt.Fprintf(&b, "List-Unsubscribe: <%s>\r\n", listUnsubscribeURL)
+ if listUnsubscribePost {
+ b.WriteString("List-Unsubscribe-Post: List-Unsubscribe=One-Click\r\n")
+ }
+ }
+
+ // Write custom headers (already filtered for safety)
+ for key, value := range headers {
+ fmt.Fprintf(&b, "%s: %s\r\n", key, value)
+ }
+
+ hasAttachments := len(attachments) > 0
+
+ if hasAttachments {
+ mixedBoundary := "posta-mixed-boundary"
+ altBoundary := "posta-alt-boundary"
+
+ fmt.Fprintf(&b, "Content-Type: multipart/mixed; boundary=\"%s\"\r\n\r\n", mixedBoundary)
+
+ // Body part
+ fmt.Fprintf(&b, "--%s\r\n", mixedBoundary)
+
+ if htmlBody != "" && textBody != "" {
+ fmt.Fprintf(&b, "Content-Type: multipart/alternative; boundary=\"%s\"\r\n\r\n", altBoundary)
+ fmt.Fprintf(&b, "--%s\r\n", altBoundary)
+ b.WriteString("Content-Type: text/plain; charset=\"UTF-8\"\r\n\r\n")
+ b.WriteString(textBody)
+ fmt.Fprintf(&b, "\r\n--%s\r\n", altBoundary)
+ b.WriteString("Content-Type: text/html; charset=\"UTF-8\"\r\n\r\n")
+ b.WriteString(htmlBody)
+ fmt.Fprintf(&b, "\r\n--%s--\r\n", altBoundary)
+ } else if htmlBody != "" {
+ b.WriteString("Content-Type: text/html; charset=\"UTF-8\"\r\n\r\n")
+ b.WriteString(htmlBody)
+ } else {
+ b.WriteString("Content-Type: text/plain; charset=\"UTF-8\"\r\n\r\n")
+ b.WriteString(textBody)
+ }
+
+ // Attachment parts
+ for _, att := range attachments {
+ fmt.Fprintf(&b, "\r\n--%s\r\n", mixedBoundary)
+ contentType := att.ContentType
+ if contentType == "" {
+ contentType = "application/octet-stream"
+ }
+ fmt.Fprintf(&b, "Content-Type: %s; name=\"%s\"\r\n", contentType, att.Filename)
+ b.WriteString("Content-Transfer-Encoding: base64\r\n")
+ fmt.Fprintf(&b, "Content-Disposition: attachment; filename=\"%s\"\r\n\r\n", att.Filename)
+
+ // Content is already base64-encoded from the API request
+ content := att.Content
+ for len(content) > 76 {
+ b.WriteString(content[:76])
+ b.WriteString("\r\n")
+ content = content[76:]
+ }
+ if len(content) > 0 {
+ b.WriteString(content)
+ }
+ }
+ fmt.Fprintf(&b, "\r\n--%s--\r\n", mixedBoundary)
+ } else {
+ altBoundary := "posta-boundary-abc123"
+ if htmlBody != "" && textBody != "" {
+ fmt.Fprintf(&b, "Content-Type: multipart/alternative; boundary=\"%s\"\r\n\r\n", altBoundary)
+ fmt.Fprintf(&b, "--%s\r\n", altBoundary)
+ b.WriteString("Content-Type: text/plain; charset=\"UTF-8\"\r\n\r\n")
+ b.WriteString(textBody)
+ fmt.Fprintf(&b, "\r\n--%s\r\n", altBoundary)
+ b.WriteString("Content-Type: text/html; charset=\"UTF-8\"\r\n\r\n")
+ b.WriteString(htmlBody)
+ fmt.Fprintf(&b, "\r\n--%s--\r\n", altBoundary)
+ } else if htmlBody != "" {
+ b.WriteString("Content-Type: text/html; charset=\"UTF-8\"\r\n\r\n")
+ b.WriteString(htmlBody)
+ } else {
+ b.WriteString("Content-Type: text/plain; charset=\"UTF-8\"\r\n\r\n")
+ b.WriteString(textBody)
+ }
+ }
+
+ return []byte(b.String())
+}
+
+// ValidateAttachments checks that attachments are within size limits.
+func ValidateAttachments(attachments []models.Attachment, maxAttachmentSize, maxTotalSize int64) error {
+ var totalSize int64
+ for _, att := range attachments {
+ if att.Filename == "" {
+ return fmt.Errorf("attachment filename is required")
+ }
+ decoded, err := base64.StdEncoding.DecodeString(att.Content)
+ if err != nil {
+ return fmt.Errorf("attachment %q has invalid base64 content", att.Filename)
+ }
+ size := int64(len(decoded))
+ if size > maxAttachmentSize {
+ return fmt.Errorf("attachment %q exceeds maximum size of %d bytes", att.Filename, maxAttachmentSize)
+ }
+ totalSize += size
+ }
+ if totalSize > maxTotalSize {
+ return fmt.Errorf("total attachment size exceeds maximum of %d bytes", maxTotalSize)
+ }
+ return nil
+}
diff --git a/internal/services/email/template_renderer.go b/internal/services/email/template_renderer.go
new file mode 100644
index 0000000..5b7ae1d
--- /dev/null
+++ b/internal/services/email/template_renderer.go
@@ -0,0 +1,294 @@
+/*
+ * 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 email
+
+import (
+ "bytes"
+ "fmt"
+ htmltmpl "html/template"
+ "regexp"
+ "strings"
+ texttmpl "text/template"
+
+ "github.com/jkaninda/okapi"
+ "github.com/vanng822/go-premailer/premailer"
+)
+
+// actionRe matches any {{ ... }} action block, including whitespace-trim variants.
+var actionRe = regexp.MustCompile(`\{\{(-?)\s*(.*?)\s*(-?)\}\}`)
+
+// identRe matches a bare identifier that needs a dot prefix (no leading dot or $).
+var identRe = regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_]*$`)
+
+// controlKeywords are Go template control keywords that must never be dot-prefixed.
+var controlKeywords = map[string]struct{}{
+ "range": {},
+ "end": {},
+ "if": {},
+ "else": {},
+ "with": {},
+ "template": {},
+ "block": {},
+ "define": {},
+ "nil": {},
+ "true": {},
+ "false": {},
+ "and": {},
+ "or": {},
+ "not": {},
+ "call": {},
+ "html": {},
+ "js": {},
+ "urlquery": {},
+ "print": {},
+ "println": {},
+ "printf": {},
+ "index": {},
+ "len": {},
+ "eq": {},
+ "ne": {},
+ "lt": {},
+ "le": {},
+ "gt": {},
+ "ge": {},
+}
+
+// normalizeTemplate rewrites bare identifiers inside {{ }} actions to their
+// dot-prefixed equivalents so they resolve against the data map instead of
+// being looked up as functions.
+//
+// Rules:
+// - {{ .varName }} → untouched (already dotted)
+// - {{ $var }} → untouched (template variable)
+// - {{ varName }} → {{ .varName }}
+// - {{ range features }} → {{ range .features }}
+// - {{ if active }} → {{ if .active }}
+// - {{ end }}, {{ else }} → untouched (no argument)
+// - {{- varName -}} → {{- .varName -}} (trim dashes preserved)
+func normalizeTemplate(s string) string {
+ return actionRe.ReplaceAllStringFunc(s, func(match string) string {
+ m := actionRe.FindStringSubmatch(match)
+ if m == nil {
+ return match
+ }
+ leftDash := m[1] // "-" or ""
+ inner := m[2] // content between {{ and }}
+ rightDash := m[3] // "-" or ""
+
+ open := "{{" + leftDash
+ close := rightDash + "}}"
+
+ // Rebuild with normalized inner content.
+ normalized := normalizeParts(inner)
+ return open + " " + normalized + " " + close
+ })
+}
+
+// normalizeParts normalizes the inner content of a template action.
+// It handles:
+// - Single tokens: "varName" → ".varName"
+// - Keyword + argument: "range features" → "range .features"
+// - Already-dotted or $-prefixed: left alone
+func normalizeParts(inner string) string {
+ parts := strings.Fields(inner)
+ if len(parts) == 0 {
+ return inner
+ }
+
+ first := parts[0]
+
+ if len(parts) == 1 {
+ return dotPrefix(first)
+ }
+
+ // Multi-token: keyword followed by an argument (e.g. "range features")
+ if _, isKeyword := controlKeywords[first]; isKeyword {
+ normalized := make([]string, len(parts))
+ normalized[0] = first
+ for i, p := range parts[1:] {
+ normalized[i+1] = dotPrefix(p)
+ }
+ return strings.Join(normalized, " ")
+ }
+
+ return inner
+}
+
+// dotPrefix adds a "." prefix to a bare identifier.
+// It leaves alone: already-dotted (.foo), variables ($foo), keywords, and "."
+func dotPrefix(token string) string {
+ if token == "." ||
+ strings.HasPrefix(token, ".") ||
+ strings.HasPrefix(token, "$") {
+ return token
+ }
+ if _, isKeyword := controlKeywords[token]; isKeyword {
+ return token
+ }
+ if identRe.MatchString(token) {
+ return "." + token
+ }
+ return token
+}
+
+type TemplateRenderer struct {
+ // MissingKeyBehavior controls how missing data keys are handled.
+ // "error" (default): return an error on missing key
+ // "zero": silently use zero value
+ // "invalid": render "<no value>"
+ MissingKeyBehavior string
+}
+
+func NewTemplateRenderer() *TemplateRenderer {
+ return &TemplateRenderer{
+ MissingKeyBehavior: "error",
+ }
+}
+
+type RenderInput struct {
+ SubjectTemplate string
+ HTMLTemplate string
+ TextTemplate string
+ CSS string
+}
+
+type RenderedTemplate struct {
+ Subject string
+ HTML string
+ Text string
+}
+
+func (r *TemplateRenderer) Render(input *RenderInput, data okapi.M) (*RenderedTemplate, error) {
+ missingKey := r.missingKeyOption()
+
+ subject, err := renderText("subject", normalizeTemplate(input.SubjectTemplate), data, missingKey)
+ if err != nil {
+ return nil, fmt.Errorf("failed to render subject: %w", err)
+ }
+
+ var html string
+ if input.HTMLTemplate != "" {
+ html, err = renderHTML("html", normalizeTemplate(input.HTMLTemplate), data, missingKey)
+ if err != nil {
+ return nil, fmt.Errorf("failed to render HTML: %w", err)
+ }
+ if input.CSS != "" {
+ html = injectCSS(html, input.CSS)
+ }
+ }
+
+ var text string
+ if input.TextTemplate != "" {
+ text, err = renderText("text", normalizeTemplate(input.TextTemplate), data, missingKey)
+ if err != nil {
+ return nil, fmt.Errorf("failed to render text: %w", err)
+ }
+ }
+
+ return &RenderedTemplate{
+ Subject: subject,
+ HTML: html,
+ Text: text,
+ }, nil
+}
+
+func (r *TemplateRenderer) missingKeyOption() string {
+ switch r.MissingKeyBehavior {
+ case "zero", "invalid":
+ return r.MissingKeyBehavior
+ default:
+ return "error"
+ }
+}
+
+// injectCSS inserts a <style> block into the rendered HTML and inlines styles
+// using premailer for maximum email client compatibility.
+func injectCSS(html, css string) string {
+ styleTag := "<style>\n" + css + "\n</style>"
+ htmlLower := strings.ToLower(html)
+
+ var withStyle string
+ switch {
+ case strings.Contains(htmlLower, "</head>"):
+ idx := strings.Index(htmlLower, "</head>")
+ withStyle = html[:idx] + styleTag + "\n" + html[idx:]
+ case strings.Contains(htmlLower, "<body"):
+ // Inject after opening <body> tag, not before </body>
+ idx := strings.Index(htmlLower, "<body")
+ end := strings.Index(html[idx:], ">")
+ if end != -1 {
+ insertAt := idx + end + 1
+ withStyle = html[:insertAt] + "\n" + styleTag + html[insertAt:]
+ } else {
+ withStyle = styleTag + "\n" + html
+ }
+ case strings.Contains(htmlLower, "</body>"):
+ idx := strings.Index(htmlLower, "</body>")
+ withStyle = html[:idx] + styleTag + "\n" + html[idx:]
+ default:
+ withStyle = styleTag + "\n" + html
+ }
+
+ opts := premailer.NewOptions()
+ opts.RemoveClasses = false
+ prem, err := premailer.NewPremailerFromString(withStyle, opts)
+ if err != nil {
+ return withStyle
+ }
+ inlined, err := prem.Transform()
+ if err != nil {
+ return withStyle
+ }
+ return inlined
+}
+
+func renderText(name, tmplStr string, data okapi.M, missingKey string) (string, error) {
+ t, err := texttmpl.New(name).
+ Option("missingkey=" + missingKey).
+ Parse(tmplStr)
+ if err != nil {
+ return "", fmt.Errorf("template parse error: %w", err)
+ }
+ var buf bytes.Buffer
+ if err := t.Execute(&buf, data); err != nil {
+ return "", fmt.Errorf("template execute error: %w", err)
+ }
+ return buf.String(), nil
+}
+
+// renderHTML uses html/template for auto-escaping of HTML content.
+func renderHTML(name, tmplStr string, data okapi.M, missingKey string) (string, error) {
+ t, err := htmltmpl.New(name).
+ Option("missingkey=" + missingKey).
+ Parse(tmplStr)
+ if err != nil {
+ return "", fmt.Errorf("template parse error: %w", err)
+ }
+ var buf bytes.Buffer
+ if err := t.Execute(&buf, data); err != nil {
+ return "", fmt.Errorf("template execute error: %w", err)
+ }
+ return buf.String(), nil
+}
diff --git a/internal/services/eventbus/eventbus.go b/internal/services/eventbus/eventbus.go
new file mode 100644
index 0000000..bb81218
--- /dev/null
+++ b/internal/services/eventbus/eventbus.go
@@ -0,0 +1,107 @@
+/*
+ * 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 eventbus
+
+import (
+ "encoding/json"
+ "sync"
+
+ "github.com/jkaninda/logger"
+ "github.com/jkaninda/posta/internal/models"
+ "github.com/jkaninda/posta/internal/storage/repositories"
+)
+
+// EventBus provides an in-memory pub/sub for events with database persistence.
+type EventBus struct {
+ repo *repositories.EventRepository
+ mu sync.RWMutex
+ subscribers map[uint64]chan *models.Event
+ nextID uint64
+}
+
+func New(repo *repositories.EventRepository) *EventBus {
+ return &EventBus{
+ repo: repo,
+ subscribers: make(map[uint64]chan *models.Event),
+ }
+}
+
+// Publish persists an event and broadcasts it to all SSE subscribers.
+func (b *EventBus) Publish(event *models.Event) {
+ if err := b.repo.Create(event); err != nil {
+ logger.Error("failed to persist event", "error", err)
+ }
+
+ b.mu.RLock()
+ defer b.mu.RUnlock()
+
+ for _, ch := range b.subscribers {
+ select {
+ case ch <- event:
+ default:
+ // subscriber too slow, skip
+ }
+ }
+}
+
+// PublishSimple is a convenience method for emitting events with JSON metadata.
+func (b *EventBus) PublishSimple(category models.EventCategory, eventType string, actorID *uint, actorName, clientIP, message string, meta map[string]any) {
+ var metaStr string
+ if meta != nil {
+ if data, err := json.Marshal(meta); err == nil {
+ metaStr = string(data)
+ }
+ }
+
+ b.Publish(&models.Event{
+ Category: category,
+ Type: eventType,
+ ActorID: actorID,
+ ActorName: actorName,
+ ClientIP: clientIP,
+ Message: message,
+ Metadata: metaStr,
+ })
+}
+
+// Subscribe returns a channel that receives new events and a function to unsubscribe.
+func (b *EventBus) Subscribe() (<-chan *models.Event, func()) {
+ ch := make(chan *models.Event, 64)
+
+ b.mu.Lock()
+ id := b.nextID
+ b.nextID++
+ b.subscribers[id] = ch
+ b.mu.Unlock()
+
+ unsub := func() {
+ b.mu.Lock()
+ delete(b.subscribers, id)
+ b.mu.Unlock()
+ close(ch)
+ }
+
+ return ch, unsub
+}
diff --git a/internal/services/ratelimit/redis_limiter.go b/internal/services/ratelimit/redis_limiter.go
new file mode 100644
index 0000000..4e72b9a
--- /dev/null
+++ b/internal/services/ratelimit/redis_limiter.go
@@ -0,0 +1,116 @@
+/*
+ * 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 ratelimit
+
+import (
+ "context"
+ "fmt"
+ "time"
+
+ "github.com/redis/go-redis/v9"
+)
+
+// SettingsProvider is an interface for retrieving dynamic rate limit settings.
+type SettingsProvider interface {
+ DefaultRateLimitHourly() int
+ DefaultRateLimitDaily() int
+}
+
+type RedisLimiter struct {
+ client *redis.Client
+ hourlyLimit int
+ dailyLimit int
+ settings SettingsProvider
+}
+
+func NewRedisLimiter(client *redis.Client, hourlyLimit, dailyLimit int) *RedisLimiter {
+ return &RedisLimiter{
+ client: client,
+ hourlyLimit: hourlyLimit,
+ dailyLimit: dailyLimit,
+ }
+}
+
+// SetSettings sets a dynamic settings provider. When set, rate limits
+// are read from the provider instead of using the static config values.
+func (l *RedisLimiter) SetSettings(sp SettingsProvider) {
+ l.settings = sp
+}
+
+func (l *RedisLimiter) effectiveLimits() (int, int) {
+ if l.settings != nil {
+ return l.settings.DefaultRateLimitHourly(), l.settings.DefaultRateLimitDaily()
+ }
+ return l.hourlyLimit, l.dailyLimit
+}
+
+// Allow checks if the user is within rate limits. Returns an error if exceeded.
+func (l *RedisLimiter) Allow(ctx context.Context, userEmail string) error {
+ hourlyLimit, dailyLimit := l.effectiveLimits()
+
+ hourKey := fmt.Sprintf("ratelimit:hour:%s:%s", userEmail, time.Now().Format("2006010215"))
+ dayKey := fmt.Sprintf("ratelimit:day:%s:%s", userEmail, time.Now().Format("20060102"))
+
+ hourCount, err := l.client.Incr(ctx, hourKey).Result()
+ if err != nil {
+ return fmt.Errorf("rate limit check failed: %w", err)
+ }
+ if hourCount == 1 {
+ l.client.Expire(ctx, hourKey, time.Hour)
+ }
+ if hourCount > int64(hourlyLimit) {
+ return fmt.Errorf("hourly rate limit exceeded (%d/%d)", hourCount, hourlyLimit)
+ }
+
+ dayCount, err := l.client.Incr(ctx, dayKey).Result()
+ if err != nil {
+ return fmt.Errorf("rate limit check failed: %w", err)
+ }
+ if dayCount == 1 {
+ l.client.Expire(ctx, dayKey, 24*time.Hour)
+ }
+ if dayCount > int64(dailyLimit) {
+ return fmt.Errorf("daily rate limit exceeded (%d/%d)", dayCount, dailyLimit)
+ }
+
+ return nil
+}
+
+// AllowLogin checks if a login attempt from the given IP is within rate limits.
+// Allows 10 attempts per 15-minute window.
+func (l *RedisLimiter) AllowLogin(ctx context.Context, ip string) error {
+ key := fmt.Sprintf("ratelimit:login:%s:%s", ip, time.Now().Format("200601021504")[:11]) // 15-min window
+ count, err := l.client.Incr(ctx, key).Result()
+ if err != nil {
+ return nil // fail open
+ }
+ if count == 1 {
+ l.client.Expire(ctx, key, 15*time.Minute)
+ }
+ if count > 10 {
+ return fmt.Errorf("too many login attempts, try again later")
+ }
+ return nil
+}
diff --git a/internal/services/retry/worker.go b/internal/services/retry/worker.go
new file mode 100644
index 0000000..1ce8923
--- /dev/null
+++ b/internal/services/retry/worker.go
@@ -0,0 +1,180 @@
+/*
+ * 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 retry
+
+import (
+ "context"
+ "sync"
+ "time"
+
+ "github.com/jkaninda/logger"
+ "github.com/jkaninda/posta/internal/models"
+ "github.com/jkaninda/posta/internal/services/email"
+ "github.com/jkaninda/posta/internal/services/webhook"
+ "github.com/jkaninda/posta/internal/storage/repositories"
+)
+
+// Worker periodically retries failed emails that haven't exceeded their
+// SMTP server's max_retries limit.
+type Worker struct {
+ emailRepo *repositories.EmailRepository
+ smtpRepo *repositories.SMTPRepository
+ sender *email.SMTPSender
+ dispatcher *webhook.Dispatcher
+ enqueuer email.EmailEnqueuer
+ interval time.Duration
+ onSent func()
+ onFailed func()
+ onRetry func()
+ stopOnce sync.Once
+ stop chan struct{}
+}
+
+func NewWorker(
+ emailRepo *repositories.EmailRepository,
+ smtpRepo *repositories.SMTPRepository,
+ dispatcher *webhook.Dispatcher,
+ interval time.Duration,
+) *Worker {
+ return &Worker{
+ emailRepo: emailRepo,
+ smtpRepo: smtpRepo,
+ sender: email.NewSMTPSender(),
+ dispatcher: dispatcher,
+ interval: interval,
+ stop: make(chan struct{}),
+ }
+}
+
+// SetEnqueuer sets an enqueuer so retries are re-enqueued to the background worker
+// instead of being sent synchronously.
+func (w *Worker) SetEnqueuer(eq email.EmailEnqueuer) {
+ w.enqueuer = eq
+}
+
+// OnSent sets a callback invoked after each successful retry.
+func (w *Worker) OnSent(fn func()) { w.onSent = fn }
+
+// OnFailed sets a callback invoked after each failed retry.
+func (w *Worker) OnFailed(fn func()) { w.onFailed = fn }
+
+// OnRetry sets a callback invoked for each retry attempt.
+func (w *Worker) OnRetry(fn func()) { w.onRetry = fn }
+
+// Start begins the retry loop in a background goroutine.
+func (w *Worker) Start(ctx context.Context) {
+ go w.run(ctx)
+}
+
+// Stop signals the worker to stop.
+func (w *Worker) Stop() {
+ w.stopOnce.Do(func() { close(w.stop) })
+}
+
+func (w *Worker) run(ctx context.Context) {
+ logger.Info("retry worker started", "interval", w.interval)
+ ticker := time.NewTicker(w.interval)
+ defer ticker.Stop()
+
+ for {
+ select {
+ case <-ctx.Done():
+ logger.Info("retry worker stopped (context cancelled)")
+ return
+ case <-w.stop:
+ logger.Info("retry worker stopped")
+ return
+ case <-ticker.C:
+ w.processRetries()
+ }
+ }
+}
+
+func (w *Worker) processRetries() {
+ // Get all SMTP servers that have retries enabled
+ smtpServers, err := w.smtpRepo.FindAllWithRetries()
+ if err != nil {
+ logger.Error("retry worker: failed to load SMTP servers", "error", err)
+ return
+ }
+
+ for _, server := range smtpServers {
+ emails, err := w.emailRepo.FindFailedForRetry(server.UserID, server.MaxRetries)
+ if err != nil {
+ logger.Error("retry worker: failed to load failed emails", "user_id", server.UserID, "error", err)
+ continue
+ }
+
+ for i := range emails {
+ w.retryEmail(&emails[i], &server)
+ }
+ }
+}
+
+func (w *Worker) retryEmail(em *models.Email, server *models.SMTPServer) {
+ if w.onRetry != nil {
+ w.onRetry()
+ }
+
+ // If an enqueuer is available, re-enqueue instead of sending synchronously
+ if w.enqueuer != nil {
+ em.Status = models.EmailStatusQueued
+ em.RetryCount++
+ _ = w.emailRepo.Update(em)
+ if err := w.enqueuer.EnqueueEmailSend(em.ID, ""); err != nil {
+ em.Status = models.EmailStatusFailed
+ em.ErrorMessage = err.Error()
+ _ = w.emailRepo.Update(em)
+ logger.Error("retry worker: failed to re-enqueue email", "id", em.ID, "error", err)
+ } else {
+ logger.Info("retry worker: email re-enqueued", "id", em.ID, "attempt", em.RetryCount)
+ }
+ return
+ }
+
+ // Synchronous fallback
+ em.RetryCount++
+
+ if err := w.sender.Send(server, em.Sender, em.Recipients, em.Subject, em.HTMLBody, em.TextBody, nil, nil, em.ListUnsubscribeURL, em.ListUnsubscribePost); err != nil {
+ em.ErrorMessage = err.Error()
+ _ = w.emailRepo.Update(em)
+ logger.Debug("retry worker: email retry failed", "id", em.ID, "attempt", em.RetryCount, "error", err)
+ if w.onFailed != nil {
+ w.onFailed()
+ }
+ return
+ }
+
+ now := time.Now()
+ em.Status = models.EmailStatusSent
+ em.SentAt = &now
+ em.ErrorMessage = ""
+ _ = w.emailRepo.Update(em)
+ w.dispatcher.Dispatch(em.UserID, "email.sent", em.UUID, em.Sender)
+ logger.Info("retry worker: email sent successfully", "id", em.ID, "attempt", em.RetryCount)
+ if w.onSent != nil {
+ w.onSent()
+ }
+}
diff --git a/internal/services/seeder/constants.go b/internal/services/seeder/constants.go
new file mode 100644
index 0000000..808791f
--- /dev/null
+++ b/internal/services/seeder/constants.go
@@ -0,0 +1,236 @@
+/*
+ * 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 seeder
+
+const defaultCSS = `body {
+ margin: 0;
+ padding: 0;
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Arial, sans-serif;
+ font-size: 16px;
+ line-height: 1.6;
+ color: #111827;
+ background-color: #f9fafb;
+}
+
+.email-wrapper {
+ width: 100%;
+ padding: 32px 0;
+ background-color: #f9fafb;
+}
+
+.email-container {
+ max-width: 600px;
+ margin: 0 auto;
+ background-color: #ffffff;
+ border-radius: 10px;
+ overflow: hidden;
+ border: 1px solid #e5e7eb;
+}
+
+.email-header {
+ background: linear-gradient(135deg, #7e22ce, #a855f7);
+ color: #ffffff;
+ padding: 36px;
+ text-align: center;
+}
+
+.email-header h1 {
+ margin: 0 0 6px;
+ font-size: 26px;
+ font-weight: 700;
+}
+
+.email-header p {
+ margin: 0;
+ font-size: 14px;
+ opacity: 0.9;
+}
+
+.email-body {
+ padding: 32px 36px;
+}
+
+.email-body h2 {
+ margin-top: 0;
+ margin-bottom: 16px;
+ color: #111827;
+ font-size: 20px;
+}
+
+.email-body p {
+ margin: 0 0 16px;
+ color: #4b5563;
+}
+
+.feature-list {
+ list-style: none;
+ padding: 0;
+ margin: 20px 0 24px;
+}
+
+.feature-list li {
+ padding: 10px 0;
+ border-bottom: 1px solid #e5e7eb;
+ color: #4b5563;
+ font-size: 15px;
+}
+
+.feature-list li:last-child {
+ border-bottom: none;
+}
+
+.btn {
+ display: inline-block;
+ padding: 14px 26px;
+ background: linear-gradient(135deg, #7e22ce, #a855f7);
+ color: #ffffff;
+ text-decoration: none;
+ border-radius: 6px;
+ font-weight: 600;
+ font-size: 14px;
+}
+
+.email-footer {
+ padding: 24px 36px;
+ text-align: center;
+ font-size: 13px;
+ color: #9ca3af;
+ border-top: 1px solid #e5e7eb;
+ background-color: #f9fafb;
+}
+
+.email-footer a {
+ color: #9333ea;
+ text-decoration: none;
+}
+`
+
+const defaultHTMLTemplate = `<div class="email-wrapper">
+ <div class="email-container">
+ <div class="email-header">
+ <h1>Welcome to Posta</h1>
+ <p>Your self-hosted email delivery platform</p>
+ </div>
+ <div class="email-body">
+ <h2>Hello {{name}},</h2>
+ <p>Welcome to <strong>{{product}}</strong>. Your account is ready and you can start sending emails immediately.</p>
+ <p>{{product}} provides the following capabilities:</p>
+ <ul class="feature-list">
+ {{range features}}
+ <li>{{.}}</li>
+ {{end}}
+ </ul>
+ <p>Helpful resources:</p>
+ <ul>
+ {{range links}}
+ <li><a href="{{.url}}">{{.title}}</a></li>
+ {{end}}
+ </ul>
+ <p style="text-align:center;margin:32px 0;">
+ <a href="{{docs}}" class="btn">View API Documentation</a>
+ </p>
+ <p>Best regards,<br/>The {{company}} Team</p>
+ </div>
+ <div class="email-footer">
+ <p>© {{year}} {{company}} — Licensed under Apache 2.0</p>
+ </div>
+ </div>
+</div>`
+
+const defaultTextTemplate = `Hello {{name}},
+
+Welcome to {{product}}.
+
+Your account is ready and you can begin sending emails immediately.
+
+Key capabilities:
+{{range features}}
+- {{.}}
+{{end}}
+
+Helpful resources:
+{{range links}}
+- {{.title}}: {{.url}}
+{{end}}
+
+Best regards,
+The {{company}} Team
+
+© {{year}} {{company}} — Licensed under Apache 2.0
+`
+
+const defaultHTMLTemplateFr = `<div class="email-wrapper">
+ <div class="email-container">
+ <div class="email-header">
+ <h1>Bienvenue sur Posta</h1>
+ <p>Votre plateforme d'envoi d'e-mails auto-hébergée</p>
+ </div>
+ <div class="email-body">
+ <h2>Bonjour {{name}},</h2>
+ <p>Bienvenue sur <strong>{{product}}</strong>. Votre compte est prêt et vous pouvez commencer à envoyer des emails immédiatement.</p>
+ <p>{{product}} offre les fonctionnalités suivantes :</p>
+ <ul class="feature-list">
+ {{range features}}
+ <li>{{.}}</li>
+ {{end}}
+ </ul>
+ <p>Ressources utiles :</p>
+ <ul>
+ {{range links}}
+ <li><a href="{{.url}}">{{.title}}</a></li>
+ {{end}}
+ </ul>
+ <p style="text-align:center;margin:32px 0;">
+ <a href="{{docs}}" class="btn">Voir la documentation</a>
+ </p>
+ <p>Cordialement,<br/>L'équipe {{company}}</p>
+ </div>
+ <div class="email-footer">
+ <p>© {{year}} {{company}} — Licence Apache 2.0</p>
+ </div>
+ </div>
+</div>`
+
+const defaultTextTemplateFr = `Bonjour {{name}},
+
+Bienvenue sur {{product}}.
+
+Votre compte est prêt et vous pouvez commencer à envoyer des emails immédiatement.
+
+Fonctionnalités principales :
+{{range features}}
+- {{.}}
+{{end}}
+
+Ressources utiles :
+{{range links}}
+- {{.title}} : {{.url}}
+{{end}}
+
+Cordialement,
+L'équipe {{company}}
+
+© {{year}} {{company}} — Licence Apache 2.0
+`
diff --git a/internal/services/seeder/seeder.go b/internal/services/seeder/seeder.go
new file mode 100644
index 0000000..9362493
--- /dev/null
+++ b/internal/services/seeder/seeder.go
@@ -0,0 +1,185 @@
+/*
+ * 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 seeder
+
+import (
+ "encoding/json"
+ "fmt"
+ "time"
+
+ goutils "github.com/jkaninda/go-utils"
+ "github.com/jkaninda/logger"
+ "github.com/jkaninda/okapi"
+ "github.com/jkaninda/posta/internal/models"
+ "github.com/jkaninda/posta/internal/storage/repositories"
+)
+
+type Seeder struct {
+ templateRepo *repositories.TemplateRepository
+ stylesheetRepo *repositories.StyleSheetRepository
+ versionRepo *repositories.TemplateVersionRepository
+ localizationRepo *repositories.TemplateLocalizationRepository
+ languageRepo *repositories.LanguageRepository
+}
+
+func New(
+ templateRepo *repositories.TemplateRepository,
+ stylesheetRepo *repositories.StyleSheetRepository,
+ versionRepo *repositories.TemplateVersionRepository,
+ localizationRepo *repositories.TemplateLocalizationRepository,
+ languageRepo *repositories.LanguageRepository,
+) *Seeder {
+ return &Seeder{
+ templateRepo: templateRepo,
+ stylesheetRepo: stylesheetRepo,
+ versionRepo: versionRepo,
+ localizationRepo: localizationRepo,
+ languageRepo: languageRepo,
+ }
+}
+
+// SeedUserDefaults creates default stylesheet and template for a user
+func (s *Seeder) SeedUserDefaults(userID uint, userName string) {
+ if userName == "" {
+ userName = "Jonas"
+ }
+ templates, total, err := s.templateRepo.FindByUserID(userID, 1, 0)
+ if err != nil || total > 0 || len(templates) > 0 {
+ return
+ }
+
+ // Create default stylesheet
+ ss := &models.StyleSheet{
+ UserID: userID,
+ Name: "Default",
+ CSS: defaultCSS,
+ }
+ if err := s.stylesheetRepo.Create(ss); err != nil {
+ logger.Error("failed to seed default stylesheet", "user_id", userID, "error", err)
+ return
+ }
+
+ sample := okapi.M{
+ "name": userName,
+ "product": "Posta",
+ "company": "Posta",
+ "year": time.Now().Year(),
+ "docs": fmt.Sprintf("%s/docs", goutils.Env("POSTA_WEB_URL", "")),
+ "features": []string{
+ "REST Email API",
+ "Versioned templates with localization",
+ "Multiple SMTP server management",
+ "Domain verification (SPF, DKIM, DMARC)",
+ "Email analytics and event webhooks",
+ },
+
+ "links": []map[string]string{
+ {
+ "title": "API Documentation",
+ "url": "/docs",
+ },
+ {
+ "title": "GitHub Repository",
+ "url": "https://github.com/jkaninda/posta",
+ },
+ },
+ }
+
+ b, _ := json.MarshalIndent(sample, "", " ")
+ sampleData := string(b)
+
+ // Create default template linked to the stylesheet
+ tmpl := &models.Template{
+ UserID: userID,
+ Name: "Welcome Email",
+ DefaultLanguage: "en",
+ Description: "Welcome email introducing Posta and its features",
+ SampleData: sampleData,
+ }
+ if err := s.templateRepo.Create(tmpl); err != nil {
+ logger.Error("failed to seed default template", "user_id", userID, "error", err)
+ return
+ }
+
+ // Create a default version with an English localization
+ v := &models.TemplateVersion{
+ TemplateID: tmpl.ID,
+ Version: 1,
+ StyleSheetID: &ss.ID,
+ SampleData: sampleData,
+ }
+ if err := s.versionRepo.Create(v); err != nil {
+ logger.Error("failed to seed default template version", "user_id", userID, "error", err)
+ return
+ }
+
+ l := &models.TemplateLocalization{
+ VersionID: v.ID,
+ Language: "en",
+ SubjectTemplate: "Welcome to Posta, {{name}}!",
+ HTMLTemplate: defaultHTMLTemplate,
+ TextTemplate: defaultTextTemplate,
+ }
+ if err := s.localizationRepo.Create(l); err != nil {
+ logger.Error("failed to seed default localization", "user_id", userID, "error", err)
+ return
+ }
+
+ lFr := &models.TemplateLocalization{
+ VersionID: v.ID,
+ Language: "fr",
+ SubjectTemplate: "Bienvenue sur Posta, {{name}} !",
+ HTMLTemplate: defaultHTMLTemplateFr,
+ TextTemplate: defaultTextTemplateFr,
+ }
+ if err := s.localizationRepo.Create(lFr); err != nil {
+ logger.Error("failed to seed French localization", "user_id", userID, "error", err)
+ }
+
+ // Activate the version
+ vID := v.ID
+ tmpl.ActiveVersionID = &vID
+ if err := s.templateRepo.Update(tmpl); err != nil {
+ logger.Error("failed to activate default version", "user_id", userID, "error", err)
+ return
+ }
+
+ // Seed default languages
+ defaultLanguages := []struct {
+ Code string
+ Name string
+ }{
+ {"en", "English"},
+ {"fr", "French"},
+ }
+ for _, dl := range defaultLanguages {
+ lang := &models.Language{UserID: userID, Code: dl.Code, Name: dl.Name}
+ if err := s.languageRepo.Create(lang); err != nil {
+ logger.Error("failed to seed language", "user_id", userID, "code", dl.Code, "error", err)
+ }
+ }
+
+ logger.Info("seeded default stylesheet, template, version, localization, and languages", "user_id", userID)
+}
diff --git a/internal/services/seeder/settings.go b/internal/services/seeder/settings.go
new file mode 100644
index 0000000..bc72c30
--- /dev/null
+++ b/internal/services/seeder/settings.go
@@ -0,0 +1,61 @@
+/*
+ * 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 seeder
+
+import (
+ "github.com/jkaninda/logger"
+ "github.com/jkaninda/posta/internal/models"
+ "github.com/jkaninda/posta/internal/storage/repositories"
+)
+
+// SeedDefaultSettings creates default platform settings if they don't already exist.
+func SeedDefaultSettings(repo *repositories.SettingRepository) {
+ defaults := []models.Setting{
+ {Key: "registration_enabled", Value: "false", Type: "bool"},
+ {Key: "require_email_verification", Value: "true", Type: "bool"},
+ {Key: "require_domain_verification", Value: "true", Type: "bool"},
+ {Key: "default_rate_limit_hourly", Value: "100", Type: "int"},
+ {Key: "default_rate_limit_daily", Value: "1000", Type: "int"},
+ {Key: "max_batch_size", Value: "100", Type: "int"},
+ {Key: "max_attachment_size_mb", Value: "10", Type: "int"},
+ {Key: "retention_days", Value: "30", Type: "int"},
+ {Key: "global_bounce_threshold", Value: "5", Type: "int"},
+ {Key: "smtp_timeout_seconds", Value: "30", Type: "int"},
+ {Key: "maintenance_mode", Value: "false", Type: "bool"},
+ {Key: "allowed_signup_domains", Value: "", Type: "string"},
+ {Key: "two_factor_required", Value: "false", Type: "bool"},
+ {Key: "audit_log_retention_days", Value: "90", Type: "int"},
+ {Key: "webhook_delivery_retention_days", Value: "30", Type: "int"},
+ }
+
+ for i := range defaults {
+ if _, err := repo.FindByKey(defaults[i].Key); err != nil {
+ if err := repo.Upsert(&defaults[i]); err != nil {
+ logger.Error("failed to seed setting", "key", defaults[i].Key, "error", err)
+ }
+ }
+ }
+ logger.Info("default platform settings seeded")
+}
diff --git a/internal/services/settings/provider.go b/internal/services/settings/provider.go
new file mode 100644
index 0000000..6b54473
--- /dev/null
+++ b/internal/services/settings/provider.go
@@ -0,0 +1,140 @@
+/*
+ * 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 settings
+
+import (
+ "strconv"
+ "sync"
+ "time"
+
+ "github.com/jkaninda/logger"
+ "github.com/jkaninda/posta/internal/storage/repositories"
+)
+
+// Provider gives live access to platform settings with a short cache.
+// It reads from the database and caches values in memory, refreshing
+// periodically so that admin changes take effect without a restart.
+type Provider struct {
+ repo *repositories.SettingRepository
+ mu sync.RWMutex
+ cache map[string]string
+ loadedAt time.Time
+ cacheTTL time.Duration
+}
+
+// NewProvider creates a settings provider with a default 30-second cache TTL.
+func NewProvider(repo *repositories.SettingRepository) *Provider {
+ p := &Provider{
+ repo: repo,
+ cache: make(map[string]string),
+ cacheTTL: 30 * time.Second,
+ }
+ p.refresh()
+ return p
+}
+
+func (p *Provider) refresh() {
+ settings, err := p.repo.FindAll()
+ if err != nil {
+ logger.Error("settings provider: failed to refresh", "error", err)
+ return
+ }
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ p.cache = make(map[string]string, len(settings))
+ for _, s := range settings {
+ p.cache[s.Key] = s.Value
+ }
+ p.loadedAt = time.Now()
+}
+
+func (p *Provider) ensureFresh() {
+ p.mu.RLock()
+ stale := time.Since(p.loadedAt) > p.cacheTTL
+ p.mu.RUnlock()
+ if stale {
+ p.refresh()
+ }
+}
+
+// GetString returns a string setting or the fallback if not found.
+func (p *Provider) GetString(key, fallback string) string {
+ p.ensureFresh()
+ p.mu.RLock()
+ defer p.mu.RUnlock()
+ if v, ok := p.cache[key]; ok {
+ return v
+ }
+ return fallback
+}
+
+// GetInt returns an integer setting or the fallback if not found or invalid.
+func (p *Provider) GetInt(key string, fallback int) int {
+ s := p.GetString(key, "")
+ if s == "" {
+ return fallback
+ }
+ v, err := strconv.Atoi(s)
+ if err != nil {
+ return fallback
+ }
+ return v
+}
+
+// GetBool returns a boolean setting or the fallback if not found.
+func (p *Provider) GetBool(key string, fallback bool) bool {
+ s := p.GetString(key, "")
+ if s == "" {
+ return fallback
+ }
+ v, err := strconv.ParseBool(s)
+ if err != nil {
+ return fallback
+ }
+ return v
+}
+
+// Convenience accessors for commonly used settings.
+
+func (p *Provider) MaintenanceMode() bool { return p.GetBool("maintenance_mode", false) }
+func (p *Provider) RegistrationEnabled() bool { return p.GetBool("registration_enabled", false) }
+func (p *Provider) RequireEmailVerification() bool {
+ return p.GetBool("require_email_verification", true)
+}
+func (p *Provider) RequireDomainVerification() bool {
+ return p.GetBool("require_domain_verification", true)
+}
+func (p *Provider) TwoFactorRequired() bool { return p.GetBool("two_factor_required", false) }
+func (p *Provider) DefaultRateLimitHourly() int { return p.GetInt("default_rate_limit_hourly", 100) }
+func (p *Provider) DefaultRateLimitDaily() int { return p.GetInt("default_rate_limit_daily", 1000) }
+func (p *Provider) MaxBatchSize() int { return p.GetInt("max_batch_size", 100) }
+func (p *Provider) MaxAttachmentSizeMB() int { return p.GetInt("max_attachment_size_mb", 10) }
+func (p *Provider) GlobalBounceThreshold() int { return p.GetInt("global_bounce_threshold", 5) }
+func (p *Provider) SMTPTimeoutSeconds() int { return p.GetInt("smtp_timeout_seconds", 30) }
+func (p *Provider) RetentionDays() int { return p.GetInt("retention_days", 30) }
+func (p *Provider) AuditLogRetentionDays() int { return p.GetInt("audit_log_retention_days", 90) }
+func (p *Provider) WebhookDeliveryRetentionDays() int {
+ return p.GetInt("webhook_delivery_retention_days", 30)
+}
diff --git a/internal/services/twofactor/totp.go b/internal/services/twofactor/totp.go
new file mode 100644
index 0000000..4c82ddc
--- /dev/null
+++ b/internal/services/twofactor/totp.go
@@ -0,0 +1,47 @@
+/*
+ * 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 twofactor
+
+import (
+ "github.com/pquerna/otp/totp"
+)
+
+// GenerateSecret creates a new TOTP secret for a user.
+func GenerateSecret(email string) (string, string, error) {
+ key, err := totp.Generate(totp.GenerateOpts{
+ Issuer: "Posta",
+ AccountName: email,
+ })
+ if err != nil {
+ return "", "", err
+ }
+ // Return secret and the otpauth URL (for QR code generation)
+ return key.Secret(), key.URL(), nil
+}
+
+// ValidateCode verifies a TOTP code against a secret.
+func ValidateCode(secret, code string) bool {
+ return totp.Validate(code, secret)
+}
diff --git a/internal/services/webhook/dispatcher.go b/internal/services/webhook/dispatcher.go
new file mode 100644
index 0000000..2c19913
--- /dev/null
+++ b/internal/services/webhook/dispatcher.go
@@ -0,0 +1,278 @@
+/*
+ * 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 webhook
+
+import (
+ "bytes"
+ "crypto/hmac"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/mail"
+ "strings"
+ "time"
+
+ "github.com/jkaninda/logger"
+
+ "github.com/jkaninda/posta/internal/models"
+ "github.com/jkaninda/posta/internal/storage/repositories"
+)
+
+const (
+ defaultMaxRetries = 3
+ defaultRetryBaseWait = 2 * time.Second
+ defaultTimeout = 10 * time.Second
+)
+
+// Config holds configurable settings for the webhook dispatcher.
+type Config struct {
+ MaxRetries int
+ Timeout time.Duration
+}
+
+type Dispatcher struct {
+ repo *repositories.WebhookRepository
+ deliveryRepo *repositories.WebhookDeliveryRepository
+ client *http.Client
+ maxRetries int
+ onDeliverySuccess func()
+ onDeliveryFailed func()
+ onDeliveryDone func(float64) // duration in seconds
+}
+
+func NewDispatcher(repo *repositories.WebhookRepository) *Dispatcher {
+ return &Dispatcher{
+ repo: repo,
+ maxRetries: defaultMaxRetries,
+ client: &http.Client{
+ Timeout: defaultTimeout,
+ },
+ }
+}
+
+// SetConfig applies configurable settings to the dispatcher.
+func (d *Dispatcher) SetConfig(cfg Config) {
+ if cfg.MaxRetries > 0 {
+ d.maxRetries = cfg.MaxRetries
+ }
+ if cfg.Timeout > 0 {
+ d.client.Timeout = cfg.Timeout
+ }
+}
+
+// SetDeliveryRepo sets the repository used to record delivery attempts.
+func (d *Dispatcher) SetDeliveryRepo(repo *repositories.WebhookDeliveryRepository) {
+ d.deliveryRepo = repo
+}
+
+// OnDeliverySuccess sets a callback invoked after each successful webhook delivery.
+func (d *Dispatcher) OnDeliverySuccess(fn func()) { d.onDeliverySuccess = fn }
+
+// OnDeliveryFailed sets a callback invoked after each failed webhook delivery.
+func (d *Dispatcher) OnDeliveryFailed(fn func()) { d.onDeliveryFailed = fn }
+
+// OnDeliveryDone sets a callback invoked after each delivery attempt with its duration.
+func (d *Dispatcher) OnDeliveryDone(fn func(float64)) { d.onDeliveryDone = fn }
+
+type Payload struct {
+ Event string `json:"event"`
+ EmailID string `json:"email_id"`
+ Timestamp string `json:"timestamp"`
+}
+
+// Dispatch sends webhook notifications for the given event. Runs asynchronously.
+func (d *Dispatcher) Dispatch(userID uint, event string, emailID string, from string) {
+ go func() {
+ webhooks, err := d.repo.FindByUserIDAndEvent(userID, event)
+ if err != nil {
+ logger.Error("failed to find webhooks", "error", err)
+ return
+ }
+
+ payload := Payload{
+ Event: event,
+ EmailID: emailID,
+ Timestamp: time.Now().UTC().Format(time.RFC3339),
+ }
+
+ body, err := json.Marshal(payload)
+ if err != nil {
+ logger.Error("failed to marshal webhook payload", "error", err)
+ return
+ }
+
+ for _, wh := range webhooks {
+ if !matchesFilters(wh.Filters, from) {
+ continue
+ }
+ d.deliverWithRetry(userID, wh, body, event)
+ }
+ }()
+}
+
+// matchesFilters checks if the sender address matches the webhook's filters.
+func matchesFilters(filters []string, from string) bool {
+ if len(filters) == 0 {
+ return true
+ }
+ if from == "" {
+ return true
+ }
+
+ addr := from
+ if parsed, err := mail.ParseAddress(from); err == nil {
+ addr = parsed.Address
+ }
+ addr = strings.ToLower(addr)
+
+ domain := ""
+ if parts := strings.SplitN(addr, "@", 2); len(parts) == 2 {
+ domain = parts[1]
+ }
+
+ for _, f := range filters {
+ f = strings.ToLower(strings.TrimSpace(f))
+ if f == "" {
+ continue
+ }
+ if f == addr {
+ return true
+ }
+ if domain != "" && f == domain {
+ return true
+ }
+ }
+ return false
+}
+
+// deliverWithRetry attempts to deliver a webhook with exponential backoff retries.
+func (d *Dispatcher) deliverWithRetry(userID uint, wh models.Webhook, body []byte, event string) {
+ var lastErr string
+ var lastStatus int
+
+ start := time.Now()
+
+ for attempt := 1; attempt <= d.maxRetries; attempt++ {
+ statusCode, err := d.doRequest(wh.URL, wh.Secret, body)
+ lastStatus = statusCode
+
+ if err == nil && statusCode < 400 {
+ d.recordDelivery(userID, wh.ID, event, models.WebhookDeliverySuccess, statusCode, "", attempt)
+ if d.onDeliverySuccess != nil {
+ d.onDeliverySuccess()
+ }
+ if d.onDeliveryDone != nil {
+ d.onDeliveryDone(time.Since(start).Seconds())
+ }
+ logger.Info("webhook delivered", "url", wh.URL, "event", event, "attempt", attempt)
+ return
+ }
+
+ if err != nil {
+ lastErr = err.Error()
+ logger.Warn("webhook delivery failed", "url", wh.URL, "attempt", attempt, "error", err)
+ } else {
+ lastErr = fmt.Sprintf("HTTP %d", statusCode)
+ logger.Warn("webhook returned error status", "url", wh.URL, "attempt", attempt, "status", statusCode)
+ }
+
+ if attempt < d.maxRetries {
+ time.Sleep(defaultRetryBaseWait * time.Duration(attempt))
+ }
+ }
+
+ // All retries exhausted
+ d.recordDelivery(userID, wh.ID, event, models.WebhookDeliveryFailed, lastStatus, lastErr, d.maxRetries)
+ if d.onDeliveryFailed != nil {
+ d.onDeliveryFailed()
+ }
+ if d.onDeliveryDone != nil {
+ d.onDeliveryDone(time.Since(start).Seconds())
+ }
+}
+
+// signPayload computes an HMAC-SHA256 signature of body using the given secret.
+func signPayload(secret string, body []byte) string {
+ mac := hmac.New(sha256.New, []byte(secret))
+ mac.Write(body)
+ return hex.EncodeToString(mac.Sum(nil))
+}
+
+// doRequest sends a single HTTP POST to the webhook URL with an HMAC signature.
+func (d *Dispatcher) doRequest(url string, secret string, body []byte) (int, error) {
+ req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(body))
+ if err != nil {
+ return 0, fmt.Errorf("failed to create request: %w", err)
+ }
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("User-Agent", "Posta-Webhook/1.0")
+ if secret != "" {
+ req.Header.Set("X-Posta-Signature", "sha256="+signPayload(secret, body))
+ }
+
+ resp, err := d.client.Do(req)
+ if err != nil {
+ return 0, err
+ }
+ _ = resp.Body.Close()
+ return resp.StatusCode, nil
+}
+
+// recordDelivery persists a webhook delivery record if the delivery repo is configured.
+func (d *Dispatcher) recordDelivery(userID, webhookID uint, event string, status models.WebhookDeliveryStatus, httpStatus int, errMsg string, attempt int) {
+ if d.deliveryRepo == nil {
+ return
+ }
+ delivery := &models.WebhookDelivery{
+ WebhookID: webhookID,
+ UserID: userID,
+ Event: event,
+ Status: status,
+ HTTPStatusCode: httpStatus,
+ ErrorMessage: errMsg,
+ Attempt: attempt,
+ }
+ if err := d.deliveryRepo.Create(delivery); err != nil {
+ logger.Error("failed to record webhook delivery", "error", err)
+ }
+}
+
+// Validate ensures the webhook URL is reachable.
+func (d *Dispatcher) Validate(url string) error {
+ req, err := http.NewRequest(http.MethodHead, url, nil)
+ if err != nil {
+ return fmt.Errorf("invalid webhook URL: %w", err)
+ }
+
+ resp, err := d.client.Do(req)
+ if err != nil {
+ return fmt.Errorf("webhook URL unreachable: %w", err)
+ }
+ _ = resp.Body.Close()
+
+ return nil
+}
diff --git a/internal/services/webhook/dispatcher_test.go b/internal/services/webhook/dispatcher_test.go
new file mode 100644
index 0000000..85bf5ac
--- /dev/null
+++ b/internal/services/webhook/dispatcher_test.go
@@ -0,0 +1,247 @@
+/*
+ * 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 webhook
+
+import (
+ "crypto/hmac"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/jkaninda/posta/internal/models"
+)
+
+// --- signPayload tests ---
+
+func TestSignPayload(t *testing.T) {
+ secret := "test-secret"
+ body := []byte(`{"event":"email.sent"}`)
+
+ sig := signPayload(secret, body)
+
+ // Verify independently
+ mac := hmac.New(sha256.New, []byte(secret))
+ mac.Write(body)
+ want := hex.EncodeToString(mac.Sum(nil))
+
+ if sig != want {
+ t.Fatalf("signPayload = %q, want %q", sig, want)
+ }
+}
+
+func TestSignPayloadDifferentSecrets(t *testing.T) {
+ body := []byte(`{"event":"email.sent"}`)
+ sig1 := signPayload("secret-a", body)
+ sig2 := signPayload("secret-b", body)
+ if sig1 == sig2 {
+ t.Fatal("different secrets should produce different signatures")
+ }
+}
+
+func TestSignPayloadDifferentBodies(t *testing.T) {
+ secret := "same-secret"
+ sig1 := signPayload(secret, []byte(`{"event":"email.sent"}`))
+ sig2 := signPayload(secret, []byte(`{"event":"email.failed"}`))
+ if sig1 == sig2 {
+ t.Fatal("different bodies should produce different signatures")
+ }
+}
+
+// --- matchesFilters tests ---
+
+func TestMatchesFilters_EmptyFilters(t *testing.T) {
+ if !matchesFilters(nil, "[email protected]") {
+ t.Error("empty filters should match any sender")
+ }
+ if !matchesFilters([]string{}, "[email protected]") {
+ t.Error("empty slice filters should match any sender")
+ }
+}
+
+func TestMatchesFilters_EmptyFrom(t *testing.T) {
+ if !matchesFilters([]string{"example.com"}, "") {
+ t.Error("empty from should match (no sender info to reject)")
+ }
+}
+
+func TestMatchesFilters_ExactMatch(t *testing.T) {
+ if !matchesFilters([]string{"[email protected]"}, "[email protected]") {
+ t.Error("exact email match should pass")
+ }
+}
+
+func TestMatchesFilters_CaseInsensitive(t *testing.T) {
+ if !matchesFilters([]string{"[email protected]"}, "[email protected]") {
+ t.Error("filter matching should be case-insensitive")
+ }
+}
+
+func TestMatchesFilters_DomainMatch(t *testing.T) {
+ if !matchesFilters([]string{"example.com"}, "[email protected]") {
+ t.Error("domain filter should match any sender from that domain")
+ }
+}
+
+func TestMatchesFilters_NoMatch(t *testing.T) {
+ if matchesFilters([]string{"other.com"}, "[email protected]") {
+ t.Error("non-matching domain should not match")
+ }
+}
+
+func TestMatchesFilters_RFC5322Address(t *testing.T) {
+ if !matchesFilters([]string{"[email protected]"}, "User Name <[email protected]>") {
+ t.Error("should parse RFC 5322 addresses")
+ }
+}
+
+func TestMatchesFilters_MultipleFilters(t *testing.T) {
+ filters := []string{"other.com", "[email protected]"}
+ if !matchesFilters(filters, "[email protected]") {
+ t.Error("should match when any filter matches")
+ }
+ if !matchesFilters(filters, "[email protected]") {
+ t.Error("should match domain filter in list")
+ }
+ if matchesFilters(filters, "[email protected]") {
+ t.Error("should not match when no filter matches")
+ }
+}
+
+// --- Dispatcher delivery tests ---
+
+func TestDispatcher_SignatureHeader(t *testing.T) {
+ var receivedSig string
+ var receivedBody []byte
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ receivedSig = r.Header.Get("X-Posta-Signature")
+ buf := make([]byte, r.ContentLength)
+ _, _ = r.Body.Read(buf)
+ receivedBody = buf
+ w.WriteHeader(http.StatusOK)
+ }))
+ defer srv.Close()
+
+ secret := "webhook-secret-123"
+ wh := models.Webhook{
+ ID: 1,
+ UserID: 1,
+ URL: srv.URL,
+ Events: []string{"email.sent"},
+ Secret: secret,
+ }
+
+ d := NewDispatcher(nil)
+ body := []byte(`{"event":"email.sent","email_id":"abc","timestamp":"2026-01-01T00:00:00Z"}`)
+
+ statusCode, err := d.doRequest(wh.URL, wh.Secret, body)
+ if err != nil {
+ t.Fatalf("doRequest error: %v", err)
+ }
+ if statusCode != 200 {
+ t.Fatalf("expected 200, got %d", statusCode)
+ }
+
+ expectedSig := "sha256=" + signPayload(secret, body)
+ if receivedSig != expectedSig {
+ t.Errorf("signature = %q, want %q", receivedSig, expectedSig)
+ }
+ _ = receivedBody
+}
+
+func TestDispatcher_NoSignatureWhenNoSecret(t *testing.T) {
+ var receivedSig string
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ receivedSig = r.Header.Get("X-Posta-Signature")
+ w.WriteHeader(http.StatusOK)
+ }))
+ defer srv.Close()
+
+ d := NewDispatcher(nil)
+ _, err := d.doRequest(srv.URL, "", []byte(`{}`))
+ if err != nil {
+ t.Fatalf("doRequest error: %v", err)
+ }
+ if receivedSig != "" {
+ t.Errorf("expected no signature header, got %q", receivedSig)
+ }
+}
+
+func TestDispatcher_RetryOnFailure(t *testing.T) {
+ var attempts atomic.Int32
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ n := attempts.Add(1)
+ if n < 3 {
+ w.WriteHeader(http.StatusInternalServerError)
+ return
+ }
+ w.WriteHeader(http.StatusOK)
+ }))
+ defer srv.Close()
+
+ d := NewDispatcher(nil)
+ d.maxRetries = 3
+
+ wh := models.Webhook{
+ ID: 1,
+ UserID: 1,
+ URL: srv.URL,
+ Events: []string{"email.sent"},
+ Secret: "secret",
+ }
+
+ payload := Payload{Event: "email.sent", EmailID: "test-123", Timestamp: time.Now().UTC().Format(time.RFC3339)}
+ body, _ := json.Marshal(payload)
+
+ d.deliverWithRetry(1, wh, body, "email.sent")
+
+ if got := attempts.Load(); got != 3 {
+ t.Errorf("expected 3 attempts, got %d", got)
+ }
+}
+
+func TestDispatcher_SetConfig(t *testing.T) {
+ d := NewDispatcher(nil)
+
+ if d.maxRetries != defaultMaxRetries {
+ t.Errorf("default maxRetries = %d, want %d", d.maxRetries, defaultMaxRetries)
+ }
+
+ d.SetConfig(Config{MaxRetries: 5, Timeout: 30 * time.Second})
+
+ if d.maxRetries != 5 {
+ t.Errorf("after SetConfig maxRetries = %d, want 5", d.maxRetries)
+ }
+ if d.client.Timeout != 30*time.Second {
+ t.Errorf("after SetConfig timeout = %v, want 30s", d.client.Timeout)
+ }
+}
diff --git a/internal/services/workermon/monitor.go b/internal/services/workermon/monitor.go
new file mode 100644
index 0000000..ef97d68
--- /dev/null
+++ b/internal/services/workermon/monitor.go
@@ -0,0 +1,141 @@
+/*
+ * 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 workermon
+
+import (
+ "context"
+ "fmt"
+ "sync"
+ "time"
+
+ "github.com/hibiken/asynq"
+ "github.com/jkaninda/logger"
+ "github.com/jkaninda/posta/internal/models"
+ "github.com/jkaninda/posta/internal/services/eventbus"
+)
+
+// Monitor periodically checks asynq worker connections and publishes
+// worker.connected / worker.disconnected events via the event bus.
+type Monitor struct {
+ inspector *asynq.Inspector
+ bus *eventbus.EventBus
+ interval time.Duration
+
+ mu sync.Mutex
+ known map[string]workerInfo // keyed by "host:pid"
+}
+
+type workerInfo struct {
+ Host string
+ PID int
+ Queues map[string]int
+}
+
+func workerKey(host string, pid int) string {
+ return fmt.Sprintf("%s:%d", host, pid)
+}
+
+func New(inspector *asynq.Inspector, bus *eventbus.EventBus, interval time.Duration) *Monitor {
+ return &Monitor{
+ inspector: inspector,
+ bus: bus,
+ interval: interval,
+ known: make(map[string]workerInfo),
+ }
+}
+
+// Start begins polling in a background goroutine. It stops when ctx is cancelled.
+func (m *Monitor) Start(ctx context.Context) {
+ go m.run(ctx)
+}
+
+func (m *Monitor) run(ctx context.Context) {
+ ticker := time.NewTicker(m.interval)
+ defer ticker.Stop()
+
+ // Do an initial check right away.
+ m.check()
+
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-ticker.C:
+ m.check()
+ }
+ }
+}
+
+func (m *Monitor) check() {
+ servers, err := m.inspector.Servers()
+ if err != nil {
+ logger.Error("worker monitor: failed to query servers", "error", err)
+ return
+ }
+
+ m.mu.Lock()
+ defer m.mu.Unlock()
+
+ current := make(map[string]workerInfo, len(servers))
+ for _, s := range servers {
+ key := workerKey(s.Host, s.PID)
+ current[key] = workerInfo{
+ Host: s.Host,
+ PID: s.PID,
+ Queues: s.Queues,
+ }
+
+ if _, exists := m.known[key]; !exists {
+ m.bus.PublishSimple(
+ models.EventCategorySystem,
+ "worker.connected",
+ nil, "system", "",
+ fmt.Sprintf("Worker connected on %s (PID %d)", s.Host, s.PID),
+ map[string]any{
+ "host": s.Host,
+ "pid": s.PID,
+ "queues": s.Queues,
+ },
+ )
+ }
+ }
+
+ for key, info := range m.known {
+ if _, exists := current[key]; !exists {
+ m.bus.PublishSimple(
+ models.EventCategorySystem,
+ "worker.disconnected",
+ nil, "system", "",
+ fmt.Sprintf("Worker disconnected from %s (PID %d)", info.Host, info.PID),
+ map[string]any{
+ "host": info.Host,
+ "pid": info.PID,
+ },
+ )
+ }
+ }
+
+ m.known = current
+}
diff --git a/internal/storage/migration/constraints.go b/internal/storage/migration/constraints.go
new file mode 100644
index 0000000..6916e76
--- /dev/null
+++ b/internal/storage/migration/constraints.go
@@ -0,0 +1,37 @@
+/*
+ * 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 migration
+
+import "gorm.io/gorm"
+
+func runConstraints(db *gorm.DB) {
+ // Add FK constraints
+ db.Exec(`DO $$ BEGIN
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'fk_template_versions_template') THEN
+ ALTER TABLE template_versions ADD CONSTRAINT fk_template_versions_template
+ FOREIGN KEY (template_id) REFERENCES templates(id) ON DELETE CASCADE;
+ END IF;
+ END $$`)
+}
diff --git a/internal/storage/migration/migration.go b/internal/storage/migration/migration.go
new file mode 100644
index 0000000..cd73edb
--- /dev/null
+++ b/internal/storage/migration/migration.go
@@ -0,0 +1,67 @@
+/*
+ * 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 migration
+
+import (
+ "fmt"
+
+ "github.com/jkaninda/logger"
+ "github.com/jkaninda/posta/internal/models"
+ "gorm.io/gorm"
+)
+
+// Run executes all schema migrations and adds FK constraints.
+func Run(db *gorm.DB) error {
+ if err := db.AutoMigrate(
+ &models.User{},
+ &models.APIKey{},
+ &models.Email{},
+ &models.StyleSheet{},
+ &models.Template{},
+ &models.TemplateVersion{},
+ &models.TemplateLocalization{},
+ &models.Language{},
+ &models.SMTPServer{},
+ &models.Server{},
+ &models.Webhook{},
+ &models.Domain{},
+ &models.Bounce{},
+ &models.Suppression{},
+ &models.Contact{},
+ &models.ContactList{},
+ &models.ContactListMember{},
+ &models.Event{},
+ &models.Setting{},
+ &models.UserSetting{},
+ &models.WebhookDelivery{},
+ ); err != nil {
+ return fmt.Errorf("failed to migrate database: %w", err)
+ }
+ // run constraints
+ runConstraints(db)
+
+ logger.Info("database migrated")
+ return nil
+}
diff --git a/internal/storage/postgres.go b/internal/storage/postgres.go
new file mode 100644
index 0000000..c20b9fa
--- /dev/null
+++ b/internal/storage/postgres.go
@@ -0,0 +1,72 @@
+/*
+ * 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 storage
+
+import (
+ "fmt"
+
+ "github.com/jkaninda/logger"
+ "github.com/jkaninda/posta/internal/models"
+ "golang.org/x/crypto/bcrypt"
+ "gorm.io/driver/postgres"
+ "gorm.io/gorm"
+)
+
+// ConnectPostgres opens a connection to PostgreSQL without running migrations.
+func ConnectPostgres(dsn string) (*gorm.DB, error) {
+ db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
+ if err != nil {
+ return nil, fmt.Errorf("failed to connect to database: %w", err)
+ }
+ logger.Info("database connected")
+ return db, nil
+}
+
+// SeedAdmin creates the default admin user
+func SeedAdmin(db *gorm.DB, email, password string) error {
+ var count int64
+ db.Model(&models.User{}).Count(&count)
+ if count > 0 {
+ return nil
+ }
+
+ hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
+ if err != nil {
+ return fmt.Errorf("failed to hash admin password: %w", err)
+ }
+
+ admin := &models.User{
+ Email: email,
+ Name: "Admin",
+ PasswordHash: string(hash),
+ Role: models.UserRoleAdmin,
+ }
+ if err := db.Create(admin).Error; err != nil {
+ return fmt.Errorf("failed to create admin user: %w", err)
+ }
+
+ logger.Info("default admin user created", "email", email)
+ return nil
+}
diff --git a/internal/storage/redis.go b/internal/storage/redis.go
new file mode 100644
index 0000000..761f2c7
--- /dev/null
+++ b/internal/storage/redis.go
@@ -0,0 +1,47 @@
+/*
+ * 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 storage
+
+import (
+ "context"
+ "fmt"
+
+ "github.com/jkaninda/logger"
+ "github.com/redis/go-redis/v9"
+)
+
+func NewRedis(addr, password string) (*redis.Client, error) {
+ client := redis.NewClient(&redis.Options{
+ Addr: addr,
+ Password: password,
+ })
+
+ if err := client.Ping(context.Background()).Err(); err != nil {
+ return nil, fmt.Errorf("failed to connect to redis: %w", err)
+ }
+
+ logger.Info("redis connected")
+ return client, nil
+}
diff --git a/internal/storage/repositories/analytics_repo.go b/internal/storage/repositories/analytics_repo.go
new file mode 100644
index 0000000..209f2b5
--- /dev/null
+++ b/internal/storage/repositories/analytics_repo.go
@@ -0,0 +1,109 @@
+/*
+ * 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"
+
+ "gorm.io/gorm"
+)
+
+type AnalyticsRepository struct {
+ db *gorm.DB
+}
+
+func NewAnalyticsRepository(db *gorm.DB) *AnalyticsRepository {
+ return &AnalyticsRepository{db: db}
+}
+
+type DailyCount struct {
+ Date string `json:"date"`
+ Count int64 `json:"count"`
+}
+
+type StatusBreakdown struct {
+ Status string `json:"status"`
+ Count int64 `json:"count"`
+}
+
+// DailyCounts returns email counts per day for a user within a date range, optionally filtered by status.
+func (r *AnalyticsRepository) DailyCounts(userID uint, from, to time.Time, status string) ([]DailyCount, error) {
+ var results []DailyCount
+ query := r.db.Table("emails").
+ Select("TO_CHAR(created_at, 'YYYY-MM-DD') as date, COUNT(*) as count").
+ Where("user_id = ? AND created_at >= ? AND created_at <= ?", userID, from, to)
+ if status != "" {
+ query = query.Where("status = ?", status)
+ }
+ err := query.Group("date").Order("date ASC").Find(&results).Error
+ return results, err
+}
+
+// StatusBreakdown returns counts grouped by status for a user within a date range.
+func (r *AnalyticsRepository) StatusBreakdown(userID uint, from, to time.Time) ([]StatusBreakdown, error) {
+ var results []StatusBreakdown
+ err := r.db.Table("emails").
+ Select("status, COUNT(*) as count").
+ Where("user_id = ? AND created_at >= ? AND created_at <= ?", userID, from, to).
+ Group("status").
+ Find(&results).Error
+ return results, err
+}
+
+// HourlyCounts returns email counts per hour for a user on a specific day.
+func (r *AnalyticsRepository) HourlyCounts(userID uint, date time.Time) ([]DailyCount, error) {
+ var results []DailyCount
+ start := time.Date(date.Year(), date.Month(), date.Day(), 0, 0, 0, 0, date.Location())
+ end := start.Add(24 * time.Hour)
+ err := r.db.Table("emails").
+ Select("TO_CHAR(created_at, 'HH24:00') as date, COUNT(*) as count").
+ Where("user_id = ? AND created_at >= ? AND created_at < ?", userID, start, end).
+ Group("date").Order("date ASC").Find(&results).Error
+ return results, err
+}
+
+// AdminDailyCounts returns email counts across all users.
+func (r *AnalyticsRepository) AdminDailyCounts(from, to time.Time, status string) ([]DailyCount, error) {
+ var results []DailyCount
+ query := r.db.Table("emails").
+ Select("TO_CHAR(created_at, 'YYYY-MM-DD') as date, COUNT(*) as count").
+ Where("created_at >= ? AND created_at <= ?", from, to)
+ if status != "" {
+ query = query.Where("status = ?", status)
+ }
+ err := query.Group("date").Order("date ASC").Find(&results).Error
+ return results, err
+}
+
+// AdminStatusBreakdown returns counts grouped by status across all users.
+func (r *AnalyticsRepository) AdminStatusBreakdown(from, to time.Time) ([]StatusBreakdown, error) {
+ var results []StatusBreakdown
+ err := r.db.Table("emails").
+ Select("status, COUNT(*) as count").
+ Where("created_at >= ? AND created_at <= ?", from, to).
+ Group("status").
+ Find(&results).Error
+ return results, err
+}
diff --git a/internal/storage/repositories/api_key_repo.go b/internal/storage/repositories/api_key_repo.go
new file mode 100644
index 0000000..5d33fe8
--- /dev/null
+++ b/internal/storage/repositories/api_key_repo.go
@@ -0,0 +1,102 @@
+/*
+ * 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 APIKeyRepository struct {
+ db *gorm.DB
+}
+
+func NewAPIKeyRepository(db *gorm.DB) *APIKeyRepository {
+ return &APIKeyRepository{db: db}
+}
+
+func (r *APIKeyRepository) Create(key *models.APIKey) error {
+ return r.db.Create(key).Error
+}
+
+func (r *APIKeyRepository) FindByPrefix(prefix string) ([]models.APIKey, error) {
+ var keys []models.APIKey
+ if err := r.db.Where("key_prefix = ?", prefix).Find(&keys).Error; err != nil {
+ return nil, err
+ }
+ return keys, nil
+}
+
+func (r *APIKeyRepository) FindByUserID(userID uint, limit, offset int) ([]models.APIKey, int64, error) {
+ var keys []models.APIKey
+ var total int64
+
+ r.db.Model(&models.APIKey{}).Where("user_id = ?", userID).Count(&total)
+
+ if err := r.db.Where("user_id = ?", userID).
+ Order("created_at DESC").
+ Limit(limit).Offset(offset).
+ Find(&keys).Error; err != nil {
+ return nil, 0, err
+ }
+ return keys, total, nil
+}
+
+func (r *APIKeyRepository) FindByID(id uint) (*models.APIKey, error) {
+ var key models.APIKey
+ if err := r.db.First(&key, id).Error; err != nil {
+ return nil, err
+ }
+ return &key, nil
+}
+
+func (r *APIKeyRepository) UpdateLastUsed(id uint) error {
+ now := time.Now()
+ return r.db.Model(&models.APIKey{}).Where("id = ?", id).Update("last_used_at", now).Error
+}
+
+func (r *APIKeyRepository) Revoke(id uint) error {
+ return r.db.Model(&models.APIKey{}).Where("id = ?", id).Update("revoked", true).Error
+}
+
+func (r *APIKeyRepository) Delete(id uint) error {
+ return r.db.Delete(&models.APIKey{}, id).Error
+}
+
+func (r *APIKeyRepository) FindAll(limit, offset int) ([]models.APIKey, int64, error) {
+ var keys []models.APIKey
+ var total int64
+
+ r.db.Model(&models.APIKey{}).Count(&total)
+
+ if err := r.db.Order("created_at DESC").
+ Limit(limit).Offset(offset).
+ Find(&keys).Error; err != nil {
+ return nil, 0, err
+ }
+ return keys, total, nil
+}
diff --git a/internal/storage/repositories/bounce_repo.go b/internal/storage/repositories/bounce_repo.go
new file mode 100644
index 0000000..29fa742
--- /dev/null
+++ b/internal/storage/repositories/bounce_repo.go
@@ -0,0 +1,73 @@
+/*
+ * 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 (
+ "github.com/jkaninda/posta/internal/models"
+ "gorm.io/gorm"
+)
+
+type BounceRepository struct {
+ db *gorm.DB
+}
+
+func NewBounceRepository(db *gorm.DB) *BounceRepository {
+ return &BounceRepository{db: db}
+}
+
+func (r *BounceRepository) Create(bounce *models.Bounce) error {
+ return r.db.Create(bounce).Error
+}
+
+func (r *BounceRepository) FindByUserID(userID uint, limit, offset int) ([]models.Bounce, int64, error) {
+ var bounces []models.Bounce
+ var total int64
+
+ r.db.Model(&models.Bounce{}).Where("user_id = ?", userID).Count(&total)
+
+ if err := r.db.Where("user_id = ?", userID).
+ Order("created_at DESC").
+ Limit(limit).Offset(offset).
+ Find(&bounces).Error; err != nil {
+ return nil, 0, err
+ }
+ return bounces, total, nil
+}
+
+func (r *BounceRepository) FindByEmailID(emailID uint) ([]models.Bounce, error) {
+ var bounces []models.Bounce
+ if err := r.db.Where("email_id = ?", emailID).Find(&bounces).Error; err != nil {
+ return nil, err
+ }
+ return bounces, nil
+}
+
+func (r *BounceRepository) CountHardBouncesByRecipient(userID uint, recipient string) (int64, error) {
+ var count int64
+ err := r.db.Model(&models.Bounce{}).
+ Where("user_id = ? AND recipient = ? AND type = ?", userID, recipient, models.BounceTypeHard).
+ Count(&count).Error
+ return count, err
+}
diff --git a/internal/storage/repositories/contact_list_repo.go b/internal/storage/repositories/contact_list_repo.go
new file mode 100644
index 0000000..ee4fe7e
--- /dev/null
+++ b/internal/storage/repositories/contact_list_repo.go
@@ -0,0 +1,95 @@
+/*
+ * 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 (
+ "github.com/jkaninda/posta/internal/models"
+ "gorm.io/gorm"
+)
+
+type ContactListRepository struct {
+ db *gorm.DB
+}
+
+func NewContactListRepository(db *gorm.DB) *ContactListRepository {
+ return &ContactListRepository{db: db}
+}
+
+func (r *ContactListRepository) Create(list *models.ContactList) error {
+ return r.db.Create(list).Error
+}
+
+func (r *ContactListRepository) FindByID(id uint) (*models.ContactList, error) {
+ var list models.ContactList
+ if err := r.db.First(&list, id).Error; err != nil {
+ return nil, err
+ }
+ return &list, nil
+}
+
+func (r *ContactListRepository) FindByUserID(userID uint, limit, offset int) ([]models.ContactList, int64, error) {
+ var lists []models.ContactList
+ var total int64
+ r.db.Model(&models.ContactList{}).Where("user_id = ?", userID).Count(&total)
+ err := r.db.Where("user_id = ?", userID).Order("created_at DESC").Limit(limit).Offset(offset).Find(&lists).Error
+ return lists, total, err
+}
+
+func (r *ContactListRepository) Update(list *models.ContactList) error {
+ return r.db.Save(list).Error
+}
+
+func (r *ContactListRepository) Delete(id uint) error {
+ return r.db.Delete(&models.ContactList{}, id).Error
+}
+
+func (r *ContactListRepository) AddMember(member *models.ContactListMember) error {
+ return r.db.Create(member).Error
+}
+
+func (r *ContactListRepository) RemoveMember(listID uint, email string) error {
+ return r.db.Where("list_id = ? AND email = ?", listID, email).Delete(&models.ContactListMember{}).Error
+}
+
+func (r *ContactListRepository) ListMembers(listID uint, limit, offset int) ([]models.ContactListMember, int64, error) {
+ var members []models.ContactListMember
+ var total int64
+ r.db.Model(&models.ContactListMember{}).Where("list_id = ?", listID).Count(&total)
+ err := r.db.Where("list_id = ?", listID).Order("created_at DESC").Limit(limit).Offset(offset).Find(&members).Error
+ return members, total, err
+}
+
+func (r *ContactListRepository) GetMemberEmails(listID uint) ([]string, error) {
+ var emails []string
+ err := r.db.Model(&models.ContactListMember{}).Where("list_id = ?", listID).Pluck("email", &emails).Error
+ return emails, err
+}
+
+// MemberCount returns the number of members in a list.
+func (r *ContactListRepository) MemberCount(listID uint) int64 {
+ var count int64
+ r.db.Model(&models.ContactListMember{}).Where("list_id = ?", listID).Count(&count)
+ return count
+}
diff --git a/internal/storage/repositories/contact_repo.go b/internal/storage/repositories/contact_repo.go
new file mode 100644
index 0000000..d508a07
--- /dev/null
+++ b/internal/storage/repositories/contact_repo.go
@@ -0,0 +1,130 @@
+/*
+ * 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 (
+ "net/mail"
+ "time"
+
+ "github.com/jkaninda/posta/internal/models"
+ "gorm.io/gorm"
+ "gorm.io/gorm/clause"
+)
+
+type ContactRepository struct {
+ db *gorm.DB
+}
+
+func NewContactRepository(db *gorm.DB) *ContactRepository {
+ return &ContactRepository{db: db}
+}
+
+// RecordSent upserts contacts for the given recipients, incrementing sent_count.
+// Recipients may use RFC 5322 format ("Display Name <email>"), in which case
+// the name and bare email are extracted.
+func (r *ContactRepository) RecordSent(userID uint, recipients []string) {
+ now := time.Now()
+ for _, raw := range recipients {
+ addr, name := parseRecipient(raw)
+ contact := models.Contact{
+ UserID: userID,
+ Email: addr,
+ Name: name,
+ SentCount: 1,
+ LastSentAt: &now,
+ }
+ updates := map[string]interface{}{
+ "sent_count": gorm.Expr("contacts.sent_count + 1"),
+ "last_sent_at": now,
+ }
+ if name != "" {
+ updates["name"] = name
+ }
+ r.db.Clauses(clause.OnConflict{
+ Columns: []clause.Column{{Name: "user_id"}, {Name: "email"}},
+ DoUpdates: clause.Assignments(updates),
+ }).Create(&contact)
+ }
+}
+
+// RecordFailed upserts contacts for the given recipients, incrementing fail_count.
+func (r *ContactRepository) RecordFailed(userID uint, recipients []string) {
+ for _, raw := range recipients {
+ addr, name := parseRecipient(raw)
+ contact := models.Contact{
+ UserID: userID,
+ Email: addr,
+ Name: name,
+ FailCount: 1,
+ }
+ updates := map[string]interface{}{
+ "fail_count": gorm.Expr("contacts.fail_count + 1"),
+ }
+ if name != "" {
+ updates["name"] = name
+ }
+ r.db.Clauses(clause.OnConflict{
+ Columns: []clause.Column{{Name: "user_id"}, {Name: "email"}},
+ DoUpdates: clause.Assignments(updates),
+ }).Create(&contact)
+ }
+}
+
+// parseRecipient extracts the bare email and display name from a recipient
+// string. It supports RFC 5322 format ("Display Name <[email protected]>").
+// If parsing fails, the original string is returned as the email with no name.
+func parseRecipient(raw string) (email, name string) {
+ addr, err := mail.ParseAddress(raw)
+ if err != nil {
+ return raw, ""
+ }
+ return addr.Address, addr.Name
+}
+
+func (r *ContactRepository) FindByUserID(userID uint, search string, limit, offset int) ([]models.Contact, int64, error) {
+ var contacts []models.Contact
+ var total int64
+
+ q := r.db.Model(&models.Contact{}).Where("user_id = ?", userID)
+ if search != "" {
+ q = q.Where("email ILIKE ? OR name ILIKE ?", "%"+search+"%", "%"+search+"%")
+ }
+ q.Count(&total)
+
+ if err := q.Order("last_sent_at DESC NULLS LAST").
+ Limit(limit).Offset(offset).
+ Find(&contacts).Error; err != nil {
+ return nil, 0, err
+ }
+ return contacts, total, nil
+}
+
+func (r *ContactRepository) FindByID(id uint) (*models.Contact, error) {
+ var contact models.Contact
+ if err := r.db.First(&contact, id).Error; err != nil {
+ return nil, err
+ }
+ return &contact, nil
+}
diff --git a/internal/storage/repositories/domain_repo.go b/internal/storage/repositories/domain_repo.go
new file mode 100644
index 0000000..0419e3c
--- /dev/null
+++ b/internal/storage/repositories/domain_repo.go
@@ -0,0 +1,90 @@
+/*
+ * 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 (
+ "github.com/jkaninda/posta/internal/models"
+ "gorm.io/gorm"
+)
+
+type DomainRepository struct {
+ db *gorm.DB
+}
+
+func NewDomainRepository(db *gorm.DB) *DomainRepository {
+ return &DomainRepository{db: db}
+}
+
+func (r *DomainRepository) Create(domain *models.Domain) error {
+ return r.db.Create(domain).Error
+}
+
+func (r *DomainRepository) Update(domain *models.Domain) error {
+ return r.db.Save(domain).Error
+}
+
+func (r *DomainRepository) Delete(id uint) error {
+ return r.db.Delete(&models.Domain{}, id).Error
+}
+
+func (r *DomainRepository) FindByID(id uint) (*models.Domain, error) {
+ var domain models.Domain
+ if err := r.db.First(&domain, id).Error; err != nil {
+ return nil, err
+ }
+ return &domain, nil
+}
+
+func (r *DomainRepository) FindByUserID(userID uint, limit, offset int) ([]models.Domain, int64, error) {
+ var domains []models.Domain
+ var total int64
+
+ r.db.Model(&models.Domain{}).Where("user_id = ?", userID).Count(&total)
+
+ if err := r.db.Where("user_id = ?", userID).
+ Order("created_at DESC").
+ Limit(limit).Offset(offset).
+ Find(&domains).Error; err != nil {
+ return nil, 0, err
+ }
+ return domains, total, nil
+}
+
+func (r *DomainRepository) FindByUserIDAndDomain(userID uint, domain string) (*models.Domain, error) {
+ var d models.Domain
+ if err := r.db.Where("user_id = ? AND domain = ?", userID, domain).First(&d).Error; err != nil {
+ return nil, err
+ }
+ return &d, nil
+}
+
+// IsOwnershipVerified checks whether the given domain is registered and ownership-verified for the user.
+func (r *DomainRepository) IsOwnershipVerified(userID uint, domainName string) bool {
+ var count int64
+ r.db.Model(&models.Domain{}).
+ Where("user_id = ? AND domain = ? AND ownership_verified = ?", userID, domainName, true).
+ Count(&count)
+ return count > 0
+}
diff --git a/internal/storage/repositories/email_repo.go b/internal/storage/repositories/email_repo.go
new file mode 100644
index 0000000..006c0b8
--- /dev/null
+++ b/internal/storage/repositories/email_repo.go
@@ -0,0 +1,111 @@
+/*
+ * 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 EmailRepository struct {
+ db *gorm.DB
+}
+
+func NewEmailRepository(db *gorm.DB) *EmailRepository {
+ return &EmailRepository{db: db}
+}
+
+func (r *EmailRepository) Create(email *models.Email) error {
+ return r.db.Create(email).Error
+}
+
+func (r *EmailRepository) Update(email *models.Email) error {
+ return r.db.Save(email).Error
+}
+
+func (r *EmailRepository) FindByID(id uint) (*models.Email, error) {
+ var email models.Email
+ if err := r.db.First(&email, id).Error; err != nil {
+ return nil, err
+ }
+ return &email, nil
+}
+
+func (r *EmailRepository) FindByUUID(uuid string) (*models.Email, error) {
+ var email models.Email
+ if err := r.db.Where("uuid = ?", uuid).First(&email).Error; err != nil {
+ return nil, err
+ }
+ return &email, nil
+}
+
+func (r *EmailRepository) FindByUserID(userID uint, limit, offset int) ([]models.Email, int64, error) {
+ var emails []models.Email
+ var total int64
+
+ r.db.Model(&models.Email{}).Where("user_id = ?", userID).Count(&total)
+
+ if err := r.db.Where("user_id = ?", userID).
+ Order("created_at DESC").
+ Limit(limit).Offset(offset).
+ Find(&emails).Error; err != nil {
+ return nil, 0, err
+ }
+ return emails, total, nil
+}
+
+// FindFailedForRetry returns failed emails with retry_count < maxRetries for a given user.
+func (r *EmailRepository) FindFailedForRetry(userID uint, maxRetries int) ([]models.Email, error) {
+ var emails []models.Email
+ if err := r.db.Where("user_id = ? AND status = ? AND retry_count < ?", userID, models.EmailStatusFailed, maxRetries).
+ Order("created_at ASC").
+ Find(&emails).Error; err != nil {
+ return nil, err
+ }
+ return emails, nil
+}
+
+func (r *EmailRepository) FindAll(limit, offset int) ([]models.Email, int64, error) {
+ var emails []models.Email
+ var total int64
+
+ r.db.Model(&models.Email{}).Count(&total)
+
+ if err := r.db.Order("created_at DESC").
+ Limit(limit).Offset(offset).
+ Find(&emails).Error; err != nil {
+ return nil, 0, err
+ }
+ return emails, total, nil
+}
+
+// DeleteOlderThan deletes email records older than the given time.
+// Returns the number of rows deleted.
+func (r *EmailRepository) DeleteOlderThan(before time.Time) (int64, error) {
+ result := r.db.Where("created_at < ?", before).Delete(&models.Email{})
+ return result.RowsAffected, result.Error
+}
diff --git a/internal/storage/repositories/event_repo.go b/internal/storage/repositories/event_repo.go
new file mode 100644
index 0000000..a347d68
--- /dev/null
+++ b/internal/storage/repositories/event_repo.go
@@ -0,0 +1,95 @@
+/*
+ * 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 EventRepository struct {
+ db *gorm.DB
+}
+
+func NewEventRepository(db *gorm.DB) *EventRepository {
+ return &EventRepository{db: db}
+}
+
+func (r *EventRepository) Create(event *models.Event) error {
+ return r.db.Create(event).Error
+}
+
+func (r *EventRepository) FindAll(limit, offset int) ([]models.Event, int64, error) {
+ var events []models.Event
+ var total int64
+
+ r.db.Model(&models.Event{}).Count(&total)
+
+ if err := r.db.Order("created_at DESC").
+ Limit(limit).Offset(offset).
+ Find(&events).Error; err != nil {
+ return nil, 0, err
+ }
+ return events, total, nil
+}
+
+func (r *EventRepository) FindByActorAndCategory(actorID uint, category models.EventCategory, limit, offset int) ([]models.Event, int64, error) {
+ var events []models.Event
+ var total int64
+
+ r.db.Model(&models.Event{}).Where("actor_id = ? AND category = ?", actorID, category).Count(&total)
+
+ if err := r.db.Where("actor_id = ? AND category = ?", actorID, category).
+ Order("created_at DESC").
+ Limit(limit).Offset(offset).
+ Find(&events).Error; err != nil {
+ return nil, 0, err
+ }
+ return events, total, nil
+}
+
+func (r *EventRepository) FindByCategory(category models.EventCategory, limit, offset int) ([]models.Event, int64, error) {
+ var events []models.Event
+ var total int64
+
+ r.db.Model(&models.Event{}).Where("category = ?", category).Count(&total)
+
+ if err := r.db.Where("category = ?", category).
+ Order("created_at DESC").
+ Limit(limit).Offset(offset).
+ Find(&events).Error; err != nil {
+ return nil, 0, err
+ }
+ return events, total, nil
+}
+
+// DeleteOlderThan deletes event records older than the given time.
+// Returns the number of rows deleted.
+func (r *EventRepository) DeleteOlderThan(before time.Time) (int64, error) {
+ result := r.db.Where("created_at < ?", before).Delete(&models.Event{})
+ return result.RowsAffected, result.Error
+}
diff --git a/internal/storage/repositories/language_repo.go b/internal/storage/repositories/language_repo.go
new file mode 100644
index 0000000..7e80677
--- /dev/null
+++ b/internal/storage/repositories/language_repo.go
@@ -0,0 +1,73 @@
+/*
+ * 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 (
+ "github.com/jkaninda/posta/internal/models"
+ "gorm.io/gorm"
+)
+
+type LanguageRepository struct {
+ db *gorm.DB
+}
+
+func NewLanguageRepository(db *gorm.DB) *LanguageRepository {
+ return &LanguageRepository{db: db}
+}
+
+func (r *LanguageRepository) Create(l *models.Language) error {
+ return r.db.Create(l).Error
+}
+
+func (r *LanguageRepository) Update(l *models.Language) error {
+ return r.db.Save(l).Error
+}
+
+func (r *LanguageRepository) Delete(id uint) error {
+ return r.db.Delete(&models.Language{}, id).Error
+}
+
+func (r *LanguageRepository) FindByID(id uint) (*models.Language, error) {
+ var l models.Language
+ if err := r.db.First(&l, id).Error; err != nil {
+ return nil, err
+ }
+ return &l, nil
+}
+
+func (r *LanguageRepository) FindByUserID(userID uint, limit, offset int) ([]models.Language, int64, error) {
+ var languages []models.Language
+ var total int64
+
+ r.db.Model(&models.Language{}).Where("user_id = ?", userID).Count(&total)
+
+ if err := r.db.Where("user_id = ?", userID).
+ Order("code ASC").
+ Limit(limit).Offset(offset).
+ Find(&languages).Error; err != nil {
+ return nil, 0, err
+ }
+ return languages, total, nil
+}
diff --git a/internal/storage/repositories/server_repo.go b/internal/storage/repositories/server_repo.go
new file mode 100644
index 0000000..9f27945
--- /dev/null
+++ b/internal/storage/repositories/server_repo.go
@@ -0,0 +1,103 @@
+/*
+ * 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 (
+ "github.com/jkaninda/posta/internal/models"
+ "gorm.io/gorm"
+)
+
+type ServerRepository struct {
+ db *gorm.DB
+}
+
+func NewServerRepository(db *gorm.DB) *ServerRepository {
+ return &ServerRepository{db: db}
+}
+
+func (r *ServerRepository) Create(server *models.Server) error {
+ return r.db.Create(server).Error
+}
+
+func (r *ServerRepository) Update(server *models.Server) error {
+ return r.db.Save(server).Error
+}
+
+func (r *ServerRepository) Delete(id uint) error {
+ return r.db.Delete(&models.Server{}, id).Error
+}
+
+func (r *ServerRepository) FindByID(id uint) (*models.Server, error) {
+ var server models.Server
+ if err := r.db.First(&server, id).Error; err != nil {
+ return nil, err
+ }
+ return &server, nil
+}
+
+func (r *ServerRepository) FindAll(limit, offset int) ([]models.Server, int64, error) {
+ var servers []models.Server
+ var total int64
+
+ r.db.Model(&models.Server{}).Count(&total)
+
+ if err := r.db.Order("created_at DESC").
+ Limit(limit).Offset(offset).
+ Find(&servers).Error; err != nil {
+ return nil, 0, err
+ }
+ return servers, total, nil
+}
+
+// FindEnabledByDomain returns the first enabled shared server whose allowed_domains
+// contains the given domain.
+func (r *ServerRepository) FindEnabledByDomain(domain string) (*models.Server, error) {
+ var server models.Server
+ if err := r.db.
+ Where("status = ? AND ? = ANY(allowed_domains)", models.SMTPStatusEnabled, domain).
+ First(&server).Error; err != nil {
+ return nil, err
+ }
+ return &server, nil
+}
+
+// IncrementSentCount atomically increases the sent_count by 1 for the given server.
+func (r *ServerRepository) IncrementSentCount(id uint) {
+ r.db.Exec("UPDATE servers SET sent_count = sent_count + 1 WHERE id = ?", id)
+}
+
+// IncrementFailedCount atomically increases the failed_count by 1 for the given server.
+func (r *ServerRepository) IncrementFailedCount(id uint) {
+ r.db.Exec("UPDATE servers SET failed_count = failed_count + 1 WHERE id = ?", id)
+}
+
+// SetStatus updates the status, validation error, and validated_at timestamp for a server.
+func (r *ServerRepository) SetStatus(id uint, status, validationError string) error {
+ return r.db.Model(&models.Server{}).Where("id = ?", id).Updates(map[string]interface{}{
+ "status": status,
+ "validation_error": validationError,
+ "validated_at": gorm.Expr("NOW()"),
+ }).Error
+}
diff --git a/internal/storage/repositories/setting_repo.go b/internal/storage/repositories/setting_repo.go
new file mode 100644
index 0000000..125804a
--- /dev/null
+++ b/internal/storage/repositories/setting_repo.go
@@ -0,0 +1,77 @@
+/*
+ * 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 (
+ "github.com/jkaninda/posta/internal/models"
+ "gorm.io/gorm"
+)
+
+type SettingRepository struct {
+ db *gorm.DB
+}
+
+func NewSettingRepository(db *gorm.DB) *SettingRepository {
+ return &SettingRepository{db: db}
+}
+
+func (r *SettingRepository) FindAll() ([]models.Setting, error) {
+ var settings []models.Setting
+ if err := r.db.Order("key ASC").Find(&settings).Error; err != nil {
+ return nil, err
+ }
+ return settings, nil
+}
+
+func (r *SettingRepository) FindByKey(key string) (*models.Setting, error) {
+ var setting models.Setting
+ if err := r.db.Where("key = ?", key).First(&setting).Error; err != nil {
+ return nil, err
+ }
+ return &setting, nil
+}
+
+func (r *SettingRepository) Upsert(setting *models.Setting) error {
+ var existing models.Setting
+ result := r.db.Where("key = ?", setting.Key).First(&existing)
+ if result.Error == nil {
+ existing.Value = setting.Value
+ existing.Type = setting.Type
+ return r.db.Save(&existing).Error
+ }
+ return r.db.Create(setting).Error
+}
+
+func (r *SettingRepository) BulkUpsert(settings []models.Setting) error {
+ return r.db.Transaction(func(tx *gorm.DB) error {
+ repo := &SettingRepository{db: tx}
+ for i := range settings {
+ if err := repo.Upsert(&settings[i]); err != nil {
+ return err
+ }
+ }
+ return nil
+ })
+}
diff --git a/internal/storage/repositories/smtp_repo.go b/internal/storage/repositories/smtp_repo.go
new file mode 100644
index 0000000..84c636e
--- /dev/null
+++ b/internal/storage/repositories/smtp_repo.go
@@ -0,0 +1,100 @@
+/*
+ * 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 (
+ "github.com/jkaninda/posta/internal/models"
+ "gorm.io/gorm"
+)
+
+type SMTPRepository struct {
+ db *gorm.DB
+}
+
+func NewSMTPRepository(db *gorm.DB) *SMTPRepository {
+ return &SMTPRepository{db: db}
+}
+
+func (r *SMTPRepository) Create(server *models.SMTPServer) error {
+ return r.db.Create(server).Error
+}
+
+func (r *SMTPRepository) Update(server *models.SMTPServer) error {
+ return r.db.Save(server).Error
+}
+
+func (r *SMTPRepository) Delete(id uint) error {
+ return r.db.Delete(&models.SMTPServer{}, id).Error
+}
+
+func (r *SMTPRepository) FindByID(id uint) (*models.SMTPServer, error) {
+ var server models.SMTPServer
+ if err := r.db.First(&server, id).Error; err != nil {
+ return nil, err
+ }
+ return &server, nil
+}
+
+func (r *SMTPRepository) FindByUserID(userID uint, limit, offset int) ([]models.SMTPServer, int64, error) {
+ var servers []models.SMTPServer
+ var total int64
+
+ r.db.Model(&models.SMTPServer{}).Where("user_id = ?", userID).Count(&total)
+
+ if err := r.db.Where("user_id = ?", userID).
+ Order("created_at DESC").
+ Limit(limit).Offset(offset).
+ Find(&servers).Error; err != nil {
+ return nil, 0, err
+ }
+ return servers, total, nil
+}
+
+// FindAllWithRetries returns all enabled SMTP servers that have max_retries > 0.
+func (r *SMTPRepository) FindAllWithRetries() ([]models.SMTPServer, error) {
+ var servers []models.SMTPServer
+ if err := r.db.Where("max_retries > 0 AND status = ?", models.SMTPStatusEnabled).Find(&servers).Error; err != nil {
+ return nil, err
+ }
+ return servers, nil
+}
+
+// FindFirstByUserID returns the first enabled SMTP server for a user.
+func (r *SMTPRepository) FindFirstByUserID(userID uint) (*models.SMTPServer, error) {
+ var server models.SMTPServer
+ if err := r.db.Where("user_id = ? AND status = ?", userID, models.SMTPStatusEnabled).First(&server).Error; err != nil {
+ return nil, err
+ }
+ return &server, nil
+}
+
+// SetStatus updates the status, validation error, and validated_at timestamp for a server.
+func (r *SMTPRepository) SetStatus(id uint, status, validationError string) error {
+ return r.db.Model(&models.SMTPServer{}).Where("id = ?", id).Updates(map[string]interface{}{
+ "status": status,
+ "validation_error": validationError,
+ "validated_at": gorm.Expr("NOW()"),
+ }).Error
+}
diff --git a/internal/storage/repositories/stylesheet_repo.go b/internal/storage/repositories/stylesheet_repo.go
new file mode 100644
index 0000000..54aa141
--- /dev/null
+++ b/internal/storage/repositories/stylesheet_repo.go
@@ -0,0 +1,73 @@
+/*
+ * 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 (
+ "github.com/jkaninda/posta/internal/models"
+ "gorm.io/gorm"
+)
+
+type StyleSheetRepository struct {
+ db *gorm.DB
+}
+
+func NewStyleSheetRepository(db *gorm.DB) *StyleSheetRepository {
+ return &StyleSheetRepository{db: db}
+}
+
+func (r *StyleSheetRepository) Create(ss *models.StyleSheet) error {
+ return r.db.Create(ss).Error
+}
+
+func (r *StyleSheetRepository) Update(ss *models.StyleSheet) error {
+ return r.db.Save(ss).Error
+}
+
+func (r *StyleSheetRepository) Delete(id uint) error {
+ return r.db.Delete(&models.StyleSheet{}, id).Error
+}
+
+func (r *StyleSheetRepository) FindByID(id uint) (*models.StyleSheet, error) {
+ var ss models.StyleSheet
+ if err := r.db.First(&ss, id).Error; err != nil {
+ return nil, err
+ }
+ return &ss, nil
+}
+
+func (r *StyleSheetRepository) FindByUserID(userID uint, limit, offset int) ([]models.StyleSheet, int64, error) {
+ var sheets []models.StyleSheet
+ var total int64
+
+ r.db.Model(&models.StyleSheet{}).Where("user_id = ?", userID).Count(&total)
+
+ if err := r.db.Where("user_id = ?", userID).
+ Order("created_at DESC").
+ Limit(limit).Offset(offset).
+ Find(&sheets).Error; err != nil {
+ return nil, 0, err
+ }
+ return sheets, total, nil
+}
diff --git a/internal/storage/repositories/suppression_repo.go b/internal/storage/repositories/suppression_repo.go
new file mode 100644
index 0000000..0508d03
--- /dev/null
+++ b/internal/storage/repositories/suppression_repo.go
@@ -0,0 +1,114 @@
+/*
+ * 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 (
+ "net/mail"
+ "strings"
+
+ "github.com/jkaninda/posta/internal/models"
+ "gorm.io/gorm"
+)
+
+// normalizeEmail extracts the bare email address from a string that may be in
+// RFC 5322 format like "Display Name <[email protected]>" and lowercases it.
+func normalizeEmail(raw string) string {
+ addr, err := mail.ParseAddress(raw)
+ if err != nil {
+ return strings.ToLower(strings.TrimSpace(raw))
+ }
+ return strings.ToLower(addr.Address)
+}
+
+type SuppressionRepository struct {
+ db *gorm.DB
+}
+
+func NewSuppressionRepository(db *gorm.DB) *SuppressionRepository {
+ return &SuppressionRepository{db: db}
+}
+
+func (r *SuppressionRepository) Create(suppression *models.Suppression) error {
+ suppression.Email = normalizeEmail(suppression.Email)
+ return r.db.Create(suppression).Error
+}
+
+func (r *SuppressionRepository) Delete(userID uint, email string) error {
+ return r.db.Where("user_id = ? AND email = ?", userID, normalizeEmail(email)).Delete(&models.Suppression{}).Error
+}
+
+func (r *SuppressionRepository) FindByUserID(userID uint, limit, offset int) ([]models.Suppression, int64, error) {
+ var suppressions []models.Suppression
+ var total int64
+
+ r.db.Model(&models.Suppression{}).Where("user_id = ?", userID).Count(&total)
+
+ if err := r.db.Where("user_id = ?", userID).
+ Order("created_at DESC").
+ Limit(limit).Offset(offset).
+ Find(&suppressions).Error; err != nil {
+ return nil, 0, err
+ }
+ return suppressions, total, nil
+}
+
+func (r *SuppressionRepository) IsSuppressed(userID uint, email string) (bool, error) {
+ var count int64
+ err := r.db.Model(&models.Suppression{}).
+ Where("user_id = ? AND email = ?", userID, normalizeEmail(email)).
+ Count(&count).Error
+ return count > 0, err
+}
+
+func (r *SuppressionRepository) FilterSuppressed(userID uint, emails []string) ([]string, error) {
+ if len(emails) == 0 {
+ return emails, nil
+ }
+
+ lowered := make([]string, len(emails))
+ for i, e := range emails {
+ lowered[i] = normalizeEmail(e)
+ }
+
+ var suppressed []string
+ if err := r.db.Model(&models.Suppression{}).
+ Where("user_id = ? AND email IN ?", userID, lowered).
+ Pluck("email", &suppressed).Error; err != nil {
+ return nil, err
+ }
+
+ suppressedSet := make(map[string]bool, len(suppressed))
+ for _, s := range suppressed {
+ suppressedSet[s] = true
+ }
+
+ var filtered []string
+ for _, e := range emails {
+ if !suppressedSet[normalizeEmail(e)] {
+ filtered = append(filtered, e)
+ }
+ }
+ return filtered, nil
+}
diff --git a/internal/storage/repositories/template_localization_repo.go b/internal/storage/repositories/template_localization_repo.go
new file mode 100644
index 0000000..a4312af
--- /dev/null
+++ b/internal/storage/repositories/template_localization_repo.go
@@ -0,0 +1,76 @@
+/*
+ * 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 (
+ "github.com/jkaninda/posta/internal/models"
+ "gorm.io/gorm"
+)
+
+type TemplateLocalizationRepository struct {
+ db *gorm.DB
+}
+
+func NewTemplateLocalizationRepository(db *gorm.DB) *TemplateLocalizationRepository {
+ return &TemplateLocalizationRepository{db: db}
+}
+
+func (r *TemplateLocalizationRepository) Create(l *models.TemplateLocalization) error {
+ return r.db.Create(l).Error
+}
+
+func (r *TemplateLocalizationRepository) Update(l *models.TemplateLocalization) error {
+ return r.db.Save(l).Error
+}
+
+func (r *TemplateLocalizationRepository) FindByID(id uint) (*models.TemplateLocalization, error) {
+ var l models.TemplateLocalization
+ if err := r.db.First(&l, id).Error; err != nil {
+ return nil, err
+ }
+ return &l, nil
+}
+
+func (r *TemplateLocalizationRepository) FindByVersionID(versionID uint) ([]models.TemplateLocalization, error) {
+ var localizations []models.TemplateLocalization
+ if err := r.db.Where("version_id = ?", versionID).
+ Order("language ASC").
+ Find(&localizations).Error; err != nil {
+ return nil, err
+ }
+ return localizations, nil
+}
+
+func (r *TemplateLocalizationRepository) FindByVersionAndLanguage(versionID uint, language string) (*models.TemplateLocalization, error) {
+ var l models.TemplateLocalization
+ if err := r.db.Where("version_id = ? AND language = ?", versionID, language).First(&l).Error; err != nil {
+ return nil, err
+ }
+ return &l, nil
+}
+
+func (r *TemplateLocalizationRepository) Delete(id uint) error {
+ return r.db.Delete(&models.TemplateLocalization{}, id).Error
+}
diff --git a/internal/storage/repositories/template_repo.go b/internal/storage/repositories/template_repo.go
new file mode 100644
index 0000000..e889660
--- /dev/null
+++ b/internal/storage/repositories/template_repo.go
@@ -0,0 +1,81 @@
+/*
+ * 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 (
+ "github.com/jkaninda/posta/internal/models"
+ "gorm.io/gorm"
+)
+
+type TemplateRepository struct {
+ db *gorm.DB
+}
+
+func NewTemplateRepository(db *gorm.DB) *TemplateRepository {
+ return &TemplateRepository{db: db}
+}
+
+func (r *TemplateRepository) Create(tmpl *models.Template) error {
+ return r.db.Create(tmpl).Error
+}
+
+func (r *TemplateRepository) Update(tmpl *models.Template) error {
+ return r.db.Save(tmpl).Error
+}
+
+func (r *TemplateRepository) Delete(id uint) error {
+ return r.db.Delete(&models.Template{}, id).Error
+}
+
+func (r *TemplateRepository) FindByID(id uint) (*models.Template, error) {
+ var tmpl models.Template
+ if err := r.db.First(&tmpl, id).Error; err != nil {
+ return nil, err
+ }
+ return &tmpl, nil
+}
+
+func (r *TemplateRepository) FindByName(userID uint, name string) (*models.Template, error) {
+ var tmpl models.Template
+ if err := r.db.Where("user_id = ? AND name = ?", userID, name).First(&tmpl).Error; err != nil {
+ return nil, err
+ }
+ return &tmpl, nil
+}
+
+func (r *TemplateRepository) FindByUserID(userID uint, limit, offset int) ([]models.Template, int64, error) {
+ var templates []models.Template
+ var total int64
+
+ r.db.Model(&models.Template{}).Where("user_id = ?", userID).Count(&total)
+
+ if err := r.db.Where("user_id = ?", userID).
+ Order("created_at DESC").
+ Limit(limit).Offset(offset).
+ Find(&templates).Error; err != nil {
+ return nil, 0, err
+ }
+ return templates, total, nil
+}
diff --git a/internal/storage/repositories/template_version_repo.go b/internal/storage/repositories/template_version_repo.go
new file mode 100644
index 0000000..8603f64
--- /dev/null
+++ b/internal/storage/repositories/template_version_repo.go
@@ -0,0 +1,78 @@
+/*
+ * 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 (
+ "github.com/jkaninda/posta/internal/models"
+ "gorm.io/gorm"
+)
+
+type TemplateVersionRepository struct {
+ db *gorm.DB
+}
+
+func NewTemplateVersionRepository(db *gorm.DB) *TemplateVersionRepository {
+ return &TemplateVersionRepository{db: db}
+}
+
+func (r *TemplateVersionRepository) Create(v *models.TemplateVersion) error {
+ return r.db.Create(v).Error
+}
+
+func (r *TemplateVersionRepository) FindByID(id uint) (*models.TemplateVersion, error) {
+ var v models.TemplateVersion
+ if err := r.db.Preload("StyleSheet").First(&v, id).Error; err != nil {
+ return nil, err
+ }
+ return &v, nil
+}
+
+func (r *TemplateVersionRepository) FindByTemplateID(templateID uint) ([]models.TemplateVersion, error) {
+ var versions []models.TemplateVersion
+ if err := r.db.Preload("StyleSheet").
+ Where("template_id = ?", templateID).
+ Order("version DESC").
+ Find(&versions).Error; err != nil {
+ return nil, err
+ }
+ return versions, nil
+}
+
+func (r *TemplateVersionRepository) NextVersion(templateID uint) (int, error) {
+ var max int
+ err := r.db.Model(&models.TemplateVersion{}).
+ Where("template_id = ?", templateID).
+ Select("COALESCE(MAX(version), 0)").
+ Scan(&max).Error
+ return max + 1, err
+}
+
+func (r *TemplateVersionRepository) Update(v *models.TemplateVersion) error {
+ return r.db.Save(v).Error
+}
+
+func (r *TemplateVersionRepository) Delete(id uint) error {
+ return r.db.Delete(&models.TemplateVersion{}, id).Error
+}
diff --git a/internal/storage/repositories/user_repo.go b/internal/storage/repositories/user_repo.go
new file mode 100644
index 0000000..b4d60ef
--- /dev/null
+++ b/internal/storage/repositories/user_repo.go
@@ -0,0 +1,80 @@
+/*
+ * 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 (
+ "github.com/jkaninda/posta/internal/models"
+ "gorm.io/gorm"
+)
+
+type UserRepository struct {
+ db *gorm.DB
+}
+
+func NewUserRepository(db *gorm.DB) *UserRepository {
+ return &UserRepository{db: db}
+}
+
+func (r *UserRepository) Create(user *models.User) error {
+ return r.db.Create(user).Error
+}
+
+func (r *UserRepository) FindByEmail(email string) (*models.User, error) {
+ var user models.User
+ if err := r.db.Where("email = ?", email).First(&user).Error; err != nil {
+ return nil, err
+ }
+ return &user, nil
+}
+
+func (r *UserRepository) FindByID(id uint) (*models.User, error) {
+ var user models.User
+ if err := r.db.First(&user, id).Error; err != nil {
+ return nil, err
+ }
+ return &user, nil
+}
+
+func (r *UserRepository) FindAll(limit, offset int) ([]models.User, int64, error) {
+ var users []models.User
+ var total int64
+
+ r.db.Model(&models.User{}).Count(&total)
+
+ if err := r.db.Order("created_at DESC").
+ Limit(limit).Offset(offset).
+ Find(&users).Error; err != nil {
+ return nil, 0, err
+ }
+ return users, total, nil
+}
+
+func (r *UserRepository) Update(user *models.User) error {
+ return r.db.Save(user).Error
+}
+
+func (r *UserRepository) Delete(id uint) error {
+ return r.db.Delete(&models.User{}, id).Error
+}
diff --git a/internal/storage/repositories/user_setting_repo.go b/internal/storage/repositories/user_setting_repo.go
new file mode 100644
index 0000000..4764d24
--- /dev/null
+++ b/internal/storage/repositories/user_setting_repo.go
@@ -0,0 +1,78 @@
+/*
+ * 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 (
+ "github.com/jkaninda/posta/internal/models"
+ "gorm.io/gorm"
+)
+
+type UserSettingRepository struct {
+ db *gorm.DB
+}
+
+func NewUserSettingRepository(db *gorm.DB) *UserSettingRepository {
+ return &UserSettingRepository{db: db}
+}
+
+// FindByUserID returns the user's settings, creating a default row if none exists.
+func (r *UserSettingRepository) FindByUserID(userID uint) (*models.UserSetting, error) {
+ var setting models.UserSetting
+ result := r.db.Where("user_id = ?", userID).First(&setting)
+ if result.Error == nil {
+ return &setting, nil
+ }
+ if result.Error == gorm.ErrRecordNotFound {
+ setting = models.UserSetting{
+ UserID: userID,
+ Timezone: "UTC",
+ EmailNotifications: true,
+ WebhookRetryCount: 3,
+ APIKeyExpiryDays: 90,
+ BounceAutoSuppress: true,
+ }
+ if err := r.db.Create(&setting).Error; err != nil {
+ return nil, err
+ }
+ return &setting, nil
+ }
+ return nil, result.Error
+}
+
+// CreateOrUpdate saves or updates the user's settings row.
+func (r *UserSettingRepository) CreateOrUpdate(setting *models.UserSetting) error {
+ return r.db.Save(setting).Error
+}
+
+// FindUsersWithDailyReport returns user IDs that have daily_report enabled.
+func (r *UserSettingRepository) FindUsersWithDailyReport() ([]uint, error) {
+ var userIDs []uint
+ if err := r.db.Model(&models.UserSetting{}).
+ Where("daily_report = ?", true).
+ Pluck("user_id", &userIDs).Error; err != nil {
+ return nil, err
+ }
+ return userIDs, nil
+}
diff --git a/internal/storage/repositories/webhook_delivery_repo.go b/internal/storage/repositories/webhook_delivery_repo.go
new file mode 100644
index 0000000..e54979b
--- /dev/null
+++ b/internal/storage/repositories/webhook_delivery_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 WebhookDeliveryRepository struct {
+ db *gorm.DB
+}
+
+func NewWebhookDeliveryRepository(db *gorm.DB) *WebhookDeliveryRepository {
+ return &WebhookDeliveryRepository{db: db}
+}
+
+func (r *WebhookDeliveryRepository) Create(d *models.WebhookDelivery) error {
+ return r.db.Create(d).Error
+}
+
+// WebhookDeliveryStats holds aggregate delivery counts.
+type WebhookDeliveryStats struct {
+ TotalDeliveries int64 `json:"total_deliveries"`
+ SuccessDeliveries int64 `json:"success_deliveries"`
+ FailedDeliveries int64 `json:"failed_deliveries"`
+ SuccessRate float64 `json:"success_rate"`
+}
+
+// StatsByUserID returns aggregate webhook delivery stats for a user.
+func (r *WebhookDeliveryRepository) StatsByUserID(userID uint) (*WebhookDeliveryStats, error) {
+ var stats WebhookDeliveryStats
+
+ r.db.Model(&models.WebhookDelivery{}).Where("user_id = ?", userID).Count(&stats.TotalDeliveries)
+ r.db.Model(&models.WebhookDelivery{}).Where("user_id = ? AND status = ?", userID, models.WebhookDeliverySuccess).Count(&stats.SuccessDeliveries)
+ r.db.Model(&models.WebhookDelivery{}).Where("user_id = ? AND status = ?", userID, models.WebhookDeliveryFailed).Count(&stats.FailedDeliveries)
+
+ if stats.TotalDeliveries > 0 {
+ stats.SuccessRate = float64(stats.SuccessDeliveries) / float64(stats.TotalDeliveries) * 100
+ }
+
+ return &stats, nil
+}
+
+// StatsAll returns aggregate webhook delivery stats across all users.
+func (r *WebhookDeliveryRepository) StatsAll() (*WebhookDeliveryStats, error) {
+ var stats WebhookDeliveryStats
+
+ r.db.Model(&models.WebhookDelivery{}).Count(&stats.TotalDeliveries)
+ r.db.Model(&models.WebhookDelivery{}).Where("status = ?", models.WebhookDeliverySuccess).Count(&stats.SuccessDeliveries)
+ r.db.Model(&models.WebhookDelivery{}).Where("status = ?", models.WebhookDeliveryFailed).Count(&stats.FailedDeliveries)
+
+ if stats.TotalDeliveries > 0 {
+ stats.SuccessRate = float64(stats.SuccessDeliveries) / float64(stats.TotalDeliveries) * 100
+ }
+
+ return &stats, nil
+}
+
+// RecentByUserID returns the most recent deliveries for a user.
+func (r *WebhookDeliveryRepository) RecentByUserID(userID uint, limit int) ([]models.WebhookDelivery, error) {
+ var deliveries []models.WebhookDelivery
+ err := r.db.Where("user_id = ?", userID).
+ Order("created_at DESC").
+ Limit(limit).
+ Find(&deliveries).Error
+ return deliveries, err
+}
+
+// FindByUserID returns paginated webhook deliveries for a user.
+func (r *WebhookDeliveryRepository) FindByUserID(userID uint, limit, offset int) ([]models.WebhookDelivery, int64, error) {
+ var deliveries []models.WebhookDelivery
+ var total int64
+ r.db.Model(&models.WebhookDelivery{}).Where("user_id = ?", userID).Count(&total)
+ err := r.db.Where("user_id = ?", userID).
+ Order("created_at DESC").
+ Limit(limit).
+ Offset(offset).
+ Find(&deliveries).Error
+ return deliveries, total, err
+}
+
+// DeleteOlderThan deletes webhook delivery records older than the given time.
+// Returns the number of rows deleted.
+func (r *WebhookDeliveryRepository) DeleteOlderThan(before time.Time) (int64, error) {
+ result := r.db.Where("created_at < ?", before).Delete(&models.WebhookDelivery{})
+ return result.RowsAffected, result.Error
+}
diff --git a/internal/storage/repositories/webhook_repo.go b/internal/storage/repositories/webhook_repo.go
new file mode 100644
index 0000000..3e8b046
--- /dev/null
+++ b/internal/storage/repositories/webhook_repo.go
@@ -0,0 +1,82 @@
+/*
+ * 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 (
+ "github.com/jkaninda/posta/internal/models"
+ "gorm.io/gorm"
+)
+
+type WebhookRepository struct {
+ db *gorm.DB
+}
+
+func NewWebhookRepository(db *gorm.DB) *WebhookRepository {
+ return &WebhookRepository{db: db}
+}
+
+func (r *WebhookRepository) Create(webhook *models.Webhook) error {
+ return r.db.Create(webhook).Error
+}
+
+func (r *WebhookRepository) Delete(id uint) error {
+ return r.db.Transaction(func(tx *gorm.DB) error {
+ if err := tx.Where("webhook_id = ?", id).Delete(&models.WebhookDelivery{}).Error; err != nil {
+ return err
+ }
+ return tx.Delete(&models.Webhook{}, id).Error
+ })
+}
+
+func (r *WebhookRepository) FindByID(id uint) (*models.Webhook, error) {
+ var webhook models.Webhook
+ if err := r.db.First(&webhook, id).Error; err != nil {
+ return nil, err
+ }
+ return &webhook, nil
+}
+
+func (r *WebhookRepository) FindByUserID(userID uint, limit, offset int) ([]models.Webhook, int64, error) {
+ var webhooks []models.Webhook
+ var total int64
+
+ r.db.Model(&models.Webhook{}).Where("user_id = ?", userID).Count(&total)
+
+ if err := r.db.Where("user_id = ?", userID).
+ Order("created_at DESC").
+ Limit(limit).Offset(offset).
+ Find(&webhooks).Error; err != nil {
+ return nil, 0, err
+ }
+ return webhooks, total, nil
+}
+
+func (r *WebhookRepository) FindByUserIDAndEvent(userID uint, event string) ([]models.Webhook, error) {
+ var webhooks []models.Webhook
+ if err := r.db.Where("user_id = ? AND ? = ANY(events)", userID, event).Find(&webhooks).Error; err != nil {
+ return nil, err
+ }
+ return webhooks, nil
+}
diff --git a/internal/worker/handler.go b/internal/worker/handler.go
new file mode 100644
index 0000000..5386ab3
--- /dev/null
+++ b/internal/worker/handler.go
@@ -0,0 +1,271 @@
+/*
+ * 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 worker
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/mail"
+ "strings"
+ "time"
+
+ "github.com/hibiken/asynq"
+ "github.com/jkaninda/logger"
+ "github.com/jkaninda/posta/internal/models"
+ "github.com/jkaninda/posta/internal/services/email"
+ "github.com/jkaninda/posta/internal/services/webhook"
+ "github.com/jkaninda/posta/internal/storage/repositories"
+)
+
+// EmailSendHandler processes email:send tasks from the Asynq queue.
+type EmailSendHandler struct {
+ emailRepo *repositories.EmailRepository
+ smtpRepo *repositories.SMTPRepository
+ serverRepo *repositories.ServerRepository
+ domainRepo *repositories.DomainRepository
+ contactRepo *repositories.ContactRepository
+ sender *email.SMTPSender
+ dispatcher *webhook.Dispatcher
+ onSent func()
+ onFailed func()
+}
+
+func NewEmailSendHandler(
+ emailRepo *repositories.EmailRepository,
+ smtpRepo *repositories.SMTPRepository,
+ serverRepo *repositories.ServerRepository,
+ domainRepo *repositories.DomainRepository,
+ contactRepo *repositories.ContactRepository,
+ dispatcher *webhook.Dispatcher,
+) *EmailSendHandler {
+ return &EmailSendHandler{
+ emailRepo: emailRepo,
+ smtpRepo: smtpRepo,
+ serverRepo: serverRepo,
+ domainRepo: domainRepo,
+ contactRepo: contactRepo,
+ sender: email.NewSMTPSender(),
+ dispatcher: dispatcher,
+ }
+}
+
+// OnSent sets a callback invoked after each successful email send.
+func (h *EmailSendHandler) OnSent(fn func()) { h.onSent = fn }
+
+// OnFailed sets a callback invoked after each permanently failed email send.
+func (h *EmailSendHandler) OnFailed(fn func()) { h.onFailed = fn }
+
+// ProcessTask handles an email:send task.
+func (h *EmailSendHandler) ProcessTask(_ context.Context, t *asynq.Task) error {
+ var payload EmailSendPayload
+ if err := json.Unmarshal(t.Payload(), &payload); err != nil {
+ return fmt.Errorf("failed to unmarshal payload: %w", err)
+ }
+
+ em, err := h.emailRepo.FindByID(payload.EmailID)
+ if err != nil {
+ return fmt.Errorf("email not found: %w", err)
+ }
+
+ // Mark as processing
+ em.Status = models.EmailStatusProcessing
+ _ = h.emailRepo.Update(em)
+
+ // Resolve sender address for validation/domain matching
+ senderAddr := em.Sender
+ if parsed, err := mail.ParseAddress(em.Sender); err == nil {
+ senderAddr = parsed.Address
+ }
+
+ // --- Server selection ---
+ // 1. Try the user's own per-account SMTP server first.
+ // 2. Fall back to a shared server whose allowed_domains covers the sender domain.
+ var smtpServer *models.SMTPServer
+ var sharedServerID uint // non-zero when a shared server is used
+
+ userServer, err := h.smtpRepo.FindFirstByUserID(em.UserID)
+ if err == nil {
+ // Validate the sender against the per-user allowed emails list
+ if len(userServer.AllowedEmails) > 0 {
+ allowed := false
+ for _, e := range userServer.AllowedEmails {
+ if e == senderAddr {
+ allowed = true
+ break
+ }
+ }
+ if !allowed {
+ h.markFailed(em, fmt.Sprintf("sender %q is not in the allowed emails list", em.Sender), 0)
+ return nil
+ }
+ }
+ smtpServer = userServer
+ } else {
+ // No per-user server – look for a shared server by sender domain
+ if h.serverRepo != nil {
+ domain := senderDomain(senderAddr)
+ if domain != "" {
+ shared, serr := h.serverRepo.FindEnabledByDomain(domain)
+ if serr == nil {
+ // In strict mode the sender's domain must be ownership-verified.
+ if shared.SecurityMode == models.ServerSecurityModeStrict {
+ if h.domainRepo == nil || !h.domainRepo.IsOwnershipVerified(em.UserID, domain) {
+ h.markFailed(em, fmt.Sprintf("shared server %q requires verified domain ownership for %q", shared.Name, domain), 0)
+ return nil
+ }
+ }
+ smtpServer = shared.ToSMTPServer()
+ sharedServerID = shared.ID
+ }
+ }
+ }
+ }
+
+ if smtpServer == nil {
+ h.markFailed(em, "no SMTP server configured for this account or domain", 0)
+ // Don't retry – adding a server won't happen automatically.
+ return nil
+ }
+
+ em.SMTPHostname = smtpServer.Host
+ _ = h.emailRepo.Update(em)
+
+ // Auto-generate plain text from HTML if not provided
+ if em.TextBody == "" && em.HTMLBody != "" {
+ em.TextBody = email.HTMLToText(em.HTMLBody)
+ }
+
+ // Parse attachments from stored JSON
+ var attachments []models.Attachment
+ if em.AttachmentsJSON != "" {
+ _ = json.Unmarshal([]byte(em.AttachmentsJSON), &attachments)
+ }
+
+ // Parse custom headers from stored JSON
+ var headers map[string]string
+ if em.HeadersJSON != "" {
+ _ = json.Unmarshal([]byte(em.HeadersJSON), &headers)
+ }
+
+ if err := h.sender.Send(smtpServer, em.Sender, em.Recipients, em.Subject, em.HTMLBody, em.TextBody, attachments, headers, em.ListUnsubscribeURL, em.ListUnsubscribePost); err != nil {
+ em.RetryCount++
+ em.Status = models.EmailStatusFailed
+ em.ErrorMessage = err.Error()
+ _ = h.emailRepo.Update(em)
+ // Increment the shared server's failure counter
+ if sharedServerID != 0 && h.serverRepo != nil {
+ go h.serverRepo.IncrementFailedCount(sharedServerID)
+ }
+ logger.Debug("worker: email send failed, will retry", "id", em.ID, "attempt", em.RetryCount, "error", err)
+ // Return error so Asynq retries the task
+ return fmt.Errorf("SMTP send failed: %w", err)
+ }
+
+ // Success
+ now := time.Now()
+ em.Status = models.EmailStatusSent
+ em.SentAt = &now
+ em.ErrorMessage = ""
+ _ = h.emailRepo.Update(em)
+ // Increment the shared server's success counter
+ if sharedServerID != 0 && h.serverRepo != nil {
+ go h.serverRepo.IncrementSentCount(sharedServerID)
+ }
+ h.dispatcher.Dispatch(em.UserID, "email.sent", em.UUID, em.Sender)
+ if h.onSent != nil {
+ h.onSent()
+ }
+ if h.contactRepo != nil {
+ go h.contactRepo.RecordSent(em.UserID, em.Recipients)
+ }
+ logger.Info("worker: email sent successfully", "id", em.ID)
+
+ return nil
+}
+
+func (h *EmailSendHandler) markFailed(em *models.Email, reason string, sharedServerID uint) {
+ em.Status = models.EmailStatusFailed
+ em.ErrorMessage = reason
+ _ = h.emailRepo.Update(em)
+ if sharedServerID != 0 && h.serverRepo != nil {
+ go h.serverRepo.IncrementFailedCount(sharedServerID)
+ }
+ h.dispatcher.Dispatch(em.UserID, "email.failed", em.UUID, em.Sender)
+ if h.onFailed != nil {
+ h.onFailed()
+ }
+ if h.contactRepo != nil {
+ go h.contactRepo.RecordFailed(em.UserID, em.Recipients)
+ }
+}
+
+// senderDomain extracts the domain part of an email address.
+func senderDomain(addr string) string {
+ parts := strings.SplitN(addr, "@", 2)
+ if len(parts) != 2 {
+ return ""
+ }
+ return strings.ToLower(parts[1])
+}
+
+// ExhaustedErrorHandler marks emails as permanently failed when Asynq exhausts
+// all retries. It implements asynq.ErrorHandler.
+type ExhaustedErrorHandler struct {
+ emailRepo *repositories.EmailRepository
+ dispatcher *webhook.Dispatcher
+ onFailed func()
+}
+
+func NewExhaustedErrorHandler(emailRepo *repositories.EmailRepository, dispatcher *webhook.Dispatcher, onFailed func()) *ExhaustedErrorHandler {
+ return &ExhaustedErrorHandler{
+ emailRepo: emailRepo,
+ dispatcher: dispatcher,
+ onFailed: onFailed,
+ }
+}
+
+func (e *ExhaustedErrorHandler) HandleError(_ context.Context, t *asynq.Task, err error) {
+ if t.Type() != TypeEmailSend {
+ return
+ }
+ var payload EmailSendPayload
+ if jsonErr := json.Unmarshal(t.Payload(), &payload); jsonErr != nil {
+ logger.Error("exhausted handler: failed to unmarshal payload", "error", jsonErr)
+ return
+ }
+ em, findErr := e.emailRepo.FindByID(payload.EmailID)
+ if findErr != nil {
+ return
+ }
+ em.Status = models.EmailStatusFailed
+ em.ErrorMessage = fmt.Sprintf("permanently failed after retries: %v", err)
+ _ = e.emailRepo.Update(em)
+ e.dispatcher.Dispatch(em.UserID, "email.failed", em.UUID, em.Sender)
+ if e.onFailed != nil {
+ e.onFailed()
+ }
+ logger.Error("worker: email permanently failed", "id", em.ID, "error", err)
+}
diff --git a/internal/worker/producer.go b/internal/worker/producer.go
new file mode 100644
index 0000000..27de363
--- /dev/null
+++ b/internal/worker/producer.go
@@ -0,0 +1,97 @@
+/*
+ * 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 worker
+
+import (
+ "fmt"
+ "time"
+
+ "github.com/hibiken/asynq"
+)
+
+// Producer enqueues email tasks into Redis via Asynq.
+type Producer struct {
+ client *asynq.Client
+ maxRetries int
+}
+
+func NewProducer(redisAddr, redisPassword string, maxRetries int) *Producer {
+ client := asynq.NewClient(asynq.RedisClientOpt{
+ Addr: redisAddr,
+ Password: redisPassword,
+ })
+ return &Producer{
+ client: client,
+ maxRetries: maxRetries,
+ }
+}
+
+// EnqueueEmailSend enqueues an email for background delivery.
+func (p *Producer) EnqueueEmailSend(emailID uint, queue string) error {
+ if queue == "" {
+ queue = QueueTransactional
+ }
+ task, err := NewEmailSendTask(emailID,
+ asynq.Queue(queue),
+ asynq.MaxRetry(p.maxRetries),
+ )
+ if err != nil {
+ return fmt.Errorf("failed to create task: %w", err)
+ }
+ _, err = p.client.Enqueue(task)
+ if err != nil {
+ return fmt.Errorf("failed to enqueue task: %w", err)
+ }
+ return nil
+}
+
+// EnqueueEmailSendAt enqueues an email for delivery at the specified time.
+func (p *Producer) EnqueueEmailSendAt(emailID uint, queue string, sendAt time.Time) error {
+ if queue == "" {
+ queue = QueueTransactional
+ }
+ delay := time.Until(sendAt)
+ if delay < 0 {
+ delay = 0
+ }
+ task, err := NewEmailSendTask(emailID,
+ asynq.Queue(queue),
+ asynq.MaxRetry(p.maxRetries),
+ asynq.ProcessIn(delay),
+ )
+ if err != nil {
+ return fmt.Errorf("failed to create task: %w", err)
+ }
+ _, err = p.client.Enqueue(task)
+ if err != nil {
+ return fmt.Errorf("failed to enqueue task: %w", err)
+ }
+ return nil
+}
+
+// Close closes the underlying Asynq client.
+func (p *Producer) Close() error {
+ return p.client.Close()
+}
diff --git a/internal/worker/tasks.go b/internal/worker/tasks.go
new file mode 100644
index 0000000..4ab72a9
--- /dev/null
+++ b/internal/worker/tasks.go
@@ -0,0 +1,52 @@
+/*
+ * 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 worker
+
+import (
+ "encoding/json"
+
+ "github.com/hibiken/asynq"
+)
+
+const (
+ TypeEmailSend = "email:send"
+
+ QueueTransactional = "transactional"
+ QueueBulk = "bulk"
+ QueueLow = "low"
+)
+
+type EmailSendPayload struct {
+ EmailID uint `json:"email_id"`
+}
+
+// NewEmailSendTask creates an Asynq task to send an email.
+func NewEmailSendTask(emailID uint, opts ...asynq.Option) (*asynq.Task, error) {
+ payload, err := json.Marshal(EmailSendPayload{EmailID: emailID})
+ if err != nil {
+ return nil, err
+ }
+ return asynq.NewTask(TypeEmailSend, payload, opts...), nil
+}
diff --git a/logo.png b/logo.png
new file mode 100644
index 0000000..b2c1660
Binary files /dev/null and b/logo.png differ
diff --git a/web/.gitignore b/web/.gitignore
new file mode 100644
index 0000000..af45a21
--- /dev/null
+++ b/web/.gitignore
@@ -0,0 +1,5 @@
+node_modules
+dist
+.env
+.env.*
+!.env.example
diff --git a/web/README.md b/web/README.md
new file mode 100644
index 0000000..796b3de
--- /dev/null
+++ b/web/README.md
@@ -0,0 +1,56 @@
+# Posta Dashboard
+
+The admin dashboard for [Posta](https://github.com/jonasfroeller/posta), built with Vue 3, TypeScript, and Vite.
+
+## Setup
+
+```bash
+npm install
+npm run dev
+```
+
+The dev server runs on port 3000 and proxies `/api/v1` requests to the backend at `localhost:9000`.
+
+## Scripts
+
+| Command | Description |
+|---|---|
+| `npm run dev` | Start development server |
+| `npm run build` | Build for production |
+| `npm run preview` | Preview production build |
+
+## Tech Stack
+
+- **Vue 3** with `<script setup>` SFCs
+- **TypeScript**
+- **Vite** for bundling
+- **Pinia** for state management
+- **Vue Router** with auth guards
+- **Axios** for API requests
+
+## Project Structure
+
+```
+src/
+ api/ API client modules (one per feature)
+ components/ Reusable components (ConfirmDialog, Pagination)
+ composables/ Composition utilities
+ layouts/ Dashboard layout with sidebar navigation
+ router/ Route definitions and auth guards
+ stores/ Pinia stores (auth, notification, theme)
+ views/ Page components organized by feature
+```
+
+## Features
+
+- JWT authentication with 2FA support
+- Email management and delivery tracking
+- Template editor with versioning and localization
+- SMTP server configuration
+- Domain verification (SPF, DKIM, DMARC)
+- Contact and list management
+- API key management
+- Webhook configuration and delivery logs
+- Analytics dashboard
+- Admin panel (users, jobs, metrics, events)
+- Light/dark/system theme support
diff --git a/web/env.d.ts b/web/env.d.ts
new file mode 100644
index 0000000..1a76292
--- /dev/null
+++ b/web/env.d.ts
@@ -0,0 +1,15 @@
+/// <reference types="vite/client" />
+
+declare module '*.vue' {
+ import type { DefineComponent } from 'vue'
+ const component: DefineComponent<object, object, unknown>
+ export default component
+}
+
+interface ImportMetaEnv {
+ readonly VITE_API_URL: string
+}
+
+interface ImportMeta {
+ readonly env: ImportMetaEnv
+}
diff --git a/web/index.html b/web/index.html
new file mode 100644
index 0000000..9492466
--- /dev/null
+++ b/web/index.html
@@ -0,0 +1,21 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <meta name="theme-color" content="#9333ea" />
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
+ <link rel="icon" type="image/png" sizes="96x96" href="/favicon-96x96.png" />
+ <link rel="icon" type="image/x-icon" href="/favicon.ico" />
+ <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png" />
+ <link rel="manifest" href="/site.webmanifest" />
+ <link rel="preconnect" href="https://fonts.googleapis.com" />
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet" />
+ <title>Posta Relay — Self-hosted Email delivery platform</title>
+ </head>
+ <body>
+ <div id="app"></div>
+ <script type="module" src="/src/main.ts"></script>
+ </body>
+</html>
diff --git a/web/package-lock.json b/web/package-lock.json
new file mode 100644
index 0000000..8a56cab
--- /dev/null
+++ b/web/package-lock.json
@@ -0,0 +1,1893 @@
+{
+ "name": "dashboard",
+ "version": "0.0.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "dashboard",
+ "version": "0.0.0",
+ "dependencies": {
+ "@mdi/font": "^7.4.47",
+ "axios": "^1.13.6",
+ "pinia": "^3.0.4",
+ "vue": "^3.5.25",
+ "vue-router": "^4.6.4"
+ },
+ "devDependencies": {
+ "@tsconfig/node22": "^22.0.5",
+ "@vitejs/plugin-vue": "^6.0.2",
+ "typescript": "^5.9.3",
+ "vite": "^7.3.1",
+ "vue-tsc": "^3.2.5"
+ }
+ },
+ "node_modules/@babel/helper-string-parser": {
+ "version": "7.27.1",
+ "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz",
+ "integrity": "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-validator-identifier": {
+ "version": "7.28.5",
+ "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz",
+ "integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/parser": {
+ "version": "7.29.0",
+ "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.0.tgz",
+ "integrity": "sha512-IyDgFV5GeDUVX4YdF/3CPULtVGSXXMLh1xVIgdCgxApktqnQV0r7/8Nqthg+8YLGaAtdyIlo2qIdZrbCv4+7ww==",
+ "license": "MIT",
+ "dependencies": {
+ "@babel/types": "^7.29.0"
+ },
+ "bin": {
+ "parser": "bin/babel-parser.js"
+ },
+ "engines": {
+ "node": ">=6.0.0"
+ }
+ },
+ "node_modules/@babel/types": {
+ "version": "7.29.0",
+ "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.0.tgz",
+ "integrity": "sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==",
+ "license": "MIT",
+ "dependencies": {
+ "@babel/helper-string-parser": "^7.27.1",
+ "@babel/helper-validator-identifier": "^7.28.5"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@esbuild/aix-ppc64": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.3.tgz",
+ "integrity": "sha512-9fJMTNFTWZMh5qwrBItuziu834eOCUcEqymSH7pY+zoMVEZg3gcPuBNxH1EvfVYe9h0x/Ptw8KBzv7qxb7l8dg==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "aix"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-arm": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.3.tgz",
+ "integrity": "sha512-i5D1hPY7GIQmXlXhs2w8AWHhenb00+GxjxRncS2ZM7YNVGNfaMxgzSGuO8o8SJzRc/oZwU2bcScvVERk03QhzA==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-arm64": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.3.tgz",
+ "integrity": "sha512-YdghPYUmj/FX2SYKJ0OZxf+iaKgMsKHVPF1MAq/P8WirnSpCStzKJFjOjzsW0QQ7oIAiccHdcqjbHmJxRb/dmg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-x64": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.3.tgz",
+ "integrity": "sha512-IN/0BNTkHtk8lkOM8JWAYFg4ORxBkZQf9zXiEOfERX/CzxW3Vg1ewAhU7QSWQpVIzTW+b8Xy+lGzdYXV6UZObQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/darwin-arm64": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.3.tgz",
+ "integrity": "sha512-Re491k7ByTVRy0t3EKWajdLIr0gz2kKKfzafkth4Q8A5n1xTHrkqZgLLjFEHVD+AXdUGgQMq+Godfq45mGpCKg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/darwin-x64": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.3.tgz",
+ "integrity": "sha512-vHk/hA7/1AckjGzRqi6wbo+jaShzRowYip6rt6q7VYEDX4LEy1pZfDpdxCBnGtl+A5zq8iXDcyuxwtv3hNtHFg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/freebsd-arm64": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.3.tgz",
+ "integrity": "sha512-ipTYM2fjt3kQAYOvo6vcxJx3nBYAzPjgTCk7QEgZG8AUO3ydUhvelmhrbOheMnGOlaSFUoHXB6un+A7q4ygY9w==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/freebsd-x64": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.3.tgz",
+ "integrity": "sha512-dDk0X87T7mI6U3K9VjWtHOXqwAMJBNN2r7bejDsc+j03SEjtD9HrOl8gVFByeM0aJksoUuUVU9TBaZa2rgj0oA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-arm": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.3.tgz",
+ "integrity": "sha512-s6nPv2QkSupJwLYyfS+gwdirm0ukyTFNl3KTgZEAiJDd+iHZcbTPPcWCcRYH+WlNbwChgH2QkE9NSlNrMT8Gfw==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-arm64": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.3.tgz",
+ "integrity": "sha512-sZOuFz/xWnZ4KH3YfFrKCf1WyPZHakVzTiqji3WDc0BCl2kBwiJLCXpzLzUBLgmp4veFZdvN5ChW4Eq/8Fc2Fg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-ia32": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.3.tgz",
+ "integrity": "sha512-yGlQYjdxtLdh0a3jHjuwOrxQjOZYD/C9PfdbgJJF3TIZWnm/tMd/RcNiLngiu4iwcBAOezdnSLAwQDPqTmtTYg==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-loong64": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.3.tgz",
+ "integrity": "sha512-WO60Sn8ly3gtzhyjATDgieJNet/KqsDlX5nRC5Y3oTFcS1l0KWba+SEa9Ja1GfDqSF1z6hif/SkpQJbL63cgOA==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-mips64el": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.3.tgz",
+ "integrity": "sha512-APsymYA6sGcZ4pD6k+UxbDjOFSvPWyZhjaiPyl/f79xKxwTnrn5QUnXR5prvetuaSMsb4jgeHewIDCIWljrSxw==",
+ "cpu": [
+ "mips64el"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-ppc64": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.3.tgz",
+ "integrity": "sha512-eizBnTeBefojtDb9nSh4vvVQ3V9Qf9Df01PfawPcRzJH4gFSgrObw+LveUyDoKU3kxi5+9RJTCWlj4FjYXVPEA==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-riscv64": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.3.tgz",
+ "integrity": "sha512-3Emwh0r5wmfm3ssTWRQSyVhbOHvqegUDRd0WhmXKX2mkHJe1SFCMJhagUleMq+Uci34wLSipf8Lagt4LlpRFWQ==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-s390x": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.3.tgz",
+ "integrity": "sha512-pBHUx9LzXWBc7MFIEEL0yD/ZVtNgLytvx60gES28GcWMqil8ElCYR4kvbV2BDqsHOvVDRrOxGySBM9Fcv744hw==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-x64": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.3.tgz",
+ "integrity": "sha512-Czi8yzXUWIQYAtL/2y6vogER8pvcsOsk5cpwL4Gk5nJqH5UZiVByIY8Eorm5R13gq+DQKYg0+JyQoytLQas4dA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/netbsd-arm64": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.3.tgz",
+ "integrity": "sha512-sDpk0RgmTCR/5HguIZa9n9u+HVKf40fbEUt+iTzSnCaGvY9kFP0YKBWZtJaraonFnqef5SlJ8/TiPAxzyS+UoA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/netbsd-x64": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.3.tgz",
+ "integrity": "sha512-P14lFKJl/DdaE00LItAukUdZO5iqNH7+PjoBm+fLQjtxfcfFE20Xf5CrLsmZdq5LFFZzb5JMZ9grUwvtVYzjiA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openbsd-arm64": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.3.tgz",
+ "integrity": "sha512-AIcMP77AvirGbRl/UZFTq5hjXK+2wC7qFRGoHSDrZ5v5b8DK/GYpXW3CPRL53NkvDqb9D+alBiC/dV0Fb7eJcw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openbsd-x64": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.3.tgz",
+ "integrity": "sha512-DnW2sRrBzA+YnE70LKqnM3P+z8vehfJWHXECbwBmH/CU51z6FiqTQTHFenPlHmo3a8UgpLyH3PT+87OViOh1AQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openharmony-arm64": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.3.tgz",
+ "integrity": "sha512-NinAEgr/etERPTsZJ7aEZQvvg/A6IsZG/LgZy+81wON2huV7SrK3e63dU0XhyZP4RKGyTm7aOgmQk0bGp0fy2g==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/sunos-x64": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.3.tgz",
+ "integrity": "sha512-PanZ+nEz+eWoBJ8/f8HKxTTD172SKwdXebZ0ndd953gt1HRBbhMsaNqjTyYLGLPdoWHy4zLU7bDVJztF5f3BHA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "sunos"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-arm64": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.3.tgz",
+ "integrity": "sha512-B2t59lWWYrbRDw/tjiWOuzSsFh1Y/E95ofKz7rIVYSQkUYBjfSgf6oeYPNWHToFRr2zx52JKApIcAS/D5TUBnA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-ia32": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.3.tgz",
+ "integrity": "sha512-QLKSFeXNS8+tHW7tZpMtjlNb7HKau0QDpwm49u0vUp9y1WOF+PEzkU84y9GqYaAVW8aH8f3GcBck26jh54cX4Q==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-x64": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.3.tgz",
+ "integrity": "sha512-4uJGhsxuptu3OcpVAzli+/gWusVGwZZHTlS63hh++ehExkVT8SgiEf7/uC/PclrPPkLhZqGgCTjd0VWLo6xMqA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@jridgewell/sourcemap-codec": {
+ "version": "1.5.5",
+ "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",
+ "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==",
+ "license": "MIT"
+ },
+ "node_modules/@mdi/font": {
+ "version": "7.4.47",
+ "resolved": "https://registry.npmjs.org/@mdi/font/-/font-7.4.47.tgz",
+ "integrity": "sha512-43MtGpd585SNzHZPcYowu/84Vz2a2g31TvPMTm9uTiCSWzaheQySUcSyUH/46fPnuPQWof2yd0pGBtzee/IQWw==",
+ "license": "Apache-2.0"
+ },
+ "node_modules/@rolldown/pluginutils": {
+ "version": "1.0.0-rc.2",
+ "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-rc.2.tgz",
+ "integrity": "sha512-izyXV/v+cHiRfozX62W9htOAvwMo4/bXKDrQ+vom1L1qRuexPock/7VZDAhnpHCLNejd3NJ6hiab+tO0D44Rgw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@rollup/rollup-android-arm-eabi": {
+ "version": "4.59.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.59.0.tgz",
+ "integrity": "sha512-upnNBkA6ZH2VKGcBj9Fyl9IGNPULcjXRlg0LLeaioQWueH30p6IXtJEbKAgvyv+mJaMxSm1l6xwDXYjpEMiLMg==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ]
+ },
+ "node_modules/@rollup/rollup-android-arm64": {
+ "version": "4.59.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.59.0.tgz",
+ "integrity": "sha512-hZ+Zxj3SySm4A/DylsDKZAeVg0mvi++0PYVceVyX7hemkw7OreKdCvW2oQ3T1FMZvCaQXqOTHb8qmBShoqk69Q==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ]
+ },
+ "node_modules/@rollup/rollup-darwin-arm64": {
+ "version": "4.59.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.59.0.tgz",
+ "integrity": "sha512-W2Psnbh1J8ZJw0xKAd8zdNgF9HRLkdWwwdWqubSVk0pUuQkoHnv7rx4GiF9rT4t5DIZGAsConRE3AxCdJ4m8rg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ]
+ },
+ "node_modules/@rollup/rollup-darwin-x64": {
+ "version": "4.59.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.59.0.tgz",
+ "integrity": "sha512-ZW2KkwlS4lwTv7ZVsYDiARfFCnSGhzYPdiOU4IM2fDbL+QGlyAbjgSFuqNRbSthybLbIJ915UtZBtmuLrQAT/w==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ]
+ },
+ "node_modules/@rollup/rollup-freebsd-arm64": {
+ "version": "4.59.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.59.0.tgz",
+ "integrity": "sha512-EsKaJ5ytAu9jI3lonzn3BgG8iRBjV4LxZexygcQbpiU0wU0ATxhNVEpXKfUa0pS05gTcSDMKpn3Sx+QB9RlTTA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ]
+ },
+ "node_modules/@rollup/rollup-freebsd-x64": {
+ "version": "4.59.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.59.0.tgz",
+ "integrity": "sha512-d3DuZi2KzTMjImrxoHIAODUZYoUUMsuUiY4SRRcJy6NJoZ6iIqWnJu9IScV9jXysyGMVuW+KNzZvBLOcpdl3Vg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-arm-gnueabihf": {
+ "version": "4.59.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.59.0.tgz",
+ "integrity": "sha512-t4ONHboXi/3E0rT6OZl1pKbl2Vgxf9vJfWgmUoCEVQVxhW6Cw/c8I6hbbu7DAvgp82RKiH7TpLwxnJeKv2pbsw==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-arm-musleabihf": {
+ "version": "4.59.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.59.0.tgz",
+ "integrity": "sha512-CikFT7aYPA2ufMD086cVORBYGHffBo4K8MQ4uPS/ZnY54GKj36i196u8U+aDVT2LX4eSMbyHtyOh7D7Zvk2VvA==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-arm64-gnu": {
+ "version": "4.59.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.59.0.tgz",
+ "integrity": "sha512-jYgUGk5aLd1nUb1CtQ8E+t5JhLc9x5WdBKew9ZgAXg7DBk0ZHErLHdXM24rfX+bKrFe+Xp5YuJo54I5HFjGDAA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-arm64-musl": {
+ "version": "4.59.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.59.0.tgz",
+ "integrity": "sha512-peZRVEdnFWZ5Bh2KeumKG9ty7aCXzzEsHShOZEFiCQlDEepP1dpUl/SrUNXNg13UmZl+gzVDPsiCwnV1uI0RUA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-loong64-gnu": {
+ "version": "4.59.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.59.0.tgz",
+ "integrity": "sha512-gbUSW/97f7+r4gHy3Jlup8zDG190AuodsWnNiXErp9mT90iCy9NKKU0Xwx5k8VlRAIV2uU9CsMnEFg/xXaOfXg==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-loong64-musl": {
+ "version": "4.59.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.59.0.tgz",
+ "integrity": "sha512-yTRONe79E+o0FWFijasoTjtzG9EBedFXJMl888NBEDCDV9I2wGbFFfJQQe63OijbFCUZqxpHz1GzpbtSFikJ4Q==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-ppc64-gnu": {
+ "version": "4.59.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.59.0.tgz",
+ "integrity": "sha512-sw1o3tfyk12k3OEpRddF68a1unZ5VCN7zoTNtSn2KndUE+ea3m3ROOKRCZxEpmT9nsGnogpFP9x6mnLTCaoLkA==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-ppc64-musl": {
+ "version": "4.59.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.59.0.tgz",
+ "integrity": "sha512-+2kLtQ4xT3AiIxkzFVFXfsmlZiG5FXYW7ZyIIvGA7Bdeuh9Z0aN4hVyXS/G1E9bTP/vqszNIN/pUKCk/BTHsKA==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-riscv64-gnu": {
+ "version": "4.59.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.59.0.tgz",
+ "integrity": "sha512-NDYMpsXYJJaj+I7UdwIuHHNxXZ/b/N2hR15NyH3m2qAtb/hHPA4g4SuuvrdxetTdndfj9b1WOmy73kcPRoERUg==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-riscv64-musl": {
+ "version": "4.59.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.59.0.tgz",
+ "integrity": "sha512-nLckB8WOqHIf1bhymk+oHxvM9D3tyPndZH8i8+35p/1YiVoVswPid2yLzgX7ZJP0KQvnkhM4H6QZ5m0LzbyIAg==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-s390x-gnu": {
+ "version": "4.59.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.59.0.tgz",
+ "integrity": "sha512-oF87Ie3uAIvORFBpwnCvUzdeYUqi2wY6jRFWJAy1qus/udHFYIkplYRW+wo+GRUP4sKzYdmE1Y3+rY5Gc4ZO+w==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-x64-gnu": {
+ "version": "4.59.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.59.0.tgz",
+ "integrity": "sha512-3AHmtQq/ppNuUspKAlvA8HtLybkDflkMuLK4DPo77DfthRb71V84/c4MlWJXixZz4uruIH4uaa07IqoAkG64fg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-x64-musl": {
+ "version": "4.59.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.59.0.tgz",
+ "integrity": "sha512-2UdiwS/9cTAx7qIUZB/fWtToJwvt0Vbo0zmnYt7ED35KPg13Q0ym1g442THLC7VyI6JfYTP4PiSOWyoMdV2/xg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-openbsd-x64": {
+ "version": "4.59.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.59.0.tgz",
+ "integrity": "sha512-M3bLRAVk6GOwFlPTIxVBSYKUaqfLrn8l0psKinkCFxl4lQvOSz8ZrKDz2gxcBwHFpci0B6rttydI4IpS4IS/jQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ]
+ },
+ "node_modules/@rollup/rollup-openharmony-arm64": {
+ "version": "4.59.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.59.0.tgz",
+ "integrity": "sha512-tt9KBJqaqp5i5HUZzoafHZX8b5Q2Fe7UjYERADll83O4fGqJ49O1FsL6LpdzVFQcpwvnyd0i+K/VSwu/o/nWlA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ]
+ },
+ "node_modules/@rollup/rollup-win32-arm64-msvc": {
+ "version": "4.59.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.59.0.tgz",
+ "integrity": "sha512-V5B6mG7OrGTwnxaNUzZTDTjDS7F75PO1ae6MJYdiMu60sq0CqN5CVeVsbhPxalupvTX8gXVSU9gq+Rx1/hvu6A==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
+ "node_modules/@rollup/rollup-win32-ia32-msvc": {
+ "version": "4.59.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.59.0.tgz",
+ "integrity": "sha512-UKFMHPuM9R0iBegwzKF4y0C4J9u8C6MEJgFuXTBerMk7EJ92GFVFYBfOZaSGLu6COf7FxpQNqhNS4c4icUPqxA==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
+ "node_modules/@rollup/rollup-win32-x64-gnu": {
+ "version": "4.59.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.59.0.tgz",
+ "integrity": "sha512-laBkYlSS1n2L8fSo1thDNGrCTQMmxjYY5G0WFWjFFYZkKPjsMBsgJfGf4TLxXrF6RyhI60L8TMOjBMvXiTcxeA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
+ "node_modules/@rollup/rollup-win32-x64-msvc": {
+ "version": "4.59.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.59.0.tgz",
+ "integrity": "sha512-2HRCml6OztYXyJXAvdDXPKcawukWY2GpR5/nxKp4iBgiO3wcoEGkAaqctIbZcNB6KlUQBIqt8VYkNSj2397EfA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
+ "node_modules/@tsconfig/node22": {
+ "version": "22.0.5",
+ "resolved": "https://registry.npmjs.org/@tsconfig/node22/-/node22-22.0.5.tgz",
+ "integrity": "sha512-hLf2ld+sYN/BtOJjHUWOk568dvjFQkHnLNa6zce25GIH+vxKfvTgm3qpaH6ToF5tu/NN0IH66s+Bb5wElHrLcw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/estree": {
+ "version": "1.0.8",
+ "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz",
+ "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@vitejs/plugin-vue": {
+ "version": "6.0.4",
+ "resolved": "https://registry.npmjs.org/@vitejs/plugin-vue/-/plugin-vue-6.0.4.tgz",
+ "integrity": "sha512-uM5iXipgYIn13UUQCZNdWkYk+sysBeA97d5mHsAoAt1u/wpN3+zxOmsVJWosuzX+IMGRzeYUNytztrYznboIkQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@rolldown/pluginutils": "1.0.0-rc.2"
+ },
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ },
+ "peerDependencies": {
+ "vite": "^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0",
+ "vue": "^3.2.25"
+ }
+ },
+ "node_modules/@volar/language-core": {
+ "version": "2.4.28",
+ "resolved": "https://registry.npmjs.org/@volar/language-core/-/language-core-2.4.28.tgz",
+ "integrity": "sha512-w4qhIJ8ZSitgLAkVay6AbcnC7gP3glYM3fYwKV3srj8m494E3xtrCv6E+bWviiK/8hs6e6t1ij1s2Endql7vzQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@volar/source-map": "2.4.28"
+ }
+ },
+ "node_modules/@volar/source-map": {
+ "version": "2.4.28",
+ "resolved": "https://registry.npmjs.org/@volar/source-map/-/source-map-2.4.28.tgz",
+ "integrity": "sha512-yX2BDBqJkRXfKw8my8VarTyjv48QwxdJtvRgUpNE5erCsgEUdI2DsLbpa+rOQVAJYshY99szEcRDmyHbF10ggQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@volar/typescript": {
+ "version": "2.4.28",
+ "resolved": "https://registry.npmjs.org/@volar/typescript/-/typescript-2.4.28.tgz",
+ "integrity": "sha512-Ja6yvWrbis2QtN4ClAKreeUZPVYMARDYZl9LMEv1iQ1QdepB6wn0jTRxA9MftYmYa4DQ4k/DaSZpFPUfxl8giw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@volar/language-core": "2.4.28",
+ "path-browserify": "^1.0.1",
+ "vscode-uri": "^3.0.8"
+ }
+ },
+ "node_modules/@vue/compiler-core": {
+ "version": "3.5.30",
+ "resolved": "https://registry.npmjs.org/@vue/compiler-core/-/compiler-core-3.5.30.tgz",
+ "integrity": "sha512-s3DfdZkcu/qExZ+td75015ljzHc6vE+30cFMGRPROYjqkroYI5NV2X1yAMX9UeyBNWB9MxCfPcsjpLS11nzkkw==",
+ "license": "MIT",
+ "dependencies": {
+ "@babel/parser": "^7.29.0",
+ "@vue/shared": "3.5.30",
+ "entities": "^7.0.1",
+ "estree-walker": "^2.0.2",
+ "source-map-js": "^1.2.1"
+ }
+ },
+ "node_modules/@vue/compiler-dom": {
+ "version": "3.5.30",
+ "resolved": "https://registry.npmjs.org/@vue/compiler-dom/-/compiler-dom-3.5.30.tgz",
+ "integrity": "sha512-eCFYESUEVYHhiMuK4SQTldO3RYxyMR/UQL4KdGD1Yrkfdx4m/HYuZ9jSfPdA+nWJY34VWndiYdW/wZXyiPEB9g==",
+ "license": "MIT",
+ "dependencies": {
+ "@vue/compiler-core": "3.5.30",
+ "@vue/shared": "3.5.30"
+ }
+ },
+ "node_modules/@vue/compiler-sfc": {
+ "version": "3.5.30",
+ "resolved": "https://registry.npmjs.org/@vue/compiler-sfc/-/compiler-sfc-3.5.30.tgz",
+ "integrity": "sha512-LqmFPDn89dtU9vI3wHJnwaV6GfTRD87AjWpTWpyrdVOObVtjIuSeZr181z5C4PmVx/V3j2p+0f7edFKGRMpQ5A==",
+ "license": "MIT",
+ "dependencies": {
+ "@babel/parser": "^7.29.0",
+ "@vue/compiler-core": "3.5.30",
+ "@vue/compiler-dom": "3.5.30",
+ "@vue/compiler-ssr": "3.5.30",
+ "@vue/shared": "3.5.30",
+ "estree-walker": "^2.0.2",
+ "magic-string": "^0.30.21",
+ "postcss": "^8.5.8",
+ "source-map-js": "^1.2.1"
+ }
+ },
+ "node_modules/@vue/compiler-ssr": {
+ "version": "3.5.30",
+ "resolved": "https://registry.npmjs.org/@vue/compiler-ssr/-/compiler-ssr-3.5.30.tgz",
+ "integrity": "sha512-NsYK6OMTnx109PSL2IAyf62JP6EUdk4Dmj6AkWcJGBvN0dQoMYtVekAmdqgTtWQgEJo+Okstbf/1p7qZr5H+bA==",
+ "license": "MIT",
+ "dependencies": {
+ "@vue/compiler-dom": "3.5.30",
+ "@vue/shared": "3.5.30"
+ }
+ },
+ "node_modules/@vue/devtools-api": {
+ "version": "7.7.9",
+ "resolved": "https://registry.npmjs.org/@vue/devtools-api/-/devtools-api-7.7.9.tgz",
+ "integrity": "sha512-kIE8wvwlcZ6TJTbNeU2HQNtaxLx3a84aotTITUuL/4bzfPxzajGBOoqjMhwZJ8L9qFYDU/lAYMEEm11dnZOD6g==",
+ "license": "MIT",
+ "dependencies": {
+ "@vue/devtools-kit": "^7.7.9"
+ }
+ },
+ "node_modules/@vue/devtools-kit": {
+ "version": "7.7.9",
+ "resolved": "https://registry.npmjs.org/@vue/devtools-kit/-/devtools-kit-7.7.9.tgz",
+ "integrity": "sha512-PyQ6odHSgiDVd4hnTP+aDk2X4gl2HmLDfiyEnn3/oV+ckFDuswRs4IbBT7vacMuGdwY/XemxBoh302ctbsptuA==",
+ "license": "MIT",
+ "dependencies": {
+ "@vue/devtools-shared": "^7.7.9",
+ "birpc": "^2.3.0",
+ "hookable": "^5.5.3",
+ "mitt": "^3.0.1",
+ "perfect-debounce": "^1.0.0",
+ "speakingurl": "^14.0.1",
+ "superjson": "^2.2.2"
+ }
+ },
+ "node_modules/@vue/devtools-shared": {
+ "version": "7.7.9",
+ "resolved": "https://registry.npmjs.org/@vue/devtools-shared/-/devtools-shared-7.7.9.tgz",
+ "integrity": "sha512-iWAb0v2WYf0QWmxCGy0seZNDPdO3Sp5+u78ORnyeonS6MT4PC7VPrryX2BpMJrwlDeaZ6BD4vP4XKjK0SZqaeA==",
+ "license": "MIT",
+ "dependencies": {
+ "rfdc": "^1.4.1"
+ }
+ },
+ "node_modules/@vue/language-core": {
+ "version": "3.2.5",
+ "resolved": "https://registry.npmjs.org/@vue/language-core/-/language-core-3.2.5.tgz",
+ "integrity": "sha512-d3OIxN/+KRedeM5wQ6H6NIpwS3P5gC9nmyaHgBk+rO6dIsjY+tOh4UlPpiZbAh3YtLdCGEX4M16RmsBqPmJV+g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@volar/language-core": "2.4.28",
+ "@vue/compiler-dom": "^3.5.0",
+ "@vue/shared": "^3.5.0",
+ "alien-signals": "^3.0.0",
+ "muggle-string": "^0.4.1",
+ "path-browserify": "^1.0.1",
+ "picomatch": "^4.0.2"
+ }
+ },
+ "node_modules/@vue/reactivity": {
+ "version": "3.5.30",
+ "resolved": "https://registry.npmjs.org/@vue/reactivity/-/reactivity-3.5.30.tgz",
+ "integrity": "sha512-179YNgKATuwj9gB+66snskRDOitDiuOZqkYia7mHKJaidOMo/WJxHKF8DuGc4V4XbYTJANlfEKb0yxTQotnx4Q==",
+ "license": "MIT",
+ "dependencies": {
+ "@vue/shared": "3.5.30"
+ }
+ },
+ "node_modules/@vue/runtime-core": {
+ "version": "3.5.30",
+ "resolved": "https://registry.npmjs.org/@vue/runtime-core/-/runtime-core-3.5.30.tgz",
+ "integrity": "sha512-e0Z+8PQsUTdwV8TtEsLzUM7SzC7lQwYKePydb7K2ZnmS6jjND+WJXkmmfh/swYzRyfP1EY3fpdesyYoymCzYfg==",
+ "license": "MIT",
+ "dependencies": {
+ "@vue/reactivity": "3.5.30",
+ "@vue/shared": "3.5.30"
+ }
+ },
+ "node_modules/@vue/runtime-dom": {
+ "version": "3.5.30",
+ "resolved": "https://registry.npmjs.org/@vue/runtime-dom/-/runtime-dom-3.5.30.tgz",
+ "integrity": "sha512-2UIGakjU4WSQ0T4iwDEW0W7vQj6n7AFn7taqZ9Cvm0Q/RA2FFOziLESrDL4GmtI1wV3jXg5nMoJSYO66egDUBw==",
+ "license": "MIT",
+ "dependencies": {
+ "@vue/reactivity": "3.5.30",
+ "@vue/runtime-core": "3.5.30",
+ "@vue/shared": "3.5.30",
+ "csstype": "^3.2.3"
+ }
+ },
+ "node_modules/@vue/server-renderer": {
+ "version": "3.5.30",
+ "resolved": "https://registry.npmjs.org/@vue/server-renderer/-/server-renderer-3.5.30.tgz",
+ "integrity": "sha512-v+R34icapydRwbZRD0sXwtHqrQJv38JuMB4JxbOxd8NEpGLny7cncMp53W9UH/zo4j8eDHjQ1dEJXwzFQknjtQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@vue/compiler-ssr": "3.5.30",
+ "@vue/shared": "3.5.30"
+ },
+ "peerDependencies": {
+ "vue": "3.5.30"
+ }
+ },
+ "node_modules/@vue/shared": {
+ "version": "3.5.30",
+ "resolved": "https://registry.npmjs.org/@vue/shared/-/shared-3.5.30.tgz",
+ "integrity": "sha512-YXgQ7JjaO18NeK2K9VTbDHaFy62WrObMa6XERNfNOkAhD1F1oDSf3ZJ7K6GqabZ0BvSDHajp8qfS5Sa2I9n8uQ==",
+ "license": "MIT"
+ },
+ "node_modules/alien-signals": {
+ "version": "3.1.2",
+ "resolved": "https://registry.npmjs.org/alien-signals/-/alien-signals-3.1.2.tgz",
+ "integrity": "sha512-d9dYqZTS90WLiU0I5c6DHj/HcKkF8ZyGN3G5x8wSbslulz70KOxaqCT0hQCo9KOyhVqzqGojvNdJXoTumZOtcw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/asynckit": {
+ "version": "0.4.0",
+ "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
+ "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==",
+ "license": "MIT"
+ },
+ "node_modules/axios": {
+ "version": "1.13.6",
+ "resolved": "https://registry.npmjs.org/axios/-/axios-1.13.6.tgz",
+ "integrity": "sha512-ChTCHMouEe2kn713WHbQGcuYrr6fXTBiu460OTwWrWob16g1bXn4vtz07Ope7ewMozJAnEquLk5lWQWtBig9DQ==",
+ "license": "MIT",
+ "dependencies": {
+ "follow-redirects": "^1.15.11",
+ "form-data": "^4.0.5",
+ "proxy-from-env": "^1.1.0"
+ }
+ },
+ "node_modules/birpc": {
+ "version": "2.9.0",
+ "resolved": "https://registry.npmjs.org/birpc/-/birpc-2.9.0.tgz",
+ "integrity": "sha512-KrayHS5pBi69Xi9JmvoqrIgYGDkD6mcSe/i6YKi3w5kekCLzrX4+nawcXqrj2tIp50Kw/mT/s3p+GVK0A0sKxw==",
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/antfu"
+ }
+ },
+ "node_modules/call-bind-apply-helpers": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
+ "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0",
+ "function-bind": "^1.1.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/combined-stream": {
+ "version": "1.0.8",
+ "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
+ "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
+ "license": "MIT",
+ "dependencies": {
+ "delayed-stream": "~1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/copy-anything": {
+ "version": "4.0.5",
+ "resolved": "https://registry.npmjs.org/copy-anything/-/copy-anything-4.0.5.tgz",
+ "integrity": "sha512-7Vv6asjS4gMOuILabD3l739tsaxFQmC+a7pLZm02zyvs8p977bL3zEgq3yDk5rn9B0PbYgIv++jmHcuUab4RhA==",
+ "license": "MIT",
+ "dependencies": {
+ "is-what": "^5.2.0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/mesqueeb"
+ }
+ },
+ "node_modules/csstype": {
+ "version": "3.2.3",
+ "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
+ "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
+ "license": "MIT"
+ },
+ "node_modules/delayed-stream": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
+ "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.4.0"
+ }
+ },
+ "node_modules/dunder-proto": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
+ "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
+ "license": "MIT",
+ "dependencies": {
+ "call-bind-apply-helpers": "^1.0.1",
+ "es-errors": "^1.3.0",
+ "gopd": "^1.2.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/entities": {
+ "version": "7.0.1",
+ "resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz",
+ "integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==",
+ "license": "BSD-2-Clause",
+ "engines": {
+ "node": ">=0.12"
+ },
+ "funding": {
+ "url": "https://github.com/fb55/entities?sponsor=1"
+ }
+ },
+ "node_modules/es-define-property": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
+ "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/es-errors": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
+ "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/es-object-atoms": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz",
+ "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==",
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/es-set-tostringtag": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz",
+ "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==",
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0",
+ "get-intrinsic": "^1.2.6",
+ "has-tostringtag": "^1.0.2",
+ "hasown": "^2.0.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/esbuild": {
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.3.tgz",
+ "integrity": "sha512-8VwMnyGCONIs6cWue2IdpHxHnAjzxnw2Zr7MkVxB2vjmQ2ivqGFb4LEG3SMnv0Gb2F/G/2yA8zUaiL1gywDCCg==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "bin": {
+ "esbuild": "bin/esbuild"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "optionalDependencies": {
+ "@esbuild/aix-ppc64": "0.27.3",
+ "@esbuild/android-arm": "0.27.3",
+ "@esbuild/android-arm64": "0.27.3",
+ "@esbuild/android-x64": "0.27.3",
+ "@esbuild/darwin-arm64": "0.27.3",
+ "@esbuild/darwin-x64": "0.27.3",
+ "@esbuild/freebsd-arm64": "0.27.3",
+ "@esbuild/freebsd-x64": "0.27.3",
+ "@esbuild/linux-arm": "0.27.3",
+ "@esbuild/linux-arm64": "0.27.3",
+ "@esbuild/linux-ia32": "0.27.3",
+ "@esbuild/linux-loong64": "0.27.3",
+ "@esbuild/linux-mips64el": "0.27.3",
+ "@esbuild/linux-ppc64": "0.27.3",
+ "@esbuild/linux-riscv64": "0.27.3",
+ "@esbuild/linux-s390x": "0.27.3",
+ "@esbuild/linux-x64": "0.27.3",
+ "@esbuild/netbsd-arm64": "0.27.3",
+ "@esbuild/netbsd-x64": "0.27.3",
+ "@esbuild/openbsd-arm64": "0.27.3",
+ "@esbuild/openbsd-x64": "0.27.3",
+ "@esbuild/openharmony-arm64": "0.27.3",
+ "@esbuild/sunos-x64": "0.27.3",
+ "@esbuild/win32-arm64": "0.27.3",
+ "@esbuild/win32-ia32": "0.27.3",
+ "@esbuild/win32-x64": "0.27.3"
+ }
+ },
+ "node_modules/estree-walker": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz",
+ "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==",
+ "license": "MIT"
+ },
+ "node_modules/fdir": {
+ "version": "6.5.0",
+ "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
+ "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12.0.0"
+ },
+ "peerDependencies": {
+ "picomatch": "^3 || ^4"
+ },
+ "peerDependenciesMeta": {
+ "picomatch": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/follow-redirects": {
+ "version": "1.15.11",
+ "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.11.tgz",
+ "integrity": "sha512-deG2P0JfjrTxl50XGCDyfI97ZGVCxIpfKYmfyrQ54n5FO/0gfIES8C/Psl6kWVDolizcaaxZJnTS0QSMxvnsBQ==",
+ "funding": [
+ {
+ "type": "individual",
+ "url": "https://github.com/sponsors/RubenVerborgh"
+ }
+ ],
+ "license": "MIT",
+ "engines": {
+ "node": ">=4.0"
+ },
+ "peerDependenciesMeta": {
+ "debug": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/form-data": {
+ "version": "4.0.5",
+ "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.5.tgz",
+ "integrity": "sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w==",
+ "license": "MIT",
+ "dependencies": {
+ "asynckit": "^0.4.0",
+ "combined-stream": "^1.0.8",
+ "es-set-tostringtag": "^2.1.0",
+ "hasown": "^2.0.2",
+ "mime-types": "^2.1.12"
+ },
+ "engines": {
+ "node": ">= 6"
+ }
+ },
+ "node_modules/fsevents": {
+ "version": "2.3.3",
+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
+ }
+ },
+ "node_modules/function-bind": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
+ "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/get-intrinsic": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
+ "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
+ "license": "MIT",
+ "dependencies": {
+ "call-bind-apply-helpers": "^1.0.2",
+ "es-define-property": "^1.0.1",
+ "es-errors": "^1.3.0",
+ "es-object-atoms": "^1.1.1",
+ "function-bind": "^1.1.2",
+ "get-proto": "^1.0.1",
+ "gopd": "^1.2.0",
+ "has-symbols": "^1.1.0",
+ "hasown": "^2.0.2",
+ "math-intrinsics": "^1.1.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/get-proto": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",
+ "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
+ "license": "MIT",
+ "dependencies": {
+ "dunder-proto": "^1.0.1",
+ "es-object-atoms": "^1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/gopd": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
+ "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/has-symbols": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",
+ "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/has-tostringtag": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz",
+ "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==",
+ "license": "MIT",
+ "dependencies": {
+ "has-symbols": "^1.0.3"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/hasown": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz",
+ "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==",
+ "license": "MIT",
+ "dependencies": {
+ "function-bind": "^1.1.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/hookable": {
+ "version": "5.5.3",
+ "resolved": "https://registry.npmjs.org/hookable/-/hookable-5.5.3.tgz",
+ "integrity": "sha512-Yc+BQe8SvoXH1643Qez1zqLRmbA5rCL+sSmk6TVos0LWVfNIB7PGncdlId77WzLGSIB5KaWgTaNTs2lNVEI6VQ==",
+ "license": "MIT"
+ },
+ "node_modules/is-what": {
+ "version": "5.5.0",
+ "resolved": "https://registry.npmjs.org/is-what/-/is-what-5.5.0.tgz",
+ "integrity": "sha512-oG7cgbmg5kLYae2N5IVd3jm2s+vldjxJzK1pcu9LfpGuQ93MQSzo0okvRna+7y5ifrD+20FE8FvjusyGaz14fw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/mesqueeb"
+ }
+ },
+ "node_modules/magic-string": {
+ "version": "0.30.21",
+ "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",
+ "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/sourcemap-codec": "^1.5.5"
+ }
+ },
+ "node_modules/math-intrinsics": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
+ "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/mime-db": {
+ "version": "1.52.0",
+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
+ "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/mime-types": {
+ "version": "2.1.35",
+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
+ "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
+ "license": "MIT",
+ "dependencies": {
+ "mime-db": "1.52.0"
+ },
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/mitt": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/mitt/-/mitt-3.0.1.tgz",
+ "integrity": "sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==",
+ "license": "MIT"
+ },
+ "node_modules/muggle-string": {
+ "version": "0.4.1",
+ "resolved": "https://registry.npmjs.org/muggle-string/-/muggle-string-0.4.1.tgz",
+ "integrity": "sha512-VNTrAak/KhO2i8dqqnqnAHOa3cYBwXEZe9h+D5h/1ZqFSTEFHdM65lR7RoIqq3tBBYavsOXV84NoHXZ0AkPyqQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/nanoid": {
+ "version": "3.3.11",
+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz",
+ "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "bin": {
+ "nanoid": "bin/nanoid.cjs"
+ },
+ "engines": {
+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
+ }
+ },
+ "node_modules/path-browserify": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/path-browserify/-/path-browserify-1.0.1.tgz",
+ "integrity": "sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/perfect-debounce": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/perfect-debounce/-/perfect-debounce-1.0.0.tgz",
+ "integrity": "sha512-xCy9V055GLEqoFaHoC1SoLIaLmWctgCUaBaWxDZ7/Zx4CTyX7cJQLJOok/orfjZAh9kEYpjJa4d0KcJmCbctZA==",
+ "license": "MIT"
+ },
+ "node_modules/picocolors": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
+ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
+ "license": "ISC"
+ },
+ "node_modules/picomatch": {
+ "version": "4.0.3",
+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz",
+ "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/jonschlinkert"
+ }
+ },
+ "node_modules/pinia": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/pinia/-/pinia-3.0.4.tgz",
+ "integrity": "sha512-l7pqLUFTI/+ESXn6k3nu30ZIzW5E2WZF/LaHJEpoq6ElcLD+wduZoB2kBN19du6K/4FDpPMazY2wJr+IndBtQw==",
+ "license": "MIT",
+ "dependencies": {
+ "@vue/devtools-api": "^7.7.7"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/posva"
+ },
+ "peerDependencies": {
+ "typescript": ">=4.5.0",
+ "vue": "^3.5.11"
+ },
+ "peerDependenciesMeta": {
+ "typescript": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/postcss": {
+ "version": "8.5.8",
+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.8.tgz",
+ "integrity": "sha512-OW/rX8O/jXnm82Ey1k44pObPtdblfiuWnrd8X7GJ7emImCOstunGbXUpp7HdBrFQX6rJzn3sPT397Wp5aCwCHg==",
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/postcss/"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/postcss"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "nanoid": "^3.3.11",
+ "picocolors": "^1.1.1",
+ "source-map-js": "^1.2.1"
+ },
+ "engines": {
+ "node": "^10 || ^12 || >=14"
+ }
+ },
+ "node_modules/proxy-from-env": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz",
+ "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==",
+ "license": "MIT"
+ },
+ "node_modules/rfdc": {
+ "version": "1.4.1",
+ "resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.4.1.tgz",
+ "integrity": "sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==",
+ "license": "MIT"
+ },
+ "node_modules/rollup": {
+ "version": "4.59.0",
+ "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.59.0.tgz",
+ "integrity": "sha512-2oMpl67a3zCH9H79LeMcbDhXW/UmWG/y2zuqnF2jQq5uq9TbM9TVyXvA4+t+ne2IIkBdrLpAaRQAvo7YI/Yyeg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree": "1.0.8"
+ },
+ "bin": {
+ "rollup": "dist/bin/rollup"
+ },
+ "engines": {
+ "node": ">=18.0.0",
+ "npm": ">=8.0.0"
+ },
+ "optionalDependencies": {
+ "@rollup/rollup-android-arm-eabi": "4.59.0",
+ "@rollup/rollup-android-arm64": "4.59.0",
+ "@rollup/rollup-darwin-arm64": "4.59.0",
+ "@rollup/rollup-darwin-x64": "4.59.0",
+ "@rollup/rollup-freebsd-arm64": "4.59.0",
+ "@rollup/rollup-freebsd-x64": "4.59.0",
+ "@rollup/rollup-linux-arm-gnueabihf": "4.59.0",
+ "@rollup/rollup-linux-arm-musleabihf": "4.59.0",
+ "@rollup/rollup-linux-arm64-gnu": "4.59.0",
+ "@rollup/rollup-linux-arm64-musl": "4.59.0",
+ "@rollup/rollup-linux-loong64-gnu": "4.59.0",
+ "@rollup/rollup-linux-loong64-musl": "4.59.0",
+ "@rollup/rollup-linux-ppc64-gnu": "4.59.0",
+ "@rollup/rollup-linux-ppc64-musl": "4.59.0",
+ "@rollup/rollup-linux-riscv64-gnu": "4.59.0",
+ "@rollup/rollup-linux-riscv64-musl": "4.59.0",
+ "@rollup/rollup-linux-s390x-gnu": "4.59.0",
+ "@rollup/rollup-linux-x64-gnu": "4.59.0",
+ "@rollup/rollup-linux-x64-musl": "4.59.0",
+ "@rollup/rollup-openbsd-x64": "4.59.0",
+ "@rollup/rollup-openharmony-arm64": "4.59.0",
+ "@rollup/rollup-win32-arm64-msvc": "4.59.0",
+ "@rollup/rollup-win32-ia32-msvc": "4.59.0",
+ "@rollup/rollup-win32-x64-gnu": "4.59.0",
+ "@rollup/rollup-win32-x64-msvc": "4.59.0",
+ "fsevents": "~2.3.2"
+ }
+ },
+ "node_modules/source-map-js": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
+ "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/speakingurl": {
+ "version": "14.0.1",
+ "resolved": "https://registry.npmjs.org/speakingurl/-/speakingurl-14.0.1.tgz",
+ "integrity": "sha512-1POYv7uv2gXoyGFpBCmpDVSNV74IfsWlDW216UPjbWufNf+bSU6GdbDsxdcxtfwb4xlI3yxzOTKClUosxARYrQ==",
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/superjson": {
+ "version": "2.2.6",
+ "resolved": "https://registry.npmjs.org/superjson/-/superjson-2.2.6.tgz",
+ "integrity": "sha512-H+ue8Zo4vJmV2nRjpx86P35lzwDT3nItnIsocgumgr0hHMQ+ZGq5vrERg9kJBo5AWGmxZDhzDo+WVIJqkB0cGA==",
+ "license": "MIT",
+ "dependencies": {
+ "copy-anything": "^4"
+ },
+ "engines": {
+ "node": ">=16"
+ }
+ },
+ "node_modules/tinyglobby": {
+ "version": "0.2.15",
+ "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz",
+ "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "fdir": "^6.5.0",
+ "picomatch": "^4.0.3"
+ },
+ "engines": {
+ "node": ">=12.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/SuperchupuDev"
+ }
+ },
+ "node_modules/typescript": {
+ "version": "5.9.3",
+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
+ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
+ "devOptional": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "tsc": "bin/tsc",
+ "tsserver": "bin/tsserver"
+ },
+ "engines": {
+ "node": ">=14.17"
+ }
+ },
+ "node_modules/vite": {
+ "version": "7.3.1",
+ "resolved": "https://registry.npmjs.org/vite/-/vite-7.3.1.tgz",
+ "integrity": "sha512-w+N7Hifpc3gRjZ63vYBXA56dvvRlNWRczTdmCBBa+CotUzAPf5b7YMdMR/8CQoeYE5LX3W4wj6RYTgonm1b9DA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "esbuild": "^0.27.0",
+ "fdir": "^6.5.0",
+ "picomatch": "^4.0.3",
+ "postcss": "^8.5.6",
+ "rollup": "^4.43.0",
+ "tinyglobby": "^0.2.15"
+ },
+ "bin": {
+ "vite": "bin/vite.js"
+ },
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ },
+ "funding": {
+ "url": "https://github.com/vitejs/vite?sponsor=1"
+ },
+ "optionalDependencies": {
+ "fsevents": "~2.3.3"
+ },
+ "peerDependencies": {
+ "@types/node": "^20.19.0 || >=22.12.0",
+ "jiti": ">=1.21.0",
+ "less": "^4.0.0",
+ "lightningcss": "^1.21.0",
+ "sass": "^1.70.0",
+ "sass-embedded": "^1.70.0",
+ "stylus": ">=0.54.8",
+ "sugarss": "^5.0.0",
+ "terser": "^5.16.0",
+ "tsx": "^4.8.1",
+ "yaml": "^2.4.2"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ },
+ "jiti": {
+ "optional": true
+ },
+ "less": {
+ "optional": true
+ },
+ "lightningcss": {
+ "optional": true
+ },
+ "sass": {
+ "optional": true
+ },
+ "sass-embedded": {
+ "optional": true
+ },
+ "stylus": {
+ "optional": true
+ },
+ "sugarss": {
+ "optional": true
+ },
+ "terser": {
+ "optional": true
+ },
+ "tsx": {
+ "optional": true
+ },
+ "yaml": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/vscode-uri": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/vscode-uri/-/vscode-uri-3.1.0.tgz",
+ "integrity": "sha512-/BpdSx+yCQGnCvecbyXdxHDkuk55/G3xwnC0GqY4gmQ3j+A+g8kzzgB4Nk/SINjqn6+waqw3EgbVF2QKExkRxQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/vue": {
+ "version": "3.5.30",
+ "resolved": "https://registry.npmjs.org/vue/-/vue-3.5.30.tgz",
+ "integrity": "sha512-hTHLc6VNZyzzEH/l7PFGjpcTvUgiaPK5mdLkbjrTeWSRcEfxFrv56g/XckIYlE9ckuobsdwqd5mk2g1sBkMewg==",
+ "license": "MIT",
+ "dependencies": {
+ "@vue/compiler-dom": "3.5.30",
+ "@vue/compiler-sfc": "3.5.30",
+ "@vue/runtime-dom": "3.5.30",
+ "@vue/server-renderer": "3.5.30",
+ "@vue/shared": "3.5.30"
+ },
+ "peerDependencies": {
+ "typescript": "*"
+ },
+ "peerDependenciesMeta": {
+ "typescript": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/vue-router": {
+ "version": "4.6.4",
+ "resolved": "https://registry.npmjs.org/vue-router/-/vue-router-4.6.4.tgz",
+ "integrity": "sha512-Hz9q5sa33Yhduglwz6g9skT8OBPii+4bFn88w6J+J4MfEo4KRRpmiNG/hHHkdbRFlLBOqxN8y8gf2Fb0MTUgVg==",
+ "license": "MIT",
+ "dependencies": {
+ "@vue/devtools-api": "^6.6.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/posva"
+ },
+ "peerDependencies": {
+ "vue": "^3.5.0"
+ }
+ },
+ "node_modules/vue-router/node_modules/@vue/devtools-api": {
+ "version": "6.6.4",
+ "resolved": "https://registry.npmjs.org/@vue/devtools-api/-/devtools-api-6.6.4.tgz",
+ "integrity": "sha512-sGhTPMuXqZ1rVOk32RylztWkfXTRhuS7vgAKv0zjqk8gbsHkJ7xfFf+jbySxt7tWObEJwyKaHMikV/WGDiQm8g==",
+ "license": "MIT"
+ },
+ "node_modules/vue-tsc": {
+ "version": "3.2.5",
+ "resolved": "https://registry.npmjs.org/vue-tsc/-/vue-tsc-3.2.5.tgz",
+ "integrity": "sha512-/htfTCMluQ+P2FISGAooul8kO4JMheOTCbCy4M6dYnYYjqLe3BExZudAua6MSIKSFYQtFOYAll7XobYwcpokGA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@volar/typescript": "2.4.28",
+ "@vue/language-core": "3.2.5"
+ },
+ "bin": {
+ "vue-tsc": "bin/vue-tsc.js"
+ },
+ "peerDependencies": {
+ "typescript": ">=5.0.0"
+ }
+ }
+ }
+}
diff --git a/web/package.json b/web/package.json
new file mode 100644
index 0000000..8c524d5
--- /dev/null
+++ b/web/package.json
@@ -0,0 +1,25 @@
+{
+ "name": "dashboard",
+ "private": true,
+ "version": "0.0.0",
+ "type": "module",
+ "scripts": {
+ "dev": "vite",
+ "build": "vite build",
+ "preview": "vite preview"
+ },
+ "dependencies": {
+ "@mdi/font": "^7.4.47",
+ "axios": "^1.13.6",
+ "pinia": "^3.0.4",
+ "vue": "^3.5.25",
+ "vue-router": "^4.6.4"
+ },
+ "devDependencies": {
+ "@tsconfig/node22": "^22.0.5",
+ "@vitejs/plugin-vue": "^6.0.2",
+ "typescript": "^5.9.3",
+ "vite": "^7.3.1",
+ "vue-tsc": "^3.2.5"
+ }
+}
diff --git a/web/public/apple-touch-icon.png b/web/public/apple-touch-icon.png
new file mode 100644
index 0000000..e496cd3
Binary files /dev/null and b/web/public/apple-touch-icon.png differ
diff --git a/web/public/favicon-96x96.png b/web/public/favicon-96x96.png
new file mode 100644
index 0000000..d4b96d2
Binary files /dev/null and b/web/public/favicon-96x96.png differ
diff --git a/web/public/favicon.ico b/web/public/favicon.ico
new file mode 100644
index 0000000..f845e7f
Binary files /dev/null and b/web/public/favicon.ico differ
diff --git a/web/public/favicon.svg b/web/public/favicon.svg
new file mode 100644
index 0000000..47097cd
--- /dev/null
+++ b/web/public/favicon.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="1000" height="1000"><g clip-path="url(#SvgjsClipPath1017)"><rect width="1000" height="1000" fill="#ffffff"></rect><g transform="matrix(1.6339869281045751,0,0,1.6339869281045751,0,166.66666666666669)"><svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="612" height="408" viewBox="0 0 612 408"><image width="612" height="408" xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAmQAAAGYCAYAAADsqf5DAAAQAElEQVR4Aex9B4BdR3X2d+aWV7ZrdyWtumTLBXeKMcX0HlIIkEII+SFACCWGQCCJ6b2aXkwPvds0U02zARtccMHGvUhW1/bXbpn5v3PfPmm1XskF2Za8c32/N/3MzHfv7vl0Zndt4C/PgGfAM+AZ8Ax4BjwDnoF7lAEvyO5R+v3kngHPgGdgoTDg9+kZ8AzsiwEvyPbFjm/zDHgGPAOeAc+AZ8AzcDcw4AXZ3UCyn2JhMOB36RnwDHgGPAOegTvLgBdkd5Y5P84z4BnwDHgGPAOeAc/AfmLgDgiy/TSjN+MZ8Ax4BjwDngHPgGfAM7AHA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H0Nh+cvP4jG//d/V/+wL+My+LYOfuldGATGFECTshG9MJ72zWBiJi97bP4+x/8zZ0vfvKOD/6Hmfj1q7Hh4HSv9WYqeSMq2ofRax3lTes4Ups3rtZMP2GZAcZYbh1JvdbhU6poV+3o5ofmxf6MqbiHUXbeBvug2zmCOc412zqUqLpv61Ddj/7uEvVYlxb8hzDH/nOtg5Xttg9Bbb0O52Hsxjb+xs7mTf/DVX+NodIcY6mN5X68wwuWc2utldiviSXb68+lcaozDmMdLGPT8V62+UTveO+13q8P/m8cOPELpA3voBw/Rh2t5p7j2jWmGDuCYqyer2Kh+ap5at8cy1qbNNM+APVZqhnuayZjG23VL97CLOtzrDeazd/CVFs6SHsQ051DlZ1q1+Wl9RmuSb5K5DvVegszlPpLapeqdsaabB2A6lLjGyxrzCz3OsNrNM14k/kBSFPkoLr8UlMetCpPc+8znGe6w/VWa16wU2yb4vxN28zYIUyrT19qq3UYU60jbDuKmfZx6mRfKh/FVHt/eTT7+dsbr3v7v375+d9++aHvfuDH8aE4Wv/2+NME1iOBC7cnJ2QXjr1nXiMEmJRNX3kz/uEb37nxxb/Zfee3X/izT33vC49v+8ldD2+duO+x7bvue/TDu+5/7COVdjyyfeeOR27Zed+j11fa8fitEzue3D6x43GK9sHHtu9+8Intu5v6F1l+6Mnbdj34xG07H3zqtp0qSw88vm3nA0/e+tMHH7/5Jw89cetPHnzilpcefGL7zgef2LbrgSe373zgiW0v0f70oae2/fTBp7b/5MGnt/1kkZVffR5nHOmJW3bueGLbSzuevOWlxj7w+Lad9z964877H7lpwT524677H71p1/209z1600tfqHTLvN3x2E07dzx2y677H79p9/2P30LdtFv1LzzKcY/dvPP+x2746X2P3kht/en9j9y4854vbd1115du3N3Yu768dffdD9+4++4vbZ2gndjx1A27v/DoTTvv+tK1L312x9U773x467964Inb/vWXnvnYzx75+sf3PfHtP9jz+Lf/YKLWJyeeeP5T1Cer+mPf+r3dT75w+66nv/OpnU9Wuv2lJ79z+0tPSS/cvpNtux//9qc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OyM4lXcc2ARMwARMwARMwgTMg4ITsDCCNRhfv0gRMwARMwARM4EIRcEJ2och7XhMwARMwARMYRQLe87IEnJAti8VOEzABEzABEzABEzh/BJyQnT/WnskETGA0CHiXJmACJnDWBJyQnTUyDzABEzABEzABEzCB1SXghGx1eY5GNO/SBEzABEzABExgVQk4IVtVnA5mAiZgAiZgAiawWgRGKY4TslG62t6rCZiACZiACZjAmiTghGxNXhYvygRMYDQIeJcmYAImUBNwQlZz8KcJmIAJmIAJmIAJXDACTsguGPrRmNi7NAETMAETMAETOD0BJ2SnZ+QeJmACJmACJmACa5vA0K/OCdnQX0JvwARMwARMwARMYNgJOCEb9ivo9ZuACYwGAe/SBExgXRNwQrauL683ZwImYAImYAImMAwEnJANw1UajTV6lyZgAiZgAiYwsgSckI3spffGTcAETMAETGAUCazNPTshW5vXxasyARMwARMwARMYIQJOyEboYnurJmACo0HAuzQBExg+Ak7Ihu+aecUmYAImYAImYALrjIATsnV2QUdjO96lCZiACZiACawvAk7I1tf19G5MwARMwARMwARWi8B5jOOE7DzC9lQmYAImYAImYAImsBwBJ2TLUbHPBEzABEaDgHdpAiawRgg4IVsjF8LLMAETMAETMAETGF0CTshG99qPxs69SxMwARMwARMYAgJOyIbgInmJJmACJmACJmACa5vASlfnhGylBD3eBEzABEzABEzABFZIwAnZCgF6uAmYgAmMBgHv0gRM4FwScEJ2Luk6tgmYgAmYgAmYgAmcAQEnZGcAyV1Gg4B3aQImYAImYAIXioATsgtF3vOagAmYgAmYgAmMIoFl9+yEbFksdpqACZiACZiACZjA+SPghOz8sfZMJmACJjAaBLxLEzCBsybghOyskXmACZiACZiACZiACawuASdkq8vT0UaDgHdpAiZgAiZgAqtKwAnZquJ0MBMwARMwARMwARM4ewLLJ2RnH8cjTMAETMAETMAETMAE3icBJ2TvE5yHmYAJmIAJrJyAI5iACdQEnJDVHPxpAiZgAiZgAiZgAheMgBOyC4beE48GAe/SBEzABEzABE5PwAnZ6Rm5hwmYgAmYgAmYgAmcUwIrTsjO6eoc3ARMwARMwARMwARGgIATshG4yN6iCZiACawDAt6CCaxrAk7I1vXl9eZMwARMwARMwASGgYATsmG4Sl7jaBDwLk3ABEzABEaWgBOykb303rgJmIAJmIAJmMBaIXA+E7K1smevwwRMwARMwARMwATWFAEnZGvqcngxJmACJmACKyfgCCYwfASckA3fNfOKTcAETMAETMAE1hkBJ2Tr7IJ6O6NBwLs0ARMwARNYXwSckK2v6+ndmIAJmIAJmIAJDCGBNZqQDSFJL9kETMAETMAETMAE3icBJ2TvE5yHmYAJmIAJrAMC3oIJrBECTsjWyIXwMkzABEzABEzABEaXgBOy0b323vloEPAuTcAETMAEhoCAE7IhuEheogmYgAmYgAmYwPomMPwJ2fq+Pt6dCZiACZiACZjACBBwQjYCF9lbNAETMAETWDkBRzCBc0nACdm5pOvYJmACJmACJmACJnAGBJyQnQEkdzGB0SDgXZqACZiACVwoAk7ILhR5z2sCJmACJmACJmACfQIjlZD192xjAiZgAiZgAiZgAmuKgBOyNXU5vBgTMAETMIF1QMBbMIGzJuCE7KyReYAJmIAJmIAJmIAJrC4BJ2Sry9PRTGA0CHiXJmACJmACq0rACdmq4nQwEzABEzABEzABEzh7Ak7IlmdmrwmYgAmYgAmYgAmcNwL/HwAA///N7+PkAAAABklEQVQDAOSaTHVjWAWdAAAAAElFTkSuQmCC"></image></svg></g></g><defs><clipPath id="SvgjsClipPath1017"><rect width="1000" height="1000" x="0" y="0" rx="350" ry="350"></rect></clipPath></defs></svg>
\ No newline at end of file
diff --git a/web/public/logo.png b/web/public/logo.png
new file mode 100644
index 0000000..b2c1660
Binary files /dev/null and b/web/public/logo.png differ
diff --git a/web/public/site.webmanifest b/web/public/site.webmanifest
new file mode 100644
index 0000000..d1b10e3
--- /dev/null
+++ b/web/public/site.webmanifest
@@ -0,0 +1,21 @@
+{
+ "name": "Posta Relay",
+ "short_name": "Posta",
+ "icons": [
+ {
+ "src": "/web-app-manifest-192x192.png",
+ "sizes": "192x192",
+ "type": "image/png",
+ "purpose": "maskable"
+ },
+ {
+ "src": "/web-app-manifest-512x512.png",
+ "sizes": "512x512",
+ "type": "image/png",
+ "purpose": "maskable"
+ }
+ ],
+ "theme_color": "#9333ea",
+ "background_color": "#ffffff",
+ "display": "standalone"
+}
diff --git a/web/public/web-app-manifest-192x192.png b/web/public/web-app-manifest-192x192.png
new file mode 100644
index 0000000..f43491f
Binary files /dev/null and b/web/public/web-app-manifest-192x192.png differ
diff --git a/web/public/web-app-manifest-512x512.png b/web/public/web-app-manifest-512x512.png
new file mode 100644
index 0000000..ddcd354
Binary files /dev/null and b/web/public/web-app-manifest-512x512.png differ
diff --git a/web/src/App.vue b/web/src/App.vue
new file mode 100644
index 0000000..334ad02
--- /dev/null
+++ b/web/src/App.vue
@@ -0,0 +1,26 @@
+<script setup lang="ts">
+import { useNotificationStore } from './stores/notification'
+import { useThemeStore } from './stores/theme'
+import ConfirmDialog from './components/ConfirmDialog.vue'
+
+useThemeStore()
+const notify = useNotificationStore()
+</script>
+
+<template>
+ <div>
+ <router-view />
+ <ConfirmDialog />
+ <div class="toast-container">
+ <div
+ v-for="n in notify.notifications"
+ :key="n.id"
+ class="toast"
+ :class="`toast-${n.type}`"
+ @click="notify.dismiss(n.id)"
+ >
+ {{ n.message }}
+ </div>
+ </div>
+ </div>
+</template>
diff --git a/web/src/api/admin.ts b/web/src/api/admin.ts
new file mode 100644
index 0000000..a9b8a96
--- /dev/null
+++ b/web/src/api/admin.ts
@@ -0,0 +1,43 @@
+import api from './client'
+import type { ApiResponse, PaginatedResponse, User, ApiKey, Email, Event, AdminMetrics, UserDetailMetrics, CronJob } from './types'
+
+export const adminApi = {
+ listUsers(page = 0, size = 20) {
+ return api.get<PaginatedResponse<User>>('/admin/users', { params: { page, size } })
+ },
+ createUser(name: string, email: string, password: string, role: string) {
+ return api.post<ApiResponse<User>>('/admin/users', { name, email, password, role })
+ },
+ updateUser(id: number, data: { role?: string; active?: boolean }) {
+ return api.put<ApiResponse<User>>(`/admin/users/${id}`, data)
+ },
+ deleteUser(id: number) {
+ return api.delete(`/admin/users/${id}`)
+ },
+ getUserMetrics(id: number) {
+ return api.get<ApiResponse<UserDetailMetrics>>(`/admin/users/${id}/metrics`)
+ },
+ disable2FA(id: number) {
+ return api.delete(`/admin/users/${id}/2fa`)
+ },
+ listApiKeys(page = 0, size = 20) {
+ return api.get<PaginatedResponse<ApiKey>>('/admin/api-keys', { params: { page, size } })
+ },
+ revokeApiKey(id: number) {
+ return api.delete(`/admin/api-keys/${id}`)
+ },
+ listEmails(page = 0, size = 20) {
+ return api.get<PaginatedResponse<Email>>('/admin/emails', { params: { page, size } })
+ },
+ getMetrics() {
+ return api.get<ApiResponse<AdminMetrics>>('/admin/metrics')
+ },
+ listEvents(page = 0, size = 20, category?: string) {
+ const params: Record<string, any> = { page, size }
+ if (category) params.category = category
+ return api.get<PaginatedResponse<Event>>('/admin/events', { params })
+ },
+ listJobs() {
+ return api.get<ApiResponse<CronJob[]>>('/admin/jobs')
+ },
+}
diff --git a/web/src/api/analytics.ts b/web/src/api/analytics.ts
new file mode 100644
index 0000000..fda41c5
--- /dev/null
+++ b/web/src/api/analytics.ts
@@ -0,0 +1,19 @@
+import api from './client'
+import type { ApiResponse, AnalyticsResponse } from './types'
+
+export const analyticsApi = {
+ user(from?: string, to?: string, status?: string) {
+ const params: Record<string, string> = {}
+ if (from) params.from = from
+ if (to) params.to = to
+ if (status) params.status = status
+ return api.get<ApiResponse<AnalyticsResponse>>('/users/me/analytics', { params })
+ },
+ admin(from?: string, to?: string, status?: string) {
+ const params: Record<string, string> = {}
+ if (from) params.from = from
+ if (to) params.to = to
+ if (status) params.status = status
+ return api.get<ApiResponse<AnalyticsResponse>>('/admin/analytics', { params })
+ },
+}
diff --git a/web/src/api/apikeys.ts b/web/src/api/apikeys.ts
new file mode 100644
index 0000000..85a9410
--- /dev/null
+++ b/web/src/api/apikeys.ts
@@ -0,0 +1,20 @@
+import api from './client'
+import type { ApiResponse, PaginatedResponse, ApiKey, ApiKeyCreateResponse } from './types'
+
+export const apiKeysApi = {
+ list(page = 0, size = 20) {
+ return api.get<PaginatedResponse<ApiKey>>('/users/me/api-keys', { params: { page, size } })
+ },
+ create(name: string, allowedIPs?: string[], expiresInDays?: number) {
+ const body: Record<string, any> = { name }
+ if (allowedIPs && allowedIPs.length > 0) body.allowed_ips = allowedIPs
+ if (expiresInDays !== undefined) body.expires_in_days = expiresInDays
+ return api.post<ApiResponse<ApiKeyCreateResponse>>('/users/me/api-keys', body)
+ },
+ revoke(id: number) {
+ return api.put(`/users/me/api-keys/${id}/revoke`)
+ },
+ delete(id: number) {
+ return api.delete(`/users/me/api-keys/${id}`)
+ },
+}
diff --git a/web/src/api/audit.ts b/web/src/api/audit.ts
new file mode 100644
index 0000000..f180e8a
--- /dev/null
+++ b/web/src/api/audit.ts
@@ -0,0 +1,10 @@
+import api from './client'
+import type { PaginatedResponse, Event } from './types'
+
+export const auditApi = {
+ list(page = 0, size = 20, category?: string) {
+ const params: Record<string, any> = { page, size }
+ if (category) params.category = category
+ return api.get<PaginatedResponse<Event>>('/users/me/audit-log', { params })
+ },
+}
diff --git a/web/src/api/auth.ts b/web/src/api/auth.ts
new file mode 100644
index 0000000..54e5ac4
--- /dev/null
+++ b/web/src/api/auth.ts
@@ -0,0 +1,37 @@
+import api from './client'
+import type { ApiResponse, AuthResponse, UserProfile, Setup2FAResponse } from './types'
+
+export const authApi = {
+ login(email: string, password: string, twoFactorCode?: string) {
+ const body: Record<string, string> = { email, password }
+ if (twoFactorCode) body.two_factor_code = twoFactorCode
+ return api.post<ApiResponse<AuthResponse>>('/auth/login', body)
+ },
+ me() {
+ return api.get<ApiResponse<UserProfile>>('/users/me')
+ },
+ updateProfile(data: { name: string; require_verified_domain?: boolean }) {
+ return api.put<ApiResponse<UserProfile>>('/users/me', data)
+ },
+ changePassword(currentPassword: string, newPassword: string) {
+ return api.put<ApiResponse<{ message: string }>>('/users/me/password', {
+ current_password: currentPassword,
+ new_password: newPassword,
+ })
+ },
+ setup2FA() {
+ return api.post<ApiResponse<Setup2FAResponse>>('/users/me/2fa/setup')
+ },
+ verify2FA(code: string) {
+ return api.post<ApiResponse<{ message: string }>>('/users/me/2fa/verify', { code })
+ },
+ disable2FA(code: string) {
+ return api.post<ApiResponse<{ message: string }>>('/users/me/2fa/disable', { code })
+ },
+ register(name: string, email: string, password: string) {
+ return api.post<ApiResponse<AuthResponse>>('/auth/register', { name, email, password })
+ },
+ registrationStatus() {
+ return api.get<ApiResponse<{ registration_enabled: boolean }>>('/auth/registration-status')
+ },
+}
diff --git a/web/src/api/bounces.ts b/web/src/api/bounces.ts
new file mode 100644
index 0000000..6f16279
--- /dev/null
+++ b/web/src/api/bounces.ts
@@ -0,0 +1,23 @@
+import api from './client'
+import type { PaginatedResponse, Bounce, Suppression, ApiResponse } from './types'
+
+export const bouncesApi = {
+ list(page = 0, size = 20) {
+ return api.get<PaginatedResponse<Bounce>>('/users/me/bounces', { params: { page, size } })
+ },
+ create(data: { email_id: number; recipient: string; type: string; reason: string }) {
+ return api.post<ApiResponse<Bounce>>('/users/me/bounces', data)
+ },
+}
+
+export const suppressionsApi = {
+ list(page = 0, size = 20) {
+ return api.get<PaginatedResponse<Suppression>>('/users/me/suppressions', { params: { page, size } })
+ },
+ create(data: { email: string; reason: string }) {
+ return api.post<ApiResponse<Suppression>>('/users/me/suppressions', data)
+ },
+ delete(email: string) {
+ return api.delete('/users/me/suppressions', { data: { email } })
+ },
+}
diff --git a/web/src/api/client.ts b/web/src/api/client.ts
new file mode 100644
index 0000000..88e2eb0
--- /dev/null
+++ b/web/src/api/client.ts
@@ -0,0 +1,31 @@
+import axios from 'axios'
+import { useAuthStore } from '../stores/auth'
+
+const api = axios.create({
+ baseURL: import.meta.env.VITE_API_URL || '/api/v1',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+})
+
+api.interceptors.request.use((config) => {
+ const auth = useAuthStore()
+ if (auth.token) {
+ config.headers.Authorization = `Bearer ${auth.token}`
+ }
+ return config
+})
+
+api.interceptors.response.use(
+ (response) => response,
+ (error) => {
+ if (error.response?.status === 401 && !error.response?.data?.data?.requires_2fa) {
+ const auth = useAuthStore()
+ auth.logout()
+ window.location.href = '/login'
+ }
+ return Promise.reject(error)
+ }
+)
+
+export default api
diff --git a/web/src/api/contactLists.ts b/web/src/api/contactLists.ts
new file mode 100644
index 0000000..1d19b82
--- /dev/null
+++ b/web/src/api/contactLists.ts
@@ -0,0 +1,26 @@
+import api from './client'
+import type { ApiResponse, PaginatedResponse, ContactList, ContactListWithCount, ContactListMember } from './types'
+
+export const contactListsApi = {
+ list(page = 0, size = 20) {
+ return api.get<PaginatedResponse<ContactListWithCount>>('/users/me/contact-lists', { params: { page, size } })
+ },
+ create(name: string, description: string) {
+ return api.post<ApiResponse<ContactList>>('/users/me/contact-lists', { name, description })
+ },
+ update(id: number, name: string, description: string) {
+ return api.put<ApiResponse<ContactList>>(`/users/me/contact-lists/${id}`, { name, description })
+ },
+ delete(id: number) {
+ return api.delete(`/users/me/contact-lists/${id}`)
+ },
+ listMembers(id: number, page = 0, size = 20) {
+ return api.get<PaginatedResponse<ContactListMember>>(`/users/me/contact-lists/${id}/members`, { params: { page, size } })
+ },
+ addMember(id: number, email: string, name: string) {
+ return api.post<ApiResponse<ContactListMember>>(`/users/me/contact-lists/${id}/members`, { email, name })
+ },
+ removeMember(id: number, email: string) {
+ return api.delete(`/users/me/contact-lists/${id}/members`, { data: { email } })
+ },
+}
diff --git a/web/src/api/contacts.ts b/web/src/api/contacts.ts
new file mode 100644
index 0000000..9e5fc4b
--- /dev/null
+++ b/web/src/api/contacts.ts
@@ -0,0 +1,11 @@
+import api from './client'
+import type { ApiResponse, PaginatedResponse, Contact } from './types'
+
+export const contactsApi = {
+ list(page = 0, size = 20, search = '') {
+ return api.get<PaginatedResponse<Contact>>('/users/me/contacts', { params: { page, size, search: search || undefined } })
+ },
+ get(id: number) {
+ return api.get<ApiResponse<Contact>>(`/users/me/contacts/${id}`)
+ },
+}
diff --git a/web/src/api/dashboard.ts b/web/src/api/dashboard.ts
new file mode 100644
index 0000000..a9b2682
--- /dev/null
+++ b/web/src/api/dashboard.ts
@@ -0,0 +1,8 @@
+import api from './client'
+import type { ApiResponse, DashboardStats } from './types'
+
+export const dashboardApi = {
+ getStats() {
+ return api.get<ApiResponse<DashboardStats>>('/users/me/dashboard/stats')
+ },
+}
diff --git a/web/src/api/domains.ts b/web/src/api/domains.ts
new file mode 100644
index 0000000..35aa2bf
--- /dev/null
+++ b/web/src/api/domains.ts
@@ -0,0 +1,20 @@
+import api from './client'
+import type { ApiResponse, PaginatedResponse, Domain } from './types'
+
+export const domainsApi = {
+ list(page = 0, size = 20) {
+ return api.get<PaginatedResponse<Domain>>('/users/me/domains', { params: { page, size } })
+ },
+ get(id: number) {
+ return api.get<ApiResponse<Domain>>(`/users/me/domains/${id}`)
+ },
+ create(domain: string) {
+ return api.post<ApiResponse<Domain>>('/users/me/domains', { domain })
+ },
+ verify(id: number) {
+ return api.post<ApiResponse<Domain>>(`/users/me/domains/${id}/verify`)
+ },
+ delete(id: number) {
+ return api.delete(`/users/me/domains/${id}`)
+ },
+}
diff --git a/web/src/api/emails.ts b/web/src/api/emails.ts
new file mode 100644
index 0000000..c558105
--- /dev/null
+++ b/web/src/api/emails.ts
@@ -0,0 +1,19 @@
+import api from './client'
+import type { ApiResponse, PaginatedResponse, Email } from './types'
+
+export interface RetryResponse {
+ id: string
+ status: string
+}
+
+export const emailsApi = {
+ list(page = 0, size = 20) {
+ return api.get<PaginatedResponse<Email>>('/users/me/emails', { params: { page, size } })
+ },
+ get(uuid: string) {
+ return api.get<ApiResponse<Email>>(`/users/me/emails/${uuid}`)
+ },
+ retry(uuid: string) {
+ return api.post<ApiResponse<RetryResponse>>(`/users/me/emails/${uuid}/retry`)
+ },
+}
diff --git a/web/src/api/info.ts b/web/src/api/info.ts
new file mode 100644
index 0000000..3b1ae1f
--- /dev/null
+++ b/web/src/api/info.ts
@@ -0,0 +1,12 @@
+import api from './client'
+
+export interface AppInfo {
+ name: string
+ version: string
+ commit_id: string
+ openapi_docs: boolean
+}
+
+export const infoApi = {
+ get: () => api.get<{ success: boolean; data: AppInfo }>('/info'),
+}
diff --git a/web/src/api/languages.ts b/web/src/api/languages.ts
new file mode 100644
index 0000000..25bda33
--- /dev/null
+++ b/web/src/api/languages.ts
@@ -0,0 +1,17 @@
+import api from './client'
+import type { ApiResponse, PaginatedResponse, Language, LanguageInput } from './types'
+
+export const languagesApi = {
+ list(page = 0, size = 100) {
+ return api.get<PaginatedResponse<Language>>('/users/me/languages', { params: { page, size } })
+ },
+ create(data: LanguageInput) {
+ return api.post<ApiResponse<Language>>('/users/me/languages', data)
+ },
+ update(id: number, data: Partial<LanguageInput>) {
+ return api.put<ApiResponse<Language>>(`/users/me/languages/${id}`, data)
+ },
+ delete(id: number) {
+ return api.delete(`/users/me/languages/${id}`)
+ },
+}
diff --git a/web/src/api/servers.ts b/web/src/api/servers.ts
new file mode 100644
index 0000000..2b78fd9
--- /dev/null
+++ b/web/src/api/servers.ts
@@ -0,0 +1,29 @@
+import api from './client'
+import type { ApiResponse, PaginatedResponse, SharedServer, SharedServerInput } from './types'
+
+export const serversApi = {
+ list(page = 0, size = 20) {
+ return api.get<PaginatedResponse<SharedServer>>('/admin/servers', { params: { page, size } })
+ },
+ get(id: number) {
+ return api.get<ApiResponse<SharedServer>>(`/admin/servers/${id}`)
+ },
+ create(data: SharedServerInput) {
+ return api.post<ApiResponse<SharedServer>>('/admin/servers', data)
+ },
+ update(id: number, data: Partial<SharedServerInput>) {
+ return api.put<ApiResponse<SharedServer>>(`/admin/servers/${id}`, data)
+ },
+ delete(id: number) {
+ return api.delete(`/admin/servers/${id}`)
+ },
+ enable(id: number) {
+ return api.post<ApiResponse<SharedServer>>(`/admin/servers/${id}/enable`)
+ },
+ disable(id: number) {
+ return api.post<ApiResponse<SharedServer>>(`/admin/servers/${id}/disable`)
+ },
+ test(id: number) {
+ return api.post<ApiResponse<{ success: boolean; message: string }>>(`/admin/servers/${id}/test`)
+ },
+}
diff --git a/web/src/api/settings.ts b/web/src/api/settings.ts
new file mode 100644
index 0000000..545943b
--- /dev/null
+++ b/web/src/api/settings.ts
@@ -0,0 +1,20 @@
+import api from './client'
+import type { ApiResponse, AdminSetting, AdminSettingInput, UserSettings } from './types'
+
+export const settingsApi = {
+ // Admin platform settings
+ getAdminSettings() {
+ return api.get<ApiResponse<AdminSetting[]>>('/admin/settings')
+ },
+ updateAdminSettings(settings: AdminSettingInput[]) {
+ return api.put<ApiResponse<AdminSetting[]>>('/admin/settings', { settings })
+ },
+
+ // User settings
+ getUserSettings() {
+ return api.get<ApiResponse<UserSettings>>('/users/me/settings')
+ },
+ updateUserSettings(data: Partial<Omit<UserSettings, 'id' | 'user_id' | 'created_at' | 'updated_at'>>) {
+ return api.put<ApiResponse<UserSettings>>('/users/me/settings', data)
+ },
+}
diff --git a/web/src/api/smtp.ts b/web/src/api/smtp.ts
new file mode 100644
index 0000000..555b9bb
--- /dev/null
+++ b/web/src/api/smtp.ts
@@ -0,0 +1,23 @@
+import api from './client'
+import type { ApiResponse, PaginatedResponse, SmtpServer, SmtpServerInput } from './types'
+
+export const smtpApi = {
+ list(page = 0, size = 20) {
+ return api.get<PaginatedResponse<SmtpServer>>('/users/me/smtp-servers', { params: { page, size } })
+ },
+ get(id: number) {
+ return api.get<ApiResponse<SmtpServer>>(`/users/me/smtp-servers/${id}`)
+ },
+ create(data: SmtpServerInput) {
+ return api.post<ApiResponse<SmtpServer>>('/users/me/smtp-servers', data)
+ },
+ update(id: number, data: Partial<SmtpServerInput>) {
+ return api.put<ApiResponse<SmtpServer>>(`/users/me/smtp-servers/${id}`, data)
+ },
+ delete(id: number) {
+ return api.delete(`/users/me/smtp-servers/${id}`)
+ },
+ test(id: number) {
+ return api.post(`/users/me/smtp-servers/${id}/test`)
+ },
+}
diff --git a/web/src/api/stylesheets.ts b/web/src/api/stylesheets.ts
new file mode 100644
index 0000000..540adec
--- /dev/null
+++ b/web/src/api/stylesheets.ts
@@ -0,0 +1,17 @@
+import api from './client'
+import type { ApiResponse, PaginatedResponse, StyleSheet, StyleSheetInput } from './types'
+
+export const stylesheetsApi = {
+ list(page = 0, size = 100) {
+ return api.get<PaginatedResponse<StyleSheet>>('/users/me/stylesheets', { params: { page, size } })
+ },
+ create(data: StyleSheetInput) {
+ return api.post<ApiResponse<StyleSheet>>('/users/me/stylesheets', data)
+ },
+ update(id: number, data: StyleSheetInput) {
+ return api.put<ApiResponse<StyleSheet>>(`/users/me/stylesheets/${id}`, data)
+ },
+ delete(id: number) {
+ return api.delete(`/users/me/stylesheets/${id}`)
+ },
+}
diff --git a/web/src/api/templates.ts b/web/src/api/templates.ts
new file mode 100644
index 0000000..6d7601c
--- /dev/null
+++ b/web/src/api/templates.ts
@@ -0,0 +1,76 @@
+import api from './client'
+import type {
+ ApiResponse,
+ PaginatedResponse,
+ Template,
+ TemplateInput,
+ TemplateExport,
+ TemplatePreview,
+ TemplateVersion,
+ TemplateVersionInput,
+ TemplateLocalization,
+ TemplateLocalizationInput,
+ SendTestInput,
+ SendTestResponse,
+} from './types'
+
+export const templatesApi = {
+ list(page = 0, size = 20) {
+ return api.get<PaginatedResponse<Template>>('/users/me/templates', { params: { page, size } })
+ },
+ create(data: TemplateInput) {
+ return api.post<ApiResponse<Template>>('/users/me/templates', data)
+ },
+ update(id: number, data: Partial<TemplateInput>) {
+ return api.put<ApiResponse<Template>>(`/users/me/templates/${id}`, data)
+ },
+ delete(id: number) {
+ return api.delete(`/users/me/templates/${id}`)
+ },
+
+ // Versions
+ listVersions(templateId: number) {
+ return api.get<ApiResponse<TemplateVersion[]>>(`/users/me/templates/${templateId}/versions`)
+ },
+ createVersion(templateId: number, data: TemplateVersionInput) {
+ return api.post<ApiResponse<TemplateVersion>>(`/users/me/templates/${templateId}/versions`, data)
+ },
+ updateVersion(templateId: number, versionId: number, data: Partial<TemplateVersionInput>) {
+ return api.put<ApiResponse<TemplateVersion>>(`/users/me/templates/${templateId}/versions/${versionId}`, data)
+ },
+ activateVersion(templateId: number, versionId: number) {
+ return api.post<ApiResponse<Template>>(`/users/me/templates/${templateId}/activate/${versionId}`)
+ },
+ deleteVersion(templateId: number, versionId: number) {
+ return api.delete(`/users/me/templates/${templateId}/versions/${versionId}`)
+ },
+
+ // Localizations
+ listLocalizations(templateId: number, versionId: number) {
+ return api.get<ApiResponse<TemplateLocalization[]>>(`/users/me/templates/${templateId}/versions/${versionId}/localizations`)
+ },
+ createLocalization(templateId: number, versionId: number, data: TemplateLocalizationInput) {
+ return api.post<ApiResponse<TemplateLocalization>>(`/users/me/templates/${templateId}/versions/${versionId}/localizations`, data)
+ },
+ updateLocalization(localizationId: number, data: Partial<Omit<TemplateLocalizationInput, 'language'>>) {
+ return api.put<ApiResponse<TemplateLocalization>>(`/users/me/localizations/${localizationId}`, data)
+ },
+ deleteLocalization(localizationId: number) {
+ return api.delete(`/users/me/localizations/${localizationId}`)
+ },
+ previewLocalization(templateId: number, versionId: number, data: { language: string; template_data: Record<string, any> }) {
+ return api.post<ApiResponse<TemplatePreview>>(`/users/me/templates/${templateId}/versions/${versionId}/preview`, data)
+ },
+
+ sendTest(templateId: number, data: SendTestInput) {
+ return api.post<ApiResponse<SendTestResponse>>(`/users/me/templates/${templateId}/send-test`, data)
+ },
+
+ // Import/Export
+ exportTemplate(templateId: number) {
+ return api.get<ApiResponse<TemplateExport>>(`/users/me/templates/${templateId}/export`)
+ },
+ importTemplate(data: TemplateExport) {
+ return api.post<ApiResponse<Template>>('/users/me/templates/import', data)
+ },
+}
diff --git a/web/src/api/types.ts b/web/src/api/types.ts
new file mode 100644
index 0000000..aee06c7
--- /dev/null
+++ b/web/src/api/types.ts
@@ -0,0 +1,546 @@
+// API Response types
+export interface ApiResponse<T> {
+ success: boolean
+ data: T
+ error?: ApiError
+}
+
+export interface ApiError {
+ code: string
+ message: string
+ error: string
+}
+
+export interface Pageable {
+ current_page: number
+ size: number
+ total_pages: number
+ total_elements: number
+ empty: boolean
+}
+
+export interface PaginatedResponse<T> {
+ success: boolean
+ data: T[]
+ pageable: Pageable
+}
+
+// Models
+export interface User {
+ id: number
+ name: string
+ email: string
+ role: 'admin' | 'user'
+ active: boolean
+ two_factor_enabled: boolean
+ created_at: string
+ last_login_at: string | null
+}
+
+export interface AuthResponse {
+ token: string
+ user: User
+}
+
+export interface Email {
+ id: number
+ uuid: string
+ user_id: number
+ api_key_id: number
+ smtp_hostname: string | null
+ sender: string
+ recipients: string[]
+ subject: string
+ html_body: string
+ text_body: string
+ attachments_json: string
+ headers_json: string
+ list_unsubscribe_url: string
+ list_unsubscribe_post: boolean
+ status: 'pending' | 'queued' | 'processing' | 'sent' | 'failed' | 'suppressed' | 'scheduled'
+ error_message: string
+ retry_count: number
+ created_at: string
+ sent_at: string | null
+ scheduled_at: string | null
+}
+
+export interface ApiKey {
+ id: number
+ user_id: number
+ name: string
+ key_prefix: string
+ created_at: string
+ expires_at: string | null
+ last_used_at: string | null
+ revoked: boolean
+ allowed_ips: string[] | null
+}
+
+export interface Contact {
+ id: number
+ user_id: number
+ email: string
+ name: string
+ sent_count: number
+ fail_count: number
+ suppressed: boolean
+ last_sent_at: string | null
+ created_at: string
+}
+
+export interface ApiKeyCreateResponse {
+ key: string
+ id: number
+ name: string
+ prefix: string
+ expires_at: string | null
+ message: string
+}
+
+export interface Template {
+ id: number
+ user_id: number
+ name: string
+ default_language: string
+ active_version_id?: number | null
+ description: string
+ active_version?: TemplateVersion | null
+ sample_data: string
+ created_at: string
+ updated_at?: string
+}
+
+export interface TemplateInput {
+ name: string
+ sample_data?: string
+ default_language?: string
+ description?: string
+}
+
+export interface TemplateExportLocalization {
+ language: string
+ subject_template: string
+ html_template: string
+ text_template: string
+}
+
+export interface TemplateExportVersion {
+ version: number
+ sample_data: string
+ is_active: boolean
+ localizations: TemplateExportLocalization[]
+}
+
+export interface TemplateExport {
+ posta_version?: string
+ exported_at?: string
+ name: string
+ description: string
+ default_language: string
+ sample_data: string
+ versions: TemplateExportVersion[]
+}
+
+export interface TemplatePreview {
+ subject: string
+ html: string
+ text: string
+}
+
+export interface SendTestInput {
+ to: string[]
+ from?: string
+ language?: string
+ template_data?: Record<string, any>
+}
+
+export interface SendTestResponse {
+ id: string
+ status: string
+}
+
+export interface TemplateVersion {
+ id: number
+ template_id: number
+ version: number
+ stylesheet_id?: number | null
+ stylesheet?: StyleSheet | null
+ sample_data: string
+ created_at: string
+}
+
+export interface TemplateVersionInput {
+ stylesheet_id?: number | null
+ sample_data?: string
+}
+
+export interface TemplateLocalization {
+ id: number
+ version_id: number
+ language: string
+ subject_template: string
+ html_template: string
+ text_template: string
+ created_at: string
+ updated_at?: string
+}
+
+export interface TemplateLocalizationInput {
+ language: string
+ subject_template: string
+ html_template: string
+ text_template: string
+}
+
+export interface Language {
+ id: number
+ user_id: number
+ code: string
+ name: string
+ created_at: string
+}
+
+export interface LanguageInput {
+ code: string
+ name: string
+}
+
+export interface StyleSheet {
+ id: number
+ user_id: number
+ name: string
+ css: string
+ created_at: string
+ updated_at?: string
+}
+
+export interface StyleSheetInput {
+ name: string
+ css: string
+}
+
+export type ServerStatus = 'enabled' | 'disabled' | 'invalid'
+
+export interface SharedServer {
+ id: number
+ name: string
+ host: string
+ port: number
+ username: string
+ encryption: 'none' | 'starttls' | 'ssl'
+ max_retries: number
+ status: ServerStatus
+ allowed_domains: string[]
+ security_mode: 'permissive' | 'strict'
+ sent_count: number
+ failed_count: number
+ validation_error: string
+ validated_at: string | null
+ created_at: string
+ updated_at: string
+}
+
+export interface SharedServerInput {
+ name: string
+ host: string
+ port: number
+ username?: string
+ password?: string
+ encryption?: 'none' | 'starttls' | 'ssl'
+ max_retries?: number
+ status?: ServerStatus
+ allowed_domains?: string[]
+ security_mode?: 'permissive' | 'strict'
+}
+
+export interface SmtpServer {
+ id: number
+ user_id: number
+ host: string
+ port: number
+ username: string
+ password: string
+ encryption: 'none' | 'starttls' | 'ssl'
+ max_retries: number
+ allowed_emails: string[]
+ status: ServerStatus
+ validation_error: string
+ validated_at: string | null
+ created_at: string
+}
+
+export interface SmtpServerInput {
+ host: string
+ port: number
+ username: string
+ password: string
+ encryption: 'none' | 'starttls' | 'ssl'
+ max_retries?: number
+ allowed_emails?: string[]
+ status?: ServerStatus
+}
+
+export interface Domain {
+ id: number
+ user_id: number
+ domain: string
+ ownership_verified: boolean
+ spf_verified: boolean
+ dkim_verified: boolean
+ dmarc_verified: boolean
+ verification_token: string
+ created_at: string
+ dns_records?: DnsRecords
+}
+
+export interface DnsRecords {
+ verification: DnsRecord
+ spf: DnsRecord
+ dkim: DnsRecord
+ dmarc: DnsRecord
+}
+
+export interface DnsRecord {
+ type: string
+ name: string
+ value: string
+}
+
+export interface Webhook {
+ id: number
+ user_id: number
+ url: string
+ events: string[]
+ filters: string[] | null
+ secret?: string
+ created_at: string
+}
+
+export interface WebhookInput {
+ url: string
+ events: string[]
+ filters: string[]
+}
+
+export interface Bounce {
+ id: number
+ user_id: number
+ email_id: number
+ recipient: string
+ type: 'hard' | 'soft' | 'complaint'
+ reason: string
+ created_at: string
+}
+
+export interface Suppression {
+ id: number
+ user_id: number
+ email: string
+ reason: string
+ created_at: string
+}
+
+export interface WebhookDelivery {
+ id: number
+ webhook_id: number
+ user_id: number
+ event: string
+ status: 'success' | 'failed'
+ http_status_code: number
+ error_message?: string
+ attempt: number
+ created_at: string
+}
+
+export interface WebhookDeliveryStats {
+ total_deliveries: number
+ success_deliveries: number
+ failed_deliveries: number
+ success_rate: number
+}
+
+export interface DashboardStats {
+ total_emails: number
+ queued_emails: number
+ processing_emails: number
+ sent_emails: number
+ failed_emails: number
+ suppressed_emails: number
+ failure_rate: number
+ total_domains: number
+ total_smtp_servers: number
+ total_api_keys: number
+ active_api_keys: number
+ total_contacts: number
+ total_bounces: number
+ total_suppressions: number
+ total_webhooks: number
+ total_contact_lists: number
+ daily_volume: DailyVolume[]
+ webhook_deliveries: WebhookDeliveryStats | null
+}
+
+export interface DailyVolume {
+ date: string
+ sent: number
+ failed: number
+}
+
+export interface AdminMetrics {
+ total_users: number
+ total_emails: number
+ queued_emails: number
+ processing_emails: number
+ sent_emails: number
+ failed_emails: number
+ suppressed_emails: number
+ failure_rate: number
+ total_api_keys: number
+ active_api_keys: number
+ total_bounces: number
+ total_suppressions: number
+ active_workers: number
+ shared_smtp_servers: number
+ total_domains: number
+ webhook_deliveries: WebhookDeliveryStats | null
+}
+
+export interface WorkerStatus {
+ active_workers: number
+ workers: WorkerDetail[]
+}
+
+export interface WorkerDetail {
+ host: string
+ pid: number
+ queues: Record<string, number>
+ type: 'embedded' | 'standalone'
+}
+
+export interface Event {
+ id: number
+ category: 'user' | 'email' | 'system'
+ type: string
+ actor_id: number | null
+ actor_name: string
+ client_ip?: string
+ message: string
+ metadata: string
+ created_at: string
+}
+
+export interface UserDetailMetrics {
+ user: User
+ total_emails: number
+ sent_emails: number
+ failed_emails: number
+ suppressed_emails: number
+ failure_rate: number
+ total_api_keys: number
+ active_api_keys: number
+ total_contacts: number
+ total_bounces: number
+ total_suppressions: number
+ total_domains: number
+ total_smtp_servers: number
+ webhook_deliveries: WebhookDeliveryStats | null
+}
+
+// Analytics
+export interface DailyCount {
+ date: string
+ count: number
+}
+
+export interface StatusBreakdown {
+ status: string
+ count: number
+}
+
+export interface AnalyticsResponse {
+ daily_counts: DailyCount[]
+ status_breakdown: StatusBreakdown[]
+}
+
+// Contact Lists
+export interface ContactList {
+ id: number
+ user_id: number
+ name: string
+ description: string
+ created_at: string
+ updated_at: string
+}
+
+export interface ContactListWithCount extends ContactList {
+ member_count: number
+}
+
+export interface ContactListMember {
+ id: number
+ list_id: number
+ email: string
+ name: string
+ created_at: string
+}
+
+// Settings
+export interface AdminSetting {
+ id: number
+ key: string
+ value: string
+ type: 'string' | 'int' | 'bool'
+ created_at: string
+ updated_at: string
+}
+
+export interface AdminSettingInput {
+ key: string
+ value: string
+ type: string
+}
+
+export interface UserSettings {
+ id: number
+ user_id: number
+ timezone: string
+ default_sender_name: string
+ default_sender_email: string
+ email_notifications: boolean
+ notification_email: string
+ webhook_retry_count: number
+ default_template_id: number | null
+ api_key_expiry_days: number
+ bounce_auto_suppress: boolean
+ daily_report: boolean
+ created_at: string
+ updated_at: string
+}
+
+// Cron Jobs
+export interface CronJob {
+ name: string
+ schedule: string
+ running: boolean
+ last_run_at: string | null
+ last_error?: string
+ next_run_at: string | null
+}
+
+// 2FA
+export interface Setup2FAResponse {
+ secret: string
+ url: string
+}
+
+// User Profile (extended)
+export interface UserProfile {
+ id: number
+ name: string
+ email: string
+ role: 'admin' | 'user'
+ two_factor_enabled: boolean
+ require_verified_domain: boolean
+ created_at: string
+}
diff --git a/web/src/api/webhooks.ts b/web/src/api/webhooks.ts
new file mode 100644
index 0000000..c220e7a
--- /dev/null
+++ b/web/src/api/webhooks.ts
@@ -0,0 +1,20 @@
+import api from './client'
+import type { ApiResponse, PaginatedResponse, Webhook, WebhookDelivery, WebhookInput } from './types'
+
+export const webhooksApi = {
+ list(page = 0, size = 20) {
+ return api.get<PaginatedResponse<Webhook>>('/users/me/webhooks', { params: { page, size } })
+ },
+ create(data: WebhookInput) {
+ return api.post<ApiResponse<Webhook>>('/users/me/webhooks', data)
+ },
+ delete(id: number) {
+ return api.delete(`/users/me/webhooks/${id}`)
+ },
+}
+
+export const webhookDeliveriesApi = {
+ list(page = 0, size = 20) {
+ return api.get<PaginatedResponse<WebhookDelivery>>('/users/me/webhook-deliveries', { params: { page, size } })
+ },
+}
diff --git a/web/src/assets/styles.css b/web/src/assets/styles.css
new file mode 100644
index 0000000..d45a7a5
--- /dev/null
+++ b/web/src/assets/styles.css
@@ -0,0 +1,532 @@
+/* ─── Light Theme (default) ─── */
+:root,
+[data-theme="light"] {
+ --primary-50: #faf5ff;
+ --primary-100: #f3e8ff;
+ --primary-200: #e9d5ff;
+ --primary-300: #d8b4fe;
+ --primary-400: #c084fc;
+ --primary-500: #a855f7;
+ --primary-600: #9333ea;
+ --primary-700: #7e22ce;
+ --primary-800: #6b21a8;
+ --primary-900: #581c87;
+
+ --success-50: #f0fdf4;
+ --success-500: #22c55e;
+ --success-600: #16a34a;
+ --success-700: #15803d;
+
+ --warning-50: #fffbeb;
+ --warning-500: #f59e0b;
+ --warning-600: #d97706;
+
+ --danger-50: #fef2f2;
+ --danger-500: #ef4444;
+ --danger-600: #dc2626;
+ --danger-700: #b91c1c;
+
+ /* Semantic tokens */
+ --bg-primary: #ffffff;
+ --bg-secondary: #f9fafb;
+ --bg-tertiary: #f3f4f6;
+ --bg-hover: #f3f4f6;
+ --bg-active: #e9d5ff;
+ --bg-input: #ffffff;
+ --bg-sidebar: #111827;
+ --bg-code: #1e1b2e;
+
+ --border-primary: #e5e7eb;
+ --border-secondary: #f3f4f6;
+ --border-input: #d1d5db;
+ --border-focus: #a855f7;
+
+ --text-primary: #111827;
+ --text-secondary: #4b5563;
+ --text-tertiary: #6b7280;
+ --text-muted: #9ca3af;
+ --text-inverse: #ffffff;
+ --text-on-primary: #ffffff;
+
+ --shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.04);
+ --shadow: 0 1px 3px rgba(0, 0, 0, 0.08), 0 1px 2px rgba(0, 0, 0, 0.04);
+ --shadow-md: 0 4px 6px rgba(0, 0, 0, 0.06), 0 2px 4px rgba(0, 0, 0, 0.04);
+ --shadow-lg: 0 10px 25px rgba(0, 0, 0, 0.08), 0 4px 10px rgba(0, 0, 0, 0.04);
+ --shadow-focus: 0 0 0 3px rgba(147, 51, 234, 0.15);
+
+ --overlay: rgba(0, 0, 0, 0.45);
+ --sidebar-hover: rgba(255, 255, 255, 0.06);
+ --sidebar-border: rgba(255, 255, 255, 0.08);
+ --sidebar-text: #9ca3af;
+ --sidebar-text-active: #ffffff;
+}
+
+/* ─── Dark Theme ─── */
+[data-theme="dark"] {
+ --bg-primary: #1a1a2e;
+ --bg-secondary: #16162a;
+ --bg-tertiary: #1e1e36;
+ --bg-hover: #252542;
+ --bg-active: #2d1b5e;
+ --bg-input: #1e1e36;
+ --bg-sidebar: #0f0f1e;
+ --bg-code: #0d0d1a;
+
+ --border-primary: #2a2a45;
+ --border-secondary: #222240;
+ --border-input: #3a3a55;
+ --border-focus: #a855f7;
+
+ --text-primary: #e8e8f0;
+ --text-secondary: #b0b0c8;
+ --text-tertiary: #8888a8;
+ --text-muted: #666680;
+ --text-inverse: #111827;
+ --text-on-primary: #ffffff;
+
+ --shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.2);
+ --shadow: 0 1px 3px rgba(0, 0, 0, 0.3), 0 1px 2px rgba(0, 0, 0, 0.2);
+ --shadow-md: 0 4px 6px rgba(0, 0, 0, 0.3), 0 2px 4px rgba(0, 0, 0, 0.2);
+ --shadow-lg: 0 10px 25px rgba(0, 0, 0, 0.4), 0 4px 10px rgba(0, 0, 0, 0.3);
+ --shadow-focus: 0 0 0 3px rgba(147, 51, 234, 0.3);
+
+ --overlay: rgba(0, 0, 0, 0.65);
+ --sidebar-hover: rgba(255, 255, 255, 0.05);
+ --sidebar-border: rgba(255, 255, 255, 0.06);
+ --sidebar-text: #8888a8;
+ --sidebar-text-active: #e8e8f0;
+
+ --success-50: #0d2818;
+ --warning-50: #2d1f0a;
+ --danger-50: #2d0f0f;
+ --primary-50: #1e0d30;
+}
+
+/* ─── Shared tokens ─── */
+:root {
+ --radius-sm: 6px;
+ --radius: 8px;
+ --radius-md: 10px;
+ --radius-lg: 12px;
+ --radius-xl: 16px;
+ --transition: 150ms ease;
+ --transition-slow: 250ms ease;
+ color-scheme: light dark;
+}
+
+/* ─── Reset ─── */
+*, *::before, *::after { margin: 0; padding: 0; box-sizing: border-box; }
+
+body {
+ font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
+ color: var(--text-primary);
+ background: var(--bg-secondary);
+ line-height: 1.6;
+ -webkit-font-smoothing: antialiased;
+ -moz-osx-font-smoothing: grayscale;
+ transition: background var(--transition-slow), color var(--transition-slow);
+}
+
+a { color: var(--primary-500); text-decoration: none; }
+a:hover { color: var(--primary-600); }
+
+/* ─── Buttons ─── */
+.btn {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 8px;
+ padding: 9px 18px;
+ border: 1px solid transparent;
+ border-radius: var(--radius);
+ font-size: 14px;
+ font-weight: 500;
+ cursor: pointer;
+ transition: all var(--transition);
+ line-height: 1.4;
+ white-space: nowrap;
+ font-family: inherit;
+}
+.btn:disabled { opacity: 0.5; cursor: not-allowed; }
+
+.btn-primary {
+ background: var(--primary-600);
+ color: var(--text-on-primary);
+ border-color: var(--primary-600);
+}
+.btn-primary:hover:not(:disabled) {
+ background: var(--primary-700);
+ border-color: var(--primary-700);
+}
+
+.btn-secondary {
+ background: var(--bg-primary);
+ color: var(--text-secondary);
+ border-color: var(--border-input);
+}
+.btn-secondary:hover:not(:disabled) {
+ background: var(--bg-hover);
+ border-color: var(--text-muted);
+}
+
+.btn-danger {
+ background: var(--danger-600);
+ color: #fff;
+ border-color: var(--danger-600);
+}
+.btn-danger:hover:not(:disabled) {
+ background: var(--danger-700);
+ border-color: var(--danger-700);
+}
+
+.btn-ghost {
+ background: transparent;
+ color: var(--text-tertiary);
+}
+.btn-ghost:hover:not(:disabled) {
+ background: var(--bg-hover);
+ color: var(--text-secondary);
+}
+
+.btn-sm { padding: 6px 12px; font-size: 13px; }
+.btn-icon { padding: 8px; border-radius: var(--radius-sm); }
+
+/* ─── Form Elements ─── */
+.form-group { margin-bottom: 20px; }
+
+.form-label {
+ display: block;
+ font-size: 13px;
+ font-weight: 500;
+ color: var(--text-secondary);
+ margin-bottom: 6px;
+}
+
+.form-input,
+.form-select,
+.form-textarea {
+ width: 100%;
+ padding: 10px 14px;
+ border: 1px solid var(--border-input);
+ border-radius: var(--radius);
+ font-size: 14px;
+ font-family: inherit;
+ color: var(--text-primary);
+ background: var(--bg-input);
+ transition: border-color var(--transition), box-shadow var(--transition);
+ outline: none;
+}
+
+.form-input:focus,
+.form-select:focus,
+.form-textarea:focus {
+ border-color: var(--border-focus);
+ box-shadow: var(--shadow-focus);
+}
+
+.form-input::placeholder,
+.form-textarea::placeholder { color: var(--text-muted); }
+
+.form-textarea {
+ min-height: 100px;
+ resize: vertical;
+ font-family: 'JetBrains Mono', 'Fira Code', 'Cascadia Code', monospace;
+ font-size: 13px;
+}
+
+.form-hint { font-size: 12px; color: var(--text-muted); margin-top: 4px; }
+.form-error { font-size: 12px; color: var(--danger-500); margin-top: 4px; }
+
+/* ─── Cards ─── */
+.card {
+ background: var(--bg-primary);
+ border: 1px solid var(--border-primary);
+ border-radius: var(--radius-lg);
+ box-shadow: var(--shadow-sm);
+ transition: background var(--transition-slow), border-color var(--transition-slow);
+}
+
+.card-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 18px 24px;
+ border-bottom: 1px solid var(--border-primary);
+}
+.card-header h2 { font-size: 15px; font-weight: 600; color: var(--text-primary); }
+
+.card-body { padding: 24px; }
+
+/* ─── Tables ─── */
+.table-wrapper { overflow-x: auto; }
+table { width: 100%; border-collapse: collapse; }
+
+th {
+ text-align: left;
+ padding: 11px 16px;
+ font-size: 11px;
+ font-weight: 600;
+ color: var(--text-muted);
+ text-transform: uppercase;
+ letter-spacing: 0.06em;
+ background: var(--bg-tertiary);
+ border-bottom: 1px solid var(--border-primary);
+}
+
+td {
+ padding: 13px 16px;
+ font-size: 14px;
+ border-bottom: 1px solid var(--border-secondary);
+ color: var(--text-secondary);
+}
+
+tr { transition: background var(--transition); }
+tr:hover td { background: var(--bg-hover); }
+
+/* ─── Badges ─── */
+.badge {
+ display: inline-flex;
+ align-items: center;
+ padding: 3px 10px;
+ border-radius: 9999px;
+ font-size: 12px;
+ font-weight: 500;
+ letter-spacing: 0.01em;
+}
+
+.badge-success { background: var(--success-50); color: var(--success-600); }
+.badge-danger { background: var(--danger-50); color: var(--danger-600); }
+.badge-warning { background: var(--warning-50); color: var(--warning-600); }
+.badge-info { background: var(--primary-50); color: var(--primary-500); }
+.badge-neutral { background: var(--bg-tertiary); color: var(--text-tertiary); }
+.badge-secondary { background: var(--bg-tertiary); color: var(--text-secondary); }
+
+/* ─── Stats ─── */
+.stats-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
+ gap: 18px;
+ margin-bottom: 28px;
+}
+
+.stat-card {
+ background: var(--bg-primary);
+ border: 1px solid var(--border-primary);
+ border-radius: var(--radius-lg);
+ padding: 22px 24px;
+ box-shadow: var(--shadow-sm);
+ transition: background var(--transition-slow), border-color var(--transition-slow), transform var(--transition);
+}
+.stat-card:hover { transform: translateY(-1px); box-shadow: var(--shadow); }
+.stat-card .stat-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 8px; }
+.stat-card .stat-label { font-size: 13px; color: var(--text-muted); font-weight: 500; }
+.stat-card .stat-value { font-size: 28px; font-weight: 700; color: var(--text-primary); letter-spacing: -0.02em; }
+.stat-card .stat-sub { font-size: 12px; color: var(--text-muted); margin-top: 4px; }
+.stat-card .stat-icon { display: flex; align-items: center; justify-content: center; width: 36px; height: 36px; border-radius: var(--radius); flex-shrink: 0; }
+.stat-icon-primary { background: var(--primary-50); color: var(--primary-600); }
+.stat-icon-success { background: var(--success-50); color: var(--success-600); }
+.stat-icon-danger { background: var(--danger-50); color: var(--danger-600); }
+.stat-icon-warning { background: var(--warning-50); color: var(--warning-600); }
+.stat-icon-secondary { background: var(--bg-tertiary); color: var(--text-secondary); }
+.stat-icon-info { background: var(--primary-50); color: var(--primary-500); }
+
+/* ─── Page Headers ─── */
+.page-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ margin-bottom: 28px;
+}
+.page-header h1 { font-size: 22px; font-weight: 700; color: var(--text-primary); letter-spacing: -0.02em; }
+
+/* ─── Pagination ─── */
+.pagination {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 14px 24px;
+ border-top: 1px solid var(--border-primary);
+}
+.pagination-info { font-size: 13px; color: var(--text-muted); }
+.pagination-buttons { display: flex; gap: 8px; }
+
+/* ─── Modal ─── */
+.modal-overlay {
+ position: fixed;
+ inset: 0;
+ background: var(--overlay);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ z-index: 1000;
+ padding: 20px;
+ backdrop-filter: blur(4px);
+ animation: fadeIn 150ms ease;
+}
+
+.modal {
+ background: var(--bg-primary);
+ border: 1px solid var(--border-primary);
+ border-radius: var(--radius-xl);
+ box-shadow: var(--shadow-lg);
+ width: 100%;
+ max-width: 520px;
+ max-height: 90vh;
+ overflow-y: auto;
+ animation: modalSlideUp 200ms ease;
+}
+
+.modal-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 20px 24px;
+ border-bottom: 1px solid var(--border-primary);
+}
+.modal-header h3 { font-size: 16px; font-weight: 600; color: var(--text-primary); }
+
+.modal-body { padding: 24px; }
+
+.modal-footer {
+ display: flex;
+ justify-content: flex-end;
+ gap: 10px;
+ padding: 16px 24px;
+ border-top: 1px solid var(--border-primary);
+}
+
+@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
+@keyframes modalSlideUp { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
+
+/* ─── Notification Toast ─── */
+.toast-container {
+ position: fixed;
+ top: 20px;
+ right: 20px;
+ z-index: 2000;
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+}
+
+.toast {
+ padding: 14px 20px;
+ border-radius: var(--radius);
+ font-size: 14px;
+ font-weight: 500;
+ box-shadow: var(--shadow-md);
+ animation: slideIn 200ms ease;
+ min-width: 280px;
+ max-width: 420px;
+ cursor: pointer;
+}
+.toast-success { background: var(--success-600); color: #fff; }
+.toast-error { background: var(--danger-600); color: #fff; }
+.toast-info { background: var(--primary-600); color: #fff; }
+
+@keyframes slideIn { from { transform: translateX(100%); opacity: 0; } to { transform: translateX(0); opacity: 1; } }
+
+/* ─── Empty State ─── */
+.empty-state { text-align: center; padding: 60px 24px; color: var(--text-muted); }
+.empty-state h3 { font-size: 16px; font-weight: 600; color: var(--text-tertiary); margin-bottom: 6px; }
+.empty-state p { font-size: 14px; }
+
+/* ─── Loading ─── */
+.spinner {
+ width: 18px;
+ height: 18px;
+ border: 2px solid var(--border-primary);
+ border-top-color: var(--primary-500);
+ border-radius: 50%;
+ animation: spin 0.6s linear infinite;
+}
+@keyframes spin { to { transform: rotate(360deg); } }
+
+.loading-page { display: flex; align-items: center; justify-content: center; min-height: 300px; }
+
+/* ─── Checkbox ─── */
+.checkbox-label {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ font-size: 14px;
+ color: var(--text-secondary);
+ cursor: pointer;
+}
+.checkbox-label input[type="checkbox"] { width: 16px; height: 16px; accent-color: var(--primary-600); }
+
+/* ─── Code block ─── */
+.code-block {
+ background: var(--bg-code);
+ color: #d4d4f8;
+ padding: 14px 18px;
+ border-radius: var(--radius);
+ font-family: 'JetBrains Mono', 'Fira Code', 'Cascadia Code', monospace;
+ font-size: 13px;
+ overflow-x: auto;
+ user-select: all;
+ border: 1px solid var(--border-primary);
+}
+
+/* ─── DNS Records ─── */
+.dns-record {
+ background: var(--bg-tertiary);
+ border: 1px solid var(--border-primary);
+ border-radius: var(--radius);
+ padding: 14px 16px;
+ margin-bottom: 10px;
+}
+.dns-record .dns-label { font-size: 12px; font-weight: 600; color: var(--text-secondary); margin-bottom: 4px; }
+.dns-record .dns-type { font-size: 11px; font-weight: 700; color: var(--primary-500); text-transform: uppercase; letter-spacing: 0.06em; }
+.dns-record .dns-name { font-size: 13px; color: var(--text-tertiary); margin-top: 2px; }
+.dns-record .dns-value { font-size: 13px; font-family: 'JetBrains Mono', monospace; color: var(--text-primary); margin-top: 6px; word-break: break-all; }
+.dns-record-highlight { border-color: var(--primary-300); background: var(--primary-50, rgba(79, 70, 229, 0.04)); }
+
+/* ─── Status ─── */
+.verified { color: var(--success-600); }
+.unverified { color: var(--text-muted); }
+
+/* ─── Tabs ─── */
+.tabs {
+ display: flex;
+ gap: 4px;
+ margin-bottom: 24px;
+ background: var(--bg-tertiary);
+ padding: 4px;
+ border-radius: var(--radius);
+ width: fit-content;
+}
+.tab {
+ padding: 7px 16px;
+ border-radius: var(--radius-sm);
+ font-size: 13px;
+ font-weight: 500;
+ cursor: pointer;
+ border: none;
+ background: transparent;
+ color: var(--text-tertiary);
+ transition: all var(--transition);
+ font-family: inherit;
+}
+.tab:hover { color: var(--text-primary); }
+.tab.active { background: var(--bg-primary); color: var(--text-primary); box-shadow: var(--shadow-sm); }
+
+/* ─── Utilities ─── */
+.text-center { text-align: center; }
+.text-right { text-align: right; }
+.text-sm { font-size: 13px; }
+.text-muted { color: var(--text-muted); }
+.mt-4 { margin-top: 16px; }
+.mb-4 { margin-bottom: 16px; }
+.flex { display: flex; }
+.items-center { align-items: center; }
+.justify-between { justify-content: space-between; }
+.gap-2 { gap: 8px; }
+.gap-3 { gap: 12px; }
+.truncate { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+
+/* ─── Scrollbar ─── */
+::-webkit-scrollbar { width: 6px; height: 6px; }
+::-webkit-scrollbar-track { background: transparent; }
+::-webkit-scrollbar-thumb { background: var(--text-muted); border-radius: 3px; }
+::-webkit-scrollbar-thumb:hover { background: var(--text-tertiary); }
diff --git a/web/src/components/ConfirmDialog.vue b/web/src/components/ConfirmDialog.vue
new file mode 100644
index 0000000..7424ff2
--- /dev/null
+++ b/web/src/components/ConfirmDialog.vue
@@ -0,0 +1,101 @@
+<script setup lang="ts">
+import { useConfirm } from '../composables/useConfirm'
+
+const { visible, options, handleConfirm, handleCancel } = useConfirm()
+
+function onKeydown(e: KeyboardEvent) {
+ if (e.key === 'Escape') handleCancel()
+}
+</script>
+
+<template>
+ <Teleport to="body">
+ <div v-if="visible" class="modal-overlay" @click.self="handleCancel" @keydown="onKeydown">
+ <div class="modal confirm-dialog" role="alertdialog" aria-modal="true">
+ <div class="modal-header">
+ <div class="confirm-header-content">
+ <div class="confirm-icon" :class="`confirm-icon-${options.variant}`">
+ <!-- Danger icon -->
+ <svg v-if="options.variant === 'danger'" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
+ <circle cx="12" cy="12" r="10" />
+ <line x1="15" y1="9" x2="9" y2="15" />
+ <line x1="9" y1="9" x2="15" y2="15" />
+ </svg>
+ <!-- Warning icon -->
+ <svg v-else-if="options.variant === 'warning'" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
+ <path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z" />
+ <line x1="12" y1="9" x2="12" y2="13" />
+ <line x1="12" y1="17" x2="12.01" y2="17" />
+ </svg>
+ <!-- Info icon -->
+ <svg v-else width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
+ <circle cx="12" cy="12" r="10" />
+ <line x1="12" y1="16" x2="12" y2="12" />
+ <line x1="12" y1="8" x2="12.01" y2="8" />
+ </svg>
+ </div>
+ <h3>{{ options.title }}</h3>
+ </div>
+ </div>
+ <div class="modal-body">
+ <p class="confirm-message">{{ options.message }}</p>
+ </div>
+ <div class="modal-footer">
+ <button class="btn btn-secondary" @click="handleCancel" ref="cancelBtn">
+ {{ options.cancelText }}
+ </button>
+ <button
+ class="btn"
+ :class="options.variant === 'danger' ? 'btn-danger' : options.variant === 'warning' ? 'btn-primary' : 'btn-primary'"
+ @click="handleConfirm"
+ >
+ {{ options.confirmText }}
+ </button>
+ </div>
+ </div>
+ </div>
+ </Teleport>
+</template>
+
+<style scoped>
+.confirm-dialog {
+ max-width: 440px;
+}
+
+.confirm-header-content {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+}
+
+.confirm-icon {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 38px;
+ height: 38px;
+ border-radius: 10px;
+ flex-shrink: 0;
+}
+
+.confirm-icon-danger {
+ background: var(--danger-50);
+ color: var(--danger-600);
+}
+
+.confirm-icon-warning {
+ background: var(--warning-50);
+ color: var(--warning-600);
+}
+
+.confirm-icon-info {
+ background: var(--primary-50);
+ color: var(--primary-600);
+}
+
+.confirm-message {
+ font-size: 14px;
+ color: var(--text-secondary);
+ line-height: 1.6;
+}
+</style>
diff --git a/web/src/components/Pagination.vue b/web/src/components/Pagination.vue
new file mode 100644
index 0000000..563796f
--- /dev/null
+++ b/web/src/components/Pagination.vue
@@ -0,0 +1,78 @@
+<script setup lang="ts">
+import { computed } from 'vue'
+import type { Pageable } from '../api/types'
+
+const props = defineProps<{
+ pageable: Pageable
+}>()
+
+const emit = defineEmits<{
+ (e: 'page', page: number): void
+}>()
+
+const currentPage = computed(() => props.pageable.current_page)
+const totalPages = computed(() => props.pageable.total_pages)
+
+const visiblePages = computed(() => {
+ const total = totalPages.value
+ const current = currentPage.value
+ if (total <= 7) return Array.from({ length: total }, (_, i) => i)
+
+ const pages: (number | null)[] = [0]
+ const start = Math.max(1, current - 1)
+ const end = Math.min(total - 2, current + 1)
+
+ if (start > 1) pages.push(null)
+ for (let i = start; i <= end; i++) pages.push(i)
+ if (end < total - 2) pages.push(null)
+ pages.push(total - 1)
+
+ return pages
+})
+</script>
+
+<template>
+ <div v-if="totalPages > 1" class="pagination">
+ <span class="pagination-info">
+ Page {{ currentPage + 1 }} of {{ totalPages }}
+ ({{ pageable.total_elements }} total)
+ </span>
+ <div class="pagination-buttons">
+ <button
+ class="btn btn-secondary btn-sm"
+ :disabled="currentPage === 0"
+ @click="emit('page', currentPage - 1)"
+ >
+ Previous
+ </button>
+ <template v-for="(p, idx) in visiblePages" :key="idx">
+ <span v-if="p === null" class="pagination-ellipsis">...</span>
+ <button
+ v-else
+ class="btn btn-sm"
+ :class="p === currentPage ? 'btn-primary' : 'btn-secondary'"
+ @click="emit('page', p)"
+ >
+ {{ p + 1 }}
+ </button>
+ </template>
+ <button
+ class="btn btn-secondary btn-sm"
+ :disabled="currentPage >= totalPages - 1"
+ @click="emit('page', currentPage + 1)"
+ >
+ Next
+ </button>
+ </div>
+ </div>
+</template>
+
+<style scoped>
+.pagination-ellipsis {
+ display: inline-flex;
+ align-items: center;
+ padding: 0 4px;
+ color: var(--text-muted);
+ font-size: 13px;
+}
+</style>
diff --git a/web/src/composables/useConfirm.ts b/web/src/composables/useConfirm.ts
new file mode 100644
index 0000000..5d03839
--- /dev/null
+++ b/web/src/composables/useConfirm.ts
@@ -0,0 +1,55 @@
+import { ref } from 'vue'
+
+export interface ConfirmOptions {
+ title: string
+ message: string
+ confirmText?: string
+ cancelText?: string
+ variant?: 'danger' | 'warning' | 'info'
+}
+
+const visible = ref(false)
+const options = ref<ConfirmOptions>({
+ title: '',
+ message: '',
+ confirmText: 'Confirm',
+ cancelText: 'Cancel',
+ variant: 'danger',
+})
+
+let resolvePromise: ((value: boolean) => void) | null = null
+
+export function useConfirm() {
+ function confirm(opts: ConfirmOptions): Promise<boolean> {
+ options.value = {
+ confirmText: 'Confirm',
+ cancelText: 'Cancel',
+ variant: 'danger',
+ ...opts,
+ }
+ visible.value = true
+ return new Promise<boolean>((resolve) => {
+ resolvePromise = resolve
+ })
+ }
+
+ function handleConfirm() {
+ visible.value = false
+ resolvePromise?.(true)
+ resolvePromise = null
+ }
+
+ function handleCancel() {
+ visible.value = false
+ resolvePromise?.(false)
+ resolvePromise = null
+ }
+
+ return {
+ visible,
+ options,
+ confirm,
+ handleConfirm,
+ handleCancel,
+ }
+}
diff --git a/web/src/composables/usePagination.ts b/web/src/composables/usePagination.ts
new file mode 100644
index 0000000..05ef5e5
--- /dev/null
+++ b/web/src/composables/usePagination.ts
@@ -0,0 +1,21 @@
+import { ref, onMounted } from 'vue'
+import { useRoute, useRouter } from 'vue-router'
+import type { Pageable } from '../api/types'
+
+export function usePagination(fetchFn: (page: number) => Promise<void>) {
+ const route = useRoute()
+ const router = useRouter()
+ const pageable = ref<Pageable>({ current_page: 0, size: 20, total_pages: 0, total_elements: 0, empty: true })
+
+ function goToPage(page: number) {
+ router.replace({ query: { ...route.query, page: page > 0 ? String(page + 1) : undefined } })
+ fetchFn(page)
+ }
+
+ onMounted(() => {
+ const p = Number(route.query.page)
+ fetchFn(p > 0 ? p - 1 : 0)
+ })
+
+ return { pageable, goToPage }
+}
diff --git a/web/src/layouts/DashboardLayout.vue b/web/src/layouts/DashboardLayout.vue
new file mode 100644
index 0000000..5ae5f41
--- /dev/null
+++ b/web/src/layouts/DashboardLayout.vue
@@ -0,0 +1,563 @@
+<script setup lang="ts">
+import { computed, ref, onMounted, onBeforeUnmount } from 'vue'
+import { useRouter, useRoute } from 'vue-router'
+import { useAuthStore } from '../stores/auth'
+import { useThemeStore } from '../stores/theme'
+import { infoApi, type AppInfo } from '../api/info'
+
+const router = useRouter()
+const route = useRoute()
+const auth = useAuthStore()
+const theme = useThemeStore()
+const sidebarCollapsed = ref(false)
+const appInfo = ref<AppInfo | null>(null)
+const userMenuOpen = ref(false)
+const themeModes = ['light', 'dark', 'system'] as const
+
+function closeUserMenu(e: MouseEvent) {
+ const el = document.querySelector('.user-menu')
+ if (el && !el.contains(e.target as Node)) {
+ userMenuOpen.value = false
+ }
+}
+
+onMounted(() => {
+ document.addEventListener('click', closeUserMenu)
+})
+onBeforeUnmount(() => {
+ document.removeEventListener('click', closeUserMenu)
+})
+
+onMounted(async () => {
+ try {
+ const res = await infoApi.get()
+ appInfo.value = res.data.data
+ } catch {
+ // Version display is non-critical
+ }
+})
+
+const user = computed(() => auth.user)
+
+const navItems = [
+ { name: 'Dashboard', path: '/', icon: 'grid' },
+ { name: 'Analytics', path: '/analytics', icon: 'bar-chart' },
+ { name: 'Emails', path: '/emails', icon: 'mail' },
+ { name: 'Templates', path: '/templates', icon: 'file-text' },
+ { name: 'Languages', path: '/languages', icon: 'type' },
+ { name: 'Stylesheets', path: '/stylesheets', icon: 'edit-3' },
+{ name: 'SMTP Servers', path: '/smtp-servers', icon: 'server' },
+ { name: 'Domains', path: '/domains', icon: 'globe' },
+ { name: 'Webhooks', path: '/webhooks', icon: 'link' },
+ { name: 'Deliveries', path: '/webhook-deliveries', icon: 'activity' },
+ { name: 'Contacts', path: '/contacts', icon: 'users' },
+ { name: 'Lists', path: '/contact-lists', icon: 'list' },
+ { name: 'Bounces', path: '/bounces', icon: 'alert-triangle' },
+ { name: 'API Keys', path: '/api-keys', icon: 'key' },
+ { name: 'Audit Log', path: '/audit-log', icon: 'activity' },
+ { name: 'Settings', path: '/settings', icon: 'settings' },
+]
+
+const adminItems = [
+ { name: 'Users', path: '/admin/users', icon: 'users' },
+ { name: 'Shared Servers', path: '/admin/servers', icon: 'server' },
+ { name: 'Jobs', path: '/admin/jobs', icon: 'clock' },
+ { name: 'Metrics', path: '/admin/metrics', icon: 'bar-chart' },
+ { name: 'Events', path: '/admin/events', icon: 'activity' },
+ { name: 'Settings', path: '/admin/settings', icon: 'settings' },
+]
+
+function isActive(path: string): boolean {
+ if (path === '/') return route.path === '/'
+ return route.path.startsWith(path)
+}
+
+function navigate(path: string) {
+ router.push(path)
+}
+
+function logout() {
+ auth.logout()
+ router.push('/login')
+}
+</script>
+
+<template>
+ <div class="layout" :class="{ collapsed: sidebarCollapsed }">
+ <aside class="sidebar">
+ <div class="sidebar-top">
+ <div class="sidebar-brand">
+ <div class="logo" @click="navigate('/')">
+ <img src="/logo.png" alt="Posta" class="logo-img" />
+ <span v-if="!sidebarCollapsed" class="logo-text">Posta Relay</span>
+ </div>
+ <button class="collapse-btn" @click="sidebarCollapsed = !sidebarCollapsed" :title="sidebarCollapsed ? 'Expand' : 'Collapse'">
+ <svg width="16" height="16" viewBox="0 0 16 16" fill="none"><path :d="sidebarCollapsed ? 'M6 3l5 5-5 5' : 'M10 3L5 8l5 5'" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
+ </button>
+ </div>
+
+ <nav class="nav">
+ <a
+ v-for="item in navItems"
+ :key="item.path"
+ class="nav-item"
+ :class="{ active: isActive(item.path) }"
+ :title="sidebarCollapsed ? item.name : ''"
+ @click="navigate(item.path)"
+ >
+ <span class="nav-icon" v-html="getIcon(item.icon)"></span>
+ <span v-if="!sidebarCollapsed" class="nav-label">{{ item.name }}</span>
+ </a>
+
+ <template v-if="user?.role === 'admin'">
+ <div v-if="!sidebarCollapsed" class="nav-section">Admin</div>
+ <div v-else class="nav-divider"></div>
+ <a
+ v-for="item in adminItems"
+ :key="item.path"
+ class="nav-item"
+ :class="{ active: isActive(item.path) }"
+ :title="sidebarCollapsed ? item.name : ''"
+ @click="navigate(item.path)"
+ >
+ <span class="nav-icon" v-html="getIcon(item.icon)"></span>
+ <span v-if="!sidebarCollapsed" class="nav-label">{{ item.name }}</span>
+ </a>
+ </template>
+ </nav>
+ </div>
+
+ <div class="sidebar-bottom">
+ <template v-if="appInfo?.openapi_docs">
+ <div v-if="!sidebarCollapsed" class="nav-section">Docs</div>
+ <div v-else class="nav-divider"></div>
+ <a class="nav-item" href="/docs" target="_blank" rel="noopener noreferrer" :title="sidebarCollapsed ? 'Swagger UI' : ''">
+ <span class="nav-icon" v-html="getIcon('book-open')"></span>
+ <span v-if="!sidebarCollapsed" class="nav-label">Swagger UI</span>
+ </a>
+ <a class="nav-item" href="/redoc" target="_blank" rel="noopener noreferrer" :title="sidebarCollapsed ? 'Redoc' : ''">
+ <span class="nav-icon" v-html="getIcon('file-text')"></span>
+ <span v-if="!sidebarCollapsed" class="nav-label">Redoc</span>
+ </a>
+ </template>
+
+ <div v-if="appInfo && !sidebarCollapsed" class="sidebar-app-info">
+ <span class="sidebar-app-version">v{{ appInfo.version }}</span>
+ </div>
+ </div>
+ </aside>
+
+ <main class="main-content">
+ <header class="topbar">
+ <div></div>
+ <div class="topbar-right">
+ <div class="user-menu" @click="userMenuOpen = !userMenuOpen">
+ <div class="user-avatar">{{ user?.name?.charAt(0)?.toUpperCase() || '?' }}</div>
+ <div class="user-menu-info">
+ <div class="user-name">{{ user?.name || 'User' }}</div>
+ <div class="user-email">{{ user?.email || '' }}</div>
+ </div>
+ <svg width="14" height="14" viewBox="0 0 16 16" fill="none"><path d="M4 6l4 4 4-4" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
+
+ <div v-if="userMenuOpen" class="user-dropdown">
+ <a class="dropdown-item" @click.stop="navigate('/profile'); userMenuOpen = false">
+ <svg width="15" height="15" viewBox="0 0 16 16" fill="none"><path d="M12.67 14v-1.33A2.67 2.67 0 0010 10H6a2.67 2.67 0 00-2.67 2.67V14" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><circle cx="8" cy="5.33" r="2.67" stroke="currentColor" stroke-width="1.5"/></svg>
+ My Profile
+ </a>
+ <div class="dropdown-divider"></div>
+ <div class="dropdown-theme">
+ <div class="dropdown-theme-label">
+ <svg width="15" height="15" viewBox="0 0 16 16" fill="none"><circle cx="8" cy="8" r="3" stroke="currentColor" stroke-width="1.5"/><path d="M8 1v2M8 13v2M1 8h2M13 8h2M3.05 3.05l1.41 1.41M11.54 11.54l1.41 1.41M3.05 12.95l1.41-1.41M11.54 4.46l1.41-1.41" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg>
+ Theme
+ </div>
+ <div class="dropdown-theme-switcher">
+ <button
+ v-for="m in themeModes"
+ :key="m"
+ :class="['dropdown-theme-btn', { active: theme.mode === m }]"
+ :title="m.charAt(0).toUpperCase() + m.slice(1)"
+ @click.stop="theme.setMode(m)"
+ >
+ <svg v-if="m === 'light'" width="14" height="14" viewBox="0 0 16 16" fill="none"><circle cx="8" cy="8" r="3" stroke="currentColor" stroke-width="1.5"/><path d="M8 1v2M8 13v2M1 8h2M13 8h2M3.05 3.05l1.41 1.41M11.54 11.54l1.41 1.41M3.05 12.95l1.41-1.41M11.54 4.46l1.41-1.41" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg>
+ <svg v-else-if="m === 'dark'" width="14" height="14" viewBox="0 0 16 16" fill="none"><path d="M14 9.5A6.5 6.5 0 016.5 2 6.5 6.5 0 1014 9.5z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
+ <svg v-else width="14" height="14" viewBox="0 0 16 16" fill="none"><rect x="2" y="3" width="12" height="10" rx="1.5" stroke="currentColor" stroke-width="1.5"/><path d="M2 5.5h12" stroke="currentColor" stroke-width="1.5"/></svg>
+ </button>
+ </div>
+ </div>
+ <div class="dropdown-divider"></div>
+ <a class="dropdown-item dropdown-item-danger" @click.stop="logout">
+ <svg width="15" height="15" viewBox="0 0 16 16" fill="none"><path d="M6 14H3.33A1.33 1.33 0 012 12.67V3.33A1.33 1.33 0 013.33 2H6M10.67 11.33L14 8l-3.33-3.33M14 8H6" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
+ Logout
+ </a>
+ </div>
+ </div>
+ </div>
+ </header>
+ <div class="main-body">
+ <router-view />
+ </div>
+ <footer class="main-footer">
+ <div class="footer-left">
+ <span>&copy; {{ new Date().getFullYear() }} Jonas Kaninda</span>
+ <span v-if="appInfo" class="footer-version" :title="appInfo.commit_id ? `Commit: ${appInfo.commit_id}` : ''">
+ v{{ appInfo.version }}<template v-if="appInfo.commit_id"> ({{ appInfo.commit_id.slice(0, 7) }})</template>
+ </span>
+ </div>
+ <div class="footer-right">
+ <a href="https://github.com/jkaninda/posta" target="_blank" rel="noopener noreferrer" class="footer-link">
+ <svg width="16" height="16" viewBox="0 0 16 16" fill="none"><path d="M8 1C4.13 1 1 4.13 1 8a7 7 0 004.79 6.65c.35.06.48-.15.48-.34 0-.17-.01-.71-.01-1.29-1.76.33-2.2-.43-2.34-.82-.08-.2-.42-.82-.71-.99-.24-.13-.59-.46-.01-.47.55-.01.94.51 1.07.71.63 1.05 1.63.76 2.03.57.06-.45.24-.76.44-.93-1.55-.17-3.18-.78-3.18-3.46 0-.76.27-1.39.71-1.88-.07-.17-.31-.89.07-1.85 0 0 .58-.19 1.9.71a6.5 6.5 0 013.46 0c1.32-.9 1.9-.71 1.9-.71.38.96.14 1.68.07 1.85.44.49.71 1.11.71 1.88 0 2.69-1.64 3.29-3.19 3.46.25.22.47.64.47 1.29 0 .93-.01 1.68-.01 1.91 0 .19.13.41.48.34A7 7 0 0015 8c0-3.87-3.13-7-7-7z" fill="currentColor"/></svg>
+ GitHub
+ </a>
+ </div>
+ </footer>
+ </main>
+ </div>
+</template>
+
+<script lang="ts">
+function getIcon(name: string): string {
+ const icons: Record<string, string> = {
+ 'grid': '<svg width="18" height="18" viewBox="0 0 18 18" fill="none"><rect x="1.5" y="1.5" width="6" height="6" rx="1.5" stroke="currentColor" stroke-width="1.5"/><rect x="10.5" y="1.5" width="6" height="6" rx="1.5" stroke="currentColor" stroke-width="1.5"/><rect x="1.5" y="10.5" width="6" height="6" rx="1.5" stroke="currentColor" stroke-width="1.5"/><rect x="10.5" y="10.5" width="6" height="6" rx="1.5" stroke="currentColor" stroke-width="1.5"/></svg>',
+ 'mail': '<svg width="18" height="18" viewBox="0 0 18 18" fill="none"><rect x="2" y="3.5" width="14" height="11" rx="2" stroke="currentColor" stroke-width="1.5"/><path d="M2 5.5l7 5 7-5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>',
+ 'key': '<svg width="18" height="18" viewBox="0 0 18 18" fill="none"><path d="M15.5 2.5l-2 2m1 1l-2 2-3-3 2-2m-3.18 3.18a4 4 0 10-5.64 5.64 4 4 0 005.64-5.64z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>',
+ 'file-text': '<svg width="18" height="18" viewBox="0 0 18 18" fill="none"><path d="M10.5 1.5H4.5a1.5 1.5 0 00-1.5 1.5v12a1.5 1.5 0 001.5 1.5h9a1.5 1.5 0 001.5-1.5V6l-4.5-4.5z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M10.5 1.5V6H15M12 9.75H6M12 12.75H6M7.5 6.75H6" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>',
+ 'server': '<svg width="18" height="18" viewBox="0 0 18 18" fill="none"><rect x="2" y="2" width="14" height="5" rx="1.5" stroke="currentColor" stroke-width="1.5"/><rect x="2" y="11" width="14" height="5" rx="1.5" stroke="currentColor" stroke-width="1.5"/><circle cx="5" cy="4.5" r="0.75" fill="currentColor"/><circle cx="5" cy="13.5" r="0.75" fill="currentColor"/></svg>',
+ 'globe': '<svg width="18" height="18" viewBox="0 0 18 18" fill="none"><circle cx="9" cy="9" r="7" stroke="currentColor" stroke-width="1.5"/><path d="M2 9h14M9 2a11.05 11.05 0 013 7 11.05 11.05 0 01-3 7 11.05 11.05 0 01-3-7 11.05 11.05 0 013-7z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>',
+ 'link': '<svg width="18" height="18" viewBox="0 0 18 18" fill="none"><path d="M7.5 10.5a3.75 3.75 0 005.3.45l2.25-2.25a3.75 3.75 0 00-5.3-5.3l-1.29 1.28" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M10.5 7.5a3.75 3.75 0 00-5.3-.45L2.96 9.3a3.75 3.75 0 005.3 5.3l1.28-1.28" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>',
+ 'alert-triangle': '<svg width="18" height="18" viewBox="0 0 18 18" fill="none"><path d="M7.86 2.87L1.21 14.25a1.31 1.31 0 001.14 1.97h13.3a1.31 1.31 0 001.14-1.97L10.14 2.87a1.31 1.31 0 00-2.28 0z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M9 6.75v3M9 12.75h.007" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg>',
+ 'users': '<svg width="18" height="18" viewBox="0 0 18 18" fill="none"><path d="M12.75 15.75v-1.5a3 3 0 00-3-3h-6a3 3 0 00-3 3v1.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><circle cx="6.75" cy="5.25" r="3" stroke="currentColor" stroke-width="1.5"/><path d="M17.25 15.75v-1.5a3 3 0 00-2.25-2.9M12 2.33a3 3 0 010 5.84" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>',
+ 'bar-chart': '<svg width="18" height="18" viewBox="0 0 18 18" fill="none"><path d="M13.5 15V7.5M9 15V3M4.5 15v-4.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>',
+ 'type': '<svg width="18" height="18" viewBox="0 0 18 18" fill="none"><path d="M3 3h12M9 3v12M5.25 15h7.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>',
+ 'clock': '<svg width="18" height="18" viewBox="0 0 18 18" fill="none"><circle cx="9" cy="9" r="7" stroke="currentColor" stroke-width="1.5"/><path d="M9 4.5V9l3 1.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>',
+ 'activity': '<svg width="18" height="18" viewBox="0 0 18 18" fill="none"><path d="M16.5 9h-3l-2.25 6.75L6.75 2.25 4.5 9h-3" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>',
+ 'book-open': '<svg width="18" height="18" viewBox="0 0 18 18" fill="none"><path d="M1.5 2.25h5.25a3 3 0 013 3v10.5a2.25 2.25 0 00-2.25-2.25H1.5V2.25zM16.5 2.25h-5.25a3 3 0 00-3 3v10.5a2.25 2.25 0 012.25-2.25h6V2.25z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>',
+ 'list': '<svg width="18" height="18" viewBox="0 0 18 18" fill="none"><path d="M6.75 4.5h9M6.75 9h9M6.75 13.5h9M2.25 4.5h.007M2.25 9h.007M2.25 13.5h.007" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>',
+ 'edit-3': '<svg width="18" height="18" viewBox="0 0 18 18" fill="none"><path d="M12 2.25l3.75 3.75L6 15.75H2.25V12L12 2.25z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>',
+ 'settings': '<svg width="18" height="18" viewBox="0 0 18 18" fill="none"><circle cx="9" cy="9" r="2.25" stroke="currentColor" stroke-width="1.5"/><path d="M14.7 11.1a1.2 1.2 0 00.24 1.32l.04.04a1.46 1.46 0 11-2.06 2.06l-.04-.04a1.2 1.2 0 00-1.32-.24 1.2 1.2 0 00-.73 1.1v.12a1.46 1.46 0 01-2.91 0v-.06a1.2 1.2 0 00-.79-1.1 1.2 1.2 0 00-1.32.24l-.04.04a1.46 1.46 0 11-2.06-2.06l.04-.04a1.2 1.2 0 00.24-1.32 1.2 1.2 0 00-1.1-.73h-.12a1.46 1.46 0 010-2.91h.06a1.2 1.2 0 001.1-.79 1.2 1.2 0 00-.24-1.32l-.04-.04a1.46 1.46 0 112.06-2.06l.04.04a1.2 1.2 0 001.32.24h.06a1.2 1.2 0 00.73-1.1v-.12a1.46 1.46 0 012.91 0v.06a1.2 1.2 0 00.73 1.1 1.2 1.2 0 001.32-.24l.04-.04a1.46 1.46 0 112.06 2.06l-.04.04a1.2 1.2 0 00-.24 1.32v.06a1.2 1.2 0 001.1.73h.12a1.46 1.46 0 010 2.91h-.06a1.2 1.2 0 00-1.1.73z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>',
+ }
+ return icons[name] || ''
+}
+export default { methods: { getIcon } }
+</script>
+
+<style scoped>
+.layout { display: flex; min-height: 100vh; }
+
+.sidebar {
+ width: 240px;
+ min-width: 240px;
+ background: var(--bg-sidebar);
+ display: flex;
+ flex-direction: column;
+ justify-content: space-between;
+ position: fixed;
+ top: 0;
+ left: 0;
+ bottom: 0;
+ z-index: 100;
+ transition: width var(--transition-slow), min-width var(--transition-slow);
+}
+
+.collapsed .sidebar { width: 64px; min-width: 64px; }
+.collapsed .main-content { margin-left: 64px; }
+
+.sidebar-top { flex: 1; overflow-y: auto; overflow-x: hidden; }
+
+.sidebar-brand {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 16px 14px 12px;
+}
+
+.logo {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ cursor: pointer;
+}
+
+.logo-img {
+ width: 36px;
+ height: 36px;
+ object-fit: contain;
+}
+
+.logo-text {
+ font-size: 22px;
+ font-weight: 800;
+ color: var(--sidebar-text-active);
+ letter-spacing: -0.5px;
+}
+
+.collapse-btn {
+ background: transparent;
+ border: none;
+ color: var(--sidebar-text);
+ cursor: pointer;
+ padding: 4px;
+ border-radius: var(--radius-sm);
+ transition: all var(--transition);
+ display: flex;
+ align-items: center;
+}
+.collapse-btn:hover { color: var(--sidebar-text-active); background: var(--sidebar-hover); }
+.collapsed .collapse-btn { display: none; }
+
+.nav { display: flex; flex-direction: column; padding: 0 8px; gap: 2px; }
+
+.nav-item {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 9px 12px;
+ border-radius: var(--radius);
+ color: var(--sidebar-text);
+ font-size: 13.5px;
+ font-weight: 500;
+ cursor: pointer;
+ transition: all var(--transition);
+ text-decoration: none;
+ white-space: nowrap;
+ overflow: hidden;
+}
+.nav-item:hover { color: var(--sidebar-text-active); background: var(--sidebar-hover); }
+.nav-item.active { color: var(--sidebar-text-active); background: var(--primary-700); }
+
+.collapsed .nav-item { justify-content: center; padding: 10px; }
+
+.nav-icon { display: flex; align-items: center; justify-content: center; flex-shrink: 0; width: 20px; height: 20px; }
+
+.nav-section {
+ padding: 20px 12px 6px;
+ font-size: 10px;
+ font-weight: 700;
+ text-transform: uppercase;
+ letter-spacing: 0.1em;
+ color: var(--sidebar-text);
+ opacity: 0.5;
+}
+
+.nav-divider {
+ height: 1px;
+ background: var(--sidebar-border);
+ margin: 12px 12px 8px;
+}
+
+.sidebar-bottom {
+ padding: 12px 8px 14px;
+ border-top: 1px solid var(--sidebar-border);
+}
+
+
+.main-content {
+ flex: 1;
+ margin-left: 240px;
+ min-height: 100vh;
+ background: var(--bg-secondary);
+ display: flex;
+ flex-direction: column;
+ transition: margin-left var(--transition-slow), background var(--transition-slow);
+}
+
+.topbar {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 12px 32px;
+ background: var(--bg-primary);
+ border-bottom: 1px solid var(--border-primary);
+ position: sticky;
+ top: 0;
+ z-index: 50;
+}
+
+.topbar-right {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+}
+
+
+.user-menu {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 6px 12px;
+ border-radius: var(--radius);
+ cursor: pointer;
+ transition: all var(--transition);
+ position: relative;
+ user-select: none;
+ color: var(--text-secondary);
+}
+.user-menu:hover { background: var(--bg-secondary); }
+
+.user-avatar {
+ width: 32px;
+ height: 32px;
+ border-radius: 50%;
+ background: var(--primary-600);
+ color: #fff;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ font-size: 13px;
+ font-weight: 600;
+ flex-shrink: 0;
+}
+
+.user-menu-info { overflow: hidden; }
+.user-name { font-size: 13px; font-weight: 600; color: var(--text-primary); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.user-email { font-size: 11px; color: var(--text-muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+
+.user-dropdown {
+ position: absolute;
+ top: calc(100% + 6px);
+ right: 0;
+ min-width: 200px;
+ background: var(--bg-primary);
+ border: 1px solid var(--border-primary);
+ border-radius: var(--radius);
+ box-shadow: var(--shadow-lg);
+ padding: 4px;
+ z-index: 200;
+}
+
+.dropdown-item {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 8px 12px;
+ font-size: 13px;
+ font-weight: 500;
+ color: var(--text-secondary);
+ border-radius: var(--radius-sm);
+ cursor: pointer;
+ transition: all var(--transition);
+ text-decoration: none;
+}
+.dropdown-item:hover { background: var(--bg-secondary); color: var(--text-primary); }
+.dropdown-item-danger:hover { background: var(--danger-50, #fef2f2); color: var(--danger-600, #dc2626); }
+
+.dropdown-divider {
+ height: 1px;
+ background: var(--border-primary);
+ margin: 4px 0;
+}
+
+.dropdown-theme {
+ padding: 6px 12px;
+}
+
+.dropdown-theme-label {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ font-size: 13px;
+ font-weight: 500;
+ color: var(--text-secondary);
+ margin-bottom: 8px;
+}
+
+.dropdown-theme-switcher {
+ display: flex;
+ background: var(--bg-secondary);
+ border: 1px solid var(--border-primary);
+ border-radius: var(--radius);
+ padding: 2px;
+ gap: 2px;
+}
+
+.dropdown-theme-btn {
+ flex: 1;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ padding: 5px;
+ border: none;
+ border-radius: calc(var(--radius) - 2px);
+ background: transparent;
+ color: var(--text-muted);
+ cursor: pointer;
+ transition: all var(--transition);
+}
+
+.dropdown-theme-btn:hover {
+ color: var(--text-primary);
+}
+
+.dropdown-theme-btn.active {
+ background: var(--bg-primary);
+ color: var(--text-primary);
+ box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06);
+}
+
+.main-body {
+ flex: 1;
+ padding: 32px;
+}
+
+.main-footer {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 16px 32px;
+ border-top: 1px solid var(--border-primary);
+ font-size: 12px;
+ color: var(--text-muted);
+}
+
+.footer-left {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+}
+
+.footer-version {
+ font-family: 'JetBrains Mono', 'Fira Code', monospace;
+ opacity: 0.7;
+}
+
+.footer-right {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+}
+
+.footer-link {
+ display: flex;
+ align-items: center;
+ gap: 5px;
+ color: var(--text-muted);
+ text-decoration: none;
+ transition: color var(--transition);
+}
+.footer-link:hover { color: var(--text-primary); }
+
+.sidebar-app-info {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 10px 12px 2px;
+ gap: 6px;
+}
+
+.sidebar-app-name {
+ font-size: 12px;
+ font-weight: 600;
+ color: var(--sidebar-text-active);
+ opacity: 0.75;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.sidebar-app-version {
+ font-size: 11px;
+ font-family: 'JetBrains Mono', 'Fira Code', monospace;
+ color: var(--sidebar-text);
+ opacity: 0.5;
+ flex-shrink: 0;
+}
+</style>
diff --git a/web/src/main.ts b/web/src/main.ts
new file mode 100644
index 0000000..7a0895c
--- /dev/null
+++ b/web/src/main.ts
@@ -0,0 +1,10 @@
+import { createApp } from 'vue'
+import { createPinia } from 'pinia'
+import App from './App.vue'
+import router from './router'
+import './assets/styles.css'
+
+const app = createApp(App)
+app.use(createPinia())
+app.use(router)
+app.mount('#app')
diff --git a/web/src/router/index.ts b/web/src/router/index.ts
new file mode 100644
index 0000000..2584c99
--- /dev/null
+++ b/web/src/router/index.ts
@@ -0,0 +1,78 @@
+import { createRouter, createWebHistory } from 'vue-router'
+import { useAuthStore } from '../stores/auth'
+
+const routes = [
+ {
+ path: '/login',
+ name: 'login',
+ component: () => import('../views/auth/Login.vue'),
+ meta: { guest: true },
+ },
+ {
+ path: '/register',
+ name: 'register',
+ component: () => import('../views/auth/Register.vue'),
+ meta: { guest: true },
+ },
+ {
+ path: '/',
+ component: () => import('../layouts/DashboardLayout.vue'),
+ meta: { auth: true },
+ children: [
+ { 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/: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: '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') },
+ { path: 'smtp-servers/:id', name: 'smtp-server-detail', component: () => import('../views/smtp/SmtpServerDetail.vue') },
+ { path: 'domains', name: 'domains', component: () => import('../views/domains/Domains.vue') },
+ { path: 'webhooks', name: 'webhooks', component: () => import('../views/webhooks/Webhooks.vue') },
+ { path: 'webhook-deliveries', name: 'webhook-deliveries', component: () => import('../views/webhooks/WebhookDeliveries.vue') },
+ { path: 'bounces', name: 'bounces', component: () => import('../views/bounces/Bounces.vue') },
+ { path: 'contacts', name: 'contacts', component: () => import('../views/contacts/Contacts.vue') },
+ { path: 'contacts/:id', name: 'contact-detail', component: () => import('../views/contacts/ContactDetail.vue') },
+ { path: 'contact-lists', name: 'contact-lists', component: () => import('../views/contact-lists/ContactLists.vue') },
+ { path: 'contact-lists/:id/members', name: 'contact-list-members', component: () => import('../views/contact-lists/ContactListMembers.vue') },
+ { path: 'analytics', name: 'analytics', component: () => import('../views/analytics/Analytics.vue') },
+ { path: 'audit-log', name: 'audit-log', component: () => import('../views/audit/AuditLog.vue') },
+ { path: 'settings', name: 'settings', component: () => import('../views/settings/Settings.vue') },
+ { path: 'profile', name: 'profile', component: () => import('../views/auth/Profile.vue') },
+ { path: 'change-password', redirect: '/profile' },
+ // Admin
+ { path: 'admin/users', name: 'admin-users', component: () => import('../views/admin/Users.vue'), meta: { admin: true } },
+ { path: 'admin/users/:id', name: 'admin-user-detail', component: () => import('../views/admin/UserDetail.vue'), meta: { admin: true } },
+ { path: 'admin/metrics', name: 'admin-metrics', component: () => import('../views/admin/Metrics.vue'), meta: { admin: true } },
+ { path: 'admin/events', name: 'admin-events', component: () => import('../views/admin/Events.vue'), meta: { admin: true } },
+ { path: 'admin/servers', name: 'admin-servers', component: () => import('../views/admin/Servers.vue'), meta: { admin: true } },
+ { path: 'admin/servers/:id', name: 'admin-server-detail', component: () => import('../views/admin/ServerDetail.vue'), meta: { admin: true } },
+ { path: 'admin/jobs', name: 'admin-jobs', component: () => import('../views/admin/Jobs.vue'), meta: { admin: true } },
+ { path: 'admin/settings', name: 'admin-settings', component: () => import('../views/admin/Settings.vue'), meta: { admin: true } },
+ ],
+ },
+]
+
+const router = createRouter({
+ history: createWebHistory(),
+ routes,
+})
+
+router.beforeEach((to) => {
+ const auth = useAuthStore()
+
+ if (to.meta.auth && !auth.isAuthenticated) {
+ return { name: 'login' }
+ }
+ if (to.meta.guest && auth.isAuthenticated) {
+ return { name: 'dashboard' }
+ }
+ if (to.meta.admin && !auth.isAdmin) {
+ return { name: 'dashboard' }
+ }
+})
+
+export default router
diff --git a/web/src/stores/auth.ts b/web/src/stores/auth.ts
new file mode 100644
index 0000000..80271ac
--- /dev/null
+++ b/web/src/stores/auth.ts
@@ -0,0 +1,48 @@
+import { defineStore } from 'pinia'
+import { ref, computed } from 'vue'
+import { authApi } from '../api/auth'
+import type { User, UserProfile, AuthResponse } from '../api/types'
+
+export const useAuthStore = defineStore('auth', () => {
+ const token = ref(localStorage.getItem('posta_token') || '')
+ const user = ref<User | null>(JSON.parse(localStorage.getItem('posta_user') || 'null'))
+
+ const isAuthenticated = computed(() => !!token.value)
+ const isAdmin = computed(() => user.value?.role === 'admin')
+
+ async function login(email: string, password: string, twoFactorCode?: string) {
+ const res = await authApi.login(email, password, twoFactorCode)
+ // Check if 2FA is required
+ if (!res.data.success && (res.data.data as any)?.requires_2fa) {
+ throw { requires2FA: true }
+ }
+ setAuth(res.data.data)
+ return res.data.data
+ }
+
+ function setAuth(data: AuthResponse) {
+ token.value = data.token
+ user.value = data.user
+ localStorage.setItem('posta_token', data.token)
+ localStorage.setItem('posta_user', JSON.stringify(data.user))
+ }
+
+ function logout() {
+ token.value = ''
+ user.value = null
+ localStorage.removeItem('posta_token')
+ localStorage.removeItem('posta_user')
+ }
+
+ async function fetchUser() {
+ try {
+ const res = await authApi.me()
+ user.value = res.data.data
+ localStorage.setItem('posta_user', JSON.stringify(res.data.data))
+ } catch {
+ logout()
+ }
+ }
+
+ return { token, user, isAuthenticated, isAdmin, login, logout, fetchUser }
+})
diff --git a/web/src/stores/notification.ts b/web/src/stores/notification.ts
new file mode 100644
index 0000000..99a5db9
--- /dev/null
+++ b/web/src/stores/notification.ts
@@ -0,0 +1,31 @@
+import { defineStore } from 'pinia'
+import { ref } from 'vue'
+
+interface Notification {
+ id: number
+ message: string
+ type: 'success' | 'error' | 'info'
+}
+
+export const useNotificationStore = defineStore('notification', () => {
+ const notifications = ref<Notification[]>([])
+ let nextId = 0
+
+ function show(message: string, type: 'success' | 'error' | 'info' = 'info', duration = 4000) {
+ const id = nextId++
+ notifications.value.push({ id, message, type })
+ if (duration > 0) {
+ setTimeout(() => dismiss(id), duration)
+ }
+ }
+
+ function success(message: string) { show(message, 'success') }
+ function error(message: string) { show(message, 'error', 6000) }
+ function info(message: string) { show(message, 'info') }
+
+ function dismiss(id: number) {
+ notifications.value = notifications.value.filter(n => n.id !== id)
+ }
+
+ return { notifications, show, success, error, info, dismiss }
+})
diff --git a/web/src/stores/theme.ts b/web/src/stores/theme.ts
new file mode 100644
index 0000000..375834d
--- /dev/null
+++ b/web/src/stores/theme.ts
@@ -0,0 +1,40 @@
+import { defineStore } from 'pinia'
+import { ref, computed, watch } from 'vue'
+
+export type ThemeMode = 'light' | 'dark' | 'system'
+
+export const useThemeStore = defineStore('theme', () => {
+ const stored = localStorage.getItem('posta_theme') as ThemeMode | null
+ const mode = ref<ThemeMode>(stored && ['light', 'dark', 'system'].includes(stored) ? stored as ThemeMode : 'system')
+
+ const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
+
+ const isDark = computed(() => {
+ if (mode.value === 'system') return mediaQuery.matches
+ return mode.value === 'dark'
+ })
+
+ function apply() {
+ document.documentElement.setAttribute('data-theme', isDark.value ? 'dark' : 'light')
+ }
+
+ function setMode(m: ThemeMode) {
+ mode.value = m
+ }
+
+ function toggle() {
+ mode.value = isDark.value ? 'light' : 'dark'
+ }
+
+ watch(mode, (val) => {
+ localStorage.setItem('posta_theme', val)
+ apply()
+ }, { immediate: true })
+
+ // Listen for OS theme changes when in system mode
+ mediaQuery.addEventListener('change', () => {
+ if (mode.value === 'system') apply()
+ })
+
+ return { mode, isDark, toggle, setMode }
+})
diff --git a/web/src/views/admin/Events.vue b/web/src/views/admin/Events.vue
new file mode 100644
index 0000000..11919a6
--- /dev/null
+++ b/web/src/views/admin/Events.vue
@@ -0,0 +1,299 @@
+<script setup lang="ts">
+import { ref, onMounted, onBeforeUnmount } from 'vue'
+import { adminApi } from '../../api/admin'
+import { useAuthStore } from '../../stores/auth'
+import type { Event, Pageable } from '../../api/types'
+
+const auth = useAuthStore()
+const loading = ref(true)
+const events = ref<Event[]>([])
+const pageable = ref<Pageable | null>(null)
+const page = ref(0)
+const category = ref('')
+const liveEvents = ref<Event[]>([])
+const streaming = ref(false)
+let eventSource: EventSource | null = null
+
+onMounted(() => {
+ loadEvents()
+ startStream()
+})
+
+onBeforeUnmount(() => {
+ stopStream()
+})
+
+async function loadEvents() {
+ loading.value = true
+ try {
+ const res = await adminApi.listEvents(page.value, 20, category.value || undefined)
+ events.value = res.data.data
+ pageable.value = res.data.pageable
+ } catch (e) {
+ console.error('Failed to load events', e)
+ } finally {
+ loading.value = false
+ }
+}
+
+async function changePage(newPage: number) {
+ page.value = newPage
+ await loadEvents()
+}
+
+function filterByCategory(cat: string) {
+ category.value = cat
+ page.value = 0
+ loadEvents()
+}
+
+function startStream() {
+ const baseUrl = import.meta.env.VITE_API_URL || '/api/v1'
+ const token = auth.token
+ if (!token) return
+ const url = `${baseUrl}/admin/events/stream?token=${encodeURIComponent(token)}`
+ eventSource = new EventSource(url)
+
+ eventSource.onopen = () => {
+ streaming.value = true
+ }
+
+ eventSource.addEventListener('message', (e) => {
+ try {
+ const evt: Event = JSON.parse(e.data)
+ liveEvents.value.unshift(evt)
+ if (liveEvents.value.length > 50) {
+ liveEvents.value.pop()
+ }
+ } catch {
+ // ignore parse errors
+ }
+ })
+
+ // Listen for all named event types
+ const eventTypes = [
+ 'user.login', 'user.created', 'user.updated', 'user.deleted',
+ 'email.queued', 'email.batch_queued',
+ 'apikey.revoked',
+ 'worker.connected', 'worker.disconnected',
+ ]
+ for (const type of eventTypes) {
+ eventSource.addEventListener(type, (e) => {
+ try {
+ const evt: Event = JSON.parse((e as MessageEvent).data)
+ liveEvents.value.unshift(evt)
+ if (liveEvents.value.length > 50) {
+ liveEvents.value.pop()
+ }
+ } catch {
+ // ignore parse errors
+ }
+ })
+ }
+
+ eventSource.onerror = () => {
+ streaming.value = false
+ }
+}
+
+function stopStream() {
+ if (eventSource) {
+ eventSource.close()
+ eventSource = null
+ streaming.value = false
+ }
+}
+
+function categoryBadgeClass(cat: string) {
+ switch (cat) {
+ case 'user': return 'badge badge-info'
+ case 'email': return 'badge badge-success'
+ case 'system': return 'badge badge-warning'
+ default: return 'badge badge-neutral'
+ }
+}
+
+function formatDate(date: string) {
+ return new Date(date).toLocaleString()
+}
+
+function timeAgo(date: string) {
+ const seconds = Math.floor((Date.now() - new Date(date).getTime()) / 1000)
+ if (seconds < 60) return 'just now'
+ if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`
+ if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`
+ return `${Math.floor(seconds / 86400)}d ago`
+}
+</script>
+
+<template>
+ <div>
+ <div class="page-header">
+ <h1>Events</h1>
+ <div style="display: flex; align-items: center; gap: 0.75rem;">
+ <span v-if="streaming" class="stream-indicator stream-active">Live</span>
+ <span v-else class="stream-indicator stream-inactive">Disconnected</span>
+ </div>
+ </div>
+
+ <!-- Live Events -->
+ <div v-if="liveEvents.length > 0" class="card" style="margin-bottom: 1.5rem;">
+ <div class="card-header">
+ <h2>Live Feed</h2>
+ <button class="btn btn-sm btn-secondary" @click="liveEvents = []">Clear</button>
+ </div>
+ <div class="card-body">
+ <div class="live-events">
+ <div v-for="(evt, i) in liveEvents" :key="'live-' + i" class="live-event-item">
+ <span :class="categoryBadgeClass(evt.category)">{{ evt.category }}</span>
+ <span class="event-type">{{ evt.type }}</span>
+ <span v-if="evt.client_ip" class="event-ip">{{ evt.client_ip }}</span>
+ <span class="event-message">{{ evt.message }}</span>
+ <span class="event-time">{{ timeAgo(evt.created_at) }}</span>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Category Filter -->
+ <div style="display: flex; gap: 0.5rem; margin-bottom: 1rem;">
+ <button class="btn btn-sm" :class="category === '' ? 'btn-primary' : 'btn-secondary'" @click="filterByCategory('')">All</button>
+ <button class="btn btn-sm" :class="category === 'user' ? 'btn-primary' : 'btn-secondary'" @click="filterByCategory('user')">User</button>
+ <button class="btn btn-sm" :class="category === 'email' ? 'btn-primary' : 'btn-secondary'" @click="filterByCategory('email')">Email</button>
+ <button class="btn btn-sm" :class="category === 'system' ? 'btn-primary' : 'btn-secondary'" @click="filterByCategory('system')">System</button>
+ </div>
+
+ <!-- Historical Events -->
+ <div v-if="loading" class="loading-page">
+ <div class="spinner"></div>
+ </div>
+
+ <template v-else>
+ <div class="card">
+ <div class="card-header">
+ <h2>Event History</h2>
+ </div>
+ <div v-if="events.length === 0" class="empty-state">
+ <h3>No events found</h3>
+ <p>No activity has been recorded yet.</p>
+ </div>
+ <div v-else class="card-body">
+ <table class="table">
+ <thead>
+ <tr>
+ <th>Category</th>
+ <th>Type</th>
+ <th>Actor</th>
+ <th>IP Address</th>
+ <th>Message</th>
+ <th>Time</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr v-for="evt in events" :key="evt.id">
+ <td><span :class="categoryBadgeClass(evt.category)">{{ evt.category }}</span></td>
+ <td><code>{{ evt.type }}</code></td>
+ <td>{{ evt.actor_name || '-' }}</td>
+ <td><code v-if="evt.client_ip">{{ evt.client_ip }}</code><span v-else>-</span></td>
+ <td>{{ evt.message }}</td>
+ <td>{{ formatDate(evt.created_at) }}</td>
+ </tr>
+ </tbody>
+ </table>
+ <div v-if="pageable && pageable.total_pages > 1" class="pagination">
+ <button class="btn btn-sm btn-secondary" :disabled="page === 0" @click="changePage(page - 1)">Previous</button>
+ <span>Page {{ page + 1 }} of {{ pageable.total_pages }}</span>
+ <button class="btn btn-sm btn-secondary" :disabled="page >= pageable.total_pages - 1" @click="changePage(page + 1)">Next</button>
+ </div>
+ </div>
+ </div>
+ </template>
+ </div>
+</template>
+
+<style scoped>
+.stream-indicator {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ font-size: 12px;
+ font-weight: 600;
+ padding: 4px 10px;
+ border-radius: 999px;
+}
+.stream-indicator::before {
+ content: '';
+ width: 8px;
+ height: 8px;
+ border-radius: 50%;
+}
+.stream-active {
+ color: var(--success-700, #15803d);
+ background: var(--success-50, #f0fdf4);
+}
+.stream-active::before {
+ background: var(--success-500, #22c55e);
+ animation: pulse 2s infinite;
+}
+.stream-inactive {
+ color: var(--text-muted);
+ background: var(--bg-secondary);
+}
+.stream-inactive::before {
+ background: var(--text-muted);
+}
+
+@keyframes pulse {
+ 0%, 100% { opacity: 1; }
+ 50% { opacity: 0.4; }
+}
+
+.live-events {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ max-height: 300px;
+ overflow-y: auto;
+}
+
+.live-event-item {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 8px 12px;
+ border-radius: var(--radius-sm, 4px);
+ background: var(--bg-secondary);
+ font-size: 13px;
+ animation: fadeIn 0.3s ease;
+}
+
+.event-type {
+ font-family: 'JetBrains Mono', 'Fira Code', monospace;
+ font-size: 12px;
+ color: var(--text-secondary);
+ min-width: 120px;
+}
+
+.event-ip {
+ font-family: 'JetBrains Mono', 'Fira Code', monospace;
+ font-size: 11px;
+ color: var(--text-muted);
+ white-space: nowrap;
+}
+
+.event-message {
+ flex: 1;
+ color: var(--text-primary);
+}
+
+.event-time {
+ font-size: 11px;
+ color: var(--text-muted);
+ white-space: nowrap;
+}
+
+@keyframes fadeIn {
+ from { opacity: 0; transform: translateY(-4px); }
+ to { opacity: 1; transform: translateY(0); }
+}
+</style>
diff --git a/web/src/views/admin/Jobs.vue b/web/src/views/admin/Jobs.vue
new file mode 100644
index 0000000..129295c
--- /dev/null
+++ b/web/src/views/admin/Jobs.vue
@@ -0,0 +1,230 @@
+<script setup lang="ts">
+import { ref, onMounted, onBeforeUnmount } from 'vue'
+import { adminApi } from '../../api/admin'
+import type { CronJob } from '../../api/types'
+
+const loading = ref(true)
+const jobs = ref<CronJob[]>([])
+let refreshTimer: ReturnType<typeof setInterval> | null = null
+
+onMounted(() => {
+ loadJobs()
+ refreshTimer = setInterval(loadJobs, 30000)
+})
+
+onBeforeUnmount(() => {
+ if (refreshTimer) {
+ clearInterval(refreshTimer)
+ }
+})
+
+async function loadJobs() {
+ try {
+ const res = await adminApi.listJobs()
+ jobs.value = res.data.data
+ } catch (e) {
+ console.error('Failed to load jobs', e)
+ } finally {
+ loading.value = false
+ }
+}
+
+function formatDate(date: string | null) {
+ if (!date) return '-'
+ return new Date(date).toLocaleString()
+}
+
+function timeUntil(date: string | null) {
+ if (!date) return '-'
+ const diff = new Date(date).getTime() - Date.now()
+ if (diff <= 0) return 'now'
+ const minutes = Math.floor(diff / 60000)
+ const hours = Math.floor(minutes / 60)
+ if (hours > 0) return `${hours}h ${minutes % 60}m`
+ return `${minutes}m`
+}
+
+function scheduleName(schedule: string) {
+ const known: Record<string, string> = {
+ '0 3 * * *': 'Daily at 03:00 UTC',
+ '0 7 * * *': 'Daily at 07:00 UTC',
+ }
+ return known[schedule] || schedule
+}
+</script>
+
+<template>
+ <div>
+ <div class="page-header">
+ <h1>Scheduled Jobs</h1>
+ <button class="btn btn-sm btn-secondary" @click="loadJobs" :disabled="loading">Refresh</button>
+ </div>
+
+ <div v-if="loading" class="loading-page">
+ <div class="spinner"></div>
+ </div>
+
+ <template v-else>
+ <div v-if="jobs.length === 0" class="empty-state">
+ <h3>No scheduled jobs</h3>
+ <p>No cron jobs are currently registered. Jobs are only available when the server is running in production mode.</p>
+ </div>
+
+ <div v-else class="jobs-grid">
+ <div v-for="job in jobs" :key="job.name" class="card job-card">
+ <div class="card-body">
+ <div class="job-header">
+ <h3 class="job-name">{{ job.name }}</h3>
+ <span v-if="job.running" class="badge badge-running">Running</span>
+ <span v-else-if="job.last_error" class="badge badge-error">Failed</span>
+ <span v-else-if="job.last_run_at" class="badge badge-success">OK</span>
+ <span v-else class="badge badge-neutral">Pending</span>
+ </div>
+
+ <div class="job-schedule">
+ <code>{{ job.schedule }}</code>
+ <span class="schedule-label">{{ scheduleName(job.schedule) }}</span>
+ </div>
+
+ <div class="job-details">
+ <div class="job-detail">
+ <span class="detail-label">Last run</span>
+ <span class="detail-value">{{ formatDate(job.last_run_at) }}</span>
+ </div>
+ <div class="job-detail">
+ <span class="detail-label">Next run</span>
+ <span class="detail-value">
+ {{ formatDate(job.next_run_at) }}
+ <span v-if="job.next_run_at" class="time-until">(in {{ timeUntil(job.next_run_at) }})</span>
+ </span>
+ </div>
+ </div>
+
+ <div v-if="job.last_error" class="job-error">
+ <span class="error-label">Last error</span>
+ <code class="error-message">{{ job.last_error }}</code>
+ </div>
+ </div>
+ </div>
+ </div>
+ </template>
+ </div>
+</template>
+
+<style scoped>
+.jobs-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
+ gap: 1rem;
+}
+
+.job-card {
+ border: 1px solid var(--border-primary);
+}
+
+.job-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ margin-bottom: 0.75rem;
+}
+
+.job-name {
+ font-size: 16px;
+ font-weight: 600;
+ margin: 0;
+}
+
+.badge-running {
+ background: var(--info-50, #eff6ff);
+ color: var(--info-700, #1d4ed8);
+}
+
+.badge-error {
+ background: var(--danger-50, #fef2f2);
+ color: var(--danger-600, #dc2626);
+}
+
+.badge-success {
+ background: var(--success-50, #f0fdf4);
+ color: var(--success-700, #15803d);
+}
+
+.badge-neutral {
+ background: var(--bg-secondary);
+ color: var(--text-muted);
+}
+
+.job-schedule {
+ display: flex;
+ align-items: center;
+ gap: 0.75rem;
+ margin-bottom: 1rem;
+ padding-bottom: 0.75rem;
+ border-bottom: 1px solid var(--border-primary);
+}
+
+.job-schedule code {
+ font-size: 12px;
+ padding: 2px 8px;
+ background: var(--bg-secondary);
+ border-radius: var(--radius-sm, 4px);
+}
+
+.schedule-label {
+ font-size: 13px;
+ color: var(--text-muted);
+}
+
+.job-details {
+ display: flex;
+ flex-direction: column;
+ gap: 0.5rem;
+}
+
+.job-detail {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ font-size: 13px;
+}
+
+.detail-label {
+ color: var(--text-muted);
+ font-weight: 500;
+}
+
+.detail-value {
+ color: var(--text-primary);
+}
+
+.time-until {
+ color: var(--text-muted);
+ font-size: 12px;
+ margin-left: 4px;
+}
+
+.job-error {
+ margin-top: 0.75rem;
+ padding-top: 0.75rem;
+ border-top: 1px solid var(--border-primary);
+}
+
+.error-label {
+ display: block;
+ font-size: 12px;
+ font-weight: 600;
+ color: var(--danger-600, #dc2626);
+ margin-bottom: 4px;
+}
+
+.error-message {
+ display: block;
+ font-size: 12px;
+ padding: 6px 10px;
+ background: var(--danger-50, #fef2f2);
+ color: var(--danger-600, #dc2626);
+ border-radius: var(--radius-sm, 4px);
+ word-break: break-word;
+}
+</style>
diff --git a/web/src/views/admin/Metrics.vue b/web/src/views/admin/Metrics.vue
new file mode 100644
index 0000000..013c1a9
--- /dev/null
+++ b/web/src/views/admin/Metrics.vue
@@ -0,0 +1,589 @@
+<script setup lang="ts">
+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'
+
+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)
+let workerSSE: EventSource | null = null
+
+onMounted(async () => {
+ try {
+ const [metricsRes, analyticsRes] = await Promise.all([
+ adminApi.getMetrics(),
+ analyticsApi.admin(),
+ ])
+ metrics.value = metricsRes.data.data
+ analytics.value = analyticsRes.data.data
+ } catch (e) {
+ console.error('Failed to load metrics', e)
+ } finally {
+ loading.value = false
+ }
+ startWorkerStream()
+})
+
+onBeforeUnmount(() => {
+ stopWorkerStream()
+})
+
+function startWorkerStream() {
+ const baseUrl = import.meta.env.VITE_API_URL || '/api/v1'
+ const token = auth.token
+ if (!token) return
+ const url = `${baseUrl}/admin/workers/stream?token=${encodeURIComponent(token)}`
+ workerSSE = new EventSource(url)
+
+ workerSSE.addEventListener('worker.status', (e) => {
+ try {
+ const status: WorkerStatus = JSON.parse((e as MessageEvent).data)
+ workerStatus.value = status
+ if (metrics.value) {
+ metrics.value.active_workers = status.active_workers
+ }
+ } catch {
+ // ignore parse errors
+ }
+ })
+
+ workerSSE.onerror = () => {
+ // Connection lost; will auto-reconnect via EventSource
+ }
+}
+
+function stopWorkerStream() {
+ if (workerSSE) {
+ workerSSE.close()
+ workerSSE = null
+ }
+}
+
+const activeWorkers = computed(() => workerStatus.value?.active_workers ?? metrics.value?.active_workers ?? 0)
+
+const deliveryRate = computed(() => {
+ if (!metrics.value || metrics.value.total_emails === 0) return 0
+ return ((metrics.value.sent_emails / metrics.value.total_emails) * 100)
+})
+
+const revokedKeys = computed(() => {
+ if (!metrics.value) return 0
+ return metrics.value.total_api_keys - metrics.value.active_api_keys
+})
+
+function failureColor(rate: number): string {
+ if (rate <= 1) return 'var(--success-600, #16a34a)'
+ if (rate <= 5) return 'var(--warning-600, #ca8a04)'
+ return 'var(--danger-600, #dc2626)'
+}
+
+// Analytics helpers
+const maxDailyCount = computed(() => {
+ if (!analytics.value?.daily_counts?.length) return 1
+ return Math.max(...analytics.value.daily_counts.map(d => d.count), 1)
+})
+
+function barHeight(count: number): string {
+ return `${Math.max((count / maxDailyCount.value) * 100, 2)}%`
+}
+
+function formatShortDate(dateStr: string): string {
+ const d = new Date(dateStr)
+ return d.toLocaleDateString(undefined, { month: 'short', day: 'numeric' })
+}
+
+function statusColor(status: string): string {
+ switch (status) {
+ case 'sent': return 'var(--success-500, #22c55e)'
+ case 'failed': return 'var(--danger-500, #ef4444)'
+ case 'pending': return 'var(--warning-500, #f59e0b)'
+ case 'queued': return 'var(--info-500, #3b82f6)'
+ case 'suppressed': return 'var(--text-muted, #9ca3af)'
+ default: return 'var(--text-muted)'
+ }
+}
+
+const totalBreakdown = computed(() => analytics.value?.status_breakdown?.reduce((s, b) => s + b.count, 0) || 0)
+</script>
+
+<template>
+ <div>
+ <div class="page-header">
+ <h1>Platform Metrics</h1>
+ </div>
+
+ <div v-if="loading" class="loading-page">
+ <div class="spinner"></div>
+ </div>
+
+ <template v-else-if="metrics">
+ <!-- Overview -->
+ <div class="metrics-section-label">Overview</div>
+ <div class="stats-grid">
+ <div class="stat-card">
+ <div class="stat-header">
+ <div class="stat-label">Total Users</div>
+ <div class="stat-icon stat-icon-primary">
+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>
+ </div>
+ </div>
+ <div class="stat-value">{{ metrics.total_users }}</div>
+ </div>
+ <div class="stat-card">
+ <div class="stat-header">
+ <div class="stat-label">Total Emails</div>
+ <div class="stat-icon stat-icon-primary">
+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>
+ </div>
+ </div>
+ <div class="stat-value">{{ metrics.total_emails }}</div>
+ </div>
+ <div class="stat-card">
+ <div class="stat-header">
+ <div class="stat-label">Active Workers</div>
+ <div class="stat-icon" :class="activeWorkers > 0 ? 'stat-icon-success' : 'stat-icon-danger'">
+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="2" width="20" height="8" rx="2"/><rect x="2" y="14" width="20" height="8" rx="2"/><circle cx="6" cy="6" r="1" fill="currentColor"/><circle cx="6" cy="18" r="1" fill="currentColor"/></svg>
+ </div>
+ </div>
+ <div class="stat-value">{{ activeWorkers }}</div>
+ <div class="stat-sub">{{ activeWorkers > 0 ? 'Processing emails' : 'No workers running' }}</div>
+ </div>
+ <div class="stat-card">
+ <div class="stat-header">
+ <div class="stat-label">Shared SMTP Servers</div>
+ <div class="stat-icon stat-icon-primary">
+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="2" width="20" height="8" rx="2"/><rect x="2" y="14" width="20" height="8" rx="2"/><line x1="6" y1="6" x2="6.01" y2="6"/><line x1="6" y1="18" x2="6.01" y2="18"/></svg>
+ </div>
+ </div>
+ <div class="stat-value">{{ metrics.shared_smtp_servers }}</div>
+ </div>
+ <div class="stat-card">
+ <div class="stat-header">
+ <div class="stat-label">Total Domains</div>
+ <div class="stat-icon stat-icon-primary">
+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>
+ </div>
+ </div>
+ <div class="stat-value">{{ metrics.total_domains }}</div>
+ </div>
+ </div>
+
+ <!-- Worker Details -->
+ <template v-if="workerStatus && workerStatus.workers.length > 0">
+ <div class="metrics-section-label">Workers</div>
+ <div class="card" style="margin-bottom: 28px;">
+ <div class="table-wrapper">
+ <table>
+ <thead>
+ <tr>
+ <th>Host</th>
+ <th>PID</th>
+ <th>Type</th>
+ <th>Queues</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr v-for="w in workerStatus.workers" :key="`${w.host}:${w.pid}`">
+ <td>{{ w.host }}</td>
+ <td>{{ w.pid }}</td>
+ <td>
+ <span class="badge" :class="w.type === 'embedded' ? 'badge-info' : 'badge-success'">
+ {{ w.type }}
+ </span>
+ </td>
+ <td>
+ <span v-for="(concurrency, queue) in w.queues" :key="queue" class="badge badge-neutral" style="margin-right: 6px;">
+ {{ queue }}: {{ concurrency }}
+ </span>
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ </div>
+ </template>
+
+ <!-- Email Delivery -->
+ <div class="metrics-section-label">Email Delivery</div>
+ <div class="stats-grid">
+ <div class="stat-card">
+ <div class="stat-header">
+ <div class="stat-label">Sent</div>
+ <div class="stat-icon stat-icon-success">
+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
+ </div>
+ </div>
+ <div class="stat-value">{{ metrics.sent_emails }}</div>
+ <div class="stat-sub">{{ deliveryRate.toFixed(1) }}% delivery rate</div>
+ </div>
+ <div v-if="metrics.queued_emails > 0 || metrics.processing_emails > 0" class="stat-card">
+ <div class="stat-header">
+ <div class="stat-label">In Queue</div>
+ <div class="stat-icon stat-icon-info">
+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
+ </div>
+ </div>
+ <div class="stat-value">{{ metrics.queued_emails + metrics.processing_emails }}</div>
+ <div class="stat-sub">{{ metrics.queued_emails }} queued, {{ metrics.processing_emails }} processing</div>
+ </div>
+ <div class="stat-card">
+ <div class="stat-header">
+ <div class="stat-label">Failed</div>
+ <div class="stat-icon stat-icon-danger">
+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>
+ </div>
+ </div>
+ <div class="stat-value">{{ metrics.failed_emails }}</div>
+ </div>
+ <div class="stat-card">
+ <div class="stat-header">
+ <div class="stat-label">Suppressed</div>
+ <div class="stat-icon stat-icon-secondary">
+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="4.93" y1="4.93" x2="19.07" y2="19.07"/></svg>
+ </div>
+ </div>
+ <div class="stat-value">{{ metrics.suppressed_emails }}</div>
+ </div>
+ <div class="stat-card">
+ <div class="stat-header">
+ <div class="stat-label">Failure Rate</div>
+ <div class="stat-icon stat-icon-warning">
+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>
+ </div>
+ </div>
+ <div class="stat-value" :style="{ color: failureColor(metrics.failure_rate) }">{{ metrics.failure_rate.toFixed(1) }}%</div>
+ </div>
+ </div>
+
+ <!-- Email delivery progress bar -->
+ <div class="card" style="margin-bottom: 28px;">
+ <div class="card-body">
+ <div class="delivery-bar-label">
+ <span>Email Status Distribution</span>
+ <span class="delivery-bar-total">{{ metrics.total_emails }} total</span>
+ </div>
+ <div class="delivery-bar" v-if="metrics.total_emails > 0">
+ <div class="delivery-segment delivery-sent" :style="{ width: (metrics.sent_emails / metrics.total_emails * 100) + '%' }" :title="`Sent: ${metrics.sent_emails}`"></div>
+ <div class="delivery-segment delivery-queued" :style="{ width: ((metrics.queued_emails + metrics.processing_emails) / metrics.total_emails * 100) + '%' }" :title="`In queue: ${metrics.queued_emails + metrics.processing_emails}`"></div>
+ <div class="delivery-segment delivery-failed" :style="{ width: (metrics.failed_emails / metrics.total_emails * 100) + '%' }" :title="`Failed: ${metrics.failed_emails}`"></div>
+ <div class="delivery-segment delivery-suppressed" :style="{ width: (metrics.suppressed_emails / metrics.total_emails * 100) + '%' }" :title="`Suppressed: ${metrics.suppressed_emails}`"></div>
+ </div>
+ <div v-else class="delivery-bar">
+ <div class="delivery-segment delivery-empty" style="width: 100%"></div>
+ </div>
+ <div class="delivery-legend">
+ <span class="legend-item"><span class="legend-dot delivery-sent"></span> Sent</span>
+ <span class="legend-item"><span class="legend-dot delivery-queued"></span> Queued</span>
+ <span class="legend-item"><span class="legend-dot delivery-failed"></span> Failed</span>
+ <span class="legend-item"><span class="legend-dot delivery-suppressed"></span> Suppressed</span>
+ </div>
+ </div>
+ </div>
+
+ <!-- Analytics (last 30 days) -->
+ <template v-if="analytics">
+ <div class="metrics-section-label">Email Volume (Last 30 Days)</div>
+ <div class="card" style="margin-bottom: 28px;">
+ <div class="card-body">
+ <div v-if="analytics.daily_counts && analytics.daily_counts.length > 0" class="admin-chart">
+ <div
+ v-for="day in analytics.daily_counts"
+ :key="day.date"
+ class="admin-chart-bar-group"
+ :title="`${formatShortDate(day.date)}: ${day.count}`"
+ >
+ <div class="admin-chart-bar" :style="{ height: barHeight(day.count) }">
+ <span v-if="day.count > 0" class="admin-chart-bar-label">{{ day.count }}</span>
+ </div>
+ <div class="admin-chart-bar-date">{{ formatShortDate(day.date) }}</div>
+ </div>
+ </div>
+ <div v-else style="text-align: center; color: var(--text-muted); padding: 24px;">No data</div>
+ </div>
+ </div>
+
+ <div v-if="analytics.status_breakdown && analytics.status_breakdown.length > 0" class="card" style="margin-bottom: 28px;">
+ <div class="card-header"><h2>Status Breakdown</h2></div>
+ <div class="card-body">
+ <div class="admin-breakdown">
+ <div v-for="s in analytics.status_breakdown" :key="s.status" class="admin-breakdown-row">
+ <div class="admin-breakdown-label">
+ <span class="admin-breakdown-dot" :style="{ background: statusColor(s.status) }"></span>
+ <span style="text-transform: capitalize">{{ s.status }}</span>
+ </div>
+ <div class="admin-breakdown-bar-track">
+ <div
+ class="admin-breakdown-bar-fill"
+ :style="{ width: (totalBreakdown > 0 ? (s.count / totalBreakdown * 100) : 0) + '%', background: statusColor(s.status) }"
+ ></div>
+ </div>
+ <div class="admin-breakdown-value">{{ s.count }}</div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </template>
+
+ <!-- Webhook Deliveries -->
+ <template v-if="metrics.webhook_deliveries && metrics.webhook_deliveries.total_deliveries > 0">
+ <div class="metrics-section-label">Webhook Deliveries</div>
+ <div class="stats-grid">
+ <div class="stat-card">
+ <div class="stat-header">
+ <div class="stat-label">Total Deliveries</div>
+ <div class="stat-icon stat-icon-primary">
+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 16.98h-5.99c-1.1 0-1.95.68-2.95 1.76C8.07 19.82 6.22 20 5 20c-1.22 0-2.2-.38-3-1"/><path d="M18 16.98h-5.99c-1.66 0-2.61-1.22-3.15-2.59C8.23 12.64 8 10.66 8 9c0-3.87 3.13-7 7-7"/><circle cx="12" cy="12" r="2"/></svg>
+ </div>
+ </div>
+ <div class="stat-value">{{ metrics.webhook_deliveries.total_deliveries }}</div>
+ </div>
+ <div class="stat-card">
+ <div class="stat-header">
+ <div class="stat-label">Successful</div>
+ <div class="stat-icon stat-icon-success">
+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
+ </div>
+ </div>
+ <div class="stat-value">{{ metrics.webhook_deliveries.success_deliveries }}</div>
+ </div>
+ <div class="stat-card">
+ <div class="stat-header">
+ <div class="stat-label">Failed</div>
+ <div class="stat-icon stat-icon-danger">
+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>
+ </div>
+ </div>
+ <div class="stat-value">{{ metrics.webhook_deliveries.failed_deliveries }}</div>
+ </div>
+ <div class="stat-card">
+ <div class="stat-header">
+ <div class="stat-label">Success Rate</div>
+ <div class="stat-icon stat-icon-info">
+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 12h-4l-3 9L9 3l-3 9H2"/></svg>
+ </div>
+ </div>
+ <div class="stat-value" :style="{ color: failureColor(100 - metrics.webhook_deliveries.success_rate) }">
+ {{ metrics.webhook_deliveries.success_rate.toFixed(1) }}%
+ </div>
+ </div>
+ </div>
+ <div class="card" style="margin-bottom: 28px;">
+ <div class="card-body">
+ <div class="delivery-bar-label">
+ <span>Webhook Delivery Distribution</span>
+ <span class="delivery-bar-total">{{ metrics.webhook_deliveries.total_deliveries }} total</span>
+ </div>
+ <div class="delivery-bar">
+ <div class="delivery-segment delivery-sent" :style="{ width: metrics.webhook_deliveries.success_rate + '%' }" :title="`Success: ${metrics.webhook_deliveries.success_deliveries}`"></div>
+ <div class="delivery-segment delivery-failed" :style="{ width: (100 - metrics.webhook_deliveries.success_rate) + '%' }" :title="`Failed: ${metrics.webhook_deliveries.failed_deliveries}`"></div>
+ </div>
+ <div class="delivery-legend">
+ <span class="legend-item"><span class="legend-dot delivery-sent"></span> Success</span>
+ <span class="legend-item"><span class="legend-dot delivery-failed"></span> Failed</span>
+ </div>
+ </div>
+ </div>
+ </template>
+
+ <!-- API Keys & Reputation -->
+ <div class="metrics-section-label">API Keys & Reputation</div>
+ <div class="stats-grid">
+ <div class="stat-card">
+ <div class="stat-header">
+ <div class="stat-label">Active API Keys</div>
+ <div class="stat-icon stat-icon-success">
+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.78 7.78 5.5 5.5 0 0 1 7.78-7.78zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"/></svg>
+ </div>
+ </div>
+ <div class="stat-value">{{ metrics.active_api_keys }}</div>
+ <div class="stat-sub">{{ revokedKeys }} revoked</div>
+ </div>
+ <div class="stat-card">
+ <div class="stat-header">
+ <div class="stat-label">Total Bounces</div>
+ <div class="stat-icon stat-icon-warning">
+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>
+ </div>
+ </div>
+ <div class="stat-value">{{ metrics.total_bounces }}</div>
+ </div>
+ <div class="stat-card">
+ <div class="stat-header">
+ <div class="stat-label">Suppressions</div>
+ <div class="stat-icon stat-icon-secondary">
+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="4.93" y1="4.93" x2="19.07" y2="19.07"/></svg>
+ </div>
+ </div>
+ <div class="stat-value">{{ metrics.total_suppressions }}</div>
+ </div>
+ </div>
+ </template>
+ </div>
+</template>
+
+<style scoped>
+.metrics-section-label {
+ font-size: 12px;
+ font-weight: 700;
+ text-transform: uppercase;
+ letter-spacing: 0.08em;
+ color: var(--text-muted);
+ margin-bottom: 12px;
+}
+
+.delivery-bar-label {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ margin-bottom: 10px;
+ font-size: 13px;
+ font-weight: 600;
+ color: var(--text-primary);
+}
+
+.delivery-bar-total {
+ font-weight: 500;
+ color: var(--text-muted);
+}
+
+.delivery-bar {
+ display: flex;
+ height: 12px;
+ border-radius: 6px;
+ overflow: hidden;
+ background: var(--bg-tertiary);
+ margin-bottom: 12px;
+}
+
+.delivery-segment {
+ transition: width 0.6s ease;
+ min-width: 0;
+}
+
+.delivery-sent { background: var(--success-500, #22c55e); }
+.delivery-queued { background: var(--primary-400, #60a5fa); }
+.delivery-failed { background: var(--danger-500, #ef4444); }
+.delivery-suppressed { background: var(--text-muted); }
+.delivery-empty { background: var(--bg-tertiary); }
+
+.delivery-legend {
+ display: flex;
+ gap: 16px;
+ flex-wrap: wrap;
+}
+
+.legend-item {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ font-size: 12px;
+ color: var(--text-secondary);
+}
+
+.legend-dot {
+ width: 10px;
+ height: 10px;
+ border-radius: 50%;
+ flex-shrink: 0;
+}
+
+.admin-chart {
+ display: flex;
+ align-items: flex-end;
+ gap: 4px;
+ height: 180px;
+ min-width: fit-content;
+ overflow-x: auto;
+}
+
+.admin-chart-bar-group {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ flex: 1;
+ min-width: 24px;
+ max-width: 40px;
+ height: 100%;
+ justify-content: flex-end;
+}
+
+.admin-chart-bar {
+ width: 100%;
+ background: var(--primary-500, #6366f1);
+ border-radius: 3px 3px 0 0;
+ min-height: 2px;
+ position: relative;
+ transition: height 0.3s ease;
+}
+
+.admin-chart-bar-label {
+ position: absolute;
+ top: -18px;
+ left: 50%;
+ transform: translateX(-50%);
+ font-size: 10px;
+ color: var(--text-muted);
+ white-space: nowrap;
+}
+
+.admin-chart-bar-date {
+ font-size: 9px;
+ color: var(--text-muted);
+ margin-top: 4px;
+ white-space: nowrap;
+ transform: rotate(-45deg);
+ transform-origin: top center;
+}
+
+.admin-breakdown {
+ display: grid;
+ gap: 10px;
+}
+
+.admin-breakdown-row {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+}
+
+.admin-breakdown-label {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ min-width: 100px;
+ font-size: 13px;
+ font-weight: 500;
+}
+
+.admin-breakdown-dot {
+ width: 10px;
+ height: 10px;
+ border-radius: 50%;
+ flex-shrink: 0;
+}
+
+.admin-breakdown-bar-track {
+ flex: 1;
+ height: 8px;
+ background: var(--bg-secondary);
+ border-radius: 4px;
+ overflow: hidden;
+}
+
+.admin-breakdown-bar-fill {
+ height: 100%;
+ border-radius: 4px;
+ transition: width 0.3s ease;
+}
+
+.admin-breakdown-value {
+ min-width: 60px;
+ text-align: right;
+ font-size: 13px;
+ font-weight: 600;
+}
+</style>
diff --git a/web/src/views/admin/ServerDetail.vue b/web/src/views/admin/ServerDetail.vue
new file mode 100644
index 0000000..60f22c5
--- /dev/null
+++ b/web/src/views/admin/ServerDetail.vue
@@ -0,0 +1,339 @@
+<script setup lang="ts">
+import { ref, onMounted } from 'vue'
+import { useRoute, useRouter } from 'vue-router'
+import { serversApi } from '../../api/servers'
+import { useNotificationStore } from '../../stores/notification'
+import { useConfirm } from '../../composables/useConfirm'
+import type { SharedServer, SharedServerInput } from '../../api/types'
+
+const route = useRoute()
+const router = useRouter()
+const notify = useNotificationStore()
+const { confirm } = useConfirm()
+
+const server = ref<SharedServer | null>(null)
+const loading = ref(true)
+
+const showModal = ref(false)
+const form = ref<SharedServerInput>({
+ name: '',
+ host: '',
+ port: 587,
+ username: '',
+ password: '',
+ encryption: 'starttls',
+ max_retries: 0,
+ allowed_domains: [],
+ security_mode: 'permissive',
+})
+const allowedDomainsText = ref('')
+const saving = ref(false)
+
+async function fetchServer() {
+ loading.value = true
+ try {
+ const id = Number(route.params.id)
+ const res = await serversApi.get(id)
+ server.value = res.data.data
+ } catch {
+ notify.error('Failed to load server')
+ } finally {
+ loading.value = false
+ }
+}
+
+function openEdit() {
+ if (!server.value) return
+ form.value = {
+ name: server.value.name,
+ host: server.value.host,
+ port: server.value.port,
+ username: server.value.username,
+ password: '',
+ encryption: server.value.encryption,
+ max_retries: server.value.max_retries ?? 0,
+ allowed_domains: server.value.allowed_domains ?? [],
+ security_mode: server.value.security_mode ?? 'permissive',
+ }
+ allowedDomainsText.value = (server.value.allowed_domains ?? []).join(', ')
+ showModal.value = true
+}
+
+async function save() {
+ if (!server.value) return
+ saving.value = true
+ const data: SharedServerInput = {
+ ...form.value,
+ allowed_domains: allowedDomainsText.value
+ .split(',')
+ .map(d => d.trim().toLowerCase())
+ .filter(d => d.length > 0),
+ }
+ try {
+ await serversApi.update(server.value.id, data)
+ notify.success('Server updated')
+ showModal.value = false
+ await fetchServer()
+ } catch {
+ notify.error('Failed to update server')
+ } finally {
+ saving.value = false
+ }
+}
+
+async function toggleStatus() {
+ if (!server.value) return
+ try {
+ if (server.value.status !== 'disabled') {
+ await serversApi.disable(server.value.id)
+ notify.success(`"${server.value.name}" disabled`)
+ } else {
+ await serversApi.enable(server.value.id)
+ notify.success(`"${server.value.name}" enabled`)
+ }
+ await fetchServer()
+ } catch {
+ notify.error('Failed to update server status')
+ }
+}
+
+async function testServer() {
+ if (!server.value) return
+ try {
+ const res = await serversApi.test(server.value.id)
+ if (res.data.data.success) {
+ notify.success('Connection test successful')
+ } else {
+ notify.error('Connection test failed: ' + res.data.data.message)
+ }
+ await fetchServer()
+ } catch {
+ notify.error('Connection test failed')
+ }
+}
+
+async function deleteServer() {
+ if (!server.value) return
+ const confirmed = await confirm({
+ title: 'Delete Shared Server',
+ message: `Are you sure you want to delete "${server.value.name}"? Any accounts relying on this server will stop receiving email delivery.`,
+ confirmText: 'Delete',
+ variant: 'danger',
+ })
+ if (!confirmed) return
+ try {
+ await serversApi.delete(server.value.id)
+ notify.success('Server deleted')
+ router.push('/admin/servers')
+ } catch {
+ notify.error('Failed to delete server')
+ }
+}
+
+function formatDate(date: string | null) {
+ if (!date) return '-'
+ return new Date(date).toLocaleString()
+}
+
+onMounted(fetchServer)
+</script>
+
+<template>
+ <div>
+ <div class="page-header">
+ <div>
+ <h1>{{ server?.name ?? 'Server Details' }}</h1>
+ </div>
+ <div class="flex gap-2">
+ <button class="btn btn-secondary" @click="router.push('/admin/servers')">Back</button>
+ </div>
+ </div>
+
+ <div v-if="loading" class="loading-page">
+ <div class="spinner"></div>
+ </div>
+
+ <template v-else-if="server">
+ <!-- Info card -->
+ <div class="card" style="margin-bottom: 24px;">
+ <div class="card-header">
+ <h2>{{ server.name }}</h2>
+ <div class="flex gap-2">
+ <span class="badge badge-success" v-if="server.status === 'enabled'">Enabled</span>
+ <span class="badge badge-danger" v-else-if="server.status === 'invalid'">Invalid</span>
+ <span class="badge badge-neutral" v-else>Disabled</span>
+ <span class="badge badge-warning" v-if="server.security_mode === 'strict'">Strict</span>
+ <span class="badge badge-neutral" v-else>Permissive</span>
+ </div>
+ </div>
+ <div class="card-body">
+ <table>
+ <tbody>
+ <tr>
+ <td style="font-weight: 600; width: 160px;">Host</td>
+ <td>{{ server.host }}</td>
+ </tr>
+ <tr>
+ <td style="font-weight: 600;">Port</td>
+ <td>{{ server.port }}</td>
+ </tr>
+ <tr>
+ <td style="font-weight: 600;">Encryption</td>
+ <td>
+ <span class="badge badge-success" v-if="server.encryption === 'ssl'">SSL</span>
+ <span class="badge badge-info" v-else-if="server.encryption === 'starttls'">STARTTLS</span>
+ <span class="badge badge-neutral" v-else>None</span>
+ </td>
+ </tr>
+ <tr>
+ <td style="font-weight: 600;">Username</td>
+ <td>{{ server.username || '-' }}</td>
+ </tr>
+ <tr>
+ <td style="font-weight: 600;">Max Retries</td>
+ <td>{{ server.max_retries }}</td>
+ </tr>
+ <tr>
+ <td style="font-weight: 600;">Security Mode</td>
+ <td>
+ <span class="badge badge-warning" v-if="server.security_mode === 'strict'">Strict</span>
+ <span class="badge badge-neutral" v-else>Permissive</span>
+ <span class="text-muted" style="margin-left: 8px; font-size: 13px;">
+ {{ server.security_mode === 'strict' ? 'Requires verified domain ownership' : 'Allows any matching domain' }}
+ </span>
+ </td>
+ </tr>
+ <tr>
+ <td style="font-weight: 600;">Allowed Domains</td>
+ <td>
+ <span v-if="server.allowed_domains && server.allowed_domains.length > 0">
+ <span
+ v-for="d in server.allowed_domains"
+ :key="d"
+ class="badge badge-neutral"
+ style="margin-right: 6px;"
+ >{{ d }}</span>
+ </span>
+ <span v-else class="text-muted">All domains</span>
+ </td>
+ </tr>
+ <tr v-if="server.status === 'invalid' && server.validation_error">
+ <td style="font-weight: 600;">Validation Error</td>
+ <td style="color: var(--color-danger, #e53e3e);">{{ server.validation_error }}</td>
+ </tr>
+ <tr>
+ <td style="font-weight: 600;">Last Validated</td>
+ <td>{{ formatDate(server.validated_at) }}</td>
+ </tr>
+ <tr>
+ <td style="font-weight: 600;">Created</td>
+ <td>{{ formatDate(server.created_at) }}</td>
+ </tr>
+ <tr>
+ <td style="font-weight: 600;">Updated</td>
+ <td>{{ formatDate(server.updated_at) }}</td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ </div>
+
+ <!-- Stats -->
+ <div class="stats-grid" style="margin-bottom: 24px;">
+ <div class="stat-card">
+ <div class="stat-label">Sent</div>
+ <div class="stat-value">{{ server.sent_count.toLocaleString() }}</div>
+ </div>
+ <div class="stat-card">
+ <div class="stat-label">Failed</div>
+ <div class="stat-value">{{ server.failed_count.toLocaleString() }}</div>
+ </div>
+ </div>
+
+ <!-- Actions -->
+ <div class="card">
+ <div class="card-header"><h2>Actions</h2></div>
+ <div class="card-body">
+ <div class="flex gap-2">
+ <button class="btn btn-primary" @click="openEdit">Edit</button>
+ <button class="btn btn-secondary" @click="testServer">Test Connection</button>
+ <button
+ class="btn btn-secondary"
+ @click="toggleStatus"
+ >{{ server.status !== 'disabled' ? 'Disable' : 'Enable' }}</button>
+ <button class="btn btn-danger" @click="deleteServer">Delete</button>
+ </div>
+ </div>
+ </div>
+ </template>
+
+ <div v-else class="empty-state">
+ <h3>Server not found</h3>
+ </div>
+
+ <!-- Edit Modal -->
+ <div v-if="showModal" class="modal-overlay" @click.self="showModal = false">
+ <div class="modal">
+ <div class="modal-header">
+ <h3>Edit Shared Server</h3>
+ </div>
+ <form @submit.prevent="save">
+ <div class="modal-body">
+ <div class="form-group">
+ <label class="form-label">Name</label>
+ <input v-model="form.name" type="text" class="form-input" required />
+ </div>
+ <div class="form-group">
+ <label class="form-label">Host</label>
+ <input v-model="form.host" type="text" class="form-input" required />
+ </div>
+ <div class="form-group">
+ <label class="form-label">Port</label>
+ <input v-model.number="form.port" type="number" class="form-input" required />
+ </div>
+ <div class="form-group">
+ <label class="form-label">Username</label>
+ <input v-model="form.username" type="text" class="form-input" />
+ </div>
+ <div class="form-group">
+ <label class="form-label">Password</label>
+ <input v-model="form.password" type="password" class="form-input" placeholder="Leave blank to keep current" />
+ </div>
+ <div class="form-group">
+ <label class="form-label">Encryption</label>
+ <select v-model="form.encryption" class="form-select">
+ <option value="none">None</option>
+ <option value="starttls">STARTTLS (port 587)</option>
+ <option value="ssl">SSL/TLS (port 465)</option>
+ </select>
+ </div>
+ <div class="form-group">
+ <label class="form-label">Max Retries</label>
+ <input v-model.number="form.max_retries" type="number" class="form-input" min="0" max="10" />
+ <span class="form-hint">Number of times to retry a failed send. Set to 0 to disable retries.</span>
+ </div>
+ <div class="form-group">
+ <label class="form-label">Allowed Domains</label>
+ <input v-model="allowedDomainsText" type="text" class="form-input" placeholder="example.com, acme.org" />
+ <span class="form-hint">Comma-separated. Leave empty to allow all domains.</span>
+ </div>
+ <div class="form-group">
+ <label class="form-label">Security Mode</label>
+ <select v-model="form.security_mode" class="form-select">
+ <option value="permissive">Permissive — allow any user whose sender domain matches</option>
+ <option value="strict">Strict — require verified domain ownership</option>
+ </select>
+ <span class="form-hint">In strict mode, users must verify ownership of their sender domain before this server is available to them.</span>
+ </div>
+ </div>
+ <div class="modal-footer">
+ <button type="button" class="btn btn-secondary" @click="showModal = false">Cancel</button>
+ <button type="submit" class="btn btn-primary" :disabled="saving">
+ {{ saving ? 'Saving...' : 'Update' }}
+ </button>
+ </div>
+ </form>
+ </div>
+ </div>
+ </div>
+</template>
diff --git a/web/src/views/admin/Servers.vue b/web/src/views/admin/Servers.vue
new file mode 100644
index 0000000..8662515
--- /dev/null
+++ b/web/src/views/admin/Servers.vue
@@ -0,0 +1,279 @@
+<script setup lang="ts">
+import { ref, onMounted } from 'vue'
+import { useRouter } from 'vue-router'
+import { serversApi } from '../../api/servers'
+import type { SharedServer, SharedServerInput, Pageable } from '../../api/types'
+import { useNotificationStore } from '../../stores/notification'
+import { useConfirm } from '../../composables/useConfirm'
+
+const router = useRouter()
+const notify = useNotificationStore()
+const { confirm } = useConfirm()
+
+const servers = ref<SharedServer[]>([])
+const pageable = ref<Pageable | null>(null)
+const loading = ref(true)
+const currentPage = ref(0)
+
+const showModal = ref(false)
+const editing = ref<SharedServer | null>(null)
+const form = ref<SharedServerInput>({
+ name: '',
+ host: '',
+ port: 587,
+ username: '',
+ password: '',
+ encryption: 'starttls',
+ max_retries: 0,
+ allowed_domains: [],
+ security_mode: 'permissive',
+})
+const allowedDomainsText = ref('')
+const saving = ref(false)
+
+async function fetchServers() {
+ loading.value = true
+ try {
+ const res = await serversApi.list(currentPage.value)
+ servers.value = res.data.data
+ pageable.value = res.data.pageable
+ } catch {
+ notify.error('Failed to load shared servers')
+ } finally {
+ loading.value = false
+ }
+}
+
+function openCreate() {
+ editing.value = null
+ form.value = { name: '', host: '', port: 587, username: '', password: '', encryption: 'starttls', max_retries: 0, allowed_domains: [], security_mode: 'permissive' }
+ allowedDomainsText.value = ''
+ showModal.value = true
+}
+
+function openEdit(server: SharedServer) {
+ editing.value = server
+ form.value = {
+ name: server.name,
+ host: server.host,
+ port: server.port,
+ username: server.username,
+ password: '',
+ encryption: server.encryption,
+ max_retries: server.max_retries ?? 0,
+ allowed_domains: server.allowed_domains ?? [],
+ security_mode: server.security_mode ?? 'permissive',
+ }
+ allowedDomainsText.value = (server.allowed_domains ?? []).join(', ')
+ showModal.value = true
+}
+
+async function save() {
+ saving.value = true
+ const data: SharedServerInput = {
+ ...form.value,
+ allowed_domains: allowedDomainsText.value
+ .split(',')
+ .map(d => d.trim().toLowerCase())
+ .filter(d => d.length > 0),
+ }
+ try {
+ if (editing.value) {
+ await serversApi.update(editing.value.id, data)
+ notify.success('Server updated')
+ } else {
+ await serversApi.create(data)
+ notify.success('Server created')
+ }
+ showModal.value = false
+ await fetchServers()
+ } catch {
+ notify.error('Failed to save server')
+ } finally {
+ saving.value = false
+ }
+}
+
+
+async function deleteServer(server: SharedServer) {
+ const confirmed = await confirm({
+ title: 'Delete Shared Server',
+ message: `Are you sure you want to delete "${server.name}"? Any accounts relying on this server will stop receiving email delivery.`,
+ confirmText: 'Delete',
+ variant: 'danger',
+ })
+ if (!confirmed) return
+ try {
+ await serversApi.delete(server.id)
+ notify.success('Server deleted')
+ await fetchServers()
+ } catch {
+ notify.error('Failed to delete server')
+ }
+}
+
+function prevPage() {
+ if (currentPage.value > 0) {
+ currentPage.value--
+ fetchServers()
+ }
+}
+
+function nextPage() {
+ if (pageable.value && currentPage.value < pageable.value.total_pages - 1) {
+ currentPage.value++
+ fetchServers()
+ }
+}
+
+onMounted(fetchServers)
+</script>
+
+<template>
+ <div>
+ <div class="page-header">
+ <div>
+ <h1>Shared SMTP Servers</h1>
+ <p class="page-description">Manage the shared SMTP pool.</p>
+ <p class="page-description">Enabled servers are available to all accounts whose sender domain matches the allowed domains list.</p>
+ </div>
+ <button class="btn btn-primary" @click="openCreate">Add Server</button>
+ </div>
+
+ <div v-if="loading" class="loading-page">
+ <div class="spinner"></div>
+ </div>
+
+ <template v-else>
+ <div class="card">
+ <div class="table-wrapper" v-if="servers.length > 0">
+ <table>
+ <thead>
+ <tr>
+ <th>Name</th>
+ <th>Host</th>
+ <th>Security</th>
+ <th>Status</th>
+ <th>Allowed Domains</th>
+ <th>Actions</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr v-for="server in servers" :key="server.id">
+ <td><strong>{{ server.name }}</strong></td>
+ <td>{{ server.host }}</td>
+ <td>
+ <span class="badge badge-warning" v-if="server.security_mode === 'strict'">Strict</span>
+ <span class="badge badge-neutral" v-else>Permissive</span>
+ </td>
+ <td>
+ <span class="badge badge-success" v-if="server.status === 'enabled'">Enabled</span>
+ <span class="badge badge-danger" v-else-if="server.status === 'invalid'" :title="server.validation_error">Invalid</span>
+ <span class="badge badge-neutral" v-else>Disabled</span>
+ <div v-if="server.status === 'invalid' && server.validation_error" class="text-muted" style="font-size: 12px; margin-top: 2px;">
+ {{ server.validation_error }}
+ </div>
+ </td>
+ <td>
+ <span v-if="server.allowed_domains && server.allowed_domains.length > 0">
+ {{ server.allowed_domains.join(', ') }}
+ </span>
+ <span v-else class="text-muted">All</span>
+ </td>
+ <td>
+ <div class="flex gap-2">
+ <button class="btn btn-secondary btn-sm" @click="router.push(`/admin/servers/${server.id}`)">View</button>
+ <button class="btn btn-secondary btn-sm" @click="openEdit(server)">Edit</button>
+ <button class="btn btn-danger btn-sm" @click="deleteServer(server)">Delete</button>
+ </div>
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+
+ <div v-else class="empty-state">
+ <h3>No shared servers</h3>
+ <p>Add a shared SMTP server to give accounts without personal SMTP configuration a delivery path.</p>
+ </div>
+
+ <div v-if="pageable && !pageable.empty" class="pagination">
+ <span class="pagination-info">
+ Page {{ pageable.current_page + 1 }} of {{ pageable.total_pages }}
+ ({{ pageable.total_elements }} total)
+ </span>
+ <div class="pagination-buttons">
+ <button class="btn btn-secondary btn-sm" :disabled="currentPage === 0" @click="prevPage">Previous</button>
+ <button class="btn btn-secondary btn-sm" :disabled="currentPage >= pageable.total_pages - 1" @click="nextPage">Next</button>
+ </div>
+ </div>
+ </div>
+ </template>
+
+ <!-- Create/Edit Modal -->
+ <div v-if="showModal" class="modal-overlay" @click.self="showModal = false">
+ <div class="modal">
+ <div class="modal-header">
+ <h3>{{ editing ? 'Edit Shared Server' : 'Add Shared Server' }}</h3>
+ </div>
+ <form @submit.prevent="save">
+ <div class="modal-body">
+ <div class="form-group">
+ <label class="form-label">Name</label>
+ <input v-model="form.name" type="text" class="form-input" placeholder="Primary Relay" required />
+ <span class="form-hint">A human-readable label for this server.</span>
+ </div>
+ <div class="form-group">
+ <label class="form-label">Host</label>
+ <input v-model="form.host" type="text" class="form-input" placeholder="smtp.example.com" required />
+ </div>
+ <div class="form-group">
+ <label class="form-label">Port</label>
+ <input v-model.number="form.port" type="number" class="form-input" placeholder="587" required />
+ </div>
+ <div class="form-group">
+ <label class="form-label">Username</label>
+ <input v-model="form.username" type="text" class="form-input" />
+ </div>
+ <div class="form-group">
+ <label class="form-label">Password</label>
+ <input v-model="form.password" type="password" class="form-input" :placeholder="editing ? 'Leave blank to keep current' : ''" :required="!editing" />
+ </div>
+ <div class="form-group">
+ <label class="form-label">Encryption</label>
+ <select v-model="form.encryption" class="form-select">
+ <option value="none">None</option>
+ <option value="starttls">STARTTLS (port 587)</option>
+ <option value="ssl">SSL/TLS (port 465)</option>
+ </select>
+ </div>
+ <div class="form-group">
+ <label class="form-label">Max Retries</label>
+ <input v-model.number="form.max_retries" type="number" class="form-input" min="0" max="10" placeholder="0" />
+ <span class="form-hint">Number of times to retry a failed send. Set to 0 to disable retries.</span>
+ </div>
+ <div class="form-group">
+ <label class="form-label">Allowed Domains</label>
+ <input v-model="allowedDomainsText" type="text" class="form-input" placeholder="example.com, acme.org" />
+ <span class="form-hint">Comma-separated list of sender domains this server accepts. Leave empty to allow all domains.</span>
+ </div>
+ <div class="form-group">
+ <label class="form-label">Security Mode</label>
+ <select v-model="form.security_mode" class="form-select">
+ <option value="permissive">Permissive — allow any user whose sender domain matches</option>
+ <option value="strict">Strict — require verified domain ownership</option>
+ </select>
+ <span class="form-hint">In strict mode, users must verify ownership of their sender domain before this server is available to them.</span>
+ </div>
+ </div>
+ <div class="modal-footer">
+ <button type="button" class="btn btn-secondary" @click="showModal = false">Cancel</button>
+ <button type="submit" class="btn btn-primary" :disabled="saving">
+ {{ saving ? 'Saving...' : (editing ? 'Update' : 'Create') }}
+ </button>
+ </div>
+ </form>
+ </div>
+ </div>
+ </div>
+</template>
diff --git a/web/src/views/admin/Settings.vue b/web/src/views/admin/Settings.vue
new file mode 100644
index 0000000..ce9a2d6
--- /dev/null
+++ b/web/src/views/admin/Settings.vue
@@ -0,0 +1,254 @@
+<script setup lang="ts">
+import { ref, onMounted, computed } from 'vue'
+import { settingsApi } from '../../api/settings'
+import type { AdminSetting } from '../../api/types'
+import { useNotificationStore } from '../../stores/notification'
+
+const notify = useNotificationStore()
+const loading = ref(true)
+const saving = ref(false)
+const settings = ref<AdminSetting[]>([])
+
+// Human-readable labels and descriptions for each setting key
+const settingMeta: Record<string, { label: string; description: string; category: string }> = {
+ registration_enabled: { label: 'User Registration', description: 'Allow new users to self-register.', category: 'General' },
+ allowed_signup_domains: { label: 'Allowed Signup Domains', description: 'Restrict registration to specific email domains (comma-separated). Leave empty to allow all.', category: 'General' },
+ maintenance_mode: { label: 'Maintenance Mode', description: 'Disable all email sending and show a maintenance banner.', category: 'General' },
+ require_email_verification: { label: 'Require Email Verification', description: 'New users must verify their email before sending.', category: 'Security' },
+ require_domain_verification: { label: 'Require Domain Verification', description: 'Users must verify domain ownership before sending.', category: 'Security' },
+ two_factor_required: { label: 'Require Two-Factor Auth', description: 'Force all users to enable 2FA.', category: 'Security' },
+ default_rate_limit_hourly: { label: 'Hourly Rate Limit', description: 'Default hourly send limit for users.', category: 'Limits' },
+ default_rate_limit_daily: { label: 'Daily Rate Limit', description: 'Default daily send limit for users.', category: 'Limits' },
+ max_batch_size: { label: 'Max Batch Size', description: 'Maximum recipients in a single batch send.', category: 'Limits' },
+ max_attachment_size_mb: { label: 'Max Attachment Size (MB)', description: 'Maximum attachment size in megabytes.', category: 'Limits' },
+ global_bounce_threshold: { label: 'Bounce Threshold', description: 'Auto-suppress a contact after this many bounces.', category: 'Limits' },
+ smtp_timeout_seconds: { label: 'SMTP Timeout (seconds)', description: 'Global SMTP connection timeout.', category: 'Limits' },
+ retention_days: { label: 'Email Log Retention (days)', description: 'How long to keep email logs before cleanup.', category: 'Retention' },
+ audit_log_retention_days: { label: 'Audit Log Retention (days)', description: 'How long to keep audit/event logs.', category: 'Retention' },
+ webhook_delivery_retention_days: { label: 'Webhook Delivery Retention (days)', description: 'How long to keep webhook delivery logs.', category: 'Retention' },
+}
+
+const categories = ['General', 'Security', 'Limits', 'Retention']
+
+function settingsByCategory(category: string) {
+ return settings.value.filter(s => {
+ const meta = settingMeta[s.key]
+ return meta ? meta.category === category : category === 'General'
+ })
+}
+
+// Track edited values separately
+const editedValues = ref<Record<string, string>>({})
+
+function getEditedValue(key: string, original: string): string {
+ return key in editedValues.value ? editedValues.value[key] : original
+}
+
+function setEditedValue(key: string, value: string) {
+ editedValues.value[key] = value
+}
+
+const hasChanges = computed(() => {
+ return settings.value.some(s => {
+ return s.key in editedValues.value && editedValues.value[s.key] !== s.value
+ })
+})
+
+onMounted(async () => {
+ try {
+ const res = await settingsApi.getAdminSettings()
+ settings.value = res.data.data || []
+ } catch {
+ notify.error('Failed to load settings')
+ } finally {
+ loading.value = false
+ }
+})
+
+async function save() {
+ saving.value = true
+ try {
+ const changedSettings = settings.value
+ .filter(s => s.key in editedValues.value && editedValues.value[s.key] !== s.value)
+ .map(s => ({
+ key: s.key,
+ value: editedValues.value[s.key],
+ type: s.type,
+ }))
+
+ if (changedSettings.length === 0) {
+ notify.success('No changes to save')
+ saving.value = false
+ return
+ }
+
+ const res = await settingsApi.updateAdminSettings(changedSettings)
+ settings.value = res.data.data || []
+ editedValues.value = {}
+ notify.success('Settings saved')
+ } catch {
+ notify.error('Failed to save settings')
+ } finally {
+ saving.value = false
+ }
+}
+
+function toggleBool(setting: AdminSetting) {
+ const current = getEditedValue(setting.key, setting.value)
+ setEditedValue(setting.key, current === 'true' ? 'false' : 'true')
+}
+</script>
+
+<template>
+ <div>
+ <div class="page-header">
+ <div>
+ <h1>Platform Settings</h1>
+ <p class="page-description">Configure platform-wide settings for all users.</p>
+ </div>
+ <button class="btn btn-primary" :disabled="saving || !hasChanges" @click="save">
+ {{ saving ? 'Saving...' : 'Save Changes' }}
+ </button>
+ </div>
+
+ <div v-if="loading" class="loading-page">
+ <div class="spinner"></div>
+ </div>
+
+ <div v-else class="settings-grid">
+ <div v-for="category in categories" :key="category" class="card">
+ <div class="card-header"><h2>{{ category }}</h2></div>
+ <div class="card-body">
+ <div
+ v-for="setting in settingsByCategory(category)"
+ :key="setting.key"
+ class="setting-row"
+ >
+ <div class="setting-info">
+ <label class="setting-label">{{ settingMeta[setting.key]?.label || setting.key }}</label>
+ <span class="setting-description">{{ settingMeta[setting.key]?.description || '' }}</span>
+ </div>
+ <div class="setting-control">
+ <!-- Boolean toggle -->
+ <template v-if="setting.type === 'bool'">
+ <button
+ :class="['toggle-btn', { active: getEditedValue(setting.key, setting.value) === 'true' }]"
+ @click="toggleBool(setting)"
+ >
+ <span class="toggle-slider"></span>
+ </button>
+ </template>
+ <!-- Number input -->
+ <template v-else-if="setting.type === 'int'">
+ <input
+ type="number"
+ class="form-input setting-input-number"
+ :value="getEditedValue(setting.key, setting.value)"
+ @input="setEditedValue(setting.key, ($event.target as HTMLInputElement).value)"
+ />
+ </template>
+ <!-- String input -->
+ <template v-else>
+ <input
+ type="text"
+ class="form-input setting-input-text"
+ :value="getEditedValue(setting.key, setting.value)"
+ @input="setEditedValue(setting.key, ($event.target as HTMLInputElement).value)"
+ />
+ </template>
+ </div>
+ </div>
+ <div v-if="settingsByCategory(category).length === 0" class="empty-state">
+ <p>No settings in this category.</p>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+</template>
+
+<style scoped>
+.settings-grid {
+ display: grid;
+ gap: 24px;
+ max-width: 720px;
+}
+
+.setting-row {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 24px;
+ padding: 14px 0;
+ border-bottom: 1px solid var(--border-primary);
+}
+
+.setting-row:last-child {
+ border-bottom: none;
+}
+
+.setting-info {
+ flex: 1;
+ min-width: 0;
+}
+
+.setting-label {
+ font-size: 14px;
+ font-weight: 500;
+ color: var(--text-primary);
+ display: block;
+}
+
+.setting-description {
+ font-size: 12px;
+ color: var(--text-muted);
+ margin-top: 2px;
+ display: block;
+}
+
+.setting-control {
+ flex-shrink: 0;
+}
+
+.setting-input-number {
+ width: 100px;
+ text-align: right;
+}
+
+.setting-input-text {
+ width: 200px;
+}
+
+.toggle-btn {
+ position: relative;
+ width: 44px;
+ height: 24px;
+ border-radius: 12px;
+ border: none;
+ background: var(--border-primary);
+ cursor: pointer;
+ transition: background 0.2s;
+ padding: 0;
+ flex-shrink: 0;
+}
+
+.toggle-btn.active {
+ background: var(--primary-600);
+}
+
+.toggle-slider {
+ position: absolute;
+ top: 2px;
+ left: 2px;
+ width: 20px;
+ height: 20px;
+ border-radius: 50%;
+ background: white;
+ transition: transform 0.2s;
+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.15);
+}
+
+.toggle-btn.active .toggle-slider {
+ transform: translateX(20px);
+}
+</style>
diff --git a/web/src/views/admin/UserDetail.vue b/web/src/views/admin/UserDetail.vue
new file mode 100644
index 0000000..623d676
--- /dev/null
+++ b/web/src/views/admin/UserDetail.vue
@@ -0,0 +1,180 @@
+<script setup lang="ts">
+import { ref, onMounted } from 'vue'
+import { useRoute, useRouter } from 'vue-router'
+import { adminApi } from '../../api/admin'
+import { useNotificationStore } from '../../stores/notification'
+import type { UserDetailMetrics } from '../../api/types'
+
+const route = useRoute()
+const router = useRouter()
+const notification = useNotificationStore()
+const loading = ref(true)
+const metrics = ref<UserDetailMetrics | null>(null)
+const disabling2FA = ref(false)
+
+onMounted(async () => {
+ try {
+ const id = Number(route.params.id)
+ const res = await adminApi.getUserMetrics(id)
+ metrics.value = res.data.data
+ } catch (e) {
+ console.error('Failed to load user metrics', e)
+ } finally {
+ loading.value = false
+ }
+})
+
+async function handleDisable2FA() {
+ if (!metrics.value || !confirm('Are you sure you want to disable 2FA for this user?')) return
+ disabling2FA.value = true
+ try {
+ await adminApi.disable2FA(metrics.value.user.id)
+ metrics.value.user.two_factor_enabled = false
+ notification.success('Two-factor authentication disabled.')
+ } catch {
+ notification.error('Failed to disable 2FA.')
+ } finally {
+ disabling2FA.value = false
+ }
+}
+
+function roleBadgeClass(role: string) {
+ switch (role) {
+ case 'admin': return 'badge badge-info'
+ case 'user': return 'badge badge-neutral'
+ default: return 'badge'
+ }
+}
+
+function formatDate(date: string) {
+ return new Date(date).toLocaleString()
+}
+</script>
+
+<template>
+ <div>
+ <div class="page-header">
+ <h1>User Details</h1>
+ <button class="btn btn-secondary" @click="router.push('/admin/users')">Back to Users</button>
+ </div>
+
+ <div v-if="loading" class="loading-page">
+ <div class="spinner"></div>
+ </div>
+
+ <template v-else-if="metrics">
+ <div class="card" style="margin-bottom: 24px;">
+ <div class="card-header">
+ <h2>{{ metrics.user.name || metrics.user.email }}</h2>
+ <span :class="roleBadgeClass(metrics.user.role)">{{ metrics.user.role }}</span>
+ </div>
+ <div class="card-body">
+ <table>
+ <tbody>
+ <tr>
+ <td style="font-weight: 600; width: 140px;">Email</td>
+ <td>{{ metrics.user.email }}</td>
+ </tr>
+ <tr>
+ <td style="font-weight: 600;">Name</td>
+ <td>{{ metrics.user.name || '-' }}</td>
+ </tr>
+ <tr>
+ <td style="font-weight: 600;">Role</td>
+ <td><span :class="roleBadgeClass(metrics.user.role)">{{ metrics.user.role }}</span></td>
+ </tr>
+ <tr>
+ <td style="font-weight: 600;">Status</td>
+ <td>
+ <span :class="metrics.user.active ? 'badge badge-success' : 'badge badge-danger'">
+ {{ metrics.user.active ? 'Active' : 'Disabled' }}
+ </span>
+ </td>
+ </tr>
+ <tr>
+ <td style="font-weight: 600;">2FA</td>
+ <td>
+ <span v-if="metrics.user.two_factor_enabled" class="badge badge-success">Enabled</span>
+ <span v-else class="badge badge-neutral">Disabled</span>
+ <button
+ v-if="metrics.user.two_factor_enabled"
+ class="btn btn-danger btn-sm"
+ style="margin-left: 12px;"
+ :disabled="disabling2FA"
+ @click="handleDisable2FA"
+ >
+ {{ disabling2FA ? 'Disabling...' : 'Disable 2FA' }}
+ </button>
+ </td>
+ </tr>
+ <tr>
+ <td style="font-weight: 600;">Created At</td>
+ <td>{{ formatDate(metrics.user.created_at) }}</td>
+ </tr>
+ <tr>
+ <td style="font-weight: 600;">Last Login</td>
+ <td>{{ metrics.user.last_login_at ? formatDate(metrics.user.last_login_at) : 'Never' }}</td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ </div>
+
+ <div class="stats-grid">
+ <div class="stat-card">
+ <div class="stat-label">Total Emails</div>
+ <div class="stat-value">{{ metrics.total_emails }}</div>
+ </div>
+ <div class="stat-card">
+ <div class="stat-label">Sent Emails</div>
+ <div class="stat-value">{{ metrics.sent_emails }}</div>
+ </div>
+ <div class="stat-card">
+ <div class="stat-label">Failed Emails</div>
+ <div class="stat-value">{{ metrics.failed_emails }}</div>
+ </div>
+ <div class="stat-card">
+ <div class="stat-label">Suppressed Emails</div>
+ <div class="stat-value">{{ metrics.suppressed_emails }}</div>
+ </div>
+ <div class="stat-card">
+ <div class="stat-label">Failure Rate (%)</div>
+ <div class="stat-value">{{ metrics.failure_rate.toFixed(1) }}</div>
+ </div>
+ <div class="stat-card">
+ <div class="stat-label">Total API Keys</div>
+ <div class="stat-value">{{ metrics.total_api_keys }}</div>
+ </div>
+ <div class="stat-card">
+ <div class="stat-label">Active API Keys</div>
+ <div class="stat-value">{{ metrics.active_api_keys }}</div>
+ </div>
+ <div class="stat-card">
+ <div class="stat-label">Total Contacts</div>
+ <div class="stat-value">{{ metrics.total_contacts }}</div>
+ </div>
+ <div class="stat-card">
+ <div class="stat-label">Total Bounces</div>
+ <div class="stat-value">{{ metrics.total_bounces }}</div>
+ </div>
+ <div class="stat-card">
+ <div class="stat-label">Total Suppressions</div>
+ <div class="stat-value">{{ metrics.total_suppressions }}</div>
+ </div>
+ <div class="stat-card">
+ <div class="stat-label">Domains</div>
+ <div class="stat-value">{{ metrics.total_domains }}</div>
+ </div>
+ <div class="stat-card">
+ <div class="stat-label">SMTP Servers</div>
+ <div class="stat-value">{{ metrics.total_smtp_servers }}</div>
+ </div>
+ </div>
+ </template>
+
+ <div v-else class="empty-state">
+ <h3>User not found</h3>
+ <p>The user you are looking for does not exist.</p>
+ </div>
+ </div>
+</template>
diff --git a/web/src/views/admin/Users.vue b/web/src/views/admin/Users.vue
new file mode 100644
index 0000000..d0f75de
--- /dev/null
+++ b/web/src/views/admin/Users.vue
@@ -0,0 +1,276 @@
+<script setup lang="ts">
+import { ref, onMounted } from 'vue'
+import { useRouter } from 'vue-router'
+import { adminApi } from '../../api/admin'
+import type { User, Pageable } from '../../api/types'
+import { useNotificationStore } from '../../stores/notification'
+import { useConfirm } from '../../composables/useConfirm'
+
+const router = useRouter()
+const notify = useNotificationStore()
+const { confirm } = useConfirm()
+const loading = ref(true)
+const users = ref<User[]>([])
+const pageable = ref<Pageable | null>(null)
+const page = ref(0)
+
+const showCreateForm = ref(false)
+const createLoading = ref(false)
+const newUser = ref({ name: '', email: '', password: '', role: 'user' })
+
+const editingUser = ref<User | null>(null)
+const editForm = ref({ role: '', active: true })
+const editLoading = ref(false)
+
+onMounted(() => {
+ loadUsers()
+})
+
+async function createUser() {
+ if (!newUser.value.email || !newUser.value.password) {
+ notify.error('Email and password are required')
+ return
+ }
+ if (newUser.value.password.length < 8) {
+ notify.error('Password must be at least 8 characters')
+ return
+ }
+ createLoading.value = true
+ try {
+ await adminApi.createUser(newUser.value.name, newUser.value.email, newUser.value.password, newUser.value.role)
+ notify.success('User created successfully')
+ showCreateForm.value = false
+ newUser.value = { name: '', email: '', password: '', role: 'user' }
+ await loadUsers()
+ } catch (e: any) {
+ const message = e?.response?.data?.error?.message || 'Failed to create user'
+ notify.error(message)
+ } finally {
+ createLoading.value = false
+ }
+}
+
+async function loadUsers() {
+ loading.value = true
+ try {
+ const res = await adminApi.listUsers(page.value)
+ users.value = res.data.data
+ pageable.value = res.data.pageable
+ } catch (e) {
+ notify.error('Failed to load users')
+ } finally {
+ loading.value = false
+ }
+}
+
+async function changePage(newPage: number) {
+ page.value = newPage
+ await loadUsers()
+}
+
+function roleBadgeClass(role: string) {
+ switch (role) {
+ case 'admin': return 'badge badge-info'
+ case 'user': return 'badge badge-neutral'
+ default: return 'badge'
+ }
+}
+
+function formatDate(date: string) {
+ return new Date(date).toLocaleString()
+}
+
+function startEdit(user: User) {
+ editingUser.value = user
+ editForm.value = { role: user.role, active: user.active }
+}
+
+function cancelEdit() {
+ editingUser.value = null
+}
+
+async function saveEdit() {
+ if (!editingUser.value) return
+ editLoading.value = true
+ try {
+ const res = await adminApi.updateUser(editingUser.value.id, editForm.value)
+ const updated = res.data.data
+ const idx = users.value.findIndex(u => u.id === updated.id)
+ if (idx !== -1) users.value[idx] = updated
+ editingUser.value = null
+ notify.success('User updated')
+ } catch (e: any) {
+ const message = e?.response?.data?.error?.message || 'Failed to update user'
+ notify.error(message)
+ } finally {
+ editLoading.value = false
+ }
+}
+
+async function toggleActive(user: User) {
+ try {
+ const res = await adminApi.updateUser(user.id, { active: !user.active })
+ const updated = res.data.data
+ const idx = users.value.findIndex(u => u.id === updated.id)
+ if (idx !== -1) users.value[idx] = updated
+ notify.success(updated.active ? 'User enabled' : 'User disabled')
+ } catch (e: any) {
+ const message = e?.response?.data?.error?.message || 'Failed to update user'
+ notify.error(message)
+ }
+}
+
+async function deleteUser(user: User) {
+ const confirmed = await confirm({
+ title: 'Delete User',
+ message: `Are you sure you want to delete "${user.email}"? This action cannot be undone. All associated data will be permanently removed.`,
+ confirmText: 'Delete User',
+ variant: 'danger',
+ })
+ if (!confirmed) return
+ try {
+ await adminApi.deleteUser(user.id)
+ notify.success('User deleted')
+ await loadUsers()
+ } catch (e) {
+ notify.error('Failed to delete user')
+ }
+}
+</script>
+
+<template>
+ <div>
+ <div class="page-header">
+ <h1>User Management</h1>
+ <button class="btn btn-primary" @click="showCreateForm = !showCreateForm">
+ {{ showCreateForm ? 'Cancel' : 'Create User' }}
+ </button>
+ </div>
+
+ <div v-if="showCreateForm" class="card" style="margin-bottom: 1.5rem;">
+ <div class="card-header"><h2>Create New User</h2></div>
+ <div class="card-body">
+ <form @submit.prevent="createUser" style="display: grid; gap: 1rem; max-width: 480px;">
+ <div class="form-group">
+ <label class="form-label" for="new-name">Name</label>
+ <input id="new-name" v-model="newUser.name" type="text" class="form-input" placeholder="Full name" />
+ </div>
+ <div class="form-group">
+ <label class="form-label" for="new-email">Email</label>
+ <input id="new-email" v-model="newUser.email" type="email" class="form-input" placeholder="[email protected]" required />
+ </div>
+ <div class="form-group">
+ <label class="form-label" for="new-password">Password</label>
+ <input id="new-password" v-model="newUser.password" type="password" class="form-input" placeholder="Minimum 8 characters" required minlength="8" />
+ </div>
+ <div class="form-group">
+ <label class="form-label" for="new-role">Role</label>
+ <select id="new-role" v-model="newUser.role" class="form-select">
+ <option value="user">user</option>
+ <option value="admin">admin</option>
+ </select>
+ </div>
+ <button type="submit" class="btn btn-primary" :disabled="createLoading">
+ {{ createLoading ? 'Creating...' : 'Create User' }}
+ </button>
+ </form>
+ </div>
+ </div>
+
+ <div v-if="loading" class="loading-page">
+ <div class="spinner"></div>
+ </div>
+
+ <template v-else>
+ <div class="card">
+ <div class="card-header">
+ <h2>Users</h2>
+ </div>
+ <div v-if="users.length === 0" class="empty-state">
+ <h3>No users found</h3>
+ <p>There are no registered users.</p>
+ </div>
+ <div v-else class="card-body">
+ <table class="table">
+ <thead>
+ <tr>
+ <th>Name</th>
+ <th>Email</th>
+ <th>Role</th>
+ <th>Status</th>
+ <th>Created At</th>
+ <th>Actions</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr v-for="user in users" :key="user.id">
+ <td>{{ user.name }}</td>
+ <td>{{ user.email }}</td>
+ <td><span :class="roleBadgeClass(user.role)">{{ user.role }}</span></td>
+ <td>
+ <span :class="user.active ? 'badge badge-success' : 'badge badge-danger'">
+ {{ user.active ? 'Active' : 'Disabled' }}
+ </span>
+ </td>
+ <td>{{ formatDate(user.created_at) }}</td>
+ <td style="display: flex; gap: 0.5rem; align-items: center;">
+ <button class="btn btn-sm btn-secondary" @click="startEdit(user)">Edit</button>
+ <button class="btn btn-sm btn-secondary" @click="router.push(`/admin/users/${user.id}`)">Details</button>
+ <button
+ class="btn btn-sm"
+ :class="user.active ? 'btn-warning' : 'btn-primary'"
+ @click="toggleActive(user)"
+ >
+ {{ user.active ? 'Disable' : 'Enable' }}
+ </button>
+ <button class="btn btn-sm btn-danger" @click="deleteUser(user)">Delete</button>
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ <div v-if="pageable && pageable.total_pages > 1" class="pagination">
+ <button
+ class="btn btn-sm btn-secondary"
+ :disabled="page === 0"
+ @click="changePage(page - 1)"
+ >
+ Previous
+ </button>
+ <span>Page {{ page + 1 }} of {{ pageable.total_pages }}</span>
+ <button
+ class="btn btn-sm btn-secondary"
+ :disabled="page >= pageable.total_pages - 1"
+ @click="changePage(page + 1)"
+ >
+ Next
+ </button>
+ </div>
+ </div>
+ </div>
+ </template>
+
+ <!-- Edit User Modal -->
+ <div v-if="editingUser" class="modal-overlay" @click.self="cancelEdit">
+ <div class="modal">
+ <div class="modal-header">
+ <h3>Edit User</h3>
+ </div>
+ <div class="modal-body">
+ <div class="form-group">
+ <label class="form-label">Role</label>
+ <select v-model="editForm.role" class="form-select">
+ <option value="user">user</option>
+ <option value="admin">admin</option>
+ </select>
+ </div>
+ </div>
+ <div class="modal-footer">
+ <button class="btn btn-secondary" @click="cancelEdit">Cancel</button>
+ <button class="btn btn-primary" :disabled="editLoading" @click="saveEdit">
+ {{ editLoading ? 'Saving...' : 'Save' }}
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+</template>
diff --git a/web/src/views/analytics/Analytics.vue b/web/src/views/analytics/Analytics.vue
new file mode 100644
index 0000000..9be788f
--- /dev/null
+++ b/web/src/views/analytics/Analytics.vue
@@ -0,0 +1,309 @@
+<script setup lang="ts">
+import { ref, computed, onMounted } from 'vue'
+import { analyticsApi } from '../../api/analytics'
+import type { DailyCount, StatusBreakdown } from '../../api/types'
+
+const loading = ref(true)
+const dailyCounts = ref<DailyCount[]>([])
+const statusBreakdown = ref<StatusBreakdown[]>([])
+
+const fromDate = ref('')
+const toDate = ref('')
+const statusFilter = ref('')
+
+// Set default range: last 30 days
+const now = new Date()
+const thirtyDaysAgo = new Date(now)
+thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30)
+fromDate.value = thirtyDaysAgo.toISOString().slice(0, 10)
+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)
+ dailyCounts.value = res.data.data.daily_counts || []
+ statusBreakdown.value = res.data.data.status_breakdown || []
+ } catch (e) {
+ console.error('Failed to load analytics', e)
+ } finally {
+ loading.value = false
+ }
+}
+
+onMounted(loadAnalytics)
+
+const totalEmails = computed(() => dailyCounts.value.reduce((sum, d) => sum + d.count, 0))
+const maxCount = computed(() => Math.max(...dailyCounts.value.map(d => d.count), 1))
+
+function barHeight(count: number): string {
+ return `${Math.max((count / maxCount.value) * 100, 2)}%`
+}
+
+function statusColor(status: string): string {
+ switch (status) {
+ case 'sent': return 'var(--success-500, #22c55e)'
+ case 'failed': return 'var(--danger-500, #ef4444)'
+ case 'pending': return 'var(--warning-500, #f59e0b)'
+ case 'queued': return 'var(--info-500, #3b82f6)'
+ case 'processing': return 'var(--warning-400, #fbbf24)'
+ case 'suppressed': return 'var(--text-muted, #9ca3af)'
+ case 'scheduled': return 'var(--primary-500, #6366f1)'
+ default: return 'var(--text-muted)'
+ }
+}
+
+function formatDate(dateStr: string): string {
+ const d = new Date(dateStr)
+ return d.toLocaleDateString(undefined, { month: 'short', day: 'numeric' })
+}
+
+const totalBreakdown = computed(() => statusBreakdown.value.reduce((sum, s) => sum + s.count, 0))
+
+function breakdownPercent(count: number): string {
+ if (totalBreakdown.value === 0) return '0'
+ return ((count / totalBreakdown.value) * 100).toFixed(1)
+}
+</script>
+
+<template>
+ <div>
+ <div class="page-header">
+ <h1>Analytics</h1>
+ </div>
+
+ <!-- Filters -->
+ <div class="card" style="margin-bottom: 24px">
+ <div class="card-body">
+ <div class="filters">
+ <div class="form-group">
+ <label class="form-label">From</label>
+ <input v-model="fromDate" type="date" class="form-input" />
+ </div>
+ <div class="form-group">
+ <label class="form-label">To</label>
+ <input v-model="toDate" type="date" class="form-input" />
+ </div>
+ <div class="form-group">
+ <label class="form-label">Status</label>
+ <select v-model="statusFilter" class="form-input">
+ <option value="">All</option>
+ <option value="sent">Sent</option>
+ <option value="failed">Failed</option>
+ <option value="pending">Pending</option>
+ <option value="queued">Queued</option>
+ <option value="suppressed">Suppressed</option>
+ <option value="scheduled">Scheduled</option>
+ </select>
+ </div>
+ <div class="form-group" style="align-self: flex-end">
+ <button class="btn btn-primary" @click="loadAnalytics" :disabled="loading">
+ {{ loading ? 'Loading...' : 'Apply' }}
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <div v-if="loading" class="loading-page">
+ <div class="spinner"></div>
+ </div>
+
+ <template v-else>
+ <!-- Summary -->
+ <div class="stats-grid" style="margin-bottom: 24px">
+ <div class="stat-card">
+ <div class="stat-header">
+ <div class="stat-label">Total in Period</div>
+ </div>
+ <div class="stat-value">{{ totalEmails }}</div>
+ </div>
+ <div v-for="s in statusBreakdown" :key="s.status" class="stat-card">
+ <div class="stat-header">
+ <div class="stat-label" style="text-transform: capitalize">{{ s.status }}</div>
+ </div>
+ <div class="stat-value">{{ s.count }}</div>
+ <div class="stat-sub">{{ breakdownPercent(s.count) }}%</div>
+ </div>
+ </div>
+
+ <!-- Daily Chart -->
+ <div class="card" style="margin-bottom: 24px">
+ <div class="card-header"><h2>Daily Email Volume</h2></div>
+ <div class="card-body">
+ <div v-if="dailyCounts.length === 0" class="empty-state">
+ <h3>No data</h3>
+ <p>No emails found in the selected date range.</p>
+ </div>
+ <div v-else class="chart-container">
+ <div class="chart">
+ <div
+ v-for="day in dailyCounts"
+ :key="day.date"
+ class="chart-bar-group"
+ :title="`${formatDate(day.date)}: ${day.count} emails`"
+ >
+ <div class="chart-bar" :style="{ height: barHeight(day.count) }">
+ <span v-if="day.count > 0" class="chart-bar-label">{{ day.count }}</span>
+ </div>
+ <div class="chart-bar-date">{{ formatDate(day.date) }}</div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Status Breakdown -->
+ <div class="card">
+ <div class="card-header"><h2>Status Breakdown</h2></div>
+ <div class="card-body">
+ <div v-if="statusBreakdown.length === 0" class="empty-state">
+ <h3>No data</h3>
+ <p>No emails found in the selected date range.</p>
+ </div>
+ <div v-else class="breakdown">
+ <div v-for="s in statusBreakdown" :key="s.status" class="breakdown-row">
+ <div class="breakdown-label">
+ <span class="breakdown-dot" :style="{ background: statusColor(s.status) }"></span>
+ <span style="text-transform: capitalize">{{ s.status }}</span>
+ </div>
+ <div class="breakdown-bar-track">
+ <div
+ class="breakdown-bar-fill"
+ :style="{ width: breakdownPercent(s.count) + '%', background: statusColor(s.status) }"
+ ></div>
+ </div>
+ <div class="breakdown-value">{{ s.count }} <span class="breakdown-pct">({{ breakdownPercent(s.count) }}%)</span></div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </template>
+ </div>
+</template>
+
+<style scoped>
+.filters {
+ display: flex;
+ gap: 16px;
+ flex-wrap: wrap;
+ align-items: flex-end;
+}
+
+.filters .form-group {
+ min-width: 140px;
+}
+
+.stat-sub {
+ font-size: 12px;
+ color: var(--text-muted);
+ margin-top: 2px;
+}
+
+.chart-container {
+ overflow-x: auto;
+ padding-bottom: 8px;
+}
+
+.chart {
+ display: flex;
+ align-items: flex-end;
+ gap: 4px;
+ height: 220px;
+ min-width: fit-content;
+}
+
+.chart-bar-group {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ flex: 1;
+ min-width: 28px;
+ max-width: 48px;
+ height: 100%;
+ justify-content: flex-end;
+}
+
+.chart-bar {
+ width: 100%;
+ background: var(--primary-500, #6366f1);
+ border-radius: 4px 4px 0 0;
+ min-height: 2px;
+ position: relative;
+ transition: height 0.3s ease;
+}
+
+.chart-bar-label {
+ position: absolute;
+ top: -20px;
+ left: 50%;
+ transform: translateX(-50%);
+ font-size: 10px;
+ color: var(--text-muted);
+ white-space: nowrap;
+}
+
+.chart-bar-date {
+ font-size: 10px;
+ color: var(--text-muted);
+ margin-top: 6px;
+ white-space: nowrap;
+ transform: rotate(-45deg);
+ transform-origin: top center;
+}
+
+.breakdown {
+ display: grid;
+ gap: 12px;
+}
+
+.breakdown-row {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+}
+
+.breakdown-label {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ min-width: 110px;
+ font-size: 13px;
+ font-weight: 500;
+ color: var(--text-primary);
+}
+
+.breakdown-dot {
+ width: 10px;
+ height: 10px;
+ border-radius: 50%;
+ flex-shrink: 0;
+}
+
+.breakdown-bar-track {
+ flex: 1;
+ height: 8px;
+ background: var(--bg-secondary);
+ border-radius: 4px;
+ overflow: hidden;
+}
+
+.breakdown-bar-fill {
+ height: 100%;
+ border-radius: 4px;
+ transition: width 0.3s ease;
+}
+
+.breakdown-value {
+ min-width: 100px;
+ text-align: right;
+ font-size: 13px;
+ font-weight: 600;
+ color: var(--text-primary);
+}
+
+.breakdown-pct {
+ font-weight: 400;
+ color: var(--text-muted);
+}
+</style>
diff --git a/web/src/views/apikeys/ApiKeys.vue b/web/src/views/apikeys/ApiKeys.vue
new file mode 100644
index 0000000..26ad68e
--- /dev/null
+++ b/web/src/views/apikeys/ApiKeys.vue
@@ -0,0 +1,337 @@
+<script setup lang="ts">
+import { ref, onMounted } from 'vue'
+import { apiKeysApi } from '../../api/apikeys'
+import { settingsApi } from '../../api/settings'
+import type { ApiKey, ApiKeyCreateResponse, Pageable } from '../../api/types'
+import { useNotificationStore } from '../../stores/notification'
+import { useConfirm } from '../../composables/useConfirm'
+
+const notify = useNotificationStore()
+const { confirm } = useConfirm()
+
+const keys = ref<ApiKey[]>([])
+const pageable = ref<Pageable>({ current_page: 0, size: 20, total_pages: 0, total_elements: 0, empty: true })
+const loading = ref(true)
+
+const showCreateModal = ref(false)
+const newKeyName = ref('')
+const newKeyIPs = ref('')
+const newKeyExpiry = ref('default')
+const defaultExpiryDays = ref(90)
+const creating = ref(false)
+
+const createdKey = ref<ApiKeyCreateResponse | null>(null)
+const showKeyModal = ref(false)
+const copied = ref(false)
+
+const expiryOptions = [
+ { label: 'Default', value: 'default' },
+ { label: '30 days', value: '30' },
+ { label: '60 days', value: '60' },
+ { label: '90 days', value: '90' },
+ { label: '180 days', value: '180' },
+ { label: '365 days', value: '365' },
+ { label: 'Never', value: 'never' },
+]
+
+async function loadSettings() {
+ try {
+ const res = await settingsApi.getUserSettings()
+ defaultExpiryDays.value = res.data.data.api_key_expiry_days || 90
+ } catch {
+ // Use fallback default
+ }
+}
+
+async function loadKeys(page = 0) {
+ loading.value = true
+ try {
+ const res = await apiKeysApi.list(page, pageable.value.size)
+ keys.value = res.data.data
+ pageable.value = res.data.pageable
+ } catch {
+ notify.error('Failed to load API keys')
+ } finally {
+ loading.value = false
+ }
+}
+
+function resolveExpiryDays(): number | undefined {
+ if (newKeyExpiry.value === 'never') return 0
+ if (newKeyExpiry.value === 'default') return undefined // let backend use user setting
+ return parseInt(newKeyExpiry.value, 10)
+}
+
+async function createKey() {
+ if (!newKeyName.value.trim()) return
+ creating.value = true
+ try {
+ const allowedIPs = newKeyIPs.value
+ .split(/[,\n]/)
+ .map(ip => ip.trim())
+ .filter(ip => ip.length > 0)
+ const expiresInDays = resolveExpiryDays()
+ const res = await apiKeysApi.create(
+ newKeyName.value.trim(),
+ allowedIPs.length > 0 ? allowedIPs : undefined,
+ expiresInDays,
+ )
+ createdKey.value = res.data.data
+ showCreateModal.value = false
+ newKeyName.value = ''
+ newKeyIPs.value = ''
+ newKeyExpiry.value = 'default'
+ showKeyModal.value = true
+ notify.success('API key created')
+ await loadKeys(pageable.value.current_page)
+ } catch {
+ notify.error('Failed to create API key')
+ } finally {
+ creating.value = false
+ }
+}
+
+async function revokeKey(key: ApiKey) {
+ const confirmed = await confirm({
+ title: 'Revoke API Key',
+ message: `Are you sure you want to revoke "${key.name}"? This key will immediately stop working and cannot be reactivated.`,
+ confirmText: 'Revoke',
+ variant: 'danger',
+ })
+ if (!confirmed) return
+ try {
+ await apiKeysApi.revoke(key.id)
+ notify.success('API key revoked')
+ await loadKeys(pageable.value.current_page)
+ } catch {
+ notify.error('Failed to revoke API key')
+ }
+}
+
+async function deleteKey(key: ApiKey) {
+ const confirmed = await confirm({
+ title: 'Delete API Key',
+ message: `Are you sure you want to permanently delete "${key.name}"? This action cannot be undone.`,
+ confirmText: 'Delete',
+ variant: 'danger',
+ })
+ if (!confirmed) return
+ try {
+ await apiKeysApi.delete(key.id)
+ notify.success('API key deleted')
+ await loadKeys(pageable.value.current_page)
+ } catch {
+ notify.error('Failed to delete API key')
+ }
+}
+
+function copyKey() {
+ if (!createdKey.value) return
+ navigator.clipboard.writeText(createdKey.value.key)
+ copied.value = true
+ setTimeout(() => (copied.value = false), 2000)
+}
+
+function closeKeyModal() {
+ showKeyModal.value = false
+ createdKey.value = null
+ copied.value = false
+}
+
+function keyStatus(key: ApiKey): { label: string; class: string } {
+ if (key.revoked) return { label: 'Revoked', class: 'badge-danger' }
+ if (key.expires_at && new Date(key.expires_at) < new Date()) return { label: 'Expired', class: 'badge-warning' }
+ return { label: 'Active', class: 'badge-success' }
+}
+
+function isActive(key: ApiKey): boolean {
+ return !key.revoked && !(key.expires_at && new Date(key.expires_at) < new Date())
+}
+
+function canDelete(key: ApiKey): boolean {
+ return key.revoked || (!!key.expires_at && new Date(key.expires_at) < new Date())
+}
+
+function formatDate(dateStr: string): string {
+ return new Date(dateStr).toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' })
+}
+
+onMounted(() => {
+ loadSettings()
+ loadKeys()
+})
+</script>
+
+<template>
+ <div>
+ <div class="page-header">
+ <h1>API Keys</h1>
+ <button class="btn btn-primary" @click="showCreateModal = true">Create Key</button>
+ </div>
+
+ <div v-if="loading" class="loading-page">
+ <div class="spinner"></div>
+ </div>
+
+ <div v-else class="card">
+ <div v-if="keys.length === 0" class="empty-state">
+ <h3>No API Keys</h3>
+ <p>Create your first API key to start sending emails.</p>
+ </div>
+
+ <template v-else>
+ <div class="table-wrapper">
+ <table>
+ <thead>
+ <tr>
+ <th>Name</th>
+ <th>Key Prefix</th>
+ <th>Created</th>
+ <th>Last Used</th>
+ <th>Expires</th>
+ <th>IP Allowlist</th>
+ <th>Status</th>
+ <th>Actions</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr v-for="key in keys" :key="key.id">
+ <td>{{ key.name }}</td>
+ <td><code>{{ key.key_prefix }}...</code></td>
+ <td>{{ formatDate(key.created_at) }}</td>
+ <td>{{ key.last_used_at ? formatDate(key.last_used_at) : 'Never' }}</td>
+ <td>{{ key.expires_at ? formatDate(key.expires_at) : 'Never' }}</td>
+ <td>
+ <template v-if="key.allowed_ips && key.allowed_ips.length > 0">
+ <code v-for="(ip, i) in key.allowed_ips.slice(0, 2)" :key="i" style="margin-right: 4px; font-size: 12px">{{ ip }}</code>
+ <span v-if="key.allowed_ips.length > 2" style="font-size: 12px; color: var(--text-muted)">+{{ key.allowed_ips.length - 2 }} more</span>
+ </template>
+ <span v-else style="color: var(--text-muted)">Any</span>
+ </td>
+ <td>
+ <span class="badge" :class="keyStatus(key).class">{{ keyStatus(key).label }}</span>
+ </td>
+ <td>
+ <div style="display: flex; gap: 6px">
+ <button
+ v-if="isActive(key)"
+ class="btn btn-warning btn-sm"
+ @click="revokeKey(key)"
+ >
+ Revoke
+ </button>
+ <button
+ v-if="canDelete(key)"
+ class="btn btn-danger btn-sm"
+ @click="deleteKey(key)"
+ >
+ Delete
+ </button>
+ </div>
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+
+ <div class="pagination">
+ <span class="pagination-info">
+ Page {{ pageable.current_page + 1 }} of {{ pageable.total_pages }} ({{ pageable.total_elements }} keys)
+ </span>
+ <div class="pagination-buttons">
+ <button
+ class="btn btn-secondary btn-sm"
+ :disabled="pageable.current_page === 0"
+ @click="loadKeys(pageable.current_page - 1)"
+ >
+ Previous
+ </button>
+ <button
+ class="btn btn-secondary btn-sm"
+ :disabled="pageable.current_page >= pageable.total_pages - 1"
+ @click="loadKeys(pageable.current_page + 1)"
+ >
+ Next
+ </button>
+ </div>
+ </div>
+ </template>
+ </div>
+
+ <!-- Create Key Modal -->
+ <div v-if="showCreateModal" class="modal-overlay" @click.self="showCreateModal = false">
+ <div class="modal">
+ <div class="modal-header">
+ <h3>Create API Key</h3>
+ </div>
+ <div class="modal-body">
+ <div class="form-group">
+ <label class="form-label">Name</label>
+ <input
+ v-model="newKeyName"
+ class="form-input"
+ placeholder="e.g. Production, Staging"
+ @keyup.enter="createKey"
+ />
+ </div>
+ <div class="form-group">
+ <label class="form-label">Expiration</label>
+ <select v-model="newKeyExpiry" class="form-input">
+ <option v-for="opt in expiryOptions" :key="opt.value" :value="opt.value">
+ {{ opt.value === 'default' ? `${opt.label} (${defaultExpiryDays} days)` : opt.label }}
+ </option>
+ </select>
+ <small style="font-size: 12px; color: var(--text-muted); margin-top: 4px; display: block">
+ Choose when this key expires. "Never" means the key will not expire.
+ </small>
+ </div>
+ <div class="form-group">
+ <label class="form-label">Allowed IPs <span style="font-weight: 400; color: var(--text-muted)">(optional)</span></label>
+ <textarea
+ v-model="newKeyIPs"
+ class="form-input"
+ rows="3"
+ placeholder="Comma or newline separated, e.g.&#10;192.168.1.1&#10;10.0.0.0/24"
+ ></textarea>
+ <small style="font-size: 12px; color: var(--text-muted); margin-top: 4px; display: block">
+ Restrict this key to specific IP addresses. Leave empty to allow all.
+ </small>
+ </div>
+ </div>
+ <div class="modal-footer">
+ <button class="btn btn-secondary" @click="showCreateModal = false">Cancel</button>
+ <button class="btn btn-primary" :disabled="creating || !newKeyName.trim()" @click="createKey">
+ {{ creating ? 'Creating...' : 'Create' }}
+ </button>
+ </div>
+ </div>
+ </div>
+
+ <!-- Show Key Modal -->
+ <div v-if="showKeyModal" class="modal-overlay">
+ <div class="modal">
+ <div class="modal-header">
+ <h3>API Key Created</h3>
+ </div>
+ <div class="modal-body">
+ <p class="text-sm" style="color: var(--danger-600); font-weight: 500; margin-bottom: 12px;">
+ Save this key. It won't be shown again.
+ </p>
+ <div class="code-block">{{ createdKey?.key }}</div>
+ <p v-if="createdKey?.expires_at" class="text-sm" style="margin-top: 8px; color: var(--text-muted)">
+ Expires: {{ formatDate(createdKey.expires_at) }}
+ </p>
+ <p v-else class="text-sm" style="margin-top: 8px; color: var(--text-muted)">
+ This key never expires.
+ </p>
+ <button class="btn btn-secondary btn-sm mt-4" @click="copyKey">
+ {{ copied ? 'Copied!' : 'Copy Key' }}
+ </button>
+ </div>
+ <div class="modal-footer">
+ <button class="btn btn-primary" @click="closeKeyModal">Done</button>
+ </div>
+ </div>
+ </div>
+ </div>
+</template>
diff --git a/web/src/views/audit/AuditLog.vue b/web/src/views/audit/AuditLog.vue
new file mode 100644
index 0000000..ff3e54a
--- /dev/null
+++ b/web/src/views/audit/AuditLog.vue
@@ -0,0 +1,108 @@
+<script setup lang="ts">
+import { ref, onMounted } from 'vue'
+import { auditApi } from '../../api/audit'
+import type { Event, Pageable } from '../../api/types'
+
+const events = ref<Event[]>([])
+const pageable = ref<Pageable>({ current_page: 0, size: 20, total_pages: 0, total_elements: 0, empty: true })
+const loading = ref(true)
+const categoryFilter = ref('')
+
+async function loadEvents(page = 0) {
+ loading.value = true
+ try {
+ const res = await auditApi.list(page, pageable.value.size, categoryFilter.value || undefined)
+ events.value = res.data.data
+ pageable.value = res.data.pageable
+ } catch (e) {
+ console.error('Failed to load audit log', e)
+ } finally {
+ loading.value = false
+ }
+}
+
+function formatDate(dateStr: string): string {
+ return new Date(dateStr).toLocaleString()
+}
+
+function categoryBadgeClass(category: string): string {
+ switch (category) {
+ case 'user': return 'badge badge-info'
+ case 'email': return 'badge badge-success'
+ case 'system': return 'badge badge-warning'
+ default: return 'badge'
+ }
+}
+
+onMounted(() => loadEvents())
+</script>
+
+<template>
+ <div>
+ <div class="page-header">
+ <h1>Audit Log</h1>
+ <div class="page-header-actions">
+ <select v-model="categoryFilter" class="form-input" style="min-width: 140px" @change="loadEvents(0)">
+ <option value="">All categories</option>
+ <option value="user">User</option>
+ <option value="email">Email</option>
+ <option value="system">System</option>
+ </select>
+ </div>
+ </div>
+
+ <div v-if="loading" class="loading-page">
+ <div class="spinner"></div>
+ </div>
+
+ <div v-else class="card">
+ <div v-if="events.length === 0" class="empty-state">
+ <h3>No audit events</h3>
+ <p>Your activity log will appear here as you use the platform.</p>
+ </div>
+
+ <template v-else>
+ <div class="table-wrapper">
+ <table>
+ <thead>
+ <tr>
+ <th>Date</th>
+ <th>Category</th>
+ <th>Type</th>
+ <th>IP Address</th>
+ <th>Message</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr v-for="event in events" :key="event.id">
+ <td style="white-space: nowrap">{{ formatDate(event.created_at) }}</td>
+ <td><span :class="categoryBadgeClass(event.category)">{{ event.category }}</span></td>
+ <td><code>{{ event.type }}</code></td>
+ <td><code v-if="event.client_ip">{{ event.client_ip }}</code><span v-else>-</span></td>
+ <td>{{ event.message }}</td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+
+ <div class="pagination">
+ <span class="pagination-info">
+ Page {{ pageable.current_page + 1 }} of {{ pageable.total_pages }} ({{ pageable.total_elements }} events)
+ </span>
+ <div class="pagination-buttons">
+ <button class="btn btn-secondary btn-sm" :disabled="pageable.current_page === 0" @click="loadEvents(pageable.current_page - 1)">Previous</button>
+ <button class="btn btn-secondary btn-sm" :disabled="pageable.current_page >= pageable.total_pages - 1" @click="loadEvents(pageable.current_page + 1)">Next</button>
+ </div>
+ </div>
+ </template>
+ </div>
+ </div>
+</template>
+
+<style scoped>
+.page-header-actions {
+ display: flex;
+ gap: 8px;
+ align-items: center;
+}
+</style>
diff --git a/web/src/views/auth/ChangePassword.vue b/web/src/views/auth/ChangePassword.vue
new file mode 100644
index 0000000..b894514
--- /dev/null
+++ b/web/src/views/auth/ChangePassword.vue
@@ -0,0 +1,71 @@
+<script setup lang="ts">
+import { ref } from 'vue'
+import { authApi } from '../../api/auth'
+import { useNotificationStore } from '../../stores/notification'
+
+const notify = useNotificationStore()
+
+const currentPassword = ref('')
+const newPassword = ref('')
+const confirmPassword = ref('')
+const loading = ref(false)
+
+async function handleSubmit() {
+ if (!currentPassword.value || !newPassword.value || !confirmPassword.value) {
+ notify.error('Please fill in all fields')
+ return
+ }
+ if (newPassword.value.length < 8) {
+ notify.error('New password must be at least 8 characters')
+ return
+ }
+ if (newPassword.value !== confirmPassword.value) {
+ notify.error('New passwords do not match')
+ return
+ }
+ loading.value = true
+ try {
+ await authApi.changePassword(currentPassword.value, newPassword.value)
+ notify.success('Password changed successfully')
+ currentPassword.value = ''
+ newPassword.value = ''
+ confirmPassword.value = ''
+ } catch (e: any) {
+ const message = e?.response?.data?.error?.message || 'Failed to change password'
+ notify.error(message)
+ } finally {
+ loading.value = false
+ }
+}
+</script>
+
+<template>
+ <div>
+ <div class="page-header">
+ <h1>Change Password</h1>
+ </div>
+
+ <div class="card">
+ <div class="card-header"><h2>Update your password</h2></div>
+ <div class="card-body">
+ <form @submit.prevent="handleSubmit" style="display: grid; gap: 1rem; max-width: 480px;">
+ <div class="form-group">
+ <label class="form-label" for="current-password">Current Password</label>
+ <input id="current-password" v-model="currentPassword" type="password" class="form-input" placeholder="Enter current password" required autocomplete="current-password" />
+ </div>
+ <div class="form-group">
+ <label class="form-label" for="new-password">New Password</label>
+ <input id="new-password" v-model="newPassword" type="password" class="form-input" placeholder="Minimum 8 characters" required minlength="8" autocomplete="new-password" />
+ </div>
+ <div class="form-group">
+ <label class="form-label" for="confirm-password">Confirm New Password</label>
+ <input id="confirm-password" v-model="confirmPassword" type="password" class="form-input" placeholder="Re-enter new password" required minlength="8" autocomplete="new-password" />
+ </div>
+ <button type="submit" class="btn btn-primary" :disabled="loading">
+ {{ loading ? 'Updating...' : 'Change Password' }}
+ </button>
+ </form>
+ </div>
+ </div>
+ </div>
+</template>
diff --git a/web/src/views/auth/Login.vue b/web/src/views/auth/Login.vue
new file mode 100644
index 0000000..a00a211
--- /dev/null
+++ b/web/src/views/auth/Login.vue
@@ -0,0 +1,226 @@
+<script setup lang="ts">
+import { ref, onMounted } from 'vue'
+import { useRouter } from 'vue-router'
+import { authApi } from '../../api/auth'
+import { useAuthStore } from '../../stores/auth'
+import { useNotificationStore } from '../../stores/notification'
+import { useThemeStore } from '../../stores/theme'
+
+const router = useRouter()
+const auth = useAuthStore()
+const notification = useNotificationStore()
+const theme = useThemeStore()
+
+const email = ref('')
+const password = ref('')
+const twoFactorCode = ref('')
+const loading = ref(false)
+const requires2FA = ref(false)
+const registrationEnabled = ref(false)
+
+onMounted(async () => {
+ try {
+ const res = await authApi.registrationStatus()
+ registrationEnabled.value = res.data.data.registration_enabled
+ } catch { /* ignore */ }
+})
+
+async function handleLogin() {
+ if (!email.value || !password.value) {
+ notification.error('Please fill in all fields.')
+ return
+ }
+ if (requires2FA.value && !twoFactorCode.value) {
+ notification.error('Please enter your 2FA code.')
+ return
+ }
+ loading.value = true
+ try {
+ await auth.login(email.value, password.value, requires2FA.value ? twoFactorCode.value : undefined)
+ router.push('/')
+ } catch (err: any) {
+ if (err?.requires2FA) {
+ requires2FA.value = true
+ notification.info('Please enter your two-factor authentication code.')
+ return
+ }
+ // Check for 2FA required response (401 with requires_2fa flag)
+ if (err?.response?.status === 401 && err?.response?.data?.data?.requires_2fa) {
+ requires2FA.value = true
+ notification.info('Please enter your two-factor authentication code.')
+ return
+ }
+ if (err?.response?.status === 429) {
+ notification.error('Too many login attempts. Please try again later.')
+ return
+ }
+ const message = err?.response?.data?.error?.message || err?.response?.data?.error || err?.message || 'Login failed.'
+ notification.error(message)
+ } finally {
+ loading.value = false
+ }
+}
+
+function resetLogin() {
+ requires2FA.value = false
+ twoFactorCode.value = ''
+}
+</script>
+
+<template>
+ <div class="auth-page">
+ <div class="auth-card">
+ <div class="auth-header">
+ <div class="auth-logo">
+ <img src="/logo.png" alt="Posta" class="logo-img" />
+ <span>Posta</span>
+ </div>
+ <p class="auth-subtitle">{{ requires2FA ? 'Two-Factor Authentication' : 'Sign in to your account' }}</p>
+ </div>
+
+ <form class="auth-form" @submit.prevent="handleLogin">
+ <template v-if="!requires2FA">
+ <div class="form-group">
+ <label class="form-label" for="email">Email</label>
+ <input id="email" v-model="email" type="email" class="form-input" placeholder="[email protected]" autocomplete="email" />
+ </div>
+ <div class="form-group">
+ <label class="form-label" for="password">Password</label>
+ <input id="password" v-model="password" type="password" class="form-input" placeholder="Enter your password" autocomplete="current-password" />
+ </div>
+ </template>
+ <template v-else>
+ <div class="form-group">
+ <label class="form-label" for="2fa-code">Authentication Code</label>
+ <input
+ id="2fa-code"
+ v-model="twoFactorCode"
+ type="text"
+ class="form-input totp-input"
+ placeholder="000000"
+ maxlength="6"
+ inputmode="numeric"
+ autocomplete="one-time-code"
+ autofocus
+ />
+ <small class="form-hint">Enter the 6-digit code from your authenticator app</small>
+ </div>
+ </template>
+ <button type="submit" class="btn btn-primary auth-btn" :disabled="loading">
+ <span v-if="loading" class="spinner"></span>
+ {{ loading ? 'Signing in...' : 'Sign in' }}
+ </button>
+ <button v-if="requires2FA" type="button" class="btn btn-secondary auth-btn" style="margin-top: 8px" @click="resetLogin">
+ Back to Login
+ </button>
+ </form>
+
+ <div class="auth-footer">
+ <template v-if="registrationEnabled">
+ <span>Don't have an account?</span>
+ <router-link to="/register">Sign up</router-link>
+ </template>
+ <span v-else>Contact your administrator for an account.</span>
+ </div>
+ </div>
+
+ <button class="theme-btn" @click="theme.toggle()" :title="theme.isDark ? 'Light mode' : 'Dark mode'">
+ <svg v-if="theme.isDark" width="18" height="18" viewBox="0 0 16 16" fill="none"><circle cx="8" cy="8" r="3" stroke="currentColor" stroke-width="1.5"/><path d="M8 1v2M8 13v2M1 8h2M13 8h2M3.05 3.05l1.41 1.41M11.54 11.54l1.41 1.41M3.05 12.95l1.41-1.41M11.54 4.46l1.41-1.41" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg>
+ <svg v-else width="18" height="18" viewBox="0 0 16 16" fill="none"><path d="M14 9.5A6.5 6.5 0 016.5 2 6.5 6.5 0 1014 9.5z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
+ </button>
+ </div>
+</template>
+
+<style scoped>
+.auth-page {
+ min-height: 100vh;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ background: var(--bg-secondary);
+ padding: 20px;
+ position: relative;
+}
+
+.auth-card {
+ width: 100%;
+ max-width: 400px;
+ background: var(--bg-primary);
+ border: 1px solid var(--border-primary);
+ border-radius: var(--radius-xl);
+ box-shadow: var(--shadow-lg);
+}
+
+.auth-header { text-align: center; padding: 36px 32px 0; }
+
+.auth-logo {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 10px;
+ margin-bottom: 10px;
+}
+.auth-logo .logo-img {
+ width: 100px;
+ height: 100px;
+ object-fit: contain;
+}
+.auth-logo span {
+ font-size: 32px;
+ font-weight: 800;
+ color: var(--text-primary);
+ letter-spacing: -0.5px;
+}
+
+.auth-subtitle { font-size: 14px; color: var(--text-muted); }
+
+.auth-form { padding: 28px 32px 20px; }
+
+.auth-btn {
+ width: 100%;
+ padding: 11px 18px;
+ font-size: 15px;
+ margin-top: 4px;
+}
+
+.totp-input {
+ font-size: 24px;
+ text-align: center;
+ letter-spacing: 8px;
+ font-family: 'JetBrains Mono', 'Fira Code', monospace;
+}
+
+.form-hint {
+ font-size: 12px;
+ color: var(--text-muted);
+ margin-top: 6px;
+}
+
+.auth-footer {
+ text-align: center;
+ padding: 0 32px 28px;
+ font-size: 14px;
+ color: var(--text-muted);
+ display: flex;
+ gap: 6px;
+ justify-content: center;
+}
+.auth-footer a { color: var(--primary-500); font-weight: 500; }
+
+.theme-btn {
+ position: fixed;
+ top: 20px;
+ right: 20px;
+ background: var(--bg-primary);
+ border: 1px solid var(--border-primary);
+ border-radius: var(--radius);
+ padding: 10px;
+ cursor: pointer;
+ color: var(--text-tertiary);
+ display: flex;
+ align-items: center;
+ transition: all var(--transition);
+ box-shadow: var(--shadow-sm);
+}
+.theme-btn:hover { color: var(--text-primary); border-color: var(--border-input); }
+</style>
diff --git a/web/src/views/auth/Profile.vue b/web/src/views/auth/Profile.vue
new file mode 100644
index 0000000..86f1c32
--- /dev/null
+++ b/web/src/views/auth/Profile.vue
@@ -0,0 +1,359 @@
+<script setup lang="ts">
+import { ref, onMounted } from 'vue'
+import { authApi } from '../../api/auth'
+import { useAuthStore } from '../../stores/auth'
+import { useNotificationStore } from '../../stores/notification'
+const auth = useAuthStore()
+const notify = useNotificationStore()
+
+// Profile
+const name = ref('')
+const email = ref('')
+const profileLoading = ref(false)
+const twoFactorEnabled = ref(false)
+
+onMounted(async () => {
+ name.value = auth.user?.name || ''
+ email.value = auth.user?.email || ''
+ // Fetch fresh profile to get 2FA status
+ try {
+ const res = await authApi.me()
+ twoFactorEnabled.value = res.data.data.two_factor_enabled
+ } catch { /* ignore */ }
+})
+
+async function handleProfileUpdate() {
+ if (!name.value.trim()) {
+ notify.error('Name is required')
+ return
+ }
+ profileLoading.value = true
+ try {
+ const res = await authApi.updateProfile({ name: name.value.trim() })
+ auth.user = res.data.data
+ localStorage.setItem('posta_user', JSON.stringify(res.data.data))
+ twoFactorEnabled.value = res.data.data.two_factor_enabled
+ notify.success('Profile updated successfully')
+ } catch (e: any) {
+ const message = e?.response?.data?.error?.message || 'Failed to update profile'
+ notify.error(message)
+ } finally {
+ profileLoading.value = false
+ }
+}
+
+// Password
+const currentPassword = ref('')
+const newPassword = ref('')
+const confirmPassword = ref('')
+const passwordLoading = ref(false)
+
+async function handlePasswordChange() {
+ if (!currentPassword.value || !newPassword.value || !confirmPassword.value) {
+ notify.error('Please fill in all fields')
+ return
+ }
+ if (newPassword.value.length < 8) {
+ notify.error('New password must be at least 8 characters')
+ return
+ }
+ if (newPassword.value !== confirmPassword.value) {
+ notify.error('New passwords do not match')
+ return
+ }
+ passwordLoading.value = true
+ try {
+ await authApi.changePassword(currentPassword.value, newPassword.value)
+ notify.success('Password changed successfully')
+ currentPassword.value = ''
+ newPassword.value = ''
+ confirmPassword.value = ''
+ } catch (e: any) {
+ const message = e?.response?.data?.error?.message || 'Failed to change password'
+ notify.error(message)
+ } finally {
+ passwordLoading.value = false
+ }
+}
+
+// 2FA
+const show2FASetup = ref(false)
+const tfaSecret = ref('')
+const tfaURL = ref('')
+const tfaCode = ref('')
+const tfaLoading = ref(false)
+const tfaDisableCode = ref('')
+const show2FADisable = ref(false)
+const tfaDisableLoading = ref(false)
+
+async function startSetup2FA() {
+ tfaLoading.value = true
+ try {
+ const res = await authApi.setup2FA()
+ tfaSecret.value = res.data.data.secret
+ tfaURL.value = res.data.data.url
+ show2FASetup.value = true
+ } catch (e: any) {
+ const message = e?.response?.data?.error?.message || 'Failed to setup 2FA'
+ notify.error(message)
+ } finally {
+ tfaLoading.value = false
+ }
+}
+
+async function verify2FA() {
+ if (!tfaCode.value || tfaCode.value.length !== 6) {
+ notify.error('Please enter a valid 6-digit code')
+ return
+ }
+ tfaLoading.value = true
+ try {
+ await authApi.verify2FA(tfaCode.value)
+ twoFactorEnabled.value = true
+ show2FASetup.value = false
+ tfaCode.value = ''
+ tfaSecret.value = ''
+ tfaURL.value = ''
+ notify.success('Two-factor authentication enabled')
+ } catch (e: any) {
+ const message = e?.response?.data?.error?.message || 'Invalid code. Please try again.'
+ notify.error(message)
+ } finally {
+ tfaLoading.value = false
+ }
+}
+
+async function disable2FA() {
+ if (!tfaDisableCode.value || tfaDisableCode.value.length !== 6) {
+ notify.error('Please enter a valid 6-digit code')
+ return
+ }
+ tfaDisableLoading.value = true
+ try {
+ await authApi.disable2FA(tfaDisableCode.value)
+ twoFactorEnabled.value = false
+ show2FADisable.value = false
+ tfaDisableCode.value = ''
+ notify.success('Two-factor authentication disabled')
+ } catch (e: any) {
+ const message = e?.response?.data?.error?.message || 'Invalid code. Please try again.'
+ notify.error(message)
+ } finally {
+ tfaDisableLoading.value = false
+ }
+}
+
+function cancel2FASetup() {
+ show2FASetup.value = false
+ tfaCode.value = ''
+ tfaSecret.value = ''
+ tfaURL.value = ''
+}
+</script>
+
+<template>
+ <div>
+ <div class="page-header">
+ <h1>Profile</h1>
+ </div>
+
+ <div class="profile-grid">
+ <!-- My Profile -->
+ <div class="card">
+ <div class="card-header"><h2>My Profile</h2></div>
+ <div class="card-body">
+ <form @submit.prevent="handleProfileUpdate" class="profile-form">
+ <div class="form-group">
+ <label class="form-label" for="profile-name">Name</label>
+ <input id="profile-name" v-model="name" type="text" class="form-input" placeholder="Your name" required />
+ </div>
+ <div class="form-group">
+ <label class="form-label" for="profile-email">Email</label>
+ <input id="profile-email" :value="email" type="email" class="form-input" disabled />
+ <small class="form-hint">Email cannot be changed</small>
+ </div>
+ <button type="submit" class="btn btn-primary" :disabled="profileLoading">
+ {{ profileLoading ? 'Saving...' : 'Save Changes' }}
+ </button>
+ </form>
+ </div>
+ </div>
+
+ <!-- Two-Factor Authentication -->
+ <div class="card">
+ <div class="card-header">
+ <h2>Two-Factor Authentication</h2>
+ <span v-if="twoFactorEnabled" class="badge badge-success">Enabled</span>
+ <span v-else class="badge badge-secondary">Disabled</span>
+ </div>
+ <div class="card-body">
+ <!-- 2FA Not Enabled -->
+ <template v-if="!twoFactorEnabled && !show2FASetup">
+ <p class="tfa-description">Add an extra layer of security to your account by requiring a code from your authenticator app.</p>
+ <button class="btn btn-primary" :disabled="tfaLoading" @click="startSetup2FA">
+ {{ tfaLoading ? 'Setting up...' : 'Enable 2FA' }}
+ </button>
+ </template>
+
+ <!-- 2FA Setup Flow -->
+ <template v-if="show2FASetup">
+ <div class="tfa-setup">
+ <p class="tfa-description">Scan this QR code with your authenticator app (Google Authenticator, Authy, etc.):</p>
+ <div class="tfa-qr">
+ <img :src="`https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(tfaURL)}`" alt="QR Code" width="200" height="200" />
+ </div>
+ <div class="tfa-secret-group">
+ <label class="form-label">Or enter this secret manually:</label>
+ <code class="tfa-secret">{{ tfaSecret }}</code>
+ </div>
+ <form @submit.prevent="verify2FA" class="profile-form" style="margin-top: 16px">
+ <div class="form-group">
+ <label class="form-label" for="tfa-code">Verification Code</label>
+ <input
+ id="tfa-code"
+ v-model="tfaCode"
+ type="text"
+ class="form-input totp-input"
+ placeholder="000000"
+ maxlength="6"
+ inputmode="numeric"
+ autocomplete="one-time-code"
+ />
+ <small class="form-hint">Enter the 6-digit code from your authenticator app to verify setup</small>
+ </div>
+ <div style="display: flex; gap: 8px">
+ <button type="submit" class="btn btn-primary" :disabled="tfaLoading">
+ {{ tfaLoading ? 'Verifying...' : 'Verify & Enable' }}
+ </button>
+ <button type="button" class="btn btn-secondary" @click="cancel2FASetup">Cancel</button>
+ </div>
+ </form>
+ </div>
+ </template>
+
+ <!-- 2FA Enabled -->
+ <template v-if="twoFactorEnabled && !show2FADisable">
+ <p class="tfa-description">Two-factor authentication is currently enabled on your account.</p>
+ <button class="btn btn-danger" @click="show2FADisable = true">Disable 2FA</button>
+ </template>
+
+ <!-- 2FA Disable Flow -->
+ <template v-if="show2FADisable">
+ <form @submit.prevent="disable2FA" class="profile-form">
+ <p class="tfa-description">Enter a code from your authenticator app to confirm disabling 2FA.</p>
+ <div class="form-group">
+ <label class="form-label" for="tfa-disable-code">Authentication Code</label>
+ <input
+ id="tfa-disable-code"
+ v-model="tfaDisableCode"
+ type="text"
+ class="form-input totp-input"
+ placeholder="000000"
+ maxlength="6"
+ inputmode="numeric"
+ autocomplete="one-time-code"
+ />
+ </div>
+ <div style="display: flex; gap: 8px">
+ <button type="submit" class="btn btn-danger" :disabled="tfaDisableLoading">
+ {{ tfaDisableLoading ? 'Disabling...' : 'Confirm Disable' }}
+ </button>
+ <button type="button" class="btn btn-secondary" @click="show2FADisable = false; tfaDisableCode = ''">Cancel</button>
+ </div>
+ </form>
+ </template>
+ </div>
+ </div>
+
+ <!-- Change Password -->
+ <div class="card">
+ <div class="card-header"><h2>Change Password</h2></div>
+ <div class="card-body">
+ <form @submit.prevent="handlePasswordChange" class="profile-form">
+ <div class="form-group">
+ <label class="form-label" for="current-password">Current Password</label>
+ <input id="current-password" v-model="currentPassword" type="password" class="form-input" placeholder="Enter current password" required autocomplete="current-password" />
+ </div>
+ <div class="form-group">
+ <label class="form-label" for="new-password">New Password</label>
+ <input id="new-password" v-model="newPassword" type="password" class="form-input" placeholder="Minimum 8 characters" required minlength="8" autocomplete="new-password" />
+ </div>
+ <div class="form-group">
+ <label class="form-label" for="confirm-password">Confirm New Password</label>
+ <input id="confirm-password" v-model="confirmPassword" type="password" class="form-input" placeholder="Re-enter new password" required minlength="8" autocomplete="new-password" />
+ </div>
+ <button type="submit" class="btn btn-primary" :disabled="passwordLoading">
+ {{ passwordLoading ? 'Updating...' : 'Change Password' }}
+ </button>
+ </form>
+ </div>
+ </div>
+ </div>
+ </div>
+</template>
+
+<style scoped>
+.profile-grid {
+ display: grid;
+ gap: 24px;
+ max-width: 640px;
+}
+
+.profile-form {
+ display: grid;
+ gap: 1rem;
+}
+
+.form-hint {
+ font-size: 12px;
+ color: var(--text-muted);
+ margin-top: 4px;
+}
+
+.tfa-description {
+ font-size: 13px;
+ color: var(--text-secondary);
+ margin-bottom: 16px;
+}
+
+.tfa-setup {
+ display: grid;
+ gap: 16px;
+}
+
+.tfa-qr {
+ display: flex;
+ justify-content: center;
+ padding: 16px;
+ background: #fff;
+ border-radius: var(--radius);
+ border: 1px solid var(--border-primary);
+ width: fit-content;
+}
+
+.tfa-secret-group {
+ display: grid;
+ gap: 6px;
+}
+
+.tfa-secret {
+ display: block;
+ padding: 10px 14px;
+ background: var(--bg-secondary);
+ border: 1px solid var(--border-primary);
+ border-radius: var(--radius);
+ font-size: 14px;
+ font-family: 'JetBrains Mono', 'Fira Code', monospace;
+ letter-spacing: 2px;
+ word-break: break-all;
+ user-select: all;
+}
+
+.totp-input {
+ font-size: 20px;
+ text-align: center;
+ letter-spacing: 8px;
+ font-family: 'JetBrains Mono', 'Fira Code', monospace;
+ max-width: 220px;
+}
+</style>
diff --git a/web/src/views/auth/Register.vue b/web/src/views/auth/Register.vue
new file mode 100644
index 0000000..e7a1937
--- /dev/null
+++ b/web/src/views/auth/Register.vue
@@ -0,0 +1,190 @@
+<script setup lang="ts">
+import { ref, onMounted } from 'vue'
+import { useRouter } from 'vue-router'
+import { authApi } from '../../api/auth'
+import { useAuthStore } from '../../stores/auth'
+import { useNotificationStore } from '../../stores/notification'
+import { useThemeStore } from '../../stores/theme'
+
+const router = useRouter()
+const auth = useAuthStore()
+const notification = useNotificationStore()
+const theme = useThemeStore()
+
+const name = ref('')
+const email = ref('')
+const password = ref('')
+const confirmPassword = ref('')
+const loading = ref(false)
+const registrationEnabled = ref<boolean | null>(null)
+
+onMounted(async () => {
+ try {
+ const res = await authApi.registrationStatus()
+ registrationEnabled.value = res.data.data.registration_enabled
+ if (!res.data.data.registration_enabled) {
+ router.replace('/login')
+ }
+ } catch {
+ router.replace('/login')
+ }
+})
+
+async function handleRegister() {
+ if (!name.value.trim() || !email.value || !password.value || !confirmPassword.value) {
+ notification.error('Please fill in all fields.')
+ return
+ }
+ if (password.value.length < 8) {
+ notification.error('Password must be at least 8 characters.')
+ return
+ }
+ if (password.value !== confirmPassword.value) {
+ notification.error('Passwords do not match.')
+ return
+ }
+ loading.value = true
+ try {
+ const res = await authApi.register(name.value.trim(), email.value.trim(), password.value)
+ // Auto-login with the returned token
+ const data = res.data.data
+ localStorage.setItem('posta_token', data.token)
+ localStorage.setItem('posta_user', JSON.stringify(data.user))
+ // Reload to pick up auth state
+ window.location.href = '/'
+ } catch (err: any) {
+ const message = err?.response?.data?.error?.message || err?.response?.data?.error || err?.message || 'Registration failed.'
+ notification.error(message)
+ } finally {
+ loading.value = false
+ }
+}
+</script>
+
+<template>
+ <div class="auth-page" v-if="registrationEnabled">
+ <div class="auth-card">
+ <div class="auth-header">
+ <div class="auth-logo">
+ <img src="/logo.png" alt="Posta" class="logo-img" />
+ <span>Posta</span>
+ </div>
+ <p class="auth-subtitle">Create your account</p>
+ </div>
+
+ <form class="auth-form" @submit.prevent="handleRegister">
+ <div class="form-group">
+ <label class="form-label" for="name">Name</label>
+ <input id="name" v-model="name" type="text" class="form-input" placeholder="Your name" autocomplete="name" />
+ </div>
+ <div class="form-group">
+ <label class="form-label" for="email">Email</label>
+ <input id="email" v-model="email" type="email" class="form-input" placeholder="[email protected]" autocomplete="email" />
+ </div>
+ <div class="form-group">
+ <label class="form-label" for="password">Password</label>
+ <input id="password" v-model="password" type="password" class="form-input" placeholder="Minimum 8 characters" autocomplete="new-password" />
+ </div>
+ <div class="form-group">
+ <label class="form-label" for="confirm-password">Confirm Password</label>
+ <input id="confirm-password" v-model="confirmPassword" type="password" class="form-input" placeholder="Re-enter your password" autocomplete="new-password" />
+ </div>
+ <button type="submit" class="btn btn-primary auth-btn" :disabled="loading">
+ <span v-if="loading" class="spinner"></span>
+ {{ loading ? 'Creating account...' : 'Create Account' }}
+ </button>
+ </form>
+
+ <div class="auth-footer">
+ <span>Already have an account?</span>
+ <router-link to="/login">Sign in</router-link>
+ </div>
+ </div>
+
+ <button class="theme-btn" @click="theme.toggle()" :title="theme.isDark ? 'Light mode' : 'Dark mode'">
+ <svg v-if="theme.isDark" width="18" height="18" viewBox="0 0 16 16" fill="none"><circle cx="8" cy="8" r="3" stroke="currentColor" stroke-width="1.5"/><path d="M8 1v2M8 13v2M1 8h2M13 8h2M3.05 3.05l1.41 1.41M11.54 11.54l1.41 1.41M3.05 12.95l1.41-1.41M11.54 4.46l1.41-1.41" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg>
+ <svg v-else width="18" height="18" viewBox="0 0 16 16" fill="none"><path d="M14 9.5A6.5 6.5 0 016.5 2 6.5 6.5 0 1014 9.5z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
+ </button>
+ </div>
+</template>
+
+<style scoped>
+.auth-page {
+ min-height: 100vh;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ background: var(--bg-secondary);
+ padding: 20px;
+ position: relative;
+}
+
+.auth-card {
+ width: 100%;
+ max-width: 400px;
+ background: var(--bg-primary);
+ border: 1px solid var(--border-primary);
+ border-radius: var(--radius-xl);
+ box-shadow: var(--shadow-lg);
+}
+
+.auth-header { text-align: center; padding: 36px 32px 0; }
+
+.auth-logo {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 10px;
+ margin-bottom: 10px;
+}
+.auth-logo .logo-img {
+ width: 80px;
+ height: 80px;
+ object-fit: contain;
+}
+.auth-logo span {
+ font-size: 26px;
+ font-weight: 800;
+ color: var(--text-primary);
+ letter-spacing: -0.5px;
+}
+
+.auth-subtitle { font-size: 14px; color: var(--text-muted); }
+
+.auth-form { padding: 28px 32px 20px; }
+
+.auth-btn {
+ width: 100%;
+ padding: 11px 18px;
+ font-size: 15px;
+ margin-top: 4px;
+}
+
+.auth-footer {
+ text-align: center;
+ padding: 0 32px 28px;
+ font-size: 14px;
+ color: var(--text-muted);
+ display: flex;
+ gap: 6px;
+ justify-content: center;
+}
+.auth-footer a { color: var(--primary-500); font-weight: 500; }
+
+.theme-btn {
+ position: fixed;
+ top: 20px;
+ right: 20px;
+ background: var(--bg-primary);
+ border: 1px solid var(--border-primary);
+ border-radius: var(--radius);
+ padding: 10px;
+ cursor: pointer;
+ color: var(--text-tertiary);
+ display: flex;
+ align-items: center;
+ transition: all var(--transition);
+ box-shadow: var(--shadow-sm);
+}
+.theme-btn:hover { color: var(--text-primary); border-color: var(--border-input); }
+</style>
diff --git a/web/src/views/bounces/Bounces.vue b/web/src/views/bounces/Bounces.vue
new file mode 100644
index 0000000..52edab2
--- /dev/null
+++ b/web/src/views/bounces/Bounces.vue
@@ -0,0 +1,259 @@
+<script setup lang="ts">
+import { ref, onMounted } from 'vue'
+import { bouncesApi, suppressionsApi } from '../../api/bounces'
+import type { Bounce, Suppression, Pageable } from '../../api/types'
+import { useNotificationStore } from '../../stores/notification'
+import { useConfirm } from '../../composables/useConfirm'
+
+const notify = useNotificationStore()
+const { confirm } = useConfirm()
+
+const activeTab = ref<'bounces' | 'suppressions'>('bounces')
+const loading = ref(true)
+
+const bounces = ref<Bounce[]>([])
+const bouncesPageable = ref<Pageable | null>(null)
+const bouncesPage = ref(0)
+
+const suppressions = ref<Suppression[]>([])
+const suppressionsPageable = ref<Pageable | null>(null)
+const suppressionsPage = ref(0)
+
+const showAddModal = ref(false)
+const addForm = ref({ email: '', reason: '' })
+
+onMounted(() => {
+ loadBounces()
+ loadSuppressions()
+})
+
+async function loadBounces() {
+ loading.value = true
+ try {
+ const res = await bouncesApi.list(bouncesPage.value)
+ bounces.value = res.data.data
+ bouncesPageable.value = res.data.pageable
+ } catch (e) {
+ notify.error('Failed to load bounces')
+ } finally {
+ loading.value = false
+ }
+}
+
+async function loadSuppressions() {
+ try {
+ const res = await suppressionsApi.list(suppressionsPage.value)
+ suppressions.value = res.data.data
+ suppressionsPageable.value = res.data.pageable
+ } catch (e) {
+ notify.error('Failed to load suppressions')
+ }
+}
+
+function switchTab(tab: 'bounces' | 'suppressions') {
+ activeTab.value = tab
+}
+
+function bounceBadgeClass(type: string) {
+ switch (type) {
+ case 'hard': return 'badge badge-danger'
+ case 'soft': return 'badge badge-warning'
+ case 'complaint': return 'badge badge-info'
+ default: return 'badge'
+ }
+}
+
+function formatDate(date: string) {
+ return new Date(date).toLocaleString()
+}
+
+async function changebouncesPage(page: number) {
+ bouncesPage.value = page
+ await loadBounces()
+}
+
+async function changeSuppressionsPage(page: number) {
+ suppressionsPage.value = page
+ await loadSuppressions()
+}
+
+async function deleteSuppression(email: string) {
+ const confirmed = await confirm({
+ title: 'Remove Suppression',
+ message: `Are you sure you want to remove "${email}" from the suppression list? This address will be able to receive emails again.`,
+ confirmText: 'Remove',
+ variant: 'warning',
+ })
+ if (!confirmed) return
+ try {
+ await suppressionsApi.delete(email)
+ notify.success('Suppression removed')
+ await loadSuppressions()
+ } catch (e) {
+ notify.error('Failed to remove suppression')
+ }
+}
+
+function openAddModal() {
+ addForm.value = { email: '', reason: '' }
+ showAddModal.value = true
+}
+
+async function addSuppression() {
+ if (!addForm.value.email) {
+ notify.error('Email is required')
+ return
+ }
+ try {
+ await suppressionsApi.create(addForm.value)
+ notify.success('Suppression added')
+ showAddModal.value = false
+ await loadSuppressions()
+ } catch (e) {
+ notify.error('Failed to add suppression')
+ }
+}
+</script>
+
+<template>
+ <div>
+ <div class="page-header">
+ <h1>Bounces & Suppressions</h1>
+ </div>
+
+ <div class="tabs">
+ <button class="tab" :class="{ active: activeTab === 'bounces' }" @click="switchTab('bounces')">Bounces</button>
+ <button class="tab" :class="{ active: activeTab === 'suppressions' }" @click="switchTab('suppressions')">Suppressions</button>
+ </div>
+
+ <div v-if="loading" class="loading-page">
+ <div class="spinner"></div>
+ </div>
+
+ <template v-else>
+ <!-- Bounces Tab -->
+ <div v-if="activeTab === 'bounces'" class="card">
+ <div class="card-header">
+ <h2>Bounces</h2>
+ </div>
+ <div v-if="bounces.length === 0" class="empty-state">
+ <h3>No bounces</h3>
+ <p>Bounced emails will appear here.</p>
+ </div>
+ <div v-else class="card-body">
+ <table class="table">
+ <thead>
+ <tr>
+ <th>Recipient</th>
+ <th>Type</th>
+ <th>Reason</th>
+ <th>Date</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr v-for="bounce in bounces" :key="bounce.id">
+ <td>{{ bounce.recipient }}</td>
+ <td><span :class="bounceBadgeClass(bounce.type)">{{ bounce.type }}</span></td>
+ <td>{{ bounce.reason }}</td>
+ <td>{{ formatDate(bounce.created_at) }}</td>
+ </tr>
+ </tbody>
+ </table>
+ <div v-if="bouncesPageable && bouncesPageable.total_pages > 1" class="pagination">
+ <button
+ class="btn btn-sm btn-secondary"
+ :disabled="bouncesPage === 0"
+ @click="changebouncesPage(bouncesPage - 1)"
+ >
+ Previous
+ </button>
+ <span>Page {{ bouncesPage + 1 }} of {{ bouncesPageable.total_pages }}</span>
+ <button
+ class="btn btn-sm btn-secondary"
+ :disabled="bouncesPage >= bouncesPageable.total_pages - 1"
+ @click="changebouncesPage(bouncesPage + 1)"
+ >
+ Next
+ </button>
+ </div>
+ </div>
+ </div>
+
+ <!-- Suppressions Tab -->
+ <div v-if="activeTab === 'suppressions'" class="card">
+ <div class="card-header">
+ <h2>Suppressions</h2>
+ <button class="btn btn-primary" @click="openAddModal">Add Suppression</button>
+ </div>
+ <div v-if="suppressions.length === 0" class="empty-state">
+ <h3>No suppressions</h3>
+ <p>Suppressed email addresses will appear here.</p>
+ </div>
+ <div v-else class="card-body">
+ <table class="table">
+ <thead>
+ <tr>
+ <th>Email</th>
+ <th>Reason</th>
+ <th>Created At</th>
+ <th>Actions</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr v-for="suppression in suppressions" :key="suppression.id">
+ <td>{{ suppression.email }}</td>
+ <td>{{ suppression.reason }}</td>
+ <td>{{ formatDate(suppression.created_at) }}</td>
+ <td>
+ <button class="btn btn-sm btn-danger" @click="deleteSuppression(suppression.email)">
+ Delete
+ </button>
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ <div v-if="suppressionsPageable && suppressionsPageable.total_pages > 1" class="pagination">
+ <button
+ class="btn btn-sm btn-secondary"
+ :disabled="suppressionsPage === 0"
+ @click="changeSuppressionsPage(suppressionsPage - 1)"
+ >
+ Previous
+ </button>
+ <span>Page {{ suppressionsPage + 1 }} of {{ suppressionsPageable.total_pages }}</span>
+ <button
+ class="btn btn-sm btn-secondary"
+ :disabled="suppressionsPage >= suppressionsPageable.total_pages - 1"
+ @click="changeSuppressionsPage(suppressionsPage + 1)"
+ >
+ Next
+ </button>
+ </div>
+ </div>
+ </div>
+ </template>
+
+ <!-- Add Suppression Modal -->
+ <div v-if="showAddModal" class="modal-overlay" @click.self="showAddModal = false">
+ <div class="modal">
+ <div class="modal-header">
+ <h2>Add Suppression</h2>
+ </div>
+ <div class="modal-body">
+ <div class="form-group">
+ <label class="form-label">Email</label>
+ <input v-model="addForm.email" type="email" class="form-input" placeholder="[email protected]" />
+ </div>
+ <div class="form-group">
+ <label class="form-label">Reason</label>
+ <input v-model="addForm.reason" type="text" class="form-input" placeholder="Reason for suppression" />
+ </div>
+ </div>
+ <div class="modal-footer">
+ <button class="btn btn-secondary" @click="showAddModal = false">Cancel</button>
+ <button class="btn btn-primary" @click="addSuppression">Add</button>
+ </div>
+ </div>
+ </div>
+ </div>
+</template>
diff --git a/web/src/views/contact-lists/ContactListMembers.vue b/web/src/views/contact-lists/ContactListMembers.vue
new file mode 100644
index 0000000..51a3b81
--- /dev/null
+++ b/web/src/views/contact-lists/ContactListMembers.vue
@@ -0,0 +1,216 @@
+<script setup lang="ts">
+import { ref, onMounted } from 'vue'
+import { useRoute, useRouter } from 'vue-router'
+import { contactListsApi } from '../../api/contactLists'
+import type { ContactListWithCount, ContactListMember, Pageable } from '../../api/types'
+import { useNotificationStore } from '../../stores/notification'
+import { useConfirm } from '../../composables/useConfirm'
+
+const route = useRoute()
+const router = useRouter()
+const notify = useNotificationStore()
+const { confirm } = useConfirm()
+
+const listId = Number(route.params.id)
+const list = ref<ContactListWithCount | null>(null)
+const members = ref<ContactListMember[]>([])
+const pageable = ref<Pageable>({ current_page: 0, size: 20, total_pages: 0, total_elements: 0, empty: true })
+const loading = ref(true)
+
+const showAddModal = ref(false)
+const addForm = ref({ email: '', name: '' })
+const addingMember = ref(false)
+
+async function loadList() {
+ try {
+ const res = await contactListsApi.list(0, 100)
+ list.value = res.data.data.find((l) => l.id === listId) || null
+ if (!list.value) {
+ notify.error('Contact list not found')
+ router.push({ name: 'contact-lists' })
+ }
+ } catch {
+ notify.error('Failed to load contact list')
+ router.push({ name: 'contact-lists' })
+ }
+}
+
+async function loadMembers(page = 0) {
+ loading.value = true
+ try {
+ const res = await contactListsApi.listMembers(listId, page, pageable.value.size)
+ members.value = res.data.data
+ pageable.value = res.data.pageable
+ } catch {
+ notify.error('Failed to load members')
+ } finally {
+ loading.value = false
+ }
+}
+
+function openAddModal() {
+ addForm.value = { email: '', name: '' }
+ showAddModal.value = true
+}
+
+async function addMember() {
+ if (!addForm.value.email.trim()) return
+ addingMember.value = true
+ try {
+ await contactListsApi.addMember(listId, addForm.value.email.trim(), addForm.value.name.trim())
+ notify.success('Member added')
+ showAddModal.value = false
+ await loadMembers(pageable.value.current_page)
+ await loadList()
+ } catch (e: any) {
+ notify.error(e?.response?.data?.error?.message || 'Failed to add member')
+ } finally {
+ addingMember.value = false
+ }
+}
+
+async function removeMember(member: ContactListMember) {
+ const confirmed = await confirm({
+ title: 'Remove Member',
+ message: `Remove "${member.email}" from this list?`,
+ confirmText: 'Remove',
+ variant: 'danger',
+ })
+ if (!confirmed) return
+ try {
+ await contactListsApi.removeMember(listId, member.email)
+ notify.success('Member removed')
+ await loadMembers(pageable.value.current_page)
+ await loadList()
+ } catch {
+ notify.error('Failed to remove member')
+ }
+}
+
+function formatDate(dateStr: string): string {
+ return new Date(dateStr).toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' })
+}
+
+onMounted(async () => {
+ await loadList()
+ await loadMembers()
+})
+</script>
+
+<template>
+ <div>
+ <div class="page-header">
+ <div>
+ <div class="breadcrumb">
+ <router-link :to="{ name: 'contact-lists' }">Contact Lists</router-link>
+ <span class="separator">/</span>
+ <span>{{ list?.name || '...' }}</span>
+ </div>
+ <h1>{{ list?.name || 'Members' }}</h1>
+ <p v-if="list?.description" class="page-description">{{ list.description }}</p>
+ </div>
+ <button class="btn btn-primary" @click="openAddModal">Add Member</button>
+ </div>
+
+ <div v-if="loading" class="loading-page">
+ <div class="spinner"></div>
+ </div>
+
+ <div v-else class="card">
+ <div v-if="members.length === 0" class="empty-state">
+ <h3>No Members</h3>
+ <p>Add members to this contact list.</p>
+ </div>
+
+ <template v-else>
+ <div class="table-wrapper">
+ <table>
+ <thead>
+ <tr>
+ <th>Email</th>
+ <th>Name</th>
+ <th>Added</th>
+ <th style="width: 1%"></th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr v-for="member in members" :key="member.id">
+ <td>{{ member.email }}</td>
+ <td>{{ member.name || '-' }}</td>
+ <td>{{ formatDate(member.created_at) }}</td>
+ <td>
+ <button class="btn btn-danger btn-sm" @click="removeMember(member)">Remove</button>
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+
+ <div class="pagination">
+ <span class="pagination-info">
+ Page {{ pageable.current_page + 1 }} of {{ pageable.total_pages }} ({{ pageable.total_elements }} members)
+ </span>
+ <div class="pagination-buttons">
+ <button class="btn btn-secondary btn-sm" :disabled="pageable.current_page === 0" @click="loadMembers(pageable.current_page - 1)">Previous</button>
+ <button class="btn btn-secondary btn-sm" :disabled="pageable.current_page >= pageable.total_pages - 1" @click="loadMembers(pageable.current_page + 1)">Next</button>
+ </div>
+ </div>
+ </template>
+ </div>
+
+ <!-- Add Member Modal -->
+ <div v-if="showAddModal" class="modal-overlay" @click.self="showAddModal = false">
+ <div class="modal">
+ <div class="modal-header">
+ <h2>Add Member</h2>
+ </div>
+ <div class="modal-body">
+ <div class="form-group">
+ <label class="form-label">Email</label>
+ <input v-model="addForm.email" type="email" class="form-input" placeholder="[email protected]" />
+ </div>
+ <div class="form-group">
+ <label class="form-label">Name</label>
+ <input v-model="addForm.name" type="text" class="form-input" placeholder="Name (optional)" />
+ </div>
+ </div>
+ <div class="modal-footer">
+ <button class="btn btn-secondary" @click="showAddModal = false">Cancel</button>
+ <button class="btn btn-primary" :disabled="addingMember || !addForm.email.trim()" @click="addMember">
+ {{ addingMember ? 'Adding...' : 'Add' }}
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+</template>
+
+<style scoped>
+.breadcrumb {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ font-size: 14px;
+ margin-bottom: 4px;
+ color: var(--text-secondary);
+}
+
+.breadcrumb a {
+ color: var(--primary-600);
+ text-decoration: none;
+}
+
+.breadcrumb a:hover {
+ text-decoration: underline;
+}
+
+.breadcrumb .separator {
+ color: var(--text-tertiary);
+}
+
+.page-description {
+ color: var(--text-secondary);
+ margin-top: 4px;
+ font-size: 14px;
+}
+</style>
diff --git a/web/src/views/contact-lists/ContactLists.vue b/web/src/views/contact-lists/ContactLists.vue
new file mode 100644
index 0000000..6555c87
--- /dev/null
+++ b/web/src/views/contact-lists/ContactLists.vue
@@ -0,0 +1,196 @@
+<script setup lang="ts">
+import { ref, onMounted } from 'vue'
+import { useRouter } from 'vue-router'
+import { contactListsApi } from '../../api/contactLists'
+import type { ContactListWithCount, Pageable } from '../../api/types'
+import { useNotificationStore } from '../../stores/notification'
+import { useConfirm } from '../../composables/useConfirm'
+
+const router = useRouter()
+const notify = useNotificationStore()
+const { confirm } = useConfirm()
+
+const lists = ref<ContactListWithCount[]>([])
+const pageable = ref<Pageable>({ current_page: 0, size: 20, total_pages: 0, total_elements: 0, empty: true })
+const loading = ref(true)
+
+// Create/Edit modal
+const showModal = ref(false)
+const editingId = ref<number | null>(null)
+const formName = ref('')
+const formDescription = ref('')
+const saving = ref(false)
+
+async function loadLists(page = 0) {
+ loading.value = true
+ try {
+ const res = await contactListsApi.list(page, pageable.value.size)
+ lists.value = res.data.data
+ pageable.value = res.data.pageable
+ } catch {
+ notify.error('Failed to load contact lists')
+ } finally {
+ loading.value = false
+ }
+}
+
+function openCreate() {
+ editingId.value = null
+ formName.value = ''
+ formDescription.value = ''
+ showModal.value = true
+}
+
+function openEdit(list: ContactListWithCount) {
+ editingId.value = list.id
+ formName.value = list.name
+ formDescription.value = list.description
+ showModal.value = true
+}
+
+async function saveList() {
+ if (!formName.value.trim()) return
+ saving.value = true
+ try {
+ if (editingId.value) {
+ await contactListsApi.update(editingId.value, formName.value.trim(), formDescription.value.trim())
+ notify.success('Contact list updated')
+ } else {
+ await contactListsApi.create(formName.value.trim(), formDescription.value.trim())
+ notify.success('Contact list created')
+ }
+ showModal.value = false
+ await loadLists(pageable.value.current_page)
+ } catch (e: any) {
+ notify.error(e?.response?.data?.error?.message || 'Failed to save contact list')
+ } finally {
+ saving.value = false
+ }
+}
+
+async function deleteList(list: ContactListWithCount) {
+ const confirmed = await confirm({
+ title: 'Delete Contact List',
+ message: `Are you sure you want to delete "${list.name}"? All members will be removed.`,
+ confirmText: 'Delete',
+ variant: 'danger',
+ })
+ if (!confirmed) return
+ try {
+ await contactListsApi.delete(list.id)
+ notify.success('Contact list deleted')
+ await loadLists(pageable.value.current_page)
+ } catch {
+ notify.error('Failed to delete contact list')
+ }
+}
+
+function openMembers(list: ContactListWithCount) {
+ router.push({ name: 'contact-list-members', params: { id: list.id } })
+}
+
+function formatDate(dateStr: string): string {
+ return new Date(dateStr).toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' })
+}
+
+onMounted(() => loadLists())
+</script>
+
+<template>
+ <div>
+ <div class="page-header">
+ <h1>Contact Lists</h1>
+ <button class="btn btn-primary" @click="openCreate">Create List</button>
+ </div>
+
+ <div v-if="loading" class="loading-page">
+ <div class="spinner"></div>
+ </div>
+
+ <div v-else class="card">
+ <div v-if="lists.length === 0" class="empty-state">
+ <h3>No Contact Lists</h3>
+ <p>Create a contact list to organize your recipients.</p>
+ </div>
+
+ <template v-else>
+ <div class="table-wrapper">
+ <table>
+ <thead>
+ <tr>
+ <th>Name</th>
+ <th>Description</th>
+ <th>Members</th>
+ <th>Created</th>
+ <th>Actions</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr v-for="list in lists" :key="list.id">
+ <td>
+ <a class="link" @click="openMembers(list)">{{ list.name }}</a>
+ </td>
+ <td>{{ list.description || '-' }}</td>
+ <td>{{ list.member_count }}</td>
+ <td>{{ formatDate(list.created_at) }}</td>
+ <td>
+ <div style="display: flex; gap: 6px">
+ <button class="btn btn-secondary btn-sm" @click="openMembers(list)">Members</button>
+ <button class="btn btn-secondary btn-sm" @click="openEdit(list)">Edit</button>
+ <button class="btn btn-danger btn-sm" @click="deleteList(list)">Delete</button>
+ </div>
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+
+ <div class="pagination">
+ <span class="pagination-info">
+ Page {{ pageable.current_page + 1 }} of {{ pageable.total_pages }} ({{ pageable.total_elements }} lists)
+ </span>
+ <div class="pagination-buttons">
+ <button class="btn btn-secondary btn-sm" :disabled="pageable.current_page === 0" @click="loadLists(pageable.current_page - 1)">Previous</button>
+ <button class="btn btn-secondary btn-sm" :disabled="pageable.current_page >= pageable.total_pages - 1" @click="loadLists(pageable.current_page + 1)">Next</button>
+ </div>
+ </div>
+ </template>
+ </div>
+
+ <!-- Create/Edit Modal -->
+ <div v-if="showModal" class="modal-overlay" @click.self="showModal = false">
+ <div class="modal">
+ <div class="modal-header">
+ <h3>{{ editingId ? 'Edit Contact List' : 'Create Contact List' }}</h3>
+ </div>
+ <div class="modal-body">
+ <div class="form-group">
+ <label class="form-label">Name</label>
+ <input v-model="formName" class="form-input" placeholder="e.g. Newsletter Subscribers" @keyup.enter="saveList" />
+ </div>
+ <div class="form-group">
+ <label class="form-label">Description</label>
+ <input v-model="formDescription" class="form-input" placeholder="Optional description" />
+ </div>
+ </div>
+ <div class="modal-footer">
+ <button class="btn btn-secondary" @click="showModal = false">Cancel</button>
+ <button class="btn btn-primary" :disabled="saving || !formName.trim()" @click="saveList">
+ {{ saving ? 'Saving...' : (editingId ? 'Update' : 'Create') }}
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+</template>
+
+<style scoped>
+.link {
+ color: var(--primary-600);
+ cursor: pointer;
+ font-weight: 500;
+}
+.link:hover {
+ text-decoration: underline;
+}
+</style>
diff --git a/web/src/views/contacts/ContactDetail.vue b/web/src/views/contacts/ContactDetail.vue
new file mode 100644
index 0000000..c73d54d
--- /dev/null
+++ b/web/src/views/contacts/ContactDetail.vue
@@ -0,0 +1,210 @@
+<script setup lang="ts">
+import { ref, onMounted } from 'vue'
+import { useRoute, useRouter } from 'vue-router'
+import { contactsApi } from '../../api/contacts'
+import { suppressionsApi } from '../../api/bounces'
+import { contactListsApi } from '../../api/contactLists'
+import type { Contact, ContactListWithCount } from '../../api/types'
+import { useNotificationStore } from '../../stores/notification'
+import { useConfirm } from '../../composables/useConfirm'
+
+const route = useRoute()
+const router = useRouter()
+const notify = useNotificationStore()
+const { confirm } = useConfirm()
+
+const loading = ref(true)
+const contact = ref<Contact | null>(null)
+const suppressingEmail = ref('')
+
+// Add to list modal
+const showAddToListModal = ref(false)
+const contactLists = ref<ContactListWithCount[]>([])
+const selectedListId = ref<number | null>(null)
+const addingToList = ref(false)
+
+onMounted(async () => {
+ try {
+ const id = Number(route.params.id)
+ const res = await contactsApi.get(id)
+ contact.value = res.data.data
+ } catch {
+ notify.error('Failed to load contact')
+ } finally {
+ loading.value = false
+ }
+})
+
+async function suppressContact() {
+ if (!contact.value) return
+ const confirmed = await confirm({
+ title: 'Suppress Contact',
+ message: `Are you sure you want to suppress "${contact.value.email}"? This contact will no longer receive emails.`,
+ confirmText: 'Suppress',
+ variant: 'warning',
+ })
+ if (!confirmed) return
+ suppressingEmail.value = contact.value.email
+ try {
+ await suppressionsApi.create({ email: contact.value.email, reason: 'Manually suppressed from contacts' })
+ notify.success(`${contact.value.email} has been suppressed.`)
+ contact.value = { ...contact.value, suppressed: true }
+ } catch (err: any) {
+ const message = err?.response?.data?.error?.message || err?.response?.data?.error || 'Failed to suppress contact.'
+ notify.error(message)
+ } finally {
+ suppressingEmail.value = ''
+ }
+}
+
+async function openAddToList() {
+ selectedListId.value = null
+ showAddToListModal.value = true
+ try {
+ const res = await contactListsApi.list(0, 100)
+ contactLists.value = res.data.data
+ } catch {
+ notify.error('Failed to load contact lists')
+ }
+}
+
+async function addToList() {
+ if (!selectedListId.value || !contact.value) return
+ addingToList.value = true
+ try {
+ await contactListsApi.addMember(selectedListId.value, contact.value.email, contact.value.name || '')
+ notify.success(`${contact.value.email} added to list.`)
+ showAddToListModal.value = false
+ } catch (err: any) {
+ notify.error(err?.response?.data?.error?.message || 'Failed to add to list')
+ } finally {
+ addingToList.value = false
+ }
+}
+
+function formatDate(date: string | null) {
+ if (!date) return '-'
+ return new Date(date).toLocaleString()
+}
+</script>
+
+<template>
+ <div>
+ <div class="page-header">
+ <h1>Contact Detail</h1>
+ <div style="display: flex; gap: 8px">
+ <button class="btn btn-secondary" @click="router.push('/contacts')">Back to Contacts</button>
+ </div>
+ </div>
+
+ <div v-if="loading" class="loading-page">
+ <div class="spinner"></div>
+ </div>
+
+ <template v-else-if="contact">
+ <div class="card" style="margin-bottom: 24px">
+ <div class="card-header">
+ <h2>{{ contact.email }}</h2>
+ <span v-if="contact.suppressed" class="badge badge-warning">Suppressed</span>
+ </div>
+ <div class="card-body">
+ <table>
+ <tbody>
+ <tr>
+ <td style="font-weight: 600; width: 140px">Email</td>
+ <td>{{ contact.email }}</td>
+ </tr>
+ <tr>
+ <td style="font-weight: 600">Name</td>
+ <td>{{ contact.name || '-' }}</td>
+ </tr>
+ <tr>
+ <td style="font-weight: 600">Sent Count</td>
+ <td>{{ contact.sent_count }}</td>
+ </tr>
+ <tr>
+ <td style="font-weight: 600">Failed Count</td>
+ <td>{{ contact.fail_count }}</td>
+ </tr>
+ <tr>
+ <td style="font-weight: 600">Last Sent</td>
+ <td>{{ formatDate(contact.last_sent_at) }}</td>
+ </tr>
+ <tr>
+ <td style="font-weight: 600">First Seen</td>
+ <td>{{ formatDate(contact.created_at) }}</td>
+ </tr>
+ <tr>
+ <td style="font-weight: 600">Status</td>
+ <td>
+ <span v-if="contact.suppressed" class="badge badge-warning">Suppressed</span>
+ <span v-else class="badge badge-success">Active</span>
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ </div>
+
+ <div class="card">
+ <div class="card-header">
+ <h2>Actions</h2>
+ </div>
+ <div class="card-body" style="display: flex; gap: 8px">
+ <button class="btn btn-secondary" @click="openAddToList">Add to List</button>
+ <button
+ v-if="!contact.suppressed"
+ class="btn btn-danger"
+ :disabled="suppressingEmail === contact.email"
+ @click="suppressContact"
+ >
+ {{ suppressingEmail === contact.email ? 'Suppressing...' : 'Suppress' }}
+ </button>
+ </div>
+ </div>
+ </template>
+
+ <div v-else class="empty-state">
+ <h3>Contact not found</h3>
+ <p>The contact you are looking for does not exist.</p>
+ </div>
+
+ <!-- Add to Contact List Modal -->
+ <div v-if="showAddToListModal" class="modal-overlay" @click.self="showAddToListModal = false">
+ <div class="modal">
+ <div class="modal-header">
+ <h2>Add to Contact List</h2>
+ </div>
+ <div class="modal-body">
+ <p style="margin-bottom: 12px">Add <strong>{{ contact?.email }}</strong> to a contact list:</p>
+ <div class="form-group">
+ <label class="form-label">Contact List</label>
+ <select v-model="selectedListId" class="form-input">
+ <option :value="null" disabled>Select a list...</option>
+ <option v-for="list in contactLists" :key="list.id" :value="list.id">
+ {{ list.name }} ({{ list.member_count }} members)
+ </option>
+ </select>
+ </div>
+ <div v-if="contactLists.length === 0" class="empty-hint">
+ No contact lists found. Create one first.
+ </div>
+ </div>
+ <div class="modal-footer">
+ <button class="btn btn-secondary" @click="showAddToListModal = false">Cancel</button>
+ <button class="btn btn-primary" :disabled="addingToList || !selectedListId" @click="addToList">
+ {{ addingToList ? 'Adding...' : 'Add' }}
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+</template>
+
+<style scoped>
+.empty-hint {
+ color: var(--text-secondary);
+ font-size: 13px;
+ font-style: italic;
+}
+</style>
diff --git a/web/src/views/contacts/Contacts.vue b/web/src/views/contacts/Contacts.vue
new file mode 100644
index 0000000..8049525
--- /dev/null
+++ b/web/src/views/contacts/Contacts.vue
@@ -0,0 +1,218 @@
+<script setup lang="ts">
+import { ref } from 'vue'
+import { useRouter } from 'vue-router'
+import { contactsApi } from '../../api/contacts'
+import { suppressionsApi } from '../../api/bounces'
+import { contactListsApi } from '../../api/contactLists'
+import type { Contact, ContactListWithCount } from '../../api/types'
+import Pagination from '../../components/Pagination.vue'
+import { usePagination } from '../../composables/usePagination'
+import { useNotificationStore } from '../../stores/notification'
+import { useConfirm } from '../../composables/useConfirm'
+
+const router = useRouter()
+const notify = useNotificationStore()
+const { confirm } = useConfirm()
+
+const contacts = ref<Contact[]>([])
+const loading = ref(true)
+const suppressingEmail = ref('')
+const search = ref('')
+let searchTimeout: ReturnType<typeof setTimeout> | null = null
+
+// Add to list modal
+const showAddToListModal = ref(false)
+const addToListContact = ref<Contact | null>(null)
+const contactLists = ref<ContactListWithCount[]>([])
+const selectedListId = ref<number | null>(null)
+const addingToList = ref(false)
+
+const { pageable, goToPage } = usePagination(loadContacts)
+
+async function loadContacts(page = 0) {
+ loading.value = true
+ try {
+ const res = await contactsApi.list(page, pageable.value.size, search.value)
+ contacts.value = res.data.data
+ pageable.value = res.data.pageable
+ } catch {
+ notify.error('Failed to load contacts')
+ } finally {
+ loading.value = false
+ }
+}
+
+function onSearchInput() {
+ if (searchTimeout) clearTimeout(searchTimeout)
+ searchTimeout = setTimeout(() => goToPage(0), 300)
+}
+
+async function suppressContact(contact: Contact) {
+ const confirmed = await confirm({
+ title: 'Suppress Contact',
+ message: `Are you sure you want to suppress "${contact.email}"? This contact will no longer receive emails.`,
+ confirmText: 'Suppress',
+ variant: 'warning',
+ })
+ if (!confirmed) return
+ suppressingEmail.value = contact.email
+ try {
+ await suppressionsApi.create({ email: contact.email, reason: 'Manually suppressed from contacts' })
+ notify.success(`${contact.email} has been suppressed.`)
+ await loadContacts(pageable.value.current_page)
+ } catch (err: any) {
+ const message = err?.response?.data?.error?.message || err?.response?.data?.error || 'Failed to suppress contact.'
+ notify.error(message)
+ } finally {
+ suppressingEmail.value = ''
+ }
+}
+
+async function openAddToList(contact: Contact) {
+ addToListContact.value = contact
+ selectedListId.value = null
+ showAddToListModal.value = true
+ try {
+ const res = await contactListsApi.list(0, 100)
+ contactLists.value = res.data.data
+ } catch {
+ notify.error('Failed to load contact lists')
+ }
+}
+
+async function addToList() {
+ if (!selectedListId.value || !addToListContact.value) return
+ addingToList.value = true
+ try {
+ await contactListsApi.addMember(selectedListId.value, addToListContact.value.email, addToListContact.value.name || '')
+ notify.success(`${addToListContact.value.email} added to list.`)
+ showAddToListModal.value = false
+ } catch (err: any) {
+ notify.error(err?.response?.data?.error?.message || 'Failed to add to list')
+ } finally {
+ addingToList.value = false
+ }
+}
+
+function formatDate(dateStr: string): string {
+ return new Date(dateStr).toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' })
+}
+
+</script>
+
+<template>
+ <div>
+ <div class="page-header">
+ <h1>Contacts</h1>
+ </div>
+
+ <div class="card">
+ <div class="card-header">
+ <input
+ v-model="search"
+ type="text"
+ class="form-input"
+ placeholder="Search by email or name..."
+ style="max-width: 320px"
+ @input="onSearchInput"
+ />
+ </div>
+
+ <div v-if="loading" class="loading-page">
+ <div class="spinner"></div>
+ </div>
+
+ <template v-else>
+ <div v-if="contacts.length === 0" class="empty-state">
+ <h3>No Contacts</h3>
+ <p v-if="search">No contacts matching "{{ search }}".</p>
+ <p v-else>Contacts will appear here once you start sending emails.</p>
+ </div>
+
+ <template v-else>
+ <div class="table-wrapper">
+ <table>
+ <thead>
+ <tr>
+ <th>Email</th>
+ <th>Name</th>
+ <th>Sent</th>
+ <th>Failed</th>
+ <th>Last Sent</th>
+ <th>First Seen</th>
+ <th style="width: 1%"></th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr v-for="contact in contacts" :key="contact.id" style="cursor: pointer" @click="router.push(`/contacts/${contact.id}`)">
+ <td>
+ {{ contact.email }}
+ <span v-if="contact.suppressed" class="badge badge-warning">Suppressed</span>
+ </td>
+ <td>{{ contact.name || '-' }}</td>
+ <td>{{ contact.sent_count }}</td>
+ <td>{{ contact.fail_count }}</td>
+ <td>{{ contact.last_sent_at ? formatDate(contact.last_sent_at) : 'Never' }}</td>
+ <td>{{ formatDate(contact.created_at) }}</td>
+ <td>
+ <div style="display: flex; gap: 6px; white-space: nowrap" @click.stop>
+ <button class="btn btn-secondary btn-sm" @click="openAddToList(contact)">Add to List</button>
+ <button
+ v-if="!contact.suppressed"
+ class="btn btn-danger btn-sm"
+ :disabled="suppressingEmail === contact.email"
+ @click="suppressContact(contact)"
+ >
+ {{ suppressingEmail === contact.email ? 'Suppressing...' : 'Suppress' }}
+ </button>
+ </div>
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+
+ <Pagination :pageable="pageable" @page="goToPage" />
+ </template>
+ </template>
+ </div>
+
+ <!-- Add to Contact List Modal -->
+ <div v-if="showAddToListModal" class="modal-overlay" @click.self="showAddToListModal = false">
+ <div class="modal">
+ <div class="modal-header">
+ <h2>Add to Contact List</h2>
+ </div>
+ <div class="modal-body">
+ <p style="margin-bottom: 12px">Add <strong>{{ addToListContact?.email }}</strong> to a contact list:</p>
+ <div class="form-group">
+ <label class="form-label">Contact List</label>
+ <select v-model="selectedListId" class="form-input">
+ <option :value="null" disabled>Select a list...</option>
+ <option v-for="list in contactLists" :key="list.id" :value="list.id">
+ {{ list.name }} ({{ list.member_count }} members)
+ </option>
+ </select>
+ </div>
+ <div v-if="contactLists.length === 0" class="empty-hint">
+ No contact lists found. Create one first.
+ </div>
+ </div>
+ <div class="modal-footer">
+ <button class="btn btn-secondary" @click="showAddToListModal = false">Cancel</button>
+ <button class="btn btn-primary" :disabled="addingToList || !selectedListId" @click="addToList">
+ {{ addingToList ? 'Adding...' : 'Add' }}
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+</template>
+
+<style scoped>
+.empty-hint {
+ color: var(--text-secondary);
+ font-size: 13px;
+ font-style: italic;
+}
+</style>
diff --git a/web/src/views/dashboard/Dashboard.vue b/web/src/views/dashboard/Dashboard.vue
new file mode 100644
index 0000000..3e76571
--- /dev/null
+++ b/web/src/views/dashboard/Dashboard.vue
@@ -0,0 +1,515 @@
+<script setup lang="ts">
+import { ref, computed, onMounted } from 'vue'
+import { useRouter } from 'vue-router'
+import { dashboardApi } from '../../api/dashboard'
+import { emailsApi } from '../../api/emails'
+import type { DashboardStats, Email } from '../../api/types'
+
+const router = useRouter()
+const loading = ref(true)
+const stats = ref<DashboardStats | null>(null)
+const recentEmails = ref<Email[]>([])
+
+onMounted(async () => {
+ try {
+ const [statsRes, emailsRes] = await Promise.all([
+ dashboardApi.getStats(),
+ emailsApi.list(0, 10),
+ ])
+ stats.value = statsRes.data.data
+ recentEmails.value = emailsRes.data.data
+ } catch (e) {
+ console.error('Failed to load dashboard data', e)
+ } finally {
+ loading.value = false
+ }
+})
+
+const chartMax = computed(() => {
+ if (!stats.value?.daily_volume) return 1
+ const max = Math.max(...stats.value.daily_volume.map(d => d.sent + d.failed))
+ return max || 1
+})
+
+function chartBarHeight(value: number): string {
+ const pct = (value / chartMax.value) * 100
+ return `${Math.max(pct, value > 0 ? 2 : 0)}%`
+}
+
+function formatChartDate(dateStr: string): string {
+ const d = new Date(dateStr + 'T00:00:00')
+ return d.toLocaleDateString(undefined, { month: 'short', day: 'numeric' })
+}
+
+function formatChartWeekday(dateStr: string): string {
+ const d = new Date(dateStr + 'T00:00:00')
+ return d.toLocaleDateString(undefined, { weekday: 'short' })
+}
+
+function statusBadgeClass(status: string) {
+ switch (status) {
+ case 'sent': return 'badge badge-success'
+ case 'failed': return 'badge badge-danger'
+ case 'pending': return 'badge badge-warning'
+ case 'queued': return 'badge badge-info'
+ case 'processing': return 'badge badge-warning'
+ case 'suppressed': return 'badge badge-secondary'
+ case 'scheduled': return 'badge badge-info'
+ default: return 'badge'
+ }
+}
+
+function formatDate(date: string | null) {
+ if (!date) return '-'
+ return new Date(date).toLocaleString()
+}
+
+function formatNumber(n: number): string {
+ if (n >= 1_000_000) return (n / 1_000_000).toFixed(1) + 'M'
+ if (n >= 10_000) return (n / 1_000).toFixed(1) + 'K'
+ return n.toLocaleString()
+}
+
+const deliveryRate = computed(() => {
+ if (!stats.value || stats.value.total_emails === 0) return 0
+ return ((stats.value.sent_emails / stats.value.total_emails) * 100)
+})
+
+const totalVolume14d = computed(() => {
+ if (!stats.value?.daily_volume) return 0
+ return stats.value.daily_volume.reduce((sum, d) => sum + d.sent + d.failed, 0)
+})
+</script>
+
+<template>
+ <div>
+ <div class="page-header">
+ <h1>Dashboard</h1>
+ </div>
+
+ <div v-if="loading" class="loading-page">
+ <div class="spinner"></div>
+ </div>
+
+ <template v-else-if="stats">
+ <!-- Primary stats row -->
+ <div class="stats-grid">
+ <div class="stat-card">
+ <div class="stat-header">
+ <div class="stat-label">Total Emails</div>
+ <div class="stat-icon stat-icon-primary">
+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>
+ </div>
+ </div>
+ <div class="stat-value">{{ formatNumber(stats.total_emails) }}</div>
+ </div>
+ <div class="stat-card">
+ <div class="stat-header">
+ <div class="stat-label">Sent</div>
+ <div class="stat-icon stat-icon-success">
+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
+ </div>
+ </div>
+ <div class="stat-value">{{ formatNumber(stats.sent_emails) }}</div>
+ <div class="stat-sub">{{ deliveryRate.toFixed(1) }}% delivery rate</div>
+ </div>
+ <div class="stat-card">
+ <div class="stat-header">
+ <div class="stat-label">Failed</div>
+ <div class="stat-icon stat-icon-danger">
+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>
+ </div>
+ </div>
+ <div class="stat-value">{{ formatNumber(stats.failed_emails) }}</div>
+ <div class="stat-sub">{{ stats.failure_rate.toFixed(1) }}% failure rate</div>
+ </div>
+ <div v-if="stats.queued_emails > 0 || stats.processing_emails > 0" class="stat-card">
+ <div class="stat-header">
+ <div class="stat-label">In Queue</div>
+ <div class="stat-icon stat-icon-info">
+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
+ </div>
+ </div>
+ <div class="stat-value">{{ formatNumber(stats.queued_emails + stats.processing_emails) }}</div>
+ </div>
+ </div>
+
+ <!-- Daily volume chart -->
+ <div class="card" style="margin-top: 20px">
+ <div class="card-header">
+ <h2>Send Volume <span style="font-weight: 400; font-size: 13px; color: var(--text-muted)">Last 14 days &middot; {{ formatNumber(totalVolume14d) }} emails</span></h2>
+ </div>
+ <div class="volume-chart">
+ <div class="volume-chart-bars">
+ <div
+ v-for="day in stats.daily_volume"
+ :key="day.date"
+ class="volume-bar-group"
+ :title="`${formatChartDate(day.date)}: ${day.sent} sent, ${day.failed} failed`"
+ >
+ <div class="volume-bar-stack">
+ <div class="volume-bar volume-bar-failed" :style="{ height: chartBarHeight(day.failed) }"></div>
+ <div class="volume-bar volume-bar-sent" :style="{ height: chartBarHeight(day.sent) }"></div>
+ </div>
+ <div class="volume-bar-label">{{ formatChartWeekday(day.date) }}</div>
+ </div>
+ </div>
+ <div class="volume-chart-legend">
+ <span class="volume-legend-item"><span class="volume-legend-dot volume-legend-sent"></span> Sent</span>
+ <span class="volume-legend-item"><span class="volume-legend-dot volume-legend-failed"></span> Failed</span>
+ </div>
+ </div>
+ </div>
+
+ <!-- Webhook Deliveries -->
+ <div v-if="stats.webhook_deliveries && stats.webhook_deliveries.total_deliveries > 0" class="card" style="margin-top: 20px">
+ <div class="card-header" style="display: flex; justify-content: space-between; align-items: center">
+ <h2>Webhook Deliveries</h2>
+ <button class="btn btn-secondary btn-sm" @click="router.push('/webhooks')">Manage Webhooks</button>
+ </div>
+ <div class="card-body">
+ <div class="wh-stats-row">
+ <div class="wh-stat">
+ <div class="wh-stat-value">{{ formatNumber(stats.webhook_deliveries.total_deliveries) }}</div>
+ <div class="wh-stat-label">Total</div>
+ </div>
+ <div class="wh-stat">
+ <div class="wh-stat-value wh-stat-success">{{ formatNumber(stats.webhook_deliveries.success_deliveries) }}</div>
+ <div class="wh-stat-label">Successful</div>
+ </div>
+ <div class="wh-stat">
+ <div class="wh-stat-value wh-stat-failed">{{ formatNumber(stats.webhook_deliveries.failed_deliveries) }}</div>
+ <div class="wh-stat-label">Failed</div>
+ </div>
+ <div class="wh-stat">
+ <div class="wh-stat-value" :class="stats.webhook_deliveries.success_rate >= 95 ? 'wh-stat-success' : stats.webhook_deliveries.success_rate >= 80 ? 'wh-stat-warning' : 'wh-stat-failed'">
+ {{ stats.webhook_deliveries.success_rate.toFixed(1) }}%
+ </div>
+ <div class="wh-stat-label">Success Rate</div>
+ </div>
+ </div>
+ <div class="wh-delivery-bar" v-if="stats.webhook_deliveries.total_deliveries > 0">
+ <div class="wh-delivery-segment wh-delivery-success" :style="{ width: stats.webhook_deliveries.success_rate + '%' }"></div>
+ <div class="wh-delivery-segment wh-delivery-failed" :style="{ width: (100 - stats.webhook_deliveries.success_rate) + '%' }"></div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Two-column layout: Infrastructure + Deliverability -->
+ <div class="dashboard-grid" style="margin-top: 20px">
+ <!-- Infrastructure -->
+ <div class="card">
+ <div class="card-header">
+ <h2>Infrastructure</h2>
+ </div>
+ <div class="dashboard-metric-list">
+ <div class="dashboard-metric" @click="router.push('/api-keys')" style="cursor: pointer">
+ <div class="dashboard-metric-label">
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m21 2-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0 3 3L22 7l-3-3m-3.5 3.5L19 4"/></svg>
+ API Keys
+ </div>
+ <div class="dashboard-metric-value">
+ <span>{{ stats.active_api_keys }}</span>
+ <span class="dashboard-metric-secondary">/ {{ stats.total_api_keys }}</span>
+ </div>
+ </div>
+ <div class="dashboard-metric" @click="router.push('/domains')" style="cursor: pointer">
+ <div class="dashboard-metric-label">
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>
+ Domains
+ </div>
+ <div class="dashboard-metric-value">{{ stats.total_domains }}</div>
+ </div>
+ <div class="dashboard-metric" @click="router.push('/smtp-servers')" style="cursor: pointer">
+ <div class="dashboard-metric-label">
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="2" width="20" height="8" rx="2"/><rect x="2" y="14" width="20" height="8" rx="2"/><line x1="6" y1="6" x2="6.01" y2="6"/><line x1="6" y1="18" x2="6.01" y2="18"/></svg>
+ SMTP Servers
+ </div>
+ <div class="dashboard-metric-value">{{ stats.total_smtp_servers }}</div>
+ </div>
+ <div class="dashboard-metric" @click="router.push('/webhooks')" style="cursor: pointer">
+ <div class="dashboard-metric-label">
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 16.98h-5.99c-1.1 0-1.95.68-2.95 1.76C8.07 19.82 6.22 20 5 20c-1.22 0-2.2-.38-3-1"/><path d="M18 16.98h-5.99c-1.66 0-2.61-1.22-3.15-2.59C8.23 12.64 8 10.66 8 9c0-3.87 3.13-7 7-7"/><circle cx="12" cy="12" r="2"/></svg>
+ Webhooks
+ </div>
+ <div class="dashboard-metric-value">{{ stats.total_webhooks }}</div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Deliverability -->
+ <div class="card">
+ <div class="card-header">
+ <h2>Deliverability</h2>
+ </div>
+ <div class="dashboard-metric-list">
+ <div class="dashboard-metric" @click="router.push('/contacts')" style="cursor: pointer">
+ <div class="dashboard-metric-label">
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>
+ Contacts
+ </div>
+ <div class="dashboard-metric-value">{{ formatNumber(stats.total_contacts) }}</div>
+ </div>
+ <div class="dashboard-metric">
+ <div class="dashboard-metric-label">
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="4.93" y1="4.93" x2="19.07" y2="19.07"/></svg>
+ Suppressed
+ </div>
+ <div class="dashboard-metric-value">{{ formatNumber(stats.suppressed_emails) }}</div>
+ </div>
+ <div class="dashboard-metric" @click="router.push('/bounces')" style="cursor: pointer">
+ <div class="dashboard-metric-label">
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 17 4 12 9 7"/><path d="M20 18v-2a4 4 0 0 0-4-4H4"/></svg>
+ Bounces
+ </div>
+ <div class="dashboard-metric-value">{{ formatNumber(stats.total_bounces) }}</div>
+ </div>
+ <div class="dashboard-metric">
+ <div class="dashboard-metric-label">
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>
+ Suppressions
+ </div>
+ <div class="dashboard-metric-value">{{ formatNumber(stats.total_suppressions) }}</div>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Recent Emails -->
+ <div class="card" style="margin-top: 20px">
+ <div class="card-header" style="display: flex; justify-content: space-between; align-items: center">
+ <h2>Recent Emails</h2>
+ <button class="btn btn-secondary btn-sm" @click="router.push('/emails')">View All</button>
+ </div>
+ <div v-if="recentEmails.length === 0" class="empty-state">
+ <h3>No emails yet</h3>
+ <p>Emails sent through the API will appear here.</p>
+ </div>
+ <div v-else class="table-wrapper">
+ <table>
+ <thead>
+ <tr>
+ <th>Subject</th>
+ <th>Recipients</th>
+ <th>Status</th>
+ <th>Date</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr
+ v-for="email in recentEmails"
+ :key="email.uuid"
+ style="cursor: pointer"
+ @click="router.push(`/emails/${email.uuid}`)"
+ >
+ <td>{{ email.subject }}</td>
+ <td>{{ email.recipients.join(', ') }}</td>
+ <td><span :class="statusBadgeClass(email.status)">{{ email.status }}</span></td>
+ <td>{{ formatDate(email.created_at) }}</td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ </div>
+ </template>
+ </div>
+</template>
+
+<style scoped>
+.dashboard-grid {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 16px;
+}
+
+@media (max-width: 768px) {
+ .dashboard-grid {
+ grid-template-columns: 1fr;
+ }
+}
+
+.dashboard-metric-list {
+ padding: 4px 0;
+}
+
+.dashboard-metric {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ padding: 12px 16px;
+ border-bottom: 1px solid var(--border-light);
+ transition: background 0.15s ease;
+}
+
+.dashboard-metric:last-child {
+ border-bottom: none;
+}
+
+.dashboard-metric:hover {
+ background: var(--bg-secondary);
+}
+
+.dashboard-metric-label {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ font-size: 14px;
+ color: var(--text-secondary);
+}
+
+.dashboard-metric-label svg {
+ color: var(--text-muted);
+ flex-shrink: 0;
+}
+
+.dashboard-metric-value {
+ font-size: 15px;
+ font-weight: 600;
+ color: var(--text-primary);
+}
+
+.dashboard-metric-secondary {
+ font-weight: 400;
+ color: var(--text-muted);
+ font-size: 13px;
+}
+
+/* Webhook delivery stats */
+.wh-stats-row {
+ display: flex;
+ gap: 24px;
+ margin-bottom: 16px;
+}
+
+.wh-stat {
+ flex: 1;
+ text-align: center;
+}
+
+.wh-stat-value {
+ font-size: 22px;
+ font-weight: 700;
+ color: var(--text-primary);
+}
+
+.wh-stat-label {
+ font-size: 12px;
+ color: var(--text-muted);
+ margin-top: 2px;
+}
+
+.wh-stat-success { color: var(--success-600, #16a34a); }
+.wh-stat-failed { color: var(--danger-600, #dc2626); }
+.wh-stat-warning { color: var(--warning-600, #ca8a04); }
+
+.wh-delivery-bar {
+ display: flex;
+ height: 8px;
+ border-radius: 4px;
+ overflow: hidden;
+ background: var(--bg-tertiary);
+}
+
+.wh-delivery-segment {
+ transition: width 0.4s ease;
+ min-width: 0;
+}
+
+.wh-delivery-success { background: var(--success-500, #22c55e); }
+.wh-delivery-failed { background: var(--danger-500, #ef4444); }
+
+/* Volume chart */
+.volume-chart {
+ padding: 16px;
+}
+
+.volume-chart-bars {
+ display: flex;
+ align-items: flex-end;
+ gap: 4px;
+ height: 140px;
+ padding-bottom: 24px;
+ position: relative;
+}
+
+.volume-bar-group {
+ flex: 1;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ height: 100%;
+ position: relative;
+}
+
+.volume-bar-stack {
+ flex: 1;
+ width: 100%;
+ max-width: 36px;
+ display: flex;
+ flex-direction: column;
+ justify-content: flex-end;
+ position: relative;
+}
+
+.volume-bar {
+ width: 100%;
+ border-radius: 3px 3px 0 0;
+ min-width: 0;
+ transition: height 0.3s ease;
+}
+
+.volume-bar-sent {
+ background: var(--primary-500);
+}
+
+.volume-bar-failed {
+ background: var(--danger-400);
+ border-radius: 3px 3px 0 0;
+}
+
+.volume-bar-sent + .volume-bar-failed,
+.volume-bar-failed + .volume-bar-sent {
+ border-radius: 0;
+}
+
+.volume-bar-stack .volume-bar:first-child {
+ border-radius: 3px 3px 0 0;
+}
+
+.volume-bar-label {
+ position: absolute;
+ bottom: -22px;
+ font-size: 11px;
+ color: var(--text-muted);
+ white-space: nowrap;
+}
+
+.volume-chart-legend {
+ display: flex;
+ gap: 16px;
+ justify-content: center;
+ margin-top: 12px;
+}
+
+.volume-legend-item {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ font-size: 12px;
+ color: var(--text-muted);
+}
+
+.volume-legend-dot {
+ width: 10px;
+ height: 10px;
+ border-radius: 2px;
+}
+
+.volume-legend-sent {
+ background: var(--primary-500);
+}
+
+.volume-legend-failed {
+ background: var(--danger-400);
+}
+</style>
diff --git a/web/src/views/domains/Domains.vue b/web/src/views/domains/Domains.vue
new file mode 100644
index 0000000..ea2880c
--- /dev/null
+++ b/web/src/views/domains/Domains.vue
@@ -0,0 +1,260 @@
+<script setup lang="ts">
+import { ref, onMounted } from 'vue'
+import { domainsApi } from '../../api/domains'
+import type { Domain, Pageable } from '../../api/types'
+import { useNotificationStore } from '../../stores/notification'
+import { useConfirm } from '../../composables/useConfirm'
+
+const notify = useNotificationStore()
+const { confirm } = useConfirm()
+
+const domains = ref<Domain[]>([])
+const pageable = ref<Pageable | null>(null)
+const loading = ref(true)
+const currentPage = ref(0)
+
+const showAddModal = ref(false)
+const newDomain = ref('')
+const saving = ref(false)
+
+const expandedDomainId = ref<number | null>(null)
+const dnsLoading = ref(false)
+const dnsRecordsDomain = ref<Domain | null>(null)
+
+async function fetchDomains() {
+ loading.value = true
+ try {
+ const res = await domainsApi.list(currentPage.value)
+ domains.value = res.data.data
+ pageable.value = res.data.pageable
+ } catch {
+ notify.error('Failed to load domains')
+ } finally {
+ loading.value = false
+ }
+}
+
+async function addDomain() {
+ if (!newDomain.value.trim()) return
+ saving.value = true
+ try {
+ await domainsApi.create(newDomain.value.trim())
+ notify.success('Domain added')
+ showAddModal.value = false
+ newDomain.value = ''
+ await fetchDomains()
+ } catch {
+ notify.error('Failed to add domain')
+ } finally {
+ saving.value = false
+ }
+}
+
+async function verifyDomain(domain: Domain) {
+ try {
+ await domainsApi.verify(domain.id)
+ notify.success(`Verification initiated for ${domain.domain}`)
+ await fetchDomains()
+ } catch {
+ notify.error('Verification failed')
+ }
+}
+
+async function viewDnsRecords(domain: Domain) {
+ if (expandedDomainId.value === domain.id) {
+ expandedDomainId.value = null
+ dnsRecordsDomain.value = null
+ return
+ }
+ dnsLoading.value = true
+ expandedDomainId.value = domain.id
+ try {
+ const res = await domainsApi.get(domain.id)
+ dnsRecordsDomain.value = res.data.data
+ } catch {
+ notify.error('Failed to load DNS records')
+ expandedDomainId.value = null
+ } finally {
+ dnsLoading.value = false
+ }
+}
+
+async function deleteDomain(domain: Domain) {
+ const confirmed = await confirm({
+ title: 'Delete Domain',
+ message: `Are you sure you want to delete "${domain.domain}"? This will remove all associated DNS records and verification status.`,
+ confirmText: 'Delete',
+ variant: 'danger',
+ })
+ if (!confirmed) return
+ try {
+ await domainsApi.delete(domain.id)
+ notify.success('Domain deleted')
+ if (expandedDomainId.value === domain.id) {
+ expandedDomainId.value = null
+ dnsRecordsDomain.value = null
+ }
+ await fetchDomains()
+ } catch {
+ notify.error('Failed to delete domain')
+ }
+}
+
+function prevPage() {
+ if (currentPage.value > 0) {
+ currentPage.value--
+ fetchDomains()
+ }
+}
+
+function nextPage() {
+ if (pageable.value && currentPage.value < pageable.value.total_pages - 1) {
+ currentPage.value++
+ fetchDomains()
+ }
+}
+
+onMounted(fetchDomains)
+</script>
+
+<template>
+ <div>
+ <div class="page-header">
+ <h1>Domains</h1>
+ <button class="btn btn-primary" @click="showAddModal = true">Add Domain</button>
+ </div>
+
+ <div v-if="loading" class="loading-page">
+ <div class="spinner"></div>
+ </div>
+
+ <template v-else>
+ <div class="card">
+ <div class="table-wrapper" v-if="domains.length > 0">
+ <table>
+ <thead>
+ <tr>
+ <th>Domain</th>
+ <th>Ownership</th>
+ <th>SPF</th>
+ <th>DKIM</th>
+ <th>DMARC</th>
+ <th>Actions</th>
+ </tr>
+ </thead>
+ <tbody>
+ <template v-for="domain in domains" :key="domain.id">
+ <tr>
+ <td>{{ domain.domain }}</td>
+ <td>
+ <span v-if="domain.ownership_verified" class="verified">&#10003;</span>
+ <span v-else class="unverified">&#10005;</span>
+ </td>
+ <td>
+ <span v-if="domain.spf_verified" class="verified">&#10003;</span>
+ <span v-else class="unverified">&#10005;</span>
+ </td>
+ <td>
+ <span v-if="domain.dkim_verified" class="verified">&#10003;</span>
+ <span v-else class="unverified">&#10005;</span>
+ </td>
+ <td>
+ <span v-if="domain.dmarc_verified" class="verified">&#10003;</span>
+ <span v-else class="unverified">&#10005;</span>
+ </td>
+ <td>
+ <div class="flex gap-2">
+ <button class="btn btn-secondary btn-sm" @click="verifyDomain(domain)">Verify</button>
+ <button class="btn btn-secondary btn-sm" @click="viewDnsRecords(domain)">
+ {{ expandedDomainId === domain.id ? 'Hide DNS' : 'View DNS Records' }}
+ </button>
+ <button class="btn btn-danger btn-sm" @click="deleteDomain(domain)">Delete</button>
+ </div>
+ </td>
+ </tr>
+ <tr v-if="expandedDomainId === domain.id">
+ <td colspan="6" style="padding: 20px 16px; background: var(--bg-tertiary);">
+ <div v-if="dnsLoading" class="loading-page" style="min-height: 100px;">
+ <div class="spinner"></div>
+ </div>
+ <div v-else-if="dnsRecordsDomain && dnsRecordsDomain.dns_records">
+ <h4 style="margin-bottom: 12px; font-size: 14px; font-weight: 600; color: var(--text-secondary);">
+ Required DNS Records for {{ domain.domain }}
+ </h4>
+ <div class="dns-record dns-record-highlight">
+ <div class="dns-label">Ownership Verification</div>
+ <div class="dns-type">{{ dnsRecordsDomain.dns_records.verification.type }}</div>
+ <div class="dns-name">{{ dnsRecordsDomain.dns_records.verification.name }}</div>
+ <div class="dns-value">{{ dnsRecordsDomain.dns_records.verification.value }}</div>
+ </div>
+ <div class="dns-record">
+ <div class="dns-label">SPF</div>
+ <div class="dns-type">{{ dnsRecordsDomain.dns_records.spf.type }}</div>
+ <div class="dns-name">{{ dnsRecordsDomain.dns_records.spf.name }}</div>
+ <div class="dns-value">{{ dnsRecordsDomain.dns_records.spf.value }}</div>
+ </div>
+ <div class="dns-record">
+ <div class="dns-label">DKIM</div>
+ <div class="dns-type">{{ dnsRecordsDomain.dns_records.dkim.type }}</div>
+ <div class="dns-name">{{ dnsRecordsDomain.dns_records.dkim.name }}</div>
+ <div class="dns-value">{{ dnsRecordsDomain.dns_records.dkim.value }}</div>
+ </div>
+ <div class="dns-record">
+ <div class="dns-label">DMARC</div>
+ <div class="dns-type">{{ dnsRecordsDomain.dns_records.dmarc.type }}</div>
+ <div class="dns-name">{{ dnsRecordsDomain.dns_records.dmarc.name }}</div>
+ <div class="dns-value">{{ dnsRecordsDomain.dns_records.dmarc.value }}</div>
+ </div>
+ </div>
+ <div v-else class="text-muted text-sm">
+ No DNS records available for this domain.
+ </div>
+ </td>
+ </tr>
+ </template>
+ </tbody>
+ </table>
+ </div>
+
+ <div v-else class="empty-state">
+ <h3>No domains</h3>
+ <p>Add a domain to verify your sending identity.</p>
+ </div>
+
+ <div v-if="pageable && !pageable.empty" class="pagination">
+ <span class="pagination-info">
+ Page {{ pageable.current_page + 1 }} of {{ pageable.total_pages }}
+ ({{ pageable.total_elements }} total)
+ </span>
+ <div class="pagination-buttons">
+ <button class="btn btn-secondary btn-sm" :disabled="currentPage === 0" @click="prevPage">Previous</button>
+ <button class="btn btn-secondary btn-sm" :disabled="currentPage >= pageable.total_pages - 1" @click="nextPage">Next</button>
+ </div>
+ </div>
+ </div>
+ </template>
+
+ <!-- Add Domain Modal -->
+ <div v-if="showAddModal" class="modal-overlay" @click.self="showAddModal = false">
+ <div class="modal">
+ <div class="modal-header">
+ <h3>Add Domain</h3>
+ </div>
+ <form @submit.prevent="addDomain">
+ <div class="modal-body">
+ <div class="form-group">
+ <label class="form-label">Domain</label>
+ <input v-model="newDomain" type="text" class="form-input" placeholder="example.com" required />
+ </div>
+ </div>
+ <div class="modal-footer">
+ <button type="button" class="btn btn-secondary" @click="showAddModal = false">Cancel</button>
+ <button type="submit" class="btn btn-primary" :disabled="saving">
+ {{ saving ? 'Adding...' : 'Add Domain' }}
+ </button>
+ </div>
+ </form>
+ </div>
+ </div>
+ </div>
+</template>
diff --git a/web/src/views/emails/EmailDetail.vue b/web/src/views/emails/EmailDetail.vue
new file mode 100644
index 0000000..1268061
--- /dev/null
+++ b/web/src/views/emails/EmailDetail.vue
@@ -0,0 +1,184 @@
+<script setup lang="ts">
+import { ref, onMounted } from 'vue'
+import { useRoute, useRouter } from 'vue-router'
+import { emailsApi } from '../../api/emails'
+import { useNotificationStore } from '../../stores/notification'
+import type { Email } from '../../api/types'
+
+const route = useRoute()
+const router = useRouter()
+const notification = useNotificationStore()
+const loading = ref(true)
+const retrying = ref(false)
+const email = ref<Email | null>(null)
+const activeTab = ref<'html' | 'text'>('html')
+
+onMounted(async () => {
+ try {
+ const uuid = route.params.id as string
+ const res = await emailsApi.get(uuid)
+ email.value = res.data.data
+ } catch (e) {
+ console.error('Failed to load email', e)
+ } finally {
+ loading.value = false
+ }
+})
+
+async function retryEmail() {
+ if (!email.value || retrying.value) return
+ retrying.value = true
+ try {
+ const res = await emailsApi.retry(email.value.uuid)
+ email.value.status = res.data.data.status as Email['status']
+ email.value.error_message = ''
+ notification.success('Email re-queued for delivery')
+ } catch (e: any) {
+ const msg = e.response?.data?.error?.message || 'Failed to retry email'
+ notification.error(msg)
+ } finally {
+ retrying.value = false
+ }
+}
+
+function statusBadgeClass(status: string) {
+ switch (status) {
+ case 'sent': return 'badge badge-success'
+ case 'failed': return 'badge badge-danger'
+ case 'pending': return 'badge badge-warning'
+ case 'queued': return 'badge badge-info'
+ case 'processing': return 'badge badge-warning'
+ case 'suppressed': return 'badge badge-secondary'
+ case 'scheduled': return 'badge badge-info'
+ default: return 'badge'
+ }
+}
+
+function formatDate(date: string | null) {
+ if (!date) return '-'
+ return new Date(date).toLocaleString()
+}
+
+function parseHeaders(json: string): Record<string, string> | null {
+ if (!json) return null
+ try {
+ const parsed = JSON.parse(json)
+ if (Object.keys(parsed).length === 0) return null
+ return parsed
+ } catch { return null }
+}
+</script>
+
+<template>
+ <div>
+ <div class="page-header">
+ <h1>Email Detail</h1>
+ <div style="display: flex; gap: 8px">
+ <button
+ v-if="email && email.status === 'failed'"
+ class="btn btn-primary"
+ :disabled="retrying"
+ @click="retryEmail"
+ >
+ {{ retrying ? 'Retrying...' : 'Retry' }}
+ </button>
+ <button class="btn btn-secondary" @click="router.push('/emails')">Back to Emails</button>
+ </div>
+ </div>
+
+ <div v-if="loading" class="loading-page">
+ <div class="spinner"></div>
+ </div>
+
+ <template v-else-if="email">
+ <div class="card" style="margin-bottom: 24px">
+ <div class="card-header">
+ <h2>{{ email.subject }}</h2>
+ <span :class="statusBadgeClass(email.status)">{{ email.status }}</span>
+ </div>
+ <div class="card-body">
+ <table>
+ <tbody>
+ <tr>
+ <td style="font-weight: 600; width: 140px">From</td>
+ <td>{{ email.sender }}</td>
+ </tr>
+ <tr>
+ <td style="font-weight: 600">To</td>
+ <td>{{ email.recipients.join(', ') }}</td>
+ </tr>
+ <tr>
+ <td style="font-weight: 600">Status</td>
+ <td><span :class="statusBadgeClass(email.status)">{{ email.status }}</span></td>
+ </tr>
+ <tr>
+ <td style="font-weight: 600">Created At</td>
+ <td>{{ formatDate(email.created_at) }}</td>
+ </tr>
+ <tr>
+ <td style="font-weight: 600">Sent At</td>
+ <td>{{ formatDate(email.sent_at) }}</td>
+ </tr>
+ <tr v-if="email.scheduled_at">
+ <td style="font-weight: 600">Scheduled At</td>
+ <td>{{ formatDate(email.scheduled_at) }}</td>
+ </tr>
+ <tr>
+ <td style="font-weight: 600">SMTP Server</td>
+ <td>{{ email.smtp_hostname || 'N/A' }}</td>
+ </tr>
+ <tr>
+ <td style="font-weight: 600">Retry Count</td>
+ <td>{{ email.retry_count }}</td>
+ </tr>
+ <tr v-if="email.list_unsubscribe_url">
+ <td style="font-weight: 600">List-Unsubscribe</td>
+ <td>
+ <code style="font-size: 12px">{{ email.list_unsubscribe_url }}</code>
+ <span v-if="email.list_unsubscribe_post" class="badge badge-info" style="margin-left: 8px">One-Click</span>
+ </td>
+ </tr>
+ <tr v-if="parseHeaders(email.headers_json)">
+ <td style="font-weight: 600">Custom Headers</td>
+ <td>
+ <div v-for="(value, key) in parseHeaders(email.headers_json)" :key="key" style="font-size: 12px; margin-bottom: 2px">
+ <code>{{ key }}: {{ value }}</code>
+ </div>
+ </td>
+ </tr>
+ <tr v-if="(email.status === 'failed' || email.status === 'suppressed') && email.error_message">
+ <td style="font-weight: 600">Error</td>
+ <td style="color: var(--danger-600)">{{ email.error_message }}</td>
+ </tr>
+ </tbody>
+ </table>
+ </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'">Text Content</button>
+ </div>
+ </div>
+ <div class="card-body">
+ <iframe
+ v-if="activeTab === 'html'"
+ :srcdoc="email.html_body"
+ style="width: 100%; min-height: 400px; border: 1px solid var(--border-primary); border-radius: var(--radius)"
+ ></iframe>
+ <pre
+ v-else
+ style="white-space: pre-wrap; word-wrap: break-word; font-size: 14px; color: var(--text-secondary); line-height: 1.6"
+ >{{ email.text_body }}</pre>
+ </div>
+ </div>
+ </template>
+
+ <div v-else class="empty-state">
+ <h3>Email not found</h3>
+ <p>The email you are looking for does not exist.</p>
+ </div>
+ </div>
+</template>
diff --git a/web/src/views/emails/Emails.vue b/web/src/views/emails/Emails.vue
new file mode 100644
index 0000000..e04c437
--- /dev/null
+++ b/web/src/views/emails/Emails.vue
@@ -0,0 +1,92 @@
+<script setup lang="ts">
+import { ref } from 'vue'
+import { useRouter } from 'vue-router'
+import { emailsApi } from '../../api/emails'
+import type { Email } from '../../api/types'
+import Pagination from '../../components/Pagination.vue'
+import { usePagination } from '../../composables/usePagination'
+
+const router = useRouter()
+const loading = ref(true)
+const emails = ref<Email[]>([])
+
+const { pageable, goToPage } = usePagination(async (page) => {
+ loading.value = true
+ try {
+ const res = await emailsApi.list(page)
+ emails.value = res.data.data
+ pageable.value = res.data.pageable
+ } catch (e) {
+ console.error('Failed to load emails', e)
+ } finally {
+ loading.value = false
+ }
+})
+
+function statusBadgeClass(status: string) {
+ switch (status) {
+ case 'sent': return 'badge badge-success'
+ case 'failed': return 'badge badge-danger'
+ case 'pending': return 'badge badge-warning'
+ case 'queued': return 'badge badge-info'
+ case 'processing': return 'badge badge-warning'
+ case 'suppressed': return 'badge badge-secondary'
+ case 'scheduled': return 'badge badge-info'
+ default: return 'badge'
+ }
+}
+
+function formatDate(date: string | null) {
+ if (!date) return '-'
+ return new Date(date).toLocaleString()
+}
+</script>
+
+<template>
+ <div>
+ <div class="page-header">
+ <h1>Email Logs</h1>
+ </div>
+
+ <div v-if="loading" class="loading-page">
+ <div class="spinner"></div>
+ </div>
+
+ <div v-else class="card">
+ <div v-if="emails.length === 0" class="empty-state">
+ <h3>No emails found</h3>
+ <p>Emails sent through the API will appear here.</p>
+ </div>
+ <template v-else>
+ <div class="table-wrapper">
+ <table>
+ <thead>
+ <tr>
+ <th>Subject</th>
+ <th>From</th>
+ <th>Recipients</th>
+ <th>Status</th>
+ <th>Sent At</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr
+ v-for="email in emails"
+ :key="email.uuid"
+ style="cursor: pointer"
+ @click="router.push(`/emails/${email.uuid}`)"
+ >
+ <td>{{ email.subject }}</td>
+ <td>{{ email.sender }}</td>
+ <td>{{ email.recipients.join(', ') }}</td>
+ <td><span :class="statusBadgeClass(email.status)">{{ email.status }}</span></td>
+ <td>{{ formatDate(email.sent_at) }}</td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ <Pagination :pageable="pageable" @page="goToPage" />
+ </template>
+ </div>
+ </div>
+</template>
diff --git a/web/src/views/languages/Languages.vue b/web/src/views/languages/Languages.vue
new file mode 100644
index 0000000..b566f53
--- /dev/null
+++ b/web/src/views/languages/Languages.vue
@@ -0,0 +1,203 @@
+<script setup lang="ts">
+import { ref, onMounted } from 'vue'
+import { languagesApi } from '../../api/languages'
+import type { Language, LanguageInput, Pageable } from '../../api/types'
+import { useNotificationStore } from '../../stores/notification'
+import { useConfirm } from '../../composables/useConfirm'
+
+const notify = useNotificationStore()
+const { confirm } = useConfirm()
+
+const languages = ref<Language[]>([])
+const pageable = ref<Pageable>({ current_page: 0, size: 20, total_pages: 0, total_elements: 0, empty: true })
+const loading = ref(true)
+
+const showModal = ref(false)
+const editing = ref<Language | null>(null)
+const saving = ref(false)
+
+const form = ref<LanguageInput>({
+ code: '',
+ name: '',
+})
+
+function resetForm() {
+ form.value = { code: '', name: '' }
+ editing.value = null
+}
+
+function openCreate() {
+ resetForm()
+ showModal.value = true
+}
+
+function openEdit(lang: Language) {
+ editing.value = lang
+ form.value = {
+ code: lang.code,
+ name: lang.name,
+ }
+ showModal.value = true
+}
+
+function closeModal() {
+ showModal.value = false
+ resetForm()
+}
+
+async function loadLanguages(page = 0) {
+ loading.value = true
+ try {
+ const res = await languagesApi.list(page, pageable.value.size)
+ languages.value = res.data.data
+ pageable.value = res.data.pageable
+ } catch {
+ notify.error('Failed to load languages')
+ } finally {
+ loading.value = false
+ }
+}
+
+async function saveLanguage() {
+ if (!form.value.code.trim() || !form.value.name.trim()) return
+ saving.value = true
+ try {
+ if (editing.value) {
+ await languagesApi.update(editing.value.id, form.value)
+ notify.success('Language updated')
+ } else {
+ await languagesApi.create(form.value)
+ notify.success('Language created')
+ }
+ closeModal()
+ await loadLanguages(pageable.value.current_page)
+ } catch {
+ notify.error(editing.value ? 'Failed to update language' : 'Language code already exists')
+ } finally {
+ saving.value = false
+ }
+}
+
+async function deleteLanguage(lang: Language) {
+ const confirmed = await confirm({
+ title: 'Delete Language',
+ message: `Are you sure you want to delete "${lang.name} (${lang.code})"?`,
+ confirmText: 'Delete',
+ variant: 'danger',
+ })
+ if (!confirmed) return
+ try {
+ await languagesApi.delete(lang.id)
+ notify.success('Language deleted')
+ await loadLanguages(pageable.value.current_page)
+ } catch {
+ notify.error('Failed to delete language')
+ }
+}
+
+function formatDate(dateStr: string): string {
+ return new Date(dateStr).toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' })
+}
+
+onMounted(() => loadLanguages())
+</script>
+
+<template>
+ <div>
+ <div class="page-header">
+ <h1>Languages</h1>
+ <button class="btn btn-primary" @click="openCreate">Add Language</button>
+ </div>
+
+ <div v-if="loading" class="loading-page">
+ <div class="spinner"></div>
+ </div>
+
+ <div v-else class="card">
+ <div v-if="languages.length === 0" class="empty-state">
+ <h3>No Languages</h3>
+ <p>Add languages to use for template localizations.</p>
+ </div>
+
+ <template v-else>
+ <div class="table-wrapper">
+ <table>
+ <thead>
+ <tr>
+ <th>Code</th>
+ <th>Name</th>
+ <th>Created</th>
+ <th>Actions</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr v-for="lang in languages" :key="lang.id">
+ <td><span class="badge badge-neutral">{{ lang.code }}</span></td>
+ <td>{{ lang.name }}</td>
+ <td>{{ formatDate(lang.created_at) }}</td>
+ <td>
+ <div class="flex gap-2">
+ <button class="btn btn-secondary btn-sm" @click="openEdit(lang)">Edit</button>
+ <button class="btn btn-danger btn-sm" @click="deleteLanguage(lang)">Delete</button>
+ </div>
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+
+ <div class="pagination">
+ <span class="pagination-info">
+ Page {{ pageable.current_page + 1 }} of {{ pageable.total_pages }} ({{ pageable.total_elements }} languages)
+ </span>
+ <div class="pagination-buttons">
+ <button
+ class="btn btn-secondary btn-sm"
+ :disabled="pageable.current_page === 0"
+ @click="loadLanguages(pageable.current_page - 1)"
+ >
+ Previous
+ </button>
+ <button
+ class="btn btn-secondary btn-sm"
+ :disabled="pageable.current_page >= pageable.total_pages - 1"
+ @click="loadLanguages(pageable.current_page + 1)"
+ >
+ Next
+ </button>
+ </div>
+ </div>
+ </template>
+ </div>
+
+ <!-- Create/Edit Language Modal -->
+ <div v-if="showModal" class="modal-overlay" @click.self="closeModal">
+ <div class="modal" style="max-width: 480px;">
+ <div class="modal-header">
+ <h3>{{ editing ? 'Edit Language' : 'Add Language' }}</h3>
+ </div>
+ <div class="modal-body">
+ <div class="form-group">
+ <label class="form-label">Code</label>
+ <input v-model="form.code" class="form-input" placeholder="e.g. en, fr, de" maxlength="10" />
+ <span class="form-hint">ISO 639-1 language code</span>
+ </div>
+ <div class="form-group">
+ <label class="form-label">Name</label>
+ <input v-model="form.name" class="form-input" placeholder="e.g. English, French" />
+ </div>
+ </div>
+ <div class="modal-footer">
+ <button class="btn btn-secondary" @click="closeModal">Cancel</button>
+ <button
+ class="btn btn-primary"
+ :disabled="saving || !form.code.trim() || !form.name.trim()"
+ @click="saveLanguage"
+ >
+ {{ saving ? 'Saving...' : (editing ? 'Update' : 'Create') }}
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+</template>
diff --git a/web/src/views/settings/Settings.vue b/web/src/views/settings/Settings.vue
new file mode 100644
index 0000000..fed1a3e
--- /dev/null
+++ b/web/src/views/settings/Settings.vue
@@ -0,0 +1,397 @@
+<script setup lang="ts">
+import { ref, onMounted } from 'vue'
+import { settingsApi } from '../../api/settings'
+import { authApi } from '../../api/auth'
+import { useAuthStore } from '../../stores/auth'
+import { useThemeStore, type ThemeMode } from '../../stores/theme'
+import { useNotificationStore } from '../../stores/notification'
+import type { UserSettings } from '../../api/types'
+
+const auth = useAuthStore()
+const theme = useThemeStore()
+const notify = useNotificationStore()
+const loading = ref(true)
+const saving = ref(false)
+
+const form = ref<Partial<UserSettings>>({
+ timezone: 'UTC',
+ default_sender_name: '',
+ default_sender_email: '',
+ email_notifications: true,
+ notification_email: '',
+ webhook_retry_count: 3,
+ api_key_expiry_days: 90,
+ bounce_auto_suppress: true,
+ daily_report: false,
+})
+
+const timezones = [
+ 'UTC', 'America/New_York', 'America/Chicago', 'America/Denver', 'America/Los_Angeles',
+ 'Europe/London', 'Europe/Paris', 'Europe/Berlin', 'Europe/Moscow',
+ 'Asia/Tokyo', 'Asia/Shanghai', 'Asia/Kolkata', 'Asia/Dubai',
+ 'Australia/Sydney', 'Pacific/Auckland','Africa/Kinshasa', 'Africa/Nairobi', 'Africa/Lagos','Africa/Lubumbashi',
+]
+
+// Domain Security
+const requireVerifiedDomain = ref(false)
+const domainSecurityLoading = ref(false)
+
+// Theme
+const themeModes: { value: ThemeMode; label: string; icon: string }[] = [
+ { value: 'light', label: 'Light', icon: 'sun' },
+ { value: 'dark', label: 'Dark', icon: 'moon' },
+ { value: 'system', label: 'System', icon: 'monitor' },
+]
+
+onMounted(async () => {
+ try {
+ const [settingsRes, profileRes] = await Promise.all([
+ settingsApi.getUserSettings(),
+ authApi.me(),
+ ])
+ const s = settingsRes.data.data
+ form.value = {
+ timezone: s.timezone || 'UTC',
+ default_sender_name: s.default_sender_name || '',
+ default_sender_email: s.default_sender_email || '',
+ email_notifications: s.email_notifications,
+ notification_email: s.notification_email || '',
+ webhook_retry_count: s.webhook_retry_count,
+ api_key_expiry_days: s.api_key_expiry_days,
+ bounce_auto_suppress: s.bounce_auto_suppress,
+ daily_report: s.daily_report,
+ }
+ requireVerifiedDomain.value = profileRes.data.data.require_verified_domain
+ } catch {
+ notify.error('Failed to load settings')
+ } finally {
+ loading.value = false
+ }
+})
+
+async function save() {
+ saving.value = true
+ try {
+ const res = await settingsApi.updateUserSettings(form.value)
+ const s = res.data.data
+ form.value = {
+ timezone: s.timezone,
+ default_sender_name: s.default_sender_name,
+ default_sender_email: s.default_sender_email,
+ email_notifications: s.email_notifications,
+ notification_email: s.notification_email,
+ webhook_retry_count: s.webhook_retry_count,
+ api_key_expiry_days: s.api_key_expiry_days,
+ bounce_auto_suppress: s.bounce_auto_suppress,
+ daily_report: s.daily_report,
+ }
+ notify.success('Settings saved')
+ } catch {
+ notify.error('Failed to save settings')
+ } finally {
+ saving.value = false
+ }
+}
+
+async function toggleDomainSecurity() {
+ domainSecurityLoading.value = true
+ try {
+ const res = await authApi.updateProfile({
+ name: auth.user?.name || '',
+ require_verified_domain: !requireVerifiedDomain.value,
+ })
+ auth.user = res.data.data
+ localStorage.setItem('posta_user', JSON.stringify(res.data.data))
+ requireVerifiedDomain.value = res.data.data.require_verified_domain
+ notify.success(requireVerifiedDomain.value ? 'Strict domain mode enabled' : 'Strict domain mode disabled')
+ } catch (e: any) {
+ const message = e?.response?.data?.error?.message || 'Failed to update setting'
+ notify.error(message)
+ } finally {
+ domainSecurityLoading.value = false
+ }
+}
+</script>
+
+<template>
+ <div>
+ <div class="page-header">
+ <h1>Settings</h1>
+ </div>
+
+ <div v-if="loading" class="loading-page">
+ <div class="spinner"></div>
+ </div>
+
+ <div v-else class="settings-grid">
+ <!-- General -->
+ <div class="card">
+ <div class="card-header"><h2>General</h2></div>
+ <div class="card-body">
+ <form @submit.prevent="save" class="settings-form">
+ <div class="form-group">
+ <label class="form-label">Timezone</label>
+ <select v-model="form.timezone" class="form-select">
+ <option v-for="tz in timezones" :key="tz" :value="tz">{{ tz }}</option>
+ </select>
+ <span class="form-hint">Used for displaying timestamps and scheduling emails.</span>
+ </div>
+ <div class="form-group">
+ <label class="form-label">Default Sender Name</label>
+ <input v-model="form.default_sender_name" type="text" class="form-input" placeholder="e.g. My Company" />
+ <span class="form-hint">Pre-filled sender name when sending emails.</span>
+ </div>
+ <div class="form-group">
+ <label class="form-label">Default Sender Email</label>
+ <input v-model="form.default_sender_email" type="email" class="form-input" placeholder="e.g. [email protected]" />
+ <span class="form-hint">Pre-filled sender address when sending emails.</span>
+ </div>
+ <button type="submit" class="btn btn-primary" :disabled="saving">
+ {{ saving ? 'Saving...' : 'Save Changes' }}
+ </button>
+ </form>
+ </div>
+ </div>
+
+ <!-- Notifications -->
+ <div class="card">
+ <div class="card-header"><h2>Notifications</h2></div>
+ <div class="card-body">
+ <div class="toggle-row">
+ <div>
+ <label class="toggle-label">Email Notifications</label>
+ <span class="form-hint">Receive notifications on failures, bounces, etc.</span>
+ </div>
+ <button
+ :class="['toggle-btn', { active: form.email_notifications }]"
+ @click="form.email_notifications = !form.email_notifications"
+ >
+ <span class="toggle-slider"></span>
+ </button>
+ </div>
+ <div class="form-group" style="margin-top: 16px">
+ <label class="form-label">Notification Email</label>
+ <input v-model="form.notification_email" type="email" class="form-input" placeholder="Defaults to your login email" />
+ <span class="form-hint">Where to send notifications (can differ from your login email).</span>
+ </div>
+ <div class="toggle-row" style="margin-top: 16px">
+ <div>
+ <label class="toggle-label">Daily Report</label>
+ <span class="form-hint">Receive a daily email summary of send statistics.</span>
+ </div>
+ <button
+ :class="['toggle-btn', { active: form.daily_report }]"
+ @click="form.daily_report = !form.daily_report"
+ >
+ <span class="toggle-slider"></span>
+ </button>
+ </div>
+ </div>
+ </div>
+
+ <!-- Email Delivery -->
+ <div class="card">
+ <div class="card-header"><h2>Email Delivery</h2></div>
+ <div class="card-body">
+ <div class="form-group">
+ <label class="form-label">Webhook Retry Count</label>
+ <input v-model.number="form.webhook_retry_count" type="number" class="form-input" min="0" max="10" />
+ <span class="form-hint">How many times to retry failed webhook deliveries.</span>
+ </div>
+ <div class="toggle-row" style="margin-top: 16px">
+ <div>
+ <label class="toggle-label">Auto-Suppress on Bounce</label>
+ <span class="form-hint">Automatically add to suppression list on hard bounce.</span>
+ </div>
+ <button
+ :class="['toggle-btn', { active: form.bounce_auto_suppress }]"
+ @click="form.bounce_auto_suppress = !form.bounce_auto_suppress"
+ >
+ <span class="toggle-slider"></span>
+ </button>
+ </div>
+ </div>
+ </div>
+
+ <!-- Domain Security -->
+ <div class="card">
+ <div class="card-header">
+ <h2>Domain Security</h2>
+ <span v-if="requireVerifiedDomain" class="badge badge-success">Strict</span>
+ <span v-else class="badge badge-secondary">Permissive</span>
+ </div>
+ <div class="card-body">
+ <p class="section-description">
+ When strict domain mode is enabled, emails can only be sent from domains you have registered and verified via DNS TXT record.
+ This prevents sending from unverified domains and protects your sender reputation.
+ </p>
+ <div class="toggle-row">
+ <label class="toggle-label">Require verified domain</label>
+ <button
+ :class="['toggle-btn', { active: requireVerifiedDomain }]"
+ :disabled="domainSecurityLoading"
+ @click="toggleDomainSecurity"
+ >
+ <span class="toggle-slider"></span>
+ </button>
+ </div>
+ </div>
+ </div>
+
+ <!-- API & Templates -->
+ <div class="card">
+ <div class="card-header"><h2>API & Templates</h2></div>
+ <div class="card-body">
+ <div class="form-group">
+ <label class="form-label">Default API Key Expiry (days)</label>
+ <input v-model.number="form.api_key_expiry_days" type="number" class="form-input" min="1" max="365" />
+ <span class="form-hint">Default expiration period for newly created API keys.</span>
+ </div>
+ </div>
+ </div>
+
+ <!-- Theme -->
+ <div class="card">
+ <div class="card-header"><h2>Theme</h2></div>
+ <div class="card-body">
+ <p class="section-description">Choose how the application looks to you.</p>
+ <div class="theme-options">
+ <button
+ v-for="m in themeModes"
+ :key="m.value"
+ :class="['theme-option', { active: theme.mode === m.value }]"
+ @click="theme.setMode(m.value)"
+ >
+ <div class="theme-option-icon">
+ <svg v-if="m.icon === 'sun'" width="20" height="20" viewBox="0 0 16 16" fill="none"><circle cx="8" cy="8" r="3" stroke="currentColor" stroke-width="1.5"/><path d="M8 1v2M8 13v2M1 8h2M13 8h2M3.05 3.05l1.41 1.41M11.54 11.54l1.41 1.41M3.05 12.95l1.41-1.41M11.54 4.46l1.41-1.41" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg>
+ <svg v-else-if="m.icon === 'moon'" width="20" height="20" viewBox="0 0 16 16" fill="none"><path d="M14 9.5A6.5 6.5 0 016.5 2 6.5 6.5 0 1014 9.5z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
+ <svg v-else width="20" height="20" viewBox="0 0 16 16" fill="none"><rect x="2" y="3" width="12" height="10" rx="1.5" stroke="currentColor" stroke-width="1.5"/><path d="M2 5.5h12" stroke="currentColor" stroke-width="1.5"/></svg>
+ </div>
+ <span class="theme-option-label">{{ m.label }}</span>
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+</template>
+
+<style scoped>
+.settings-grid {
+ display: grid;
+ gap: 24px;
+ max-width: 640px;
+}
+
+.settings-form {
+ display: grid;
+ gap: 1rem;
+}
+
+.form-hint {
+ font-size: 12px;
+ color: var(--text-muted);
+ margin-top: 4px;
+ display: block;
+}
+
+.section-description {
+ font-size: 13px;
+ color: var(--text-secondary);
+ margin-bottom: 16px;
+}
+
+.toggle-row {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+}
+
+.toggle-label {
+ font-size: 14px;
+ font-weight: 500;
+ color: var(--text-primary);
+}
+
+.toggle-btn {
+ position: relative;
+ width: 44px;
+ height: 24px;
+ border-radius: 12px;
+ border: none;
+ background: var(--border-primary);
+ cursor: pointer;
+ transition: background 0.2s;
+ padding: 0;
+ flex-shrink: 0;
+}
+
+.toggle-btn.active {
+ background: var(--primary-600);
+}
+
+.toggle-btn:disabled {
+ opacity: 0.5;
+ cursor: not-allowed;
+}
+
+.toggle-slider {
+ position: absolute;
+ top: 2px;
+ left: 2px;
+ width: 20px;
+ height: 20px;
+ border-radius: 50%;
+ background: white;
+ transition: transform 0.2s;
+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.15);
+}
+
+.toggle-btn.active .toggle-slider {
+ transform: translateX(20px);
+}
+
+.theme-options {
+ display: flex;
+ gap: 12px;
+}
+
+.theme-option {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 8px;
+ padding: 16px 24px;
+ border: 2px solid var(--border-primary);
+ border-radius: var(--radius);
+ background: var(--bg-primary);
+ color: var(--text-secondary);
+ cursor: pointer;
+ transition: all var(--transition);
+ font-family: inherit;
+ min-width: 90px;
+}
+
+.theme-option:hover {
+ border-color: var(--primary-400);
+ color: var(--text-primary);
+}
+
+.theme-option.active {
+ border-color: var(--primary-600);
+ color: var(--primary-600);
+ background: var(--primary-50, rgba(79, 70, 229, 0.05));
+}
+
+.theme-option-icon {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+}
+
+.theme-option-label {
+ font-size: 13px;
+ font-weight: 500;
+}
+</style>
diff --git a/web/src/views/smtp/SmtpServerDetail.vue b/web/src/views/smtp/SmtpServerDetail.vue
new file mode 100644
index 0000000..2fd3881
--- /dev/null
+++ b/web/src/views/smtp/SmtpServerDetail.vue
@@ -0,0 +1,291 @@
+<script setup lang="ts">
+import { ref, onMounted } from 'vue'
+import { useRoute, useRouter } from 'vue-router'
+import { smtpApi } from '../../api/smtp'
+import { useNotificationStore } from '../../stores/notification'
+import { useConfirm } from '../../composables/useConfirm'
+import type { SmtpServer, SmtpServerInput } from '../../api/types'
+
+const route = useRoute()
+const router = useRouter()
+const notify = useNotificationStore()
+const { confirm } = useConfirm()
+
+const server = ref<SmtpServer | null>(null)
+const loading = ref(true)
+
+const showModal = ref(false)
+const form = ref<SmtpServerInput>({
+ host: '',
+ port: 587,
+ username: '',
+ password: '',
+ encryption: 'starttls',
+ max_retries: 0,
+ allowed_emails: [],
+})
+const allowedEmailsText = ref('')
+const saving = ref(false)
+
+async function fetchServer() {
+ loading.value = true
+ try {
+ const id = Number(route.params.id)
+ const res = await smtpApi.get(id)
+ server.value = res.data.data
+ } catch {
+ notify.error('Failed to load SMTP server')
+ } finally {
+ loading.value = false
+ }
+}
+
+function openEdit() {
+ if (!server.value) return
+ form.value = {
+ host: server.value.host,
+ port: server.value.port,
+ username: server.value.username,
+ password: '',
+ encryption: server.value.encryption,
+ max_retries: server.value.max_retries ?? 0,
+ allowed_emails: server.value.allowed_emails ?? [],
+ }
+ allowedEmailsText.value = (server.value.allowed_emails ?? []).join(', ')
+ showModal.value = true
+}
+
+async function save() {
+ if (!server.value) return
+ saving.value = true
+ const data: SmtpServerInput = {
+ ...form.value,
+ allowed_emails: allowedEmailsText.value
+ .split(',')
+ .map(e => e.trim())
+ .filter(e => e.length > 0),
+ }
+ try {
+ await smtpApi.update(server.value.id, data)
+ notify.success('SMTP server updated')
+ showModal.value = false
+ await fetchServer()
+ } catch {
+ notify.error('Failed to update SMTP server')
+ } finally {
+ saving.value = false
+ }
+}
+
+async function toggleStatus() {
+ if (!server.value) return
+ try {
+ const newStatus = server.value.status === 'disabled' ? 'enabled' : 'disabled'
+ await smtpApi.update(server.value.id, { status: newStatus } as Partial<SmtpServerInput>)
+ await fetchServer()
+ notify.success(newStatus === 'enabled' ? 'SMTP server enabled' : 'SMTP server disabled')
+ } catch {
+ notify.error('Failed to update SMTP server')
+ }
+}
+
+async function testServer() {
+ if (!server.value) return
+ try {
+ const res = await smtpApi.test(server.value.id)
+ if (res.data.data.success) {
+ notify.success('Connection test successful')
+ } else {
+ notify.error('Connection test failed: ' + res.data.data.message)
+ }
+ await fetchServer()
+ } catch {
+ notify.error('Connection test failed')
+ }
+}
+
+async function deleteServer() {
+ if (!server.value) return
+ const confirmed = await confirm({
+ title: 'Delete SMTP Server',
+ message: `Are you sure you want to delete "${server.value.host}"? Emails using this server will no longer be delivered.`,
+ confirmText: 'Delete',
+ variant: 'danger',
+ })
+ if (!confirmed) return
+ try {
+ await smtpApi.delete(server.value.id)
+ notify.success('SMTP server deleted')
+ router.push('/smtp-servers')
+ } catch {
+ notify.error('Failed to delete SMTP server')
+ }
+}
+
+function formatDate(date: string | null) {
+ if (!date) return '-'
+ return new Date(date).toLocaleString()
+}
+
+onMounted(fetchServer)
+</script>
+
+<template>
+ <div>
+ <div class="page-header">
+ <div>
+ <h1>{{ server?.host ?? 'SMTP Server Details' }}</h1>
+ </div>
+ <div class="flex gap-2">
+ <button class="btn btn-secondary" @click="router.push('/smtp-servers')">Back</button>
+ </div>
+ </div>
+
+ <div v-if="loading" class="loading-page">
+ <div class="spinner"></div>
+ </div>
+
+ <template v-else-if="server">
+ <!-- Info card -->
+ <div class="card" style="margin-bottom: 24px;">
+ <div class="card-header">
+ <h2>{{ server.host }}:{{ server.port }}</h2>
+ <div class="flex gap-2">
+ <span class="badge badge-success" v-if="server.status === 'enabled'">Enabled</span>
+ <span class="badge badge-danger" v-else-if="server.status === 'invalid'">Invalid</span>
+ <span class="badge badge-neutral" v-else>Disabled</span>
+ </div>
+ </div>
+ <div class="card-body">
+ <table>
+ <tbody>
+ <tr>
+ <td style="font-weight: 600; width: 160px;">Host</td>
+ <td>{{ server.host }}</td>
+ </tr>
+ <tr>
+ <td style="font-weight: 600;">Port</td>
+ <td>{{ server.port }}</td>
+ </tr>
+ <tr>
+ <td style="font-weight: 600;">Encryption</td>
+ <td>
+ <span class="badge badge-success" v-if="server.encryption === 'ssl'">SSL</span>
+ <span class="badge badge-info" v-else-if="server.encryption === 'starttls'">STARTTLS</span>
+ <span class="badge badge-neutral" v-else>None</span>
+ </td>
+ </tr>
+ <tr>
+ <td style="font-weight: 600;">Username</td>
+ <td>{{ server.username || '-' }}</td>
+ </tr>
+ <tr>
+ <td style="font-weight: 600;">Max Retries</td>
+ <td>{{ server.max_retries }}</td>
+ </tr>
+ <tr>
+ <td style="font-weight: 600;">Allowed Emails</td>
+ <td>
+ <span v-if="server.allowed_emails && server.allowed_emails.length > 0">
+ <span
+ v-for="e in server.allowed_emails"
+ :key="e"
+ class="badge badge-neutral"
+ style="margin-right: 6px;"
+ >{{ e }}</span>
+ </span>
+ <span v-else class="text-muted">All emails</span>
+ </td>
+ </tr>
+ <tr v-if="server.status === 'invalid' && server.validation_error">
+ <td style="font-weight: 600;">Validation Error</td>
+ <td style="color: var(--color-danger, #e53e3e);">{{ server.validation_error }}</td>
+ </tr>
+ <tr>
+ <td style="font-weight: 600;">Last Validated</td>
+ <td>{{ formatDate(server.validated_at) }}</td>
+ </tr>
+ <tr>
+ <td style="font-weight: 600;">Created</td>
+ <td>{{ formatDate(server.created_at) }}</td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ </div>
+
+ <!-- Actions -->
+ <div class="card">
+ <div class="card-header"><h2>Actions</h2></div>
+ <div class="card-body">
+ <div class="flex gap-2">
+ <button class="btn btn-primary" @click="openEdit">Edit</button>
+ <button class="btn btn-secondary" @click="testServer">Test Connection</button>
+ <button
+ class="btn btn-secondary"
+ @click="toggleStatus"
+ >{{ server.status !== 'disabled' ? 'Disable' : 'Enable' }}</button>
+ <button class="btn btn-danger" @click="deleteServer">Delete</button>
+ </div>
+ </div>
+ </div>
+ </template>
+
+ <div v-else class="empty-state">
+ <h3>SMTP server not found</h3>
+ </div>
+
+ <!-- Edit Modal -->
+ <div v-if="showModal" class="modal-overlay" @click.self="showModal = false">
+ <div class="modal">
+ <div class="modal-header">
+ <h3>Edit SMTP Server</h3>
+ </div>
+ <form @submit.prevent="save">
+ <div class="modal-body">
+ <div class="form-group">
+ <label class="form-label">Host</label>
+ <input v-model="form.host" type="text" class="form-input" placeholder="smtp.example.com" required />
+ </div>
+ <div class="form-group">
+ <label class="form-label">Port</label>
+ <input v-model.number="form.port" type="number" class="form-input" placeholder="587" required />
+ </div>
+ <div class="form-group">
+ <label class="form-label">Username</label>
+ <input v-model="form.username" type="text" class="form-input" required />
+ </div>
+ <div class="form-group">
+ <label class="form-label">Password</label>
+ <input v-model="form.password" type="password" class="form-input" placeholder="Leave blank to keep current" />
+ </div>
+ <div class="form-group">
+ <label class="form-label">Encryption</label>
+ <select v-model="form.encryption" class="form-select">
+ <option value="none">None</option>
+ <option value="starttls">STARTTLS (port 587)</option>
+ <option value="ssl">SSL/TLS (port 465)</option>
+ </select>
+ </div>
+ <div class="form-group">
+ <label class="form-label">Max Retries</label>
+ <input v-model.number="form.max_retries" type="number" class="form-input" min="0" max="10" />
+ <span class="form-hint">Number of times to retry failed emails. Set to 0 to disable retries.</span>
+ </div>
+ <div class="form-group">
+ <label class="form-label">Allowed Emails</label>
+ <input v-model="allowedEmailsText" type="text" class="form-input" placeholder="[email protected], [email protected]" />
+ <span class="form-hint">Comma-separated. Leave empty to allow all.</span>
+ </div>
+ </div>
+ <div class="modal-footer">
+ <button type="button" class="btn btn-secondary" @click="showModal = false">Cancel</button>
+ <button type="submit" class="btn btn-primary" :disabled="saving">
+ {{ saving ? 'Saving...' : 'Update' }}
+ </button>
+ </div>
+ </form>
+ </div>
+ </div>
+ </div>
+</template>
diff --git a/web/src/views/smtp/SmtpServers.vue b/web/src/views/smtp/SmtpServers.vue
new file mode 100644
index 0000000..ff5c1f1
--- /dev/null
+++ b/web/src/views/smtp/SmtpServers.vue
@@ -0,0 +1,258 @@
+<script setup lang="ts">
+import { ref, onMounted } from 'vue'
+import { useRouter } from 'vue-router'
+import { smtpApi } from '../../api/smtp'
+import type { SmtpServer, SmtpServerInput, Pageable } from '../../api/types'
+import { useNotificationStore } from '../../stores/notification'
+import { useConfirm } from '../../composables/useConfirm'
+
+const router = useRouter()
+const notify = useNotificationStore()
+const { confirm } = useConfirm()
+
+const servers = ref<SmtpServer[]>([])
+const pageable = ref<Pageable | null>(null)
+const loading = ref(true)
+const currentPage = ref(0)
+
+const showModal = ref(false)
+const editing = ref<SmtpServer | null>(null)
+const form = ref<SmtpServerInput>({
+ host: '',
+ port: 587,
+ username: '',
+ password: '',
+ encryption: 'starttls',
+ allowed_emails: [],
+})
+const allowedEmailsText = ref('')
+const saving = ref(false)
+
+async function fetchServers() {
+ loading.value = true
+ try {
+ const res = await smtpApi.list(currentPage.value)
+ servers.value = res.data.data
+ pageable.value = res.data.pageable
+ } catch {
+ notify.error('Failed to load SMTP servers')
+ } finally {
+ loading.value = false
+ }
+}
+
+function openCreate() {
+ editing.value = null
+ form.value = { host: '', port: 587, username: '', password: '', encryption: 'starttls', max_retries: 0, allowed_emails: [] }
+ allowedEmailsText.value = ''
+ showModal.value = true
+}
+
+function openEdit(server: SmtpServer) {
+ editing.value = server
+ form.value = {
+ host: server.host,
+ port: server.port,
+ username: server.username,
+ password: '',
+ encryption: server.encryption,
+ max_retries: server.max_retries || 0,
+ allowed_emails: server.allowed_emails || [],
+ }
+ allowedEmailsText.value = (server.allowed_emails || []).join(', ')
+ showModal.value = true
+}
+
+async function save() {
+ saving.value = true
+ const data: SmtpServerInput = {
+ ...form.value,
+ allowed_emails: allowedEmailsText.value
+ .split(',')
+ .map(e => e.trim())
+ .filter(e => e.length > 0),
+ }
+ try {
+ if (editing.value) {
+ await smtpApi.update(editing.value.id, data)
+ notify.success('SMTP server updated')
+ } else {
+ await smtpApi.create(data)
+ notify.success('SMTP server created')
+ }
+ showModal.value = false
+ await fetchServers()
+ } catch {
+ notify.error('Failed to save SMTP server')
+ } finally {
+ saving.value = false
+ }
+}
+
+async function deleteServer(server: SmtpServer) {
+ const confirmed = await confirm({
+ title: 'Delete SMTP Server',
+ message: `Are you sure you want to delete "${server.host}"? Emails using this server will no longer be delivered.`,
+ confirmText: 'Delete',
+ variant: 'danger',
+ })
+ if (!confirmed) return
+ try {
+ await smtpApi.delete(server.id)
+ notify.success('SMTP server deleted')
+ await fetchServers()
+ } catch {
+ notify.error('Failed to delete SMTP server')
+ }
+}
+
+function prevPage() {
+ if (currentPage.value > 0) {
+ currentPage.value--
+ fetchServers()
+ }
+}
+
+function nextPage() {
+ if (pageable.value && currentPage.value < pageable.value.total_pages - 1) {
+ currentPage.value++
+ fetchServers()
+ }
+}
+
+onMounted(fetchServers)
+</script>
+
+<template>
+ <div>
+ <div class="page-header">
+ <h1>SMTP Servers</h1>
+ <button class="btn btn-primary" @click="openCreate">Add Server</button>
+ </div>
+
+ <div v-if="loading" class="loading-page">
+ <div class="spinner"></div>
+ </div>
+
+ <template v-else>
+ <div class="card">
+ <div class="table-wrapper" v-if="servers.length > 0">
+ <table>
+ <thead>
+ <tr>
+ <th>Host</th>
+ <th>Port</th>
+ <th>Username</th>
+ <th>Encryption</th>
+ <th>Status</th>
+ <th>Max Retries</th>
+ <th>Allowed Emails</th>
+ <th>Actions</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr v-for="server in servers" :key="server.id">
+ <td>{{ server.host }}</td>
+ <td>{{ server.port }}</td>
+ <td>{{ server.username }}</td>
+ <td>
+ <span class="badge badge-success" v-if="server.encryption === 'ssl'">SSL</span>
+ <span class="badge badge-info" v-else-if="server.encryption === 'starttls'">STARTTLS</span>
+ <span class="badge badge-neutral" v-else>None</span>
+ </td>
+ <td>
+ <span v-if="server.status === 'enabled'" class="badge badge-success">Enabled</span>
+ <span v-else-if="server.status === 'invalid'" class="badge badge-danger">Invalid</span>
+ <span v-else class="badge badge-neutral">Disabled</span>
+ </td>
+ <td>{{ server.max_retries }}</td>
+ <td>
+ <span v-if="server.allowed_emails && server.allowed_emails.length > 0">
+ {{ server.allowed_emails.join(', ') }}
+ </span>
+ <span v-else class="text-muted">All</span>
+ </td>
+ <td>
+ <div class="flex gap-2">
+ <button class="btn btn-secondary btn-sm" @click="router.push(`/smtp-servers/${server.id}`)">View</button>
+ <button class="btn btn-secondary btn-sm" @click="openEdit(server)">Edit</button>
+ <button class="btn btn-danger btn-sm" @click="deleteServer(server)">Delete</button>
+ </div>
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+
+ <div v-else class="empty-state">
+ <h3>No SMTP servers</h3>
+ <p>Add an SMTP server to start sending emails.</p>
+ </div>
+
+ <div v-if="pageable && !pageable.empty" class="pagination">
+ <span class="pagination-info">
+ Page {{ pageable.current_page + 1 }} of {{ pageable.total_pages }}
+ ({{ pageable.total_elements }} total)
+ </span>
+ <div class="pagination-buttons">
+ <button class="btn btn-secondary btn-sm" :disabled="currentPage === 0" @click="prevPage">Previous</button>
+ <button class="btn btn-secondary btn-sm" :disabled="currentPage >= pageable.total_pages - 1" @click="nextPage">Next</button>
+ </div>
+ </div>
+ </div>
+ </template>
+
+ <!-- Create/Edit Modal -->
+ <div v-if="showModal" class="modal-overlay" @click.self="showModal = false">
+ <div class="modal">
+ <div class="modal-header">
+ <h3>{{ editing ? 'Edit SMTP Server' : 'Add SMTP Server' }}</h3>
+ </div>
+ <form @submit.prevent="save">
+ <div class="modal-body">
+ <div class="form-group">
+ <label class="form-label">Host</label>
+ <input v-model="form.host" type="text" class="form-input" placeholder="smtp.example.com" required />
+ </div>
+ <div class="form-group">
+ <label class="form-label">Port</label>
+ <input v-model.number="form.port" type="number" class="form-input" placeholder="587" required />
+ </div>
+ <div class="form-group">
+ <label class="form-label">Username</label>
+ <input v-model="form.username" type="text" class="form-input" required />
+ </div>
+ <div class="form-group">
+ <label class="form-label">Password</label>
+ <input v-model="form.password" type="password" class="form-input" :required="!editing" />
+ </div>
+ <div class="form-group">
+ <label class="form-label">Encryption</label>
+ <select v-model="form.encryption" class="form-select">
+ <option value="none">None</option>
+ <option value="starttls">STARTTLS (port 587)</option>
+ <option value="ssl">SSL/TLS (port 465)</option>
+ </select>
+ </div>
+ <div class="form-group">
+ <label class="form-label">Max Retries</label>
+ <input v-model.number="form.max_retries" type="number" class="form-input" min="0" max="10" placeholder="0" />
+ <span class="form-hint">Number of times to retry failed emails. Set to 0 to disable retries.</span>
+ </div>
+ <div class="form-group">
+ <label class="form-label">Allowed Emails</label>
+ <input v-model="allowedEmailsText" type="text" class="form-input" placeholder="[email protected], [email protected]" />
+ <span class="form-hint">Comma-separated list of allowed sender emails. Leave empty to allow all.</span>
+ </div>
+ </div>
+ <div class="modal-footer">
+ <button type="button" class="btn btn-secondary" @click="showModal = false">Cancel</button>
+ <button type="submit" class="btn btn-primary" :disabled="saving">
+ {{ saving ? 'Saving...' : (editing ? 'Update' : 'Create') }}
+ </button>
+ </div>
+ </form>
+ </div>
+ </div>
+ </div>
+</template>
diff --git a/web/src/views/stylesheets/Stylesheets.vue b/web/src/views/stylesheets/Stylesheets.vue
new file mode 100644
index 0000000..e0426e1
--- /dev/null
+++ b/web/src/views/stylesheets/Stylesheets.vue
@@ -0,0 +1,213 @@
+<script setup lang="ts">
+import { ref, onMounted } from 'vue'
+import { stylesheetsApi } from '../../api/stylesheets'
+import type { StyleSheet, StyleSheetInput, Pageable } from '../../api/types'
+import { useNotificationStore } from '../../stores/notification'
+import { useConfirm } from '../../composables/useConfirm'
+
+const notify = useNotificationStore()
+const { confirm } = useConfirm()
+
+const stylesheets = ref<StyleSheet[]>([])
+const pageable = ref<Pageable>({ current_page: 0, size: 20, total_pages: 0, total_elements: 0, empty: true })
+const loading = ref(true)
+
+const showModal = ref(false)
+const editing = ref<StyleSheet | null>(null)
+const saving = ref(false)
+
+const form = ref<StyleSheetInput>({
+ name: '',
+ css: '',
+})
+
+function resetForm() {
+ form.value = { name: '', css: '' }
+ editing.value = null
+}
+
+function openCreate() {
+ resetForm()
+ showModal.value = true
+}
+
+function openEdit(sheet: StyleSheet) {
+ editing.value = sheet
+ form.value = {
+ name: sheet.name,
+ css: sheet.css,
+ }
+ showModal.value = true
+}
+
+function closeModal() {
+ showModal.value = false
+ resetForm()
+}
+
+async function loadStylesheets(page = 0) {
+ loading.value = true
+ try {
+ const res = await stylesheetsApi.list(page, pageable.value.size)
+ stylesheets.value = res.data.data
+ pageable.value = res.data.pageable
+ } catch {
+ notify.error('Failed to load stylesheets')
+ } finally {
+ loading.value = false
+ }
+}
+
+async function saveStylesheet() {
+ if (!form.value.name.trim()) return
+ saving.value = true
+ try {
+ if (editing.value) {
+ await stylesheetsApi.update(editing.value.id, form.value)
+ notify.success('Stylesheet updated')
+ } else {
+ await stylesheetsApi.create(form.value)
+ notify.success('Stylesheet created')
+ }
+ closeModal()
+ await loadStylesheets(pageable.value.current_page)
+ } catch {
+ notify.error(editing.value ? 'Failed to update stylesheet' : 'Failed to create stylesheet')
+ } finally {
+ saving.value = false
+ }
+}
+
+async function deleteStylesheet(sheet: StyleSheet) {
+ const confirmed = await confirm({
+ title: 'Delete Stylesheet',
+ message: `Are you sure you want to delete "${sheet.name}"? Templates using this stylesheet will lose their styling.`,
+ confirmText: 'Delete',
+ variant: 'danger',
+ })
+ if (!confirmed) return
+ try {
+ await stylesheetsApi.delete(sheet.id)
+ notify.success('Stylesheet deleted')
+ await loadStylesheets(pageable.value.current_page)
+ } catch {
+ notify.error('Failed to delete stylesheet')
+ }
+}
+
+function formatDate(dateStr: string): string {
+ return new Date(dateStr).toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' })
+}
+
+onMounted(() => loadStylesheets())
+</script>
+
+<template>
+ <div>
+ <div class="page-header">
+ <h1>Stylesheets</h1>
+ <button class="btn btn-primary" @click="openCreate">Create Stylesheet</button>
+ </div>
+
+ <div v-if="loading" class="loading-page">
+ <div class="spinner"></div>
+ </div>
+
+ <div v-else class="card">
+ <div v-if="stylesheets.length === 0" class="empty-state">
+ <h3>No Stylesheets</h3>
+ <p>Create a stylesheet to reuse CSS across your email templates.</p>
+ </div>
+
+ <template v-else>
+ <div class="table-wrapper">
+ <table>
+ <thead>
+ <tr>
+ <th>Name</th>
+ <th>Created</th>
+ <th>Updated</th>
+ <th>Actions</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr v-for="sheet in stylesheets" :key="sheet.id">
+ <td>{{ sheet.name }}</td>
+ <td>{{ formatDate(sheet.created_at) }}</td>
+ <td>
+ <span v-if="sheet.updated_at">{{ formatDate(sheet.updated_at) }}</span>
+ <span v-else class="text-muted">&mdash;</span>
+ </td>
+ <td>
+ <div class="flex gap-2">
+ <button class="btn btn-secondary btn-sm" @click="openEdit(sheet)">Edit</button>
+ <button class="btn btn-danger btn-sm" @click="deleteStylesheet(sheet)">Delete</button>
+ </div>
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+
+ <div class="pagination">
+ <span class="pagination-info">
+ Page {{ pageable.current_page + 1 }} of {{ pageable.total_pages }} ({{ pageable.total_elements }} stylesheets)
+ </span>
+ <div class="pagination-buttons">
+ <button
+ class="btn btn-secondary btn-sm"
+ :disabled="pageable.current_page === 0"
+ @click="loadStylesheets(pageable.current_page - 1)"
+ >
+ Previous
+ </button>
+ <button
+ class="btn btn-secondary btn-sm"
+ :disabled="pageable.current_page >= pageable.total_pages - 1"
+ @click="loadStylesheets(pageable.current_page + 1)"
+ >
+ Next
+ </button>
+ </div>
+ </div>
+ </template>
+ </div>
+
+ <!-- Create/Edit Stylesheet Modal -->
+ <div v-if="showModal" class="modal-overlay" @click.self="closeModal">
+ <div class="modal" style="max-width: 640px;">
+ <div class="modal-header">
+ <h3>{{ editing ? 'Edit Stylesheet' : 'Create Stylesheet' }}</h3>
+ </div>
+ <div class="modal-body">
+ <div class="form-group">
+ <label class="form-label">Name</label>
+ <input v-model="form.name" class="form-input" placeholder="e.g. Brand Styles" />
+ </div>
+ <div class="form-group">
+ <label class="form-label">CSS</label>
+ <textarea v-model="form.css" class="form-textarea css-editor" rows="12" placeholder="body { font-family: sans-serif; }"></textarea>
+ <span class="form-hint">This CSS will be injected as a &lt;style&gt; block into templates that use this stylesheet.</span>
+ </div>
+ </div>
+ <div class="modal-footer">
+ <button class="btn btn-secondary" @click="closeModal">Cancel</button>
+ <button
+ class="btn btn-primary"
+ :disabled="saving || !form.name.trim()"
+ @click="saveStylesheet"
+ >
+ {{ saving ? 'Saving...' : (editing ? 'Update' : 'Create') }}
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+</template>
+
+<style scoped>
+.css-editor {
+ font-family: 'JetBrains Mono', 'Fira Code', monospace;
+ font-size: 13px;
+}
+</style>
diff --git a/web/src/views/templates/TemplateDetail.vue b/web/src/views/templates/TemplateDetail.vue
new file mode 100644
index 0000000..f122bf8
--- /dev/null
+++ b/web/src/views/templates/TemplateDetail.vue
@@ -0,0 +1,742 @@
+<script setup lang="ts">
+import { ref, onMounted, computed } from 'vue'
+import { useRoute, useRouter } from 'vue-router'
+import { templatesApi } from '../../api/templates'
+import { stylesheetsApi } from '../../api/stylesheets'
+import { languagesApi } from '../../api/languages'
+import type {
+ Template,
+ TemplateVersion,
+ TemplateLocalization,
+ TemplateLocalizationInput,
+ TemplatePreview,
+ StyleSheet,
+ Language,
+} from '../../api/types'
+import { useNotificationStore } from '../../stores/notification'
+import { useConfirm } from '../../composables/useConfirm'
+
+const route = useRoute()
+const router = useRouter()
+const notify = useNotificationStore()
+const { confirm } = useConfirm()
+
+const templateId = Number(route.params.id)
+
+const template = ref<Template | null>(null)
+const versions = ref<TemplateVersion[]>([])
+const localizations = ref<TemplateLocalization[]>([])
+const stylesheets = ref<StyleSheet[]>([])
+const languages = ref<Language[]>([])
+const loading = ref(true)
+const selectedVersion = ref<TemplateVersion | null>(null)
+
+// Localization modal
+const showLocModal = ref(false)
+const editingLoc = ref<TemplateLocalization | null>(null)
+const savingLoc = ref(false)
+const locForm = ref<TemplateLocalizationInput>({
+ language: '',
+ subject_template: '',
+ html_template: '',
+ text_template: '',
+})
+
+// Preview
+const showPreview = ref(false)
+const previewLang = ref('')
+const previewData = ref('{\n "name": "John",\n "company": "Acme"\n}')
+const preview = ref<TemplatePreview | null>(null)
+const previewLoading = ref(false)
+const previewError = ref('')
+
+// Send test
+const showSendTest = ref(false)
+const sendingTest = ref(false)
+const sendTestForm = ref({
+ to: '',
+ from: '',
+ language: '',
+ data: '{\n "name": "John",\n "company": "Acme"\n}',
+})
+
+// Version creation
+const creatingVersion = ref(false)
+const newVersionStylesheetId = ref<number | null>(null)
+
+// Version stylesheet edit
+const showVersionStylesheetModal = ref(false)
+const editingVersion = ref<TemplateVersion | null>(null)
+const editVersionStylesheetId = ref<number | null>(null)
+const savingVersionStylesheet = ref(false)
+
+const isActive = computed(() => (v: TemplateVersion) =>
+ template.value?.active_version_id === v.id,
+)
+
+async function loadAll() {
+ loading.value = true
+ try {
+ const [tmplRes, versionsRes, ssRes, langRes] = await Promise.all([
+ templatesApi.list(0, 100),
+ templatesApi.listVersions(templateId),
+ stylesheetsApi.list(0, 100),
+ languagesApi.list(0, 100),
+ ])
+ template.value = tmplRes.data.data.find((t: Template) => t.id === templateId) || null
+ versions.value = versionsRes.data.data || []
+ stylesheets.value = ssRes.data.data || []
+ languages.value = langRes.data.data || []
+
+ if (!template.value) {
+ notify.error('Template not found')
+ return
+ }
+
+ // Auto-select the active version or the first one
+ if (versions.value.length > 0) {
+ const active = versions.value.find(v => v.id === template.value?.active_version_id)
+ await selectVersion(active || versions.value[0])
+ }
+ } catch {
+ notify.error('Failed to load template')
+ } finally {
+ loading.value = false
+ }
+}
+
+async function selectVersion(v: TemplateVersion) {
+ selectedVersion.value = v
+ try {
+ const res = await templatesApi.listLocalizations(templateId, v.id)
+ localizations.value = res.data.data || []
+ } catch {
+ localizations.value = []
+ }
+}
+
+async function createVersion() {
+ creatingVersion.value = true
+ try {
+ const res = await templatesApi.createVersion(templateId, {
+ stylesheet_id: newVersionStylesheetId.value,
+ sample_data: template.value?.sample_data || '',
+ })
+ versions.value.unshift(res.data.data)
+ await selectVersion(res.data.data)
+ notify.success(`Version ${res.data.data.version} created`)
+ newVersionStylesheetId.value = null
+ } catch {
+ notify.error('Failed to create version')
+ } finally {
+ creatingVersion.value = false
+ }
+}
+
+function openEditVersionStylesheet(v: TemplateVersion) {
+ editingVersion.value = v
+ editVersionStylesheetId.value = v.stylesheet_id ?? null
+ showVersionStylesheetModal.value = true
+}
+
+async function saveVersionStylesheet() {
+ if (!editingVersion.value) return
+ savingVersionStylesheet.value = true
+ try {
+ const res = await templatesApi.updateVersion(templateId, editingVersion.value.id, {
+ stylesheet_id: editVersionStylesheetId.value,
+ })
+ const idx = versions.value.findIndex(v => v.id === editingVersion.value!.id)
+ if (idx >= 0) versions.value[idx] = res.data.data
+ if (selectedVersion.value?.id === editingVersion.value.id) {
+ selectedVersion.value = res.data.data
+ }
+ notify.success('Version stylesheet updated')
+ showVersionStylesheetModal.value = false
+ } catch {
+ notify.error('Failed to update version stylesheet')
+ } finally {
+ savingVersionStylesheet.value = false
+ }
+}
+
+async function activateVersion(v: TemplateVersion) {
+ try {
+ const res = await templatesApi.activateVersion(templateId, v.id)
+ template.value = res.data.data
+ notify.success(`Version ${v.version} activated`)
+ } catch {
+ notify.error('Failed to activate version')
+ }
+}
+
+async function deleteVersion(v: TemplateVersion) {
+ if (template.value?.active_version_id === v.id) {
+ notify.error('Cannot delete the active version')
+ return
+ }
+ const confirmed = await confirm({
+ title: 'Delete Version',
+ message: `Delete version ${v.version}? All its localizations will also be deleted.`,
+ confirmText: 'Delete',
+ variant: 'danger',
+ })
+ if (!confirmed) return
+ try {
+ await templatesApi.deleteVersion(templateId, v.id)
+ versions.value = versions.value.filter(x => x.id !== v.id)
+ if (selectedVersion.value?.id === v.id) {
+ selectedVersion.value = versions.value[0] || null
+ if (selectedVersion.value) await selectVersion(selectedVersion.value)
+ else localizations.value = []
+ }
+ notify.success('Version deleted')
+ } catch {
+ notify.error('Failed to delete version')
+ }
+}
+
+function openCreateLoc() {
+ editingLoc.value = null
+ locForm.value = { language: '', subject_template: '', html_template: '', text_template: '' }
+ showLocModal.value = true
+}
+
+function openEditLoc(l: TemplateLocalization) {
+ editingLoc.value = l
+ locForm.value = {
+ language: l.language,
+ subject_template: l.subject_template,
+ html_template: l.html_template,
+ text_template: l.text_template,
+ }
+ showLocModal.value = true
+}
+
+async function saveLoc() {
+ if (!selectedVersion.value) return
+ savingLoc.value = true
+ try {
+ if (editingLoc.value) {
+ const res = await templatesApi.updateLocalization(editingLoc.value.id, {
+ subject_template: locForm.value.subject_template,
+ html_template: locForm.value.html_template,
+ text_template: locForm.value.text_template,
+ })
+ const idx = localizations.value.findIndex(l => l.id === editingLoc.value!.id)
+ if (idx >= 0) localizations.value[idx] = res.data.data
+ notify.success('Localization updated')
+ } else {
+ const res = await templatesApi.createLocalization(templateId, selectedVersion.value.id, locForm.value)
+ localizations.value.push(res.data.data)
+ notify.success('Localization created')
+ }
+ showLocModal.value = false
+ } catch {
+ notify.error(editingLoc.value ? 'Failed to update localization' : 'Language already exists for this version')
+ } finally {
+ savingLoc.value = false
+ }
+}
+
+async function deleteLoc(l: TemplateLocalization) {
+ const confirmed = await confirm({
+ title: 'Delete Localization',
+ message: `Delete the "${l.language}" localization? This cannot be undone.`,
+ confirmText: 'Delete',
+ variant: 'danger',
+ })
+ if (!confirmed) return
+ try {
+ await templatesApi.deleteLocalization(l.id)
+ localizations.value = localizations.value.filter(x => x.id !== l.id)
+ notify.success('Localization deleted')
+ } catch {
+ notify.error('Failed to delete localization')
+ }
+}
+
+async function renderPreview() {
+ if (!selectedVersion.value || !previewLang.value) return
+ previewLoading.value = true
+ previewError.value = ''
+ preview.value = null
+
+ let data: Record<string, any> = {}
+ try {
+ data = JSON.parse(previewData.value)
+ } catch {
+ previewError.value = 'Invalid JSON in sample data'
+ previewLoading.value = false
+ return
+ }
+
+ try {
+ const res = await templatesApi.previewLocalization(templateId, selectedVersion.value.id, {
+ language: previewLang.value,
+ 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
+ }
+}
+
+function openSendTest() {
+ sendTestForm.value = {
+ to: '',
+ from: '',
+ language: template.value?.default_language || 'en',
+ data: selectedVersion.value?.sample_data || '{\n "name": "John",\n "company": "Acme"\n}',
+ }
+ showSendTest.value = true
+}
+
+async function sendTest() {
+ if (!sendTestForm.value.to.trim()) return
+ sendingTest.value = true
+
+ let data: Record<string, any> = {}
+ try {
+ data = JSON.parse(sendTestForm.value.data)
+ } catch {
+ notify.error('Invalid JSON in sample data')
+ sendingTest.value = false
+ return
+ }
+
+ try {
+ const to = sendTestForm.value.to.split(',').map(e => e.trim()).filter(Boolean)
+ await templatesApi.sendTest(templateId, {
+ to,
+ from: sendTestForm.value.from || undefined,
+ language: sendTestForm.value.language || undefined,
+ template_data: data,
+ })
+ notify.success('Test email sent')
+ showSendTest.value = false
+ } catch (e: any) {
+ notify.error(e.response?.data?.error?.message || 'Failed to send test email')
+ } finally {
+ sendingTest.value = false
+ }
+}
+
+function openPreview(lang: string) {
+ previewLang.value = lang
+ preview.value = null
+ previewError.value = ''
+ if (selectedVersion.value?.sample_data) {
+ previewData.value = selectedVersion.value.sample_data
+ }
+ showPreview.value = true
+ renderPreview()
+}
+
+function formatDate(dateStr: string): string {
+ return new Date(dateStr).toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' })
+}
+
+onMounted(loadAll)
+</script>
+
+<template>
+ <div>
+ <div class="page-header">
+ <h1>{{ template?.name || 'Template' }}</h1>
+ <div class="flex gap-2">
+ <button class="btn btn-primary" @click="openSendTest" :disabled="!template?.active_version_id">Send Test</button>
+ <button class="btn btn-secondary" @click="router.push('/templates')">Back to Templates</button>
+ </div>
+ </div>
+
+ <div v-if="loading" class="loading-page">
+ <div class="spinner"></div>
+ </div>
+
+ <template v-else-if="template">
+ <!-- Template Info -->
+ <div class="card" style="margin-bottom: 24px;">
+ <div class="card-body">
+ <table>
+ <tbody>
+ <tr>
+ <td class="info-label">Name</td>
+ <td>{{ template.name }}</td>
+ </tr>
+ <tr v-if="template.description">
+ <td class="info-label">Description</td>
+ <td>{{ template.description }}</td>
+ </tr>
+ <tr>
+ <td class="info-label">Default Language</td>
+ <td><span class="badge badge-info">{{ template.default_language }}</span></td>
+ </tr>
+ <tr>
+ <td class="info-label">Active Version</td>
+ <td>
+ <span v-if="template.active_version_id" class="badge badge-success">
+ v{{ versions.find(v => v.id === template!.active_version_id)?.version || '?' }}
+ </span>
+ <span v-else class="text-muted">None</span>
+ </td>
+ </tr>
+ <tr>
+ <td class="info-label">Created</td>
+ <td>{{ formatDate(template.created_at) }}</td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ </div>
+
+ <!-- Versions -->
+ <div class="card" style="margin-bottom: 24px;">
+ <div class="card-header">
+ <h2>Versions</h2>
+ <div class="flex gap-2 align-center">
+ <select v-model="newVersionStylesheetId" class="form-select form-select-sm">
+ <option :value="null">No stylesheet</option>
+ <option v-for="ss in stylesheets" :key="ss.id" :value="ss.id">{{ ss.name }}</option>
+ </select>
+ <button class="btn btn-primary btn-sm" @click="createVersion" :disabled="creatingVersion">
+ {{ creatingVersion ? 'Creating...' : 'New Version' }}
+ </button>
+ </div>
+ </div>
+
+ <div v-if="versions.length === 0" class="empty-state">
+ <p>No versions yet. Create one to start adding localizations.</p>
+ </div>
+
+ <div v-else class="table-wrapper">
+ <table>
+ <thead>
+ <tr>
+ <th>Version</th>
+ <th>Stylesheet</th>
+ <th>Created</th>
+ <th>Status</th>
+ <th>Actions</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr
+ v-for="v in versions"
+ :key="v.id"
+ :class="{ 'row-selected': selectedVersion?.id === v.id }"
+ style="cursor: pointer;"
+ @click="selectVersion(v)"
+ >
+ <td><strong>v{{ v.version }}</strong></td>
+ <td>
+ <span v-if="v.stylesheet" class="badge badge-neutral">{{ v.stylesheet.name }}</span>
+ <span v-else class="text-muted">&mdash;</span>
+ </td>
+ <td>{{ formatDate(v.created_at) }}</td>
+ <td>
+ <span v-if="isActive(v)" class="badge badge-success">Active</span>
+ <span v-else class="badge badge-neutral">Draft</span>
+ </td>
+ <td>
+ <div class="flex gap-2" @click.stop>
+ <button
+ class="btn btn-secondary btn-sm"
+ @click="openEditVersionStylesheet(v)"
+ >Edit</button>
+ <button
+ v-if="!isActive(v)"
+ class="btn btn-primary btn-sm"
+ @click="activateVersion(v)"
+ >Activate</button>
+ <button
+ v-if="!isActive(v)"
+ class="btn btn-danger btn-sm"
+ @click="deleteVersion(v)"
+ >Delete</button>
+ </div>
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ </div>
+
+ <!-- Localizations for selected version -->
+ <div v-if="selectedVersion" class="card">
+ <div class="card-header">
+ <h2>Localizations &mdash; v{{ selectedVersion.version }}</h2>
+ <button class="btn btn-primary btn-sm" @click="openCreateLoc">Add Language</button>
+ </div>
+
+ <div v-if="localizations.length === 0" class="empty-state">
+ <p>No localizations yet. Add a language to start defining content.</p>
+ </div>
+
+ <div v-else class="table-wrapper">
+ <table>
+ <thead>
+ <tr>
+ <th>Language</th>
+ <th>Subject</th>
+ <th>Updated</th>
+ <th>Actions</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr v-for="l in localizations" :key="l.id">
+ <td>
+ <strong>{{ l.language }}</strong>
+ <span v-if="l.language === template.default_language" class="badge badge-info" style="margin-left: 6px;">default</span>
+ </td>
+ <td class="truncate" style="max-width: 300px;">{{ l.subject_template }}</td>
+ <td>
+ <span v-if="l.updated_at">{{ formatDate(l.updated_at) }}</span>
+ <span v-else>{{ formatDate(l.created_at) }}</span>
+ </td>
+ <td>
+ <div class="flex gap-2">
+ <button class="btn btn-secondary btn-sm" @click="openPreview(l.language)">Preview</button>
+ <button class="btn btn-secondary btn-sm" @click="openEditLoc(l)">Edit</button>
+ <button class="btn btn-danger btn-sm" @click="deleteLoc(l)">Delete</button>
+ </div>
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ </div>
+ </template>
+
+ <div v-else class="empty-state">
+ <h3>Template not found</h3>
+ </div>
+
+ <!-- Localization Create/Edit Modal -->
+ <div v-if="showLocModal" class="modal-overlay" @click.self="showLocModal = false">
+ <div class="modal" style="max-width: 720px;">
+ <div class="modal-header">
+ <h3>{{ editingLoc ? `Edit Localization (${editingLoc.language})` : 'Add Localization' }}</h3>
+ </div>
+ <div class="modal-body">
+ <div v-if="!editingLoc" class="form-group">
+ <label class="form-label">Language</label>
+ <select v-model="locForm.language" class="form-select">
+ <option value="" disabled>Select a language</option>
+ <option v-for="lang in languages" :key="lang.id" :value="lang.code">{{ lang.name }} ({{ lang.code }})</option>
+ </select>
+ <span class="form-hint">Choose from your configured languages</span>
+ </div>
+ <div class="form-group">
+ <label class="form-label">Subject Template</label>
+ <input v-model="locForm.subject_template" class="form-input" placeholder="e.g. Welcome {{name}}!" />
+ </div>
+ <div class="form-group">
+ <label class="form-label">HTML Template</label>
+ <textarea v-model="locForm.html_template" class="form-textarea" rows="8" placeholder="<html>...</html>"></textarea>
+ </div>
+ <div class="form-group">
+ <label class="form-label">Text Template</label>
+ <textarea v-model="locForm.text_template" class="form-textarea" rows="4" placeholder="Plain text version..."></textarea>
+ </div>
+ </div>
+ <div class="modal-footer">
+ <button class="btn btn-secondary" @click="showLocModal = false">Cancel</button>
+ <button
+ class="btn btn-primary"
+ :disabled="savingLoc || (!editingLoc && !locForm.language.trim()) || !locForm.subject_template.trim()"
+ @click="saveLoc"
+ >
+ {{ savingLoc ? 'Saving...' : (editingLoc ? 'Update' : 'Create') }}
+ </button>
+ </div>
+ </div>
+ </div>
+
+ <!-- Send Test Modal -->
+ <div v-if="showSendTest" class="modal-overlay" @click.self="showSendTest = false">
+ <div class="modal" style="max-width: 560px;">
+ <div class="modal-header">
+ <h3>Send Test Email</h3>
+ </div>
+ <div class="modal-body">
+ <div class="form-group">
+ <label class="form-label">To</label>
+ <input v-model="sendTestForm.to" class="form-input" placeholder="[email protected]" />
+ <span class="form-hint">Comma-separated for multiple recipients</span>
+ </div>
+ <div class="form-group">
+ <label class="form-label">From (optional)</label>
+ <input v-model="sendTestForm.from" class="form-input" placeholder="noreply@localhost" />
+ </div>
+ <div class="form-group">
+ <label class="form-label">Language</label>
+ <select v-model="sendTestForm.language" class="form-select">
+ <option v-for="l in localizations" :key="l.language" :value="l.language">{{ l.language }}</option>
+ </select>
+ </div>
+ <div class="form-group">
+ <label class="form-label">Sample Data (JSON)</label>
+ <textarea v-model="sendTestForm.data" class="form-textarea" rows="4" placeholder='{"name": "John"}'></textarea>
+ </div>
+ </div>
+ <div class="modal-footer">
+ <button class="btn btn-secondary" @click="showSendTest = false">Cancel</button>
+ <button
+ class="btn btn-primary"
+ :disabled="sendingTest || !sendTestForm.to.trim()"
+ @click="sendTest"
+ >
+ {{ sendingTest ? 'Sending...' : 'Send Test' }}
+ </button>
+ </div>
+ </div>
+ </div>
+
+ <!-- Preview Modal -->
+ <div v-if="showPreview" class="modal-overlay" @click.self="showPreview = false">
+ <div class="modal" style="max-width: 800px;">
+ <div class="modal-header">
+ <h3>Preview &mdash; {{ previewLang }}</h3>
+ </div>
+ <div class="modal-body">
+ <div class="form-group">
+ <label class="form-label">Sample Data (JSON)</label>
+ <textarea v-model="previewData" class="form-textarea" rows="3" placeholder='{"name": "John"}'></textarea>
+ </div>
+ <button class="btn btn-secondary btn-sm" style="margin-bottom: 16px;" @click="renderPreview" :disabled="previewLoading">
+ {{ previewLoading ? 'Rendering...' : 'Refresh Preview' }}
+ </button>
+
+ <div v-if="previewError" class="preview-error">{{ previewError }}</div>
+
+ <template v-if="preview">
+ <div class="preview-section">
+ <div class="preview-label">Subject</div>
+ <div class="preview-content">{{ preview.subject }}</div>
+ </div>
+ <div v-if="preview.html" class="preview-section">
+ <div class="preview-label">HTML</div>
+ <div class="preview-html">
+ <iframe :srcdoc="preview.html" sandbox="" class="preview-iframe"></iframe>
+ </div>
+ </div>
+ <div v-if="preview.text" class="preview-section">
+ <div class="preview-label">Plain Text</div>
+ <div class="preview-text">{{ preview.text }}</div>
+ </div>
+ </template>
+ </div>
+ <div class="modal-footer">
+ <button class="btn btn-secondary" @click="showPreview = false">Close</button>
+ </div>
+ </div>
+ </div>
+ <!-- Edit Version Stylesheet Modal -->
+ <div v-if="showVersionStylesheetModal" class="modal-overlay" @click.self="showVersionStylesheetModal = false">
+ <div class="modal" style="max-width: 420px;">
+ <div class="modal-header">
+ <h3>Edit Version v{{ editingVersion?.version }} Stylesheet</h3>
+ </div>
+ <div class="modal-body">
+ <div class="form-group">
+ <label class="form-label">Stylesheet</label>
+ <select v-model="editVersionStylesheetId" class="form-select">
+ <option :value="null">No stylesheet</option>
+ <option v-for="ss in stylesheets" :key="ss.id" :value="ss.id">{{ ss.name }}</option>
+ </select>
+ </div>
+ </div>
+ <div class="modal-footer">
+ <button class="btn btn-secondary" @click="showVersionStylesheetModal = false">Cancel</button>
+ <button
+ class="btn btn-primary"
+ :disabled="savingVersionStylesheet"
+ @click="saveVersionStylesheet"
+ >
+ {{ savingVersionStylesheet ? 'Saving...' : 'Save' }}
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+</template>
+
+<style scoped>
+.info-label {
+ font-weight: 600;
+ width: 140px;
+ color: var(--text-secondary);
+}
+
+.row-selected {
+ background: var(--bg-tertiary);
+}
+
+.align-center {
+ align-items: center;
+}
+
+.form-select-sm {
+ padding: 4px 8px;
+ font-size: 13px;
+ max-width: 160px;
+}
+
+.preview-section {
+ margin-bottom: 16px;
+}
+
+.preview-label {
+ font-size: 11px;
+ font-weight: 600;
+ text-transform: uppercase;
+ letter-spacing: 0.06em;
+ color: var(--text-muted);
+ margin-bottom: 6px;
+}
+
+.preview-content {
+ padding: 10px 14px;
+ background: var(--bg-tertiary);
+ border: 1px solid var(--border-primary);
+ border-radius: var(--radius);
+ font-size: 14px;
+ color: var(--text-primary);
+}
+
+.preview-html {
+ border: 1px solid var(--border-primary);
+ border-radius: var(--radius);
+ overflow: hidden;
+}
+
+.preview-iframe {
+ width: 100%;
+ min-height: 300px;
+ border: none;
+ background: #fff;
+}
+
+.preview-text {
+ padding: 10px 14px;
+ background: var(--bg-tertiary);
+ border: 1px solid var(--border-primary);
+ border-radius: var(--radius);
+ font-family: 'JetBrains Mono', 'Fira Code', monospace;
+ font-size: 13px;
+ color: var(--text-secondary);
+ white-space: pre-wrap;
+}
+
+.preview-error {
+ padding: 10px 14px;
+ background: var(--danger-50);
+ color: var(--danger-600);
+ border-radius: var(--radius);
+ font-size: 13px;
+ margin-bottom: 16px;
+}
+</style>
diff --git a/web/src/views/templates/TemplatePreview.vue b/web/src/views/templates/TemplatePreview.vue
new file mode 100644
index 0000000..53cfdaa
--- /dev/null
+++ b/web/src/views/templates/TemplatePreview.vue
@@ -0,0 +1,309 @@
+<script setup lang="ts">
+import { ref, onMounted, watch } from 'vue'
+import { useRoute, useRouter } from 'vue-router'
+import { templatesApi } from '../../api/templates'
+import type { Template, TemplatePreview, TemplateLocalization, TemplateVersion } from '../../api/types'
+import { useNotificationStore } from '../../stores/notification'
+
+const route = useRoute()
+const router = useRouter()
+const notify = useNotificationStore()
+
+const template = ref<Template | null>(null)
+const version = ref<TemplateVersion | null>(null)
+const localization = ref<TemplateLocalization | null>(null)
+const preview = ref<TemplatePreview | null>(null)
+const loading = ref(true)
+const previewLoading = ref(false)
+const previewError = ref('')
+const activeTab = ref<'html' | 'text'>('html')
+const sampleData = ref('{\n "name": "John",\n "company": "Acme"\n}')
+
+let debounceTimer: ReturnType<typeof setTimeout> | null = null
+watch(sampleData, () => {
+ if (debounceTimer) clearTimeout(debounceTimer)
+ debounceTimer = setTimeout(() => renderPreview(), 500)
+})
+
+onMounted(async () => {
+ const id = Number(route.params.id)
+
+ try {
+ // Load template
+ const res = await templatesApi.list(0, 100)
+ template.value = res.data.data.find((t: Template) => t.id === id) || null
+
+ if (!template.value) {
+ notify.error('Template not found')
+ loading.value = false
+ return
+ }
+
+ if (template.value.sample_data) sampleData.value = template.value.sample_data
+
+ // Load the active version and its default localization
+ if (template.value.active_version_id) {
+ const versionsRes = await templatesApi.listVersions(id)
+ version.value = (versionsRes.data.data || []).find((v: TemplateVersion) => v.id === template.value!.active_version_id) || null
+
+ const locRes = await templatesApi.listLocalizations(id, template.value.active_version_id)
+ const locs: TemplateLocalization[] = locRes.data.data || []
+ localization.value =
+ locs.find(l => l.language === template.value!.default_language) ||
+ locs[0] || null
+ }
+
+ await renderPreview()
+ } catch {
+ notify.error('Failed to load template')
+ } finally {
+ loading.value = false
+ }
+})
+
+async function renderPreview() {
+ if (!template.value || !localization.value || !template.value.active_version_id) return
+ previewLoading.value = true
+ previewError.value = ''
+ preview.value = null
+
+ let data: Record<string, any> = {}
+ try {
+ data = JSON.parse(sampleData.value)
+ } catch {
+ previewError.value = 'Invalid JSON in sample data'
+ previewLoading.value = false
+ return
+ }
+
+ try {
+ const res = await templatesApi.previewLocalization(
+ template.value.id,
+ template.value.active_version_id,
+ { language: localization.value.language, template_data: data },
+ )
+ preview.value = res.data.data
+ } catch (e: any) {
+ previewError.value = e.response?.data?.error?.message || 'Failed to render template'
+ } finally {
+ previewLoading.value = false
+ }
+}
+
+function formatDate(dateStr: string): string {
+ return new Date(dateStr).toLocaleDateString(undefined, {
+ year: 'numeric',
+ month: 'short',
+ day: 'numeric',
+ hour: '2-digit',
+ minute: '2-digit',
+ })
+}
+</script>
+
+<template>
+ <div>
+ <div class="page-header">
+ <h1>Template Preview</h1>
+ <button class="btn btn-secondary" @click="router.push('/templates')">Back to Templates</button>
+ </div>
+
+ <div v-if="loading" class="loading-page">
+ <div class="spinner"></div>
+ </div>
+
+ <template v-else-if="template">
+ <!-- Template Info -->
+ <div class="card" style="margin-bottom: 24px;">
+ <div class="card-header">
+ <h2>{{ template.name }}</h2>
+ <div class="flex gap-2">
+ <span v-if="localization" class="badge badge-success">{{ localization.language }}</span>
+ <span v-if="version" class="badge badge-neutral">v{{ version.version }}</span>
+ </div>
+ </div>
+ <div class="card-body">
+ <table>
+ <tbody>
+ <tr v-if="localization">
+ <td class="info-label">Subject</td>
+ <td><code>{{ localization.subject_template }}</code></td>
+ </tr>
+ <tr>
+ <td class="info-label">Language</td>
+ <td><span class="badge badge-info">{{ template.default_language }}</span></td>
+ </tr>
+ <tr v-if="version?.stylesheet">
+ <td class="info-label">Stylesheet</td>
+ <td><span class="badge badge-neutral">{{ version.stylesheet.name }}</span></td>
+ </tr>
+ <tr>
+ <td class="info-label">Created</td>
+ <td>{{ formatDate(template.created_at) }}</td>
+ </tr>
+ <tr v-if="template.updated_at">
+ <td class="info-label">Updated</td>
+ <td>{{ formatDate(template.updated_at) }}</td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ </div>
+
+ <!-- No active version warning -->
+ <div v-if="!localization" class="card" style="margin-bottom: 24px;">
+ <div class="card-body">
+ <div class="text-muted" style="text-align: center; padding: 20px 0;">
+ No localization available. Add a localization to the active version to preview this template.
+ </div>
+ </div>
+ </div>
+
+ <!-- Sample Data + Render -->
+ <div v-if="localization" class="card" style="margin-bottom: 24px;">
+ <div class="card-header">
+ <h2>Sample Data</h2>
+ <button
+ class="btn btn-primary btn-sm"
+ @click="renderPreview"
+ :disabled="previewLoading"
+ >
+ {{ previewLoading ? 'Rendering...' : 'Render Preview' }}
+ </button>
+ </div>
+ <div class="card-body">
+ <textarea
+ v-model="sampleData"
+ class="form-textarea"
+ rows="4"
+ placeholder='{"name": "John", "company": "Acme"}'
+ ></textarea>
+ <span class="form-hint">
+ JSON object with variables for your template. Use &#123;&#123;key&#125;&#125; or &#123;&#123;.key&#125;&#125; in templates.
+ </span>
+ </div>
+ </div>
+
+ <!-- Rendered Preview -->
+ <div v-if="previewError" class="preview-error" style="margin-bottom: 24px;">
+ {{ previewError }}
+ </div>
+
+ <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 class="rendered-subject">{{ 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-full"></iframe>
+ </div>
+ <div v-else class="text-muted text-sm" style="padding: 20px 0; text-align: center;">
+ No HTML template defined.
+ </div>
+ </div>
+ <pre
+ v-else
+ class="preview-text-block"
+ >{{ preview.text || 'No text template defined.' }}</pre>
+ </div>
+ </div>
+ </template>
+
+ <!-- Source Code -->
+ <div v-if="localization" class="card" style="margin-top: 24px;">
+ <div class="card-header">
+ <h2>Template Source</h2>
+ </div>
+ <div class="card-body">
+ <div v-if="localization.html_template" style="margin-bottom: 16px;">
+ <div class="source-label">HTML Template</div>
+ <pre class="code-block">{{ localization.html_template }}</pre>
+ </div>
+ <div v-if="localization.text_template" style="margin-bottom: 16px;">
+ <div class="source-label">Text Template</div>
+ <pre class="code-block">{{ localization.text_template }}</pre>
+ </div>
+ <div v-if="version?.stylesheet" style="margin-bottom: 16px;">
+ <div class="source-label">Stylesheet: {{ version.stylesheet.name }}</div>
+ <pre class="code-block">{{ version.stylesheet.css }}</pre>
+ </div>
+ <div v-if="!localization.html_template && !localization.text_template" class="text-muted text-sm">
+ No template body defined.
+ </div>
+ </div>
+ </div>
+ </template>
+
+ <div v-else class="empty-state">
+ <h3>Template not found</h3>
+ <p>The template you are looking for does not exist.</p>
+ </div>
+ </div>
+</template>
+
+<style scoped>
+.info-label {
+ font-weight: 600;
+ width: 120px;
+ color: var(--text-secondary);
+}
+
+.rendered-subject {
+ font-size: 16px;
+ font-weight: 500;
+ color: var(--text-primary);
+}
+
+.preview-html-frame {
+ border: 1px solid var(--border-primary);
+ border-radius: var(--radius);
+ overflow: hidden;
+}
+
+.preview-iframe-full {
+ width: 100%;
+ min-height: 400px;
+ border: none;
+ background: #fff;
+}
+
+.preview-text-block {
+ white-space: pre-wrap;
+ word-wrap: break-word;
+ font-size: 14px;
+ color: var(--text-secondary);
+ line-height: 1.6;
+ margin: 0;
+}
+
+.preview-error {
+ padding: 12px 16px;
+ background: var(--danger-50);
+ color: var(--danger-600);
+ border-radius: var(--radius);
+ font-size: 13px;
+}
+
+.source-label {
+ font-size: 11px;
+ font-weight: 600;
+ text-transform: uppercase;
+ letter-spacing: 0.06em;
+ color: var(--text-muted);
+ margin-bottom: 6px;
+}
+</style>
diff --git a/web/src/views/templates/Templates.vue b/web/src/views/templates/Templates.vue
new file mode 100644
index 0000000..17111d1
--- /dev/null
+++ b/web/src/views/templates/Templates.vue
@@ -0,0 +1,298 @@
+<script setup lang="ts">
+import { ref, onMounted } from 'vue'
+import { useRouter } from 'vue-router'
+import { templatesApi } from '../../api/templates'
+import { languagesApi } from '../../api/languages'
+import type { Template, TemplateInput, TemplateExport, Language, Pageable } from '../../api/types'
+import { useNotificationStore } from '../../stores/notification'
+import { useConfirm } from '../../composables/useConfirm'
+
+const router = useRouter()
+const notify = useNotificationStore()
+const { confirm } = useConfirm()
+
+const templates = ref<Template[]>([])
+const pageable = ref<Pageable>({ current_page: 0, size: 20, total_pages: 0, total_elements: 0, empty: true })
+const loading = ref(true)
+
+const showModal = ref(false)
+const editing = ref<Template | null>(null)
+const saving = ref(false)
+
+const languages = ref<Language[]>([])
+
+const form = ref<TemplateInput>({
+ name: '',
+ sample_data: '',
+ default_language: 'en',
+ description: '',
+})
+
+async function loadLanguages() {
+ try {
+ const res = await languagesApi.list(0, 100)
+ languages.value = res.data.data
+ } catch {
+ // Non-critical
+ }
+}
+
+function resetForm() {
+ form.value = { name: '', sample_data: '', default_language: 'en', description: '' }
+ editing.value = null
+}
+
+function openCreate() {
+ resetForm()
+ showModal.value = true
+}
+
+function openEdit(template: Template) {
+ editing.value = template
+ form.value = {
+ name: template.name,
+ sample_data: template.sample_data || '',
+ default_language: template.default_language || 'en',
+ description: template.description || '',
+ }
+ showModal.value = true
+}
+
+function closeModal() {
+ showModal.value = false
+ resetForm()
+}
+
+async function loadTemplates(page = 0) {
+ loading.value = true
+ try {
+ const res = await templatesApi.list(page, pageable.value.size)
+ templates.value = res.data.data
+ pageable.value = res.data.pageable
+ } catch {
+ notify.error('Failed to load templates')
+ } finally {
+ loading.value = false
+ }
+}
+
+async function saveTemplate() {
+ if (!form.value.name.trim()) return
+ saving.value = true
+ try {
+ if (editing.value) {
+ await templatesApi.update(editing.value.id, form.value)
+ notify.success('Template updated')
+ } else {
+ await templatesApi.create(form.value)
+ notify.success('Template created')
+ }
+ closeModal()
+ await loadTemplates(pageable.value.current_page)
+ } catch {
+ notify.error(editing.value ? 'Failed to update template' : 'Failed to create template')
+ } finally {
+ saving.value = false
+ }
+}
+
+async function deleteTemplate(template: Template) {
+ const confirmed = await confirm({
+ title: 'Delete Template',
+ message: `Are you sure you want to delete "${template.name}"? This action cannot be undone.`,
+ confirmText: 'Delete',
+ variant: 'danger',
+ })
+ if (!confirmed) return
+ try {
+ await templatesApi.delete(template.id)
+ notify.success('Template deleted')
+ await loadTemplates(pageable.value.current_page)
+ } catch {
+ notify.error('Failed to delete template')
+ }
+}
+
+async function exportTemplate(template: Template) {
+ try {
+ const res = await templatesApi.exportTemplate(template.id)
+ const data = res.data.data
+ const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' })
+ const url = URL.createObjectURL(blob)
+ const a = document.createElement('a')
+ a.href = url
+ a.download = `${data.name}.json`
+ a.click()
+ URL.revokeObjectURL(url)
+ notify.success('Template exported')
+ } catch {
+ notify.error('Failed to export template')
+ }
+}
+
+const importInput = ref<HTMLInputElement | null>(null)
+const importing = ref(false)
+
+function triggerImport() {
+ importInput.value?.click()
+}
+
+async function handleImportFile(event: Event) {
+ const input = event.target as HTMLInputElement
+ const file = input.files?.[0]
+ if (!file) return
+
+ importing.value = true
+ try {
+ const text = await file.text()
+ const data: TemplateExport = JSON.parse(text)
+ await templatesApi.importTemplate(data)
+ notify.success('Template imported')
+ await loadTemplates(pageable.value.current_page)
+ } catch {
+ notify.error('Failed to import template. Please check the file format.')
+ } finally {
+ importing.value = false
+ input.value = ''
+ }
+}
+
+function formatDate(dateStr: string): string {
+ return new Date(dateStr).toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' })
+}
+
+onMounted(() => {
+ loadTemplates()
+ loadLanguages()
+})
+</script>
+
+<template>
+ <div>
+ <div class="page-header">
+ <h1>Templates</h1>
+ <div class="flex gap-2">
+ <input ref="importInput" type="file" accept=".json" style="display: none" @change="handleImportFile" />
+ <button class="btn btn-secondary" :disabled="importing" @click="triggerImport">
+ {{ importing ? 'Importing...' : 'Import' }}
+ </button>
+ <button class="btn btn-primary" @click="openCreate">Create Template</button>
+ </div>
+ </div>
+
+ <div v-if="loading" class="loading-page">
+ <div class="spinner"></div>
+ </div>
+
+ <div v-else class="card">
+ <div v-if="templates.length === 0" class="empty-state">
+ <h3>No Templates</h3>
+ <p>Create your first template to reuse email layouts.</p>
+ </div>
+
+ <template v-else>
+ <div class="table-wrapper">
+ <table>
+ <thead>
+ <tr>
+ <th>Name</th>
+ <th>Language</th>
+ <th>Active Version</th>
+ <th>Created</th>
+ <th>Actions</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr v-for="tmpl in templates" :key="tmpl.id">
+ <td>
+ <div>{{ tmpl.name }}</div>
+ <div v-if="tmpl.description" class="text-muted text-sm">{{ tmpl.description }}</div>
+ </td>
+ <td><span class="badge badge-neutral">{{ tmpl.default_language }}</span></td>
+ <td>
+ <span v-if="tmpl.active_version_id" class="badge badge-success">v{{ tmpl.active_version?.version || '?' }}</span>
+ <span v-else class="text-muted">&mdash;</span>
+ </td>
+ <td>{{ formatDate(tmpl.created_at) }}</td>
+ <td>
+ <div class="flex gap-2">
+ <button class="btn btn-primary btn-sm" @click="router.push({ name: 'template-detail', params: { id: tmpl.id } })">Versions</button>
+ <button class="btn btn-secondary btn-sm" @click="router.push({ name: 'template-preview', params: { id: tmpl.id } })">Preview</button>
+ <button class="btn btn-secondary btn-sm" @click="openEdit(tmpl)">Edit</button>
+ <button class="btn btn-secondary btn-sm" @click="exportTemplate(tmpl)">Export</button>
+ <button class="btn btn-danger btn-sm" @click="deleteTemplate(tmpl)">Delete</button>
+ </div>
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+
+ <div class="pagination">
+ <span class="pagination-info">
+ Page {{ pageable.current_page + 1 }} of {{ pageable.total_pages }} ({{ pageable.total_elements }} templates)
+ </span>
+ <div class="pagination-buttons">
+ <button
+ class="btn btn-secondary btn-sm"
+ :disabled="pageable.current_page === 0"
+ @click="loadTemplates(pageable.current_page - 1)"
+ >
+ Previous
+ </button>
+ <button
+ class="btn btn-secondary btn-sm"
+ :disabled="pageable.current_page >= pageable.total_pages - 1"
+ @click="loadTemplates(pageable.current_page + 1)"
+ >
+ Next
+ </button>
+ </div>
+ </div>
+ </template>
+ </div>
+
+ <!-- Create/Edit Template Modal -->
+ <div v-if="showModal" class="modal-overlay" @click.self="closeModal">
+ <div class="modal" style="max-width: 560px;">
+ <div class="modal-header">
+ <h3>{{ editing ? 'Edit Template' : 'Create Template' }}</h3>
+ </div>
+
+ <div class="modal-body">
+ <div class="form-group">
+ <label class="form-label">Name</label>
+ <input v-model="form.name" class="form-input" placeholder="e.g. Welcome Email" />
+ </div>
+ <div class="form-group">
+ <label class="form-label">Description</label>
+ <input v-model="form.description" class="form-input" placeholder="e.g. Sent after user registration" />
+ </div>
+ <div class="form-group">
+ <label class="form-label">Default Language</label>
+ <select v-model="form.default_language" class="form-select">
+ <option v-for="lang in languages" :key="lang.id" :value="lang.code">{{ lang.name }} ({{ lang.code }})</option>
+ </select>
+ <span class="form-hint">Fallback language when no localization matches the requested language</span>
+ </div>
+ <div class="form-group">
+ <label class="form-label">Sample Data (JSON)</label>
+ <textarea v-model="form.sample_data" class="form-textarea" rows="3" placeholder='{"name": "John", "company": "Acme"}'></textarea>
+ <span class="form-hint">Default sample data for previewing template localizations</span>
+ </div>
+ </div>
+
+ <div class="modal-footer">
+ <button class="btn btn-secondary" @click="closeModal">Cancel</button>
+ <button
+ class="btn btn-primary"
+ :disabled="saving || !form.name.trim()"
+ @click="saveTemplate"
+ >
+ {{ saving ? 'Saving...' : (editing ? 'Update' : 'Create') }}
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+</template>
diff --git a/web/src/views/webhooks/WebhookDeliveries.vue b/web/src/views/webhooks/WebhookDeliveries.vue
new file mode 100644
index 0000000..6318be2
--- /dev/null
+++ b/web/src/views/webhooks/WebhookDeliveries.vue
@@ -0,0 +1,77 @@
+<script setup lang="ts">
+import { ref } from 'vue'
+import { webhookDeliveriesApi } from '../../api/webhooks'
+import type { WebhookDelivery } from '../../api/types'
+import Pagination from '../../components/Pagination.vue'
+import { usePagination } from '../../composables/usePagination'
+
+const loading = ref(true)
+const deliveries = ref<WebhookDelivery[]>([])
+
+const { pageable, goToPage } = usePagination(async (page) => {
+ loading.value = true
+ try {
+ const res = await webhookDeliveriesApi.list(page)
+ deliveries.value = res.data.data
+ pageable.value = res.data.pageable
+ } catch (e) {
+ console.error('Failed to load webhook deliveries', e)
+ } finally {
+ loading.value = false
+ }
+})
+
+function statusBadgeClass(status: string) {
+ return status === 'success' ? 'badge badge-success' : 'badge badge-danger'
+}
+
+function formatDate(date: string) {
+ return new Date(date).toLocaleString()
+}
+</script>
+
+<template>
+ <div>
+ <div class="page-header">
+ <h1>Webhook Deliveries</h1>
+ </div>
+
+ <div v-if="loading" class="loading-page">
+ <div class="spinner"></div>
+ </div>
+
+ <div v-else class="card">
+ <div v-if="deliveries.length === 0" class="empty-state">
+ <h3>No deliveries yet</h3>
+ <p>Webhook delivery attempts will appear here.</p>
+ </div>
+ <template v-else>
+ <div class="table-wrapper">
+ <table>
+ <thead>
+ <tr>
+ <th>Event</th>
+ <th>Status</th>
+ <th>HTTP Status</th>
+ <th>Attempt</th>
+ <th>Error</th>
+ <th>Delivered At</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr v-for="d in deliveries" :key="d.id">
+ <td><span class="badge badge-neutral">{{ d.event }}</span></td>
+ <td><span :class="statusBadgeClass(d.status)">{{ d.status }}</span></td>
+ <td>{{ d.http_status_code || '-' }}</td>
+ <td>{{ d.attempt }}</td>
+ <td class="truncate" style="max-width: 280px;">{{ d.error_message || '-' }}</td>
+ <td>{{ formatDate(d.created_at) }}</td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ <Pagination :pageable="pageable" @page="goToPage" />
+ </template>
+ </div>
+ </div>
+</template>
diff --git a/web/src/views/webhooks/Webhooks.vue b/web/src/views/webhooks/Webhooks.vue
new file mode 100644
index 0000000..a80dcf5
--- /dev/null
+++ b/web/src/views/webhooks/Webhooks.vue
@@ -0,0 +1,272 @@
+<script setup lang="ts">
+import { ref } from 'vue'
+import { webhooksApi } from '../../api/webhooks'
+import type { Webhook, WebhookInput } from '../../api/types'
+import Pagination from '../../components/Pagination.vue'
+import { usePagination } from '../../composables/usePagination'
+import { useNotificationStore } from '../../stores/notification'
+import { useConfirm } from '../../composables/useConfirm'
+
+const notify = useNotificationStore()
+const { confirm } = useConfirm()
+
+const webhooks = ref<Webhook[]>([])
+const loading = ref(true)
+
+const { pageable, goToPage } = usePagination(fetchWebhooks)
+
+const showModal = ref(false)
+const form = ref<WebhookInput>({
+ url: '',
+ events: [],
+ filters: [],
+})
+const filterInput = ref('')
+const saving = ref(false)
+
+const createdWebhook = ref<Webhook | null>(null)
+const showSecretModal = ref(false)
+const copied = ref(false)
+
+const availableEvents = ['email.sent', 'email.failed']
+
+async function fetchWebhooks(page = 0) {
+ loading.value = true
+ try {
+ const res = await webhooksApi.list(page)
+ webhooks.value = res.data.data
+ pageable.value = res.data.pageable
+ } catch {
+ notify.error('Failed to load webhooks')
+ } finally {
+ loading.value = false
+ }
+}
+
+function openCreate() {
+ form.value = { url: '', events: [], filters: [] }
+ filterInput.value = ''
+ showModal.value = true
+}
+
+function addFilter() {
+ const val = filterInput.value.trim().toLowerCase()
+ if (val && !form.value.filters.includes(val)) {
+ form.value.filters.push(val)
+ }
+ filterInput.value = ''
+}
+
+function removeFilter(index: number) {
+ form.value.filters.splice(index, 1)
+}
+
+function toggleEvent(event: string) {
+ const idx = form.value.events.indexOf(event)
+ if (idx >= 0) {
+ form.value.events.splice(idx, 1)
+ } else {
+ form.value.events.push(event)
+ }
+}
+
+async function createWebhook() {
+ if (!form.value.url.trim() || form.value.events.length === 0) return
+ saving.value = true
+ try {
+ const res = await webhooksApi.create(form.value)
+ createdWebhook.value = res.data.data
+ showModal.value = false
+ showSecretModal.value = true
+ notify.success('Webhook created')
+ await fetchWebhooks()
+ } catch {
+ notify.error('Failed to create webhook')
+ } finally {
+ saving.value = false
+ }
+}
+
+function copySecret() {
+ if (!createdWebhook.value?.secret) return
+ navigator.clipboard.writeText(createdWebhook.value.secret)
+ copied.value = true
+ setTimeout(() => (copied.value = false), 2000)
+}
+
+function closeSecretModal() {
+ showSecretModal.value = false
+ createdWebhook.value = null
+ copied.value = false
+}
+
+async function deleteWebhook(webhook: Webhook) {
+ const confirmed = await confirm({
+ title: 'Delete Webhook',
+ message: `Are you sure you want to delete the webhook for "${webhook.url}"?`,
+ confirmText: 'Delete',
+ variant: 'danger',
+ })
+ if (!confirmed) return
+ try {
+ await webhooksApi.delete(webhook.id)
+ notify.success('Webhook deleted')
+ await fetchWebhooks()
+ } catch {
+ notify.error('Failed to delete webhook')
+ }
+}
+
+function formatDate(dateStr: string): string {
+ return new Date(dateStr).toLocaleDateString('en-US', {
+ year: 'numeric',
+ month: 'short',
+ day: 'numeric',
+ })
+}
+
+</script>
+
+<template>
+ <div>
+ <div class="page-header">
+ <h1>Webhooks</h1>
+ <button class="btn btn-primary" @click="openCreate">Add Webhook</button>
+ </div>
+
+ <div v-if="loading" class="loading-page">
+ <div class="spinner"></div>
+ </div>
+
+ <template v-else>
+ <div class="card">
+ <div class="table-wrapper" v-if="webhooks.length > 0">
+ <table>
+ <thead>
+ <tr>
+ <th>URL</th>
+ <th>Events</th>
+ <th>Filters</th>
+ <th>Created At</th>
+ <th>Actions</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr v-for="webhook in webhooks" :key="webhook.id">
+ <td class="truncate" style="max-width: 300px;">{{ webhook.url }}</td>
+ <td>
+ <div class="flex gap-2" style="flex-wrap: wrap;">
+ <span v-for="event in webhook.events" :key="event" class="badge badge-neutral">
+ {{ event }}
+ </span>
+ </div>
+ </td>
+ <td>
+ <div class="flex gap-2" style="flex-wrap: wrap;" v-if="webhook.filters && webhook.filters.length > 0">
+ <span v-for="filter in webhook.filters" :key="filter" class="badge badge-neutral">
+ {{ filter }}
+ </span>
+ </div>
+ <span v-else class="text-muted">All senders</span>
+ </td>
+ <td>{{ formatDate(webhook.created_at) }}</td>
+ <td>
+ <button class="btn btn-danger btn-sm" @click="deleteWebhook(webhook)">Delete</button>
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+
+ <div v-else class="empty-state">
+ <h3>No webhooks</h3>
+ <p>Add a webhook to receive event notifications.</p>
+ </div>
+
+ <Pagination :pageable="pageable" @page="goToPage" />
+ </div>
+ </template>
+
+ <!-- Create Webhook Modal -->
+ <div v-if="showModal" class="modal-overlay" @click.self="showModal = false">
+ <div class="modal">
+ <div class="modal-header">
+ <h3>Add Webhook</h3>
+ </div>
+ <form @submit.prevent="createWebhook">
+ <div class="modal-body">
+ <div class="form-group">
+ <label class="form-label">URL</label>
+ <input v-model="form.url" type="url" class="form-input" placeholder="https://example.com/webhook" required />
+ </div>
+ <div class="form-group">
+ <label class="form-label">Events</label>
+ <div style="display: flex; flex-direction: column; gap: 8px; margin-top: 4px;">
+ <label v-for="event in availableEvents" :key="event" class="checkbox-label">
+ <input
+ type="checkbox"
+ :checked="form.events.includes(event)"
+ @change="toggleEvent(event)"
+ />
+ {{ event }}
+ </label>
+ </div>
+ </div>
+ <div class="form-group">
+ <label class="form-label">Sender Filters <span class="text-muted">(optional)</span></label>
+ <p style="font-size: 0.85em; color: var(--text-muted); margin: 0 0 8px;">
+ Restrict this webhook to specific senders. Enter an email address or domain. Leave empty to fire for all emails.
+ </p>
+ <div style="display: flex; gap: 8px;">
+ <input
+ v-model="filterInput"
+ type="text"
+ class="form-input"
+ placeholder="e.g. example.com or [email protected]"
+ @keydown.enter.prevent="addFilter"
+ />
+ <button type="button" class="btn btn-secondary" @click="addFilter">Add</button>
+ </div>
+ <div v-if="form.filters.length > 0" style="display: flex; flex-wrap: wrap; gap: 6px; margin-top: 8px;">
+ <span v-for="(filter, idx) in form.filters" :key="filter" class="badge badge-neutral" style="cursor: pointer;" @click="removeFilter(idx)">
+ {{ filter }} &times;
+ </span>
+ </div>
+ </div>
+ </div>
+ <div class="modal-footer">
+ <button type="button" class="btn btn-secondary" @click="showModal = false">Cancel</button>
+ <button type="submit" class="btn btn-primary" :disabled="saving || form.events.length === 0">
+ {{ saving ? 'Creating...' : 'Create Webhook' }}
+ </button>
+ </div>
+ </form>
+ </div>
+ </div>
+
+ <!-- Signing Secret Modal -->
+ <div v-if="showSecretModal" class="modal-overlay">
+ <div class="modal">
+ <div class="modal-header">
+ <h3>Webhook Signing Secret</h3>
+ </div>
+ <div class="modal-body">
+ <p class="text-sm" style="color: var(--danger-600); font-weight: 500; margin-bottom: 12px;">
+ Save this secret. It won't be shown again.
+ </p>
+ <div class="code-block">{{ createdWebhook?.secret }}</div>
+ <p class="text-sm" style="margin-top: 12px; color: var(--text-muted);">
+ Use this secret to verify webhook signatures. Each delivery includes an
+ <code>X-Posta-Signature</code> header with an HMAC-SHA256 signature of the payload.
+ </p>
+ <button class="btn btn-secondary btn-sm mt-4" @click="copySecret">
+ {{ copied ? 'Copied!' : 'Copy Secret' }}
+ </button>
+ </div>
+ <div class="modal-footer">
+ <button class="btn btn-primary" @click="closeSecretModal">Done</button>
+ </div>
+ </div>
+ </div>
+ </div>
+</template>
diff --git a/web/tsconfig.json b/web/tsconfig.json
new file mode 100644
index 0000000..ac09dd6
--- /dev/null
+++ b/web/tsconfig.json
@@ -0,0 +1,21 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "strict": true,
+ "jsx": "preserve",
+ "resolveJsonModule": true,
+ "isolatedModules": true,
+ "esModuleInterop": true,
+ "lib": ["ES2022", "DOM", "DOM.Iterable"],
+ "skipLibCheck": true,
+ "noEmit": true,
+ "paths": {
+ "@/*": ["./src/*"]
+ },
+ "baseUrl": "."
+ },
+ "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.vue", "env.d.ts"],
+ "references": [{ "path": "./tsconfig.node.json" }]
+}
diff --git a/web/tsconfig.node.json b/web/tsconfig.node.json
new file mode 100644
index 0000000..257785d
--- /dev/null
+++ b/web/tsconfig.node.json
@@ -0,0 +1,11 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "allowSyntheticDefaultImports": true,
+ "strict": true,
+ "noEmit": true
+ },
+ "include": ["vite.config.ts"]
+}
diff --git a/web/vite.config.ts b/web/vite.config.ts
new file mode 100644
index 0000000..a93c139
--- /dev/null
+++ b/web/vite.config.ts
@@ -0,0 +1,21 @@
+import { defineConfig } from 'vite'
+import vue from '@vitejs/plugin-vue'
+import { resolve } from 'path'
+
+export default defineConfig({
+ plugins: [vue()],
+ resolve: {
+ alias: {
+ '@': resolve(__dirname, 'src'),
+ },
+ },
+ server: {
+ port: 3000,
+ proxy: {
+ '/api/v1': {
+ target: 'http://localhost:9000',
+ changeOrigin: true,
+ },
+ },
+ },
+})