O

ouhammmourachid / bookings

Public

Appointment and reservation backend: bookable resources with opening hours, an availability endpoint, and overlap checks so the same slot can't be booked twice.

  • Other
  • 0 deploys
  • 0 forks

Bookings: resources, slots and no double-booking

Appointment and reservation backend: bookable resources with opening hours, an availability endpoint, and overlap checks so the same slot can't be booked twice.

What you get

  • Resources (rooms, desks, people, courts...) with opening hours and slot length
  • GET /api/resources/{id}/availability?date=YYYY-MM-DD lists free slots
  • Overlapping bookings are refused
  • Bookings must be in the future and inside opening hours
  • Users cancel their own bookings; resource owners see every booking on their resources

Collections

resources

FieldTypeNotes
name (required)text
descriptiontext
owner (required)relation → usersSet by a hook to the signed-in user
slot_minutes (required)numberSlot length for availability
open_hournumberUTC hour, 0-23
close_hour (required)numberUTC hour, 1-24
disabledboolStop taking bookings
ActionWho can do it
List / viewdisabled = false || owner = @request.auth.id
Createsigned-in users
Updateowner = @request.auth.id
Deleteowner = @request.auth.id

bookings

Bookings are cancelled, not deleted, so history is kept.

FieldTypeNotes
resource (required)relation → resources
user (required)relation → usersSet by a hook to the signed-in user
starts_at (required)dateUTC
ends_at (required)dateUTC
statusselectconfirmed or cancelled
notetext
ActionWho can do it
List / viewuser = @request.auth.id || resource.owner = @request.auth.id
Createsigned-in users
Updateuser = @request.auth.id || resource.owner = @request.auth.id
Deletesuperusers only

Hooks

All hooks are in pb_hooks/main.pb.js and commented.

Quick start

import PocketBase from "pocketbase"
const pb = new PocketBase("https://YOUR-INSTANCE.pocketshub.com")

const { slots } = await pb.send(`/api/resources/${resourceId}/availability?date=2027-01-15`, {})

await pb.collection("bookings").create({
  resource: resourceId, starts_at: slots[0].starts_at, ends_at: slots[0].ends_at, note: "Team sync",
})

// Cancel:
await pb.collection("bookings").update(bookingId, { status: "cancelled" })

Notes

  • All times are UTC. Convert to the user's timezone in your frontend.

License

MIT

resources
  • id
  • name
  • description
  • ownersingle
  • slot_minutes
  • open_hour
  • close_hour
  • disabled
  • created
  • updated
bookings
  • id
  • resourcesingle
  • usersingle
  • starts_at
  • ends_at
  • statussingle
  • note
  • created
  • updated

2 collections, 1 relation. Hover a collection to trace its relations

main.pb.js138 lines
/// <reference path="../pb_data/types.d.ts" />

// All times are UTC. open_hour / close_hour on a resource are UTC hours (0-24).

// Resources belong to the signed-in user who creates them.
onRecordCreateRequest((e) => {
  if (!e.hasSuperuserAuth()) {
    if (!e.auth) throw new UnauthorizedError("Sign in to create resources.")
    e.record.set("owner", e.auth.id)
  }
  if (e.record.getInt("close_hour") <= e.record.getInt("open_hour")) {
    throw new BadRequestError("close_hour must be after open_hour.")
  }
  e.next()
}, "resources")

onRecordUpdateRequest((e) => {
  if (!e.hasSuperuserAuth() && e.record.original().getString("owner") !== e.record.getString("owner")) {
    throw new ForbiddenError("A resource can't be moved to another user.")
  }
  if (e.record.getInt("close_hour") <= e.record.getInt("open_hour")) {
    throw new BadRequestError("close_hour must be after open_hour.")
  }
  e.next()
}, "resources")

