commit a93a1194e63fae8da73124d632bfe9befcabec5a Author: jmcqueen Date: Thu Jul 16 16:25:41 2026 -0400 Add Webex booking webhook with occupancy tracking and utilization reports. Track in-meeting occupancy via xAPI polling and workspaceMetrics, store Webex attendee counts for linked meetings, and surface under-utilized room bookings on the dashboard. Co-authored-by: Cursor diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..172fb6a --- /dev/null +++ b/.dockerignore @@ -0,0 +1,9 @@ +node_modules +npm-debug.log +Dockerfile +.dockerignore +.git +.gitignore +README.md +.env +data/ \ No newline at end of file diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..d1f5fd8 --- /dev/null +++ b/.env.example @@ -0,0 +1,14 @@ +PORT=3000 + +# Webex Bot Token (for sending NoShow messages) +WEBEX_BOT_TOKEN=your_webex_bot_bearer_token_here + +# OAuth2 credentials for the Operations / Workspace token (the one used in GET /workspaces) +WEBEX_CLIENT_ID=your_client_id_here +WEBEX_CLIENT_SECRET=your_client_secret_here +WEBEX_REFRESH_TOKEN=your_initial_refresh_token_here # We'll populate this on first run + +# Occupancy tracking (optional) +OCCUPANCY_POLL_INTERVAL_MS=180000 # Poll xAPI every 3 minutes during active meetings +UNDER_UTILIZED_THRESHOLD_PCT=25 # Flag meetings below 25% of room capacity +WORKSPACE_METRICS_END_DELAY_MS=45000 # Wait before fetching workspaceMetrics at meeting end \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..eb25975 --- /dev/null +++ b/.gitignore @@ -0,0 +1,20 @@ +# Dependencies +node_modules/ + +# Secrets and local config +.env +tokens/ + +# Runtime data +data/ +logs/ + +# OS +.DS_Store +Thumbs.db + +# Editor +.idea/ +.vscode/ +*.swp +*.swo diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..ae530fb --- /dev/null +++ b/Dockerfile @@ -0,0 +1,42 @@ +# syntax=docker/dockerfile:1 +FROM node:20-alpine AS base + +# Stage 1: Dependencies +FROM base AS deps +WORKDIR /app +COPY package*.json ./ +RUN npm ci --only=production && \ + # Clean up to keep image small + npm cache clean --force + +# Stage 2: Production runtime +FROM base AS runner +WORKDIR /app + +# Create non-root user for security +RUN addgroup --system --gid 1001 nodejs && \ + adduser --system --uid 1001 --ingroup nodejs expressuser + +# Copy production dependencies +COPY --from=deps /app/node_modules ./node_modules +COPY --from=deps /app/package.json ./ + +# Copy application code +COPY src/ ./src/ +COPY tokens/ ./tokens/ + +# Create data directory for SQLite and set permissions +RUN mkdir -p /app/data && \ + chown -R expressuser:nodejs /app + +USER expressuser + +# Expose port +EXPOSE 1867 + +# Healthcheck +HEALTHCHECK --interval=30s --timeout=5s --start-period=5s --retries=3 \ + CMD node -e "require('http').get('http://localhost:1867/health', (res) => process.exit(res.statusCode === 200 ? 0 : 1))" || exit 1 + +ENV NODE_ENV=production +CMD ["node", "src/server.js"] \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..a55cc05 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,19 @@ +version: '3.9' + +services: + webhook: + build: . + container_name: webex-booking-webhook + restart: unless-stopped + ports: + - "1867:1867" # or whatever port you're using locally + env_file: + - .env + volumes: + - ./data:/app/data # Persistent SQLite DB + - ./tokens:/app/tokens # Read-only tokens + healthcheck: + test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:1867/health"] + interval: 30s + timeout: 5s + retries: 3 \ No newline at end of file diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..7efb9a5 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,1742 @@ +{ + "name": "webex-booking-webhook", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "webex-booking-webhook", + "version": "1.0.0", + "dependencies": { + "axios": "^1.8.0", + "better-sqlite3": "^11.0.0", + "dotenv": "^16.4.0", + "express": "^4.21.0" + }, + "devDependencies": { + "nodemon": "^3.1.0" + } + }, + "node_modules/accepts": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", + "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", + "license": "MIT", + "dependencies": { + "mime-types": "~2.1.34", + "negotiator": "0.6.3" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/anymatch": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", + "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", + "dev": true, + "license": "ISC", + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/array-flatten": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", + "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==", + "license": "MIT" + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", + "license": "MIT" + }, + "node_modules/axios": { + "version": "1.15.0", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.15.0.tgz", + "integrity": "sha512-wWyJDlAatxk30ZJer+GeCWS209sA42X+N5jU2jy6oHTp7ufw8uzUTVFBX9+wTfAlhiJXGS0Bq7X6efruWjuK9Q==", + "license": "MIT", + "dependencies": { + "follow-redirects": "^1.15.11", + "form-data": "^4.0.5", + "proxy-from-env": "^2.1.0" + } + }, + "node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/better-sqlite3": { + "version": "11.10.0", + "resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-11.10.0.tgz", + "integrity": "sha512-EwhOpyXiOEL/lKzHz9AW1msWFNzGc/z+LzeB3/jnFJpxu+th2yqvzsSWas1v9jgs9+xiXJcD5A8CJxAG2TaghQ==", + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "bindings": "^1.5.0", + "prebuild-install": "^7.1.1" + } + }, + "node_modules/binary-extensions": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz", + "integrity": "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/bindings": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz", + "integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==", + "license": "MIT", + "dependencies": { + "file-uri-to-path": "1.0.0" + } + }, + "node_modules/bl": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz", + "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==", + "license": "MIT", + "dependencies": { + "buffer": "^5.5.0", + "inherits": "^2.0.4", + "readable-stream": "^3.4.0" + } + }, + "node_modules/body-parser": { + "version": "1.20.4", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.4.tgz", + "integrity": "sha512-ZTgYYLMOXY9qKU/57FAo8F+HA2dGX7bqGc71txDRC1rS4frdFI5R7NhluHxH6M0YItAP0sHB4uqAOcYKxO6uGA==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "content-type": "~1.0.5", + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "~1.2.0", + "http-errors": "~2.0.1", + "iconv-lite": "~0.4.24", + "on-finished": "~2.4.1", + "qs": "~6.14.0", + "raw-body": "~2.5.3", + "type-is": "~1.6.18", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/brace-expansion": { + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.5.tgz", + "integrity": "sha512-VZznLgtwhn+Mact9tfiwx64fA9erHH/MCXEUfB/0bX/6Fz6ny5EGTXYltMocqg4xFAQZtnO3DHWWXi8RiuN7cQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/braces": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "dev": true, + "license": "MIT", + "dependencies": { + "fill-range": "^7.1.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/buffer": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", + "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.1.13" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/chokidar": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz", + "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==", + "dev": true, + "license": "MIT", + "dependencies": { + "anymatch": "~3.1.2", + "braces": "~3.0.2", + "glob-parent": "~5.1.2", + "is-binary-path": "~2.1.0", + "is-glob": "~4.0.1", + "normalize-path": "~3.0.0", + "readdirp": "~3.6.0" + }, + "engines": { + "node": ">= 8.10.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + } + }, + "node_modules/chownr": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz", + "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==", + "license": "ISC" + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "license": "MIT", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/content-disposition": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", + "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", + "license": "MIT", + "dependencies": { + "safe-buffer": "5.2.1" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.7.tgz", + "integrity": "sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA==", + "license": "MIT" + }, + "node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/decompress-response": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz", + "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==", + "license": "MIT", + "dependencies": { + "mimic-response": "^3.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/deep-extend": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz", + "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==", + "license": "MIT", + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/destroy": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", + "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", + "license": "MIT", + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/dotenv": { + "version": "16.6.1", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz", + "integrity": "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/end-of-stream": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz", + "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==", + "license": "MIT", + "dependencies": { + "once": "^1.4.0" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", + "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-set-tostringtag": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", + "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/expand-template": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz", + "integrity": "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==", + "license": "(MIT OR WTFPL)", + "engines": { + "node": ">=6" + } + }, + "node_modules/express": { + "version": "4.22.1", + "resolved": "https://registry.npmjs.org/express/-/express-4.22.1.tgz", + "integrity": "sha512-F2X8g9P1X7uCPZMA3MVf9wcTqlyNp7IhH5qPCI0izhaOIYXaW9L535tGA3qmjRzpH+bZczqq7hVKxTR4NWnu+g==", + "license": "MIT", + "dependencies": { + "accepts": "~1.3.8", + "array-flatten": "1.1.1", + "body-parser": "~1.20.3", + "content-disposition": "~0.5.4", + "content-type": "~1.0.4", + "cookie": "~0.7.1", + "cookie-signature": "~1.0.6", + "debug": "2.6.9", + "depd": "2.0.0", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "finalhandler": "~1.3.1", + "fresh": "~0.5.2", + "http-errors": "~2.0.0", + "merge-descriptors": "1.0.3", + "methods": "~1.1.2", + "on-finished": "~2.4.1", + "parseurl": "~1.3.3", + "path-to-regexp": "~0.1.12", + "proxy-addr": "~2.0.7", + "qs": "~6.14.0", + "range-parser": "~1.2.1", + "safe-buffer": "5.2.1", + "send": "~0.19.0", + "serve-static": "~1.16.2", + "setprototypeof": "1.2.0", + "statuses": "~2.0.1", + "type-is": "~1.6.18", + "utils-merge": "1.0.1", + "vary": "~1.1.2" + }, + "engines": { + "node": ">= 0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/file-uri-to-path": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz", + "integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==", + "license": "MIT" + }, + "node_modules/fill-range": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", + "dev": true, + "license": "MIT", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/finalhandler": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.2.tgz", + "integrity": "sha512-aA4RyPcd3badbdABGDuTXCMTtOneUCAYH/gxoYRTZlIJdF0YPWuGqiAsIrhNnnqdXGswYk6dGujem4w80UJFhg==", + "license": "MIT", + "dependencies": { + "debug": "2.6.9", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "on-finished": "~2.4.1", + "parseurl": "~1.3.3", + "statuses": "~2.0.2", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/follow-redirects": { + "version": "1.16.0", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.0.tgz", + "integrity": "sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "license": "MIT", + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, + "node_modules/form-data": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.5.tgz", + "integrity": "sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w==", + "license": "MIT", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "es-set-tostringtag": "^2.1.0", + "hasown": "^2.0.2", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fs-constants": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz", + "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==", + "license": "MIT" + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/github-from-package": { + "version": "0.0.0", + "resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz", + "integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==", + "license": "MIT" + }, + "node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "license": "MIT", + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/ignore-by-default": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/ignore-by-default/-/ignore-by-default-1.0.1.tgz", + "integrity": "sha512-Ius2VYcGNk7T90CppJqcIkS5ooHUZyIQK+ClZfMfMNFEF9VSE73Fq+906u/CWu92x4gzZMWOwfFYckPObzdEbA==", + "dev": true, + "license": "ISC" + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ini": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", + "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==", + "license": "ISC" + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-binary-path": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", + "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", + "dev": true, + "license": "MIT", + "dependencies": { + "binary-extensions": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/merge-descriptors": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz", + "integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/methods": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", + "license": "MIT", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mimic-response": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz", + "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/minimatch": { + "version": "10.2.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz", + "integrity": "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "brace-expansion": "^5.0.5" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/mkdirp-classic": { + "version": "0.5.3", + "resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz", + "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==", + "license": "MIT" + }, + "node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "license": "MIT" + }, + "node_modules/napi-build-utils": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-2.0.0.tgz", + "integrity": "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==", + "license": "MIT" + }, + "node_modules/negotiator": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", + "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/node-abi": { + "version": "3.89.0", + "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.89.0.tgz", + "integrity": "sha512-6u9UwL0HlAl21+agMN3YAMXcKByMqwGx+pq+P76vii5f7hTPtKDp08/H9py6DY+cfDw7kQNTGEj/rly3IgbNQA==", + "license": "MIT", + "dependencies": { + "semver": "^7.3.5" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/nodemon": { + "version": "3.1.14", + "resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.1.14.tgz", + "integrity": "sha512-jakjZi93UtB3jHMWsXL68FXSAosbLfY0In5gtKq3niLSkrWznrVBzXFNOEMJUfc9+Ke7SHWoAZsiMkNP3vq6Jw==", + "dev": true, + "license": "MIT", + "dependencies": { + "chokidar": "^3.5.2", + "debug": "^4", + "ignore-by-default": "^1.0.1", + "minimatch": "^10.2.1", + "pstree.remy": "^1.1.8", + "semver": "^7.5.3", + "simple-update-notifier": "^2.0.0", + "supports-color": "^5.5.0", + "touch": "^3.1.0", + "undefsafe": "^2.0.5" + }, + "bin": { + "nodemon": "bin/nodemon.js" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/nodemon" + } + }, + "node_modules/nodemon/node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/nodemon/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-to-regexp": { + "version": "0.1.13", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.13.tgz", + "integrity": "sha512-A/AGNMFN3c8bOlvV9RreMdrv7jsmF9XIfDeCd87+I8RNg6s78BhJxMu69NEMHBSJFxKidViTEdruRwEk/WIKqA==", + "license": "MIT" + }, + "node_modules/picomatch": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", + "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/prebuild-install": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz", + "integrity": "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==", + "deprecated": "No longer maintained. Please contact the author of the relevant native addon; alternatives are available.", + "license": "MIT", + "dependencies": { + "detect-libc": "^2.0.0", + "expand-template": "^2.0.3", + "github-from-package": "0.0.0", + "minimist": "^1.2.3", + "mkdirp-classic": "^0.5.3", + "napi-build-utils": "^2.0.0", + "node-abi": "^3.3.0", + "pump": "^3.0.0", + "rc": "^1.2.7", + "simple-get": "^4.0.0", + "tar-fs": "^2.0.0", + "tunnel-agent": "^0.6.0" + }, + "bin": { + "prebuild-install": "bin.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/proxy-from-env": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-2.1.0.tgz", + "integrity": "sha512-cJ+oHTW1VAEa8cJslgmUZrc+sjRKgAKl3Zyse6+PV38hZe/V6Z14TbCuXcan9F9ghlz4QrFr2c92TNF82UkYHA==", + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/pstree.remy": { + "version": "1.1.8", + "resolved": "https://registry.npmjs.org/pstree.remy/-/pstree.remy-1.1.8.tgz", + "integrity": "sha512-77DZwxQmxKnu3aR542U+X8FypNzbfJ+C5XQDk3uWjWxn6151aIMGthWYRXTqT1E5oJvg+ljaa2OJi+VfvCOQ8w==", + "dev": true, + "license": "MIT" + }, + "node_modules/pump": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz", + "integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==", + "license": "MIT", + "dependencies": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + }, + "node_modules/qs": { + "version": "6.14.2", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.2.tgz", + "integrity": "sha512-V/yCWTTF7VJ9hIh18Ugr2zhJMP01MY7c5kh4J870L7imm6/DIzBsNLTXzMwUA3yZ5b/KBqLx8Kp3uRvd7xSe3Q==", + "license": "BSD-3-Clause", + "dependencies": { + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "2.5.3", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.3.tgz", + "integrity": "sha512-s4VSOf6yN0rvbRZGxs8Om5CWj6seneMwK3oDb4lWDH0UPhWcxwOWw5+qk24bxq87szX1ydrwylIOp2uG1ojUpA==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.4.24", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/rc": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz", + "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==", + "license": "(BSD-2-Clause OR MIT OR Apache-2.0)", + "dependencies": { + "deep-extend": "^0.6.0", + "ini": "~1.3.0", + "minimist": "^1.2.0", + "strip-json-comments": "~2.0.1" + }, + "bin": { + "rc": "cli.js" + } + }, + "node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/readdirp": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", + "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", + "dev": true, + "license": "MIT", + "dependencies": { + "picomatch": "^2.2.1" + }, + "engines": { + "node": ">=8.10.0" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/semver": { + "version": "7.7.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz", + "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/send": { + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/send/-/send-0.19.2.tgz", + "integrity": "sha512-VMbMxbDeehAxpOtWJXlcUS5E8iXh6QmN+BkRX1GARS3wRaXEEgzCcB10gTQazO42tpNIya8xIyNx8fll1OFPrg==", + "license": "MIT", + "dependencies": { + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "~0.5.2", + "http-errors": "~2.0.1", + "mime": "1.6.0", + "ms": "2.1.3", + "on-finished": "~2.4.1", + "range-parser": "~1.2.1", + "statuses": "~2.0.2" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/send/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/serve-static": { + "version": "1.16.3", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.3.tgz", + "integrity": "sha512-x0RTqQel6g5SY7Lg6ZreMmsOzncHFU7nhnRWkKgWuMTu5NN0DR5oruckMqRvacAN9d5w6ARnRBXl9xhDCgfMeA==", + "license": "MIT", + "dependencies": { + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "parseurl": "~1.3.3", + "send": "~0.19.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, + "node_modules/side-channel": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", + "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3", + "side-channel-list": "^1.0.0", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", + "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/simple-concat": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz", + "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/simple-get": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-4.0.1.tgz", + "integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "decompress-response": "^6.0.0", + "once": "^1.3.1", + "simple-concat": "^1.0.0" + } + }, + "node_modules/simple-update-notifier": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/simple-update-notifier/-/simple-update-notifier-2.0.0.tgz", + "integrity": "sha512-a2B9Y0KlNXl9u/vsW6sTIu9vGEpfKu2wRV6l1H3XEas/0gUIzGzBoP/IouTcUQbm9JWZLH3COxyn03TYlFax6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "semver": "^7.5.3" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/strip-json-comments": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", + "integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^3.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/tar-fs": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.4.tgz", + "integrity": "sha512-mDAjwmZdh7LTT6pNleZ05Yt65HC3E+NiQzl672vQG38jIrehtJk/J3mNwIg+vShQPcLF/LV7CMnDW6vjj6sfYQ==", + "license": "MIT", + "dependencies": { + "chownr": "^1.1.1", + "mkdirp-classic": "^0.5.2", + "pump": "^3.0.0", + "tar-stream": "^2.1.4" + } + }, + "node_modules/tar-stream": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz", + "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==", + "license": "MIT", + "dependencies": { + "bl": "^4.0.3", + "end-of-stream": "^1.4.1", + "fs-constants": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^3.1.1" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/touch": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/touch/-/touch-3.1.1.tgz", + "integrity": "sha512-r0eojU4bI8MnHr8c5bNo7lJDdI2qXlWWJk6a9EAFG7vbhTjElYhBVS3/miuE0uOuoLdb8Mc/rVfsmm6eo5o9GA==", + "dev": true, + "license": "ISC", + "bin": { + "nodetouch": "bin/nodetouch.js" + } + }, + "node_modules/tunnel-agent": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", + "integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==", + "license": "Apache-2.0", + "dependencies": { + "safe-buffer": "^5.0.1" + }, + "engines": { + "node": "*" + } + }, + "node_modules/type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "license": "MIT", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/undefsafe": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/undefsafe/-/undefsafe-2.0.5.tgz", + "integrity": "sha512-WxONCrssBM8TSPRqN5EmsjVrsv4A8X12J4ArBiiayv3DyyG3ZlIg6yysuuSYdZsVz3TKcTg2fd//Ujd4CHV1iA==", + "dev": true, + "license": "MIT" + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "license": "MIT" + }, + "node_modules/utils-merge": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", + "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==", + "license": "MIT", + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "license": "ISC" + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..7528ca2 --- /dev/null +++ b/package.json @@ -0,0 +1,23 @@ +{ + "name": "webex-booking-webhook", + "version": "1.0.0", + "description": "Webex Booking Webhook โ†’ SQLite (NoShow handling + notifications)", + "main": "src/server.js", + "type": "module", + "scripts": { + "start": "node src/server.js", + "dev": "nodemon src/server.js", + "docker:build": "docker compose build", + "docker:up": "docker compose up -d", + "docker:logs": "docker compose logs -f" + }, + "dependencies": { + "axios": "^1.8.0", + "better-sqlite3": "^11.0.0", + "dotenv": "^16.4.0", + "express": "^4.21.0" + }, + "devDependencies": { + "nodemon": "^3.1.0" + } +} \ No newline at end of file diff --git a/src/server.js b/src/server.js new file mode 100644 index 0000000..c4edc93 --- /dev/null +++ b/src/server.js @@ -0,0 +1,2414 @@ +import express from 'express'; +import Database from 'better-sqlite3'; +import axios from 'axios'; +import fs from 'fs'; +import path from 'path'; +import dotenv from 'dotenv'; + +dotenv.config(); + +// Create logs directory if it doesn't exist +const LOG_DIR = path.join(process.cwd(), 'logs'); +if (!fs.existsSync(LOG_DIR)) { + fs.mkdirSync(LOG_DIR, { recursive: true }); +} + +const WEBHOOK_LOG_PATH = path.join(LOG_DIR, 'webhook.log'); + +// Simple logger function +function logWebhook(payload) { + const timestamp = new Date().toISOString(); + const logEntry = `[${timestamp}] ${JSON.stringify(payload)}\n\n`; + + // Append to file + fs.appendFile(WEBHOOK_LOG_PATH, logEntry, (err) => { + if (err) console.error('Failed to write to webhook.log:', err.message); + }); + + // Still show a summary in console + console.log(`๐Ÿ“ฅ Webhook logged โ†’ logs/webhook.log | Type: ${payload.type || 'unknown'} | Events: ${payload.events?.length || 0}`); +} + +const app = express(); +app.use(express.json()); + +const PORT = process.env.PORT || 3000; +const DB_PATH = path.join(process.cwd(), 'data', 'active_bookings.db'); +const TOKEN_PATH = path.join(process.cwd(), 'tokens', 'wbxOpsToken.json'); + +const WEBEX_BOT_TOKEN = process.env.WEBEX_BOT_TOKEN; +const CLIENT_ID = process.env.WEBEX_CLIENT_ID; +const CLIENT_SECRET = process.env.WEBEX_CLIENT_SECRET; +const WEBHOOK_AUTH_TOKEN = process.env.WEBHOOK_AUTH_TOKEN; +const OCCUPANCY_POLL_INTERVAL_MS = Number(process.env.OCCUPANCY_POLL_INTERVAL_MS) || 180000; +const UNDER_UTILIZED_THRESHOLD_PCT = Number(process.env.UNDER_UTILIZED_THRESHOLD_PCT) || 25; +const WORKSPACE_METRICS_END_DELAY_MS = Number(process.env.WORKSPACE_METRICS_END_DELAY_MS) || 45000; + +if (!WEBEX_BOT_TOKEN) console.warn('โš ๏ธ WEBEX_BOT_TOKEN not set'); +if (!CLIENT_ID || !CLIENT_SECRET) console.warn('โš ๏ธ Missing WEBEX_CLIENT_ID or CLIENT_SECRET'); +if (!WEBHOOK_AUTH_TOKEN) { + console.error('โŒ WEBHOOK_AUTH_TOKEN is required in .env for security'); + process.exit(1); +} + +// ====================== SQLite Setup ====================== +const db = new Database(DB_PATH); +db.pragma('journal_mode = WAL'); + +db.exec(` + CREATE TABLE IF NOT EXISTS bookings ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + Title TEXT, + MeetingId TEXT NOT NULL, + OrganizerName TEXT, + OrganizerEmail TEXT, + OrganizerId TEXT, + StartTime TEXT, + Duration TEXT, + WorkspaceId TEXT NOT NULL, + DeviceId TEXT, + DeviceName TEXT, + CalendarEmail TEXT, + googleEventId TEXT, + IsRecurring INTEGER DEFAULT 0, + Guests INTEGER DEFAULT 0, + calendarRoomName TEXT, + Cause TEXT, + MinutesFreed INTEGER, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP, + UNIQUE(MeetingId, WorkspaceId) + ); +`); +console.log('โœ… SQLite database ready'); + +// Safe column addition for Start/End tracking +const extraColumns = [ + { name: 'ActualStartTime', type: 'TEXT' }, + { name: 'ActualEndTime', type: 'TEXT' } +]; + +for (const col of extraColumns) { + try { + const exists = db.prepare(`SELECT 1 FROM pragma_table_info('bookings') WHERE name = ?`).get(col.name); + if (!exists) { + db.exec(`ALTER TABLE bookings ADD COLUMN ${col.name} ${col.type}`); + console.log(`โœ… Added column: ${col.name}`); + } + } catch (e) { } +} + +// xAPI / Room Analytics columns +const xapiColumns = [ + { name: 'RoomPeopleCount', type: 'INTEGER' }, + { name: 'MicActivity', type: 'INTEGER' }, // 0-100 + { name: 'CallActive', type: 'INTEGER' }, // 0 or 1 + { name: 'EndedBy', type: 'TEXT' }, // Who ended it (if known) + { name: 'xAPI_LastChecked', type: 'TEXT' } +]; + +for (const col of xapiColumns) { + try { + const exists = db.prepare(`SELECT 1 FROM pragma_table_info('bookings') WHERE name = ?`).get(col.name); + if (!exists) { + db.exec(`ALTER TABLE bookings ADD COLUMN ${col.name} ${col.type}`); + console.log(`โœ… Added xAPI column: ${col.name}`); + } + } catch (e) { } +} +// Safe way to add columns (SQLite doesn't support IF NOT EXISTS on ALTER TABLE) +const columnsToAdd = [ + { name: 'googleEventId', type: 'TEXT' }, + { name: 'calendarRoomName', type: 'TEXT' }, + { name: 'enrichmentStatus', type: 'TEXT' } +]; + +// Webex Meeting Info columns from Google Calendar +const webexColumns = [ + { name: 'webexMeetingId', type: 'TEXT' }, + { name: 'webexSipAddress', type: 'TEXT' }, + { name: 'WebexAttendeeCount', type: 'INTEGER' } +]; + +for (const col of webexColumns) { + try { + const exists = db.prepare(`SELECT 1 FROM pragma_table_info('bookings') WHERE name = ?`).get(col.name); + if (!exists) { + db.exec(`ALTER TABLE bookings ADD COLUMN ${col.name} ${col.type}`); + console.log(`โœ… Added column: ${col.name}`); + } + } catch (e) { + console.log(`Column ${col.name} already exists`); + } +} + +// Webex Password column +try { + const exists = db.prepare(`SELECT 1 FROM pragma_table_info('bookings') WHERE name = ?`).get('webexPassword'); + if (!exists) { + db.exec(`ALTER TABLE bookings ADD COLUMN webexPassword TEXT`); + console.log(`โœ… Added column: webexPassword`); + } +} catch (e) { + console.log(`Column webexPassword already exists`); +} + +// Location / Workspace columns +const locationColumns = [ + { name: 'LocationName', type: 'TEXT' }, + { name: 'Floor', type: 'TEXT' }, + { name: 'RoomType', type: 'TEXT' }, + { name: 'Capacity', type: 'INTEGER' } +]; + +for (const col of locationColumns) { + try { + const exists = db.prepare(`SELECT 1 FROM pragma_table_info('bookings') WHERE name = ?`).get(col.name); + if (!exists) { + db.exec(`ALTER TABLE bookings ADD COLUMN ${col.name} ${col.type}`); + console.log(`โœ… Added column: ${col.name}`); + } + } catch (e) { } +} + +// Occupancy aggregate columns +const occupancyColumns = [ + { name: 'RoomPeopleCountMax', type: 'INTEGER' }, + { name: 'RoomPeopleCountAvg', type: 'REAL' }, + { name: 'RoomPeopleCountSamples', type: 'INTEGER' }, + { name: 'OccupancyPctMax', type: 'REAL' }, + { name: 'OccupancySource', type: 'TEXT' } +]; + +for (const col of occupancyColumns) { + try { + const exists = db.prepare(`SELECT 1 FROM pragma_table_info('bookings') WHERE name = ?`).get(col.name); + if (!exists) { + db.exec(`ALTER TABLE bookings ADD COLUMN ${col.name} ${col.type}`); + console.log(`โœ… Added occupancy column: ${col.name}`); + } + } catch (e) { } +} + +db.exec(` + CREATE TABLE IF NOT EXISTS occupancy_samples ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + MeetingId TEXT NOT NULL, + WorkspaceId TEXT NOT NULL, + sampled_at TEXT NOT NULL, + people_count INTEGER NOT NULL, + source TEXT NOT NULL + ); +`); +console.log('โœ… Occupancy samples table ready'); + +// Workspace lookup cache (to resolve base64 IDs to friendly names) +db.exec(` + CREATE TABLE IF NOT EXISTS workspace_lookup ( + workspaceId TEXT PRIMARY KEY, + displayName TEXT, + locationName TEXT, + floorId TEXT, + roomType TEXT, + capacity INTEGER, + sipAddress TEXT, + lastUpdated DATETIME DEFAULT CURRENT_TIMESTAMP + ); +`); +console.log('โœ… Workspace lookup table ready'); + +/* +// ====================== ONE-TIME FULL LOCATION BACKFILL ====================== +// Run this once to populate both the lookup table and existing bookings +console.log('๐Ÿ”„ Running FULL location backfill...'); + +const uniqueWorkspaces = db.prepare(` + SELECT DISTINCT WorkspaceId FROM bookings +`).all(); + +let cached = 0; +let updated = 0; + +for (const row of uniqueWorkspaces) { + try { + const workspace = await getWorkspaceInfo(row.WorkspaceId); + + if (workspace && workspace.displayName) { + // Cache the workspace + db.prepare(` + INSERT OR REPLACE INTO workspace_lookup + (workspaceId, displayName, locationName, floorId, roomType, capacity, sipAddress) + VALUES (?, ?, ?, ?, ?, ?, ?) + `).run( + row.WorkspaceId, + workspace.displayName, + workspace.locationName, + workspace.floorId, + workspace.roomType, + workspace.capacity, + workspace.sipAddress + ); + cached++; + + // Update all bookings for this workspace + const result = db.prepare(` + UPDATE bookings + SET LocationName = ?, + Floor = ?, + RoomType = ?, + Capacity = ? + WHERE WorkspaceId = ? + `).run( + workspace.displayName, + workspace.floorId, + workspace.roomType, + workspace.capacity, + row.WorkspaceId + ); + + updated += result.changes; + } + } catch (err) { + console.error(` Failed to backfill workspace ${row.WorkspaceId}:`, err.message); + } +} + +console.log(`โœ… Full backfill completed:`); +console.log(` - Cached ${cached} workspaces`); +console.log(` - Updated ${updated} booking records with location data`); +*/ +/* +// === RE-BACKFILL to apply cached names to all bookings === +console.log('๐Ÿ”„ Applying cached workspace names to all bookings...'); + +const result = db.prepare(` + UPDATE bookings + SET LocationName = ( + SELECT displayName + FROM workspace_lookup + WHERE workspace_lookup.workspaceId = bookings.WorkspaceId + ), + Floor = ( + SELECT floorId + FROM workspace_lookup + WHERE workspace_lookup.workspaceId = bookings.WorkspaceId + ), + RoomType = ( + SELECT roomType + FROM workspace_lookup + WHERE workspace_lookup.workspaceId = bookings.WorkspaceId + ), + Capacity = ( + SELECT capacity + FROM workspace_lookup + WHERE workspace_lookup.workspaceId = bookings.WorkspaceId + ) + WHERE LocationName IS NULL OR LocationName LIKE 'Y2lzY29zcGFyazov%' -- only update raw IDs +`).run(); + +console.log(`โœ… Applied friendly names to ${result.changes} bookings`); +*/ +/* +// ====================== TEMPORARY FULL LOCATION BACKFILL ====================== +// Run this once to populate workspace_lookup and update all existing bookings +// You can remove this block after it runs successfully +console.log('๐Ÿ”„ Running FULL location backfill...'); + +const uniqueWorkspaces = db.prepare(` + SELECT DISTINCT WorkspaceId FROM bookings +`).all(); + +let cached = 0; +let updated = 0; + +for (const row of uniqueWorkspaces) { + try { + const workspace = await getWorkspaceInfo(row.WorkspaceId); + + if (workspace && workspace.displayName) { + // 1. Cache the workspace info + db.prepare(` + INSERT OR REPLACE INTO workspace_lookup + (workspaceId, displayName, locationName, floorId, roomType, capacity, sipAddress) + VALUES (?, ?, ?, ?, ?, ?, ?) + `).run( + row.WorkspaceId, + workspace.displayName, + workspace.locationName, + workspace.floorId, + workspace.roomType, + workspace.capacity, + workspace.sipAddress + ); + cached++; + + // 2. Update all bookings for this workspace + const result = db.prepare(` + UPDATE bookings + SET LocationName = ?, + Floor = ?, + RoomType = ?, + Capacity = ? + WHERE WorkspaceId = ? + `).run( + workspace.displayName, + workspace.floorId, + workspace.roomType, + workspace.capacity, + row.WorkspaceId + ); + + updated += result.changes; + } + } catch (err) { + console.error(` Failed to backfill workspace ${row.WorkspaceId}:`, err.message); + } +} + +console.log(`โœ… Full backfill completed:`); +console.log(` - Cached ${cached} workspaces`); +console.log(` - Updated ${updated} booking records with location data`); +*/ +/* +const result = db.prepare(` + UPDATE bookings +SET + LocationName = COALESCE( + (SELECT displayName FROM workspace_lookup WHERE workspace_lookup.workspaceId = bookings.WorkspaceId), + bookings.LocationName + ), + Floor = COALESCE( + (SELECT floorId FROM workspace_lookup WHERE workspace_lookup.workspaceId = bookings.WorkspaceId), + bookings.Floor + ), + RoomType = COALESCE( + (SELECT roomType FROM workspace_lookup WHERE workspace_lookup.workspaceId = bookings.WorkspaceId), + bookings.RoomType + ), + Capacity = COALESCE( + (SELECT capacity FROM workspace_lookup WHERE workspace_lookup.workspaceId = bookings.WorkspaceId), + bookings.Capacity + ) +WHERE LocationName LIKE 'Y2lzY%' + OR Floor LIKE 'Y2lzY%' + OR LocationName IS NULL + OR Floor IS NULL; +`).run(); +*/ + +// Floor lookup cache +db.exec(` + CREATE TABLE IF NOT EXISTS floor_lookup ( + floorId TEXT PRIMARY KEY, + locationId TEXT, + floorNumber INTEGER, + displayName TEXT, + lastUpdated DATETIME DEFAULT CURRENT_TIMESTAMP + ); +`); +console.log('โœ… Floor lookup table ready'); + + +// ====================== TOKEN MANAGEMENT ====================== +async function readTokenFile() { + try { + const raw = fs.readFileSync(TOKEN_PATH, 'utf8'); + return JSON.parse(raw); + } catch (err) { + console.error('โŒ Could not read wbxOpsToken.json'); + throw err; + } +} + +async function writeTokenFile(tokenData) { + fs.writeFileSync(TOKEN_PATH, JSON.stringify(tokenData, null, 2)); + console.log('โœ… Token file updated'); +} + +async function refreshAccessToken() { + const current = await readTokenFile(); + if (!current.refresh_token) throw new Error('No refresh_token found'); + + console.log('๐Ÿ”„ Refreshing Webex access token...'); + + const response = await axios.post('https://webexapis.com/v1/access_token', + new URLSearchParams({ + grant_type: 'refresh_token', + client_id: CLIENT_ID, + client_secret: CLIENT_SECRET, + refresh_token: current.refresh_token, + }), { + headers: { 'Content-Type': 'application/x-www-form-urlencoded' } + } + ); + + const newData = { + access_token: response.data.access_token, + refresh_token: response.data.refresh_token || current.refresh_token, + expires_in: response.data.expires_in, + token_type: response.data.token_type, + expires_at: Date.now() + (response.data.expires_in * 1000) - 60000 // 1 min safety buffer + }; + + await writeTokenFile(newData); + return newData.access_token; +} + +async function getValidAccessToken() { + let tokenData = await readTokenFile(); + if (!tokenData.expires_at || Date.now() > tokenData.expires_at) { + return await refreshAccessToken(); + } + return tokenData.access_token; +} + +// ====================== HELPERS ====================== + +// Small delay helper +const delay = ms => new Promise(resolve => setTimeout(resolve, ms)); + +// Resolve floorId to friendly name using Webex API +async function getFloorInfo(locationId, floorId) { + if (!locationId || !floorId) return null; + + // Check cache first + const cached = db.prepare(` + SELECT displayName, floorNumber + FROM floor_lookup + WHERE floorId = ? + `).get(floorId); + + if (cached) return cached.displayName || `Floor ${cached.floorNumber || ''}`; + + // Not cached โ†’ call Webex API + try { + const token = await getValidAccessToken(); + const url = `https://webexapis.com/v1/locations/${locationId}/floors/${floorId}`; + + const res = await axios.get(url, { + headers: { Authorization: `Bearer ${token}` } + }); + + const floor = res.data || {}; + const friendlyName = floor.displayName || `Floor ${floor.floorNumber || ''}`; + + // Cache it + db.prepare(` + INSERT OR REPLACE INTO floor_lookup (floorId, locationId, floorNumber, displayName) + VALUES (?, ?, ?, ?) + `).run(floorId, locationId, floor.floorNumber, friendlyName); + + console.log(`โœ… Cached floor: ${friendlyName} (${floorId})`); + return friendlyName; + + } catch (err) { + console.error(`Failed to resolve floor ${floorId}:`, err.response?.data || err.message); + return null; + } +} + +async function getWorkspaceInfo(workspaceId) { + if (!workspaceId) return { displayName: 'Unknown Room', calendarEmail: null }; + + // Check cache + const cached = db.prepare(` + SELECT displayName, locationName, floorId, roomType, capacity, sipAddress, calendarEmail + FROM workspace_lookup + WHERE workspaceId = ? + `).get(workspaceId); + + if (cached) { + // Update existing bookings with the cached calendarEmail (this fixes old records) + if (cached.calendarEmail) { + db.prepare(` + UPDATE bookings + SET CalendarEmail = ? + WHERE WorkspaceId = ? AND (CalendarEmail IS NULL OR CalendarEmail = '') + `).run(cached.calendarEmail, workspaceId); + } + + return { + displayName: cached.displayName || 'Unknown Room', + locationName: cached.locationName, + floorId: cached.floorId, + roomType: cached.roomType, + capacity: cached.capacity, + sipAddress: cached.sipAddress, + calendarEmail: cached.calendarEmail || null + }; + } + + // Fresh fetch from Webex + try { + const token = await getValidAccessToken(); + const res = await axios.get(`https://webexapis.com/v1/workspaces/${workspaceId}`, { + headers: { Authorization: `Bearer ${token}` } + }); + + const ws = res.data || {}; + + const data = { + displayName: ws.displayName || ws.name || 'Unknown Room', + locationName: ws.workspaceLocationId ? ws.workspaceLocationId.split('/').pop() : null, + floorId: ws.floorId ? ws.floorId.split('/').pop() : null, + roomType: ws.type || null, + capacity: ws.capacity || null, + sipAddress: ws.sipAddress || null, + calendarEmail: ws.calendar?.emailAddress || null + }; + + // Cache it + db.prepare(` + INSERT OR REPLACE INTO workspace_lookup + (workspaceId, displayName, locationName, floorId, roomType, capacity, sipAddress, calendarEmail) + VALUES (?, ?, ?, ?, ?, ?, ?, ?) + `).run( + workspaceId, + data.displayName, + data.locationName, + data.floorId, + data.roomType, + data.capacity, + data.sipAddress, + data.calendarEmail + ); + + // Also update any existing bookings immediately + if (data.calendarEmail) { + db.prepare(` + UPDATE bookings + SET CalendarEmail = ? + WHERE WorkspaceId = ? + `).run(data.calendarEmail, workspaceId); + } + + console.log(`โœ… Cached workspace: ${data.displayName} | Calendar: ${data.calendarEmail || 'none'}`); + return data; + + } catch (err) { + console.error(`Failed to fetch workspace ${workspaceId}:`, err.message); + return { displayName: 'Unknown Room', calendarEmail: null }; + } +} + +async function getXAPIRoomData(deviceId) { + if (!deviceId) { + return { peopleCount: 0, micActivity: 0, callActive: 0, endedBy: "No Device", xAPI_LastChecked: new Date().toISOString() }; + } + + const token = await getValidAccessToken(); + + try { + const headers = { Authorization: `Bearer ${token}` }; + + const peopleRes = await axios.get('https://webexapis.com/v1/xapi/status/', { + headers, + params: { deviceId, name: "RoomAnalytics.PeopleCount.Current" } + }); + console.log(`People: `, JSON.stringify(peopleRes.data)); + const voiceRes = await axios.get('https://webexapis.com/v1/xapi/status/', { + headers, + params: { deviceId, name: "Audio.Microphones.VoiceActivityDetector.Activity" } + }); + console.log(`Mic: `, JSON.stringify(voiceRes.data)); + const callRes = await axios.get('https://webexapis.com/v1/xapi/status/', { + headers, + params: { deviceId, name: "SystemUnit.State.NumberOfActiveCalls" } + }); + console.log(`Call Active: `, JSON.stringify(callRes.data)); + const peopleCount = peopleRes.data?.result?.RoomAnalytics?.PeopleCount?.Current || 0; + const voiceActivity = voiceRes.data?.result?.Audio?.Microphones?.VoiceActivityDetector?.Activity || false; + const activeCalls = callRes.data?.result?.SystemUnit?.State?.NumberOfActiveCalls || 0; + + return { + peopleCount: Math.max(0, peopleCount), // -1 becomes 0 + micActivity: (voiceActivity === true || voiceActivity === "True") ? 1 : 0, + callActive: activeCalls > 0, + endedBy: "xAPI", + xAPI_LastChecked: new Date().toISOString() + }; + + } catch (err) { + console.error(`xAPI failed for device ${deviceId}:`, err.response?.data || err.message); + return { + peopleCount: 0, + micActivity: 0, + callActive: 0, + endedBy: "xAPI_Failed", + xAPI_LastChecked: new Date().toISOString() + }; + } +} + +// ====================== OCCUPANCY TRACKING ====================== +let occupancyPollInProgress = false; +let workspaceMetricsScopeWarned = false; +let meetingParticipantsScopeWarned = false; + +const insertOccupancySample = db.prepare(` + INSERT INTO occupancy_samples (MeetingId, WorkspaceId, sampled_at, people_count, source) + VALUES (?, ?, ?, ?, ?) +`); + +const updateRunningOccupancy = db.prepare(` + UPDATE bookings + SET RoomPeopleCountMax = ?, + RoomPeopleCountAvg = ?, + RoomPeopleCountSamples = ? + WHERE (MeetingId = ? OR Id = ?) AND WorkspaceId = ? +`); + +function recordOccupancySample(meetingId, workspaceId, peopleCount, source) { + insertOccupancySample.run(meetingId, workspaceId, new Date().toISOString(), peopleCount, source); +} + +function updateRunningOccupancyAggregates(meetingId, workspaceId, newCount) { + const booking = db.prepare(` + SELECT RoomPeopleCountMax, RoomPeopleCountAvg, RoomPeopleCountSamples + FROM bookings + WHERE (MeetingId = ? OR Id = ?) AND WorkspaceId = ? + `).get(meetingId, meetingId, workspaceId); + + const samples = booking?.RoomPeopleCountSamples || 0; + const existingMax = booking?.RoomPeopleCountMax ?? 0; + const existingAvg = booking?.RoomPeopleCountAvg ?? 0; + + const newMax = Math.max(existingMax, newCount); + const newAvg = samples === 0 ? newCount : ((existingAvg * samples) + newCount) / (samples + 1); + const newSamples = samples + 1; + + updateRunningOccupancy.run(newMax, newAvg, newSamples, meetingId, meetingId, workspaceId); + return { max: newMax, avg: newAvg, samples: newSamples }; +} + +function computeTimeWeightedAvg(samples, windowStart, windowEnd) { + if (!samples || samples.length === 0) return { avg: null, max: null }; + + const startMs = new Date(windowStart).getTime(); + const endMs = new Date(windowEnd).getTime(); + const sorted = [...samples].sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime()); + + let max = 0; + let weightedSum = 0; + let totalWeight = 0; + + for (let i = 0; i < sorted.length; i++) { + const ts = new Date(sorted[i].timestamp).getTime(); + const value = sorted[i].value; + max = Math.max(max, value); + + const nextTs = i < sorted.length - 1 ? new Date(sorted[i + 1].timestamp).getTime() : endMs; + const duration = Math.max(0, Math.min(nextTs, endMs) - Math.max(ts, startMs)); + if (duration > 0) { + weightedSum += value * duration; + totalWeight += duration; + } + } + + if (totalWeight === 0) { + max = Math.max(...sorted.map(s => s.value)); + const simpleAvg = sorted.reduce((sum, s) => sum + s.value, 0) / sorted.length; + return { avg: simpleAvg, max }; + } + + return { avg: weightedSum / totalWeight, max }; +} + +async function getWorkspacePeopleMetrics(workspaceId, from, to) { + if (!workspaceId || !from || !to) { + return { samples: [], avg: null, max: null, available: false }; + } + + try { + const token = await getValidAccessToken(); + const res = await axios.get('https://webexapis.com/v1/workspaceMetrics', { + headers: { Authorization: `Bearer ${token}` }, + params: { + workspaceId, + metricName: 'peopleCount', + aggregation: 'none', + from, + to, + sortBy: 'oldestFirst' + } + }); + + const items = res.data?.items || []; + const samples = items.map(item => ({ + timestamp: item.timestamp, + value: Math.max(0, item.value ?? 0) + })); + + const { avg, max } = computeTimeWeightedAvg(samples, from, to); + return { samples, avg, max, available: true }; + + } catch (err) { + if (err.response?.status === 403 && !workspaceMetricsScopeWarned) { + workspaceMetricsScopeWarned = true; + console.warn('โš ๏ธ workspaceMetrics requires spark-admin:workspace_metrics_read scope; falling back to xAPI-only'); + } else if (err.response?.status !== 403) { + console.error(`workspaceMetrics failed for ${workspaceId}:`, err.response?.data || err.message); + } + return { samples: [], avg: null, max: null, available: false }; + } +} + +async function finalizeMeetingOccupancy(booking, workspaceId, meetingId, endPeopleCount, isNoShow) { + if (isNoShow) { + db.prepare(` + UPDATE bookings + SET RoomPeopleCountMax = 0, + RoomPeopleCountAvg = 0, + RoomPeopleCountSamples = 0, + OccupancyPctMax = 0, + OccupancySource = 'none' + WHERE (MeetingId = ? OR Id = ?) AND WorkspaceId = ? + `).run(meetingId, meetingId, workspaceId); + return; + } + + const xapiMax = booking.RoomPeopleCountMax ?? 0; + const xapiAvg = booking.RoomPeopleCountAvg ?? 0; + const xapiSamples = booking.RoomPeopleCountSamples ?? 0; + const endCount = endPeopleCount ?? 0; + + recordOccupancySample(meetingId, workspaceId, endCount, 'xapi_end'); + + const from = booking.ActualStartTime || booking.StartTime; + const to = booking.ActualEndTime || new Date().toISOString(); + + await delay(WORKSPACE_METRICS_END_DELAY_MS); + + let wmData = await getWorkspacePeopleMetrics(workspaceId, from, to); + if (wmData.available && wmData.samples.length === 0) { + await delay(WORKSPACE_METRICS_END_DELAY_MS); + wmData = await getWorkspacePeopleMetrics(workspaceId, from, to); + } + + for (const sample of wmData.samples) { + insertOccupancySample.run(meetingId, workspaceId, sample.timestamp, sample.value, 'workspace_metrics'); + } + + let finalMax = Math.max(xapiMax, endCount); + let finalAvg; + let source; + + if (xapiSamples >= 2) { + if (wmData.max !== null) finalMax = Math.max(finalMax, wmData.max); + finalAvg = xapiAvg; + source = wmData.available && wmData.samples.length > 0 ? 'hybrid' : 'xapi'; + } else if (wmData.available && wmData.samples.length > 0) { + finalMax = Math.max(finalMax, wmData.max ?? 0); + finalAvg = wmData.avg ?? endCount; + source = 'workspaceMetrics'; + } else if (xapiSamples >= 1) { + finalAvg = xapiAvg; + source = 'xapi'; + } else { + finalMax = endCount; + finalAvg = endCount; + source = endCount > 0 ? 'xapi' : 'none'; + } + + const capacity = booking.Capacity || 0; + const occupancyPctMax = capacity > 0 ? Math.round((finalMax / capacity) * 1000) / 10 : null; + + db.prepare(` + UPDATE bookings + SET RoomPeopleCountMax = ?, + RoomPeopleCountAvg = ?, + OccupancyPctMax = ?, + OccupancySource = ? + WHERE (MeetingId = ? OR Id = ?) AND WorkspaceId = ? + `).run( + finalMax, + Math.round(finalAvg * 10) / 10, + occupancyPctMax, + source, + meetingId, meetingId, workspaceId + ); + + console.log(`๐Ÿ“Š Occupancy finalized - Max: ${finalMax}, Avg: ${finalAvg}, Pct: ${occupancyPctMax}%, Source: ${source}`); +} + +async function resolveWebexMeetingInstanceId(webexMeetingId, startTime, hostEmail) { + if (!webexMeetingId) return null; + + const tryIds = [webexMeetingId]; + if (/^\d+$/.test(String(webexMeetingId))) { + try { + const token = await getValidAccessToken(); + const res = await axios.get('https://webexapis.com/v1/meetings', { + headers: { Authorization: `Bearer ${token}` }, + params: { meetingNumber: webexMeetingId, max: 1 } + }); + const match = res.data?.items?.[0]; + if (match?.id) tryIds.unshift(match.id); + } catch (err) { + // fall through to direct id + } + } + + if (startTime && hostEmail) { + try { + const token = await getValidAccessToken(); + const startMs = new Date(startTime).getTime(); + const from = new Date(startMs - 60 * 60 * 1000).toISOString(); + const to = new Date(startMs + 4 * 60 * 60 * 1000).toISOString(); + const res = await axios.get('https://webexapis.com/v1/meetings', { + headers: { Authorization: `Bearer ${token}` }, + params: { from, to, hostEmail, max: 25 } + }); + const match = (res.data?.items || []).find(m => + m.id === webexMeetingId || + String(m.meetingNumber) === String(webexMeetingId) + ); + if (match?.id && !tryIds.includes(match.id)) tryIds.unshift(match.id); + } catch (err) { + // fall through + } + } + + return tryIds[0]; +} + +async function fetchWebexAttendeeCount(webexMeetingId, startTime = null, hostEmail = null) { + if (!webexMeetingId) return null; + + const meetingInstanceId = await resolveWebexMeetingInstanceId(webexMeetingId, startTime, hostEmail); + if (!meetingInstanceId) return null; + + try { + const token = await getValidAccessToken(); + const uniqueAttendees = new Set(); + let url = 'https://webexapis.com/v1/meetingParticipants'; + let params = { meetingId: meetingInstanceId, max: 100 }; + + while (url) { + const res = await axios.get(url, { + headers: { Authorization: `Bearer ${token}` }, + params: url === 'https://webexapis.com/v1/meetingParticipants' ? params : undefined + }); + + for (const participant of res.data?.items || []) { + uniqueAttendees.add(participant.id || participant.email || participant.displayName); + } + + const next = res.data?.links?.next || res.data?.next; + if (next) { + url = next; + params = undefined; + } else { + url = null; + } + } + + return uniqueAttendees.size; + + } catch (err) { + if (err.response?.status === 403 && !meetingParticipantsScopeWarned) { + meetingParticipantsScopeWarned = true; + console.warn('โš ๏ธ meetingParticipants requires meeting:admin_participants_read scope; attendee counts unavailable'); + } else if (err.response?.status !== 403 && err.response?.status !== 404) { + console.error(`meetingParticipants failed for ${meetingInstanceId}:`, err.response?.data || err.message); + } + return null; + } +} + +function getMeetingWebexMeta(meetingId) { + return db.prepare(` + SELECT MeetingId, StartTime, + MAX(webexMeetingId) as webexMeetingId, + MAX(WebexAttendeeCount) as WebexAttendeeCount, + MAX(OrganizerEmail) as OrganizerEmail, + MAX(ActualEndTime) as ActualEndTime + FROM bookings + WHERE MeetingId = ? + GROUP BY MeetingId, StartTime + ORDER BY StartTime DESC + LIMIT 1 + `).get(meetingId); +} + +async function storeWebexAttendeeCount(meetingId, startTime, webexMeetingId, hostEmail = null) { + if (!webexMeetingId) return null; + + const existing = db.prepare(` + SELECT MAX(WebexAttendeeCount) as count + FROM bookings + WHERE MeetingId = ? AND StartTime = ? AND WebexAttendeeCount IS NOT NULL + `).get(meetingId, startTime); + if (existing?.count != null) return existing.count; + + await delay(WORKSPACE_METRICS_END_DELAY_MS); + let count = await fetchWebexAttendeeCount(webexMeetingId, startTime, hostEmail); + if (count === null) { + await delay(WORKSPACE_METRICS_END_DELAY_MS); + count = await fetchWebexAttendeeCount(webexMeetingId, startTime, hostEmail); + } + + if (count !== null) { + db.prepare(` + UPDATE bookings + SET WebexAttendeeCount = ? + WHERE MeetingId = ? AND StartTime = ? + `).run(count, meetingId, startTime); + console.log(`๐Ÿ‘ฅ WebexAttendeeCount saved: ${count} for meeting ${meetingId}`); + } + + return count; +} + +async function syncWebexAttendeeCountForMeeting(meetingId, workspaceId = null) { + const meta = workspaceId + ? db.prepare(` + SELECT MeetingId, StartTime, + webexMeetingId, WebexAttendeeCount, OrganizerEmail, ActualEndTime + FROM bookings + WHERE (MeetingId = ? OR Id = ?) AND WorkspaceId = ? + `).get(meetingId, meetingId, workspaceId) + : getMeetingWebexMeta(meetingId); + + if (!meta?.webexMeetingId || !meta.ActualEndTime || meta.WebexAttendeeCount != null) { + return meta?.WebexAttendeeCount ?? null; + } + return storeWebexAttendeeCount( + meta.MeetingId, + meta.StartTime, + meta.webexMeetingId, + meta.OrganizerEmail + ); +} + +async function backfillWebexAttendeeCounts(meetings) { + for (const meeting of meetings) { + if (!meeting.webexMeetingId || meeting.WebexAttendeeCount != null) continue; + const count = await storeWebexAttendeeCount( + meeting.MeetingId, + meeting.StartTime, + meeting.webexMeetingId, + meeting.HostEmail + ); + if (count !== null) meeting.WebexAttendeeCount = count; + await delay(300); + } +} + +async function pollActiveMeetingOccupancy() { + if (occupancyPollInProgress) return; + occupancyPollInProgress = true; + + try { + const activeMeetings = db.prepare(` + SELECT MeetingId, WorkspaceId, DeviceId + FROM bookings + WHERE ActualStartTime IS NOT NULL + AND ActualEndTime IS NULL + AND DeviceId IS NOT NULL + AND (Cause IS NULL OR Cause = '') + `).all(); + + for (const meeting of activeMeetings) { + try { + const xapiData = await getXAPIRoomData(meeting.DeviceId); + recordOccupancySample(meeting.MeetingId, meeting.WorkspaceId, xapiData.peopleCount, 'xapi_poll'); + updateRunningOccupancyAggregates(meeting.MeetingId, meeting.WorkspaceId, xapiData.peopleCount); + await delay(500); + } catch (err) { + console.error(`Occupancy poll failed for ${meeting.MeetingId}:`, err.message); + } + } + + if (activeMeetings.length > 0) { + console.log(`๐Ÿ“ก Occupancy poll: ${activeMeetings.length} active meeting(s)`); + } + } finally { + occupancyPollInProgress = false; + } +} + +async function sendNoShowMessage(booking, minutesFreed) { + if (!WEBEX_BOT_TOKEN) return; + + const markdown = `**Meeting No Show** +Title: ${booking.Title || 'N/A'} +Organizer: ${booking.OrganizerName} (${booking.OrganizerEmail}) +Starting: ${new Date(booking.StartTime).toLocaleString()} +Duration: ${booking.Duration} min +MinutesFreed: ${minutesFreed} min +Recurring: ${Boolean(booking.IsRecurring)} +Workspace: ${booking.DeviceName || 'N/A'}`; + + try { + await axios.post('https://webexapis.com/v1/messages', { + toPersonEmail: 'mcqueenj@ae.com', + markdown + }, { + headers: { + Authorization: `Bearer ${WEBEX_BOT_TOKEN}`, + 'Content-Type': 'application/json' + } + }); + console.log('โœ… NoShow notification sent to Webex'); + } catch (err) { + console.error('โŒ Webex message failed:', err.response?.data?.message || err.message); + } +} + +// ====================== AUTH MIDDLEWARE ====================== +function authenticateWebhook(req, res, next) { + const authHeader = req.headers.authorization; + if (!authHeader || authHeader !== `${WEBHOOK_AUTH_TOKEN}`) { + console.warn(`โŒ Unauthorized webhook attempt from ${req.ip}`); + return res.status(401).send('Unauthorized'); + } + next(); +} + +// ====================== ROUTES ====================== +app.get('/health', (req, res) => res.status(200).send('OK')); + +// Protected Webhook Endpoint - Keep all bookings for analytics +app.post('/bookings', authenticateWebhook, async (req, res) => { + const timestamp = new Date().toISOString(); + console.log(`[${timestamp}] ๐Ÿ“ฅ Received webhook - Type: ${req.body.type}, Events: ${req.body.events?.length || 0}`); + + try { + const payload = req.body; + + if (payload.type === 'healthCheck' || !payload.events) { + console.log(`[${timestamp}] โœ… Health check received`); + return res.status(200).send('OK'); + } + + const incomingEvents = payload.events || []; + let processed = 0; + + for (const event of incomingEvents) { + if (!event.key || !event.value) continue; + + const eventKey = event.key; + const value = event.value; + const workspaceId = payload.workspaceId; + const deviceId = payload.deviceId; + const meetingId = value.MeetingId || value.Id || 'unknown'; + const cause = (value.Cause || value.cause || '').toLowerCase().trim(); + + console.log(`[${timestamp}] โ†’ ${eventKey} | MeetingId: ${meetingId} | Cause: "${value.Cause || value.cause || 'none'}"`); + + if (eventKey === 'Bookings.BookingCreated') { + try { + const workspace = await getWorkspaceInfo(workspaceId); + const calendarEmail = workspace.calendarEmail || null; + + const exists = db.prepare(`SELECT 1 FROM bookings WHERE MeetingId = ? AND WorkspaceId = ?`) + .get(meetingId, workspaceId); + + if (!exists) { + db.prepare(` + INSERT INTO bookings ( + Title, MeetingId, OrganizerName, OrganizerEmail, OrganizerId, + StartTime, Duration, WorkspaceId, DeviceId, DeviceName, + CalendarEmail, IsRecurring, Guests, enrichmentStatus, + LocationName, Floor, RoomType, Capacity + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + `).run( + value.Title, + meetingId, + value.OrganizerName, + value.OrganizerEmail, + value.OrganizerId, + value.StartTime, + value.Duration?.toString(), + workspaceId, + deviceId, + workspace.displayName || 'Unknown Room', + calendarEmail, + value.IsRecurring ? 1 : 0, + 0, + null, + workspace.displayName, + workspace.floorId, + workspace.roomType, + workspace.capacity + ); + console.log(`[${timestamp}] โœ… Added booking: ${meetingId}`); + processed++; + } + } catch (err) { + console.error(`[${timestamp}] โŒ BookingCreated error:`, err.message); + } + } + else if (eventKey === 'Bookings.Start') { + db.prepare(` + UPDATE bookings SET ActualStartTime = ?, + RoomPeopleCountMax = 0, + RoomPeopleCountAvg = 0, + RoomPeopleCountSamples = 0 + WHERE (MeetingId = ? OR Id = ?) AND WorkspaceId = ? + `).run(value.timestamp || timestamp, meetingId, meetingId, workspaceId); + console.log(`[${timestamp}] ๐Ÿ•’ Recorded ActualStartTime for ${meetingId}`); + } + else if (eventKey === 'Bookings.End' || eventKey === 'Bookings.Deleted') { + const isNoShow = cause === 'noshow'; + + try { + const existing = db.prepare(` + SELECT Cause FROM bookings + WHERE (MeetingId = ? OR Id = ?) AND WorkspaceId = ? + `).get(meetingId, meetingId, workspaceId); + + if (existing && existing.Cause === 'NoShow') { + console.log(`[${timestamp}] โญ๏ธ Skipping - already marked as NoShow for ${meetingId}`); + } + else if (isNoShow) { + // Mark as NoShow and capture xAPI with delay + db.prepare(` + UPDATE bookings + SET ActualEndTime = ?, MinutesFreed = ?, + Cause = 'NoShow', Guests = 0, enrichmentStatus = 'success' + WHERE (MeetingId = ? OR Id = ?) AND WorkspaceId = ? + `).run( + value.timestamp || timestamp, + value.MinutesFreed || 0, + meetingId, meetingId, workspaceId + ); + + const booking = db.prepare(`SELECT * FROM bookings WHERE (MeetingId = ? OR Id = ?) AND WorkspaceId = ?`) + .get(meetingId, meetingId, workspaceId); + + if (booking) await sendNoShowMessage(booking, value.MinutesFreed || 0); + console.log(`[${timestamp}] โœ… NoShow recorded for ${meetingId}`); + } + else { + // NORMAL END / DELETED โ†’ Just mark as ended, DO NOT DELETE + db.prepare(` + UPDATE bookings + SET ActualEndTime = ?, Cause = 'Ended' + WHERE (MeetingId = ? OR Id = ?) AND WorkspaceId = ? + `).run( + value.timestamp || timestamp, + meetingId, meetingId, workspaceId + ); + console.log(`[${timestamp}] โœ… Normal meeting ended (kept for analytics): ${meetingId}`); + } + + // Always capture xAPI data at end of meeting + if (deviceId) { + console.log(`[${timestamp}] ๐Ÿ“ก Fetching xAPI data for device ${deviceId}`); + if (isNoShow) await new Promise(r => setTimeout(r, 3000)); // 3s delay for NoShow + + const xapiData = await getXAPIRoomData(deviceId); + + db.prepare(` + UPDATE bookings + SET RoomPeopleCount = ?, MicActivity = ?, CallActive = ?, xAPI_LastChecked = ? + WHERE (MeetingId = ? OR Id = ?) AND WorkspaceId = ? + `).run( + xapiData.peopleCount, + xapiData.micActivity, + xapiData.callActive ? 1 : 0, + xapiData.xAPI_LastChecked, + meetingId, meetingId, workspaceId + ); + + const booking = db.prepare(`SELECT * FROM bookings WHERE (MeetingId = ? OR Id = ?) AND WorkspaceId = ?`) + .get(meetingId, meetingId, workspaceId); + + if (booking) { + await finalizeMeetingOccupancy(booking, workspaceId, meetingId, xapiData.peopleCount, isNoShow); + } + + console.log(`[${timestamp}] ๐Ÿ“Š xAPI saved - People: ${xapiData.peopleCount}, Mic: ${xapiData.micActivity}, Call: ${xapiData.callActive}`); + } + + if (!isNoShow) { + await syncWebexAttendeeCountForMeeting(meetingId, workspaceId); + } + } catch (err) { + console.error(`[${timestamp}] โŒ Error processing ${eventKey}:`, err.message); + } + } + } + + console.log(`[${timestamp}] โœ… Finished processing webhook`); + res.status(200).send('OK'); + + } catch (err) { + console.error(`[${new Date().toISOString()}] โŒ Webhook error:`, err.message); + res.status(500).send('Internal error'); + } +}); + +// ====================== REPORT HELPERS ====================== +function escapeHtml(value) { + return String(value ?? '') + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"'); +} + +function formatMinutes(mins) { + const n = Number(mins) || 0; + if (n < 60) return `${n} min`; + const h = Math.floor(n / 60); + const m = n % 60; + return m ? `${h}h ${m}m` : `${h}h`; +} + +function formatMeetingDateTime(iso) { + if (!iso) return 'โ€”'; + const d = new Date(iso); + if (Number.isNaN(d.getTime())) return String(iso); + return d.toLocaleString(); +} + +function csvEscape(val) { + if (val == null) return ''; + const s = String(val); + if (s.includes(',') || s.includes('"') || s.includes('\n')) { + return `"${s.replace(/"/g, '""')}"`; + } + return s; +} + +function rowsToCsv(headers, rows) { + let csv = headers.join(',') + '\n'; + for (const row of rows) { + csv += headers.map(h => csvEscape(row[h])).join(',') + '\n'; + } + return csv; +} + +const REPORT_CSS = ` + body { font-family: Arial, sans-serif; margin: 20px; background: #f4f6f9; color: #1f2937; } + h1 { color: #1e3a8a; margin-bottom: 4px; } + h2 { color: #1e3a8a; margin-top: 32px; } + .muted { color: #555; } + .nav { display: flex; flex-wrap: wrap; gap: 10px; margin: 16px 0 8px; } + .nav a, .btn { + display: inline-block; background: #1e40af; color: white; padding: 10px 16px; + border-radius: 6px; text-decoration: none; font-size: 14px; border: none; cursor: pointer; + } + .nav a.secondary, .btn.secondary { background: #64748b; } + .nav a:hover, .btn:hover { background: #1e3a8a; } + .summary-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 16px; margin: 20px 0; } + .card { background: white; padding: 18px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.08); text-align: center; } + .card h2 { margin: 0; font-size: 2.1em; color: #1e40af; } + .card p { margin: 8px 0 0; color: #555; font-size: 0.92em; } + .card.accent h2 { color: #b45309; } + table { width: 100%; border-collapse: collapse; background: white; box-shadow: 0 2px 10px rgba(0,0,0,0.08); margin-top: 12px; font-size: 14px; } + th, td { padding: 10px 12px; text-align: left; border-bottom: 1px solid #e5e7eb; vertical-align: top; } + th { background: #1e40af; color: white; position: sticky; top: 0; } + tr:hover { background: #f1f5f9; } + .dates { max-width: 420px; white-space: normal; word-break: break-word; color: #374151; font-size: 12px; } + .rate-high { color: #b91c1c; font-weight: 600; } + .rate-mid { color: #b45309; font-weight: 600; } + .footer-links { margin-top: 28px; color: #555; } + .footer-links a { color: #1e40af; text-decoration: none; margin-right: 16px; } +`; + +// Recurring series: flagged recurring OR Google recurring event id (_R...) +const RECURRING_WHERE = `(IsRecurring = 1 OR (googleEventId IS NOT NULL AND googleEventId LIKE '%_R%'))`; + +// Per-room filter: only normally-ended bookings (excludes NoShow rows) +const UNDER_UTILIZED_ROOM_WHERE = `(Cause = 'Ended' OR (Cause IS NULL AND ActualEndTime IS NOT NULL)) + AND Cause != 'NoShow' + AND Capacity > 0 + AND RoomPeopleCountMax IS NOT NULL`; + +// Meetings eligible for occupancy reports: no room in the meeting was a NoShow +const NON_NOSHOW_MEETING_SUBQUERY = ` + SELECT MeetingId, StartTime + FROM bookings + WHERE datetime(StartTime) > datetime('now', '-30 days') + GROUP BY MeetingId, StartTime + HAVING SUM(CASE WHEN Cause = 'NoShow' THEN 1 ELSE 0 END) = 0 +`; + +function formatRoomLabel(booking) { + const name = booking.calendarRoomName || booking.DeviceName || booking.LocationName || 'Unknown'; + const type = booking.RoomType ? ` [${booking.RoomType}]` : ''; + return `${name} (${booking.Capacity || '?'})${type}`; +} + +function getUnderUtilizedMeetings(threshold, limit = 200) { + const meetings = db.prepare(` + SELECT + b.MeetingId, + b.StartTime, + b.Title, + COALESCE(NULLIF(b.OrganizerName, ''), b.OrganizerEmail, 'Unknown') as Host, + COALESCE(b.OrganizerEmail, '') as HostEmail, + COUNT(*) as roomCount, + SUM(b.Capacity) as totalCapacity, + MAX(b.RoomPeopleCountMax) as maxPeople, + MIN(b.OccupancyPctMax) as worstOccupancyPct, + MAX(b.Guests) as Guests, + MAX(b.webexMeetingId) as webexMeetingId, + MAX(b.WebexAttendeeCount) as WebexAttendeeCount, + GROUP_CONCAT(DISTINCT b.OccupancySource) as OccupancySource, + MAX(b.Duration) as Duration + FROM bookings b + INNER JOIN (${NON_NOSHOW_MEETING_SUBQUERY}) eligible + ON b.MeetingId = eligible.MeetingId AND b.StartTime = eligible.StartTime + WHERE (b.Cause = 'Ended' OR (b.Cause IS NULL AND b.ActualEndTime IS NOT NULL)) + AND b.Cause != 'NoShow' + AND b.Capacity > 0 + AND datetime(b.StartTime) > datetime('now', '-30 days') + GROUP BY b.MeetingId, b.StartTime + HAVING SUM(CASE WHEN b.RoomPeopleCountMax IS NOT NULL AND b.OccupancyPctMax < ? THEN 1 ELSE 0 END) > 0 + ORDER BY worstOccupancyPct ASC, b.StartTime DESC + LIMIT ? + `).all(threshold, limit); + + const roomStmt = db.prepare(` + SELECT + calendarRoomName, DeviceName, LocationName, RoomType, Capacity, + RoomPeopleCountMax, RoomPeopleCountAvg, RoomPeopleCount, OccupancyPctMax, OccupancySource + FROM bookings + WHERE MeetingId = ? AND StartTime = ? + AND (Cause = 'Ended' OR (Cause IS NULL AND ActualEndTime IS NOT NULL)) + AND Cause != 'NoShow' + AND Capacity > 0 + ORDER BY OccupancyPctMax ASC, COALESCE(calendarRoomName, DeviceName, LocationName) + `); + + return meetings.map(meeting => { + const rooms = roomStmt.all(meeting.MeetingId, meeting.StartTime); + return { + ...meeting, + rooms: rooms.map(room => ({ + label: formatRoomLabel(room), + capacity: room.Capacity, + maxPeople: room.RoomPeopleCountMax, + occupancyPct: room.OccupancyPctMax, + source: room.OccupancySource + })) + }; + }); +} + +function getUnderUtilizedMeetingCount(threshold) { + return db.prepare(` + SELECT COUNT(*) as n FROM ( + SELECT b.MeetingId, b.StartTime + FROM bookings b + INNER JOIN (${NON_NOSHOW_MEETING_SUBQUERY}) eligible + ON b.MeetingId = eligible.MeetingId AND b.StartTime = eligible.StartTime + WHERE (b.Cause = 'Ended' OR (b.Cause IS NULL AND b.ActualEndTime IS NOT NULL)) + AND b.Cause != 'NoShow' + AND b.Capacity > 0 + AND datetime(b.StartTime) > datetime('now', '-30 days') + GROUP BY b.MeetingId, b.StartTime + HAVING SUM(CASE WHEN b.RoomPeopleCountMax IS NOT NULL AND b.OccupancyPctMax < ? THEN 1 ELSE 0 END) > 0 + ) + `).get(threshold); +} + +function getUnderUtilizedSummary(threshold) { + const meetings = getUnderUtilizedMeetings(threshold, 10000); + if (meetings.length === 0) { + return { totalUnderUtilized: 0, avgOccupancyPct: 0, avgCapacity: 0, avgPeakPeople: 0 }; + } + + const totalUnderUtilized = meetings.length; + const avgOccupancyPct = Math.round( + meetings.reduce((sum, m) => sum + (m.worstOccupancyPct || 0), 0) / meetings.length * 10 + ) / 10; + const avgCapacity = Math.round( + meetings.reduce((sum, m) => sum + (m.totalCapacity || 0), 0) / meetings.length * 10 + ) / 10; + const avgPeakPeople = Math.round( + meetings.reduce((sum, m) => sum + (m.maxPeople || 0), 0) / meetings.length * 10 + ) / 10; + + return { totalUnderUtilized, avgOccupancyPct, avgCapacity, avgPeakPeople }; +} + +function getRecurringMultiNoShows() { + return db.prepare(` + SELECT + Title, + COALESCE(NULLIF(OrganizerName, ''), OrganizerEmail, 'Unknown') as Host, + COALESCE(OrganizerEmail, '') as HostEmail, + GROUP_CONCAT(DISTINCT COALESCE(NULLIF(calendarRoomName, ''), NULLIF(DeviceName, ''), NULLIF(LocationName, ''), 'Unknown')) as RoomNames, + SUM(CASE WHEN Cause = 'NoShow' THEN 1 ELSE 0 END) as noShows, + COUNT(*) as totalMeetings, + ROUND(100.0 * SUM(CASE WHEN Cause = 'NoShow' THEN 1 ELSE 0 END) / COUNT(*), 1) as noShowRate, + COALESCE(SUM(CASE WHEN Cause = 'NoShow' THEN MinutesFreed ELSE 0 END), 0) as minutesSaved, + GROUP_CONCAT(CASE WHEN Cause = 'NoShow' THEN date(StartTime) END) as noShowDates, + MIN(CASE WHEN Cause = 'NoShow' THEN date(StartTime) END) as firstNoShow, + MAX(CASE WHEN Cause = 'NoShow' THEN date(StartTime) END) as lastNoShow + FROM bookings + WHERE ${RECURRING_WHERE} + GROUP BY COALESCE(Title, ''), COALESCE(OrganizerEmail, ''), COALESCE(OrganizerName, '') + HAVING SUM(CASE WHEN Cause = 'NoShow' THEN 1 ELSE 0 END) > 1 + ORDER BY noShows DESC, totalMeetings DESC + `).all(); +} + +// ====================== MAIN REPORTS DASHBOARD ====================== +app.get('/reports', (req, res) => { + try { + const stats = db.prepare(` + SELECT + COUNT(*) as totalBookings, + SUM(CASE WHEN Cause = 'NoShow' THEN 1 ELSE 0 END) as totalNoShows, + SUM(CASE WHEN Cause = 'Ended' OR (Cause IS NULL AND ActualEndTime IS NOT NULL) THEN 1 ELSE 0 END) as normalEnded, + SUM(CASE WHEN RoomPeopleCount = 0 AND Cause IS NULL THEN 1 ELSE 0 END) as ghostedMeetings, + ROUND(AVG(CASE WHEN RoomPeopleCount > 0 THEN RoomPeopleCount ELSE NULL END), 1) as avgPeopleCount, + ROUND(100.0 * SUM(CASE WHEN Cause = 'NoShow' THEN 1 ELSE 0 END) / COUNT(*), 1) as noShowRate, + ROUND(100.0 * SUM(CASE WHEN RoomPeopleCount > 0 THEN 1 ELSE 0 END) / COUNT(*), 1) as utilizationRate, + COALESCE(SUM(CASE WHEN Cause = 'NoShow' THEN MinutesFreed ELSE 0 END), 0) as minutesSaved + FROM bookings + WHERE datetime(StartTime) > datetime('now', '-30 days') + `).get(); + + const roomStats = db.prepare(` + SELECT + COALESCE(w.displayName, b.LocationName, 'Unknown') as Room, + COALESCE(b.RoomType, 'โ€”') as RoomType, + COUNT(*) as totalBookings, + SUM(CASE WHEN b.Cause = 'NoShow' THEN 1 ELSE 0 END) as noShows, + SUM(CASE WHEN b.Cause = 'Ended' OR (b.Cause IS NULL AND b.ActualEndTime IS NOT NULL) THEN 1 ELSE 0 END) as normalEnded, + ROUND(100.0 * SUM(CASE WHEN b.Cause = 'NoShow' THEN 1 ELSE 0 END) / COUNT(*), 1) as noShowRate, + ROUND(AVG(b.RoomPeopleCountAvg), 1) as avgPeople, + ROUND(AVG(b.RoomPeopleCountMax), 1) as avgPeakPeople, + ROUND(AVG(COALESCE(b.Capacity, 0)), 1) as avgCapacity + FROM bookings b + LEFT JOIN workspace_lookup w ON b.WorkspaceId = w.workspaceId + WHERE datetime(b.StartTime) > datetime('now', '-30 days') + GROUP BY COALESCE(w.displayName, b.LocationName), b.RoomType + ORDER BY noShowRate DESC + LIMIT 15 + `).all(); + + const underUtilizedCount = getUnderUtilizedMeetingCount(UNDER_UTILIZED_THRESHOLD_PCT); + + const topHosts = db.prepare(` + SELECT + COALESCE(NULLIF(OrganizerName, ''), OrganizerEmail, 'Unknown') as Host, + COALESCE(OrganizerEmail, '') as HostEmail, + SUM(CASE WHEN Cause = 'NoShow' THEN 1 ELSE 0 END) as noShows, + SUM(CASE WHEN Cause = 'Ended' OR (Cause IS NULL AND ActualEndTime IS NOT NULL) THEN 1 ELSE 0 END) as normalEnded, + COALESCE(SUM(CASE WHEN Cause = 'NoShow' THEN MinutesFreed ELSE 0 END), 0) as minutesSaved + FROM bookings + WHERE datetime(StartTime) > datetime('now', '-30 days') + GROUP BY COALESCE(OrganizerEmail, OrganizerName) + HAVING SUM(CASE WHEN Cause = 'NoShow' THEN 1 ELSE 0 END) > 0 + ORDER BY noShows DESC, minutesSaved DESC + LIMIT 10 + `).all(); + + const recurringCount = db.prepare(` + SELECT COUNT(*) as n FROM ( + SELECT 1 FROM bookings + WHERE ${RECURRING_WHERE} + GROUP BY COALESCE(Title, ''), COALESCE(OrganizerEmail, ''), COALESCE(OrganizerName, '') + HAVING SUM(CASE WHEN Cause = 'NoShow' THEN 1 ELSE 0 END) > 1 + ) + `).get(); + + const html = ` + + + + + + Room Utilization Dashboard + + + +

