Skip to content

Support tickets with an SLA

Customers open support tickets and see only their own. Agents see every ticket and resolve it. A ticket that nobody resolves within four hours turns overdue by itself. The example is one App of about 110 lines and one script that runs it on SQLite.

When What the App does
A customer opens a ticket Saves it in the general queue, due in four hours
A person lists the tickets Shows a customer the tickets that customer opened, and an agent every ticket
An open ticket passes its due time Moves it to overdue at the next hourly check
An agent resolves a ticket Moves it to resolved. A customer’s call is refused
A ticket is resolved Counts it for its queue

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 tickets.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:

Tickets App is running in Workspace bfff7117-facc-5759-a097-913c3bac2fe3
Clock: Wed, 01 Jan 2020 00:00:00 GMT
As Alice: "Printer" is open, due Wed, 01 Jan 2020 04:00:00 GMT
Clock: Wed, 01 Jan 2020 02:00:00 GMT
As Carol: "Laptop" is open, due Wed, 01 Jan 2020 06:00:00 GMT
As Alice: sees "Printer", open
As Carol: sees "Laptop", open
As Bob: sees "Printer", open
As Bob: sees "Laptop", open
As Carol: Alice's ticket is not there
Clock: Wed, 01 Jan 2020 05:00:00 GMT
As Bob: sees "Printer", overdue
As Bob: sees "Laptop", open
As Alice: Refused. Grant assertion failed for the current principal: none of [prn::tickets:role/agent] held
As Bob: "Printer" is resolved
Metric: 0 resolved in General
Metric: 1 resolved in General

The script adds three people and makes every call as one of them. Alice and Carol are customers and Bob is an agent. Its clock starts on 1 January 2020 and moves only when the script moves it.

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

tickets.ts
const openTicket = app.addMutation('open', async (input: OpenInput, current, ctx) => {
const general = await ctx.getItemByKeyPath('general');
if (general === undefined) throw new Error('Queue not found');
return await general.createChild(current.templates.ticket, {
properties: {
dueAt: ctx.now.plus({ hours: 4 }),
openedBy: ctx.principalId,
subject: input.subject,
},
});
});

open finds the queue by its key, general, and creates the ticket as its child. ctx.now is the time of the call, so the ticket is due four hours after it. ctx.principalId is the Identifier of the person who makes the call. The ticket starts in open, its default state.

The queue is there because of an App Hook. onCreate runs when a Workspace is created:

tickets.ts
app.onCreate(async (prev, current, ctx) => {
await prev();
const workspace = await ctx.getWorkspaceItem();
await workspace.createChild(current.templates.queue, {
key: 'general',
properties: { name: 'General' },
});
});

Alice opens “Printer” at midnight. Carol opens “Laptop” two hours after her:

Clock: Wed, 01 Jan 2020 00:00:00 GMT
As Alice: "Printer" is open, due Wed, 01 Jan 2020 04:00:00 GMT
Clock: Wed, 01 Jan 2020 02:00:00 GMT
As Carol: "Laptop" is open, due Wed, 01 Jan 2020 06:00:00 GMT
tickets.ts
const opener = ticket.addRole('opener', async (item) => {
const openedBy = item.properties.openedBy;
return typeof openedBy === 'string' ? [openedBy] : [];
});
const agents = ticket.addRole('agents', async () => [agent.prn]);
ticket.addGrant(opener, Object.values(ticket.properties));
ticket.addGrant(agents, Object.values(ticket.properties));

A Template Role says who holds it for each Item. For opener, the callback returns the Identifier saved in openedBy, so one person holds it: the customer who opened the ticket. agents returns the agent Role, so every agent holds it. Each Grant shows the ticket to the people who hold that Role.

The list Query selects every ticket and names nobody:

tickets.ts
const list = app.addQuery('list', async (_input: unknown, current) => {
const tickets = current.templates.ticket.selectItems();
const page = await tickets.sort(['$createdAt asc']).execute();
return page.results;
});

The Runtime returns the tickets the caller holds a Role for. Alice and Carol each see one ticket, and Bob sees both. Carol asks for Alice’s ticket by its Identifier and finds nothing:

