UNPKG

@pinelab/vendure-plugin-metrics

Version:

Vendure plugin measuring and visualizing e-commerce metrics

65 lines (64 loc) 2.34 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.RevenuePerProduct = void 0; const graphql_1 = require("../ui/generated/graphql"); /** * Calculates the revenue generated by each product variant. * calculates the total revenue if no variants are provided. */ class RevenuePerProduct { constructor() { this.metricType = graphql_1.AdvancedMetricType.Currency; this.code = 'revenue-per-product'; this.allowProductSelection = true; } getTitle(ctx) { return `Revenue`; } calculateDataPoints(ctx, orders, sessions, variants) { if (!variants.length) { // Return total revenue let legendLabel = 'Total Revenue'; if (ctx.channel.pricesIncludeTax) { legendLabel += ' (incl. tax)'; } else { legendLabel += ' (excl. tax)'; } const totalFieldName = ctx.channel.pricesIncludeTax ? 'totalWithTax' : 'total'; const totalRevenue = orders.reduce((total, current) => total + current[totalFieldName], 0); return [ { legendLabel, value: totalRevenue / 100, }, ]; } // Else calculate revenue per variant // Map orders to lines, but st the order object on each line const lines = orders .map((order) => { order.lines.forEach((l) => (l.order = order)); return order.lines; }) .flat(); const dataPoints = []; const totalFieldName = ctx.channel.pricesIncludeTax ? 'proratedLinePriceWithTax' : 'proratedLinePrice'; variants.forEach((variant) => { // Find order lines per variant id const linesForVariant = lines.filter((line) => line.productVariant.id === variant.id); // Sum of order lines with this variant const revenue = linesForVariant.reduce((total, current) => total + current[totalFieldName], 0); dataPoints.push({ legendLabel: variant.name, value: revenue / 100, }); }); return dataPoints; } } exports.RevenuePerProduct = RevenuePerProduct;