// Zone numbers for the member Reports screen (2026-10-10). A READ-ONLY view over DATA_DIR/zones.json (the store // zones.js owns): views, viewable views, clicks and credits for the member's zones over the chosen days, by Central // day and by zone. Counting mirrors zones.statusOf / pubZone: bots excluded, `ok` = viewable, `k` = clicked. // Credits per zone are the lifetime meter zones.js keeps (z.credits); there is no dated credit log in the store yet. // Parsed on demand with a short cache so a 300k-impression file is not re-read on every click of the range picker. // Move this into zones.js as zones.summary(owner, days) when that file is free. 'use strict'; const fs = require('fs'); const path = require('path'); let DATA_DIR = null; let cache = { at: 0, mtime: 0, db: null }; const DAY = 86400000, TTL = 30 * 1000; function init(opts) { DATA_DIR = opts.dataDir; } function load() { const file = path.join(DATA_DIR, 'zones.json'); let mtime = 0; try { mtime = fs.statSync(file).mtimeMs; } catch (e) { return { zones: [], imps: [] }; } if (cache.db && cache.mtime === mtime && Date.now() - cache.at < TTL) return cache.db; let db; try { db = JSON.parse(fs.readFileSync(file, 'utf8')); } catch (e) { db = {}; } db = { zones: Array.isArray(db.zones) ? db.zones : [], imps: Array.isArray(db.imps) ? db.imps : [] }; cache = { at: Date.now(), mtime, db }; return db; } const norm = e => String(e || '').trim().toLowerCase(); const ctDay = ts => new Date(ts).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' }); async function summary(owner, days) { const db = load(); const mine = db.zones.filter(z => z.owner === norm(owner)); const ids = new Set(mine.map(z => z.id)); const since = Date.now() - (Number(days) || 30) * DAY; const imps = db.imps.filter(i => ids.has(i.z) && i.ts >= since && !i.bot); const dayMap = {}; for (const i of imps) { const d = dayMap[ctDay(i.ts)] = dayMap[ctDay(i.ts)] || { day: ctDay(i.ts), views: 0, viewable: 0, clicks: 0 }; d.views++; if (i.ok) d.viewable++; if (i.k) d.clicks++; } const byDay = Object.values(dayMap).sort((a, b) => a.day < b.day ? -1 : 1); const byZone = mine.map(z => { const zi = imps.filter(i => i.z === z.id); const seen = zi.filter(i => i.ok).length; return { id: z.id, name: z.name, site: z.site, size: z.size, active: !!z.active, paused: !!z.adminPaused, views: zi.length, viewable: seen, viewablePct: zi.length ? Math.round(seen / zi.length * 100) : null, clicks: zi.filter(i => i.k).length, paid: zi.filter(i => i.ok && !i.house && !i.off).length, credits: z.credits || 0 }; }).sort((a, b) => b.views - a.views); return { zones: mine.length, views: imps.length, viewable: imps.filter(i => i.ok).length, clicks: imps.filter(i => i.k).length, paid: imps.filter(i => i.ok && !i.house && !i.off).length, credits: mine.reduce((n, z) => n + (z.credits || 0), 0), byDay, byZone }; } module.exports = { init, summary };