Files
gochat/internal/service/audit_service.go
T
2026-06-04 15:44:48 +08:00

63 lines
2.0 KiB
Go

package service
import (
"context"
"fmt"
"github.com/gochat/gochat/internal/model"
"github.com/gochat/gochat/internal/repository"
applogger "github.com/gochat/gochat/pkg/logger"
)
// AuditService implements business logic for AuditLog operations.
// Reference: Chatwoot enterprise audit log feature + P2B M11 spec
type AuditService struct {
repo *repository.AuditRepo
}
// NewAuditService creates a new AuditLog service.
func NewAuditService(repo *repository.AuditRepo) *AuditService {
return &AuditService{repo: repo}
}
// ListByAccount retrieves paginated audit log entries for an account with optional filters.
// page and pageSize follow the project pagination convention (page >= 1, pageSize capped at 100).
func (s *AuditService) ListByAccount(ctx context.Context, accountID uint, action string, auditableType string, page int, pageSize int) ([]model.Audit, int64, error) {
if page < 1 {
page = 1
}
if pageSize < 1 {
pageSize = 25
}
if pageSize > 100 {
pageSize = 100
}
offset := (page - 1) * pageSize
audits, total, err := s.repo.FindByAccount(ctx, accountID, action, auditableType, offset, pageSize)
if err != nil {
applogger.L().Errorf("AuditService.ListByAccount account=%d action=%s auditableType=%s: %v", accountID, action, auditableType, err)
return nil, 0, fmt.Errorf("failed to list audit logs: %w", err)
}
return audits, total, nil
}
// CreateAudit creates a new audit log entry.
func (s *AuditService) CreateAudit(ctx context.Context, audit *model.Audit) (*model.Audit, error) {
if err := s.repo.Create(ctx, audit); err != nil {
applogger.L().Errorf("AuditService.CreateAudit: %v", err)
return nil, fmt.Errorf("failed to create audit log: %w", err)
}
return audit, nil
}
// GetByID retrieves a single audit log entry by ID.
func (s *AuditService) GetByID(ctx context.Context, id uint) (*model.Audit, error) {
audit, err := s.repo.FindByID(ctx, id)
if err != nil {
applogger.L().Errorf("AuditService.GetByID id=%d: %v", id, err)
return nil, fmt.Errorf("audit log not found: %w", err)
}
return audit, nil
}