Skip to content

Sales pipeline with stages

Deals move from lead to won or lost. Each stage allows only the next sensible moves, and the App counts the wins of each rep, month by month. The example is one App of about 120 lines and one script that runs it on SQLite.

When What the App does
A rep opens a deal Saves it as a lead that belongs to that rep
A rep moves a deal Makes the move when the deal’s stage allows it, and refuses any other
Nobody moves an open deal for 14 days Marks it stale at the next daily check
A deal is won Counts it for its rep, in the month it was won

You need the project from the Quickstart: Node.js 24, tsx and the packages it installs. The App has a Metric, so install one more package:

Terminal window
npm install @pyn-backend/platform-projector-sqlite

Create pipeline.ts and run.ts in the project, with the code under The whole App. Run the script:

Terminal window
PYN_ENV=local npx tsx run.ts

It prints:

Pipeline App is running in Workspace c641fd11-637b-547c-9bb4-fd1a1fc7e37c
Clock: Wed, 01 Jan 2020 00:00:00 GMT
As Alice: joined as the rep Alice
As Bob: joined as the rep Bob
As Alice: "Acme" is lead
As Alice: "Globex" is lead
As Bob: "Initech" is lead
As Alice: "Acme" is qualified
As Alice: "Acme" is proposal
As Alice: "Acme" is won
As Alice: Refused. A lead deal cannot win
As Alice: "Globex" is qualified
As Alice: "Globex" is proposal
As Alice: "Globex" is qualified
As Bob: "Initech" is qualified
Clock: Sat, 11 Jan 2020 00:00:00 GMT
As Alice: "Globex" is proposal
Clock: Thu, 16 Jan 2020 00:00:00 GMT
As Bob: sees Alice's deal "Acme", won
As Bob: sees Alice's deal "Globex", proposal
As Bob: sees Bob's deal "Initech", qualified, stale
As Alice: "Globex" is won
As Bob: "Initech" is proposal
Clock: Wed, 05 Feb 2020 00:00:00 GMT
As Bob: "Initech" is won
Metric: February: Alice 0, Bob 0
Metric: January: Alice 2, Bob 0
Metric: February: Alice 0, Bob 1
Metric: March: Alice 0, Bob 0

The script adds two people, Alice and Bob, and gives both the sales Role. Every operation of the App is granted to that Role. The script makes every call after that as Alice or as Bob. Its clock starts on 1 January 2020 and moves only when the script moves it.

Each part shows the lines of pipeline.ts behind one row above, and what they print.

pipeline.ts
const rep = app.addTemplate('rep');
rep.addProperty('name', 'string');
const deal = app.addTemplate('deal');
deal.addProperty('name', 'string');
deal.addProperty('movedAt', 'datetime');
deal.addProperty('stale', 'boolean');
deal.addRelation('rep', 'many-to-one', rep, { toKey: 'deals' });

A rep is an Item of the App’s own rep Template. A deal holds its name, the time of its last move and a stale mark. Its Relation points at a rep, and many-to-one says many deals point at one rep. A deal calls the Relation rep, and a rep calls it deals.

pipeline.ts
const join = app.addMutation('join', async (input: NameInput, current, ctx) => {
const workspace = await ctx.getWorkspaceItem();
return await workspace.upsertChildByKey(current.templates.rep, {
key: ctx.principalId,
onConflict: 'merge',
properties: { name: input.name },
});
});

join saves the rep of the person who calls it. ctx.principalId is the Identifier of that person, and join makes it the key of the rep. upsertChildByKey finds the child with that key or creates it, so a person who joins twice has one rep.

pipeline.ts
const open = app.addMutation('open', async (input: NameInput, current, ctx) => {
const owner = await ctx.getItemByKeyPath(ctx.principalId);
if (owner === undefined) throw new Error('Join before you open a deal');
const workspace = await ctx.getWorkspaceItem();
const item = await workspace.createChild(current.templates.deal, {
properties: { movedAt: ctx.now, name: input.name },
});
const relation = item.relations.rep;
if (relation.type === 'one') await relation.set(owner);
return item;
});

open finds the caller’s rep by that key, and the App refuses a person who has not joined. It creates the deal with ctx.now, the time of the call, as the time of its last move. Then it points the deal’s Relation at the rep. The deal starts in lead, its default state.

