Aller au contenu

Planning des chambres d’hôtel

La douche de la 104 fuit. Relogez le prochain client, bloquez la chambre pour le plombier et repérez les nuits déjà complètes.

  • Hébergement
  • Casa Noma
  • Colonnes de ligne
  • Lignes de synthèse
  • Minimap
  • Arborescence de ressources
  • Annuler et rétablir
  • Menu contextuel
  • Glisser et redimensionner
  • Thèmes
  • Démo avec données fictives

Mission

0 étapes faites sur 3

Lundi 26 octobre, midi : le client qui quitte la 104 signale une fuite dans la douche. Le plombier a besoin de trois nuits.

  1. Sortez la réservation Varga (arrivée mardi) de la chambre 104. — À faire

    Glissez-la d’une ligne vers le haut, en 103, ou en 201 comme surclassement. Les chambres occupées la refusent.

  2. Étirez le blocage hors service de la 104 sur trois nuits. — À faire

    Glissez son bord droit jusqu’à jeudi. Les travaux finissent à 14:00, prêts pour l’arrivée suivante.

  3. Trouvez les nuits que le salon du design rend complètes. — À faire

    Elles sont au-delà de ces deux semaines : cliquez sur Complet au-dessus du planning, sur les barres rouges de la bande d’occupation ou sur la flèche de la semaine suivante.

Environ 30 secondes. Les étapes se cochent au fur et à mesure.

Clavier : placez le focus sur la grille, puis flèches, Entrée et Alt+flèches pour déplacer.

Casa Noma
Double standard101Rue102Rue103Cour104CourDouble supérieure201Balcon202Balcon203CourJunior suite301Terrasse302TerrasseSuite jardin401JardinHaddad4 nuitsNovak2 nuitsFerreira3 nuitsSato5 nuitsO’Neill5 nuitsJensen2 nuitsDubois3 nuitsTanaka3 nuitsSilva2 nuitsKaya2 nuitsOkafor2 nuitsBianchi4 nuitsPetrov4 nuitsVarga3 nuitsLaine3 nuitsMoreno3 nuitsHors service1 nuitKeller3 nuitsNakamura3 nuitsFischer2 nuitsOrtega4 nuitsCosta4 nuitsKim2 nuitsHaas3 nuitsIvanova3 nuitsDuarte2 nuitsQuinn2 nuitsAlbers2 nuitsSousa4 nuitsVidal3 nuitsHart4 nuitsEriksen3 nuitsNavarro3 nuitsSaleh3 nuitsRinaldi3 nuitsPark2 nuitsMercer3 nuitsAndersen4 nuitsGarcía4 nuitsBecker4 nuits↘ 1 ↗ 3↘ 2 ↗ 3↘ 2 ↗ 2↘ 1 ↗ 2↘ 3 ↗ 2↘ 3 ↗ 2↘ 1 ↗ 2↘ 1 ↗ 4↘ 1 ↗ 1↘ 1 ↗ 1↘ 2 ↗ 1↘ 1 ↗ 1↘ 1 ↗ 3↘ 0 ↗ 1↘ 4 ↗ 1↘ 6 ↗ 0Arrivées · départspar date26 oct.2 nov.9 nov.lun. 26mar. 27mer. 28jeu. 29ven. 30sam. 31dim. 1lun. 2mar. 3mer. 4jeu. 5ven. 6sam. 7dim. 8lun. 9mar. 10mer. 11jeu. 12

Aperçu de la première imageEn direct : le vrai moteur Pro, dans votre navigateurEnviron 30 secondes. Les étapes se cochent au fur et à mesure. Clavier : placez le focus sur la grille, puis flèches, Entrée et Alt+flèches pour déplacer.

La situation.

Casa Noma est un hôtel de charme fictif de dix chambres : quatre doubles standard, trois supérieures, deux junior suites et une suite jardin. La réception planifie sur un planning à une ligne par chambre et une colonne par nuit. Les clients arrivent à 14:00 et partent à 11:00 : un jour de recouche, un séjour se termine et le suivant commence dans la même colonne sans chevauchement.

Les chambres tombent en panne. Quand l’une d’elles sort de la vente, la réception doit reloger les clients prévus sans les déclasser, caler les travaux entre un départ et une arrivée et surveiller les nuits déjà pleines. Des barres seules ne distinguent pas une nuit calme d’une nuit complète ; ce planning compte les chambres libres par type et par nuit.

