UNPKG

@lovebowls/leagueelements

Version:

League Elements package for LoveBowls

1,366 lines (1,272 loc) 70.6 kB
var LeagueMatchesAttention = (function () { 'use strict'; const panelStyles = ` .panel { margin-bottom: var(--le-padding-m, 1.25em); border: 1px solid var(--le-border-color-light, #f0f0f0); border-radius: var(--le-border-radius-standard, 4px); background-color: var(--le-background-color-panel, #fff); } .panel-header-shared { padding: var(--le-padding-s, 0.75em) var(--le-padding-m, 1.25em); /* Increased padding */ border-bottom: 1px solid var(--le-border-color-medium, #eee); font-weight: bold; color: var(--le-text-color-primary, #333); background-color: var(--le-background-color-header, #f9f9f9); display: flex; justify-content: space-between; align-items: center; font-size: var(--le-font-size-medium, 1.1em); } .panel .panel-header { display: flex; justify-content: space-between; align-items: center; background-color: var(--le-background-color-header, #f9f9f9); } .panel-content { padding: var(--le-padding-m, 1.25em); background-color: var(--le-background-color-panel, #fff); /* Common border for content area if needed border: 1px solid var(--le-border-color-light, #f0f0f0); */ } .controls-panel { /* Layout properties moved to mobile/desktop sections */ padding: 0; margin-bottom: var(--le-padding-s, 0.5rem); margin-top: var(--le-padding-s, 0.5rem); background: transparent; border: none; display: flex; justify-content: space-between; align-items: center; gap: var(--le-padding-m, 1rem); } .filter-controls { gap: var(--le-padding-s, 0.5rem); display: flex; align-items: center; flex: 1; } /* Enhanced dropdown styling for button-like appearance */ .controls-panel .dropdown-shared { position: relative; display: inline-block; } .controls-panel .dropdown-select-shared { appearance: none; -webkit-appearance: none; -moz-appearance: none; background-color: var(--le-background-color-button, #f0f0f0); border: 1px solid var(--le-border-color-medium, #ddd); border-radius: var(--le-border-radius-standard, 4px); padding: var(--le-padding-xs, 0.25rem); font-size: var(--le-font-size-dropdown, 1em)); color: var(--le-text-color-primary, #333); cursor: pointer; line-height: 1.4; min-width: 150px; transition: all 0.2s ease; font-weight: 500; } .controls-panel .dropdown-select-shared:hover { background-color: var(--le-background-color-button-hover, #e0e0e0); border-color: var(--le-border-color-dark, #ccc); box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); } .controls-panel .dropdown-select-shared:focus { outline: none; border-color: var(--le-text-color-accent, #2196f3); box-shadow: 0 0 0 2px rgba(33, 150, 243, 0.2); background-color: var(--le-background-color-panel, #fff); } .controls-panel .dropdown-select-shared:active { background-color: var(--le-background-color-button-hover, #e0e0e0); transform: translateY(1px); } `; const buttonStyles = ` .button-shared { padding: 4px 8px; border: 1px solid var(--le-border-color-medium, #ccc); background-color: var(--le-background-color-button, #f0f0f0); color: var(--le-text-color-primary, #333); /* Ensure text color contrasts with button background */ cursor: pointer; border-radius: var(--le-border-radius-standard, 4px); font-size: var(--le-font-size-button, var(--le-font-size-medium, 1.15em)); /* Use variable with fallback */ text-decoration: none; display: inline-block; text-align: center; line-height: normal; /* Ensure consistent line height */ white-space: nowrap; /* Prevent text wrapping */ vertical-align: middle; /* Align nicely if next to text/icons */ user-select: none; /* Prevent text selection on click */ transition: background-color 0.2s ease-in-out, border-color 0.2s ease-in-out; /* Smooth transitions */ } .button-shared:hover:not(:disabled) { background-color: var(--le-background-color-button-hover, #e0e0e0); border-color: var(--le-border-color-dark, #bbb); /* Slightly darker border on hover */ /* color: var(--le-text-color-accent-hover, inherit); Optional: change text color on hover */ } .button-shared:active:not(:disabled) { /* Optional: style for active (pressed) state */ /* background-color: var(--le-background-color-button-active, #d0d0d0); */ } .button-shared:disabled, .button-shared.disabled { /* Allow class-based disabling too */ background-color: var(--le-background-color-button-disabled, #eee); color: var(--le-text-color-secondary, #aaa); border-color: var(--le-border-color-medium, #ccc); /* Use medium border for disabled state */ cursor: not-allowed; opacity: 0.7; /* Visually indicate disabled state */ } /* Variations */ .button-shared.button-primary { background-color: var(--le-color-primary, #007bff); color: var(--le-text-color-on-primary, #fff); border-color: var(--le-color-primary, #007bff); } .button-shared.button-primary:hover:not(:disabled) { background-color: var(--le-color-primary-hover, #0056b3); border-color: var(--le-color-primary-hover, #0056b3); } .button-shared.button-secondary-light { background-color: var(--le-background-color-button-secondary-light, #f8f9fa); color: var(--le-text-color-secondary-light-text, #212529); border-color: var(--le-border-color-secondary-light, #ced4da); } .button-shared.button-secondary-light:hover:not(:disabled) { background-color: var(--le-background-color-button-secondary-light-hover, #e2e6ea); border-color: var(--le-border-color-secondary-light-hover, #dae0e5); color: var(--le-text-color-secondary-light-text-hover, #212529); } /* Example for a darker secondary button if needed elsewhere .button-shared.button-secondary { background-color: var(--le-color-secondary, #6c757d); color: var(--le-text-color-on-secondary, #fff); border-color: var(--le-color-secondary, #6c757d); } .button-shared.button-secondary:hover:not(:disabled) { background-color: var(--le-color-secondary-hover, #5a6268); border-color: var(--le-color-secondary-hover, #5a6268); } */ `; const listStyles = ` .list-container { max-height: 200px; overflow-y: auto; } .list-panel { border: 1px solid var(--le-border-color-medium, #ddd); border-radius: var(--le-border-radius-standard, 4px); background: var(--le-background-color-panel, #fff); } .list-panel h4 { margin: 0; padding: var(--le-padding-m, 1rem); background: var(--le-background-color-header, #f8f9fa); border-bottom: 1px solid var(--le-border-color-light, #eee); color: var(--le-text-color-primary, #333); } .list-panel.disabled { pointer-events: none; opacity: 0.6; } .list { list-style: none; margin: 0; padding: 0; } .list-item{ display: flex; justify-content: space-between; align-items: center; padding: var(--le-padding-xs) var(--le-padding-s); border-bottom: 1px solid var(--le-border-color-light, #eee); cursor: pointer; transition: background-color 0.2s ease; min-height: 2.5rem; /* Ensure consistent height for action buttons */ box-sizing: border-box; } .list-panel.disabled .list-item { cursor: not-allowed; } .list-item:last-child { border-bottom: none; } /* Example of a text part within a list item that should grow */ .list-item .list-item-text-primary { flex-grow: 1; font-size: var(--le-font-size-medium, 1.2em); text-align: left; /* Ensure text is left-aligned */ display: flex; align-items: center; /* Center text vertically within its container */ } /* Example of an actions container part within a list item */ .list-item .list-item-actions { flex-shrink: 0; /* Prevent actions from shrinking */ display: flex; gap: var(--le-padding-xs, 0.4em); /* Increased gap */ align-items: center; min-height: 2rem; /* Reserve space for buttons even when empty */ } .list-item:hover { background-color: var(--le-background-color-hover, #f5f5f5); } .list-item.selected { background-color: var(--le-background-color-selected, #e3f2fd); border-left: 3px solid var(--le-border-color-primary, #2196f3); animation: highlightItem 0.6s ease-out; } @keyframes highlightItem { 0% { background-color: var(--le-background-color-accent, #108CFF); box-shadow: 0 0 0 2px rgba(16, 140, 255, 0.3), 0 2px 8px rgba(16, 140, 255, 0.2); } 100% { background-color: var(--le-background-color-selected, #e3f2fd); box-shadow: none; } } /* Mobile-specific list item adjustments */ @media (max-width: 768px) { .list-item { min-height: 4rem; /* Slightly taller for mobile touch targets */ padding: 0 var(--le-padding-xs, 1rem);; } .list-item .list-item-actions { min-height: 2.5rem; /* Larger touch targets for mobile */ } .list-item .list-item-actions .button-shared { min-height: 2.5rem; /* Ensure buttons are touch-friendly */ } } `; const pagingStyles = ` /* Paging Controls Styles */ .paging-controls { display: flex; justify-content: flex-end; gap: var(--le-padding-s, 0.5rem); margin-top: var(--le-padding-s, 0.5rem); padding: var(--le-padding-xs, 0.25rem) 0; background-color: transparent; border: none; font-size: var(--le-font-size-xs, 0.75em); } .paging-btn { background: var(--le-background-color-button, #f5f5f5); border: 1px solid var(--le-border-color-dark, #ccc); border-radius: var(--le-border-radius-small, 3px); padding: var(--le-padding-xs, 0.2rem) var(--le-padding-s, 0.7rem); cursor: pointer; color: var(--le-text-color-primary, #333); transition: background-color 0.2s ease-in-out, border-color 0.2s ease-in-out; user-select: none; } .paging-btn:hover:not(:disabled) { background: var(--le-background-color-button-hover, #e0e0e0); border-color: var(--le-border-color-dark, #bbb); } .paging-btn:disabled { background: var(--le-background-color-button-disabled, #eee); color: var(--le-text-color-secondary, #aaa); cursor: not-allowed; opacity: 0.7; } `; const BASE_STYLES = ` ${panelStyles} ${buttonStyles} ${listStyles} ${pagingStyles} :host { display: block; font-family: var(--le-font-family-main, 'Open Sans', Helvetica, Arial, sans-serif); box-sizing: border-box; color: var(--le-text-color-primary, #333); } .match-item { padding: var(--swal-padding-xs, 0.2rem) 0; display: flex; align-items: center; gap: var(--le-padding-xs, 0.25em); } .match-date { color: var(--le-text-color-secondary, #666); margin-bottom: var(--le-padding-xs, 0.2em); } .error { color: var(--le-text-color-error, #ff0000); padding: var(--le-padding-s, 0.5rem); background-color: var(--le-background-color-error, #fff0f0); border-radius: var(--swal-border-radius-standard, 4px); } .warning-icon-future-result { color: var(--le-color-status-warning, #f39c12); } .warning-icon-conflict { color: var(--le-color-status-conflict, #e67e22); } .warning-icon-pending-result { color: var(--le-color-status-pending, #e74c3c); } .warning-icon-no-date { color: var(--le-color-status-info, #2196f3); } .warning-icon { flex-shrink: 0; } `; const MOBILE_STYLES = ` ${BASE_STYLES} .match-item { padding: var(--swal-padding-xs, 0.2rem) 0; } /* Mobile: Ensure no height constraints for dynamic content-based height */ .attention-matches { max-height: none; overflow-y: visible; } `; const DESKTOP_STYLES = ` ${BASE_STYLES} .match-item { padding: var(--swal-padding-xs, 0.2rem) 0; } /* Desktop: Add height constraints if needed for space management */ .attention-matches { max-height: 300px; overflow-y: auto; } `; const TEMPLATE = ` <div class="attention-matches"> {{attentionMatches}} </div> <div class="paging-controls" id="attention-paging" {{showPaging}}> <button class="paging-btn button-shared button" id="attention-prev" {{prevDisabled}}>&lt; Prev</button> <button class="paging-btn button-shared button" id="attention-next" {{nextDisabled}}>Next &gt;</button> </div> `; /** * Safely register a custom element, avoiding duplicate registration errors * in single-page applications where modules may be loaded multiple times. * * @param {string} tagName - The custom element tag name (e.g., 'league-element') * @param {CustomElementConstructor} elementClass - The element class constructor * @param {boolean} [logRegistration=false] - Whether to log successful registrations */ function safeDefine(tagName, elementClass, logRegistration = false) { if (!customElements.get(tagName)) { customElements.define(tagName, elementClass); if (logRegistration) { console.log(`[ElementRegistry] Registered custom element: ${tagName}`); } } else if (logRegistration) { console.log(`[ElementRegistry] Custom element already registered: ${tagName}`); } } // Define custom event types for the LeagueMatchesAttention element class LeagueMatchesAttentionEvent extends CustomEvent { constructor(detail) { super('league-matches-attention-event', { detail, bubbles: true, // Ensure event bubbles up through the DOM composed: true, // Ensure event crosses shadow DOM boundaries cancelable: true // Make the event cancelable }); } } /** * Custom element to display matches requiring attention with paging. * * @element league-matches-attention * @attr {string} data - JSON stringified League instance object * @attr {boolean} [is-mobile] - Whether to use mobile styles * @attr {string} [team-mapping] - JSON stringified array of {value, label} objects mapping team values to display names * * Emits 'league-matches-attention-event' with detail { type: 'matchClick', match } */ class LeagueMatchesAttention extends HTMLElement { constructor() { super(); this.shadow = this.attachShadow({ mode: 'open' }); this.league = null; // Store the league instance instead of just matches this.currentPage = 0; this.itemsPerPage = 5; this.teamMapping = {}; } static get observedAttributes() { return ['data', 'is-mobile', 'team-mapping']; } connectedCallback() { if (this.hasAttribute('team-mapping')) { this._setTeamMapping(this.getAttribute('team-mapping')); } this.render(); } attributeChangedCallback(name, oldValue, newValue) { if (oldValue === newValue) return; if (name === 'data') { this.loadData(newValue); } else if (name === 'is-mobile') { this.render(); } else if (name === 'team-mapping') { this._setTeamMapping(newValue); this.render(); // Re-render to apply new team names } } _setTeamMapping(mappingData) { try { if (!mappingData) { this.teamMapping = {}; return; } // Parse mapping from the attribute string const dataObj = typeof mappingData === 'string' ? JSON.parse(mappingData) : mappingData; // Handle either array of {_id, name} objects or direct _id -> name mapping object if (Array.isArray(dataObj)) { // Convert array of objects to a simple map this.teamMapping = {}; dataObj.forEach(team => { if (team._id) { this.teamMapping[team._id] = team.name || team._id; } }); } else { // Assume we already have a direct mapping object this.teamMapping = dataObj; } } catch (error) { console.error('[LeagueMatchesAttention] Error parsing team mapping:', error); this.teamMapping = {}; } } // Add a utility method to get display name for a team getTeamDisplayName(teamId) { if (!teamId || !this.teamMapping) { return teamId; } // With standardized team model, teamMapping is a simple object map of _id -> name const teamName = this.teamMapping[teamId]; if (teamName) { return teamName; } return teamId; } /** * Loads and parses the league data. * @param {string|Object} data - League instance or JSON string */ async loadData(data) { try { if (typeof data === 'string') { const parsedData = JSON.parse(data); // Import League class to create a proper instance const { League } = await Promise.resolve().then(function () { return index; }); this.league = new League(parsedData); } else if (data && typeof data === 'object') { // If it's already a League instance, use it directly if (data.getMatchesRequiringAttention && data.getConflictingMatchIds) { this.league = data; } else { // It's plain data, create a League instance const { League } = await Promise.resolve().then(function () { return index; }); this.league = new League(data); } } else { this.league = null; } this.currentPage = 0; this.render(); this.dispatchEvent(new LeagueMatchesAttentionEvent({ type: 'dataLoaded', league: this.league })); } catch (error) { const errorMessage = 'Failed to load league data for attention matches'; this.showError(errorMessage); console.error('Error loading league data for attention matches:', error); this.dispatchEvent(new LeagueMatchesAttentionEvent({ type: 'error', message: errorMessage, error })); } } /** * Shows an error message in the component. * @param {string} message */ showError(message) { const content = this.shadow.querySelector('.attention-matches'); if (content) { content.innerHTML = `<div class="error">${message}</div>`; } } _hasNextPage() { if (!this.league || typeof this.league.getMatchesRequiringAttention !== 'function') { return false; } const list = this.league.getMatchesRequiringAttention(); return (this.currentPage + 1) * this.itemsPerPage < list.length; } /** * Renders the list of matches requiring attention for the current page. * @returns {string} */ renderAttentionMatches() { if (!this.league || typeof this.league.getMatchesRequiringAttention !== 'function') { return '<div class="no-data">No league data available</div>'; } const matches = this.league.getMatchesRequiringAttention(); const start = this.currentPage * this.itemsPerPage; const pageItems = matches.slice(start, start + this.itemsPerPage); if (pageItems.length === 0) { if (matches.length > 0) { return '<div class="no-data">None</div>'; } return '<div class="no-data">None</div>'; } const today = new Date(); today.setHours(0, 0, 0, 0); let conflictingIds = new Set(); if (typeof this.league.getConflictingMatchIds === 'function') { conflictingIds = this.league.getConflictingMatchIds(); } return pageItems.map(match => { // Get display names for teams const homeTeamId = match.homeTeam?._id; const awayTeamId = match.awayTeam?._id; const homeTeamDisplay = match.homeTeam?.name || this.getTeamDisplayName(homeTeamId); const awayTeamDisplay = match.awayTeam?.name || this.getTeamDisplayName(awayTeamId); let warningSymbol = ''; let warningClass = ''; let tooltipText = ''; if (match.result && match.date) { const matchDate = new Date(match.date); matchDate.setHours(0, 0, 0, 0); if (matchDate > today) { tooltipText = "Result entered for a future match date."; warningSymbol = '&#9888;'; warningClass = 'warning-icon-future-result'; } } else if (conflictingIds.has(match._id)) { tooltipText = "Scheduling conflict on this date."; warningSymbol = '&#9888;'; warningClass = 'warning-icon-conflict'; } else if (match.date && !match.result) { const matchDate = new Date(match.date); matchDate.setHours(0, 0, 0, 0); if (matchDate < today) { tooltipText = "Match date passed, result pending."; warningSymbol = '&#9203;'; warningClass = 'warning-icon-pending-result'; } } else if (!match.date && !match.result) { tooltipText = "No date set for match"; warningSymbol = '&#128197;'; warningClass = 'warning-icon-no-date'; } const titleAttr = tooltipText ? ` title="${this.escapeHtml(tooltipText)}"` : ''; const dataAttr = tooltipText ? ` data-attention-reason="${this.escapeHtml(tooltipText)}"` : ''; const warningSpan = warningSymbol ? `<span class="warning-icon ${warningClass}" title="${this.escapeHtml(tooltipText)}">${warningSymbol}</span>` : ''; return ` <div class="match-item list-item"> ${warningSpan} <a href="#" class="match-link list-item-text-primary" data-match-id="${match._id}"${titleAttr}${dataAttr}> ${this.escapeHtml(homeTeamDisplay)} vs ${this.escapeHtml(awayTeamDisplay)} </a> </div> `; }).join(''); } _fillTemplate(template) { const showPaging = this.currentPage > 0 || this._hasNextPage(); return template.replace('{{attentionMatches}}', this.renderAttentionMatches()).replace('{{prevDisabled}}', this.currentPage === 0 ? 'disabled' : '').replace('{{nextDisabled}}', this._hasNextPage() ? '' : 'disabled').replace('{{showPaging}}', showPaging ? '' : 'style="display: none;"'); } render() { const isMobile = this.getAttribute('is-mobile') === 'true'; this.shadow.innerHTML = ` <style>${isMobile ? MOBILE_STYLES : DESKTOP_STYLES}</style> ${this._fillTemplate(TEMPLATE)} `; this.setupEventListeners(); } setupEventListeners() { // Paging buttons const prevBtn = this.shadow.querySelector('#attention-prev'); const nextBtn = this.shadow.querySelector('#attention-next'); if (prevBtn) { prevBtn.onclick = () => { if (this.currentPage > 0) { this.currentPage--; this.render(); } }; } if (nextBtn) { nextBtn.onclick = () => { if (this._hasNextPage()) { this.currentPage++; this.render(); } }; } // Match click handlers const matchLinks = this.shadow.querySelectorAll('.match-link'); matchLinks.forEach((link, index) => { link.onclick = e => { e.preventDefault(); e.stopPropagation(); const matchId = link.dataset.matchId; const attentionReason = link.dataset.attentionReason; let match = null; if (this.league && typeof this.league.getMatchesRequiringAttention === 'function') { match = this.league.getMatchesRequiringAttention().find(m => m._id === matchId); } if (match) { // Create and dispatch the event const event = new LeagueMatchesAttentionEvent({ type: 'matchClick', match: match, attentionReason: attentionReason }); const dispatchResult = this.dispatchEvent(event); // If the event was canceled, log it if (!dispatchResult) { console.warn('[LeagueMatchesAttention] Event was canceled by a listener'); } } else { console.warn('[LeagueMatchesAttention] No match found for ID:', matchId); } }; }); // Add a global click handler to the shadow root to see if clicks are reaching it this.shadow.addEventListener('click', e => { if (e.target.classList.contains('match-link')) { console.log('[LeagueMatchesAttention] Shadow root click handler - match link clicked'); } }, { capture: true }); } // Public API methods setPage(pageNumber) { if (pageNumber >= 0 && pageNumber !== this.currentPage) { this.currentPage = pageNumber; this.render(); } } // Helper method for HTML escaping escapeHtml(unsafe = '') { const str = String(unsafe); return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;"); } } // Register the custom element safeDefine('league-matches-attention', LeagueMatchesAttention); /** * Validation utilities for the leagueJS */ function validateLeague(data) { const errors = []; if (!data.name) { errors.push('League name is required'); } if (data.settings) { if (typeof data.settings.pointsForWin !== 'undefined') { if (typeof data.settings.pointsForWin !== 'number' || data.settings.pointsForWin < 0) { errors.push('Invalid points settings'); } } if (typeof data.settings.pointsForDraw !== 'undefined') { if (typeof data.settings.pointsForDraw !== 'number' || data.settings.pointsForDraw < 0) { errors.push('Invalid points settings'); } } if (typeof data.settings.pointsForLoss !== 'undefined') { if (typeof data.settings.pointsForLoss !== 'number' || data.settings.pointsForLoss < 0) { errors.push('Invalid points settings'); } } // Validate timesTeamsPlayOther if (typeof data.settings.timesTeamsPlayOther !== 'undefined') { if (typeof data.settings.timesTeamsPlayOther !== 'number' || data.settings.timesTeamsPlayOther < 1 || data.settings.timesTeamsPlayOther > 10) { errors.push('timesTeamsPlayOther must be an integer between 1 and 10'); } } } return { isValid: errors.length === 0, errors }; } function validateTeam(data) { const errors = []; if (!data._id || !data._id.trim()) { errors.push('Team ID is required'); } return { isValid: errors.length === 0, errors }; } function validateMatch(data) { const errors = []; if (!data.homeTeam || !data.homeTeam._id) { errors.push('Home team is required'); } if (!data.awayTeam || !data.awayTeam._id) { errors.push('Away team is required'); } if (data.date && !(data.date instanceof Date) && isNaN(new Date(data.date).getTime())) { errors.push('Invalid date format'); } // Validate result scores if result object exists if (data.result) { if (typeof data.result.homeScore !== 'number' || data.result.homeScore < 0) { errors.push('Home score must be a non-negative number'); } if (typeof data.result.awayScore !== 'number' || data.result.awayScore < 0) { errors.push('Away score must be a non-negative number'); } // Optionally, could add validation for rinkScores structure here if needed } return { isValid: errors.length === 0, errors }; } /** * Generates a GUID (Globally Unique Identifier) * @returns {string} A GUID string in the format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx */ function generateGUID() { // Generate random hex digits const hex = () => Math.floor(Math.random() * 16).toString(16); // Build GUID in format: 8-4-4-4-12 return [ // 8 hex digits Array(8).fill(0).map(hex).join(''), // 4 hex digits Array(4).fill(0).map(hex).join(''), // 4 hex digits Array(4).fill(0).map(hex).join(''), // 4 hex digits Array(4).fill(0).map(hex).join(''), // 12 hex digits Array(12).fill(0).map(hex).join('')].join('-'); } /** * Team model representing a bowls team */ class Team { /** * Create a new Team * @param {Object} data - Team data * @param {string} data._id - Unique identifier for the team * @param {string} [data.name] - Name of the team (defaults to _id if not provided) * @param {Date} [data.createdAt] - Creation date (defaults to current date) * @param {Date} [data.updatedAt] - Last update date (defaults to current date) */ constructor(data) { const validationResult = validateTeam(data); if (!validationResult.isValid) { throw new Error(validationResult.errors[0]); } this._id = data._id || generateGUID(); this.name = data.name || data._id; this.createdAt = data.createdAt || new Date(); this.updatedAt = data.updatedAt || new Date(); } /** * Update team details * @param {Object} updates - Updated team details */ update(updates) { Object.assign(this.details, updates); this.updatedAt = new Date(); } /** * Convert team to JSON * @returns {Object} - JSON representation of the team */ toJSON() { return { _id: this._id, name: this.name, createdAt: this.createdAt, updatedAt: this.updatedAt }; } } /** * Match model representing a bowls match between two teams * @typedef {Object} MatchData * @property {Object} homeTeam - Home team object with _id property * @property {Object} awayTeam - Away team object with _id property * @property {string} [_id] - Unique identifier for the match * @property {Date|string|null} [date] - Match date (can be null for unscheduled matches) * @property {number} [rink] - Assigned rink number for the match * @property {Object} [result] - Optional match result data containing scores * @property {number} [result.homeScore] - Home team's score * @property {number} [result.awayScore] - Away team's score * @property {Array<Object>} [result.rinkScores] - Optional individual rink scores * @property {Date} [createdAt] - Creation date (defaults to current date) * @property {Date} [updatedAt] - Last update date (defaults to current date) */ class Match { /** * Create a new Match * @param {Object} data - Match data * @param {Object} data.homeTeam - Home team object with _id property * @param {Object} data.awayTeam - Away team object with _id property * @param {Date|string|null} [data.date] - Match date (can be null for unscheduled matches) * @param {number} [data.rink] - Assigned rink number for the match * @param {Object} [data.result] - Optional match result data containing scores * @param {number} [data.result.homeScore] - Home team's score * @param {number} [data.result.awayScore] - Away team's score * @param {Array<Object>} [data.result.rinkScores] - Optional individual rink scores * @param {Date} [data.createdAt] - Creation date (defaults to current date) * @param {Date} [data.updatedAt] - Last update date (defaults to current date) */ constructor(data) { const validationResult = validateMatch(data); if (!validationResult.isValid) { throw new Error(validationResult.errors[0]); } if (data.homeTeam._id === data.awayTeam._id) { throw new Error('Home and away teams must be different'); } this._id = data._id || generateGUID(); this.homeTeam = data.homeTeam; this.awayTeam = data.awayTeam; this.date = data.date ? new Date(data.date) : null; this.rink = data.rink || null; this.createdAt = data.createdAt || new Date(); this.updatedAt = data.updatedAt || new Date(); // Process result if scores are provided if (data.result && typeof data.result.homeScore === 'number' && typeof data.result.awayScore === 'number') { this.result = { homeScore: data.result.homeScore, awayScore: data.result.awayScore, rinkScores: data.result.rinkScores || null }; } else { this.result = null; // Ensure result is null if scores are not provided } } /** * Get the home team name * @returns {string} - The name of the home team */ get homeTeamName() { return this.homeTeam.name; } /** * Get the away team name * @returns {string} - The name of the away team */ get awayTeamName() { return this.awayTeam.name; } /** * Determines the winner of the match based on scores. * @returns {string|null} - The name of the winning team, 'draw', or null if no result is set. */ getWinner() { if (!this.result) { return null; } if (this.result.homeScore > this.result.awayScore) { return this.homeTeamName; } if (this.result.awayScore > this.result.homeScore) { return this.awayTeamName; } return 'draw'; } /** * Checks if the match resulted in a draw. * @returns {boolean|null} - True if it's a draw, false otherwise, or null if no result is set. */ isDraw() { if (!this.result) { return null; } return this.result.homeScore === this.result.awayScore; } /** * Set rink scores for an existing match result * @param {Array} rinkScores - Array of rink scores [{homeScore, awayScore}, ...] * @returns {boolean} - True if scores were set, false if no result exists */ setRinkScores(rinkScores) { if (!this.result) return false; this.result.rinkScores = rinkScores; this.updatedAt = new Date(); return true; } /** * Get rink win/draw counts * @returns {Object|null} - Object with rink win counts or null if no rink scores */ getRinkResults() { if (!this.result || !this.result.rinkScores) return null; const rinkResults = { homeWins: 0, awayWins: 0, draws: 0, total: this.result.rinkScores.length }; this.result.rinkScores.forEach(rink => { if (rink.homeScore > rink.awayScore) { rinkResults.homeWins++; } else if (rink.awayScore > rink.homeScore) { rinkResults.awayWins++; } else { rinkResults.draws++; } }); return rinkResults; } /** * Convert match to JSON * @returns {Object} - JSON representation of the match */ toJSON() { const jsonResult = this.result ? { ...this.result, winner: this.getWinner(), isDraw: this.isDraw() } : null; return { _id: this._id, homeTeam: this.homeTeam, awayTeam: this.awayTeam, date: this.date, rink: this.rink, result: jsonResult, createdAt: this.createdAt, updatedAt: this.updatedAt }; } } /** * Find the next valid date based on scheduling pattern */ function _findNextValidDate(fromDate, schedulingPattern, intervalNumber, intervalUnit, selectedDays, isFirstRound = false) { if (isFirstRound) { // For the first round, use the start date as-is if it's valid, otherwise find the next valid date if (schedulingPattern === 'dayOfWeek' && selectedDays.length > 0) { const currentDay = fromDate.getDay(); if (selectedDays.includes(currentDay)) { return new Date(fromDate); } // Start date is not a valid day, find the next one for (let i = 1; i < 7; i++) { const checkDay = (currentDay + i) % 7; if (selectedDays.includes(checkDay)) { const nextDate = new Date(fromDate); nextDate.setDate(nextDate.getDate() + i); return nextDate; } } } return new Date(fromDate); } if (schedulingPattern === 'dayOfWeek' && selectedDays.length > 0) { // Find the next occurrence of one of the selected days const currentDay = fromDate.getDay(); // Find the next selected day (starting from tomorrow) for (let i = 1; i <= 7; i++) { const checkDay = (currentDay + i) % 7; if (selectedDays.includes(checkDay)) { const nextDate = new Date(fromDate); nextDate.setDate(nextDate.getDate() + i); return nextDate; } } } // Use interval pattern (or fallback) return new Date(fromDate); } /** * Get the next scheduling date after a match date */ function _getNextSchedulingDate(currentDate, schedulingPattern, intervalNumber, intervalUnit, selectedDays) { const nextDate = new Date(currentDate); if (schedulingPattern === 'interval') { // Add interval if (intervalUnit === 'weeks') { nextDate.setDate(nextDate.getDate() + intervalNumber * 7); } else { nextDate.setDate(nextDate.getDate() + intervalNumber); } } else if (schedulingPattern === 'dayOfWeek' && selectedDays.length > 0) { // Move to next occurrence of selected days const currentDay = currentDate.getDay(); let daysToAdd = 1; // Start from tomorrow // Find the next selected day for (let i = 1; i <= 7; i++) { const checkDay = (currentDay + i) % 7; if (selectedDays.includes(checkDay)) { daysToAdd = i; break; } } nextDate.setDate(nextDate.getDate() + daysToAdd); } else { // Fallback to weekly nextDate.setDate(nextDate.getDate() + 7); } return nextDate; } /** * Private helper method to assign rinks to matches * @param {object} league - The league instance * @param {Array} matches - Array of match data * @returns {Array} - Array of assigned rink numbers (or null if no rinks assigned) */ function _assignRinksToMatches(league, matches) { if (!league.settings.maxRinksPerSession || league.settings.maxRinksPerSession < 1) { // No rink assignment if maxRinksPerSession is not set or invalid return matches.map(() => null); } const maxRinks = league.settings.maxRinksPerSession; const assignedRinks = []; // Create an array of available rink numbers const availableRinks = Array.from({ length: maxRinks }, (_, i) => i + 1); for (let i = 0; i < matches.length; i++) { if (availableRinks.length === 0) { // If we've run out of available rinks, reset the pool availableRinks.push(...Array.from({ length: maxRinks }, (_, i) => i + 1)); } // Randomly select a rink from available rinks const randomIndex = Math.floor(Math.random() * availableRinks.length); const selectedRink = availableRinks.splice(randomIndex, 1)[0]; assignedRinks.push(selectedRink); } return assignedRinks; } /** * Private helper method to assign dates to matches based on scheduling parameters */ function _assignMatchDates(league, allMatches, startDate, schedulingPattern, intervalNumber, intervalUnit, selectedDays, maxMatchesPerDay) { // Group matches by round for scheduling const matchesByRound = {}; for (const matchData of allMatches) { if (!matchesByRound[matchData.roundKey]) { matchesByRound[matchData.roundKey] = []; } matchesByRound[matchData.roundKey].push(matchData); } // Sort round keys to ensure consistent scheduling order const sortedRoundKeys = Object.keys(matchesByRound).sort(); let currentDate = new Date(startDate); let isFirstRound = true; for (const roundKey of sortedRoundKeys) { const roundMatches = matchesByRound[roundKey]; if (maxMatchesPerDay && roundMatches.length > maxMatchesPerDay) { // Split matches across multiple days if there's a limit let matchIndex = 0; while (matchIndex < roundMatches.length) { const matchesForThisDate = roundMatches.slice(matchIndex, matchIndex + maxMatchesPerDay); // Find the next valid date const validDate = _findNextValidDate(currentDate, schedulingPattern, intervalNumber, intervalUnit, selectedDays, isFirstRound); // Assign rinks for matches on this date const assignedRinks = _assignRinksToMatches(league, matchesForThisDate); // Create matches for this date for (let i = 0; i < matchesForThisDate.length; i++) { const matchData = matchesForThisDate[i]; const match = new Match({ homeTeam: matchData.homeTeam, awayTeam: matchData.awayTeam, date: new Date(validDate), rink: assignedRinks[i] }); if (!league.addMatch(match)) { return false; // If addMatch fails, abort } } matchIndex += maxMatchesPerDay; isFirstRound = false; // Move to next date for remaining matches if (matchIndex < roundMatches.length) { currentDate = _getNextSchedulingDate(validDate, schedulingPattern, intervalNumber, intervalUnit, selectedDays); } } // Set current date for next round if (matchIndex >= roundMatches.length) { currentDate = _getNextSchedulingDate(currentDate, schedulingPattern, intervalNumber, intervalUnit, selectedDays); } } else { // All matches in this round can fit on one day const validDate = _findNextValidDate(currentDate, schedulingPattern, intervalNumber, intervalUnit, selectedDays, isFirstRound); // Assign rinks for matches on this date const assignedRinks = _assignRinksToMatches(league, roundMatches); // Create matches for this date for (let i = 0; i < roundMatches.length; i++) { const matchData = roundMatches[i]; const match = new Match({ homeTeam: matchData.homeTeam, awayTeam: matchData.awayTeam, date: new Date(validDate), rink: assignedRinks[i] }); if (!league.addMatch(match)) { return false; // If addMatch fails, abort } } isFirstRound = false; // Move to next date for next round currentDate = _getNextSchedulingDate(validDate, schedulingPattern, intervalNumber, intervalUnit, selectedDays); } } return true; } /** * Initialise fixtures for the league using a round-robin algorithm. * Each team plays once per match day. Fixtures are scheduled according to the provided scheduling parameters. * Teams will play each other `this.settings.timesTeamsPlayOther` times, with home and away fixtures balanced * as per the cycles of the round-robin generation (e.g., first cycle A vs B, second cycle B vs A). * * @param {object} league - The league instance * @param {Date} [startDate] - The start date for the first round of matches. If null, matches will have null dates. * @param {Object} [schedulingParams] - Advanced scheduling parameters * @param {string} [schedulingParams.schedulingPattern='interval'] - 'interval' or 'dayOfWeek' * @param {number} [schedulingParams.intervalNumber=1] - Number of interval units between match days * @param {string} [schedulingParams.intervalUnit='weeks'] - 'days' or 'weeks' * @param {Array<number>} [schedulingParams.selectedDays] - Array of day numbers (0=Sunday, 1=Monday, etc.) for dayOfWeek pattern * @param {number} [schedulingParams.maxMatchesPerDay] - Maximum matches per day (defaults to maxRinksPerSession if not provided) * @returns {boolean} - True if fixtures were successfully created, false if there are fewer than 2 teams or if a match fails to be added. */ function initialiseFixtures(league, startDate, schedulingParams = {}) { league.matches = []; // Clear any existing matches if (league.teams.length < 2) { return false; // Not enough teams to create fixtures } // Set default scheduling parameters const { schedulingPattern = 'interval', intervalNumber = 1, intervalUnit = 'weeks', selectedDays = [], maxMatchesPerDay = league.settings.maxRinksPerSession || null } = schedulingParams; // Prepare team list for scheduling. Add a dummy "BYE" team if the number of teams is odd. let scheduleTeams = [...league.teams]; const BYE_TEAM_MARKER = { _id: `__BYE_TEAM_INTERNAL_${Date.now()}__`, name: 'BYE' }; // Unique marker for the bye team if (scheduleTeams.length % 2 !== 0) { scheduleTeams.push(BYE_TEAM_MARKER); } const numEffectiveTeams = scheduleTeams.length; // This will now always be even // Calculate the number of rounds needed for all unique pairings once const roundsPerCycle = numEffectiveTeams - 1; // Generate all matches first, then assign dates const allMatches = []; // The round-robin algorithm fixes one team and rotates the others. // We'll fix the last team in the `scheduleTeams` list. const fixedTeam = scheduleTeams[numEffectiveTeams - 1]; // The list of teams that will be rotated. const initialRotatingTeams = scheduleTeams.slice(0, numEffectiveTeams - 1); // Loop for each full set of fixtures (e.g., once for "home" games, once for "away" games if timesTeamsPlayOther is 2) for (let cycle = 0; cycle < league.settings.timesTeamsPlayOther; cycle++) { // For each cycle, re-initialize the rotating teams to ensure the same sequence of pairings. let currentRotatingTeams = [...initialRotatingTeams]; for (let roundNum = 0; roundNum < roundsPerCycle; roundNum++) { const conceptualPairsForThisRound = []; // Stores {team1, team2} for this specific round // 1. Match involving the fixed team (e.g., scheduleTeams[n-1]) // Its opponent is the first team in the current rotated list. const opponentForFixed = currentRotatingTeams[0]; if (fixedTeam._id !== BYE_TEAM_MARKER._id && opponentForFixed._id !== BYE_TEAM_MARKER._id) { // For balanced home/away games, the fixed team should alternate home/away status in each round if (roundNum % 2 === 0) { conceptualPairsForThisRound.push({ team1: opponentForFixed, team2: fixedTeam }); // fixed team is away } else { conceptualPairsForThisRound.push({ team1: fixedTeam, team2: opponentForFixed }); // fixed team is home } } // 2. Other matches from the `currentRotatingTeams` list. // The list has `numEffectiveTeams - 1` elements (an odd number). // The first element `currentRotatingTeams[0]` is already paired with `fixedTeam`. // The remaining elements `currentRotatingTeams[1]` to `currentRotatingTeams[length-1]` are paired up. const rotatingListLength = currentRotatingTeams.length; for (let j = 1; j <= (rotatingListLength - 1) / 2; j++) { const teamA_idx = j; const teamB_idx = rotatingListLength - j; // Pairs j-th from start with j-th from end (0-indexed list) const teamA = currentRotatingTeams[teamA_idx]; const teamB = currentRotatingTeams[teamB_idx]; if (teamA._id !== BYE_TEAM_MARKER._id && teamB._id !== BYE_TEAM_MARKER._id) { conceptualPairsForThisRound.push({ team1: teamA, team2: teamB }); } } // Store matches for this round for (const pair of conceptualPairsForThisRound) { let homeTeam, awayTeam; // For even cycles (0, 2, ...), team1 is home. For odd cycles (1, 3, ...), team2 is home. // This ensures that if pair (X,Y) is generated, cycle 0 schedules X vs Y, cycle 1 schedules Y vs X. if (cycle % 2 === 0) { homeTeam = pair.team1; awayTeam = pair.team2; } else { homeTeam = pair.team2; awayTeam = pair.team1; } allMatches.push({ homeTeam, awayTeam, roundKey: `${cycle}-${roundNum}` }); } // Rotate `currentRotatingTeams` for the next round: the last element moves to the front. if (currentRotatingTeams.length > 1) { // Rotation only makes sense for 2+ teams const lastTeamInRotatingList = currentRotatingTeams.pop(); currentRotatingTeams.unshift(lastTeamInRotatingList); } } } // Now assign dates to matches based on scheduling pattern if (startDate) { _assignMatchDates(league, allMatches, startDate, schedulingPattern, intervalNumber, intervalUnit, selectedDays, maxMatchesPerDay); } else { // No start date provided - create matches without dates but with rinks if configured const assignedRinks = _assignRinksToMatches(league, allMatches); for (let i = 0; i < allMatches.length; i++) { const matchData = allMatches[i]; const match = new Match({ homeTeam: matchData.homeTeam, awayTeam: matchData.awayTeam, date: null, rink: assignedRinks[i] }); if (!league.addMatch(match)) { return false; // If addMatch fails (e.g., duplicate _id), abort. } } } return true; } /** * Returns a set of match IDs that are