Alice and Bob join, and each opens deals:

Clock: Wed, 01 Jan 2020 00:00:00 GMT
As Alice: joined as the rep Alice
As Bob: joined as the rep Bob
As Alice: "Acme" is lead
As Alice: "Globex" is lead
As Bob: "Initech" is lead
pipeline.ts
const lead = deal.addState('lead').setDefault();
const qualified = deal.addState('qualified');
const proposal = deal.addState('proposal');
const won = deal.addState('won');
const lost = deal.addState('lost');
lead.addTransition('qualify', qualified);
qualified.addTransition('propose', proposal);
proposal.addTransition('rework', qualified);
proposal.addTransition('win', won);
lead.addTransition('lose', lost);
qualified.addTransition('lose', lost);
proposal.addTransition('lose', lost);

A deal has five states and seven transitions. A transition belongs to the state it leaves, and names the state it leads to:

stateDiagram-v2
  direction LR
  [*] --> lead
  lead --> qualified: qualify
  qualified --> proposal: propose
  proposal --> qualified: rework
  proposal --> won: win
  lead --> lost: lose
  qualified --> lost: lose
  proposal --> lost: lose

rework leads back a stage, and no transition leaves won or lost.

pipeline.ts
const move = app.addMutation('move', async (input: MoveInput, current, ctx) => {
const item = await current.templates.deal.getItem(input.id);
if (item === undefined) throw new Error('Deal not found');
const transitions = item.state?.transitions ?? {};
if (!Object.keys(transitions).includes(input.move)) {
throw new Error(`A ${item.state?.value} deal cannot ${input.move}`);
}
const moved = await transitions[input.move].execute({});
const updated = await moved.updateProperties({ movedAt: ctx.now, stale: false });
if (updated.state?.value === 'won') await updated.events.won.publish({});
return updated;
});

move takes the key of a transition. A deal has only the transitions declared on its current state, so Object.keys(transitions) lists the moves its stage allows. For any other key the App refuses, with its own message. For a key in the list, move executes the transition and saves the time of the call.

Alice takes Acme through every stage. She tries to win Globex while it is a lead, and the App refuses. Then she moves Globex two stages forward and one back, and Bob qualifies Initech:

As Alice: "Acme" is qualified
As Alice: "Acme" is proposal
As Alice: "Acme" is won
As Alice: Refused. A lead deal cannot win
As Alice: "Globex" is qualified
As Alice: "Globex" is proposal
As Alice: "Globex" is qualified
As Bob: "Initech" is qualified
pipeline.ts
const staleCheck = deal.addEvent('staleCheck');
staleCheck.addSchedule('daily', '0 9 * * *').state(['lead', 'qualified', 'proposal']);
staleCheck.addListener('flag', async (_event, item, _current, ctx) => {
const movedAt = item.propertyValues.movedAt;
if (movedAt?.type !== 'datetime') return;
const staleAt = movedAt.value.plus({ days: 14 });
if (staleAt <= ctx.now) await item.updateProperties({ stale: true });
});

0 9 * * * is a crontab: 9:00 every day. state([...]) keeps the schedule to deals in the three open stages. When the queued work runs and 9:00 has passed since the last run, the Runtime publishes staleCheck once for each of those deals. The Listener adds 14 days to the time of the last move, and marks the deal stale when that time has come.

move saves stale: false with the time of the call, so the 14 days start again with every move.

The schedule starts the first time the queued work runs. In run.ts, the script runs it once before it moves the clock:

run.ts
// Run the queued work once, so the schedule starts counting.
// Then move the clock ten days, and move Globex forward again.
await harness.tickAll();
await harness.tickAll({ days: 10 });
console.log(`Clock: ${system.current.toUTCString()}`);
await moveDeal('Alice', people.alice, globex, 'propose');
// Move the clock five more days. Initech last moved 15 days ago.
await harness.tickAll({ days: 5 });

On 16 January, nobody has moved Initech for 15 days, and Alice moved Globex five days ago. Acme is won, so the schedule leaves it out. Bob lists the deals, and every rep sees every deal:

Clock: Sat, 11 Jan 2020 00:00:00 GMT
As Alice: "Globex" is proposal
Clock: Thu, 16 Jan 2020 00:00:00 GMT
As Bob: sees Alice's deal "Acme", won
As Bob: sees Alice's deal "Globex", proposal
As Bob: sees Bob's deal "Initech", qualified, stale
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;
});