Ce que vous allez faire

Vous déplacerez une réservation hors d’une chambre en panne (un surclassement est accepté, un déclassement refusé), prolongerez les travaux à trois nuits aux vraies heures de l’hôtel et trouverez les nuits complètes grâce à la bande d’occupation.

Où s’arrête la bibliothèque et où commence votre application.

SuperScheduler fournit

  • Arbre de ressources des types et des chambres avec rowHeaderColumns (chambre, vue, étages) ; la puce d’étage est une zone de l’en-tête de ligne (action: 'None') qui garde son clic.
  • Une ligne figée en haut (frozen: 'top', cellsDisabled) que onBeforeCellRender remplit avec les arrivées et départs de chaque date ; les lignes de type montrent les chambres libres par nuit.
  • Des séjours à l’heure exacte sur une échelle de nuits (useEventBoxes: 'Never') déplacés par nuits entières avec eventMoveByCell, avec des zones aux deux extrémités : l’initiale du client à l’arrivée, une porte au départ.
  • Des en-têtes de nuit écrits par onBeforeTimeHeaderRender (ce soir porte sa propre étiquette), un séparateur à l’instant de la réception et des cellules désactivées pour la suite jardin fermée.
  • La prévention des chevauchements, le redimensionnement guidé dans onEventResizing, les déplacements au clavier et un historique qui enregistre aussi les étages (history.push).
  • La minicarte alimentée par votre propre série, des niveaux de zoom, scrollTo et le sujet viewport de super-scheduler/hooks (useSchedulerState, subscribeScheduler) derrière le navigateur de dates.
  • Des cartes au survol et la carte de glisser (super-scheduler/react-render), la mise en évidence des conflits et un menu contextuel à l’habillage du produit (theme du Menu).

Le code de cet exemple décide

  • Surclassement oui, déclassement non, capacité de la chambre et aucune arrivée dans le passé : les refus dans onEventMoving et onEventResizing.
  • Les heures de l’hôtel au redimensionnement : les séjours finissent à 11:00, les réparations à 14:00, jamais moins d’une nuit.
  • Le statut de réception de chaque séjour (parti, en séjour, arrive aujourd’hui, confirmé, option), les chiffres du jour et les arrivées et départs par date.
  • Les étages (sale, propre, contrôlée) et si un client attendu aujourd’hui peut déjà avoir la chambre.
  • L’occupation par nuit, les chambres libres par type et par nuit, les nuits complètes et les actions : chambre équivalente, surclassement, une nuit de plus, confirmer une option.

Le code de cette démo.

Ce sont les fichiers exécutés par cette page, pas une copie simplifiée. Ils compilent avec les exports publics de SuperScheduler Pro.

tsx.zip

L’intégration : échelle de nuits aux heures exactes, rowHeaderColumns avec la zone d’étage, la feuille du jour figée, les cellules de disponibilité, les jours fermés, les en-têtes de nuit, la carte au survol, le verdict de glisser en nuits, le menu contextuel et les callbacks où les règles de la réception refusent ou ajustent un changement.

/**
 * Casa Noma tape chart: rooms grouped by room type over four weeks, one column per night.
 *
 * Library: resource tree with row-header columns (a housekeeping chip that owns its click as a
 * row-header area), a frozen day-sheet row, exact-time stays (check-in 14:00, check-out 11:00) on
 * a day scale with areas at their ends, night headers written by onBeforeTimeHeaderRender, a
 * separator at the front desk's moment, drag/resize with conflict highlighting, disabled cells,
 * zoom levels, keyboard and history, the event hover card and the drag card
 * (super-scheduler/react-render), and a context menu. Application: upgrades and downgrades,
 * capacity, hotel times for resized edges, the out-of-order room, housekeeping, the free rooms per
 * type and night, and what the cards say in nights. Those rules live in ./rules and run below;
 * ./chart-paint writes the markup.
 */
