Files
GoMFT/components/jobs.templ
T
StarFleetCPTN db6259f8a3 feat: Implement configuration and job duplication functionality
- Added duplication feature for configurations and jobs, allowing users to create copies of existing entries.
- Introduced new buttons in the UI for duplicating configurations and jobs, enhancing user experience.
- Implemented backend logic to handle duplication requests, ensuring proper ownership checks and data integrity.
- Added notifications for successful duplication actions to inform users of the outcome.
- Updated relevant templates and handlers to support the new duplication functionality.
2025-03-22 22:19:05 -07:00

441 lines
18 KiB
Templ

package components
import (
"context"
"fmt"
"github.com/starfleetcptn/gomft/internal/db"
)
// Dialog component for confirmation dialogs using Flowbite modal
templ JobDialog(id string, title string, message string, confirmClass string, confirmText string, action string, jobID uint, jobName string) {
<div id={ id } tabindex="-1" aria-hidden="true" class="hidden fixed inset-0 bg-gray-900/50 dark:bg-gray-900/80 backdrop-blur-sm z-50 flex items-center justify-center overflow-y-auto overflow-x-hidden">
<div class="relative p-4 w-full max-w-md h-auto">
<div class="relative bg-white rounded-lg shadow dark:bg-gray-700">
<div class="flex items-center justify-between p-4 md:p-5 border-b rounded-t dark:border-gray-600">
<h3 class="text-xl font-medium text-gray-900 dark:text-white flex items-center">
<i class="fas fa-exclamation-triangle text-yellow-400 me-2 fa-2x"></i>
{ title }
</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 inline-flex justify-center items-center dark:hover:bg-gray-600 dark:hover:text-white" onclick={ hideJobDialog(id) }>
<i class="fas fa-times"></i>
<span class="sr-only">Close modal</span>
</button>
</div>
<div class="p-4 md:p-5 text-center">
<p class="text-gray-500 dark:text-gray-300 mb-5">
{ message }
</p>
<div class="flex justify-end space-x-3">
<button type="button" class="py-2.5 px-5 text-sm font-medium text-gray-900 focus:outline-none bg-white rounded-lg border border-gray-200 hover:bg-gray-100 hover:text-blue-700 focus:z-10 focus:ring-4 focus:ring-gray-100 dark:focus:ring-gray-700 dark:bg-gray-800 dark:text-gray-400 dark:border-gray-600 dark:hover:text-white dark:hover:bg-gray-700" onclick={ hideJobDialog(id) }>
Cancel
</button>
<button
type="button"
class={ confirmClass }
hx-delete={ fmt.Sprintf("/jobs/%d", jobID) }
hx-target="closest li"
hx-swap="delete"
data-job-name={ jobName }
data-job-id={ fmt.Sprint(jobID) }
id={ fmt.Sprintf("delete-btn-%d", jobID) }
onclick={ triggerJobDelete(id, jobID, jobName) }>
{ confirmText }
</button>
</div>
</div>
</div>
</div>
</div>
}
script hideJobDialog(id string) {
document.getElementById(id).classList.add("hidden");
}
script showJobDialog(id string) {
document.getElementById(id).classList.remove("hidden");
}
script triggerJobDelete(dialogId string, jobID uint, jobName string) {
// Hide the dialog
document.getElementById(dialogId).classList.add("hidden");
// Add debugging info
console.log(`Job deletion triggered for: ${jobName} (ID: ${jobID})`);
// Store data in a way that's accessible to event handlers
window.lastDeletedJob = {
id: jobID,
name: jobName
};
// Add custom marker to track this deletion
window.currentlyDeletingJob = true;
}
type JobsData struct {
Jobs []db.Job
ConfigCount map[uint]int // Maps job ID to number of configs
}
templ Jobs(ctx context.Context, data JobsData) {
@LayoutWithContext("Scheduled Jobs", ctx) {
<script>
// Debug notification system
console.log("Jobs template loaded, setting up notification system");
// Create a global notyf instance immediately
window.notyf = new Notyf({
duration: 3000,
position: {
x: 'right',
y: 'top',
},
types: [
{
type: 'success',
background: '#38c172',
icon: {
className: 'fas fa-check-circle',
tagName: 'i'
}
},
{
type: 'error',
background: '#e3342f',
icon: {
className: 'fas fa-exclamation-circle',
tagName: 'i'
}
}
]
});
console.log("Notyf initialized:", window.notyf);
// Global function to handle job running
window.runJob = function(button) {
// Get job data from button attributes
const jobId = button.getAttribute('data-job-id');
const jobName = button.getAttribute('data-job-name') || `Job #${jobId}`;
console.log(`Run job clicked for: ${jobName} (ID: ${jobId})`);
// No loading notification - just listen for the response
button.addEventListener('htmx:afterRequest', function(event) {
console.log("Run job request completed:", event.detail);
if (event.detail.successful) {
let displayName = jobName;
// Try to extract job name from response headers
if (event.detail.headers && event.detail.headers['HX-Job-Name']) {
displayName = event.detail.headers['HX-Job-Name'];
}
console.log(`Showing success notification for job: ${displayName}`);
window.notyf.success(`Job "${displayName}" started successfully!`);
} else {
let errorMsg = `Failed to start job "${jobName}"`;
if (event.detail.xhr && event.detail.xhr.responseText) {
errorMsg = `Error: ${event.detail.xhr.responseText}`;
}
console.log(`Showing error notification: ${errorMsg}`);
window.notyf.error(errorMsg);
}
}, { once: true });
};
// Track all HTMX events for debugging
document.addEventListener('htmx:beforeRequest', function(event) {
console.log("HTMX before request:", event.detail);
// Check if this is a DELETE request by examining the URL and method
const path = event.detail.path;
const method = event.detail.verb;
console.log(`Request path: ${path}, method: ${method}`);
// Pattern match for job deletions (e.g., /jobs/123)
if (path && method === 'DELETE' && path.match(/^\/jobs\/\d+$/)) {
console.log("Detected job deletion request via URL pattern");
// This is definitely a delete request - store this information
window.isJobDeleteRequest = true;
}
});
// Track HTMX after-request events for job deletion
document.addEventListener('htmx:afterRequest', function(event) {
console.log("HTMX after request:", event.detail);
// Check for job deletion multiple ways
const isDeleteRequest =
// Check global flag from the triggerJobDelete function
window.currentlyDeletingJob ||
// Check flag from beforeRequest handler
window.isJobDeleteRequest ||
// Check URL pattern directly from this event
(event.detail.pathInfo && event.detail.pathInfo.requestPath &&
event.detail.pathInfo.requestPath.match(/^\/jobs\/\d+$/) &&
event.detail.verb === 'DELETE');
console.log(`Is delete request: ${isDeleteRequest}`);
// If this is a successful delete request, show notification
if (isDeleteRequest && event.detail.successful) {
console.log("Delete request was successful");
let jobName = "Unknown";
// Try multiple sources for job name
if (event.detail.elt && event.detail.elt.getAttribute) {
jobName = event.detail.elt.getAttribute('data-job-name') || jobName;
}
if (jobName === "Unknown" && window.lastDeletedJob) {
// Fallback to our stored job info
jobName = window.lastDeletedJob.name;
}
console.log(`Showing success notification for deleted job: ${jobName}`);
window.notyf.success(`Job "${jobName}" deleted successfully`);
// Clear flags
window.currentlyDeletingJob = false;
window.isJobDeleteRequest = false;
window.lastDeletedJob = null;
}
});
// Track HTMX error events for job deletion
document.addEventListener('htmx:responseError', function(event) {
console.log("HTMX response error:", event.detail);
// Similar logic as success but for errors
const isDeleteRequest =
window.currentlyDeletingJob ||
window.isJobDeleteRequest ||
(event.detail.pathInfo && event.detail.pathInfo.requestPath &&
event.detail.pathInfo.requestPath.match(/^\/jobs\/\d+$/) &&
event.detail.verb === 'DELETE');
if (isDeleteRequest) {
console.log("Delete request failed");
let jobName = "Unknown";
// Try multiple sources for job name
if (event.detail.elt && event.detail.elt.getAttribute) {
jobName = event.detail.elt.getAttribute('data-job-name') || jobName;
}
if (jobName === "Unknown" && window.lastDeletedJob) {
// Fallback to our stored job info
jobName = window.lastDeletedJob.name;
}
let errorMsg = `Failed to delete job "${jobName}"`;
if (event.detail.xhr && event.detail.xhr.responseText) {
errorMsg = `Error: ${event.detail.xhr.responseText}`;
}
console.log(`Showing error notification: ${errorMsg}`);
window.notyf.error(errorMsg);
// Clear flags
window.currentlyDeletingJob = false;
window.isJobDeleteRequest = false;
window.lastDeletedJob = null;
}
});
</script>
<div id="jobs-container" style="min-height: 100vh; background-color: rgb(249, 250, 251);" class="jobs-page bg-gray-50 dark:bg-gray-900">
<div class="pb-8 w-full">
<div class="mb-6 flex flex-col md:flex-row md:items-center md:justify-between gap-4">
<h1 class="text-2xl font-bold text-gray-900 dark:text-white flex items-center">
<i class="fas fa-calendar-alt w-6 h-6 mr-2 text-blue-500 dark:text-blue-400"></i>
Scheduled Jobs
</h1>
<a href="/jobs/new" class="flex items-center justify-center text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 font-medium rounded-lg px-5 py-2.5 dark:bg-blue-600 dark:hover:bg-blue-700 focus:outline-none dark:focus:ring-blue-800">
<i class="fas fa-plus w-4 h-4 mr-2"></i>
New Job
</a>
</div>
<div class="mt-6">
if len(data.Jobs) == 0 {
<div class="bg-white dark:bg-gray-800 shadow-md rounded-lg p-12 flex flex-col items-center justify-center text-center">
<div class="inline-block p-4 rounded-full bg-gray-100 dark:bg-gray-700 mb-4">
<i class="fas fa-list text-3xl text-gray-400 dark:text-gray-500"></i>
</div>
<h3 class="mt-2 text-lg font-medium text-gray-900 dark:text-white">No jobs</h3>
<p class="mt-1 text-sm text-gray-500 dark:text-gray-400">Get started by creating a new transfer job.</p>
<div class="mt-6">
<a href="/jobs/new" class="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 dark:bg-blue-600 dark:hover:bg-blue-700 focus:outline-none dark:focus:ring-blue-800">
<i class="fas fa-plus mr-2"></i>
New Job
</a>
</div>
</div>
} else {
<div class="bg-white dark:bg-gray-800 shadow-md sm:rounded-lg overflow-hidden">
<div class="relative overflow-x-auto">
<ul role="list" class="divide-y divide-gray-200 dark:divide-gray-700">
for _, job := range data.Jobs {
<li>
<div class="block hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors">
<div class="px-4 py-4 sm:px-6">
<div class="flex items-center justify-between">
<div class="flex items-center">
<p class="text-sm font-medium text-blue-600 dark:text-blue-400 truncate">
if job.Name != "" {
{ job.Name }
} else {
{ job.Config.Name }
}
</p>
if job.GetEnabled() {
<span class="inline-flex items-center bg-green-100 text-green-800 text-xs font-medium mr-2 px-2.5 py-0.5 rounded-full dark:bg-green-900 dark:text-green-300 ml-2">
<i class="fas fa-circle-check text-green-500 dark:text-green-400 mr-1"></i>
Active
</span>
} else {
<span class="inline-flex items-center bg-gray-100 text-gray-800 text-xs font-medium mr-2 px-2.5 py-0.5 rounded-full dark:bg-gray-700 dark:text-gray-300 ml-2">
<i class="fas fa-circle-xmark text-gray-500 dark:text-gray-400 mr-1"></i>
Inactive
</span>
}
</div>
<div class="ml-2 flex-shrink-0 flex space-x-2">
<button
hx-post={ fmt.Sprintf("/jobs/%d/run", job.ID) }
hx-swap="none"
class="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 font-medium rounded-lg text-xs px-3 py-1.5 dark:bg-blue-600 dark:hover:bg-blue-700 focus:outline-none dark:focus:ring-blue-800"
data-job-id={ fmt.Sprint(job.ID) }
data-job-name={ job.Name }
onclick="window.runJob(this)">
<i class="fas fa-play mr-1"></i>
Run Now
</button>
<a href={ templ.SafeURL(fmt.Sprintf("/jobs/%d", job.ID)) } class="py-1.5 px-3 text-xs font-medium text-gray-900 focus:outline-none bg-white rounded-lg border border-gray-200 hover:bg-gray-100 hover:text-blue-700 focus:z-10 focus:ring-4 focus:ring-gray-100 dark:focus:ring-gray-700 dark:bg-gray-800 dark:text-gray-400 dark:border-gray-600 dark:hover:text-white dark:hover:bg-gray-700">
<i class="fas fa-pen-to-square mr-1"></i>
Edit
</a>
<button
hx-post={ fmt.Sprintf("/jobs/%d/duplicate", job.ID) }
hx-swap="innerHTML"
hx-target="body"
class="text-indigo-700 bg-indigo-100 hover:bg-indigo-200 focus:ring-4 focus:outline-none focus:ring-indigo-300 font-medium rounded-lg text-xs px-3 py-1.5 text-center inline-flex items-center dark:bg-indigo-700 dark:text-indigo-300 dark:hover:bg-indigo-600 dark:focus:ring-indigo-800"
data-job-id={ fmt.Sprint(job.ID) }
data-job-name={ job.Name }>
<i class="fas fa-clone mr-1"></i>
Duplicate
</button>
<!-- Add delete dialog for each job -->
@JobDialog(
fmt.Sprintf("delete-job-dialog-%d", job.ID),
"Delete Job",
fmt.Sprintf("Are you sure you want to delete the job '%s'? This cannot be undone.", determineJobName(job)),
"text-white bg-red-700 hover:bg-red-800 focus:ring-4 focus:ring-red-300 font-medium rounded-lg text-sm px-5 py-2.5 dark:bg-red-600 dark:hover:bg-red-700 focus:outline-none dark:focus:ring-red-800",
"Delete",
"delete",
job.ID,
determineJobName(job),
)
<button
type="button"
onclick={ showJobDialog(fmt.Sprintf("delete-job-dialog-%d", job.ID)) }
class="focus:outline-none text-white bg-red-700 hover:bg-red-800 focus:ring-4 focus:ring-red-300 font-medium rounded-lg text-xs px-3 py-1.5 dark:bg-red-600 dark:hover:bg-red-700 dark:focus:ring-red-900">
<i class="fas fa-trash mr-1"></i>
Delete
</button>
</div>
</div>
<div class="mt-2 sm:flex sm:justify-between">
<div class="sm:flex flex-wrap">
<p class="flex items-center text-sm text-gray-500 dark:text-gray-400">
<i class="fas fa-gear text-gray-400 dark:text-gray-500 mr-1.5"></i>
Configs:
<span class="ml-1">
if count, ok := data.ConfigCount[job.ID]; ok && count > 1 {
{ fmt.Sprintf("%d configurations", count) }
} else if job.ConfigID > 0 {
{ job.Config.Name }
} else {
{ "None" }
}
</span>
</p>
<p class="mt-2 flex items-center text-sm text-gray-500 dark:text-gray-400 sm:mt-0 sm:ml-6">
<i class="fas fa-calendar text-gray-400 dark:text-gray-500 mr-1.5"></i>
Schedule: { job.Schedule }
</p>
if job.LastRun != nil {
<p class="mt-2 flex items-center text-sm text-gray-500 dark:text-gray-400 sm:mt-0 sm:ml-6">
<i class="fas fa-clock text-gray-400 dark:text-gray-500 mr-1.5"></i>
Last Run: { job.LastRun.Format("2006-01-02 15:04:05") }
</p>
}
</div>
if job.NextRun != nil {
<div class="mt-2 flex items-center text-sm text-gray-500 dark:text-gray-400 sm:mt-0">
<i class="fas fa-hourglass-start text-gray-400 dark:text-gray-500 mr-1.5"></i>
<p>
Next Run: { job.NextRun.Format("2006-01-02 15:04:05") }
</p>
</div>
}
</div>
</div>
</div>
</li>
}
</ul>
</div>
</div>
}
</div>
<!-- Help Notice -->
<div class="mt-8 p-4 bg-gray-50 border border-gray-200 rounded-lg dark:bg-gray-800 dark:border-gray-700">
<div class="flex">
<div class="flex-shrink-0">
<i class="fas fa-info-circle text-blue-400 dark:text-blue-400"></i>
</div>
<div class="ml-3">
<p class="text-sm text-blue-700 dark:text-blue-400">
Transfer jobs run according to their schedule and transfer files between configured sources and destinations
</p>
</div>
</div>
</div>
</div>
</div>
<script>
// Set dark background color if in dark mode
if (document.documentElement.classList.contains('dark')) {
document.getElementById('jobs-container').style.backgroundColor = '#111827';
}
// Add event listener for theme changes
document.addEventListener('DOMContentLoaded', function() {
const themeToggle = document.getElementById('theme-toggle');
if (themeToggle) {
themeToggle.addEventListener('click', function() {
setTimeout(function() {
const isDark = document.documentElement.classList.contains('dark');
document.getElementById('jobs-container').style.backgroundColor = isDark ? '#111827' : 'rgb(249, 250, 251)';
}, 50);
});
}
});
</script>
}
}
// Helper function to determine the job name (reuse this logic to keep it consistent)
func determineJobName(job db.Job) string {
if job.Name != "" {
return job.Name
}
return job.Config.Name
}