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e94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72a044b
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
// Initialize PWA
function initPWA() {
    // Check if the browser supports service workers
    if ('serviceWorker' in navigator) {
        navigator.serviceWorker.register('/sw.js')
            .then(registration => {
                console.log('Service Worker registered with scope:', registration.scope);
                
                // Request permission for notifications
                if ('Notification' in window) {
                    Notification.requestPermission().then(permission => {
                        if (permission === 'granted') {
                            console.log('Notification permission granted.');
                        }
                    });
                }
            })
            .catch(error => {
                console.log('Service Worker registration failed:', error);
            });
    }
}
// Ticket storage using localStorage
const TICKETS_KEY = 'bugtracker_tickets';

// Initialize with sample tickets if none exist
function initTickets() {
    if (!localStorage.getItem(TICKETS_KEY)) {
        const sampleTickets = [
            {
                title: "Login Page Bug",
                status: "open",
                priority: "high",
                assigned: "John D.",
                date: "2023-11-15",
                description: "Users unable to login with Google auth"
            },
            {
                title: "Mobile Responsiveness",
                status: "in-progress",
                priority: "medium",
                assigned: "Sarah K.",
                date: "2023-11-10",
                description: "Dashboard breaks on mobile devices"
            },
            {
                title: "API Timeout",
                status: "resolved",
                priority: "low",
                assigned: "Mike T.",
                date: "2023-11-05",
                description: "Product API times out after 5 seconds"
            }
        ];
        localStorage.setItem(TICKETS_KEY, JSON.stringify(sampleTickets));
    }
}

// Get all tickets
function getTickets() {
    initTickets();
    return JSON.parse(localStorage.getItem(TICKETS_KEY));
}

// Save tickets to localStorage
function saveTickets(tickets) {
    localStorage.setItem(TICKETS_KEY, JSON.stringify(tickets));
}

// Function to create a new ticket
function createNewTicket(ticketData) {
    const tickets = getTickets();
    tickets.push(ticketData);
    saveTickets(tickets);
    
    // Show notification
    if ('Notification' in window && Notification.permission === 'granted') {
        new Notification('New Ticket Created', {
            body: `Ticket "${ticketData.title}" has been created.`,
            icon: '/icons/icon-192x192.png'
        });
    }
    
    // Refresh ticket display if on tickets page
    if (window.location.pathname.includes('tickets.html') || 
        window.location.pathname.includes('index.html')) {
        loadTickets();
    }
}

// Function to render tickets
function loadTickets(filters = {}) {
    const container = document.querySelector('.tickets-container') || 
                     document.querySelector('.grid.grid-cols-1');
    
    if (!container) return;
    
    container.innerHTML = '';
    
    const tickets = getTickets();
    let filteredTickets = [...tickets];
    
    // Apply filters
    if (filters.status) {
        filteredTickets = filteredTickets.filter(t => t.status === filters.status);
    }
    if (filters.priority) {
        filteredTickets = filteredTickets.filter(t => t.priority === filters.priority);
    }
    if (filters.assigned) {
        filteredTickets = filteredTickets.filter(t => t.assigned === filters.assigned);
    }
    if (filters.date) {
        const now = new Date();
        filteredTickets = filteredTickets.filter(t => {
            const ticketDate = new Date(t.date);
            switch(filters.date) {
                case 'today':
                    return ticketDate.toDateString() === now.toDateString();
                case 'week':
                    const weekStart = new Date(now);
                    weekStart.setDate(now.getDate() - now.getDay());
                    return ticketDate >= weekStart;
                case 'month':
                    return ticketDate.getMonth() === now.getMonth() && 
                           ticketDate.getFullYear() === now.getFullYear();
                default:
                    return true;
            }
        });
    }
    
    filteredTickets.forEach(ticket => {
        const card = document.createElement('custom-ticket-card');
        card.setAttribute('title', ticket.title);
        card.setAttribute('status', ticket.status);
        card.setAttribute('priority', ticket.priority);
        card.setAttribute('assigned', ticket.assigned);
        card.setAttribute('date', ticket.date);
        card.innerHTML = ticket.description;
        container.appendChild(card);
    });
    
    feather.replace();
}

// Initialize the ticket filters
function initTicketFilters() {
    const filterElement = document.querySelector('ticket-filters');
    if (!filterElement) return;
    
    filterElement.shadowRoot.querySelector('.apply').addEventListener('click', () => {
        const filters = {
            status: filterElement.shadowRoot.querySelector('#status').value,
            priority: filterElement.shadowRoot.querySelector('#priority').value,
            assigned: filterElement.shadowRoot.querySelector('#assigned').value,
            date: filterElement.shadowRoot.querySelector('#date').value
        };
        loadTickets(filters);
    });
    
    filterElement.shadowRoot.querySelector('.reset').addEventListener('click', () => {
        filterElement.shadowRoot.querySelectorAll('select').forEach(select => {
            select.value = '';
        });
        loadTickets();
    });
}

