metrics-strategies.ts 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import { RequestContext } from '@vendure/core';
  2. import { MetricData } from '../service/metrics.service.js';
  3. import { MetricInterval, MetricSummaryEntry, MetricType } from '../types.js';
  4. /**
  5. * Calculate your metric data based on the given input.
  6. * Be careful with heavy queries and calculations,
  7. * as this function is executed everytime a user views its dashboard
  8. *
  9. */
  10. export interface MetricCalculation {
  11. type: MetricType;
  12. getTitle(ctx: RequestContext): string;
  13. calculateEntry(ctx: RequestContext, interval: MetricInterval, data: MetricData): MetricSummaryEntry;
  14. }
  15. export function getMonthName(monthNr: number): string {
  16. const monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
  17. return monthNames[monthNr];
  18. }
  19. /**
  20. * Calculates the average order value per month/week
  21. */
  22. export class AverageOrderValueMetric implements MetricCalculation {
  23. readonly type = MetricType.AverageOrderValue;
  24. getTitle(ctx: RequestContext): string {
  25. return 'average-order-value';
  26. }
  27. calculateEntry(ctx: RequestContext, interval: MetricInterval, data: MetricData): MetricSummaryEntry {
  28. const label = data.date.toISOString();
  29. if (!data.orders.length) {
  30. return {
  31. label,
  32. value: 0,
  33. };
  34. }
  35. const total = data.orders.map(o => o.totalWithTax).reduce((_total, current) => _total + current);
  36. const average = Math.round(total / data.orders.length);
  37. return {
  38. label,
  39. value: average,
  40. };
  41. }
  42. }
  43. /**
  44. * Calculates number of orders
  45. */
  46. export class OrderCountMetric implements MetricCalculation {
  47. readonly type = MetricType.OrderCount;
  48. getTitle(ctx: RequestContext): string {
  49. return 'order-count';
  50. }
  51. calculateEntry(ctx: RequestContext, interval: MetricInterval, data: MetricData): MetricSummaryEntry {
  52. const label = data.date.toISOString();
  53. return {
  54. label,
  55. value: data.orders.length,
  56. };
  57. }
  58. }
  59. /**
  60. * Calculates order total
  61. */
  62. export class OrderTotalMetric implements MetricCalculation {
  63. readonly type = MetricType.OrderTotal;
  64. getTitle(ctx: RequestContext): string {
  65. return 'order-totals';
  66. }
  67. calculateEntry(ctx: RequestContext, interval: MetricInterval, data: MetricData): MetricSummaryEntry {
  68. const label = data.date.toISOString();
  69. return {
  70. label,
  71. value: data.orders.map(o => o.totalWithTax).reduce((_total, current) => _total + current, 0),
  72. };
  73. }
  74. }