forked from uadmin/uadmin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
process_form.go
548 lines (517 loc) · 17.2 KB
/
process_form.go
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
package uadmin
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"reflect"
"strconv"
"strings"
"time"
)
// processForm verifies form data and stores it to DB
func processForm(modelName string, w http.ResponseWriter, r *http.Request, session *Session, s *ModelSchema) reflect.Value { //(errMap map[string]string) {
var log *Log
user := session.User
//errMap = map[string]string{}
now := time.Now()
DType := reflect.TypeOf(now)
DType1 := reflect.TypeOf(&now)
tempID, _ := strconv.ParseUint(r.FormValue("ID"), 10, 64)
ID := uint(tempID)
isNew := ID == 0
m, ok := NewModel(modelName, true)
if !ok {
Trail(ERROR, "processForm.NewModel model not found (%s)", modelName)
pageErrorHandler(w, r, session)
return m
}
// Fetch record from DB if not new
if ID != 0 {
Get(m.Interface(), "id = ?", ID)
}
if ID != 0 && LogEdit {
func() {
log = &Log{}
log.ParseRecord(m, modelName, ID, &user, log.Action.Modified(), r)
log.Save()
}()
}
// Get Type
t := reflect.TypeOf(m.Interface()).Elem()
perm := user.GetAccess(modelName)
appList := []Approval{}
// Check if there is a field name Createdby
_, hasCreatedBy := t.FieldByName("CreatedBy")
_, hasCreatedByID := t.FieldByName("CreatedByID")
hasCustomCreatedByID := false
customCreatedByID := ""
for index := 0; index < t.NumField(); index++ {
if strings.Contains(t.Field(index).Tag.Get("uadmin"), "created_by_id") {
hasCustomCreatedByID = true
customCreatedByID = t.Field(index).Name
break
}
}
// Check for UpdatedBy
_, hasUpdatedBy := t.FieldByName("UpdatedBy")
_, hasUpdatedByID := t.FieldByName("UpdatedByID")
hasCustomUpdatedByID := false
customUpdatedByID := ""
for index := 0; index < t.NumField(); index++ {
if strings.Contains(t.Field(index).Tag.Get("uadmin"), "updated_by_id") {
hasCustomUpdatedByID = true
customUpdatedByID = t.Field(index).Name
break
}
}
// Check for CreatedAt
_, hasCreatedAt := t.FieldByName("CreatedAt")
hasCustomCreatedAt := false
customCreatedAt := ""
for index := 0; index < t.NumField(); index++ {
if strings.Contains(t.Field(index).Tag.Get("uadmin"), "created_at") {
hasCustomCreatedAt = true
customCreatedAt = t.Field(index).Name
break
}
}
// Check for ModifiedAt
_, hasModifiedAt := t.FieldByName("ModifiedAt")
hasCustomModifiedAt := false
customModifiedAt := ""
for index := 0; index < t.NumField(); index++ {
if strings.Contains(t.Field(index).Tag.Get("uadmin"), "modified_at") {
hasCustomModifiedAt = true
customModifiedAt = t.Field(index).Name
break
}
}
// Check for validation method
_, isValidate := t.MethodByName("Validate")
// Process Fields
for index := 0; index < t.NumField(); index++ {
// Ignore private fields
if strings.ToLower(string(t.Field(index).Name[0])) == string(t.Field(index).Name[0]) {
continue
}
f := s.FieldByName(t.Field(index).Name)
if strings.HasSuffix(t.Field(index).Name, "ID") && f.Name == "" {
f = s.FieldByName(strings.TrimSuffix(t.Field(index).Name, "ID"))
}
if f.ReadOnly == "true" || (strings.Contains(f.ReadOnly, "new") && isNew) || (strings.Contains(f.ReadOnly, "edit") && !isNew) {
continue
}
if t.Field(index).Type.Kind() == reflect.Int {
_v := r.FormValue(t.Field(index).Name)
i, _ := strconv.ParseInt(_v, 10, 64)
// Check if approval is required
if f.Approval && m.Elem().FieldByName(t.Field(index).Name).Int() != i && !perm.Approval {
appList = append(appList, Approval{
ModelName: modelName,
ColumnName: f.Name,
OldValue: fmt.Sprint(m.Elem().FieldByName(t.Field(index).Name).Int()),
NewValue: fmt.Sprint(i),
ChangedBy: user.Username,
ChangeDate: now,
})
} else {
m.Elem().FieldByName(t.Field(index).Name).SetInt(i)
}
} else if t.Field(index).Type.Kind() == reflect.String {
// Check if Multi lingual
val := ""
if f.Type == cMULTILINGUAL {
tVal := map[string]string{}
for _, lang := range activeLangs {
tVal[lang.Code] = fmt.Sprint(r.FormValue(lang.Code + "-" + t.Field(index).Name))
}
buffer := &bytes.Buffer{}
encoder := json.NewEncoder(buffer)
encoder.SetEscapeHTML(false)
_ = encoder.Encode(tVal)
val = buffer.String()
} else if f.Type == "image" || f.Type == "file" {
f.Value = m.Elem().FieldByName(f.Name)
val = processUpload(r, f, modelName, session, s)
if val == "" {
// Check if the delete tag is set
if r.FormValue(f.Name+"-delete") != "delete" {
continue
}
}
} else {
val = fmt.Sprint(r.FormValue(t.Field(index).Name))
}
// Check if approval is required
if f.Approval && m.Elem().FieldByName(t.Field(index).Name).String() != val && !perm.Approval {
// Check if the field is multilingual and if it has a pending approval. If there is a pending
// approval, add the changes to the existing approval instead of adding a new approval
newApproval := Approval{}
if f.Type == cMULTILINGUAL {
Get(&newApproval, "model_name = ? AND column_name = ? AND model_pk = ? AND approval_action = 0", modelName, f.Name, ID)
transObj := map[string]string{}
json.Unmarshal([]byte(newApproval.NewValue), &transObj)
oldVal := ""
newVal := ""
appVal := ""
changed := false
for _, lang := range activeLangs {
oldVal = Translate(m.Elem().FieldByName(t.Field(index).Name).String(), lang.Code, false)
newVal = Translate(val, lang.Code, false)
appVal = Translate(newApproval.NewValue, lang.Code, false)
if oldVal != newVal {
transObj[lang.Code] = newVal
changed = true
} else if newVal != appVal && newApproval.ID != 0 {
changed = true
transObj[lang.Code] = appVal
} else {
transObj[lang.Code] = newVal
}
}
if changed {
buf, _ := json.Marshal(transObj)
newApproval.ModelName = modelName
newApproval.ColumnName = f.Name
newApproval.OldValue = m.Elem().FieldByName(t.Field(index).Name).String()
newApproval.NewValue = string(buf)
newApproval.ChangedBy = user.Username
newApproval.ChangeDate = now
appList = append(appList, newApproval)
} else {
m.Elem().FieldByName(t.Field(index).Name).SetString(val)
}
} else {
appList = append(appList, Approval{
ModelName: modelName,
ColumnName: f.Name,
OldValue: m.Elem().FieldByName(t.Field(index).Name).String(),
NewValue: val,
ChangedBy: user.Username,
ChangeDate: now,
})
}
} else {
m.Elem().FieldByName(t.Field(index).Name).SetString(val)
}
} else if t.Field(index).Type.Kind() == reflect.Bool {
var val bool
val = false
if string(r.FormValue(t.Field(index).Name)) == "on" {
val = true
}
// Check if approval is required
if f.Approval && m.Elem().FieldByName(t.Field(index).Name).Bool() != val && !perm.Approval {
appList = append(appList, Approval{
ModelName: modelName,
ColumnName: f.Name,
OldValue: fmt.Sprint(m.Elem().FieldByName(t.Field(index).Name).Bool()),
NewValue: fmt.Sprint(val),
ChangedBy: user.Username,
ChangeDate: now,
})
} else {
m.Elem().FieldByName(t.Field(index).Name).SetBool(val)
}
} else if t.Field(index).Type.Kind() == reflect.Uint {
_v := r.FormValue(t.Field(index).Name)
i, _ := strconv.ParseUint(_v, 10, 64)
val := uint(i)
// Check if approval is required
if f.Approval && m.Elem().FieldByName(t.Field(index).Name).Uint() != uint64(val) && !perm.Approval {
appList = append(appList, Approval{
ModelName: modelName,
ColumnName: f.Name,
OldValue: fmt.Sprint(m.Elem().FieldByName(t.Field(index).Name).Uint()),
NewValue: fmt.Sprint(val),
ChangedBy: user.Username,
ChangeDate: now,
})
} else {
m.Elem().FieldByName(t.Field(index).Name).Set(reflect.ValueOf(val))
}
} else if t.Field(index).Type.Kind() == reflect.Float64 {
_v := r.FormValue(t.Field(index).Name)
i, _ := strconv.ParseFloat(_v, 64)
// Check if approval is required
if f.Approval && m.Elem().FieldByName(t.Field(index).Name).Float() != i && !perm.Approval {
appList = append(appList, Approval{
ModelName: modelName,
ColumnName: f.Name,
OldValue: fmt.Sprint(m.Elem().FieldByName(t.Field(index).Name).Float()),
NewValue: fmt.Sprint(i),
ChangedBy: user.Username,
ChangeDate: now,
})
} else {
m.Elem().FieldByName(t.Field(index).Name).Set(reflect.ValueOf(i))
}
} else if t.Field(index).Type.Kind() == reflect.Slice {
Field := m.Elem().Field(index)
_v := r.Form[t.Field(index).Name]
// Initialize the list and item
m2mListType := reflect.TypeOf(Field.Interface())
m2mList := reflect.New(m2mListType).Elem()
m2mItemType := reflect.TypeOf(Field.Interface()).Elem()
// Append the selected items from the form
for _, m2mID := range _v {
m2mItem := reflect.Zero(m2mItemType)
m2mItem = reflect.New(m2mItemType).Elem()
Get(m2mItem.Addr().Interface(), "id="+fmt.Sprint(m2mID))
m2mList = reflect.Append(m2mList, m2mItem)
}
// Set the list to the field
m.Elem().FieldByName(t.Field(index).Name).Set(m2mList)
} else if t.Field(index).Type == DType {
if r.FormValue(t.Field(index).Name) == "" {
continue
}
tm, err := time.Parse("2006-01-02 15:04", r.FormValue(t.Field(index).Name))
if err != nil {
tm, err = time.Parse("2006-01-02T15:04", r.FormValue(t.Field(index).Name))
}
if err != nil {
tm, err = time.Parse("2006-01-02T15:04:05", r.FormValue(t.Field(index).Name))
}
if err != nil {
tm, err = time.Parse("2006-01-02 15:04:05", r.FormValue(t.Field(index).Name))
}
if err != nil {
Trail(WARNING, "Unable to parse date: %s (%s)", r.FormValue(t.Field(index).Name), err)
continue
}
tm = time.Date(tm.Year(), tm.Month(), tm.Day(), tm.Hour(), tm.Minute(), tm.Second(), tm.Nanosecond(), getTZ())
if m.Elem().FieldByName(t.Field(index).Name).Interface().(time.Time).IsZero() {
tmTemp := time.Time{}
tmTemp = time.Date(tmTemp.Year(), tmTemp.Month(), tmTemp.Day(), tmTemp.Hour(), tmTemp.Minute(), tmTemp.Second(), tmTemp.Nanosecond(), getTZ())
m.Elem().FieldByName(t.Field(index).Name).Set(reflect.ValueOf(tmTemp))
}
// Check if approval is required
if f.Approval && !tm.Equal(m.Elem().FieldByName(t.Field(index).Name).Interface().(time.Time)) && !perm.Approval {
appList = append(appList, Approval{
ModelName: modelName,
ColumnName: f.Name,
OldValue: m.Elem().FieldByName(t.Field(index).Name).Interface().(time.Time).Format("2006-01-02 15:04:05-07:00"),
NewValue: tm.Format("2006-01-02 15:04:05-07:00"),
ChangedBy: user.Username,
ChangeDate: now,
})
} else {
//if tm.IsZero() {
// tm = now
//}
m.Elem().FieldByName(t.Field(index).Name).Set(reflect.ValueOf(tm))
}
} else if t.Field(index).Type == DType1 {
if r.FormValue(t.Field(index).Name) == "" {
if f.Approval && !m.Elem().FieldByName(t.Field(index).Name).IsNil() && !perm.Approval {
appList = append(appList, Approval{
ModelName: modelName,
ColumnName: f.Name,
OldValue: m.Elem().FieldByName(t.Field(index).Name).Elem().Interface().(time.Time).Format("2006-01-02 15:04:05-07:00"),
NewValue: "",
ChangedBy: user.Username,
ChangeDate: now,
})
} else {
var tm *time.Time
m.Elem().FieldByName(t.Field(index).Name).Set(reflect.ValueOf(tm))
}
} else {
tm, err := time.Parse("2006-01-02 15:04", r.FormValue(t.Field(index).Name))
if err != nil {
tm, err = time.Parse("2006-01-02T15:04", r.FormValue(t.Field(index).Name))
}
if err != nil {
tm, err = time.Parse("2006-01-02T15:04:05", r.FormValue(t.Field(index).Name))
}
if err != nil {
tm, err = time.Parse("2006-01-02 15:04:05", r.FormValue(t.Field(index).Name))
}
if err != nil {
Trail(WARNING, "Unable to parse date: %s (%s)", r.FormValue(t.Field(index).Name), err)
continue
}
tm = time.Date(tm.Year(), tm.Month(), tm.Day(), tm.Hour(), tm.Minute(), tm.Second(), tm.Nanosecond(), getTZ())
tmOld := m.Elem().FieldByName(t.Field(index).Name)
valChanged := !tmOld.IsNil() && !tm.Equal(tmOld.Elem().Interface().(time.Time))
valChanged = valChanged || tmOld.IsNil()
oldVal := ""
if !tmOld.IsNil() {
oldVal = tmOld.Elem().Interface().(time.Time).Format("2006-01-02 15:04:05-07:00")
}
if f.Approval && valChanged && !perm.Approval {
appList = append(appList, Approval{
ModelName: modelName,
ColumnName: f.Name,
OldValue: oldVal,
NewValue: tm.Format("2006-01-02 15:04:05-07:00"),
ChangedBy: user.Username,
ChangeDate: now,
})
} else {
m.Elem().FieldByName(t.Field(index).Name).Set(reflect.ValueOf(&tm))
}
}
}
}
// Create Log before changing anything
if !isNew {
if LogEdit {
func() {
log.Save()
}()
}
if hasUpdatedBy {
if m.Elem().FieldByName("UpdatedBy").Type().Kind() == reflect.String {
m.Elem().FieldByName("UpdatedBy").SetString(user.Username)
}
}
if hasUpdatedByID {
if m.Elem().FieldByName("UpdatedByID").Type().Kind() == reflect.Uint {
m.Elem().FieldByName("UpdatedByID").SetUint(uint64(user.ID))
}
}
if hasCustomUpdatedByID {
if m.Elem().FieldByName(customUpdatedByID).Type().Kind() == reflect.Uint {
m.Elem().FieldByName(customUpdatedByID).SetUint(uint64(user.ID))
}
}
if hasModifiedAt {
if m.Elem().FieldByName("ModifiedAt").Type() == DType {
m.Elem().FieldByName("ModifiedAt").Set(reflect.ValueOf(now))
}
if m.Elem().FieldByName("ModifiedAt").Type() == DType1 {
m.Elem().FieldByName("ModifiedAt").Set(reflect.ValueOf(&now))
}
}
if hasCustomModifiedAt {
if m.Elem().FieldByName(customModifiedAt).Type() == DType {
m.Elem().FieldByName(customModifiedAt).Set(reflect.ValueOf(now))
}
if m.Elem().FieldByName(customModifiedAt).Type() == DType1 {
m.Elem().FieldByName(customModifiedAt).Set(reflect.ValueOf(&now))
}
}
} else {
if hasCreatedBy {
if m.Elem().FieldByName("CreatedBy").Type().Kind() == reflect.String {
m.Elem().FieldByName("CreatedBy").SetString(user.Username)
}
}
if hasCreatedByID {
if m.Elem().FieldByName("CreatedByID").Type().Kind() == reflect.Uint {
m.Elem().FieldByName("CreatedByID").SetUint(uint64(user.ID))
}
}
if hasCustomCreatedByID {
if m.Elem().FieldByName(customCreatedByID).Type().Kind() == reflect.Uint {
m.Elem().FieldByName(customCreatedByID).SetUint(uint64(user.ID))
}
}
if hasCreatedAt {
if m.Elem().FieldByName("CreatedAt").Type() == DType {
m.Elem().FieldByName("CreatedAt").Set(reflect.ValueOf(now))
}
if m.Elem().FieldByName("CreatedAt").Type() == DType1 {
m.Elem().FieldByName("CreatedAt").Set(reflect.ValueOf(&now))
}
}
if hasCustomCreatedAt {
if m.Elem().FieldByName(customCreatedAt).Type() == DType {
m.Elem().FieldByName(customCreatedAt).Set(reflect.ValueOf(now))
}
if m.Elem().FieldByName(customCreatedAt).Type() == DType1 {
m.Elem().FieldByName(customCreatedAt).Set(reflect.ValueOf(&now))
}
}
}
if isValidate {
in := []reflect.Value{}
validate := m.MethodByName("Validate")
ret := validate.Call(in)
if ret[0].Len() > 0 {
tempErrMap, _ := ret[0].Interface().(map[string]string)
for k, v := range tempErrMap {
for i := range s.Fields {
if s.Fields[i].Name == k {
s.Fields[i].ErrMsg = v
}
}
//s.FieldByName(k).ErrMsg = v
}
}
}
formError := false
for _, f := range s.Fields {
if f.ErrMsg != "" {
formError = true
break
}
}
if formError {
// ERROR OCCURRED THEN RETURN
newURL := "new?"
if !isNew {
newURL = fmt.Sprintf("%d?", ID)
}
var val string
for i := 0; i < t.NumField(); i++ {
val = fmt.Sprint(m.Elem().FieldByName(t.Field(i).Name))
if m.Elem().FieldByName(t.Field(i).Name).Type().String() == "time.Time" {
val = m.Elem().FieldByName(t.Field(i).Name).Interface().(time.Time).Format("2006-01-02 15:04:05")
} else if m.Elem().FieldByName(t.Field(i).Name).Type().String() == "*time.Time" {
if m.Elem().FieldByName(t.Field(i).Name).IsNil() {
val = ""
} else {
val = m.Elem().FieldByName(t.Field(i).Name).Interface().(*time.Time).Format("2006-01-02 15:04:05")
}
}
newURL += t.Field(i).Name + "=" + fmt.Sprint(val) + "&"
}
newURL = strings.Replace(newURL, "\n", "", -1)
r.Form.Set("new_url", newURL[0:len(newURL)-1])
return m
}
// Save the record
var saverI saver
saverI, ok = m.Interface().(saver)
if !ok {
Save(m.Elem().Addr().Interface())
} else {
saverI.Save()
}
// Save Approvals
for _, approval := range appList {
approval.ModelPK = GetID(m)
approval.Save()
}
// Store the log for a new record
if LogAdd {
if isNew {
ID = GetID(m)
log = &Log{}
log.ParseRecord(m, modelName, ID, &user, log.Action.Added(), r)
log.Save()
}
}
// Redirect the user to the proper URL
newURL := strings.TrimPrefix(r.URL.Path, RootURL)
if r.FormValue("save") == "" {
newURL = RootURL + strings.Split(newURL, "/")[0]
if r.FormValue("return_url") != "" {
newURL = r.FormValue("return_url")
}
http.Redirect(w, r, newURL, http.StatusSeeOther)
return m
}
if r.FormValue("save") == "another" {
newURL = RootURL + strings.Split(newURL, "/")[0] + "/new"
http.Redirect(w, r, newURL, http.StatusSeeOther)
return m
}
newURL = RootURL + strings.Split(newURL, "/")[0] + "/" + fmt.Sprint(ID)
http.Redirect(w, r, newURL, http.StatusSeeOther)
return m
}