// Initialize charts for reports page
function initCharts() {
    if (!window.location.pathname.includes('reports.html')) return;
    
    const tickets = getTickets();
    
    // Status Chart
    const statusCounts = {
        open: 0,
        'in-progress': 0,
        resolved: 0
    };
    
    tickets.forEach(ticket => {
        statusCounts[ticket.status]++;
    });
    
    new Chart(document.getElementById('statusChart').getContext('2d'), {
        type: 'doughnut',
        data: {
            labels: ['Open', 'In Progress', 'Resolved'],
            datasets: [{
                data: [statusCounts.open, statusCounts['in-progress'], statusCounts.resolved],
                backgroundColor: ['#f59e0b', '#3b82f6', '#10b981']
            }]
        }
    });
    
    // Priority Chart
    const priorityCounts = {
        high: 0,
        medium: 0,
        low: 0
    };
    
    tickets.forEach(ticket => {
        priorityCounts[ticket.priority]++;
    });
    
    new Chart(document.getElementById('priorityChart').getContext('2d'), {
        type: 'pie',
        data: {
            labels: ['High', 'Medium', 'Low'],
            datasets: [{
                data: [priorityCounts.high, priorityCounts.medium, priorityCounts.low],
                backgroundColor: ['#ef4444', '#f97316', '#22c55e']
            }]
        }
    });
    
    // Timeline Chart - Group by month
    const monthlyCounts = {};
    tickets.forEach(ticket => {
        const date = new Date(ticket.date);
        const monthYear = `${date.getFullYear()}-${date.getMonth()}`;
        monthlyCounts[monthYear] = (monthlyCounts[monthYear] || 0) + 1;
    });
    
    const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    const currentYear = new Date().getFullYear();
    
    new Chart(document.getElementById('timelineChart').getContext('2d'), {
        type: 'line',
        data: {
            labels: months,
            datasets: [{
                label: 'Tickets Created',
                data: months.map((_, i) => {
                    const key = `${currentYear}-${i}`;
                    return monthlyCounts[key] || 0;
                }),
                borderColor: '#3b82f6',
                backgroundColor: 'rgba(59, 130, 246, 0.1)',
                fill: true,
                tension: 0.3
            }]
        },
        options: {
            responsive: true,
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });
}
// Function to export reports data as PDF
function exportReports() {
    const { jsPDF } = window.jspdf;
    const doc = new jsPDF();
    const tickets = getTickets();
    const date = new Date().toLocaleDateString();
    
    // Add title
    doc.setFontSize(20);
    doc.text('RapidAction - Reports Export', 15, 20);
// Add metadata
    doc.setFontSize(12);
    doc.text(`Generated on: ${date}`, 15, 30);
    doc.text(`Total Tickets: ${tickets.length}`, 15, 37);
    
    // Status report
    const statusCounts = {
        open: 0,
        'in-progress': 0,
        resolved: 0
    };
    
    tickets.forEach(ticket => {
        statusCounts[ticket.status]++;
    });
    
    doc.setFontSize(16);
    doc.text('Tickets by Status', 15, 55);
    doc.setFontSize(12);
    doc.text(`Open: ${statusCounts.open}`, 15, 65);
    doc.text(`In Progress: ${statusCounts['in-progress']}`, 15, 75);
    doc.text(`Resolved: ${statusCounts.resolved}`, 15, 85);
    
    // Priority report
    const priorityCounts = {
        high: 0,
        medium: 0,
        low: 0
    };
    
    tickets.forEach(ticket => {
        priorityCounts[ticket.priority]++;
    });
    
    doc.setFontSize(16);
    doc.text('Tickets by Priority', 15, 105);
    doc.setFontSize(12);
    doc.text(`High: ${priorityCounts.high}`, 15, 115);
    doc.text(`Medium: ${priorityCounts.medium}`, 15, 125);
    doc.text(`Low: ${priorityCounts.low}`, 15, 135);
    
    // Timeline data
    doc.setFontSize(16);
    doc.text('Monthly Ticket Activity', 15, 155);
    doc.setFontSize(12);
    
    const monthlyCounts = {};
    tickets.forEach(ticket => {
        const date = new Date(ticket.date);
        const monthYear = `${date.getFullYear()}-${date.getMonth()}`;
        monthlyCounts[monthYear] = (monthlyCounts[monthYear] || 0) + 1;
    });
    
    const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    const currentYear = new Date().getFullYear();
    let yPos = 165;
    
    months.forEach((month, i) => {
        const key = `${currentYear}-${i}`;
        const count = monthlyCounts[key] || 0;
        doc.text(`${month}: ${count}`, 15, yPos);
        yPos += 10;
    });
    
    // Save PDF
    doc.save(`bugtracker-reports-${date.replace(/\//g, '-')}.pdf`);
}

// Function to export project data as PDF
function exportProject() {
const { jsPDF } = window.jspdf;
    const doc = new jsPDF();
    const tickets = getTickets();
    const date = new Date().toLocaleDateString();
    
    // Add title
    doc.setFontSize(20);
    doc.text('RapidAction - Tickets Export', 15, 20);
// Add metadata
    doc.setFontSize(12);
    doc.text(`Generated on: ${date}`, 15, 30);
    doc.text(`Total Tickets: ${tickets.length}`, 15, 37);
    
    // Prepare table data
    const tableData = tickets.map(ticket => [
        ticket.title,
        ticket.status,
        ticket.priority,
        ticket.assigned,
        ticket.date,
        ticket.description.substring(0, 50) + '...'
    ]);
    
    // Add table
    doc.autoTable({
        head: [['Title', 'Status', 'Priority', 'Assigned', 'Date', 'Description']],
        body: tableData,
        startY: 45,
        theme: 'grid',
        headStyles: {
            fillColor: [79, 70, 229], // Purple color
            textColor: 255
        },
        columnStyles: {
            0: { cellWidth: 40 },
            1: { cellWidth: 20 },
            2: { cellWidth: 20 },
            3: { cellWidth: 25 },
            4: { cellWidth: 20 },
            5: { cellWidth: 'auto' }
        }
    });
    
    // Save PDF
    doc.save(`bugtracker-export-${date.replace(/\//g, '-')}.pdf`);
}
// Ticket creation modal
function showNewTicketModal() {
    const modal = document.createElement('div');
    modal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50';
    modal.innerHTML = `
        <div class="bg-white rounded-lg p-6 w-full max-w-md">
            <h2 class="text-xl font-bold mb-4">Create New Ticket</h2>
            <form id="ticketForm" class="space-y-4">
                <div>
                    <label for="ticketTitle" class="block text-sm font-medium text-gray-700">Title</label>
                    <input type="text" id="ticketTitle" required class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500">
                </div>
                <div>
                    <label for="ticketDescription" class="block text-sm font-medium text-gray-700">Description</label>
                    <textarea id="ticketDescription" rows="3" required class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"></textarea>
                </div>
                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <label for="ticketPriority" class="block text-sm font-medium text-gray-700">Priority</label>
                        <select id="ticketPriority" required class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500">
                            <option value="high">High</option>
                            <option value="medium" selected>Medium</option>
                            <option value="low">Low</option>
                        </select>
                    </div>
                    <div>
                        <label for="ticketAssignee" class="block text-sm font-medium text-gray-700">Assignee</label>
                        <select id="ticketAssignee" required class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500">
                            <option value="John D.">John D.</option>
                            <option value="Sarah K.">Sarah K.</option>
                            <option value="Mike T.">Mike T.</option>
                        </select>
                    </div>
                </div>
                <div class="flex justify-end space-x-3">
                    <button type="button" id="cancelTicket" class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50">Cancel</button>
                    <button type="submit" class="px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600">Create Ticket</button>
                </div>
            </form>
        </div>
    `;

    document.body.appendChild(modal);

    modal.querySelector('#cancelTicket').addEventListener('click', () => {
        document.body.removeChild(modal);
    });

    modal.querySelector('#ticketForm').addEventListener('submit', (e) => {
        e.preventDefault();
        const ticketData = {
            title: document.getElementById('ticketTitle').value,
            description: document.getElementById('ticketDescription').value,
            priority: document.getElementById('ticketPriority').value,
            assigned: document.getElementById('ticketAssignee').value,
            status: 'open',
            date: new Date().toISOString().split('T')[0]
        };
        createNewTicket(ticketData);
        document.body.removeChild(modal);
    });
}
// Initialize app when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
    initPWA();
    initTickets();
    
    // Export reports button event listener
    document.getElementById('exportReportsBtn')?.addEventListener('click', exportReports);
// Export button event listener
    document.getElementById('exportBtn')?.addEventListener('click', exportProject);
    
    // New ticket button event listener
    document.querySelectorAll('#newTicketBtn, button.bg-blue-500').forEach(btn => {
        if (btn.textContent.includes('New Ticket')) {
            btn.addEventListener('click', showNewTicketModal);
        }
    });
    
    // Load tickets on relevant pages
    if (window.location.pathname.includes('tickets.html') || 
        window.location.pathname.includes('index.html')) {
        loadTickets();
        initTicketFilters();
    }
    
    // Initialize charts on reports page
    if (window.location.pathname.includes('reports.html')) {
        initCharts();
    }
    
    // Initialize settings manager on settings page
    if (window.location.pathname.includes('settings.html')) {
        const settingsManager = new SettingsManager();
        settingsManager.loadSection('profile');
    }
});