const PACIFIC = 'America/Los_Angeles'; function doGet() { const cache = CacheService.getScriptCache(); const today = Utilities.formatDate(new Date(), PACIFIC, 'yyyy-MM-dd'); const cacheKey = 'leaderboard-v1-' + today; let payload = cache.get(cacheKey); if (!payload) { const monday = new Date(today + 'T00:00:00Z'); monday.setUTCDate(monday.getUTCDate() - (monday.getUTCDay() + 6) % 7); const starts = { today, week: monday.toISOString().slice(0, 10), month: today.slice(0, 7) + '-01' }; const sales = readSales_(); const periods = {}; for (const [period, start] of Object.entries(starts)) { const agents = new Map(); for (const [day, name, alp] of sales) { if (day < start || day > today) continue; const key = name.toLowerCase(); const agent = agents.get(key) || { name, cents: 0, reports: 0 }; agent.cents += Math.round(alp * 100); agent.reports++; agents.set(key, agent); } periods[period] = Array.from(agents.values()); } payload = JSON.stringify({ asOf: new Date().toISOString(), today, periods }); try { cache.put(cacheKey, payload, 25); } catch (error) { console.warn('Leaderboard totals could not be cached.'); } } return ContentService.createTextOutput(payload).setMimeType(ContentService.MimeType.JSON); } function readSales_() { const tracker = SpreadsheetApp.openById('13aowghbCQdX4gAHAWgtk-txDUd8yDUlliMHJ3eol54I'); const zone = PACIFIC; const sheet = tracker.getSheetByName('Sheet1'); const lastRow = sheet.getLastRow(); if (lastRow < 2) return []; const monthStart = Utilities.formatDate(new Date(), zone, 'yyyy-MM') + '-01'; const today = Utilities.formatDate(new Date(), zone, 'yyyy-MM-dd'); const monday = new Date(today + 'T00:00:00Z'); monday.setUTCDate(monday.getUTCDate() - (monday.getUTCDay() + 6) % 7); const weekStart = monday.toISOString().slice(0, 10); const start = weekStart < monthStart ? weekStart : monthStart; const sales = []; for (const [date, name, alp] of sheet.getRange(2, 1, lastRow - 1, 3).getValues()) { if (!(date instanceof Date) || typeof name !== 'string' || !name.trim() || !Number.isFinite(alp)) continue; const day = Utilities.formatDate(date, zone, 'yyyy-MM-dd'); if (day >= start && day <= today) sales.push([day, name.trim(), alp]); } return sales; }