Skip to content

Count things month by month

Publish an Event for the thing you count. Add a Metric that counts the Event, with a Dimension that says what each count belongs to. Then read the Metric once for each month, with that month as the interval of the query.

In the pipeline App, move publishes won when a deal is won. wins counts those Events, and the Dimension handler returns the rep the deal points at:

pipeline.ts
const wonEvent = deal.addEvent('won');
const wins = app.addMetric('wins');
wins.addEvent(wonEvent);
const byRep = app.addMetricDimension('rep', [rep]);
wins.addDimension(byRep, 1, async (event, _dimension, ctx) => {
const item = await ctx.getItem(event.itemId);
const relation = item?.relations.rep;
return relation?.type === 'one' ? await relation.get() : undefined;
});

In run.ts, the script reads the wins of one month. from and to are the first and the last millisecond of that month:

run.ts
const metric = ctx.apps.pipeline.metrics.wins;
const byRep = metric.dimensions.rep;
const from = new Date(Date.UTC(2020, month - 1, 1));
const to = new Date(Date.UTC(2020, month, 1) - 1);
const report = await metric
.query('count')
.focalDimension(byRep)
.dimensions([byRep])
.interval(from, to)
.period('month')
.execute();
const entries = report.entries.month.entries;
return [entries[reps.alice]?.value ?? 0, entries[reps.bob]?.value ?? 0];

Alice won two deals in January, and Bob won one in February. The script reads February, runs the queued work, then reads three months:

Metric: February: Alice 0, Bob 0
Metric: January: Alice 2, Bob 0
Metric: February: Alice 0, Bob 1
Metric: March: Alice 0, Bob 0

Look at February. Bob has 0 before the queued work runs, and 1 after it.

The period is a label, not a bucket: one query over a whole year puts every count under the one entry, report.entries.month. The interval includes both of its ends, so each month ends one millisecond before the next begins.

The whole App: Sales pipeline with stages. Step by step: Tutorial: compose and measure.