Room Utilization & Meeting Analytics Dashboard

+

Last 30 days โ€ข Updated: ${escapeHtml(new Date().toLocaleString())}

+ + + +
+
+

${stats.totalBookings || 0}

+

Total Bookings

+
+
+

${stats.totalNoShows || 0}

+

NoShow Events

+
+
+

${formatMinutes(stats.minutesSaved)}

+

Time Saved (NoShows)

+
+
+

${stats.noShowRate || 0}%

+

NoShow Rate

+
+
+

${recurringCount?.n || 0}

+

Recurring Series with 2+ NoShows

+
+
+

${stats.utilizationRate || 0}%

+

Utilization Rate (โ‰ฅ1 person)

+
+
+

${underUtilizedCount?.n || 0}

+

Under-Utilized Meetings (<${UNDER_UTILIZED_THRESHOLD_PCT}% capacity)

+
+
+ +

Top Hosts by NoShow (Last 30 Days)

+ + + + + + + + + + + + + ${topHosts.map((h, i) => ` + + + + + + + + + `).join('') || ''} + +
#HostEmailNoShowsNormal EndedTime Saved
${i + 1}${escapeHtml(h.Host)}${escapeHtml(h.HostEmail)}${h.noShows}${h.normalEnded || 0}${formatMinutes(h.minutesSaved)} (${h.minutesSaved} min)
No NoShow data in the last 30 days.
+ +