A Metric counts Events. move publishes won when a deal reaches the won state, and each won Event adds 1 to wins. The Dimension handler loads the deal, follows its Relation and returns the rep, so the Metric keeps a count for each rep.

A query reads the counts for one interval. In run.ts, showWins asks for one month:

run.ts
// Read the Metric as Bob: the wins of each rep in one month of 2020.
const showWins = async (label: string, month: number) => {
const [alice, bob] = await as(people.bob, async (ctx) => {
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];
});
console.log(`Metric: ${label} Alice ${alice}, Bob ${bob}`);
};

The interval picks the month. It includes both of its ends, so it ends one millisecond before the next month begins. The period is a label: with 'month', the count for each rep sits under report.entries.month. A count for each month takes one query for each month.

A projector builds the counts when the queued work runs. The script reads February before that, then three months after it:

As Alice: "Globex" is won
As Bob: "Initech" is proposal
Clock: Wed, 05 Feb 2020 00:00:00 GMT
As Bob: "Initech" is won
Metric: February: Alice 0, Bob 0
Metric: January: Alice 2, Bob 0
Metric: February: Alice 0, Bob 1
Metric: March: Alice 0, Bob 0

Alice won Acme and Globex in January, and Bob won Initech in February. Nobody won a deal in March.

pipeline.ts
pipeline.ts
import type { AppSpec } from '@alpynehq/alpyne-types/builder';
interface NameInput {
readonly name: string;
}
interface MoveInput {
readonly id: string;
readonly move: string;
}
export const pipelineApp: AppSpec = (app) => {
app.configure('pipeline');
const sales = app.addRole('sales', { label: 'Sales' });
const rep = app.addTemplate('rep');
rep.addProperty('name', 'string');
const deal = app.addTemplate('deal');
deal.addProperty('name', 'string');
deal.addProperty('movedAt', 'datetime');
deal.addProperty('stale', 'boolean');
deal.addRelation('rep', 'many-to-one', rep, { toKey: 'deals' });
const everyRep = async () => [sales.prn];
const repSales = rep.addRole('sales', everyRep);
rep.addGrant(repSales, Object.values(rep.properties));
const dealSales = deal.addRole('sales', everyRep);
deal.addGrant(dealSales, Object.values(deal.properties));
const lead = deal.addState('lead').setDefault();
const qualified = deal.addState('qualified');
const proposal = deal.addState('proposal');
const won = deal.addState('won');
const lost = deal.addState('lost');
lead.addTransition('qualify', qualified);
qualified.addTransition('propose', proposal);
proposal.addTransition('rework', qualified);
proposal.addTransition('win', won);
lead.addTransition('lose', lost);
qualified.addTransition('lose', lost);
proposal.addTransition('lose', lost);
const staleCheck = deal.addEvent('staleCheck');
staleCheck.addSchedule('daily', '0 9 * * *').state(['lead', 'qualified', 'proposal']);
staleCheck.addListener('flag', async (_event, item, _current, ctx) => {
const movedAt = item.propertyValues.movedAt;
if (movedAt?.type !== 'datetime') return;
const staleAt = movedAt.value.plus({ days: 14 });
if (staleAt <= ctx.now) await item.updateProperties({ stale: true });
});
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;
});
const join = app.addMutation('join', async (input: NameInput, current, ctx) => {
const workspace = await ctx.getWorkspaceItem();
return await workspace.upsertChildByKey(current.templates.rep, {
key: ctx.principalId,
onConflict: 'merge',
properties: { name: input.name },
});
});
join.input.addProperty('name', 'string').mandatory();
join.output.item(rep).mandatory();
const open = app.addMutation('open', async (input: NameInput, current, ctx) => {
const owner = await ctx.getItemByKeyPath(ctx.principalId);
if (owner === undefined) throw new Error('Join before you open a deal');
const workspace = await ctx.getWorkspaceItem();
const item = await workspace.createChild(current.templates.deal, {
properties: { movedAt: ctx.now, name: input.name },
});
const relation = item.relations.rep;
if (relation.type === 'one') await relation.set(owner);
return item;
});
open.input.addProperty('name', 'string').mandatory();
open.output.item(deal).mandatory();
const move = app.addMutation('move', async (input: MoveInput, current, ctx) => {
const item = await current.templates.deal.getItem(input.id);
if (item === undefined) throw new Error('Deal not found');
const transitions = item.state?.transitions ?? {};
if (!Object.keys(transitions).includes(input.move)) {
throw new Error(`A ${item.state?.value} deal cannot ${input.move}`);
}
const moved = await transitions[input.move].execute({});
const updated = await moved.updateProperties({ movedAt: ctx.now, stale: false });
if (updated.state?.value === 'won') await updated.events.won.publish({});
return updated;
});
move.input.addProperty('id', 'id').mandatory();
move.input.addProperty('move', 'string').mandatory();
move.output.item(deal).mandatory();
const list = app.addQuery('list', async (_input: unknown, current) => {
const deals = current.templates.deal.selectItems();
const page = await deals.sort(['$createdAt asc']).execute();
return page.results;
});
list.output.item(deal).array();
join.addGrant(sales);
open.addGrant(sales);
move.addGrant(sales);
list.addGrant(sales);
};
run.ts
run.ts
import type { WriteRuntimeInstance } from '@alpynehq/alpyne-types/runtime';
import { createSqliteKnexDatabase } from '@pyn-backend/data-knex-sqlite';
import { createHarnessInstance } from '@pyn-backend/platform-harness-public';
import { createSqliteProjector } from '@pyn-backend/platform-projector-sqlite';
import { createSqliteInstance } from '@pyn-backend/platform-reactor-sqlite';
import { createSqlitePlatformService } from '@pyn-backend/platform-service-sqlite';
import { createTestConfigurationService } from '@pyn-backend/service-configuration-test';
import { createTestCronService } from '@pyn-backend/service-cron-test';
import { createTestSystemService } from '@pyn-backend/service-system-test';
import { createTestDynamicConfigService } from '@pyn-backend/test-services-dynamic-config';
import { createTestLoggerService } from '@pyn-backend/test-services-logger';
import { pipelineApp } from './pipeline';
// A SQLite database, held in memory, with the Alpyne tables.
const knex = await createSqliteKnexDatabase(':memory:');
await knex.current.migrate.latest();
// The services a Runtime depends on.
const system = createTestSystemService();
const services = {
configuration: createTestConfigurationService(),
cron: createTestCronService({ system }),
dynamicConfig: createTestDynamicConfigService(),
knex,
logger: createTestLoggerService(),
system,
};
// The SQLite Runtime with the App loaded, a projector for its Metric, and a Workspace to hold its data.
const platform = createSqlitePlatformService(services);
const reactor = createSqliteInstance({ ...services, platform }, {});
const runtime = { ...services, platform, reactor };
const harness = await createHarnessInstance(runtime, pipelineApp);
await harness.ticker.register(createSqliteProjector(runtime, { spec: pipelineApp }));
const workspace = await harness.createWorkspace();
console.log(`Pipeline App is running in Workspace ${workspace.workspaceId}`);
// Add two people. Alice and Bob both work in sales.
const people = await workspace.write(async (ctx) => {
const root = await ctx.getWorkspaceItem();
const user = ctx.apps.identity.templates.user;
const roles = ctx.apps.pipeline.roles;
const templatePrn = 'prn::identity:template/user';
const alice = await user.createItem(root, { properties: { displayName: 'Alice' } });
const bob = await user.createItem(root, { properties: { displayName: 'Bob' } });
await roles.sales.assign({ id: alice.id, templatePrn });
await roles.sales.assign({ id: bob.id, templatePrn });
return { alice: alice.id, bob: bob.id };
});
// Run a call as one person.
const as = async <T>(id: string, fn: (ctx: WriteRuntimeInstance) => Promise<T>) => {
const instance = await platform.createInstance({
identityId: crypto.randomUUID(),
principalId: id,
rolePrns: [],
sessionId: crypto.randomUUID(),
type: 'principal',
workspaceId: workspace.workspaceId,
});
return await instance.execute('readwrite', { payload: {}, traceId: 'example' }, fn);
};
// Join as a rep, as one person.
const join = async (name: string, id: string) => {
const rep = await as(id, async (ctx) => {
const pipeline = ctx.apps.pipeline;
return await pipeline.mutations.join.handler({ name }, pipeline, ctx);
});
console.log(`As ${name}:`.padEnd(11) + `joined as the rep ${rep.properties.name}`);
return rep.id;
};
// Open a deal as one person.
const openDeal = async (name: string, id: string, deal: string) => {
const opened = await as(id, async (ctx) => {
const pipeline = ctx.apps.pipeline;
return await pipeline.mutations.open.handler({ name: deal }, pipeline, ctx);
});
console.log(`As ${name}:`.padEnd(11) + `"${deal}" is ${opened.state.value}`);
return opened.id;
};
// Make one move on a deal as one person.
const moveDeal = async (name: string, id: string, deal: string, move: string) => {
try {
const moved = await as(id, async (ctx) => {
const pipeline = ctx.apps.pipeline;
return await pipeline.mutations.move.handler({ id: deal, move }, pipeline, ctx);
});
console.log(`As ${name}:`.padEnd(11) + `"${moved.properties.name}" is ${moved.state.value}`);
} catch (error) {
const reason = error instanceof Error ? error.message : String(error);
console.log(`As ${name}:`.padEnd(11) + `Refused. ${reason}`);
}
};
// List the deals one person sees. Follow the Relation from each deal to its rep.
const listDeals = async (name: string, id: string) => {
await as(id, async (ctx) => {
const pipeline = ctx.apps.pipeline;
const deals = await pipeline.queries.list.handler({}, pipeline, ctx);
for (const deal of deals) {
const rep = await deal.relations.rep.get();
const { name: title, stale } = deal.properties;
const line = `sees ${rep.properties.name}'s deal "${title}", ${deal.state.value}`;
console.log(`As ${name}:`.padEnd(11) + line + (stale === true ? ', stale' : ''));
}
});
};
// Alice and Bob join. Each opens deals of their own.
console.log(`Clock: ${system.current.toUTCString()}`);
const reps = { alice: await join('Alice', people.alice), bob: await join('Bob', people.bob) };
const acme = await openDeal('Alice', people.alice, 'Acme');
const globex = await openDeal('Alice', people.alice, 'Globex');
const initech = await openDeal('Bob', people.bob, 'Initech');
// Alice takes Acme through every stage.
await moveDeal('Alice', people.alice, acme, 'qualify');
await moveDeal('Alice', people.alice, acme, 'propose');
await moveDeal('Alice', people.alice, acme, 'win');
// She tries to win Globex while it is a lead. Then she moves it two stages forward and one back.
await moveDeal('Alice', people.alice, globex, 'win');
await moveDeal('Alice', people.alice, globex, 'qualify');
await moveDeal('Alice', people.alice, globex, 'propose');
await moveDeal('Alice', people.alice, globex, 'rework');
// Bob qualifies Initech, and then leaves it alone.
await moveDeal('Bob', people.bob, initech, 'qualify');
// Run the queued work once, so the schedule starts counting.
// Then move the clock ten days, and move Globex forward again.
await harness.tickAll();
await harness.tickAll({ days: 10 });
console.log(`Clock: ${system.current.toUTCString()}`);
await moveDeal('Alice', people.alice, globex, 'propose');
// Move the clock five more days. Initech last moved 15 days ago.
await harness.tickAll({ days: 5 });
console.log(`Clock: ${system.current.toUTCString()}`);
await listDeals('Bob', people.bob);
// Alice wins Globex in January. Bob wins Initech in February.
await moveDeal('Alice', people.alice, globex, 'win');
await moveDeal('Bob', people.bob, initech, 'propose');
await harness.tickAll({ days: 20 });
console.log(`Clock: ${system.current.toUTCString()}`);
await moveDeal('Bob', people.bob, initech, 'win');
// Read the Metric as Bob: the wins of each rep in one month of 2020.
const showWins = async (label: string, month: number) => {
const [alice, bob] = await as(people.bob, async (ctx) => {
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];
});
console.log(`Metric: ${label} Alice ${alice}, Bob ${bob}`);
};
// Show February before the queued work runs. Then show three months, one query for each.
await showWins('February:', 2);
await harness.tickAll();
await showWins('January: ', 1);
await showWins('February:', 2);
await showWins('March: ', 3);
await knex.destroy();