فهرست منبع

fix(devices): emit the new-device flags the clients page already asks for

buildOverview hardcoded NewToday to 0 and IsNew was only set by the demo dataset, so the new-device pill and both counters on /devices stayed empty in live. Derive IsNew (server local day) and NewThisWeek (rolling seven days) from device_seen.first_seen, and make the 7-day tile count NewThisWeek instead of IsNew.

Co-authored-by: Bann-DEV <hef.fangyuan@gmail.com>
Bann-DEV 1 ماه پیش
والد
کامیت
7dbddb7150

+ 3 - 0
app/src/data/types.ts

@@ -251,7 +251,10 @@ export interface Device {
   /** Tráfico actual Mbps */
   trafficMbps: number
   online: boolean
+  /** Primera vez que el server lo vio es HOY (pill "Nuevo", "+N hoy"). */
   isNew?: boolean
+  /** ... y esa primera vez cae dentro de los últimos 7 días (tile "New (7 days)"). */
+  newThisWeek?: boolean
   sparkline: number[]
   /** Puerto físico del router/switch donde se aprende la MAC (cableados; FDB). */
   port?: string | null

+ 1 - 1
app/src/pages/Devices.tsx

@@ -400,7 +400,7 @@ function StatsStrip({
   const { refreshKey } = useDashboard()
   const { deviceTotals, adguard } = useNetPulse()
   const reduce = useReducedMotion()
-  const newThisWeekDevices = allDevices.filter((d) => d.isNew)
+  const newThisWeekDevices = allDevices.filter((d) => d.newThisWeek)
   // #1003: el umbral de señal débil es el ajuste global (/api/settings/thresholds),
   // no un -70 hardcodeado; mismo criterio que la matriz de roaming (#906).
   const weakDbm = useWeakSignalDbm()

+ 3 - 6
app/src/pages/devices-data.ts

@@ -33,8 +33,6 @@ export interface ClientDevice extends Device {
   adguard: boolean
   /** Grupo del filtro "Tipo" (devices.md §③) */
   group: FilterGroup
-  /** Visto por primera vez en los últimos 7 días (stat "Nuevos (7 días)") */
-  newThisWeek?: boolean
 }
 
 // 'infra' primero (D6): hipervisores, CTs y switches gestionados de un vistazo.
@@ -87,7 +85,7 @@ const CANON_DETAILS: Record<string, Omit<ClientDevice, keyof Device>> = {
   },
   'galaxy-tab-s9': {
     hostname: 'galaxy-tab-s9', dhcpLease: 'renews in 11h 5min',
-    traffic24hRx: '640 MB', traffic24hTx: '48 MB', adguard: true, group: 'moviles', newThisWeek: true,
+    traffic24hRx: '640 MB', traffic24hTx: '48 MB', adguard: true, group: 'moviles',
   },
   // D1: el GS308E vuelve a ser Device (además del distnode managed del canon).
   // Su grupo visible es 'infra' (lo reasigna Devices.tsx con device.infra/lldp).
@@ -178,7 +176,8 @@ function isMACName(name: string): boolean {
 }
 
 /** Metadatos de cliente que pueden venir inline (canon JSON / API demo).
- *  firstSeen/lastSeen NO van aquí: viajan en Device como epochs (#954). */
+ *  firstSeen/lastSeen NO van aquí: viajan en Device como epochs (#954), y
+ *  newThisWeek tampoco: es alta de device_seen, no detalle del demo. */
 interface InlineDetails {
   hostname?: string
   dhcpLease?: string
@@ -186,7 +185,6 @@ interface InlineDetails {
   traffic24hTx?: string
   adguard?: boolean
   group?: FilterGroup
-  newThisWeek?: boolean
 }
 
 /** Extrae los metadatos inline del canon; null si el Device no los trae. */
@@ -200,7 +198,6 @@ function inlineDetails(d: Device): Omit<ClientDevice, keyof Device> | null {
     traffic24hTx: raw.traffic24hTx ?? '—',
     adguard: raw.adguard ?? true,
     group: raw.group ?? TYPE_TO_GROUP[d.type],
-    newThisWeek: raw.newThisWeek,
   }
 }
 

+ 53 - 1
server-go/internal/adapters/device_seen.go

@@ -4,6 +4,7 @@ import (
 	"fmt"
 	"net"
 	"strings"
+	"time"
 
 	"github.com/gnacho/netpulse/server-go/internal/alerts"
 )
@@ -303,7 +304,10 @@ func (l *Live) trackNewClients(firstTimers []Device, devices []Device, dists []D
 
 // applyDeviceSeen rellena FirstSeenMs/LastSeenMs de cada dispositivo desde
 // device_seen (#954). Los sin fila (nunca vistos online por ESTE server, o
-// demo sin BD) quedan a 0 y la app muestra "—".
+// demo sin BD) quedan a 0 y la app muestra "—". Además fija IsNew e
+// IsNewThisWeek leyendo el alta del registro: era la única evidencia de
+// "nuevo" que tenía el live y nunca se usó, así que el pill, la lista de la
+// semana y deviceTotals.newToday salían siempre vacíos.
 func (l *Live) applyDeviceSeen(devices []Device) {
 	if l.db == nil || len(devices) == 0 {
 		return
@@ -312,10 +316,13 @@ func (l *Live) applyDeviceSeen(devices []Device) {
 	if err != nil {
 		return
 	}
+	now := l.seenNow()
 	for i := range devices {
 		if s, ok := byMac[normSeenMAC(devices[i].MAC)]; ok {
 			devices[i].FirstSeenMs = s.first
 			devices[i].LastSeenMs = s.last
+			devices[i].IsNew = s.isNewToday(now)
+			devices[i].NewThisWeek = s.isNewThisWeek(now)
 			// #1315: la fuente viva pierde nombre e IP cuando el lease DHCP
 			// expira (el cliente sigue listado vía estación/ARP/FDB): Name
 			// vuelve a ser la MAC y la IP queda vacía. El registro (#1145)
@@ -352,6 +359,48 @@ type seenRow struct {
 	deviceType  string
 }
 
+// isNewToday: el registro (#954) se abrió en el día local del server. Mismo
+// criterio de "hoy" que el pico de tráfico diario (live.go): arranque del
+// día en la zona del server, no ventana móvil de 24 h. first_seen=0 —sin
+// fila— nunca es nuevo: la app lo muestra como "—".
+func (s seenRow) isNewToday(now time.Time) bool {
+	if s.first <= 0 {
+		return false
+	}
+	startOfDay := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location()).UnixMilli()
+	return s.first >= startOfDay
+}
+
+// isNewThisWeek: el alta cayó en los últimos 7 días (ventana móvil). Es el
+// tile "New (7 days)" de la app, que hasta ahora leía isNew —un flag que en
+// el canon demo es "hoy", no "7 días"—, así que ambos flags conviven: isNew
+// para el pill y el contador de hoy, isNewThisWeek para la semana.
+func (s seenRow) isNewThisWeek(now time.Time) bool {
+	return s.first > 0 && s.first >= now.Add(-7*24*time.Hour).UnixMilli()
+}
+
+// seenNow: reloj del Live con su inyectable (l.now) y fallback al real, para
+// que los tests de "hoy" no dependan del calendario.
+func (l *Live) seenNow() time.Time {
+	if l.now != nil {
+		return l.now()
+	}
+	return time.Now()
+}
+
+// countNewToday: clientes cuyo registro se abrió hoy. IsNew lo pone
+// applyDeviceSeen (y ghostDevices); en el demo lo suma deviceTotalsOf sobre
+// el mismo flag, así que live y demo cuentan lo mismo.
+func countNewToday(devices []Device) int {
+	n := 0
+	for _, d := range devices {
+		if d.IsNew {
+			n++
+		}
+	}
+	return n
+}
+
 // seenByMac carga la tabla device_seen completa (una query, sin N+1).
 // #1315: un nombre con forma de MAC (BDs contaminadas por ciclos previos)
 // se devuelve vacío: nunca se restaura ni emite una MAC como nombre.
@@ -409,6 +458,7 @@ func (l *Live) ghostDevices(devices []Device) []Device {
 	if err != nil {
 		tomb = map[string]bool{}
 	}
+	now := l.seenNow()
 	var out []Device
 	for rawMac, s := range byMac {
 		mac := normSeenMAC(rawMac)
@@ -432,6 +482,8 @@ func (l *Live) ghostDevices(devices []Device) []Device {
 			Band:        "—",
 			FirstSeenMs: s.first,
 			LastSeenMs:  s.last,
+			IsNew:       s.isNewToday(now),
+			NewThisWeek: s.isNewThisWeek(now),
 		}
 		// #1315: el fantasma conserva el último tipo inferido (misma
 		// stickiness que applyDeviceSeen: al expirar el lease la

+ 95 - 1
server-go/internal/adapters/device_seen_test.go

@@ -1,6 +1,9 @@
 package adapters
 
-import "testing"
+import (
+	"testing"
+	"time"
+)
 
 // #954: first_seen se fija en el alta y no se toca después; last_seen
 // avanza en cada ciclo online. Los clientes offline no entran en la tabla.
@@ -409,3 +412,94 @@ func TestGhostDevicesStickyType(t *testing.T) {
 		t.Errorf("ghost Type = %q, want desconocido (nunca hubo inferencia)", g.Type)
 	}
 }
+
+// "Nuevo" = alta del registro HOY y "esta semana" = alta en los últimos 7
+// días. Sin esto el live no marcaba NUNCA ninguno de los dos y el tile
+// "New (7 days)" se quedaba en 0 aunque la tabla de clientes de abajo listara
+// los descubiertos esa misma semana.
+func TestDeviceSeenNewFlagsFromSeenDay(t *testing.T) {
+	d := openLiveTestDB(t)
+	now := time.Date(2026, 3, 14, 12, 0, 0, 0, time.UTC)
+	l := &Live{db: d, now: func() time.Time { return now }}
+	hoy := now.Add(-6 * time.Hour).UnixMilli()   // mismo día, antes del mediodía
+	ayer := now.Add(-20 * time.Hour).UnixMilli() // ayer
+	cuatro := now.Add(-4 * 24 * time.Hour).UnixMilli()
+	ocho := now.Add(-8 * 24 * time.Hour).UnixMilli()
+	l.noteDevicesSeen([]Device{
+		{MAC: "aa:bb:cc:dd:ee:ff", Online: true},
+		{MAC: "11:22:33:44:55:66", Online: true},
+	}, hoy)
+	l.noteDevicesSeen([]Device{{MAC: "22:33:44:55:66:77", Online: true}}, ayer)
+	l.noteDevicesSeen([]Device{{MAC: "33:44:55:66:77:88", Online: true}}, cuatro)
+	l.noteDevicesSeen([]Device{{MAC: "44:55:66:77:88:99", Online: true}}, ocho)
+
+	out := []Device{
+		{MAC: "AA:BB:CC:DD:EE:FF", Online: true},
+		{MAC: "11:22:33:44:55:66", Online: true},
+		{MAC: "22:33:44:55:66:77", Online: true},
+		{MAC: "33:44:55:66:77:88", Online: true},
+		{MAC: "44:55:66:77:88:99", Online: true},
+		{MAC: "55:66:77:88:99:AA", Online: true}, // sin fila: nunca visto por este server
+	}
+	l.applyDeviceSeen(out)
+	want := []struct{ isNew, isWeek bool }{
+		{true, true},  // hoy
+		{true, true},  // hoy
+		{false, true}, // ayer
+		{false, true}, // hace 4 días
+		{false, false},
+		{false, false}, // sin registro → la app pinta "—"
+	}
+	for i, w := range want {
+		if out[i].IsNew != w.isNew || out[i].NewThisWeek != w.isWeek {
+			t.Errorf("[%d] %s: isNew=%v newThisWeek=%v, want %v/%v",
+				i, out[i].MAC, out[i].IsNew, out[i].NewThisWeek, w.isNew, w.isWeek)
+		}
+	}
+	if got := countNewToday(out); got != 2 {
+		t.Errorf("countNewToday = %d, want 2", got)
+	}
+	if out[5].FirstSeenMs != 0 {
+		t.Errorf("sin fila no debe inventar first_seen: %d", out[5].FirstSeenMs)
+	}
+
+	// Los fantasmas (ya fuera de toda fuente viva) leen el mismo first_seen:
+	// un alta de hoy que se fue sigue siendo un alta de hoy.
+	ghosts := l.ghostDevices(nil)
+	if len(ghosts) != 5 {
+		t.Fatalf("ghosts = %d, want 5 (ninguno está en la lista que se pasa)", len(ghosts))
+	}
+	for _, g := range ghosts {
+		isWeek := g.MAC != "44:55:66:77:88:99"
+		isNew := g.MAC == "AA:BB:CC:DD:EE:FF" || g.MAC == "11:22:33:44:55:66"
+		if g.IsNew != isNew || g.NewThisWeek != isWeek {
+			t.Errorf("ghost %s: isNew=%v newThisWeek=%v, want %v/%v",
+				g.MAC, g.IsNew, g.NewThisWeek, isNew, isWeek)
+		}
+	}
+}
+
+// Los dos cortes: "hoy" es el día local del server (como el pico de tráfico
+// diario), la semana es una ventana móvil de 7 × 24 h.
+func TestNewFlagsCutAtDayAndWeek(t *testing.T) {
+	now := time.Date(2026, 3, 14, 0, 0, 0, 1, time.UTC)
+	startOfDay := time.Date(2026, 3, 14, 0, 0, 0, 0, time.UTC).UnixMilli()
+	if !(seenRow{first: startOfDay}).isNewToday(now) {
+		t.Error("el primer ms del día es nuevo")
+	}
+	if (seenRow{first: startOfDay - 1}).isNewToday(now) {
+		t.Error("último ms de ayer no es nuevo, por 1 ms que sea")
+	}
+	week := now.Add(-7 * 24 * time.Hour).UnixMilli()
+	if !(seenRow{first: week}).isNewThisWeek(now) {
+		t.Error("justo hace 7 días sigue siendo esta semana")
+	}
+	if (seenRow{first: week - 1}).isNewThisWeek(now) {
+		t.Error("1 ms fuera de la ventana de 7 días no es de esta semana")
+	}
+	for name, s := range map[string]seenRow{"hoy": {first: startOfDay}, "sin fila": {first: 0}, "negativo": {first: -1}} {
+		if s.isNewToday(now) != (s.first > 0) || s.isNewThisWeek(now) != (s.first > 0) {
+			t.Errorf("%s: los dos flags deben negar un alta ausente", name)
+		}
+	}
+}

+ 2 - 1
server-go/internal/adapters/live.go

@@ -3997,7 +3997,8 @@ func (l *Live) buildOverview(ctx context.Context) (*Overview, error) {
 		Traffic: TrafficByRange{H1: trafficOf("1h"), H24: trafficOf("24h"), D7: trafficOf("7d"), D30: trafficOf("30d")},
 		Adguard: ag, Wireguard: wgStats, Routers: routerList,
 		DeviceTotals: DeviceTotals{
-			Total: len(devices), Online: online, KnownOffline: len(devices) - online, NewToday: 0,
+			Total: len(devices), Online: online, KnownOffline: len(devices) - online,
+			NewToday: countNewToday(devices),
 		},
 		TopDevices: top, Alerts: alertsCopy, UnreadAlerts: unread,
 		DistributionNodes: distNodes,

+ 11 - 3
server-go/internal/adapters/types.go

@@ -249,7 +249,9 @@ type Router struct {
 	LldpHint string `json:"lldpHint,omitempty"`
 }
 
-// DeviceTotals del overview (quirk: NewToday=0 en live).
+// DeviceTotals del overview. NewToday: clientes cuyo alta en device_seen
+// (#954) es de hoy; en el demo lo suma deviceTotalsOf sobre IsNew, mismo
+// criterio y mismo número.
 type DeviceTotals struct {
 	Total        int `json:"total"`
 	Online       int `json:"online"`
@@ -337,8 +339,14 @@ type Device struct {
 	Traffic24hTx string   `json:"traffic24hTx,omitempty"`
 	Adguard      *bool    `json:"adguard,omitempty"` // puntero: demo emite true/false explícito; live lo omite (paridad Node)
 	Group        string   `json:"group,omitempty"`
-	IsNew        bool     `json:"isNew,omitempty"`
-	NewThisWeek  bool     `json:"newThisWeek,omitempty"`
+	// IsNew: el alta del registro device_seen (#954) es de hoy. Lo fijan
+	// applyDeviceSeen y ghostDevices leyendo first_seen; la app lo usa para el
+	// pill "Nuevo" y para el "+N hoy" de deviceTotals.newToday.
+	IsNew bool `json:"isNew,omitempty"`
+	// NewThisWeek: el alta cayó en los últimos 7 días (ventana móvil). Es el
+	// tile "New (7 days)"; en el canon demo viene a mano junto a los tres
+	// IsNew (que también son de esta semana).
+	NewThisWeek bool `json:"newThisWeek,omitempty"`
 }
 
 // LldpInfo identifica un vecino que se anuncia por LLDP (switch gestionado,