checkSlot function

SlotCheck checkSlot(
  1. SlotRules rules,
  2. Object start, {
  3. Instant? from,
  4. Instant? to,
})

Whether start is one of the slots findSlots would offer — what a server asks before saving a booking, with the same rules as the page. start is an Instant, a ZonedDateTime or their ISO text (as a request body has it; a time written below the millisecond is misaligned, slots never are). Without from/to, the range is the slot itself.

Implementation

SlotCheck checkSlot(SlotRules rules, Object start, {Instant? from, Instant? to}) {
  try {
    final problems = <Problem>[];
    final read = readMomentExact(start);
    if (read == null) {
      return SlotRefused(SlotRefusal.invalidQuery, [
        Problem(ProblemCode.invalidSlotQuery, Severity.error, 'start', jsText(start)),
      ]);
    }
    final p = _plan(rules, from, to, read.at, problems);
    if (p == null || problems.any((x) => x.isError)) return SlotRefused(SlotRefusal.invalidQuery, problems);
    final t = read.at.epochMilliseconds;
    if (t < p.from || t + p.dur > p.to) return const SlotRefused(SlotRefusal.outOfRange);
    _Opening? opening;
    for (final o in p.open) {
      if (o.s <= t && t + p.dur <= o.e) {
        opening = o;
        break;
      }
    }
    if (opening == null) return const SlotRefused(SlotRefusal.closed);
    // Off the grid — or between milliseconds, which slots never are.
    if (t < opening.a || (t - opening.a) % p.step != 0 || !read.exact) {
      return const SlotRefused(SlotRefusal.misaligned);
    }
    final slot = _slotAt(p, t);
    final reason = _refusal(p, t, slot.start, [0]);
    return reason != null ? SlotRefused(reason) : SlotAccepted(slot);
  } catch (e) {
    return SlotRefused(SlotRefusal.invalidQuery, [
      Problem(ProblemCode.invalidSlotQuery, Severity.error, 'query', '$e'),
    ]);
  }
}