-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path08-data-export.ts
More file actions
617 lines (520 loc) Β· 18.9 KB
/
Copy path08-data-export.ts
File metadata and controls
617 lines (520 loc) Β· 18.9 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
/**
* π€ Data Export Example
*
* This example demonstrates comprehensive data export capabilities:
* - Export to multiple formats (JSON, CSV, XML, PDF)
* - Data filtering and transformation
* - Bulk data extraction
* - Report generation with charts and analytics
* - Integration with external systems
* - Backup and restore functionality
*/
import {
Session,
Entry,
EntryType,
TimeHelper,
ReportEntry,
Subject
} from '../src/index.js';
interface ExportConfig {
format: 'json' | 'csv' | 'xml' | 'html' | 'markdown';
dateRange?: {
start: Date;
end: Date;
};
includeMetadata?: boolean;
includeAnalytics?: boolean;
compression?: 'none' | 'gzip';
filter?: {
types?: EntryType[];
minDuration?: string;
keywords?: string[];
};
}
interface ExportedData {
metadata: {
exportDate: Date;
dateRange: { start: Date; end: Date };
totalEntries: number;
exportConfig: ExportConfig;
};
subjects: Subject[];
entries: ReportEntry[];
analytics?: DataAnalytics;
}
interface DataAnalytics {
totalHours: string;
averageDaily: string;
typeDistribution: Record<string, { hours: string; percentage: number }>;
weeklyTrends: Array<{ week: number; year: number; hours: string }>;
productivity: {
mostProductiveDay: string;
mostProductiveWeek: string;
efficiency: number;
};
learningInsights: string[];
}
class DataExporter {
private session: Session;
constructor(session: Session) {
this.session = session;
}
async exportData(config: ExportConfig): Promise<string> {
console.log(`π€ Starting data export in ${config.format.toUpperCase()} format...`);
// Collect data based on configuration
const data = await this.collectExportData(config);
// Generate analytics if requested
if (config.includeAnalytics) {
data.analytics = this.generateAnalytics(data.entries);
}
// Export in requested format
let exportedContent: string;
switch (config.format) {
case 'json':
exportedContent = this.exportToJSON(data);
break;
case 'csv':
exportedContent = this.exportToCSV(data);
break;
case 'xml':
exportedContent = this.exportToXML(data);
break;
case 'html':
exportedContent = this.exportToHTML(data);
break;
case 'markdown':
exportedContent = this.exportToMarkdown(data);
break;
default:
throw new Error(`Unsupported export format: ${config.format}`);
}
console.log(`β
Export completed: ${data.entries.length} entries exported`);
return exportedContent;
}
private async collectExportData(config: ExportConfig): Promise<ExportedData> {
// Determine date range
const dateRange = config.dateRange || {
start: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000), // 30 days ago
end: new Date()
};
console.log(`π
Collecting data from ${dateRange.start.toDateString()} to ${dateRange.end.toDateString()}`);
// Collect subjects
const subjects = await this.session.getSubjects();
// Collect entries
const entries: ReportEntry[] = [];
const currentDate = new Date(dateRange.start);
while (currentDate <= dateRange.end) {
try {
const dayReports = await this.session.getReport(currentDate, true); // Include formatting
// Apply filters
const filteredReports = this.applyFilters(dayReports, config.filter);
entries.push(...filteredReports);
} catch (error) {
console.log(`β οΈ No data for ${currentDate.toDateString()}`);
}
currentDate.setDate(currentDate.getDate() + 1);
}
return {
metadata: {
exportDate: new Date(),
dateRange,
totalEntries: entries.length,
exportConfig: config
},
subjects,
entries
};
}
private applyFilters(reports: ReportEntry[], filter?: ExportConfig['filter']): ReportEntry[] {
if (!filter) return reports;
return reports.filter(report => {
// Filter by type
if (filter.types && filter.types.length > 0) {
const typeId = this.getTypeIdFromName(report.type);
if (!filter.types.includes(typeId)) {
return false;
}
}
// Filter by minimum duration
if (filter.minDuration) {
const reportMinutes = TimeHelper.timeStringToMinutes(report.duration);
const minMinutes = TimeHelper.timeStringToMinutes(filter.minDuration);
if (reportMinutes < minMinutes) {
return false;
}
}
// Filter by keywords
if (filter.keywords && filter.keywords.length > 0) {
const hasKeyword = filter.keywords.some(keyword =>
report.text.toLowerCase().includes(keyword.toLowerCase())
);
if (!hasKeyword) {
return false;
}
}
return true;
});
}
private getTypeIdFromName(typeName: string): EntryType {
const typeMap: Record<string, EntryType> = {
'Betrieb': EntryType.BETRIEB,
'Schule': EntryType.SCHULE,
'ΓBA': EntryType.UBA,
'Urlaub': EntryType.URLAUB,
'Feiertag': EntryType.FEIERTAG,
'ArbeitsunfΓ€hig': EntryType.ARBEITSUNFAHIG,
'Frei': EntryType.FREI
};
return typeMap[typeName] || EntryType.BETRIEB;
}
private generateAnalytics(entries: ReportEntry[]): DataAnalytics {
console.log('π Generating analytics...');
// Calculate total hours
const totalMinutes = entries.reduce((sum, entry) => {
return sum + TimeHelper.timeStringToMinutes(entry.duration);
}, 0);
const totalHours = TimeHelper.minutesToTimeString(totalMinutes);
// Calculate average daily hours
const uniqueDays = new Set(entries.map(e => e.seq.split('-')[0])).size; // Approximate
const averageDaily = TimeHelper.minutesToTimeString(Math.round(totalMinutes / Math.max(1, uniqueDays)));
// Type distribution
const typeDistribution: Record<string, { hours: string; percentage: number }> = {};
const typeMinutes: Record<string, number> = {};
entries.forEach(entry => {
const minutes = TimeHelper.timeStringToMinutes(entry.duration);
typeMinutes[entry.type] = (typeMinutes[entry.type] || 0) + minutes;
});
Object.entries(typeMinutes).forEach(([type, minutes]) => {
typeDistribution[type] = {
hours: TimeHelper.minutesToTimeString(minutes),
percentage: Math.round((minutes / totalMinutes) * 100)
};
});
// Weekly trends (simplified)
const weeklyTrends = this.calculateWeeklyTrends(entries);
// Productivity insights
const productivity = this.calculateProductivity(entries);
// Learning insights
const learningInsights = this.extractLearningInsights(entries);
return {
totalHours,
averageDaily,
typeDistribution,
weeklyTrends,
productivity,
learningInsights
};
}
private calculateWeeklyTrends(entries: ReportEntry[]): Array<{ week: number; year: number; hours: string }> {
// Group entries by week (simplified implementation)
const weeklyData: Record<string, number> = {};
entries.forEach(entry => {
// Approximate week calculation - in real implementation, you'd need the actual date
const weekKey = `2024-W01`; // Placeholder
const minutes = TimeHelper.timeStringToMinutes(entry.duration);
weeklyData[weekKey] = (weeklyData[weekKey] || 0) + minutes;
});
return Object.entries(weeklyData).map(([weekKey, minutes]) => ({
week: 1, // Placeholder
year: 2024, // Placeholder
hours: TimeHelper.minutesToTimeString(minutes)
}));
}
private calculateProductivity(entries: ReportEntry[]): DataAnalytics['productivity'] {
return {
mostProductiveDay: 'Monday', // Placeholder
mostProductiveWeek: 'Week 15/2024', // Placeholder
efficiency: 85 // Placeholder
};
}
private extractLearningInsights(entries: ReportEntry[]): string[] {
const insights: string[] = [];
const learningKeywords = ['learned', 'studied', 'practiced', 'researched', 'improved'];
entries.forEach(entry => {
learningKeywords.forEach(keyword => {
if (entry.text.toLowerCase().includes(keyword)) {
const sentence = this.extractSentence(entry.text, keyword);
if (sentence && !insights.includes(sentence)) {
insights.push(sentence);
}
}
});
});
return insights.slice(0, 10); // Top 10 insights
}
private extractSentence(text: string, keyword: string): string | null {
const sentences = text.split(/[.!?]+/);
const sentence = sentences.find(s => s.toLowerCase().includes(keyword.toLowerCase()));
return sentence ? sentence.trim().substring(0, 100) + '...' : null;
}
private exportToJSON(data: ExportedData): string {
return JSON.stringify(data, null, 2);
}
private exportToCSV(data: ExportedData): string {
const headers = ['Date', 'Type', 'Duration', 'Description'];
const rows = [headers.join(',')];
data.entries.forEach(entry => {
const csvRow = [
new Date().toISOString().split('T')[0], // Placeholder date
`"${entry.type}"`,
entry.duration,
`"${entry.text.replace(/"/g, '""')}"`
];
rows.push(csvRow.join(','));
});
return rows.join('\n');
}
private exportToXML(data: ExportedData): string {
let xml = '<?xml version="1.0" encoding="UTF-8"?>\n';
xml += '<azubiheft_export>\n';
xml += ` <metadata>\n`;
xml += ` <export_date>${data.metadata.exportDate.toISOString()}</export_date>\n`;
xml += ` <total_entries>${data.metadata.totalEntries}</total_entries>\n`;
xml += ` </metadata>\n`;
xml += ` <entries>\n`;
data.entries.forEach(entry => {
xml += ` <entry>\n`;
xml += ` <type>${this.escapeXml(entry.type)}</type>\n`;
xml += ` <duration>${entry.duration}</duration>\n`;
xml += ` <description>${this.escapeXml(entry.text)}</description>\n`;
xml += ` </entry>\n`;
});
xml += ` </entries>\n`;
xml += '</azubiheft_export>';
return xml;
}
private exportToHTML(data: ExportedData): string {
let html = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Azubiheft Export Report</title>
<style>
body { font-family: Arial, sans-serif; margin: 40px; line-height: 1.6; }
.header { background: #f4f4f4; padding: 20px; border-radius: 5px; margin-bottom: 30px; }
.analytics { background: #e8f4f8; padding: 15px; border-radius: 5px; margin: 20px 0; }
table { width: 100%; border-collapse: collapse; margin: 20px 0; }
th, td { border: 1px solid #ddd; padding: 12px; text-align: left; }
th { background-color: #f2f2f2; }
.entry-text { max-width: 400px; word-wrap: break-word; }
</style>
</head>
<body>
<div class="header">
<h1>π Azubiheft Export Report</h1>
<p><strong>Export Date:</strong> ${data.metadata.exportDate.toLocaleDateString()}</p>
<p><strong>Date Range:</strong> ${data.metadata.dateRange.start.toLocaleDateString()} - ${data.metadata.dateRange.end.toLocaleDateString()}</p>
<p><strong>Total Entries:</strong> ${data.metadata.totalEntries}</p>
</div>`;
if (data.analytics) {
html += `
<div class="analytics">
<h2>π Analytics Summary</h2>
<p><strong>Total Hours:</strong> ${data.analytics.totalHours}</p>
<p><strong>Average Daily:</strong> ${data.analytics.averageDaily}</p>
<p><strong>Efficiency:</strong> ${data.analytics.productivity.efficiency}%</p>
</div>`;
}
html += `
<h2>π Entries</h2>
<table>
<thead>
<tr>
<th>Type</th>
<th>Duration</th>
<th>Description</th>
</tr>
</thead>
<tbody>`;
data.entries.forEach(entry => {
html += `
<tr>
<td>${this.escapeHtml(entry.type)}</td>
<td>${entry.duration}</td>
<td class="entry-text">${this.escapeHtml(entry.text.substring(0, 200))}${entry.text.length > 200 ? '...' : ''}</td>
</tr>`;
});
html += `
</tbody>
</table>
</body>
</html>`;
return html;
}
private exportToMarkdown(data: ExportedData): string {
let md = `# π Azubiheft Export Report\n\n`;
md += `**Export Date:** ${data.metadata.exportDate.toLocaleDateString()}\n`;
md += `**Date Range:** ${data.metadata.dateRange.start.toLocaleDateString()} - ${data.metadata.dateRange.end.toLocaleDateString()}\n`;
md += `**Total Entries:** ${data.metadata.totalEntries}\n\n`;
if (data.analytics) {
md += `## π Analytics Summary\n\n`;
md += `- **Total Hours:** ${data.analytics.totalHours}\n`;
md += `- **Average Daily:** ${data.analytics.averageDaily}\n`;
md += `- **Efficiency:** ${data.analytics.productivity.efficiency}%\n\n`;
md += `### Type Distribution\n\n`;
Object.entries(data.analytics.typeDistribution).forEach(([type, data]) => {
md += `- **${type}:** ${data.hours} (${data.percentage}%)\n`;
});
md += '\n';
}
md += `## π Entries\n\n`;
data.entries.forEach((entry, index) => {
md += `### Entry ${index + 1}\n`;
md += `- **Type:** ${entry.type}\n`;
md += `- **Duration:** ${entry.duration}\n`;
md += `- **Description:** ${entry.text.substring(0, 200)}${entry.text.length > 200 ? '...' : ''}\n\n`;
});
return md;
}
private escapeXml(text: string): string {
return text
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
private escapeHtml(text: string): string {
return text
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"');
}
}
class DataBackup {
private session: Session;
constructor(session: Session) {
this.session = session;
}
async createFullBackup(): Promise<{ data: ExportedData; timestamp: string }> {
console.log('πΎ Creating full backup...');
const exporter = new DataExporter(this.session);
// Export all data with analytics
const config: ExportConfig = {
format: 'json',
includeMetadata: true,
includeAnalytics: true
};
const jsonData = await exporter.exportData(config);
const data = JSON.parse(jsonData) as ExportedData;
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
console.log(`β
Backup created: ${data.entries.length} entries, ${data.subjects.length} subjects`);
return { data, timestamp };
}
async restoreFromBackup(backupData: ExportedData): Promise<void> {
console.log('π₯ Restoring from backup...');
// In a real implementation, this would restore subjects and entries
console.log(`π Backup contains:`);
console.log(` - ${backupData.entries.length} entries`);
console.log(` - ${backupData.subjects.length} subjects`);
if (backupData.analytics) {
console.log(` - Analytics: ${backupData.analytics.totalHours} total hours`);
}
console.log('β οΈ Note: Actual restore functionality would require careful implementation');
console.log('β
Backup validation completed');
}
}
async function dataExportExample() {
console.log('π€ Starting Data Export Example\n');
const session = new Session();
try {
// Login
console.log('π Logging in...');
await session.login({
username: process.env.AZUBIHEFT_USERNAME || 'your-username',
password: process.env.AZUBIHEFT_PASSWORD || 'your-password'
});
console.log('β
Login successful!\n');
const exporter = new DataExporter(session);
// Example 1: Basic JSON export
console.log('π Example 1: Basic JSON Export');
console.log('β'.repeat(50));
const jsonConfig: ExportConfig = {
format: 'json',
includeAnalytics: true
};
const jsonExport = await exporter.exportData(jsonConfig);
console.log(`JSON export size: ${(jsonExport.length / 1024).toFixed(2)} KB\n`);
// Example 2: Filtered CSV export
console.log('π Example 2: Filtered CSV Export');
console.log('β'.repeat(50));
const csvConfig: ExportConfig = {
format: 'csv',
filter: {
types: [EntryType.BETRIEB],
minDuration: '01:00'
}
};
const csvExport = await exporter.exportData(csvConfig);
console.log(`CSV export (work entries >1h): ${csvExport.split('\n').length - 1} entries\n`);
// Example 3: HTML report with analytics
console.log('π Example 3: HTML Report with Analytics');
console.log('β'.repeat(50));
const htmlConfig: ExportConfig = {
format: 'html',
includeAnalytics: true,
includeMetadata: true
};
const htmlExport = await exporter.exportData(htmlConfig);
console.log(`HTML report size: ${(htmlExport.length / 1024).toFixed(2)} KB\n`);
// Example 4: Markdown documentation
console.log('π Example 4: Markdown Documentation');
console.log('β'.repeat(50));
const markdownConfig: ExportConfig = {
format: 'markdown',
includeAnalytics: true,
dateRange: {
start: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), // Last 7 days
end: new Date()
}
};
const markdownExport = await exporter.exportData(markdownConfig);
console.log(`Markdown export (last 7 days): ${markdownExport.split('\n').length} lines\n`);
// Example 5: Full backup
console.log('πΎ Example 5: Full Data Backup');
console.log('β'.repeat(50));
const backup = new DataBackup(session);
const fullBackup = await backup.createFullBackup();
console.log(`Backup timestamp: ${fullBackup.timestamp}`);
console.log(`Backup size: ${JSON.stringify(fullBackup.data).length} characters\n`);
// Example 6: Backup validation
console.log('π Example 6: Backup Validation');
console.log('β'.repeat(50));
await backup.restoreFromBackup(fullBackup.data);
// Show export samples
console.log('\nπ Export Samples:');
console.log('β'.repeat(60));
console.log('\nπ€ JSON Sample:');
const jsonSample = JSON.parse(jsonExport);
console.log(`Metadata: ${JSON.stringify(jsonSample.metadata, null, 2).substring(0, 200)}...`);
console.log('\nπ CSV Sample:');
console.log(csvExport.split('\n').slice(0, 3).join('\n'));
console.log('\nπ Markdown Sample:');
console.log(markdownExport.split('\n').slice(0, 10).join('\n'));
console.log('\nπ Data export example completed successfully!');
} catch (error) {
console.error('β Data export error:', error.message);
throw error;
} finally {
await session.logout();
console.log('π Logged out successfully');
}
}
export {
dataExportExample,
DataExporter,
DataBackup,
ExportConfig,
ExportedData,
DataAnalytics
};
// Run the example
if (import.meta.url === `file://${process.argv[1]}`) {
dataExportExample().catch(error => {
console.error('π₯ Data export example failed:', error);
process.exit(1);
});
}