agy-family 0.2.9 → 0.2.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agy-family",
3
- "version": "0.2.9",
3
+ "version": "0.2.10",
4
4
  "description": "Zero-privacy-leak transparent usage dashboard, /family slash command, and fair-use budget guardrail for Google One / Antigravity family groups.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -47,7 +47,7 @@ import {
47
47
  writeHostConfig,
48
48
  } from '../src/host.mjs';
49
49
 
50
- const CLI_VERSION = '0.2.9';
50
+ const CLI_VERSION = '0.2.10';
51
51
  const THIS_CLI_PATH = fileURLToPath(import.meta.url);
52
52
  const PACKAGE_ROOT = resolve(dirname(THIS_CLI_PATH), '..', '..', '..');
53
53
 
@@ -716,7 +716,7 @@ export async function runHeadlessSync({ cfg, fullSync = false, home = homedir(),
716
716
  const { payload, scan, nextSyncedHashes, nextAccountLedger } = await buildSyncPayload({
717
717
  deviceId,
718
718
  clientKind: 'cli',
719
- clientVersion: '0.2.9',
719
+ clientVersion: '0.2.10',
720
720
  home,
721
721
  fileCache: cache,
722
722
  syncedHashes: prevHashes,
@@ -82,7 +82,7 @@ export function diffSyncBuckets(buckets, syncedHashes = null, { fullSync = false
82
82
  export async function buildSyncPayload({
83
83
  deviceId,
84
84
  clientKind = 'cli',
85
- clientVersion = '0.2.9',
85
+ clientVersion = '0.2.10',
86
86
  home,
87
87
  roots = null,
88
88
  sourceFilter = 'all',
@@ -155,7 +155,7 @@ export async function buildSyncPayload({
155
155
  deviceId: String(deviceId || deriveAnonymousDeviceId()).slice(0, 32),
156
156
  client: {
157
157
  kind: clientKind === 'extension' ? 'extension' : 'cli',
158
- version: String(clientVersion || '0.2.9').slice(0, 24),
158
+ version: String(clientVersion || '0.2.10').slice(0, 24),
159
159
  },
160
160
  account: {
161
161
  emailHash: effectiveReportedHash,
@@ -23,7 +23,7 @@ import {
23
23
  import { renderDashboardHtml } from './ui.mjs';
24
24
  import { dispatchWebhook, sendDedupedAlert, validateWebhookUrl } from './webhooks.mjs';
25
25
 
26
- export const SERVER_VERSION = '0.2.9';
26
+ export const SERVER_VERSION = '0.2.10';
27
27
  const MAX_BUCKETS_PER_SYNC = 1000;
28
28
  const MAX_DEVICES_PER_MEMBER = 8;
29
29
  const MAX_TOKENS_PER_BUCKET = 500_000_000;
@@ -336,13 +336,18 @@ export function createApp({
336
336
  const settings = await loadSettings(db, envDefaults);
337
337
  const viewErr = await requireViewKeyIfEnabled(request, url, settings, now);
338
338
  if (viewErr) return viewErr;
339
- const period = ['today', '7d', 'cycle', '30d'].includes(url.searchParams.get('period'))
340
- ? url.searchParams.get('period')
341
- : 'today';
339
+ const from = (url.searchParams.get('from') || '').trim();
340
+ const to = (url.searchParams.get('to') || '').trim();
341
+ const rawPeriod = url.searchParams.get('period');
342
+ const period = ['today', 'yesterday', '7d', 'cycle', '30d', 'custom'].includes(rawPeriod)
343
+ ? rawPeriod
344
+ : from
345
+ ? 'custom'
346
+ : 'today';
342
347
  const source = ['desktop', 'cli'].includes(url.searchParams.get('source'))
343
348
  ? url.searchParams.get('source')
344
349
  : 'all';
345
- const board = await buildBoardPayload(db, { period, source, envDefaults, now });
350
+ const board = await buildBoardPayload(db, { period, from, to, source, envDefaults, now });
346
351
  return jsonRes(board);
347
352
  }
348
353
 
@@ -351,19 +356,25 @@ export function createApp({
351
356
  const settings = await loadSettings(db, envDefaults);
352
357
  const viewErr = await requireViewKeyIfEnabled(request, url, settings, now);
353
358
  if (viewErr) return viewErr;
354
- const period = ['today', '7d', 'cycle', '30d'].includes(url.searchParams.get('period'))
355
- ? url.searchParams.get('period')
356
- : 'cycle';
359
+ const from = (url.searchParams.get('from') || '').trim();
360
+ const to = (url.searchParams.get('to') || '').trim();
361
+ const rawPeriod = url.searchParams.get('period');
362
+ const period = ['today', 'yesterday', '7d', 'cycle', '30d', 'custom'].includes(rawPeriod)
363
+ ? rawPeriod
364
+ : from
365
+ ? 'custom'
366
+ : 'cycle';
357
367
  const source = ['desktop', 'cli'].includes(url.searchParams.get('source'))
358
368
  ? url.searchParams.get('source')
359
369
  : 'all';
360
- const board = await buildBoardPayload(db, { period, source, envDefaults, now });
370
+ const board = await buildBoardPayload(db, { period, from, to, source, envDefaults, now });
361
371
  const csv = buildBoardCsv(board);
372
+ const fileTag = period === 'custom' && board.window ? `${board.window.fromDate}_${board.window.toDate}` : period;
362
373
  return new Response(csv, {
363
374
  status: 200,
364
375
  headers: {
365
376
  'Content-Type': 'text/csv; charset=utf-8',
366
- 'Content-Disposition': `attachment; filename="agy-family-${period}.csv"`,
377
+ 'Content-Disposition': `attachment; filename="agy-family-${fileTag}.csv"`,
367
378
  'Cache-Control': 'no-store',
368
379
  'Referrer-Policy': 'no-referrer',
369
380
  'X-Content-Type-Options': 'nosniff',
@@ -378,10 +389,15 @@ export function createApp({
378
389
  const viewErr = await requireViewKeyIfEnabled(request, url, settings, now);
379
390
  if (viewErr) return viewErr;
380
391
  const memberId = decodeURIComponent(boardMemberMatch[1]);
381
- const period = ['today', '7d', 'cycle', '30d'].includes(url.searchParams.get('period'))
382
- ? url.searchParams.get('period')
383
- : 'today';
384
- const detail = await buildMemberDetailPayload(db, memberId, { period, envDefaults, now });
392
+ const from = (url.searchParams.get('from') || '').trim();
393
+ const to = (url.searchParams.get('to') || '').trim();
394
+ const rawPeriod = url.searchParams.get('period');
395
+ const period = ['today', 'yesterday', '7d', 'cycle', '30d', 'custom'].includes(rawPeriod)
396
+ ? rawPeriod
397
+ : from
398
+ ? 'custom'
399
+ : 'today';
400
+ const detail = await buildMemberDetailPayload(db, memberId, { period, from, to, envDefaults, now });
385
401
  if (!detail) return jsonRes({ error: 'Member not found.' }, 404);
386
402
  return jsonRes(detail);
387
403
  }
@@ -261,7 +261,27 @@ export function computeCycleInfo({ now = Date.now(), timezoneOffsetMin = 480, cy
261
261
  };
262
262
  }
263
263
 
264
- export function getPeriodWindow(period, { now = Date.now(), timezoneOffsetMin = 480, cycleResetDay = 1 } = {}) {
264
+ function parseIsoDateParts(raw) {
265
+ const m = String(raw || '').trim().match(/^(\d{4})-(\d{2})-(\d{2})$/);
266
+ if (!m) return null;
267
+ const y = Number(m[1]);
268
+ const mo = Number(m[2]);
269
+ const d = Number(m[3]);
270
+ if (y < 2020 || y > 2100 || mo < 1 || mo > 12 || d < 1 || d > 31) return null;
271
+ const check = new Date(Date.UTC(y, mo - 1, d));
272
+ if (check.getUTCFullYear() !== y || check.getUTCMonth() !== mo - 1 || check.getUTCDate() !== d) return null;
273
+ return { y, mo, d, key: `${y}-${String(mo).padStart(2, '0')}-${String(d).padStart(2, '0')}` };
274
+ }
275
+
276
+ function formatLocalDateKey(utcMs, offsetMs) {
277
+ const dt = new Date(utcMs + offsetMs);
278
+ return `${dt.getUTCFullYear()}-${String(dt.getUTCMonth() + 1).padStart(2, '0')}-${String(dt.getUTCDate()).padStart(2, '0')}`;
279
+ }
280
+
281
+ export function getPeriodWindow(
282
+ period,
283
+ { now = Date.now(), timezoneOffsetMin = 480, cycleResetDay = 1, from = '', to = '' } = {},
284
+ ) {
265
285
  const offsetMs = (Number(timezoneOffsetMin) || 0) * 60 * 1000;
266
286
  const localNow = new Date(now + offsetMs);
267
287
  const y = localNow.getUTCFullYear();
@@ -271,15 +291,67 @@ export function getPeriodWindow(period, { now = Date.now(), timezoneOffsetMin =
271
291
  const localDayStartUtc = Date.UTC(y, m, d, 0, 0, 0) - offsetMs;
272
292
  const dateKey = `${y}-${String(m + 1).padStart(2, '0')}-${String(d).padStart(2, '0')}`;
273
293
 
294
+ if (period === 'custom' || (from && parseIsoDateParts(from))) {
295
+ const pFrom = parseIsoDateParts(from);
296
+ const pTo = parseIsoDateParts(to) || pFrom;
297
+ if (pFrom && pTo) {
298
+ let startDayUtc = Date.UTC(pFrom.y, pFrom.mo - 1, pFrom.d, 0, 0, 0) - offsetMs;
299
+ let endDayUtc = Date.UTC(pTo.y, pTo.mo - 1, pTo.d, 0, 0, 0) - offsetMs;
300
+ if (startDayUtc > endDayUtc) {
301
+ const tmp = startDayUtc;
302
+ startDayUtc = endDayUtc;
303
+ endDayUtc = tmp;
304
+ }
305
+ // Cap custom window at 366 days
306
+ if (endDayUtc - startDayUtc > 365 * DAY_MS) {
307
+ startDayUtc = endDayUtc - 365 * DAY_MS;
308
+ }
309
+ const endMs = endDayUtc + DAY_MS - 1;
310
+ const fromDate = formatLocalDateKey(startDayUtc, offsetMs);
311
+ const toDate = formatLocalDateKey(endDayUtc, offsetMs);
312
+ const days = Math.max(1, Math.round((endDayUtc - startDayUtc) / DAY_MS) + 1);
313
+ return {
314
+ period: 'custom',
315
+ startMs: startDayUtc,
316
+ endMs,
317
+ fromDate,
318
+ toDate,
319
+ days,
320
+ dateKey,
321
+ windowKey: `custom:${fromDate}..${toDate}`,
322
+ };
323
+ }
324
+ }
325
+
326
+ if (period === 'yesterday') {
327
+ const startMs = localDayStartUtc - DAY_MS;
328
+ const endMs = localDayStartUtc - 1;
329
+ const yKey = formatLocalDateKey(startMs, offsetMs);
330
+ return {
331
+ period: 'yesterday',
332
+ startMs,
333
+ endMs,
334
+ fromDate: yKey,
335
+ toDate: yKey,
336
+ days: 1,
337
+ dateKey,
338
+ windowKey: `yesterday:${yKey}`,
339
+ };
340
+ }
341
+
274
342
  if (period === '7d') {
275
343
  // ISO week key for alert deduplication (Monday-start local week)
276
344
  const dow = (localNow.getUTCDay() + 6) % 7;
277
345
  const weekStartDate = new Date(Date.UTC(y, m, d - dow, 0, 0, 0));
278
346
  const weekKey = `${weekStartDate.getUTCFullYear()}-${String(weekStartDate.getUTCMonth() + 1).padStart(2, '0')}-${String(weekStartDate.getUTCDate()).padStart(2, '0')}`;
347
+ const startMs = localDayStartUtc - 6 * DAY_MS;
279
348
  return {
280
349
  period: '7d',
281
- startMs: localDayStartUtc - 6 * DAY_MS,
350
+ startMs,
282
351
  endMs: now,
352
+ fromDate: formatLocalDateKey(startMs, offsetMs),
353
+ toDate: dateKey,
354
+ days: 7,
283
355
  dateKey,
284
356
  weekKey,
285
357
  windowKey: `7d:${weekKey}`,
@@ -287,10 +359,14 @@ export function getPeriodWindow(period, { now = Date.now(), timezoneOffsetMin =
287
359
  }
288
360
 
289
361
  if (period === '30d') {
362
+ const startMs = localDayStartUtc - 29 * DAY_MS;
290
363
  return {
291
364
  period: '30d',
292
- startMs: localDayStartUtc - 29 * DAY_MS,
365
+ startMs,
293
366
  endMs: now,
367
+ fromDate: formatLocalDateKey(startMs, offsetMs),
368
+ toDate: dateKey,
369
+ days: 30,
294
370
  dateKey,
295
371
  windowKey: `30d:${dateKey}`,
296
372
  };
@@ -309,10 +385,14 @@ export function getPeriodWindow(period, { now = Date.now(), timezoneOffsetMin =
309
385
  }
310
386
  const startMs = Date.UTC(cy, cm, resetDay, 0, 0, 0) - offsetMs;
311
387
  const cycleKey = `${cy}-${String(cm + 1).padStart(2, '0')}-${String(resetDay).padStart(2, '0')}`;
388
+ const days = Math.max(1, Math.floor((localDayStartUtc - startMs) / DAY_MS) + 1);
312
389
  return {
313
390
  period: 'cycle',
314
391
  startMs,
315
392
  endMs: now,
393
+ fromDate: cycleKey,
394
+ toDate: dateKey,
395
+ days,
316
396
  dateKey,
317
397
  windowKey: `cycle:${cycleKey}`,
318
398
  };
@@ -322,6 +402,9 @@ export function getPeriodWindow(period, { now = Date.now(), timezoneOffsetMin =
322
402
  period: 'today',
323
403
  startMs: localDayStartUtc,
324
404
  endMs: now,
405
+ fromDate: dateKey,
406
+ toDate: dateKey,
407
+ days: 1,
325
408
  dateKey,
326
409
  windowKey: `today:${dateKey}`,
327
410
  };
@@ -575,7 +658,10 @@ export async function computeCreditsReconciliation(db, members, settings, cycleI
575
658
  };
576
659
  }
577
660
 
578
- export async function buildBoardPayload(db, { period = 'today', source = 'all', envDefaults = {}, now = Date.now() } = {}) {
661
+ export async function buildBoardPayload(
662
+ db,
663
+ { period = 'today', from = '', to = '', source = 'all', envDefaults = {}, now = Date.now() } = {},
664
+ ) {
579
665
  const settings = await loadSettings(db, envDefaults);
580
666
  const sourceFilter = ['desktop', 'cli'].includes(source) ? source : 'all';
581
667
  const offsetMs = (Number(settings.timezoneOffsetMin) || 0) * 60 * 1000;
@@ -583,6 +669,8 @@ export async function buildBoardPayload(db, { period = 'today', source = 'all',
583
669
  now,
584
670
  timezoneOffsetMin: settings.timezoneOffsetMin,
585
671
  cycleResetDay: settings.cycleResetDay,
672
+ from,
673
+ to,
586
674
  });
587
675
  const cycleInfo = computeCycleInfo({
588
676
  now,
@@ -600,14 +688,20 @@ export async function buildBoardPayload(db, { period = 'today', source = 'all',
600
688
  cycleResetDay: settings.cycleResetDay,
601
689
  }).startMs;
602
690
 
603
- // Daily trend spans 7d for today/7d, 30d for 30d, and cycle start -> today (up to 31d) for cycle.
604
- const trendStartMs =
605
- win.period === '30d'
606
- ? win.startMs
607
- : win.period === 'cycle'
608
- ? Math.max(cycleInfo.cycleStartMs, todayStartMs - 30 * DAY_MS)
609
- : sevenDaysStart;
610
- const trendDaysCount = Math.max(1, Math.min(31, Math.floor((todayStartMs - trendStartMs) / DAY_MS) + 1));
691
+ // Daily trend spans selected custom range (up to 45d), 30d for 30d, cycle start->today for cycle, or 7d.
692
+ let trendStartMs = sevenDaysStart;
693
+ let trendEndDayStartMs = todayStartMs;
694
+ if (win.period === '30d') {
695
+ trendStartMs = win.startMs;
696
+ } else if (win.period === 'cycle') {
697
+ trendStartMs = Math.max(cycleInfo.cycleStartMs, todayStartMs - 30 * DAY_MS);
698
+ } else if (win.period === 'custom') {
699
+ const customEndDay = win.endMs + 1 - DAY_MS;
700
+ trendEndDayStartMs = customEndDay;
701
+ trendStartMs = Math.max(win.startMs, customEndDay - 44 * DAY_MS);
702
+ }
703
+ const trendDaysCount = Math.max(1, Math.min(45, Math.floor((trendEndDayStartMs - trendStartMs) / DAY_MS) + 1));
704
+ const trendEndMs = trendStartMs + trendDaysCount * DAY_MS - 1;
611
705
 
612
706
  const membersRaw = await db.all(
613
707
  'SELECT id, name, role, color, quota_pct, expected_email_hash, last_account_status, daily_cap_usd, weekly_cap_usd, cycle_cap_usd, active, created_at, last_seen_at, last_client_kind, last_client_version FROM members WHERE active = 1 ORDER BY created_at ASC',
@@ -641,12 +735,19 @@ export async function buildBoardPayload(db, { period = 'today', source = 'all',
641
735
  });
642
736
  }
643
737
 
644
- // Build 24h timeline slots
738
+ // Build 24h timeline slots (exact 00:00..23:00 for single-day yesterday/custom, rolling 24h otherwise)
645
739
  const curHour = Math.floor(now / HOUR_MS) * HOUR_MS;
646
740
  const hourlyMap = new Map();
647
- for (let i = 23; i >= 0; i--) {
648
- const h = curHour - i * HOUR_MS;
649
- hourlyMap.set(h, { hourMs: h, usd: 0, tokens: 0, steps: 0 });
741
+ if (win.period === 'yesterday' || (win.period === 'custom' && win.days === 1)) {
742
+ for (let i = 0; i < 24; i++) {
743
+ const h = win.startMs + i * HOUR_MS;
744
+ hourlyMap.set(h, { hourMs: h, usd: 0, tokens: 0, steps: 0 });
745
+ }
746
+ } else {
747
+ for (let i = 23; i >= 0; i--) {
748
+ const h = curHour - i * HOUR_MS;
749
+ hourlyMap.set(h, { hourMs: h, usd: 0, tokens: 0, steps: 0 });
750
+ }
650
751
  }
651
752
 
652
753
  // Build daily trend slots
@@ -696,7 +797,7 @@ export async function buildBoardPayload(db, { period = 'today', source = 'all',
696
797
  slot.steps += steps;
697
798
  }
698
799
 
699
- if (b.bucket_hour_ms >= trendStartMs) {
800
+ if (b.bucket_hour_ms >= trendStartMs && b.bucket_hour_ms <= trendEndMs) {
700
801
  const dayIdx = Math.floor((b.bucket_hour_ms - trendStartMs) / DAY_MS);
701
802
  const dayKey = trendStartMs + dayIdx * DAY_MS;
702
803
  const dSlot = dailyTrendMap.get(dayKey);
@@ -713,7 +814,7 @@ export async function buildBoardPayload(db, { period = 'today', source = 'all',
713
814
  cycleUsedUsd += usd;
714
815
  }
715
816
 
716
- if (b.bucket_hour_ms < win.startMs) continue;
817
+ if (b.bucket_hour_ms < win.startMs || b.bucket_hour_ms > win.endMs) continue;
717
818
 
718
819
  const entry = byMember.get(b.member_id);
719
820
  if (!entry) continue;
@@ -911,6 +1012,14 @@ export async function buildBoardPayload(db, { period = 'today', source = 'all',
911
1012
  period: win.period,
912
1013
  source: sourceFilter,
913
1014
  windowStartMs: win.startMs,
1015
+ windowEndMs: win.endMs,
1016
+ window: {
1017
+ startMs: win.startMs,
1018
+ endMs: win.endMs,
1019
+ fromDate: win.fromDate,
1020
+ toDate: win.toDate,
1021
+ days: win.days,
1022
+ },
914
1023
  generatedAt: now,
915
1024
  rules: {
916
1025
  maxMembers: MAX_FAMILY_MEMBERS,
@@ -1037,7 +1146,11 @@ export async function checkOfflineMembersAndAlert(
1037
1146
  };
1038
1147
  }
1039
1148
 
1040
- export async function buildMemberDetailPayload(db, memberId, { period = 'today', envDefaults = {}, now = Date.now() } = {}) {
1149
+ export async function buildMemberDetailPayload(
1150
+ db,
1151
+ memberId,
1152
+ { period = 'today', from = '', to = '', envDefaults = {}, now = Date.now() } = {},
1153
+ ) {
1041
1154
  const member = await db.get(
1042
1155
  'SELECT id, name, role, color, quota_pct, expected_email_hash, last_account_status, daily_cap_usd, weekly_cap_usd, cycle_cap_usd, active, created_at, last_seen_at, last_client_kind, last_client_version FROM members WHERE id = ? AND active = 1',
1043
1156
  [memberId],
@@ -1057,6 +1170,8 @@ export async function buildMemberDetailPayload(db, memberId, { period = 'today',
1057
1170
  now,
1058
1171
  timezoneOffsetMin: settings.timezoneOffsetMin,
1059
1172
  cycleResetDay: settings.cycleResetDay,
1173
+ from,
1174
+ to,
1060
1175
  });
1061
1176
  const todayWin = getPeriodWindow('today', {
1062
1177
  now,
@@ -1092,7 +1207,7 @@ export async function buildMemberDetailPayload(db, memberId, { period = 'today',
1092
1207
  if (gr.bucket_hour_ms >= todayWin.startMs) groupTodayUsd += u;
1093
1208
  if (gr.bucket_hour_ms >= weeklyWin.startMs) groupWeeklyUsd += u;
1094
1209
  if (gr.bucket_hour_ms >= cycleWin.startMs) groupCycleUsd += u;
1095
- if (gr.bucket_hour_ms >= win.startMs) groupPeriodUsd += u;
1210
+ if (gr.bucket_hour_ms >= win.startMs && gr.bucket_hour_ms <= win.endMs) groupPeriodUsd += u;
1096
1211
  }
1097
1212
  groupTodayUsd = roundUsd(groupTodayUsd);
1098
1213
  groupWeeklyUsd = roundUsd(groupWeeklyUsd);
@@ -1167,7 +1282,7 @@ export async function buildMemberDetailPayload(db, memberId, { period = 'today',
1167
1282
  }
1168
1283
  }
1169
1284
 
1170
- if (b.bucket_hour_ms < win.startMs) continue;
1285
+ if (b.bucket_hour_ms < win.startMs || b.bucket_hour_ms > win.endMs) continue;
1171
1286
  const devId = String(b.device_id || 'unknown');
1172
1287
  const dev = deviceMap.get(devId) || {
1173
1288
  deviceId: devId,
@@ -227,7 +227,12 @@ export function renderDashboardHtml({ boardTitle = 'Antigravity Family Board' }
227
227
  color: var(--ink);
228
228
  box-shadow: 0 0 0 1px var(--hairline);
229
229
  }
230
+ .seg-group button.is-tab-loading::after,
231
+ .range-trigger.is-tab-loading .range-chev {
232
+ display: none;
233
+ }
230
234
  .seg-group button.is-tab-loading::after {
235
+ display: inline-block;
231
236
  content: "";
232
237
  width: 9px;
233
238
  height: 9px;
@@ -237,6 +242,223 @@ export function renderDashboardHtml({ boardTitle = 'Antigravity Family Board' }
237
242
  animation: agf-spin 0.65s linear infinite;
238
243
  flex-shrink: 0;
239
244
  }
245
+ .range-picker {
246
+ position: relative;
247
+ display: inline-flex;
248
+ }
249
+ .range-trigger {
250
+ display: inline-flex;
251
+ align-items: center;
252
+ gap: 6px;
253
+ height: 28px;
254
+ padding: 0 10px;
255
+ border-radius: var(--r-md);
256
+ background: var(--surface-card);
257
+ border: 1px solid var(--hairline-strong);
258
+ color: var(--ink);
259
+ font-size: 12.5px;
260
+ font-weight: 500;
261
+ cursor: pointer;
262
+ white-space: nowrap;
263
+ line-height: 1;
264
+ transition: border-color 0.16s ease, background-color 0.16s ease, box-shadow 0.16s ease;
265
+ }
266
+ .range-trigger:hover {
267
+ background: var(--canvas-soft);
268
+ border-color: var(--muted);
269
+ }
270
+ .range-picker.open .range-trigger {
271
+ border-color: var(--primary);
272
+ box-shadow: 0 0 0 2px rgba(245, 78, 0, 0.12);
273
+ }
274
+ .range-ico { color: var(--muted); flex-shrink: 0; }
275
+ .range-picker.open .range-ico { color: var(--primary); }
276
+ .range-dates {
277
+ font-size: 11.5px;
278
+ color: var(--muted);
279
+ font-weight: 400;
280
+ }
281
+ .range-dates:empty { display: none; }
282
+ .range-dates::before { content: "· "; opacity: 0.7; }
283
+ .range-chev {
284
+ color: var(--muted);
285
+ flex-shrink: 0;
286
+ transition: transform 0.16s ease;
287
+ }
288
+ .range-picker.open .range-chev { transform: rotate(180deg); color: var(--ink); }
289
+ .range-trigger.is-tab-loading::after {
290
+ content: "";
291
+ width: 10px;
292
+ height: 10px;
293
+ border-radius: 50%;
294
+ border: 1.5px solid var(--hairline-strong);
295
+ border-top-color: var(--primary);
296
+ animation: agf-spin 0.65s linear infinite;
297
+ flex-shrink: 0;
298
+ }
299
+ .range-popover {
300
+ display: none;
301
+ position: absolute;
302
+ top: calc(100% + 6px);
303
+ left: 0;
304
+ z-index: 180;
305
+ background: var(--surface-card);
306
+ border: 1px solid var(--hairline-strong);
307
+ border-radius: var(--r-lg);
308
+ box-shadow: 0 12px 32px rgba(0, 0, 0, 0.11), 0 2px 6px rgba(0, 0, 0, 0.05);
309
+ width: 416px;
310
+ max-width: calc(100vw - 24px);
311
+ overflow: hidden;
312
+ }
313
+ [data-theme="dark"] .range-popover {
314
+ box-shadow: 0 16px 38px rgba(0, 0, 0, 0.45);
315
+ }
316
+ .range-picker.open .range-popover {
317
+ display: flex;
318
+ animation: agf-pane-in 0.15s cubic-bezier(0.22, 1, 0.36, 1);
319
+ }
320
+ .range-presets {
321
+ width: 124px;
322
+ flex-shrink: 0;
323
+ padding: 10px 8px;
324
+ background: var(--canvas-soft);
325
+ border-right: 1px solid var(--hairline);
326
+ display: flex;
327
+ flex-direction: column;
328
+ gap: 2px;
329
+ }
330
+ .range-presets-title {
331
+ font-size: 10.5px;
332
+ font-weight: 600;
333
+ color: var(--muted);
334
+ padding: 2px 8px 6px;
335
+ letter-spacing: 0.02em;
336
+ }
337
+ .range-presets button {
338
+ display: flex;
339
+ align-items: center;
340
+ justify-content: space-between;
341
+ width: 100%;
342
+ border: none;
343
+ background: transparent;
344
+ color: var(--body);
345
+ font-size: 12.5px;
346
+ font-weight: 500;
347
+ padding: 6px 8px;
348
+ border-radius: 6px;
349
+ cursor: pointer;
350
+ text-align: left;
351
+ transition: background-color 0.13s ease, color 0.13s ease;
352
+ }
353
+ .range-presets button:hover {
354
+ background: var(--hover);
355
+ color: var(--ink);
356
+ }
357
+ .range-presets button.active {
358
+ background: var(--surface-card);
359
+ color: var(--primary);
360
+ box-shadow: 0 0 0 1px var(--hairline);
361
+ }
362
+ .range-cal {
363
+ flex: 1;
364
+ padding: 11px 12px 10px;
365
+ display: flex;
366
+ flex-direction: column;
367
+ gap: 8px;
368
+ min-width: 0;
369
+ }
370
+ .cal-head {
371
+ display: flex;
372
+ align-items: center;
373
+ justify-content: space-between;
374
+ gap: 6px;
375
+ }
376
+ .cal-month-title {
377
+ font-size: 12.5px;
378
+ font-weight: 600;
379
+ color: var(--ink);
380
+ }
381
+ .cal-nav-btn {
382
+ width: 24px;
383
+ height: 24px;
384
+ display: inline-flex;
385
+ align-items: center;
386
+ justify-content: center;
387
+ border: 1px solid var(--hairline);
388
+ background: var(--surface-card);
389
+ color: var(--body);
390
+ border-radius: 6px;
391
+ cursor: pointer;
392
+ font-size: 13px;
393
+ line-height: 1;
394
+ }
395
+ .cal-nav-btn:hover { background: var(--hover); color: var(--ink); }
396
+ .cal-nav-btn:disabled { opacity: 0.35; cursor: not-allowed; }
397
+ .cal-weekdays, .cal-days {
398
+ display: grid;
399
+ grid-template-columns: repeat(7, 1fr);
400
+ gap: 2px;
401
+ }
402
+ .cal-weekdays span {
403
+ text-align: center;
404
+ font-size: 10.5px;
405
+ color: var(--muted);
406
+ padding: 2px 0;
407
+ }
408
+ .cal-day {
409
+ height: 28px;
410
+ border: none;
411
+ background: transparent;
412
+ color: var(--ink);
413
+ font-size: 12px;
414
+ font-family: var(--font-mono);
415
+ border-radius: 6px;
416
+ cursor: pointer;
417
+ position: relative;
418
+ transition: background-color 0.1s ease, color 0.1s ease;
419
+ }
420
+ .cal-day:hover:not(:disabled):not(.edge) {
421
+ background: var(--hover);
422
+ }
423
+ .cal-day.other-month { color: var(--muted); opacity: 0.45; }
424
+ .cal-day:disabled { opacity: 0.28; cursor: not-allowed; }
425
+ .cal-day.is-today:not(.edge)::after {
426
+ content: "";
427
+ position: absolute;
428
+ bottom: 3px;
429
+ left: 50%;
430
+ transform: translateX(-50%);
431
+ width: 4px;
432
+ height: 4px;
433
+ border-radius: 50%;
434
+ background: var(--primary);
435
+ }
436
+ .cal-day.in-range {
437
+ background: rgba(245, 78, 0, 0.12);
438
+ color: var(--ink);
439
+ border-radius: 3px;
440
+ }
441
+ .cal-day.edge {
442
+ background: var(--primary);
443
+ color: #fff;
444
+ font-weight: 600;
445
+ border-radius: 6px;
446
+ }
447
+ .cal-foot {
448
+ display: flex;
449
+ align-items: center;
450
+ justify-content: space-between;
451
+ gap: 8px;
452
+ padding-top: 8px;
453
+ border-top: 1px solid var(--hairline);
454
+ }
455
+ .cal-summary {
456
+ font-size: 11px;
457
+ color: var(--muted);
458
+ overflow: hidden;
459
+ text-overflow: ellipsis;
460
+ white-space: nowrap;
461
+ }
240
462
 
241
463
  .header-actions {
242
464
  display: flex;
@@ -1232,6 +1454,7 @@ export function renderDashboardHtml({ boardTitle = 'Antigravity Family Board' }
1232
1454
  @media (prefers-reduced-motion: reduce) {
1233
1455
  .top-progress-bar, .panel-load-line::after, .skel, .inline-spin,
1234
1456
  .btn.btn-loading::before, .seg-group button.is-tab-loading::after,
1457
+ .range-trigger.is-tab-loading::after, .range-picker.open .range-popover,
1235
1458
  .icon-refresh.spinning svg, .tab-pane.active, .agf-reveal, .svg-chart.chart-pop {
1236
1459
  animation: none !important;
1237
1460
  }
@@ -1252,6 +1475,10 @@ export function renderDashboardHtml({ boardTitle = 'Antigravity Family Board' }
1252
1475
  .kpi-grid { grid-template-columns: 1fr; }
1253
1476
  .row-2, .row-3 { grid-template-columns: 1fr; }
1254
1477
  .detail-grid { grid-template-columns: 1fr; }
1478
+ .range-picker.open .range-popover { flex-direction: column; width: min(320px, calc(100vw - 24px)); }
1479
+ .range-presets { width: 100%; border-right: none; border-bottom: 1px solid var(--hairline); flex-direction: row; flex-wrap: wrap; }
1480
+ .range-presets-title { width: 100%; }
1481
+ .range-presets button { width: auto; }
1255
1482
  }
1256
1483
  </style>
1257
1484
  </head>
@@ -1277,11 +1504,41 @@ export function renderDashboardHtml({ boardTitle = 'Antigravity Family Board' }
1277
1504
  </div>
1278
1505
 
1279
1506
  <div class="header-controls">
1280
- <div class="seg-group" id="periodTabs">
1281
- <button data-p="today" class="active" data-i18n="today">今日</button>
1282
- <button data-p="7d" data-i18n="week">近 7 天</button>
1283
- <button data-p="cycle" data-i18n="cycle">本周期</button>
1284
- <button data-p="30d" data-i18n="days30">30 天</button>
1507
+ <div class="range-picker" id="rangePicker">
1508
+ <button type="button" class="range-trigger" id="rangeTrigger" aria-haspopup="dialog" aria-expanded="false">
1509
+ <svg class="range-ico" width="13" height="13" viewBox="0 0 16 16" fill="none" aria-hidden="true">
1510
+ <rect x="2" y="3.2" width="12" height="10.8" rx="2" stroke="currentColor" stroke-width="1.4"/>
1511
+ <path d="M2 6.5H14M5.3 1.8V4.2M10.7 1.8V4.2" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"/>
1512
+ </svg>
1513
+ <span class="range-label" id="rangeLabel">今日</span>
1514
+ <span class="range-dates mono" id="rangeDates"></span>
1515
+ <svg class="range-chev" width="11" height="11" viewBox="0 0 16 16" fill="none" aria-hidden="true">
1516
+ <path d="M4.5 6.5L8 10L11.5 6.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
1517
+ </svg>
1518
+ </button>
1519
+ <div class="range-popover" id="rangePopover" role="dialog" aria-label="Date range">
1520
+ <div class="range-presets" id="periodPresets">
1521
+ <div class="range-presets-title" id="rangePresetsTitle">快捷范围</div>
1522
+ <button type="button" data-p="today" class="active" data-i18n="today">今日</button>
1523
+ <button type="button" data-p="yesterday" id="presetYesterdayBtn">昨日</button>
1524
+ <button type="button" data-p="7d" data-i18n="week">近 7 天</button>
1525
+ <button type="button" data-p="cycle" data-i18n="cycle">本周期</button>
1526
+ <button type="button" data-p="30d" data-i18n="days30">30 天</button>
1527
+ </div>
1528
+ <div class="range-cal">
1529
+ <div class="cal-head">
1530
+ <button type="button" class="cal-nav-btn" id="calPrevBtn" aria-label="Previous month">‹</button>
1531
+ <span class="cal-month-title mono" id="calMonthTitle"></span>
1532
+ <button type="button" class="cal-nav-btn" id="calNextBtn" aria-label="Next month">›</button>
1533
+ </div>
1534
+ <div class="cal-weekdays" id="calWeekdays"></div>
1535
+ <div class="cal-days" id="calDays"></div>
1536
+ <div class="cal-foot">
1537
+ <span class="cal-summary mono" id="calSummary"></span>
1538
+ <button type="button" class="btn btn-primary btn-sm" id="calApplyBtn">应用</button>
1539
+ </div>
1540
+ </div>
1541
+ </div>
1285
1542
  </div>
1286
1543
  <div class="seg-group" id="sourceFilter">
1287
1544
  <button data-src="all" class="active" data-i18n="srcAll">全部</button>
@@ -1416,7 +1673,7 @@ export function renderDashboardHtml({ boardTitle = 'Antigravity Family Board' }
1416
1673
 
1417
1674
  <footer class="foot">
1418
1675
  <span data-i18n="privacyNote">隐私承诺:客户端仅只读扫描本地 SQLite 数值元数据,绝不上传 Prompt、代码、文件路径或 Google 凭据。</span>
1419
- <span class="mono">agy-family v0.2.9 · MIT</span>
1676
+ <span class="mono">agy-family v0.2.10 · MIT</span>
1420
1677
  </footer>
1421
1678
  </main>
1422
1679
 
@@ -1730,6 +1987,14 @@ const I18N = {
1730
1987
  let lang = localStorage.getItem('agf_lang') || (navigator.language?.startsWith('zh') ? 'zh' : 'en');
1731
1988
  let theme = localStorage.getItem('agf_theme') || 'light';
1732
1989
  let period = 'today';
1990
+ let customFrom = '';
1991
+ let customTo = '';
1992
+ let boardTzOffsetMin = 480;
1993
+ let calYear = new Date().getFullYear();
1994
+ let calMonth = new Date().getMonth();
1995
+ let draftFrom = '';
1996
+ let draftTo = '';
1997
+ let hoverDay = '';
1733
1998
  let sourceFilter = 'all';
1734
1999
  let sortKey = 'usd';
1735
2000
  let sortDir = 'desc';
@@ -1858,6 +2123,13 @@ function applyI18n() {
1858
2123
  const k = el.getAttribute('data-i18n');
1859
2124
  if (I18N[lang][k]) el.textContent = I18N[lang][k];
1860
2125
  });
2126
+ const pt = document.getElementById('rangePresetsTitle');
2127
+ if (pt) pt.textContent = lang === 'zh' ? '快捷范围' : 'Presets';
2128
+ const yb = document.getElementById('presetYesterdayBtn');
2129
+ if (yb) yb.textContent = lang === 'zh' ? '昨日' : 'Yesterday';
2130
+ const ab = document.getElementById('calApplyBtn');
2131
+ if (ab) ab.textContent = lang === 'zh' ? '应用' : 'Apply';
2132
+ updateRangeTriggerLabel(lastBoardData?.window || null);
1861
2133
  updateAdminHeaderTitle();
1862
2134
  renderGuideBody();
1863
2135
  }
@@ -1908,8 +2180,20 @@ function setTopProgress(loading) {
1908
2180
  }
1909
2181
  }
1910
2182
 
2183
+ function buildBoardQueryParams(includeSource) {
2184
+ const qs = new URLSearchParams({ period });
2185
+ if (period === 'custom' && customFrom) {
2186
+ qs.set('from', customFrom);
2187
+ qs.set('to', customTo || customFrom);
2188
+ }
2189
+ if (includeSource && sourceFilter !== 'all') qs.set('source', sourceFilter);
2190
+ return qs;
2191
+ }
2192
+
1911
2193
  function clearTabLoadingSpinners() {
1912
- document.querySelectorAll('.seg-group button.is-tab-loading').forEach((b) => b.classList.remove('is-tab-loading'));
2194
+ document.querySelectorAll('.seg-group button.is-tab-loading, .range-trigger.is-tab-loading').forEach((b) => {
2195
+ b.classList.remove('is-tab-loading');
2196
+ });
1913
2197
  }
1914
2198
 
1915
2199
  async function withBtnLoading(btn, fn) {
@@ -1998,8 +2282,7 @@ async function fetchBoard(opts) {
1998
2282
  }
1999
2283
  }
2000
2284
 
2001
- const qs = new URLSearchParams({ period });
2002
- if (sourceFilter !== 'all') qs.set('source', sourceFilter);
2285
+ const qs = buildBoardQueryParams(true);
2003
2286
  try {
2004
2287
  const res = await fetch('/api/board?' + qs.toString(), { headers: viewHeaders() });
2005
2288
  if (seq !== boardReqSeq) return;
@@ -2058,7 +2341,20 @@ function renderActivityChart(d) {
2058
2341
  if (head) {
2059
2342
  if (isDaily) {
2060
2343
  const nDays = (d.dailyTrend || []).length || 7;
2061
- head.textContent = lang === 'zh' ? '近 ' + nDays + ' 天每日占比走势' : 'Daily usage share (' + nDays + 'd)';
2344
+ if (d.period === 'custom' && d.window?.fromDate) {
2345
+ const sLbl = fmtShortDate(d.window.fromDate);
2346
+ const eLbl = fmtShortDate(d.window.toDate || d.window.fromDate);
2347
+ head.textContent = lang === 'zh'
2348
+ ? (sLbl === eLbl ? sLbl : sLbl + '–' + eLbl) + ' 每日占比走势'
2349
+ : 'Daily share (' + (sLbl === eLbl ? sLbl : sLbl + '–' + eLbl) + ')';
2350
+ } else {
2351
+ head.textContent = lang === 'zh' ? '近 ' + nDays + ' 天每日占比走势' : 'Daily usage share (' + nDays + 'd)';
2352
+ }
2353
+ } else if (d.period === 'yesterday') {
2354
+ head.textContent = lang === 'zh' ? '昨日 24 小时用量占比节律' : 'Yesterday 24h usage rhythm';
2355
+ } else if (d.period === 'custom' && d.window?.days === 1 && d.window?.fromDate) {
2356
+ const sLbl = fmtShortDate(d.window.fromDate);
2357
+ head.textContent = lang === 'zh' ? sLbl + ' 24 小时用量占比节律' : sLbl + ' 24h usage rhythm';
2062
2358
  } else {
2063
2359
  head.textContent = t('hourlyTitle');
2064
2360
  }
@@ -2149,7 +2445,7 @@ async function loadMemberDetail(memberId) {
2149
2445
  '<div class="detail-col"><div class="skel" style="width:88px;height:11px;margin-bottom:8px"></div><div class="skel" style="width:100%;height:12px;margin-bottom:6px"></div><div class="skel" style="width:74%;height:12px"></div></div>' +
2150
2446
  '</div>' +
2151
2447
  '</div>';
2152
- const qs = new URLSearchParams({ period });
2448
+ const qs = buildBoardQueryParams(false);
2153
2449
  try {
2154
2450
  const res = await fetch('/api/board/member/' + encodeURIComponent(memberId) + '?' + qs.toString(), { headers: viewHeaders() });
2155
2451
  if (seq !== detailReqSeq) return;
@@ -2419,19 +2715,33 @@ function renderBoard(d) {
2419
2715
  const isPoolMode = s.quotaMode === 'pool';
2420
2716
  const maxSeats = d.rules.maxMembers || 6;
2421
2717
 
2718
+ if (d.rules && Number.isFinite(Number(d.rules.timezoneOffsetMin))) {
2719
+ boardTzOffsetMin = Number(d.rules.timezoneOffsetMin);
2720
+ }
2721
+ updateRangeTriggerLabel(d.window || null);
2722
+
2422
2723
  // KPI 1: Hero Usage / Pool %
2724
+ const winFromShort = d.window?.fromDate ? fmtShortDate(d.window.fromDate) : '';
2725
+ const winToShort = d.window?.toDate ? fmtShortDate(d.window.toDate) : winFromShort;
2726
+ const customRangeTitle = winFromShort
2727
+ ? (winFromShort === winToShort ? winFromShort : winFromShort + ' – ' + winToShort)
2728
+ : (lang === 'zh' ? '自定义范围' : 'Custom range');
2423
2729
  const periodNames = isPoolMode
2424
2730
  ? {
2425
2731
  today: lang === 'zh' ? '今日共享总池已用' : 'Today pool used',
2732
+ yesterday: lang === 'zh' ? '昨日共享总池已用' : 'Yesterday pool used',
2426
2733
  '7d': lang === 'zh' ? '近 7 天共享总池已用' : '7d pool used',
2427
2734
  cycle: lang === 'zh' ? '本周期共享总池已用' : 'Cycle pool used',
2428
2735
  '30d': lang === 'zh' ? '近 30 天共享总池已用' : '30d pool used',
2736
+ custom: lang === 'zh' ? customRangeTitle + ' 共享总池已用' : customRangeTitle + ' pool used',
2429
2737
  }
2430
2738
  : {
2431
2739
  today: lang === 'zh' ? '今日家庭组总用量' : 'Today family usage',
2740
+ yesterday: lang === 'zh' ? '昨日家庭组总用量' : 'Yesterday family usage',
2432
2741
  '7d': lang === 'zh' ? '近 7 天家庭组总用量' : '7-day family usage',
2433
2742
  cycle: lang === 'zh' ? '本周期家庭组总用量' : 'Cycle family usage',
2434
2743
  '30d': lang === 'zh' ? '近 30 天家庭组总用量' : '30-day family usage',
2744
+ custom: lang === 'zh' ? customRangeTitle + ' 家庭组总用量' : customRangeTitle + ' usage',
2435
2745
  };
2436
2746
  document.getElementById('heroEyebrow').textContent = periodNames[d.period] || t('heroSpend');
2437
2747
  document.getElementById('heroPacingReset').textContent = cyc.nextResetLabel
@@ -3067,19 +3377,273 @@ document.getElementById('checkOfflineBtn').addEventListener('click', async () =>
3067
3377
 
3068
3378
  document.getElementById('refreshBtn')?.addEventListener('click', () => fetchBoard());
3069
3379
 
3070
- document.querySelectorAll('#periodTabs button').forEach((btn) => {
3380
+ function fmtShortDate(isoKey) {
3381
+ const parts = String(isoKey || '').split('-');
3382
+ if (parts.length !== 3) return String(isoKey || '');
3383
+ return parts[1] + '/' + parts[2];
3384
+ }
3385
+
3386
+ function getTodayBoardKey() {
3387
+ const d = new Date(Date.now() + (Number(boardTzOffsetMin) || 0) * 60000);
3388
+ return d.getUTCFullYear() + '-' + String(d.getUTCMonth() + 1).padStart(2, '0') + '-' + String(d.getUTCDate()).padStart(2, '0');
3389
+ }
3390
+
3391
+ function isoDateDiffDays(aKey, bKey) {
3392
+ const pa = String(aKey || '').split('-').map(Number);
3393
+ const pb = String(bKey || '').split('-').map(Number);
3394
+ if (pa.length !== 3 || pb.length !== 3) return 1;
3395
+ const ta = Date.UTC(pa[0], pa[1] - 1, pa[2]);
3396
+ const tb = Date.UTC(pb[0], pb[1] - 1, pb[2]);
3397
+ return Math.round(Math.abs(tb - ta) / 86400000) + 1;
3398
+ }
3399
+
3400
+ function updateRangeTriggerLabel(winObj) {
3401
+ const lblEl = document.getElementById('rangeLabel');
3402
+ const datesEl = document.getElementById('rangeDates');
3403
+ if (!lblEl || !datesEl) return;
3404
+
3405
+ const wFrom = winObj?.fromDate || (period === 'custom' ? customFrom : '');
3406
+ const wTo = winObj?.toDate || (period === 'custom' ? (customTo || customFrom) : '');
3407
+ const presetLabels = {
3408
+ today: t('today'),
3409
+ yesterday: lang === 'zh' ? '昨日' : 'Yesterday',
3410
+ '7d': t('week'),
3411
+ cycle: t('cycle'),
3412
+ '30d': t('days30'),
3413
+ };
3414
+
3415
+ if (period === 'custom' && wFrom) {
3416
+ const s = fmtShortDate(wFrom);
3417
+ const e = fmtShortDate(wTo || wFrom);
3418
+ const days = winObj?.days || isoDateDiffDays(wFrom, wTo || wFrom);
3419
+ lblEl.textContent = s === e ? s : s + ' – ' + e;
3420
+ datesEl.textContent = days === 1
3421
+ ? (lang === 'zh' ? '单日' : '1d')
3422
+ : (lang === 'zh' ? days + ' 天' : days + 'd');
3423
+ } else {
3424
+ lblEl.textContent = presetLabels[period] || t('today');
3425
+ if (wFrom) {
3426
+ const s = fmtShortDate(wFrom);
3427
+ const e = fmtShortDate(wTo || wFrom);
3428
+ datesEl.textContent = s === e ? s : s + '–' + e;
3429
+ } else {
3430
+ datesEl.textContent = '';
3431
+ }
3432
+ }
3433
+
3434
+ document.querySelectorAll('#periodPresets button').forEach((b) => {
3435
+ b.classList.toggle('active', b.getAttribute('data-p') === period);
3436
+ });
3437
+ }
3438
+
3439
+ function renderRangeCalendar() {
3440
+ const titleEl = document.getElementById('calMonthTitle');
3441
+ const wkEl = document.getElementById('calWeekdays');
3442
+ const daysEl = document.getElementById('calDays');
3443
+ const sumEl = document.getElementById('calSummary');
3444
+ const applyBtn = document.getElementById('calApplyBtn');
3445
+ const nextBtn = document.getElementById('calNextBtn');
3446
+ if (!titleEl || !wkEl || !daysEl) return;
3447
+
3448
+ const todayKey = getTodayBoardKey();
3449
+ const todayParts = todayKey.split('-').map(Number);
3450
+ const enMonths = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
3451
+ titleEl.textContent = lang === 'zh'
3452
+ ? calYear + '年 ' + String(calMonth + 1).padStart(2, '0') + '月'
3453
+ : enMonths[calMonth] + ' ' + calYear;
3454
+
3455
+ if (nextBtn) {
3456
+ nextBtn.disabled = calYear > todayParts[0] || (calYear === todayParts[0] && calMonth >= todayParts[1] - 1);
3457
+ }
3458
+
3459
+ const wds = lang === 'zh' ? ['一', '二', '三', '四', '五', '六', '日'] : ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'];
3460
+ wkEl.innerHTML = wds.map((w) => '<span>' + w + '</span>').join('');
3461
+
3462
+ const firstDow = (new Date(Date.UTC(calYear, calMonth, 1)).getUTCDay() + 6) % 7;
3463
+ const daysInMonth = new Date(Date.UTC(calYear, calMonth + 1, 0)).getUTCDate();
3464
+ const prevMonthDays = new Date(Date.UTC(calYear, calMonth, 0)).getUTCDate();
3465
+
3466
+ let rangeA = draftFrom;
3467
+ let rangeB = draftTo || (draftFrom && hoverDay ? hoverDay : '');
3468
+ if (rangeA && rangeB && rangeA > rangeB) {
3469
+ const tmp = rangeA;
3470
+ rangeA = rangeB;
3471
+ rangeB = tmp;
3472
+ }
3473
+
3474
+ const cells = [];
3475
+ for (let i = 0; i < 42; i++) {
3476
+ let y = calYear;
3477
+ let m = calMonth;
3478
+ let d = 1;
3479
+ let isOther = false;
3480
+ if (i < firstDow) {
3481
+ isOther = true;
3482
+ m -= 1;
3483
+ if (m < 0) { m = 11; y -= 1; }
3484
+ d = prevMonthDays - firstDow + i + 1;
3485
+ } else if (i >= firstDow + daysInMonth) {
3486
+ isOther = true;
3487
+ m += 1;
3488
+ if (m > 11) { m = 0; y += 1; }
3489
+ d = i - firstDow - daysInMonth + 1;
3490
+ } else {
3491
+ d = i - firstDow + 1;
3492
+ }
3493
+ const key = y + '-' + String(m + 1).padStart(2, '0') + '-' + String(d).padStart(2, '0');
3494
+ const isFuture = key > todayKey;
3495
+ const isEdge = Boolean((rangeA && key === rangeA) || (rangeB && key === rangeB));
3496
+ const inRange = Boolean(rangeA && rangeB && key > rangeA && key < rangeB);
3497
+ const cls = ['cal-day'];
3498
+ if (isOther) cls.push('other-month');
3499
+ if (key === todayKey) cls.push('is-today');
3500
+ if (isEdge) cls.push('edge');
3501
+ else if (inRange) cls.push('in-range');
3502
+ cells.push(
3503
+ '<button type="button" class="' + cls.join(' ') + '" data-day="' + key + '"' + (isFuture ? ' disabled' : '') + '>' + d + '</button>',
3504
+ );
3505
+ }
3506
+ daysEl.innerHTML = cells.join('');
3507
+
3508
+ if (sumEl) {
3509
+ if (draftFrom && draftTo) {
3510
+ const a = draftFrom <= draftTo ? draftFrom : draftTo;
3511
+ const b = draftFrom <= draftTo ? draftTo : draftFrom;
3512
+ const cnt = isoDateDiffDays(a, b);
3513
+ sumEl.textContent = a === b
3514
+ ? fmtShortDate(a) + (lang === 'zh' ? ' (单日)' : ' (1d)')
3515
+ : fmtShortDate(a) + ' → ' + fmtShortDate(b) + ' · ' + cnt + (lang === 'zh' ? ' 天' : 'd');
3516
+ } else if (draftFrom) {
3517
+ sumEl.textContent = lang === 'zh'
3518
+ ? '起点 ' + fmtShortDate(draftFrom) + ',再点选结束日'
3519
+ : 'Start ' + fmtShortDate(draftFrom) + ', pick end date';
3520
+ } else {
3521
+ sumEl.textContent = lang === 'zh' ? '点击日期选择起止范围' : 'Click start & end dates';
3522
+ }
3523
+ }
3524
+ if (applyBtn) {
3525
+ applyBtn.disabled = !draftFrom;
3526
+ }
3527
+ }
3528
+
3529
+ function openRangePopover() {
3530
+ const picker = document.getElementById('rangePicker');
3531
+ const trigger = document.getElementById('rangeTrigger');
3532
+ if (!picker || !trigger) return;
3533
+ const win = lastBoardData?.window;
3534
+ const todayKey = getTodayBoardKey();
3535
+ draftFrom = period === 'custom' && customFrom ? customFrom : (win?.fromDate || todayKey);
3536
+ draftTo = period === 'custom' && (customTo || customFrom) ? (customTo || customFrom) : (win?.toDate || todayKey);
3537
+ hoverDay = '';
3538
+ const anchorParts = (draftTo || todayKey).split('-').map(Number);
3539
+ if (anchorParts.length === 3) {
3540
+ calYear = anchorParts[0];
3541
+ calMonth = anchorParts[1] - 1;
3542
+ }
3543
+ renderRangeCalendar();
3544
+ picker.classList.add('open');
3545
+ trigger.setAttribute('aria-expanded', 'true');
3546
+ }
3547
+
3548
+ function closeRangePopover() {
3549
+ const picker = document.getElementById('rangePicker');
3550
+ const trigger = document.getElementById('rangeTrigger');
3551
+ if (picker) picker.classList.remove('open');
3552
+ if (trigger) trigger.setAttribute('aria-expanded', 'false');
3553
+ }
3554
+
3555
+ document.getElementById('rangeTrigger')?.addEventListener('click', (e) => {
3556
+ e.stopPropagation();
3557
+ const picker = document.getElementById('rangePicker');
3558
+ if (picker?.classList.contains('open')) closeRangePopover();
3559
+ else openRangePopover();
3560
+ });
3561
+
3562
+ document.getElementById('rangePopover')?.addEventListener('click', (e) => {
3563
+ e.stopPropagation();
3564
+ });
3565
+
3566
+ document.addEventListener('click', () => {
3567
+ closeRangePopover();
3568
+ });
3569
+ document.addEventListener('keydown', (e) => {
3570
+ if (e.key === 'Escape') closeRangePopover();
3571
+ });
3572
+
3573
+ document.querySelectorAll('#periodPresets button').forEach((btn) => {
3071
3574
  btn.addEventListener('click', () => {
3072
- const nextPeriod = btn.dataset.p;
3073
- document.querySelectorAll('#periodTabs button').forEach((b) => b.classList.remove('active'));
3074
- btn.classList.add('active');
3575
+ const nextPeriod = btn.getAttribute('data-p') || 'today';
3075
3576
  period = nextPeriod;
3577
+ customFrom = '';
3578
+ customTo = '';
3076
3579
  if (!chartModeManual) {
3077
- chartMode = period === 'today' ? 'hourly' : 'daily';
3580
+ chartMode = (period === 'today' || period === 'yesterday') ? 'hourly' : 'daily';
3078
3581
  }
3079
- fetchBoard({ triggerBtn: btn });
3582
+ updateRangeTriggerLabel(null);
3583
+ closeRangePopover();
3584
+ fetchBoard({ triggerBtn: document.getElementById('rangeTrigger') });
3080
3585
  });
3081
3586
  });
3082
3587
 
3588
+ document.getElementById('calPrevBtn')?.addEventListener('click', () => {
3589
+ calMonth -= 1;
3590
+ if (calMonth < 0) { calMonth = 11; calYear -= 1; }
3591
+ renderRangeCalendar();
3592
+ });
3593
+ document.getElementById('calNextBtn')?.addEventListener('click', () => {
3594
+ calMonth += 1;
3595
+ if (calMonth > 11) { calMonth = 0; calYear += 1; }
3596
+ renderRangeCalendar();
3597
+ });
3598
+
3599
+ document.getElementById('calDays')?.addEventListener('click', (e) => {
3600
+ const btn = e.target.closest('button.cal-day');
3601
+ if (!btn || btn.disabled) return;
3602
+ const day = btn.getAttribute('data-day');
3603
+ if (!day) return;
3604
+ if (!draftFrom || (draftFrom && draftTo)) {
3605
+ draftFrom = day;
3606
+ draftTo = '';
3607
+ hoverDay = '';
3608
+ } else {
3609
+ if (day < draftFrom) {
3610
+ draftTo = draftFrom;
3611
+ draftFrom = day;
3612
+ } else {
3613
+ draftTo = day;
3614
+ }
3615
+ hoverDay = '';
3616
+ }
3617
+ renderRangeCalendar();
3618
+ });
3619
+
3620
+ document.getElementById('calDays')?.addEventListener('mouseover', (e) => {
3621
+ if (!draftFrom || draftTo) return;
3622
+ const btn = e.target.closest('button.cal-day');
3623
+ if (!btn || btn.disabled) return;
3624
+ const day = btn.getAttribute('data-day') || '';
3625
+ if (day !== hoverDay) {
3626
+ hoverDay = day;
3627
+ renderRangeCalendar();
3628
+ }
3629
+ });
3630
+
3631
+ document.getElementById('calApplyBtn')?.addEventListener('click', () => {
3632
+ if (!draftFrom) return;
3633
+ const a = draftTo && draftTo < draftFrom ? draftTo : draftFrom;
3634
+ const b = draftTo ? (draftTo < draftFrom ? draftFrom : draftTo) : draftFrom;
3635
+ period = 'custom';
3636
+ customFrom = a;
3637
+ customTo = b;
3638
+ const days = isoDateDiffDays(a, b);
3639
+ if (!chartModeManual) {
3640
+ chartMode = days === 1 ? 'hourly' : 'daily';
3641
+ }
3642
+ updateRangeTriggerLabel({ fromDate: a, toDate: b, days });
3643
+ closeRangePopover();
3644
+ fetchBoard({ triggerBtn: document.getElementById('rangeTrigger') });
3645
+ });
3646
+
3083
3647
  document.querySelectorAll('#sourceFilter button').forEach((btn) => {
3084
3648
  btn.addEventListener('click', () => {
3085
3649
  const nextSrc = btn.getAttribute('data-src') || 'all';
@@ -3119,8 +3683,7 @@ document.getElementById('memberTableHead')?.addEventListener('click', (e) => {
3119
3683
  document.getElementById('exportCsvBtn').addEventListener('click', async () => {
3120
3684
  const btn = document.getElementById('exportCsvBtn');
3121
3685
  await withBtnLoading(btn, async () => {
3122
- const qs = new URLSearchParams({ period });
3123
- if (sourceFilter !== 'all') qs.set('source', sourceFilter);
3686
+ const qs = buildBoardQueryParams(true);
3124
3687
  try {
3125
3688
  const res = await fetch('/api/board/export.csv?' + qs.toString(), { headers: viewHeaders() });
3126
3689
  if (!res.ok) return;
@@ -3128,7 +3691,8 @@ document.getElementById('exportCsvBtn').addEventListener('click', async () => {
3128
3691
  const objUrl = URL.createObjectURL(blob);
3129
3692
  const a = document.createElement('a');
3130
3693
  a.href = objUrl;
3131
- a.download = 'agy-family-' + period + (sourceFilter !== 'all' ? '-' + sourceFilter : '') + '.csv';
3694
+ const tag = period === 'custom' && customFrom ? (customFrom + '_' + (customTo || customFrom)) : period;
3695
+ a.download = 'agy-family-' + tag + (sourceFilter !== 'all' ? '-' + sourceFilter : '') + '.csv';
3132
3696
  document.body.appendChild(a);
3133
3697
  a.click();
3134
3698
  document.body.removeChild(a);