|
Line 0
Link Here
|
|
|
1 |
import dayjs from "../../../../utils/dayjs.mjs"; |
| 2 |
import { |
| 3 |
isoArrayToDates, |
| 4 |
toDayjs, |
| 5 |
addDays, |
| 6 |
subDays, |
| 7 |
formatYMD, |
| 8 |
} from "./date-utils.mjs"; |
| 9 |
import { managerLogger as logger } from "./logger.mjs"; |
| 10 |
import { createConstraintStrategy } from "./strategies.mjs"; |
| 11 |
import { |
| 12 |
// eslint-disable-next-line no-unused-vars |
| 13 |
IntervalTree, |
| 14 |
buildIntervalTree, |
| 15 |
} from "./algorithms/interval-tree.mjs"; |
| 16 |
import { |
| 17 |
SweepLineProcessor, |
| 18 |
processCalendarView, |
| 19 |
} from "./algorithms/sweep-line-processor.mjs"; |
| 20 |
import { idsEqual, includesId } from "./id-utils.mjs"; |
| 21 |
import { |
| 22 |
CONSTRAINT_MODE_END_DATE_ONLY, |
| 23 |
CONSTRAINT_MODE_NORMAL, |
| 24 |
SELECTION_ANY_AVAILABLE, |
| 25 |
SELECTION_SPECIFIC_ITEM, |
| 26 |
} from "./constants.mjs"; |
| 27 |
|
| 28 |
const $__ = globalThis.$__ || (str => str); |
| 29 |
|
| 30 |
/** |
| 31 |
* Calculates the maximum end date for a booking period based on start date and maximum period. |
| 32 |
* Follows Koha circulation behavior where maxPeriod represents days to ADD to start date. |
| 33 |
* |
| 34 |
* @param {Date|string|import('dayjs').Dayjs} startDate - The start date |
| 35 |
* @param {number} maxPeriod - Maximum period in days (from circulation rules) |
| 36 |
* @returns {import('dayjs').Dayjs} The maximum end date |
| 37 |
*/ |
| 38 |
export function calculateMaxEndDate(startDate, maxPeriod) { |
| 39 |
if (!maxPeriod || maxPeriod <= 0) { |
| 40 |
throw new Error('maxPeriod must be a positive number'); |
| 41 |
} |
| 42 |
|
| 43 |
const start = dayjs(startDate).startOf("day"); |
| 44 |
// Add maxPeriod days (matches CalcDateDue behavior) |
| 45 |
return start.add(maxPeriod, "day"); |
| 46 |
} |
| 47 |
|
| 48 |
/** |
| 49 |
* Validates if an end date exceeds the maximum allowed period |
| 50 |
* |
| 51 |
* @param {Date|string|import('dayjs').Dayjs} startDate - The start date |
| 52 |
* @param {Date|string|import('dayjs').Dayjs} endDate - The proposed end date |
| 53 |
* @param {number} maxPeriod - Maximum period in days |
| 54 |
* @returns {boolean} True if end date is valid (within limits) |
| 55 |
*/ |
| 56 |
export function validateBookingPeriod(startDate, endDate, maxPeriod) { |
| 57 |
if (!maxPeriod || maxPeriod <= 0) { |
| 58 |
return true; // No limit |
| 59 |
} |
| 60 |
|
| 61 |
const maxEndDate = calculateMaxEndDate(startDate, maxPeriod); |
| 62 |
const proposedEnd = dayjs(endDate).startOf("day"); |
| 63 |
|
| 64 |
return !proposedEnd.isAfter(maxEndDate, "day"); |
| 65 |
} |
| 66 |
|
| 67 |
/** |
| 68 |
* Build unavailableByDate map from IntervalTree for backward compatibility |
| 69 |
* @param {IntervalTree} intervalTree - The interval tree containing all bookings/checkouts |
| 70 |
* @param {import('dayjs').Dayjs} today - Today's date for range calculation |
| 71 |
* @param {Array} allItemIds - Array of all item IDs |
| 72 |
* @param {number|string|null} editBookingId - The booking_id being edited (exclude from results) |
| 73 |
* @param {Object} options - Additional options for optimization |
| 74 |
* @param {Object} [options] - Additional options for optimization |
| 75 |
* @param {Date} [options.visibleStartDate] - Start of visible calendar range |
| 76 |
* @param {Date} [options.visibleEndDate] - End of visible calendar range |
| 77 |
* @param {boolean} [options.onDemand] - Whether to build map on-demand for visible dates only |
| 78 |
* @returns {import('../../types/bookings').UnavailableByDate} |
| 79 |
*/ |
| 80 |
function buildUnavailableByDateMap( |
| 81 |
intervalTree, |
| 82 |
today, |
| 83 |
allItemIds, |
| 84 |
editBookingId, |
| 85 |
options = {} |
| 86 |
) { |
| 87 |
/** @type {import('../../types/bookings').UnavailableByDate} */ |
| 88 |
const unavailableByDate = {}; |
| 89 |
|
| 90 |
if (!intervalTree || intervalTree.size === 0) { |
| 91 |
return unavailableByDate; |
| 92 |
} |
| 93 |
|
| 94 |
let startDate, endDate; |
| 95 |
if ( |
| 96 |
options.onDemand && |
| 97 |
options.visibleStartDate && |
| 98 |
options.visibleEndDate |
| 99 |
) { |
| 100 |
startDate = subDays(options.visibleStartDate, 7); |
| 101 |
endDate = addDays(options.visibleEndDate, 7); |
| 102 |
logger.debug("Building unavailableByDate map for visible range only", { |
| 103 |
start: formatYMD(startDate), |
| 104 |
end: formatYMD(endDate), |
| 105 |
days: endDate.diff(startDate, "day") + 1, |
| 106 |
}); |
| 107 |
} else { |
| 108 |
startDate = subDays(today, 7); |
| 109 |
endDate = addDays(today, 90); |
| 110 |
logger.debug("Building unavailableByDate map with limited range", { |
| 111 |
start: formatYMD(startDate), |
| 112 |
end: formatYMD(endDate), |
| 113 |
days: endDate.diff(startDate, "day") + 1, |
| 114 |
}); |
| 115 |
} |
| 116 |
|
| 117 |
const rangeIntervals = intervalTree.queryRange( |
| 118 |
startDate.toDate(), |
| 119 |
endDate.toDate() |
| 120 |
); |
| 121 |
|
| 122 |
// Exclude the booking being edited |
| 123 |
const relevantIntervals = editBookingId |
| 124 |
? rangeIntervals.filter( |
| 125 |
interval => interval.metadata?.booking_id != editBookingId |
| 126 |
) |
| 127 |
: rangeIntervals; |
| 128 |
|
| 129 |
const processor = new SweepLineProcessor(); |
| 130 |
const sweptMap = processor.processIntervals( |
| 131 |
relevantIntervals, |
| 132 |
startDate.toDate(), |
| 133 |
endDate.toDate(), |
| 134 |
allItemIds |
| 135 |
); |
| 136 |
|
| 137 |
// Ensure the map contains all dates in the requested range, even if empty |
| 138 |
const filledMap = sweptMap && typeof sweptMap === "object" ? sweptMap : {}; |
| 139 |
for ( |
| 140 |
let d = startDate.clone(); |
| 141 |
d.isSameOrBefore(endDate, "day"); |
| 142 |
d = d.add(1, "day") |
| 143 |
) { |
| 144 |
const key = d.format("YYYY-MM-DD"); |
| 145 |
if (!filledMap[key]) filledMap[key] = {}; |
| 146 |
} |
| 147 |
|
| 148 |
// Normalize reasons for legacy API expectations: convert 'core' -> 'booking' |
| 149 |
Object.keys(filledMap).forEach(dateKey => { |
| 150 |
const byItem = filledMap[dateKey]; |
| 151 |
Object.keys(byItem).forEach(itemId => { |
| 152 |
const original = byItem[itemId]; |
| 153 |
if (original && original instanceof Set) { |
| 154 |
const mapped = new Set(); |
| 155 |
original.forEach(reason => { |
| 156 |
mapped.add(reason === "core" ? "booking" : reason); |
| 157 |
}); |
| 158 |
byItem[itemId] = mapped; |
| 159 |
} |
| 160 |
}); |
| 161 |
}); |
| 162 |
|
| 163 |
return filledMap; |
| 164 |
} |
| 165 |
|
| 166 |
// Small helper to standardize constraint function return shape |
| 167 |
function buildConstraintResult(filtered, total) { |
| 168 |
const filteredOutCount = total - filtered.length; |
| 169 |
return { |
| 170 |
filtered, |
| 171 |
filteredOutCount, |
| 172 |
total, |
| 173 |
constraintApplied: filtered.length !== total, |
| 174 |
}; |
| 175 |
} |
| 176 |
|
| 177 |
/** |
| 178 |
* Optimized lead period validation using range queries instead of individual point queries |
| 179 |
* @param {import("dayjs").Dayjs} startDate - Potential start date to validate |
| 180 |
* @param {number} leadDays - Number of lead period days to check |
| 181 |
* @param {Object} intervalTree - Interval tree for conflict checking |
| 182 |
* @param {string|null} selectedItem - Selected item ID or null |
| 183 |
* @param {number|null} editBookingId - Booking ID being edited |
| 184 |
* @param {Array} allItemIds - All available item IDs |
| 185 |
* @returns {boolean} True if start date should be blocked due to lead period conflicts |
| 186 |
*/ |
| 187 |
function validateLeadPeriodOptimized( |
| 188 |
startDate, |
| 189 |
leadDays, |
| 190 |
intervalTree, |
| 191 |
selectedItem, |
| 192 |
editBookingId, |
| 193 |
allItemIds |
| 194 |
) { |
| 195 |
if (leadDays <= 0) return false; |
| 196 |
|
| 197 |
const leadStart = startDate.subtract(leadDays, "day"); |
| 198 |
const leadEnd = startDate.subtract(1, "day"); |
| 199 |
|
| 200 |
logger.debug( |
| 201 |
`Optimized lead period check: ${formatYMD(leadStart)} to ${formatYMD( |
| 202 |
leadEnd |
| 203 |
)}` |
| 204 |
); |
| 205 |
|
| 206 |
// Use range query to get all conflicts in the lead period at once |
| 207 |
const leadConflicts = intervalTree.queryRange( |
| 208 |
leadStart.valueOf(), |
| 209 |
leadEnd.valueOf(), |
| 210 |
selectedItem != null ? String(selectedItem) : null |
| 211 |
); |
| 212 |
|
| 213 |
const relevantLeadConflicts = leadConflicts.filter( |
| 214 |
c => !editBookingId || c.metadata.booking_id != editBookingId |
| 215 |
); |
| 216 |
|
| 217 |
if (selectedItem) { |
| 218 |
// For specific item, any conflict in lead period blocks the start date |
| 219 |
return relevantLeadConflicts.length > 0; |
| 220 |
} else { |
| 221 |
// For "any item" mode, need to check if there are conflicts for ALL items |
| 222 |
// on ANY day in the lead period |
| 223 |
if (relevantLeadConflicts.length === 0) return false; |
| 224 |
|
| 225 |
const unavailableItemIds = new Set( |
| 226 |
relevantLeadConflicts.map(c => c.itemId) |
| 227 |
); |
| 228 |
const allUnavailable = |
| 229 |
allItemIds.length > 0 && |
| 230 |
allItemIds.every(id => unavailableItemIds.has(String(id))); |
| 231 |
|
| 232 |
logger.debug(`Lead period multi-item check (optimized):`, { |
| 233 |
leadPeriod: `${formatYMD(leadStart)} to ${formatYMD(leadEnd)}`, |
| 234 |
totalItems: allItemIds.length, |
| 235 |
conflictsFound: relevantLeadConflicts.length, |
| 236 |
unavailableItems: Array.from(unavailableItemIds), |
| 237 |
allUnavailable: allUnavailable, |
| 238 |
decision: allUnavailable ? "BLOCK" : "ALLOW", |
| 239 |
}); |
| 240 |
|
| 241 |
return allUnavailable; |
| 242 |
} |
| 243 |
} |
| 244 |
|
| 245 |
/** |
| 246 |
* Optimized trail period validation using range queries instead of individual point queries |
| 247 |
* @param {import("dayjs").Dayjs} endDate - Potential end date to validate |
| 248 |
* @param {number} trailDays - Number of trail period days to check |
| 249 |
* @param {Object} intervalTree - Interval tree for conflict checking |
| 250 |
* @param {string|null} selectedItem - Selected item ID or null |
| 251 |
* @param {number|null} editBookingId - Booking ID being edited |
| 252 |
* @param {Array} allItemIds - All available item IDs |
| 253 |
* @returns {boolean} True if end date should be blocked due to trail period conflicts |
| 254 |
*/ |
| 255 |
function validateTrailPeriodOptimized( |
| 256 |
endDate, |
| 257 |
trailDays, |
| 258 |
intervalTree, |
| 259 |
selectedItem, |
| 260 |
editBookingId, |
| 261 |
allItemIds |
| 262 |
) { |
| 263 |
if (trailDays <= 0) return false; |
| 264 |
|
| 265 |
const trailStart = endDate.add(1, "day"); |
| 266 |
const trailEnd = endDate.add(trailDays, "day"); |
| 267 |
|
| 268 |
logger.debug( |
| 269 |
`Optimized trail period check: ${formatYMD(trailStart)} to ${formatYMD( |
| 270 |
trailEnd |
| 271 |
)}` |
| 272 |
); |
| 273 |
|
| 274 |
// Use range query to get all conflicts in the trail period at once |
| 275 |
const trailConflicts = intervalTree.queryRange( |
| 276 |
trailStart.valueOf(), |
| 277 |
trailEnd.valueOf(), |
| 278 |
selectedItem != null ? String(selectedItem) : null |
| 279 |
); |
| 280 |
|
| 281 |
const relevantTrailConflicts = trailConflicts.filter( |
| 282 |
c => !editBookingId || c.metadata.booking_id != editBookingId |
| 283 |
); |
| 284 |
|
| 285 |
if (selectedItem) { |
| 286 |
// For specific item, any conflict in trail period blocks the end date |
| 287 |
return relevantTrailConflicts.length > 0; |
| 288 |
} else { |
| 289 |
// For "any item" mode, need to check if there are conflicts for ALL items |
| 290 |
// on ANY day in the trail period |
| 291 |
if (relevantTrailConflicts.length === 0) return false; |
| 292 |
|
| 293 |
const unavailableItemIds = new Set( |
| 294 |
relevantTrailConflicts.map(c => c.itemId) |
| 295 |
); |
| 296 |
const allUnavailable = |
| 297 |
allItemIds.length > 0 && |
| 298 |
allItemIds.every(id => unavailableItemIds.has(String(id))); |
| 299 |
|
| 300 |
logger.debug(`Trail period multi-item check (optimized):`, { |
| 301 |
trailPeriod: `${trailStart.format( |
| 302 |
"YYYY-MM-DD" |
| 303 |
)} to ${trailEnd.format("YYYY-MM-DD")}`, |
| 304 |
totalItems: allItemIds.length, |
| 305 |
conflictsFound: relevantTrailConflicts.length, |
| 306 |
unavailableItems: Array.from(unavailableItemIds), |
| 307 |
allUnavailable: allUnavailable, |
| 308 |
decision: allUnavailable ? "BLOCK" : "ALLOW", |
| 309 |
}); |
| 310 |
|
| 311 |
return allUnavailable; |
| 312 |
} |
| 313 |
} |
| 314 |
|
| 315 |
/** |
| 316 |
* Extracts and validates configuration from circulation rules |
| 317 |
* @param {Object} circulationRules - Raw circulation rules object |
| 318 |
* @param {Date|import('dayjs').Dayjs} todayArg - Optional today value for deterministic tests |
| 319 |
* @returns {Object} Normalized configuration object |
| 320 |
*/ |
| 321 |
function extractBookingConfiguration(circulationRules, todayArg) { |
| 322 |
const today = todayArg |
| 323 |
? toDayjs(todayArg).startOf("day") |
| 324 |
: dayjs().startOf("day"); |
| 325 |
const leadDays = Number(circulationRules?.bookings_lead_period) || 0; |
| 326 |
const trailDays = Number(circulationRules?.bookings_trail_period) || 0; |
| 327 |
// In unconstrained mode, do not enforce a default max period |
| 328 |
const maxPeriod = |
| 329 |
Number(circulationRules?.maxPeriod) || |
| 330 |
Number(circulationRules?.issuelength) || |
| 331 |
0; |
| 332 |
const isEndDateOnly = |
| 333 |
circulationRules?.booking_constraint_mode === |
| 334 |
CONSTRAINT_MODE_END_DATE_ONLY; |
| 335 |
const calculatedDueDate = circulationRules?.calculated_due_date |
| 336 |
? dayjs(circulationRules.calculated_due_date).startOf("day") |
| 337 |
: null; |
| 338 |
const calculatedPeriodDays = Number( |
| 339 |
circulationRules?.calculated_period_days |
| 340 |
) |
| 341 |
? Number(circulationRules.calculated_period_days) |
| 342 |
: null; |
| 343 |
|
| 344 |
logger.debug("Booking configuration extracted:", { |
| 345 |
today: today.format("YYYY-MM-DD"), |
| 346 |
leadDays, |
| 347 |
trailDays, |
| 348 |
maxPeriod, |
| 349 |
isEndDateOnly, |
| 350 |
rawRules: circulationRules, |
| 351 |
}); |
| 352 |
|
| 353 |
return { |
| 354 |
today, |
| 355 |
leadDays, |
| 356 |
trailDays, |
| 357 |
maxPeriod, |
| 358 |
isEndDateOnly, |
| 359 |
calculatedDueDate, |
| 360 |
calculatedPeriodDays, |
| 361 |
}; |
| 362 |
} |
| 363 |
|
| 364 |
/** |
| 365 |
* Creates the main disable function that determines if a date should be disabled |
| 366 |
* @param {Object} intervalTree - Interval tree for conflict checking |
| 367 |
* @param {Object} config - Configuration object from extractBookingConfiguration |
| 368 |
* @param {Array<import('../../types/bookings').BookableItem>} bookableItems - Array of bookable items |
| 369 |
* @param {string|null} selectedItem - Selected item ID or null |
| 370 |
* @param {number|null} editBookingId - Booking ID being edited |
| 371 |
* @param {Array<Date>} selectedDates - Currently selected dates |
| 372 |
* @returns {(date: Date) => boolean} Disable function for Flatpickr |
| 373 |
*/ |
| 374 |
function createDisableFunction( |
| 375 |
intervalTree, |
| 376 |
config, |
| 377 |
bookableItems, |
| 378 |
selectedItem, |
| 379 |
editBookingId, |
| 380 |
selectedDates |
| 381 |
) { |
| 382 |
const { |
| 383 |
today, |
| 384 |
leadDays, |
| 385 |
trailDays, |
| 386 |
maxPeriod, |
| 387 |
isEndDateOnly, |
| 388 |
calculatedDueDate, |
| 389 |
} = config; |
| 390 |
const allItemIds = bookableItems.map(i => String(i.item_id)); |
| 391 |
const strategy = createConstraintStrategy( |
| 392 |
isEndDateOnly ? CONSTRAINT_MODE_END_DATE_ONLY : CONSTRAINT_MODE_NORMAL |
| 393 |
); |
| 394 |
|
| 395 |
return date => { |
| 396 |
const dayjs_date = dayjs(date).startOf("day"); |
| 397 |
|
| 398 |
// Guard clause: Basic past date validation |
| 399 |
if (dayjs_date.isBefore(today, "day")) return true; |
| 400 |
|
| 401 |
// Guard clause: No bookable items available |
| 402 |
if (!bookableItems || bookableItems.length === 0) { |
| 403 |
logger.debug( |
| 404 |
`Date ${dayjs_date.format( |
| 405 |
"YYYY-MM-DD" |
| 406 |
)} disabled - no bookable items available` |
| 407 |
); |
| 408 |
return true; |
| 409 |
} |
| 410 |
|
| 411 |
// Mode-specific start date validation |
| 412 |
if ( |
| 413 |
strategy.validateStartDateSelection( |
| 414 |
dayjs_date, |
| 415 |
{ |
| 416 |
today, |
| 417 |
leadDays, |
| 418 |
trailDays, |
| 419 |
maxPeriod, |
| 420 |
isEndDateOnly, |
| 421 |
calculatedDueDate, |
| 422 |
}, |
| 423 |
intervalTree, |
| 424 |
selectedItem, |
| 425 |
editBookingId, |
| 426 |
allItemIds, |
| 427 |
selectedDates |
| 428 |
) |
| 429 |
) { |
| 430 |
return true; |
| 431 |
} |
| 432 |
|
| 433 |
// Mode-specific intermediate date handling |
| 434 |
const intermediateResult = strategy.handleIntermediateDate( |
| 435 |
dayjs_date, |
| 436 |
selectedDates, |
| 437 |
{ |
| 438 |
today, |
| 439 |
leadDays, |
| 440 |
trailDays, |
| 441 |
maxPeriod, |
| 442 |
isEndDateOnly, |
| 443 |
calculatedDueDate, |
| 444 |
} |
| 445 |
); |
| 446 |
if (intermediateResult === true) { |
| 447 |
return true; |
| 448 |
} |
| 449 |
|
| 450 |
// Guard clause: Standard point-in-time availability check |
| 451 |
const pointConflicts = intervalTree.query( |
| 452 |
dayjs_date.valueOf(), |
| 453 |
selectedItem != null ? String(selectedItem) : null |
| 454 |
); |
| 455 |
const relevantPointConflicts = pointConflicts.filter( |
| 456 |
interval => |
| 457 |
!editBookingId || interval.metadata.booking_id != editBookingId |
| 458 |
); |
| 459 |
|
| 460 |
// Guard clause: Specific item conflicts |
| 461 |
if (selectedItem && relevantPointConflicts.length > 0) { |
| 462 |
logger.debug( |
| 463 |
`Date ${dayjs_date.format( |
| 464 |
"YYYY-MM-DD" |
| 465 |
)} blocked for item ${selectedItem}:`, |
| 466 |
relevantPointConflicts.map(c => c.type) |
| 467 |
); |
| 468 |
return true; |
| 469 |
} |
| 470 |
|
| 471 |
// Guard clause: All items unavailable (any item mode) |
| 472 |
if (!selectedItem) { |
| 473 |
const unavailableItemIds = new Set( |
| 474 |
relevantPointConflicts.map(c => c.itemId) |
| 475 |
); |
| 476 |
const allUnavailable = |
| 477 |
allItemIds.length > 0 && |
| 478 |
allItemIds.every(id => unavailableItemIds.has(String(id))); |
| 479 |
|
| 480 |
logger.debug( |
| 481 |
`Multi-item availability check for ${dayjs_date.format( |
| 482 |
"YYYY-MM-DD" |
| 483 |
)}:`, |
| 484 |
{ |
| 485 |
totalItems: allItemIds.length, |
| 486 |
allItemIds: allItemIds, |
| 487 |
conflictsFound: relevantPointConflicts.length, |
| 488 |
unavailableItemIds: Array.from(unavailableItemIds), |
| 489 |
allUnavailable: allUnavailable, |
| 490 |
decision: allUnavailable ? "BLOCK" : "ALLOW", |
| 491 |
} |
| 492 |
); |
| 493 |
|
| 494 |
if (allUnavailable) { |
| 495 |
logger.debug( |
| 496 |
`Date ${dayjs_date.format( |
| 497 |
"YYYY-MM-DD" |
| 498 |
)} blocked - all items unavailable` |
| 499 |
); |
| 500 |
return true; |
| 501 |
} |
| 502 |
} |
| 503 |
|
| 504 |
// Lead/trail period validation using optimized queries |
| 505 |
if (!selectedDates || selectedDates.length === 0) { |
| 506 |
// Potential start date - check lead period |
| 507 |
if (leadDays > 0) { |
| 508 |
logger.debug( |
| 509 |
`Checking lead period for ${dayjs_date.format( |
| 510 |
"YYYY-MM-DD" |
| 511 |
)} (${leadDays} days)` |
| 512 |
); |
| 513 |
} |
| 514 |
|
| 515 |
// Optimized lead period validation using range queries |
| 516 |
if ( |
| 517 |
validateLeadPeriodOptimized( |
| 518 |
dayjs_date, |
| 519 |
leadDays, |
| 520 |
intervalTree, |
| 521 |
selectedItem, |
| 522 |
editBookingId, |
| 523 |
allItemIds |
| 524 |
) |
| 525 |
) { |
| 526 |
logger.debug( |
| 527 |
`Start date ${dayjs_date.format( |
| 528 |
"YYYY-MM-DD" |
| 529 |
)} blocked - lead period conflict (optimized check)` |
| 530 |
); |
| 531 |
return true; |
| 532 |
} |
| 533 |
} else if ( |
| 534 |
selectedDates[0] && |
| 535 |
(!selectedDates[1] || |
| 536 |
dayjs(selectedDates[1]).isSame(dayjs_date, "day")) |
| 537 |
) { |
| 538 |
// Potential end date - check trail period |
| 539 |
const start = dayjs(selectedDates[0]).startOf("day"); |
| 540 |
|
| 541 |
// Basic end date validations |
| 542 |
if (dayjs_date.isBefore(start, "day")) return true; |
| 543 |
// Respect backend-calculated due date in end_date_only mode only if it's not before start |
| 544 |
if ( |
| 545 |
isEndDateOnly && |
| 546 |
config.calculatedDueDate && |
| 547 |
!config.calculatedDueDate.isBefore(start, "day") |
| 548 |
) { |
| 549 |
const targetEnd = config.calculatedDueDate; |
| 550 |
if (dayjs_date.isAfter(targetEnd, "day")) return true; |
| 551 |
} else if (maxPeriod > 0) { |
| 552 |
const maxEndDate = calculateMaxEndDate(start, maxPeriod); |
| 553 |
if (dayjs_date.isAfter(maxEndDate, "day")) |
| 554 |
return true; |
| 555 |
} |
| 556 |
|
| 557 |
// Optimized trail period validation using range queries |
| 558 |
if ( |
| 559 |
validateTrailPeriodOptimized( |
| 560 |
dayjs_date, |
| 561 |
trailDays, |
| 562 |
intervalTree, |
| 563 |
selectedItem, |
| 564 |
editBookingId, |
| 565 |
allItemIds |
| 566 |
) |
| 567 |
) { |
| 568 |
logger.debug( |
| 569 |
`End date ${dayjs_date.format( |
| 570 |
"YYYY-MM-DD" |
| 571 |
)} blocked - trail period conflict (optimized check)` |
| 572 |
); |
| 573 |
return true; |
| 574 |
} |
| 575 |
} |
| 576 |
|
| 577 |
return false; |
| 578 |
}; |
| 579 |
} |
| 580 |
|
| 581 |
/** |
| 582 |
* Logs comprehensive debug information for OPAC booking selection debugging |
| 583 |
* @param {Array} bookings - Array of booking objects |
| 584 |
* @param {Array} checkouts - Array of checkout objects |
| 585 |
* @param {Array} bookableItems - Array of bookable items |
| 586 |
* @param {string|null} selectedItem - Selected item ID |
| 587 |
* @param {Object} circulationRules - Circulation rules |
| 588 |
*/ |
| 589 |
function logBookingDebugInfo( |
| 590 |
bookings, |
| 591 |
checkouts, |
| 592 |
bookableItems, |
| 593 |
selectedItem, |
| 594 |
circulationRules |
| 595 |
) { |
| 596 |
logger.debug("OPAC Selection Debug:", { |
| 597 |
selectedItem: selectedItem, |
| 598 |
selectedItemType: |
| 599 |
selectedItem === null |
| 600 |
? SELECTION_ANY_AVAILABLE |
| 601 |
: SELECTION_SPECIFIC_ITEM, |
| 602 |
bookableItems: bookableItems.map(item => ({ |
| 603 |
item_id: item.item_id, |
| 604 |
title: item.title, |
| 605 |
item_type_id: item.item_type_id, |
| 606 |
holding_library: item.holding_library, |
| 607 |
available_pickup_locations: item.available_pickup_locations, |
| 608 |
})), |
| 609 |
circulationRules: { |
| 610 |
booking_constraint_mode: circulationRules?.booking_constraint_mode, |
| 611 |
maxPeriod: circulationRules?.maxPeriod, |
| 612 |
bookings_lead_period: circulationRules?.bookings_lead_period, |
| 613 |
bookings_trail_period: circulationRules?.bookings_trail_period, |
| 614 |
}, |
| 615 |
bookings: bookings.map(b => ({ |
| 616 |
booking_id: b.booking_id, |
| 617 |
item_id: b.item_id, |
| 618 |
start_date: b.start_date, |
| 619 |
end_date: b.end_date, |
| 620 |
patron_id: b.patron_id, |
| 621 |
})), |
| 622 |
checkouts: checkouts.map(c => ({ |
| 623 |
item_id: c.item_id, |
| 624 |
checkout_date: c.checkout_date, |
| 625 |
due_date: c.due_date, |
| 626 |
patron_id: c.patron_id, |
| 627 |
})), |
| 628 |
}); |
| 629 |
} |
| 630 |
|
| 631 |
/** |
| 632 |
* Pure function for Flatpickr's `disable` option. |
| 633 |
* Disables dates that overlap with existing bookings or checkouts for the selected item, or when not enough items are available. |
| 634 |
* Also handles end_date_only constraint mode by disabling intermediate dates. |
| 635 |
* |
| 636 |
* @param {Array} bookings - Array of booking objects ({ booking_id, item_id, start_date, end_date }) |
| 637 |
* @param {Array} checkouts - Array of checkout objects ({ item_id, due_date, ... }) |
| 638 |
* @param {Array} bookableItems - Array of all bookable item objects (must have item_id) |
| 639 |
* @param {number|string|null} selectedItem - The currently selected item (item_id or null for 'any') |
| 640 |
* @param {number|string|null} editBookingId - The booking_id being edited (if any) |
| 641 |
* @param {Array} selectedDates - Array of currently selected dates in Flatpickr (can be empty, or [start], or [start, end]) |
| 642 |
* @param {Object} circulationRules - Circulation rules object (leadDays, trailDays, maxPeriod, booking_constraint_mode, etc.) |
| 643 |
* @param {Date|import('dayjs').Dayjs} todayArg - Optional today value for deterministic tests |
| 644 |
* @param {Object} options - Additional options for optimization |
| 645 |
* @returns {import('../../types/bookings').AvailabilityResult} |
| 646 |
*/ |
| 647 |
export function calculateDisabledDates( |
| 648 |
bookings, |
| 649 |
checkouts, |
| 650 |
bookableItems, |
| 651 |
selectedItem, |
| 652 |
editBookingId, |
| 653 |
selectedDates = [], |
| 654 |
circulationRules = {}, |
| 655 |
todayArg = undefined, |
| 656 |
options = {} |
| 657 |
) { |
| 658 |
logger.time("calculateDisabledDates"); |
| 659 |
const normalizedSelectedItem = |
| 660 |
selectedItem != null ? String(selectedItem) : null; |
| 661 |
logger.debug("calculateDisabledDates called", { |
| 662 |
bookingsCount: bookings.length, |
| 663 |
checkoutsCount: checkouts.length, |
| 664 |
itemsCount: bookableItems.length, |
| 665 |
normalizedSelectedItem, |
| 666 |
editBookingId, |
| 667 |
selectedDates, |
| 668 |
circulationRules, |
| 669 |
}); |
| 670 |
|
| 671 |
// Log comprehensive debug information for OPAC debugging |
| 672 |
logBookingDebugInfo( |
| 673 |
bookings, |
| 674 |
checkouts, |
| 675 |
bookableItems, |
| 676 |
normalizedSelectedItem, |
| 677 |
circulationRules |
| 678 |
); |
| 679 |
|
| 680 |
// Build IntervalTree with all booking/checkout data |
| 681 |
const intervalTree = buildIntervalTree( |
| 682 |
bookings, |
| 683 |
checkouts, |
| 684 |
circulationRules |
| 685 |
); |
| 686 |
|
| 687 |
// Extract and validate configuration |
| 688 |
const config = extractBookingConfiguration(circulationRules, todayArg); |
| 689 |
const allItemIds = bookableItems.map(i => String(i.item_id)); |
| 690 |
|
| 691 |
// Create optimized disable function using extracted helper |
| 692 |
const normalizedEditBookingId = |
| 693 |
editBookingId != null ? Number(editBookingId) : null; |
| 694 |
const disableFunction = createDisableFunction( |
| 695 |
intervalTree, |
| 696 |
config, |
| 697 |
bookableItems, |
| 698 |
normalizedSelectedItem, |
| 699 |
normalizedEditBookingId, |
| 700 |
selectedDates |
| 701 |
); |
| 702 |
|
| 703 |
// Build unavailableByDate for backward compatibility and markers |
| 704 |
// Pass options for performance optimization |
| 705 |
|
| 706 |
const unavailableByDate = buildUnavailableByDateMap( |
| 707 |
intervalTree, |
| 708 |
config.today, |
| 709 |
allItemIds, |
| 710 |
normalizedEditBookingId, |
| 711 |
options |
| 712 |
); |
| 713 |
|
| 714 |
logger.debug("IntervalTree-based availability calculated", { |
| 715 |
treeSize: intervalTree.size, |
| 716 |
}); |
| 717 |
logger.timeEnd("calculateDisabledDates"); |
| 718 |
|
| 719 |
return { |
| 720 |
disable: disableFunction, |
| 721 |
unavailableByDate: unavailableByDate, |
| 722 |
}; |
| 723 |
} |
| 724 |
|
| 725 |
/** |
| 726 |
* Derive effective circulation rules with constraint options applied. |
| 727 |
* - Applies maxPeriod only for constraining modes |
| 728 |
* - Strips caps for unconstrained mode |
| 729 |
* @param {import('../../types/bookings').CirculationRule} [baseRules={}] |
| 730 |
* @param {import('../../types/bookings').ConstraintOptions} [constraintOptions={}] |
| 731 |
* @returns {import('../../types/bookings').CirculationRule} |
| 732 |
*/ |
| 733 |
export function deriveEffectiveRules(baseRules = {}, constraintOptions = {}) { |
| 734 |
const effectiveRules = { ...baseRules }; |
| 735 |
const mode = constraintOptions.dateRangeConstraint; |
| 736 |
if (mode === "issuelength" || mode === "issuelength_with_renewals") { |
| 737 |
if (constraintOptions.maxBookingPeriod) { |
| 738 |
effectiveRules.maxPeriod = constraintOptions.maxBookingPeriod; |
| 739 |
} |
| 740 |
} else { |
| 741 |
if ("maxPeriod" in effectiveRules) delete effectiveRules.maxPeriod; |
| 742 |
if ("issuelength" in effectiveRules) delete effectiveRules.issuelength; |
| 743 |
} |
| 744 |
return effectiveRules; |
| 745 |
} |
| 746 |
|
| 747 |
/** |
| 748 |
* Convenience: take full circulationRules array and constraint options, |
| 749 |
* return effective rules applying maxPeriod logic. |
| 750 |
* @param {import('../../types/bookings').CirculationRule[]} circulationRules |
| 751 |
* @param {import('../../types/bookings').ConstraintOptions} [constraintOptions={}] |
| 752 |
* @returns {import('../../types/bookings').CirculationRule} |
| 753 |
*/ |
| 754 |
export function toEffectiveRules(circulationRules, constraintOptions = {}) { |
| 755 |
const baseRules = circulationRules?.[0] || {}; |
| 756 |
return deriveEffectiveRules(baseRules, constraintOptions); |
| 757 |
} |
| 758 |
|
| 759 |
/** |
| 760 |
* Calculate maximum booking period from circulation rules and constraint mode. |
| 761 |
*/ |
| 762 |
export function calculateMaxBookingPeriod( |
| 763 |
circulationRules, |
| 764 |
dateRangeConstraint, |
| 765 |
customDateRangeFormula = null |
| 766 |
) { |
| 767 |
if (!dateRangeConstraint) return null; |
| 768 |
const rules = circulationRules?.[0]; |
| 769 |
if (!rules) return null; |
| 770 |
const issuelength = parseInt(rules.issuelength) || 0; |
| 771 |
switch (dateRangeConstraint) { |
| 772 |
case "issuelength": |
| 773 |
return issuelength; |
| 774 |
case "issuelength_with_renewals": |
| 775 |
const renewalperiod = parseInt(rules.renewalperiod) || 0; |
| 776 |
const renewalsallowed = parseInt(rules.renewalsallowed) || 0; |
| 777 |
return issuelength + renewalperiod * renewalsallowed; |
| 778 |
case "custom": |
| 779 |
return typeof customDateRangeFormula === "function" |
| 780 |
? customDateRangeFormula(rules) |
| 781 |
: null; |
| 782 |
default: |
| 783 |
return null; |
| 784 |
} |
| 785 |
} |
| 786 |
|
| 787 |
/** |
| 788 |
* Convenience wrapper to calculate availability (disable fn + map) given a dateRange. |
| 789 |
* Accepts ISO strings for dateRange and returns the result of calculateDisabledDates. |
| 790 |
* @returns {import('../../types/bookings').AvailabilityResult} |
| 791 |
*/ |
| 792 |
export function calculateAvailabilityData(dateRange, storeData, options = {}) { |
| 793 |
const { |
| 794 |
bookings, |
| 795 |
checkouts, |
| 796 |
bookableItems, |
| 797 |
circulationRules, |
| 798 |
bookingItemId, |
| 799 |
bookingId, |
| 800 |
} = storeData; |
| 801 |
|
| 802 |
if (!bookings || !checkouts || !bookableItems) { |
| 803 |
return { disable: () => false, unavailableByDate: {} }; |
| 804 |
} |
| 805 |
|
| 806 |
const baseRules = circulationRules?.[0] || {}; |
| 807 |
const maxBookingPeriod = calculateMaxBookingPeriod( |
| 808 |
circulationRules, |
| 809 |
options.dateRangeConstraint, |
| 810 |
options.customDateRangeFormula |
| 811 |
); |
| 812 |
const effectiveRules = deriveEffectiveRules(baseRules, { |
| 813 |
dateRangeConstraint: options.dateRangeConstraint, |
| 814 |
maxBookingPeriod, |
| 815 |
}); |
| 816 |
|
| 817 |
let selectedDatesArray = []; |
| 818 |
if (Array.isArray(dateRange)) { |
| 819 |
selectedDatesArray = isoArrayToDates(dateRange); |
| 820 |
} else if (typeof dateRange === "string") { |
| 821 |
throw new TypeError( |
| 822 |
"calculateAvailabilityData expects an array of ISO/date values for dateRange" |
| 823 |
); |
| 824 |
} |
| 825 |
|
| 826 |
return calculateDisabledDates( |
| 827 |
bookings, |
| 828 |
checkouts, |
| 829 |
bookableItems, |
| 830 |
bookingItemId, |
| 831 |
bookingId, |
| 832 |
selectedDatesArray, |
| 833 |
effectiveRules |
| 834 |
); |
| 835 |
} |
| 836 |
|
| 837 |
/** |
| 838 |
* Pure function to handle Flatpickr's onChange event logic for booking period selection. |
| 839 |
* Determines the valid end date range, applies circulation rules, and returns validation info. |
| 840 |
* |
| 841 |
* @param {Array} selectedDates - Array of currently selected dates ([start], or [start, end]) |
| 842 |
* @param {Object} circulationRules - Circulation rules object (leadDays, trailDays, maxPeriod, etc.) |
| 843 |
* @param {Array} bookings - Array of bookings |
| 844 |
* @param {Array} checkouts - Array of checkouts |
| 845 |
* @param {Array} bookableItems - Array of all bookable items |
| 846 |
* @param {number|string|null} selectedItem - The currently selected item |
| 847 |
* @param {number|string|null} editBookingId - The booking_id being edited (if any) |
| 848 |
* @param {Date|import('dayjs').Dayjs} todayArg - Optional today value for deterministic tests |
| 849 |
* @returns {Object} - { valid: boolean, errors: Array<string>, newMaxEndDate: Date|null, newMinEndDate: Date|null } |
| 850 |
*/ |
| 851 |
export function handleBookingDateChange( |
| 852 |
selectedDates, |
| 853 |
circulationRules, |
| 854 |
bookings, |
| 855 |
checkouts, |
| 856 |
bookableItems, |
| 857 |
selectedItem, |
| 858 |
editBookingId, |
| 859 |
todayArg = undefined, |
| 860 |
options = {} |
| 861 |
) { |
| 862 |
logger.time("handleBookingDateChange"); |
| 863 |
logger.debug("handleBookingDateChange called", { |
| 864 |
selectedDates, |
| 865 |
circulationRules, |
| 866 |
selectedItem, |
| 867 |
editBookingId, |
| 868 |
}); |
| 869 |
const dayjsStart = selectedDates[0] |
| 870 |
? toDayjs(selectedDates[0]).startOf("day") |
| 871 |
: null; |
| 872 |
const dayjsEnd = selectedDates[1] |
| 873 |
? toDayjs(selectedDates[1]).endOf("day") |
| 874 |
: null; |
| 875 |
const errors = []; |
| 876 |
let valid = true; |
| 877 |
let newMaxEndDate = null; |
| 878 |
let newMinEndDate = null; // Declare and initialize here |
| 879 |
|
| 880 |
// Validate: ensure start date is present |
| 881 |
if (!dayjsStart) { |
| 882 |
errors.push(String($__("Start date is required."))); |
| 883 |
valid = false; |
| 884 |
} else { |
| 885 |
// Apply circulation rules: leadDays, trailDays, maxPeriod (in days) |
| 886 |
const leadDays = circulationRules?.leadDays || 0; |
| 887 |
const _trailDays = circulationRules?.trailDays || 0; // Still needed for start date check |
| 888 |
const maxPeriod = |
| 889 |
Number(circulationRules?.maxPeriod) || |
| 890 |
Number(circulationRules?.issuelength) || |
| 891 |
0; |
| 892 |
|
| 893 |
// Calculate min end date; max end date only when constrained |
| 894 |
newMinEndDate = dayjsStart.add(1, "day").startOf("day"); |
| 895 |
if (maxPeriod > 0) { |
| 896 |
newMaxEndDate = calculateMaxEndDate(dayjsStart, maxPeriod).startOf("day"); |
| 897 |
} else { |
| 898 |
newMaxEndDate = null; |
| 899 |
} |
| 900 |
|
| 901 |
// Validate: start must be after today + leadDays |
| 902 |
const today = todayArg |
| 903 |
? toDayjs(todayArg).startOf("day") |
| 904 |
: dayjs().startOf("day"); |
| 905 |
if (dayjsStart.isBefore(today.add(leadDays, "day"))) { |
| 906 |
errors.push( |
| 907 |
String($__("Start date is too soon (lead time required)")) |
| 908 |
); |
| 909 |
valid = false; |
| 910 |
} |
| 911 |
|
| 912 |
// Validate: end must not be before start (only if end date exists) |
| 913 |
if (dayjsEnd && dayjsEnd.isBefore(dayjsStart)) { |
| 914 |
errors.push(String($__("End date is before start date"))); |
| 915 |
valid = false; |
| 916 |
} |
| 917 |
|
| 918 |
// Validate: period must not exceed maxPeriod unless overridden in end_date_only by backend due date |
| 919 |
if (dayjsEnd) { |
| 920 |
const isEndDateOnly = |
| 921 |
circulationRules?.booking_constraint_mode === |
| 922 |
CONSTRAINT_MODE_END_DATE_ONLY; |
| 923 |
const dueStr = circulationRules?.calculated_due_date; |
| 924 |
const hasBackendDue = Boolean(dueStr); |
| 925 |
if (!isEndDateOnly || !hasBackendDue) { |
| 926 |
if ( |
| 927 |
maxPeriod > 0 && |
| 928 |
dayjsEnd.diff(dayjsStart, "day") + 1 > maxPeriod |
| 929 |
) { |
| 930 |
errors.push( |
| 931 |
String($__("Booking period exceeds maximum allowed")) |
| 932 |
); |
| 933 |
valid = false; |
| 934 |
} |
| 935 |
} |
| 936 |
} |
| 937 |
|
| 938 |
// Strategy-specific enforcement for end date (e.g., end_date_only) |
| 939 |
const strategy = createConstraintStrategy( |
| 940 |
circulationRules?.booking_constraint_mode |
| 941 |
); |
| 942 |
const enforcement = strategy.enforceEndDateSelection( |
| 943 |
dayjsStart, |
| 944 |
dayjsEnd, |
| 945 |
circulationRules |
| 946 |
); |
| 947 |
if (!enforcement.ok) { |
| 948 |
errors.push( |
| 949 |
String( |
| 950 |
$__( |
| 951 |
"In end date only mode, you can only select the calculated end date" |
| 952 |
) |
| 953 |
) |
| 954 |
); |
| 955 |
valid = false; |
| 956 |
} |
| 957 |
|
| 958 |
// Validate: check for booking/checkouts overlap using calculateDisabledDates |
| 959 |
// This check is only meaningful if we have at least a start date, |
| 960 |
// and if an end date is also present, we check the whole range. |
| 961 |
// If only start date, effectively checks that single day. |
| 962 |
const endDateForLoop = dayjsEnd || dayjsStart; // If no end date, loop for the start date only |
| 963 |
|
| 964 |
const disableFnResults = calculateDisabledDates( |
| 965 |
bookings, |
| 966 |
checkouts, |
| 967 |
bookableItems, |
| 968 |
selectedItem, |
| 969 |
editBookingId, |
| 970 |
selectedDates, // Pass selectedDates |
| 971 |
circulationRules, // Pass circulationRules |
| 972 |
todayArg, // Pass todayArg |
| 973 |
options |
| 974 |
); |
| 975 |
for ( |
| 976 |
let d = dayjsStart.clone(); |
| 977 |
d.isSameOrBefore(endDateForLoop, "day"); |
| 978 |
d = d.add(1, "day") |
| 979 |
) { |
| 980 |
if (disableFnResults.disable(d.toDate())) { |
| 981 |
errors.push( |
| 982 |
String( |
| 983 |
$__("Date %s is unavailable.").format( |
| 984 |
d.format("YYYY-MM-DD") |
| 985 |
) |
| 986 |
) |
| 987 |
); |
| 988 |
valid = false; |
| 989 |
break; |
| 990 |
} |
| 991 |
} |
| 992 |
} |
| 993 |
|
| 994 |
logger.debug("Date change validation result", { valid, errors }); |
| 995 |
logger.timeEnd("handleBookingDateChange"); |
| 996 |
|
| 997 |
return { |
| 998 |
valid, |
| 999 |
errors, |
| 1000 |
newMaxEndDate: newMaxEndDate ? newMaxEndDate.toDate() : null, |
| 1001 |
newMinEndDate: newMinEndDate ? newMinEndDate.toDate() : null, |
| 1002 |
}; |
| 1003 |
} |
| 1004 |
|
| 1005 |
/** |
| 1006 |
* Aggregate all booking/checkouts for a given date (for calendar indicators) |
| 1007 |
* @param {import('../../types/bookings').UnavailableByDate} unavailableByDate - Map produced by buildUnavailableByDateMap |
| 1008 |
* @param {string|Date|import("dayjs").Dayjs} dateStr - date to check (YYYY-MM-DD or Date or dayjs) |
| 1009 |
* @param {Array<import('../../types/bookings').BookableItem>} bookableItems - Array of all bookable items |
| 1010 |
* @returns {import('../../types/bookings').CalendarMarker[]} indicators for that date |
| 1011 |
*/ |
| 1012 |
export function getBookingMarkersForDate( |
| 1013 |
unavailableByDate, |
| 1014 |
dateStr, |
| 1015 |
bookableItems = [] |
| 1016 |
) { |
| 1017 |
// Guard against unavailableByDate itself being undefined or null |
| 1018 |
if (!unavailableByDate) { |
| 1019 |
return []; // No data, so no markers |
| 1020 |
} |
| 1021 |
|
| 1022 |
const d = |
| 1023 |
typeof dateStr === "string" |
| 1024 |
? dayjs(dateStr).startOf("day") |
| 1025 |
: dayjs(dateStr).isValid() |
| 1026 |
? dayjs(dateStr).startOf("day") |
| 1027 |
: dayjs().startOf("day"); |
| 1028 |
const key = d.format("YYYY-MM-DD"); |
| 1029 |
const markers = []; |
| 1030 |
|
| 1031 |
const findItem = item_id => { |
| 1032 |
if (item_id == null) return undefined; |
| 1033 |
return bookableItems.find(i => idsEqual(i?.item_id, item_id)); |
| 1034 |
}; |
| 1035 |
|
| 1036 |
const entry = unavailableByDate[key]; // This was line 496 |
| 1037 |
|
| 1038 |
// Guard against the specific date key not being in the map |
| 1039 |
if (!entry) { |
| 1040 |
return []; // No data for this specific date, so no markers |
| 1041 |
} |
| 1042 |
|
| 1043 |
// Now it's safe to use Object.entries(entry) |
| 1044 |
for (const [item_id, reasons] of Object.entries(entry)) { |
| 1045 |
const item = findItem(item_id); |
| 1046 |
for (const reason of reasons) { |
| 1047 |
let type = reason; |
| 1048 |
// Map IntervalTree/Sweep reasons to CSS class names |
| 1049 |
if (type === "booking") type = "booked"; |
| 1050 |
if (type === "core") type = "booked"; |
| 1051 |
if (type === "checkout") type = "checked-out"; |
| 1052 |
// lead and trail periods keep their original names for CSS |
| 1053 |
markers.push({ |
| 1054 |
/** @type {import('../../types/bookings').MarkerType} */ |
| 1055 |
type: /** @type {any} */ (type), |
| 1056 |
item: String(item_id), |
| 1057 |
itemName: item?.title || String(item_id), |
| 1058 |
barcode: item?.barcode || item?.external_id || null, |
| 1059 |
}); |
| 1060 |
} |
| 1061 |
} |
| 1062 |
return markers; |
| 1063 |
} |
| 1064 |
|
| 1065 |
/** |
| 1066 |
* Constrain pickup locations based on selected itemtype or item |
| 1067 |
* Returns { filtered, filteredOutCount, total, constraintApplied } |
| 1068 |
* |
| 1069 |
* @param {Array<import('../../types/bookings').PickupLocation>} pickupLocations |
| 1070 |
* @param {Array<import('../../types/bookings').BookableItem>} bookableItems |
| 1071 |
* @param {string|number|null} bookingItemtypeId |
| 1072 |
* @param {string|number|null} bookingItemId |
| 1073 |
* @returns {import('../../types/bookings').ConstraintResult<import('../../types/bookings').PickupLocation>} |
| 1074 |
*/ |
| 1075 |
export function constrainPickupLocations( |
| 1076 |
pickupLocations, |
| 1077 |
bookableItems, |
| 1078 |
bookingItemtypeId, |
| 1079 |
bookingItemId |
| 1080 |
) { |
| 1081 |
logger.debug("constrainPickupLocations called", { |
| 1082 |
inputLocations: pickupLocations.length, |
| 1083 |
bookingItemtypeId, |
| 1084 |
bookingItemId, |
| 1085 |
bookableItems: bookableItems.length, |
| 1086 |
locationDetails: pickupLocations.map(loc => ({ |
| 1087 |
library_id: loc.library_id, |
| 1088 |
pickup_items: loc.pickup_items?.length || 0, |
| 1089 |
})), |
| 1090 |
}); |
| 1091 |
|
| 1092 |
if (!bookingItemtypeId && !bookingItemId) { |
| 1093 |
logger.debug( |
| 1094 |
"constrainPickupLocations: No constraints, returning all locations" |
| 1095 |
); |
| 1096 |
return buildConstraintResult(pickupLocations, pickupLocations.length); |
| 1097 |
} |
| 1098 |
const filtered = pickupLocations.filter(loc => { |
| 1099 |
if (bookingItemId) { |
| 1100 |
return ( |
| 1101 |
loc.pickup_items && includesId(loc.pickup_items, bookingItemId) |
| 1102 |
); |
| 1103 |
} |
| 1104 |
if (bookingItemtypeId) { |
| 1105 |
return ( |
| 1106 |
loc.pickup_items && |
| 1107 |
bookableItems.some( |
| 1108 |
item => |
| 1109 |
idsEqual(item.item_type_id, bookingItemtypeId) && |
| 1110 |
includesId(loc.pickup_items, item.item_id) |
| 1111 |
) |
| 1112 |
); |
| 1113 |
} |
| 1114 |
return true; |
| 1115 |
}); |
| 1116 |
logger.debug("constrainPickupLocations result", { |
| 1117 |
inputCount: pickupLocations.length, |
| 1118 |
outputCount: filtered.length, |
| 1119 |
filteredOutCount: pickupLocations.length - filtered.length, |
| 1120 |
constraints: { |
| 1121 |
bookingItemtypeId, |
| 1122 |
bookingItemId, |
| 1123 |
}, |
| 1124 |
}); |
| 1125 |
|
| 1126 |
return buildConstraintResult(filtered, pickupLocations.length); |
| 1127 |
} |
| 1128 |
|
| 1129 |
/** |
| 1130 |
* Constrain bookable items based on selected pickup location and/or itemtype |
| 1131 |
* Returns { filtered, filteredOutCount, total, constraintApplied } |
| 1132 |
* |
| 1133 |
* @param {Array<import('../../types/bookings').BookableItem>} bookableItems |
| 1134 |
* @param {Array<import('../../types/bookings').PickupLocation>} pickupLocations |
| 1135 |
* @param {string|null} pickupLibraryId |
| 1136 |
* @param {string|number|null} bookingItemtypeId |
| 1137 |
* @returns {import('../../types/bookings').ConstraintResult<import('../../types/bookings').BookableItem>} |
| 1138 |
*/ |
| 1139 |
export function constrainBookableItems( |
| 1140 |
bookableItems, |
| 1141 |
pickupLocations, |
| 1142 |
pickupLibraryId, |
| 1143 |
bookingItemtypeId |
| 1144 |
) { |
| 1145 |
logger.debug("constrainBookableItems called", { |
| 1146 |
inputItems: bookableItems.length, |
| 1147 |
pickupLibraryId, |
| 1148 |
bookingItemtypeId, |
| 1149 |
pickupLocations: pickupLocations.length, |
| 1150 |
itemDetails: bookableItems.map(item => ({ |
| 1151 |
item_id: item.item_id, |
| 1152 |
item_type_id: item.item_type_id, |
| 1153 |
title: item.title, |
| 1154 |
})), |
| 1155 |
}); |
| 1156 |
|
| 1157 |
if (!pickupLibraryId && !bookingItemtypeId) { |
| 1158 |
logger.debug( |
| 1159 |
"constrainBookableItems: No constraints, returning all items" |
| 1160 |
); |
| 1161 |
return buildConstraintResult(bookableItems, bookableItems.length); |
| 1162 |
} |
| 1163 |
const filtered = bookableItems.filter(item => { |
| 1164 |
if (pickupLibraryId && bookingItemtypeId) { |
| 1165 |
const found = pickupLocations.find( |
| 1166 |
loc => |
| 1167 |
idsEqual(loc.library_id, pickupLibraryId) && |
| 1168 |
loc.pickup_items && |
| 1169 |
includesId(loc.pickup_items, item.item_id) |
| 1170 |
); |
| 1171 |
const match = |
| 1172 |
idsEqual(item.item_type_id, bookingItemtypeId) && found; |
| 1173 |
return match; |
| 1174 |
} |
| 1175 |
if (pickupLibraryId) { |
| 1176 |
const found = pickupLocations.find( |
| 1177 |
loc => |
| 1178 |
idsEqual(loc.library_id, pickupLibraryId) && |
| 1179 |
loc.pickup_items && |
| 1180 |
includesId(loc.pickup_items, item.item_id) |
| 1181 |
); |
| 1182 |
return found; |
| 1183 |
} |
| 1184 |
if (bookingItemtypeId) { |
| 1185 |
return idsEqual(item.item_type_id, bookingItemtypeId); |
| 1186 |
} |
| 1187 |
return true; |
| 1188 |
}); |
| 1189 |
logger.debug("constrainBookableItems result", { |
| 1190 |
inputCount: bookableItems.length, |
| 1191 |
outputCount: filtered.length, |
| 1192 |
filteredOutCount: bookableItems.length - filtered.length, |
| 1193 |
filteredItems: filtered.map(item => ({ |
| 1194 |
item_id: item.item_id, |
| 1195 |
item_type_id: item.item_type_id, |
| 1196 |
title: item.title, |
| 1197 |
})), |
| 1198 |
constraints: { |
| 1199 |
pickupLibraryId, |
| 1200 |
bookingItemtypeId, |
| 1201 |
}, |
| 1202 |
}); |
| 1203 |
|
| 1204 |
return buildConstraintResult(filtered, bookableItems.length); |
| 1205 |
} |
| 1206 |
|
| 1207 |
/** |
| 1208 |
* Constrain item types based on selected pickup location or item |
| 1209 |
* Returns { filtered, filteredOutCount, total, constraintApplied } |
| 1210 |
* @param {Array<import('../../types/bookings').ItemType>} itemTypes |
| 1211 |
* @param {Array<import('../../types/bookings').BookableItem>} bookableItems |
| 1212 |
* @param {Array<import('../../types/bookings').PickupLocation>} pickupLocations |
| 1213 |
* @param {string|null} pickupLibraryId |
| 1214 |
* @param {string|number|null} bookingItemId |
| 1215 |
* @returns {import('../../types/bookings').ConstraintResult<import('../../types/bookings').ItemType>} |
| 1216 |
*/ |
| 1217 |
export function constrainItemTypes( |
| 1218 |
itemTypes, |
| 1219 |
bookableItems, |
| 1220 |
pickupLocations, |
| 1221 |
pickupLibraryId, |
| 1222 |
bookingItemId |
| 1223 |
) { |
| 1224 |
if (!pickupLibraryId && !bookingItemId) { |
| 1225 |
return buildConstraintResult(itemTypes, itemTypes.length); |
| 1226 |
} |
| 1227 |
const filtered = itemTypes.filter(type => { |
| 1228 |
if (bookingItemId) { |
| 1229 |
return bookableItems.some( |
| 1230 |
item => |
| 1231 |
idsEqual(item.item_id, bookingItemId) && |
| 1232 |
idsEqual(item.item_type_id, type.item_type_id) |
| 1233 |
); |
| 1234 |
} |
| 1235 |
if (pickupLibraryId) { |
| 1236 |
return bookableItems.some( |
| 1237 |
item => |
| 1238 |
idsEqual(item.item_type_id, type.item_type_id) && |
| 1239 |
pickupLocations.find( |
| 1240 |
loc => |
| 1241 |
idsEqual(loc.library_id, pickupLibraryId) && |
| 1242 |
loc.pickup_items && |
| 1243 |
includesId(loc.pickup_items, item.item_id) |
| 1244 |
) |
| 1245 |
); |
| 1246 |
} |
| 1247 |
return true; |
| 1248 |
}); |
| 1249 |
return buildConstraintResult(filtered, itemTypes.length); |
| 1250 |
} |
| 1251 |
|
| 1252 |
/** |
| 1253 |
* Calculate constraint highlighting data for calendar display |
| 1254 |
* @param {Date|import('dayjs').Dayjs} startDate - Selected start date |
| 1255 |
* @param {Object} circulationRules - Circulation rules object |
| 1256 |
* @param {Object} constraintOptions - Additional constraint options |
| 1257 |
* @returns {import('../../types/bookings').ConstraintHighlighting | null} Constraint highlighting |
| 1258 |
*/ |
| 1259 |
export function calculateConstraintHighlighting( |
| 1260 |
startDate, |
| 1261 |
circulationRules, |
| 1262 |
constraintOptions = {} |
| 1263 |
) { |
| 1264 |
const strategy = createConstraintStrategy( |
| 1265 |
circulationRules?.booking_constraint_mode |
| 1266 |
); |
| 1267 |
const result = strategy.calculateConstraintHighlighting( |
| 1268 |
startDate, |
| 1269 |
circulationRules, |
| 1270 |
constraintOptions |
| 1271 |
); |
| 1272 |
logger.debug("Constraint highlighting calculated", result); |
| 1273 |
return result; |
| 1274 |
} |
| 1275 |
|
| 1276 |
/** |
| 1277 |
* Determine if calendar should navigate to show target end date |
| 1278 |
* @param {Date|import('dayjs').Dayjs} startDate - Selected start date |
| 1279 |
* @param {Date|import('dayjs').Dayjs} targetEndDate - Calculated target end date |
| 1280 |
* @param {import('../../types/bookings').CalendarCurrentView} currentView - Current calendar view info |
| 1281 |
* @returns {import('../../types/bookings').CalendarNavigationTarget} |
| 1282 |
*/ |
| 1283 |
export function getCalendarNavigationTarget( |
| 1284 |
startDate, |
| 1285 |
targetEndDate, |
| 1286 |
currentView = {} |
| 1287 |
) { |
| 1288 |
logger.debug("Checking calendar navigation", { |
| 1289 |
startDate, |
| 1290 |
targetEndDate, |
| 1291 |
currentView, |
| 1292 |
}); |
| 1293 |
|
| 1294 |
const start = toDayjs(startDate); |
| 1295 |
const target = toDayjs(targetEndDate); |
| 1296 |
|
| 1297 |
// Never navigate backwards if target is before the chosen start |
| 1298 |
if (target.isBefore(start, "day")) { |
| 1299 |
logger.debug("Target end before start; skip navigation"); |
| 1300 |
return { shouldNavigate: false }; |
| 1301 |
} |
| 1302 |
|
| 1303 |
// If we know the currently visible range, do not navigate when target is already visible |
| 1304 |
if (currentView.visibleStartDate && currentView.visibleEndDate) { |
| 1305 |
const visibleStart = toDayjs(currentView.visibleStartDate).startOf( |
| 1306 |
"day" |
| 1307 |
); |
| 1308 |
const visibleEnd = toDayjs(currentView.visibleEndDate).endOf("day"); |
| 1309 |
const inView = |
| 1310 |
target.isSameOrAfter(visibleStart, "day") && |
| 1311 |
target.isSameOrBefore(visibleEnd, "day"); |
| 1312 |
if (inView) { |
| 1313 |
logger.debug("Target end date already visible; no navigation"); |
| 1314 |
return { shouldNavigate: false }; |
| 1315 |
} |
| 1316 |
} |
| 1317 |
|
| 1318 |
// Fallback: navigate when target month differs from start month |
| 1319 |
if (start.month() !== target.month() || start.year() !== target.year()) { |
| 1320 |
const navigationTarget = { |
| 1321 |
shouldNavigate: true, |
| 1322 |
targetMonth: target.month(), |
| 1323 |
targetYear: target.year(), |
| 1324 |
targetDate: target.toDate(), |
| 1325 |
}; |
| 1326 |
logger.debug("Calendar should navigate", navigationTarget); |
| 1327 |
return navigationTarget; |
| 1328 |
} |
| 1329 |
|
| 1330 |
logger.debug("No navigation needed - same month"); |
| 1331 |
return { shouldNavigate: false }; |
| 1332 |
} |
| 1333 |
|
| 1334 |
/** |
| 1335 |
* Aggregate markers by type for display |
| 1336 |
* @param {Array} markers - Array of booking markers |
| 1337 |
* @returns {import('../../types/bookings').MarkerAggregation} Aggregated counts by type |
| 1338 |
*/ |
| 1339 |
export function aggregateMarkersByType(markers) { |
| 1340 |
logger.debug("Aggregating markers", { count: markers.length }); |
| 1341 |
|
| 1342 |
const aggregated = markers.reduce((acc, marker) => { |
| 1343 |
// Exclude lead and trail markers from visual display |
| 1344 |
if (marker.type !== "lead" && marker.type !== "trail") { |
| 1345 |
acc[marker.type] = (acc[marker.type] || 0) + 1; |
| 1346 |
} |
| 1347 |
return acc; |
| 1348 |
}, {}); |
| 1349 |
|
| 1350 |
logger.debug("Markers aggregated", aggregated); |
| 1351 |
return aggregated; |
| 1352 |
} |
| 1353 |
|
| 1354 |
// Re-export the new efficient data structure builders |
| 1355 |
export { buildIntervalTree, processCalendarView }; |