All Rooms - Ranked by NoShow Rate

+ + + + + + + + + + + + + + + + ${roomStats.map(room => ` + + + + + + + + + + + + `).join('')} + +
RoomRoom TypeTotal BookingsNoShowsNormal EndedNoShow RateAvg PeopleAvg Peak PeopleAvg Capacity
${escapeHtml(room.Room)}${escapeHtml(room.RoomType)}${room.totalBookings}${room.noShows}${room.normalEnded}${room.noShowRate}%${room.avgPeople || 'โ€”'}${room.avgPeakPeople || 'โ€”'}${room.avgCapacity || 'โ€”'}
+ + + +`; + + res.send(html); + } catch (err) { + console.error('โŒ Dashboard error:', err.message); + res.status(500).send('Error generating dashboard'); + } +}); + +// ====================== UNDER-UTILIZED MEETINGS REPORT ====================== +app.get('/reports/under-utilized', async (req, res) => { + try { + let meetings = getUnderUtilizedMeetings(UNDER_UTILIZED_THRESHOLD_PCT); + await backfillWebexAttendeeCounts(meetings); + const summary = getUnderUtilizedSummary(UNDER_UTILIZED_THRESHOLD_PCT); + + const html = ` + + + + + + Under-Utilized Meetings Report + + + +

