File size: 9,542 Bytes
82d5968 fc1f67d 82d5968 fc1f67d 82d5968 fc1f67d 82d5968 8304476 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 | // Service Worker Registration
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/sw.js').then(registration => {
console.log('ServiceWorker registration successful with scope: ', registration.scope);
}).catch(err => {
console.log('ServiceWorker registration failed: ', err);
});
});
}
// Initialize IndexedDB
function initDB() {
return new Promise((resolve, reject) => {
const request = indexedDB.open('LodgeMasterDB', 1);
request.onerror = (event) => {
console.error('Database error:', event.target.error);
reject(event.target.error);
};
request.onsuccess = (event) => {
const db = event.target.result;
resolve(db);
};
request.onupgradeneeded = (event) => {
const db = event.target.result;
// Create object stores
if (!db.objectStoreNames.contains('bookings')) {
const bookingsStore = db.createObjectStore('bookings', { keyPath: 'id', autoIncrement: true });
bookingsStore.createIndex('roomNumber', 'roomNumber', { unique: false });
bookingsStore.createIndex('status', 'status', { unique: false });
}
if (!db.objectStoreNames.contains('payments')) {
const paymentsStore = db.createObjectStore('payments', { keyPath: 'id', autoIncrement: true });
paymentsStore.createIndex('bookingId', 'bookingId', { unique: false });
paymentsStore.createIndex('date', 'date', { unique: false });
}
if (!db.objectStoreNames.contains('rooms')) {
db.createObjectStore('rooms', { keyPath: 'number' });
}
if (!db.objectStoreNames.contains('settings')) {
db.createObjectStore('settings', { keyPath: 'key' });
}
};
});
}
// Check online status
function checkOnlineStatus() {
if (!navigator.onLine) {
showOfflineAlert();
}
window.addEventListener('online', () => {
hideOfflineAlert();
syncData();
});
window.addEventListener('offline', showOfflineAlert);
}
function showOfflineAlert() {
const alert = document.createElement('div');
alert.className = 'fixed bottom-4 left-4 bg-yellow-500 text-white px-4 py-2 rounded-md shadow-md z-50';
alert.id = 'offline-alert';
alert.innerHTML = '⚠️ You are currently offline. Changes will be synced when you reconnect.';
document.body.appendChild(alert);
}
function hideOfflineAlert() {
const alert = document.getElementById('offline-alert');
if (alert) {
alert.remove();
}
}
// Sync data when coming back online
async function syncData() {
const db = await initDB();
const tx = db.transaction(['bookings', 'payments'], 'readwrite');
// TODO: Implement actual sync logic with backend
console.log('Syncing data with server...');
// Show sync success message
const syncAlert = document.createElement('div');
syncAlert.className = 'fixed bottom-4 left-4 bg-green-500 text-white px-4 py-2 rounded-md shadow-md z-50';
syncAlert.innerHTML = '✓ Data synced successfully!';
document.body.appendChild(syncAlert);
setTimeout(() => {
syncAlert.remove();
}, 3000);
}
// Initialize the app
document.addEventListener('DOMContentLoaded', () => {
checkOnlineStatus();
// Add click handlers for all buttons
document.querySelectorAll('button').forEach(button => {
if (!button.hasAttribute('data-no-handler')) {
button.addEventListener('click', handleButtonClick);
}
});
// Initialize form submissions
document.querySelectorAll('form').forEach(form => {
form.addEventListener('submit', handleFormSubmit);
});
// Initialize tooltips
const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
tooltipTriggerList.map(tooltipTriggerEl => {
return new bootstrap.Tooltip(tooltipTriggerEl);
});
// Load offline data if needed
if (!navigator.onLine) {
loadOfflineData();
}
// Initialize real-time room updates
if (window.location.pathname === '/dashboard.html') {
setInterval(fetchRoomStatus, 30000); // Update every 30 seconds
}
});
// Fetch room status from API
async function fetchRoomStatus() {
try {
const response = await fetch('/api/rooms/status');
const data = await response.json();
updateRoomCards(data);
} catch (error) {
console.error('Error fetching room status:', error);
}
}
// Update room cards with fresh data
function updateRoomCards(rooms) {
rooms.forEach(room => {
const card = document.querySelector(`room-card[room-number="${room.number}"]`);
if (card) {
card.setAttribute('status', room.status);
card.setAttribute('booking-type', room.bookingType || '');
card.setAttribute('guest-name', room.guestName || '');
card.setAttribute('checkout-time', room.checkoutTime || '');
}
});
}
// Handle offline booking submission
async function submitOfflineBooking(bookingData) {
const db = await initDB();
const tx = db.transaction('bookings', 'readwrite');
const store = tx.objectStore('bookings');
return new Promise((resolve, reject) => {
const request = store.add({
...bookingData,
offline: true,
syncStatus: 'pending',
createdAt: new Date().toISOString()
});
request.onsuccess = () => resolve();
request.onerror = (event) => reject(event.target.error);
});
}
async function loadOfflineData() {
const db = await initDB();
const tx = db.transaction(['bookings', 'payments', 'rooms'], 'readonly');
const bookings = await tx.objectStore('bookings').getAll();
const payments = await tx.objectStore('payments').getAll();
const rooms = await tx.objectStore('rooms').getAll();
return { bookings, payments, rooms };
}
function handleButtonClick(e) {
const button = e.currentTarget;
const action = button.dataset.action;
switch(action) {
case 'new-booking':
window.location.href = '/bookings.html?new=true';
break;
case 'check-out':
const roomNumber = button.dataset.room;
handleCheckOut(roomNumber);
break;
case 'print-report':
window.print();
break;
case 'record-payment':
const bookingId = button.dataset.booking;
window.location.href = `/payments.html?booking=${bookingId}`;
break;
case 'view-details':
const id = button.dataset.id;
window.location.href = `/booking-details.html?id=${id}`;
break;
case 'edit-booking':
const editId = button.dataset.id;
window.location.href = `/bookings.html?edit=${editId}`;
break;
default:
console.log('Button clicked:', button.textContent);
}
}
async function handleFormSubmit(e) {
e.preventDefault();
const form = e.currentTarget;
const formData = new FormData(form);
const formAction = form.getAttribute('action') || form.dataset.action;
const formMethod = form.getAttribute('method') || 'POST';
try {
if (navigator.onLine) {
const response = await fetch(formAction, {
method: formMethod,
body: formData
});
const result = await response.json();
showToast('Success: ' + result.message);
} else {
await saveFormDataOffline(formData, formAction);
showToast('Saved offline. Will sync when online.');
}
} catch (error) {
showToast('Error: ' + error.message, 'error');
}
}
async function saveFormDataOffline(formData, action) {
const db = await initDB();
const tx = db.transaction('pendingActions', 'readwrite');
const store = tx.objectStore('pendingActions');
const pendingAction = {
action: action,
data: Object.fromEntries(formData),
timestamp: new Date().toISOString()
};
await store.add(pendingAction);
}
function showToast(message, type = 'success') {
const toast = document.createElement('div');
toast.className = `fixed bottom-4 right-4 px-4 py-2 rounded-md shadow-md z-50 ${
type === 'success' ? 'bg-green-500' : 'bg-red-500'
} text-white`;
toast.textContent = message;
document.body.appendChild(toast);
setTimeout(() => {
toast.remove();
}, 3000);
}
// Utility function for currency formatting
function formatUGX(amount) {
return new Intl.NumberFormat('en-UG', {
style: 'currency',
currency: 'UGX',
minimumFractionDigits: 0
}).format(amount);
}
// Login form validation
function validateLoginForm(email, password) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
return { valid: false, message: 'Please enter a valid email address' };
}
if (password.length < 6) {
return { valid: false, message: 'Password must be at least 6 characters' };
}
return { valid: true };
}
|