Skip to content
Snippets Groups Projects
Select Git revision
  • d62b8803834959f8a15c28d0b829e237277536bc
  • main default protected
  • v1.298.0
  • v1.297.0
  • v1.296.0
  • v1.295.0
  • v1.294.0
  • v1.293.0
  • v1.292.0
  • v1.291.0
  • v1.290.0
  • v1.289.0
  • v1.288.0
  • v1.287.0
  • v1.286.0
  • v1.285.0
  • v1.284.0
  • v1.283.0
  • v1.282.0
  • v1.281.0
  • v1.280.0
  • v1.279.0
22 results

audit.go

Blame
  • audit.go 17.48 KiB
    package audit
    
    import (
    	"encoding/json"
    	"fmt"
    	"github.com/r3labs/diff/v2"
    	"github.com/samber/lo"
    	"gitlab.bob.co.za/bob-public-utils/bobgroup-go-utils/errors"
    	"gitlab.bob.co.za/bob-public-utils/bobgroup-go-utils/logs"
    	"gitlab.bob.co.za/bob-public-utils/bobgroup-go-utils/number_utils"
    	"gitlab.bob.co.za/bob-public-utils/bobgroup-go-utils/reflection"
    	"gitlab.bob.co.za/bob-public-utils/bobgroup-go-utils/string_utils"
    	"reflect"
    	"regexp"
    	"strconv"
    	"strings"
    )
    
    type FieldChange struct {
    	From any `json:"change_from"`
    	To   any `json:"change_to"`
    }
    
    type IAuditFormatter interface {
    	FormatForAuditEvent() string
    }
    
    func VerifyAuditEvents(original any, new any) error {
    	if original != nil {
    		structValue := reflect.ValueOf(original)
    		if structValue.Kind() != reflect.Struct {
    			return errors.Error("original object is not of type struct")
    		}
    	}
    
    	if new != nil {
    		structValue := reflect.ValueOf(new)
    		if structValue.Kind() != reflect.Struct {
    			return errors.Error("new object is not of type struct")
    		}
    	}
    
    	return nil
    }
    
    func GetChanges(original any, new any) (map[string]any, error) {
    	// Clean audit events
    	original = cleanStruct(original)
    	new = cleanStruct(new)
    
    	changes := map[string]any{}
    	changelog, err := diff.Diff(original, new)
    	if err != nil {
    		return changes, err
    	}
    
    	for _, change := range changelog {
    
    		if len(change.Path) == 1 {
    			// Root object change
    			field := ToSnakeCase(change.Path[0])
    			changes[field] = FieldChange{
    				From: change.From,
    				To:   change.To,
    			}
    		} else if len(change.Path) == 2 {
    			// Child object changed
    			// ["Account", "ID"]
    			// 0 = Object
    			// 1 = field