-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig-manager.js
More file actions
1447 lines (1278 loc) · 50.2 KB
/
config-manager.js
File metadata and controls
1447 lines (1278 loc) · 50.2 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
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const fs = require('fs').promises;
const path = require('path');
const readline = require('readline');
const { v4: uuidv4 } = require('uuid');
const usageStats = require('./usage-stats');
const axios = require('axios');
const { exec } = require('child_process');
const { promisify } = require('util');
const execAsync = promisify(exec);
require('dotenv').config();
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const question = (query) => new Promise((resolve) => rl.question(query, resolve));
const colors = {
reset: '\x1b[0m',
bright: '\x1b[1m',
dim: '\x1b[2m',
underscore: '\x1b[4m',
blink: '\x1b[5m',
reverse: '\x1b[7m',
hidden: '\x1b[8m',
fg: {
black: '\x1b[30m',
red: '\x1b[31m',
green: '\x1b[32m',
yellow: '\x1b[33m',
blue: '\x1b[34m',
magenta: '\x1b[35m',
cyan: '\x1b[36m',
white: '\x1b[37m',
crimson: '\x1b[38m'
},
bg: {
black: '\x1b[40m',
red: '\x1b[41m',
green: '\x1b[42m',
yellow: '\x1b[43m',
blue: '\x1b[44m',
magenta: '\x1b[45m',
cyan: '\x1b[46m',
white: '\x1b[47m',
crimson: '\x1b[48m'
}
};
function getTimestamp() {
const now = new Date();
return `[${now.toLocaleTimeString()}]`;
}
// Consolidate show functions into a single utility
const show = {
success: (message) => console.log(colors.fg.green + `${getTimestamp()} ${message}` + colors.reset),
error: (message) => console.log(colors.fg.red + `${getTimestamp()} ${message}` + colors.reset),
info: (message) => console.log(colors.fg.cyan + `${getTimestamp()} ${message}` + colors.reset)
};
async function loadConfig() {
try {
const configPath = path.join(__dirname, 'config.json');
try {
// Try to read the file
const data = await fs.readFile(configPath, 'utf8');
return JSON.parse(data);
} catch (error) {
if (error.code === 'ENOENT') {
// File doesn't exist, create default config
const defaultConfig = {
stores: [],
searches: [],
webhooks: [],
settings: {
defaultInterval: 5,
defaultWebhook: null
}
};
// Save default config
await fs.writeFile(configPath, JSON.stringify(defaultConfig, null, 2));
show.success('Created new config.json with default settings');
return defaultConfig;
}
throw error; // Re-throw if it's not a "file not found" error
}
} catch (error) {
show.error(`Error loading config.json: ${error.message}`);
process.exit(1);
}
}
async function saveConfig(config) {
try {
const configPath = path.join(__dirname, 'config.json');
await fs.writeFile(configPath, JSON.stringify(config, null, 4));
show.success('Configuration saved successfully!');
} catch (error) {
console.error('Error saving config:', error.message);
}
}
async function listWebhooks(config) {
console.log('\n' + colors.fg.yellow + `${getTimestamp()} === Webhooks ===` + colors.reset);
if (config.webhooks.length === 0) {
show.info('No webhooks configured');
return;
}
config.webhooks.forEach((webhook, index) => {
console.log(colors.fg.cyan + `\n${getTimestamp()} ${index + 1}. ${webhook.name}` + colors.reset);
console.log(` URL: ${webhook.url.substring(0, 30)}...`);
console.log(` ID: ${webhook.id}`);
if (webhook.id === config.defaultWebhookId) {
console.log(colors.fg.green + ' Status: Default' + colors.reset);
}
});
}
async function listStores(config) {
console.log('\n=== Stores ===');
if (config.stores.length === 0) {
console.log('No stores configured.');
return;
}
config.stores.forEach((store, index) => {
console.log(`${index + 1}. ${store.name || '(no name)'}${store.type ? ' [' + store.type + ']' : ''}`);
if (store.url) {
console.log(` URL: ${store.url}`);
}
if (store.storeId) {
console.log(` Store ID: ${store.storeId}`);
}
console.log(` Status: ${store.enabled ? 'Enabled' : 'Disabled'}`);
console.log(` Interval: ${store.interval || '(default)'} minutes`);
if (store.webhook || store.webhookId) {
console.log(` Webhook: ${store.webhook || store.webhookId}`);
}
console.log('---');
});
}
async function listSearches(config) {
console.log('\n=== Searches ===');
if (config.searches.length === 0) {
console.log('No searches configured.');
return;
}
config.searches.forEach((search, index) => {
console.log(`${index + 1}. ${search.name || '(no name)'}${search.type ? ' [' + search.type + ']' : ''}`);
if (search.url) {
console.log(` URL: ${search.url}`);
}
if (search.searchTerm) {
console.log(` Search Term: ${search.searchTerm}`);
}
if (search.categoryId) {
console.log(` Category ID: ${search.categoryId}`);
}
if (search.categoryPath) {
console.log(` Category Path: ${search.categoryPath}`);
}
console.log(` Status: ${search.enabled ? 'Enabled' : 'Disabled'}`);
console.log(` Interval: ${search.interval || '(default)'} minutes`);
if (search.webhook || search.webhookId) {
console.log(` Webhook: ${search.webhook || search.webhookId}`);
}
console.log('---');
});
}
// Helper function to extract store ID from URL
function extractStoreId(url) {
try {
// Remove any trailing slashes and get the last part of the URL
const cleanUrl = url.replace(/\/$/, '');
const storeId = cleanUrl.split('/').pop();
return storeId;
} catch (error) {
return null;
}
}
async function addStore() {
console.clear();
const config = await loadConfig();
console.log('\n=== Add New Store ===');
// Get store URL or ID
const storeInput = await question('Enter store URL or ID (e.g., https://www.ebay.ca/str/surplusbydesign or surplusbydesign): ');
if (!storeInput) {
console.log('Store URL/ID is required');
return;
}
// Get check interval
const intervalInput = await question('Enter check interval in minutes (default: 5): ');
let interval = intervalInput ? parseInt(intervalInput) : 5;
if (isNaN(interval) || interval < 1) {
console.log('Invalid interval. Using default of 5 minutes.');
interval = 5;
}
// Get webhook assignment
console.log('\nAvailable webhooks:');
config.webhooks.forEach((webhook, index) => {
console.log(`${index + 1}. ${webhook.name} (${webhook.url.substring(0, 30)}...)`);
});
const webhookChoice = await question('Choose webhook number (press Enter for default): ');
let webhookId = null;
if (webhookChoice) {
const webhookIndex = parseInt(webhookChoice) - 1;
if (webhookIndex >= 0 && webhookIndex < config.webhooks.length) {
webhookId = config.webhooks[webhookIndex].id;
}
}
// Add the store
const store = {
id: storeInput,
name: storeInput.split('/').pop().split('?')[0], // Extract name from URL or use ID
interval,
enabled: true,
webhookId
};
config.stores.push(store);
await saveConfig(config);
console.log('Store added successfully!');
}
async function addSearch() {
console.clear();
const config = await loadConfig();
console.log('\n=== Add New Search ===');
const name = await question('Enter search name: ');
const url = await question('Enter eBay search URL: ');
const interval = parseInt(await question('Enter check interval in minutes: '));
const enabled = (await question('Enable search? (y/n): ')).toLowerCase() === 'y';
// List available webhooks
console.log('\nAvailable webhooks:');
config.webhooks.forEach((webhook, index) => {
console.log(`${index + 1}. ${webhook.name}`);
});
const webhookIndex = parseInt(await question('Select webhook (number): ')) - 1;
if (webhookIndex < 0 || webhookIndex >= config.webhooks.length) {
console.error('Invalid webhook selection');
return;
}
const webhook = config.webhooks[webhookIndex].name;
config.searches.push({
name,
url,
interval,
enabled,
webhook
});
await saveConfig(config);
console.log('Search added successfully!');
}
async function deleteSearch() {
console.clear();
const config = await loadConfig();
console.log('\n=== Delete Search ===');
if (config.searches.length === 0) {
show.error('No searches configured');
return;
}
// Show all searches
console.log('\nConfigured searches:');
config.searches.forEach((search, index) => {
console.log(`${index + 1}. ${search.name} (${search.type})`);
console.log(` Term: ${search.searchTerm}`);
console.log(` Interval: ${search.interval} minutes`);
console.log(` Status: ${search.enabled ? 'Enabled' : 'Disabled'}`);
console.log(''); // Add blank line between searches
});
const searchNumber = await question('Enter search number to delete: ');
const searchIndex = parseInt(searchNumber) - 1;
if (isNaN(searchIndex) || searchIndex < 0 || searchIndex >= config.searches.length) {
show.error('Invalid search number');
return;
}
const search = config.searches[searchIndex];
const confirm = await question(`Are you sure you want to delete "${search.name}"? (y/n): `);
if (confirm.toLowerCase() === 'y') {
config.searches.splice(searchIndex, 1);
await saveConfig(config);
show.success('Search deleted successfully');
} else {
show.info('Deletion cancelled');
}
}
async function toggleStoreStatus(index) {
const config = await loadConfig();
const store = config.stores[index];
store.enabled = !store.enabled;
await saveConfig(config);
console.log(`Store "${store.name}" ${store.enabled ? 'enabled' : 'disabled'}.`);
}
async function toggleSearchStatus() {
console.clear();
const config = await loadConfig();
console.log('\n=== Toggle Search Status ===');
if (config.searches.length === 0) {
show.error('No searches configured');
return;
}
// Show all searches
console.log('\nConfigured searches:');
config.searches.forEach((search, index) => {
console.log(`${index + 1}. ${search.name} (${search.type})`);
console.log(` Term: ${search.searchTerm}`);
console.log(` Current Status: ${search.enabled ? 'Enabled' : 'Disabled'}`);
console.log(''); // Add blank line between searches
});
const searchNumber = await question('Enter search number to toggle: ');
const searchIndex = parseInt(searchNumber) - 1;
if (isNaN(searchIndex) || searchIndex < 0 || searchIndex >= config.searches.length) {
show.error('Invalid search number');
return;
}
const search = config.searches[searchIndex];
search.enabled = !search.enabled;
await saveConfig(config);
show.success(`Search "${search.name}" is now ${search.enabled ? 'enabled' : 'disabled'}`);
}
async function updateSearchInterval() {
console.clear();
const config = await loadConfig();
console.log('\n=== Update Check Interval ===');
if (config.searches.length === 0) {
show.error('No searches configured');
return;
}
// Show all searches
console.log('\nConfigured searches:');
config.searches.forEach((search, index) => {
console.log(`${index + 1}. ${search.name} (${search.type})`);
console.log(` Term: ${search.searchTerm}`);
console.log(` Current Interval: ${search.interval} minutes`);
console.log(''); // Add blank line between searches
});
const searchNumber = await question('Enter search number to update: ');
const searchIndex = parseInt(searchNumber) - 1;
if (isNaN(searchIndex) || searchIndex < 0 || searchIndex >= config.searches.length) {
show.error('Invalid search number');
return;
}
const search = config.searches[searchIndex];
const newInterval = await question(`Enter new check interval in minutes (current: ${search.interval}): `);
const interval = parseInt(newInterval);
if (!isNaN(interval) && interval > 0) {
search.interval = interval;
await saveConfig(config);
show.success(`Check interval updated to ${interval} minutes`);
} else {
show.error('Invalid interval. No changes made.');
}
}
async function updateSearchWebhook() {
console.clear();
const config = await loadConfig();
console.log('\n=== Update Webhook Assignment ===');
if (config.searches.length === 0) {
show.error('No searches configured');
return;
}
if (config.webhooks.length === 0) {
show.error('No webhooks configured');
return;
}
// Show all searches
console.log('\nConfigured searches:');
config.searches.forEach((search, index) => {
console.log(`${index + 1}. ${search.name} (${search.type})`);
console.log(` Term: ${search.searchTerm}`);
console.log(` Current Webhook: ${search.webhookId ? config.webhooks.find(w => w.id === search.webhookId)?.name || 'None' : 'None'}`);
console.log(''); // Add blank line between searches
});
const searchNumber = await question('Enter search number to update: ');
const searchIndex = parseInt(searchNumber) - 1;
if (isNaN(searchIndex) || searchIndex < 0 || searchIndex >= config.searches.length) {
show.error('Invalid search number');
return;
}
const search = config.searches[searchIndex];
// Show available webhooks
console.log('\nAvailable webhooks:');
config.webhooks.forEach((webhook, index) => {
console.log(`${index + 1}. ${webhook.name} (${webhook.url.substring(0, 30)}...)`);
});
console.log(`${config.webhooks.length + 1}. None (remove webhook)`);
const webhookChoice = await question('Choose webhook number: ');
const webhookIndex = parseInt(webhookChoice) - 1;
if (webhookIndex === config.webhooks.length) {
search.webhookId = null;
show.success('Webhook removed from search');
} else if (webhookIndex >= 0 && webhookIndex < config.webhooks.length) {
search.webhookId = config.webhooks[webhookIndex].id;
show.success(`Webhook "${config.webhooks[webhookIndex].name}" assigned to search`);
} else {
show.error('Invalid webhook choice. No changes made.');
return;
}
await saveConfig(config);
}
async function editWebhook(index) {
console.clear();
const config = await loadConfig();
const webhook = config.webhooks[index];
console.log('\n=== Edit Webhook ===');
console.log(`Current Name: ${webhook.name}`);
console.log(`Current URL: ${webhook.url}`);
const newName = await question('Enter new name (or press Enter to keep current): ');
const newUrl = await question('Enter new URL (or press Enter to keep current): ');
if (newName) {
if (config.webhooks.some(w => w.name === newName && w.id !== webhook.id)) {
console.log('A webhook with this name already exists.');
return;
}
webhook.name = newName;
}
if (newUrl) {
try {
new URL(newUrl);
webhook.url = newUrl;
} catch (e) {
console.log('Invalid URL format. Changes not saved.');
return;
}
}
await saveConfig(config);
console.log('Webhook updated successfully.');
}
async function addWebhook() {
console.clear();
const config = await loadConfig();
console.log('\n=== Add New Webhook ===');
const name = await question('Enter webhook name: ');
if (!name) {
console.log('Webhook name is required.');
return;
}
// Check if webhook name already exists
if (config.webhooks.some(w => w.name === name)) {
console.log('A webhook with this name already exists.');
return;
}
const url = await question('Enter Discord webhook URL: ');
if (!url) {
console.log('Webhook URL is required.');
return;
}
// Validate URL format
try {
new URL(url);
} catch (e) {
console.log('Invalid URL format. Please enter a valid Discord webhook URL.');
return;
}
// Add new webhook
config.webhooks.push({
name,
url,
id: uuidv4()
});
// Save configuration
await saveConfig(config);
console.log(`Webhook "${name}" added successfully.`);
}
async function deleteWebhook(index) {
const config = await loadConfig();
const webhook = config.webhooks[index];
const confirm = await question(`Are you sure you want to delete webhook "${webhook.name}"? (y/n): `);
if (confirm.toLowerCase() === 'y') {
config.webhooks.splice(index, 1);
await saveConfig(config);
console.log(`Webhook "${webhook.name}" deleted successfully.`);
} else {
console.log('Deletion cancelled.');
}
}
async function setDefaultWebhook(index) {
const config = await loadConfig();
const webhook = config.webhooks[index];
// Remove default status from all webhooks
config.webhooks.forEach(w => w.isDefault = false);
// Set the selected webhook as default
webhook.isDefault = true;
await saveConfig(config);
console.log(`Webhook "${webhook.name}" set as default.`);
}
async function editStore(index) {
console.clear();
const config = await loadConfig();
const store = config.stores[index];
console.log('\n=== Edit Store ===');
console.log(`Current Name: ${store.name}`);
console.log(`Current URL: ${store.url}`);
console.log(`Current Interval: ${store.interval} minutes`);
const newName = await question('Enter new name (or press Enter to keep current): ');
const newUrl = await question('Enter new URL (or press Enter to keep current): ');
const newInterval = await question('Enter new interval in minutes (or press Enter to keep current): ');
if (newName) store.name = newName;
if (newUrl) store.url = newUrl;
if (newInterval) {
const interval = parseInt(newInterval);
if (!isNaN(interval) && interval > 0) {
store.interval = interval;
}
}
await saveConfig(config);
console.log('Store updated successfully.');
}
async function editSearch() {
console.clear();
const config = await loadConfig();
console.log('\n=== Edit Search ===');
if (config.searches.length === 0) {
show.error('No searches configured');
return;
}
// Show all searches
console.log('\nConfigured searches:');
config.searches.forEach((search, index) => {
console.log(`${index + 1}. ${search.name} (${search.type})`);
console.log(` Term: ${search.searchTerm}`);
console.log(` Interval: ${search.interval} minutes`);
console.log(` Status: ${search.enabled ? 'Enabled' : 'Disabled'}`);
console.log(''); // Add blank line between searches
});
const searchNumber = await question('Enter search number to edit: ');
const searchIndex = parseInt(searchNumber) - 1;
if (isNaN(searchIndex) || searchIndex < 0 || searchIndex >= config.searches.length) {
show.error('Invalid search number');
return;
}
const search = config.searches[searchIndex];
console.log(`\nEditing search: ${search.name}`);
const newName = await question(`Enter new name (current: ${search.name}): `);
const newTerm = await question(`Enter new search term (current: ${search.searchTerm}): `);
const newInterval = await question(`Enter new check interval in minutes (current: ${search.interval}): `);
if (newName) search.name = newName;
if (newTerm) search.searchTerm = newTerm;
if (newInterval) {
const interval = parseInt(newInterval);
if (!isNaN(interval) && interval > 0) {
search.interval = interval;
} else {
show.error('Invalid interval. Keeping current value.');
}
}
await saveConfig(config);
show.success('Search updated successfully');
}
// Add new view mode functions
async function showWebhookView() {
console.clear();
const config = await loadConfig();
console.log('==========================================');
console.log('=== Webhooks ===');
config.webhooks.forEach((webhook, index) => {
console.log(`${index + 1}. ${webhook.name}`);
console.log(` URL: ${webhook.url}`);
console.log(` Status: ${webhook.isDefault ? 'Default' : 'Active'}`);
console.log('');
});
console.log('==========================================');
console.log('\nOptions:');
console.log('- Press Enter to return to main menu');
console.log('- Press number to select webhook');
console.log('- Press A to add new webhook');
const input = await question('\nEnter your choice: ');
if (input === '') {
return showMenu();
} else if (input.toLowerCase() === 'a') {
await addWebhook();
return showWebhookView();
} else {
const index = parseInt(input) - 1;
if (index >= 0 && index < config.webhooks.length) {
await showWebhookActions(index);
}
return showWebhookView();
}
}
async function showWebhookActions(index) {
const config = await loadConfig();
console.clear();
const webhook = config.webhooks[index];
console.log('==========================================');
console.log(`=== Webhook: ${webhook.name} ===`);
console.log(`URL: ${webhook.url}`);
console.log(`Status: ${webhook.isDefault ? 'Default' : 'Active'}`);
console.log('==========================================');
console.log('\nOptions:');
console.log('- Press E to edit webhook');
console.log('- Press D to delete webhook');
console.log('- Press S to set as default');
console.log('- Press B to go back');
const input = await question('\nEnter your choice: ');
switch(input.toLowerCase()) {
case 'e':
await editWebhook(index);
break;
case 'd':
await deleteWebhook(index);
break;
case 's':
await setDefaultWebhook(index);
break;
case 'b':
return;
}
}
async function showDataManagementView() {
console.clear();
console.log('==========================================');
console.log('=== Data Management ===');
console.log('1. View Daily Statistics');
console.log('2. View Monthly Statistics');
console.log('3. View Total Usage');
console.log('4. Clear Old Statistics');
console.log('==========================================');
console.log('\nOptions:');
console.log('- Press number to select option');
console.log('- Press Enter to return to main menu');
const input = await question('\nEnter your choice: ');
if (input === '') {
return showMenu();
}
switch(input) {
case '1':
await showDailyStats();
break;
case '2':
await showMonthlyStats();
break;
case '3':
await showTotalStats();
break;
case '4':
await clearOldStats();
break;
}
return showDataManagementView();
}
async function showDailyStats() {
console.clear();
console.log('==========================================');
console.log('=== Daily Statistics ===');
const today = new Date().toISOString().split('T')[0];
const stats = usageStats.getDailyStats(today);
console.log(`Date: ${today}`);
console.log(`Total Bytes: ${(stats.total_bytes / 1024 / 1024).toFixed(2)} MB`);
console.log(`Total Requests: ${stats.total_requests}`);
console.log(`Total Items: ${stats.total_items}`);
console.log('==========================================');
await question('\nPress Enter to continue...');
}
async function showMonthlyStats() {
console.clear();
console.log('==========================================');
console.log('=== Monthly Statistics ===');
const month = new Date().toISOString().substring(0, 7);
const stats = usageStats.getMonthlyStats(month);
console.log(`Month: ${month}`);
console.log(`Total Bytes: ${(stats.total_bytes / 1024 / 1024).toFixed(2)} MB`);
console.log(`Total Requests: ${stats.total_requests}`);
console.log(`Total Items: ${stats.total_items}`);
console.log('==========================================');
await question('\nPress Enter to continue...');
}
async function showTotalStats() {
console.clear();
console.log('==========================================');
console.log('=== Total Usage Statistics ===');
const stats = usageStats.getTotalStats();
console.log(`Total Bytes: ${(stats.total_bytes / 1024 / 1024).toFixed(2)} MB`);
console.log(`Total Requests: ${stats.total_requests}`);
console.log(`Total Items: ${stats.total_items}`);
console.log('==========================================');
await question('\nPress Enter to continue...');
}
async function clearOldStats() {
console.clear();
console.log('==========================================');
console.log('=== Clear Old Statistics ===');
const days = await question('Enter number of days to keep (default: 30): ');
const daysToKeep = parseInt(days) || 30;
usageStats.clearOldStats(daysToKeep);
console.log(`Cleared statistics older than ${daysToKeep} days`);
console.log('==========================================');
await question('\nPress Enter to continue...');
}
// Modify showMenu to include new view mode system
async function showMenu() {
console.clear();
console.log('=== eBay Scanner Configuration Manager ===');
console.log('1. Webhook Management');
console.log('2. Store Management');
console.log('3. Search Management');
console.log('4. Data Management');
console.log('5. Exit');
const choice = await question('\nEnter your choice: ');
switch (choice) {
case '1':
await showWebhookView();
break;
case '2':
await showStoreView();
break;
case '3':
await showSearchView();
break;
case '4':
await showDataManagementView();
break;
case '5':
console.log('Exiting configuration...');
return;
default:
console.log('Invalid choice. Please enter a number between 1 and 5.');
}
return showMenu();
}
async function showStoreView() {
console.clear();
const config = await loadConfig();
console.log('==========================================');
console.log('=== Stores ===');
config.stores.forEach((store, index) => {
console.log(`${index + 1}. ${store.name}`);
console.log(` URL: ${store.url}`);
console.log(` Status: ${store.enabled ? 'Enabled' : 'Disabled'}`);
console.log('');
});
console.log('==========================================');
console.log('\nOptions:');
console.log('- Press Enter to return to main menu');
console.log('- Press number to select store');
console.log('- Press A to add new store');
const input = await question('\nEnter your choice: ');
if (input === '') {
return showMenu();
} else if (input.toLowerCase() === 'a') {
await configureStore();
return showStoreView();
} else {
const index = parseInt(input) - 1;
if (index >= 0 && index < config.stores.length) {
await showStoreActions(index);
}
return showStoreView();
}
}
async function showSearchView() {
console.clear();
const config = await loadConfig();
while (true) {
console.log('\n=== Search Management ===');
console.log('1. List all searches');
console.log('2. Add new search (URL)');
// Only show API option if credentials are available
const hasApiCredentials = process.env.EBAY_APP_ID && process.env.EBAY_CERT_ID;
if (hasApiCredentials) {
console.log('3. Add new search (API)');
} else {
console.log('3. Add new search (API) - Requires eBay API credentials');
}
console.log('4. Edit search');
console.log('5. Delete search');
console.log('6. Toggle search status');
console.log('7. Update check interval');
console.log('8. Update webhook assignment');
console.log('9. Back to main menu');
const choice = await question('\nEnter your choice: ');
switch (choice) {
case '1':
await listSearches(config);
break;
case '2':
await addSearch();
break;
case '3':
if (hasApiCredentials) {
await configureApiSearch();
} else {
show.info('eBay API credentials not found. Please set EBAY_APP_ID and EBAY_CERT_ID in your .env file to use API features.');
show.info('You can still use URL-based searches without API credentials.');
}
break;
case '4':
await editSearch();
break;
case '5':
await deleteSearch();
break;
case '6':
await toggleSearchStatus();
break;
case '7':
await updateSearchInterval();
break;
case '8':
await updateSearchWebhook();
break;
case '9':
return;
default:
console.log('Invalid choice');
}
}
}
async function showStoreActions(index) {
const config = await loadConfig();
console.clear();
const store = config.stores[index];
console.log('==========================================');
console.log(`=== Store: ${store.name} ===`);
console.log(`URL: ${store.url}`);
console.log(`Status: ${store.enabled ? 'Enabled' : 'Disabled'}`);
console.log('==========================================');
console.log('\nOptions:');
console.log('- Press E to edit store');
console.log('- Press D to delete store');
console.log('- Press T to toggle status');
console.log('- Press B to go back');
const input = await question('\nEnter your choice: ');
switch(input.toLowerCase()) {
case 'e':
await editStore(index);
break;
case 'd':
await deleteStore(index);
break;
case 't':
await toggleStoreStatus(index);
break;
case 'b':
return;
}
}
async function lookupCategories(searchTerm) {
try {
// Get eBay token
const token = await getEbayToken();
if (!token) {
show.error('Failed to get eBay token');
return null;
}
// Get category tree ID for Canadian marketplace
const treeResponse = await axios.get(
'https://api.ebay.com/commerce/taxonomy/v1/get_default_category_tree_id',
{
params: { marketplace_id: 'EBAY_CA' },
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
}
);
const treeId = treeResponse.data.categoryTreeId;
if (!treeId) {
show.error('Failed to get category tree ID');
return null;
}
// Get category suggestions
show.info('Requesting category suggestions...');
const suggestionsResponse = await axios.get(
`https://api.ebay.com/commerce/taxonomy/v1/category_tree/${treeId}/get_category_suggestions`,
{
params: {
q: searchTerm,
limit: 10
},
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
}
);
const suggestions = suggestionsResponse.data.categorySuggestions;
if (!suggestions || !Array.isArray(suggestions) || suggestions.length === 0) {
show.info('No category suggestions found for this search term');
return null;
}
// Display category suggestions
console.log('\n=== Category Suggestions ===');
console.log('IMPORTANT: Selecting a category will ONLY show items from that specific category.');
console.log('For example, selecting "Cell Phones & Smartphones" will exclude accessories and parts.\n');
suggestions.forEach((suggestion, index) => {
if (suggestion && suggestion.category) {
const category = suggestion.category;