// New booking: booked by the signed-in user, inside opening hours, in the future.
onRecordCreateRequest((e) => {
  if (!e.hasSuperuserAuth()) {
    if (!e.auth) throw new UnauthorizedError("Sign in to book.")
    e.record.set("user", e.auth.id)
  }
  e.record.set("status", "confirmed")

  let resource
  try {
    resource = e.app.findRecordById("resources", e.record.getString("resource"))
  } catch (_) {
    throw new BadRequestError("Resource not found.")
  }
  if (resource.getBool("disabled")) throw new BadRequestError("This resource can't be booked right now.")

  const start = new Date(e.record.getString("starts_at").replace(" ", "T"))
  const end = new Date(e.record.getString("ends_at").replace(" ", "T"))
  if (isNaN(start.getTime()) || isNaN(end.getTime())) throw new BadRequestError("starts_at and ends_at are required.")
  if (end <= start) throw new BadRequestError("ends_at must be after starts_at.")
  if (start < new Date()) throw new BadRequestError("You can't book in the past.")

  const sameDay = start.toISOString().slice(0, 10) === new Date(end.getTime() - 1).toISOString().slice(0, 10)
  const startMinutes = start.getUTCHours() * 60 + start.getUTCMinutes()
  const endMinutes = startMinutes + (end - start) / 60000
  if (!sameDay || startMinutes < resource.getInt("open_hour") * 60 || endMinutes > resource.getInt("close_hour") * 60) {
    throw new BadRequestError(
      `Bookings must be between ${resource.getInt("open_hour")}:00 and ${resource.getInt("close_hour")}:00 UTC on the same day.`,
    )
  }

  e.next()
}, "bookings")

// The overlap check runs in the model hook, right before the insert.
onRecordCreate((e) => {
  const clash = e.app.countRecords(
    "bookings",
    $dbx.exp(
      "resource = {:resource} AND status = 'confirmed' AND starts_at < {:end} AND ends_at > {:start}",
      {
        resource: e.record.getString("resource"),
        start: e.record.getString("starts_at"),
        end: e.record.getString("ends_at"),
      },
    ),
  )
  if (clash > 0) throw new BadRequestError("That time is already booked.")
  e.next()
}, "bookings")

// Changes to a booking: only the status (to "cancelled") and the note.
onRecordUpdateRequest((e) => {
  if (!e.hasSuperuserAuth()) {
    const original = e.record.original()
    for (const field of ["resource", "user", "starts_at", "ends_at"]) {
      if (original.getString(field) !== e.record.getString(field)) {
        throw new BadRequestError("To change the time, cancel this booking and make a new one.")
      }
    }
    if (original.getString("status") === "cancelled" && e.record.getString("status") !== "cancelled") {
      throw new BadRequestError("A cancelled booking can't be restored. Make a new one.")
    }
  }
  e.next()
}, "bookings")

// GET /api/resources/{id}/availability?date=YYYY-MM-DD  -> free slots for that UTC day.
routerAdd("GET", "/api/resources/{id}/availability", (e) => {
  const date = e.request.url.query().get("date")
  if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) throw new BadRequestError("Pass ?date=YYYY-MM-DD.")

  let resource
  try {
    resource = $app.findRecordById("resources", e.request.pathValue("id"))
  } catch (_) {
    throw new NotFoundError("Resource not found.")
  }
  if (resource.getBool("disabled")) throw new NotFoundError("Resource not found.")

  const toPb = (d) => d.toISOString().replace("T", " ")
  const dayStart = new Date(date + "T00:00:00.000Z")
  const dayEnd = new Date(dayStart.getTime() + 24 * 3600 * 1000)
  const booked = $app
    .findRecordsByFilter(
      "bookings",
      "resource = {:resource} && status = 'confirmed' && starts_at < {:dayEnd} && ends_at > {:dayStart}",
      "starts_at",
      1000,
      0,
      { resource: resource.id, dayStart: toPb(dayStart), dayEnd: toPb(dayEnd) },
    )
    .map((b) => ({
      start: new Date(b.getString("starts_at").replace(" ", "T")).getTime(),
      end: new Date(b.getString("ends_at").replace(" ", "T")).getTime(),
    }))

  const slotMs = Math.max(5, resource.getInt("slot_minutes")) * 60000
  const now = Date.now()
  const slots = []
  for (
    let t = dayStart.getTime() + resource.getInt("open_hour") * 3600000;
    t + slotMs <= dayStart.getTime() + resource.getInt("close_hour") * 3600000;
    t += slotMs
  ) {
    const end = t + slotMs
    const free = t > now && !booked.some((b) => b.start < end && b.end > t)
    if (free) slots.push({ starts_at: toPb(new Date(t)), ends_at: toPb(new Date(end)) })
  }

  return e.json(200, { resource: resource.id, date: date, slot_minutes: slotMs / 60000, slots: slots })
})