File size: 7,305 Bytes
7beb700
 
 
1cea019
 
 
6de5368
7beb700
 
1cea019
7beb700
 
 
 
 
1cea019
7beb700
 
1cea019
 
 
7beb700
 
 
1cea019
7beb700
 
1cea019
 
 
 
 
 
 
7beb700
 
1cea019
 
 
 
 
7beb700
1cea019
 
 
 
7beb700
 
1cea019
 
 
7beb700
1cea019
 
7beb700
1cea019
 
 
7beb700
 
1cea019
 
 
 
 
 
 
 
 
 
 
7beb700
 
1cea019
 
 
7beb700
 
1cea019
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7beb700
1cea019
 
 
 
 
 
7beb700
1cea019
 
 
 
 
7beb700
 
 
1cea019
 
 
 
 
 
 
 
 
 
7beb700
 
1cea019
 
 
 
 
 
 
 
 
7beb700
 
 
 
 
1cea019
7beb700
 
 
 
 
 
 
 
1cea019
7beb700
 
 
1cea019
 
7beb700
 
1cea019
 
 
 
 
 
7beb700
 
1cea019
 
 
 
 
 
 
 
 
 
7beb700
1cea019
 
 
 
 
 
7beb700
1cea019
 
 
7beb700
 
1cea019
 
7beb700
1cea019
 
 
 
7beb700
1cea019
 
 
 
7beb700
1cea019
7beb700
 
1cea019
 
 
7beb700
 
1cea019
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6de5368
 
1cea019
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7beb700
 
1cea019
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7beb700
 
 
 
 
 
6de5368
1cea019
 
6de5368
 
 
1cea019
6de5368
 
 
1cea019
 
 
 
 
 
 
 
 
6de5368
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
package validation

import (
	"context"
	"fmt"
	"reflect"
	"regexp"
	"strings"
	"sync"
	"time"

	v10 "github.com/go-playground/validator/v10"
	"gorm.io/gorm"
)

type ValidatorOptionSource interface {
	GetValidOptions(key string) ([]string, error)
	GetValidKeys() []string
	Refresh() error
	StartAutoRefresh(ctx context.Context, interval time.Duration)
	HasKey(key string) bool
}

// --------------------
// DBOptionSource with Safe Handling
// --------------------

type DBOptionSource struct {
	db         *gorm.DB
	options    map[string][]string
	mu         sync.RWMutex
	lastUpdate time.Time
	expiry     time.Duration
	stopChan   chan struct{}
}

func NewDBOptionSource(db *gorm.DB, expiry time.Duration) (*DBOptionSource, error) {
	source := &DBOptionSource{
		db:       db,
		expiry:   expiry,
		stopChan: make(chan struct{}),
	}
	if err := source.Refresh(); err != nil {
		return nil, fmt.Errorf("failed to initialize DB option source: %w", err)
	}
	return source, nil
}

func (s *DBOptionSource) Refresh() error {
	s.mu.Lock()
	defer s.mu.Unlock()

	// Buat session baru tanpa transaction
	tx := s.db.Session(&gorm.Session{SkipDefaultTransaction: true})

	var results []struct {
		Slug  string `gorm:"column:slug"`
		Value string `gorm:"column:value"`
	}

	err := tx.Raw(`
        SELECT
            c.option_slug AS slug,
            v.option_value AS value
        FROM option_categories c
        JOIN option_values v ON c.id = v.option_category_id
        ORDER BY c.id, v.id
    `).Scan(&results).Error

	if err != nil {
		return fmt.Errorf("failed to refresh options: %w", err)
	}

	newOptions := make(map[string][]string)
	for _, r := range results {
		newOptions[r.Slug] = append(newOptions[r.Slug], r.Value)
	}

	s.options = newOptions
	s.lastUpdate = time.Now()

	fmt.Println("options refreshed")

	return nil
}

func (s *DBOptionSource) StartAutoRefresh(ctx context.Context, interval time.Duration) {
	ticker := time.NewTicker(interval)
	go func() {
		for {
			select {
			case <-ticker.C:
				s.mu.Lock()
				needsRefresh := time.Since(s.lastUpdate) > s.expiry
				s.mu.Unlock()

				if needsRefresh {
					if err := s.Refresh(); err != nil {
						fmt.Printf("failed to auto-refresh options: %v\n", err)
					}
				}
			case <-ctx.Done():
				ticker.Stop()
				return
			case <-s.stopChan:
				ticker.Stop()
				return
			}
		}
	}()
}

func (s *DBOptionSource) StopAutoRefresh() {
	close(s.stopChan)
}

func (s *DBOptionSource) HasKey(key string) bool {
	s.mu.RLock()
	defer s.mu.RUnlock()
	_, exists := s.options[key]
	return exists
}

