UNPKG

@pinelab/vendure-plugin-metrics

Version:

Vendure plugin measuring and visualizing e-commerce metrics

49 lines (48 loc) 1.75 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.UnitsSoldMetric = void 0; const graphql_1 = require("../ui/generated/graphql"); /** * Calculates the number of products sold per month. * calculates the sum of all items in an order if no variantIds are provided */ class UnitsSoldMetric { constructor() { this.metricType = graphql_1.AdvancedMetricType.Number; this.code = 'units-sold'; this.allowProductSelection = true; } getTitle(ctx) { return `Units sold`; } calculateDataPoints(ctx, orders, sessions, variants) { const lines = orders.map((order) => order.lines).flat(); // Return the nr of products sold if (!variants.length) { // Return total sum of quantities if no variantIds given const total = lines .map((line) => line.quantity) .reduce((total, current) => total + current, 0); return [ { legendLabel: 'Total of all variants', value: total, }, ]; } // Else calculate sum per variant const dataPoints = []; variants.forEach((variant) => { // Find order lines per variant id const linesForVariant = lines.filter((line) => line.productVariant.id === variant.id); // Sum of quantities for this variant const sum = linesForVariant.reduce((total, current) => total + current.quantity, 0); dataPoints.push({ legendLabel: variant.name, value: sum, }); }); return dataPoints; } } exports.UnitsSoldMetric = UnitsSoldMetric;