import { useCallback, useMemo, useState, type RefObject } from 'react'
import { SuperScheduler } from 'super-scheduler'
import type {
  SchedulerBeforeTimeHeaderRenderArgs,
  SchedulerEventsChangeArgs,
} from 'super-scheduler'
import type { SchedulerHistory } from 'super-scheduler/history'
import { SuperSchedulerComponent, type SchedulerRenderProps } from 'super-scheduler/react-render'
import { format, plural } from '../../i18n/format'
import { DAY, civil, parseCivil } from '../../scheduler/civil'
import { createHeaderHook } from '../../scheduler/live-headers'
import { toneClass } from '../../scheduler/tones'
import { createEventMenu, type MenuEntry } from '../kit/context-menu'
import { formatDay } from '../kit/format'
import { useEventHover, type HoverCardModel } from '../kit/hover-card'
import { KEYS } from '../kit/keys'
import { useDropRefusal } from '../kit/use-drop-refusal'
import { skinClass, skinMenuTheme } from '../registry'
import type { DemoCommon } from '../types'
import {
  CHART_GEOMETRY,
  STATUS_TONES,
  SUMMARY_ID,
  isItemEvent,
  isRoomTypeId,
  readItemFields,
  toItem,
  toResources,
  type ItemEvent,
} from './adapter'
import {
  freeHtml,
  housekeepingArea,
  isTonight,
  movementsHtml,
  nightHeader,
  repairHtml,
  roomHtml,
  sheetColumns,
  stateWord,
  stayEnds,
  stayHtml,
  typeHtml,
  viewHtml,
} from './chart-paint'
import {
  BUSINESS_NOW,
  CHART,
  CLOSURES,
  REPAIR_NIGHTS,
  ROOMS,
  type Housekeeping,
  type RoomItem,
} from './model'
import {
  equivalentRoom,
  extendByNight,
  freeByType,
  isClosed,
  isUpgrade,
  moveRefusal,
  movementsByDate,
  nextHousekeeping,
  nightsOf,
  resizeTo,
  roomById,
  statusOf,
  upgradeRoom,
  type Extension,
  type MoveRefusal,
} from './rules'
import { createNightCard, itemCard } from './stay-card'
import type { CasaNomaText, ZoomId } from './text'

/** What the chart asks the demo to do (context menu, keyboard). */
export type ItemAction =
  'details' | 'equivalent' | 'upgrade' | 'extend' | 'confirm' | 'housekeeping'

/** The menu's label for one more night: the new departure, or why it cannot be. */
export function extendLabel(extension: Extension, text: CasaNomaText, tag: string): string {
  if (extension.ok) return format(text.actions.extend, { date: formatDay(extension.end, tag) })
  if (extension.reason === 'taken')
    return format(text.actions.extendTaken, {
      name: extension.by.kind === 'stay' ? extension.by.guest : text.outOfOrder,
    })
  return text.actions.extendClosed
}

export interface CasaNomaSchedulerProps {
  readonly events: ItemEvent[]
  /** The same events as business objects, for the availability cells. */
  readonly items: readonly RoomItem[]
  /** Dates of the sold-out nights (the night pips mark them). */
  readonly soldOut: ReadonlySet<string>
  readonly text: CasaNomaText
  readonly common: DemoCommon
  /** BCP 47 tag for labels, and the scheduler locale id. */
  readonly tag: string
  readonly schedulerLocale: string
  /** Level on mount. Later changes go through control.zoom so the view animates from where it is. */
  readonly initialZoom: ZoomId
  /** The item shown in the side sheet: it gets the selection ring. */
  readonly selected: string | null
  readonly history: SchedulerHistory
  readonly controlRef: RefObject<SuperScheduler.Scheduler | null>
  readonly onEventsChange: (args: SchedulerEventsChangeArgs) => void
  readonly onSelect: (id: string) => void
  readonly onMoved: (id: string) => void
  readonly onResized: (id: string, edge: 'start' | 'end') => void
  readonly onRefused: (id: string, message: string) => void
  readonly onAction: (action: ItemAction, id: string) => void
  readonly onZoomLevel: (level: ZoomId) => void
  /** Housekeeping state of every room, and the click on a room's chip. */
  readonly housekeeping: Readonly<Record<string, Housekeeping>>
  readonly onHousekeeping: (room: string) => void
  /** Narrow stages drop the view column. */
  readonly narrow: boolean
}

/** Weeks over nights. The night format tells the level-of-detail planner how narrow its label is. */
const TIME_HEADERS: SuperScheduler.TimeHeaderData[] = [
  { groupBy: 'Week', height: CHART_GEOMETRY.header.week },
  { groupBy: 'Day', height: CHART_GEOMETRY.header.night, format: 'd' },
]

