@ordinatio/scheduling 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +22 -0
- package/LICENSE +21 -0
- package/README.md +254 -2
- package/dist/index.d.mts +1895 -0
- package/dist/index.d.ts +1895 -0
- package/dist/index.js +3940 -0
- package/dist/index.mjs +3847 -0
- package/package.json +50 -3
- package/prisma/migrations/20261016150000_baseline/migration.sql +476 -0
- package/prisma/migrations/migration_lock.toml +3 -0
- package/prisma/schema.prisma +502 -0
- package/prisma.config.ts +12 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.2.0
|
|
4
|
+
|
|
5
|
+
The first release on npm.
|
|
6
|
+
|
|
7
|
+
- **Engine.** Calendars, appointment types, weekly hours and date overrides, open-slot search, booking,
|
|
8
|
+
cancel, reschedule, no-show, group events, repeat series, team round-robin, and a queue of notifications
|
|
9
|
+
with reminders.
|
|
10
|
+
- **Its own database tables.** The package brings its own Prisma schema and one baseline migration that
|
|
11
|
+
builds an empty Postgres database. It needs `@prisma/client` 7.3 or newer.
|
|
12
|
+
- **Adapters.** Plug-in points for the clock, notifications, payments, calendar sync and sign-in, each with an
|
|
13
|
+
in-memory version and a contract check. Notifications and payments are wired into the engine through
|
|
14
|
+
`adaptersToCallbacks`.
|
|
15
|
+
- **Day picking.** Asking for the slots of a day now uses the calendar's own day. Before, a calendar west of
|
|
16
|
+
UTC could return the previous day's slots.
|
|
17
|
+
- **Types.** `SchedulingDb` no longer requires a `client` table, which the package's own schema does not have.
|
|
18
|
+
- **README and quick start** with a check that follows them in an empty folder.
|
|
19
|
+
|
|
20
|
+
Not in this package yet: the HTTP API, the booking widget (published separately) and the staff dashboard.
|
|
21
|
+
The clock, calendar-sync and sign-in adapters have an interface and an in-memory version, but the engine
|
|
22
|
+
does not use them yet.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Ordinatio
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,255 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @ordinatio/scheduling
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A booking engine. It finds open times, books one, and refuses a second booking for the same time. It keeps
|
|
4
|
+
its data in your own Postgres database.
|
|
5
|
+
|
|
6
|
+
**Status:** version 0.1.0. It is not on npm yet. Until it is, install it from a packed tarball: see
|
|
7
|
+
`examples/scheduling-starter` in this repository. The steps below are the steps for after the release.
|
|
8
|
+
|
|
9
|
+
## Words used here
|
|
10
|
+
|
|
11
|
+
- **Calendar:** one person or room that can be booked.
|
|
12
|
+
- **Appointment type:** a kind of booking, such as "Consultation, 30 minutes".
|
|
13
|
+
- **Weekly hours:** the hours a calendar is open each week.
|
|
14
|
+
- **Slot:** one open time that can be booked.
|
|
15
|
+
- **Adapter:** a small piece of code you supply for anything outside the database: payment, email, text
|
|
16
|
+
messages, calendar sync, the clock, sign-in.
|
|
17
|
+
|
|
18
|
+
## What you need
|
|
19
|
+
|
|
20
|
+
- Node 22 or newer.
|
|
21
|
+
- A Postgres database with nothing in it. Write down its address. It looks like
|
|
22
|
+
`postgresql://user:password@localhost:5432/your_empty_database`.
|
|
23
|
+
- npm. (pnpm works too.)
|
|
24
|
+
- Peer dependency: `@prisma/client` 7.3 or newer. This README was tested with 7.6.0. The quick start also
|
|
25
|
+
uses `@prisma/adapter-pg` to connect to Postgres.
|
|
26
|
+
|
|
27
|
+
## Quick start
|
|
28
|
+
|
|
29
|
+
You will build a small project that books one appointment and then shows a second booking for the same time
|
|
30
|
+
being refused. It takes about five minutes.
|
|
31
|
+
|
|
32
|
+
### 1. Make a project
|
|
33
|
+
|
|
34
|
+
Make an empty folder and open a terminal in it. Then run:
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
npm init -y
|
|
38
|
+
npm pkg set type=module
|
|
39
|
+
npm install @ordinatio/scheduling @prisma/client@7.6.0 @prisma/adapter-pg@7.6.0
|
|
40
|
+
npm install --save-dev prisma@7.6.0 tsx
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
### 2. Build the tables
|
|
44
|
+
|
|
45
|
+
Put your own database address in the first line. The package brings its own table definitions and one
|
|
46
|
+
migration. These two commands create the tables in your empty database.
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
export DATABASE_URL="postgresql://user:password@localhost:5432/your_empty_database"
|
|
50
|
+
npx prisma generate --config node_modules/@ordinatio/scheduling/prisma.config.ts
|
|
51
|
+
npx prisma migrate deploy --config node_modules/@ordinatio/scheduling/prisma.config.ts
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
### 3. Write the script
|
|
55
|
+
|
|
56
|
+
Save this as `book.ts` in the same folder. Every table belongs to an organization, so the script first adds
|
|
57
|
+
one row for it. That row is the only thing your app must provide.
|
|
58
|
+
|
|
59
|
+
```ts file=book.ts
|
|
60
|
+
import { PrismaClient } from '@prisma/client';
|
|
61
|
+
import { PrismaPg } from '@prisma/adapter-pg';
|
|
62
|
+
import {
|
|
63
|
+
createCalendar,
|
|
64
|
+
createAppointmentType,
|
|
65
|
+
setWeeklyAvailability,
|
|
66
|
+
getAvailableSlots,
|
|
67
|
+
bookAppointment,
|
|
68
|
+
} from '@ordinatio/scheduling';
|
|
69
|
+
|
|
70
|
+
const connectionString = process.env.DATABASE_URL?.trim();
|
|
71
|
+
if (!connectionString) {
|
|
72
|
+
console.error('DATABASE_URL is not set.');
|
|
73
|
+
process.exit(2);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const prisma = new PrismaClient({ adapter: new PrismaPg({ connectionString }) });
|
|
77
|
+
|
|
78
|
+
// The next weekday at least two days away, at noon UTC, so it is the same day in the Americas.
|
|
79
|
+
function nextWeekday(): Date {
|
|
80
|
+
const day = new Date();
|
|
81
|
+
day.setUTCHours(12, 0, 0, 0);
|
|
82
|
+
day.setUTCDate(day.getUTCDate() + 2);
|
|
83
|
+
while ([0, 6].includes(day.getUTCDay())) day.setUTCDate(day.getUTCDate() + 1);
|
|
84
|
+
return day;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
async function main(): Promise<void> {
|
|
88
|
+
const timezone = 'America/New_York';
|
|
89
|
+
const suffix = Date.now().toString(36);
|
|
90
|
+
|
|
91
|
+
const organization = await prisma.organization.upsert({
|
|
92
|
+
where: { id: 'demo-org' },
|
|
93
|
+
update: {},
|
|
94
|
+
create: { id: 'demo-org', name: 'Demo Studio' },
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
const calendar = await createCalendar(prisma, {
|
|
98
|
+
organizationId: organization.id,
|
|
99
|
+
name: 'Front desk',
|
|
100
|
+
slug: `front-desk-${suffix}`,
|
|
101
|
+
type: 'STAFF',
|
|
102
|
+
timezone,
|
|
103
|
+
});
|
|
104
|
+
const appointmentType = await createAppointmentType(prisma, {
|
|
105
|
+
organizationId: organization.id,
|
|
106
|
+
name: 'Consultation',
|
|
107
|
+
slug: `consultation-${suffix}`,
|
|
108
|
+
duration: 30,
|
|
109
|
+
calendarIds: [calendar.id],
|
|
110
|
+
});
|
|
111
|
+
await setWeeklyAvailability(
|
|
112
|
+
prisma,
|
|
113
|
+
calendar.id,
|
|
114
|
+
[1, 2, 3, 4, 5].map((dayOfWeek) => ({ dayOfWeek, startTime: '09:00', endTime: '17:00', minNotice: 0 })),
|
|
115
|
+
);
|
|
116
|
+
|
|
117
|
+
const { slots } = await getAvailableSlots(prisma, {
|
|
118
|
+
calendarId: calendar.id,
|
|
119
|
+
date: nextWeekday(),
|
|
120
|
+
duration: appointmentType.duration,
|
|
121
|
+
timezone,
|
|
122
|
+
});
|
|
123
|
+
if (slots.length === 0) throw new Error('No open slots were found.');
|
|
124
|
+
const slot = slots[0];
|
|
125
|
+
console.log(`Open slots on the demo day: ${slots.length}. Booking the first, at ${slot.start.toISOString()}.`);
|
|
126
|
+
|
|
127
|
+
const booking = await bookAppointment(prisma, {
|
|
128
|
+
calendarId: calendar.id,
|
|
129
|
+
typeId: appointmentType.id,
|
|
130
|
+
startTime: slot.start,
|
|
131
|
+
timezone,
|
|
132
|
+
clientName: 'Jane Smith',
|
|
133
|
+
clientEmail: 'jane@example.com',
|
|
134
|
+
});
|
|
135
|
+
console.log(`Booked: ${booking.id}`);
|
|
136
|
+
console.log(` ${booking.clientName} <${booking.clientEmail}>`);
|
|
137
|
+
console.log(` ${booking.typeName} with ${booking.calendarName}`);
|
|
138
|
+
console.log(` ${booking.startTime.toISOString()} to ${booking.endTime.toISOString()} (${booking.status})`);
|
|
139
|
+
|
|
140
|
+
try {
|
|
141
|
+
await bookAppointment(prisma, {
|
|
142
|
+
calendarId: calendar.id,
|
|
143
|
+
typeId: appointmentType.id,
|
|
144
|
+
startTime: slot.start,
|
|
145
|
+
timezone,
|
|
146
|
+
clientName: 'John Doe',
|
|
147
|
+
clientEmail: 'john@example.com',
|
|
148
|
+
});
|
|
149
|
+
} catch (error) {
|
|
150
|
+
const code = (error as { code?: string }).code;
|
|
151
|
+
if (code !== 'SCHED_301') throw error;
|
|
152
|
+
console.log(`Second booking for the same slot was refused: ${code} (slot not available).`);
|
|
153
|
+
console.log('Demo complete.');
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
throw new Error('The second booking for the same slot was accepted. Double booking must be refused.');
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
main()
|
|
160
|
+
.catch((error) => {
|
|
161
|
+
console.error(error instanceof Error ? error.message : error);
|
|
162
|
+
process.exitCode = 1;
|
|
163
|
+
})
|
|
164
|
+
.finally(() => prisma.$disconnect());
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
### 4. Run it
|
|
168
|
+
|
|
169
|
+
```bash
|
|
170
|
+
npx tsx book.ts
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
It prints this. The times and the booking id will differ.
|
|
174
|
+
|
|
175
|
+
```text expected
|
|
176
|
+
Open slots on the demo day: <count>. Booking the first, at <time>.
|
|
177
|
+
Booked: <id>
|
|
178
|
+
Jane Smith <jane@example.com>
|
|
179
|
+
Consultation with Front desk
|
|
180
|
+
<start> to <end> (CONFIRMED)
|
|
181
|
+
Second booking for the same slot was refused: SCHED_301 (slot not available).
|
|
182
|
+
Demo complete.
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
The second booking is refused by the database, not only by the script. The package's migration creates a
|
|
186
|
+
unique index on live bookings, so two people who book the same slot at the same moment cannot both win.
|
|
187
|
+
|
|
188
|
+
### Check that this README still works
|
|
189
|
+
|
|
190
|
+
From this package's folder, run `bash scripts/check-readme.sh`. It follows the steps above in an empty folder
|
|
191
|
+
against a scratch Postgres database and compares the output with the block above. It needs a local Postgres
|
|
192
|
+
that your user can create databases in.
|
|
193
|
+
|
|
194
|
+
### Use it in an app you already have
|
|
195
|
+
|
|
196
|
+
The tables are defined in `node_modules/@ordinatio/scheduling/prisma/schema.prisma`. Add those models to your
|
|
197
|
+
own Prisma schema, or keep them in their own database. Bookings need an `Organization` row. If your app
|
|
198
|
+
already has an `Organization` table, merge the two by hand and check the migration before you run it.
|
|
199
|
+
|
|
200
|
+
## Adapters
|
|
201
|
+
|
|
202
|
+
The engine does not call any vendor. Everything outside the database goes through small adapters you
|
|
203
|
+
supply, so the same engine runs in tests, in an example app, and in production.
|
|
204
|
+
|
|
205
|
+
Not every adapter is wired into the engine yet:
|
|
206
|
+
|
|
207
|
+
- **Wired today** (through `adaptersToCallbacks`): `notifications` and `payments`.
|
|
208
|
+
- **Interface and in-memory version only, not yet used by the engine:** `clock`, `calendarSync`, `auth`.
|
|
209
|
+
The engine still reads the system time, and calendar sync and sign-in still live in the host app.
|
|
210
|
+
A custom `clock` does not change the engine's idea of "now" yet.
|
|
211
|
+
|
|
212
|
+
| Adapter | Job | Promise the contract check enforces |
|
|
213
|
+
|---|---|---|
|
|
214
|
+
| `clock` | The current time | `now()` returns a valid `Date` and does not go backwards across six consecutive calls |
|
|
215
|
+
| `notifications` | Send an email or text | Never reports `SENT` for an empty or blank recipient |
|
|
216
|
+
| `payments` | Charge, verify, refund | A zero charge fails; an unknown payment is not paid; `verify` returns the metadata, and the charged amount when the adapter can convert the currency; a fully refunded payment is not paid; a partial refund needs an `idempotencyKey` and works up to what is left, never beyond; a repeated refund key refunds once; a repeat refund says `ALREADY_REFUNDED`; a repeated charge `idempotencyKey` charges once |
|
|
217
|
+
| `calendarSync` | Add, move, remove a calendar event | Repeat upserts do not throw and keep one external id when ids are returned; removing a missing event does not throw |
|
|
218
|
+
| `auth` | Turn request headers into `{ userId, organizationId, roles }` | Returns `null`, never throws, for missing or unknown credentials |
|
|
219
|
+
|
|
220
|
+
The checks cannot see inside your calendar provider, so "one event per appointment" is yours to test
|
|
221
|
+
beyond what the external id shows.
|
|
222
|
+
|
|
223
|
+
```ts
|
|
224
|
+
import { createInMemoryAdapters, adaptersToCallbacks, bookAppointment } from '@ordinatio/scheduling';
|
|
225
|
+
|
|
226
|
+
const { adapters, records } = createInMemoryAdapters();
|
|
227
|
+
await bookAppointment(db, input, adaptersToCallbacks(adapters));
|
|
228
|
+
console.log(records.sent); // the confirmation that would have been sent
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
`createInMemoryAdapters()` never touches the network. It records every message, charge, refund and
|
|
232
|
+
calendar event, and gives a clock you can move (`clock.set(date)`, `clock.advance(ms)`). The clock
|
|
233
|
+
starts at a fixed date (2026-01-01 UTC), not the real time, unless you pass `now`.
|
|
234
|
+
|
|
235
|
+
### Check your own adapter
|
|
236
|
+
|
|
237
|
+
Each adapter has a contract check that returns a list of plain-language failures. An empty list means
|
|
238
|
+
the adapter keeps the promises above.
|
|
239
|
+
|
|
240
|
+
```ts
|
|
241
|
+
import { checkPaymentContract } from '@ordinatio/scheduling';
|
|
242
|
+
|
|
243
|
+
// A payment the client confirms in the browser (charge returns REQUIRES_ACTION) needs a way to confirm it
|
|
244
|
+
// here, for example the provider's test card. Without completePayment the check fails instead of passing.
|
|
245
|
+
const failures = await checkPaymentContract(myStripeAdapter, {
|
|
246
|
+
completePayment: async (charge) => confirmWithTestCard(charge.paymentId!),
|
|
247
|
+
});
|
|
248
|
+
if (failures.length > 0) throw new Error(failures.join('\n'));
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
Available: `checkClockContract`, `checkNotificationContract`, `checkPaymentContract`,
|
|
252
|
+
`checkCalendarSyncContract`, `checkAuthContract`. Run them against a sandbox account, not a live one:
|
|
253
|
+
the payment check makes a real charge and refund (use the provider's test mode), the notification check sends a real message to
|
|
254
|
+
`contract@example.com`, and the calendar check creates and removes a real event. Pass valid
|
|
255
|
+
credentials as the second argument to `checkAuthContract`, or it cannot check that valid sign-ins work.
|