@attraccess/plugin-reservations 0.1.0-nightly.1140.3 → 0.1.0-nightly.1161.1

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/dist/index.js CHANGED
@@ -35,7 +35,7 @@ __export(plugin_exports, {
35
35
  module.exports = __toCommonJS(plugin_exports);
36
36
 
37
37
  // backend/api/settings.controller.ts
38
- var import_plugins_backend_sdk7 = require("@attraccess/plugins-backend-sdk");
38
+ var import_plugins_backend_sdk8 = require("@attraccess/plugins-backend-sdk");
39
39
  var import_common12 = require("@nestjs/common");
40
40
  var import_swagger4 = require("@nestjs/swagger");
41
41
 
@@ -47,6 +47,7 @@ var PLUGIN_CONTEXT = /* @__PURE__ */ Symbol.for("attraccess.plugin.context");
47
47
  var RESERVATION_NOTIFIER = /* @__PURE__ */ Symbol.for("attraccess.reservations.notifier");
48
48
  var RESERVATION_CLOCK = /* @__PURE__ */ Symbol.for("attraccess.reservations.clock");
49
49
  var READER_HORIZON_MS = 24 * 60 * 6e4;
50
+ var CAPACITY_REDUCED_REASON = "machine capacity reduced";
50
51
 
51
52
  // backend/reservations/actor.ts
52
53
  function subjectOfPrincipal(principal) {
@@ -165,6 +166,7 @@ var BOOKING_CONFLICT_CODES = [
165
166
  "OUTSIDE_BOOKABLE_HOURS",
166
167
  "USER_BOOKING_LIMIT",
167
168
  "OVERLAP",
169
+ "OWN_OVERLAP",
168
170
  "MAINTENANCE"
169
171
  ];
170
172
  var STATE_CONFLICT_CODES = [
@@ -191,29 +193,354 @@ var ReservationError = class extends import_common2.HttpException {
191
193
  super({ code, message, ...extra }, STATUS_BY_CODE[code] ?? import_common2.HttpStatus.CONFLICT);
192
194
  __publicField(this, "code", code);
193
195
  }
194
- };
196
+ };
197
+
198
+ // backend/reservations/directory.service.ts
199
+ var import_plugins_backend_sdk2 = require("@attraccess/plugins-backend-sdk");
200
+ var import_common3 = require("@nestjs/common");
201
+
202
+ // backend/reservations/capacity.ts
203
+ var import_plugins_backend_sdk = require("@attraccess/plugins-backend-sdk");
204
+
205
+ // backend/time/zone.ts
206
+ var formatters = /* @__PURE__ */ new Map();
207
+ function formatterFor(timeZone) {
208
+ let formatter = formatters.get(timeZone);
209
+ if (!formatter) {
210
+ formatter = new Intl.DateTimeFormat("en-US", {
211
+ timeZone,
212
+ hourCycle: "h23",
213
+ year: "numeric",
214
+ month: "numeric",
215
+ day: "numeric",
216
+ hour: "numeric",
217
+ minute: "numeric",
218
+ second: "numeric"
219
+ });
220
+ formatters.set(timeZone, formatter);
221
+ }
222
+ return formatter;
223
+ }
224
+ function isValidTimeZone(timeZone) {
225
+ if (typeof timeZone !== "string" || timeZone.length === 0 || timeZone.length > 100) return false;
226
+ try {
227
+ new Intl.DateTimeFormat("en-US", { timeZone });
228
+ return true;
229
+ } catch {
230
+ return false;
231
+ }
232
+ }
233
+ function serverTimeZone() {
234
+ const resolved = Intl.DateTimeFormat().resolvedOptions().timeZone;
235
+ return isValidTimeZone(resolved) ? resolved : "UTC";
236
+ }
237
+ function getWallClock(date, timeZone) {
238
+ const parts = formatterFor(timeZone).formatToParts(date);
239
+ const read = (type) => Number(parts.find((part) => part.type === type)?.value ?? 0);
240
+ return {
241
+ year: read("year"),
242
+ month: read("month"),
243
+ day: read("day"),
244
+ hour: read("hour") % 24,
245
+ minute: read("minute"),
246
+ second: read("second")
247
+ };
248
+ }
249
+ function offsetMs(date, timeZone) {
250
+ const wall = getWallClock(date, timeZone);
251
+ const asUtc = Date.UTC(wall.year, wall.month - 1, wall.day, wall.hour, wall.minute, wall.second);
252
+ return asUtc - Math.floor(date.getTime() / 1e3) * 1e3;
253
+ }
254
+ var DAY_MS = 864e5;
255
+ function wallOf(date, timeZone) {
256
+ const wall = getWallClock(date, timeZone);
257
+ return Date.UTC(wall.year, wall.month - 1, wall.day, wall.hour, wall.minute, wall.second);
258
+ }
259
+ function wallClockToDate(local, timeZone) {
260
+ const target = Date.UTC(
261
+ local.year,
262
+ local.month - 1,
263
+ local.day,
264
+ local.hour ?? 0,
265
+ local.minute ?? 0,
266
+ local.second ?? 0
267
+ );
268
+ const before = offsetMs(new Date(target - DAY_MS), timeZone);
269
+ const after = offsetMs(new Date(target + DAY_MS), timeZone);
270
+ const first = target - before;
271
+ if (before === after || wallOf(new Date(first), timeZone) === target) return new Date(first);
272
+ const second = target - after;
273
+ if (wallOf(new Date(second), timeZone) === target) return new Date(second);
274
+ return new Date(first);
275
+ }
276
+ function localDateOf(date, timeZone) {
277
+ const { year, month, day } = getWallClock(date, timeZone);
278
+ return { year, month, day };
279
+ }
280
+ function addLocalDays(date, days) {
281
+ const moved = new Date(Date.UTC(date.year, date.month - 1, date.day + days));
282
+ return { year: moved.getUTCFullYear(), month: moved.getUTCMonth() + 1, day: moved.getUTCDate() };
283
+ }
284
+ function weekdayOf(date) {
285
+ return new Date(Date.UTC(date.year, date.month - 1, date.day)).getUTCDay();
286
+ }
287
+ function localMinutesOfDay(date, timeZone) {
288
+ const wall = getWallClock(date, timeZone);
289
+ return wall.hour * 60 + wall.minute;
290
+ }
291
+ function isWholeMinute(date) {
292
+ return date.getTime() % 6e4 === 0;
293
+ }
294
+
295
+ // backend/time/bookable-hours.ts
296
+ var WEEKDAYS = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
297
+ var MAX_RANGES_PER_DAY = 8;
298
+ var HM = /^([01]\d|2[0-3]):([0-5]\d)$|^24:00$/;
299
+ function parseHm(value) {
300
+ const [hours, minutes] = value.split(":").map(Number);
301
+ return hours * 60 + minutes;
302
+ }
303
+ function hasRestrictions(hours) {
304
+ return WEEKDAYS.some((day) => (hours[day]?.length ?? 0) > 0);
305
+ }
306
+ function validateBookableHours(input) {
307
+ const errors = [];
308
+ if (input === null || typeof input !== "object" || Array.isArray(input)) {
309
+ return [{ field: "bookableHours", message: "must be an object keyed by weekday" }];
310
+ }
311
+ for (const [day, ranges] of Object.entries(input)) {
312
+ const field = `bookableHours.${day}`;
313
+ if (!WEEKDAYS.includes(day)) {
314
+ errors.push({ field, message: `unknown weekday, expected one of ${WEEKDAYS.join(", ")}` });
315
+ continue;
316
+ }
317
+ if (!Array.isArray(ranges) || ranges.length > MAX_RANGES_PER_DAY) {
318
+ errors.push({ field, message: `must be a list of at most ${MAX_RANGES_PER_DAY} ranges` });
319
+ continue;
320
+ }
321
+ const parsed = [];
322
+ for (const range2 of ranges) {
323
+ const start = range2?.start;
324
+ const end = range2?.end;
325
+ if (typeof start !== "string" || typeof end !== "string" || !HM.test(start) || !HM.test(end) || start === "24:00") {
326
+ errors.push({ field, message: "ranges need start and end as HH:mm (end may be 24:00)" });
327
+ continue;
328
+ }
329
+ if (parseHm(start) >= parseHm(end)) {
330
+ errors.push({ field, message: `range ${start}-${end} must end after it starts` });
331
+ continue;
332
+ }
333
+ parsed.push([parseHm(start), parseHm(end)]);
334
+ }
335
+ parsed.sort((a, b) => a[0] - b[0]);
336
+ for (let i = 1; i < parsed.length; i += 1) {
337
+ if (parsed[i][0] < parsed[i - 1][1]) errors.push({ field, message: "ranges must not overlap" });
338
+ }
339
+ }
340
+ return errors;
341
+ }
342
+ function normalizeBookableHours(hours) {
343
+ const result = {};
344
+ for (const day of WEEKDAYS) {
345
+ const ranges = hours[day];
346
+ if (ranges && ranges.length > 0) {
347
+ result[day] = ranges.map(({ start, end }) => ({ start, end })).sort((a, b) => parseHm(a.start) - parseHm(b.start));
348
+ }
349
+ }
350
+ return result;
351
+ }
352
+ function bookableIntervals(hours, timeZone, from, to) {
353
+ const first = addLocalDays(localDateOf(from, timeZone), -1);
354
+ const last = addLocalDays(localDateOf(to, timeZone), 1);
355
+ const raw = [];
356
+ const key = (d) => d.year * 1e4 + d.month * 100 + d.day;
357
+ for (let day = first; key(day) <= key(last); day = addLocalDays(day, 1)) {
358
+ for (const range2 of hours[WEEKDAYS[weekdayOf(day)]] ?? []) {
359
+ const toMidnight = range2.end === "24:00";
360
+ raw.push({
361
+ start: wallClockToDate(
362
+ { ...day, hour: Math.floor(parseHm(range2.start) / 60), minute: parseHm(range2.start) % 60 },
363
+ timeZone
364
+ ),
365
+ end: toMidnight ? wallClockToDate(addLocalDays(day, 1), timeZone) : wallClockToDate(
366
+ { ...day, hour: Math.floor(parseHm(range2.end) / 60), minute: parseHm(range2.end) % 60 },
367
+ timeZone
368
+ ),
369
+ fromMidnight: parseHm(range2.start) === 0,
370
+ toMidnight
371
+ });
372
+ }
373
+ }
374
+ raw.sort((a, b) => a.start.getTime() - b.start.getTime());
375
+ const joined = [];
376
+ for (const interval of raw) {
377
+ const previous = joined[joined.length - 1];
378
+ const crossesMidnight = previous?.toMidnight && interval.fromMidnight && interval.start.getTime() === previous.end.getTime();
379
+ if (previous && crossesMidnight) {
380
+ previous.end = interval.end;
381
+ previous.toMidnight = interval.toMidnight;
382
+ } else {
383
+ joined.push({ ...interval });
384
+ }
385
+ }
386
+ return joined.map(({ start, end }) => ({ start, end }));
387
+ }
388
+ function isWithinBookableHours(hours, timeZone, start, end) {
389
+ if (!hasRestrictions(hours)) return true;
390
+ return bookableIntervals(hours, timeZone, start, end).some(
391
+ (interval) => interval.start.getTime() <= start.getTime() && end.getTime() <= interval.end.getTime()
392
+ );
393
+ }
394
+
395
+ // backend/reservations/rules.ts
396
+ var MINUTE_MS = 6e4;
397
+ var PAST_TOLERANCE_MS = MINUTE_MS;
398
+ function blockedSpan(booking) {
399
+ return {
400
+ start: new Date(booking.startTime.getTime() - booking.bufferBeforeMinutes * MINUTE_MS),
401
+ end: new Date(booking.endTime.getTime() + booking.bufferAfterMinutes * MINUTE_MS)
402
+ };
403
+ }
404
+ function spansOverlap(a, b) {
405
+ return a.start.getTime() < b.end.getTime() && b.start.getTime() < a.end.getTime();
406
+ }
407
+ function checkBookingRules(args) {
408
+ const { settings, timeZone, start, end, now } = args;
409
+ if (Number.isNaN(start.getTime()) || Number.isNaN(end.getTime()) || end.getTime() <= start.getTime()) {
410
+ return new ReservationError("INVALID_RANGE", "The end must be after the start");
411
+ }
412
+ if (start.getTime() < now.getTime() - PAST_TOLERANCE_MS) {
413
+ return new ReservationError("IN_THE_PAST", "The booking starts in the past");
414
+ }
415
+ const step = settings.timeStepMinutes;
416
+ const durationMinutes = (end.getTime() - start.getTime()) / MINUTE_MS;
417
+ const onGrid = isWholeMinute(start) && isWholeMinute(end) && localMinutesOfDay(start, timeZone) % step === 0 && durationMinutes % step === 0;
418
+ if (!onGrid) {
419
+ return new ReservationError("OFF_TIME_STEP", `Start and duration must be a multiple of ${step} minutes`);
420
+ }
421
+ if (durationMinutes < settings.minDurationMinutes) {
422
+ return new ReservationError("DURATION_TOO_SHORT", `The minimum duration is ${settings.minDurationMinutes} minutes`);
423
+ }
424
+ if (durationMinutes > settings.maxDurationMinutes) {
425
+ return new ReservationError("DURATION_TOO_LONG", `The maximum duration is ${settings.maxDurationMinutes} minutes`);
426
+ }
427
+ if (start.getTime() > now.getTime() + settings.maxAdvanceDays * 864e5) {
428
+ return new ReservationError(
429
+ "BEYOND_MAX_ADVANCE",
430
+ `Bookings can be made at most ${settings.maxAdvanceDays} days ahead`
431
+ );
432
+ }
433
+ if (settings.minLeadMinutes > 0 && start.getTime() < now.getTime() + settings.minLeadMinutes * MINUTE_MS) {
434
+ return new ReservationError(
435
+ "LEAD_TIME_TOO_SHORT",
436
+ `Bookings must be made at least ${settings.minLeadMinutes} minutes before they start`
437
+ );
438
+ }
439
+ const span = blockedSpan({
440
+ startTime: start,
441
+ endTime: end,
442
+ bufferBeforeMinutes: settings.bufferBeforeMinutes,
443
+ bufferAfterMinutes: settings.bufferAfterMinutes
444
+ });
445
+ if (!isWithinBookableHours(settings.bookableHours, timeZone, span.start, span.end)) {
446
+ return new ReservationError("OUTSIDE_BOOKABLE_HOURS", "The booking is outside the bookable hours");
447
+ }
448
+ return null;
449
+ }
450
+
451
+ // backend/reservations/capacity.ts
452
+ function sessionLimitOf(resource) {
453
+ return resource?.type === import_plugins_backend_sdk.ResourceType.Machine ? Math.max(1, resource.maxParallelSessions ?? 1) : 1;
454
+ }
455
+ function peakConcurrency(spans, window) {
456
+ const from = window.start.getTime();
457
+ const to = window.end.getTime();
458
+ const events = [];
459
+ for (const span of spans) {
460
+ const start = Math.max(span.start.getTime(), from);
461
+ const end = Math.min(span.end.getTime(), to);
462
+ if (start >= end) continue;
463
+ events.push([start, 1], [end, -1]);
464
+ }
465
+ events.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
466
+ let open = 0;
467
+ let peak = 0;
468
+ for (const [, delta] of events) {
469
+ open += delta;
470
+ peak = Math.max(peak, open);
471
+ }
472
+ return peak;
473
+ }
474
+ function exceedsCapacity(occupying, candidate, limit) {
475
+ return peakConcurrency(occupying, candidate) + 1 > limit;
476
+ }
477
+ function heldBookings(args) {
478
+ const at = args.at.getTime();
479
+ const seen = /* @__PURE__ */ new Set();
480
+ return args.confirmed.filter(
481
+ (b) => b.userId !== args.starterId && b.startTime.getTime() <= at && at < b.endTime.getTime() && !args.inSession.has(b.userId) && !args.overridden?.has(b.id)
482
+ ).sort((a, b) => a.endTime.getTime() - b.endTime.getTime() || a.startTime.getTime() - b.startTime.getTime()).filter((b) => !seen.has(b.userId) && !!seen.add(b.userId));
483
+ }
484
+ function selectExcessBookings(occupying, limit, now) {
485
+ const nowMs = now.getTime();
486
+ const remaining = new Set(
487
+ occupying.map((booking) => ({ booking, ...spanMs(booking) })).filter((span) => span.end > nowMs)
488
+ );
489
+ const instants = [...new Set([...remaining].map((span) => Math.max(span.start, nowMs)))].sort((a, b) => a - b);
490
+ const cancelled = [];
491
+ for (const t of instants) {
492
+ for (let victim = excessAt(remaining, t, limit, nowMs); victim; victim = excessAt(remaining, t, limit, nowMs)) {
493
+ remaining.delete(victim);
494
+ cancelled.push(victim.booking);
495
+ }
496
+ }
497
+ return cancelled;
498
+ }
499
+ function spanMs(booking) {
500
+ const span = blockedSpan(booking);
501
+ return { start: span.start.getTime(), end: span.end.getTime() };
502
+ }
503
+ function excessAt(spans, t, limit, nowMs) {
504
+ const covering = [...spans].filter((span) => span.start <= t && t < span.end);
505
+ if (covering.length <= limit) return void 0;
506
+ return covering.filter(({ booking }) => booking.startTime.getTime() > nowMs && !booking.checkedInAt).sort((a, b) => b.booking.createdAt.getTime() - a.booking.createdAt.getTime() || b.booking.id - a.booking.id)[0];
507
+ }
195
508
 
196
509
  // backend/reservations/directory.service.ts
197
- var import_plugins_backend_sdk = require("@attraccess/plugins-backend-sdk");
198
- var import_common3 = require("@nestjs/common");
199
510
  var DirectoryService = class {
200
511
  constructor(context) {
201
512
  __publicField(this, "context", context);
202
513
  }
203
514
  async getResource(resourceId) {
204
- const row = await this.context.getRepository(import_plugins_backend_sdk.Resource).findOne({ where: { id: resourceId }, select: { id: true, name: true } });
515
+ const row = await this.context.getRepository(import_plugins_backend_sdk2.Resource).findOne({ where: { id: resourceId }, select: { id: true, name: true } });
205
516
  return row ? { id: row.id, name: row.name } : null;
206
517
  }
518
+ /** Effective session limit (core's rule): 1 for doors, unknown resources and machines without parallel sessions. */
519
+ async getSessionLimit(resourceId, manager) {
520
+ return await this.findSessionLimit(resourceId, manager) ?? 1;
521
+ }
522
+ /** Effective session limit, or null when the resource does not exist (anymore: deleted resources are not found). */
523
+ async findSessionLimit(resourceId, manager) {
524
+ const row = await (manager ? manager.getRepository(import_plugins_backend_sdk2.Resource) : this.context.getRepository(import_plugins_backend_sdk2.Resource)).findOne({
525
+ where: { id: resourceId },
526
+ select: { id: true, type: true, maxParallelSessions: true }
527
+ });
528
+ return row ? sessionLimitOf(row) : null;
529
+ }
530
+ /** Running sessions on the resource, earliest first. */
531
+ getActiveSessions(resourceId) {
532
+ return this.context.resourceAccess.getActiveSessions(resourceId);
533
+ }
207
534
  async getResourceNames(resourceIds) {
208
535
  const ids = [...new Set(resourceIds)];
209
536
  if (ids.length === 0) return /* @__PURE__ */ new Map();
210
- const rows = await this.context.getRepository(import_plugins_backend_sdk.Resource).createQueryBuilder("resource").select(["resource.id", "resource.name"]).where("resource.id IN (:...ids)", { ids }).getMany();
537
+ const rows = await this.context.getRepository(import_plugins_backend_sdk2.Resource).createQueryBuilder("resource").select(["resource.id", "resource.name"]).where("resource.id IN (:...ids)", { ids }).getMany();
211
538
  return new Map(rows.map((row) => [row.id, row.name]));
212
539
  }
213
540
  async getUserNames(userIds) {
214
541
  const ids = [...new Set(userIds)];
215
542
  if (ids.length === 0) return /* @__PURE__ */ new Map();
216
- const rows = await this.context.getRepository(import_plugins_backend_sdk.User).createQueryBuilder("user").select(["user.id", "user.username"]).where("user.id IN (:...ids)", { ids }).getMany();
543
+ const rows = await this.context.getRepository(import_plugins_backend_sdk2.User).createQueryBuilder("user").select(["user.id", "user.username"]).where("user.id IN (:...ids)", { ids }).getMany();
217
544
  return new Map(rows.map((row) => [row.id, row.username]));
218
545
  }
219
546
  };
@@ -229,7 +556,7 @@ var import_common9 = require("@nestjs/common");
229
556
  var import_common8 = require("@nestjs/common");
230
557
 
231
558
  // backend/entities/reservation.entity.ts
232
- var import_plugins_backend_sdk2 = require("@attraccess/plugins-backend-sdk");
559
+ var import_plugins_backend_sdk3 = require("@attraccess/plugins-backend-sdk");
233
560
  var RESERVATION_STATUSES = [
234
561
  "pending",
235
562
  "confirmed",
@@ -279,91 +606,91 @@ var ReservationEntity = class {
279
606
  }
280
607
  };
281
608
  __decorateClass([
282
- (0, import_plugins_backend_sdk2.PrimaryGeneratedColumn)({ type: "integer" })
609
+ (0, import_plugins_backend_sdk3.PrimaryGeneratedColumn)({ type: "integer" })
283
610
  ], ReservationEntity.prototype, "id", 2);
284
611
  __decorateClass([
285
- (0, import_plugins_backend_sdk2.Column)({ type: "integer" })
612
+ (0, import_plugins_backend_sdk3.Column)({ type: "integer" })
286
613
  ], ReservationEntity.prototype, "resourceId", 2);
287
614
  __decorateClass([
288
- (0, import_plugins_backend_sdk2.Column)({ type: "integer" })
615
+ (0, import_plugins_backend_sdk3.Column)({ type: "integer" })
289
616
  ], ReservationEntity.prototype, "userId", 2);
290
617
  __decorateClass([
291
- (0, import_plugins_backend_sdk2.Column)({ type: "datetime" })
618
+ (0, import_plugins_backend_sdk3.Column)({ type: "datetime" })
292
619
  ], ReservationEntity.prototype, "startTime", 2);
293
620
  __decorateClass([
294
- (0, import_plugins_backend_sdk2.Column)({ type: "datetime" })
621
+ (0, import_plugins_backend_sdk3.Column)({ type: "datetime" })
295
622
  ], ReservationEntity.prototype, "endTime", 2);
296
623
  __decorateClass([
297
- (0, import_plugins_backend_sdk2.Column)({ type: "integer", default: 0 })
624
+ (0, import_plugins_backend_sdk3.Column)({ type: "integer", default: 0 })
298
625
  ], ReservationEntity.prototype, "bufferBeforeMinutes", 2);
299
626
  __decorateClass([
300
- (0, import_plugins_backend_sdk2.Column)({ type: "integer", default: 0 })
627
+ (0, import_plugins_backend_sdk3.Column)({ type: "integer", default: 0 })
301
628
  ], ReservationEntity.prototype, "bufferAfterMinutes", 2);
302
629
  __decorateClass([
303
- (0, import_plugins_backend_sdk2.Column)({ type: "varchar" })
630
+ (0, import_plugins_backend_sdk3.Column)({ type: "varchar" })
304
631
  ], ReservationEntity.prototype, "status", 2);
305
632
  __decorateClass([
306
- (0, import_plugins_backend_sdk2.Column)({ type: "varchar", nullable: true })
633
+ (0, import_plugins_backend_sdk3.Column)({ type: "varchar", nullable: true })
307
634
  ], ReservationEntity.prototype, "note", 2);
308
635
  __decorateClass([
309
- (0, import_plugins_backend_sdk2.Column)({ type: "datetime" })
636
+ (0, import_plugins_backend_sdk3.Column)({ type: "datetime" })
310
637
  ], ReservationEntity.prototype, "createdAt", 2);
311
638
  __decorateClass([
312
- (0, import_plugins_backend_sdk2.Column)({ type: "datetime", nullable: true })
639
+ (0, import_plugins_backend_sdk3.Column)({ type: "datetime", nullable: true })
313
640
  ], ReservationEntity.prototype, "endedEarlyAt", 2);
314
641
  __decorateClass([
315
- (0, import_plugins_backend_sdk2.Column)({ type: "integer", nullable: true })
642
+ (0, import_plugins_backend_sdk3.Column)({ type: "integer", nullable: true })
316
643
  ], ReservationEntity.prototype, "cancelledBy", 2);
317
644
  __decorateClass([
318
- (0, import_plugins_backend_sdk2.Column)({ type: "varchar", nullable: true })
645
+ (0, import_plugins_backend_sdk3.Column)({ type: "varchar", nullable: true })
319
646
  ], ReservationEntity.prototype, "cancelReason", 2);
320
647
  __decorateClass([
321
- (0, import_plugins_backend_sdk2.Column)({ type: "integer", nullable: true })
648
+ (0, import_plugins_backend_sdk3.Column)({ type: "integer", nullable: true })
322
649
  ], ReservationEntity.prototype, "decidedBy", 2);
323
650
  __decorateClass([
324
- (0, import_plugins_backend_sdk2.Column)({ type: "varchar", nullable: true })
651
+ (0, import_plugins_backend_sdk3.Column)({ type: "varchar", nullable: true })
325
652
  ], ReservationEntity.prototype, "decisionReason", 2);
326
653
  __decorateClass([
327
- (0, import_plugins_backend_sdk2.Column)({ type: "datetime", nullable: true })
654
+ (0, import_plugins_backend_sdk3.Column)({ type: "datetime", nullable: true })
328
655
  ], ReservationEntity.prototype, "decidedAt", 2);
329
656
  __decorateClass([
330
- (0, import_plugins_backend_sdk2.Column)({ type: "datetime", nullable: true })
657
+ (0, import_plugins_backend_sdk3.Column)({ type: "datetime", nullable: true })
331
658
  ], ReservationEntity.prototype, "checkedInAt", 2);
332
659
  __decorateClass([
333
- (0, import_plugins_backend_sdk2.Column)({ type: "integer", nullable: true })
660
+ (0, import_plugins_backend_sdk3.Column)({ type: "integer", nullable: true })
334
661
  ], ReservationEntity.prototype, "checkedInUsageId", 2);
335
662
  __decorateClass([
336
- (0, import_plugins_backend_sdk2.Column)({ type: "datetime", nullable: true })
663
+ (0, import_plugins_backend_sdk3.Column)({ type: "datetime", nullable: true })
337
664
  ], ReservationEntity.prototype, "keptAt", 2);
338
665
  __decorateClass([
339
- (0, import_plugins_backend_sdk2.Column)({ type: "datetime", nullable: true })
666
+ (0, import_plugins_backend_sdk3.Column)({ type: "datetime", nullable: true })
340
667
  ], ReservationEntity.prototype, "confirmationSentAt", 2);
341
668
  __decorateClass([
342
- (0, import_plugins_backend_sdk2.Column)({ type: "datetime", nullable: true })
669
+ (0, import_plugins_backend_sdk3.Column)({ type: "datetime", nullable: true })
343
670
  ], ReservationEntity.prototype, "stillNeededSentAt", 2);
344
671
  __decorateClass([
345
- (0, import_plugins_backend_sdk2.Column)({ type: "datetime", nullable: true })
672
+ (0, import_plugins_backend_sdk3.Column)({ type: "datetime", nullable: true })
346
673
  ], ReservationEntity.prototype, "reminder24hSentAt", 2);
347
674
  __decorateClass([
348
- (0, import_plugins_backend_sdk2.Column)({ type: "datetime", nullable: true })
675
+ (0, import_plugins_backend_sdk3.Column)({ type: "datetime", nullable: true })
349
676
  ], ReservationEntity.prototype, "handoverSentAt", 2);
350
677
  __decorateClass([
351
- (0, import_plugins_backend_sdk2.Column)({ type: "datetime", nullable: true })
678
+ (0, import_plugins_backend_sdk3.Column)({ type: "datetime", nullable: true })
352
679
  ], ReservationEntity.prototype, "overrunSentAt", 2);
353
680
  __decorateClass([
354
- (0, import_plugins_backend_sdk2.Column)({ type: "datetime", nullable: true })
681
+ (0, import_plugins_backend_sdk3.Column)({ type: "datetime", nullable: true })
355
682
  ], ReservationEntity.prototype, "noShowNotifiedAt", 2);
356
683
  __decorateClass([
357
- (0, import_plugins_backend_sdk2.Column)({ type: "datetime", nullable: true })
684
+ (0, import_plugins_backend_sdk3.Column)({ type: "datetime", nullable: true })
358
685
  ], ReservationEntity.prototype, "expiredNotifiedAt", 2);
359
686
  ReservationEntity = __decorateClass([
360
- (0, import_plugins_backend_sdk2.Entity)({ name: "reservations_reservation" }),
361
- (0, import_plugins_backend_sdk2.Index)("IDX_reservations_reservation_slot", ["resourceId", "status", "startTime", "endTime"]),
362
- (0, import_plugins_backend_sdk2.Index)("IDX_reservations_reservation_user", ["userId", "status"])
687
+ (0, import_plugins_backend_sdk3.Entity)({ name: "reservations_reservation" }),
688
+ (0, import_plugins_backend_sdk3.Index)("IDX_reservations_reservation_slot", ["resourceId", "status", "startTime", "endTime"]),
689
+ (0, import_plugins_backend_sdk3.Index)("IDX_reservations_reservation_user", ["userId", "status"])
363
690
  ], ReservationEntity);
364
691
 
365
692
  // backend/ical/visibility.service.ts
366
- var import_plugins_backend_sdk3 = require("@attraccess/plugins-backend-sdk");
693
+ var import_plugins_backend_sdk4 = require("@attraccess/plugins-backend-sdk");
367
694
  var import_common4 = require("@nestjs/common");
368
695
  var import_typeorm = require("typeorm");
369
696
  var ACTIVE_INTRODUCTION_EXISTS_SQL = `EXISTS (
@@ -389,9 +716,9 @@ var VisibilityService = class {
389
716
  const userId = subjectUserId(subject);
390
717
  const ids = [...new Set(resourceIds)];
391
718
  if (ids.length === 0) return [];
392
- const base = this.context.getRepository(import_plugins_backend_sdk3.Resource).createQueryBuilder("resource").select("resource.id", "id").where("resource.id IN (:...ids)", { ids });
719
+ const base = this.context.getRepository(import_plugins_backend_sdk4.Resource).createQueryBuilder("resource").select("resource.id", "id").where("resource.id IN (:...ids)", { ids });
393
720
  if (!await this.access.hasUpdatePermission(subject)) {
394
- const visibleGroups = this.context.getRepository(import_plugins_backend_sdk3.ResourceGroup).createQueryBuilder("vg").select("vg.id").where("vg.isHidden = :notHidden", { notHidden: false }).orWhere(
721
+ const visibleGroups = this.context.getRepository(import_plugins_backend_sdk4.ResourceGroup).createQueryBuilder("vg").select("vg.id").where("vg.isHidden = :notHidden", { notHidden: false }).orWhere(
395
722
  `EXISTS (SELECT 1 FROM "resource_introducer" "ri" WHERE "ri"."resourceGroupId" = vg.id AND "ri"."userId" = :userId)`
396
723
  ).orWhere(ACTIVE_INTRODUCTION_EXISTS_SQL);
397
724
  base.leftJoin("resource.groups", "rg").andWhere(new import_typeorm.Brackets((qb) => qb.where("rg.id IS NULL").orWhere(`rg.id IN (${visibleGroups.getQuery()})`))).setParameters({ ...visibleGroups.getParameters(), notHidden: false, userId });
@@ -404,20 +731,20 @@ var VisibilityService = class {
404
731
  * their role rows, so anything acting on their behalf without a session (iCal feeds) must check this.
405
732
  */
406
733
  async isActiveAccount(userId) {
407
- const user = await this.context.getRepository(import_plugins_backend_sdk3.User).findOne({ where: { id: userId }, select: { id: true, isDisabled: true } });
734
+ const user = await this.context.getRepository(import_plugins_backend_sdk4.User).findOne({ where: { id: userId }, select: { id: true, isDisabled: true } });
408
735
  return user !== null && !user.isDisabled;
409
736
  }
410
737
  /** The subset of `resourceIds` whose sessions always need a supervisor (`supervision_required`). */
411
738
  async resourceIdsRequiringSupervision(resourceIds) {
412
739
  const ids = [...new Set(resourceIds)];
413
740
  if (ids.length === 0) return [];
414
- const rows = await this.context.getRepository(import_plugins_backend_sdk3.Resource).createQueryBuilder("resource").select("resource.id", "id").where("resource.id IN (:...ids)", { ids }).andWhere("resource.supervisionMode = :mode", { mode: import_plugins_backend_sdk3.SupervisionMode.SUPERVISION_REQUIRED }).getRawMany();
741
+ const rows = await this.context.getRepository(import_plugins_backend_sdk4.Resource).createQueryBuilder("resource").select("resource.id", "id").where("resource.id IN (:...ids)", { ids }).andWhere("resource.supervisionMode = :mode", { mode: import_plugins_backend_sdk4.SupervisionMode.SUPERVISION_REQUIRED }).getRawMany();
415
742
  return rows.map((row) => Number(row.id));
416
743
  }
417
744
  /** Ids of all resources in the given groups. */
418
745
  async resourceIdsOfGroups(groupIds) {
419
746
  if (groupIds.length === 0) return [];
420
- const rows = await this.context.getRepository(import_plugins_backend_sdk3.Resource).createQueryBuilder("resource").select("resource.id", "id").innerJoin("resource.groups", "g").where("g.id IN (:...groupIds)", { groupIds }).distinct(true).getRawMany();
747
+ const rows = await this.context.getRepository(import_plugins_backend_sdk4.Resource).createQueryBuilder("resource").select("resource.id", "id").innerJoin("resource.groups", "g").where("g.id IN (:...groupIds)", { groupIds }).distinct(true).getRawMany();
421
748
  return rows.map((row) => Number(row.id));
422
749
  }
423
750
  };
@@ -431,7 +758,7 @@ VisibilityService = __decorateClass([
431
758
  var import_common5 = require("@nestjs/common");
432
759
 
433
760
  // backend/entities/resource-settings.entity.ts
434
- var import_plugins_backend_sdk4 = require("@attraccess/plugins-backend-sdk");
761
+ var import_plugins_backend_sdk5 = require("@attraccess/plugins-backend-sdk");
435
762
  var ResourceSettingsEntity = class {
436
763
  constructor() {
437
764
  __publicField(this, "resourceId");
@@ -447,264 +774,74 @@ var ResourceSettingsEntity = class {
447
774
  __publicField(this, "maxActiveBookingsPerUser");
448
775
  __publicField(this, "whoCanBook");
449
776
  __publicField(this, "confirmWindowMinutes");
450
- __publicField(this, "checkInEnabled");
451
- __publicField(this, "checkInGraceMinutes");
452
- __publicField(this, "earlyCheckInMinutes");
453
- __publicField(this, "handoverReminderMinutes");
454
- __publicField(this, "bookableHours");
455
- __publicField(this, "updatedAt");
456
- }
457
- };
458
- __decorateClass([
459
- (0, import_plugins_backend_sdk4.PrimaryColumn)({ type: "integer" })
460
- ], ResourceSettingsEntity.prototype, "resourceId", 2);
461
- __decorateClass([
462
- (0, import_plugins_backend_sdk4.Column)({ type: "boolean", default: false })
463
- ], ResourceSettingsEntity.prototype, "enabled", 2);
464
- __decorateClass([
465
- (0, import_plugins_backend_sdk4.Column)({ type: "boolean", default: false })
466
- ], ResourceSettingsEntity.prototype, "approvalRequired", 2);
467
- __decorateClass([
468
- (0, import_plugins_backend_sdk4.Column)({ type: "integer", default: 15 })
469
- ], ResourceSettingsEntity.prototype, "timeStepMinutes", 2);
470
- __decorateClass([
471
- (0, import_plugins_backend_sdk4.Column)({ type: "integer", default: 15 })
472
- ], ResourceSettingsEntity.prototype, "minDurationMinutes", 2);
473
- __decorateClass([
474
- (0, import_plugins_backend_sdk4.Column)({ type: "integer", default: 240 })
475
- ], ResourceSettingsEntity.prototype, "maxDurationMinutes", 2);
476
- __decorateClass([
477
- (0, import_plugins_backend_sdk4.Column)({ type: "integer", default: 30 })
478
- ], ResourceSettingsEntity.prototype, "maxAdvanceDays", 2);
479
- __decorateClass([
480
- (0, import_plugins_backend_sdk4.Column)({ type: "integer", default: 0 })
481
- ], ResourceSettingsEntity.prototype, "minLeadMinutes", 2);
482
- __decorateClass([
483
- (0, import_plugins_backend_sdk4.Column)({ type: "integer", default: 0 })
484
- ], ResourceSettingsEntity.prototype, "bufferBeforeMinutes", 2);
485
- __decorateClass([
486
- (0, import_plugins_backend_sdk4.Column)({ type: "integer", default: 0 })
487
- ], ResourceSettingsEntity.prototype, "bufferAfterMinutes", 2);
488
- __decorateClass([
489
- (0, import_plugins_backend_sdk4.Column)({ type: "integer", default: 3 })
490
- ], ResourceSettingsEntity.prototype, "maxActiveBookingsPerUser", 2);
491
- __decorateClass([
492
- (0, import_plugins_backend_sdk4.Column)({ type: "varchar", default: "can-start" })
493
- ], ResourceSettingsEntity.prototype, "whoCanBook", 2);
494
- __decorateClass([
495
- (0, import_plugins_backend_sdk4.Column)({ type: "integer", default: 60 })
496
- ], ResourceSettingsEntity.prototype, "confirmWindowMinutes", 2);
497
- __decorateClass([
498
- (0, import_plugins_backend_sdk4.Column)({ type: "boolean", default: true })
499
- ], ResourceSettingsEntity.prototype, "checkInEnabled", 2);
500
- __decorateClass([
501
- (0, import_plugins_backend_sdk4.Column)({ type: "integer", default: 15 })
502
- ], ResourceSettingsEntity.prototype, "checkInGraceMinutes", 2);
503
- __decorateClass([
504
- (0, import_plugins_backend_sdk4.Column)({ type: "integer", default: 15 })
505
- ], ResourceSettingsEntity.prototype, "earlyCheckInMinutes", 2);
506
- __decorateClass([
507
- (0, import_plugins_backend_sdk4.Column)({ type: "integer", default: 15 })
508
- ], ResourceSettingsEntity.prototype, "handoverReminderMinutes", 2);
509
- __decorateClass([
510
- (0, import_plugins_backend_sdk4.Column)({ type: "text", default: "{}" })
511
- ], ResourceSettingsEntity.prototype, "bookableHours", 2);
512
- __decorateClass([
513
- (0, import_plugins_backend_sdk4.Column)({ type: "datetime" })
514
- ], ResourceSettingsEntity.prototype, "updatedAt", 2);
515
- ResourceSettingsEntity = __decorateClass([
516
- (0, import_plugins_backend_sdk4.Entity)({ name: "reservations_resource_settings" })
517
- ], ResourceSettingsEntity);
518
-
519
- // backend/time/zone.ts
520
- var formatters = /* @__PURE__ */ new Map();
521
- function formatterFor(timeZone) {
522
- let formatter = formatters.get(timeZone);
523
- if (!formatter) {
524
- formatter = new Intl.DateTimeFormat("en-US", {
525
- timeZone,
526
- hourCycle: "h23",
527
- year: "numeric",
528
- month: "numeric",
529
- day: "numeric",
530
- hour: "numeric",
531
- minute: "numeric",
532
- second: "numeric"
533
- });
534
- formatters.set(timeZone, formatter);
535
- }
536
- return formatter;
537
- }
538
- function isValidTimeZone(timeZone) {
539
- if (typeof timeZone !== "string" || timeZone.length === 0 || timeZone.length > 100) return false;
540
- try {
541
- new Intl.DateTimeFormat("en-US", { timeZone });
542
- return true;
543
- } catch {
544
- return false;
545
- }
546
- }
547
- function serverTimeZone() {
548
- const resolved = Intl.DateTimeFormat().resolvedOptions().timeZone;
549
- return isValidTimeZone(resolved) ? resolved : "UTC";
550
- }
551
- function getWallClock(date, timeZone) {
552
- const parts = formatterFor(timeZone).formatToParts(date);
553
- const read = (type) => Number(parts.find((part) => part.type === type)?.value ?? 0);
554
- return {
555
- year: read("year"),
556
- month: read("month"),
557
- day: read("day"),
558
- hour: read("hour") % 24,
559
- minute: read("minute"),
560
- second: read("second")
561
- };
562
- }
563
- function offsetMs(date, timeZone) {
564
- const wall = getWallClock(date, timeZone);
565
- const asUtc = Date.UTC(wall.year, wall.month - 1, wall.day, wall.hour, wall.minute, wall.second);
566
- return asUtc - Math.floor(date.getTime() / 1e3) * 1e3;
567
- }
568
- var DAY_MS = 864e5;
569
- function wallOf(date, timeZone) {
570
- const wall = getWallClock(date, timeZone);
571
- return Date.UTC(wall.year, wall.month - 1, wall.day, wall.hour, wall.minute, wall.second);
572
- }
573
- function wallClockToDate(local, timeZone) {
574
- const target = Date.UTC(
575
- local.year,
576
- local.month - 1,
577
- local.day,
578
- local.hour ?? 0,
579
- local.minute ?? 0,
580
- local.second ?? 0
581
- );
582
- const before = offsetMs(new Date(target - DAY_MS), timeZone);
583
- const after = offsetMs(new Date(target + DAY_MS), timeZone);
584
- const first = target - before;
585
- if (before === after || wallOf(new Date(first), timeZone) === target) return new Date(first);
586
- const second = target - after;
587
- if (wallOf(new Date(second), timeZone) === target) return new Date(second);
588
- return new Date(first);
589
- }
590
- function localDateOf(date, timeZone) {
591
- const { year, month, day } = getWallClock(date, timeZone);
592
- return { year, month, day };
593
- }
594
- function addLocalDays(date, days) {
595
- const moved = new Date(Date.UTC(date.year, date.month - 1, date.day + days));
596
- return { year: moved.getUTCFullYear(), month: moved.getUTCMonth() + 1, day: moved.getUTCDate() };
597
- }
598
- function weekdayOf(date) {
599
- return new Date(Date.UTC(date.year, date.month - 1, date.day)).getUTCDay();
600
- }
601
- function localMinutesOfDay(date, timeZone) {
602
- const wall = getWallClock(date, timeZone);
603
- return wall.hour * 60 + wall.minute;
604
- }
605
- function isWholeMinute(date) {
606
- return date.getTime() % 6e4 === 0;
607
- }
608
-
609
- // backend/time/bookable-hours.ts
610
- var WEEKDAYS = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
611
- var MAX_RANGES_PER_DAY = 8;
612
- var HM = /^([01]\d|2[0-3]):([0-5]\d)$|^24:00$/;
613
- function parseHm(value) {
614
- const [hours, minutes] = value.split(":").map(Number);
615
- return hours * 60 + minutes;
616
- }
617
- function hasRestrictions(hours) {
618
- return WEEKDAYS.some((day) => (hours[day]?.length ?? 0) > 0);
619
- }
620
- function validateBookableHours(input) {
621
- const errors = [];
622
- if (input === null || typeof input !== "object" || Array.isArray(input)) {
623
- return [{ field: "bookableHours", message: "must be an object keyed by weekday" }];
624
- }
625
- for (const [day, ranges] of Object.entries(input)) {
626
- const field = `bookableHours.${day}`;
627
- if (!WEEKDAYS.includes(day)) {
628
- errors.push({ field, message: `unknown weekday, expected one of ${WEEKDAYS.join(", ")}` });
629
- continue;
630
- }
631
- if (!Array.isArray(ranges) || ranges.length > MAX_RANGES_PER_DAY) {
632
- errors.push({ field, message: `must be a list of at most ${MAX_RANGES_PER_DAY} ranges` });
633
- continue;
634
- }
635
- const parsed = [];
636
- for (const range2 of ranges) {
637
- const start = range2?.start;
638
- const end = range2?.end;
639
- if (typeof start !== "string" || typeof end !== "string" || !HM.test(start) || !HM.test(end) || start === "24:00") {
640
- errors.push({ field, message: "ranges need start and end as HH:mm (end may be 24:00)" });
641
- continue;
642
- }
643
- if (parseHm(start) >= parseHm(end)) {
644
- errors.push({ field, message: `range ${start}-${end} must end after it starts` });
645
- continue;
646
- }
647
- parsed.push([parseHm(start), parseHm(end)]);
648
- }
649
- parsed.sort((a, b) => a[0] - b[0]);
650
- for (let i = 1; i < parsed.length; i += 1) {
651
- if (parsed[i][0] < parsed[i - 1][1]) errors.push({ field, message: "ranges must not overlap" });
652
- }
653
- }
654
- return errors;
655
- }
656
- function normalizeBookableHours(hours) {
657
- const result = {};
658
- for (const day of WEEKDAYS) {
659
- const ranges = hours[day];
660
- if (ranges && ranges.length > 0) {
661
- result[day] = ranges.map(({ start, end }) => ({ start, end })).sort((a, b) => parseHm(a.start) - parseHm(b.start));
662
- }
663
- }
664
- return result;
665
- }
666
- function bookableIntervals(hours, timeZone, from, to) {
667
- const first = addLocalDays(localDateOf(from, timeZone), -1);
668
- const last = addLocalDays(localDateOf(to, timeZone), 1);
669
- const raw = [];
670
- const key = (d) => d.year * 1e4 + d.month * 100 + d.day;
671
- for (let day = first; key(day) <= key(last); day = addLocalDays(day, 1)) {
672
- for (const range2 of hours[WEEKDAYS[weekdayOf(day)]] ?? []) {
673
- const toMidnight = range2.end === "24:00";
674
- raw.push({
675
- start: wallClockToDate(
676
- { ...day, hour: Math.floor(parseHm(range2.start) / 60), minute: parseHm(range2.start) % 60 },
677
- timeZone
678
- ),
679
- end: toMidnight ? wallClockToDate(addLocalDays(day, 1), timeZone) : wallClockToDate(
680
- { ...day, hour: Math.floor(parseHm(range2.end) / 60), minute: parseHm(range2.end) % 60 },
681
- timeZone
682
- ),
683
- fromMidnight: parseHm(range2.start) === 0,
684
- toMidnight
685
- });
686
- }
687
- }
688
- raw.sort((a, b) => a.start.getTime() - b.start.getTime());
689
- const joined = [];
690
- for (const interval of raw) {
691
- const previous = joined[joined.length - 1];
692
- const crossesMidnight = previous?.toMidnight && interval.fromMidnight && interval.start.getTime() === previous.end.getTime();
693
- if (previous && crossesMidnight) {
694
- previous.end = interval.end;
695
- previous.toMidnight = interval.toMidnight;
696
- } else {
697
- joined.push({ ...interval });
698
- }
699
- }
700
- return joined.map(({ start, end }) => ({ start, end }));
701
- }
702
- function isWithinBookableHours(hours, timeZone, start, end) {
703
- if (!hasRestrictions(hours)) return true;
704
- return bookableIntervals(hours, timeZone, start, end).some(
705
- (interval) => interval.start.getTime() <= start.getTime() && end.getTime() <= interval.end.getTime()
706
- );
707
- }
777
+ __publicField(this, "checkInEnabled");
778
+ __publicField(this, "checkInGraceMinutes");
779
+ __publicField(this, "earlyCheckInMinutes");
780
+ __publicField(this, "handoverReminderMinutes");
781
+ __publicField(this, "bookableHours");
782
+ __publicField(this, "updatedAt");
783
+ }
784
+ };
785
+ __decorateClass([
786
+ (0, import_plugins_backend_sdk5.PrimaryColumn)({ type: "integer" })
787
+ ], ResourceSettingsEntity.prototype, "resourceId", 2);
788
+ __decorateClass([
789
+ (0, import_plugins_backend_sdk5.Column)({ type: "boolean", default: false })
790
+ ], ResourceSettingsEntity.prototype, "enabled", 2);
791
+ __decorateClass([
792
+ (0, import_plugins_backend_sdk5.Column)({ type: "boolean", default: false })
793
+ ], ResourceSettingsEntity.prototype, "approvalRequired", 2);
794
+ __decorateClass([
795
+ (0, import_plugins_backend_sdk5.Column)({ type: "integer", default: 15 })
796
+ ], ResourceSettingsEntity.prototype, "timeStepMinutes", 2);
797
+ __decorateClass([
798
+ (0, import_plugins_backend_sdk5.Column)({ type: "integer", default: 15 })
799
+ ], ResourceSettingsEntity.prototype, "minDurationMinutes", 2);
800
+ __decorateClass([
801
+ (0, import_plugins_backend_sdk5.Column)({ type: "integer", default: 240 })
802
+ ], ResourceSettingsEntity.prototype, "maxDurationMinutes", 2);
803
+ __decorateClass([
804
+ (0, import_plugins_backend_sdk5.Column)({ type: "integer", default: 30 })
805
+ ], ResourceSettingsEntity.prototype, "maxAdvanceDays", 2);
806
+ __decorateClass([
807
+ (0, import_plugins_backend_sdk5.Column)({ type: "integer", default: 0 })
808
+ ], ResourceSettingsEntity.prototype, "minLeadMinutes", 2);
809
+ __decorateClass([
810
+ (0, import_plugins_backend_sdk5.Column)({ type: "integer", default: 0 })
811
+ ], ResourceSettingsEntity.prototype, "bufferBeforeMinutes", 2);
812
+ __decorateClass([
813
+ (0, import_plugins_backend_sdk5.Column)({ type: "integer", default: 0 })
814
+ ], ResourceSettingsEntity.prototype, "bufferAfterMinutes", 2);
815
+ __decorateClass([
816
+ (0, import_plugins_backend_sdk5.Column)({ type: "integer", default: 3 })
817
+ ], ResourceSettingsEntity.prototype, "maxActiveBookingsPerUser", 2);
818
+ __decorateClass([
819
+ (0, import_plugins_backend_sdk5.Column)({ type: "varchar", default: "can-start" })
820
+ ], ResourceSettingsEntity.prototype, "whoCanBook", 2);
821
+ __decorateClass([
822
+ (0, import_plugins_backend_sdk5.Column)({ type: "integer", default: 60 })
823
+ ], ResourceSettingsEntity.prototype, "confirmWindowMinutes", 2);
824
+ __decorateClass([
825
+ (0, import_plugins_backend_sdk5.Column)({ type: "boolean", default: true })
826
+ ], ResourceSettingsEntity.prototype, "checkInEnabled", 2);
827
+ __decorateClass([
828
+ (0, import_plugins_backend_sdk5.Column)({ type: "integer", default: 15 })
829
+ ], ResourceSettingsEntity.prototype, "checkInGraceMinutes", 2);
830
+ __decorateClass([
831
+ (0, import_plugins_backend_sdk5.Column)({ type: "integer", default: 15 })
832
+ ], ResourceSettingsEntity.prototype, "earlyCheckInMinutes", 2);
833
+ __decorateClass([
834
+ (0, import_plugins_backend_sdk5.Column)({ type: "integer", default: 15 })
835
+ ], ResourceSettingsEntity.prototype, "handoverReminderMinutes", 2);
836
+ __decorateClass([
837
+ (0, import_plugins_backend_sdk5.Column)({ type: "text", default: "{}" })
838
+ ], ResourceSettingsEntity.prototype, "bookableHours", 2);
839
+ __decorateClass([
840
+ (0, import_plugins_backend_sdk5.Column)({ type: "datetime" })
841
+ ], ResourceSettingsEntity.prototype, "updatedAt", 2);
842
+ ResourceSettingsEntity = __decorateClass([
843
+ (0, import_plugins_backend_sdk5.Entity)({ name: "reservations_resource_settings" })
844
+ ], ResourceSettingsEntity);
708
845
 
709
846
  // backend/settings/settings.model.ts
710
847
  var WHO_CAN_BOOK = ["can-start", "managers-only", "any-user"];
@@ -912,7 +1049,7 @@ ResourceSettingsService = __decorateClass([
912
1049
  var import_common6 = require("@nestjs/common");
913
1050
 
914
1051
  // backend/entities/global-settings.entity.ts
915
- var import_plugins_backend_sdk5 = require("@attraccess/plugins-backend-sdk");
1052
+ var import_plugins_backend_sdk6 = require("@attraccess/plugins-backend-sdk");
916
1053
  var GlobalSettingsEntity = class {
917
1054
  constructor() {
918
1055
  __publicField(this, "key");
@@ -920,13 +1057,13 @@ var GlobalSettingsEntity = class {
920
1057
  }
921
1058
  };
922
1059
  __decorateClass([
923
- (0, import_plugins_backend_sdk5.PrimaryColumn)({ type: "varchar" })
1060
+ (0, import_plugins_backend_sdk6.PrimaryColumn)({ type: "varchar" })
924
1061
  ], GlobalSettingsEntity.prototype, "key", 2);
925
1062
  __decorateClass([
926
- (0, import_plugins_backend_sdk5.Column)({ type: "text" })
1063
+ (0, import_plugins_backend_sdk6.Column)({ type: "text" })
927
1064
  ], GlobalSettingsEntity.prototype, "value", 2);
928
1065
  GlobalSettingsEntity = __decorateClass([
929
- (0, import_plugins_backend_sdk5.Entity)({ name: "reservations_global_settings" })
1066
+ (0, import_plugins_backend_sdk6.Entity)({ name: "reservations_global_settings" })
930
1067
  ], GlobalSettingsEntity);
931
1068
 
932
1069
  // backend/settings/global-settings.service.ts
@@ -1070,7 +1207,7 @@ var KeyedMutex = class {
1070
1207
  var import_common7 = require("@nestjs/common");
1071
1208
 
1072
1209
  // backend/entities/notice.entity.ts
1073
- var import_plugins_backend_sdk6 = require("@attraccess/plugins-backend-sdk");
1210
+ var import_plugins_backend_sdk7 = require("@attraccess/plugins-backend-sdk");
1074
1211
  var NoticeEntity = class {
1075
1212
  constructor() {
1076
1213
  __publicField(this, "id");
@@ -1081,23 +1218,23 @@ var NoticeEntity = class {
1081
1218
  }
1082
1219
  };
1083
1220
  __decorateClass([
1084
- (0, import_plugins_backend_sdk6.PrimaryGeneratedColumn)({ type: "integer" })
1221
+ (0, import_plugins_backend_sdk7.PrimaryGeneratedColumn)({ type: "integer" })
1085
1222
  ], NoticeEntity.prototype, "id", 2);
1086
1223
  __decorateClass([
1087
- (0, import_plugins_backend_sdk6.Column)({ type: "integer" })
1224
+ (0, import_plugins_backend_sdk7.Column)({ type: "integer" })
1088
1225
  ], NoticeEntity.prototype, "reservationId", 2);
1089
1226
  __decorateClass([
1090
- (0, import_plugins_backend_sdk6.Column)({ type: "varchar" })
1227
+ (0, import_plugins_backend_sdk7.Column)({ type: "varchar" })
1091
1228
  ], NoticeEntity.prototype, "kind", 2);
1092
1229
  __decorateClass([
1093
- (0, import_plugins_backend_sdk6.Column)({ type: "varchar", default: "" })
1230
+ (0, import_plugins_backend_sdk7.Column)({ type: "varchar", default: "" })
1094
1231
  ], NoticeEntity.prototype, "refKey", 2);
1095
1232
  __decorateClass([
1096
- (0, import_plugins_backend_sdk6.Column)({ type: "datetime" })
1233
+ (0, import_plugins_backend_sdk7.Column)({ type: "datetime" })
1097
1234
  ], NoticeEntity.prototype, "sentAt", 2);
1098
1235
  NoticeEntity = __decorateClass([
1099
- (0, import_plugins_backend_sdk6.Entity)({ name: "reservations_notice" }),
1100
- (0, import_plugins_backend_sdk6.Index)("UQ_reservations_notice", ["reservationId", "kind", "refKey"], { unique: true })
1236
+ (0, import_plugins_backend_sdk7.Entity)({ name: "reservations_notice" }),
1237
+ (0, import_plugins_backend_sdk7.Index)("UQ_reservations_notice", ["reservationId", "kind", "refKey"], { unique: true })
1101
1238
  ], NoticeEntity);
1102
1239
 
1103
1240
  // backend/reservations/reservation.store.ts
@@ -1175,6 +1312,17 @@ var ReservationStore = class {
1175
1312
  to: new Date(to.getTime() + MAX_BUFFER_MINUTES * 6e4)
1176
1313
  }).getMany();
1177
1314
  }
1315
+ /** Confirmed bookings running at `now` ([start, end)), read through the host's transaction (start capacity hook). */
1316
+ findRunningConfirmed(manager, resourceId, now) {
1317
+ return manager.getRepository(ReservationEntity).createQueryBuilder("r").where("r.resourceId = :resourceId AND r.status = :status", { resourceId, status: "confirmed" }).andWhere("r.startTime <= :now AND r.endTime > :now", { now }).orderBy("r.startTime", "ASC").getMany();
1318
+ }
1319
+ /**
1320
+ * Pending + confirmed bookings of the resource whose buffer-aware span can still matter at or after `now`
1321
+ * (the capacity reconciliation after a lowered limit).
1322
+ */
1323
+ findOccupyingFrom(resourceId, now) {
1324
+ return this.findLiveOverlapping(resourceId, new Date(now.getTime() - MAX_BUFFER_MINUTES * 6e4), null);
1325
+ }
1178
1326
  countLiveForUser(manager, userId, resourceId, now) {
1179
1327
  return manager.getRepository(ReservationEntity).createQueryBuilder("r").where("r.userId = :userId AND r.resourceId = :resourceId AND r.status IN (:...statuses)", {
1180
1328
  userId,
@@ -1299,62 +1447,6 @@ ReservationStore = __decorateClass([
1299
1447
  __decorateParam(0, (0, import_common7.Inject)(PLUGIN_CONTEXT))
1300
1448
  ], ReservationStore);
1301
1449
 
1302
- // backend/reservations/rules.ts
1303
- var MINUTE_MS = 6e4;
1304
- var PAST_TOLERANCE_MS = MINUTE_MS;
1305
- function blockedSpan(booking) {
1306
- return {
1307
- start: new Date(booking.startTime.getTime() - booking.bufferBeforeMinutes * MINUTE_MS),
1308
- end: new Date(booking.endTime.getTime() + booking.bufferAfterMinutes * MINUTE_MS)
1309
- };
1310
- }
1311
- function spansOverlap(a, b) {
1312
- return a.start.getTime() < b.end.getTime() && b.start.getTime() < a.end.getTime();
1313
- }
1314
- function checkBookingRules(args) {
1315
- const { settings, timeZone, start, end, now } = args;
1316
- if (Number.isNaN(start.getTime()) || Number.isNaN(end.getTime()) || end.getTime() <= start.getTime()) {
1317
- return new ReservationError("INVALID_RANGE", "The end must be after the start");
1318
- }
1319
- if (start.getTime() < now.getTime() - PAST_TOLERANCE_MS) {
1320
- return new ReservationError("IN_THE_PAST", "The booking starts in the past");
1321
- }
1322
- const step = settings.timeStepMinutes;
1323
- const durationMinutes = (end.getTime() - start.getTime()) / MINUTE_MS;
1324
- const onGrid = isWholeMinute(start) && isWholeMinute(end) && localMinutesOfDay(start, timeZone) % step === 0 && durationMinutes % step === 0;
1325
- if (!onGrid) {
1326
- return new ReservationError("OFF_TIME_STEP", `Start and duration must be a multiple of ${step} minutes`);
1327
- }
1328
- if (durationMinutes < settings.minDurationMinutes) {
1329
- return new ReservationError("DURATION_TOO_SHORT", `The minimum duration is ${settings.minDurationMinutes} minutes`);
1330
- }
1331
- if (durationMinutes > settings.maxDurationMinutes) {
1332
- return new ReservationError("DURATION_TOO_LONG", `The maximum duration is ${settings.maxDurationMinutes} minutes`);
1333
- }
1334
- if (start.getTime() > now.getTime() + settings.maxAdvanceDays * 864e5) {
1335
- return new ReservationError(
1336
- "BEYOND_MAX_ADVANCE",
1337
- `Bookings can be made at most ${settings.maxAdvanceDays} days ahead`
1338
- );
1339
- }
1340
- if (settings.minLeadMinutes > 0 && start.getTime() < now.getTime() + settings.minLeadMinutes * MINUTE_MS) {
1341
- return new ReservationError(
1342
- "LEAD_TIME_TOO_SHORT",
1343
- `Bookings must be made at least ${settings.minLeadMinutes} minutes before they start`
1344
- );
1345
- }
1346
- const span = blockedSpan({
1347
- startTime: start,
1348
- endTime: end,
1349
- bufferBeforeMinutes: settings.bufferBeforeMinutes,
1350
- bufferAfterMinutes: settings.bufferAfterMinutes
1351
- });
1352
- if (!isWithinBookableHours(settings.bookableHours, timeZone, span.start, span.end)) {
1353
- return new ReservationError("OUTSIDE_BOOKABLE_HOURS", "The booking is outside the bookable hours");
1354
- }
1355
- return null;
1356
- }
1357
-
1358
1450
  // backend/reservations/reservation.service.ts
1359
1451
  var MAX_TEXT_LENGTH = 500;
1360
1452
  var DISABLED_REASON = "reservations disabled";
@@ -1501,8 +1593,17 @@ var ReservationService = class {
1501
1593
  }
1502
1594
  }
1503
1595
  const candidates = await this.store.findOverlapCandidates(manager, input.resourceId, span.start, span.end);
1504
- if (candidates.some((other) => spansOverlap(span, blockedSpan(other)))) {
1505
- throw new ReservationError("OVERLAP", "The time is already reserved");
1596
+ const overlapping = candidates.filter((other) => spansOverlap(span, blockedSpan(other)));
1597
+ const limit = await this.directory.getSessionLimit(input.resourceId, manager);
1598
+ if (limit <= 1) {
1599
+ if (overlapping.length > 0) throw new ReservationError("OVERLAP", "The time is already reserved");
1600
+ } else {
1601
+ if (overlapping.some((other) => other.userId === actor.userId)) {
1602
+ throw new ReservationError("OWN_OVERLAP", "You already have a booking for this resource at that time");
1603
+ }
1604
+ if (exceedsCapacity(overlapping.map(blockedSpan), span, limit)) {
1605
+ throw new ReservationError("OVERLAP", "All slots are booked at that time");
1606
+ }
1506
1607
  }
1507
1608
  const entity = new ReservationEntity();
1508
1609
  Object.assign(entity, {
@@ -1705,6 +1806,54 @@ var ReservationService = class {
1705
1806
  if (cancelled.length > 0) this.invalidateViews(resourceId);
1706
1807
  return cancelled.length;
1707
1808
  }
1809
+ // ------------------------------------------------ lowered session limit
1810
+ /**
1811
+ * Cancels the bookings a lowered session limit left without a slot: the newest-created not-yet-started ones first,
1812
+ * until every instant fits (see `selectExcessBookings`). Running bookings are never touched. Takes the resource lock;
1813
+ * idempotent, so it also serves the start-up and scheduler reconciliation. A higher limit cancels nothing, and so
1814
+ * does a resource that no longer exists (deleted: its bookings are not over capacity).
1815
+ * `actorUserId` null = no user (system): the audit then attributes each cancellation to its holder.
1816
+ */
1817
+ async cancelExcessBookings(resourceId, actorUserId) {
1818
+ return this.mutex.run(resourceId, async () => {
1819
+ const now = this.clock();
1820
+ const limit = await this.directory.findSessionLimit(resourceId);
1821
+ if (limit === null) return 0;
1822
+ const occupying = await this.store.findOccupyingFrom(resourceId, now);
1823
+ if (occupying.length <= limit) return 0;
1824
+ const cancelled = [];
1825
+ for (const booking of selectExcessBookings(occupying, limit, now)) {
1826
+ if (await this.cancelForCapacity(booking, actorUserId)) cancelled.push(booking);
1827
+ }
1828
+ this.notifyEach(
1829
+ "onRemoved",
1830
+ cancelled,
1831
+ (booking) => this.notifier.onRemoved(booking, { byUserId: null, reason: CAPACITY_REDUCED_REASON })
1832
+ );
1833
+ if (cancelled.length > 0) this.invalidateViews(resourceId);
1834
+ return cancelled.length;
1835
+ });
1836
+ }
1837
+ /** Cancels one booking that lost its slot and audits it; false when it changed meanwhile. */
1838
+ async cancelForCapacity(booking, actorUserId) {
1839
+ const patch = { status: "cancelled", cancelledBy: actorUserId, cancelReason: CAPACITY_REDUCED_REASON };
1840
+ if (!await this.store.transition(booking.id, [booking.status], patch, { notCheckedIn: true })) return false;
1841
+ Object.assign(booking, patch);
1842
+ await this.audit.record(
1843
+ "cancelled",
1844
+ // The user who lowered the limit; without one, the holder (system principal).
1845
+ ReservationAudit.systemPrincipal(actorUserId ?? booking.userId),
1846
+ { type: "reservation", id: booking.id },
1847
+ {
1848
+ resourceId: booking.resourceId,
1849
+ holderUserId: booking.userId,
1850
+ byManager: actorUserId !== null && actorUserId !== booking.userId,
1851
+ reason: CAPACITY_REDUCED_REASON,
1852
+ bulk: true
1853
+ }
1854
+ );
1855
+ return true;
1856
+ }
1708
1857
  // ------------------------------------------- scheduler / hook transitions
1709
1858
  async system(id, from, changes, action, options = {}) {
1710
1859
  const changed = await this.store.transition(id, from, changes, options);
@@ -2242,6 +2391,7 @@ var AvailabilityDto = class {
2242
2391
  __publicField(this, "isManager");
2243
2392
  __publicField(this, "canBook");
2244
2393
  __publicField(this, "rules");
2394
+ __publicField(this, "slots");
2245
2395
  __publicField(this, "reservations");
2246
2396
  __publicField(this, "maintenance");
2247
2397
  }
@@ -2270,6 +2420,12 @@ __decorateClass([
2270
2420
  __decorateClass([
2271
2421
  (0, import_swagger.ApiProperty)({ type: () => PublicBookingRulesDto })
2272
2422
  ], AvailabilityDto.prototype, "rules", 2);
2423
+ __decorateClass([
2424
+ (0, import_swagger.ApiProperty)({
2425
+ type: Number,
2426
+ description: "Effective session limit N of the resource: how many bookings may overlap (each takes one slot). 1 for doors, machines without parallel sessions and while reservations are disabled"
2427
+ })
2428
+ ], AvailabilityDto.prototype, "slots", 2);
2273
2429
  __decorateClass([
2274
2430
  (0, import_swagger.ApiProperty)({
2275
2431
  type: () => [ReservationDto],
@@ -2618,7 +2774,7 @@ __decorateClass([
2618
2774
  ], ReservationSettingsController.prototype, "getGlobal", 1);
2619
2775
  __decorateClass([
2620
2776
  (0, import_common12.Put)("settings/global"),
2621
- (0, import_plugins_backend_sdk7.Auth)("system.settings.manage"),
2777
+ (0, import_plugins_backend_sdk8.Auth)("system.settings.manage"),
2622
2778
  (0, import_swagger4.ApiOperation)({ summary: "Update plugin-wide settings (requires system.settings.manage)" }),
2623
2779
  (0, import_swagger4.ApiBody)({ type: UpdateGlobalSettingsBody }),
2624
2780
  (0, import_swagger4.ApiOkResponse)({ type: GlobalSettingsDto }),
@@ -2628,7 +2784,7 @@ __decorateClass([
2628
2784
  ], ReservationSettingsController.prototype, "updateGlobal", 1);
2629
2785
  ReservationSettingsController = __decorateClass([
2630
2786
  (0, import_swagger4.ApiTags)("Reservations"),
2631
- (0, import_plugins_backend_sdk7.Auth)(),
2787
+ (0, import_plugins_backend_sdk8.Auth)(),
2632
2788
  (0, import_common12.Controller)("reservations"),
2633
2789
  __decorateParam(0, (0, import_common12.Inject)(SettingsAdminService)),
2634
2790
  __decorateParam(1, (0, import_common12.Inject)(AccessService)),
@@ -2636,7 +2792,7 @@ ReservationSettingsController = __decorateClass([
2636
2792
  ], ReservationSettingsController);
2637
2793
 
2638
2794
  // backend/events/event-handlers.service.ts
2639
- var import_plugins_backend_sdk9 = require("@attraccess/plugins-backend-sdk");
2795
+ var import_plugins_backend_sdk10 = require("@attraccess/plugins-backend-sdk");
2640
2796
  var import_common16 = require("@nestjs/common");
2641
2797
 
2642
2798
  // backend/hooks/pending-decisions.ts
@@ -2688,7 +2844,7 @@ PendingDecisionStore = __decorateClass([
2688
2844
  ], PendingDecisionStore);
2689
2845
 
2690
2846
  // backend/notifications/host-info.service.ts
2691
- var import_plugins_backend_sdk8 = require("@attraccess/plugins-backend-sdk");
2847
+ var import_plugins_backend_sdk9 = require("@attraccess/plugins-backend-sdk");
2692
2848
  var import_common14 = require("@nestjs/common");
2693
2849
  var MANAGER_PERMISSIONS = ["resources.update"];
2694
2850
  function normalizeLanguage(locale, fallback) {
@@ -2702,7 +2858,7 @@ var HostInfoService = class {
2702
2858
  __publicField(this, "context", context);
2703
2859
  }
2704
2860
  async setting(key) {
2705
- const row = await this.context.getRepository(import_plugins_backend_sdk8.Setting).findOneBy({ parent: "app", key });
2861
+ const row = await this.context.getRepository(import_plugins_backend_sdk9.Setting).findOneBy({ parent: "app", key });
2706
2862
  const value = row?.value?.trim();
2707
2863
  return value ? value : null;
2708
2864
  }
@@ -2726,7 +2882,7 @@ var HostInfoService = class {
2726
2882
  if (ids.length === 0) return result;
2727
2883
  const [fallback, rows] = await Promise.all([
2728
2884
  this.getDefaultLanguage(),
2729
- this.context.getRepository(import_plugins_backend_sdk8.User).createQueryBuilder("user").select(["user.id", "user.locale"]).where("user.id IN (:...ids)", { ids }).getMany()
2885
+ this.context.getRepository(import_plugins_backend_sdk9.User).createQueryBuilder("user").select(["user.id", "user.locale"]).where("user.id IN (:...ids)", { ids }).getMany()
2730
2886
  ]);
2731
2887
  for (const row of rows) result.set(row.id, normalizeLanguage(row.locale, fallback));
2732
2888
  for (const id of ids) if (!result.has(id)) result.set(id, fallback);
@@ -2734,7 +2890,7 @@ var HostInfoService = class {
2734
2890
  }
2735
2891
  /** Health entries of the resource that are currently unhealthy (a resource may carry several). */
2736
2892
  countUnhealthyEntries(resourceId) {
2737
- return this.context.getRepository(import_plugins_backend_sdk8.ResourceHealthState).countBy({ resourceId, status: "unhealthy" });
2893
+ return this.context.getRepository(import_plugins_backend_sdk9.ResourceHealthState).countBy({ resourceId, status: "unhealthy" });
2738
2894
  }
2739
2895
  /**
2740
2896
  * Users managing the resource: everyone holding `resources.update` (role join, one query; the global
@@ -2745,8 +2901,8 @@ var HostInfoService = class {
2745
2901
  */
2746
2902
  async managerIdsOf(resourceId) {
2747
2903
  const [introducers, permitted] = await Promise.all([
2748
- this.context.getRepository(import_plugins_backend_sdk8.ResourceIntroducer).createQueryBuilder("introducer").select("introducer.userId", "userId").innerJoin("introducer.user", "user", "user.deletedAt IS NULL").leftJoin("introducer.resourceGroup", "group").leftJoin("group.resources", "resource").where("(introducer.resourceId = :resourceId OR resource.id = :resourceId)", { resourceId }).getRawMany(),
2749
- this.context.getRepository(import_plugins_backend_sdk8.UserRole).createQueryBuilder("ur").select("ur.userId", "userId").distinct(true).innerJoin("ur.user", "user", "user.deletedAt IS NULL").innerJoin("ur.role", "role").innerJoin("role.rolePermissions", "rp").where("rp.permissionKey IN (:...keys)", { keys: MANAGER_PERMISSIONS }).getRawMany()
2904
+ this.context.getRepository(import_plugins_backend_sdk9.ResourceIntroducer).createQueryBuilder("introducer").select("introducer.userId", "userId").innerJoin("introducer.user", "user", "user.deletedAt IS NULL").leftJoin("introducer.resourceGroup", "group").leftJoin("group.resources", "resource").where("(introducer.resourceId = :resourceId OR resource.id = :resourceId)", { resourceId }).getRawMany(),
2905
+ this.context.getRepository(import_plugins_backend_sdk9.UserRole).createQueryBuilder("ur").select("ur.userId", "userId").distinct(true).innerJoin("ur.user", "user", "user.deletedAt IS NULL").innerJoin("ur.role", "role").innerJoin("role.rolePermissions", "rp").where("rp.permissionKey IN (:...keys)", { keys: MANAGER_PERMISSIONS }).getRawMany()
2750
2906
  ]);
2751
2907
  return [...new Set([...introducers, ...permitted].map((row) => Number(row.userId)))];
2752
2908
  }
@@ -2957,13 +3113,17 @@ function endedEarlyByManager(m, r) {
2957
3113
  severity: "warning"
2958
3114
  };
2959
3115
  }
2960
- function removed(m, r) {
3116
+ function removed(m, r, capacityReduced = false) {
2961
3117
  const { lang, resourceName } = m;
2962
3118
  return {
2963
- email: { template: "removed", variables: bookingVariables(m, r) },
3119
+ email: { template: "removed", variables: { ...bookingVariables(m, r), removal: { capacity: capacityReduced } } },
2964
3120
  title: pick(lang, `Booking removed: ${resourceName}`, `Reservierung entfernt: ${resourceName}`),
2965
3121
  lines: [
2966
- pick(
3122
+ capacityReduced ? pick(
3123
+ lang,
3124
+ `${resourceName} now allows fewer parallel bookings, so your booking (${when(m, r)}) no longer fit and was cancelled.`,
3125
+ `F\xFCr ${resourceName} sind jetzt weniger parallele Buchungen m\xF6glich, daher passte deine Reservierung (${when(m, r)}) nicht mehr und wurde storniert.`
3126
+ ) : pick(
2967
3127
  lang,
2968
3128
  `Reservations were switched off for ${resourceName}, so your booking (${when(m, r)}) was cancelled.`,
2969
3129
  `Reservierungen wurden f\xFCr ${resourceName} deaktiviert, daher wurde deine Reservierung (${when(m, r)}) storniert.`
@@ -3332,13 +3492,14 @@ var ReservationNotifications = class {
3332
3492
  );
3333
3493
  }
3334
3494
  async onRemoved(r, context) {
3335
- if (context.byUserId === r.userId) return;
3495
+ const capacityReduced = context.reason === CAPACITY_REDUCED_REASON;
3496
+ if (!capacityReduced && context.byUserId === r.userId) return;
3336
3497
  await this.send(
3337
3498
  "bookings",
3338
3499
  r.resourceId,
3339
3500
  [r.userId],
3340
3501
  `reservations:removed:${r.id}`,
3341
- (m) => removed(m, r)
3502
+ (m) => removed(m, r, capacityReduced)
3342
3503
  );
3343
3504
  }
3344
3505
  // ------------------------------------- scheduler / event notifications
@@ -3467,7 +3628,7 @@ ReservationNotifications = __decorateClass([
3467
3628
  var HOUR_MS = 36e5;
3468
3629
  var DAY_MS2 = 24 * HOUR_MS;
3469
3630
  var ReservationEventHandlers = class {
3470
- constructor(context, store, reservations, settings, access, notifications, hostInfo, decisions, clock) {
3631
+ constructor(context, store, reservations, settings, access, notifications, hostInfo, decisions, clock, directory) {
3471
3632
  __publicField(this, "context", context);
3472
3633
  __publicField(this, "store", store);
3473
3634
  __publicField(this, "reservations", reservations);
@@ -3477,6 +3638,7 @@ var ReservationEventHandlers = class {
3477
3638
  __publicField(this, "hostInfo", hostInfo);
3478
3639
  __publicField(this, "decisions", decisions);
3479
3640
  __publicField(this, "clock", clock);
3641
+ __publicField(this, "directory", directory);
3480
3642
  __publicField(this, "logger", new import_common16.Logger("ReservationsEvents"));
3481
3643
  __publicField(this, "subscriptions", []);
3482
3644
  }
@@ -3497,11 +3659,12 @@ var ReservationEventHandlers = class {
3497
3659
  }
3498
3660
  });
3499
3661
  this.subscriptions = [
3500
- on(import_plugins_backend_sdk9.SystemEvent.RESOURCE_USAGE_SESSION_STARTED, (p) => this.onSessionStart(p)),
3501
- on(import_plugins_backend_sdk9.SystemEvent.RESOURCE_USAGE_SESSION_TAKEN_OVER, (p) => this.onSessionStart(p)),
3502
- on(import_plugins_backend_sdk9.SystemEvent.RESOURCE_USAGE_SESSION_ENDED, (p) => this.onSessionEnded(p)),
3503
- on(import_plugins_backend_sdk9.SystemEvent.MAINTENANCE_CHANGED, (p) => this.onMaintenance(p)),
3504
- on(import_plugins_backend_sdk9.SystemEvent.RESOURCE_HEALTH_CHANGED, (p) => this.onHealth(p))
3662
+ on(import_plugins_backend_sdk10.SystemEvent.RESOURCE_USAGE_SESSION_STARTED, (p) => this.onSessionStart(p)),
3663
+ on(import_plugins_backend_sdk10.SystemEvent.RESOURCE_USAGE_SESSION_TAKEN_OVER, (p) => this.onSessionStart(p)),
3664
+ on(import_plugins_backend_sdk10.SystemEvent.RESOURCE_USAGE_SESSION_ENDED, (p) => this.onSessionEnded(p)),
3665
+ on(import_plugins_backend_sdk10.SystemEvent.MAINTENANCE_CHANGED, (p) => this.onMaintenance(p)),
3666
+ on(import_plugins_backend_sdk10.SystemEvent.RESOURCE_HEALTH_CHANGED, (p) => this.onHealth(p)),
3667
+ on(import_plugins_backend_sdk10.SystemEvent.RESOURCE_SESSION_LIMIT_CHANGED, (p) => this.onSessionLimitChanged(p))
3505
3668
  ];
3506
3669
  }
3507
3670
  unsubscribe() {
@@ -3525,7 +3688,7 @@ var ReservationEventHandlers = class {
3525
3688
  settings.earlyCheckInMinutes
3526
3689
  );
3527
3690
  if (candidate) await this.reservations.markCheckedIn(candidate.id, usageId, startTime);
3528
- const active = (await this.store.findActiveForResource(resourceId, startTime)).find((r) => r.userId !== userId);
3691
+ const active = await this.overriddenBooking(resourceId, userId, startTime);
3529
3692
  if (!active) return;
3530
3693
  if (!await this.access.isManager(userId, resourceId)) return;
3531
3694
  if (!await this.store.claimNotice(active.id, "override_start", String(usageId), this.clock())) return;
@@ -3537,6 +3700,24 @@ var ReservationEventHandlers = class {
3537
3700
  );
3538
3701
  await this.notifications.notifyOverrideStart(active, userId);
3539
3702
  }
3703
+ /**
3704
+ * The booking a start of `userId` overrode, if any. On a single-slot machine every running booking of someone else.
3705
+ * On a shared machine anyone may start while a slot is free, so only a start that took a held slot overrode one:
3706
+ * the other sessions plus the slots held at the start fill the machine. It names the first held booking, the one the
3707
+ * gate's override question asks about first.
3708
+ */
3709
+ async overriddenBooking(resourceId, userId, startTime) {
3710
+ const running = await this.store.findActiveForResource(resourceId, startTime);
3711
+ const active = running.find((r) => r.userId !== userId);
3712
+ if (!active) return void 0;
3713
+ const limit = await this.directory.getSessionLimit(resourceId);
3714
+ if (limit <= 1) return active;
3715
+ if (running.some((r) => r.userId === userId)) return void 0;
3716
+ const sessions = (await this.directory.getActiveSessions(resourceId)).filter((s) => s.userId !== userId);
3717
+ const inSession = new Set(sessions.map((session) => session.userId));
3718
+ const held = heldBookings({ confirmed: running, starterId: userId, inSession, at: startTime });
3719
+ return sessions.length + held.length >= limit ? held[0] : void 0;
3720
+ }
3540
3721
  /**
3541
3722
  * A session ended. If it ran inside the holder's own booking without a check-in (it started before the
3542
3723
  * early check-in window and ended before the no-show deadline), it counts as the check-in. When the holder
@@ -3560,6 +3741,15 @@ var ReservationEventHandlers = class {
3560
3741
  const own = (await this.store.findActiveForResource(event.resourceId, now)).find((r) => r.userId === event.userId);
3561
3742
  if (own) this.decisions.record(event.userId, event.resourceId, own.id, now.getTime());
3562
3743
  }
3744
+ // ------------------------------------------------------------ session limit
3745
+ /**
3746
+ * The machine lost slots: cancel the newest not-yet-started bookings that no longer fit (see
3747
+ * `ReservationService.cancelExcessBookings`). A higher limit cancels nothing.
3748
+ */
3749
+ async onSessionLimitChanged(event) {
3750
+ if (event.newLimit >= event.previousLimit) return;
3751
+ await this.reservations.cancelExcessBookings(event.resourceId, event.actorUserId);
3752
+ }
3563
3753
  // ------------------------------------------------------------- maintenance
3564
3754
  /**
3565
3755
  * Notifies each holder of bookings overlapping the maintenance window once per maintenance: every affected booking
@@ -3641,7 +3831,8 @@ ReservationEventHandlers = __decorateClass([
3641
3831
  __decorateParam(5, (0, import_common16.Inject)(ReservationNotifications)),
3642
3832
  __decorateParam(6, (0, import_common16.Inject)(HostInfoService)),
3643
3833
  __decorateParam(7, (0, import_common16.Inject)(PendingDecisionStore)),
3644
- __decorateParam(8, (0, import_common16.Inject)(RESERVATION_CLOCK))
3834
+ __decorateParam(8, (0, import_common16.Inject)(RESERVATION_CLOCK)),
3835
+ __decorateParam(9, (0, import_common16.Inject)(DirectoryService))
3645
3836
  ], ReservationEventHandlers);
3646
3837
 
3647
3838
  // backend/hooks/pending-decision.service.ts
@@ -3819,6 +4010,7 @@ var ReservationQueryService = class {
3819
4010
  isManager: false,
3820
4011
  canBook: canBook2,
3821
4012
  rules,
4013
+ slots: 1,
3822
4014
  reservations: [],
3823
4015
  maintenance: []
3824
4016
  };
@@ -3830,7 +4022,8 @@ var ReservationQueryService = class {
3830
4022
  end: new Date(to.getTime() + settings.bufferAfterMinutes * MINUTE_MS2)
3831
4023
  };
3832
4024
  const margin = MAX_BUFFER_MINUTES * MINUTE_MS2;
3833
- const [candidates, windows] = await Promise.all([
4025
+ const [slots, candidates, windows] = await Promise.all([
4026
+ this.directory.getSessionLimit(resourceId),
3834
4027
  this.store.findOccupying(
3835
4028
  resourceId,
3836
4029
  new Date(span.start.getTime() - margin),
@@ -3846,6 +4039,7 @@ var ReservationQueryService = class {
3846
4039
  isManager,
3847
4040
  canBook,
3848
4041
  rules,
4042
+ slots,
3849
4043
  reservations: await this.present(actor, rows, /* @__PURE__ */ new Map([[resourceId, isManager]])),
3850
4044
  maintenance: windows.map((window) => ({
3851
4045
  startTime: window.startTime.toISOString(),
@@ -3916,9 +4110,9 @@ PendingDecisionService = __decorateClass([
3916
4110
  var import_common19 = require("@nestjs/common");
3917
4111
 
3918
4112
  // backend/reader-ui/texts.ts
3919
- var import_plugins_backend_sdk10 = require("@attraccess/plugins-backend-sdk");
4113
+ var import_plugins_backend_sdk11 = require("@attraccess/plugins-backend-sdk");
3920
4114
  var READER_NAME_MAX = 16;
3921
- var ROW_MAX = import_plugins_backend_sdk10.READER_UI_LIMITS.maxListRowChars;
4115
+ var ROW_MAX = import_plugins_backend_sdk11.READER_UI_LIMITS.maxListRowChars;
3922
4116
  function fit(text, max) {
3923
4117
  return text.length <= max ? text : text.slice(0, max).trimEnd();
3924
4118
  }
@@ -3987,6 +4181,8 @@ var readerTexts = {
3987
4181
  return long.length <= ROW_MAX ? long : fit(pick(c.lang, `Res., check-in ${at}`, `Res., Check-in ${at}`), ROW_MAX);
3988
4182
  },
3989
4183
  rowReservedUntil: (end, c) => fit(pick(c.lang, `Reserved until ${readerTime(end, c)}`, `Reserviert bis ${readerTime(end, c)}`), ROW_MAX),
4184
+ /** Shared machine, bookings run but slots remain: "2/3 reserved" (≤ 24 characters). */
4185
+ rowSlotsReserved: (reserved, slots, c) => fit(pick(c.lang, `${reserved}/${slots} reserved`, `${reserved}/${slots} reserviert`), ROW_MAX),
3990
4186
  rowOwnUntil: (end, c) => {
3991
4187
  const until = readerTime(end, c);
3992
4188
  const long = pick(c.lang, `Your booking until ${until}`, `Deine Buchung bis ${until}`);
@@ -4009,6 +4205,7 @@ var readerTexts = {
4009
4205
  ) : [pick(c.lang, `then reserved until ${readerTime(end, c)}`, `dann reserviert bis ${readerTime(end, c)}`)]
4010
4206
  ],
4011
4207
  reserved: (start, end, c, holder) => holder ? named(pick(c.lang, `Reserved by ${holder}`, `Reserviert von ${holder}`), range(start, end, c)) : [pick(c.lang, `Reserved ${range(start, end, c)}`, `Reserviert ${range(start, end, c)}`)],
4208
+ slotsReserved: (reserved, slots, c) => pick(c.lang, `${reserved} of ${slots} slots reserved`, `${reserved} von ${slots} Pl\xE4tzen reserviert`),
4012
4209
  own: (start, end, c) => pick(c.lang, `Your booking ${range(start, end, c)}`, `Deine Buchung ${range(start, end, c)}`),
4013
4210
  /** Its own line under the booking, so the parenthesis never starts a wrapped line by itself. */
4014
4211
  checkInLine: (deadline, c) => pick(c.lang, `(check in by ${readerTime(deadline, c)})`, `(Check-in bis ${readerTime(deadline, c)})`),
@@ -4068,6 +4265,11 @@ async function startBlockedQuery(ctx) {
4068
4265
  const deadline = hookDeadline();
4069
4266
  return (await resolveHookServices(deadline)).preStart.evaluateStartBlocked(ctx, deadline);
4070
4267
  }
4268
+ var startCapacityHook = async (ctx) => {
4269
+ const deadline = hookDeadline();
4270
+ const { startCapacity } = await resolveHookServices(deadline);
4271
+ return startCapacity ? startCapacity.evaluate(ctx, deadline) : { heldSlots: 0 };
4272
+ };
4071
4273
  var readerUiProvider = {
4072
4274
  async getSlotContributions(ctx) {
4073
4275
  const deadline = hookDeadline();
@@ -4085,6 +4287,14 @@ var MINUTE_MS3 = 6e4;
4085
4287
  var MAX_HOLDER_NAME_CHARS = 40;
4086
4288
  var reservationStepKey = (id) => `reservation-${id}`;
4087
4289
  var overrideStepKey = (id) => `override-${id}`;
4290
+ function overriddenBookingIds(stepKeys) {
4291
+ return new Set(
4292
+ stepKeys.flatMap((key) => {
4293
+ const match = /^override-(\d+)$/.exec(key);
4294
+ return match ? [Number(match[1])] : [];
4295
+ })
4296
+ );
4297
+ }
4088
4298
  var PreStartService = class {
4089
4299
  constructor(settings, globalSettings, store, access, directory, visibility, clock) {
4090
4300
  __publicField(this, "settings", settings);
@@ -4107,10 +4317,11 @@ var PreStartService = class {
4107
4317
  if (!settings.enabled) return ALLOW;
4108
4318
  const now = ctx.now ?? this.clock();
4109
4319
  const horizon = new Date(now.getTime() + settings.confirmWindowMinutes * MINUTE_MS3 + 1);
4110
- const others = (await this.store.findConfirmedOverlapping(ctx.resourceId, now, horizon)).filter(
4111
- (reservation) => reservation.userId !== ctx.userId
4112
- );
4320
+ const confirmed2 = await this.store.findConfirmedOverlapping(ctx.resourceId, now, horizon);
4321
+ const others = confirmed2.filter((reservation) => reservation.userId !== ctx.userId);
4113
4322
  if (others.length === 0) return ALLOW;
4323
+ const limit = await this.directory.getSessionLimit(ctx.resourceId);
4324
+ if (limit > 1) return this.evaluateShared(ctx, confirmed2, limit, now);
4114
4325
  const nowMs = now.getTime();
4115
4326
  const active = others.filter((r) => r.startTime.getTime() <= nowMs);
4116
4327
  if (active.length > 0) {
@@ -4121,6 +4332,37 @@ var PreStartService = class {
4121
4332
  (r) => r.startTime.getTime() > nowMs && !ctx.confirmedStepKeys.includes(reservationStepKey(r.id))
4122
4333
  );
4123
4334
  if (!upcoming) return ALLOW;
4335
+ return this.askReservedSoon(ctx, upcoming, now);
4336
+ }
4337
+ /**
4338
+ * The gate on a machine with several slots. Running bookings block only when the slots they hold fill the
4339
+ * machine for this starter (the starter's own running booking is their slot); an upcoming booking is asked about
4340
+ * only when starting now would leave it without a slot at its start.
4341
+ */
4342
+ async evaluateShared(ctx, confirmed2, limit, now) {
4343
+ const nowMs = now.getTime();
4344
+ const sessions = await this.directory.getActiveSessions(ctx.resourceId);
4345
+ const inSession = new Set(sessions.map((session) => session.userId));
4346
+ const running = confirmed2.filter((r) => r.startTime.getTime() <= nowMs);
4347
+ const overridden = overriddenBookingIds(ctx.confirmedStepKeys);
4348
+ if (!running.some((r) => r.userId === ctx.userId)) {
4349
+ const held = heldBookings({ confirmed: running, starterId: ctx.userId, inSession, at: now, overridden });
4350
+ if (held.length > 0 && limit - sessions.length - held.length <= 0) {
4351
+ const verdict = await this.whenActive(ctx, held, now);
4352
+ if (verdict) return verdict;
4353
+ }
4354
+ }
4355
+ for (const booking of confirmed2) {
4356
+ if (booking.userId === ctx.userId || booking.startTime.getTime() <= nowMs) continue;
4357
+ if (ctx.confirmedStepKeys.includes(reservationStepKey(booking.id))) continue;
4358
+ const heldThen = heldBookings({ confirmed: confirmed2, starterId: ctx.userId, inSession, at: booking.startTime, overridden });
4359
+ if (sessions.length + 1 + heldThen.length > limit) return this.askReservedSoon(ctx, booking, now);
4360
+ }
4361
+ return ALLOW;
4362
+ }
4363
+ /** The "Reserved soon ... Start anyway?" question for an upcoming booking of someone else. */
4364
+ async askReservedSoon(ctx, upcoming, now) {
4365
+ const nowMs = now.getTime();
4124
4366
  const { language: lang } = ctx;
4125
4367
  const minutes = Math.max(1, Math.ceil((upcoming.startTime.getTime() - nowMs) / MINUTE_MS3));
4126
4368
  const from = await this.timeText(ctx, upcoming.startTime, now);
@@ -4160,8 +4402,22 @@ var PreStartService = class {
4160
4402
  }
4161
4403
  if (!this.settings.getCachedSettings(ctx.resourceId).enabled) return null;
4162
4404
  const now = ctx.now ?? this.clock();
4163
- const active = (await this.store.findActiveForResource(ctx.resourceId, now)).find((r) => r.userId !== ctx.userId);
4405
+ const running = await this.store.findActiveForResource(ctx.resourceId, now);
4406
+ let active = running.find((r) => r.userId !== ctx.userId);
4164
4407
  if (!active) return null;
4408
+ const limit = await this.directory.getSessionLimit(ctx.resourceId);
4409
+ if (limit > 1) {
4410
+ if (running.some((r) => r.userId === ctx.userId)) return null;
4411
+ const sessions = await this.directory.getActiveSessions(ctx.resourceId);
4412
+ const held = heldBookings({
4413
+ confirmed: running,
4414
+ starterId: ctx.userId,
4415
+ inSession: new Set(sessions.map((session) => session.userId)),
4416
+ at: now
4417
+ });
4418
+ if (held.length === 0 || limit - sessions.length - held.length > 0) return null;
4419
+ active = held[0];
4420
+ }
4165
4421
  const viewer = subjectOfPrincipal(ctx.principal);
4166
4422
  if (await this.access.isManager(viewer, ctx.resourceId)) return null;
4167
4423
  if ((await this.visibility.filterVisible(viewer, [ctx.resourceId])).length === 0) return null;
@@ -4170,6 +4426,17 @@ var PreStartService = class {
4170
4426
  const until = formatTime(active.endTime, { lang: ctx.language, timeZone });
4171
4427
  return { reason: reservedReason(ctx.language, until, holder), until: active.endTime };
4172
4428
  }
4429
+ /**
4430
+ * The `RESERVED` refusal for a start that finds every free slot held for `booking`'s holder: same text and
4431
+ * holder-name rule as the gate's block, used by the host's atomic start check.
4432
+ */
4433
+ async reservedBlockReason(ctx, booking, now) {
4434
+ const starter = subjectOfPrincipal(ctx.principal);
4435
+ const until = await this.timeText(ctx, booking.endTime, now);
4436
+ const found = await this.holderNameFor(starter, booking);
4437
+ const holder = found && ctx.origin === "reader" ? readerName(found) : found;
4438
+ return reservedReason(ctx.language, until, holder);
4439
+ }
4173
4440
  /**
4174
4441
  * The booking holder's name for a viewer who may see who uses the machine (core's usage attribution rule, the
4175
4442
  * same one that decides who sees the current user of a running session); null for everyone else.
@@ -4252,13 +4519,13 @@ function reservedReason(lang, until, holder) {
4252
4519
  }
4253
4520
 
4254
4521
  // backend/hooks/publisher.ts
4255
- var import_common22 = require("@nestjs/common");
4522
+ var import_common23 = require("@nestjs/common");
4256
4523
 
4257
4524
  // backend/reader-ui/reader-ui.service.ts
4258
- var import_plugins_backend_sdk11 = require("@attraccess/plugins-backend-sdk");
4525
+ var import_plugins_backend_sdk12 = require("@attraccess/plugins-backend-sdk");
4259
4526
  var import_common20 = require("@nestjs/common");
4260
4527
  var MINUTE_MS4 = 6e4;
4261
- var SLOT = import_plugins_backend_sdk11.READER_UI_SLOTS;
4528
+ var SLOT = import_plugins_backend_sdk12.READER_UI_SLOTS;
4262
4529
  var ReaderUiService = class {
4263
4530
  constructor(settings, globalSettings, store, access, directory, clock) {
4264
4531
  __publicField(this, "settings", settings);
@@ -4298,14 +4565,17 @@ var ReaderUiService = class {
4298
4565
  const early = settings.earlyCheckInMinutes * MINUTE_MS4;
4299
4566
  const running = bookings.find((r) => r.startTime.getTime() <= nowMs);
4300
4567
  const upcoming = bookings.filter((r) => r.startTime.getTime() > nowMs);
4301
- const own = userId === void 0 ? void 0 : this.ownBooking(userId, running, upcoming, nowMs, early);
4302
- const subject = own ?? running ?? upcoming[0];
4303
- if (!subject) return [];
4568
+ const limit = await this.directory.getSessionLimit(ctx.resourceId);
4569
+ const shared = limit > 1 ? await this.sharedSlots(ctx, bookings, limit, now) : null;
4570
+ const own = userId === void 0 ? void 0 : this.ownBooking(userId, running, upcoming, nowMs, early, shared);
4571
+ const subject = this.subjectOf(own, running, upcoming, shared);
4572
+ if (!subject && !(shared && shared.reserved > 0)) return [];
4304
4573
  const nameOf = this.nameResolver(ctx);
4305
- const holder = own ? void 0 : await nameOf(subject);
4306
- const state = this.describe(subject, running === subject, settings, clock, holder, own !== void 0);
4574
+ const holder = !subject || own ? void 0 : await nameOf(subject);
4575
+ const state = subject ? this.describe(subject, subject.startTime.getTime() <= nowMs, settings, clock, holder, own !== void 0) : this.reservedCount(shared?.reserved ?? 0, limit, bookings, nowMs, clock);
4307
4576
  const boundaries = [state.boundary, nextLocalMidnight(now, clock.timeZone).getTime()];
4308
4577
  if (upcoming[0]) boundaries.push(upcoming[0].startTime.getTime());
4578
+ if (shared) boundaries.push(...bookings.flatMap((r) => [r.startTime.getTime(), r.endTime.getTime()]));
4309
4579
  const contributions = [];
4310
4580
  const add = (slotId, key, tree, text, tone) => contributions.push({ slotId, key, tree, fallback: { text, tone } });
4311
4581
  add(
@@ -4315,17 +4585,10 @@ var ReaderUiService = class {
4315
4585
  state.row,
4316
4586
  state.tone
4317
4587
  );
4318
- let sessionBooking;
4319
- if (ctx.sessionActive === true && userId !== void 0 && settings.confirmWindowMinutes > 0) {
4320
- const window = settings.confirmWindowMinutes * MINUTE_MS4;
4321
- const next = upcoming.find((r) => r.userId !== userId && r.startTime.getTime() - nowMs <= window);
4322
- if (next) sessionBooking = next;
4323
- else {
4324
- const opens = upcoming.find((r) => r.userId !== userId);
4325
- if (opens) boundaries.push(opens.startTime.getTime() - window);
4326
- }
4327
- }
4328
- if (subject !== sessionBooking) {
4588
+ const countdown = this.sessionCountdown(ctx, settings, upcoming, shared, nowMs);
4589
+ const sessionBooking = countdown.next;
4590
+ if (countdown.opensAt !== void 0) boundaries.push(countdown.opensAt);
4591
+ if (subject !== sessionBooking || !subject) {
4329
4592
  const lines = state.body.map((text) => ({ t: "text", text, style: "body" }));
4330
4593
  add(
4331
4594
  SLOT.RESOURCE_DETAILS_BODY,
@@ -4337,21 +4600,8 @@ var ReaderUiService = class {
4337
4600
  if (sessionBooking) {
4338
4601
  const next = sessionBooking;
4339
4602
  const sessionHolder = next === subject ? holder : await nameOf(next);
4340
- const texts = readerTexts.sessionReserved(next.startTime, next.endTime, clock, sessionHolder);
4341
- const lines = texts.map((text) => ({ t: "text", text, style: "small", fill: true }));
4342
- add(
4343
- SLOT.RESOURCE_DETAILS_SESSION,
4344
- "reserved-soon",
4345
- {
4346
- t: "row",
4347
- c: [
4348
- lines.length === 1 ? lines[0] : { t: "col", gap: 0, fill: true, c: lines },
4349
- { t: "countdown", to: next.startTime, tone: "warning" }
4350
- ]
4351
- },
4352
- texts.join(" "),
4353
- "warning"
4354
- );
4603
+ const { tree, text } = this.sessionTree(next, clock, sessionHolder);
4604
+ add(SLOT.RESOURCE_DETAILS_SESSION, "reserved-soon", tree, text, "warning");
4355
4605
  boundaries.push(next.startTime.getTime());
4356
4606
  }
4357
4607
  if (userId !== void 0 && upcoming.length > 0 && !own) {
@@ -4360,11 +4610,93 @@ var ReaderUiService = class {
4360
4610
  const expiresAt = new Date(Math.min(...boundaries.filter((at) => at > nowMs)));
4361
4611
  return contributions.map((c) => ({ ...c, expiresAt }));
4362
4612
  }
4363
- /** Your own booking while it runs or within the early check-in window before it starts. */
4364
- ownBooking(userId, running, upcoming, nowMs, early) {
4613
+ /**
4614
+ * The slot picture of a shared machine: sessions and the bookings that hold slots for the viewer's disadvantage.
4615
+ * `ownRunning`: the viewer's own running booking (their slot); `blocker`: the running booking to name when no free
4616
+ * slot is left for the viewer (a signed-out reader counts as nobody); `reserved`: running bookings (one per person);
4617
+ * `nextLacking`: the next booking of someone else that would find no slot at its start if the viewer started now;
4618
+ * `lacksSlotWith`: whether a booking would lack its slot with the viewer's session running (as in the gate: sessions,
4619
+ * one more slot for a viewer not in session yet, and the slots held at the booking's start).
4620
+ */
4621
+ async sharedSlots(ctx, bookings, limit, now) {
4622
+ const nowMs = now.getTime();
4623
+ const sessions = await this.directory.getActiveSessions(ctx.resourceId);
4624
+ const inSession = new Set(sessions.map((session) => session.userId));
4625
+ const running = bookings.filter((r) => r.startTime.getTime() <= nowMs);
4626
+ const viewerId = ctx.userId ?? -1;
4627
+ const held = heldBookings({ confirmed: running, starterId: viewerId, inSession, at: now });
4628
+ const ownRunning = running.find((r) => r.userId === viewerId);
4629
+ const free = limit - sessions.length - held.length;
4630
+ const lacksSlotWith = (booking, viewer) => sessions.length + (viewer === void 0 || inSession.has(viewer) ? 0 : 1) + heldBookings({ confirmed: bookings, starterId: viewer ?? -1, inSession, at: booking.startTime }).length > limit;
4631
+ return {
4632
+ ownRunning,
4633
+ blocker: !ownRunning && held.length > 0 && free <= 0 ? held[0] : void 0,
4634
+ reserved: new Set(running.map((r) => r.userId)).size,
4635
+ nextLacking: bookings.find(
4636
+ (r) => r.startTime.getTime() > nowMs && r.userId !== ctx.userId && lacksSlotWith(r, ctx.userId)
4637
+ ),
4638
+ lacksSlotWith
4639
+ };
4640
+ }
4641
+ /** Bookings run but slots remain: a short success text with the count (Latin-1, within the row limit). */
4642
+ reservedCount(reserved, limit, bookings, nowMs, clock) {
4643
+ const ends = bookings.filter((r) => r.startTime.getTime() <= nowMs).map((r) => r.endTime.getTime());
4644
+ return {
4645
+ row: readerTexts.rowSlotsReserved(reserved, limit, clock),
4646
+ body: [readerTexts.slotsReserved(reserved, limit, clock)],
4647
+ tone: "success",
4648
+ boundary: Math.min(...ends)
4649
+ };
4650
+ }
4651
+ /**
4652
+ * The booking the details are about. On a shared machine a running booking only shows as a warning when it holds
4653
+ * the last free slot, and an upcoming booking only if it would lack its slot (the gate would ask about it); with
4654
+ * none of these a short count replaces it (no subject).
4655
+ */
4656
+ subjectOf(own, running, upcoming, shared) {
4657
+ if (!shared) return own ?? running ?? upcoming[0];
4658
+ return own ?? shared.blocker ?? shared.nextLacking;
4659
+ }
4660
+ /**
4661
+ * Session area: another user's booking that starts within the confirm window (on a shared machine only one the
4662
+ * viewer's session would leave without a slot), or when the window opens for the next one.
4663
+ */
4664
+ sessionCountdown(ctx, settings, upcoming, shared, nowMs) {
4665
+ const userId = ctx.userId;
4666
+ if (ctx.sessionActive !== true || userId === void 0 || settings.confirmWindowMinutes <= 0) return {};
4667
+ const window = settings.confirmWindowMinutes * MINUTE_MS4;
4668
+ const needsSlot = (r) => r.userId !== userId && (!shared || shared.lacksSlotWith(r, userId));
4669
+ const next = upcoming.find((r) => needsSlot(r) && r.startTime.getTime() - nowMs <= window);
4670
+ if (next) return { next };
4671
+ const opens = upcoming.find(needsSlot);
4672
+ return opens ? { opensAt: opens.startTime.getTime() - window } : {};
4673
+ }
4674
+ /** The session-area row: the booking's range and a countdown to its start. */
4675
+ sessionTree(next, clock, holder) {
4676
+ const texts = readerTexts.sessionReserved(next.startTime, next.endTime, clock, holder);
4677
+ const lines = texts.map((text) => ({ t: "text", text, style: "small", fill: true }));
4678
+ return {
4679
+ tree: {
4680
+ t: "row",
4681
+ c: [
4682
+ lines.length === 1 ? lines[0] : { t: "col", gap: 0, fill: true, c: lines },
4683
+ { t: "countdown", to: next.startTime, tone: "warning" }
4684
+ ]
4685
+ },
4686
+ text: texts.join(" ")
4687
+ };
4688
+ }
4689
+ /**
4690
+ * Your own booking while it runs or within the early check-in window before it starts. On a shared machine your
4691
+ * running booking is found among all running ones, and a booking that leaves you no free slot wins over your
4692
+ * upcoming one (you could not start yet).
4693
+ */
4694
+ ownBooking(userId, running, upcoming, nowMs, early, shared) {
4695
+ const soon = () => upcoming.find((r) => r.userId === userId && r.startTime.getTime() - nowMs <= early);
4696
+ if (shared) return shared.ownRunning ?? (shared.blocker ? void 0 : soon());
4365
4697
  if (running?.userId === userId) return running;
4366
4698
  if (running) return void 0;
4367
- return upcoming.find((r) => r.userId === userId && r.startTime.getTime() - nowMs <= early);
4699
+ return soon();
4368
4700
  }
4369
4701
  /**
4370
4702
  * Resolves holder names for this viewer: undefined for a signed-out reader (no lookup at all), for the
@@ -4433,8 +4765,45 @@ ReaderUiService = __decorateClass([
4433
4765
  __decorateParam(5, (0, import_common20.Inject)(RESERVATION_CLOCK))
4434
4766
  ], ReaderUiService);
4435
4767
 
4436
- // backend/hooks/session-end.service.ts
4768
+ // backend/hooks/start-capacity.service.ts
4437
4769
  var import_common21 = require("@nestjs/common");
4770
+ var StartCapacityService = class {
4771
+ constructor(settings, store, preStart) {
4772
+ __publicField(this, "settings", settings);
4773
+ __publicField(this, "store", store);
4774
+ __publicField(this, "preStart", preStart);
4775
+ }
4776
+ async evaluate(ctx, deadline = hookDeadline()) {
4777
+ if (!this.settings.isWarm) {
4778
+ await waitUntil(this.settings.whenReady(), deadline, "Reservation settings are not loaded yet");
4779
+ }
4780
+ if (!this.settings.getCachedSettings(ctx.resourceId).enabled) return { heldSlots: 0 };
4781
+ const running = await this.store.findRunningConfirmed(ctx.manager, ctx.resourceId, ctx.now);
4782
+ if (running.length === 0 || running.some((r) => r.userId === ctx.userId)) return { heldSlots: 0 };
4783
+ const held = heldBookings({
4784
+ confirmed: running,
4785
+ starterId: ctx.userId,
4786
+ // A holder in session (or starting) is counted through `occupiedSlots`, never twice.
4787
+ inSession: new Set(ctx.usersInSession),
4788
+ at: ctx.now,
4789
+ overridden: overriddenBookingIds(ctx.confirmedStepKeys)
4790
+ });
4791
+ if (held.length === 0 || ctx.occupiedSlots + held.length < ctx.sessionLimit) return { heldSlots: held.length };
4792
+ return {
4793
+ heldSlots: held.length,
4794
+ reason: await this.preStart.reservedBlockReason(ctx, held[0], ctx.now)
4795
+ };
4796
+ }
4797
+ };
4798
+ StartCapacityService = __decorateClass([
4799
+ (0, import_common21.Injectable)(),
4800
+ __decorateParam(0, (0, import_common21.Inject)(ResourceSettingsService)),
4801
+ __decorateParam(1, (0, import_common21.Inject)(ReservationStore)),
4802
+ __decorateParam(2, (0, import_common21.Inject)(PreStartService))
4803
+ ], StartCapacityService);
4804
+
4805
+ // backend/hooks/session-end.service.ts
4806
+ var import_common22 = require("@nestjs/common");
4438
4807
  var NONE = Object.freeze({ decision: "none" });
4439
4808
  var SessionEndService = class {
4440
4809
  constructor(settings, globalSettings, store, reservations, decisions, clock) {
@@ -4444,7 +4813,7 @@ var SessionEndService = class {
4444
4813
  __publicField(this, "reservations", reservations);
4445
4814
  __publicField(this, "decisions", decisions);
4446
4815
  __publicField(this, "clock", clock);
4447
- __publicField(this, "logger", new import_common21.Logger("ReservationsSessionEnd"));
4816
+ __publicField(this, "logger", new import_common22.Logger("ReservationsSessionEnd"));
4448
4817
  }
4449
4818
  /** `deadline` (epoch ms) bounds the wait for the settings cache; past it this throws (host policy applies). */
4450
4819
  async evaluate(ctx, deadline = hookDeadline()) {
@@ -4495,39 +4864,46 @@ var SessionEndService = class {
4495
4864
  }
4496
4865
  };
4497
4866
  SessionEndService = __decorateClass([
4498
- (0, import_common21.Injectable)(),
4499
- __decorateParam(0, (0, import_common21.Inject)(ResourceSettingsService)),
4500
- __decorateParam(1, (0, import_common21.Inject)(GlobalSettingsService)),
4501
- __decorateParam(2, (0, import_common21.Inject)(ReservationStore)),
4502
- __decorateParam(3, (0, import_common21.Inject)(ReservationService)),
4503
- __decorateParam(4, (0, import_common21.Inject)(PendingDecisionStore)),
4504
- __decorateParam(5, (0, import_common21.Inject)(RESERVATION_CLOCK))
4867
+ (0, import_common22.Injectable)(),
4868
+ __decorateParam(0, (0, import_common22.Inject)(ResourceSettingsService)),
4869
+ __decorateParam(1, (0, import_common22.Inject)(GlobalSettingsService)),
4870
+ __decorateParam(2, (0, import_common22.Inject)(ReservationStore)),
4871
+ __decorateParam(3, (0, import_common22.Inject)(ReservationService)),
4872
+ __decorateParam(4, (0, import_common22.Inject)(PendingDecisionStore)),
4873
+ __decorateParam(5, (0, import_common22.Inject)(RESERVATION_CLOCK))
4505
4874
  ], SessionEndService);
4506
4875
 
4507
4876
  // backend/hooks/publisher.ts
4508
4877
  var HookServicePublisher = class {
4509
- constructor(preStart, sessionEnd, readerUi) {
4878
+ constructor(preStart, startCapacity, sessionEnd, readerUi) {
4510
4879
  __publicField(this, "preStart", preStart);
4880
+ __publicField(this, "startCapacity", startCapacity);
4511
4881
  __publicField(this, "sessionEnd", sessionEnd);
4512
4882
  __publicField(this, "readerUi", readerUi);
4513
4883
  }
4514
4884
  onModuleInit() {
4515
- publishHookServices({ preStart: this.preStart, sessionEnd: this.sessionEnd, readerUi: this.readerUi });
4885
+ publishHookServices({
4886
+ preStart: this.preStart,
4887
+ startCapacity: this.startCapacity,
4888
+ sessionEnd: this.sessionEnd,
4889
+ readerUi: this.readerUi
4890
+ });
4516
4891
  }
4517
4892
  onModuleDestroy() {
4518
4893
  publishHookServices(null);
4519
4894
  }
4520
4895
  };
4521
4896
  HookServicePublisher = __decorateClass([
4522
- (0, import_common22.Injectable)(),
4523
- __decorateParam(0, (0, import_common22.Inject)(PreStartService)),
4524
- __decorateParam(1, (0, import_common22.Inject)(SessionEndService)),
4525
- __decorateParam(2, (0, import_common22.Inject)(ReaderUiService))
4897
+ (0, import_common23.Injectable)(),
4898
+ __decorateParam(0, (0, import_common23.Inject)(PreStartService)),
4899
+ __decorateParam(1, (0, import_common23.Inject)(StartCapacityService)),
4900
+ __decorateParam(2, (0, import_common23.Inject)(SessionEndService)),
4901
+ __decorateParam(3, (0, import_common23.Inject)(ReaderUiService))
4526
4902
  ], HookServicePublisher);
4527
4903
 
4528
4904
  // backend/ical/ical.controller.ts
4529
- var import_plugins_backend_sdk13 = require("@attraccess/plugins-backend-sdk");
4530
- var import_common24 = require("@nestjs/common");
4905
+ var import_plugins_backend_sdk14 = require("@attraccess/plugins-backend-sdk");
4906
+ var import_common25 = require("@nestjs/common");
4531
4907
  var import_swagger6 = require("@nestjs/swagger");
4532
4908
 
4533
4909
  // backend/ical/ical.dto.ts
@@ -4658,11 +5034,11 @@ __decorateClass([
4658
5034
  ], IcalFeedSecretDto.prototype, "token", 2);
4659
5035
 
4660
5036
  // backend/ical/ical.service.ts
4661
- var import_common23 = require("@nestjs/common");
5037
+ var import_common24 = require("@nestjs/common");
4662
5038
  var import_node_crypto2 = require("node:crypto");
4663
5039
 
4664
5040
  // backend/entities/ical-feed.entity.ts
4665
- var import_plugins_backend_sdk12 = require("@attraccess/plugins-backend-sdk");
5041
+ var import_plugins_backend_sdk13 = require("@attraccess/plugins-backend-sdk");
4666
5042
  var IcalFeedEntity = class {
4667
5043
  constructor() {
4668
5044
  __publicField(this, "id");
@@ -4677,35 +5053,35 @@ var IcalFeedEntity = class {
4677
5053
  }
4678
5054
  };
4679
5055
  __decorateClass([
4680
- (0, import_plugins_backend_sdk12.PrimaryGeneratedColumn)({ type: "integer" })
5056
+ (0, import_plugins_backend_sdk13.PrimaryGeneratedColumn)({ type: "integer" })
4681
5057
  ], IcalFeedEntity.prototype, "id", 2);
4682
5058
  __decorateClass([
4683
- (0, import_plugins_backend_sdk12.Column)({ type: "integer" })
5059
+ (0, import_plugins_backend_sdk13.Column)({ type: "integer" })
4684
5060
  ], IcalFeedEntity.prototype, "userId", 2);
4685
5061
  __decorateClass([
4686
- (0, import_plugins_backend_sdk12.Column)({ type: "varchar" })
5062
+ (0, import_plugins_backend_sdk13.Column)({ type: "varchar" })
4687
5063
  ], IcalFeedEntity.prototype, "name", 2);
4688
5064
  __decorateClass([
4689
- (0, import_plugins_backend_sdk12.Column)({ type: "varchar", unique: true })
5065
+ (0, import_plugins_backend_sdk13.Column)({ type: "varchar", unique: true })
4690
5066
  ], IcalFeedEntity.prototype, "tokenHash", 2);
4691
5067
  __decorateClass([
4692
- (0, import_plugins_backend_sdk12.Column)({ type: "varchar", nullable: true })
5068
+ (0, import_plugins_backend_sdk13.Column)({ type: "varchar", nullable: true })
4693
5069
  ], IcalFeedEntity.prototype, "tokenPrefix", 2);
4694
5070
  __decorateClass([
4695
- (0, import_plugins_backend_sdk12.Column)({ type: "text" })
5071
+ (0, import_plugins_backend_sdk13.Column)({ type: "text" })
4696
5072
  ], IcalFeedEntity.prototype, "selection", 2);
4697
5073
  __decorateClass([
4698
- (0, import_plugins_backend_sdk12.Column)({ type: "datetime" })
5074
+ (0, import_plugins_backend_sdk13.Column)({ type: "datetime" })
4699
5075
  ], IcalFeedEntity.prototype, "createdAt", 2);
4700
5076
  __decorateClass([
4701
- (0, import_plugins_backend_sdk12.Column)({ type: "datetime", nullable: true })
5077
+ (0, import_plugins_backend_sdk13.Column)({ type: "datetime", nullable: true })
4702
5078
  ], IcalFeedEntity.prototype, "revokedAt", 2);
4703
5079
  __decorateClass([
4704
- (0, import_plugins_backend_sdk12.Column)({ type: "datetime", nullable: true })
5080
+ (0, import_plugins_backend_sdk13.Column)({ type: "datetime", nullable: true })
4705
5081
  ], IcalFeedEntity.prototype, "lastUsedAt", 2);
4706
5082
  IcalFeedEntity = __decorateClass([
4707
- (0, import_plugins_backend_sdk12.Entity)({ name: "reservations_ical_feed" }),
4708
- (0, import_plugins_backend_sdk12.Index)("IDX_reservations_ical_feed_user", ["userId"])
5083
+ (0, import_plugins_backend_sdk13.Entity)({ name: "reservations_ical_feed" }),
5084
+ (0, import_plugins_backend_sdk13.Index)("IDX_reservations_ical_feed_user", ["userId"])
4709
5085
  ], IcalFeedEntity);
4710
5086
 
4711
5087
  // backend/ical/ical-format.ts
@@ -5006,16 +5382,16 @@ var IcalService = class {
5006
5382
  }
5007
5383
  };
5008
5384
  IcalService = __decorateClass([
5009
- (0, import_common23.Injectable)(),
5010
- __decorateParam(0, (0, import_common23.Inject)(PLUGIN_CONTEXT)),
5011
- __decorateParam(1, (0, import_common23.Inject)(ReservationStore)),
5012
- __decorateParam(2, (0, import_common23.Inject)(ResourceSettingsService)),
5013
- __decorateParam(3, (0, import_common23.Inject)(GlobalSettingsService)),
5014
- __decorateParam(4, (0, import_common23.Inject)(AccessService)),
5015
- __decorateParam(5, (0, import_common23.Inject)(DirectoryService)),
5016
- __decorateParam(6, (0, import_common23.Inject)(VisibilityService)),
5017
- __decorateParam(7, (0, import_common23.Inject)(HostInfoService)),
5018
- __decorateParam(8, (0, import_common23.Inject)(RESERVATION_CLOCK))
5385
+ (0, import_common24.Injectable)(),
5386
+ __decorateParam(0, (0, import_common24.Inject)(PLUGIN_CONTEXT)),
5387
+ __decorateParam(1, (0, import_common24.Inject)(ReservationStore)),
5388
+ __decorateParam(2, (0, import_common24.Inject)(ResourceSettingsService)),
5389
+ __decorateParam(3, (0, import_common24.Inject)(GlobalSettingsService)),
5390
+ __decorateParam(4, (0, import_common24.Inject)(AccessService)),
5391
+ __decorateParam(5, (0, import_common24.Inject)(DirectoryService)),
5392
+ __decorateParam(6, (0, import_common24.Inject)(VisibilityService)),
5393
+ __decorateParam(7, (0, import_common24.Inject)(HostInfoService)),
5394
+ __decorateParam(8, (0, import_common24.Inject)(RESERVATION_CLOCK))
5019
5395
  ], IcalService);
5020
5396
 
5021
5397
  // backend/ical/rate-limiter.ts
@@ -5085,14 +5461,14 @@ var IcalFeedsController = class {
5085
5461
  }
5086
5462
  };
5087
5463
  __decorateClass([
5088
- (0, import_common24.Get)(),
5464
+ (0, import_common25.Get)(),
5089
5465
  (0, import_swagger6.ApiOperation)({ summary: "My calendar feeds (without their secret URLs)" }),
5090
5466
  (0, import_swagger6.ApiOkResponse)({ type: [IcalFeedDto] }),
5091
- __decorateParam(0, (0, import_common24.Req)())
5467
+ __decorateParam(0, (0, import_common25.Req)())
5092
5468
  ], IcalFeedsController.prototype, "list", 1);
5093
5469
  __decorateClass([
5094
- (0, import_common24.Post)(),
5095
- (0, import_common24.UseGuards)(import_plugins_backend_sdk13.SessionOnlyGuard),
5470
+ (0, import_common25.Post)(),
5471
+ (0, import_common25.UseGuards)(import_plugins_backend_sdk14.SessionOnlyGuard),
5096
5472
  (0, import_swagger6.ApiForbiddenResponse)({ description: "Session authentication required (API tokens cannot issue feed URLs)" }),
5097
5473
  (0, import_swagger6.ApiOperation)({
5098
5474
  summary: "Create a calendar feed",
@@ -5101,24 +5477,24 @@ __decorateClass([
5101
5477
  (0, import_swagger6.ApiBody)({ type: CreateIcalFeedBody }),
5102
5478
  (0, import_swagger6.ApiCreatedResponse)({ type: IcalFeedSecretDto }),
5103
5479
  ApiReservationErrors({ badRequest: true, conflict: ["FEED_LIMIT"] }),
5104
- __decorateParam(0, (0, import_common24.Body)(validated(CreateIcalFeedBody))),
5105
- __decorateParam(1, (0, import_common24.Req)())
5480
+ __decorateParam(0, (0, import_common25.Body)(validated(CreateIcalFeedBody))),
5481
+ __decorateParam(1, (0, import_common25.Req)())
5106
5482
  ], IcalFeedsController.prototype, "create", 1);
5107
5483
  __decorateClass([
5108
- (0, import_common24.Patch)(":id"),
5484
+ (0, import_common25.Patch)(":id"),
5109
5485
  (0, import_swagger6.ApiOperation)({ summary: "Rename a feed or change what it shows (the URL stays)" }),
5110
5486
  (0, import_swagger6.ApiParam)(FEED_ID),
5111
5487
  (0, import_swagger6.ApiBody)({ type: UpdateIcalFeedBody }),
5112
5488
  (0, import_swagger6.ApiOkResponse)({ type: IcalFeedDto }),
5113
5489
  ApiReservationErrors({ badRequest: true, notFound: true }),
5114
- __decorateParam(0, (0, import_common24.Param)("id", import_common24.ParseIntPipe)),
5115
- __decorateParam(1, (0, import_common24.Body)(validated(UpdateIcalFeedBody))),
5116
- __decorateParam(2, (0, import_common24.Req)())
5490
+ __decorateParam(0, (0, import_common25.Param)("id", import_common25.ParseIntPipe)),
5491
+ __decorateParam(1, (0, import_common25.Body)(validated(UpdateIcalFeedBody))),
5492
+ __decorateParam(2, (0, import_common25.Req)())
5117
5493
  ], IcalFeedsController.prototype, "update", 1);
5118
5494
  __decorateClass([
5119
- (0, import_common24.Post)(":id/regenerate"),
5120
- (0, import_common24.HttpCode)(200),
5121
- (0, import_common24.UseGuards)(import_plugins_backend_sdk13.SessionOnlyGuard),
5495
+ (0, import_common25.Post)(":id/regenerate"),
5496
+ (0, import_common25.HttpCode)(200),
5497
+ (0, import_common25.UseGuards)(import_plugins_backend_sdk14.SessionOnlyGuard),
5122
5498
  (0, import_swagger6.ApiForbiddenResponse)({ description: "Session authentication required (API tokens cannot issue feed URLs)" }),
5123
5499
  (0, import_swagger6.ApiOperation)({
5124
5500
  summary: "Issue a new secret URL; the old one answers 404 immediately",
@@ -5127,23 +5503,23 @@ __decorateClass([
5127
5503
  (0, import_swagger6.ApiParam)(FEED_ID),
5128
5504
  (0, import_swagger6.ApiOkResponse)({ type: IcalFeedSecretDto }),
5129
5505
  ApiReservationErrors({ notFound: true }),
5130
- __decorateParam(0, (0, import_common24.Param)("id", import_common24.ParseIntPipe)),
5131
- __decorateParam(1, (0, import_common24.Req)())
5506
+ __decorateParam(0, (0, import_common25.Param)("id", import_common25.ParseIntPipe)),
5507
+ __decorateParam(1, (0, import_common25.Req)())
5132
5508
  ], IcalFeedsController.prototype, "regenerate", 1);
5133
5509
  __decorateClass([
5134
- (0, import_common24.Delete)(":id"),
5135
- (0, import_common24.HttpCode)(204),
5510
+ (0, import_common25.Delete)(":id"),
5511
+ (0, import_common25.HttpCode)(204),
5136
5512
  (0, import_swagger6.ApiOperation)({ summary: "Revoke a feed (its URL answers 404 from now on)" }),
5137
5513
  (0, import_swagger6.ApiParam)(FEED_ID),
5138
5514
  ApiReservationErrors({ notFound: true }),
5139
- __decorateParam(0, (0, import_common24.Param)("id", import_common24.ParseIntPipe)),
5140
- __decorateParam(1, (0, import_common24.Req)())
5515
+ __decorateParam(0, (0, import_common25.Param)("id", import_common25.ParseIntPipe)),
5516
+ __decorateParam(1, (0, import_common25.Req)())
5141
5517
  ], IcalFeedsController.prototype, "revoke", 1);
5142
5518
  IcalFeedsController = __decorateClass([
5143
5519
  (0, import_swagger6.ApiTags)("Reservations"),
5144
- (0, import_plugins_backend_sdk13.Auth)(),
5145
- (0, import_common24.Controller)("reservations/ical/feeds"),
5146
- __decorateParam(0, (0, import_common24.Inject)(IcalService))
5520
+ (0, import_plugins_backend_sdk14.Auth)(),
5521
+ (0, import_common25.Controller)("reservations/ical/feeds"),
5522
+ __decorateParam(0, (0, import_common25.Inject)(IcalService))
5147
5523
  ], IcalFeedsController);
5148
5524
  var ICAL_RATE_LIMIT = { perFeedPerMinute: 60, perIpPerMinute: 240 };
5149
5525
  var IcalPublicController = class {
@@ -5154,40 +5530,40 @@ var IcalPublicController = class {
5154
5530
  __publicField(this, "perIp", new RateLimiter(ICAL_RATE_LIMIT.perIpPerMinute, 6e4));
5155
5531
  }
5156
5532
  async feed(file, request, response) {
5157
- if (!file.endsWith(".ics")) throw new import_common24.NotFoundException();
5533
+ if (!file.endsWith(".ics")) throw new import_common25.NotFoundException();
5158
5534
  const token = file.slice(0, -4);
5159
- if (!FEED_TOKEN_PATTERN.test(token)) throw new import_common24.NotFoundException();
5535
+ if (!FEED_TOKEN_PATTERN.test(token)) throw new import_common25.NotFoundException();
5160
5536
  const now = this.clock().getTime();
5161
5537
  const ip = (request.ip ?? "unknown").slice(0, 64);
5162
5538
  let wait = this.perIp.hit(ip, now);
5163
5539
  if (wait === 0) wait = this.perFeed.hit(`${ip}|${hashToken(token)}`, now);
5164
5540
  if (wait > 0) {
5165
5541
  response.setHeader("Retry-After", String(wait));
5166
- throw new import_common24.HttpException("Too many requests", import_common24.HttpStatus.TOO_MANY_REQUESTS);
5542
+ throw new import_common25.HttpException("Too many requests", import_common25.HttpStatus.TOO_MANY_REQUESTS);
5167
5543
  }
5168
5544
  const calendar = await this.ical.renderForToken(token);
5169
- if (calendar === null) throw new import_common24.NotFoundException();
5545
+ if (calendar === null) throw new import_common25.NotFoundException();
5170
5546
  return calendar;
5171
5547
  }
5172
5548
  };
5173
5549
  __decorateClass([
5174
- (0, import_common24.Get)(":file"),
5175
- (0, import_common24.Header)("Cache-Control", "private, max-age=60"),
5176
- (0, import_common24.Header)("Content-Type", "text/calendar; charset=utf-8"),
5550
+ (0, import_common25.Get)(":file"),
5551
+ (0, import_common25.Header)("Cache-Control", "private, max-age=60"),
5552
+ (0, import_common25.Header)("Content-Type", "text/calendar; charset=utf-8"),
5177
5553
  (0, import_swagger6.ApiOperation)({ summary: "iCalendar feed (the token in the URL is the credential; no session)" }),
5178
5554
  (0, import_swagger6.ApiParam)({ name: "file", type: String, description: "`<token>.ics`" }),
5179
5555
  (0, import_swagger6.ApiProduces)("text/calendar"),
5180
5556
  (0, import_swagger6.ApiOkResponse)({ description: "RFC 5545 calendar", schema: { type: "string" } }),
5181
5557
  ApiReservationErrors({ notFound: true }),
5182
- __decorateParam(0, (0, import_common24.Param)("file")),
5183
- __decorateParam(1, (0, import_common24.Req)()),
5184
- __decorateParam(2, (0, import_common24.Res)({ passthrough: true }))
5558
+ __decorateParam(0, (0, import_common25.Param)("file")),
5559
+ __decorateParam(1, (0, import_common25.Req)()),
5560
+ __decorateParam(2, (0, import_common25.Res)({ passthrough: true }))
5185
5561
  ], IcalPublicController.prototype, "feed", 1);
5186
5562
  IcalPublicController = __decorateClass([
5187
5563
  (0, import_swagger6.ApiTags)("Reservations"),
5188
- (0, import_common24.Controller)("reservations/ical"),
5189
- __decorateParam(0, (0, import_common24.Inject)(IcalService)),
5190
- __decorateParam(1, (0, import_common24.Inject)(RESERVATION_CLOCK))
5564
+ (0, import_common25.Controller)("reservations/ical"),
5565
+ __decorateParam(0, (0, import_common25.Inject)(IcalService)),
5566
+ __decorateParam(1, (0, import_common25.Inject)(RESERVATION_CLOCK))
5191
5567
  ], IcalPublicController);
5192
5568
 
5193
5569
  // backend/notifications/email/template-specs.ts
@@ -5298,15 +5674,22 @@ var TEMPLATE_SPECS = [
5298
5674
  {
5299
5675
  id: "removed",
5300
5676
  label: {
5301
- en: "Booking removed (reservations switched off)",
5302
- de: "Reservierung entfernt (Reservierungen deaktiviert)"
5677
+ en: "Booking removed (reservations switched off or fewer parallel bookings allowed)",
5678
+ de: "Reservierung entfernt (Reservierungen deaktiviert oder weniger parallele Buchungen m\xF6glich)"
5303
5679
  },
5304
5680
  subject: { en: "Booking removed: {resource}", de: "Reservierung entfernt: {resource}" },
5305
5681
  paragraphs: [
5306
5682
  [
5307
5683
  "body",
5308
5684
  "Reservations were switched off for <strong>{resource}</strong>, so your booking ({when}) was cancelled.",
5309
- "Reservierungen wurden f\xFCr <strong>{resource}</strong> deaktiviert, daher wurde deine Reservierung ({when}) storniert."
5685
+ "Reservierungen wurden f\xFCr <strong>{resource}</strong> deaktiviert, daher wurde deine Reservierung ({when}) storniert.",
5686
+ "unless:removal.capacity"
5687
+ ],
5688
+ [
5689
+ "body_capacity",
5690
+ "<strong>{resource}</strong> now allows fewer parallel bookings, so your booking ({when}) no longer fit and was cancelled.",
5691
+ "F\xFCr <strong>{resource}</strong> sind jetzt weniger parallele Buchungen m\xF6glich, daher passte deine Reservierung ({when}) nicht mehr und wurde storniert.",
5692
+ "if:removal.capacity"
5310
5693
  ]
5311
5694
  ]
5312
5695
  },
@@ -5596,7 +5979,7 @@ function toTemplate(spec) {
5596
5979
  var EMAIL_TEMPLATES = TEMPLATE_SPECS.map(toTemplate);
5597
5980
 
5598
5981
  // backend/scheduler/scheduler.service.ts
5599
- var import_common25 = require("@nestjs/common");
5982
+ var import_common26 = require("@nestjs/common");
5600
5983
  var TICK_INTERVAL_MS = 6e4;
5601
5984
  var MINUTE_MS5 = 6e4;
5602
5985
  var HOUR_MS2 = 60 * MINUTE_MS5;
@@ -5604,16 +5987,18 @@ var STILL_NEEDED_LEAD_MS = 48 * HOUR_MS2;
5604
5987
  var REMINDER_LEAD_MS = 24 * HOUR_MS2;
5605
5988
  var OVERRUN_CHECK_WINDOW_MS = 5 * TICK_INTERVAL_MS;
5606
5989
  var NO_SHOW_NOTICE_WINDOW_MS = 5 * TICK_INTERVAL_MS;
5990
+ var CAPACITY_RECONCILE_MS = HOUR_MS2;
5607
5991
  var confirmedAt = (r) => (r.decidedAt ?? r.createdAt).getTime();
5608
5992
  var ReservationScheduler = class {
5609
- constructor(context, store, reservations, settings, notifications, clock) {
5993
+ constructor(context, store, reservations, settings, notifications, clock, directory) {
5610
5994
  __publicField(this, "context", context);
5611
5995
  __publicField(this, "store", store);
5612
5996
  __publicField(this, "reservations", reservations);
5613
5997
  __publicField(this, "settings", settings);
5614
5998
  __publicField(this, "notifications", notifications);
5615
5999
  __publicField(this, "clock", clock);
5616
- __publicField(this, "logger", new import_common25.Logger("ReservationsScheduler"));
6000
+ __publicField(this, "directory", directory);
6001
+ __publicField(this, "logger", new import_common26.Logger("ReservationsScheduler"));
5617
6002
  __publicField(this, "timer", null);
5618
6003
  __publicField(this, "running", false);
5619
6004
  __publicField(this, "inflight", null);
@@ -5621,6 +6006,8 @@ var ReservationScheduler = class {
5621
6006
  __publicField(this, "startsAnnouncedUntil", null);
5622
6007
  /** Bookings that start up to here (now + the reader horizon) were already announced to the readers. */
5623
6008
  __publicField(this, "readerHorizonAnnouncedUntil", null);
6009
+ /** When every resource was last checked against its current session limit (see `reconcileCapacity`). */
6010
+ __publicField(this, "capacityReconciledAt", null);
5624
6011
  }
5625
6012
  async onModuleInit() {
5626
6013
  await this.settings.whenReady().catch(() => void 0);
@@ -5652,6 +6039,7 @@ var ReservationScheduler = class {
5652
6039
  }
5653
6040
  async runSteps(now) {
5654
6041
  const steps = [
6042
+ ["reconcile capacity", (at) => this.reconcileCapacity(at)],
5655
6043
  ["expire pending", (at) => this.expirePending(at)],
5656
6044
  ["no-show", (at) => this.markNoShows(at)],
5657
6045
  ["announce starts", (at) => this.announceStarts(at)],
@@ -5670,6 +6058,25 @@ var ReservationScheduler = class {
5670
6058
  }
5671
6059
  }
5672
6060
  }
6061
+ /**
6062
+ * Safety net for limit changes the plugin missed (it was disabled or the server was down): checks every enabled
6063
+ * resource against its current session limit with the same algorithm as the limit-changed event. Right after
6064
+ * start-up and then once per hour; idempotent.
6065
+ */
6066
+ async reconcileCapacity(now) {
6067
+ if (this.capacityReconciledAt && now.getTime() - this.capacityReconciledAt.getTime() < CAPACITY_RECONCILE_MS)
6068
+ return;
6069
+ this.capacityReconciledAt = now;
6070
+ for (const resourceId of this.settings.getEnabledResourceIds()) {
6071
+ try {
6072
+ await this.reservations.cancelExcessBookings(resourceId, null);
6073
+ } catch (error) {
6074
+ this.logger.error(
6075
+ `capacity reconciliation of resource ${resourceId} failed: ${error instanceof Error ? error.message : String(error)}`
6076
+ );
6077
+ }
6078
+ }
6079
+ }
5673
6080
  isEnabled(r) {
5674
6081
  return this.settings.getCachedSettings(r.resourceId).enabled;
5675
6082
  }
@@ -5776,6 +6183,21 @@ var ReservationScheduler = class {
5776
6183
  if (await this.store.claimFlag(r.id, "reminder24hSentAt", now)) await this.notifications.notifyReminder24h(r);
5777
6184
  });
5778
6185
  }
6186
+ /** Slots held at the booking's start by other people's confirmed bookings (holders in session count as sessions). */
6187
+ async heldAtStart(r, sessions) {
6188
+ const confirmed2 = await this.store.findConfirmedOverlapping(
6189
+ r.resourceId,
6190
+ r.startTime,
6191
+ new Date(r.startTime.getTime() + 1)
6192
+ );
6193
+ const inSession = new Set(sessions.map((session) => session.userId));
6194
+ return heldBookings({ confirmed: confirmed2, starterId: r.userId, inSession, at: r.startTime }).length;
6195
+ }
6196
+ /** Shared machine: the holder is in session, or a slot was free for them at the start besides the lingering ones. */
6197
+ async holderHadSlot(r, sessions, lingering, limit) {
6198
+ if (sessions.some((session) => session.userId === r.userId)) return true;
6199
+ return limit - lingering - await this.heldAtStart(r, sessions) > 0;
6200
+ }
5779
6201
  /** Users with a running session on the resource, other than the holder, shortly before a booking starts. */
5780
6202
  async handover(now) {
5781
6203
  const widest = Math.max(
@@ -5788,10 +6210,11 @@ var ReservationScheduler = class {
5788
6210
  const settings = this.settings.getCachedSettings(r.resourceId);
5789
6211
  const minutes = settings.handoverReminderMinutes;
5790
6212
  if (!settings.enabled || minutes <= 0 || r.startTime.getTime() - now.getTime() > minutes * MINUTE_MS5) return;
5791
- const others = (await this.context.resourceAccess.getActiveSessions(r.resourceId)).filter(
5792
- (session) => session.userId !== r.userId
5793
- );
6213
+ const sessions = await this.context.resourceAccess.getActiveSessions(r.resourceId);
6214
+ const others = sessions.filter((session) => session.userId !== r.userId);
5794
6215
  if (others.length === 0) return;
6216
+ const limit = await this.directory.getSessionLimit(r.resourceId);
6217
+ if (limit > 1 && others.length + await this.heldAtStart(r, sessions) < limit) return;
5795
6218
  if (await this.store.claimFlag(r.id, "handoverSentAt", now)) {
5796
6219
  await this.notifications.notifyHandover(r, [...new Set(others.map((session) => session.userId))]);
5797
6220
  }
@@ -5807,10 +6230,13 @@ var ReservationScheduler = class {
5807
6230
  const recent = await this.store.findUpcomingConfirmed(new Date(now.getTime() - OVERRUN_CHECK_WINDOW_MS), now);
5808
6231
  await this.each(recent, async (r) => {
5809
6232
  if (!this.isEnabled(r) || r.overrunSentAt || r.endTime.getTime() <= now.getTime()) return;
5810
- const lingering = (await this.context.resourceAccess.getActiveSessions(r.resourceId)).filter(
6233
+ const sessions = await this.context.resourceAccess.getActiveSessions(r.resourceId);
6234
+ const lingering = sessions.filter(
5811
6235
  (session) => session.userId !== r.userId && session.startTime.getTime() < r.startTime.getTime()
5812
6236
  );
5813
6237
  if (lingering.length === 0) return;
6238
+ const limit = await this.directory.getSessionLimit(r.resourceId);
6239
+ if (limit > 1 && await this.holderHadSlot(r, sessions, lingering.length, limit)) return;
5814
6240
  if (await this.store.claimFlag(r.id, "overrunSentAt", now)) {
5815
6241
  await this.notifications.notifyOverrun(r, [...new Set(lingering.map((session) => session.userId))]);
5816
6242
  }
@@ -5818,18 +6244,19 @@ var ReservationScheduler = class {
5818
6244
  }
5819
6245
  };
5820
6246
  ReservationScheduler = __decorateClass([
5821
- (0, import_common25.Injectable)(),
5822
- __decorateParam(0, (0, import_common25.Inject)(PLUGIN_CONTEXT)),
5823
- __decorateParam(1, (0, import_common25.Inject)(ReservationStore)),
5824
- __decorateParam(2, (0, import_common25.Inject)(ReservationService)),
5825
- __decorateParam(3, (0, import_common25.Inject)(ResourceSettingsService)),
5826
- __decorateParam(4, (0, import_common25.Inject)(ReservationNotifications)),
5827
- __decorateParam(5, (0, import_common25.Inject)(RESERVATION_CLOCK))
6247
+ (0, import_common26.Injectable)(),
6248
+ __decorateParam(0, (0, import_common26.Inject)(PLUGIN_CONTEXT)),
6249
+ __decorateParam(1, (0, import_common26.Inject)(ReservationStore)),
6250
+ __decorateParam(2, (0, import_common26.Inject)(ReservationService)),
6251
+ __decorateParam(3, (0, import_common26.Inject)(ResourceSettingsService)),
6252
+ __decorateParam(4, (0, import_common26.Inject)(ReservationNotifications)),
6253
+ __decorateParam(5, (0, import_common26.Inject)(RESERVATION_CLOCK)),
6254
+ __decorateParam(6, (0, import_common26.Inject)(DirectoryService))
5828
6255
  ], ReservationScheduler);
5829
6256
 
5830
6257
  // backend/api/reservations.controller.ts
5831
- var import_plugins_backend_sdk14 = require("@attraccess/plugins-backend-sdk");
5832
- var import_common26 = require("@nestjs/common");
6258
+ var import_plugins_backend_sdk15 = require("@attraccess/plugins-backend-sdk");
6259
+ var import_common27 = require("@nestjs/common");
5833
6260
  var import_swagger7 = require("@nestjs/swagger");
5834
6261
  var RESERVATION_ID = { name: "id", type: Number, description: "Reservation id" };
5835
6262
  var STATUS_QUERY = {
@@ -5918,19 +6345,19 @@ var ReservationsController = class {
5918
6345
  }
5919
6346
  };
5920
6347
  __decorateClass([
5921
- (0, import_common26.Get)("resources/:resourceId/pending-decision"),
6348
+ (0, import_common27.Get)("resources/:resourceId/pending-decision"),
5922
6349
  (0, import_swagger7.ApiOperation)({
5923
6350
  summary: 'The caller\u2019s running booking that still awaits a "keep or free the rest?" answer on this resource',
5924
6351
  description: "Set when the holder stopped a session inside their own running booking (kept for 15 minutes in memory). The body is the booking, or the JSON value null when nothing is pending. Cleared by keep, end-early, expiry and the holder\u2019s next session start."
5925
6352
  }),
5926
6353
  (0, import_swagger7.ApiParam)({ name: "resourceId", type: Number }),
5927
6354
  (0, import_swagger7.ApiOkResponse)({ type: ReservationDto, description: "The booking, or null" }),
5928
- __decorateParam(0, (0, import_common26.Param)("resourceId", import_common26.ParseIntPipe)),
5929
- __decorateParam(1, (0, import_common26.Req)()),
5930
- __decorateParam(2, (0, import_common26.Res)())
6355
+ __decorateParam(0, (0, import_common27.Param)("resourceId", import_common27.ParseIntPipe)),
6356
+ __decorateParam(1, (0, import_common27.Req)()),
6357
+ __decorateParam(2, (0, import_common27.Res)())
5931
6358
  ], ReservationsController.prototype, "pendingDecision", 1);
5932
6359
  __decorateClass([
5933
- (0, import_common26.Get)("resources/:resourceId/availability"),
6360
+ (0, import_common27.Get)("resources/:resourceId/availability"),
5934
6361
  (0, import_swagger7.ApiOperation)({
5935
6362
  summary: "Bookings, booking rules and the caller\u2019s booking permission of a resource for a time range",
5936
6363
  description: "Lists pending and confirmed bookings and maintenance that can collide with a booking inside [from, to), i.e. the range widened by the resource\u2019s buffers. Other users\u2019 bookings carry a holder id only for managers of the resource; the holder name is shown to the holder, managers and everyone who may see who uses the resource (core\u2019s activity-visibility rule). Resources the caller cannot see answer 404."
@@ -5940,33 +6367,33 @@ __decorateClass([
5940
6367
  (0, import_swagger7.ApiQuery)({ name: "to", type: String, description: "ISO 8601 end of the range, at most 62 days after from" }),
5941
6368
  (0, import_swagger7.ApiOkResponse)({ type: AvailabilityDto }),
5942
6369
  ApiReservationErrors({ badRequest: true, notFound: true }),
5943
- __decorateParam(0, (0, import_common26.Param)("resourceId", import_common26.ParseIntPipe)),
5944
- __decorateParam(1, (0, import_common26.Query)("from")),
5945
- __decorateParam(2, (0, import_common26.Query)("to")),
5946
- __decorateParam(3, (0, import_common26.Req)())
6370
+ __decorateParam(0, (0, import_common27.Param)("resourceId", import_common27.ParseIntPipe)),
6371
+ __decorateParam(1, (0, import_common27.Query)("from")),
6372
+ __decorateParam(2, (0, import_common27.Query)("to")),
6373
+ __decorateParam(3, (0, import_common27.Req)())
5947
6374
  ], ReservationsController.prototype, "availability", 1);
5948
6375
  __decorateClass([
5949
- (0, import_common26.Get)("mine"),
6376
+ (0, import_common27.Get)("mine"),
5950
6377
  (0, import_swagger7.ApiOperation)({ summary: "List the caller\u2019s own bookings" }),
5951
6378
  (0, import_swagger7.ApiQuery)({ name: "scope", required: false, enum: ["upcoming", "past"], description: "Default: upcoming" }),
5952
6379
  (0, import_swagger7.ApiQuery)(STATUS_QUERY),
5953
6380
  (0, import_swagger7.ApiOkResponse)({ type: [ReservationDto] }),
5954
6381
  ApiReservationErrors({ badRequest: true }),
5955
- __decorateParam(0, (0, import_common26.Req)()),
5956
- __decorateParam(1, (0, import_common26.Query)("scope")),
5957
- __decorateParam(2, (0, import_common26.Query)("status"))
6382
+ __decorateParam(0, (0, import_common27.Req)()),
6383
+ __decorateParam(1, (0, import_common27.Query)("scope")),
6384
+ __decorateParam(2, (0, import_common27.Query)("status"))
5958
6385
  ], ReservationsController.prototype, "listMine", 1);
5959
6386
  __decorateClass([
5960
- (0, import_common26.Get)("manage/access"),
6387
+ (0, import_common27.Get)("manage/access"),
5961
6388
  (0, import_swagger7.ApiOperation)({
5962
6389
  summary: "Whether the caller manages any resource (shows the manager pages)",
5963
6390
  description: "True for resources.update holders and for maintainers/introducers of at least one resource."
5964
6391
  }),
5965
6392
  (0, import_swagger7.ApiOkResponse)({ type: ManagerAccessDto }),
5966
- __decorateParam(0, (0, import_common26.Req)())
6393
+ __decorateParam(0, (0, import_common27.Req)())
5967
6394
  ], ReservationsController.prototype, "managerAccess", 1);
5968
6395
  __decorateClass([
5969
- (0, import_common26.Get)("manage"),
6396
+ (0, import_common27.Get)("manage"),
5970
6397
  (0, import_swagger7.ApiOperation)({
5971
6398
  summary: "List bookings of the resources the caller manages",
5972
6399
  description: "resources.update sees all resources; maintainers and introducers see the resources they manage. 25 per page."
@@ -5978,15 +6405,15 @@ __decorateClass([
5978
6405
  (0, import_swagger7.ApiQuery)({ name: "page", required: false, type: Number, description: "1-based, default 1" }),
5979
6406
  (0, import_swagger7.ApiOkResponse)({ type: ManagedReservationListDto }),
5980
6407
  ApiReservationErrors({ badRequest: true, forbidden: true }),
5981
- __decorateParam(0, (0, import_common26.Req)()),
5982
- __decorateParam(1, (0, import_common26.Query)("resourceId")),
5983
- __decorateParam(2, (0, import_common26.Query)("status")),
5984
- __decorateParam(3, (0, import_common26.Query)("from")),
5985
- __decorateParam(4, (0, import_common26.Query)("to")),
5986
- __decorateParam(5, (0, import_common26.Query)("page"))
6408
+ __decorateParam(0, (0, import_common27.Req)()),
6409
+ __decorateParam(1, (0, import_common27.Query)("resourceId")),
6410
+ __decorateParam(2, (0, import_common27.Query)("status")),
6411
+ __decorateParam(3, (0, import_common27.Query)("from")),
6412
+ __decorateParam(4, (0, import_common27.Query)("to")),
6413
+ __decorateParam(5, (0, import_common27.Query)("page"))
5987
6414
  ], ReservationsController.prototype, "listManaged", 1);
5988
6415
  __decorateClass([
5989
- (0, import_common26.Post)(),
6416
+ (0, import_common27.Post)(),
5990
6417
  (0, import_swagger7.ApiOperation)({
5991
6418
  summary: "Book a resource",
5992
6419
  description: "Creates a confirmed booking, or a pending one when the resource requires approval. Violated rules answer 409 with a typed code."
@@ -5994,81 +6421,81 @@ __decorateClass([
5994
6421
  (0, import_swagger7.ApiBody)({ type: CreateReservationBody }),
5995
6422
  (0, import_swagger7.ApiCreatedResponse)({ type: ReservationDto }),
5996
6423
  ApiReservationErrors({ badRequest: true, notFound: true, conflict: BOOKING_CONFLICT_CODES }),
5997
- __decorateParam(0, (0, import_common26.Body)(validated(CreateReservationBody))),
5998
- __decorateParam(1, (0, import_common26.Req)())
6424
+ __decorateParam(0, (0, import_common27.Body)(validated(CreateReservationBody))),
6425
+ __decorateParam(1, (0, import_common27.Req)())
5999
6426
  ], ReservationsController.prototype, "create", 1);
6000
6427
  __decorateClass([
6001
- (0, import_common26.Get)(":id"),
6428
+ (0, import_common27.Get)(":id"),
6002
6429
  (0, import_swagger7.ApiOperation)({ summary: "Get a booking (holder or manager of its resource)" }),
6003
6430
  (0, import_swagger7.ApiParam)(RESERVATION_ID),
6004
6431
  (0, import_swagger7.ApiOkResponse)({ type: ReservationDto }),
6005
6432
  ApiReservationErrors({ notFound: true }),
6006
- __decorateParam(0, (0, import_common26.Param)("id", import_common26.ParseIntPipe)),
6007
- __decorateParam(1, (0, import_common26.Req)())
6433
+ __decorateParam(0, (0, import_common27.Param)("id", import_common27.ParseIntPipe)),
6434
+ __decorateParam(1, (0, import_common27.Req)())
6008
6435
  ], ReservationsController.prototype, "get", 1);
6009
6436
  __decorateClass([
6010
- (0, import_common26.Post)(":id/cancel"),
6011
- (0, import_common26.HttpCode)(200),
6437
+ (0, import_common27.Post)(":id/cancel"),
6438
+ (0, import_common27.HttpCode)(200),
6012
6439
  (0, import_swagger7.ApiOperation)({ summary: "Cancel a pending or upcoming booking (holder, or a manager with a reason)" }),
6013
6440
  (0, import_swagger7.ApiParam)(RESERVATION_ID),
6014
6441
  (0, import_swagger7.ApiBody)({ type: ReasonBody, required: false }),
6015
6442
  (0, import_swagger7.ApiOkResponse)({ type: ReservationDto }),
6016
6443
  ApiReservationErrors({ notFound: true, conflict: ["NOT_CANCELLABLE", "ALREADY_STARTED"] }),
6017
- __decorateParam(0, (0, import_common26.Param)("id", import_common26.ParseIntPipe)),
6018
- __decorateParam(1, (0, import_common26.Body)(validated(ReasonBody))),
6019
- __decorateParam(2, (0, import_common26.Req)())
6444
+ __decorateParam(0, (0, import_common27.Param)("id", import_common27.ParseIntPipe)),
6445
+ __decorateParam(1, (0, import_common27.Body)(validated(ReasonBody))),
6446
+ __decorateParam(2, (0, import_common27.Req)())
6020
6447
  ], ReservationsController.prototype, "cancel", 1);
6021
6448
  __decorateClass([
6022
- (0, import_common26.Post)(":id/end-early"),
6023
- (0, import_common26.HttpCode)(200),
6449
+ (0, import_common27.Post)(":id/end-early"),
6450
+ (0, import_common27.HttpCode)(200),
6024
6451
  (0, import_swagger7.ApiOperation)({ summary: "End a running booking now and free the rest (holder or manager)" }),
6025
6452
  (0, import_swagger7.ApiParam)(RESERVATION_ID),
6026
6453
  (0, import_swagger7.ApiOkResponse)({ type: ReservationDto }),
6027
6454
  ApiReservationErrors({ notFound: true, conflict: ["NOT_ACTIVE"] }),
6028
- __decorateParam(0, (0, import_common26.Param)("id", import_common26.ParseIntPipe)),
6029
- __decorateParam(1, (0, import_common26.Req)())
6455
+ __decorateParam(0, (0, import_common27.Param)("id", import_common27.ParseIntPipe)),
6456
+ __decorateParam(1, (0, import_common27.Req)())
6030
6457
  ], ReservationsController.prototype, "endEarly", 1);
6031
6458
  __decorateClass([
6032
- (0, import_common26.Post)(":id/keep"),
6033
- (0, import_common26.HttpCode)(200),
6459
+ (0, import_common27.Post)(":id/keep"),
6460
+ (0, import_common27.HttpCode)(200),
6034
6461
  (0, import_swagger7.ApiOperation)({ summary: 'Keep the booking ("still needed" / keep the rest after stopping); holder only' }),
6035
6462
  (0, import_swagger7.ApiParam)(RESERVATION_ID),
6036
6463
  (0, import_swagger7.ApiOkResponse)({ type: ReservationDto }),
6037
6464
  ApiReservationErrors({ notFound: true, conflict: ["ALREADY_FINISHED"] }),
6038
- __decorateParam(0, (0, import_common26.Param)("id", import_common26.ParseIntPipe)),
6039
- __decorateParam(1, (0, import_common26.Req)())
6465
+ __decorateParam(0, (0, import_common27.Param)("id", import_common27.ParseIntPipe)),
6466
+ __decorateParam(1, (0, import_common27.Req)())
6040
6467
  ], ReservationsController.prototype, "keep", 1);
6041
6468
  __decorateClass([
6042
- (0, import_common26.Post)(":id/approve"),
6043
- (0, import_common26.HttpCode)(200),
6469
+ (0, import_common27.Post)(":id/approve"),
6470
+ (0, import_common27.HttpCode)(200),
6044
6471
  (0, import_swagger7.ApiOperation)({ summary: "Approve a pending booking (manager)" }),
6045
6472
  (0, import_swagger7.ApiParam)(RESERVATION_ID),
6046
6473
  (0, import_swagger7.ApiBody)({ type: ReasonBody, required: false }),
6047
6474
  (0, import_swagger7.ApiOkResponse)({ type: ReservationDto }),
6048
6475
  ApiReservationErrors({ notFound: true, forbidden: true, conflict: STATE_CONFLICT_CODES }),
6049
- __decorateParam(0, (0, import_common26.Param)("id", import_common26.ParseIntPipe)),
6050
- __decorateParam(1, (0, import_common26.Body)(validated(ReasonBody))),
6051
- __decorateParam(2, (0, import_common26.Req)())
6476
+ __decorateParam(0, (0, import_common27.Param)("id", import_common27.ParseIntPipe)),
6477
+ __decorateParam(1, (0, import_common27.Body)(validated(ReasonBody))),
6478
+ __decorateParam(2, (0, import_common27.Req)())
6052
6479
  ], ReservationsController.prototype, "approve", 1);
6053
6480
  __decorateClass([
6054
- (0, import_common26.Post)(":id/reject"),
6055
- (0, import_common26.HttpCode)(200),
6481
+ (0, import_common27.Post)(":id/reject"),
6482
+ (0, import_common27.HttpCode)(200),
6056
6483
  (0, import_swagger7.ApiOperation)({ summary: "Reject a pending booking (manager)" }),
6057
6484
  (0, import_swagger7.ApiParam)(RESERVATION_ID),
6058
6485
  (0, import_swagger7.ApiBody)({ type: ReasonBody, required: false }),
6059
6486
  (0, import_swagger7.ApiOkResponse)({ type: ReservationDto }),
6060
6487
  ApiReservationErrors({ notFound: true, forbidden: true, conflict: STATE_CONFLICT_CODES }),
6061
- __decorateParam(0, (0, import_common26.Param)("id", import_common26.ParseIntPipe)),
6062
- __decorateParam(1, (0, import_common26.Body)(validated(ReasonBody))),
6063
- __decorateParam(2, (0, import_common26.Req)())
6488
+ __decorateParam(0, (0, import_common27.Param)("id", import_common27.ParseIntPipe)),
6489
+ __decorateParam(1, (0, import_common27.Body)(validated(ReasonBody))),
6490
+ __decorateParam(2, (0, import_common27.Req)())
6064
6491
  ], ReservationsController.prototype, "reject", 1);
6065
6492
  ReservationsController = __decorateClass([
6066
6493
  (0, import_swagger7.ApiTags)("Reservations"),
6067
- (0, import_plugins_backend_sdk14.Auth)(),
6068
- (0, import_common26.Controller)("reservations"),
6069
- __decorateParam(0, (0, import_common26.Inject)(ReservationService)),
6070
- __decorateParam(1, (0, import_common26.Inject)(ReservationQueryService)),
6071
- __decorateParam(2, (0, import_common26.Inject)(PendingDecisionService))
6494
+ (0, import_plugins_backend_sdk15.Auth)(),
6495
+ (0, import_common27.Controller)("reservations"),
6496
+ __decorateParam(0, (0, import_common27.Inject)(ReservationService)),
6497
+ __decorateParam(1, (0, import_common27.Inject)(ReservationQueryService)),
6498
+ __decorateParam(2, (0, import_common27.Inject)(PendingDecisionService))
6072
6499
  ], ReservationsController);
6073
6500
 
6074
6501
  // backend/plugin.ts
@@ -6083,6 +6510,7 @@ var plugin = {
6083
6510
  preStartHook,
6084
6511
  sessionEndHook,
6085
6512
  startBlockedQuery,
6513
+ startCapacityHook,
6086
6514
  readerUi: readerUiProvider,
6087
6515
  register(context) {
6088
6516
  return {
@@ -6107,6 +6535,7 @@ var plugin = {
6107
6535
  PendingDecisionStore,
6108
6536
  PendingDecisionService,
6109
6537
  PreStartService,
6538
+ StartCapacityService,
6110
6539
  SessionEndService,
6111
6540
  ReaderUiService,
6112
6541
  HookServicePublisher,