90 lines
1.9 KiB
Go
90 lines
1.9 KiB
Go
package utils
|
|
|
|
import (
|
|
"context"
|
|
"reflect"
|
|
"strings"
|
|
|
|
"github.com/Caknoooo/go-gin-clean-starter/database/entities"
|
|
"github.com/Caknoooo/go-gin-clean-starter/pkg/constants"
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
func GetInitials(name string) string {
|
|
name = strings.TrimSpace(name)
|
|
words := strings.Fields(name)
|
|
if len(words) == 0 {
|
|
return ""
|
|
}
|
|
if len(words) == 1 {
|
|
// Jika hanya satu kata, ambil 3 huruf awal (atau kurang jika <3)
|
|
initial := words[0]
|
|
if len(initial) > 3 {
|
|
initial = initial[:3]
|
|
}
|
|
return strings.ToUpper(initial)
|
|
}
|
|
// Jika lebih dari satu kata, ambil huruf pertama tiap kata
|
|
var initials string
|
|
for _, w := range words {
|
|
if len(w) > 0 {
|
|
initials += string(w[0])
|
|
}
|
|
}
|
|
return strings.ToUpper(initials)
|
|
}
|
|
|
|
func GetUserID(ctx context.Context) string {
|
|
val := ctx.Value(constants.USERID)
|
|
if id, ok := val.(string); ok {
|
|
return id
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func GetWarehouseID(ctx context.Context) string {
|
|
val := ctx.Value(constants.WAREHOUSEID)
|
|
if id, ok := val.(string); ok {
|
|
return id
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func FillAuditTrail(ctx context.Context, action string) entities.FullAuditTrail {
|
|
userID := GetUserID(ctx)
|
|
uid, _ := uuid.Parse(userID)
|
|
audit := entities.Audit{}
|
|
switch action {
|
|
case "create":
|
|
audit.CreatedBy = uid
|
|
case "update":
|
|
audit.UpdatedBy = uid
|
|
case "delete":
|
|
audit.DeletedBy = uid
|
|
}
|
|
return entities.FullAuditTrail{Audit: audit}
|
|
}
|
|
|
|
func GetChangedFields(before, after interface{}) map[string]map[string]interface{} {
|
|
changes := make(map[string]map[string]interface{})
|
|
vBefore := reflect.ValueOf(before)
|
|
vAfter := reflect.ValueOf(after)
|
|
t := vBefore.Type()
|
|
|
|
for i := 0; i < vBefore.NumField(); i++ {
|
|
field := t.Field(i).Name
|
|
if field == "FullAuditTrail" {
|
|
continue
|
|
}
|
|
valBefore := vBefore.Field(i).Interface()
|
|
valAfter := vAfter.Field(i).Interface()
|
|
if !reflect.DeepEqual(valBefore, valAfter) {
|
|
changes[field] = map[string]interface{}{
|
|
"old": valBefore,
|
|
"new": valAfter,
|
|
}
|
|
}
|
|
}
|
|
return changes
|
|
}
|