Under-Utilized Meetings

+

Non-NoShow meetings where at least one room peaked below ${UNDER_UTILIZED_THRESHOLD_PCT}% of capacity โ€ข All rooms validated per meeting โ€ข Last 30 days โ€ข Updated: ${escapeHtml(new Date().toLocaleString())}

+ + + +
+
+

${summary.totalUnderUtilized || 0}

+

Under-Utilized Meetings

+
+
+

${summary.avgOccupancyPct || 0}%

+

Avg Worst-Room Occupancy %

+
+
+

${summary.avgPeakPeople || 0}

+

Avg Peak People (per meeting)

+
+
+

${summary.avgCapacity || 0}

+

Avg Total Capacity

+
+
+ +

Meetings Below ${UNDER_UTILIZED_THRESHOLD_PCT}% Capacity

+ + + + + + + + + + + + + + + + + + ${meetings.map(m => ` + + + + + + + + + + + + + + `).join('') || ``} + +
Date & TimeTitleHostRoomsRoom CountTotal CapacityMax PeopleWorst Occupancy %Invited GuestsWebex AttendeesSource
${escapeHtml(formatMeetingDateTime(m.StartTime))}${escapeHtml(m.Title)}${escapeHtml(m.Host)}
${escapeHtml(m.HostEmail)}
${m.rooms.map(r => ` +
${escapeHtml(r.label)} โ€” peak: ${r.maxPeople ?? 'โ€”'}, ${r.occupancyPct ?? 'โ€”'}%
+ `).join('')}
${m.roomCount}${m.totalCapacity ?? 'โ€”'}${m.maxPeople ?? 'โ€”'}${m.worstOccupancyPct ?? 'โ€”'}%${m.Guests ?? 0}${m.webexMeetingId ? (m.WebexAttendeeCount ?? 'โ€”') : 'โ€”'}${escapeHtml(m.OccupancySource || 'โ€”')}
No under-utilized meetings found (threshold: <${UNDER_UTILIZED_THRESHOLD_PCT}% of capacity).
+ +`; + + res.send(html); + } catch (err) { + console.error('โŒ Under-utilized report error:', err.message); + res.status(500).send('Error generating under-utilized report'); + } +}); + +app.get('/reports/under-utilized.csv', async (req, res) => { + try { + let meetings = getUnderUtilizedMeetings(UNDER_UTILIZED_THRESHOLD_PCT, 10000); + await backfillWebexAttendeeCounts(meetings); + const rows = meetings.flatMap(m => m.rooms.map(room => ({ + DateTime: formatMeetingDateTime(m.StartTime), + Title: m.Title, + Host: m.Host, + HostEmail: m.HostEmail, + Room: room.label, + RoomCount: m.roomCount, + RoomCapacity: room.capacity, + TotalCapacity: m.totalCapacity, + MaxPeople: room.maxPeople, + OccupancyPct: room.occupancyPct, + MeetingWorstOccupancyPct: m.worstOccupancyPct, + InvitedGuests: m.Guests, + WebexAttendeeCount: m.webexMeetingId ? (m.WebexAttendeeCount ?? '') : '', + Source: room.source || m.OccupancySource, + Duration: m.Duration + }))); + + const headers = ['DateTime', 'Title', 'Host', 'HostEmail', 'Room', 'RoomCount', 'RoomCapacity', 'TotalCapacity', 'MaxPeople', 'OccupancyPct', 'MeetingWorstOccupancyPct', 'InvitedGuests', 'WebexAttendeeCount', 'Source', 'Duration']; + res.setHeader('Content-Type', 'text/csv'); + res.setHeader('Content-Disposition', 'attachment; filename="under_utilized_meetings_30d.csv"'); + res.send(rowsToCsv(headers, rows)); + console.log(`๐Ÿ“Š Under-utilized CSV downloaded (${rows.length} room rows, ${meetings.length} meetings)`); + } catch (err) { + console.error('โŒ Under-utilized CSV error:', err.message); + res.status(500).send('Error generating CSV'); + } +}); + +// ====================== 30-DAY MEETING SUMMARY REPORT ====================== +app.get('/reports/meeting-summary', (req, res) => { + try { + const summary = db.prepare(` + SELECT + COUNT(*) as totalBookings, + SUM(CASE WHEN Cause = 'NoShow' THEN 1 ELSE 0 END) as totalNoShows, + COALESCE(SUM(CASE WHEN Cause = 'NoShow' THEN MinutesFreed ELSE 0 END), 0) as minutesSaved, + ROUND(100.0 * SUM(CASE WHEN Cause = 'NoShow' THEN 1 ELSE 0 END) / NULLIF(COUNT(*), 0), 1) as noShowRate, + COUNT(DISTINCT CASE WHEN Cause = 'NoShow' THEN OrganizerEmail END) as hostsWithNoShows + FROM bookings + WHERE datetime(StartTime) > datetime('now', '-30 days') + `).get(); + + const hostsByNoShows = db.prepare(` + SELECT + COALESCE(NULLIF(OrganizerName, ''), OrganizerEmail, 'Unknown') as Host, + COALESCE(OrganizerEmail, '') as HostEmail, + COUNT(*) as noShows, + COALESCE(SUM(MinutesFreed), 0) as minutesSaved, + ROUND(AVG(CAST(MinutesFreed AS REAL)), 1) as avgMinutesFreed, + GROUP_CONCAT(DISTINCT COALESCE(NULLIF(calendarRoomName, ''), NULLIF(DeviceName, ''), 'Unknown')) as rooms + FROM bookings + WHERE Cause = 'NoShow' + AND datetime(StartTime) > datetime('now', '-30 days') + GROUP BY COALESCE(OrganizerEmail, OrganizerName) + ORDER BY noShows DESC, minutesSaved DESC + LIMIT 50 + `).all(); + + const hostsByTimeSaved = db.prepare(` + SELECT + COALESCE(NULLIF(OrganizerName, ''), OrganizerEmail, 'Unknown') as Host, + COALESCE(OrganizerEmail, '') as HostEmail, + COUNT(*) as noShows, + COALESCE(SUM(MinutesFreed), 0) as minutesSaved + FROM bookings + WHERE Cause = 'NoShow' + AND datetime(StartTime) > datetime('now', '-30 days') + GROUP BY COALESCE(OrganizerEmail, OrganizerName) + ORDER BY minutesSaved DESC, noShows DESC + LIMIT 50 + `).all(); + + const recentNoShows = db.prepare(` + SELECT + date(StartTime) as meetingDate, + Title, + COALESCE(NULLIF(OrganizerName, ''), OrganizerEmail, 'Unknown') as Host, + COALESCE(OrganizerEmail, '') as HostEmail, + COALESCE(NULLIF(calendarRoomName, ''), NULLIF(DeviceName, ''), NULLIF(LocationName, ''), 'Unknown') as Room, + COALESCE(MinutesFreed, 0) as MinutesFreed, + Duration + FROM bookings + WHERE Cause = 'NoShow' + AND datetime(StartTime) > datetime('now', '-30 days') + ORDER BY StartTime DESC + LIMIT 100 + `).all(); + + const html = ` + + + + + + 30-Day Meeting Report โ€” NoShows + + + +

