package store import ( "context" "sort" "strings" "time" ) type moduleDayKey struct{ tenant, module, day string } type moduleSeenKey struct{ tenant, module, month, subject string } func (m *Memory) PutModuleUserDay(_ context.Context, d ModuleUserDay) error { if d.Module == "" || d.Count < 0 || !validDay(d.Day) { return ErrInvalidInput } m.mu.Lock() defer m.mu.Unlock() if _, ok := m.tenants[d.TenantID]; !ok { return ErrNotFound } m.moduleDays[moduleDayKey{d.TenantID, d.Module, d.Day}] = d.Count return nil } func (m *Memory) AddModuleUsersSeen(_ context.Context, tenantID, module, month string, subjects []string) (int, error) { if module == "" || !ValidMonth(month) { return 0, ErrInvalidInput } m.mu.Lock() defer m.mu.Unlock() if _, ok := m.tenants[tenantID]; !ok { return 0, ErrNotFound } now, added := time.Now().UTC(), 0 for _, sub := range subjects { if sub == "" { continue } k := moduleSeenKey{tenantID, module, month, sub} if _, ok := m.moduleSeen[k]; !ok { m.moduleSeen[k] = now added++ } } return added, nil } func (m *Memory) ModuleUserCounts(_ context.Context, tenantID, month string) ([]ModuleUserCount, error) { if !ValidMonth(month) { return nil, ErrInvalidInput } m.mu.RLock() defer m.mu.RUnlock() byModule := map[string]*ModuleUserCount{} for k, n := range m.moduleDays { if k.tenant != tenantID || !strings.HasPrefix(k.day, month+"-") { continue } c, ok := byModule[k.module] // The peak; on a tie the earliest day (as the Postgres query). if !ok || n > c.Count || (n == c.Count && k.day < c.PeakDay) { byModule[k.module] = &ModuleUserCount{Module: k.module, Count: n, PeakDay: k.day} } } seen := map[string]int{} for k := range m.moduleSeen { if k.tenant == tenantID && k.month == month { seen[k.module]++ } } for mod, n := range seen { if _, ok := byModule[mod]; !ok { // a module is counted one way only byModule[mod] = &ModuleUserCount{Module: mod, Count: n} } } out := make([]ModuleUserCount, 0, len(byModule)) for _, c := range byModule { out = append(out, *c) } sort.Slice(out, func(i, j int) bool { return out[i].Module < out[j].Module }) return out, nil } // deleteModuleUsers drops a purged tenant's counts (ON DELETE CASCADE in // Postgres). Caller holds the lock. func (m *Memory) deleteModuleUsers(tenantID string) { for k := range m.moduleDays { if k.tenant == tenantID { delete(m.moduleDays, k) } } for k := range m.moduleSeen { if k.tenant == tenantID { delete(m.moduleSeen, k) } } } // ValidMonth reports whether s is a calendar month "YYYY-MM". func ValidMonth(s string) bool { _, err := time.Parse("2006-01", s) return err == nil && len(s) == 7 } func validDay(s string) bool { _, err := time.Parse("2006-01-02", s) return err == nil && len(s) == 10 }