-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
581 lines (497 loc) · 20 KB
/
Copy pathscript.js
File metadata and controls
581 lines (497 loc) · 20 KB
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
// Initialize logging system
const logger = {
info: function(message) {
console.log(`[INFO] ${new Date().toISOString()}: ${message}`);
},
error: function(message, error = null) {
console.error(`[ERROR] ${new Date().toISOString()}: ${message}`, error);
},
warn: function(message) {
console.warn(`[WARNING] ${new Date().toISOString()}: ${message}`);
}
};
// Data model
class BoQProject {
constructor(id = null, name = '', date = new Date().toISOString().split('T')[0], items = []) {
this.id = id || this.generateId();
this.name = name;
this.date = date;
this.items = items;
}
generateId() {
return 'proj_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
}
addItem(item) {
this.items.push(item);
logger.info(`Added item to project ${this.name}: ${item.description}`);
}
removeItem(index) {
if (index >= 0 && index < this.items.length) {
const removedItem = this.items.splice(index, 1)[0];
logger.info(`Removed item from project ${this.name}: ${removedItem.description}`);
return true;
}
logger.error(`Failed to remove item at index ${index} from project ${this.name}`);
return false;
}
calculateTotal() {
return this.items.reduce((sum, item) => sum + item.total, 0);
}
toJSON() {
return {
id: this.id,
name: this.name,
date: this.date,
items: this.items
};
}
static fromJSON(json) {
return new BoQProject(json.id, json.name, json.date, json.items);
}
}
// Storage manager
const storageManager = {
saveProject(project) {
try {
// Get existing projects
const projects = this.getAllProjects();
// Find if project already exists
const index = projects.findIndex(p => p.id === project.id);
if (index !== -1) {
// Update existing project
projects[index] = project.toJSON();
} else {
// Add new project
projects.push(project.toJSON());
}
// Save back to localStorage
localStorage.setItem('boqProjects', JSON.stringify(projects));
logger.info(`Project saved: ${project.name} (${project.id})`);
return true;
} catch (error) {
logger.error('Failed to save project', error);
return false;
}
},
getProject(id) {
try {
const projects = this.getAllProjects();
const projectData = projects.find(p => p.id === id);
if (projectData) {
logger.info(`Project loaded: ${projectData.name} (${projectData.id})`);
return BoQProject.fromJSON(projectData);
}
logger.warn(`Project not found: ${id}`);
return null;
} catch (error) {
logger.error(`Failed to get project: ${id}`, error);
return null;
}
},
getAllProjects() {
try {
const projectsJson = localStorage.getItem('boqProjects');
return projectsJson ? JSON.parse(projectsJson) : [];
} catch (error) {
logger.error('Failed to get all projects', error);
return [];
}
},
deleteProject(id) {
try {
const projects = this.getAllProjects();
const index = projects.findIndex(p => p.id === id);
if (index !== -1) {
const deletedProject = projects.splice(index, 1)[0];
localStorage.setItem('boqProjects', JSON.stringify(projects));
logger.info(`Project deleted: ${deletedProject.name} (${deletedProject.id})`);
return true;
}
logger.warn(`Failed to delete project: ${id} - not found`);
return false;
} catch (error) {
logger.error(`Failed to delete project: ${id}`, error);
return false;
}
}
};
// UI Controller
const uiController = {
// DOM elements
elements: {
projectName: document.getElementById('projectName'),
projectDate: document.getElementById('projectDate'),
boqForm: document.getElementById('boqForm'),
description: document.getElementById('description'),
quantity: document.getElementById('quantity'),
unit: document.getElementById('unit'),
rate: document.getElementById('rate'),
boqBody: document.getElementById('boqBody'),
grandTotal: document.getElementById('grandTotal'),
clearBtn: document.getElementById('clearBtn'),
saveBtn: document.getElementById('saveBtn'),
downloadPdfBtn: document.getElementById('downloadPdfBtn'),
downloadCsvBtn: document.getElementById('downloadCsvBtn'),
savedProjectsModal: new bootstrap.Modal(document.getElementById('savedProjectsModal')),
savedProjectsBody: document.getElementById('savedProjectsBody')
},
// Current project
currentProject: new BoQProject(),
// Initialize the UI
init() {
logger.info('Initializing UI');
this.setCurrentDate();
this.bindEvents();
this.renderTable();
},
// Set the current date in the date input
setCurrentDate() {
const today = new Date().toISOString().split('T')[0];
this.elements.projectDate.value = today;
this.currentProject.date = today;
},
// Bind event listeners
bindEvents() {
// Form submission
this.elements.boqForm.addEventListener('submit', (e) => {
e.preventDefault();
this.addItem();
});
// Clear button
this.elements.clearBtn.addEventListener('click', () => {
if (confirm('Are you sure you want to clear all items?')) {
this.clearItems();
}
});
// Save button
this.elements.saveBtn.addEventListener('click', () => {
this.saveProject();
});
// Download PDF button
this.elements.downloadPdfBtn.addEventListener('click', () => {
this.downloadPdf();
});
// Download CSV button
this.elements.downloadCsvBtn.addEventListener('click', () => {
this.downloadCsv();
});
// Project name change
this.elements.projectName.addEventListener('input', (e) => {
this.currentProject.name = e.target.value;
});
// Project date change
this.elements.projectDate.addEventListener('change', (e) => {
this.currentProject.date = e.target.value;
});
},
// Add a new item to the BoQ
addItem() {
try {
const description = this.elements.description.value;
const quantity = parseFloat(this.elements.quantity.value);
const unit = this.elements.unit.value;
const rate = parseFloat(this.elements.rate.value);
const total = quantity * rate;
const item = {
description,
quantity,
unit,
rate,
total
};
this.currentProject.addItem(item);
this.renderTable();
this.elements.boqForm.reset();
this.elements.description.focus();
} catch (error) {
logger.error('Failed to add item', error);
alert('Failed to add item. Please check your inputs and try again.');
}
},
// Delete an item from the BoQ
deleteItem(index) {
if (this.currentProject.removeItem(index)) {
this.renderTable();
}
},
// Clear all items
clearItems() {
this.currentProject.items = [];
logger.info('All items cleared');
this.renderTable();
},
// Render the BoQ table
renderTable() {
const tbody = this.elements.boqBody;
tbody.innerHTML = '';
this.currentProject.items.forEach((item, index) => {
const row = document.createElement('tr');
row.innerHTML = `
<td>${item.description}</td>
<td>${item.quantity.toFixed(2)}</td>
<td>${item.unit}</td>
<td>$${item.rate.toFixed(2)}</td>
<td>$${item.total.toFixed(2)}</td>
<td>
<button class="btn btn-danger btn-sm delete-btn">
<i class="bi bi-trash"></i> Delete
</button>
</td>
`;
// Add delete button event listener
const deleteBtn = row.querySelector('.delete-btn');
deleteBtn.addEventListener('click', () => {
this.deleteItem(index);
});
// Add highlight animation
row.classList.add('highlight-row');
tbody.appendChild(row);
});
// Update grand total
const grandTotal = this.currentProject.calculateTotal();
this.elements.grandTotal.textContent = `$${grandTotal.toFixed(2)}`;
},
// Save the current project
saveProject() {
try {
// Check if project has a name
if (!this.elements.projectName.value.trim()) {
alert('Please enter a project name before saving.');
this.elements.projectName.focus();
return;
}
// Update project properties
this.currentProject.name = this.elements.projectName.value;
this.currentProject.date = this.elements.projectDate.value;
// Save to storage
if (storageManager.saveProject(this.currentProject)) {
alert('Project saved successfully!');
} else {
alert('Failed to save project. Please try again.');
}
} catch (error) {
logger.error('Failed to save project', error);
alert('An error occurred while saving the project.');
}
},
// Load a project
loadProject(id) {
try {
const project = storageManager.getProject(id);
if (project) {
this.currentProject = project;
this.elements.projectName.value = project.name;
this.elements.projectDate.value = project.date;
this.renderTable();
return true;
}
return false;
} catch (error) {
logger.error(`Failed to load project: ${id}`, error);
alert('Failed to load project. Please try again.');
return false;
}
},
// Render saved projects
renderSavedProjects() {
try {
const projects = storageManager.getAllProjects();
const tbody = this.elements.savedProjectsBody;
tbody.innerHTML = '';
if (projects.length === 0) {
tbody.innerHTML = '<tr><td colspan="5" class="text-center">No saved projects found.</td></tr>';
return;
}
projects.forEach(project => {
const row = document.createElement('tr');
const totalItems = project.items.length;
const grandTotal = project.items.reduce((sum, item) => sum + item.total, 0);
row.innerHTML = `
<td>${project.name}</td>
<td>${project.date}</td>
<td>${totalItems}</td>
<td>$${grandTotal.toFixed(2)}</td>
<td>
<button class="btn btn-primary btn-sm me-1 load-btn" data-id="${project.id}">
Load
</button>
<button class="btn btn-info btn-sm me-1 preview-btn" data-id="${project.id}">
Preview
</button>
<button class="btn btn-danger btn-sm delete-proj-btn" data-id="${project.id}">
Delete
</button>
</td>
`;
tbody.appendChild(row);
});
// Add event listeners
const loadButtons = tbody.querySelectorAll('.load-btn');
loadButtons.forEach(btn => {
btn.addEventListener('click', () => {
const id = btn.getAttribute('data-id');
this.loadProject(id);
this.elements.savedProjectsModal.hide();
});
});
const previewButtons = tbody.querySelectorAll('.preview-btn');
previewButtons.forEach(btn => {
btn.addEventListener('click', () => {
const id = btn.getAttribute('data-id');
this.previewProject(id);
});
});
const deleteButtons = tbody.querySelectorAll('.delete-proj-btn');
deleteButtons.forEach(btn => {
btn.addEventListener('click', () => {
const id = btn.getAttribute('data-id');
if (confirm('Are you sure you want to delete this project?')) {
storageManager.deleteProject(id);
this.renderSavedProjects();
}
});
});
} catch (error) {
logger.error('Failed to render saved projects', error);
alert('Failed to load saved projects.');
}
}
},
// Download the BoQ as PDF
downloadPdf: function() {
try {
const { jsPDF } = window.jspdf;
const doc = new jsPDF();
// Get project details
const projectName = this.elements.projectName.value || 'Unnamed Project';
const projectDate = this.elements.projectDate.value || new Date().toISOString().split('T')[0];
// Set up document
doc.setFontSize(22);
doc.text('Bill of Quantities', 105, 20, { align: 'center' });
doc.setFontSize(14);
doc.text(`Project: ${projectName}`, 20, 35);
doc.text(`Date: ${projectDate}`, 20, 45);
// Create table
const tableColumn = ['Description', 'Quantity', 'Unit', 'Rate ($)', 'Total ($)'];
const tableRows = [];
this.currentProject.items.forEach(item => {
const itemData = [
item.description,
item.quantity.toFixed(2),
item.unit,
item.rate.toFixed(2),
item.total.toFixed(2)
];
tableRows.push(itemData);
});
// Add table to document
doc.autoTable({
head: [tableColumn],
body: tableRows,
startY: 55,
theme: 'striped',
headStyles: {
fillColor: [41, 128, 185],
textColor: 255
},
foot: [['', '', '', 'Grand Total', `$${this.currentProject.calculateTotal().toFixed(2)}`]],
footStyles: {
fillColor: [41, 128, 185],
textColor: 255,
fontStyle: 'bold'
}
});
// Save PDF
doc.save(`${projectName}_BoQ.pdf`);
logger.info(`PDF downloaded for project: ${projectName}`);
} catch (error) {
logger.error('Failed to download PDF', error);
alert('Failed to generate PDF. Please try again.');
}
},
// Download the BoQ as CSV
downloadCsv: function() {
try {
// Get project details
const projectName = this.elements.projectName.value || 'Unnamed Project';
// Create CSV content
let csvContent = 'Description,Quantity,Unit,Rate ($),Total ($)\n';
this.currentProject.items.forEach(item => {
csvContent += `"${item.description}",${item.quantity.toFixed(2)},"${item.unit}",${item.rate.toFixed(2)},${item.total.toFixed(2)}\n`;
});
csvContent += `\n,,,Grand Total,$${this.currentProject.calculateTotal().toFixed(2)}`;
// Create download link
const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.setAttribute('href', url);
link.setAttribute('download', `${projectName}_BoQ.csv`);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
logger.info(`CSV downloaded for project: ${projectName}`);
} catch (error) {
logger.error('Failed to download CSV', error);
alert('Failed to generate CSV. Please try again.');
}
},
// Preview the current project in PDF format
previewCurrentProject: function() {
try {
logger.info('Opening PDF preview for current project');
// Save current project to session storage for the preview page
const projectData = this.currentProject.toJSON();
sessionStorage.setItem('previewProject', JSON.stringify(projectData));
// Open the preview page in a new tab
window.open('pdf-preview.html', '_blank');
} catch (error) {
logger.error('Failed to open PDF preview', error);
alert('Failed to open preview. Please try again.');
}
},
// Preview a saved project in PDF format
previewProject: function(id) {
try {
logger.info(`Opening PDF preview for project: ${id}`);
// Get the project and store it in session storage
const project = storageManager.getProject(id);
if (project) {
sessionStorage.setItem('previewProject', JSON.stringify(project.toJSON()));
window.open('pdf-preview.html', '_blank');
} else {
throw new Error(`Project not found: ${id}`);
}
} catch (error) {
logger.error(`Failed to preview project: ${id}`, error);
alert('Failed to open preview. Please try again.');
}
}
};
// Initialize the application
document.addEventListener('DOMContentLoaded', () => {
logger.info('Application starting');
// Set up date picker with today's date
uiController.init();
// Add event listener for save button
document.getElementById('saveBtn').addEventListener('click', () => {
uiController.saveProject();
});
// Add event listener for preview button
document.getElementById('previewBtn').addEventListener('click', () => {
uiController.previewCurrentProject();
});
// Show saved projects when clicking on the dropdown
const savedProjectsModal = document.getElementById('savedProjectsModal');
savedProjectsModal.addEventListener('show.bs.modal', () => {
uiController.renderSavedProjects();
});
// Check for project ID in URL parameters (for editing from saved-projects page)
const urlParams = new URLSearchParams(window.location.search);
const projectId = urlParams.get('project');
if (projectId) {
logger.info(`Loading project from URL parameter: ${projectId}`);
uiController.loadProject(projectId);
}
logger.info('Application initialized successfully');
});