30-Day Meeting Report

+

NoShow totals, time saved, and host rankings โ€ข Updated: ${escapeHtml(new Date().toLocaleString())}

+ + + +
+
+

${summary.totalNoShows || 0}

+

Total NoShow Meetings

+
+
+

${formatMinutes(summary.minutesSaved)}

+

Total Time Saved
${summary.minutesSaved || 0} minutes

+
+
+

${summary.noShowRate || 0}%

+

NoShow Rate of All Bookings

+
+
+

${summary.hostsWithNoShows || 0}

+

Hosts with NoShows

+
+
+

${summary.totalBookings || 0}

+

Total Bookings (30 days)

+
+
+ +

Hosts with the Most NoShow Meetings

+ + + + + + + + + + + + + + ${hostsByNoShows.map((h, i) => ` + + + + + + + + + + `).join('') || ''} + +
#HostEmailNoShowsTime SavedAvg Freed / NoShowRooms
${i + 1}${escapeHtml(h.Host)}${escapeHtml(h.HostEmail)}${h.noShows}${formatMinutes(h.minutesSaved)} (${h.minutesSaved} min)${h.avgMinutesFreed ?? 'โ€”'} min${escapeHtml(h.rooms)}
No data
+ +

Hosts with the Most Time Saved

+ + + + + + + + + + + + ${hostsByTimeSaved.map((h, i) => ` + + + + + + + + `).join('') || ''} + +
#HostEmailTime SavedNoShows
${i + 1}${escapeHtml(h.Host)}${escapeHtml(h.HostEmail)}${formatMinutes(h.minutesSaved)} (${h.minutesSaved} min)${h.noShows}
No data
+ +

