mirror of
https://github.com/StarFleetCPTN/GoMFT.git
synced 2026-09-08 15:41:20 +02:00
feat: Enhance notifications and pagination functionality
- Implemented pagination for user notifications, allowing users to navigate through their notifications more efficiently. - Updated the notifications page to display the total count of notifications and provide controls for adjusting the number of notifications shown per page. - Added backend support for fetching paginated notifications and counting total notifications for users. - Improved the user interface for notifications, including a new layout and additional help sections to guide users on managing their notifications.
This commit is contained in:
@@ -81,11 +81,11 @@ templ AdminDatabaseTools(ctx context.Context, backups []BackupFile) {
|
||||
</div>
|
||||
<p class="text-gray-600 dark:text-gray-400 mb-4">Export system configurations and jobs for backup or migration.</p>
|
||||
<div class="flex space-x-2">
|
||||
<a href="/admin/export-configs" class="flex-1 px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 dark:bg-green-700 dark:hover:bg-green-800 text-center">
|
||||
<a href="/admin/database/export-configs" class="flex-1 px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 dark:bg-green-700 dark:hover:bg-green-800 text-center">
|
||||
<i class="fas fa-cogs mr-2"></i>
|
||||
Export Configs
|
||||
</a>
|
||||
<a href="/admin/export-jobs" class="flex-1 px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 dark:bg-green-700 dark:hover:bg-green-800 text-center">
|
||||
<a href="/admin/database/export-jobs" class="flex-1 px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 dark:bg-green-700 dark:hover:bg-green-800 text-center">
|
||||
<i class="fas fa-tasks mr-2"></i>
|
||||
Export Jobs
|
||||
</a>
|
||||
|
||||
@@ -147,15 +147,15 @@ templ Dashboard(ctx context.Context, data DashboardData) {
|
||||
<div class="flex items-center">
|
||||
<div class="flex-shrink-0">
|
||||
if job.Status == "completed" {
|
||||
<span class="inline-flex items-center justify-center h-12 w-12 rounded-full bg-green-100 dark:bg-green-900">
|
||||
<span class="inline-flex items-center justify-center h-12 w-12 rounded-full text-green-600 bg-green-100 dark:bg-green-900">
|
||||
<i class="fas fa-check-circle w-6 h-6 flex items-center justify-center"></i>
|
||||
</span>
|
||||
} else if job.Status == "failed" {
|
||||
<span class="inline-flex items-center justify-center h-12 w-12 rounded-full bg-red-100 dark:bg-red-900">
|
||||
<span class="inline-flex items-center justify-center h-12 w-12 rounded-full text-red-600 bg-red-100 dark:bg-red-900">
|
||||
<i class="fas fa-exclamation-circle w-6 h-6 flex items-center justify-center"></i>
|
||||
</span>
|
||||
} else {
|
||||
<span class="inline-flex items-center justify-center h-12 w-12 rounded-full bg-blue-100 dark:bg-blue-900">
|
||||
<span class="inline-flex items-center justify-center h-12 w-12 rounded-full text-blue-600 bg-blue-100 dark:bg-blue-900">
|
||||
<i class="fas fa-tasks w-6 h-6 flex items-center justify-center"></i>
|
||||
</span>
|
||||
}
|
||||
|
||||
+66
-98
@@ -2,13 +2,13 @@ package components
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/gin-gonic/gin"
|
||||
"time"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// AppVersion will be set at build time using ldflags
|
||||
// Example build command:
|
||||
// Example build command:
|
||||
// go build -ldflags "-X github.com/starfleetcptn/gomft/components.AppVersion=1.2.3"
|
||||
var AppVersion = "dev"
|
||||
|
||||
@@ -48,22 +48,22 @@ templ LayoutWithContext(title string, ctx context.Context) {
|
||||
<meta name="theme-color" content="#2563eb"/>
|
||||
<meta name="apple-mobile-web-app-capable" content="yes"/>
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent"/>
|
||||
<link rel="apple-touch-icon" sizes="180x180" href="/static/apple-touch-icon.png">
|
||||
<link rel="icon" type="image/png" sizes="32x32" href="/static/favicon-32x32.png">
|
||||
<link rel="icon" type="image/png" sizes="16x16" href="/static/favicon-16x16.png">
|
||||
<link rel="manifest" href="/static/site.webmanifest">
|
||||
<link rel="apple-touch-icon" sizes="180x180" href="/static/apple-touch-icon.png"/>
|
||||
<link rel="icon" type="image/png" sizes="32x32" href="/static/favicon-32x32.png"/>
|
||||
<link rel="icon" type="image/png" sizes="16x16" href="/static/favicon-16x16.png"/>
|
||||
<link rel="manifest" href="/static/site.webmanifest"/>
|
||||
<title>{ title } - GoMFT</title>
|
||||
<script src="https://unpkg.com/htmx.org@1.9.10"></script>
|
||||
<script src="https://unpkg.com/alpinejs@3.13.5/dist/cdn.min.js" defer></script>
|
||||
<!-- Tailwind CSS with Flowbite -->
|
||||
<script src="https://cdn.tailwindcss.com"></script>
|
||||
<link href="https://cdnjs.cloudflare.com/ajax/libs/flowbite/2.2.1/flowbite.min.css" rel="stylesheet" />
|
||||
<link href="https://cdnjs.cloudflare.com/ajax/libs/flowbite/2.2.1/flowbite.min.css" rel="stylesheet"/>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/flowbite/2.2.1/flowbite.min.js"></script>
|
||||
<script src="/static/js/app.js"></script>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"/>
|
||||
<link rel="stylesheet" href="/static/css/app.css"/>
|
||||
<!-- Notyf Toast Notifications -->
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/notyf@3/notyf.min.css" />
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/notyf@3/notyf.min.css"/>
|
||||
<script src="https://cdn.jsdelivr.net/npm/notyf@3/notyf.min.js"></script>
|
||||
<script>
|
||||
// Initialize Notyf and make it available globally
|
||||
@@ -180,7 +180,7 @@ templ LayoutWithContext(title string, ctx context.Context) {
|
||||
background-color: #1f2937 !important;
|
||||
}
|
||||
</style>
|
||||
<link rel="stylesheet" href="https://rsms.me/inter/inter.css">
|
||||
<link rel="stylesheet" href="https://rsms.me/inter/inter.css"/>
|
||||
<script>
|
||||
// Immediate theme application
|
||||
// This script runs before the DOM is fully loaded
|
||||
@@ -243,69 +243,34 @@ templ LayoutWithContext(title string, ctx context.Context) {
|
||||
Files
|
||||
</a>
|
||||
if isAdmin(ctx) {
|
||||
<div class="pt-4 mt-4 border-t border-gray-200 dark:border-gray-700">
|
||||
<p class="px-3 text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">
|
||||
Administration
|
||||
</p>
|
||||
<div class="mt-1 space-y-1">
|
||||
<!-- Admin dropdown menu -->
|
||||
<button
|
||||
type="button"
|
||||
class="flex items-center w-full p-2 text-sm font-medium text-gray-700 rounded-lg transition duration-75 group hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-700"
|
||||
aria-controls="dropdown-admin"
|
||||
data-collapse-toggle="dropdown-admin"
|
||||
aria-expanded="true"
|
||||
>
|
||||
<i class="fas fa-shield-alt w-5 h-5 text-gray-500 dark:text-gray-400 mr-3"></i>
|
||||
<span class="flex-1 text-left whitespace-nowrap">Admin Console</span>
|
||||
<i class="fas fa-chevron-down w-4 h-4"></i>
|
||||
</button>
|
||||
<ul id="dropdown-admin" class="hidden py-2 space-y-1">
|
||||
<li>
|
||||
<a href="/admin" class="flex items-center p-2 pl-11 w-full text-sm font-normal text-gray-700 rounded-lg transition duration-75 group hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-700">
|
||||
<i class="fas fa-tachometer-alt w-4 h-4 mr-2 text-gray-500 dark:text-gray-400"></i>
|
||||
Dashboard
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="/admin/users" class="flex items-center p-2 pl-11 w-full text-sm font-normal text-gray-700 rounded-lg transition duration-75 group hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-700">
|
||||
<i class="fas fa-users w-4 h-4 mr-2 text-gray-500 dark:text-gray-400"></i>
|
||||
Users
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="/admin/roles" class="flex items-center p-2 pl-11 w-full text-sm font-normal text-gray-700 rounded-lg transition duration-75 group hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-700">
|
||||
<i class="fas fa-user-shield w-4 h-4 mr-2 text-gray-500 dark:text-gray-400"></i>
|
||||
Roles
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="/admin/audit" class="flex items-center p-2 pl-11 w-full text-sm font-normal text-gray-700 rounded-lg transition duration-75 group hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-700">
|
||||
<i class="fas fa-clipboard-list w-4 h-4 mr-2 text-gray-500 dark:text-gray-400"></i>
|
||||
Audit Logs
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="/admin/database" class="flex items-center p-2 pl-11 w-full text-sm font-normal text-gray-700 rounded-lg transition duration-75 group hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-700">
|
||||
<i class="fas fa-database w-4 h-4 mr-2 text-gray-500 dark:text-gray-400"></i>
|
||||
Database Tools
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="/admin/settings" class="flex items-center p-2 pl-11 w-full text-sm font-normal text-gray-700 rounded-lg transition duration-75 group hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-700">
|
||||
<i class="fas fa-cog w-4 h-4 mr-2 text-gray-500 dark:text-gray-400"></i>
|
||||
Settings
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<p class="px-3 text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">
|
||||
Administration
|
||||
</p>
|
||||
<a href="/admin/users" class="group flex items-center px-2 py-2 text-sm font-medium rounded-md text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-700">
|
||||
<i class="fas fa-users w-4 h-4 mr-2 text-gray-500 dark:text-gray-400"></i>
|
||||
Users
|
||||
</a>
|
||||
<a href="/admin/roles" class="group flex items-center px-2 py-2 text-sm font-medium rounded-md text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-700">
|
||||
<i class="fas fa-user-shield w-4 h-4 mr-2 text-gray-500 dark:text-gray-400"></i>
|
||||
Roles
|
||||
</a>
|
||||
<a href="/admin/audit" class="group flex items-center px-2 py-2 text-sm font-medium rounded-md text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-700">
|
||||
<i class="fas fa-clipboard-list w-4 h-4 mr-2 text-gray-500 dark:text-gray-400"></i>
|
||||
Audit Logs
|
||||
</a>
|
||||
<a href="/admin/database" class="group flex items-center px-2 py-2 text-sm font-medium rounded-md text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-700">
|
||||
<i class="fas fa-database w-4 h-4 mr-2 text-gray-500 dark:text-gray-400"></i>
|
||||
Database Tools
|
||||
</a>
|
||||
<a href="/admin/settings" class="group flex items-center px-2 py-2 text-sm font-medium rounded-md text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-700">
|
||||
<i class="fas fa-cog w-4 h-4 mr-2 text-gray-500 dark:text-gray-400"></i>
|
||||
Settings
|
||||
</a>
|
||||
}
|
||||
</div>
|
||||
</nav>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<!-- Mobile menu -->
|
||||
<div class="md:hidden fixed top-0 z-30 w-full">
|
||||
<div class="bg-white dark:bg-gray-800 shadow-sm">
|
||||
@@ -322,7 +287,6 @@ templ LayoutWithContext(title string, ctx context.Context) {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Main Content -->
|
||||
<div class="md:pl-64 flex flex-col flex-1 w-full bg-gray-50 dark:bg-gray-900">
|
||||
<!-- Main header -->
|
||||
@@ -346,29 +310,30 @@ templ LayoutWithContext(title string, ctx context.Context) {
|
||||
<i class="fas fa-sun hidden dark:block"></i>
|
||||
<i class="fas fa-moon block dark:hidden"></i>
|
||||
</button>
|
||||
|
||||
<!-- Notification Bell -->
|
||||
<div class="relative">
|
||||
<button
|
||||
type="button"
|
||||
class="p-2 text-gray-500 rounded-lg hover:text-gray-900 hover:bg-gray-100 dark:text-gray-400 dark:hover:text-white dark:hover:bg-gray-700 focus:ring-4 focus:ring-gray-300 dark:focus:ring-gray-600 relative"
|
||||
id="notification-bell"
|
||||
<button
|
||||
type="button"
|
||||
class="p-2 text-gray-500 rounded-lg hover:text-gray-900 hover:bg-gray-100 dark:text-gray-400 dark:hover:text-white dark:hover:bg-gray-700 focus:ring-4 focus:ring-gray-300 dark:focus:ring-gray-600 relative"
|
||||
id="notification-bell"
|
||||
data-dropdown-toggle="notification-dropdown"
|
||||
hx-get="/notifications/dropdown"
|
||||
hx-trigger="click once"
|
||||
hx-target="#notification-dropdown-content"
|
||||
data-dropdown-placement="bottom-end">
|
||||
hx-target="#notification-dropdown-content"
|
||||
data-dropdown-placement="bottom-end"
|
||||
>
|
||||
<span class="sr-only">View notifications</span>
|
||||
<i class="fas fa-bell"></i>
|
||||
<!-- Notification badge will be loaded dynamically -->
|
||||
<div hx-get="/notifications/count" hx-trigger="load, notification-updated from:body" id="notification-count-container"></div>
|
||||
</button>
|
||||
|
||||
<!-- Notification dropdown -->
|
||||
<div class="hidden overflow-hidden z-50 my-4 max-w-sm md:max-w-md w-full text-base list-none bg-white rounded divide-y divide-gray-100 shadow-lg dark:divide-gray-600 dark:bg-gray-700 rounded-xl"
|
||||
id="notification-dropdown"
|
||||
style="min-width: 320px; width: 100%;"
|
||||
data-dropdown-placement="bottom-end">
|
||||
<div
|
||||
class="hidden overflow-hidden z-50 my-4 max-w-sm md:max-w-md w-full text-base list-none bg-white rounded divide-y divide-gray-100 shadow-lg dark:divide-gray-600 dark:bg-gray-700 rounded-xl"
|
||||
id="notification-dropdown"
|
||||
style="min-width: 320px; width: 100%;"
|
||||
data-dropdown-placement="bottom-end"
|
||||
>
|
||||
<div id="notification-dropdown-content">
|
||||
<!-- Content will be loaded dynamically via HTMX -->
|
||||
<div class="block py-2 px-4 text-base font-medium text-center text-gray-700 bg-gray-50 dark:bg-gray-600 dark:text-gray-300">
|
||||
@@ -395,38 +360,44 @@ templ LayoutWithContext(title string, ctx context.Context) {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- User menu dropdown -->
|
||||
<div class="relative">
|
||||
<button type="button"
|
||||
class="flex text-sm rounded-full focus:ring-4 focus:ring-gray-300 dark:focus:ring-gray-600"
|
||||
id="user-menu-button"
|
||||
data-dropdown-toggle="user-dropdown"
|
||||
data-dropdown-placement="bottom-end">
|
||||
<button
|
||||
type="button"
|
||||
class="flex text-sm rounded-full focus:ring-4 focus:ring-gray-300 dark:focus:ring-gray-600"
|
||||
id="user-menu-button"
|
||||
data-dropdown-toggle="user-dropdown"
|
||||
data-dropdown-placement="bottom-end"
|
||||
>
|
||||
<span class="sr-only">Open user menu</span>
|
||||
<div class="h-8 w-8 rounded-full bg-primary-100 text-primary-700 flex items-center justify-center dark:bg-primary-900 dark:text-primary-300">
|
||||
<span class="text-sm font-medium">{ getUserInitial(ctx) }</span>
|
||||
</div>
|
||||
</button>
|
||||
|
||||
<!-- Dropdown menu -->
|
||||
<div class="z-50 hidden my-4 text-base list-none bg-white divide-y divide-gray-100 rounded-lg shadow dark:bg-gray-700 dark:divide-gray-600"
|
||||
id="user-dropdown">
|
||||
<div
|
||||
class="z-50 hidden my-4 text-base list-none bg-white divide-y divide-gray-100 rounded-lg shadow dark:bg-gray-700 dark:divide-gray-600"
|
||||
id="user-dropdown"
|
||||
>
|
||||
<div class="px-4 py-3">
|
||||
<span class="block text-sm text-gray-900 dark:text-white">{ getUserEmail(ctx) }</span>
|
||||
</div>
|
||||
<ul class="py-2" aria-labelledby="user-menu-button">
|
||||
<li>
|
||||
<a href="/profile"
|
||||
class="flex items-center px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 dark:hover:bg-gray-600 dark:text-gray-200 dark:hover:text-white">
|
||||
<a
|
||||
href="/profile"
|
||||
class="flex items-center px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 dark:hover:bg-gray-600 dark:text-gray-200 dark:hover:text-white"
|
||||
>
|
||||
<i class="fas fa-user-circle mr-2 w-4"></i>
|
||||
Profile
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<form method="POST" action="/logout">
|
||||
<button type="submit"
|
||||
class="w-full text-left flex items-center px-4 py-2 text-sm text-red-600 hover:bg-gray-100 dark:hover:bg-gray-600 dark:hover:text-white">
|
||||
<button
|
||||
type="submit"
|
||||
class="w-full text-left flex items-center px-4 py-2 text-sm text-red-600 hover:bg-gray-100 dark:hover:bg-gray-600 dark:hover:text-white"
|
||||
>
|
||||
<i class="fas fa-sign-out-alt mr-2 w-4"></i>
|
||||
Sign out
|
||||
</button>
|
||||
@@ -438,7 +409,6 @@ templ LayoutWithContext(title string, ctx context.Context) {
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<!-- Page Content -->
|
||||
<main class="flex-1 bg-gray-50 dark:bg-gray-900">
|
||||
<div class="py-6 bg-gray-50 dark:bg-gray-900">
|
||||
@@ -449,7 +419,6 @@ templ LayoutWithContext(title string, ctx context.Context) {
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<!-- Footer -->
|
||||
<footer class="bg-gray-50 dark:bg-gray-900 border-t border-gray-200 dark:border-gray-700">
|
||||
<div class="max-w-screen-2xl mx-auto py-4 px-4 sm:px-6 lg:px-8">
|
||||
@@ -491,7 +460,6 @@ templ LayoutWithContext(title string, ctx context.Context) {
|
||||
</footer>
|
||||
</div>
|
||||
}
|
||||
|
||||
<script>
|
||||
// Add script to ensure dark mode is properly applied
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
@@ -595,4 +563,4 @@ func getUserEmail(ctx context.Context) string {
|
||||
// Helper function to get current year
|
||||
func getCurrentYear() string {
|
||||
return time.Now().Format("2006")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,84 +3,313 @@ package components
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// Note: To implement pagination, update the NotificationsData struct in notifications.templ
|
||||
// to include these fields:
|
||||
// CurrentPage int
|
||||
// TotalPages int
|
||||
// TotalCount int
|
||||
// PerPage int
|
||||
|
||||
templ NotificationsPage(ctx context.Context, data NotificationsData) {
|
||||
@LayoutWithContext("Notifications", ctx) {
|
||||
<div class="bg-white dark:bg-gray-800 shadow-sm rounded-lg overflow-hidden">
|
||||
<div class="p-6">
|
||||
<div class="flex justify-between items-center mb-6">
|
||||
<h1 class="text-2xl font-bold text-gray-900 dark:text-white">Notifications</h1>
|
||||
<div class="flex space-x-2">
|
||||
<a
|
||||
href="/notifications/mark-all-read"
|
||||
hx-post="/notifications/mark-all-read"
|
||||
hx-swap="none"
|
||||
hx-target="#notification-bell"
|
||||
class="text-sm font-medium text-primary-600 hover:text-primary-700 dark:text-primary-400 dark:hover:text-primary-300"
|
||||
>
|
||||
<i class="fas fa-check-double mr-1"></i>
|
||||
Mark all as read
|
||||
</a>
|
||||
<div class="py-6 px-4 mx-auto max-w-7xl lg:px-8">
|
||||
<!-- Page Header -->
|
||||
<div class="flex flex-col sm:flex-row sm:items-center sm:justify-between mb-8">
|
||||
<h1 class="text-2xl font-bold text-gray-900 dark:text-white flex items-center">
|
||||
<i class="fas fa-bell w-6 h-6 mr-2 text-blue-500 dark:text-blue-400"></i>
|
||||
Notifications
|
||||
</h1>
|
||||
<div class="text-sm text-gray-500 dark:text-gray-400 bg-gray-50 dark:bg-gray-800 rounded-lg px-4 py-2 inline-flex items-center">
|
||||
<i class="fas fa-info-circle mr-2"></i>
|
||||
<span class="font-medium">Total: { fmt.Sprint(data.TotalCount) } notifications</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Controls and Filters -->
|
||||
<div class="mb-6 p-4 bg-white border border-gray-200 rounded-lg shadow-sm dark:bg-gray-800 dark:border-gray-700">
|
||||
<div class="flex flex-col sm:flex-row sm:items-center gap-4">
|
||||
<div class="ml-auto">
|
||||
<label class="inline-flex items-center text-sm text-gray-700 dark:text-gray-300">
|
||||
Show
|
||||
<select
|
||||
id="perPage"
|
||||
name="perPage"
|
||||
class="mx-2 bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
|
||||
hx-get={ fmt.Sprintf("/notifications?page=1&perPage=%s", "${this.value}") }
|
||||
hx-target="body"
|
||||
hx-swap="innerHTML"
|
||||
hx-trigger="change"
|
||||
>
|
||||
<option value="10" selected?={ data.PerPage == 10 }>10</option>
|
||||
<option value="25" selected?={ data.PerPage == 25 }>25</option>
|
||||
<option value="50" selected?={ data.PerPage == 50 }>50</option>
|
||||
<option value="100" selected?={ data.PerPage == 100 }>100</option>
|
||||
</select>
|
||||
entries
|
||||
</label>
|
||||
</div>
|
||||
<a
|
||||
href="/notifications/mark-all-read"
|
||||
hx-post="/notifications/mark-all-read"
|
||||
hx-swap="none"
|
||||
hx-target="#notification-bell"
|
||||
class="inline-flex items-center py-2.5 px-4 text-sm font-medium text-white bg-blue-700 rounded-lg border border-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800"
|
||||
>
|
||||
<i class="fas fa-check-double w-4 h-4 mr-2"></i>
|
||||
Mark all as read
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Main Content -->
|
||||
if len(data.Notifications) == 0 {
|
||||
<div class="p-8 text-center bg-white dark:bg-gray-800 rounded-lg shadow border border-gray-200 dark:border-gray-700">
|
||||
<div class="flex justify-center mb-4">
|
||||
<span class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-gray-100 dark:bg-gray-700">
|
||||
<i class="fas fa-bell-slash text-gray-400 dark:text-gray-500 text-3xl"></i>
|
||||
</span>
|
||||
</div>
|
||||
<h3 class="text-lg font-medium text-gray-900 dark:text-white">No notifications</h3>
|
||||
<p class="mt-1 text-sm text-gray-500 dark:text-gray-400">You don't have any notifications yet.</p>
|
||||
</div>
|
||||
} else {
|
||||
<div class="bg-white border border-gray-200 rounded-lg shadow-sm dark:border-gray-700 dark:bg-gray-800 overflow-hidden">
|
||||
<ul class="divide-y divide-gray-200 dark:divide-gray-700">
|
||||
for _, notification := range data.Notifications {
|
||||
<li id={ "notification-" + fmt.Sprintf("%d", notification.ID) }
|
||||
class={ templ.KV("bg-blue-50 dark:bg-blue-900/20", !notification.IsRead) }>
|
||||
<div class="block transition-colors px-4 py-4 sm:px-6">
|
||||
<div class="flex items-start">
|
||||
<div class="flex-shrink-0 mr-4">
|
||||
<div class={ "w-12 h-12 rounded-full flex items-center justify-center", GetNotificationBgColor(notification.Type) }>
|
||||
<i class={ GetNotificationIcon(notification.Type) }></i>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex-1 min-w-0">
|
||||
<div class="flex justify-between items-start">
|
||||
<div>
|
||||
<h3 class="text-base font-medium text-gray-900 dark:text-white">{ notification.Title }</h3>
|
||||
<p class="text-sm text-gray-500 dark:text-gray-400 mt-1">{ notification.Message }</p>
|
||||
</div>
|
||||
<div class="flex items-center text-xs text-gray-500 dark:text-gray-400">
|
||||
<span>{ FormatNotificationTime(notification.CreatedAt) }</span>
|
||||
if !notification.IsRead {
|
||||
<button
|
||||
hx-post={ "/notifications/" + fmt.Sprintf("%d", notification.ID) + "/read" }
|
||||
hx-target={ "#notification-" + fmt.Sprintf("%d", notification.ID) }
|
||||
hx-swap="outerHTML"
|
||||
class="ml-4 text-blue-700 bg-blue-100 hover:bg-blue-200 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-3 py-1.5 text-center inline-flex items-center dark:text-blue-400 dark:bg-blue-900/30 dark:hover:bg-blue-900/40 dark:focus:ring-blue-800"
|
||||
>
|
||||
<i class="fas fa-check w-3.5 h-3.5 mr-1.5"></i>
|
||||
Mark as read
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-2">
|
||||
<a
|
||||
href={ templ.SafeURL(notification.Link) }
|
||||
class="text-blue-700 bg-blue-100 hover:bg-blue-200 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-3 py-1.5 text-center inline-flex items-center dark:text-blue-400 dark:bg-blue-900/30 dark:hover:bg-blue-900/40 dark:focus:ring-blue-800">
|
||||
<i class="fas fa-eye w-3.5 h-3.5 mr-1.5"></i>
|
||||
View details
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
}
|
||||
</ul>
|
||||
|
||||
<!-- Pagination -->
|
||||
if data.TotalPages > 1 {
|
||||
<div class="mt-6 flex flex-col sm:flex-row justify-between items-center py-4 px-4 border-t border-gray-200 dark:border-gray-700">
|
||||
<!-- Mobile pagination -->
|
||||
<div class="flex-1 flex justify-between gap-4 sm:hidden w-full mb-4 sm:mb-0">
|
||||
if data.CurrentPage > 1 {
|
||||
<a
|
||||
href={ templ.SafeURL("/notifications?page=" + strconv.Itoa(data.CurrentPage-1) + "&perPage=" + strconv.Itoa(data.PerPage)) }
|
||||
hx-get={ "/notifications?page=" + strconv.Itoa(data.CurrentPage-1) + "&perPage=" + strconv.Itoa(data.PerPage) }
|
||||
hx-target="body"
|
||||
hx-swap="innerHTML"
|
||||
class="w-full inline-flex justify-center items-center px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-100 dark:bg-gray-800 dark:border-gray-600 dark:text-gray-400 dark:hover:bg-gray-700"
|
||||
>
|
||||
<i class="fas fa-chevron-left mr-1"></i> Previous
|
||||
</a>
|
||||
} else {
|
||||
<span class="w-full inline-flex justify-center items-center px-4 py-2 text-sm font-medium text-gray-400 bg-gray-100 border border-gray-300 rounded-lg dark:bg-gray-800 dark:border-gray-600 dark:text-gray-600 cursor-not-allowed">
|
||||
<i class="fas fa-chevron-left mr-1"></i> Previous
|
||||
</span>
|
||||
}
|
||||
|
||||
if data.CurrentPage < data.TotalPages {
|
||||
<a
|
||||
href={ templ.SafeURL("/notifications?page=" + strconv.Itoa(data.CurrentPage+1) + "&perPage=" + strconv.Itoa(data.PerPage)) }
|
||||
hx-get={ "/notifications?page=" + strconv.Itoa(data.CurrentPage+1) + "&perPage=" + strconv.Itoa(data.PerPage) }
|
||||
hx-target="body"
|
||||
hx-swap="innerHTML"
|
||||
class="w-full inline-flex justify-center items-center px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-100 dark:bg-gray-800 dark:border-gray-600 dark:text-gray-400 dark:hover:bg-gray-700"
|
||||
>
|
||||
Next <i class="fas fa-chevron-right ml-1"></i>
|
||||
</a>
|
||||
} else {
|
||||
<span class="w-full inline-flex justify-center items-center px-4 py-2 text-sm font-medium text-gray-400 bg-gray-100 border border-gray-300 rounded-lg dark:bg-gray-800 dark:border-gray-600 dark:text-gray-600 cursor-not-allowed">
|
||||
Next <i class="fas fa-chevron-right ml-1"></i>
|
||||
</span>
|
||||
}
|
||||
</div>
|
||||
|
||||
<!-- Desktop pagination -->
|
||||
<div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
|
||||
<div>
|
||||
<p class="text-sm text-gray-700 dark:text-gray-300">
|
||||
Showing
|
||||
<span class="font-medium">{ fmt.Sprint((data.CurrentPage-1)*data.PerPage + 1) }</span>
|
||||
to
|
||||
<span class="font-medium">{ fmt.Sprint(minInt((data.CurrentPage)*data.PerPage, data.TotalCount)) }</span>
|
||||
of
|
||||
<span class="font-medium">{ fmt.Sprint(data.TotalCount) }</span>
|
||||
notifications
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<nav class="isolate inline-flex -space-x-px rounded-md shadow-sm" aria-label="Pagination">
|
||||
<!-- First page -->
|
||||
<a
|
||||
href={ templ.SafeURL("/notifications?page=1&perPage=" + strconv.Itoa(data.PerPage)) }
|
||||
hx-get={ "/notifications?page=1&perPage=" + strconv.Itoa(data.PerPage) }
|
||||
hx-target="body"
|
||||
hx-swap="innerHTML"
|
||||
class={ "relative inline-flex items-center justify-center rounded-l-lg border border-gray-300 bg-white px-3 py-2 text-sm font-medium text-gray-500 hover:bg-gray-50 focus:z-20 dark:bg-gray-800 dark:border-gray-600 dark:text-gray-400 dark:hover:bg-gray-700", templ.KV("opacity-50 pointer-events-none", data.CurrentPage == 1) }
|
||||
>
|
||||
<span class="sr-only">First</span>
|
||||
<i class="fas fa-angle-double-left text-xs"></i>
|
||||
</a>
|
||||
|
||||
<!-- Previous page -->
|
||||
<a
|
||||
href={ templ.SafeURL("/notifications?page=" + strconv.Itoa(maxInt(1, data.CurrentPage-1)) + "&perPage=" + strconv.Itoa(data.PerPage)) }
|
||||
hx-get={ "/notifications?page=" + strconv.Itoa(maxInt(1, data.CurrentPage-1)) + "&perPage=" + strconv.Itoa(data.PerPage) }
|
||||
hx-target="body"
|
||||
hx-swap="innerHTML"
|
||||
class={ "relative inline-flex items-center justify-center border border-gray-300 bg-white px-3 py-2 text-sm font-medium text-gray-500 hover:bg-gray-50 focus:z-20 dark:bg-gray-800 dark:border-gray-600 dark:text-gray-400 dark:hover:bg-gray-700", templ.KV("opacity-50 pointer-events-none", data.CurrentPage == 1) }
|
||||
>
|
||||
<span class="sr-only">Previous</span>
|
||||
<i class="fas fa-angle-left text-xs"></i>
|
||||
</a>
|
||||
|
||||
<!-- Page numbers -->
|
||||
@notificationPageNumbers(data.CurrentPage, data.TotalPages, data.PerPage)
|
||||
|
||||
<!-- Next page -->
|
||||
<a
|
||||
href={ templ.SafeURL("/notifications?page=" + strconv.Itoa(minInt(data.TotalPages, data.CurrentPage+1)) + "&perPage=" + strconv.Itoa(data.PerPage)) }
|
||||
hx-get={ "/notifications?page=" + strconv.Itoa(minInt(data.TotalPages, data.CurrentPage+1)) + "&perPage=" + strconv.Itoa(data.PerPage) }
|
||||
hx-target="body"
|
||||
hx-swap="innerHTML"
|
||||
class={ "relative inline-flex items-center justify-center border border-gray-300 bg-white px-3 py-2 text-sm font-medium text-gray-500 hover:bg-gray-50 focus:z-20 dark:bg-gray-800 dark:border-gray-600 dark:text-gray-400 dark:hover:bg-gray-700", templ.KV("opacity-50 pointer-events-none", data.CurrentPage == data.TotalPages) }
|
||||
>
|
||||
<span class="sr-only">Next</span>
|
||||
<i class="fas fa-angle-right text-xs"></i>
|
||||
</a>
|
||||
|
||||
<!-- Last page -->
|
||||
<a
|
||||
href={ templ.SafeURL("/notifications?page=" + strconv.Itoa(data.TotalPages) + "&perPage=" + strconv.Itoa(data.PerPage)) }
|
||||
hx-get={ "/notifications?page=" + strconv.Itoa(data.TotalPages) + "&perPage=" + strconv.Itoa(data.PerPage) }
|
||||
hx-target="body"
|
||||
hx-swap="innerHTML"
|
||||
class={ "relative inline-flex items-center justify-center rounded-r-lg border border-gray-300 bg-white px-3 py-2 text-sm font-medium text-gray-500 hover:bg-gray-50 focus:z-20 dark:bg-gray-800 dark:border-gray-600 dark:text-gray-400 dark:hover:bg-gray-700", templ.KV("opacity-50 pointer-events-none", data.CurrentPage == data.TotalPages) }
|
||||
>
|
||||
<span class="sr-only">Last</span>
|
||||
<i class="fas fa-angle-double-right text-xs"></i>
|
||||
</a>
|
||||
</nav>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
|
||||
<!-- Help Section -->
|
||||
<div class="bg-gray-50 dark:bg-gray-800 rounded-lg shadow-sm mt-8 p-4 border border-gray-200 dark:border-gray-700">
|
||||
<div class="flex items-start mb-2">
|
||||
<div class="flex items-center h-5">
|
||||
<i class="fas fa-info-circle w-4 h-4 text-blue-500 dark:text-blue-400 mr-2"></i>
|
||||
</div>
|
||||
<div class="ml-2 text-sm">
|
||||
<p class="text-gray-700 dark:text-gray-300">Notifications keep you updated on important system events and alerts.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex items-start mt-4">
|
||||
<div class="flex items-center h-5">
|
||||
<i class="fas fa-bell w-4 h-4 text-blue-500 dark:text-blue-400 mr-2"></i>
|
||||
</div>
|
||||
<div class="ml-2 text-sm">
|
||||
<p class="text-gray-700 dark:text-gray-300">Unread notifications are highlighted in blue. Mark them as read to clear the highlight.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
if len(data.Notifications) == 0 {
|
||||
<div class="text-center py-12">
|
||||
<div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-gray-100 dark:bg-gray-700 mb-4">
|
||||
<i class="fas fa-bell-slash text-2xl text-gray-500 dark:text-gray-400"></i>
|
||||
</div>
|
||||
<h3 class="text-lg font-medium text-gray-900 dark:text-white mb-1">No notifications</h3>
|
||||
<p class="text-gray-500 dark:text-gray-400">You don't have any notifications yet.</p>
|
||||
<div class="flex items-start mt-4">
|
||||
<div class="flex items-center h-5">
|
||||
<i class="fas fa-list-ol w-4 h-4 text-blue-500 dark:text-blue-400 mr-2"></i>
|
||||
</div>
|
||||
} else {
|
||||
<div class="divide-y divide-gray-200 dark:divide-gray-700">
|
||||
for _, notification := range data.Notifications {
|
||||
<div
|
||||
class={ "py-4 flex items-start", templ.KV("bg-blue-50 dark:bg-blue-900/20", !notification.IsRead) }
|
||||
id={ "notification-" + fmt.Sprintf("%d", notification.ID) }>
|
||||
<div class="flex-shrink-0 mr-4">
|
||||
<div class={ "w-12 h-12 rounded-full flex items-center justify-center", GetNotificationBgColor(notification.Type) }>
|
||||
<i class={ GetNotificationIcon(notification.Type) }></i>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex-1 min-w-0">
|
||||
<div class="flex justify-between items-start">
|
||||
<div>
|
||||
<h3 class="text-base font-medium text-gray-900 dark:text-white">{ notification.Title }</h3>
|
||||
<p class="text-sm text-gray-500 dark:text-gray-400 mt-1">{ notification.Message }</p>
|
||||
</div>
|
||||
<div class="flex items-center text-xs text-gray-500 dark:text-gray-400">
|
||||
<span>{ FormatNotificationTime(notification.CreatedAt) }</span>
|
||||
if !notification.IsRead {
|
||||
<button
|
||||
hx-post={ "/notifications/" + fmt.Sprintf("%d", notification.ID) + "/read" }
|
||||
hx-target={ "#notification-" + fmt.Sprintf("%d", notification.ID) }
|
||||
hx-swap="outerHTML"
|
||||
class="ml-4 text-primary-600 hover:text-primary-700 dark:text-primary-400 dark:hover:text-primary-300"
|
||||
>
|
||||
<i class="fas fa-check"></i>
|
||||
<span class="sr-only">Mark as read</span>
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-2">
|
||||
<a
|
||||
href={ templ.SafeURL(notification.Link) }
|
||||
class="inline-flex items-center text-sm font-medium text-primary-600 hover:text-primary-700 dark:text-primary-400 dark:hover:text-primary-300">
|
||||
<span>View details</span>
|
||||
<i class="fas fa-chevron-right ml-1 text-xs"></i>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
<div class="ml-2 text-sm">
|
||||
<p class="text-gray-700 dark:text-gray-300">Adjust how many notifications to display per page using the dropdown menu.</p>
|
||||
</div>
|
||||
|
||||
<!-- Pagination will go here if needed -->
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
// Helper function for pagination math
|
||||
func minInt(a, b int) int {
|
||||
if a < b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// Helper function for pagination math
|
||||
func maxInt(a, b int) int {
|
||||
if a > b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// Add the pageNumbers template for consistent pagination layout
|
||||
templ notificationPageNumbers(currentPage int, totalPages int, perPage int) {
|
||||
// Show at most 5 page numbers with the current page in the middle when possible
|
||||
for i := 1; i <= totalPages; i++ {
|
||||
if i == currentPage {
|
||||
<span aria-current="page" class="relative z-10 inline-flex items-center bg-blue-600 px-4 py-2 text-sm font-medium text-white focus:z-20 border border-blue-600 dark:bg-blue-600">
|
||||
{ fmt.Sprint(i) }
|
||||
</span>
|
||||
} else if i == 1 || i == totalPages || (i >= currentPage-2 && i <= currentPage+2) {
|
||||
<a
|
||||
href={ templ.SafeURL("/notifications?page=" + strconv.Itoa(i) + "&perPage=" + strconv.Itoa(perPage)) }
|
||||
hx-get={ "/notifications?page=" + strconv.Itoa(i) + "&perPage=" + strconv.Itoa(perPage) }
|
||||
hx-target="body"
|
||||
hx-swap="innerHTML"
|
||||
hx-indicator={ fmt.Sprintf("#page-indicator-%d", i) }
|
||||
class="relative inline-flex items-center px-4 py-2 text-sm font-medium text-gray-500 hover:bg-gray-50 focus:z-20 border border-gray-300 bg-white dark:bg-gray-800 dark:border-gray-600 dark:text-gray-400 dark:hover:bg-gray-700 relative"
|
||||
>
|
||||
{ fmt.Sprint(i) }
|
||||
<span id={ fmt.Sprintf("page-indicator-%d", i) } class="htmx-indicator absolute top-0 right-0 w-4 h-4 -mt-1 -mr-1">
|
||||
<i class="fas fa-spinner fa-spin text-xs"></i>
|
||||
</span>
|
||||
</a>
|
||||
} else if i == currentPage-3 || i == currentPage+3 {
|
||||
<span class="relative inline-flex items-center px-4 py-2 text-sm font-medium text-gray-700 border border-gray-300 bg-white dark:bg-gray-800 dark:border-gray-600 dark:text-gray-400">
|
||||
...
|
||||
</span>
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,11 @@ import (
|
||||
type NotificationsData struct {
|
||||
Notifications []db.UserNotification
|
||||
UnreadCount int64
|
||||
// Pagination fields
|
||||
CurrentPage int
|
||||
TotalPages int
|
||||
TotalCount int
|
||||
PerPage int
|
||||
}
|
||||
|
||||
// FormatNotificationTime formats a notification time in a user-friendly way
|
||||
|
||||
+170
-332
@@ -86,14 +86,165 @@ templ Settings(ctx context.Context, data SettingsData) {
|
||||
<div class="block p-4 rounded-lg bg-white dark:bg-gray-800" id="notifications" role="tabpanel" aria-labelledby="notifications-tab">
|
||||
<div class="flex justify-between items-center mb-4">
|
||||
<h2 class="text-xl font-semibold text-gray-900 dark:text-white">Notification Services</h2>
|
||||
<button
|
||||
type="button"
|
||||
class="px-4 py-2 text-sm font-medium text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 rounded-lg dark:bg-blue-600 dark:hover:bg-blue-700 focus:outline-none dark:focus:ring-blue-800"
|
||||
data-modal-target="add-notification-modal"
|
||||
data-modal-toggle="add-notification-modal"
|
||||
>
|
||||
<i class="fas fa-plus mr-2"></i>Add Service
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Add Notification Service Form -->
|
||||
<div class="mb-6 p-6 border border-gray-200 rounded-lg shadow-sm dark:border-gray-700">
|
||||
<h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4">
|
||||
Add Notification Service
|
||||
</h3>
|
||||
<form id="add-notification-form" hx-post="/admin/settings/notifications" hx-target="body">
|
||||
<div class="mb-6">
|
||||
<label for="notification_type" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Notification Type</label>
|
||||
<select id="notification_type" name="type" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500">
|
||||
<option value="">Select a type</option>
|
||||
<option value="webhook">Webhook</option>
|
||||
<option value="email" disabled>Email (Coming Soon)</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="mb-6 hidden common-fields">
|
||||
<label for="notification_name" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Name</label>
|
||||
<input type="text" id="notification_name" name="name" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" placeholder="My Notification Service" required />
|
||||
</div>
|
||||
<div class="mb-6 hidden common-fields">
|
||||
<label for="notification_description" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Description</label>
|
||||
<textarea id="notification_description" name="description" rows="3" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" placeholder="Description for this notification service"></textarea>
|
||||
</div>
|
||||
|
||||
<!-- Dynamic fields based on notification type -->
|
||||
<div id="email_fields" class="hidden notification-fields">
|
||||
<div class="mb-6">
|
||||
<label for="smtp_host" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">SMTP Host</label>
|
||||
<input type="text" id="smtp_host" name="smtp_host" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" placeholder="smtp.example.com" />
|
||||
</div>
|
||||
<div class="mb-6">
|
||||
<label for="smtp_port" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">SMTP Port</label>
|
||||
<input type="number" id="smtp_port" name="smtp_port" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" placeholder="587" />
|
||||
</div>
|
||||
<div class="mb-6">
|
||||
<label for="smtp_username" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">SMTP Username</label>
|
||||
<input type="text" id="smtp_username" name="smtp_username" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" placeholder="user@example.com" />
|
||||
</div>
|
||||
<div class="mb-6">
|
||||
<label for="smtp_password" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">SMTP Password</label>
|
||||
<input type="password" id="smtp_password" name="smtp_password" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" />
|
||||
</div>
|
||||
<div class="mb-6">
|
||||
<label for="from_email" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">From Email</label>
|
||||
<input type="email" id="from_email" name="from_email" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" placeholder="notifications@example.com" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="webhook_fields" class="hidden notification-fields">
|
||||
<div class="mb-6">
|
||||
<label for="webhook_url" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Webhook URL</label>
|
||||
<input type="url" id="webhook_url" name="webhook_url" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" placeholder="https://api.example.com/webhook" />
|
||||
</div>
|
||||
<div class="mb-6">
|
||||
<label for="method" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">HTTP Method</label>
|
||||
<select id="method" name="method" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500">
|
||||
<option value="POST">POST</option>
|
||||
<option value="PUT">PUT</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="mb-6">
|
||||
<label for="headers" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Headers (JSON)</label>
|
||||
<textarea id="headers" name="headers" rows="3" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" placeholder='{"Content-Type": "application/json", "Authorization": "Bearer token"}'></textarea>
|
||||
</div>
|
||||
<div class="mb-6">
|
||||
<label for="payload_template" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Payload Template (JSON)</label>
|
||||
<textarea id="payload_template" name="payload_template" rows="5" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" placeholder='{
|
||||
"event": "{{job.event}}",
|
||||
"job": {
|
||||
"id": "{{job.id}}",
|
||||
"name": "{{job.name}}",
|
||||
"status": "{{job.status}}",
|
||||
"message": "{{job.message}}",
|
||||
"started_at": "{{job.started_at}}",
|
||||
"completed_at": "{{job.completed_at}}",
|
||||
"duration_seconds": {{job.duration_seconds}},
|
||||
"config_id": "{{job.config_id}}",
|
||||
"config_name": "{{job.config_name}}",
|
||||
"transfer_bytes": {{job.transfer_bytes}},
|
||||
"file_count": {{job.file_count}}
|
||||
},
|
||||
"instance": {
|
||||
"id": "{{instance.id}}",
|
||||
"name": "{{instance.name}}",
|
||||
"version": "{{instance.version}}",
|
||||
"environment": "{{instance.environment}}"
|
||||
},
|
||||
"timestamp": "{{timestamp}}",
|
||||
"notification_id": "{{notification.id}}"
|
||||
}'></textarea>
|
||||
<p class="mt-1 text-sm text-gray-500 dark:text-gray-400">Use {`variable`} placeholders for dynamic values. Available variables: job.*, instance.*, timestamp, notification.*</p>
|
||||
</div>
|
||||
<div class="mb-6">
|
||||
<label class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Event Triggers</label>
|
||||
<div class="space-y-2">
|
||||
<div class="flex items-center">
|
||||
<input id="trigger_job_start" name="trigger_job_start" type="checkbox" class="w-4 h-4 border border-gray-300 rounded bg-gray-50 focus:ring-3 focus:ring-blue-300 dark:bg-gray-700 dark:border-gray-600 dark:focus:ring-blue-600 dark:ring-offset-gray-800" checked />
|
||||
<label for="trigger_job_start" class="ml-2 text-sm font-medium text-gray-900 dark:text-white">Job Start</label>
|
||||
</div>
|
||||
<div class="flex items-center">
|
||||
<input id="trigger_job_complete" name="trigger_job_complete" type="checkbox" class="w-4 h-4 border border-gray-300 rounded bg-gray-50 focus:ring-3 focus:ring-blue-300 dark:bg-gray-700 dark:border-gray-600 dark:focus:ring-blue-600 dark:ring-offset-gray-800" checked />
|
||||
<label for="trigger_job_complete" class="ml-2 text-sm font-medium text-gray-900 dark:text-white">Job Complete</label>
|
||||
</div>
|
||||
<div class="flex items-center">
|
||||
<input id="trigger_job_error" name="trigger_job_error" type="checkbox" class="w-4 h-4 border border-gray-300 rounded bg-gray-50 focus:ring-3 focus:ring-blue-300 dark:bg-gray-700 dark:border-gray-600 dark:focus:ring-blue-600 dark:ring-offset-gray-800" checked />
|
||||
<label for="trigger_job_error" class="ml-2 text-sm font-medium text-gray-900 dark:text-white">Job Error</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mb-6">
|
||||
<label for="secret_key" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Secret Key (for signature verification)</label>
|
||||
<input type="text" id="secret_key" name="secret_key" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" placeholder="Optional signature verification key" />
|
||||
<p class="mt-1 text-sm text-gray-500 dark:text-gray-400">If provided, all webhooks will include an X-GoMFT-Signature header</p>
|
||||
</div>
|
||||
<div class="mb-6">
|
||||
<label for="retry_policy" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Retry Policy</label>
|
||||
<select id="retry_policy" name="retry_policy" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500">
|
||||
<option value="none">No retries</option>
|
||||
<option value="simple" selected>Simple (3 retries)</option>
|
||||
<option value="exponential">Exponential backoff</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<!-- Test notification button -->
|
||||
<div class="mb-6 p-4 bg-gray-50 border border-gray-200 rounded-lg dark:bg-gray-700 dark:border-gray-600">
|
||||
<div class="flex items-center justify-between mb-2">
|
||||
<h4 class="text-base font-medium text-gray-900 dark:text-white">Test Configuration</h4>
|
||||
<button
|
||||
type="button"
|
||||
id="test-webhook-btn" hx-post="/admin/settings/notifications/test" hx-trigger="click" hx-target="#test-notification-result" hx-swap="outerHTML"
|
||||
class="px-3 py-2 text-xs font-medium text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 rounded-lg dark:bg-blue-600 dark:hover:bg-blue-700 focus:outline-none dark:focus:ring-blue-800"
|
||||
>
|
||||
<i class="fas fa-paper-plane mr-1"></i>
|
||||
Send Test Notification
|
||||
</button>
|
||||
</div>
|
||||
<p class="text-sm text-gray-500 dark:text-gray-400">
|
||||
Send a test notification to verify your configuration works correctly before saving.
|
||||
</p>
|
||||
<div id="test-notification-result" class="mt-3 hidden">
|
||||
<!-- Result will be shown here -->
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex items-start mb-6 hidden common-fields">
|
||||
<div class="flex items-center h-5">
|
||||
<input id="is_enabled" name="is_enabled" type="checkbox" class="w-4 h-4 border border-gray-300 rounded bg-gray-50 focus:ring-3 focus:ring-blue-300 dark:bg-gray-700 dark:border-gray-600 dark:focus:ring-blue-600 dark:ring-offset-gray-800" checked />
|
||||
</div>
|
||||
<div class="ml-3 text-sm">
|
||||
<label for="is_enabled" class="font-medium text-gray-900 dark:text-white">Enable this notification service</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="hidden common-fields">
|
||||
<button type="submit" class="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800">Add Service</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
if len(data.NotificationServices) == 0 {
|
||||
@@ -102,15 +253,7 @@ templ Settings(ctx context.Context, data SettingsData) {
|
||||
<i class="fas fa-bell text-2xl text-blue-600 dark:text-blue-400"></i>
|
||||
</div>
|
||||
<h3 class="mb-2 text-lg font-semibold text-gray-900 dark:text-white">No notification services configured</h3>
|
||||
<p class="text-gray-500 dark:text-gray-400 mb-4">Add your first notification service to start receiving alerts about jobs and system events.</p>
|
||||
<button
|
||||
type="button"
|
||||
class="px-4 py-2 text-sm font-medium text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 rounded-lg dark:bg-blue-600 dark:hover:bg-blue-700 focus:outline-none dark:focus:ring-blue-800"
|
||||
data-modal-target="add-notification-modal"
|
||||
data-modal-toggle="add-notification-modal"
|
||||
>
|
||||
<i class="fas fa-plus mr-2"></i>Add Notification Service
|
||||
</button>
|
||||
<p class="text-gray-500 dark:text-gray-400 mb-4">Use the form above to add your first notification service.</p>
|
||||
</div>
|
||||
} else {
|
||||
<div class="bg-white border border-gray-200 rounded-lg shadow-sm dark:border-gray-700 dark:bg-gray-800 overflow-hidden">
|
||||
@@ -240,148 +383,6 @@ templ Settings(ctx context.Context, data SettingsData) {
|
||||
</ul>
|
||||
</div>
|
||||
}
|
||||
|
||||
// if len(data.NotificationServices) == 0 {
|
||||
// <div class="text-center py-8">
|
||||
// <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-blue-100 dark:bg-blue-900 mb-4">
|
||||
// <i class="fas fa-bell text-2xl text-blue-600 dark:text-blue-400"></i>
|
||||
// </div>
|
||||
// <h3 class="mb-2 text-lg font-semibold text-gray-900 dark:text-white">No notification services configured</h3>
|
||||
// <p class="text-gray-500 dark:text-gray-400 mb-4">Add your first notification service to start receiving alerts about jobs and system events.</p>
|
||||
// <button
|
||||
// type="button"
|
||||
// class="px-4 py-2 text-sm font-medium text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 rounded-lg dark:bg-blue-600 dark:hover:bg-blue-700 focus:outline-none dark:focus:ring-blue-800"
|
||||
// data-modal-target="add-notification-modal"
|
||||
// data-modal-toggle="add-notification-modal"
|
||||
// >
|
||||
// <i class="fas fa-plus mr-2"></i>Add Notification Service
|
||||
// </button>
|
||||
// </div>
|
||||
// } else {
|
||||
// <div class="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
|
||||
// for _, service := range data.NotificationServices {
|
||||
// <div class="p-4 bg-white border border-gray-200 rounded-lg shadow-sm dark:bg-gray-800 dark:border-gray-700">
|
||||
// <div class="flex items-center justify-between mb-3">
|
||||
// <div class="flex items-center">
|
||||
// if service.Type == "email" {
|
||||
// <div class="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center text-blue-600 dark:bg-blue-900 dark:text-blue-400">
|
||||
// <i class="fas fa-envelope"></i>
|
||||
// </div>
|
||||
// } else if service.Type == "webhook" {
|
||||
// <div class="w-10 h-10 rounded-full bg-green-100 flex items-center justify-center text-green-600 dark:bg-green-900 dark:text-green-400">
|
||||
// <i class="fas fa-code"></i>
|
||||
// </div>
|
||||
// } else {
|
||||
// <div class="w-10 h-10 rounded-full bg-gray-100 flex items-center justify-center text-gray-600 dark:bg-gray-700 dark:text-gray-400">
|
||||
// <i class="fas fa-bell"></i>
|
||||
// </div>
|
||||
// }
|
||||
// <h3 class="ml-3 text-lg font-semibold text-gray-900 dark:text-white">{ service.Name }</h3>
|
||||
// </div>
|
||||
// <div class="flex">
|
||||
// <div class="inline-flex">
|
||||
// <button
|
||||
// type="button"
|
||||
// class="text-gray-500 bg-white focus:outline-none hover:bg-gray-100 focus:ring-4 focus:ring-gray-200 rounded-lg text-sm p-2 mr-1 dark:bg-gray-800 dark:text-gray-400 dark:hover:bg-gray-700 dark:hover:text-white dark:focus:ring-gray-700"
|
||||
// data-modal-target="edit-notification-modal"
|
||||
// data-modal-toggle="edit-notification-modal"
|
||||
// data-service-id={ fmt.Sprint(service.ID) }
|
||||
// >
|
||||
// <i class="fas fa-edit"></i>
|
||||
// </button>
|
||||
// <button
|
||||
// type="button"
|
||||
// class="text-red-500 bg-white focus:outline-none hover:bg-gray-100 focus:ring-4 focus:ring-gray-200 rounded-lg text-sm p-2 dark:bg-gray-800 dark:text-red-400 dark:hover:bg-gray-700 dark:hover:text-white dark:focus:ring-gray-700"
|
||||
// hx-delete={ "/admin/settings/notifications/" + fmt.Sprint(service.ID) }
|
||||
// hx-confirm="Are you sure you want to delete this notification service? This cannot be undone."
|
||||
// hx-target="body"
|
||||
// >
|
||||
// <i class="fas fa-trash-alt"></i>
|
||||
// </button>
|
||||
// </div>
|
||||
// </div>
|
||||
// </div>
|
||||
// <div class="flex items-center mb-2">
|
||||
// <span class={ "px-2 py-1 text-xs font-medium rounded-full",
|
||||
// templ.KV("bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-300", service.IsEnabled),
|
||||
// templ.KV("bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300", !service.IsEnabled) }>
|
||||
// if service.IsEnabled {
|
||||
// Active
|
||||
// } else {
|
||||
// Disabled
|
||||
// }
|
||||
// </span>
|
||||
// <span class="ml-2 px-2 py-1 text-xs font-medium bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-300 rounded-full">
|
||||
// { service.Type }
|
||||
// </span>
|
||||
// if len(service.EventTriggers) > 0 && service.Type == "webhook" {
|
||||
// <span class="ml-2 px-2 py-1 text-xs font-medium bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-300 rounded-full">
|
||||
// { fmt.Sprintf("%d triggers", len(service.EventTriggers)) }
|
||||
// </span>
|
||||
// }
|
||||
// if service.SuccessCount > 0 || service.FailureCount > 0 {
|
||||
// <span class="ml-2 px-2 py-1 text-xs font-medium bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300 rounded-full">
|
||||
// { fmt.Sprintf("%d/%d", service.SuccessCount, service.SuccessCount + service.FailureCount) }
|
||||
// </span>
|
||||
// }
|
||||
// </div>
|
||||
// <p class="text-sm text-gray-500 dark:text-gray-400 mb-2">{ service.Description }</p>
|
||||
// if service.Type == "webhook" {
|
||||
// <div class="mt-3 pt-3 border-t border-gray-200 dark:border-gray-700">
|
||||
// <h4 class="text-sm font-medium text-gray-900 dark:text-white mb-2">Webhook Configuration</h4>
|
||||
// <div class="grid grid-cols-2 gap-2">
|
||||
// <div class="text-xs">
|
||||
// <span class="text-gray-500 dark:text-gray-400">Events:</span>
|
||||
// <span class="ml-1 text-gray-900 dark:text-gray-300">
|
||||
// if len(service.EventTriggers) == 0 {
|
||||
// None
|
||||
// } else {
|
||||
// for i, trigger := range service.EventTriggers {
|
||||
// if i > 0 {
|
||||
// <span>, </span>
|
||||
// }
|
||||
// { trigger }
|
||||
// }
|
||||
// }
|
||||
// </span>
|
||||
// </div>
|
||||
// <div class="text-xs">
|
||||
// <span class="text-gray-500 dark:text-gray-400">Retry:</span>
|
||||
// <span class="ml-1 text-gray-900 dark:text-gray-300">
|
||||
// if service.RetryPolicy == "" {
|
||||
// Default
|
||||
// } else {
|
||||
// { service.RetryPolicy }
|
||||
// }
|
||||
// </span>
|
||||
// </div>
|
||||
// <div class="text-xs">
|
||||
// <span class="text-gray-500 dark:text-gray-400">Secret Key:</span>
|
||||
// <span class="ml-1 text-gray-900 dark:text-gray-300">
|
||||
// if service.SecretKey == "" {
|
||||
// None
|
||||
// } else {
|
||||
// <i class="fas fa-check-circle text-green-500"></i> Configured
|
||||
// }
|
||||
// </span>
|
||||
// </div>
|
||||
// <div class="text-xs">
|
||||
// <span class="text-gray-500 dark:text-gray-400">Custom Payload:</span>
|
||||
// <span class="ml-1 text-gray-900 dark:text-gray-300">
|
||||
// if service.PayloadTemplate == "" {
|
||||
// Default
|
||||
// } else {
|
||||
// <i class="fas fa-check-circle text-green-500"></i> Custom
|
||||
// }
|
||||
// </span>
|
||||
// </div>
|
||||
// </div>
|
||||
// </div>
|
||||
// }
|
||||
// </div>
|
||||
// }
|
||||
// </div>
|
||||
// }
|
||||
</div>
|
||||
|
||||
<!-- General Tab -->
|
||||
@@ -434,177 +435,6 @@ templ Settings(ctx context.Context, data SettingsData) {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Add Notification Service Modal -->
|
||||
<div id="add-notification-modal" tabindex="-1" aria-hidden="true" class="fixed top-0 left-0 right-0 z-50 hidden w-full p-4 overflow-x-hidden overflow-y-auto md:inset-0 h-[calc(100%-1rem)] max-h-full">
|
||||
<div class="relative w-full max-w-2xl max-h-full">
|
||||
<div class="relative bg-white rounded-lg shadow dark:bg-gray-700">
|
||||
<div class="flex items-start justify-between p-4 border-b rounded-t dark:border-gray-600">
|
||||
<h3 class="text-xl font-semibold text-gray-900 dark:text-white">
|
||||
Add Notification Service
|
||||
</h3>
|
||||
<button type="button" class="text-gray-400 bg-transparent hover:bg-gray-200 hover:text-gray-900 rounded-lg text-sm w-8 h-8 ml-auto inline-flex justify-center items-center dark:hover:bg-gray-600 dark:hover:text-white" data-modal-hide="add-notification-modal">
|
||||
<i class="fas fa-times"></i>
|
||||
<span class="sr-only">Close modal</span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="p-6 space-y-6">
|
||||
<form id="add-notification-form" hx-post="/admin/settings/notifications" hx-target="body">
|
||||
<div class="mb-6">
|
||||
<label for="notification_type" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Notification Type</label>
|
||||
<select id="notification_type" name="type" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500">
|
||||
<option value="">Select a type</option>
|
||||
<option value="email">Email</option>
|
||||
<option value="webhook">Webhook</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="mb-6">
|
||||
<label for="notification_name" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Name</label>
|
||||
<input type="text" id="notification_name" name="name" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" placeholder="My Email Notification" required />
|
||||
</div>
|
||||
<div class="mb-6">
|
||||
<label for="notification_description" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Description</label>
|
||||
<textarea id="notification_description" name="description" rows="3" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" placeholder="Description for this notification service"></textarea>
|
||||
</div>
|
||||
|
||||
<!-- Dynamic fields based on notification type -->
|
||||
<div id="email_fields" class="hidden notification-fields">
|
||||
<div class="mb-6">
|
||||
<label for="smtp_host" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">SMTP Host</label>
|
||||
<input type="text" id="smtp_host" name="smtp_host" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" placeholder="smtp.example.com" />
|
||||
</div>
|
||||
<div class="mb-6">
|
||||
<label for="smtp_port" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">SMTP Port</label>
|
||||
<input type="number" id="smtp_port" name="smtp_port" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" placeholder="587" />
|
||||
</div>
|
||||
<div class="mb-6">
|
||||
<label for="smtp_username" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">SMTP Username</label>
|
||||
<input type="text" id="smtp_username" name="smtp_username" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" placeholder="user@example.com" />
|
||||
</div>
|
||||
<div class="mb-6">
|
||||
<label for="smtp_password" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">SMTP Password</label>
|
||||
<input type="password" id="smtp_password" name="smtp_password" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" />
|
||||
</div>
|
||||
<div class="mb-6">
|
||||
<label for="from_email" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">From Email</label>
|
||||
<input type="email" id="from_email" name="from_email" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" placeholder="notifications@example.com" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="webhook_fields" class="hidden notification-fields">
|
||||
<div class="mb-6">
|
||||
<label for="webhook_url" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Webhook URL</label>
|
||||
<input type="url" id="webhook_url" name="webhook_url" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" placeholder="https://api.example.com/webhook" />
|
||||
</div>
|
||||
<div class="mb-6">
|
||||
<label for="method" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">HTTP Method</label>
|
||||
<select id="method" name="method" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500">
|
||||
<option value="POST">POST</option>
|
||||
<option value="PUT">PUT</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="mb-6">
|
||||
<label for="headers" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Headers (JSON)</label>
|
||||
<textarea id="headers" name="headers" rows="3" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" placeholder='{"Content-Type": "application/json", "Authorization": "Bearer token"}'></textarea>
|
||||
</div>
|
||||
<div class="mb-6">
|
||||
<label for="payload_template" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Payload Template (JSON)</label>
|
||||
<textarea id="payload_template" name="payload_template" rows="5" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" placeholder='{
|
||||
"event": "{{job.event}}",
|
||||
"job": {
|
||||
"id": "{{job.id}}",
|
||||
"name": "{{job.name}}",
|
||||
"status": "{{job.status}}",
|
||||
"message": "{{job.message}}",
|
||||
"started_at": "{{job.started_at}}",
|
||||
"completed_at": "{{job.completed_at}}",
|
||||
"duration_seconds": {{job.duration_seconds}},
|
||||
"config_id": "{{job.config_id}}",
|
||||
"config_name": "{{job.config_name}}",
|
||||
"transfer_bytes": {{job.transfer_bytes}},
|
||||
"file_count": {{job.file_count}}
|
||||
},
|
||||
"instance": {
|
||||
"id": "{{instance.id}}",
|
||||
"name": "{{instance.name}}",
|
||||
"version": "{{instance.version}}",
|
||||
"environment": "{{instance.environment}}"
|
||||
},
|
||||
"timestamp": "{{timestamp}}",
|
||||
"notification_id": "{{notification.id}}"
|
||||
}'></textarea>
|
||||
<p class="mt-1 text-sm text-gray-500 dark:text-gray-400">Use {`variable`} placeholders for dynamic values. Available variables: job.*, instance.*, timestamp, notification.*</p>
|
||||
</div>
|
||||
<div class="mb-6">
|
||||
<label class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Event Triggers</label>
|
||||
<div class="space-y-2">
|
||||
<div class="flex items-center">
|
||||
<input id="trigger_job_start" name="trigger_job_start" type="checkbox" class="w-4 h-4 border border-gray-300 rounded bg-gray-50 focus:ring-3 focus:ring-blue-300 dark:bg-gray-700 dark:border-gray-600 dark:focus:ring-blue-600 dark:ring-offset-gray-800" checked />
|
||||
<label for="trigger_job_start" class="ml-2 text-sm font-medium text-gray-900 dark:text-white">Job Start</label>
|
||||
</div>
|
||||
<div class="flex items-center">
|
||||
<input id="trigger_job_complete" name="trigger_job_complete" type="checkbox" class="w-4 h-4 border border-gray-300 rounded bg-gray-50 focus:ring-3 focus:ring-blue-300 dark:bg-gray-700 dark:border-gray-600 dark:focus:ring-blue-600 dark:ring-offset-gray-800" checked />
|
||||
<label for="trigger_job_complete" class="ml-2 text-sm font-medium text-gray-900 dark:text-white">Job Complete</label>
|
||||
</div>
|
||||
<div class="flex items-center">
|
||||
<input id="trigger_job_error" name="trigger_job_error" type="checkbox" class="w-4 h-4 border border-gray-300 rounded bg-gray-50 focus:ring-3 focus:ring-blue-300 dark:bg-gray-700 dark:border-gray-600 dark:focus:ring-blue-600 dark:ring-offset-gray-800" checked />
|
||||
<label for="trigger_job_error" class="ml-2 text-sm font-medium text-gray-900 dark:text-white">Job Error</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mb-6">
|
||||
<label for="secret_key" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Secret Key (for signature verification)</label>
|
||||
<input type="text" id="secret_key" name="secret_key" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" placeholder="Optional signature verification key" />
|
||||
<p class="mt-1 text-sm text-gray-500 dark:text-gray-400">If provided, all webhooks will include an X-GoMFT-Signature header</p>
|
||||
</div>
|
||||
<div class="mb-6">
|
||||
<label for="retry_policy" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Retry Policy</label>
|
||||
<select id="retry_policy" name="retry_policy" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500">
|
||||
<option value="none">No retries</option>
|
||||
<option value="simple" selected>Simple (3 retries)</option>
|
||||
<option value="exponential">Exponential backoff</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<!-- Test notification button -->
|
||||
<div class="mb-6 p-4 bg-gray-50 border border-gray-200 rounded-lg dark:bg-gray-700 dark:border-gray-600">
|
||||
<div class="flex items-center justify-between mb-2">
|
||||
<h4 class="text-base font-medium text-gray-900 dark:text-white">Test Configuration</h4>
|
||||
<button
|
||||
type="button"
|
||||
id="test-webhook-btn" hx-post="/admin/settings/notifications/test" hx-trigger="click" hx-target="#test-notification-result" hx-swap="outerHTML"
|
||||
class="px-3 py-2 text-xs font-medium text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 rounded-lg dark:bg-blue-600 dark:hover:bg-blue-700 focus:outline-none dark:focus:ring-blue-800"
|
||||
>
|
||||
<i class="fas fa-paper-plane mr-1"></i>
|
||||
Send Test Notification
|
||||
</button>
|
||||
</div>
|
||||
<p class="text-sm text-gray-500 dark:text-gray-400">
|
||||
Send a test notification to verify your configuration works correctly before saving.
|
||||
</p>
|
||||
<div id="test-notification-result" class="mt-3 hidden">
|
||||
<!-- Result will be shown here -->
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex items-start mb-6">
|
||||
<div class="flex items-center h-5">
|
||||
<input id="is_enabled" name="is_enabled" type="checkbox" class="w-4 h-4 border border-gray-300 rounded bg-gray-50 focus:ring-3 focus:ring-blue-300 dark:bg-gray-700 dark:border-gray-600 dark:focus:ring-blue-600 dark:ring-offset-gray-800" checked />
|
||||
</div>
|
||||
<div class="ml-3 text-sm">
|
||||
<label for="is_enabled" class="font-medium text-gray-900 dark:text-white">Enable this notification service</label>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
<div class="flex items-center justify-end p-6 space-x-2 border-t border-gray-200 rounded-b dark:border-gray-600">
|
||||
<button data-modal-hide="add-notification-modal" type="button" class="text-gray-500 bg-white hover:bg-gray-100 focus:ring-4 focus:outline-none focus:ring-gray-200 rounded-lg border border-gray-200 text-sm font-medium px-5 py-2.5 hover:text-gray-900 focus:z-10 dark:bg-gray-700 dark:text-gray-300 dark:border-gray-500 dark:hover:text-white dark:hover:bg-gray-600 dark:focus:ring-gray-600">Cancel</button>
|
||||
<button form="add-notification-form" type="submit" class="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800">Add Service</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@toggleNotificationFields()
|
||||
}
|
||||
@@ -613,19 +443,27 @@ script toggleNotificationFields() {
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
const typeSelector = document.getElementById('notification_type');
|
||||
const allFields = document.querySelectorAll('.notification-fields');
|
||||
const commonFields = document.querySelectorAll('.common-fields');
|
||||
|
||||
typeSelector.addEventListener('change', function() {
|
||||
// Hide all fields first
|
||||
allFields.forEach(field => field.classList.add('hidden'));
|
||||
|
||||
// Show the selected type's fields
|
||||
// Show/hide common fields based on selection
|
||||
const selectedType = this.value;
|
||||
if (selectedType) {
|
||||
// Show common fields (name, description)
|
||||
commonFields.forEach(field => field.classList.remove('hidden'));
|
||||
|
||||
// Show the selected type's specific fields
|
||||
const fieldsToShow = document.getElementById(`${selectedType}_fields`);
|
||||
if (fieldsToShow) {
|
||||
fieldsToShow.classList.remove('hidden');
|
||||
}
|
||||
} else {
|
||||
// Hide common fields if no type selected
|
||||
commonFields.forEach(field => field.classList.add('hidden'));
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,6 +38,20 @@ func (db *DB) GetUserNotifications(userID uint, limit int) ([]UserNotification,
|
||||
return notifications, result.Error
|
||||
}
|
||||
|
||||
// GetUserNotificationCount returns the total count of notifications for a user
|
||||
func (db *DB) GetUserNotificationCount(userID uint) (int64, error) {
|
||||
var count int64
|
||||
result := db.Model(&UserNotification{}).Where("user_id = ?", userID).Count(&count)
|
||||
return count, result.Error
|
||||
}
|
||||
|
||||
// GetPaginatedUserNotifications returns paginated notifications for a user
|
||||
func (db *DB) GetPaginatedUserNotifications(userID uint, offset, limit int) ([]UserNotification, error) {
|
||||
var notifications []UserNotification
|
||||
result := db.Where("user_id = ?", userID).Order("created_at DESC").Offset(offset).Limit(limit).Find(¬ifications)
|
||||
return notifications, result.Error
|
||||
}
|
||||
|
||||
// GetUnreadNotificationCount returns the count of unread notifications for a user
|
||||
func (db *DB) GetUnreadNotificationCount(userID uint) (int64, error) {
|
||||
var count int64
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -74,30 +75,25 @@ func (h *Handlers) GetBackupFiles() ([]components.BackupFile, error) {
|
||||
|
||||
// HandleBackupDatabase creates a backup of the current database
|
||||
func (h *Handlers) HandleBackupDatabase(c *gin.Context) {
|
||||
// Close the existing database connection to ensure a clean backup
|
||||
h.DB.Close()
|
||||
// Instead of closing the database connection, get a new connection to the database
|
||||
// This will use the underlying connection pool - just checking connection availability
|
||||
_, err := h.DB.DB.DB()
|
||||
if err != nil {
|
||||
h.HandleError(c, http.StatusInternalServerError, "Database Error", "Failed to access database", err)
|
||||
return
|
||||
}
|
||||
|
||||
// Generate a backup filename with timestamp
|
||||
timestamp := time.Now().Format("2006-01-02-150405")
|
||||
backupName := fmt.Sprintf("backup-%s.db", timestamp)
|
||||
backupPath := filepath.Join(h.BackupDir, backupName)
|
||||
|
||||
// Copy the database file
|
||||
err := copyFile(h.DBPath, backupPath)
|
||||
if err != nil {
|
||||
// Reopen DB and preserve auth
|
||||
if !h.reopenDatabaseWithAuth(c, "after+backup+attempt") {
|
||||
return
|
||||
}
|
||||
// Copy the database file without closing the main connection
|
||||
if err := backupDatabaseFile(h.DBPath, backupPath); err != nil {
|
||||
c.Redirect(http.StatusSeeOther, "/admin/database?error=Failed+to+create+backup&details="+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// Reopen the database connection and preserve auth
|
||||
if !h.reopenDatabaseWithAuth(c, "after+backup") {
|
||||
return
|
||||
}
|
||||
|
||||
c.Redirect(http.StatusSeeOther, "/admin/database?status=Backup+created+successfully")
|
||||
}
|
||||
|
||||
@@ -130,36 +126,74 @@ func (h *Handlers) HandleRestoreDatabase(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// Close the database connection
|
||||
h.DB.Close()
|
||||
|
||||
// Create a backup of the current database before restoring
|
||||
currentBackupName := fmt.Sprintf("pre-restore-%s.db", time.Now().Format("2006-01-02-150405"))
|
||||
currentBackupPath := filepath.Join(h.BackupDir, currentBackupName)
|
||||
if err := copyFile(h.DBPath, currentBackupPath); err != nil {
|
||||
// Reopen DB and preserve auth
|
||||
if !h.reopenDatabaseWithAuth(c, "after+pre-restore+backup+attempt") {
|
||||
return
|
||||
}
|
||||
|
||||
if err := backupDatabaseFile(h.DBPath, currentBackupPath); err != nil {
|
||||
c.Redirect(http.StatusSeeOther, "/admin/database?error=Failed+to+backup+current+database&details="+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// Store auth info from context
|
||||
userID, userExists := c.Get("userID")
|
||||
email, emailExists := c.Get("email")
|
||||
username, usernameExists := c.Get("username")
|
||||
isAdmin, adminExists := c.Get("isAdmin")
|
||||
|
||||
// Close current connections before restore
|
||||
sqlDB, err := h.DB.DB.DB()
|
||||
if err != nil {
|
||||
c.Redirect(http.StatusSeeOther, "/admin/database?error=Failed+to+access+database&details="+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// Close the current connection pool
|
||||
if err := sqlDB.Close(); err != nil {
|
||||
fmt.Printf("Warning: Error closing database connection: %v\n", err)
|
||||
}
|
||||
|
||||
// Wait for connections to fully close
|
||||
time.Sleep(1 * time.Second)
|
||||
|
||||
// Restore the database by copying the backup file
|
||||
if err := copyFile(backupPath, h.DBPath); err != nil {
|
||||
// Reopen DB and preserve auth
|
||||
if !h.reopenDatabaseWithAuth(c, "after+restore+attempt") {
|
||||
// Need to reopen the database
|
||||
newDB, reopenErr := db.ReopenWithoutMigrations(h.DBPath)
|
||||
if reopenErr != nil {
|
||||
c.Redirect(http.StatusSeeOther, "/admin/database?error=Critical+error:+Database+restore+failed+and+reconnection+failed&details="+reopenErr.Error())
|
||||
return
|
||||
}
|
||||
h.DB = newDB
|
||||
|
||||
c.Redirect(http.StatusSeeOther, "/admin/database?error=Failed+to+restore+database&details="+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// Reopen the database connection with the restored database and preserve auth
|
||||
if !h.reopenDatabaseWithAuth(c, "after+restore") {
|
||||
// Reopen the database connection with the restored database
|
||||
newDB, err := db.ReopenWithoutMigrations(h.DBPath)
|
||||
if err != nil {
|
||||
c.Redirect(http.StatusSeeOther, "/admin/database?error=Failed+to+reconnect+to+database+after+restore&details="+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// Update the handler's database connection
|
||||
h.DB = newDB
|
||||
|
||||
// Restore auth context
|
||||
if userExists {
|
||||
c.Set("userID", userID)
|
||||
}
|
||||
if emailExists {
|
||||
c.Set("email", email)
|
||||
}
|
||||
if usernameExists {
|
||||
c.Set("username", username)
|
||||
}
|
||||
if adminExists {
|
||||
c.Set("isAdmin", isAdmin)
|
||||
}
|
||||
|
||||
// Clean up temp file if it was an upload
|
||||
if strings.HasPrefix(filename, "temp-") {
|
||||
os.Remove(backupPath)
|
||||
@@ -255,23 +289,12 @@ func (h *Handlers) HandleVacuumDatabase(c *gin.Context) {
|
||||
backupName := fmt.Sprintf("pre-vacuum-%s.db", timestamp)
|
||||
backupPath := filepath.Join(h.BackupDir, backupName)
|
||||
|
||||
// Close DB connection to make a clean backup
|
||||
h.DB.Close()
|
||||
|
||||
if err := copyFile(h.DBPath, backupPath); err != nil {
|
||||
// Reopen DB and preserve auth
|
||||
if !h.reopenDatabaseWithAuth(c, "after+backup+attempt") {
|
||||
return
|
||||
}
|
||||
// Make a backup without closing the DB
|
||||
if err := backupDatabaseFile(h.DBPath, backupPath); err != nil {
|
||||
c.Redirect(http.StatusSeeOther, "/admin/database?error=Failed+to+backup+before+vacuum&details="+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// Reopen DB and preserve auth
|
||||
if !h.reopenDatabaseWithAuth(c, "after+backup") {
|
||||
return
|
||||
}
|
||||
|
||||
// Run vacuum command
|
||||
result := h.DB.Exec("VACUUM")
|
||||
if result.Error != nil {
|
||||
@@ -282,80 +305,6 @@ func (h *Handlers) HandleVacuumDatabase(c *gin.Context) {
|
||||
c.Redirect(http.StatusSeeOther, "/admin/database?status=Database+optimized+successfully")
|
||||
}
|
||||
|
||||
// reopenDatabaseWithAuth safely closes and reopens the database while preserving user authentication
|
||||
func (h *Handlers) reopenDatabaseWithAuth(c *gin.Context, reason string) (success bool) {
|
||||
// Store auth info from context
|
||||
userID, userExists := c.Get("userID")
|
||||
email, emailExists := c.Get("email")
|
||||
username, usernameExists := c.Get("username")
|
||||
isAdmin, adminExists := c.Get("isAdmin")
|
||||
|
||||
// First close the existing connection if it exists
|
||||
if h.DB != nil {
|
||||
h.DB.Close()
|
||||
// Set to nil to avoid using a closed connection
|
||||
h.DB = nil
|
||||
}
|
||||
|
||||
// Make sure we wait a moment to ensure the file is released
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
|
||||
// Reopen database WITHOUT running migrations
|
||||
newDB, err := db.ReopenWithoutMigrations(h.DBPath)
|
||||
if err != nil {
|
||||
c.Redirect(http.StatusSeeOther, fmt.Sprintf("/admin/database?error=Failed+to+reconnect+to+database+%s&details=%s", reason, err.Error()))
|
||||
return false
|
||||
}
|
||||
|
||||
// Verify the connection works by executing a simple query
|
||||
var count int64
|
||||
if err := newDB.Raw("SELECT 1").Scan(&count).Error; err != nil {
|
||||
c.Redirect(http.StatusSeeOther, fmt.Sprintf("/admin/database?error=Database+connection+test+failed+%s&details=%s", reason, err.Error()))
|
||||
return false
|
||||
}
|
||||
|
||||
// Only after validation, assign the new database connection
|
||||
h.DB = newDB
|
||||
|
||||
// Restore auth context
|
||||
if userExists {
|
||||
c.Set("userID", userID)
|
||||
}
|
||||
if emailExists {
|
||||
c.Set("email", email)
|
||||
}
|
||||
if usernameExists {
|
||||
c.Set("username", username)
|
||||
}
|
||||
if adminExists {
|
||||
c.Set("isAdmin", isAdmin)
|
||||
}
|
||||
|
||||
// If we had a user, attempt to reload their info
|
||||
if userExists && h.DB != nil {
|
||||
var user db.User
|
||||
userIDValue, ok := userID.(uint)
|
||||
if !ok {
|
||||
// Try to convert from float64 (the JWT parser returns numbers as float64)
|
||||
if userIDFloat, ok := userID.(float64); ok {
|
||||
userIDValue = uint(userIDFloat)
|
||||
}
|
||||
}
|
||||
|
||||
if userIDValue > 0 {
|
||||
result := h.DB.Preload("Roles").First(&user, userIDValue)
|
||||
if result.Error == nil {
|
||||
c.Set("user", &user)
|
||||
} else {
|
||||
// Log the error but continue - we still have basic user info from JWT
|
||||
fmt.Printf("Error loading user roles after DB reconnect: %v\n", result.Error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// HandleClearJobHistory clears job history records
|
||||
func (h *Handlers) HandleClearJobHistory(c *gin.Context) {
|
||||
// Check if DB is nil
|
||||
@@ -376,23 +325,12 @@ func (h *Handlers) HandleClearJobHistory(c *gin.Context) {
|
||||
backupName := fmt.Sprintf("pre-clear-history-%s.db", timestamp)
|
||||
backupPath := filepath.Join(h.BackupDir, backupName)
|
||||
|
||||
// Close DB connection to make a clean backup
|
||||
h.DB.Close()
|
||||
|
||||
if err := copyFile(h.DBPath, backupPath); err != nil {
|
||||
// Reopen DB and preserve auth
|
||||
if !h.reopenDatabaseWithAuth(c, "after+backup+attempt") {
|
||||
return
|
||||
}
|
||||
// Make a backup without closing the DB
|
||||
if err := backupDatabaseFile(h.DBPath, backupPath); err != nil {
|
||||
c.Redirect(http.StatusSeeOther, "/admin/database?error=Failed+to+backup+before+clearing+history&details="+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// Reopen DB and preserve auth
|
||||
if !h.reopenDatabaseWithAuth(c, "after+backup") {
|
||||
return
|
||||
}
|
||||
|
||||
// Make sure we have a valid connection before executing the DELETE
|
||||
var testCount int64
|
||||
if err := h.DB.Raw("SELECT COUNT(*) FROM job_histories").Scan(&testCount).Error; err != nil {
|
||||
@@ -430,6 +368,159 @@ func (h *Handlers) HandleClearJobHistory(c *gin.Context) {
|
||||
c.Redirect(http.StatusSeeOther, "/admin/database?status=Job+history+cleared+successfully+"+logMessage)
|
||||
}
|
||||
|
||||
// backupDatabaseFile creates a copy of the database file without closing the connection
|
||||
func backupDatabaseFile(srcPath, destPath string) error {
|
||||
// Copy the database using the WAL mode safe approach
|
||||
srcFile, err := os.Open(srcPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open source database: %v", err)
|
||||
}
|
||||
defer srcFile.Close()
|
||||
|
||||
destFile, err := os.Create(destPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create destination file: %v", err)
|
||||
}
|
||||
defer destFile.Close()
|
||||
|
||||
_, err = io.Copy(destFile, srcFile)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to copy database: %v", err)
|
||||
}
|
||||
|
||||
// Also copy the WAL files if they exist
|
||||
walPath := srcPath + "-wal"
|
||||
if _, err := os.Stat(walPath); err == nil {
|
||||
if err := copyFile(walPath, destPath+"-wal"); err != nil {
|
||||
fmt.Printf("Warning: failed to copy WAL file: %v\n", err)
|
||||
}
|
||||
}
|
||||
|
||||
shmPath := srcPath + "-shm"
|
||||
if _, err := os.Stat(shmPath); err == nil {
|
||||
if err := copyFile(shmPath, destPath+"-shm"); err != nil {
|
||||
fmt.Printf("Warning: failed to copy SHM file: %v\n", err)
|
||||
}
|
||||
}
|
||||
|
||||
return destFile.Sync()
|
||||
}
|
||||
|
||||
// reopenDatabaseWithAuth safely closes and reopens the database while preserving user authentication
|
||||
// This is now only used as a fallback when necessary, not as the primary approach
|
||||
func (h *Handlers) reopenDatabaseWithAuth(c *gin.Context, reason string) (success bool) {
|
||||
// Store auth info from context
|
||||
userID, userExists := c.Get("userID")
|
||||
email, emailExists := c.Get("email")
|
||||
username, usernameExists := c.Get("username")
|
||||
isAdmin, adminExists := c.Get("isAdmin")
|
||||
|
||||
// First close the existing connection if it exists
|
||||
if h.DB != nil {
|
||||
// Close the database connection properly
|
||||
if err := h.DB.Close(); err != nil {
|
||||
fmt.Printf("Warning: Error closing database connection: %v\n", err)
|
||||
}
|
||||
|
||||
// Set to nil to avoid using a closed connection
|
||||
h.DB = nil
|
||||
}
|
||||
|
||||
// Make sure we wait longer to ensure the file is completely released
|
||||
// Different OSes might need different times for file handles to be released
|
||||
time.Sleep(1000 * time.Millisecond)
|
||||
|
||||
// Define max retry attempts and backoff times
|
||||
maxRetries := 5
|
||||
var err error
|
||||
|
||||
// Attempt to reopen the database with retries
|
||||
for attempt := 0; attempt < maxRetries; attempt++ {
|
||||
// Reopen database WITHOUT running migrations
|
||||
h.DB, err = db.ReopenWithoutMigrations(h.DBPath)
|
||||
if err == nil {
|
||||
// Verify the connection works by executing a simple query
|
||||
var count int64
|
||||
if verifyErr := h.DB.Raw("SELECT 1").Scan(&count).Error; verifyErr == nil {
|
||||
break // Successfully reopened and verified
|
||||
} else {
|
||||
// Close this failed connection
|
||||
h.DB.Close()
|
||||
h.DB = nil
|
||||
err = verifyErr
|
||||
fmt.Printf("Database verification failed on attempt %d: %v\n", attempt+1, verifyErr)
|
||||
}
|
||||
} else {
|
||||
fmt.Printf("Database reopen failed on attempt %d: %v\n", attempt+1, err)
|
||||
}
|
||||
|
||||
// Wait before retrying, with increasing backoff
|
||||
waitTime := time.Duration(1000*(attempt+1)) * time.Millisecond
|
||||
fmt.Printf("Waiting %v before retry #%d\n", waitTime, attempt+1)
|
||||
time.Sleep(waitTime)
|
||||
}
|
||||
|
||||
// If all retries failed, redirect with error
|
||||
if err != nil {
|
||||
c.Redirect(http.StatusSeeOther, fmt.Sprintf("/admin/database?error=Failed+to+reconnect+to+database+%s&details=%s", reason, err.Error()))
|
||||
return false
|
||||
}
|
||||
|
||||
// Restore auth context
|
||||
if userExists {
|
||||
c.Set("userID", userID)
|
||||
}
|
||||
if emailExists {
|
||||
c.Set("email", email)
|
||||
}
|
||||
if usernameExists {
|
||||
c.Set("username", username)
|
||||
}
|
||||
if adminExists {
|
||||
c.Set("isAdmin", isAdmin)
|
||||
}
|
||||
|
||||
// If we had a user, attempt to reload their info
|
||||
if userExists && h.DB != nil {
|
||||
var user db.User
|
||||
userIDValue, ok := userID.(uint)
|
||||
if !ok {
|
||||
// Try to convert from float64 (the JWT parser returns numbers as float64)
|
||||
if userIDFloat, ok := userID.(float64); ok {
|
||||
userIDValue = uint(userIDFloat)
|
||||
} else {
|
||||
// Try string conversion as a last resort
|
||||
if userIDStr, ok := userID.(string); ok {
|
||||
if parsed, err := strconv.ParseUint(userIDStr, 10, 32); err == nil {
|
||||
userIDValue = uint(parsed)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if userIDValue > 0 {
|
||||
// Try to load the user with their roles
|
||||
result := h.DB.Preload("Roles").First(&user, userIDValue)
|
||||
if result.Error == nil {
|
||||
c.Set("user", &user)
|
||||
} else {
|
||||
// Log the error but continue - we still have basic user info from JWT
|
||||
fmt.Printf("Error loading user roles after DB reconnect: %v\n", result.Error)
|
||||
|
||||
// Try a simpler query as fallback
|
||||
simpleResult := h.DB.First(&user, userIDValue)
|
||||
if simpleResult.Error == nil {
|
||||
c.Set("user", &user)
|
||||
fmt.Println("Loaded user without roles after DB reconnect")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Printf("Database successfully reopened after %s\n", reason)
|
||||
return true
|
||||
}
|
||||
|
||||
// Helper function to copy a file
|
||||
func copyFile(src, dst string) error {
|
||||
sourceFile, err := os.Open(src)
|
||||
@@ -465,3 +556,101 @@ func formatFileSize(size int64) string {
|
||||
}
|
||||
return fmt.Sprintf("%.1f %cB", float64(size)/float64(div), "KMGTPE"[exp])
|
||||
}
|
||||
|
||||
// HandleExportConfigs exports system configurations as JSON
|
||||
func (h *Handlers) HandleExportConfigs(c *gin.Context) {
|
||||
// Check if DB is nil
|
||||
if h.DB == nil {
|
||||
c.Redirect(http.StatusSeeOther, "/admin/database?error=Database+connection+is+not+available")
|
||||
return
|
||||
}
|
||||
|
||||
// Check if user is authenticated and is admin
|
||||
_, exists := c.Get("userID")
|
||||
if !exists {
|
||||
c.Redirect(http.StatusSeeOther, "/login")
|
||||
return
|
||||
}
|
||||
|
||||
isAdmin, adminExists := c.Get("isAdmin")
|
||||
if !adminExists || isAdmin != true {
|
||||
h.HandleError(c, http.StatusForbidden, "Permission Denied", "You do not have permission to export configurations", nil)
|
||||
return
|
||||
}
|
||||
|
||||
// Query all system configurations
|
||||
var configs []db.TransferConfig
|
||||
if err := h.DB.Find(&configs).Error; err != nil {
|
||||
c.Redirect(http.StatusSeeOther, "/admin/database?error=Failed+to+export+configurations&details="+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// Generate filename with timestamp
|
||||
timestamp := time.Now().Format("2006-01-02-150405")
|
||||
filename := fmt.Sprintf("gomft-configs-%s.json", timestamp)
|
||||
|
||||
// Set headers for file download
|
||||
c.Header("Content-Description", "File Transfer")
|
||||
c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=%s", filename))
|
||||
c.Header("Content-Type", "application/json")
|
||||
|
||||
// Write the JSON to response
|
||||
c.JSON(http.StatusOK, configs)
|
||||
}
|
||||
|
||||
// HandleExportJobs exports jobs as JSON
|
||||
func (h *Handlers) HandleExportJobs(c *gin.Context) {
|
||||
// Check if DB is nil
|
||||
if h.DB == nil {
|
||||
c.Redirect(http.StatusSeeOther, "/admin/database?error=Database+connection+is+not+available")
|
||||
return
|
||||
}
|
||||
|
||||
// Check if user is authenticated and is admin
|
||||
_, exists := c.Get("userID")
|
||||
if !exists {
|
||||
c.Redirect(http.StatusSeeOther, "/login")
|
||||
return
|
||||
}
|
||||
|
||||
isAdmin, adminExists := c.Get("isAdmin")
|
||||
if !adminExists || isAdmin != true {
|
||||
h.HandleError(c, http.StatusForbidden, "Permission Denied", "You do not have permission to export jobs", nil)
|
||||
return
|
||||
}
|
||||
|
||||
// Query all jobs with all possible relationships
|
||||
var jobs []db.Job
|
||||
query := h.DB.Model(&db.Job{})
|
||||
|
||||
// Check if each relation exists before trying to preload
|
||||
// This makes the export more robust against schema changes
|
||||
|
||||
// Try to preload steps if they exist
|
||||
if h.DB.Migrator().HasTable("job_steps") {
|
||||
query = query.Preload("Steps")
|
||||
}
|
||||
|
||||
// Try to preload schedules if they exist
|
||||
if h.DB.Migrator().HasTable("job_schedules") {
|
||||
query = query.Preload("Schedule")
|
||||
}
|
||||
|
||||
// Get the jobs with appropriate preloads
|
||||
if err := query.Find(&jobs).Error; err != nil {
|
||||
c.Redirect(http.StatusSeeOther, "/admin/database?error=Failed+to+export+jobs&details="+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// Generate filename with timestamp
|
||||
timestamp := time.Now().Format("2006-01-02-150405")
|
||||
filename := fmt.Sprintf("gomft-jobs-%s.json", timestamp)
|
||||
|
||||
// Set headers for file download
|
||||
c.Header("Content-Description", "File Transfer")
|
||||
c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=%s", filename))
|
||||
c.Header("Content-Type", "application/json")
|
||||
|
||||
// Write the JSON to response
|
||||
c.JSON(http.StatusOK, jobs)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"math"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
@@ -12,8 +13,56 @@ import (
|
||||
func (h *Handlers) HandleNotifications(c *gin.Context) {
|
||||
userID := c.GetUint("userID")
|
||||
|
||||
// Get notifications for the user
|
||||
notifications, err := h.DB.GetUserNotifications(userID, 50) // Get more for the full page
|
||||
// Get pagination parameters from query
|
||||
pageStr := c.DefaultQuery("page", "1")
|
||||
perPageStr := c.DefaultQuery("perPage", "10")
|
||||
|
||||
page, err := strconv.Atoi(pageStr)
|
||||
if err != nil || page < 1 {
|
||||
page = 1
|
||||
}
|
||||
|
||||
perPage, err := strconv.Atoi(perPageStr)
|
||||
if err != nil {
|
||||
perPage = 10
|
||||
}
|
||||
|
||||
// Ensure perPage is one of the allowed values
|
||||
validPerPage := []int{10, 25, 50, 100}
|
||||
isValid := false
|
||||
for _, v := range validPerPage {
|
||||
if v == perPage {
|
||||
isValid = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !isValid {
|
||||
perPage = 10
|
||||
}
|
||||
|
||||
// Get total count for pagination
|
||||
totalCount, err := h.DB.GetUserNotificationCount(userID)
|
||||
if err != nil {
|
||||
c.String(http.StatusInternalServerError, "Failed to count notifications")
|
||||
return
|
||||
}
|
||||
|
||||
// Calculate total pages
|
||||
totalPages := int(math.Ceil(float64(totalCount) / float64(perPage)))
|
||||
if totalPages < 1 {
|
||||
totalPages = 1
|
||||
}
|
||||
|
||||
// Ensure page is within range
|
||||
if page > totalPages {
|
||||
page = totalPages
|
||||
}
|
||||
|
||||
// Calculate offset for database query
|
||||
offset := (page - 1) * perPage
|
||||
|
||||
// Get paginated notifications for the user
|
||||
notifications, err := h.DB.GetPaginatedUserNotifications(userID, offset, perPage)
|
||||
if err != nil {
|
||||
c.String(http.StatusInternalServerError, "Failed to load notifications")
|
||||
return
|
||||
@@ -29,6 +78,10 @@ func (h *Handlers) HandleNotifications(c *gin.Context) {
|
||||
data := components.NotificationsData{
|
||||
Notifications: notifications,
|
||||
UnreadCount: unreadCount,
|
||||
CurrentPage: page,
|
||||
TotalPages: totalPages,
|
||||
TotalCount: int(totalCount),
|
||||
PerPage: perPage,
|
||||
}
|
||||
|
||||
// Render the notifications page
|
||||
|
||||
@@ -118,12 +118,12 @@ func (h *Handlers) RegisterRoutes(router *gin.Engine) {
|
||||
adminRoles := admin.Group("/roles")
|
||||
adminRoles.Use(h.PermissionMiddleware("roles.admin"))
|
||||
{
|
||||
adminRoles.GET("", h.AdminRoles)
|
||||
adminRoles.GET("/new", h.AdminNewRolePage)
|
||||
adminRoles.GET("/:id/edit", h.AdminEditRolePage)
|
||||
adminRoles.POST("", h.AdminCreateRole)
|
||||
adminRoles.PUT("/:id", h.AdminUpdateRole)
|
||||
adminRoles.DELETE("/:id", h.AdminDeleteRole)
|
||||
adminRoles.GET("", h.HandleRoles)
|
||||
adminRoles.GET("/new", h.HandleNewRole)
|
||||
adminRoles.GET("/:id/edit", h.HandleRoles)
|
||||
adminRoles.POST("", h.HandleCreateRole)
|
||||
adminRoles.PUT("/:id", h.HandleEditRole)
|
||||
adminRoles.DELETE("/:id", h.HandleDeleteRole)
|
||||
}
|
||||
|
||||
// Audit log routes
|
||||
@@ -159,6 +159,8 @@ func (h *Handlers) RegisterRoutes(router *gin.Engine) {
|
||||
dbGroup.GET("/refresh-backups", h.HandleRefreshBackups)
|
||||
dbGroup.POST("/vacuum-database", h.HandleVacuumDatabase)
|
||||
dbGroup.POST("/clear-job-history", h.HandleClearJobHistory)
|
||||
dbGroup.GET("/export-configs", h.PermissionMiddleware("system.export"), h.HandleExportConfigs)
|
||||
dbGroup.GET("/export-jobs", h.PermissionMiddleware("system.export"), h.HandleExportJobs)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -571,317 +570,312 @@ func (h *Handlers) AdminDeleteUser(c *gin.Context) {
|
||||
}
|
||||
|
||||
// AdminRoles handles the GET /admin/roles route
|
||||
func (h *Handlers) AdminRoles(c *gin.Context) {
|
||||
var dbRoles []db.Role
|
||||
if err := h.DB.Find(&dbRoles).Error; err != nil {
|
||||
c.String(http.StatusInternalServerError, "Error fetching roles")
|
||||
return
|
||||
}
|
||||
// func (h *Handlers) AdminRoles(c *gin.Context) {
|
||||
// var dbRoles []db.Role
|
||||
// if err := h.DB.Find(&dbRoles).Error; err != nil {
|
||||
// c.String(http.StatusInternalServerError, "Error fetching roles")
|
||||
// return
|
||||
// }
|
||||
|
||||
// Convert db.Role to components.Role
|
||||
var roles []components.Role
|
||||
for _, dbRole := range dbRoles {
|
||||
role := components.Role{
|
||||
ID: dbRole.ID,
|
||||
Name: dbRole.Name,
|
||||
Description: dbRole.Description,
|
||||
Permissions: dbRole.Permissions,
|
||||
}
|
||||
roles = append(roles, role)
|
||||
}
|
||||
// // Convert db.Role to components.Role
|
||||
// var roles []components.Role
|
||||
// for _, dbRole := range dbRoles {
|
||||
// role := components.Role{
|
||||
// ID: dbRole.ID,
|
||||
// Name: dbRole.Name,
|
||||
// Description: dbRole.Description,
|
||||
// Permissions: dbRole.Permissions,
|
||||
// }
|
||||
// roles = append(roles, role)
|
||||
// }
|
||||
|
||||
// Use components instead of HTML templates
|
||||
data := components.RolesData{
|
||||
Roles: roles,
|
||||
}
|
||||
// // Use components instead of HTML templates
|
||||
// data := components.RolesData{
|
||||
// Roles: roles,
|
||||
// }
|
||||
|
||||
ctx := h.CreateTemplateContext(c)
|
||||
components.AdminRoles(ctx, data).Render(ctx, c.Writer)
|
||||
}
|
||||
// ctx := h.CreateTemplateContext(c)
|
||||
// components.AdminRoles(ctx, data).Render(ctx, c.Writer)
|
||||
// }
|
||||
|
||||
// AdminNewRolePage handles the GET /admin/roles/new route
|
||||
func (h *Handlers) AdminNewRolePage(c *gin.Context) {
|
||||
// Create an empty role for the form
|
||||
role := &components.Role{
|
||||
ID: 0,
|
||||
Name: "",
|
||||
Description: "",
|
||||
Permissions: []string{},
|
||||
}
|
||||
// func (h *Handlers) AdminNewRolePage(c *gin.Context) {
|
||||
// // Create an empty role for the form
|
||||
// role := &components.Role{
|
||||
// ID: 0,
|
||||
// Name: "",
|
||||
// Description: "",
|
||||
// Permissions: []string{},
|
||||
// }
|
||||
|
||||
// All available permissions
|
||||
allPermissions := []string{
|
||||
"users.view", "users.create", "users.edit", "users.delete",
|
||||
"roles.view", "roles.create", "roles.edit", "roles.delete",
|
||||
"transfers.view", "transfers.create", "transfers.edit", "transfers.delete",
|
||||
"audit.view",
|
||||
}
|
||||
// // All available permissions
|
||||
// allPermissions := []string{
|
||||
// "users.view", "users.create", "users.edit", "users.delete",
|
||||
// "roles.view", "roles.create", "roles.edit", "roles.delete",
|
||||
// "transfers.view", "transfers.create", "transfers.edit", "transfers.delete",
|
||||
// "audit.view",
|
||||
// }
|
||||
|
||||
// Use components instead of HTML templates
|
||||
data := components.RoleFormData{
|
||||
Role: role,
|
||||
IsNew: true,
|
||||
AllPermissions: allPermissions,
|
||||
}
|
||||
// // Use components instead of HTML templates
|
||||
// data := components.RoleFormData{
|
||||
// Role: role,
|
||||
// IsNew: true,
|
||||
// AllPermissions: allPermissions,
|
||||
// }
|
||||
|
||||
ctx := h.CreateTemplateContext(c)
|
||||
components.AdminRoleForm(ctx, data).Render(ctx, c.Writer)
|
||||
}
|
||||
// ctx := h.CreateTemplateContext(c)
|
||||
// components.AdminRoleForm(ctx, data).Render(ctx, c.Writer)
|
||||
// }
|
||||
|
||||
// AdminCreateRole handles the POST /admin/roles route
|
||||
func (h *Handlers) AdminCreateRole(c *gin.Context) {
|
||||
var role db.Role
|
||||
if err := c.ShouldBind(&role); err != nil {
|
||||
c.String(http.StatusBadRequest, fmt.Sprintf("Invalid form data: %v", err))
|
||||
return
|
||||
}
|
||||
// func (h *Handlers) AdminCreateRole(c *gin.Context) {
|
||||
// name := c.PostForm("name")
|
||||
// description := c.PostForm("description")
|
||||
// permissions := c.PostFormArray("permissions[]")
|
||||
|
||||
// Process permissions
|
||||
permissionsStr := c.PostForm("permissions")
|
||||
if permissionsStr != "" {
|
||||
permissions := strings.Split(permissionsStr, ",")
|
||||
for i, p := range permissions {
|
||||
permissions[i] = strings.TrimSpace(p)
|
||||
}
|
||||
role.Permissions = db.Permissions(permissions)
|
||||
}
|
||||
// // Create role
|
||||
// role := &db.Role{
|
||||
// Name: name,
|
||||
// Description: description,
|
||||
// }
|
||||
// role.SetPermissions(permissions)
|
||||
|
||||
// Start a transaction
|
||||
tx := h.DB.Begin()
|
||||
if tx.Error != nil {
|
||||
c.String(http.StatusInternalServerError, "Failed to begin transaction")
|
||||
return
|
||||
}
|
||||
// // Validate role
|
||||
// if err := role.Validate(); err != nil {
|
||||
// ctx := components.CreateTemplateContext(c)
|
||||
// data := components.RoleFormData{
|
||||
// Role: &components.Role{Name: name, Description: description, Permissions: permissions},
|
||||
// IsNew: true,
|
||||
// ErrorMessage: err.Error(),
|
||||
// AllPermissions: GetAllPermissions(),
|
||||
// }
|
||||
// _ = components.AdminRoleForm(ctx, data).Render(ctx, c.Writer)
|
||||
// return
|
||||
// }
|
||||
|
||||
// Save the role
|
||||
if err := tx.Create(&role).Error; err != nil {
|
||||
tx.Rollback()
|
||||
c.String(http.StatusInternalServerError, fmt.Sprintf("Failed to create role: %v", err))
|
||||
return
|
||||
}
|
||||
// // Start transaction
|
||||
// tx := h.DB.Begin()
|
||||
// if err := tx.Error; err != nil {
|
||||
// handleRoleError(c, role, true, "Failed to begin transaction: "+err.Error())
|
||||
// return
|
||||
// }
|
||||
|
||||
// Create audit log for role creation
|
||||
adminID := c.GetUint("userID")
|
||||
auditDetails := map[string]interface{}{
|
||||
"name": role.Name,
|
||||
"description": role.Description,
|
||||
"permissions": role.Permissions,
|
||||
}
|
||||
// // Create role in database
|
||||
// if err := tx.Create(role).Error; err != nil {
|
||||
// tx.Rollback()
|
||||
// handleRoleError(c, role, true, "Failed to create role: "+err.Error())
|
||||
// return
|
||||
// }
|
||||
|
||||
auditLog := db.AuditLog{
|
||||
Action: "create",
|
||||
EntityType: "role",
|
||||
EntityID: role.ID,
|
||||
UserID: adminID,
|
||||
Details: auditDetails,
|
||||
Timestamp: time.Now(),
|
||||
}
|
||||
// // Create audit log
|
||||
// userID := getUserID(c) // Implement this helper to get current user ID
|
||||
// if err := role.AuditLog(tx, "create", userID); err != nil {
|
||||
// tx.Rollback()
|
||||
// handleRoleError(c, role, true, "Failed to create audit log: "+err.Error())
|
||||
// return
|
||||
// }
|
||||
|
||||
if err := tx.Create(&auditLog).Error; err != nil {
|
||||
tx.Rollback()
|
||||
c.String(http.StatusInternalServerError, "Failed to create audit log")
|
||||
return
|
||||
}
|
||||
// // Commit transaction
|
||||
// if err := tx.Commit().Error; err != nil {
|
||||
// handleRoleError(c, role, true, "Failed to commit transaction: "+err.Error())
|
||||
// return
|
||||
// }
|
||||
|
||||
// Commit the transaction
|
||||
if err := tx.Commit().Error; err != nil {
|
||||
c.String(http.StatusInternalServerError, "Failed to commit transaction")
|
||||
return
|
||||
}
|
||||
|
||||
c.Redirect(http.StatusFound, "/admin/roles")
|
||||
}
|
||||
// c.Redirect(http.StatusFound, "/admin/roles")
|
||||
// }
|
||||
|
||||
// AdminEditRolePage handles the GET /admin/roles/:id/edit route
|
||||
func (h *Handlers) AdminEditRolePage(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
// func (h *Handlers) AdminEditRolePage(c *gin.Context) {
|
||||
// id := c.Param("id")
|
||||
|
||||
var dbRole db.Role
|
||||
if err := h.DB.First(&dbRole, id).Error; err != nil {
|
||||
c.Redirect(http.StatusFound, "/admin/roles")
|
||||
return
|
||||
}
|
||||
// var dbRole db.Role
|
||||
// if err := h.DB.First(&dbRole, id).Error; err != nil {
|
||||
// c.Redirect(http.StatusFound, "/admin/roles")
|
||||
// return
|
||||
// }
|
||||
|
||||
// Convert db.Role to components.Role
|
||||
role := &components.Role{
|
||||
ID: dbRole.ID,
|
||||
Name: dbRole.Name,
|
||||
Description: dbRole.Description,
|
||||
Permissions: dbRole.Permissions,
|
||||
}
|
||||
// // Convert db.Role to components.Role
|
||||
// role := &components.Role{
|
||||
// ID: dbRole.ID,
|
||||
// Name: dbRole.Name,
|
||||
// Description: dbRole.Description,
|
||||
// Permissions: dbRole.Permissions,
|
||||
// }
|
||||
|
||||
// All available permissions
|
||||
allPermissions := []string{
|
||||
"users.view", "users.create", "users.edit", "users.delete",
|
||||
"roles.view", "roles.create", "roles.edit", "roles.delete",
|
||||
"transfers.view", "transfers.create", "transfers.edit", "transfers.delete",
|
||||
"audit.view",
|
||||
}
|
||||
// // All available permissions
|
||||
// allPermissions := []string{
|
||||
// "users.view", "users.create", "users.edit", "users.delete",
|
||||
// "roles.view", "roles.create", "roles.edit", "roles.delete",
|
||||
// "transfers.view", "transfers.create", "transfers.edit", "transfers.delete",
|
||||
// "audit.view",
|
||||
// }
|
||||
|
||||
// Use components instead of HTML templates
|
||||
data := components.RoleFormData{
|
||||
Role: role,
|
||||
IsNew: false,
|
||||
AllPermissions: allPermissions,
|
||||
}
|
||||
// // Use components instead of HTML templates
|
||||
// data := components.RoleFormData{
|
||||
// Role: role,
|
||||
// IsNew: false,
|
||||
// AllPermissions: allPermissions,
|
||||
// }
|
||||
|
||||
ctx := h.CreateTemplateContext(c)
|
||||
components.AdminRoleForm(ctx, data).Render(ctx, c.Writer)
|
||||
}
|
||||
// ctx := h.CreateTemplateContext(c)
|
||||
// components.AdminRoleForm(ctx, data).Render(ctx, c.Writer)
|
||||
// }
|
||||
|
||||
// AdminUpdateRole handles the PUT /admin/roles/:id route
|
||||
func (h *Handlers) AdminUpdateRole(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
// func (h *Handlers) AdminUpdateRole(c *gin.Context) {
|
||||
// id := c.Param("id")
|
||||
|
||||
var role db.Role
|
||||
if err := h.DB.First(&role, id).Error; err != nil {
|
||||
c.String(http.StatusNotFound, "Role not found")
|
||||
return
|
||||
}
|
||||
// var role db.Role
|
||||
// if err := h.DB.First(&role, id).Error; err != nil {
|
||||
// c.String(http.StatusNotFound, "Role not found")
|
||||
// return
|
||||
// }
|
||||
|
||||
// Store original role state for audit log
|
||||
oldRole := role
|
||||
// // Store original role state for audit log
|
||||
// oldRole := role
|
||||
|
||||
// Update role with form data
|
||||
name := c.PostForm("name")
|
||||
if name != "" {
|
||||
role.Name = name
|
||||
}
|
||||
// // Update role with form data
|
||||
// name := c.PostForm("name")
|
||||
// if name != "" {
|
||||
// role.Name = name
|
||||
// }
|
||||
|
||||
description := c.PostForm("description")
|
||||
if description != "" {
|
||||
role.Description = description
|
||||
}
|
||||
// description := c.PostForm("description")
|
||||
// if description != "" {
|
||||
// role.Description = description
|
||||
// }
|
||||
|
||||
// Process permissions
|
||||
permissionsStr := c.PostForm("permissions")
|
||||
if permissionsStr != "" {
|
||||
permissions := strings.Split(permissionsStr, ",")
|
||||
for i, p := range permissions {
|
||||
permissions[i] = strings.TrimSpace(p)
|
||||
}
|
||||
role.Permissions = db.Permissions(permissions)
|
||||
}
|
||||
// // Process permissions
|
||||
// permissionsStr := c.PostForm("permissions")
|
||||
// if permissionsStr != "" {
|
||||
// permissions := strings.Split(permissionsStr, ",")
|
||||
// for i, p := range permissions {
|
||||
// permissions[i] = strings.TrimSpace(p)
|
||||
// }
|
||||
// role.Permissions = db.Permissions(permissions)
|
||||
// }
|
||||
|
||||
// Start a transaction
|
||||
tx := h.DB.Begin()
|
||||
if tx.Error != nil {
|
||||
c.String(http.StatusInternalServerError, "Failed to begin transaction")
|
||||
return
|
||||
}
|
||||
// // Start a transaction
|
||||
// tx := h.DB.Begin()
|
||||
// if tx.Error != nil {
|
||||
// c.String(http.StatusInternalServerError, "Failed to begin transaction")
|
||||
// return
|
||||
// }
|
||||
|
||||
// Save the role
|
||||
if err := tx.Save(&role).Error; err != nil {
|
||||
tx.Rollback()
|
||||
c.String(http.StatusInternalServerError, fmt.Sprintf("Failed to update role: %v", err))
|
||||
return
|
||||
}
|
||||
// // Save the role
|
||||
// if err := tx.Save(&role).Error; err != nil {
|
||||
// tx.Rollback()
|
||||
// c.String(http.StatusInternalServerError, fmt.Sprintf("Failed to update role: %v", err))
|
||||
// return
|
||||
// }
|
||||
|
||||
// Create audit log entry
|
||||
adminID := c.GetUint("userID")
|
||||
auditDetails := map[string]interface{}{
|
||||
"name": role.Name,
|
||||
"description": role.Description,
|
||||
"permissions": role.Permissions,
|
||||
"previous_state": map[string]interface{}{
|
||||
"name": oldRole.Name,
|
||||
"description": oldRole.Description,
|
||||
"permissions": oldRole.Permissions,
|
||||
},
|
||||
}
|
||||
// // Create audit log entry
|
||||
// adminID := c.GetUint("userID")
|
||||
// auditDetails := map[string]interface{}{
|
||||
// "name": role.Name,
|
||||
// "description": role.Description,
|
||||
// "permissions": role.Permissions,
|
||||
// "previous_state": map[string]interface{}{
|
||||
// "name": oldRole.Name,
|
||||
// "description": oldRole.Description,
|
||||
// "permissions": oldRole.Permissions,
|
||||
// },
|
||||
// }
|
||||
|
||||
auditLog := db.AuditLog{
|
||||
Action: "update",
|
||||
EntityType: "role",
|
||||
EntityID: role.ID,
|
||||
UserID: adminID,
|
||||
Details: auditDetails,
|
||||
Timestamp: time.Now(),
|
||||
}
|
||||
// auditLog := db.AuditLog{
|
||||
// Action: "update",
|
||||
// EntityType: "role",
|
||||
// EntityID: role.ID,
|
||||
// UserID: adminID,
|
||||
// Details: auditDetails,
|
||||
// Timestamp: time.Now(),
|
||||
// }
|
||||
|
||||
if err := tx.Create(&auditLog).Error; err != nil {
|
||||
tx.Rollback()
|
||||
c.String(http.StatusInternalServerError, "Failed to create audit log")
|
||||
return
|
||||
}
|
||||
// if err := tx.Create(&auditLog).Error; err != nil {
|
||||
// tx.Rollback()
|
||||
// c.String(http.StatusInternalServerError, "Failed to create audit log")
|
||||
// return
|
||||
// }
|
||||
|
||||
// Commit the transaction
|
||||
if err := tx.Commit().Error; err != nil {
|
||||
c.String(http.StatusInternalServerError, "Failed to commit transaction")
|
||||
return
|
||||
}
|
||||
// // Commit the transaction
|
||||
// if err := tx.Commit().Error; err != nil {
|
||||
// c.String(http.StatusInternalServerError, "Failed to commit transaction")
|
||||
// return
|
||||
// }
|
||||
|
||||
c.Redirect(http.StatusFound, "/admin/roles")
|
||||
}
|
||||
// c.Redirect(http.StatusFound, "/admin/roles")
|
||||
// }
|
||||
|
||||
// AdminDeleteRole handles the DELETE /admin/roles/:id route
|
||||
func (h *Handlers) AdminDeleteRole(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
adminID := c.GetUint("userID")
|
||||
// func (h *Handlers) AdminDeleteRole(c *gin.Context) {
|
||||
// id := c.Param("id")
|
||||
// adminID := c.GetUint("userID")
|
||||
|
||||
var role db.Role
|
||||
if err := h.DB.First(&role, id).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Role not found"})
|
||||
return
|
||||
}
|
||||
// var role db.Role
|
||||
// if err := h.DB.First(&role, id).Error; err != nil {
|
||||
// c.JSON(http.StatusNotFound, gin.H{"error": "Role not found"})
|
||||
// return
|
||||
// }
|
||||
|
||||
// Check if role is in use
|
||||
var count int64
|
||||
h.DB.Table("user_roles").Where("role_id = ?", role.ID).Count(&count)
|
||||
if count > 0 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Role is assigned to users and cannot be deleted"})
|
||||
return
|
||||
}
|
||||
// // Check if role is in use
|
||||
// var count int64
|
||||
// h.DB.Table("user_roles").Where("role_id = ?", role.ID).Count(&count)
|
||||
// if count > 0 {
|
||||
// c.JSON(http.StatusBadRequest, gin.H{"error": "Role is assigned to users and cannot be deleted"})
|
||||
// return
|
||||
// }
|
||||
|
||||
// Start a transaction
|
||||
tx := h.DB.Begin()
|
||||
if tx.Error != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to begin transaction"})
|
||||
return
|
||||
}
|
||||
// // Start a transaction
|
||||
// tx := h.DB.Begin()
|
||||
// if tx.Error != nil {
|
||||
// c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to begin transaction"})
|
||||
// return
|
||||
// }
|
||||
|
||||
// Create audit log before deletion
|
||||
auditDetails := map[string]interface{}{
|
||||
"name": role.Name,
|
||||
"description": role.Description,
|
||||
"permissions": role.Permissions,
|
||||
}
|
||||
// // Create audit log before deletion
|
||||
// auditDetails := map[string]interface{}{
|
||||
// "name": role.Name,
|
||||
// "description": role.Description,
|
||||
// "permissions": role.Permissions,
|
||||
// }
|
||||
|
||||
auditLog := db.AuditLog{
|
||||
Action: "delete",
|
||||
EntityType: "role",
|
||||
EntityID: role.ID,
|
||||
UserID: adminID,
|
||||
Details: auditDetails,
|
||||
Timestamp: time.Now(),
|
||||
}
|
||||
// auditLog := db.AuditLog{
|
||||
// Action: "delete",
|
||||
// EntityType: "role",
|
||||
// EntityID: role.ID,
|
||||
// UserID: adminID,
|
||||
// Details: auditDetails,
|
||||
// Timestamp: time.Now(),
|
||||
// }
|
||||
|
||||
if err := tx.Create(&auditLog).Error; err != nil {
|
||||
tx.Rollback()
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create audit log"})
|
||||
return
|
||||
}
|
||||
// if err := tx.Create(&auditLog).Error; err != nil {
|
||||
// tx.Rollback()
|
||||
// c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create audit log"})
|
||||
// return
|
||||
// }
|
||||
|
||||
// Delete the role
|
||||
if err := tx.Delete(&role).Error; err != nil {
|
||||
tx.Rollback()
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("Failed to delete role: %v", err)})
|
||||
return
|
||||
}
|
||||
// // Delete the role
|
||||
// if err := tx.Delete(&role).Error; err != nil {
|
||||
// tx.Rollback()
|
||||
// c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("Failed to delete role: %v", err)})
|
||||
// return
|
||||
// }
|
||||
|
||||
// Commit the transaction
|
||||
if err := tx.Commit().Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to commit transaction"})
|
||||
return
|
||||
}
|
||||
// // Commit the transaction
|
||||
// if err := tx.Commit().Error; err != nil {
|
||||
// c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to commit transaction"})
|
||||
// return
|
||||
// }
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"message": "Role deleted successfully"})
|
||||
}
|
||||
// c.JSON(http.StatusOK, gin.H{"message": "Role deleted successfully"})
|
||||
// }
|
||||
|
||||
// AdminUserRoles handles the GET /admin/users/:id/roles route
|
||||
func (h *Handlers) AdminUserRoles(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
|
||||
fmt.Println("AdminUserRoles")
|
||||
|
||||
var user db.User
|
||||
if err := h.DB.First(&user, id).Error; err != nil {
|
||||
c.Redirect(http.StatusFound, "/admin/users")
|
||||
|
||||
Reference in New Issue
Block a user