pre-clean

Signed-off-by: boris <boris@borishub.co.uk>
This commit is contained in:
boris
2025-04-21 21:24:46 +01:00
parent 78508a7cbd
commit 8877faa631
15 changed files with 1302 additions and 407 deletions

View File

@@ -1,46 +1,46 @@
/**
* Comments functionality for facility management
* Facility status (comments) manager for adding, removing and editing user comments.
*/
// Create a namespace for comments functionality
// Create a namespace to avoid global scope conflicts with facilityData.js
const CommentsManager = {
// Track initialization states
// Initialization states
state: {
isInitializing: false,
isInitialized: false,
isinitialised: false,
isDomReady: false,
isAuthReady: false
},
/**
* Initialize comments functionality
* initialise status functionality
*/
initialize() {
if (this.state.isInitialized) return;
initialise() {
if (this.state.isinitialised) return;
console.log('Initializing comments...');
// Initialize comment modal handlers
this.initializeCommentModals();
// initialise comment modal handlers
this.initialiseCommentModals();
// Set up form handlers
this.setupCommentFormHandlers();
console.log('Comments initialized with auth state:', {
console.log('Comments initialised with auth state:', {
isAuthenticated: this.isAuthenticated(),
user: window.simpleAuth.getUser()
});
this.state.isInitialized = true;
this.state.isinitialised = true;
},
/**
* Check if we can initialize
* Check if initialisation possible
*/
checkInitialize() {
checkinitialise() {
if (this.state.isDomReady && this.state.isAuthReady && !this.state.isInitializing) {
this.state.isInitializing = true;
this.initialize();
this.initialise();
this.state.isInitializing = false;
}
},
@@ -53,33 +53,33 @@ const CommentsManager = {
},
/**
* Initialize comment modals
* initialise comment modals
*/
initializeCommentModals() {
initialiseCommentModals() {
// Status modal (comments view)
const statusModal = document.getElementById('statusModal');
if (statusModal) {
statusModal.addEventListener('show.bs.modal', (event) => {
console.log('Comments modal is about to show');
// Get the button that triggered the modal
const button = event.relatedTarget;
// Get the facility ID from the data attribute
const facilityId = button.getAttribute('data-facility-id');
console.log('Facility ID for comments:', facilityId);
// Get facility ID from either the button or the modal's data attribute
let facilityId;
// First try to get it from the button that triggered the modal
if (event.relatedTarget) {
facilityId = event.relatedTarget.getAttribute('data-facility-id');
}
// If not found in button, try the modal's data attribute
if (!facilityId && statusModal.hasAttribute('data-facility-id')) {
facilityId = statusModal.getAttribute('data-facility-id');
}
if (!facilityId) {
console.error('No facility ID found for comments');
return;
}
// Set the facility ID in the comment form
const commentForm = document.getElementById('commentForm');
if (commentForm) {
const facilityIdInput = commentForm.querySelector('#commentFacilityId');
if (facilityIdInput) {
facilityIdInput.value = facilityId;
}
}
// Store the facility ID on the modal for later use
statusModal.setAttribute('data-facility-id', facilityId);
// Load facility comments
this.loadFacilityComments(facilityId);
@@ -90,13 +90,10 @@ const CommentsManager = {
const editCommentModal = document.getElementById('editCommentModal');
if (editCommentModal) {
editCommentModal.addEventListener('show.bs.modal', (event) => {
console.log('Edit comment modal is about to show');
const button = event.relatedTarget;
const commentId = button.getAttribute('data-comment-id');
const commentText = button.getAttribute('data-comment-text');
console.log('Comment ID:', commentId, 'Comment text:', commentText);
// Set the comment ID and text in the form
const editForm = document.getElementById('editCommentForm');
if (editForm) {
@@ -151,27 +148,34 @@ const CommentsManager = {
const formData = new FormData(commentForm);
// Get form data
// Get form data and ensure proper types
const statusComment = formData.get('commentText');
const facilityId = formData.get('facilityId');
console.log('Comment form data:', { facilityId, statusComment });
// Validate form data
if (!facilityId) {
console.error('No facility ID found in form');
alert('Error: No facility ID found');
commentForm.submitting = false;
return;
}
if (!statusComment) {
alert('Please enter a comment');
commentForm.submitting = false;
return;
}
try {
console.log('Sending comment request...');
// Use the API client to add a status comment
const data = await window.api.addFacilityStatus(facilityId, statusComment);
console.log('Comment response:', data);
const data = await window.api.addFacilityStatus(facilityId.toString(), statusComment);
if (data.success) {
console.log('Comment added successfully');
// Reset the form
commentForm.reset();
// Reload comments to show the new one
this.loadFacilityComments(facilityId);
this.loadFacilityComments(facilityId.toString());
} else {
console.error('Comment failed:', data.error);
alert(data.error || 'Failed to add comment');
@@ -249,21 +253,8 @@ const CommentsManager = {
* Creates a comment form dynamically for authenticated users
*/
createCommentFormForAuthenticatedUser(facilityId) {
// Add detailed logging of auth state
console.log('Creating comment form with auth state:', {
simpleAuthExists: !!window.simpleAuth,
simpleAuthMethods: window.simpleAuth ? Object.keys(window.simpleAuth) : null,
token: window.simpleAuth ? window.simpleAuth.getToken() : null,
user: window.simpleAuth ? window.simpleAuth.getUser() : null,
localStorage: {
token: localStorage.getItem('token'),
user: localStorage.getItem('user')
}
});
// First check if simpleAuth is available
if (!window.simpleAuth) {
console.warn('SimpleAuth not initialized yet');
return `
<div class="alert alert-warning mb-0">
<i class="bi bi-hourglass-split me-2"></i>
@@ -278,14 +269,7 @@ const CommentsManager = {
const user = window.simpleAuth.getUser();
const isAuthenticated = window.simpleAuth.isAuthenticated();
console.log('Authentication validation:', {
hasToken: !!token,
hasUser: !!user,
isAuthenticated: isAuthenticated
});
if (!isAuthenticated || !token || !user) {
console.log('User not authenticated:', { isAuthenticated, token: !!token, user: !!user });
return `
<div class="alert alert-info mb-0">
<i class="bi bi-info-circle me-2"></i>
@@ -295,7 +279,6 @@ const CommentsManager = {
}
// User is authenticated, create the comment form
console.log('User is authenticated, creating comment form');
return `
<form id="commentForm" class="mt-3">
<input type="hidden" id="commentFacilityId" name="facilityId" value="${this.escapeHtml(facilityId)}">
@@ -327,24 +310,30 @@ const CommentsManager = {
*/
async loadFacilityComments(facilityId) {
try {
console.log('Loading comments for facility:', facilityId);
if (!facilityId) {
throw new Error('No facility ID provided');
}
// Ensure facilityId is a string
facilityId = facilityId.toString();
// Show loading indicator
const commentsContainer = document.getElementById('commentsContainer');
if (commentsContainer) {
commentsContainer.innerHTML = `
<div class="text-center py-4">
<div class="spinner-border text-success" role="status">
<span class="visually-hidden">Loading...</span>
</div>
<p class="mt-2 text-muted">Loading comments...</p>
</div>
`;
if (!commentsContainer) {
throw new Error('Comments container not found');
}
commentsContainer.innerHTML = `
<div class="text-center py-4">
<div class="spinner-border text-success" role="status">
<span class="visually-hidden">Loading...</span>
</div>
<p class="mt-2 text-muted">Loading comments...</p>
</div>
`;
// Use the API client to get facility statuses
const data = await window.api.getFacilityStatuses(facilityId);
console.log('Comments API response:', data);
// Validate the response
if (!data || typeof data !== 'object') {
@@ -364,7 +353,6 @@ const CommentsManager = {
} catch (error) {
console.error('Error loading comments:', error);
console.error('Error stack:', error.stack);
const commentsContainer = document.getElementById('commentsContainer');
if (commentsContainer) {
@@ -383,22 +371,32 @@ const CommentsManager = {
*/
renderComments(comments, facilityId) {
const commentsContainer = document.getElementById('commentsContainer');
if (!commentsContainer) return;
if (!commentsContainer) {
console.error('Comments container not found');
return;
}
// Clear the container
commentsContainer.innerHTML = '';
// Add the comment form for authenticated users
commentsContainer.innerHTML += this.createCommentFormForAuthenticatedUser(facilityId);
commentsContainer.innerHTML = this.createCommentFormForAuthenticatedUser(facilityId);
// Re-initialise the comment form handler immediately after creating the form
const commentForm = document.getElementById('commentForm');
if (commentForm) {
this.setupCommentFormHandler(commentForm);
}
// If no comments, show a message
if (!comments || comments.length === 0) {
commentsContainer.innerHTML += `
<div class="alert alert-light mt-3">
<i class="bi bi-chat-dots me-2"></i>
No comments yet. Be the first to add a comment!
</div>
const noCommentsDiv = document.createElement('div');
noCommentsDiv.className = 'alert alert-light mt-3';
noCommentsDiv.innerHTML = `
<i class="bi bi-chat-dots me-2"></i>
No comments yet. Be the first to add a comment!
`;
commentsContainer.appendChild(noCommentsDiv);
return;
}
@@ -453,12 +451,6 @@ const CommentsManager = {
});
commentsContainer.appendChild(commentsList);
// Re-initialize the comment form handler
const commentForm = document.getElementById('commentForm');
if (commentForm) {
this.setupCommentFormHandler(commentForm);
}
},
/**
@@ -471,16 +463,10 @@ const CommentsManager = {
}
try {
console.log('Deleting comment:', commentId, 'for facility:', facilityId);
// Use the API client to delete a status comment
const data = await window.api.deleteFacilityStatus(commentId, facilityId);
console.log('Delete comment response:', data);
if (data.success) {
console.log('Comment deleted successfully');
// Reload comments to reflect the deletion
this.loadFacilityComments(facilityId);
} else {
@@ -529,22 +515,22 @@ const CommentsManager = {
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', () => {
CommentsManager.state.isDomReady = true;
CommentsManager.checkInitialize();
CommentsManager.checkinitialise();
});
} else {
CommentsManager.state.isDomReady = true;
CommentsManager.checkInitialize();
CommentsManager.checkinitialise();
}
// Listen for simpleAuth ready
if (window.simpleAuth) {
CommentsManager.state.isAuthReady = true;
CommentsManager.checkInitialize();
CommentsManager.checkinitialise();
} else {
window.addEventListener('simpleAuthReady', () => {
console.log('SimpleAuth is now ready');
CommentsManager.state.isAuthReady = true;
CommentsManager.checkInitialize();
CommentsManager.checkinitialise();
});
// Fallback timeout in case the event doesn't fire
@@ -552,10 +538,10 @@ if (window.simpleAuth) {
if (!CommentsManager.state.isAuthReady && window.simpleAuth) {
console.log('SimpleAuth found via timeout check');
CommentsManager.state.isAuthReady = true;
CommentsManager.checkInitialize();
CommentsManager.checkinitialise();
}
}, 1000);
}
// Export the CommentsManager to the window object
// Export the CommentsManager to the window
window.CommentsManager = CommentsManager;