64 lines
1.8 KiB
Go
64 lines
1.8 KiB
Go
package repository
|
|
|
|
import (
|
|
"context"
|
|
|
|
"gorm.io/gorm"
|
|
|
|
"github.com/gochat/gochat/internal/model"
|
|
)
|
|
|
|
// AuditRepo implements GORM repository for Audit (audit log entries).
|
|
// Reference: Chatwoot enterprise Audit model + P2B M11 spec
|
|
type AuditRepo struct {
|
|
db *gorm.DB
|
|
}
|
|
|
|
// NewAuditRepo creates a new Audit repository.
|
|
func NewAuditRepo(db *gorm.DB) *AuditRepo {
|
|
return &AuditRepo{db: db}
|
|
}
|
|
|
|
// FindByID retrieves an audit log entry by primary key.
|
|
func (r *AuditRepo) FindByID(ctx context.Context, id uint) (*model.Audit, error) {
|
|
var audit model.Audit
|
|
if err := r.db.WithContext(ctx).First(&audit, id).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
return &audit, nil
|
|
}
|
|
|
|
// FindByAccount retrieves audit log entries for an account with optional filters.
|
|
// Returns the filtered list and total count for pagination.
|
|
func (r *AuditRepo) FindByAccount(ctx context.Context, accountID uint, actionFilter string, auditableTypeFilter string, offset int, limit int) ([]model.Audit, int64, error) {
|
|
query := r.db.WithContext(ctx).Where("account_id = ?", accountID)
|
|
|
|
if actionFilter != "" {
|
|
query = query.Where("action = ?", actionFilter)
|
|
}
|
|
if auditableTypeFilter != "" {
|
|
query = query.Where("auditable_type = ?", auditableTypeFilter)
|
|
}
|
|
|
|
var total int64
|
|
if err := query.Model(&model.Audit{}).Count(&total).Error; err != nil {
|
|
return nil, 0, err
|
|
}
|
|
|
|
var audits []model.Audit
|
|
if err := query.Order("created_at DESC").Offset(offset).Limit(limit).Find(&audits).Error; err != nil {
|
|
return nil, 0, err
|
|
}
|
|
|
|
return audits, total, nil
|
|
}
|
|
|
|
// Create creates a new audit log entry.
|
|
func (r *AuditRepo) Create(ctx context.Context, audit *model.Audit) error {
|
|
return r.db.WithContext(ctx).Create(audit).Error
|
|
}
|
|
|
|
// Delete deletes an audit log entry by primary key.
|
|
func (r *AuditRepo) Delete(ctx context.Context, id uint) error {
|
|
return r.db.WithContext(ctx).Delete(&model.Audit{}, id).Error
|
|
} |