/** One night per column: two weeks to work in, the whole month to look ahead. */
const ZOOM_LEVELS: SuperScheduler.ZoomLevel[] = [
  {
    id: 'fortnight',
    properties: { scale: 'Day', cellWidth: CHART_GEOMETRY.cellWidth, timeHeaders: TIME_HEADERS },
  },
  { id: 'month', properties: { scale: 'Day', cellWidth: 40, timeHeaders: TIME_HEADERS } },
]

const ZOOM_IDS: readonly ZoomId[] = ['fortnight', 'month']
const CHART_START = parseCivil(CHART.start)
const NOW = parseCivil(BUSINESS_NOW)
const ROOM_COUNT = new Map<SuperScheduler.ResourceId, number>(
  ROOMS.map((room) => [room.type, ROOMS.filter((other) => other.type === room.type).length]),
)

function readItem(data: SuperScheduler.EventData): RoomItem | null {
  return isItemEvent(data) ? toItem(data) : null
}

export function CasaNomaScheduler(props: CasaNomaSchedulerProps) {
  const { events, items, soldOut, text, common, tag, schedulerLocale, initialZoom } = props
  const { selected, history, controlRef, housekeeping, narrow } = props
  const { onEventsChange, onSelect, onMoved, onResized, onRefused, onAction, onZoomLevel } = props
  const { onHousekeeping } = props

  const resources = useMemo(() => toResources(text), [text])

  // Day labels shorten below a cell width. A zoom animation lands after the headers of its last
  // frames were drawn, so each settled level gets a fresh hook: a new hook makes the control label
  // its headers again. Today's column is marked on top of the shared labels.
  const [level, setLevel] = useState<ZoomId>(initialZoom)
  const timeHeaders = useMemo(() => {
    const labels = createHeaderHook(tag)
    return {
      level,
      hook: (args: SchedulerBeforeTimeHeaderRenderArgs) => {
        const header = args.header
        if (header.level !== 1) {
          labels(args)
          header.cssClass = 'cn-th-week'
          return
        }
        const start = header.start.getTime()
        const full = soldOut.has(civil(start).slice(0, 10))
        header.html = nightHeader(start, tag, text, level === 'month', full)
        header.cssClass = isTonight(start) ? 'cn-th-night cn-today' : 'cn-th-night'
        if (full) header.toolTip = text.card.full
      },
    }
  }, [level, tag, text, soldOut]).hook
  const free = useMemo(() => freeByType(items, CLOSURES, CHART.start, CHART.days), [items])
  const movements = useMemo(() => movementsByDate(items, CHART.start, CHART.days), [items])

  // A change refused while dragging (category, capacity, the past, overlap) is said on release.
  const refusal = useDropRefusal(onRefused)

  // Hover card: the nights as front-desk pips, guests, booking, total and the rule that applies.
  const card = useCallback(
    (event: SuperScheduler.Event): HoverCardModel | null => {
      const item = items.find((candidate) => candidate.id === String(event.id()))
      return item === undefined
        ? null
        : itemCard(item, items, soldOut, text, common, tag, housekeeping)
    },
    [items, soldOut, text, common, tag, housekeeping],
  )
  const { eventHover, closeHover, suppressHover } = useEventHover(card)

  // Drag verdict counted in nights: the room, arrival → departure, the nights as pips.
  const dragCard = useMemo(
    () => createNightCard({ items, soldOut, text, common, tag }),
    [items, soldOut, text, common, tag],
  )

  // Context menu: rebuilt when the chart changes, so its labels name the real room and night.
  const contextMenu = useMemo(
    () =>
      createEventMenu({
        theme: skinMenuTheme('hotel-rooms'),
        title: (event) => format(common.kit.menuTitle, { name: event.text() }),
        onOpenChange: (open) => suppressHover(open),
        entries: (event) => {
          const id = String(event.id())
          const item = items.find((candidate) => candidate.id === id)
          if (item === undefined) return []
          const entries: MenuEntry[] = [
            {
              label: common.kit.openDetails,
              icon: 'details',
              keys: KEYS.details,
              run: () => onAction('details', id),
            },
          ]
          const extension = extendByNight(item, items, CLOSURES, BUSINESS_NOW)
          if (item.kind === 'repair') {
            entries.push({
              label: extendLabel(extension, text, tag),
              icon: 'after',
              primary: nightsOf(item.start, item.end) < REPAIR_NIGHTS,
              disabled: !extension.ok,
              run: () => onAction('extend', id),
            })
            return entries
          }
          const status = statusOf(item, BUSINESS_NOW)
          if (status === 'departed') return entries
          // An option is what the front desk acts on first: confirm it.
          if (status === 'option')
            entries.push({
              label: text.actions.confirm,
              icon: 'confirm',
              primary: true,
              run: () => onAction('confirm', id),
            })
          const same = equivalentRoom(item, items, CLOSURES, BUSINESS_NOW)
          const better = upgradeRoom(item, items, CLOSURES, BUSINESS_NOW)
          const betterType = better === null ? undefined : roomById(better)?.type
          entries.push(
            {
              label:
                same === null
                  ? format(text.actions.noEquivalent, { type: text.roomTypes[item.booked] })
                  : format(text.actions.equivalent, { room: same }),
              icon: 'handover',
              disabled: same === null,
              run: () => onAction('equivalent', id),
            },
            {
              label:
                better === null || betterType === undefined
                  ? text.actions.noUpgrade
                  : format(text.actions.upgrade, {
                      room: better,
                      type: text.roomTypes[betterType],
                    }),
              icon: 'layers',
              disabled: better === null,
              run: () => onAction('upgrade', id),
            },
            'separator',
            {
              label: extendLabel(extension, text, tag),
              icon: 'after',
              disabled: !extension.ok,
              run: () => onAction('extend', id),
            },
            {
              label: housekeepingLabel(item.room, housekeeping, text, tag),
              icon: 'confirm',
              run: () => onAction('housekeeping', id),
            },
          )
          return entries
        },
      }),
    [items, common, text, tag, housekeeping, onAction, suppressHover],
  )

  const config = useMemo<SchedulerRenderProps>(() => {
    const refusalText = (reason: MoveRefusal | null) =>
      reason === null ? null : text.rules[reason]
    const overlapText = (conflicts: readonly SuperScheduler.Event[]) => {
      const first = conflicts[0]
      return first === undefined ? null : format(common.kit.overlaps, { name: first.text() })
    }

    return {
      locale: schedulerLocale,
      startDate: CHART.start,
      days: CHART.days,
      // Hotel weeks run Monday to Sunday in every locale (as the static preview draws them).
      weekStarts: 1,
      zoomLevels: ZOOM_LEVELS,
      zoom: initialZoom,
      zoomPosition: 'left',
      // Exact hotel times on a night scale: a stay is drawn from 14:00 to 11:00 and keeps those
      // times when it is dragged by whole nights. Resized edges are snapped by the hotel rules.
      useEventBoxes: 'Never',
      eventMoveByCell: true,
      snapToGridEventResizing: false,
      height: '100%',
      treeEnabled: true,
      treePreventParentUsage: true,
      rowHeaderColumns: narrow
        ? [
            { text: text.columns.room, width: CHART_GEOMETRY.narrowColumns.room },
            { text: text.columns.housekeeping, width: CHART_GEOMETRY.narrowColumns.housekeeping },
          ]
        : [
            { text: text.columns.room, width: CHART_GEOMETRY.roomColumn },
            { text: text.columns.view, width: CHART_GEOMETRY.viewColumn },
            { text: text.columns.housekeeping, width: CHART_GEOMETRY.housekeepingColumn },
          ],
      rowHeaderWidth: narrow
        ? CHART_GEOMETRY.narrowColumns.room + CHART_GEOMETRY.narrowColumns.housekeeping
        : CHART_GEOMETRY.rowHeaderWidth,
      rowHeaderWidthAutoFit: false,
      treeIndent: 12,
      eventHeight: CHART_GEOMETRY.eventHeight,
      rowMarginTop: CHART_GEOMETRY.rowMarginTop,
      rowMarginBottom: CHART_GEOMETRY.rowMarginBottom,
      allowEventOverlap: false,
      conflictHighlight: true,
      // The Casa Noma skin (tokens.css, theme.css) keys on the product's skin class.
      cssClass: skinClass('hotel-rooms'),
      durationBarVisible: false,
      crosshairType: 'Header',
      // The front desk's moment (Monday noon): a fixed instant of the scenario, not the visitor's clock.
      separators: [{ location: BUSINESS_NOW, layer: 'BelowEvents', width: 2, cssClass: 'cn-now' }],
      showToolTip: false,
      keyboardEnabled: true,
      keyboardTarget: 'component',
      keyboardMode: 'Full',
      history,
      controlRef,
      onEventsChange,

      // The day sheet, room types (merged across the columns) and rooms: number, view, housekeeping.
      onBeforeRowHeaderRender: (args) => {
        const row = args.row
        const id = row.id
        if (id === SUMMARY_ID) {
          row.cssClass = 'cn-row cn-row--sheet'
          const keys = sheetColumns(text, narrow)
          row.columns.forEach((column, index) => {
            column.html = keys[index] ?? ''
          })
          return
        }
        const room = roomById(String(id))
        if (room === null) {
          row.cssClass = 'ss-rh--group cn-row cn-row--type'
          row.html = typeHtml(String(row.name), ROOM_COUNT.get(id) ?? 0)
          const first = row.columns[0]
          if (first !== undefined) first.html = row.html
          return
        }
        row.cssClass = 'cn-row cn-row--room'
        const state = housekeeping[room.id] ?? 'dirty'
        const [first, second, third] = row.columns
        if (first !== undefined) first.html = roomHtml(room, text)
        const chip = narrow ? second : third
        if (!narrow && second !== undefined) second.html = viewHtml(room, text)
        if (chip !== undefined) {
          chip.html = ''
          chip.areas = [
            housekeepingArea(room.id, state, nextHousekeeping(state), text, tag, onHousekeeping),
          ]
        }
      },

      // The day sheet counts arrivals and departures; group rows show the rooms still free each
      // night; closed days disable a room's cells; tonight's column is warm.
      onBeforeCellRender: (args) => {
        const { cell } = args
        const day = cell.start.getTime()
        const index = Math.round((day - CHART_START) / DAY)
        const tonight = isTonight(day) ? ' cn-today' : ''
        if (cell.resource === SUMMARY_ID) {
          const counts = movements[index]
          // Narrow nights (Month) stack the two marks.
          const stacked = (args.control.cellWidth ?? CHART_GEOMETRY.cellWidth) < 64
          cell.properties.html = counts === undefined ? '' : movementsHtml(counts, text, stacked)
          cell.properties.cssClass = `cn-sheet-cell${tonight}`
          return
        }
        if (isRoomTypeId(cell.resource)) {
          const count = free[cell.resource][index]
          if (count === undefined) return
          cell.properties.html = freeHtml(count)
          cell.properties.cssClass = `cn-avail${count === 0 ? ' cn-full' : ''}${tonight}`
          return
        }
        if (isClosed(String(cell.resource), day, CLOSURES)) cell.properties.disabled = true
        else if (tonight !== '') cell.properties.cssClass = 'cn-today'
      },

      onBeforeEventRender: (args) => {
        const fields = readItemFields(args.data)
        if (fields === null) return
        const start = args.data.start.value
        const end = args.data.end.value
        const isSelected = String(args.data.id) === selected
        if (fields.kind === 'repair') {
          args.data.html = repairHtml({ start, end }, text, tag)
          args.data.cssClass = `cn-item cn-repair ${toneClass('blocked')}${isSelected ? ' cn-selected' : ''}`
          return
        }
        const status = statusOf(
          { start, end, ...(fields.option === true ? { option: true } : {}) },
          BUSINESS_NOW,
        )
        const room = args.data.resource === undefined ? '' : String(args.data.resource)
        const stay = {
          guest: fields.guest,
          guests: fields.guests,
          start,
          end,
          status,
          upgrade: isUpgrade({ room, booked: fields.booked }),
          housekeeping: status === 'due-in' ? (housekeeping[room] ?? null) : null,
        }
        args.data.html = stayHtml(stay, text, tag)
        args.data.areas = stayEnds(stay, text, tag)
        const classes = ['cn-item', 'cn-stay', `cn-${status}`, toneClass(STATUS_TONES[status])]
        if (stay.upgrade) classes.push('cn-upgraded')
        if (isSelected) classes.push('cn-selected')
        args.data.cssClass = classes.join(' ')
        args.data.ariaLabel = `${fields.guest}, ${text.statuses[status]}, ${plural(text.nights, nightsOf(start, end), tag)}`
      },

      // Categories, capacity and the past are front-desk rules; overlap and closed days are the library's.
      onEventMoving: (args) => {
        const id = String(args.e.id())
        const item = readItem(args.e.data)
        if (item === null) return
        const message = refusalText(
          moveRefusal(item, String(args.resource), BUSINESS_NOW, args.start.getTime()),
        )
        if (message !== null) {
          args.allowed = false
          args.message = message
          refusal.track(id, message)
          return
        }
        refusal.track(id, overlapText(args.conflicts))
      },

      // Final check before the commit (also covers keyboard moves).
      onEventMove: (args) => {
        const item = readItem(args.e.data)
        if (item === null) return
        const message = refusalText(
          moveRefusal(item, String(args.newResource), BUSINESS_NOW, args.newStart.getTime()),
        )
        if (message !== null) {
          args.preventDefault()
          refusal.clear()
          onRefused(String(args.e.id()), message)
        }
      },

      // Edges snap to hotel times: stays end at 11:00 and start at 14:00, repairs the other way round.
      onEventResizing: (args) => {
        const item = readItem(args.e.data)
        if (item === null) return
        const edge = args.what
        const next = resizeTo(item, edge, (edge === 'end' ? args.end : args.start).getTime())
        args.start = new SuperScheduler.Date(next.start)
        args.end = new SuperScheduler.Date(next.end)
        const message = edge === 'start' ? startRefusal(item, next.start, text) : null
        if (message !== null) {
          args.allowed = false
          args.message = message
          refusal.track(String(args.e.id()), message)
          return
        }
        refusal.track(String(args.e.id()), overlapText(args.conflicts))
      },

      onEventResize: (args) => {
        const item = readItem(args.e.data)
        if (item === null) return
        const next = resizeTo(
          item,
          args.what,
          (args.what === 'end' ? args.newEnd : args.newStart).getTime(),
        )
        const message = args.what === 'start' ? startRefusal(item, next.start, text) : null
        if (message !== null) {
          args.preventDefault()
          refusal.clear()
          onRefused(String(args.e.id()), message)
          return
        }
        args.newStart = new SuperScheduler.Date(next.start)
        args.newEnd = new SuperScheduler.Date(next.end)
      },

      onEventMoved: (args) => {
        refusal.clear()
        onMoved(String(args.e.id()))
      },
      onEventResized: (args) => {
        refusal.clear()
        onResized(String(args.e.id()), args.what)
      },
      // A click (or Enter) docks the stay into the side sheet; the hover card steps aside.
      onEventClick: (args) => {
        closeHover()
        onSelect(String(args.e.id()))
      },

      onZoom: (args) => {
        if (args.phase !== 'end') return
        const next = ZOOM_IDS[args.level]
        if (next === undefined) return
        setLevel(next)
        onZoomLevel(next)
      },
    }
  }, [
    history,
    controlRef,
    free,
    movements,
    housekeeping,
    narrow,
    selected,
    common,
    refusal,
    closeHover,
    onEventsChange,
    onMoved,
    onRefused,
    onResized,
    onSelect,
    onZoomLevel,
    onHousekeeping,
    schedulerLocale,
    tag,
    text,
    initialZoom,
  ])

  return (
    <SuperSchedulerComponent
      {...config}
      onBeforeTimeHeaderRender={timeHeaders}
      resources={resources}
      events={events}
      eventHover={eventHover}
      dragCard={dragCard}
      contextMenu={contextMenu}
    />
  )
}

/** The menu's housekeeping action for a stay's room: its next state. */
export function housekeepingLabel(
  room: string,
  states: Readonly<Record<string, Housekeeping>>,
  text: CasaNomaText,
  tag: string,
): string {
  const next = nextHousekeeping(states[room] ?? 'dirty')
  return format(text.housekeeping.mark, {
    room,
    next: stateWord(text.housekeeping.states[next], tag),
  })
}

/** A guest in the house keeps the check-in; a guest still to come cannot check in in the past. */
function startRefusal(item: RoomItem, start: number, text: CasaNomaText): string | null {
  if (item.kind !== 'stay') return null
  const status = statusOf(item, BUSINESS_NOW)
  if (status === 'in-house') return text.rules.checkedIn
  return start < NOW ? text.rules.past : null
}

L’archive contient les fichiers de cet exemple et un README. Elle n’inclut ni SuperScheduler Pro ni aucune clé de téléchargement.