-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathtools.ts
More file actions
1416 lines (1185 loc) · 61.5 KB
/
tools.ts
File metadata and controls
1416 lines (1185 loc) · 61.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
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
import { z } from 'zod';
import { KeepaClient } from './keepa-client.js';
import { KeepaDomain, KeepaDataType, ProductFinderResult, CategoryInsights, SalesVelocityData, InventoryAnalysis } from './types.js';
export const ProductLookupSchema = z.object({
asin: z.string().describe('Amazon ASIN (product identifier)'),
domain: z.number().min(1).max(11).default(1).describe('Amazon domain (1=US, 2=UK, 3=DE, etc.)'),
days: z.number().min(1).max(365).optional().describe('Number of days of price history to include'),
history: z.boolean().default(false).describe('Include full price history'),
offers: z.number().min(0).max(100).optional().describe('Number of marketplace offers to include'),
variations: z.boolean().default(false).describe('Include product variations'),
rating: z.boolean().default(false).describe('Include product rating data'),
});
export const BatchProductLookupSchema = z.object({
asins: z.array(z.string()).max(100).describe('Array of Amazon ASINs (max 100)'),
domain: z.number().min(1).max(11).default(1).describe('Amazon domain (1=US, 2=UK, 3=DE, etc.)'),
days: z.number().min(1).max(365).optional().describe('Number of days of price history to include'),
history: z.boolean().default(false).describe('Include full price history'),
});
export const DealSearchSchema = z.object({
domain: z.number().min(1).max(11).default(1).describe('Amazon domain (1=US, 2=UK, 3=DE, etc.)'),
categoryId: z.number().optional().describe('Amazon category ID to filter by'),
minPrice: z.number().min(0).optional().describe('Minimum price in cents'),
maxPrice: z.number().min(0).optional().describe('Maximum price in cents'),
minDiscount: z.number().min(0).max(100).optional().describe('Minimum discount percentage'),
minRating: z.number().min(1).max(5).optional().describe('Minimum product rating (1-5 stars)'),
isPrime: z.boolean().optional().describe('Filter for Prime eligible deals only'),
sortType: z.number().min(0).max(4).default(0).describe('Sort type (0=deal score, 1=price, 2=discount, 3=rating, 4=reviews)'),
page: z.number().min(0).default(0).describe('Page number for pagination'),
perPage: z.number().min(1).max(50).default(25).describe('Results per page (max 50)'),
});
export const SellerLookupSchema = z.object({
seller: z.string().describe('Seller ID or name'),
domain: z.number().min(1).max(11).default(1).describe('Amazon domain (1=US, 2=UK, 3=DE, etc.)'),
storefront: z.number().min(0).max(100000).optional().describe('Number of storefront ASINs to retrieve'),
});
export const BestSellersSchema = z.object({
domain: z.number().min(1).max(11).default(1).describe('Amazon domain (1=US, 2=UK, 3=DE, etc.)'),
category: z.number().describe('Amazon category ID'),
page: z.number().min(0).default(0).describe('Page number for pagination'),
});
export const PriceHistorySchema = z.object({
asin: z.string().describe('Amazon ASIN (product identifier)'),
domain: z.number().min(1).max(11).default(1).describe('Amazon domain (1=US, 2=UK, 3=DE, etc.)'),
dataType: z.number().min(0).max(30).describe('Data type (0=Amazon, 1=New, 2=Used, 3=Sales Rank, etc.)'),
days: z.number().min(1).max(365).default(30).describe('Number of days of history'),
});
export const ProductFinderSchema = z.object({
domain: z.number().min(1).max(11).default(1).describe('Amazon domain (1=US, 2=UK, 3=DE, etc.)'),
categoryId: z.number().optional().describe('Amazon category ID to search within'),
minRating: z.number().min(1).max(5).optional().describe('Minimum product rating (1-5 stars)'),
maxRating: z.number().min(1).max(5).optional().describe('Maximum product rating (1-5 stars)'),
minPrice: z.number().min(0).optional().describe('Minimum price in cents'),
maxPrice: z.number().min(0).optional().describe('Maximum price in cents'),
minShipping: z.number().min(0).optional().describe('Minimum shipping cost in cents'),
maxShipping: z.number().min(0).optional().describe('Maximum shipping cost in cents'),
minMonthlySales: z.number().min(0).optional().describe('Minimum estimated monthly sales'),
maxMonthlySales: z.number().min(0).optional().describe('Maximum estimated monthly sales'),
minSellerCount: z.number().min(0).optional().describe('Minimum number of sellers'),
maxSellerCount: z.number().min(0).optional().describe('Maximum number of sellers'),
sellerCountTimeframe: z.enum(['current', '30day', '90day', '180day', '365day']).default('90day').describe('Timeframe for seller count (current, 30day, 90day, 180day, 365day)'),
isPrime: z.boolean().optional().describe('Filter for Prime eligible products only'),
hasReviews: z.boolean().optional().describe('Filter for products with reviews only'),
productType: z.number().min(0).max(2).default(0).optional().describe('Product type (0=standard, 1=variation parent, 2=variation child)'),
sortBy: z.enum(['monthlySold', 'price', 'rating', 'reviewCount', 'salesRank']).default('monthlySold').describe('Sort results by field'),
sortOrder: z.enum(['asc', 'desc']).default('desc').describe('Sort order (ascending or descending)'),
page: z.number().min(0).default(0).describe('Page number for pagination'),
perPage: z.number().min(1).max(50).default(25).describe('Results per page (max 50)'),
});
export const CategoryAnalysisSchema = z.object({
domain: z.number().min(1).max(11).default(1).describe('Amazon domain (1=US, 2=UK, 3=DE, etc.)'),
categoryId: z.number().describe('Amazon category ID to analyze'),
analysisType: z.enum(['overview', 'top_performers', 'opportunities', 'trends']).default('overview').describe('Type of analysis to perform'),
priceRange: z.enum(['budget', 'mid', 'premium', 'luxury']).optional().describe('Focus on specific price range'),
minRating: z.number().min(1).max(5).default(3.0).describe('Minimum rating for products to include'),
includeSubcategories: z.boolean().default(false).describe('Include analysis of subcategories'),
timeframe: z.enum(['week', 'month', 'quarter', 'year']).default('month').describe('Timeframe for trend analysis'),
sellerCountTimeframe: z.enum(['current', '30day', '90day', '180day', '365day']).default('90day').describe('Timeframe for seller count analysis (current, 30day, 90day, 180day, 365day)'),
});
export const SalesVelocitySchema = z.object({
domain: z.number().min(1).max(11).default(1).describe('Amazon domain (1=US, 2=UK, 3=DE, etc.)'),
categoryId: z.number().optional().describe('Amazon category ID to filter by'),
asin: z.string().optional().describe('Single ASIN to analyze'),
asins: z.array(z.string()).max(50).optional().describe('Array of ASINs to analyze (max 50)'),
timeframe: z.enum(['week', 'month', 'quarter']).default('month').describe('Time period for velocity calculation'),
minVelocity: z.number().min(0).optional().describe('Minimum daily sales velocity'),
maxVelocity: z.number().min(0).optional().describe('Maximum daily sales velocity'),
minPrice: z.number().min(0).optional().describe('Minimum price in cents'),
maxPrice: z.number().min(0).optional().describe('Maximum price in cents'),
minRating: z.number().min(1).max(5).default(3.0).describe('Minimum product rating'),
sortBy: z.enum(['velocity', 'turnoverRate', 'revenueVelocity', 'trend']).default('velocity').describe('Sort results by metric'),
sortOrder: z.enum(['asc', 'desc']).default('desc').describe('Sort order'),
sellerCountTimeframe: z.enum(['current', '30day', '90day', '180day', '365day']).default('90day').describe('Timeframe for seller count analysis (current, 30day, 90day, 180day, 365day)'),
page: z.number().min(0).default(0).describe('Page number for pagination'),
perPage: z.number().min(1).max(50).default(25).describe('Results per page (max 50)'),
});
export const InventoryAnalysisSchema = z.object({
domain: z.number().min(1).max(11).default(1).describe('Amazon domain (1=US, 2=UK, 3=DE, etc.)'),
categoryId: z.number().optional().describe('Amazon category ID to analyze'),
asins: z.array(z.string()).max(100).optional().describe('Specific ASINs to analyze (your inventory)'),
analysisType: z.enum(['overview', 'fast_movers', 'slow_movers', 'stockout_risks', 'seasonal']).default('overview').describe('Type of inventory analysis'),
timeframe: z.enum(['week', 'month', 'quarter']).default('month').describe('Analysis timeframe'),
sellerCountTimeframe: z.enum(['current', '30day', '90day', '180day', '365day']).default('90day').describe('Timeframe for seller count analysis (current, 30day, 90day, 180day, 365day)'),
targetTurnoverRate: z.number().min(1).max(50).default(12).describe('Target inventory turns per year'),
});
export const TokenStatusSchema = z.object({});
export class KeepaTools {
constructor(private client: KeepaClient) {}
async lookupProduct(params: z.infer<typeof ProductLookupSchema>): Promise<string> {
try {
const product = await this.client.getProductByAsin(
params.asin,
params.domain as KeepaDomain,
{
days: params.days,
history: params.history,
offers: params.offers,
variations: params.variations,
rating: params.rating,
}
);
if (!product) {
return `Product not found for ASIN: ${params.asin}`;
}
const domain = params.domain as KeepaDomain;
const domainName = this.client.getDomainName(domain);
let result = `**Product Information for ${params.asin}**\n\n`;
result += `🏪 **Marketplace**: ${domainName}\n`;
result += `📦 **Title**: ${product.title || 'N/A'}\n`;
result += `🏷️ **Brand**: ${product.brand || 'N/A'}\n`;
result += `📊 **Category**: ${product.productGroup || 'N/A'}\n`;
if (product.stats) {
const currentPrice = product.stats.current[0];
if (currentPrice && currentPrice !== -1) {
result += `💰 **Current Price**: ${this.client.formatPrice(currentPrice, domain)}\n`;
}
const avgPrice = product.stats.avg[0];
if (avgPrice && avgPrice !== -1) {
result += `📈 **Average Price**: ${this.client.formatPrice(avgPrice, domain)}\n`;
}
if (product.stats.salesRankReference) {
result += `📊 **Sales Rank**: #${product.stats.salesRankReference.toLocaleString()}\n`;
}
}
if (params.rating && product.stats?.current[16]) {
const rating = product.stats.current[16] / 10;
const reviewCount = product.stats.current[17];
result += `⭐ **Rating**: ${rating.toFixed(1)}/5.0 (${reviewCount} reviews)\n`;
}
if (product.offers && product.offers.length > 0) {
result += `\n**Marketplace Offers**: ${product.offers.length} available\n`;
const topOffers = product.offers.slice(0, 3);
topOffers.forEach((offer, i) => {
result += `${i + 1}. ${offer.isAmazon ? '🟦 Amazon' : '🏪 3P Seller'} - `;
result += `${offer.isPrime ? '⚡ Prime' : 'Standard'} - `;
result += `${offer.isFBA ? 'FBA' : 'FBM'}\n`;
});
}
if (params.variations && product.variations && product.variations.length > 0) {
result += `\n**Variations**: ${product.variations.length} available\n`;
}
return result;
} catch (error) {
return `Error looking up product: ${error instanceof Error ? error.message : 'Unknown error'}`;
}
}
async batchLookupProducts(params: z.infer<typeof BatchProductLookupSchema>): Promise<string> {
try {
const products = await this.client.getProductsBatch(
params.asins,
params.domain as KeepaDomain,
{
days: params.days,
history: params.history,
}
);
const domain = params.domain as KeepaDomain;
const domainName = this.client.getDomainName(domain);
let result = `**Batch Product Lookup Results (${products.length}/${params.asins.length} found)**\n\n`;
result += `🏪 **Marketplace**: ${domainName}\n\n`;
products.forEach((product, i) => {
result += `**${i + 1}. ${product.asin}**\n`;
result += `📦 ${product.title || 'N/A'}\n`;
result += `🏷️ ${product.brand || 'N/A'}\n`;
if (product.stats?.current[0] && product.stats.current[0] !== -1) {
result += `💰 ${this.client.formatPrice(product.stats.current[0], domain)}\n`;
}
if (product.stats?.salesRankReference) {
result += `📊 Rank: #${product.stats.salesRankReference.toLocaleString()}\n`;
}
result += '\n';
});
const notFound = params.asins.filter(asin =>
!products.some(product => product.asin === asin)
);
if (notFound.length > 0) {
result += `**Not Found**: ${notFound.join(', ')}\n`;
}
return result;
} catch (error) {
return `Error in batch lookup: ${error instanceof Error ? error.message : 'Unknown error'}`;
}
}
async searchDeals(params: z.infer<typeof DealSearchSchema>): Promise<string> {
try {
const deals = await this.client.getDeals({
domainId: params.domain,
categoryId: params.categoryId,
minPrice: params.minPrice,
maxPrice: params.maxPrice,
minDiscount: params.minDiscount,
minRating: params.minRating,
isPrime: params.isPrime,
sortType: params.sortType,
page: params.page,
perPage: params.perPage,
});
if (deals.length === 0) {
return 'No deals found matching your criteria.';
}
const domain = params.domain as KeepaDomain;
const domainName = this.client.getDomainName(domain);
let result = `**Amazon Deals Found: ${deals.length}**\n\n`;
result += `🏪 **Marketplace**: ${domainName}\n\n`;
deals.forEach((deal, i) => {
result += `**${i + 1}. ${deal.asin}**\n`;
result += `📦 **${deal.title}**\n`;
result += `🏷️ Brand: ${deal.brand || 'N/A'}\n`;
result += `💰 **Price**: ${this.client.formatPrice(deal.price, domain)}`;
if (deal.shipping > 0) {
result += ` + ${this.client.formatPrice(deal.shipping, domain)} shipping`;
}
result += '\n';
result += `📊 **Discount**: ${deal.deltaPercent}% (${this.client.formatPrice(Math.abs(deal.delta), domain)} off)\n`;
result += `📈 **Avg Price**: ${this.client.formatPrice(deal.avgPrice, domain)}\n`;
result += `🏆 **Deal Score**: ${deal.dealScore}\n`;
if (deal.salesRank) {
result += `📊 **Sales Rank**: #${deal.salesRank.toLocaleString()}\n`;
}
if (deal.isLightningDeal) {
result += `⚡ **Lightning Deal**\n`;
}
if (deal.isPrimeExclusive) {
result += `🔥 **Prime Exclusive**\n`;
}
if (deal.coupon) {
result += `🎫 **Coupon**: ${deal.coupon}% additional discount\n`;
}
result += '\n';
});
return result;
} catch (error) {
return `Error searching deals: ${error instanceof Error ? error.message : 'Unknown error'}`;
}
}
async lookupSeller(params: z.infer<typeof SellerLookupSchema>): Promise<string> {
try {
const sellers = await this.client.getSeller({
seller: params.seller,
domain: params.domain,
storefront: params.storefront,
});
if (sellers.length === 0) {
return `Seller not found: ${params.seller}`;
}
const seller = sellers[0];
const domain = params.domain as KeepaDomain;
const domainName = this.client.getDomainName(domain);
let result = `**Seller Information**\n\n`;
result += `🏪 **Marketplace**: ${domainName}\n`;
result += `🏷️ **Seller ID**: ${seller.sellerId}\n`;
result += `📛 **Name**: ${seller.sellerName}\n`;
result += `⭐ **Rating**: ${seller.avgRating ? `${seller.avgRating}/5.0` : 'N/A'}\n`;
result += `📊 **Rating Count**: ${seller.ratingCount?.toLocaleString() || 'N/A'}\n`;
result += `🚩 **Scammer Status**: ${seller.isScammer ? '⚠️ Flagged as scammer' : '✅ Clean'}\n`;
result += `📦 **Amazon Seller**: ${seller.isAmazon ? 'Yes' : 'No'}\n`;
result += `🚚 **FBA Available**: ${seller.hasFBA ? 'Yes' : 'No'}\n`;
result += `📮 **FBM Available**: ${seller.hasFBM ? 'Yes' : 'No'}\n`;
if (seller.totalStorefrontAsins) {
result += `🏪 **Total Products**: ${seller.totalStorefrontAsins.toLocaleString()}\n`;
}
if (seller.startDate) {
const startDate = new Date(this.client.keepaTimeToUnixTime(seller.startDate));
result += `📅 **Started Selling**: ${startDate.toLocaleDateString()}\n`;
}
if (seller.storefront && seller.storefront.length > 0) {
result += `\n**Sample Storefront Products**: ${Math.min(5, seller.storefront.length)} shown\n`;
seller.storefront.slice(0, 5).forEach((asin, i) => {
result += `${i + 1}. ${asin}\n`;
});
if (seller.storefront.length > 5) {
result += `... and ${seller.storefront.length - 5} more\n`;
}
}
return result;
} catch (error) {
return `Error looking up seller: ${error instanceof Error ? error.message : 'Unknown error'}`;
}
}
async getBestSellers(params: z.infer<typeof BestSellersSchema>): Promise<string> {
try {
const bestSellers = await this.client.getBestSellers({
domain: params.domain,
category: params.category,
page: params.page,
});
if (bestSellers.length === 0) {
return `No best sellers found for category ${params.category}`;
}
const domain = params.domain as KeepaDomain;
const domainName = this.client.getDomainName(domain);
let result = `**Best Sellers - Category ${params.category}**\n\n`;
result += `🏪 **Marketplace**: ${domainName}\n`;
result += `📊 **Found**: ${bestSellers.length} products\n\n`;
bestSellers.forEach((product, i) => {
const rank = params.page * 100 + i + 1;
result += `**#${rank} - ${product.asin}**\n`;
result += `📦 **${product.title}**\n`;
result += `📊 **Sales Rank**: #${product.salesRank.toLocaleString()}\n`;
if (product.price) {
result += `💰 **Price**: ${this.client.formatPrice(product.price, domain)}\n`;
}
if (product.rating && product.reviewCount) {
result += `⭐ **Rating**: ${product.rating}/5.0 (${product.reviewCount.toLocaleString()} reviews)\n`;
}
result += `🚚 **Prime**: ${product.isPrime ? 'Yes' : 'No'}\n`;
result += '\n';
});
return result;
} catch (error) {
return `Error getting best sellers: ${error instanceof Error ? error.message : 'Unknown error'}`;
}
}
async getPriceHistory(params: z.infer<typeof PriceHistorySchema>): Promise<string> {
try {
const product = await this.client.getProductByAsin(
params.asin,
params.domain as KeepaDomain,
{
days: params.days,
history: true,
}
);
if (!product || !product.csv) {
return `No price history found for ASIN: ${params.asin}`;
}
const priceData = this.client.parseCSVData(product.csv, params.dataType);
if (priceData.length === 0) {
return `No data available for the specified data type (${params.dataType})`;
}
const domain = params.domain as KeepaDomain;
const domainName = this.client.getDomainName(domain);
const dataTypeNames: Record<number, string> = {
[KeepaDataType.AMAZON]: 'Amazon Price',
[KeepaDataType.NEW]: 'New Price',
[KeepaDataType.USED]: 'Used Price',
[KeepaDataType.SALES_RANK]: 'Sales Rank',
[KeepaDataType.RATING]: 'Rating',
[KeepaDataType.COUNT_REVIEWS]: 'Review Count',
};
const dataTypeName = dataTypeNames[params.dataType] || `Data Type ${params.dataType}`;
let result = `**Price History for ${params.asin}**\n\n`;
result += `🏪 **Marketplace**: ${domainName}\n`;
result += `📊 **Data Type**: ${dataTypeName}\n`;
result += `📅 **Period**: Last ${params.days} days\n`;
result += `📈 **Data Points**: ${priceData.length}\n\n`;
if (priceData.length > 0) {
const latest = priceData[priceData.length - 1];
const oldest = priceData[0];
result += `**Latest Value**: `;
if (params.dataType <= 2 || params.dataType === 18) {
result += `${this.client.formatPrice(latest.value, domain)}\n`;
} else {
result += `${latest.value.toLocaleString()}\n`;
}
result += `**Date**: ${new Date(latest.timestamp).toLocaleDateString()}\n\n`;
if (params.dataType <= 2 || params.dataType === 18) {
const prices = priceData.map(d => d.value).filter(v => v > 0);
if (prices.length > 0) {
const min = Math.min(...prices);
const max = Math.max(...prices);
const avg = prices.reduce((sum, price) => sum + price, 0) / prices.length;
result += `**Price Statistics**:\n`;
result += `• Minimum: ${this.client.formatPrice(min, domain)}\n`;
result += `• Maximum: ${this.client.formatPrice(max, domain)}\n`;
result += `• Average: ${this.client.formatPrice(Math.round(avg), domain)}\n\n`;
}
}
result += `**Recent History** (last 10 data points):\n`;
const recentData = priceData.slice(-10);
recentData.forEach((point, i) => {
const date = new Date(point.timestamp).toLocaleDateString();
let value: string;
if (params.dataType <= 2 || params.dataType === 18) {
value = this.client.formatPrice(point.value, domain);
} else {
value = point.value.toLocaleString();
}
result += `${recentData.length - i}. ${date}: ${value}\n`;
});
}
return result;
} catch (error) {
return `Error getting price history: ${error instanceof Error ? error.message : 'Unknown error'}`;
}
}
async findProducts(params: z.infer<typeof ProductFinderSchema>): Promise<string> {
try {
const domain = params.domain as KeepaDomain;
const domainName = this.client.getDomainName(domain);
let result = `**Amazon Product Finder Results**\n\n`;
result += `🏪 **Marketplace**: ${domainName}\n`;
result += `🔍 **Search Criteria**:\n`;
if (params.categoryId) {
result += `• Category: ${params.categoryId}\n`;
}
if (params.minRating || params.maxRating) {
const min = params.minRating || 1;
const max = params.maxRating || 5;
result += `• Rating: ${min}-${max} stars\n`;
}
if (params.minPrice || params.maxPrice) {
const min = params.minPrice ? this.client.formatPrice(params.minPrice, domain) : 'Any';
const max = params.maxPrice ? this.client.formatPrice(params.maxPrice, domain) : 'Any';
result += `• Price: ${min} - ${max}\n`;
}
if (params.minShipping || params.maxShipping) {
const min = params.minShipping ? this.client.formatPrice(params.minShipping, domain) : 'Any';
const max = params.maxShipping ? this.client.formatPrice(params.maxShipping, domain) : 'Any';
result += `• Shipping: ${min} - ${max}\n`;
}
if (params.minMonthlySales || params.maxMonthlySales) {
const min = params.minMonthlySales?.toLocaleString() || 'Any';
const max = params.maxMonthlySales?.toLocaleString() || 'Any';
result += `• Monthly Sales: ${min} - ${max}\n`;
}
if (params.minSellerCount || params.maxSellerCount) {
const min = params.minSellerCount || 'Any';
const max = params.maxSellerCount || 'Any';
const timeframeDesc = params.sellerCountTimeframe === '90day' ? '90-day average' :
params.sellerCountTimeframe === 'current' ? 'current' :
params.sellerCountTimeframe === '30day' ? '30-day average' :
params.sellerCountTimeframe === '180day' ? '180-day average' :
'365-day average';
result += `• Seller Count: ${min} - ${max} (${timeframeDesc})\n`;
}
if (params.isPrime !== undefined) {
result += `• Prime Only: ${params.isPrime ? 'Yes' : 'No'}\n`;
}
if (params.hasReviews !== undefined) {
result += `• Has Reviews: ${params.hasReviews ? 'Yes' : 'No'}\n`;
}
result += `• Sort: ${params.sortBy} (${params.sortOrder})\n\n`;
// Make real API call to Keepa
const products = await this.client.searchProducts(params);
if (products.length === 0) {
result += `❌ **No products found** matching your criteria.\n\n`;
result += `**Suggestions:**\n`;
result += `• Try widening your price range\n`;
result += `• Reduce minimum rating requirements\n`;
result += `• Remove category restrictions\n`;
result += `• Adjust monthly sales thresholds\n`;
return result;
}
result += `📊 **Found ${products.length} products** (Page ${params.page + 1}):\n\n`;
products.forEach((product: any, i: number) => {
const rank = params.page * params.perPage + i + 1;
const title = product.title || product.productTitle || 'Unknown Product';
const monthlySold = product.monthlySold || product.stats?.monthlySold || 0;
const rating = product.stats?.current_RATING ? product.stats.current_RATING / 10 : product.rating;
const reviewCount = product.stats?.current_COUNT_REVIEWS || product.reviewCount;
const price = product.stats?.current_AMAZON || product.price;
const shipping = product.stats?.current_BUY_BOX_SHIPPING || product.shipping;
const salesRank = product.stats?.current_SALES || product.salesRank;
const sellerInfo = this.client.getSellerCount(product, params.sellerCountTimeframe);
const sellerCount = sellerInfo.count;
// Determine competition level
let competition = 'Medium';
if (sellerCount <= 3) competition = 'Low';
else if (sellerCount >= 10) competition = 'High';
result += `**${rank}. ${product.asin}** ${competition === 'Low' ? '🟢' : competition === 'Medium' ? '🟡' : '🔴'}\n`;
result += `📦 **${title}**\n`;
if (product.brand) {
result += `🏷️ Brand: ${product.brand}\n`;
}
if (price && price > 0) {
result += `💰 **Price**: ${this.client.formatPrice(price, domain)}`;
if (shipping && shipping > 0) {
result += ` + ${this.client.formatPrice(shipping, domain)} shipping`;
}
result += '\n';
}
if (rating && reviewCount) {
result += `⭐ **Rating**: ${rating.toFixed(1)}/5.0 (${reviewCount.toLocaleString()} reviews)\n`;
}
if (monthlySold && monthlySold > 0) {
result += `📈 **Monthly Sales**: ~${monthlySold.toLocaleString()} units\n`;
}
if (salesRank) {
result += `📊 **Sales Rank**: #${salesRank.toLocaleString()}\n`;
}
result += `🏪 **Sellers**: ${sellerCount} (${sellerInfo.description})\n`;
if (product.isPrime) {
result += `⚡ **Prime Eligible**\n`;
}
// Calculate estimated profit margin
if (price && price > 1000) {
const estimatedMargin = Math.max(15, Math.min(40, 30 - (sellerCount * 2)));
result += `💹 **Est. Profit Margin**: ${estimatedMargin}%\n`;
}
result += `🎯 **Competition**: ${competition}\n\n`;
});
result += `**💡 Pro Tips:**\n`;
result += `• Green dots (🟢) indicate low competition opportunities\n`;
result += `• High monthly sales + low competition = potential goldmine\n`;
result += `• Check review velocity and listing quality before proceeding\n`;
result += `• Use price history tool for deeper market analysis\n`;
return result;
} catch (error) {
console.error('Product finder error:', error);
const errorMessage = error instanceof Error ? error.message :
typeof error === 'string' ? error :
JSON.stringify(error);
return `Error in product finder: ${errorMessage}`;
}
}
async analyzeCategory(params: z.infer<typeof CategoryAnalysisSchema>): Promise<string> {
try {
const domain = params.domain as KeepaDomain;
const domainName = this.client.getDomainName(domain);
let result = `**📊 Category Analysis Report**\n\n`;
result += `🏪 **Marketplace**: ${domainName}\n`;
result += `🏷️ **Category**: ID ${params.categoryId}\n`;
result += `📈 **Analysis Type**: ${params.analysisType.charAt(0).toUpperCase() + params.analysisType.slice(1).replace('_', ' ')}\n`;
result += `⏱️ **Timeframe**: ${params.timeframe}\n\n`;
// Get real data based on analysis type
switch (params.analysisType) {
case 'overview':
result += await this.getCategoryOverview(params, domain);
break;
case 'top_performers':
result += await this.getTopPerformers(params, domain);
break;
case 'opportunities':
result += await this.getOpportunities(params, domain);
break;
case 'trends':
result += await this.getTrends(params, domain);
break;
}
return result;
} catch (error) {
console.error('Category analysis error:', error);
const errorMessage = error instanceof Error ? error.message :
typeof error === 'string' ? error :
JSON.stringify(error);
return `Error analyzing category: ${errorMessage}`;
}
}
private async getCategoryOverview(params: z.infer<typeof CategoryAnalysisSchema>, domain: KeepaDomain): Promise<string> {
// Get best sellers for overview
const bestSellers = await this.client.getBestSellers({
domain: params.domain,
category: params.categoryId,
page: 0
});
// Get some products from the category using search
const categoryProducts = await this.client.searchProducts({
domain: params.domain,
categoryId: params.categoryId,
minRating: params.minRating,
perPage: 20,
sortBy: 'monthlySold'
});
let result = `**📈 Category Overview**\n\n`;
if (bestSellers.length > 0) {
result += `🏆 **Best Sellers**: ${bestSellers.length} products found\n`;
result += `💰 **Price Range**: ${this.client.formatPrice(
Math.min(...bestSellers.filter(p => p.price).map(p => p.price!)),
domain
)} - ${this.client.formatPrice(
Math.max(...bestSellers.filter(p => p.price).map(p => p.price!)),
domain
)}\n`;
}
if (categoryProducts.length > 0) {
const avgRating = categoryProducts
.filter(p => p.stats?.current_RATING)
.reduce((sum, p) => sum + (p.stats!.current_RATING! / 10), 0) / categoryProducts.length;
result += `⭐ **Average Rating**: ${avgRating.toFixed(1)}/5.0\n`;
result += `📊 **Sample Size**: ${categoryProducts.length} products analyzed\n\n`;
}
result += `**🎯 Market Insights:**\n`;
result += `• Category shows ${categoryProducts.length > 15 ? 'high' : categoryProducts.length > 8 ? 'moderate' : 'low'} product diversity\n`;
result += `• Competition level appears ${bestSellers.length > 50 ? 'high' : bestSellers.length > 20 ? 'moderate' : 'manageable'}\n`;
result += `• Price points span multiple market segments\n\n`;
return result;
}
private async getTopPerformers(params: z.infer<typeof CategoryAnalysisSchema>, domain: KeepaDomain): Promise<string> {
const topProducts = await this.client.searchProducts({
domain: params.domain,
categoryId: params.categoryId,
minRating: Math.max(4.0, params.minRating || 4.0),
sortBy: 'monthlySold',
sortOrder: 'desc',
perPage: 10
});
let result = `**🏆 Top Performers**\n\n`;
if (topProducts.length === 0) {
result += `❌ No top performers found in this category.\n\n`;
return result;
}
topProducts.forEach((product: any, i: number) => {
const title = product.title || product.productTitle || `Product ${product.asin}`;
const rating = product.stats?.current_RATING ? product.stats.current_RATING / 10 : 0;
const monthlySold = product.monthlySold || 0;
const price = product.stats?.current_AMAZON || 0;
result += `**${i + 1}. ${title.substring(0, 50)}${title.length > 50 ? '...' : ''}**\n`;
result += `📦 ASIN: ${product.asin}\n`;
if (rating > 0) result += `⭐ ${rating.toFixed(1)}/5.0\n`;
if (monthlySold > 0) result += `📈 ~${monthlySold.toLocaleString()} monthly sales\n`;
if (price > 0) result += `💰 ${this.client.formatPrice(price, domain)}\n`;
result += `\n`;
});
return result;
}
private async getOpportunities(params: z.infer<typeof CategoryAnalysisSchema>, domain: KeepaDomain): Promise<string> {
// Look for products with good ratings but low competition (few sellers)
const opportunities = await this.client.searchProducts({
domain: params.domain,
categoryId: params.categoryId,
minRating: 4.0,
maxSellerCount: 5, // Low competition
minMonthlySales: 500, // Decent sales
sortBy: 'monthlySold',
sortOrder: 'desc',
perPage: 15
});
let result = `**🎯 Market Opportunities**\n\n`;
if (opportunities.length === 0) {
result += `❌ No clear opportunities found with current criteria.\n`;
result += `💡 Try expanding search criteria or exploring subcategories.\n\n`;
return result;
}
result += `Found ${opportunities.length} potential opportunities with low competition:\n\n`;
opportunities.slice(0, 8).forEach((product: any, i: number) => {
const title = product.title || product.productTitle || `Product ${product.asin}`;
const rating = product.stats?.current_RATING ? product.stats.current_RATING / 10 : 0;
const sellerInfo = this.client.getSellerCount(product, params.sellerCountTimeframe);
const sellerCount = sellerInfo.count;
const monthlySold = product.monthlySold || 0;
result += `**${i + 1}. ${title.substring(0, 40)}${title.length > 40 ? '...' : ''}** 🟢\n`;
result += `📦 ${product.asin} | ⭐ ${rating.toFixed(1)} | 👥 ${sellerCount} sellers (${sellerInfo.description}) | 📈 ${monthlySold} monthly\n\n`;
});
result += `**💡 Opportunity Insights:**\n`;
result += `• Low seller count indicates less competition\n`;
result += `• Good ratings suggest market acceptance\n`;
result += `• Monthly sales show proven demand\n\n`;
return result;
}
private async getTrends(params: z.infer<typeof CategoryAnalysisSchema>, domain: KeepaDomain): Promise<string> {
// Get recent products and best sellers to analyze trends
const recentProducts = await this.client.searchProducts({
domain: params.domain,
categoryId: params.categoryId,
sortBy: 'monthlySold',
sortOrder: 'desc',
perPage: 20
});
let result = `**📊 Category Trends**\n\n`;
if (recentProducts.length === 0) {
result += `❌ Insufficient data for trend analysis.\n\n`;
return result;
}
// Analyze price trends
const prices = recentProducts
.filter(p => p.stats?.current_AMAZON && p.stats.current_AMAZON > 0)
.map(p => p.stats!.current_AMAZON!);
if (prices.length > 0) {
const avgPrice = prices.reduce((sum, price) => sum + price, 0) / prices.length;
const medianPrice = prices.sort((a, b) => a - b)[Math.floor(prices.length / 2)];
result += `**💰 Pricing Trends:**\n`;
result += `• Average Price: ${this.client.formatPrice(avgPrice, domain)}\n`;
result += `• Median Price: ${this.client.formatPrice(medianPrice, domain)}\n`;
result += `• Price Range: ${this.client.formatPrice(Math.min(...prices), domain)} - ${this.client.formatPrice(Math.max(...prices), domain)}\n\n`;
}
// Analyze rating trends
const ratings = recentProducts
.filter(p => p.stats?.current_RATING)
.map(p => p.stats!.current_RATING! / 10);
if (ratings.length > 0) {
const avgRating = ratings.reduce((sum, rating) => sum + rating, 0) / ratings.length;
const highRatedCount = ratings.filter(r => r >= 4.5).length;
result += `**⭐ Quality Trends:**\n`;
result += `• Average Rating: ${avgRating.toFixed(1)}/5.0\n`;
result += `• High-Rated Products (4.5+): ${highRatedCount}/${ratings.length} (${Math.round(highRatedCount/ratings.length*100)}%)\n\n`;
}
result += `**📈 Market Insights:**\n`;
result += `• Category appears ${ratings.length > 15 ? 'mature' : 'developing'} with ${recentProducts.length} active products\n`;
result += `• Quality standards are ${ratings.length > 0 && ratings.reduce((sum, r) => sum + r, 0) / ratings.length > 4.0 ? 'high' : 'moderate'}\n`;
result += `• Competition level suggests ${prices.length > 0 && prices.length > 10 ? 'saturated' : 'growing'} market\n\n`;
return result;
}
private generateRecommendations(params: z.infer<typeof CategoryAnalysisSchema>, insights: { competitionLevel: string; averagePrice: number; marketSaturation: number; opportunityScore: number }): string[] {
const recommendations = [];
if (insights.opportunityScore > 70) {
recommendations.push('🎯 High opportunity category - consider immediate entry with differentiated product');
} else if (insights.opportunityScore > 40) {
recommendations.push('⚖️ Moderate opportunity - focus on niche segments or product improvements');
} else {
recommendations.push('⚠️ Saturated market - only enter with significant competitive advantages');
}
if (insights.competitionLevel === 'Low') {
recommendations.push('🟢 Low competition detected - opportunity for premium positioning');
} else if (insights.competitionLevel === 'High') {
recommendations.push('🔴 High competition - focus on unique value propositions and cost optimization');
}
if (insights.averagePrice > 5000) {
recommendations.push('💰 Higher price point category - justify premium with quality and features');
} else {
recommendations.push('💸 Price-sensitive market - optimize for cost-effectiveness and value');
}
if (params.analysisType === 'opportunities') {
recommendations.push('🔍 Use Product Finder tool to identify specific low-competition products');
recommendations.push('📊 Analyze top performers for successful product patterns');
}
recommendations.push('📈 Monitor trends regularly to time market entry/exit decisions');
return recommendations;
}
async analyzeSalesVelocity(params: z.infer<typeof SalesVelocitySchema>): Promise<string> {
try {
const domain = params.domain as KeepaDomain;
const domainName = this.client.getDomainName(domain);
let result = `**🚀 Sales Velocity Analysis**\n\n`;
result += `🏪 **Marketplace**: ${domainName}\n`;
result += `⏱️ **Timeframe**: ${params.timeframe}\n`;
result += `📊 **Sort By**: ${params.sortBy} (${params.sortOrder})\n\n`;
// Get real sales velocity data from Keepa API
const velocityData = await this.getRealSalesVelocityData(params, domain);
if (velocityData.length === 0) {
result += `❌ **No products found** matching your velocity criteria.\n\n`;
result += `**Suggestions:**\n`;
result += `• Lower minimum velocity requirements\n`;
result += `• Expand price range filters\n`;
result += `• Try different category or remove category filter\n`;
return result;
}
result += `📈 **Found ${velocityData.length} products** with velocity data:\n\n`;
velocityData.forEach((product, i) => {
const rank = params.page * params.perPage + i + 1;
result += `**${rank}. ${product.asin}** ${this.getVelocityIndicator(product.salesVelocity.trend)}\n`;
result += `📦 **${product.title}**\n`;
result += `🏷️ Brand: ${product.brand || 'N/A'}\n`;
result += `💰 Price: ${this.client.formatPrice(product.price, domain)}\n\n`;
result += `**📊 Sales Velocity:**\n`;
result += `• Daily: ${product.salesVelocity.daily} units\n`;
result += `• Weekly: ${product.salesVelocity.weekly} units\n`;
result += `• Monthly: ${product.salesVelocity.monthly} units\n`;
result += `• Trend: ${product.salesVelocity.trend} (${product.salesVelocity.changePercent > 0 ? '+' : ''}${product.salesVelocity.changePercent}%)\n\n`;
result += `**📦 Inventory Metrics:**\n`;
result += `• Turnover Rate: ${product.inventoryMetrics.turnoverRate}x/month\n`;
result += `• Days of Inventory: ${product.inventoryMetrics.daysOfInventory} days\n`;
result += `• Stockout Risk: ${product.inventoryMetrics.stockoutRisk} ${this.getRiskEmoji(product.inventoryMetrics.stockoutRisk)}\n`;
result += `• Recommended Order: ${product.inventoryMetrics.recommendedOrderQuantity} units\n\n`;
result += `**💰 Revenue Metrics:**\n`;
result += `• Revenue Velocity: ${this.client.formatPrice(product.profitability.revenueVelocity * 100, domain)}/day\n`;
result += `• Est. Gross Margin: ${product.profitability.grossMarginEstimate}%\n`;
result += `• Profit Velocity: ${this.client.formatPrice(product.profitability.profitVelocity * 100, domain)}/day\n\n`;
result += `**📈 Market Info:**\n`;
result += `• Rating: ${product.marketMetrics.rating}/5.0 (${product.marketMetrics.reviewCount} reviews)\n`;
result += `• Sales Rank: #${product.marketMetrics.salesRank.toLocaleString()}\n`;
result += `• Competition: ${product.marketMetrics.competition}\n`;
result += `• Seasonality: ${product.marketMetrics.seasonality}\n`;
if (product.alerts.length > 0) {
result += `\n**⚠️ Alerts:**\n`;
product.alerts.forEach(alert => {
result += `• ${alert}\n`;
});
}
result += '\n---\n\n';
});
result += `**💡 Key Insights:**\n`;
const fastMovers = velocityData.filter(p => p.salesVelocity.monthly >= 30).length;
const slowMovers = velocityData.filter(p => p.salesVelocity.monthly < 10).length;
const highRisk = velocityData.filter(p => p.inventoryMetrics.stockoutRisk === 'High').length;
result += `• Fast Movers (>30/month): ${fastMovers} products\n`;
result += `• Slow Movers (<10/month): ${slowMovers} products\n`;
result += `• High Stockout Risk: ${highRisk} products\n`;
result += `• Average Turnover: ${(velocityData.reduce((sum, p) => sum + p.inventoryMetrics.turnoverRate, 0) / velocityData.length).toFixed(1)}x/month\n\n`;
result += `**🎯 Inventory Recommendations:**\n`;
result += `• Focus on products with >20 units/month for consistent cash flow\n`;
result += `• Avoid products with >30 days of inventory unless seasonal\n`;
result += `• Monitor high stockout risk products for reorder points\n`;
result += `• Consider increasing orders for accelerating trend products\n`;
return result;
} catch (error) {
return `Error analyzing sales velocity: ${error instanceof Error ? error.message : 'Unknown error'}`;
}
}
private async getRealSalesVelocityData(params: z.infer<typeof SalesVelocitySchema>, domain: KeepaDomain): Promise<SalesVelocityData[]> {
let products: any[] = [];
// If specific ASINs provided, get those products
if (params.asin) {
const product = await this.client.getProduct({
asin: params.asin,
domain: params.domain,
history: true,
rating: true
});
if (product.length > 0) products = product;
} else if (params.asins && params.asins.length > 0) {
products = await this.client.getProduct({
asins: params.asins,
domain: params.domain,
history: true,
rating: true
});
} else {
// Search for products in category with sales velocity criteria
const searchParams: any = {
domain: params.domain,
sortBy: 'monthlySold',
sortOrder: params.sortOrder,
perPage: params.perPage,
page: params.page
};
if (params.categoryId) searchParams.categoryId = params.categoryId;
if (params.minPrice) searchParams.minPrice = params.minPrice;
if (params.maxPrice) searchParams.maxPrice = params.maxPrice;
if (params.minRating) searchParams.minRating = params.minRating;