[add] new table widget ( 60% )

This commit is contained in:
Max 2022-09-24 22:37:18 +08:00
parent bab6ca51b5
commit d012aac872
19 changed files with 1569 additions and 5 deletions

View file

@ -17,8 +17,8 @@ import (
//
// API:
// GET /api/__yao/app/setting -> Default process: yao.app.Xgen
// GET /api/__yao/app/menu -> Default process: yao.app.Menu
// GET /api/__yao/app/setting -> Default process: yao.app.Xgen
// GET /api/__yao/app/menu -> Default process: yao.app.Menu
//
// Process:
// yao.app.Setting Return the App DSL

View file

@ -0,0 +1,38 @@
package component
// DSL the component DSL
type DSL struct {
Type string `json:"type,omitempty"`
In string `json:"in,omitempty"`
Out string `json:"out,omitempty"`
Props PropsDSL `json:"props,omitempty"`
}
// InstanceDSL the component instance DSL
type InstanceDSL struct {
Name string `json:"name,omitempty"`
Width interface{} `json:"width,omitempty"`
Height interface{} `json:"height,omitempty"`
}
// ActionDSL the component action DSL
type ActionDSL struct {
Title string `json:"title,omitempty"`
Icon string `json:"icon,omitempty"`
Style string `json:"style,omitempty"`
Props PropsDSL `json:"props,omitempty"`
Confirm ConfirmActionDSL `json:"confirm,omitempty"`
Action map[string]ParamsDSL `json:"actions,omitempty"`
}
// ConfirmActionDSL action.confirm
type ConfirmActionDSL struct {
Title string `json:"title,omitempty"`
Desc string `json:"desc,omitempty"`
}
// PropsDSL component props
type PropsDSL map[string]interface{}
// ParamsDSL action params
type ParamsDSL map[string]interface{}

View file

@ -3,6 +3,7 @@ package login
import (
"fmt"
"path/filepath"
"strings"
jsoniter "github.com/json-iterator/go"
"github.com/yaoapp/gou"
@ -14,7 +15,7 @@ import (
//
// API:
// GET /api/__yao/login/:id/captcha -> Default process: yao.utils.Captcha :query
// POST /api/__yao/login/:id -> Default process: yao.admin.Login :payload
// POST /api/__yao/login/:id -> Default process: yao.admin.Login :payload
//
// Logins the loaded login widgets
@ -40,7 +41,8 @@ func LoadFrom(dir string, prefix string) error {
dsl := &DSL{ID: id}
err := jsoniter.Unmarshal(data, dsl)
if err != nil {
messages = append(messages, err.Error())
messages = append(messages, fmt.Sprintf("[%s] %s", id, err.Error()))
return
}
// Apply a language pack
@ -51,6 +53,10 @@ func LoadFrom(dir string, prefix string) error {
Logins[id] = dsl
})
if len(messages) > 0 {
return fmt.Errorf(strings.Join(messages, ";"))
}
return err
}

View file

@ -1,6 +1,6 @@
package login
// DSL the app DSL
// DSL the login DSL
type DSL struct {
ID string `json:"id,omitempty"`
Name string `json:"name,omitempty"`

359
widgets/table/action.go Normal file
View file

@ -0,0 +1,359 @@
package table
import (
"fmt"
"github.com/yaoapp/gou"
"github.com/yaoapp/kun/any"
"github.com/yaoapp/kun/exception"
"github.com/yaoapp/kun/log"
"github.com/yaoapp/kun/maps"
)
var processActionDefaults = map[string]*ProcessActionDSL{
"Setting": {
Name: "yao.table.Setting",
Process: "yao.table.Xgen",
Default: []interface{}{},
},
"Component": {
Name: "yao.table.Component",
Default: []interface{}{nil, nil, nil},
},
"Search": {
Name: "yao.table.Search",
Default: []interface{}{nil, 1, 20},
},
"Get": {
Name: "yao.table.Get",
Default: []interface{}{nil},
},
"Find": {
Name: "yao.table.Find",
Default: []interface{}{nil, nil},
},
"Save": {
Name: "yao.table.Save",
Default: []interface{}{nil},
},
"Create": {
Name: "yao.table.Create",
Default: []interface{}{nil},
},
"Insert": {
Name: "yao.table.Insert",
Default: []interface{}{nil, nil},
},
"Update": {
Name: "yao.table.Update",
Default: []interface{}{nil, nil},
},
"UpdateWhere": {
Name: "yao.table.UpdateWhere",
Default: []interface{}{nil, nil},
},
"UpdateIn": {
Name: "yao.table.UpdateIn",
Default: []interface{}{nil, nil},
},
"Delete": {
Name: "yao.table.Delete",
Default: []interface{}{nil},
},
"DeleteWhere": {
Name: "yao.table.DeleteWhere",
Default: []interface{}{nil},
},
"DeleteIn": {
Name: "yao.table.DeleteIn",
Default: []interface{}{nil},
},
}
// SetDefaultProcess set the default value of action
func (action *ActionDSL) SetDefaultProcess() {
action.Setting = action.newProcessAction("Setting", action.Setting, nil, nil)
action.Component = action.newProcessAction("Component", action.Component, nil, nil)
action.Search = action.newProcessAction("Search", action.Search, action.BeforeSearch, action.AfterSearch)
action.Get = action.newProcessAction("Get", action.Get, action.BeforeGet, action.AfterGet)
action.Find = action.newProcessAction("Find", action.Find, action.BeforeFind, action.AfterFind)
action.Save = action.newProcessAction("Save", action.Save, action.BeforeSave, action.AfterSave)
action.Create = action.newProcessAction("Create", action.Create, action.BeforeCreate, action.AfterCreate)
action.Insert = action.newProcessAction("Insert", action.Insert, action.BeforeInsert, action.AfterInsert)
action.Update = action.newProcessAction("Update", action.Update, action.BeforeUpdate, action.AfterUpdate)
action.UpdateWhere = action.newProcessAction("UpdateWhere", action.UpdateWhere, action.BeforeUpdateWhere, action.AfterUpdateWhere)
action.UpdateIn = action.newProcessAction("UpdateIn", action.UpdateIn, action.BeforeUpdateIn, action.AfterUpdateIn)
action.Delete = action.newProcessAction("Delete", action.Delete, action.BeforeDelete, action.AfterDelete)
action.DeleteWhere = action.newProcessAction("DeleteWhere", action.DeleteWhere, action.BeforeDeleteWhere, action.AfterDeleteWhere)
action.DeleteIn = action.newProcessAction("DeleteIn", action.DeleteIn, action.BeforeDeleteIn, action.AfterDeleteIn)
}
// BindModel bind model
func (action *ActionDSL) BindModel(m *gou.Model) {
name := m.ID // should be id
action.Search.Bind(fmt.Sprintf("models.%s.Paginate", name))
action.Get.Bind(fmt.Sprintf("models.%s.Get", name))
action.Find.Bind(fmt.Sprintf("models.%s.Find", name))
action.Save.Bind(fmt.Sprintf("models.%s.Save", name))
action.Create.Bind(fmt.Sprintf("models.%s.Create", name))
action.Insert.Bind(fmt.Sprintf("models.%s.Insert", name))
action.Update.Bind(fmt.Sprintf("models.%s.Update", name))
action.UpdateWhere.Bind(fmt.Sprintf("models.%s.UpdateWhere", name))
action.UpdateIn.Bind(fmt.Sprintf("models.%s.UpdateWhere", name))
action.Delete.Bind(fmt.Sprintf("models.%s.Delete", name))
action.DeleteWhere.Bind(fmt.Sprintf("models.%s.DeleteWhere", name))
action.DeleteIn.Bind(fmt.Sprintf("models.%s.DeleteWhere", name))
// bind options
if action.Bind.Option != nil {
action.Search.Default[0] = action.Bind.Option
action.Get.Default[0] = action.Bind.Option
action.Find.Default[1] = action.Bind.Option
}
}
// setDefault Set the process action disabled
func (action *ActionDSL) newProcessAction(name string, p *ProcessActionDSL, before *BeforeHookActionDSL, after *AfterHookActionDSL) *ProcessActionDSL {
if p == nil {
p = &ProcessActionDSL{}
}
p.After = after
p.Before = before
if defaultProcess, has := processActionDefaults[name]; has {
p.Name = defaultProcess.Name
if p.Process == "" {
p.Process = defaultProcess.Process
}
if p.Guard == "" {
p.Guard = defaultProcess.Guard
}
if p.Default == nil {
p.Default = defaultProcess.Default
}
// format defaults
if len(p.Default) != len(defaultProcess.Default) {
defauts := defaultProcess.Default
nums := len(p.Default)
if nums > len(defaultProcess.Default) {
nums = len(defaultProcess.Default)
}
for i := 0; i < nums; i++ {
defauts[i] = p.Default[i]
}
p.Default = defauts
}
}
return p
}
// Bind the process name
func (p *ProcessActionDSL) Bind(name string) {
p.ProcessBind = name
}
// Args get the process args
func (p *ProcessActionDSL) Args(process *gou.Process) []interface{} {
process.ValidateArgNums(1)
args := p.Default
nums := len(process.Args[1:])
if nums > len(args) {
nums = len(args)
}
for i := 0; i < nums; i++ {
args[i] = p.deepMergeDefault(process.Args[i+1], args[i])
}
return args
}
// Exec exec the process
func (p *ProcessActionDSL) Exec(process *gou.Process) (interface{}, error) {
tab, err := Get(process)
if err != nil {
return nil, err
}
args := p.Args(process)
// Process
name := p.Process
if name == "" {
name = p.ProcessBind
}
if name == "" {
log.Error("[table] %s %s process is required", tab.ID, p.Name)
return nil, fmt.Errorf("[table] %s %s process is required", tab.ID, p.Name)
}
// Before Hook
if p.Before != nil {
log.Trace("[table] %s %s before: exec(%v)", tab.ID, p.Name, args)
newArgs, err := p.Before.Exec(args, process.Sid, process.Global)
if err != nil {
log.Error("[table] %s %s before: %s", tab.ID, p.Name, err.Error())
} else {
log.Trace("[table] %s %s before: args:%v", tab.ID, p.Name, args)
args = newArgs
}
}
// Compute In
switch p.Name {
case "yao.table.Save", "yao.table.Create":
switch args[0].(type) {
case map[string]interface{}:
data := args[0].(map[string]interface{})
err := tab.computeSave(process, data)
if err != nil {
log.Error("[table] %s %s -> %s %s", tab.ID, p.Name, name, err.Error())
}
args[0] = data
}
break
case "yao.table.Update", "yao.table.UpdateWhere", "yao.table.UpdateIn":
switch args[1].(type) {
case map[string]interface{}:
data := args[1].(map[string]interface{})
err := tab.computeSave(process, data)
if err != nil {
log.Error("[table] %s %s -> %s %s", tab.ID, p.Name, name, err.Error())
}
args[1] = data
}
break
case "yao.table.Insert":
break
}
// Execute Process
act, err := gou.ProcessOf(name, args...)
if err != nil {
log.Error("[table] %s %s -> %s %s", tab.ID, p.Name, name, err.Error())
return nil, fmt.Errorf("[table] %s %s -> %s %s", tab.ID, p.Name, name, err.Error())
}
res, err := act.WithGlobal(process.Global).WithSID(process.Sid).Exec()
if err != nil {
log.Error("[table] %s %s -> %s %s", tab.ID, p.Name, name, err.Error())
return nil, fmt.Errorf("[table] %s %s -> %s %s", tab.ID, p.Name, name, err.Error())
}
// Compute Out
switch p.Name {
case "yao.table.Search":
if newMap, ok := res.(map[string]interface{}); ok {
err := tab.computeSearch(process, newMap, "data")
if err != nil {
log.Error("[table] %s %s -> %s %s", tab.ID, p.Name, name, err.Error())
}
res = newMap
}
break
case "yao.table.Get":
if _, ok := res.([]maps.MapStr); ok {
data := []interface{}{}
for _, v := range res.([]maps.MapStr) {
data = append(data, map[string]interface{}(v))
}
res = data
}
if data, ok := res.([]interface{}); ok {
err := tab.computeGet(process, data)
if err != nil {
log.Error("[table] %s %s -> %s %s", tab.ID, p.Name, name, err.Error())
}
res = data
}
break
case "yao.table.Find":
switch res.(type) {
case map[string]interface{}, maps.MapStr:
data := any.MapOf(res).MapStrAny
err := tab.computeFind(process, data)
if err != nil {
log.Error("[table] %s %s -> %s %s", tab.ID, p.Name, name, err.Error())
}
res = data
}
break
}
// After hook
if p.After != nil {
log.Trace("[table] %s %s after: exec(%v)", tab.ID, p.Name, res)
newRes, err := p.After.Exec(res, process.Sid, process.Global)
if err != nil {
log.Error("[table] %s %s after: %s", tab.ID, p.Name, err.Error())
} else {
log.Trace("[table] %s %s after: %v", tab.ID, p.Name, newRes)
res = newRes
}
}
return res, nil
}
// MustExec exec the process
func (p *ProcessActionDSL) MustExec(process *gou.Process) interface{} {
res, err := p.Exec(process)
if err != nil {
exception.New(err.Error(), 500).Throw()
}
return res
}
// deepMergeDefault deep merge args
func (p *ProcessActionDSL) deepMergeDefault(value interface{}, defaults interface{}) interface{} {
if value == nil {
return defaults
}
switch defaults.(type) {
case map[string]interface{}:
defaultMap := defaults.(map[string]interface{})
valueMap := any.Of(value).MapStr()
for key, v := range defaultMap {
valueMap[key] = p.deepMergeDefault(valueMap[key], v)
}
return valueMap
case []interface{}:
defaultArr := defaults.([]interface{})
valueArr := any.Of(value).CArray()
// pad
nums := len(defaultArr) - len(valueArr)
for i := 0; i < nums; i++ {
valueArr = append(valueArr, nil)
}
// set default
for idx, v := range defaultArr {
valueArr[idx] = p.deepMergeDefault(valueArr[idx], v)
}
return valueArr
}
return value
}

3
widgets/table/api.go Normal file
View file

@ -0,0 +1,3 @@
package table
// export api

53
widgets/table/bind.go Normal file
View file

@ -0,0 +1,53 @@
package table
import (
"fmt"
"github.com/yaoapp/gou"
)
// Bind model / store / table / ...
func (dsl *DSL) Bind() error {
if dsl.Action.Bind == nil {
return nil
}
if dsl.Action.Bind.Model != "" {
return dsl.bindModel()
}
if dsl.Action.Bind.Store != "" {
return dsl.bindStore()
}
if dsl.Action.Bind.Table != "" {
return dsl.bindTable()
}
return nil
}
func (dsl *DSL) bindModel() error {
id := dsl.Action.Bind.Model
m, has := gou.Models[id]
if !has {
return fmt.Errorf("%s does not exist", id)
}
dsl.Action.BindModel(m)
dsl.Fields.BindModel(m)
dsl.Layout.BindModel(m)
return nil
}
func (dsl *DSL) bindStore() error {
id := dsl.Action.Bind.Store
return fmt.Errorf("bind.store %s does not support yet", id)
}
func (dsl *DSL) bindTable() error {
id := dsl.Action.Bind.Table
return fmt.Errorf("bind.table %s does not support yet", id)
}

115
widgets/table/compute.go Normal file
View file

@ -0,0 +1,115 @@
package table
import (
"fmt"
"strings"
"github.com/yaoapp/gou"
"github.com/yaoapp/kun/any"
"github.com/yaoapp/kun/log"
"github.com/yaoapp/kun/maps"
)
func (dsl *DSL) computeSearch(process *gou.Process, res map[string]interface{}, itemKey string) error {
if data, has := res[itemKey]; has {
if arr, ok := data.([]interface{}); ok {
err := dsl.computeGet(process, arr)
if err != nil {
return err
}
res[itemKey] = arr
}
}
return nil
}
func (dsl *DSL) computeGet(process *gou.Process, data []interface{}) error {
messages := []string{}
for idx, row := range data {
switch row.(type) {
case map[string]interface{}, maps.MapStr:
rowMap := any.MapOf(row).MapStrAny
err := dsl.computeFind(process, rowMap)
if err != nil {
messages = append(messages, err.Error())
}
data[idx] = rowMap
}
}
if len(messages) > 0 {
return fmt.Errorf("%s", strings.Join(messages, ";"))
}
return nil
}
func (dsl *DSL) computeFind(process *gou.Process, values map[string]interface{}) error {
messages := []string{}
for key := range values {
err := dsl.computeOut(process, key, values)
if err != nil {
messages = append(messages, err.Error())
}
}
if len(messages) > 0 {
return fmt.Errorf("%s", strings.Join(messages, ";"))
}
return nil
}
func (dsl *DSL) computeSave(process *gou.Process, values map[string]interface{}) error {
messages := []string{}
for key := range values {
err := dsl.computeIn(process, key, values)
if err != nil {
messages = append(messages, err.Error())
}
}
if len(messages) > 0 {
return fmt.Errorf("%s", strings.Join(messages, ";"))
}
return nil
}
func (dsl *DSL) computeIn(process *gou.Process, key string, values map[string]interface{}) error {
if name, has := dsl.ComputesIn[key]; has {
compute, err := gou.ProcessOf(name, key, values[key], values)
if err != nil {
log.Error("[table] %s compute-in -> %s %s %s", dsl.ID, name, key, err.Error())
return fmt.Errorf("[table] %s compute-in -> %s %s %s", dsl.ID, name, key, err.Error())
}
res, err := compute.WithGlobal(process.Global).WithSID(process.Sid).Exec()
if err != nil {
log.Error("[table] %s compute-in -> %s %s %s", dsl.ID, name, key, err.Error())
return fmt.Errorf("[table] %s compute-in -> %s %s %s", dsl.ID, name, key, err.Error())
}
values[key] = res
}
return nil
}
func (dsl *DSL) computeOut(process *gou.Process, key string, values map[string]interface{}) error {
if name, has := dsl.ComputesOut[key]; has {
compute, err := gou.ProcessOf(name, key, values[key], values)
if err != nil {
log.Error("[table] %s compute-out -> %s %s %s", dsl.ID, name, key, err.Error())
return fmt.Errorf("[table] %s compute-out -> %s %s %s", dsl.ID, name, key, err.Error())
}
res, err := compute.WithGlobal(process.Global).WithSID(process.Sid).Exec()
if err != nil {
log.Error("[table] %s compute-out -> %s %s %s", dsl.ID, name, key, err.Error())
return fmt.Errorf("[table] %s compute-out -> %s %s %s", dsl.ID, name, key, err.Error())
}
values[key] = res
}
return nil
}

7
widgets/table/export.go Normal file
View file

@ -0,0 +1,7 @@
package table
// Export process & api
func Export() error {
exportProcess()
return nil
}

7
widgets/table/fields.go Normal file
View file

@ -0,0 +1,7 @@
package table
import "github.com/yaoapp/gou"
// BindModel bind model
func (fields *FieldsDSL) BindModel(m *gou.Model) {
}

66
widgets/table/hook.go Normal file
View file

@ -0,0 +1,66 @@
package table
import (
"fmt"
"github.com/yaoapp/gou"
)
// Exec execute the hook
func (hook *BeforeHookActionDSL) Exec(args []interface{}, sid string, global map[string]interface{}) ([]interface{}, error) {
p, err := gou.ProcessOf(hook.String(), args...)
if err != nil {
return nil, fmt.Errorf("%s %s", hook.String(), err.Error())
}
res, err := p.WithGlobal(global).WithSID(sid).Exec()
if err != nil {
return nil, fmt.Errorf("[%s] %s", hook.String(), err.Error())
}
newArgs, ok := res.([]interface{})
if !ok {
return nil, fmt.Errorf("%s return value is not an array", hook.String())
}
if len(newArgs) != len(args) {
return nil, fmt.Errorf("%s return value is not correct. should: array[%d], got: array[%d]", hook.String(), len(args), len(newArgs))
}
return newArgs, nil
}
// Exec execute the hook
func (hook *AfterHookActionDSL) Exec(value interface{}, sid string, global map[string]interface{}) (interface{}, error) {
args := []interface{}{}
switch value.(type) {
case []interface{}:
args = value.([]interface{})
default:
args = append(args, value)
}
p, err := gou.ProcessOf(hook.String(), args...)
if err != nil {
return nil, fmt.Errorf("[%s] %s", hook.String(), err.Error())
}
res, err := p.WithGlobal(global).WithSID(sid).Exec()
if err != nil {
return nil, fmt.Errorf("[%s] %s", hook.String(), err.Error())
}
return res, nil
}
// String cast to string
func (hook *BeforeHookActionDSL) String() string {
return string(*hook)
}
// String cast to string
func (hook *AfterHookActionDSL) String() string {
return string(*hook)
}

7
widgets/table/lang.go Normal file
View file

@ -0,0 +1,7 @@
package table
// Lang for applying a language pack
func (dsl *DSL) Lang(trans func(widget string, inst string, value *string) bool) {
widget := "table"
trans(widget, dsl.ID, &dsl.Name)
}

10
widgets/table/layout.go Normal file
View file

@ -0,0 +1,10 @@
package table
import (
"github.com/yaoapp/gou"
)
// BindModel bind model
func (layout *LayoutDSL) BindModel(m *gou.Model) {
layout.Primary = m.PrimaryKey
}

114
widgets/table/process.go Normal file
View file

@ -0,0 +1,114 @@
package table
import (
"strings"
"github.com/yaoapp/gou"
)
// Export process
func exportProcess() {
gou.RegisterProcessHandler("yao.table.setting", processSetting)
gou.RegisterProcessHandler("yao.table.xgen", processXgen)
gou.RegisterProcessHandler("yao.table.component", processComponent)
gou.RegisterProcessHandler("yao.table.search", processSearch)
gou.RegisterProcessHandler("yao.table.get", processGet)
gou.RegisterProcessHandler("yao.table.find", processFind)
gou.RegisterProcessHandler("yao.table.save", processSave)
gou.RegisterProcessHandler("yao.table.create", processCreate)
gou.RegisterProcessHandler("yao.table.insert", processInsert)
gou.RegisterProcessHandler("yao.table.update", processUpdate)
gou.RegisterProcessHandler("yao.table.updatewhere", processUpdateWhere)
gou.RegisterProcessHandler("yao.table.updatein", processUpdateIn)
gou.RegisterProcessHandler("yao.table.delete", processDelete)
gou.RegisterProcessHandler("yao.table.deletewhere", processDeleteWhere)
gou.RegisterProcessHandler("yao.table.deletein", processDeleteIn)
}
func processXgen(process *gou.Process) interface{} {
return nil
}
func processComponent(process *gou.Process) interface{} {
return nil
}
func processSetting(process *gou.Process) interface{} {
tab := MustGet(process)
return tab.Action.Setting.MustExec(process)
}
func processSearch(process *gou.Process) interface{} {
tab := MustGet(process)
return tab.Action.Search.MustExec(process)
}
func processGet(process *gou.Process) interface{} {
tab := MustGet(process)
return tab.Action.Get.MustExec(process)
}
func processSave(process *gou.Process) interface{} {
tab := MustGet(process)
return tab.Action.Save.MustExec(process)
}
func processCreate(process *gou.Process) interface{} {
tab := MustGet(process)
return tab.Action.Create.MustExec(process)
}
func processFind(process *gou.Process) interface{} {
tab := MustGet(process)
return tab.Action.Find.MustExec(process)
}
func processInsert(process *gou.Process) interface{} {
tab := MustGet(process)
return tab.Action.Insert.MustExec(process)
}
func processUpdate(process *gou.Process) interface{} {
tab := MustGet(process)
return tab.Action.Update.MustExec(process)
}
func processUpdateWhere(process *gou.Process) interface{} {
tab := MustGet(process)
return tab.Action.UpdateWhere.MustExec(process)
}
func processUpdateIn(process *gou.Process) interface{} {
process.ValidateArgNums(3)
tab := MustGet(process)
ids := strings.Split(process.ArgsString(1), ",")
process.Args[1] = gou.QueryParam{
Wheres: []gou.QueryWhere{
{Column: tab.Layout.Primary, OP: "in", Value: ids},
},
}
return tab.Action.UpdateIn.MustExec(process)
}
func processDelete(process *gou.Process) interface{} {
tab := MustGet(process)
return tab.Action.Delete.MustExec(process)
}
func processDeleteWhere(process *gou.Process) interface{} {
tab := MustGet(process)
return tab.Action.DeleteWhere.MustExec(process)
}
func processDeleteIn(process *gou.Process) interface{} {
process.ValidateArgNums(2)
tab := MustGet(process)
ids := strings.Split(process.ArgsString(1), ",")
process.Args[1] = gou.QueryParam{
Wheres: []gou.QueryWhere{
{Column: tab.Layout.Primary, OP: "in", Value: ids},
},
}
return tab.Action.DeleteIn.MustExec(process)
}

View file

@ -0,0 +1,346 @@
package table
import (
"fmt"
"testing"
"github.com/stretchr/testify/assert"
"github.com/yaoapp/gou"
"github.com/yaoapp/kun/any"
"github.com/yaoapp/yao/config"
q "github.com/yaoapp/yao/query"
)
func TestProcessSearch(t *testing.T) {
load(t)
clear(t)
testData(t)
params := map[string]interface{}{
"withs": map[string]interface{}{
"user": map[string]interface{}{},
},
}
args := []interface{}{"pet", params, 1, 5}
res, err := gou.NewProcess("yao.table.search", args...).Exec()
if err != nil {
t.Fatal(err)
}
data := any.Of(res).MapStr().Dot()
assert.Equal(t, "AfterSearch", data.Get("after:hook"))
assert.Equal(t, "1", fmt.Sprintf("%v", data.Get("pagesize")))
assert.Equal(t, "3", fmt.Sprintf("%v", data.Get("total")))
assert.Equal(t, "#FF0000", data.Get("data.0.status.color"))
assert.Equal(t, "status", data.Get("data.0.status.field"))
assert.Equal(t, "checked", data.Get("data.0.status.label"))
assert.Equal(t, "Cookie", data.Get("data.0.status.name"))
}
func TestProcessGet(t *testing.T) {
load(t)
clear(t)
testData(t)
params := map[string]interface{}{
"limit": 2,
"withs": map[string]interface{}{
"user": map[string]interface{}{},
},
}
args := []interface{}{"pet", params}
res, err := gou.NewProcess("yao.table.get", args...).Exec()
if err != nil {
t.Fatal(err)
}
arr := any.Of(res).CArray()
assert.Equal(t, 2, len(arr))
data := any.Of(arr[0]).MapStr().Dot()
assert.Equal(t, "#FF0000", data.Get("status.color"))
assert.Equal(t, "status", data.Get("status.field"))
assert.Equal(t, "checked", data.Get("status.label"))
assert.Equal(t, "Cookie", data.Get("status.name"))
}
func TestProcessFind(t *testing.T) {
load(t)
clear(t)
testData(t)
args := []interface{}{"pet", 1}
res, err := gou.NewProcess("yao.table.find", args...).Exec()
if err != nil {
t.Fatal(err)
}
data := any.Of(res).MapStr().Dot()
assert.Equal(t, "#FF0000", data.Get("status.color"))
assert.Equal(t, "status", data.Get("status.field"))
assert.Equal(t, "checked", data.Get("status.label"))
assert.Equal(t, "Cookie", data.Get("status.name"))
}
func TestProcessSave(t *testing.T) {
load(t)
clear(t)
testData(t)
args := []interface{}{"pet", map[string]interface{}{
"name": "New Pet",
"type": "cat",
"status": "checked",
"mode": "enabled",
"stay": 66,
"cost": 24,
"doctor_id": 1,
}}
res, err := gou.NewProcess("yao.table.Save", args...).Exec()
if err != nil {
t.Fatal(err)
}
assert.Equal(t, "4", fmt.Sprintf("%v", res))
res, err = gou.NewProcess("yao.table.find", "pet", res).Exec()
if err != nil {
t.Fatal(err)
}
data := any.Of(res).MapStr().Dot()
assert.Equal(t, "New Pet|New Pet", data.Get("name"))
}
func TestProcessCreate(t *testing.T) {
load(t)
clear(t)
testData(t)
args := []interface{}{"pet", map[string]interface{}{
"id": 6,
"name": "New Pet",
"type": "cat",
"status": "checked",
"mode": "enabled",
"stay": 66,
"cost": 24,
"doctor_id": 1,
}}
res, err := gou.NewProcess("yao.table.Create", args...).Exec()
if err != nil {
t.Fatal(err)
}
assert.Equal(t, "6", fmt.Sprintf("%v", res))
res, err = gou.NewProcess("yao.table.find", "pet", res).Exec()
if err != nil {
t.Fatal(err)
}
data := any.Of(res).MapStr().Dot()
assert.Equal(t, "New Pet|New Pet", data.Get("name"))
}
func TestProcessUpdate(t *testing.T) {
load(t)
clear(t)
testData(t)
args := []interface{}{"pet", 1, map[string]interface{}{
"name": "New Pet",
"type": "cat",
"status": "checked",
"mode": "enabled",
"stay": 66,
"cost": 24,
"doctor_id": 1,
}}
_, err := gou.NewProcess("yao.table.Update", args...).Exec()
if err != nil {
t.Fatal(err)
}
res, err := gou.NewProcess("yao.table.find", "pet", 1).Exec()
if err != nil {
t.Fatal(err)
}
data := any.Of(res).MapStr().Dot()
assert.Equal(t, "New Pet|New Pet", data.Get("name"))
}
func TestProcessUpdateWhere(t *testing.T) {
load(t)
clear(t)
testData(t)
args := []interface{}{"pet",
map[string]interface{}{"wheres": []map[string]interface{}{{"column": "id", "value": 1}}},
map[string]interface{}{
"name": "New Pet",
"type": "cat",
"status": "checked",
"mode": "enabled",
"stay": 66,
"cost": 24,
"doctor_id": 1,
}}
_, err := gou.NewProcess("yao.table.UpdateWhere", args...).Exec()
if err != nil {
t.Fatal(err)
}
res, err := gou.NewProcess("yao.table.find", "pet", 1).Exec()
if err != nil {
t.Fatal(err)
}
data := any.Of(res).MapStr().Dot()
assert.Equal(t, "New Pet|New Pet", data.Get("name"))
}
func TestProcessUpdateIn(t *testing.T) {
load(t)
clear(t)
testData(t)
args := []interface{}{"pet", "1",
map[string]interface{}{
"name": "New Pet",
"type": "cat",
"status": "checked",
"mode": "enabled",
"stay": 66,
"cost": 24,
"doctor_id": 1,
}}
_, err := gou.NewProcess("yao.table.UpdateIn", args...).Exec()
if err != nil {
t.Fatal(err)
}
res, err := gou.NewProcess("yao.table.find", "pet", 1).Exec()
if err != nil {
t.Fatal(err)
}
data := any.Of(res).MapStr().Dot()
assert.Equal(t, "New Pet|New Pet", data.Get("name"))
}
func TestProcessInsert(t *testing.T) {
load(t)
clear(t)
args := []interface{}{"pet",
[]string{"name", "type", "status", "mode", "stay", "cost", "doctor_id"},
[][]interface{}{
{"Cookie", "cat", "checked", "enabled", 200, 105, 1},
{"Baby", "dog", "checked", "enabled", 186, 24, 1},
{"Poo", "others", "checked", "enabled", 199, 66, 1},
},
}
_, err := gou.NewProcess("yao.table.Insert", args...).Exec()
if err != nil {
t.Fatal(err)
}
res, err := gou.NewProcess("yao.table.find", "pet", 1).Exec()
if err != nil {
t.Fatal(err)
}
data := any.Of(res).MapStr().Dot()
assert.Equal(t, "Cookie", data.Get("name"))
}
func TestProcessDelete(t *testing.T) {
load(t)
clear(t)
testData(t)
args := []interface{}{"pet", 1}
_, err := gou.NewProcess("yao.table.Delete", args...).Exec()
if err != nil {
t.Fatal(err)
}
_, err = gou.NewProcess("yao.table.find", "pet", 1).Exec()
assert.Contains(t, err.Error(), "ID=1")
}
func TestProcessDeleteWhere(t *testing.T) {
load(t)
clear(t)
testData(t)
args := []interface{}{
"pet",
map[string]interface{}{"wheres": []map[string]interface{}{{"column": "id", "value": 1}}},
}
_, err := gou.NewProcess("yao.table.DeleteWhere", args...).Exec()
if err != nil {
t.Fatal(err)
}
_, err = gou.NewProcess("yao.table.find", "pet", 1).Exec()
assert.Contains(t, err.Error(), "ID=1")
}
func TestProcessDeleteIn(t *testing.T) {
load(t)
clear(t)
testData(t)
args := []interface{}{"pet", "1"}
_, err := gou.NewProcess("yao.table.DeleteIn", args...).Exec()
if err != nil {
t.Fatal(err)
}
_, err = gou.NewProcess("yao.table.find", "pet", 1).Exec()
assert.Contains(t, err.Error(), "ID=1")
}
func load(t *testing.T) {
prepare(t)
err := Load(config.Conf)
if err != nil {
t.Fatal(err)
}
q.Load(config.Conf)
}
func testData(t *testing.T) {
pet := gou.Select("pet")
err := pet.Insert(
[]string{"name", "type", "status", "mode", "stay", "cost", "doctor_id"},
[][]interface{}{
{"Cookie", "cat", "checked", "enabled", 200, 105, 1},
{"Baby", "dog", "checked", "enabled", 186, 24, 1},
{"Poo", "others", "checked", "enabled", 199, 66, 1},
},
)
if err != nil {
t.Fatal(err)
}
}
func clear(t *testing.T) {
pet := gou.Select("pet")
err := pet.DropTable()
if err != nil {
t.Fatal(err)
}
err = pet.Migrate(true)
if err != nil {
t.Fatal(err)
}
}

208
widgets/table/table.go Normal file
View file

@ -0,0 +1,208 @@
package table
import (
"fmt"
"path/filepath"
"strings"
jsoniter "github.com/json-iterator/go"
"github.com/yaoapp/gou"
"github.com/yaoapp/gou/lang"
"github.com/yaoapp/kun/exception"
"github.com/yaoapp/yao/config"
"github.com/yaoapp/yao/share"
"github.com/yaoapp/yao/widgets/component"
)
//
// API:
// GET /api/__yao/table/:id/setting -> Default process: yao.table.Xgen
// GET /api/__yao/table/:id/search -> Default process: yao.table.Search $param.id :query $query.page $query.pagesize
// GET /api/__yao/table/:id/get -> Default process: yao.table.Get $param.id :query
// GET /api/__yao/table/:id/find/:primary -> Default process: yao.table.Find $param.id $param.primary :query
// GET /api/__yao/table/:id/component/:name/:method -> Default process: yao.table.Component $param.id $param.name $param.method :query
// POST /api/__yao/table/:id/save -> Default process: yao.table.Save $param.id $param.primary :payload
// POST /api/__yao/table/:id/insert -> Default process: yao.table.Insert :payload
// POST /api/__yao/table/:id/update/:primary -> Default process: yao.table.Update $param.id $param.primary :payload
// POST /api/__yao/table/:id/update/where -> Default process: yao.table.UpdateWhere $param.id :query :payload
// POST /api/__yao/table/:id/update/in -> Default process: yao.table.UpdateIn $param.id $query.ids :payload
// POST /api/__yao/table/:id/delete/:primary -> Default process: yao.table.Delete $param.id $param.primary
// POST /api/__yao/table/:id/delete/where -> Default process: yao.table.DeleteWhere $param.id :query
// POST /api/__yao/table/:id/delete/in -> Default process: yao.table.DeleteIn $param.id $query.ids
//
// Process:
// yao.table.Setting Return the App DSL
// yao.table.Xgen Return the Xgen setting
// yao.table.Search Return the records with pagination
// yao.table.Get Return the records without pagination
// yao.table.Find Return the record via the given primary key
// yao.table.Component Return the result defined in props.xProps
// yao.table.Save Save a record, if given a primary key update, else insert
// yao.table.Create Create a record
// yao.table.Insert Insert records
// yao.table.Update update record via the given primary key
// yao.table.UpdateWhere update record via the given query params
// yao.table.UpdateIn update record via the given primary key list
// yao.table.Delete delete record via the given primary key
// yao.table.DeleteWhere delete record via the given query params
// yao.table.DeleteIn delete record via the given primary key list
//
// Hook:
// before:find
// after:find
// before:search
// after:search
// before:get
// after:get
// before:save
// after:save
// before:create
// after:create
// before:delete
// after:delete
// before:insert
// after:insert
// before:delete-in
// after:delete-in
// before:delete-where
// after:delete-where
// before:update-in
// after:update-in
// before:update-where
// after:update-where
//
// Tables the loaded table widgets
var Tables map[string]*DSL = map[string]*DSL{}
// New create a new DSL
func New(id string) *DSL {
return &DSL{
ID: id,
Components: map[string]*component.DSL{},
ComputesIn: map[string]string{},
ComputesOut: map[string]string{},
}
}
// Load load task
func Load(cfg config.Config) error {
var root = filepath.Join(cfg.Root, "tables")
return LoadFrom(root, "")
}
// LoadFrom load from dir
func LoadFrom(dir string, prefix string) error {
if share.DirNotExists(dir) {
return fmt.Errorf("%s does not exists", dir)
}
messages := []string{}
err := share.Walk(dir, ".json", func(root, filename string) {
id := prefix + share.ID(root, filename)
data := share.ReadFile(filename)
dsl := New(id)
err := jsoniter.Unmarshal(data, dsl)
if err != nil {
messages = append(messages, fmt.Sprintf("[%s] %s", id, err.Error()))
return
}
if dsl.Action == nil {
dsl.Action = &ActionDSL{}
}
dsl.Action.SetDefaultProcess()
if dsl.Layout == nil {
dsl.Layout = &LayoutDSL{}
}
if dsl.Fields == nil {
dsl.Fields = &FieldsDSL{}
}
// Bind model / store / table / ...
err = dsl.Bind()
if err != nil {
messages = append(messages, fmt.Sprintf("[%s] %s", id, err.Error()))
return
}
// Parse
dsl.Parse()
// Validate
err = dsl.Validate()
if err != nil {
messages = append(messages, fmt.Sprintf("[%s] %s", id, err.Error()))
return
}
// Apply a language pack
if lang.Default != nil {
lang.Default.Apply(dsl)
}
Tables[id] = dsl
})
if len(messages) > 0 {
return fmt.Errorf(strings.Join(messages, ";"))
}
return err
}
// Get table via process or id
func Get(table interface{}) (*DSL, error) {
id := ""
switch table.(type) {
case string:
id = table.(string)
case *gou.Process:
id = table.(*gou.Process).ArgsString(0)
default:
return nil, fmt.Errorf("%v type does not support", table)
}
t, has := Tables[id]
if !has {
return nil, fmt.Errorf("%s does not exist", id)
}
return t, nil
}
// MustGet Get table via process or id thow error
func MustGet(table interface{}) *DSL {
t, err := Get(table)
if err != nil {
exception.New(err.Error(), 500).Throw()
}
return t
}
// Parse Layout default
func (dsl *DSL) Parse() {
if dsl.Fields == nil {
dsl.Fields = &FieldsDSL{
Filter: map[string]FilterFiledsDSL{},
Table: map[string]ViewFiledsDSL{},
}
}
for name, field := range dsl.Fields.Table {
if field.In != "" {
dsl.ComputesIn[field.Bind] = field.In
dsl.ComputesIn[name] = field.In
}
if field.Out != "" {
dsl.ComputesOut[field.Bind] = field.Out
dsl.ComputesOut[name] = field.Out
}
}
}

View file

@ -0,0 +1,56 @@
package table
import (
"os"
"testing"
"github.com/stretchr/testify/assert"
"github.com/yaoapp/yao/config"
"github.com/yaoapp/yao/lang"
"github.com/yaoapp/yao/model"
"github.com/yaoapp/yao/script"
"github.com/yaoapp/yao/share"
)
func TestLoad(t *testing.T) {
prepare(t)
err := Load(config.Conf)
if err != nil {
t.Fatal(err)
}
assert.Equal(t, 2, len(Tables))
}
func prepare(t *testing.T, language ...string) {
// langs
if len(language) < 1 {
os.Unsetenv("YAO_LANG")
} else {
os.Setenv("YAO_LANG", language[0])
}
lang.Load(config.Conf)
share.DBConnect(config.Conf.DB) // removed later
// load scripts
err := script.Load(config.Conf)
if err != nil {
t.Fatal(err)
}
// load models
err = model.Load(config.Conf)
if err != nil {
t.Fatal(err)
}
// load scripts
// export
err = Export()
if err != nil {
t.Fatal(err)
}
}

163
widgets/table/types.go Normal file
View file

@ -0,0 +1,163 @@
package table
import "github.com/yaoapp/yao/widgets/component"
// DSL the table DSL
type DSL struct {
ID string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Action *ActionDSL `json:"action"`
Layout *LayoutDSL `json:"layout"`
Fields *FieldsDSL `json:"fields"`
ComputesIn map[string]string `json:"-"`
ComputesOut map[string]string `json:"-"`
Components map[string]*component.DSL `json:"-"`
Filters map[string]*component.DSL `json:"-"`
}
// ActionDSL the table action DSL
type ActionDSL struct {
Bind *BindActionDSL `json:"bind,omitempty"`
Setting *ProcessActionDSL `json:"setting,omitempty"`
Component *ProcessActionDSL `json:"component,omitempty"`
Search *ProcessActionDSL `json:"search,omitempty"`
Get *ProcessActionDSL `json:"get,omitempty"`
Find *ProcessActionDSL `json:"find,omitempty"`
Save *ProcessActionDSL `json:"save,omitempty"`
Create *ProcessActionDSL `json:"create,omitempty"`
Insert *ProcessActionDSL `json:"insert,omitempty"`
Delete *ProcessActionDSL `json:"delete,omitempty"`
DeleteIn *ProcessActionDSL `json:"delete-in,omitempty"`
DeleteWhere *ProcessActionDSL `json:"delete-where,omitempty"`
Update *ProcessActionDSL `json:"update,omitempty"`
UpdateIn *ProcessActionDSL `json:"update-in,omitempty"`
UpdateWhere *ProcessActionDSL `json:"update-where,omitempty"`
BeforeFind *BeforeHookActionDSL `json:"before:find,omitempty"`
AfterFind *AfterHookActionDSL `json:"after:find,omitempty"`
BeforeSearch *BeforeHookActionDSL `json:"before:search,omitempty"`
AfterSearch *AfterHookActionDSL `json:"after:search,omitempty"`
BeforeGet *BeforeHookActionDSL `json:"before:get,omitempty"`
AfterGet *AfterHookActionDSL `json:"after:get,omitempty"`
BeforeSave *BeforeHookActionDSL `json:"before:save,omitempty"`
AfterSave *AfterHookActionDSL `json:"after:save,omitempty"`
BeforeCreate *BeforeHookActionDSL `json:"before:create,omitempty"`
AfterCreate *AfterHookActionDSL `json:"after:create,omitempty"`
BeforeInsert *BeforeHookActionDSL `json:"before:insert,omitempty"`
AfterInsert *AfterHookActionDSL `json:"after:insert,omitempty"`
BeforeDelete *BeforeHookActionDSL `json:"before:delete,omitempty"`
AfterDelete *AfterHookActionDSL `json:"after:delete,omitempty"`
BeforeDeleteIn *BeforeHookActionDSL `json:"before:delete-in,omitempty"`
AfterDeleteIn *AfterHookActionDSL `json:"after:delete-in,omitempty"`
BeforeDeleteWhere *BeforeHookActionDSL `json:"before:delete-where,omitempty"`
AfterDeleteWhere *AfterHookActionDSL `json:"after:delete-where,omitempty"`
BeforeUpdate *BeforeHookActionDSL `json:"before:update,omitempty"`
AfterUpdate *AfterHookActionDSL `json:"after:update,omitempty"`
BeforeUpdateIn *BeforeHookActionDSL `json:"before:update-in,omitempty"`
AfterUpdateIn *AfterHookActionDSL `json:"after:update-in,omitempty"`
BeforeUpdateWhere *BeforeHookActionDSL `json:"before:update-where,omitempty"`
AfterUpdateWhere *AfterHookActionDSL `json:"after:update-where,omitempty"`
}
// BindActionDSL action.bind
type BindActionDSL struct {
Model string `json:"model,omitempty"` // bind model
Store string `json:"store,omitempty"` // bind store
Table string `json:"table,omitempty"` // bind table
Option map[string]interface{} `json:"option,omitempty"` // bind option
}
// BeforeHookActionDSL action.before:search ...
type BeforeHookActionDSL string
// AfterHookActionDSL action.after:search ...
type AfterHookActionDSL string
// ProcessActionDSL action.search ...
type ProcessActionDSL struct {
Name string `json:"-"`
Process string `json:"process,omitempty"`
ProcessBind string `json:"bind,omitempty"`
Guard string `json:"guard,omitempty"`
Default []interface{} `json:"default,omitempty"`
Disable bool `json:"disable,omitempty"`
Before *BeforeHookActionDSL `json:"-"`
After *AfterHookActionDSL `json:"-"`
}
// LayoutDSL the table layout
type LayoutDSL struct {
Primary string `json:"primary,omitempty"`
Header *HeaderLayoutDSL `json:"header,omitempty"`
Filter *FilterLayoutDSL `json:"filter,omitempty"`
Table *ViewLayoutDSL `json:"table,omitempty"`
}
// HeaderLayoutDSL layout.header
type HeaderLayoutDSL struct {
Preset PresetHeaderDSL `json:"preset,omitempty"`
Actions []component.ActionDSL `json:"actions,omitempty"`
}
// PresetHeaderDSL layout.header.preset
type PresetHeaderDSL struct {
Batch BatchPresetDSL `json:"batch,omitempty"`
Import ImportPresetDSL `json:"import,omitempty"`
}
// BatchPresetDSL layout.header.preset.batch
type BatchPresetDSL struct {
Columns []component.InstanceDSL `json:"columns,omitempty"`
Deletable bool `json:"deletable,omitempty"`
}
// ImportPresetDSL layout.header.preset.import
type ImportPresetDSL struct {
Name string `json:"name,omitempty"`
Operation []OperationImportDSL `json:"operation,omitempty"`
}
// OperationImportDSL layout.header.preset.import.operation[*]
type OperationImportDSL struct {
Title string `json:"title,omitempty"`
Link string `json:"link,omitempty"`
}
// FilterLayoutDSL layout.filter
type FilterLayoutDSL struct {
BtnAddText string `json:"btnAddText,omitempty"`
Columns []component.InstanceDSL `json:"columns,omitempty"`
}
// ViewLayoutDSL layout.table
type ViewLayoutDSL struct {
Props component.PropsDSL `json:"props,omitempty"`
Columns []component.InstanceDSL `json:"columns,omitempty"`
Operation OperationTableDSL `json:"operation,omitempty"`
}
// OperationTableDSL layout.table.operation
type OperationTableDSL struct {
Fold bool `json:"fold,omitempty"`
Actions []component.ActionDSL `json:"actions,omitempty"`
}
// FieldsDSL the table fields DSL
type FieldsDSL struct {
Filter map[string]FilterFiledsDSL `json:"filter,omitempty"`
Table map[string]ViewFiledsDSL `json:"table,omitempty"`
}
// FilterFiledsDSL fields.filter
type FilterFiledsDSL struct {
Bind string `json:"bind,omitempty"`
Edit *component.DSL `json:"edit,omitempty"`
}
// ViewFiledsDSL fields.table
type ViewFiledsDSL struct {
Bind string `json:"bind,omitempty"`
In string `json:"in,omitempty"`
Out string `json:"out,omitempty"`
View *component.DSL `json:"view,omitempty"`
Edit *component.DSL `json:"edit,omitempty"`
}

View file

@ -0,0 +1,6 @@
package table
// Validate table
func (dsl *DSL) Validate() error {
return nil
}