Room bookings that refuse a clash
People book a room for a time slot. When a person makes a booking, the App checks the bookings of that room and refuses a slot that overlaps one. A canceled booking frees its slot. The example is one App of about 120 lines and one script that runs it on SQLite.
What it does
Section titled “What it does”| When | What the App does |
|---|---|
| A person books a room for a slot | Saves the booking for that room, with the times it starts and ends |
| The slot overlaps a booking of that room | Refuses, and says when the room is booked |
| A person asks which rooms are free for a slot | Lists every room with no booking that overlaps the slot |
| A person cancels a booking | Moves it to canceled, which frees its slot. Another person’s call is refused |
Run it
Section titled “Run it”You need the project from the Quickstart: Node.js 24, tsx and the packages it installs. Create bookings.ts and run.ts in the project, with the code under The whole App. Run the script:
PYN_ENV=local npx tsx run.tsIt prints:
Bookings App is running in Workspace 7c5a4e9b-b240-54cf-b7f8-382a9e65507fClock: Wed, 01 Jan 2020 00:00:00 GMTAs Alice: Maple, Wed, 01 Jan 2020 10:00 to 11:00, is bookedClock: Wed, 01 Jan 2020 09:00:00 GMTAs Bob: Refused. Maple is booked from 10:00 to 11:00As Bob: Oak, Wed, 01 Jan 2020 10:30 to 11:30, is bookedAs Bob: free from 10:00 to 11:00: no roomAs Bob: free from 11:30 to 12:30: Maple, OakAs Bob: Refused. Only the person who booked can cancelAs Alice: Maple, Wed, 01 Jan 2020 10:00 to 11:00, is canceledAs Bob: free from 10:00 to 11:00: MapleAs Bob: Maple, Wed, 01 Jan 2020 10:30 to 11:30, is bookedThe script adds two people, Alice and Bob, and gives both the staff Role. Staff see every room and every booking, and every operation of the App is granted to them. The script makes every call after that as Alice or as Bob, one call after another. Its clock starts on 1 January 2020 and moves only when the script moves it.
How it works
Section titled “How it works”Each part shows the lines of bookings.ts behind one row above, and what they print.
A person books a room for a slot
Section titled “A person books a room for a slot” const room = app.addTemplate('room'); room.addProperty('name', 'string');
const booking = app.addTemplate('booking'); booking.addProperty('bookedBy', 'id'); booking.addProperty('start', 'datetime'); booking.addProperty('end', 'datetime'); booking.addRelation('room', 'many-to-one', room, { toKey: 'bookings' });A booking holds the person who made it, and its start and its end as datetime Properties. Its Relation points at a room, and many-to-one says many bookings point at one room. A booking calls the Relation room, and a room calls it bookings.
const timesOf = (ctx: ReadRuntimeInstance, slot: SlotInput) => { if (slot.to <= slot.from) throw new Error('A slot ends after it starts'); const day = ctx.now.startOf('day'); const start = day.plus({ hours: slot.from }); return { end: day.plus({ hours: slot.to }), start }; };A person names a slot with two hours of the day, such as 10 and 11, or 10.5 for 10:30. ctx.now is the time of the call, as a Luxon DateTime, and a datetime Property takes a DateTime. So timesOf adds each hour to the start of the day of the call. The App refuses a slot that does not end after it starts.
const book = app.addMutation('book', async (input: BookInput, current, ctx) => { const target = await current.templates.room.selectItems().key(input.room).first(); if (target === undefined) throw new Error('Room not found'); const clash = await findClash(ctx, target, input); const name = target.properties.name; if (clash !== undefined) throw new Error(`${name} is booked from ${clash}`); const workspace = await ctx.getWorkspaceItem(); const item = await workspace.createChild(current.templates.booking, { properties: { bookedBy: ctx.principalId, ...timesOf(ctx, input) }, }); const relation = item.relations.room; if (relation.type === 'one') await relation.set(target); return item; });book finds the room by its key and asks findClash, in the next part, for a booking in the way. When there is none, it creates the booking with the two times and ctx.principalId, the Identifier of the person who makes the call. Then it points the booking’s Relation at the room. The booking starts in booked, its default state.
Alice books Maple from 10 to 11 while the clock stands at midnight:
Clock: Wed, 01 Jan 2020 00:00:00 GMTAs Alice: Maple, Wed, 01 Jan 2020 10:00 to 11:00, is bookedThe slot overlaps a booking of that room
Section titled “The slot overlaps a booking of that room” const findClash = async (ctx: ReadRuntimeInstance, target: ReadItem, slot: SlotInput) => { const { end, start } = timesOf(ctx, slot); const bookings = target.relations.bookings; if (bookings.type !== 'many') return undefined; const stillBooked = bookings.select().state(['booked']); for await (const other of stillBooked.iterator()) { const { end: until, start: since } = other.propertyValues; if (since?.type !== 'datetime' || until?.type !== 'datetime') continue; if (since.value < end && start < until.value) { return `${since.value.toFormat('HH:mm')} to ${until.value.toFormat('HH:mm')}`; } } return undefined; };findClash follows the Relation from the room’s side. select() starts a selector over the bookings that point at the room, state(['booked']) keeps it to the ones still booked, and iterator() walks every one of them. Two slots overlap when each starts before the other ends, so a slot can start at the minute another ends.
findClash returns the times of the first booking that overlaps, as text. book puts them in its message and throws, before it creates anything.
The script moves the clock to 9:00, and Bob asks for Maple from 10:30 to 11:30. His hours count from the start of the same day, so the slot overlaps Alice’s booking and the App refuses. The same slot in Oak overlaps nothing:
Clock: Wed, 01 Jan 2020 09:00:00 GMTAs Bob: Refused. Maple is booked from 10:00 to 11:00As Bob: Oak, Wed, 01 Jan 2020 10:30 to 11:30, is bookedA person asks which rooms are free for a slot
Section titled “A person asks which rooms are free for a slot” const free = app.addQuery('free', async (input: SlotInput, current, ctx) => { const page = await current.templates.room.selectItems().sort(['$createdAt asc']).execute(); const rooms: ReadItem[] = page.results; const clashes = await Promise.all(rooms.map((item) => findClash(ctx, item, input))); return rooms.filter((_item, index) => clashes[index] === undefined); });The free Query asks findClash about every room, and returns the rooms where nothing is in the way. It uses the rule book uses: it lists a room for a slot when book accepts that slot for the room, and leaves it out when book refuses.
The rooms are there because of an App Hook. onCreate runs when a Workspace is created, and saves each room under a key:
app.onCreate(async (prev, current, ctx) => { await prev(); const workspace = await ctx.getWorkspaceItem(); for (const name of ['Maple', 'Oak']) { const key = name.toLowerCase(); await workspace.createChild(current.templates.room, { key, properties: { name } }); } });From 10:00 to 11:00, Alice has Maple and Bob’s booking takes Oak from 10:30. Bob’s booking ends at 11:30, and Oak is free from that minute:
As Bob: free from 10:00 to 11:00: no roomAs Bob: free from 11:30 to 12:30: Maple, OakA person cancels a booking
Section titled “A person cancels a booking” const booked = booking.addState('booked').setDefault(); const canceled = booking.addState('canceled'); booked.addTransition('cancel', canceled);A booking has two states and one transition, cancel, from booked to canceled.
const cancel = app.addMutation('cancel', async (input: IdInput, current, ctx) => { const item = await current.templates.booking.getItem(input.id); if (item === undefined) throw new Error('Booking not found'); if (item.properties.bookedBy !== ctx.principalId) { throw new Error('Only the person who booked can cancel'); } const transition = item.state?.transitions.cancel; if (transition === undefined) throw new Error('The booking is already canceled'); return await transition.execute({}); });cancel compares the person saved on the booking with the person who makes the call, and the App refuses anyone else with its own message. Then it executes the transition. A canceled booking has no cancel transition, so the App refuses a second call too.
findClash selects only the bookings still booked, so a canceled booking is in nobody’s way. The App refuses Bob’s call to cancel Alice’s booking. Alice cancels it, Maple is free again, and Bob books the slot the App refused:
As Bob: Refused. Only the person who booked can cancelAs Alice: Maple, Wed, 01 Jan 2020 10:00 to 11:00, is canceledAs Bob: free from 10:00 to 11:00: MapleAs Bob: Maple, Wed, 01 Jan 2020 10:30 to 11:30, is bookedThe whole App
Section titled “The whole App”bookings.ts
import type { AppSpec } from '@alpynehq/alpyne-types/builder';import type { ReadItem, ReadRuntimeInstance } from '@alpynehq/alpyne-types/runtime';
interface SlotInput { readonly from: number; readonly to: number;}
interface BookInput extends SlotInput { readonly room: string;}
interface IdInput { readonly id: string;}
export const bookingsApp: AppSpec = (app) => { app.configure('bookings');
const staff = app.addRole('staff', { label: 'Staff' });
const room = app.addTemplate('room'); room.addProperty('name', 'string');
const booking = app.addTemplate('booking'); booking.addProperty('bookedBy', 'id'); booking.addProperty('start', 'datetime'); booking.addProperty('end', 'datetime'); booking.addRelation('room', 'many-to-one', room, { toKey: 'bookings' });
const everyStaff = async () => [staff.prn]; const roomStaff = room.addRole('staff', everyStaff); room.addGrant(roomStaff, Object.values(room.properties)); const bookingStaff = booking.addRole('staff', everyStaff); booking.addGrant(bookingStaff, Object.values(booking.properties));
const booked = booking.addState('booked').setDefault(); const canceled = booking.addState('canceled'); booked.addTransition('cancel', canceled);
// The start and the end of a slot, as times on the day of the call. const timesOf = (ctx: ReadRuntimeInstance, slot: SlotInput) => { if (slot.to <= slot.from) throw new Error('A slot ends after it starts'); const day = ctx.now.startOf('day'); const start = day.plus({ hours: slot.from }); return { end: day.plus({ hours: slot.to }), start }; };
// The times, as text, of the first booking of a room that is still booked and overlaps a slot. const findClash = async (ctx: ReadRuntimeInstance, target: ReadItem, slot: SlotInput) => { const { end, start } = timesOf(ctx, slot); const bookings = target.relations.bookings; if (bookings.type !== 'many') return undefined; const stillBooked = bookings.select().state(['booked']); for await (const other of stillBooked.iterator()) { const { end: until, start: since } = other.propertyValues; if (since?.type !== 'datetime' || until?.type !== 'datetime') continue; if (since.value < end && start < until.value) { return `${since.value.toFormat('HH:mm')} to ${until.value.toFormat('HH:mm')}`; } } return undefined; };
const book = app.addMutation('book', async (input: BookInput, current, ctx) => { const target = await current.templates.room.selectItems().key(input.room).first(); if (target === undefined) throw new Error('Room not found'); const clash = await findClash(ctx, target, input); const name = target.properties.name; if (clash !== undefined) throw new Error(`${name} is booked from ${clash}`); const workspace = await ctx.getWorkspaceItem(); const item = await workspace.createChild(current.templates.booking, { properties: { bookedBy: ctx.principalId, ...timesOf(ctx, input) }, }); const relation = item.relations.room; if (relation.type === 'one') await relation.set(target); return item; }); book.input.addProperty('room', 'string').mandatory(); book.input.addProperty('from', 'number').mandatory(); book.input.addProperty('to', 'number').mandatory(); book.output.item(booking).mandatory();
const cancel = app.addMutation('cancel', async (input: IdInput, current, ctx) => { const item = await current.templates.booking.getItem(input.id); if (item === undefined) throw new Error('Booking not found'); if (item.properties.bookedBy !== ctx.principalId) { throw new Error('Only the person who booked can cancel'); } const transition = item.state?.transitions.cancel; if (transition === undefined) throw new Error('The booking is already canceled'); return await transition.execute({}); }); cancel.input.addProperty('id', 'id').mandatory(); cancel.output.item(booking).mandatory();
const free = app.addQuery('free', async (input: SlotInput, current, ctx) => { const page = await current.templates.room.selectItems().sort(['$createdAt asc']).execute(); const rooms: ReadItem[] = page.results; const clashes = await Promise.all(rooms.map((item) => findClash(ctx, item, input))); return rooms.filter((_item, index) => clashes[index] === undefined); }); free.input.addProperty('from', 'number').mandatory(); free.input.addProperty('to', 'number').mandatory(); free.output.item(room).array();
book.addGrant(staff); cancel.addGrant(staff); free.addGrant(staff);
app.onCreate(async (prev, current, ctx) => { await prev(); const workspace = await ctx.getWorkspaceItem(); for (const name of ['Maple', 'Oak']) { const key = name.toLowerCase(); await workspace.createChild(current.templates.room, { key, properties: { name } }); } });};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 { 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 { bookingsApp } from './bookings';
// 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, 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, bookingsApp);const workspace = await harness.createWorkspace();console.log(`Bookings App is running in Workspace ${workspace.workspaceId}`);
// Add two people. Alice and Bob are both staff.const people = await workspace.write(async (ctx) => { const root = await ctx.getWorkspaceItem(); const user = ctx.apps.identity.templates.user; const roles = ctx.apps.bookings.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.staff.assign({ id: alice.id, templatePrn }); await roles.staff.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);};
// An hour of the day as text: 10.5 is 10:30.const time = (hour: number) => new Date(hour * 3600000).toISOString().slice(11, 16);
// A slot as text: the day and the time it starts, then the time it ends.const slot = (start: Date, end: Date) => { return `${start.toUTCString().slice(0, 22)} to ${end.toUTCString().slice(17, 22)}`;};
// Book a room as one person, from one hour of the day to another.// Follow the Relation from the booking to its room.const book = async (name: string, id: string, room: string, from: number, to: number) => { return await as(id, async (ctx) => { const bookings = ctx.apps.bookings; const booking = await bookings.mutations.book.handler({ from, room, to }, bookings, ctx); const booked = await booking.relations.room.get(); const { end, start } = booking.properties; const text = `${booked.properties.name}, ${slot(start.toJSDate(), end.toJSDate())}`; console.log(`As ${name}:`.padEnd(11) + `${text}, is ${booking.state.value}`); return booking.id; });};
// Cancel a booking as one person.const cancel = async (name: string, id: string, booking: string) => { await as(id, async (ctx) => { const bookings = ctx.apps.bookings; const canceled = await bookings.mutations.cancel.handler({ id: booking }, bookings, ctx); const booked = await canceled.relations.room.get(); const { end, start } = canceled.properties; const text = `${booked.properties.name}, ${slot(start.toJSDate(), end.toJSDate())}`; console.log(`As ${name}:`.padEnd(11) + `${text}, is ${canceled.state.value}`); });};
// Ask as one person which rooms are free from one hour of the day to another.const showFree = async (name: string, id: string, from: number, to: number) => { const rooms = await as(id, async (ctx) => { const bookings = ctx.apps.bookings; return await bookings.queries.free.handler({ from, to }, bookings, ctx); }); const names: string[] = []; for (const room of rooms) names.push(room.properties.name); const answer = names.length === 0 ? 'no room' : names.join(', '); console.log(`As ${name}:`.padEnd(11) + `free from ${time(from)} to ${time(to)}: ${answer}`);};
// Print the reason the App gives when it refuses a call.const refused = (name: string, error: unknown) => { const reason = error instanceof Error ? error.message : String(error); console.log(`As ${name}:`.padEnd(11) + `Refused. ${reason}`);};
// Alice books Maple from 10:00 to 11:00, while the clock stands at midnight.console.log(`Clock: ${system.current.toUTCString()}`);const first = await book('Alice', people.alice, 'maple', 10, 11);
// Move the clock to 9:00 on the same day.// Bob asks for Maple from 10:30 to 11:30, which overlaps Alice's booking.// Then he books the same slot in Oak.await harness.tickAll({ hours: 9 });console.log(`Clock: ${system.current.toUTCString()}`);try { await book('Bob', people.bob, 'maple', 10.5, 11.5);} catch (error) { refused('Bob', error);}await book('Bob', people.bob, 'oak', 10.5, 11.5);
// Bob asks which rooms are free for two slots.await showFree('Bob', people.bob, 10, 11);await showFree('Bob', people.bob, 11.5, 12.5);
// Bob tries to cancel Alice's booking. Then Alice cancels it.try { await cancel('Bob', people.bob, first);} catch (error) { refused('Bob', error);}await cancel('Alice', people.alice, first);
// Maple is free again, and Bob books the slot the App refused.await showFree('Bob', people.bob, 10, 11);await book('Bob', people.bob, 'maple', 10.5, 11.5);
await knex.destroy();