As Alice: sees "Printer", open
As Carol: sees "Laptop", open
As Bob: sees "Printer", open
As Bob: sees "Laptop", open
As Carol: Alice's ticket is not there
tickets.ts
const open = ticket.addState('open').setDefault();
const overdue = ticket.addState('overdue');
const resolved = ticket.addState('resolved');
open.addTransition('breach', overdue);
open.addTransition('resolve', resolved);
overdue.addTransition('resolve', resolved);
const slaCheck = ticket.addEvent('slaCheck');
slaCheck.addSchedule('hourly', '0 * * * *').state(['open']);
slaCheck.addListener('markOverdue', async (_event, item, _current, ctx) => {
const dueAt = item.propertyValues.dueAt;
const breach = item.state?.transitions.breach;
if (dueAt?.type !== 'datetime' || breach === undefined) return;
if (dueAt.value <= ctx.now) await breach.execute({});
});

A ticket has three states. 0 * * * * is a crontab: every hour, on the hour. state(['open']) keeps the schedule to open tickets. When the queued work runs and an hour mark has passed since the last run, the Runtime publishes slaCheck once for each open ticket. The Listener compares the due time with ctx.now, and executes breach on a ticket that is due.

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 two hours.
await harness.tickAll();
await harness.tickAll({ hours: 2 });

At 2:00 the check finds “Printer” two hours short of its due time. At 5:00 it finds “Printer” an hour past it, and “Laptop” with an hour to go:

Clock: Wed, 01 Jan 2020 05:00:00 GMT
As Bob: sees "Printer", overdue
As Bob: sees "Laptop", open
tickets.ts
openTicket.addGrant(customer);
list.addGrant(customer);
list.addGrant(agent);
resolveTicket.addGrant(agent);

A Grant on an operation says which Role calls it. resolve is granted to agents and Alice is a customer, so the Runtime refuses her call.

tickets.ts
const resolveTicket = app.addMutation('resolve', async (input: IdInput, current) => {
const item = await current.templates.ticket.getItem(input.id);
if (item === undefined) throw new Error('Ticket not found');
const transition = item.state?.transitions.resolve;
if (transition === undefined) {
throw new Error(`A ${item.state?.value} ticket cannot be resolved`);
}
const updated = await transition.execute({});
await updated.events.resolved.publish({});
return updated;
});

Bob’s call reaches the handler. It executes the resolve transition, which leads to resolved from open and from overdue, then publishes the resolved Event. A resolved ticket has no resolve transition, so the App refuses a second call with its own message.

As Alice: Refused. Grant assertion failed for the current principal: none of [prn::tickets:role/agent] held
As Bob: "Printer" is resolved
tickets.ts
const resolvedEvent = ticket.addEvent('resolved');
const resolvedTickets = app.addMetric('resolvedTickets');
resolvedTickets.addEvent(resolvedEvent);
const byQueue = app.addMetricDimension('queue', [queue]);
resolvedTickets.addDimension(byQueue, 1, async (event, _dimension, ctx) => {
const item = await ctx.getItem(event.itemId);
return await item?.getParent();
});

A Metric counts Events. Each resolved Event adds 1 to resolvedTickets. The Dimension handler loads the ticket and returns its parent, the queue, so the Metric keeps a count for each queue.

A projector builds the counts when the queued work runs. The script reads the Metric as Bob, before and after:

