forked from qor/qor
/
resource.go
449 lines (401 loc) · 12.2 KB
/
resource.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
package admin
import (
"fmt"
"reflect"
"strconv"
"strings"
"time"
"github.com/jinzhu/gorm"
"github.com/jinzhu/inflection"
"github.com/jinzhu/now"
"github.com/qor/qor"
"github.com/qor/qor/resource"
"github.com/qor/qor/roles"
"github.com/qor/qor/utils"
)
type Resource struct {
resource.Resource
admin *Admin
Config *Config
Metas []*Meta
actions []*Action
scopes []*Scope
filters map[string]*Filter
searchAttrs *[]string
sortableAttrs *[]string
indexSections []*Section
newSections []*Section
editSections []*Section
showSections []*Section
IsSetShowAttrs bool
cachedMetas *map[string][]*Meta
SearchHandler func(keyword string, context *qor.Context) *gorm.DB
}
func (res *Resource) Meta(meta *Meta) {
if res.GetMeta(meta.Name) != nil {
utils.ExitWithMsg("Duplicated meta %v defined for resource %v", meta.Name, res.Name)
}
res.Metas = append(res.Metas, meta)
meta.base = res
meta.updateMeta()
}
func (res Resource) GetAdmin() *Admin {
return res.admin
}
func (res Resource) ToParam() string {
if res.Config.Singleton == true {
return utils.ToParamString(res.Name)
}
return utils.ToParamString(inflection.Plural(res.Name))
}
func (res Resource) UseTheme(theme string) []string {
if res.Config != nil {
for _, t := range res.Config.Themes {
if t == theme {
return res.Config.Themes
}
}
res.Config.Themes = append(res.Config.Themes, theme)
}
return res.Config.Themes
}
func (res *Resource) convertObjectToJSONMap(context *Context, value interface{}, kind string) interface{} {
reflectValue := reflect.ValueOf(value)
for reflectValue.Kind() == reflect.Ptr {
reflectValue = reflectValue.Elem()
}
switch reflectValue.Kind() {
case reflect.Slice:
values := []interface{}{}
for i := 0; i < reflectValue.Len(); i++ {
values = append(values, res.convertObjectToJSONMap(context, reflectValue.Index(i).Addr().Interface(), kind))
}
return values
case reflect.Struct:
var metas []*Meta
if kind == "index" {
metas = res.ConvertSectionToMetas(res.allowedSections(res.IndexAttrs(), context, roles.Update))
} else if kind == "edit" {
metas = res.ConvertSectionToMetas(res.allowedSections(res.EditAttrs(), context, roles.Update))
} else if kind == "show" {
metas = res.ConvertSectionToMetas(res.allowedSections(res.ShowAttrs(), context, roles.Read))
}
values := map[string]interface{}{}
for _, meta := range metas {
if meta.HasPermission(roles.Read, context.Context) {
if valuer := meta.GetFormattedValuer(); valuer != nil {
value := valuer(value, context.Context)
if meta.GetResource() != nil {
value = meta.Resource.(*Resource).convertObjectToJSONMap(context, value, kind)
}
values[meta.GetName()] = value
}
}
}
return values
default:
return value
}
}
func (res *Resource) Decode(context *qor.Context, value interface{}) error {
return resource.Decode(context, value, res)
}
func (res *Resource) allAttrs() []string {
var attrs []string
scope := &gorm.Scope{Value: res.Value}
Fields:
for _, field := range scope.GetModelStruct().StructFields {
for _, meta := range res.Metas {
if field.Name == meta.FieldName {
attrs = append(attrs, meta.Name)
continue Fields
}
}
if field.IsForeignKey {
continue
}
for _, value := range []string{"CreatedAt", "UpdatedAt", "DeletedAt"} {
if value == field.Name {
continue Fields
}
}
if (field.IsNormal || field.Relationship != nil) && !field.IsIgnored {
attrs = append(attrs, field.Name)
}
}
MetaIncluded:
for _, meta := range res.Metas {
for _, attr := range attrs {
if attr == meta.FieldName || attr == meta.Name {
continue MetaIncluded
}
}
attrs = append(attrs, meta.Name)
}
return attrs
}
func (res *Resource) getAttrs(attrs []string) []string {
if len(attrs) == 0 {
return res.allAttrs()
} else {
var onlyExcludeAttrs = true
for _, attr := range attrs {
if !strings.HasPrefix(attr, "-") {
onlyExcludeAttrs = false
break
}
}
if onlyExcludeAttrs {
return append(res.allAttrs(), attrs...)
}
return attrs
}
}
func (res *Resource) IndexAttrs(values ...interface{}) []*Section {
res.setSections(&res.indexSections, values...)
return res.indexSections
}
func (res *Resource) NewAttrs(values ...interface{}) []*Section {
res.setSections(&res.newSections, values...)
return res.newSections
}
func (res *Resource) EditAttrs(values ...interface{}) []*Section {
res.setSections(&res.editSections, values...)
return res.editSections
}
func (res *Resource) ShowAttrs(values ...interface{}) []*Section {
if len(values) > 0 {
if values[len(values)-1] == false {
values = values[:len(values)-1]
} else {
res.IsSetShowAttrs = true
}
}
res.setSections(&res.showSections, values...)
return res.showSections
}
func (res *Resource) SortableAttrs(columns ...string) []string {
if len(columns) != 0 || res.sortableAttrs == nil {
if len(columns) == 0 {
columns = res.ConvertSectionToStrings(res.indexSections)
}
res.sortableAttrs = &[]string{}
scope := res.GetAdmin().Config.DB.NewScope(res.Value)
for _, column := range columns {
if field, ok := scope.FieldByName(column); ok && field.DBName != "" {
attrs := append(*res.sortableAttrs, column)
res.sortableAttrs = &attrs
}
}
}
return *res.sortableAttrs
}
func (res *Resource) SearchAttrs(columns ...string) []string {
if len(columns) != 0 || res.searchAttrs == nil {
if len(columns) == 0 {
columns = res.ConvertSectionToStrings(res.indexSections)
}
if len(columns) > 0 {
res.searchAttrs = &columns
res.SearchHandler = func(keyword string, context *qor.Context) *gorm.DB {
db := context.GetDB()
var joinConditionsMap = map[string][]string{}
var conditions []string
var keywords []interface{}
scope := db.NewScope(res.Value)
for _, column := range columns {
currentScope, nextScope := scope, scope
if strings.Contains(column, ".") {
for _, field := range strings.Split(column, ".") {
column = field
currentScope = nextScope
if field, ok := scope.FieldByName(field); ok {
if relationship := field.Relationship; relationship != nil {
nextScope = currentScope.New(reflect.New(field.Field.Type()).Interface())
key := fmt.Sprintf("LEFT JOIN %v ON", nextScope.TableName())
for index := range relationship.ForeignDBNames {
if relationship.Kind == "has_one" || relationship.Kind == "has_many" {
joinConditionsMap[key] = append(joinConditionsMap[key],
fmt.Sprintf("%v.%v = %v.%v",
nextScope.QuotedTableName(), scope.Quote(relationship.ForeignDBNames[index]),
currentScope.QuotedTableName(), scope.Quote(relationship.AssociationForeignDBNames[index]),
))
} else if relationship.Kind == "belongs_to" {
joinConditionsMap[key] = append(joinConditionsMap[key],
fmt.Sprintf("%v.%v = %v.%v",
currentScope.QuotedTableName(), scope.Quote(relationship.ForeignDBNames[index]),
nextScope.QuotedTableName(), scope.Quote(relationship.AssociationForeignDBNames[index]),
))
}
}
}
}
}
}
var tableName = currentScope.Quote(currentScope.TableName())
if field, ok := currentScope.FieldByName(column); ok && field.IsNormal {
switch field.Field.Kind() {
case reflect.String:
conditions = append(conditions, fmt.Sprintf("upper(%v.%v) like upper(?)", tableName, scope.Quote(field.DBName)))
keywords = append(keywords, "%"+keyword+"%")
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
if _, err := strconv.Atoi(keyword); err == nil {
conditions = append(conditions, fmt.Sprintf("%v.%v = ?", tableName, scope.Quote(field.DBName)))
keywords = append(keywords, keyword)
}
case reflect.Float32, reflect.Float64:
if _, err := strconv.ParseFloat(keyword, 64); err == nil {
conditions = append(conditions, fmt.Sprintf("%v.%v = ?", tableName, scope.Quote(field.DBName)))
keywords = append(keywords, keyword)
}
case reflect.Bool:
if value, err := strconv.ParseBool(keyword); err == nil {
conditions = append(conditions, fmt.Sprintf("%v.%v = ?", tableName, scope.Quote(field.DBName)))
keywords = append(keywords, value)
}
case reflect.Struct:
// time ?
if _, ok := field.Field.Interface().(time.Time); ok {
if parsedTime, err := now.Parse(keyword); err == nil {
conditions = append(conditions, fmt.Sprintf("%v.%v = ?", tableName, scope.Quote(field.DBName)))
keywords = append(keywords, parsedTime)
}
}
case reflect.Ptr:
// time ?
if _, ok := field.Field.Interface().(*time.Time); ok {
if parsedTime, err := now.Parse(keyword); err == nil {
conditions = append(conditions, fmt.Sprintf("%v.%v = ?", tableName, scope.Quote(field.DBName)))
keywords = append(keywords, parsedTime)
}
}
default:
conditions = append(conditions, fmt.Sprintf("%v.%v = ?", tableName, scope.Quote(field.DBName)))
keywords = append(keywords, keyword)
}
}
}
// join conditions
if len(joinConditionsMap) > 0 {
var joinConditions []string
for key, values := range joinConditionsMap {
joinConditions = append(joinConditions, fmt.Sprintf("%v %v", key, strings.Join(values, " AND ")))
}
db = db.Joins(strings.Join(joinConditions, " "))
}
// search conditions
if len(conditions) > 0 {
return db.Where(strings.Join(conditions, " OR "), keywords...)
} else {
return db
}
}
}
}
return columns
}
func (res *Resource) getCachedMetas(cacheKey string, fc func() []resource.Metaor) []*Meta {
if res.cachedMetas == nil {
res.cachedMetas = &map[string][]*Meta{}
}
if values, ok := (*res.cachedMetas)[cacheKey]; ok {
return values
} else {
values := fc()
var metas []*Meta
for _, value := range values {
metas = append(metas, value.(*Meta))
}
(*res.cachedMetas)[cacheKey] = metas
return metas
}
}
func (res *Resource) GetMetas(attrs []string) []resource.Metaor {
if len(attrs) == 0 {
attrs = res.allAttrs()
}
var showSections, ignoredAttrs []string
for _, attr := range attrs {
if strings.HasPrefix(attr, "-") {
ignoredAttrs = append(ignoredAttrs, strings.TrimLeft(attr, "-"))
} else {
showSections = append(showSections, attr)
}
}
primaryKey := res.PrimaryFieldName()
metas := []resource.Metaor{}
Attrs:
for _, attr := range showSections {
for _, a := range ignoredAttrs {
if attr == a {
continue Attrs
}
}
var meta *Meta
for _, m := range res.Metas {
if m.GetName() == attr {
meta = m
break
}
}
if meta == nil {
meta = &Meta{}
meta.Name = attr
meta.base = res
if attr == primaryKey {
meta.Type = "hidden"
}
meta.updateMeta()
}
metas = append(metas, meta)
}
return metas
}
func (res *Resource) GetMeta(name string) *Meta {
for _, meta := range res.Metas {
if meta.Name == name || meta.GetFieldName() == name {
return meta
}
}
return nil
}
func (res *Resource) GetMetaOrNew(name string) *Meta {
for _, meta := range res.Metas {
if meta.Name == name || meta.GetFieldName() == name {
return meta
}
}
for _, meta := range res.allMetas() {
if meta.Name == name || meta.GetFieldName() == name {
return meta
}
}
return nil
}
func (res *Resource) allMetas() []*Meta {
return res.getCachedMetas("all_metas", func() []resource.Metaor {
return res.GetMetas([]string{})
})
}
func (res *Resource) allowedSections(sections []*Section, context *Context, roles ...roles.PermissionMode) []*Section {
for _, section := range sections {
var editableRows [][]string
for _, row := range section.Rows {
var editableColumns []string
for _, column := range row {
for _, role := range roles {
meta := res.GetMetaOrNew(column)
if meta != nil && meta.HasPermission(role, context.Context) {
editableColumns = append(editableColumns, column)
break
}
}
}
if len(editableColumns) > 0 {
editableRows = append(editableRows, editableColumns)
}
}
section.Rows = editableRows
}
return sections
}