Recent NoShows (Last 30 Days)

+ + + + + + + + + + + + + ${recentNoShows.map(r => ` + + + + + + + + + `).join('') || ''} + +
DateTitleHostRoomDurationMinutes Freed
${escapeHtml(r.meetingDate)}${escapeHtml(r.Title)}${escapeHtml(r.Host)}
${escapeHtml(r.HostEmail)}
${escapeHtml(r.Room)}${escapeHtml(r.Duration)} min${r.MinutesFreed}
No data
+ +`; + + res.send(html); + } catch (err) { + console.error('โŒ Meeting summary report error:', err.message); + res.status(500).send('Error generating meeting summary report'); + } +}); + +// CSV for 30-day meeting summary (hosts + time saved) +app.get('/reports/meeting-summary.csv', (req, res) => { + try { + const rows = db.prepare(` + SELECT + COALESCE(NULLIF(OrganizerName, ''), OrganizerEmail, 'Unknown') as Host, + COALESCE(OrganizerEmail, '') as HostEmail, + COUNT(*) as NoShows, + COALESCE(SUM(MinutesFreed), 0) as MinutesSaved, + ROUND(AVG(CAST(MinutesFreed AS REAL)), 1) as AvgMinutesFreed, + GROUP_CONCAT(DISTINCT COALESCE(NULLIF(calendarRoomName, ''), NULLIF(DeviceName, ''), 'Unknown')) as Rooms + FROM bookings + WHERE Cause = 'NoShow' + AND datetime(StartTime) > datetime('now', '-30 days') + GROUP BY COALESCE(OrganizerEmail, OrganizerName) + ORDER BY NoShows DESC, MinutesSaved DESC + `).all(); + + const headers = ['Host', 'HostEmail', 'NoShows', 'MinutesSaved', 'AvgMinutesFreed', 'Rooms']; + res.setHeader('Content-Type', 'text/csv'); + res.setHeader('Content-Disposition', 'attachment; filename="meeting_summary_30d.csv"'); + res.send(rowsToCsv(headers, rows)); + console.log(`๐Ÿ“Š 30-day meeting summary CSV downloaded (${rows.length} hosts)`); + } catch (err) { + console.error('โŒ Meeting summary CSV error:', err.message); + res.status(500).send('Error generating CSV'); + } +}); + +// ====================== RECURRING MULTI-NOSHOW REPORT ====================== +app.get('/reports/recurring-noshows', (req, res) => { + try { + const series = getRecurringMultiNoShows(); + const totals = series.reduce((acc, s) => { + acc.series += 1; + acc.noShows += s.noShows; + acc.meetings += s.totalMeetings; + acc.minutes += s.minutesSaved; + return acc; + }, { series: 0, noShows: 0, meetings: 0, minutes: 0 }); + + const html = ` + + + + + + Recurring Multi-NoShow Report + + + +