Metric: 0 resolved in General
Metric: 1 resolved in General
tickets.ts
tickets.ts
import type { AppSpec } from '@alpynehq/alpyne-types/builder';
interface OpenInput {
readonly subject: string;
}
interface IdInput {
readonly id: string;
}
export const ticketsApp: AppSpec = (app) => {
app.configure('tickets');
const customer = app.addRole('customer', { label: 'Customer' });
const agent = app.addRole('agent', { label: 'Agent' });
const queue = app.addTemplate('queue');
queue.addProperty('name', 'string');
const everyone = queue.addRole('everyone', async () => [customer.prn, agent.prn]);
queue.addGrant(everyone, Object.values(queue.properties));
const ticket = app.addTemplate('ticket');
ticket.addProperty('subject', 'string');
ticket.addProperty('openedBy', 'id');
ticket.addProperty('dueAt', 'datetime');
const opener = ticket.addRole('opener', async (item) => {
const openedBy = item.properties.openedBy;
return typeof openedBy === 'string' ? [openedBy] : [];
});
const agents = ticket.addRole('agents', async () => [agent.prn]);
ticket.addGrant(opener, Object.values(ticket.properties));
ticket.addGrant(agents, Object.values(ticket.properties));
const open = ticket.addState('open').setDefault();
const overdue = ticket.addState('overdue');
const resolved = ticket.addState('resolved');
open.addTransition('breach', overdue);
open.addTransition('resolve', resolved);
overdue.addTransition('resolve', resolved);
const slaCheck = ticket.addEvent('slaCheck');
slaCheck.addSchedule('hourly', '0 * * * *').state(['open']);
slaCheck.addListener('markOverdue', async (_event, item, _current, ctx) => {
const dueAt = item.propertyValues.dueAt;
const breach = item.state?.transitions.breach;
if (dueAt?.type !== 'datetime' || breach === undefined) return;
if (dueAt.value <= ctx.now) await breach.execute({});
});
const resolvedEvent = ticket.addEvent('resolved');
const resolvedTickets = app.addMetric('resolvedTickets');
resolvedTickets.addEvent(resolvedEvent);
const byQueue = app.addMetricDimension('queue', [queue]);
resolvedTickets.addDimension(byQueue, 1, async (event, _dimension, ctx) => {
const item = await ctx.getItem(event.itemId);
return await item?.getParent();
});
const openTicket = app.addMutation('open', async (input: OpenInput, current, ctx) => {
const general = await ctx.getItemByKeyPath('general');
if (general === undefined) throw new Error('Queue not found');
return await general.createChild(current.templates.ticket, {
properties: {
dueAt: ctx.now.plus({ hours: 4 }),
openedBy: ctx.principalId,
subject: input.subject,
},
});
});
openTicket.input.addProperty('subject', 'string').mandatory();
openTicket.output.item(ticket).mandatory();
const resolveTicket = app.addMutation('resolve', async (input: IdInput, current) => {
const item = await current.templates.ticket.getItem(input.id);
if (item === undefined) throw new Error('Ticket not found');
const transition = item.state?.transitions.resolve;
if (transition === undefined) {
throw new Error(`A ${item.state?.value} ticket cannot be resolved`);
}
const updated = await transition.execute({});
await updated.events.resolved.publish({});
return updated;
});
resolveTicket.input.addProperty('id', 'id').mandatory();
resolveTicket.output.item(ticket).mandatory();
const list = app.addQuery('list', async (_input: unknown, current) => {
const tickets = current.templates.ticket.selectItems();
const page = await tickets.sort(['$createdAt asc']).execute();
return page.results;
});
list.output.item(ticket).array();
openTicket.addGrant(customer);
list.addGrant(customer);
list.addGrant(agent);
resolveTicket.addGrant(agent);
app.onCreate(async (prev, current, ctx) => {
await prev();
const workspace = await ctx.getWorkspaceItem();
await workspace.createChild(current.templates.queue, {
key: 'general',
properties: { name: 'General' },
});
});
};
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 { ticketsApp } from './tickets';
// 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, ticketsApp);
await harness.ticker.register(createSqliteProjector(runtime, { spec: ticketsApp }));
const workspace = await harness.createWorkspace();
console.log(`Tickets App is running in Workspace ${workspace.workspaceId}`);
// Add three people. Alice and Carol are customers and Bob is an agent.
const people = await workspace.write(async (ctx) => {
const root = await ctx.getWorkspaceItem();
const user = ctx.apps.identity.templates.user;
const roles = ctx.apps.tickets.roles;
const templatePrn = 'prn::identity:template/user';
const alice = await user.createItem(root, { properties: { displayName: 'Alice' } });
const carol = await user.createItem(root, { properties: { displayName: 'Carol' } });
const bob = await user.createItem(root, { properties: { displayName: 'Bob' } });
await roles.customer.assign({ id: alice.id, templatePrn });
await roles.customer.assign({ id: carol.id, templatePrn });
await roles.agent.assign({ id: bob.id, templatePrn });
return { alice: alice.id, bob: bob.id, carol: carol.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);
};
// Open a ticket as one person.
const openTicket = async (name: string, id: string, subject: string) => {
const ticket = await as(id, async (ctx) => {
const tickets = ctx.apps.tickets;
return await tickets.mutations.open.handler({ subject }, tickets, ctx);
});
const due = ticket.properties.dueAt.toJSDate().toUTCString();
console.log(`As ${name}:`.padEnd(11) + `"${subject}" is ${ticket.state.value}, due ${due}`);
return ticket.id;
};
// List the tickets one person sees.
const listTickets = async (name: string, id: string) => {
const tickets = await as(id, async (ctx) => {
const app = ctx.apps.tickets;
return await app.queries.list.handler({}, app, ctx);
});
for (const ticket of tickets) {
console.log(`As ${name}:`.padEnd(11) + `sees "${ticket.properties.subject}", ${ticket.state.value}`);
}
};
// Alice opens a ticket at midnight.
console.log(`Clock: ${system.current.toUTCString()}`);
const printer = await openTicket('Alice', people.alice, 'Printer');
// Run the queued work once, so the schedule starts counting.
// Then move the clock two hours.
await harness.tickAll();
await harness.tickAll({ hours: 2 });
console.log(`Clock: ${system.current.toUTCString()}`);
// Carol opens a ticket two hours after Alice.
await openTicket('Carol', people.carol, 'Laptop');
// Each customer sees her own ticket. The agent sees both.
await listTickets('Alice', people.alice);
await listTickets('Carol', people.carol);
await listTickets('Bob', people.bob);
// Carol asks for Alice's ticket by its Identifier.
const found = await as(people.carol, async (ctx) => await ctx.getItem(printer));
console.log(`As Carol: Alice's ticket is ${found === undefined ? 'not there' : 'there'}`);
// Move the clock three more hours. Alice's ticket was due at 4:00 and Carol's is due at 6:00.
await harness.tickAll({ hours: 3 });
console.log(`Clock: ${system.current.toUTCString()}`);
await listTickets('Bob', people.bob);
// Try to resolve the overdue ticket as Alice.
try {
await as(people.alice, async (ctx) => {
const tickets = ctx.apps.tickets;
return await tickets.mutations.resolve.handler({ id: printer }, tickets, ctx);
});
} catch (error) {
const reason = error instanceof Error ? error.message : String(error);
console.log(`As Alice: Refused. ${reason}`);
}
// Read the Metric as Bob: the number of resolved tickets in the general queue.
const showResolved = async () => {
const count = await as(people.bob, async (ctx) => {
const metric = ctx.apps.tickets.metrics.resolvedTickets;
const byQueue = metric.dimensions.queue;
const general = await ctx.getItemByKeyPath('general');
const from = ctx.now.minus({ days: 7 }).toJSDate();
const to = ctx.now.toJSDate();
const report = await metric
.query('count')
.focalDimension(byQueue)
.dimensions([byQueue])
.interval(from, to)
.period('day')
.execute();
const entry = general === undefined ? undefined : report.entries.day.entries[general.id];
return { name: general?.properties.name, value: entry?.value ?? 0 };
});
console.log(`Metric: ${count.value} resolved in ${count.name}`);
};
// Resolve the overdue ticket as Bob. Show the Metric before and after the queued work runs.
const resolved = await as(people.bob, async (ctx) => {
const tickets = ctx.apps.tickets;
return await tickets.mutations.resolve.handler({ id: printer }, tickets, ctx);
});
console.log(`As Bob: "${resolved.properties.subject}" is ${resolved.state.value}`);
await showResolved();
await harness.tickAll();
await showResolved();
await knex.destroy();