package insight import ( "context" "crypto/rand" "crypto/sha256" "encoding/hex" "fmt" "time" ) type Service struct { repository repositoryStore builder Builder now func() time.Time } type repositoryStore interface { DatasetMetadata(context.Context) (string, time.Time, error) ActiveCatalogVersion(context.Context) (string, error) MerchantScopes(context.Context) ([]MerchantScope, error) Create(context.Context, CreateRequest) (Job, bool, error) Latest(context.Context, int64, string, Module) (Snapshot, error) GetJob(context.Context, int64, string) (Job, error) EventsAfter(context.Context, int64, string, int64) ([]Event, error) Claim(context.Context) (claimedJob, error) Complete(context.Context, claimedJob, Analysis, string, string) error } func NewService(repository repositoryStore, builder Builder) *Service { return &Service{repository: repository, builder: builder, now: time.Now} } func (s *Service) Latest(ctx context.Context, merchantID int64, terminalID string, module Module) (Snapshot, error) { if terminalID != "" { // Validation is deliberately tenant-scoped and returns the same public result as a missing terminal. if _, err := s.builder.Build(ctx, merchantID, terminalID, module); err != nil { return Snapshot{}, err } } return s.repository.Latest(ctx, merchantID, terminalID, module) } func (s *Service) Refresh(ctx context.Context, merchantID int64, terminalID string, module Module, idempotencyKey string) (Job, bool, error) { return s.enqueue(ctx, merchantID, terminalID, module, "MANUAL", true, idempotencyKey) } func (s *Service) Enqueue(ctx context.Context, merchantID int64, terminalID string, module Module, reason string) (Job, bool, error) { return s.enqueue(ctx, merchantID, terminalID, module, reason, false, "") } func (s *Service) EnqueueAll(ctx context.Context, reason string) (int, error) { scopes, err := s.repository.MerchantScopes(ctx) if err != nil { return 0, err } watermark, dataThrough, err := s.repository.DatasetMetadata(ctx) if err != nil { return 0, err } catalog, err := s.repository.ActiveCatalogVersion(ctx) if err != nil { return 0, err } timeContext := BuildTimeContext(s.now(), dataThrough) modules := []Module{ModuleOverview, ModulePayments, ModuleFees, ModulePeers, ModuleTransactions, ModuleGrowth} created := 0 for _, scope := range scopes { for _, module := range modules { if err := ctx.Err(); err != nil { return created, err } if _, cached, err := s.enqueuePrepared(ctx, scope.MerchantID, scope.TerminalID, module, reason, false, "", watermark, catalog, timeContext); err != nil { return created, err } else if !cached { created++ } } } return created, nil } func (s *Service) enqueue(ctx context.Context, merchantID int64, terminalID string, module Module, reason string, manual bool, key string) (Job, bool, error) { watermark, dataThrough, err := s.repository.DatasetMetadata(ctx) if err != nil { return Job{}, false, err } catalog, err := s.repository.ActiveCatalogVersion(ctx) if err != nil { return Job{}, false, err } tc := BuildTimeContext(s.now(), dataThrough) return s.enqueuePrepared(ctx, merchantID, terminalID, module, reason, manual, key, watermark, catalog, tc) } func (s *Service) enqueuePrepared(ctx context.Context, merchantID int64, terminalID string, module Module, reason string, manual bool, key, watermark, catalog string, tc TimeContext) (Job, bool, error) { fingerprint := hash(fmt.Sprintf("%d|%s|%s|%s|%s|%s|%s|%s", merchantID, terminalID, module, tc.AsOfDate, watermark, catalog, AnalyticsVersion, "1.0.0")) requestHash := hash(fmt.Sprintf("%d|%s|%s|%t", merchantID, terminalID, module, manual)) return s.repository.Create(ctx, CreateRequest{MerchantID: merchantID, TerminalID: terminalID, Module: module, TriggerReason: reason, ManualRefresh: manual, IdempotencyKey: key, RequestHash: requestHash, Fingerprint: fingerprint, Time: tc, Confidence: confidenceFor(tc.Freshness), CatalogVersion: catalog, Evidence: []byte(`{}`)}) } func (s *Service) GetJob(ctx context.Context, merchantID int64, jobID string) (Job, error) { return s.repository.GetJob(ctx, merchantID, jobID) } func (s *Service) EventsAfter(ctx context.Context, merchantID int64, jobID string, after int64) ([]Event, error) { return s.repository.EventsAfter(ctx, merchantID, jobID, after) } func (s *Service) ProcessNext(ctx context.Context) error { job, err := s.repository.Claim(ctx) if err != nil { return err } analysis, err := s.builder.Build(ctx, job.MerchantID, job.TerminalID, job.Module) if err != nil { return fmt.Errorf("building %s insight: %w", job.Module, err) } // The deterministic copy is always publishable. A provider can replace it only after // evidence-reference validation; until then PARTIAL is explicit and last-good remains visible. return s.repository.Complete(ctx, job, analysis, "PARTIAL", "DETERMINISTIC_FALLBACK") } func confidenceFor(f Freshness) Confidence { if f == FreshnessStale { return ConfidenceLow } return ConfidenceMedium } func hash(value string) string { sum := sha256.Sum256([]byte(value)) return hex.EncodeToString(sum[:]) } func newID(prefix string) string { value := make([]byte, 12) if _, err := rand.Read(value); err != nil { panic("crypto/rand unavailable") } return prefix + hex.EncodeToString(value) }