Recurring Meetings โ€” Multiple NoShows

+

+ Recurring series (IsRecurring or Google recurring event) with more than one NoShow. + Shows NoShows vs total tracked meetings for that series โ€ข Updated: ${escapeHtml(new Date().toLocaleString())} +

+ + + +
+
+

${totals.series}

+

Recurring Series with 2+ NoShows

+
+
+

${totals.noShows}

+

Total NoShows in These Series

+
+
+

${totals.meetings}

+

Total Meetings Tracked

+
+
+

${totals.meetings ? Math.round(1000 * totals.noShows / totals.meetings) / 10 : 0}%

+

Overall NoShow Rate (these series)

+
+
+

${formatMinutes(totals.minutes)}

+

Time Saved Across Series

+
+
+ +

Series Detail

+ + + + + + + + + + + + + + + + ${series.map(s => { + const rateClass = s.noShowRate >= 75 ? 'rate-high' : (s.noShowRate >= 40 ? 'rate-mid' : ''); + return ` + + + + + + + + + + + `; + }).join('') || ''} + +
TitleHostCalendar RoomNoShowsTotal MeetingsNoShow RateTime SavedFirst โ†’ Last NoShowNoShow Dates
${escapeHtml(s.Title || '(no title)')}${escapeHtml(s.Host)}
${escapeHtml(s.HostEmail)}
${escapeHtml(s.RoomNames)}${s.noShows}${s.totalMeetings}${s.noShowRate}%${formatMinutes(s.minutesSaved)}${escapeHtml(s.firstNoShow)} โ†’ ${escapeHtml(s.lastNoShow)}${escapeHtml(s.noShowDates)}
No recurring series with more than one NoShow.
+ +`; + + res.send(html); + } catch (err) { + console.error('โŒ Recurring NoShow report error:', err.message); + res.status(500).send('Error generating recurring NoShow report'); + } +}); + +app.get('/reports/recurring-noshows.csv', (req, res) => { + try { + const series = getRecurringMultiNoShows(); + const rows = series.map(s => ({ + Title: s.Title, + Host: s.Host, + HostEmail: s.HostEmail, + CalendarRoomName: s.RoomNames, + NoShows: s.noShows, + TotalMeetings: s.totalMeetings, + NoShowRate: s.noShowRate, + MinutesSaved: s.minutesSaved, + FirstNoShow: s.firstNoShow, + LastNoShow: s.lastNoShow, + NoShowDates: s.noShowDates + })); + const headers = ['Title', 'Host', 'HostEmail', 'CalendarRoomName', 'NoShows', 'TotalMeetings', + 'NoShowRate', 'MinutesSaved', 'FirstNoShow', 'LastNoShow', 'NoShowDates']; + res.setHeader('Content-Type', 'text/csv'); + res.setHeader('Content-Disposition', 'attachment; filename="recurring_multi_noshows.csv"'); + res.send(rowsToCsv(headers, rows)); + console.log(`๐Ÿ“Š Recurring multi-NoShow CSV downloaded (${rows.length} series)`); + } catch (err) { + console.error('โŒ Recurring NoShow CSV error:', err.message); + res.status(500).send('Error generating CSV'); + } +}); + +// ====================== CSV DOWNLOAD ENDPOINT (all NoShows) ====================== +app.get('/reports/noshows', (req, res) => { + try { + const rows = db.prepare(` + SELECT + MeetingId, Title, OrganizerName, OrganizerEmail, StartTime, + Duration, DeviceName, calendarRoomName, MinutesFreed, IsRecurring, + created_at as DetectedAt + FROM bookings + WHERE Cause = 'NoShow' + ORDER BY created_at DESC + `).all(); + + if (rows.length === 0) { + return res.status(404).send('No NoShow records found.'); + } + + const headers = ['MeetingId', 'Title', 'OrganizerName', 'OrganizerEmail', 'StartTime', + 'Duration', 'DeviceName', 'calendarRoomName', 'MinutesFreed', 'IsRecurring', 'DetectedAt']; + + res.setHeader('Content-Type', 'text/csv'); + res.setHeader('Content-Disposition', 'attachment; filename="noshows_report.csv"'); + res.send(rowsToCsv(headers, rows)); + + console.log(`๐Ÿ“Š CSV report downloaded (${rows.length} records)`); + } catch (err) { + console.error('โŒ CSV generation error:', err.message); + res.status(500).send('Error generating CSV'); + } +}); + +app.get('/needs-enrichment', authenticateWebhook, async (req, res) => { + try { + const pending = db.prepare(` + SELECT id, MeetingId, WorkspaceId, StartTime, Title, OrganizerEmail, + CalendarEmail, DeviceName + FROM bookings + WHERE googleEventId IS NULL + AND (enrichmentStatus IS NULL OR enrichmentStatus != 'failed') + AND Cause IS NULL + AND datetime(StartTime) > datetime('now', '-72 hours') -- widened from 48h + ORDER BY StartTime ASC + LIMIT 20 + `).all(); + + // Re-fetch CalendarEmail if missing (safety net) + for (let b of pending) { + if (!b.CalendarEmail && b.WorkspaceId) { + try { + const ws = await getWorkspaceInfo(b.WorkspaceId); + if (ws.calendarEmail) { + db.prepare(`UPDATE bookings SET CalendarEmail = ? WHERE MeetingId = ? AND WorkspaceId = ?`) + .run(ws.calendarEmail, b.MeetingId, b.WorkspaceId); + b.CalendarEmail = ws.calendarEmail; + } + } catch (e) {} + } + } + + console.log(`๐Ÿ“ค Returning ${pending.length} bookings for enrichment`); + res.json(pending); + } catch (err) { + console.error('โŒ /needs-enrichment error:', err.message); + res.status(500).json({ error: 'Internal error' }); + } +}); + +// POST /enrich โ†’ Apps Script pushes enriched data back (including Webex details) +app.post('/enrich', authenticateWebhook, (req, res) => { + try { + const enrichedList = req.body; + if (!Array.isArray(enrichedList)) { + return res.status(400).json({ error: 'Expected array' }); + } + + let updated = 0; + const meetingsToSync = new Set(); + for (const item of enrichedList) { + db.prepare(` + UPDATE bookings + SET googleEventId = ?, + isRecurring = ?, + Guests = ?, + calendarRoomName = ?, + webexMeetingId = ?, + webexPassword = ?, + webexSipAddress = ?, + googleEventCreator = ?, + enrichmentStatus = 'success' + WHERE MeetingId = ? AND WorkspaceId = ? + `).run( + item.googleEventId || null, + item.isRecurring ? 1 : 0, + item.Guests || 0, + item.calendarRoomName || null, + item.webexMeetingId || null, + item.webexPassword || null, + item.webexSipAddress || null, + item.googleEventCreator || null, // New field + item.MeetingId, + item.WorkspaceId + ); + if (item.webexMeetingId && item.MeetingId) { + meetingsToSync.add(item.MeetingId); + } + updated++; + } + + console.log(`โœ… Enriched ${updated} bookings (including googleEventCreator)`); + res.json({ success: true, updated }); + + for (const meetingId of meetingsToSync) { + syncWebexAttendeeCountForMeeting(meetingId).catch(err => { + console.error(`WebexAttendeeCount sync failed for ${meetingId}:`, err.message); + }); + } + } catch (err) { + console.error('โŒ /enrich error:', err.message); + res.status(500).json({ error: 'Internal error' }); + } +}); + +// ====================== ENRICHMENT FAILURE REPORTING ====================== +// Apps Script calls this to mark bookings that could not be enriched +app.post('/enrich-failed', authenticateWebhook, (req, res) => { + try { + const failedList = req.body; + if (!Array.isArray(failedList)) { + return res.status(400).json({ error: 'Expected array' }); + } + + let updated = 0; + + for (const item of failedList) { + if (!item.MeetingId || !item.WorkspaceId) continue; + + db.prepare(` + UPDATE bookings + SET enrichmentStatus = 'failed' + WHERE MeetingId = ? AND WorkspaceId = ? + `).run(item.MeetingId, item.WorkspaceId); + + updated++; + } + + console.log(`๐Ÿ“› Marked ${updated} bookings as enrichment failed`); + res.json({ success: true, updated }); + } catch (err) { + console.error('โŒ /enrich-failed error:', err.message); + res.status(500).json({ error: 'Internal error' }); + } +}); + +// Manual cleanup endpoint (useful for testing) +app.post('/cleanup', authenticateWebhook, (req, res) => { + try { + const result = db.prepare(` + DELETE FROM bookings + WHERE Cause IS NULL + AND datetime(StartTime) < datetime('now', '-72 hours') + `).run(); + + res.json({ + success: true, + removed: result.changes, + message: `Removed ${result.changes} old normal bookings` + }); + + console.log(`๐Ÿงน Manual cleanup requested: Removed ${result.changes} bookings`); + } catch (err) { + console.error('โŒ Manual cleanup failed:', err.message); + res.status(500).json({ error: 'Cleanup failed' }); + } +}); + +// ====================== DAILY CLEANUP ====================== +// Removes normal bookings (not NoShow) older than 72 hours +function runDailyCleanup() { + try { + const result = db.prepare(` + DELETE FROM bookings + WHERE Cause IS NULL + AND datetime(StartTime) < datetime('now', '-72 hours') + `).run(); + + if (result.changes > 0) { + console.log(`๐Ÿงน Daily cleanup: Removed ${result.changes} normal (non-NoShow) bookings older than 72 hours`); + } else { + console.log('๐Ÿงน Daily cleanup: No bookings needed removal'); + } + } catch (err) { + console.error('โŒ Daily cleanup failed:', err.message); + } +} + +// Run cleanup immediately on startup +console.log('๐Ÿงน Running initial cleanup on startup...'); +//runDailyCleanup(); + +// Run cleanup every 6 hours (so we don't miss the daily window) +//setInterval(runDailyCleanup, 6 * 60 * 60 * 1000); // every 6 hours + +// ... all your other functions are here (getWorkspaceInfo, getFloorInfo, getXAPIRoomData, etc.) + +// ====================== FULL LOCATION + FLOOR BACKFILL ====================== +// THIS MUST BE THE VERY LAST THING BEFORE app.listen +/* + +console.log('๐Ÿ”„ Running FULL location + floor backfill...'); + +const uniqueWorkspaces = db.prepare(`SELECT DISTINCT WorkspaceId FROM bookings`).all(); + +let cachedWorkspaces = 0; +let cachedFloors = 0; +let updatedBookings = 0; + +for (const row of uniqueWorkspaces) { + try { + const workspace = await getWorkspaceInfo(row.WorkspaceId); + + if (workspace && workspace.displayName) { + db.prepare(` + INSERT OR REPLACE INTO workspace_lookup + (workspaceId, displayName, locationName, floorId, roomType, capacity, sipAddress) + VALUES (?, ?, ?, ?, ?, ?, ?) + `).run( + row.WorkspaceId, + workspace.displayName, + workspace.locationName, + workspace.floorId, + workspace.roomType, + workspace.capacity, + workspace.sipAddress + ); + cachedWorkspaces++; + + if (workspace.floorId && workspace.locationName) { + const friendlyFloor = await getFloorInfo(workspace.locationName, workspace.floorId); + if (friendlyFloor) cachedFloors++; + } + + const result = db.prepare(` + UPDATE bookings + SET LocationName = ?, + Floor = ?, + RoomType = ?, + Capacity = ? + WHERE WorkspaceId = ? + `).run( + workspace.displayName, + workspace.floorId, + workspace.roomType, + workspace.capacity, + row.WorkspaceId + ); + + updatedBookings += result.changes; + } + } catch (err) { + console.error(`Failed to backfill workspace ${row.WorkspaceId}:`, err.message); + } +} + +console.log(`โœ… Full backfill completed:`); +console.log(` - Cached ${cachedWorkspaces} workspaces`); +console.log(` - Cached ${cachedFloors} floors`); +console.log(` - Updated ${updatedBookings} booking records`); +*/ + + +/* +// ====================== ONE-TIME CALENDAR EMAIL BACKFILL ====================== +console.log('๐Ÿ”„ Running one-time calendar email backfill...'); + +const workspacesToUpdate = db.prepare(` + SELECT workspaceId FROM workspace_lookup + WHERE calendarEmail IS NULL OR calendarEmail = '' +`).all(); + +let updated = 0; + +for (const row of workspacesToUpdate) { + try { + const fresh = await getWorkspaceInfo(row.workspaceId); // This will re-fetch and cache the calendarEmail + if (fresh.calendarEmail) { + updated++; + console.log(`โœ… Backfilled calendar email for ${fresh.displayName}`); + } + } catch (err) { + console.error(`Failed to backfill calendar for ${row.workspaceId}`); + } +} + +console.log(`โœ… Calendar email backfill completed: Updated ${updated} workspaces`); +*/ +// ====================== START SERVER ====================== +setInterval(pollActiveMeetingOccupancy, OCCUPANCY_POLL_INTERVAL_MS); +console.log(`๐Ÿ“ก Occupancy polling enabled every ${OCCUPANCY_POLL_INTERVAL_MS / 1000}s`); + +app.listen(PORT, () => { + console.log(`๐Ÿš€ Webex Booking Webhook running on http://localhost:${PORT}`); + console.log(`๐Ÿ” Protected webhook: /bookings`); + console.log(`๐Ÿ”‘ Authentication: ${WEBHOOK_AUTH_TOKEN.substring(0, 8)}...`); +}); \ No newline at end of file