func (s *DBOptionSource) GetValidOptions(key string) ([]string, error) {
	s.mu.RLock()
	needsRefresh := time.Since(s.lastUpdate) > s.expiry
	s.mu.RUnlock()

	if needsRefresh {
		if err := s.Refresh(); err != nil {
			return nil, fmt.Errorf("failed to refresh options: %w", err)
		}
	}

	s.mu.RLock()
	defer s.mu.RUnlock()

	options, exists := s.options[key]
	if !exists {
		return nil, nil // Return nil instead of error for missing keys
	}

	copied := make([]string, len(options))
	copy(copied, options)
	return copied, nil
}

func (s *DBOptionSource) GetValidKeys() []string {
	s.mu.RLock()
	defer s.mu.RUnlock()

	keys := make([]string, 0, len(s.options))
	for k := range s.options {
		keys = append(keys, k)
	}
	return keys
}

// --------------------
// Validator with Safe Rule Handling
// --------------------

type Validator struct {
	source   ValidatorOptionSource
	validate *v10.Validate
}

func NewValidator(source ValidatorOptionSource) *Validator {
	validate := v10.New()
	return &Validator{
		source:   source,
		validate: validate,
	}
}

func (v *Validator) RegisterAllCustomRules() error {
	// First register static validation rules
	staticRules := map[string]func(v10.FieldLevel) bool{
		"password":     v.validatePassword,
		"phone-number": v.validatePhoneNumber,
	}

	for name, fn := range staticRules {
		if err := v.validate.RegisterValidation(name, fn); err != nil {
			return fmt.Errorf("failed to register %s validation: %w", name, err)
		}
	}

	// Then register dynamic option rules
	for _, key := range v.source.GetValidKeys() {
		if !v.source.HasKey(key) {
			continue // Skip if key doesn't exist
		}

		if err := v.validate.RegisterValidation(key, v.createOptionRule(key)); err != nil {
			return fmt.Errorf("failed to register validation for %s: %w", key, err)
		}
	}

	return nil
}
func (v *Validator) Validate(input interface{}) error {
	if input == nil {
		return nil
	}

	val := reflect.ValueOf(input)
	if val.Kind() == reflect.Ptr {
		if val.IsNil() {
			return nil
		}
		val = val.Elem() // Dereference the pointer
	}

	err := v.validate.Struct(input)
	if err == nil {
		return nil
	}

	// Filter out errors for nil/empty fields
	if ve, ok := err.(v10.ValidationErrors); ok {
		var filteredErrors v10.ValidationErrors
		for _, fe := range ve {
			fieldValue := val.FieldByName(fe.StructField())
			if !fieldValue.IsValid() {
				continue
			}

			if !isEmpty(fieldValue) {
				filteredErrors = append(filteredErrors, fe)
			} else {
				fmt.Printf("Ignoring validation error for empty field: %s\n", fe.Field())
			}
		}

		if len(filteredErrors) > 0 {
			return filteredErrors
		}
		return nil
	}

	return err
}

// isEmpty checks if a value is nil or empty
func isEmpty(v reflect.Value) bool {
	switch v.Kind() {
	case reflect.String:
		return v.Len() == 0
	case reflect.Ptr, reflect.Interface:
		return v.IsNil()
	case reflect.Slice, reflect.Map, reflect.Array:
		return v.Len() == 0
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return v.Int() == 0
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		return v.Uint() == 0
	case reflect.Float32, reflect.Float64:
		return v.Float() == 0
	case reflect.Bool:
		return !v.Bool()
	case reflect.Struct:
		if t, ok := v.Interface().(time.Time); ok {
			return t.IsZero()
		}
		// Consider non-time structs as non-empty
		return false
	default:
		return false
	}
}

// createOptionRule remains the same as previous version
func (v *Validator) createOptionRule(key string) func(v10.FieldLevel) bool {
	return func(fl v10.FieldLevel) bool {
		field := fl.Field()
		if isEmpty(field) {
			return true
		}

		value := field.String()
		validOptions, err := v.source.GetValidOptions(key)
		if err != nil || validOptions == nil {
			return true
		}

		for _, opt := range validOptions {
			if opt == value {
				return true
			}
		}

		return false
	}
}

func (v *Validator) validatePassword(fl v10.FieldLevel) bool {
	password := fl.Field().String()
	return len(password) >= 8 &&
		strings.ContainsAny(password, "abcdefghijklmnopqrstuvwxyz") &&
		strings.ContainsAny(password, "ABCDEFGHIJKLMNOPQRSTUVWXYZ") &&
		strings.ContainsAny(password, "0123456789")
}

func (v *Validator) validatePhoneNumber(fl v10.FieldLevel) bool {
	phone := NormalizePhoneNumber(fl.Field().String())
	return strings.HasPrefix(phone, "+62")
}

func NormalizePhoneNumber(input string) string {
	re := regexp.MustCompile(`[^0-9\+]`)
	input = re.ReplaceAllString(input, "")

	switch {
	case strings.HasPrefix(input, "0"):
		return "+62" + input[1:]
	case strings.HasPrefix(input, "62") && !strings.HasPrefix(input, "+62"):
		return "+" + input
	case strings.HasPrefix(input, "8"):
		return "+62" + input
	default:
		return input
	}
}