-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path09-cli-tool.ts
More file actions
677 lines (585 loc) · 19.4 KB
/
Copy path09-cli-tool.ts
File metadata and controls
677 lines (585 loc) · 19.4 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
#!/usr/bin/env node
/**
* 🖥️ CLI Tool Example
*
* This example demonstrates building a command-line interface for azubiheft-api:
* - Interactive CLI with commands and subcommands
* - Configuration management
* - Progress indicators and user feedback
* - Input validation and error handling
* - Batch operations and automation
* - Help system and documentation
*/
import {
Session,
Entry,
EntryType,
TimeHelper,
isAuthError,
isNotLoggedInError
} from '../src/index.js';
interface CLIConfig {
username?: string;
password?: string;
baseUrl?: string;
defaultDuration?: string;
autoLogin?: boolean;
}
interface Command {
name: string;
description: string;
usage: string;
handler: (args: string[], config: CLIConfig) => Promise<void>;
examples?: string[];
}
class AzubiheftCLI {
private session: Session;
private config: CLIConfig = {};
private commands: Map<string, Command> = new Map();
constructor() {
this.session = new Session();
this.setupCommands();
this.loadConfig();
}
private setupCommands(): void {
const commands: Command[] = [
{
name: 'login',
description: 'Login to azubiheft.de',
usage: 'login [username] [password]',
handler: this.handleLogin.bind(this),
examples: [
'login myuser mypass',
'login # Interactive prompt'
]
},
{
name: 'logout',
description: 'Logout from azubiheft.de',
usage: 'logout',
handler: this.handleLogout.bind(this)
},
{
name: 'status',
description: 'Show login status and account info',
usage: 'status',
handler: this.handleStatus.bind(this)
},
{
name: 'add',
description: 'Add a new report entry',
usage: 'add <message> [duration] [type]',
handler: this.handleAdd.bind(this),
examples: [
'add "Worked on API development" 04:00 work',
'add "Attended programming class" 03:30 school',
'add "Code review session" # Uses default duration'
]
},
{
name: 'list',
description: 'List reports for a date',
usage: 'list [date]',
handler: this.handleList.bind(this),
examples: [
'list',
'list 2024-01-15',
'list today',
'list yesterday'
]
},
{
name: 'delete',
description: 'Delete reports for a date',
usage: 'delete [date] [entry_number]',
handler: this.handleDelete.bind(this),
examples: [
'delete # Delete all entries for today',
'delete 2024-01-15 # Delete all entries for specific date',
'delete today 1 # Delete first entry for today'
]
},
{
name: 'subjects',
description: 'Manage subjects',
usage: 'subjects [list|add|delete] [name|id]',
handler: this.handleSubjects.bind(this),
examples: [
'subjects list',
'subjects add "Web Development"',
'subjects delete 123'
]
},
{
name: 'week',
description: 'Show weekly summary',
usage: 'week [date]',
handler: this.handleWeek.bind(this),
examples: [
'week',
'week 2024-01-15'
]
},
{
name: 'export',
description: 'Export data to file',
usage: 'export <format> [filename] [date_range]',
handler: this.handleExport.bind(this),
examples: [
'export json reports.json',
'export csv data.csv last-week',
'export html report.html 2024-01-01:2024-01-31'
]
},
{
name: 'config',
description: 'Manage CLI configuration',
usage: 'config [get|set|list] [key] [value]',
handler: this.handleConfig.bind(this),
examples: [
'config list',
'config set defaultDuration 08:00',
'config get username'
]
},
{
name: 'help',
description: 'Show help information',
usage: 'help [command]',
handler: this.handleHelp.bind(this)
}
];
commands.forEach(cmd => this.commands.set(cmd.name, cmd));
}
async run(args: string[]): Promise<void> {
if (args.length === 0) {
this.showWelcome();
return;
}
const [commandName, ...commandArgs] = args;
const command = this.commands.get(commandName);
if (!command) {
console.error(`❌ Unknown command: ${commandName}`);
console.log('💡 Use "help" to see available commands');
process.exit(1);
}
try {
await command.handler(commandArgs, this.config);
} catch (error) {
console.error(`❌ Command failed: ${error.message}`);
if (isAuthError(error)) {
console.log('💡 Try logging in first with: login');
} else if (isNotLoggedInError(error)) {
console.log('💡 You need to login first: login');
}
process.exit(1);
}
}
private showWelcome(): void {
console.log(`
🚀 Azubiheft CLI Tool
Usage: azubiheft-cli <command> [options]
Quick Start:
azubiheft-cli login # Login to your account
azubiheft-cli add "Daily work" 08:00 # Add a report entry
azubiheft-cli list # Show today's entries
azubiheft-cli help # Show all commands
💡 Use "azubiheft-cli help <command>" for detailed help on any command.
`);
}
private async handleLogin(args: string[], config: CLIConfig): Promise<void> {
let username = args[0] || config.username;
let password = args[1] || config.password;
if (!username) {
username = await this.promptInput('Username: ');
}
if (!password) {
password = await this.promptInput('Password: ', true);
}
console.log('🔐 Logging in...');
try {
await this.session.login({ username, password });
console.log('✅ Login successful!');
// Save credentials if not provided via config
if (!config.username) {
this.config.username = username;
this.saveConfig();
}
} catch (error) {
if (isAuthError(error)) {
console.error('❌ Login failed: Invalid credentials');
} else {
throw error;
}
}
}
private async handleLogout(): Promise<void> {
await this.session.logout();
console.log('👋 Logged out successfully');
}
private async handleStatus(): Promise<void> {
const isLoggedIn = await this.session.isLoggedIn();
if (isLoggedIn) {
console.log('✅ Status: Logged in');
try {
const subjects = await this.session.getSubjects();
console.log(`📚 Available subjects: ${subjects.length}`);
const today = new Date();
const reports = await this.session.getReport(today);
console.log(`📋 Today's entries: ${reports.length}`);
} catch (error) {
console.log('⚠️ Could not fetch account details');
}
} else {
console.log('❌ Status: Not logged in');
console.log('💡 Use "login" command to authenticate');
}
}
private async handleAdd(args: string[], config: CLIConfig): Promise<void> {
if (args.length === 0) {
console.error('❌ Message is required');
console.log('Usage: add <message> [duration] [type]');
return;
}
const message = args[0];
const duration = args[1] || config.defaultDuration || '08:00';
const typeArg = args[2] || 'work';
// Parse entry type
const entryType = this.parseEntryType(typeArg);
console.log(`📝 Adding entry: "${message}" (${duration})`);
const entry = new Entry(new Date(), message, duration, entryType);
try {
entry.validate();
await this.session.writeReports([entry]);
console.log('✅ Entry added successfully!');
} catch (error) {
console.error(`❌ Failed to add entry: ${error.message}`);
}
}
private async handleList(args: string[]): Promise<void> {
const dateArg = args[0] || 'today';
const date = this.parseDate(dateArg);
console.log(`📋 Reports for ${date.toDateString()}:`);
try {
const reports = await this.session.getReport(date);
if (reports.length === 0) {
console.log('📭 No entries found');
return;
}
reports.forEach((report, index) => {
console.log(` ${index + 1}. [${report.type}] ${report.duration} - ${report.text.substring(0, 60)}${report.text.length > 60 ? '...' : ''}`);
});
// Calculate total time
const totalMinutes = reports.reduce((sum, report) => {
return sum + TimeHelper.timeStringToMinutes(report.duration);
}, 0);
console.log(`\n⏱️ Total time: ${TimeHelper.minutesToTimeString(totalMinutes)}`);
} catch (error) {
console.log('📭 No entries found for this date');
}
}
private async handleDelete(args: string[]): Promise<void> {
const dateArg = args[0] || 'today';
const entryNumber = args[1] ? parseInt(args[1]) : undefined;
const date = this.parseDate(dateArg);
if (entryNumber) {
console.log(`🗑️ Deleting entry #${entryNumber} for ${date.toDateString()}...`);
} else {
console.log(`🗑️ Deleting all entries for ${date.toDateString()}...`);
}
// Confirm deletion
const confirmed = await this.promptConfirm('Are you sure? (y/N): ');
if (!confirmed) {
console.log('❌ Deletion cancelled');
return;
}
try {
await this.session.deleteReport(date, entryNumber);
console.log('✅ Entries deleted successfully!');
} catch (error) {
console.error(`❌ Failed to delete: ${error.message}`);
}
}
private async handleSubjects(args: string[]): Promise<void> {
const action = args[0] || 'list';
switch (action) {
case 'list':
await this.listSubjects();
break;
case 'add':
if (!args[1]) {
console.error('❌ Subject name is required');
return;
}
await this.addSubject(args[1]);
break;
case 'delete':
if (!args[1]) {
console.error('❌ Subject ID is required');
return;
}
await this.deleteSubject(args[1]);
break;
default:
console.error(`❌ Unknown subjects action: ${action}`);
console.log('Available actions: list, add, delete');
}
}
private async listSubjects(): Promise<void> {
console.log('📚 Available subjects:');
try {
const subjects = await this.session.getSubjects();
subjects.forEach(subject => {
const isBuiltIn = parseInt(subject.id) <= 7;
console.log(` ${isBuiltIn ? '🔧' : '⭐'} ${subject.name} (ID: ${subject.id})`);
});
} catch (error) {
console.error(`❌ Failed to fetch subjects: ${error.message}`);
}
}
private async addSubject(name: string): Promise<void> {
console.log(`➕ Adding subject: "${name}"`);
try {
await this.session.addSubject(name);
console.log('✅ Subject added successfully!');
} catch (error) {
console.error(`❌ Failed to add subject: ${error.message}`);
}
}
private async deleteSubject(id: string): Promise<void> {
console.log(`🗑️ Deleting subject ID: ${id}`);
const confirmed = await this.promptConfirm('Are you sure? (y/N): ');
if (!confirmed) {
console.log('❌ Deletion cancelled');
return;
}
try {
await this.session.deleteSubject(id);
console.log('✅ Subject deleted successfully!');
} catch (error) {
console.error(`❌ Failed to delete subject: ${error.message}`);
}
}
private async handleWeek(args: string[]): Promise<void> {
const dateArg = args[0] || 'today';
const date = this.parseDate(dateArg);
const weekInfo = TimeHelper.getISOWeek(date);
console.log(`📅 Weekly summary for Week ${weekInfo.week}/${weekInfo.year}:`);
// This is a simplified implementation
// In a full CLI, you'd implement proper weekly aggregation
console.log('⚠️ Full weekly summary feature not implemented in this example');
console.log('💡 This would show aggregated data for the entire week');
}
private async handleExport(args: string[]): Promise<void> {
if (args.length === 0) {
console.error('❌ Export format is required');
console.log('Available formats: json, csv, html, markdown');
return;
}
const format = args[0];
const filename = args[1] || `azubiheft-export.${format}`;
console.log(`📤 Exporting data in ${format.toUpperCase()} format...`);
console.log('⚠️ Export feature not fully implemented in this example');
console.log(`💡 Would export to: ${filename}`);
}
private async handleConfig(args: string[]): Promise<void> {
const action = args[0] || 'list';
switch (action) {
case 'list':
console.log('⚙️ Current configuration:');
Object.entries(this.config).forEach(([key, value]) => {
const displayValue = key === 'password' ? '*'.repeat(8) : value;
console.log(` ${key}: ${displayValue}`);
});
break;
case 'get':
if (!args[1]) {
console.error('❌ Config key is required');
return;
}
const value = this.config[args[1] as keyof CLIConfig];
console.log(`${args[1]}: ${value || 'not set'}`);
break;
case 'set':
if (!args[1] || !args[2]) {
console.error('❌ Config key and value are required');
return;
}
(this.config as any)[args[1]] = args[2];
this.saveConfig();
console.log(`✅ Set ${args[1]} = ${args[2]}`);
break;
default:
console.error(`❌ Unknown config action: ${action}`);
}
}
private async handleHelp(args: string[]): Promise<void> {
if (args.length === 0) {
this.showAllCommands();
} else {
this.showCommandHelp(args[0]);
}
}
private showAllCommands(): void {
console.log('🚀 Azubiheft CLI Commands:\n');
this.commands.forEach(command => {
console.log(`📋 ${command.name.padEnd(12)} ${command.description}`);
console.log(` Usage: azubiheft-cli ${command.usage}\n`);
});
console.log('💡 Use "help <command>" for detailed information about a specific command.');
}
private showCommandHelp(commandName: string): void {
const command = this.commands.get(commandName);
if (!command) {
console.error(`❌ Unknown command: ${commandName}`);
return;
}
console.log(`📋 Command: ${command.name}`);
console.log(`📄 Description: ${command.description}`);
console.log(`💻 Usage: azubiheft-cli ${command.usage}`);
if (command.examples && command.examples.length > 0) {
console.log('\n💡 Examples:');
command.examples.forEach(example => {
console.log(` azubiheft-cli ${example}`);
});
}
}
private parseEntryType(typeArg: string): EntryType {
const typeMap: Record<string, EntryType> = {
'work': EntryType.BETRIEB,
'company': EntryType.BETRIEB,
'betrieb': EntryType.BETRIEB,
'school': EntryType.SCHULE,
'schule': EntryType.SCHULE,
'uba': EntryType.UBA,
'vacation': EntryType.URLAUB,
'urlaub': EntryType.URLAUB,
'holiday': EntryType.FEIERTAG,
'feiertag': EntryType.FEIERTAG,
'sick': EntryType.ARBEITSUNFAHIG,
'krank': EntryType.ARBEITSUNFAHIG,
'free': EntryType.FREI,
'frei': EntryType.FREI
};
return typeMap[typeArg.toLowerCase()] || EntryType.BETRIEB;
}
private parseDate(dateArg: string): Date {
const today = new Date();
switch (dateArg.toLowerCase()) {
case 'today':
return today;
case 'yesterday':
const yesterday = new Date(today);
yesterday.setDate(today.getDate() - 1);
return yesterday;
case 'tomorrow':
const tomorrow = new Date(today);
tomorrow.setDate(today.getDate() + 1);
return tomorrow;
default:
// Try to parse as ISO date
const parsed = new Date(dateArg);
if (isNaN(parsed.getTime())) {
throw new Error(`Invalid date format: ${dateArg}`);
}
return parsed;
}
}
private async promptInput(prompt: string, isPassword = false): Promise<string> {
// In a real CLI, you'd use a proper input library like 'inquirer' or 'prompts'
// This is a simplified version for the example
process.stdout.write(prompt);
return new Promise((resolve) => {
const stdin = process.stdin;
stdin.setRawMode(true);
stdin.resume();
stdin.setEncoding('utf8');
let input = '';
const onData = (char: string) => {
if (char === '\r' || char === '\n') {
stdin.setRawMode(false);
stdin.pause();
stdin.removeListener('data', onData);
console.log();
resolve(input);
} else if (char === '\u0003') { // Ctrl+C
process.exit();
} else if (char === '\u007f') { // Backspace
if (input.length > 0) {
input = input.slice(0, -1);
process.stdout.write('\b \b');
}
} else {
input += char;
process.stdout.write(isPassword ? '*' : char);
}
};
stdin.on('data', onData);
});
}
private async promptConfirm(prompt: string): Promise<boolean> {
const response = await this.promptInput(prompt);
return response.toLowerCase() === 'y' || response.toLowerCase() === 'yes';
}
private loadConfig(): void {
// In a real CLI, you'd load from ~/.azubiheft-cli or similar
this.config = {
defaultDuration: '08:00',
autoLogin: false
};
}
private saveConfig(): void {
// In a real CLI, you'd save to ~/.azubiheft-cli or similar
console.log('💾 Configuration saved');
}
}
// Example CLI runner
async function cliToolExample() {
console.log('🖥️ Azubiheft CLI Tool Example\n');
console.log('This example demonstrates how to build a CLI tool for azubiheft-api.');
console.log('In a real implementation, you would:');
console.log('');
console.log('1. Install CLI dependencies:');
console.log(' npm install commander inquirer chalk ora');
console.log('');
console.log('2. Add CLI binary to package.json:');
console.log(' "bin": { "azubiheft-cli": "./dist/cli.js" }');
console.log('');
console.log('3. Build and link for local testing:');
console.log(' npm run build && npm link');
console.log('');
console.log('4. Use the CLI globally:');
console.log(' azubiheft-cli login');
console.log(' azubiheft-cli add "Daily work" 08:00');
console.log(' azubiheft-cli list');
console.log('');
// Simulate CLI usage
const cli = new AzubiheftCLI();
console.log('🎭 Simulating CLI commands:\n');
console.log('$ azubiheft-cli help');
await cli.run(['help']);
console.log('\n$ azubiheft-cli help add');
await cli.run(['help', 'add']);
console.log('\n💡 To test with real credentials, modify the example or run:');
console.log(' node examples/09-cli-tool.js login status');
}
// Export for use in other examples
export { AzubiheftCLI, CLIConfig };
// Run as CLI if called directly
if (import.meta.url === `file://${process.argv[1]}`) {
const args = process.argv.slice(2);
if (args.length > 0 && args[0] !== 'example') {
// Run as actual CLI
const cli = new AzubiheftCLI();
cli.run(args).catch(error => {
console.error('CLI error:', error);
process.exit(1);
});
} else {
// Run the example
cliToolExample().catch(error => {
console.error('💥 CLI tool example failed:', error);
process.exit(1);
});
}
}