-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdata-parser.js
More file actions
740 lines (693 loc) · 25.5 KB
/
Copy pathdata-parser.js
File metadata and controls
740 lines (693 loc) · 25.5 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
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
/**
* AI-Driven Project Risk Manager - Data Parser Module
* Exposed globally as window.DataParser
*/
(function() {
'use strict';
// Private Helper: Date Normalizer to YYYY-MM-DD
function normalizeDateStr(val) {
if (!val) return null;
const str = String(val).trim();
if (!str) return null;
// If already in YYYY-MM-DD format
if (/^\d{4}-\d{2}-\d{2}$/.test(str)) {
return str;
}
// Try browser parsing
const parsed = new Date(str);
if (isNaN(parsed.getTime())) {
// Try parsing common formats like MM/DD/YYYY or DD/MM/YYYY
const slashParts = str.split('/');
if (slashParts.length === 3) {
let [p1, p2, p3] = slashParts.map(x => parseInt(x, 10));
if (p3 > 1000) { // e.g. Year at the end
let month = p1;
let day = p2;
let year = p3;
if (month > 0 && month <= 12 && day > 0 && day <= 31) {
return `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
}
}
}
return str; // return original if it can't be parsed/normalized
}
const y = parsed.getFullYear();
const m = String(parsed.getMonth() + 1).padStart(2, '0');
const d = String(parsed.getDate()).padStart(2, '0');
return `${y}-${m}-${d}`;
}
// Private Helper: Date validation
function isValidDate(dateStr) {
if (typeof dateStr !== 'string') return false;
const reg = /^\d{4}-\d{2}-\d{2}$/;
if (!reg.test(dateStr)) return false;
const d = new Date(dateStr);
return d instanceof Date && !isNaN(d.getTime());
}
// Column Mappings for CSV Parser (Case-Insensitive & Alias Tolerant)
const taskMappings = {
id: ['id', 'task id', 'task_id'],
name: ['name', 'task name', 'task_name', 'title'],
description: ['description', 'desc'],
startDate: ['startdate', 'start date', 'start_date'],
endDate: ['enddate', 'end date', 'end_date'],
plannedStartDate: ['plannedstartdate', 'planned start date', 'planned_start_date', 'plannedstart', 'planned start'],
plannedEndDate: ['plannedenddate', 'planned end date', 'planned_end_date', 'plannedend', 'planned end'],
duration: ['duration'],
percentComplete: ['percentcomplete', 'percent complete', '% complete', 'completion', 'progress'],
assignee: ['assignee', 'owner', 'resource'],
dependencies: ['dependencies', 'predecessors', 'depends on', 'dependency'],
priority: ['priority'],
status: ['status'],
milestone: ['milestone', 'is milestone', 'is_milestone'],
category: ['category', 'phase'],
estimatedEffort: ['estimatedeffort', 'estimated effort', 'planned effort', 'est effort', 'estimated_effort'],
actualEffort: ['actualeffort', 'actual effort', 'act effort', 'actual_effort'],
notes: ['notes', 'comment', 'comments']
};
const milestoneMappings = {
id: ['id', 'milestone id', 'milestone_id'],
name: ['name', 'milestone name', 'milestone_name', 'title'],
plannedDate: ['planneddate', 'planned date', 'planned_date', 'date'],
actualDate: ['actualdate', 'actual date', 'actual_date'],
status: ['status'],
dependentTasks: ['dependenttasks', 'dependent tasks', 'tasks', 'predecessors', 'dependent_tasks']
};
const logMappings = {
id: ['id', 'log id', 'log_id'],
date: ['date', 'log date', 'log_date'],
type: ['type', 'log type', 'log_type'],
severity: ['severity'],
message: ['message', 'log message', 'log_message', 'description'],
taskId: ['taskid', 'task id', 'task_id'],
author: ['author', 'user', 'logged by']
};
const statusReportMappings = {
id: ['id', 'report id', 'report_id'],
date: ['date', 'report date', 'report_date'],
period: ['period', 'reporting period'],
overallStatus: ['overallstatus', 'overall status', 'status'],
completedTasks: ['completedtasks', 'completed tasks', 'completed_tasks'],
risksIdentified: ['risksidentified', 'risks identified', 'risks_identified', 'risks'],
summary: ['summary', 'notes']
};
function mapHeaders(headers, mappings) {
const map = {};
headers.forEach((h, index) => {
const cleaned = h.toLowerCase().trim().replace(/[\s_-]+/g, '');
for (const [key, aliases] of Object.entries(mappings)) {
const aliasMatch = aliases.some(alias => alias.toLowerCase().replace(/[\s_-]+/g, '') === cleaned);
if (aliasMatch) {
map[key] = index;
break;
}
}
});
return map;
}
// Private Helper: Parse CSV text respecting quoted fields
function parseCSVLines(csvText, delimiter) {
const result = [];
let row = [];
let col = '';
let inQuotes = false;
let i = 0;
while (i < csvText.length) {
const char = csvText[i];
const nextChar = csvText[i + 1];
if (inQuotes) {
if (char === '"') {
if (nextChar === '"') {
col += '"';
i += 2;
} else {
inQuotes = false;
i++;
}
} else {
col += char;
i++;
}
} else {
if (char === '"') {
inQuotes = true;
i++;
} else if (char === delimiter) {
row.push(col.trim());
col = '';
i++;
} else if (char === '\r' || char === '\n') {
row.push(col.trim());
if (row.length > 0 && row.some(cell => cell !== '')) {
result.push(row);
}
row = [];
col = '';
if (char === '\r' && nextChar === '\n') {
i += 2;
} else {
i++;
}
} else {
col += char;
i++;
}
}
}
if (col !== '' || row.length > 0) {
row.push(col.trim());
if (row.length > 0 && row.some(cell => cell !== '')) {
result.push(row);
}
}
return result;
}
// Exposing API
window.DataParser = {
/**
* Parse CSV string into ProjectData format
* @param {string} csvString
* @param {string} dataType - 'tasks' | 'milestones' | 'logs' | 'statusReports'
* @returns {Object} ProjectData
*/
parseCSV(csvString, dataType = 'tasks') {
if (typeof csvString !== 'string') {
csvString = '';
}
// Auto-detect delimiter
const firstLine = csvString.split(/\r?\n/)[0] || '';
let delimiter = ',';
const commaCount = (firstLine.match(/,/g) || []).length;
const semiCount = (firstLine.match(/;/g) || []).length;
if (semiCount > commaCount) {
delimiter = ';';
}
const lines = parseCSVLines(csvString, delimiter);
if (lines.length === 0) {
return this.normalizeProject({});
}
const headers = lines[0];
const rows = lines.slice(1);
let mappings = taskMappings;
if (dataType === 'milestones') mappings = milestoneMappings;
else if (dataType === 'logs') mappings = logMappings;
else if (dataType === 'statusReports') mappings = statusReportMappings;
const headerMap = mapHeaders(headers, mappings);
const items = rows.map(row => {
const item = {};
for (const [key, idx] of Object.entries(headerMap)) {
let val = row[idx];
if (val === undefined || val === null) {
val = '';
}
// Format conversions
if (key === 'dependencies' || key === 'dependentTasks' || key === 'completedTasks') {
item[key] = val ? val.split(';').map(x => x.trim()).filter(Boolean) : [];
} else if (key === 'percentComplete' || key === 'risksIdentified') {
const parsed = parseInt(val, 10);
item[key] = isNaN(parsed) ? 0 : parsed;
} else if (key === 'milestone') {
item[key] = val.toLowerCase() === 'true' || val === '1' || val.toLowerCase() === 'yes' || val.toLowerCase() === 'y';
} else if (['estimatedEffort', 'actualEffort', 'duration', 'budget', 'actualSpend'].includes(key)) {
const parsed = parseFloat(val);
item[key] = isNaN(parsed) ? 0 : parsed;
} else {
item[key] = val;
}
}
return item;
});
const rawData = {};
rawData[dataType] = items;
return this.normalizeProject(rawData);
},
/**
* Parse JSON string into ProjectData format
* @param {string} jsonString
* @returns {Object} ProjectData
*/
parseJSON(jsonString) {
try {
const data = JSON.parse(jsonString);
return this.normalizeProject(data);
} catch (e) {
throw new Error('Invalid JSON format: ' + e.message);
}
},
/**
* Validate project data structure
* @param {Object} projectData
* @returns {Object} { valid: boolean, errors: string[] }
*/
validateProject(projectData) {
const errors = [];
if (!projectData || typeof projectData !== 'object') {
return { valid: false, errors: ['Project data must be a valid object.'] };
}
// Check main tasks
const tasks = projectData.tasks || [];
const taskIds = new Set(tasks.map(t => t.id).filter(Boolean));
tasks.forEach((task, idx) => {
const label = task.id ? `Task "${task.id}"` : `Task at index ${idx}`;
if (!task.id) errors.push(`${label} is missing an 'id'.`);
if (!task.name) errors.push(`${label} is missing a 'name'.`);
if (!('startDate' in task)) errors.push(`${label} is missing 'startDate' field.`);
if (!('endDate' in task)) errors.push(`${label} is missing 'endDate' field.`);
// Date validation
if (task.startDate && !isValidDate(task.startDate)) {
errors.push(`${label} has invalid 'startDate': "${task.startDate}". Must be ISO YYYY-MM-DD.`);
}
if (task.endDate && !isValidDate(task.endDate)) {
errors.push(`${label} has invalid 'endDate': "${task.endDate}". Must be ISO YYYY-MM-DD.`);
}
if (task.plannedStartDate && !isValidDate(task.plannedStartDate)) {
errors.push(`${label} has invalid 'plannedStartDate': "${task.plannedStartDate}". Must be ISO YYYY-MM-DD.`);
}
if (task.plannedEndDate && !isValidDate(task.plannedEndDate)) {
errors.push(`${label} has invalid 'plannedEndDate': "${task.plannedEndDate}". Must be ISO YYYY-MM-DD.`);
}
// Dependencies validation
const deps = task.dependencies || [];
if (!Array.isArray(deps)) {
errors.push(`${label} 'dependencies' must be an array.`);
} else {
deps.forEach(depId => {
if (!taskIds.has(depId)) {
errors.push(`${label} references non-existent dependency ID: "${depId}".`);
}
});
}
// percentComplete validation
if (typeof task.percentComplete !== 'number' || task.percentComplete < 0 || task.percentComplete > 100) {
errors.push(`${label} 'percentComplete' must be a number between 0 and 100.`);
}
// Priority and Status checks
const validPriorities = ['low', 'medium', 'high', 'critical'];
const validStatuses = ['not-started', 'in-progress', 'completed', 'delayed', 'at-risk'];
if (task.priority && !validPriorities.includes(task.priority)) {
errors.push(`${label} has invalid priority: "${task.priority}". Must be one of: ${validPriorities.join(', ')}.`);
}
if (task.status && !validStatuses.includes(task.status)) {
errors.push(`${label} has invalid status: "${task.status}". Must be one of: ${validStatuses.join(', ')}.`);
}
});
// Milestones validation
const milestones = projectData.milestones || [];
milestones.forEach((m, idx) => {
const label = m.id ? `Milestone "${m.id}"` : `Milestone at index ${idx}`;
if (!m.id) errors.push(`${label} is missing an 'id'.`);
if (!m.name) errors.push(`${label} is missing a 'name'.`);
if (!m.plannedDate) errors.push(`${label} is missing 'plannedDate'.`);
if (m.plannedDate && !isValidDate(m.plannedDate)) {
errors.push(`${label} has invalid 'plannedDate': "${m.plannedDate}".`);
}
if (m.actualDate && !isValidDate(m.actualDate)) {
errors.push(`${label} has invalid 'actualDate': "${m.actualDate}".`);
}
const mDeps = m.dependentTasks || [];
if (!Array.isArray(mDeps)) {
errors.push(`${label} 'dependentTasks' must be an array.`);
} else {
mDeps.forEach(depId => {
if (!taskIds.has(depId)) {
errors.push(`${label} references non-existent task ID in dependentTasks: "${depId}".`);
}
});
}
});
// Logs validation
const logs = projectData.logs || [];
logs.forEach((log, idx) => {
const label = log.id ? `Log "${log.id}"` : `Log at index ${idx}`;
if (!log.id) errors.push(`${label} is missing 'id'.`);
if (!log.date) errors.push(`${label} is missing 'date'.`);
if (log.date && !isValidDate(log.date)) {
errors.push(`${label} has invalid 'date': "${log.date}".`);
}
const validLogTypes = ["risk", "issue", "change", "progress", "decision"];
if (log.type && !validLogTypes.includes(log.type)) {
errors.push(`${label} has invalid type: "${log.type}". Must be one of: ${validLogTypes.join(', ')}.`);
}
if (log.taskId && !taskIds.has(log.taskId)) {
errors.push(`${label} references non-existent taskId: "${log.taskId}".`);
}
});
// Status reports validation
const statusReports = projectData.statusReports || [];
statusReports.forEach((sr, idx) => {
const label = sr.id ? `Status Report "${sr.id}"` : `Status Report at index ${idx}`;
if (!sr.id) errors.push(`${label} is missing 'id'.`);
if (!sr.date) errors.push(`${label} is missing 'date'.`);
if (sr.date && !isValidDate(sr.date)) {
errors.push(`${label} has invalid 'date': "${sr.date}".`);
}
const completed = sr.completedTasks || [];
if (Array.isArray(completed)) {
completed.forEach(taskId => {
if (!taskIds.has(taskId)) {
errors.push(`${label} references non-existent task ID in completedTasks: "${taskId}".`);
}
});
}
});
return {
valid: errors.length === 0,
errors: errors
};
},
/**
* Normalize raw parsed data, filling default values and fixing formats
* @param {Object} rawData
* @returns {Object} Normalized ProjectData
*/
normalizeProject(rawData) {
const data = rawData || {};
const normalized = {
project: {
name: data.project?.name || "Cloud Migration Platform",
description: data.project?.description || "",
startDate: normalizeDateStr(data.project?.startDate) || "",
endDate: normalizeDateStr(data.project?.endDate) || "",
manager: data.project?.manager || "",
budget: parseFloat(data.project?.budget) || 0,
actualSpend: parseFloat(data.project?.actualSpend) || 0
},
tasks: [],
milestones: [],
logs: [],
statusReports: []
};
if (Array.isArray(data.tasks)) {
normalized.tasks = data.tasks.map(t => ({
id: t.id || "",
name: t.name || "",
description: t.description || "",
startDate: normalizeDateStr(t.startDate) || null,
endDate: normalizeDateStr(t.endDate) || null,
plannedStartDate: normalizeDateStr(t.plannedStartDate) || "",
plannedEndDate: normalizeDateStr(t.plannedEndDate) || "",
duration: parseInt(t.duration, 10) || 0,
percentComplete: parseInt(t.percentComplete, 10) || 0,
assignee: t.assignee || "",
dependencies: Array.isArray(t.dependencies) ? t.dependencies : [],
priority: t.priority || "medium",
status: t.status || "not-started",
milestone: typeof t.milestone === 'boolean' ? t.milestone : false,
category: t.category || "Planning",
estimatedEffort: parseFloat(t.estimatedEffort) || 0,
actualEffort: parseFloat(t.actualEffort) || 0,
notes: t.notes || ""
}));
}
if (Array.isArray(data.milestones)) {
normalized.milestones = data.milestones.map(m => ({
id: m.id || "",
name: m.name || "",
plannedDate: normalizeDateStr(m.plannedDate) || "",
actualDate: normalizeDateStr(m.actualDate) || null,
status: m.status || "not-started",
dependentTasks: Array.isArray(m.dependentTasks) ? m.dependentTasks : []
}));
}
if (Array.isArray(data.logs)) {
normalized.logs = data.logs.map(l => ({
id: l.id || "",
date: normalizeDateStr(l.date) || "",
type: l.type || "progress",
severity: l.severity || "low",
message: l.message || "",
taskId: l.taskId || "",
author: l.author || ""
}));
}
if (Array.isArray(data.statusReports)) {
normalized.statusReports = data.statusReports.map(sr => ({
id: sr.id || "",
date: normalizeDateStr(sr.date) || "",
period: sr.period || "",
overallStatus: sr.overallStatus || "on-track",
completedTasks: Array.isArray(sr.completedTasks) ? sr.completedTasks : [],
risksIdentified: parseInt(sr.risksIdentified, 10) || 0,
summary: sr.summary || ""
}));
}
return normalized;
},
/**
* Fetch and return sample-data.json relative to current URL context
* @returns {Promise<Object>} Normalized ProjectData
*/
async loadSampleData() {
try {
const response = await fetch('sample-data.json');
if (response.ok) {
const data = await response.json();
return this.normalizeProject(data);
}
} catch (e) {
console.warn('Could not fetch sample-data.json directly (likely CORS/file:// protocol). Loading offline fallback data.', e);
}
// Hardcoded fallback data for CORS/file:// offline use
const fallbackData = {
project: {
name: "Cloud Migration Platform (Offline Fallback)",
description: "Enterprise cloud migration and modernization initiative",
startDate: "2026-01-15",
endDate: "2026-08-30",
manager: "Sarah Chen",
budget: 2500000,
actualSpend: 1650000
},
tasks: [
{
id: "T-001",
name: "Requirements Gathering",
startDate: "2026-01-15",
endDate: "2026-02-15",
plannedStartDate: "2026-01-15",
plannedEndDate: "2026-02-10",
duration: 31,
percentComplete: 100,
assignee: "Sarah Chen",
dependencies: [],
priority: "high",
status: "completed",
milestone: false,
category: "Planning",
estimatedEffort: 240,
actualEffort: 280
},
{
id: "T-002",
name: "VPC and Subnet Setup",
startDate: "2026-02-16",
endDate: "2026-03-10",
plannedStartDate: "2026-02-16",
plannedEndDate: "2026-03-10",
duration: 22,
percentComplete: 100,
assignee: "Emma Davis",
dependencies: ["T-001"],
priority: "high",
status: "completed",
category: "Infrastructure",
estimatedEffort: 120,
actualEffort: 120
},
{
id: "T-003",
name: "Database Migration Setup",
startDate: "2026-03-11",
endDate: "2026-04-10",
plannedStartDate: "2026-03-11",
plannedEndDate: "2026-04-05",
duration: 30,
percentComplete: 75,
assignee: "Alex Rivera",
dependencies: ["T-002"],
priority: "critical",
status: "delayed",
category: "Development",
estimatedEffort: 160,
actualEffort: 220
},
{
id: "T-004",
name: "API Gateway Configuration",
startDate: "2026-03-15",
endDate: "2026-04-05",
plannedStartDate: "2026-03-12",
plannedEndDate: "2026-04-01",
duration: 21,
percentComplete: 40,
assignee: "Alex Rivera",
dependencies: ["T-002"],
priority: "high",
status: "at-risk",
category: "Development",
estimatedEffort: 80,
actualEffort: 110
},
{
id: "T-005",
name: "Auth Integration",
startDate: "2026-03-20",
endDate: "2026-04-15",
plannedStartDate: "2026-03-20",
plannedEndDate: "2026-04-15",
duration: 26,
percentComplete: 50,
assignee: "Alex Rivera",
dependencies: ["T-002"],
priority: "high",
status: "at-risk",
category: "Development",
estimatedEffort: 120,
actualEffort: 120
},
{
id: "T-006",
name: "User Acceptance Testing",
startDate: "2026-04-16",
endDate: "2026-05-15",
plannedStartDate: "2026-04-16",
plannedEndDate: "2026-05-15",
duration: 29,
percentComplete: 0,
assignee: "James Smith",
dependencies: ["T-003", "T-004", "T-005"],
priority: "medium",
status: "not-started",
category: "Testing",
estimatedEffort: 200,
actualEffort: 0
}
],
milestones: [
{
id: "M-001",
name: "Requirements Signoff",
plannedDate: "2026-02-15",
actualDate: "2026-02-15",
status: "completed",
dependentTasks: ["T-001"]
},
{
id: "M-002",
name: "Infrastructure Operational",
plannedDate: "2026-03-10",
actualDate: "2026-03-10",
status: "completed",
dependentTasks: ["T-002"]
},
{
id: "M-003",
name: "Testing Complete",
plannedDate: "2026-05-15",
actualDate: null,
status: "not-started",
dependentTasks: ["T-006"]
}
],
logs: [
{
id: "L-001",
date: "2026-03-15",
type: "risk",
severity: "high",
message: "Database replication connectivity drops",
taskId: "T-003",
author: "Alex Rivera"
},
{
id: "L-002",
date: "2026-03-25",
type: "issue",
severity: "high",
message: "IAM group configuration sync delay",
taskId: "T-002",
author: "Emma Davis"
}
],
statusReports: [
{
id: "SR-001",
date: "2026-02-28",
period: "February 2026",
overallStatus: "on-track",
completedTasks: ["T-001"],
risksIdentified: 1,
summary: "Requirements and migration plan fully locked. Setting up VPC and security accounts."
},
{
id: "SR-002",
date: "2026-03-31",
period: "March 2026",
overallStatus: "warning",
completedTasks: ["T-002"],
risksIdentified: 3,
summary: "Infrastructure setup complete. Database setup and auth integration lagging due to Alex Rivera's bandwidth limits."
}
]
};
return this.normalizeProject(fallbackData);
},
/**
* Save project data to localStorage under key 'riskmanager_project'
* @param {Object} projectData
*/
saveToStorage(projectData) {
const normalized = this.normalizeProject(projectData);
try {
localStorage.setItem('riskmanager_project', JSON.stringify(normalized));
} catch (e) {
console.error('Failed to save to localStorage:', e);
}
},
/**
* Load project data from localStorage
* @returns {Object|null} ProjectData or null if not present
*/
loadFromStorage() {
try {
const dataStr = localStorage.getItem('riskmanager_project');
if (!dataStr) return null;
const data = JSON.parse(dataStr);
return this.normalizeProject(data);
} catch (e) {
console.error('Failed to parse stored project data:', e);
return null;
}
},
/**
* Clear stored project data from localStorage
*/
clearStorage() {
try {
localStorage.removeItem('riskmanager_project');
} catch (e) {
console.error('Failed to clear localStorage:', e);
}
},
/**
* Export project data as downloadable JSON file
* @param {Object} projectData
*/
exportProject(projectData) {
const normalized = this.normalizeProject(projectData);
const jsonStr = JSON.stringify(normalized, null, 2);
const blob = new Blob([jsonStr], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
const fileName = (normalized.project?.name || 'project')
.toLowerCase()
.replace(/[^a-z0-9]+/g, '_') + '_data.json';
a.download = fileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
};
})();