im 管理后台
This commit is contained in:
@@ -0,0 +1,305 @@
|
||||
// Package views
|
||||
// @Link https://github.com/bufanyun/hotgo
|
||||
// @Copyright Copyright (c) 2023 HotGo CLI
|
||||
// @Author Ms <133814250@qq.com>
|
||||
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
|
||||
package views
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"hotgo/internal/consts"
|
||||
"hotgo/internal/library/hggen/internal/cmd/gendao"
|
||||
"hotgo/internal/model/input/sysin"
|
||||
|
||||
"github.com/gogf/gf/v2/database/gdb"
|
||||
"github.com/gogf/gf/v2/frame/g"
|
||||
"github.com/gogf/gf/v2/text/gregex"
|
||||
"github.com/gogf/gf/v2/text/gstr"
|
||||
"github.com/gogf/gf/v2/util/gconv"
|
||||
)
|
||||
|
||||
// DoTableColumns 获取指定表生成字段列表
|
||||
func DoTableColumns(ctx context.Context, in *sysin.GenCodesColumnListInp, config gendao.CGenDaoInput) (fields []*sysin.GenCodesColumnListModel, err error) {
|
||||
var (
|
||||
sql string
|
||||
conf = g.DB(in.Name).GetConfig()
|
||||
)
|
||||
|
||||
// 根据数据库类型使用不同的SQL
|
||||
if conf.Type == consts.DBPgsql {
|
||||
// PostgreSQL: 使用pg_catalog查询列详细信息
|
||||
sql = `
|
||||
SELECT
|
||||
a.attnum as id,
|
||||
a.attname as name,
|
||||
COALESCE(col_description(a.attrelid, a.attnum), '') as dc,
|
||||
t.typname as dataType,
|
||||
CASE
|
||||
WHEN a.atttypmod > 0 THEN t.typname || '(' || (a.atttypmod - 4) || ')'
|
||||
ELSE t.typname
|
||||
END as sqlType,
|
||||
CASE
|
||||
WHEN a.atttypmod > 0 THEN a.atttypmod - 4
|
||||
ELSE NULL
|
||||
END as length,
|
||||
CASE WHEN a.attnotnull THEN 'NO' ELSE 'YES' END as isAllowNull,
|
||||
pg_get_expr(ad.adbin, ad.adrelid) as defaultValue,
|
||||
CASE
|
||||
WHEN pk.contype = 'p' THEN 'PRI'
|
||||
WHEN uk.contype = 'u' THEN 'UNI'
|
||||
ELSE ''
|
||||
END as "index",
|
||||
CASE
|
||||
WHEN ad.adbin IS NOT NULL AND ad.adbin LIKE '%nextval%' THEN 'auto_increment'
|
||||
ELSE ''
|
||||
END as extra
|
||||
FROM pg_attribute a
|
||||
JOIN pg_class c ON a.attrelid = c.oid
|
||||
JOIN pg_namespace n ON c.relnamespace = n.oid
|
||||
JOIN pg_type t ON a.atttypid = t.oid
|
||||
LEFT JOIN pg_attrdef ad ON a.attrelid = ad.adrelid AND a.attnum = ad.adnum
|
||||
LEFT JOIN pg_constraint pk ON pk.conrelid = c.oid AND pk.contype = 'p' AND a.attnum = ANY(pk.conkey)
|
||||
LEFT JOIN pg_constraint uk ON uk.conrelid = c.oid AND uk.contype = 'u' AND a.attnum = ANY(uk.conkey)
|
||||
WHERE n.nspname = 'public'
|
||||
AND c.relname = '` + in.Table + `'
|
||||
AND a.attnum > 0
|
||||
AND NOT a.attisdropped
|
||||
ORDER BY a.attnum`
|
||||
} else {
|
||||
// MySQL: 使用information_schema.COLUMNS
|
||||
sql = fmt.Sprintf("SELECT ORDINAL_POSITION as id, COLUMN_NAME as name, COLUMN_COMMENT as dc, DATA_TYPE as dataType, COLUMN_TYPE as sqlType, CHARACTER_MAXIMUM_LENGTH as length, IS_NULLABLE as isAllowNull, COLUMN_DEFAULT as defaultValue, COLUMN_KEY as `index`, EXTRA as extra FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = '%s' AND TABLE_NAME = '%s' ORDER BY id ASC", conf.Name, in.Table)
|
||||
}
|
||||
|
||||
err = g.DB(in.Name).Ctx(ctx).Raw(sql).Scan(&fields)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if len(fields) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
for _, field := range fields {
|
||||
if in.IsLink == 1 {
|
||||
CustomLinkAttributes(ctx, in.Alias, field, config)
|
||||
} else {
|
||||
CustomAttributes(ctx, field, config)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// CustomLinkAttributes 可自定义关联表的字段属性
|
||||
func CustomLinkAttributes(ctx context.Context, alias string, field *sysin.GenCodesColumnListModel, in gendao.CGenDaoInput) {
|
||||
field.GoName, field.GoType, field.TsName, field.TsType = GenGotype(ctx, field, in)
|
||||
|
||||
field.GoName = gstr.UcFirst(alias + field.GoName)
|
||||
field.TsName = gstr.LcFirst(field.GoName)
|
||||
|
||||
setDefaultQueryWhere(field)
|
||||
setDefaultValue(field)
|
||||
}
|
||||
|
||||
// CustomAttributes 可自定义的字段属性
|
||||
func CustomAttributes(ctx context.Context, field *sysin.GenCodesColumnListModel, in gendao.CGenDaoInput) {
|
||||
field.GoName, field.GoType, field.TsName, field.TsType = GenGotype(ctx, field, in)
|
||||
setDefault(field)
|
||||
}
|
||||
|
||||
// GenGotype 生成字段的go类型
|
||||
func GenGotype(ctx context.Context, field *sysin.GenCodesColumnListModel, in gendao.CGenDaoInput) (goName, typeName, tsName string, tsType string) {
|
||||
var err error
|
||||
tsName = getJsonTagFromCase(field.Name, in.JsonCase)
|
||||
goName = gstr.CaseCamel(field.Name)
|
||||
|
||||
typeName, err = CheckLocalTypeForField(ctx, field.DataType, nil)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
switch gdb.LocalType(typeName) {
|
||||
case gdb.LocalTypeDate, gdb.LocalTypeDatetime:
|
||||
if in.StdTime {
|
||||
typeName = "time.Time"
|
||||
} else {
|
||||
typeName = "*gtime.Time"
|
||||
}
|
||||
|
||||
case gdb.LocalTypeInt64Bytes:
|
||||
typeName = "int64"
|
||||
|
||||
case gdb.LocalTypeUint64Bytes:
|
||||
typeName = "uint64"
|
||||
|
||||
// Special type handle.
|
||||
case gdb.LocalTypeJson, gdb.LocalTypeJsonb:
|
||||
if in.GJsonSupport {
|
||||
typeName = "*gjson.Json"
|
||||
} else {
|
||||
typeName = "string"
|
||||
}
|
||||
}
|
||||
|
||||
tsType = ShiftMap[typeName]
|
||||
return
|
||||
}
|
||||
|
||||
// CheckLocalTypeForField checks and returns corresponding type for given db type.
|
||||
func CheckLocalTypeForField(ctx context.Context, fieldType string, fieldValue interface{}) (string, error) {
|
||||
var (
|
||||
typeName string
|
||||
typePattern string
|
||||
)
|
||||
match, _ := gregex.MatchString(`(.+?)\((.+)\)`, fieldType)
|
||||
if len(match) == 3 {
|
||||
typeName = gstr.Trim(match[1])
|
||||
typePattern = gstr.Trim(match[2])
|
||||
} else {
|
||||
typeName = gstr.Split(fieldType, " ")[0]
|
||||
}
|
||||
typeName = strings.ToLower(typeName)
|
||||
switch typeName {
|
||||
case
|
||||
"binary",
|
||||
"varbinary",
|
||||
"blob",
|
||||
"tinyblob",
|
||||
"mediumblob",
|
||||
"longblob":
|
||||
return string(gdb.LocalTypeBytes), nil
|
||||
|
||||
case
|
||||
"int",
|
||||
"tinyint",
|
||||
"small_int",
|
||||
"smallint",
|
||||
"medium_int",
|
||||
"mediumint",
|
||||
"serial":
|
||||
if gstr.ContainsI(fieldType, "unsigned") {
|
||||
return string(gdb.LocalTypeUint), nil
|
||||
}
|
||||
return string(gdb.LocalTypeInt), nil
|
||||
|
||||
case
|
||||
"big_int",
|
||||
"bigint",
|
||||
"bigserial":
|
||||
if gstr.ContainsI(fieldType, "unsigned") {
|
||||
return string(gdb.LocalTypeUint64), nil
|
||||
}
|
||||
return string(gdb.LocalTypeInt64), nil
|
||||
|
||||
case
|
||||
"real":
|
||||
return string(gdb.LocalTypeFloat32), nil
|
||||
|
||||
case
|
||||
"float",
|
||||
"double",
|
||||
"decimal",
|
||||
"money",
|
||||
"numeric",
|
||||
"smallmoney":
|
||||
return string(gdb.LocalTypeFloat64), nil
|
||||
|
||||
case
|
||||
"bit":
|
||||
// It is suggested using bit(1) as boolean.
|
||||
if typePattern == "1" {
|
||||
return string(gdb.LocalTypeBool), nil
|
||||
}
|
||||
s := gconv.String(fieldValue)
|
||||
// mssql is true|false string.
|
||||
if strings.EqualFold(s, "true") || strings.EqualFold(s, "false") {
|
||||
return string(gdb.LocalTypeBool), nil
|
||||
}
|
||||
if gstr.ContainsI(fieldType, "unsigned") {
|
||||
return string(gdb.LocalTypeUint64Bytes), nil
|
||||
}
|
||||
return string(gdb.LocalTypeInt64Bytes), nil
|
||||
|
||||
case
|
||||
"bool":
|
||||
return string(gdb.LocalTypeBool), nil
|
||||
|
||||
case
|
||||
"date":
|
||||
return string(gdb.LocalTypeDate), nil
|
||||
|
||||
case
|
||||
"datetime",
|
||||
"timestamp",
|
||||
"timestamptz":
|
||||
return string(gdb.LocalTypeDatetime), nil
|
||||
|
||||
case
|
||||
"json":
|
||||
return string(gdb.LocalTypeJson), nil
|
||||
|
||||
case
|
||||
"jsonb":
|
||||
return string(gdb.LocalTypeJsonb), nil
|
||||
|
||||
default:
|
||||
// Auto-detect field type, using key match.
|
||||
switch {
|
||||
case strings.Contains(typeName, "text") || strings.Contains(typeName, "char") || strings.Contains(typeName, "character"):
|
||||
return string(gdb.LocalTypeString), nil
|
||||
|
||||
case strings.Contains(typeName, "float") || strings.Contains(typeName, "double") || strings.Contains(typeName, "numeric"):
|
||||
return string(gdb.LocalTypeFloat64), nil
|
||||
|
||||
case strings.Contains(typeName, "bool"):
|
||||
return string(gdb.LocalTypeBool), nil
|
||||
|
||||
case strings.Contains(typeName, "binary") || strings.Contains(typeName, "blob"):
|
||||
return string(gdb.LocalTypeBytes), nil
|
||||
|
||||
case strings.Contains(typeName, "int"):
|
||||
if gstr.ContainsI(fieldType, "unsigned") {
|
||||
return string(gdb.LocalTypeUint), nil
|
||||
}
|
||||
return string(gdb.LocalTypeInt), nil
|
||||
|
||||
case strings.Contains(typeName, "time"):
|
||||
return string(gdb.LocalTypeDatetime), nil
|
||||
|
||||
case strings.Contains(typeName, "date"):
|
||||
return string(gdb.LocalTypeDatetime), nil
|
||||
|
||||
default:
|
||||
return string(gdb.LocalTypeString), nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// getJsonTagFromCase call gstr.Case* function to convert the s to specified case.
|
||||
func getJsonTagFromCase(str, caseStr string) string {
|
||||
switch gstr.ToLower(caseStr) {
|
||||
case gstr.ToLower("Camel"):
|
||||
return gstr.CaseCamel(str)
|
||||
|
||||
case gstr.ToLower("CamelLower"):
|
||||
return gstr.CaseCamelLower(str)
|
||||
|
||||
case gstr.ToLower("Kebab"):
|
||||
return gstr.CaseKebab(str)
|
||||
|
||||
case gstr.ToLower("KebabScreaming"):
|
||||
return gstr.CaseKebabScreaming(str)
|
||||
|
||||
case gstr.ToLower("Snake"):
|
||||
return gstr.CaseSnake(str)
|
||||
|
||||
case gstr.ToLower("SnakeFirstUpper"):
|
||||
return gstr.CaseSnakeFirstUpper(str)
|
||||
|
||||
case gstr.ToLower("SnakeScreaming"):
|
||||
return gstr.CaseSnakeScreaming(str)
|
||||
}
|
||||
return str
|
||||
}
|
||||
@@ -0,0 +1,326 @@
|
||||
// Package views
|
||||
// @Link https://github.com/bufanyun/hotgo
|
||||
// @Copyright Copyright (c) 2023 HotGo CLI
|
||||
// @Author Ms <133814250@qq.com>
|
||||
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
|
||||
package views
|
||||
|
||||
import (
|
||||
"github.com/gogf/gf/v2/text/gstr"
|
||||
"hotgo/internal/consts"
|
||||
"hotgo/internal/model/input/sysin"
|
||||
)
|
||||
|
||||
// 默认表单组件映射 Ts -> 表单组件
|
||||
var defaultFormModeMap = map[string]string{
|
||||
TsTypeString: FormModeInput,
|
||||
TsTypeNumber: FormModeInputNumber,
|
||||
TsTypeBoolean: FormModeInputNumber,
|
||||
TsTypeArray: FormModeInputDynamic,
|
||||
TsTypeTuple: FormModeInputDynamic,
|
||||
TsTypeAny: FormModeInput,
|
||||
}
|
||||
|
||||
var defaultEditFields = map[string]bool{
|
||||
"id": false,
|
||||
"created_at": false,
|
||||
"updated_at": false,
|
||||
"deleted_at": false,
|
||||
}
|
||||
|
||||
var defaultEditSwitch = map[string]bool{
|
||||
"id": false,
|
||||
"level": false,
|
||||
"tree": false,
|
||||
"created_by": false,
|
||||
"updated_by": false,
|
||||
"deleted_by": false,
|
||||
"created_at": false,
|
||||
"updated_at": false,
|
||||
"deleted_at": false,
|
||||
}
|
||||
|
||||
var defaultListSwitch = map[string]bool{
|
||||
"level": false,
|
||||
"tree": false,
|
||||
"deleted_at": false,
|
||||
}
|
||||
|
||||
var defaultExportSwitch = map[string]bool{
|
||||
"level": false,
|
||||
"tree": false,
|
||||
"deleted_at": false,
|
||||
}
|
||||
|
||||
var defaultQuerySwitch = map[string]bool{
|
||||
"level": false,
|
||||
"tree": false,
|
||||
"deleted_at": false,
|
||||
}
|
||||
|
||||
var defaultSort = map[string]bool{
|
||||
"id": true,
|
||||
"sort": true,
|
||||
}
|
||||
|
||||
var defaultTreeFields = []string{"pid", "level", "tree"}
|
||||
|
||||
// 默认表单验证映射 物理类型命名识别
|
||||
var defaultFormRoleMap = map[string]string{
|
||||
"mobile": FormRolePhone,
|
||||
"qq": FormRoleQq,
|
||||
"email": FormRoleEmail,
|
||||
"id_card": FormRoleIdCard,
|
||||
"bank_card": FormRoleBankCard,
|
||||
"password": FormRolePassword,
|
||||
"pass": FormRolePassword,
|
||||
"price": FormRoleAmount,
|
||||
}
|
||||
|
||||
// 默认查询条件映射 go类型识别
|
||||
var defaultWhereModeMap = map[string]string{
|
||||
GoTypeString: WhereModeLike,
|
||||
GoTypeDate: WhereModeEq,
|
||||
GoTypeDatetime: WhereModeEq,
|
||||
GoTypeInt: WhereModeEq,
|
||||
GoTypeUint: WhereModeEq,
|
||||
GoTypeInt64: WhereModeEq,
|
||||
GoTypeUint64: WhereModeEq,
|
||||
GoTypeIntSlice: WhereModeIn,
|
||||
GoTypeInt64Slice: WhereModeIn,
|
||||
GoTypeUint64Slice: WhereModeIn,
|
||||
GoTypeFloat32: WhereModeEq,
|
||||
GoTypeFloat64: WhereModeEq,
|
||||
GoTypeBytes: WhereModeEq,
|
||||
GoTypeTime: WhereModeEq,
|
||||
GoTypeGTime: WhereModeEq,
|
||||
GoTypeJson: WhereModeJsonContains,
|
||||
}
|
||||
|
||||
// setDefault 设置默认属性
|
||||
func setDefault(field *sysin.GenCodesColumnListModel) {
|
||||
setDefaultEdit(field)
|
||||
|
||||
setDefaultFormMode(field)
|
||||
|
||||
setDefaultFormRole(field)
|
||||
|
||||
setDefaultDictType(field)
|
||||
|
||||
setDefaultList(field)
|
||||
|
||||
setDefaultExport(field)
|
||||
|
||||
setDefaultQuery(field)
|
||||
|
||||
setDefaultQueryWhere(field)
|
||||
|
||||
setDefaultValue(field)
|
||||
|
||||
if field.IsAllowNull == "NO" {
|
||||
field.Required = true
|
||||
}
|
||||
|
||||
if IsIndexUNI(field.Index) {
|
||||
field.Unique = true
|
||||
}
|
||||
|
||||
if df, ok := defaultSort[field.Name]; ok {
|
||||
field.IsSort = df
|
||||
}
|
||||
|
||||
if field.Dc == "" {
|
||||
field.Dc = field.Name
|
||||
}
|
||||
}
|
||||
|
||||
// setDefaultEdit 设置默认编辑
|
||||
func setDefaultEdit(field *sysin.GenCodesColumnListModel) {
|
||||
field.IsEdit = true
|
||||
|
||||
if IsIndexPK(field.Index) {
|
||||
field.IsEdit = false
|
||||
return
|
||||
}
|
||||
|
||||
if df, ok := defaultEditFields[field.Name]; ok {
|
||||
field.IsEdit = df
|
||||
}
|
||||
|
||||
if df, ok := defaultEditSwitch[field.Name]; ok {
|
||||
field.IsEdit = df
|
||||
}
|
||||
}
|
||||
|
||||
// setDefaultFormMode 设置默认表单组件
|
||||
func setDefaultFormMode(field *sysin.GenCodesColumnListModel) {
|
||||
field.FormMode = FormModeInput
|
||||
if df, ok := defaultFormModeMap[field.TsType]; ok {
|
||||
field.FormMode = df
|
||||
}
|
||||
|
||||
if gstr.HasSuffix(field.GoName, "Status") && IsNumberType(field.GoType) {
|
||||
field.FormMode = FormModeSelect
|
||||
return
|
||||
}
|
||||
|
||||
if field.GoName == "CreatedAt" {
|
||||
field.FormMode = FormModeTimeRange
|
||||
return
|
||||
}
|
||||
|
||||
if (field.GoName == "ProvinceId" || field.GoName == "CityId") && IsNumberType(field.GoType) {
|
||||
field.FormMode = FormModeCitySelector
|
||||
return
|
||||
}
|
||||
|
||||
if field.DataType == "datetime" || field.DataType == "timestamp" || field.DataType == "timestamptz" {
|
||||
field.FormMode = FormModeTime
|
||||
return
|
||||
}
|
||||
|
||||
if field.DataType == "date" {
|
||||
field.FormMode = FormModeDate
|
||||
return
|
||||
}
|
||||
|
||||
if field.GoType == GoTypeString && field.Length >= 256 && field.Length <= 512 {
|
||||
field.FormMode = FormModeInputTextarea
|
||||
return
|
||||
}
|
||||
|
||||
if field.GoType == GoTypeString && field.Length > 512 {
|
||||
field.FormMode = FormModeInputEditor
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// setDefaultFormRole 设置默认表单验证
|
||||
func setDefaultFormRole(field *sysin.GenCodesColumnListModel) {
|
||||
field.FormRole = FormRoleNone
|
||||
|
||||
switch field.GoType {
|
||||
case GoTypeUint, GoTypeUint64:
|
||||
field.FormRole = FormRoleNum
|
||||
return
|
||||
}
|
||||
|
||||
if df, ok := defaultFormRoleMap[field.Name]; ok {
|
||||
field.FormRole = df
|
||||
}
|
||||
}
|
||||
|
||||
// setDefaultDictType 设置默认字典类型
|
||||
func setDefaultDictType(field *sysin.GenCodesColumnListModel) {
|
||||
if gstr.HasSuffix(field.GoName, "Status") && IsNumberType(field.GoType) {
|
||||
field.DictType = 3 // 默认系统状态ID
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// setDefaultList 设置默认列表
|
||||
func setDefaultList(field *sysin.GenCodesColumnListModel) {
|
||||
field.IsList = true
|
||||
switch field.GoType {
|
||||
case GoTypeIntSlice, GoTypeInt64Slice, GoTypeUint64Slice, GoTypeBytes, GoTypeJson:
|
||||
field.IsList = false
|
||||
return
|
||||
}
|
||||
|
||||
if field.Length >= 500 {
|
||||
field.IsList = false
|
||||
return
|
||||
}
|
||||
|
||||
if df, ok := defaultListSwitch[field.Name]; ok {
|
||||
field.IsList = df
|
||||
}
|
||||
}
|
||||
|
||||
// setDefaultExport 设置默认导出
|
||||
func setDefaultExport(field *sysin.GenCodesColumnListModel) {
|
||||
field.IsExport = true
|
||||
switch field.GoType {
|
||||
case GoTypeIntSlice, GoTypeInt64Slice, GoTypeUint64Slice, GoTypeBytes, GoTypeJson:
|
||||
field.IsExport = false
|
||||
return
|
||||
}
|
||||
|
||||
if field.Length >= 500 {
|
||||
field.IsExport = false
|
||||
return
|
||||
}
|
||||
|
||||
if df, ok := defaultExportSwitch[field.Name]; ok {
|
||||
field.IsExport = df
|
||||
}
|
||||
}
|
||||
|
||||
// setDefaultQuery 设置默认查询
|
||||
func setDefaultQuery(field *sysin.GenCodesColumnListModel) {
|
||||
field.IsQuery = false
|
||||
|
||||
if IsIndexPK(field.Index) {
|
||||
field.IsQuery = true
|
||||
return
|
||||
}
|
||||
|
||||
if gstr.HasSuffix(field.GoName, "Status") && IsNumberType(field.GoType) {
|
||||
field.IsQuery = true
|
||||
return
|
||||
}
|
||||
|
||||
if field.GoName == "CreatedAt" {
|
||||
field.IsQuery = true
|
||||
return
|
||||
}
|
||||
|
||||
if df, ok := defaultQuerySwitch[field.Name]; ok {
|
||||
field.IsQuery = df
|
||||
}
|
||||
}
|
||||
|
||||
// setDefaultQueryWhere 设置默认查询条件
|
||||
func setDefaultQueryWhere(field *sysin.GenCodesColumnListModel) {
|
||||
field.QueryWhere = WhereModeEq
|
||||
|
||||
if field.GoName == "CreatedAt" {
|
||||
field.QueryWhere = WhereModeBetween
|
||||
return
|
||||
}
|
||||
|
||||
if field.Length >= 500 {
|
||||
field.QueryWhere = WhereModeLikeAll
|
||||
return
|
||||
}
|
||||
|
||||
if df, ok := defaultWhereModeMap[field.GoType]; ok {
|
||||
field.QueryWhere = df
|
||||
}
|
||||
}
|
||||
|
||||
// setDefaultValue 设置默认value
|
||||
func setDefaultValue(field *sysin.GenCodesColumnListModel) {
|
||||
var value interface{}
|
||||
if field.DefaultValue == nil {
|
||||
switch field.GoType {
|
||||
case GoTypeString, GoTypeBytes, GoTypeDate, GoTypeDatetime, GoTypeTime, GoTypeGTime:
|
||||
value = ""
|
||||
case GoTypeIntSlice, GoTypeInt64Slice, GoTypeUint64Slice, GoTypeJson:
|
||||
value = nil
|
||||
case GoTypeInt, GoTypeUint, GoTypeInt64, GoTypeUint64:
|
||||
value = 0
|
||||
case GoTypeBool:
|
||||
value = false
|
||||
}
|
||||
} else {
|
||||
value = consts.ConvType(field.DefaultValue, field.GoType)
|
||||
}
|
||||
|
||||
// 时间类型不做默认值处理
|
||||
if field.GoType == GoTypeGTime {
|
||||
value = ""
|
||||
}
|
||||
|
||||
field.DefaultValue = value
|
||||
}
|
||||
@@ -0,0 +1,343 @@
|
||||
// Package views
|
||||
// @Link https://github.com/bufanyun/hotgo
|
||||
// @Copyright Copyright (c) 2023 HotGo CLI
|
||||
// @Author Ms <133814250@qq.com>
|
||||
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
|
||||
package views
|
||||
|
||||
import (
|
||||
"github.com/gogf/gf/v2/text/gstr"
|
||||
"hotgo/internal/model/input/sysin"
|
||||
"hotgo/utility/validate"
|
||||
)
|
||||
|
||||
// 字段映射关系
|
||||
|
||||
// go类型
|
||||
const (
|
||||
GoTypeString = "string"
|
||||
GoTypeDate = "date"
|
||||
GoTypeDatetime = "datetime"
|
||||
GoTypeInt = "int"
|
||||
GoTypeUint = "uint"
|
||||
GoTypeInt64 = "int64"
|
||||
GoTypeUint64 = "uint64"
|
||||
GoTypeIntSlice = "[]int"
|
||||
GoTypeInt64Slice = "[]int64"
|
||||
GoTypeUint64Slice = "[]uint64"
|
||||
GoTypeFloat32 = "float32"
|
||||
GoTypeFloat64 = "float64"
|
||||
GoTypeBytes = "[]byte"
|
||||
GoTypeBool = "bool"
|
||||
GoTypeTime = "time.Time"
|
||||
GoTypeGTime = "*gtime.Time"
|
||||
GoTypeJson = "*gjson.Json"
|
||||
)
|
||||
|
||||
var GoTypeNameMap = map[string]string{
|
||||
GoTypeString: GoTypeString,
|
||||
GoTypeDate: GoTypeDate,
|
||||
GoTypeDatetime: GoTypeDatetime,
|
||||
GoTypeInt: GoTypeInt,
|
||||
GoTypeUint: GoTypeUint,
|
||||
GoTypeInt64: GoTypeInt64,
|
||||
GoTypeUint64: GoTypeUint64,
|
||||
GoTypeIntSlice: GoTypeIntSlice,
|
||||
GoTypeInt64Slice: GoTypeInt64Slice,
|
||||
GoTypeUint64Slice: GoTypeUint64Slice,
|
||||
GoTypeFloat32: GoTypeFloat32,
|
||||
GoTypeFloat64: GoTypeFloat64,
|
||||
GoTypeBytes: GoTypeBytes,
|
||||
GoTypeBool: GoTypeBool,
|
||||
GoTypeTime: GoTypeTime,
|
||||
GoTypeGTime: GoTypeGTime,
|
||||
GoTypeJson: GoTypeJson,
|
||||
}
|
||||
|
||||
// ts类型
|
||||
const (
|
||||
TsTypeString = "string"
|
||||
TsTypeNumber = "number"
|
||||
TsTypeBoolean = "boolean"
|
||||
TsTypeArray = "array"
|
||||
TsTypeTuple = "tuple"
|
||||
TsTypeAny = "any"
|
||||
)
|
||||
|
||||
var TsTypeNameMap = map[string]string{
|
||||
TsTypeString: TsTypeString,
|
||||
TsTypeNumber: TsTypeNumber,
|
||||
TsTypeBoolean: TsTypeBoolean,
|
||||
TsTypeArray: TsTypeArray,
|
||||
TsTypeTuple: TsTypeTuple,
|
||||
TsTypeAny: TsTypeAny,
|
||||
}
|
||||
|
||||
// ShiftMap Go -> Ts 类型转换
|
||||
var ShiftMap = map[string]string{
|
||||
GoTypeString: TsTypeString,
|
||||
GoTypeDate: TsTypeString,
|
||||
GoTypeDatetime: TsTypeString,
|
||||
GoTypeInt: TsTypeNumber,
|
||||
GoTypeUint: TsTypeNumber,
|
||||
GoTypeInt64: TsTypeNumber,
|
||||
GoTypeUint64: TsTypeNumber,
|
||||
GoTypeIntSlice: TsTypeArray,
|
||||
GoTypeInt64Slice: TsTypeArray,
|
||||
GoTypeUint64Slice: TsTypeArray,
|
||||
GoTypeFloat32: TsTypeNumber,
|
||||
GoTypeFloat64: TsTypeNumber,
|
||||
GoTypeBytes: TsTypeString,
|
||||
GoTypeBool: TsTypeBoolean,
|
||||
GoTypeTime: TsTypeString,
|
||||
GoTypeGTime: TsTypeString,
|
||||
GoTypeJson: TsTypeAny,
|
||||
}
|
||||
|
||||
// 表单组件
|
||||
const (
|
||||
FormModeInput = "Input" // 文本输入
|
||||
FormModeInputNumber = "InputNumber" // 数字输入
|
||||
FormModeInputTextarea = "InputTextarea" // 文本域
|
||||
FormModeInputEditor = "InputEditor" // 富文本
|
||||
FormModeInputYaml = "InputYaml" // YAML配置
|
||||
FormModeInputDynamic = "InputDynamic" // 动态键值对
|
||||
FormModeDate = "Date" // 日期选择(Y-M-D)
|
||||
FormModeDateRange = "DateRange" // 日期范围选择
|
||||
FormModeTime = "Time" // 时间选择(Y-M-D H:i:s)
|
||||
FormModeTimeRange = "TimeRange" // 时间范围选择
|
||||
FormModeRadio = "Radio" // 单选按钮
|
||||
FormModeCheckbox = "Checkbox" // 复选按钮
|
||||
FormModeSelect = "Select" // 单选下拉框
|
||||
FormModeSelectMultiple = "SelectMultiple" // 多选下拉框
|
||||
FormModeTreeSelect = "TreeSelect" // 树型选择
|
||||
FormModeCascader = "Cascader" // 级联选择
|
||||
FormModeUploadImage = "UploadImage" // 单图上传
|
||||
FormModeUploadImages = "UploadImages" // 多图上传
|
||||
FormModeUploadFile = "UploadFile" // 单文件上传
|
||||
FormModeUploadFiles = "UploadFiles" // 多文件上传
|
||||
FormModeSwitch = "Switch" // 开关
|
||||
FormModeRate = "Rate" // 评分
|
||||
FormModeCitySelector = "CitySelector" // 省市区选择
|
||||
FormModePidTreeSelect = "PidTreeSelect" // 树型上级选择,树表生成专用
|
||||
)
|
||||
|
||||
var FormModes = []string{
|
||||
FormModeInput, FormModeInputNumber, FormModeInputTextarea, FormModeInputEditor, FormModeInputYaml, FormModeInputDynamic,
|
||||
FormModeDate, FormModeDateRange, FormModeTime, FormModeTimeRange,
|
||||
FormModeRadio, FormModeCheckbox, FormModeSelect, FormModeSelectMultiple, FormModeTreeSelect, FormModeCascader,
|
||||
FormModeUploadImage, FormModeUploadImages, FormModeUploadFile, FormModeUploadFiles,
|
||||
FormModeSwitch,
|
||||
FormModeRate,
|
||||
FormModeCitySelector,
|
||||
}
|
||||
|
||||
var FormModeMap = map[string]string{
|
||||
FormModeInput: "文本输入",
|
||||
FormModeInputNumber: "数字输入",
|
||||
FormModeInputTextarea: "文本域",
|
||||
FormModeInputEditor: "富文本",
|
||||
FormModeInputYaml: "YAML配置",
|
||||
FormModeInputDynamic: "动态键值对",
|
||||
FormModeDate: "日期选择(Y-M-D)",
|
||||
FormModeDateRange: "日期范围选择",
|
||||
FormModeTime: "时间选择(Y-M-D H:i:s)",
|
||||
FormModeTimeRange: "时间范围选择",
|
||||
FormModeRadio: "单选按钮",
|
||||
FormModeCheckbox: "复选按钮",
|
||||
FormModeSelect: "单选下拉框",
|
||||
FormModeSelectMultiple: "多选下拉框",
|
||||
FormModeTreeSelect: "树型选择",
|
||||
FormModeCascader: "级联选择",
|
||||
FormModeUploadImage: "单图上传",
|
||||
FormModeUploadImages: "多图上传",
|
||||
FormModeUploadFile: "单文件上传",
|
||||
FormModeUploadFiles: "多文件上传",
|
||||
FormModeSwitch: "开关",
|
||||
FormModeRate: "评分",
|
||||
FormModeCitySelector: "省市区选择",
|
||||
}
|
||||
|
||||
// 表单验证
|
||||
const (
|
||||
FormRoleNone = "none"
|
||||
FormRoleIp = "ip"
|
||||
FormRolePercentage = "percentage"
|
||||
FormRoleTel = "tel"
|
||||
FormRolePhone = "phone"
|
||||
FormRoleQq = "qq"
|
||||
FormRoleEmail = "email"
|
||||
FormRoleIdCard = "idCard"
|
||||
FormRoleNum = "num"
|
||||
FormRoleBankCard = "bankCard"
|
||||
FormRoleWeibo = "weibo"
|
||||
FormRoleUserName = "userName"
|
||||
FormRoleAccount = "account"
|
||||
FormRolePassword = "password"
|
||||
FormRoleAmount = "amount"
|
||||
FormRoleYaml = "yaml"
|
||||
)
|
||||
|
||||
var FormRoleMap = map[string]string{
|
||||
FormRoleNone: "不验证",
|
||||
FormRoleIp: "Ipv4或Ipv6",
|
||||
FormRolePercentage: "0-100百分比",
|
||||
FormRoleTel: "固话格式",
|
||||
FormRolePhone: "手机号",
|
||||
FormRoleQq: "QQ号码",
|
||||
FormRoleEmail: "邮箱",
|
||||
FormRoleIdCard: "身份证",
|
||||
FormRoleNum: "非零正整数",
|
||||
FormRoleBankCard: "银行卡",
|
||||
FormRoleWeibo: "微博号",
|
||||
FormRoleUserName: "用户名",
|
||||
FormRoleAccount: "账号",
|
||||
FormRolePassword: "密码",
|
||||
FormRoleAmount: "金额",
|
||||
FormRoleYaml: "YAML格式",
|
||||
}
|
||||
|
||||
// 查询条件
|
||||
const (
|
||||
WhereModeEq = "=" // =
|
||||
WhereModeNeq = "!=" // !=
|
||||
WhereModeGt = ">" // >
|
||||
WhereModeGte = ">=" // >=
|
||||
WhereModeLt = "<" // <
|
||||
WhereModeLte = "<=" // <=
|
||||
WhereModeIn = "IN" // IN (...)
|
||||
WhereModeNotIn = "NOT IN" // NOT IN (...)
|
||||
WhereModeBetween = "BETWEEN" // BETWEEN
|
||||
WhereModeNotBetween = "NOT BETWEEN" // NOT BETWEEN
|
||||
WhereModeLike = "LIKE" // LIKE
|
||||
WhereModeLikeAll = "LIKE %...%" // LIKE %...%
|
||||
WhereModeNotLike = "NOT LIKE" // NOT LIKE
|
||||
WhereModeJsonContains = "JSON_CONTAINS(doc, val)" // JSON_CONTAINS(json_doc, val[, path]) // 判断是否包含某个json值
|
||||
)
|
||||
|
||||
var WhereModes = []string{WhereModeEq,
|
||||
WhereModeNeq, WhereModeGt, WhereModeGte, WhereModeLt, WhereModeLte,
|
||||
WhereModeIn, WhereModeNotIn,
|
||||
WhereModeBetween, WhereModeNotBetween,
|
||||
WhereModeLike, WhereModeLikeAll, WhereModeNotLike,
|
||||
WhereModeJsonContains,
|
||||
}
|
||||
|
||||
// 表格列的排序方式
|
||||
const (
|
||||
TableAlignLeft = "left"
|
||||
TableAlignRight = "right"
|
||||
TableAlignCenter = "center"
|
||||
)
|
||||
|
||||
var TableAligns = []string{TableAlignLeft, TableAlignRight, TableAlignCenter}
|
||||
|
||||
var TableAlignMap = map[string]string{
|
||||
TableAlignLeft: "居左",
|
||||
TableAlignRight: "居右",
|
||||
TableAlignCenter: "居中",
|
||||
}
|
||||
|
||||
// IsNumberType 是否是数字类型
|
||||
func IsNumberType(goType string) bool {
|
||||
switch goType {
|
||||
case GoTypeInt, GoTypeUint, GoTypeInt64, GoTypeUint64:
|
||||
return true
|
||||
case GoTypeFloat32, GoTypeFloat64:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// IsSelectFormMode 是否是选择器组件
|
||||
func IsSelectFormMode(formMode string) bool {
|
||||
switch formMode {
|
||||
case FormModeRadio, FormModeCheckbox, FormModeSelect, FormModeSelectMultiple, FormModeCitySelector, FormModeTreeSelect, FormModeCascader:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func HasColumn(fields []*sysin.GenCodesColumnListModel, column string) bool {
|
||||
for _, field := range fields {
|
||||
if field.Name == column {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func HasColumnWithFormMode(fields []*sysin.GenCodesColumnListModel, formMode string) bool {
|
||||
for _, field := range fields {
|
||||
if field.FormMode == formMode {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func HasMaxSort(fields []*sysin.GenCodesColumnListModel) bool {
|
||||
return HasColumn(fields, "sort")
|
||||
}
|
||||
|
||||
func HasStatus(headOps []string, fields []*sysin.GenCodesColumnListModel) bool {
|
||||
if !gstr.InArray(headOps, "status") {
|
||||
return false
|
||||
}
|
||||
return HasColumn(fields, "status")
|
||||
}
|
||||
|
||||
func HasSwitch(fields []*sysin.GenCodesColumnListModel) bool {
|
||||
return HasColumnWithFormMode(fields, FormModeSwitch)
|
||||
}
|
||||
|
||||
func HasHookMemberSummary(fields []*sysin.GenCodesColumnListModel) bool {
|
||||
for _, field := range fields {
|
||||
if IsMemberSummaryField(field.Name) {
|
||||
if field.IsList {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func HasQueryMemberSummary(fields []*sysin.GenCodesColumnListModel) bool {
|
||||
for _, field := range fields {
|
||||
if IsMemberSummaryField(field.Name) {
|
||||
if field.IsQuery {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func IsMemberSummaryField(name string) bool {
|
||||
switch name {
|
||||
case "created_by", "updated_by", "deleted_by":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// ReviseFields 校正字段值,兼容版本升级前的老数据格式
|
||||
func ReviseFields(fields []*sysin.GenCodesColumnListModel) []*sysin.GenCodesColumnListModel {
|
||||
for _, field := range fields {
|
||||
if !validate.InSlice(TableAligns, field.Align) {
|
||||
field.Align = TableAlignLeft
|
||||
}
|
||||
|
||||
if field.Width < 1 {
|
||||
field.Width = -1
|
||||
}
|
||||
if field.Width > 2000 {
|
||||
field.Width = 2000
|
||||
}
|
||||
|
||||
if field.FormGridSpan < 1 {
|
||||
field.FormGridSpan = 1
|
||||
}
|
||||
}
|
||||
return fields
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,354 @@
|
||||
// Package views
|
||||
// @Link https://github.com/bufanyun/hotgo
|
||||
// @Copyright Copyright (c) 2023 HotGo CLI
|
||||
// @Author Ms <133814250@qq.com>
|
||||
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
|
||||
package views
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/olekukonko/tablewriter/renderer"
|
||||
"github.com/olekukonko/tablewriter/tw"
|
||||
"strings"
|
||||
|
||||
"hotgo/internal/dao"
|
||||
"hotgo/internal/model/input/sysin"
|
||||
|
||||
"github.com/gogf/gf/v2/database/gdb"
|
||||
"github.com/gogf/gf/v2/errors/gerror"
|
||||
"github.com/gogf/gf/v2/frame/g"
|
||||
"github.com/gogf/gf/v2/text/gstr"
|
||||
"github.com/olekukonko/tablewriter"
|
||||
)
|
||||
|
||||
const (
|
||||
InputTypeListInp = 1 // 列表输入
|
||||
InputTypeListModel = 2 // 列表输出
|
||||
InputTypeExportModel = 3 // 列表导出
|
||||
InputTypeEditInpValidator = 4 // 添加&编辑验证器
|
||||
InputTypeUpdateFields = 5 // 编辑修改过滤字段
|
||||
InputTypeInsertFields = 6 // 编辑新增过滤字段
|
||||
InputTypeTreeOptionFields = 7 // 关系树查询字段
|
||||
EditInpValidatorGenerally = "if err := g.Validator().Rules(\"%s\").Data(in.%s).Messages(\"%s\").Run(ctx); err != nil {\n\t\treturn err.Current()\n\t}\n"
|
||||
EditInpValidatorYaml = "if err := validate.ValidateYAML(in.%s); err != nil {\n\t\treturn gerror.Newf(\"%s必须为有效的YAML格式: %%s\", err.Error())\n\t}\n"
|
||||
)
|
||||
|
||||
var (
|
||||
// tablewriter Options
|
||||
twRenderer = tablewriter.WithRenderer(renderer.NewBlueprint(tw.Rendition{
|
||||
Borders: tw.Border{Top: tw.Off, Bottom: tw.Off, Left: tw.Off, Right: tw.Off},
|
||||
Settings: tw.Settings{
|
||||
Separators: tw.Separators{BetweenRows: tw.Off, BetweenColumns: tw.Off},
|
||||
},
|
||||
Symbols: tw.NewSymbols(tw.StyleASCII),
|
||||
}))
|
||||
twConfig = tablewriter.WithConfig(tablewriter.Config{
|
||||
Row: tw.CellConfig{
|
||||
Formatting: tw.CellFormatting{AutoWrap: tw.WrapNone},
|
||||
},
|
||||
})
|
||||
)
|
||||
|
||||
func (l *gCurd) inputTplData(ctx context.Context, in *CurdPreviewInput) (data g.Map, err error) {
|
||||
data = make(g.Map)
|
||||
data["listInpColumns"] = l.generateInputListColumns(ctx, in, InputTypeListInp)
|
||||
data["listModelColumns"] = l.generateInputListColumns(ctx, in, InputTypeListModel)
|
||||
data["exportModelColumns"] = l.generateInputListColumns(ctx, in, InputTypeExportModel)
|
||||
data["editInpValidator"] = l.generateInputListColumns(ctx, in, InputTypeEditInpValidator)
|
||||
data["updateFieldsColumns"] = l.generateInputListColumns(ctx, in, InputTypeUpdateFields)
|
||||
data["insertFieldsColumns"] = l.generateInputListColumns(ctx, in, InputTypeInsertFields)
|
||||
data["viewModelColumns"] = l.generateInputViewColumns(ctx, in)
|
||||
if in.options.Step.IsTreeTable {
|
||||
data["treeOptionFields"] = l.generateInputListColumns(ctx, in, InputTypeTreeOptionFields)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (l *gCurd) generateInputViewColumns(ctx context.Context, in *CurdPreviewInput) string {
|
||||
buffer := bytes.NewBuffer(nil)
|
||||
|
||||
index := 0
|
||||
array := make([][]string, 1000)
|
||||
// 主表
|
||||
for _, field := range in.masterFields {
|
||||
// 查询用户摘要
|
||||
if field.IsList && in.options.Step.HasHookMemberSummary && IsMemberSummaryField(field.Name) {
|
||||
tagKey := "`"
|
||||
descriptionTag := gstr.Replace(formatComment(field.Dc)+"摘要信息", `"`, `\"`)
|
||||
result := []string{" #" + field.GoName + "Summa"}
|
||||
result = append(result, " #*hook.MemberSumma")
|
||||
result = append(result, " #"+fmt.Sprintf(tagKey+`json:"%s"`, field.TsName+"Summa"))
|
||||
result = append(result, " #"+fmt.Sprintf(`dc:"%s"`+tagKey, descriptionTag))
|
||||
array[index] = result
|
||||
index++
|
||||
}
|
||||
}
|
||||
|
||||
table := tablewriter.NewTable(buffer, twRenderer, twConfig)
|
||||
table.Bulk(array)
|
||||
table.Render()
|
||||
stContent := buffer.String()
|
||||
// Let's do this hack of table writer for indent!
|
||||
stContent = gstr.Replace(stContent, " #", "")
|
||||
stContent = gstr.Replace(stContent, "` ", "`")
|
||||
stContent = gstr.Replace(stContent, "``", "")
|
||||
stContent = removeEndWrap(stContent)
|
||||
|
||||
buffer.Reset()
|
||||
buffer.WriteString(stContent)
|
||||
return "\tentity." + in.In.DaoName + "\n" + buffer.String()
|
||||
}
|
||||
|
||||
func (l *gCurd) generateInputListColumns(ctx context.Context, in *CurdPreviewInput, inputType int) string {
|
||||
buffer := bytes.NewBuffer(nil)
|
||||
index := 0
|
||||
array := make([][]string, 1000)
|
||||
// 主表
|
||||
for _, field := range in.masterFields {
|
||||
row := l.generateStructFieldDefinition(in, field, inputType, true)
|
||||
if row == nil {
|
||||
continue
|
||||
}
|
||||
array[index] = row
|
||||
index++
|
||||
|
||||
switch inputType {
|
||||
case InputTypeListModel:
|
||||
// 查询用户摘要
|
||||
if field.IsList && in.options.Step.HasHookMemberSummary && IsMemberSummaryField(field.Name) {
|
||||
tagKey := "`"
|
||||
descriptionTag := gstr.Replace(formatComment(field.Dc)+"摘要信息", `"`, `\"`)
|
||||
result := []string{" #" + field.GoName + "Summa"}
|
||||
result = append(result, " #*hook.MemberSumma")
|
||||
result = append(result, " #"+fmt.Sprintf(tagKey+`json:"%s"`, field.TsName+"Summa"))
|
||||
result = append(result, " #"+fmt.Sprintf(`dc:"%s"`+tagKey, descriptionTag))
|
||||
array[index] = result
|
||||
index++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 关联表
|
||||
if len(in.options.Join) > 0 {
|
||||
for _, v := range in.options.Join {
|
||||
if !isEffectiveJoin(v) {
|
||||
continue
|
||||
}
|
||||
for _, field := range v.Columns {
|
||||
row := l.generateStructFieldDefinition(in, field, inputType, false)
|
||||
if row != nil {
|
||||
array[index] = row
|
||||
index++
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
table := tablewriter.NewTable(buffer, twRenderer, twConfig)
|
||||
table.Bulk(array)
|
||||
table.Render()
|
||||
stContent := buffer.String()
|
||||
// Let's do this hack of table writer for indent!
|
||||
stContent = gstr.Replace(stContent, " #", "")
|
||||
stContent = gstr.Replace(stContent, "` ", "`")
|
||||
stContent = gstr.Replace(stContent, "``", "")
|
||||
stContent = removeEndWrap(stContent)
|
||||
|
||||
buffer.Reset()
|
||||
buffer.WriteString(stContent)
|
||||
return buffer.String()
|
||||
}
|
||||
|
||||
// generateStructFieldForModel generates and returns the attribute definition for specified field.
|
||||
func (l *gCurd) generateStructFieldDefinition(in *CurdPreviewInput, field *sysin.GenCodesColumnListModel, inputType int, isMaster bool) []string {
|
||||
var (
|
||||
tagKey = "`"
|
||||
result = []string{" #" + field.GoName}
|
||||
descriptionTag = gstr.Replace(formatComment(field.Dc), `"`, `\"`)
|
||||
)
|
||||
|
||||
addResult := func() []string {
|
||||
result = append(result, " #"+field.GoType)
|
||||
result = append(result, " #"+fmt.Sprintf(tagKey+`json:"%s"`, field.TsName))
|
||||
result = append(result, " #"+fmt.Sprintf(`dc:"%s"`+tagKey, descriptionTag))
|
||||
return result
|
||||
}
|
||||
|
||||
isUpdateOrInsertInputFields := func() bool {
|
||||
if !isMaster {
|
||||
return field.IsEdit
|
||||
}
|
||||
|
||||
if field.IsEdit {
|
||||
return true
|
||||
}
|
||||
|
||||
// 树表内部维护字段
|
||||
if in.options.Step.IsTreeTable && gstr.InArray(defaultTreeFields, field.Name) {
|
||||
return true
|
||||
}
|
||||
|
||||
// 修改人
|
||||
if inputType == InputTypeUpdateFields && field.GoName == "UpdatedBy" {
|
||||
return true
|
||||
}
|
||||
|
||||
// 创建人
|
||||
if inputType == InputTypeInsertFields && field.GoName == "CreatedBy" {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
isQuery := false
|
||||
|
||||
switch inputType {
|
||||
case InputTypeListInp:
|
||||
if in.options.Step.IsTreeTable && IsPidName(field.Name) {
|
||||
isQuery = true
|
||||
field.QueryWhere = WhereModeEq
|
||||
}
|
||||
if !field.IsQuery && !isQuery {
|
||||
return nil
|
||||
}
|
||||
|
||||
if field.QueryWhere == WhereModeBetween {
|
||||
result = append(result, " #[]"+field.GoType)
|
||||
} else {
|
||||
// 查询用户摘要时,固定接收字符串类型
|
||||
if field.IsQuery && in.options.Step.HasQueryMemberSummary && IsMemberSummaryField(field.Name) {
|
||||
result = append(result, " #string")
|
||||
} else {
|
||||
result = append(result, " #"+field.GoType)
|
||||
}
|
||||
}
|
||||
result = append(result, " #"+fmt.Sprintf(tagKey+`json:"%s"`, field.TsName))
|
||||
result = append(result, " #"+fmt.Sprintf(`dc:"%s"`+tagKey, descriptionTag))
|
||||
|
||||
case InputTypeListModel:
|
||||
// 主表的主键
|
||||
if IsIndexPK(field.Index) && isMaster {
|
||||
addResult()
|
||||
// 树表的pid字段
|
||||
} else if in.options.Step.IsTreeTable && IsPidName(field.Name) {
|
||||
addResult()
|
||||
} else if field.IsList {
|
||||
addResult()
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
case InputTypeExportModel:
|
||||
if !field.IsExport {
|
||||
return nil
|
||||
}
|
||||
addResult()
|
||||
case InputTypeEditInpValidator:
|
||||
if !field.IsEdit {
|
||||
return nil
|
||||
}
|
||||
if !field.Required && (field.FormRole == "none" || field.FormRole == "") {
|
||||
return nil
|
||||
}
|
||||
rule := "// 验证" + field.Dc + "\n"
|
||||
if field.Required && (field.FormRole == FormRoleNone || field.FormRole == "") {
|
||||
field.FormRole = "required"
|
||||
}
|
||||
if err, s := makeValidatorFunc(field); err != nil {
|
||||
return nil
|
||||
} else {
|
||||
rule += s
|
||||
}
|
||||
result = []string{rule}
|
||||
case InputTypeUpdateFields:
|
||||
if !isUpdateOrInsertInputFields() {
|
||||
return nil
|
||||
}
|
||||
addResult()
|
||||
case InputTypeInsertFields:
|
||||
if !isUpdateOrInsertInputFields() {
|
||||
return nil
|
||||
}
|
||||
addResult()
|
||||
case InputTypeTreeOptionFields:
|
||||
if IsIndexPK(field.Index) {
|
||||
return addResult()
|
||||
}
|
||||
if IsPidName(field.Name) {
|
||||
return addResult()
|
||||
}
|
||||
if in.options.Tree.TitleColumn == field.Name {
|
||||
return addResult()
|
||||
}
|
||||
return nil
|
||||
default:
|
||||
panic("inputType is invalid")
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func makeValidatorFunc(field *sysin.GenCodesColumnListModel) (err error, rule string) {
|
||||
if field.FormRole == "required" {
|
||||
rule = fmt.Sprintf(EditInpValidatorGenerally, "required", field.GoName, field.Dc+"不能为空")
|
||||
} else if field.FormRole == FormRoleIp {
|
||||
rule = fmt.Sprintf(EditInpValidatorGenerally, "ip", field.GoName, field.Dc+"必须为IPV4或IPV6")
|
||||
} else if field.FormRole == FormRolePercentage {
|
||||
rule = fmt.Sprintf(EditInpValidatorGenerally, "min:0|max:100", field.GoName, field.Dc+"必须0-100之间")
|
||||
} else if field.FormRole == FormRoleTel {
|
||||
rule = fmt.Sprintf(EditInpValidatorGenerally, "telephone", field.GoName, field.Dc+"不是座机号码")
|
||||
} else if field.FormRole == FormRolePhone {
|
||||
rule = fmt.Sprintf(EditInpValidatorGenerally, "phone", field.GoName, field.Dc+"不是手机号码")
|
||||
} else if field.FormRole == FormRoleQq {
|
||||
rule = fmt.Sprintf(EditInpValidatorGenerally, "qq", field.GoName, field.Dc+"不是QQ号码")
|
||||
} else if field.FormRole == FormRoleEmail {
|
||||
rule = fmt.Sprintf(EditInpValidatorGenerally, "email", field.GoName, field.Dc+"不是邮箱地址")
|
||||
} else if field.FormRole == FormRoleIdCard {
|
||||
rule = fmt.Sprintf(EditInpValidatorGenerally, "resident-id", field.GoName, field.Dc+"不是身份证号码")
|
||||
} else if field.FormRole == FormRoleNum {
|
||||
rule = fmt.Sprintf(EditInpValidatorGenerally, "min:1", field.GoName, field.Dc+"必须大于0")
|
||||
} else if field.FormRole == FormRoleBankCard {
|
||||
rule = fmt.Sprintf(EditInpValidatorGenerally, "bank-card", field.GoName, field.Dc+"不是银行卡号")
|
||||
} else if field.FormRole == FormRoleWeibo {
|
||||
rule = fmt.Sprintf(EditInpValidatorGenerally, "regex:^[0-9a-zA-Z\\u4e00-\\u9fa5_-]*$", field.GoName, field.Dc+"不是微博号")
|
||||
} else if field.FormRole == FormRoleUserName {
|
||||
rule = fmt.Sprintf(EditInpValidatorGenerally, "regex:^[0-9a-zA-Z]{6,16}$", field.GoName, field.Dc+"必须为6-16位由字母和数字组成")
|
||||
} else if field.FormRole == FormRoleAccount {
|
||||
rule = fmt.Sprintf(EditInpValidatorGenerally, "regex:^[\\w_\\d]{6,16}$", field.GoName, field.Dc+"必须为6-16位由字母、数字或下划线组成")
|
||||
} else if field.FormRole == FormRolePassword {
|
||||
rule = fmt.Sprintf(EditInpValidatorGenerally, "regex:^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,18}$", field.GoName, field.Dc+"必须包含6-18为字母和数字")
|
||||
} else if field.FormRole == FormRoleAmount {
|
||||
rule = fmt.Sprintf(EditInpValidatorGenerally, "regex:(^[0-9]{1,10}$)|(^[0-9]{1,10}[\\\\.]{1}[0-9]{1,2}$)", field.GoName, field.Dc+"最多允许输入10位整数及2位小数")
|
||||
} else if field.FormRole == FormRoleYaml {
|
||||
rule = fmt.Sprintf(EditInpValidatorYaml, field.GoName, field.Dc)
|
||||
} else {
|
||||
err = gerror.New("not support")
|
||||
}
|
||||
|
||||
// 生成验证字典
|
||||
if field.DictType > 0 {
|
||||
var (
|
||||
ctx = context.Background()
|
||||
valueType gdb.Value
|
||||
resultValue gdb.Result
|
||||
)
|
||||
valueType, err = dao.SysDictType.Ctx(ctx).Fields(dao.SysDictType.Columns().Type).Where(dao.SysDictType.Columns().Id, field.DictType).Value()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
resultValue, err = dao.SysDictData.Ctx(context.Background()).Fields(dao.SysDictData.Columns().Value).Where(dao.SysDictData.Columns().Type, valueType.String()).All()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if resultValue.Len() > 0 {
|
||||
names := make([]string, 0)
|
||||
for _, item := range resultValue {
|
||||
names = append(names, item["value"].String())
|
||||
}
|
||||
dictRule := "in:" + strings.Join(names, ",")
|
||||
rule += fmt.Sprintf(EditInpValidatorGenerally, dictRule, field.GoName, field.Dc+"值不正确")
|
||||
err = nil
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,318 @@
|
||||
// Package views
|
||||
// @Link https://github.com/bufanyun/hotgo
|
||||
// @Copyright Copyright (c) 2023 HotGo CLI
|
||||
// @Author Ms <133814250@qq.com>
|
||||
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
|
||||
package views
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/gogf/gf/v2/frame/g"
|
||||
"github.com/gogf/gf/v2/text/gstr"
|
||||
"hotgo/internal/consts"
|
||||
"hotgo/internal/model/input/sysin"
|
||||
)
|
||||
|
||||
const (
|
||||
LogicWhereComments = "\n\t// 查询%s\n"
|
||||
LogicWhereNoSupport = "\t// TODO 暂不支持生成[ %s ]查询方式,请自行补充此处代码!"
|
||||
LogicEditUpdate = "\tif _, err = s.Model(ctx%s).\n\t\t\tFields(%sin.%sUpdateFields{}).\n\t\t\tWherePri(in.%s).Data(in).Update(); err != nil {\n\t\t\terr = gerror.Wrap(err, \"修改%s失败,请稍后重试!\")\n\t\t}\n\t\treturn"
|
||||
LogicEditInsert = "\tif _, err = s.Model(ctx, &handler.Option{FilterAuth: false}).\n\t\tFields(%sin.%sInsertFields{}).\n\t\tData(in).OmitEmptyData().Insert(); err != nil {\n\t\terr = gerror.Wrap(err, \"新增%s失败,请稍后重试!\")\n\t}"
|
||||
LogicEditUnique = "\t// 验证'%s'唯一\n\tif err = hgorm.IsUnique(ctx, &dao.%s, g.Map{dao.%s.Columns().%s: in.%s}, \"%s已存在\", in.%s); err != nil {\n\t\treturn\n\t}\n"
|
||||
LogicSwitchUpdate = "g.Map{\n\t\tin.Key: in.Value,\n%s}"
|
||||
LogicStatusUpdate = "g.Map{\n\t\tdao.%s.Columns().Status: in.Status,\n%s}"
|
||||
LogicDeletedUpdate = "g.Map{\n%s}"
|
||||
)
|
||||
|
||||
func (l *gCurd) logicTplData(ctx context.Context, in *CurdPreviewInput) (data g.Map, err error) {
|
||||
data = make(g.Map)
|
||||
data["listWhere"] = l.generateLogicListWhere(ctx, in)
|
||||
data["listJoin"] = l.generateLogicListJoin(ctx, in)
|
||||
data["listFields"] = l.generateLogicListFields(ctx, in)
|
||||
data["listOrder"] = l.generateLogicListOrder(ctx, in)
|
||||
data["edit"] = l.generateLogicEdit(ctx, in)
|
||||
data["switchFields"] = l.generateLogicSwitchFields(ctx, in)
|
||||
data["switchUpdate"] = l.generateLogicSwitchUpdate(ctx, in)
|
||||
data["statusUpdate"] = l.generateLogicStatusUpdate(ctx, in)
|
||||
data["deletedUpdate"] = l.generateLogicDeletedUpdate(ctx, in)
|
||||
return
|
||||
}
|
||||
|
||||
func (l *gCurd) generateLogicDeletedUpdate(ctx context.Context, in *CurdPreviewInput) string {
|
||||
isDestroy := false
|
||||
var update string
|
||||
for _, field := range in.masterFields {
|
||||
if field.GoName == "DeletedBy" {
|
||||
update += "\t\tdao." + in.In.DaoName + ".Columns().DeletedBy: contexts.GetUserId(ctx),\n"
|
||||
isDestroy = true
|
||||
}
|
||||
if field.GoName == "DeletedAt" {
|
||||
update += "\t\tdao." + in.In.DaoName + ".Columns().DeletedAt: gtime.Now(),\n"
|
||||
}
|
||||
}
|
||||
|
||||
if !isDestroy {
|
||||
return ""
|
||||
}
|
||||
|
||||
update += "\t"
|
||||
return fmt.Sprintf(LogicDeletedUpdate, update)
|
||||
}
|
||||
|
||||
func (l *gCurd) generateLogicStatusUpdate(ctx context.Context, in *CurdPreviewInput) string {
|
||||
var update string
|
||||
for _, field := range in.masterFields {
|
||||
if field.GoName == "UpdatedBy" {
|
||||
update += "\t\tdao." + in.In.DaoName + ".Columns().UpdatedBy: contexts.GetUserId(ctx),\n"
|
||||
}
|
||||
}
|
||||
|
||||
update += "\t"
|
||||
return fmt.Sprintf(LogicStatusUpdate, in.In.DaoName, update)
|
||||
}
|
||||
|
||||
func (l *gCurd) generateLogicSwitchUpdate(ctx context.Context, in *CurdPreviewInput) string {
|
||||
var update string
|
||||
for _, field := range in.masterFields {
|
||||
if field.GoName == "UpdatedBy" {
|
||||
update += "\t\tdao." + in.In.DaoName + ".Columns().UpdatedBy: contexts.GetUserId(ctx),\n"
|
||||
}
|
||||
}
|
||||
|
||||
update += "\t"
|
||||
return fmt.Sprintf(LogicSwitchUpdate, update)
|
||||
}
|
||||
|
||||
func (l *gCurd) generateLogicSwitchFields(ctx context.Context, in *CurdPreviewInput) string {
|
||||
buffer := bytes.NewBuffer(nil)
|
||||
if in.options.Step.HasSwitch {
|
||||
for _, field := range in.masterFields {
|
||||
if field.FormMode == "Switch" {
|
||||
buffer.WriteString("\t\tdao." + in.In.DaoName + ".Columns()." + field.GoName + ",\n")
|
||||
}
|
||||
}
|
||||
}
|
||||
return buffer.String()
|
||||
}
|
||||
|
||||
func (l *gCurd) generateLogicEdit(ctx context.Context, in *CurdPreviewInput) g.Map {
|
||||
var (
|
||||
data = make(g.Map)
|
||||
updateBuffer = bytes.NewBuffer(nil)
|
||||
insertBuffer = bytes.NewBuffer(nil)
|
||||
uniqueBuffer = bytes.NewBuffer(nil)
|
||||
validationBuffer = bytes.NewBuffer(nil)
|
||||
)
|
||||
|
||||
for _, field := range in.masterFields {
|
||||
if field.GoName == "UpdatedBy" {
|
||||
updateBuffer.WriteString("\t\tin.UpdatedBy = contexts.GetUserId(ctx)\n")
|
||||
}
|
||||
|
||||
if field.GoName == "CreatedBy" {
|
||||
insertBuffer.WriteString("\tin.CreatedBy = contexts.GetUserId(ctx)\n")
|
||||
}
|
||||
|
||||
if field.Unique {
|
||||
uniqueBuffer.WriteString(fmt.Sprintf(LogicEditUnique, field.GoName, in.In.DaoName, in.In.DaoName, field.GoName, field.GoName, field.Dc, in.pk.GoName))
|
||||
}
|
||||
|
||||
// 添加 YAML 格式验证
|
||||
if field.IsEdit && field.FormRole == FormRoleYaml {
|
||||
validationBuffer.WriteString(fmt.Sprintf(EditInpValidatorYaml, field.GoName, field.Dc))
|
||||
}
|
||||
}
|
||||
|
||||
notFilterAuth := ""
|
||||
if gstr.InArray(in.options.ColumnOps, "notFilterAuth") {
|
||||
notFilterAuth = ", &handler.Option{FilterAuth: false}"
|
||||
}
|
||||
|
||||
updateBuffer.WriteString(fmt.Sprintf(LogicEditUpdate, notFilterAuth, in.options.TemplateGroup, in.In.VarName, in.pk.GoName, in.In.TableComment))
|
||||
insertBuffer.WriteString(fmt.Sprintf(LogicEditInsert, in.options.TemplateGroup, in.In.VarName, in.In.TableComment))
|
||||
|
||||
data["update"] = updateBuffer.String()
|
||||
data["insert"] = insertBuffer.String()
|
||||
data["unique"] = uniqueBuffer.String()
|
||||
data["validation"] = validationBuffer.String()
|
||||
return data
|
||||
}
|
||||
|
||||
func (l *gCurd) generateLogicListOrder(ctx context.Context, in *CurdPreviewInput) string {
|
||||
statement := ""
|
||||
if hasEffectiveJoins(in.options.Join) {
|
||||
statement = "dao." + in.In.DaoName + ".Table() + \".\" +"
|
||||
}
|
||||
buffer := bytes.NewBuffer(nil)
|
||||
if in.options.Step.HasMaxSort {
|
||||
buffer.WriteString("OrderAsc(" + statement + "dao." + in.In.DaoName + ".Columns().Sort).")
|
||||
}
|
||||
buffer.WriteString("OrderDesc(" + statement + "dao." + in.In.DaoName + ".Columns()." + in.pk.GoName + ")")
|
||||
return buffer.String()
|
||||
}
|
||||
|
||||
func (l *gCurd) generateLogicListJoin(ctx context.Context, in *CurdPreviewInput) (link string) {
|
||||
connector := `"="`
|
||||
if hasEffectiveJoins(in.options.Join) {
|
||||
linkBuffer := bytes.NewBuffer(nil)
|
||||
for _, join := range in.options.Join {
|
||||
if isEffectiveJoin(join) {
|
||||
linkBuffer.WriteString("\tmod = mod." + consts.GenCodesJoinLinkMap[join.LinkMode] + "OnFields(dao." + join.DaoName + ".Table(), dao." + in.In.DaoName + ".Columns()." + gstr.CaseCamel(join.MasterField) + "," + connector + ", dao." + join.DaoName + ".Columns()." + gstr.CaseCamel(join.Field) + ")\n")
|
||||
}
|
||||
}
|
||||
link = linkBuffer.String()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (l *gCurd) generateLogicListFields(ctx context.Context, in *CurdPreviewInput) (fields string) {
|
||||
selectBuffer := bytes.NewBuffer(nil)
|
||||
if hasEffectiveJoins(in.options.Join) {
|
||||
selectBuffer.WriteString("mod = mod.FieldsPrefix(dao." + in.In.DaoName + ".Table(), " + in.options.TemplateGroup + "in." + in.In.VarName + "ListModel{})\n")
|
||||
for _, join := range in.options.Join {
|
||||
if isEffectiveJoin(join) {
|
||||
selectBuffer.WriteString("mod = mod.Fields(hgorm.JoinFields(ctx, " + in.options.TemplateGroup + "in." + in.In.VarName + "ListModel{}, &dao." + join.DaoName + ", \"" + join.Alias + "\"))\n")
|
||||
}
|
||||
}
|
||||
fields = selectBuffer.String()
|
||||
} else {
|
||||
fields = fmt.Sprintf("mod = mod.Fields(%sin.%sListModel{})", in.options.TemplateGroup, in.In.VarName)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (l *gCurd) generateLogicListWhere(ctx context.Context, in *CurdPreviewInput) string {
|
||||
buffer := bytes.NewBuffer(nil)
|
||||
|
||||
// 主表
|
||||
l.generateLogicListWhereEach(buffer, in, in.masterFields, in.In.DaoName, "")
|
||||
|
||||
// 关联表
|
||||
if hasEffectiveJoins(in.options.Join) {
|
||||
for _, v := range in.options.Join {
|
||||
if isEffectiveJoin(v) {
|
||||
l.generateLogicListWhereEach(buffer, in, v.Columns, v.DaoName, v.Alias)
|
||||
}
|
||||
}
|
||||
}
|
||||
return buffer.String()
|
||||
}
|
||||
|
||||
func (l *gCurd) generateLogicListWhereEach(buffer *bytes.Buffer, in *CurdPreviewInput, fields []*sysin.GenCodesColumnListModel, daoName string, alias string) {
|
||||
isLink := false
|
||||
if alias != "" {
|
||||
alias = `"` + alias + `."+`
|
||||
isLink = true
|
||||
}
|
||||
|
||||
tablePrefix := ""
|
||||
wherePrefix := "Where"
|
||||
if isLink {
|
||||
wherePrefix = "WherePrefix"
|
||||
tablePrefix = "dao." + daoName + ".Table(), "
|
||||
}
|
||||
|
||||
for _, field := range fields {
|
||||
isQuery := false
|
||||
// 树表查询上级
|
||||
if in.options.Step.IsTreeTable && IsPidName(field.Name) {
|
||||
isQuery = true
|
||||
field.QueryWhere = WhereModeEq
|
||||
}
|
||||
|
||||
if (!field.IsQuery && !isQuery) || field.QueryWhere == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
buffer.WriteString(fmt.Sprintf(LogicWhereComments, field.Dc))
|
||||
|
||||
var (
|
||||
linkMode string
|
||||
whereTag string
|
||||
columnName string
|
||||
)
|
||||
|
||||
// 查询用户摘要
|
||||
if field.IsQuery && in.options.Step.HasQueryMemberSummary && IsMemberSummaryField(field.Name) {
|
||||
servicePackName := "service"
|
||||
if in.options.Step.IsAddon {
|
||||
servicePackName = "isc"
|
||||
}
|
||||
buffer.WriteString(fmt.Sprintf("if in.%v != \"\" {\n\t\t\t\tids, err := %v.AdminMember().GetIdsByKeyword(ctx, in.%v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, 0, err\n\t\t\t\t}\n\t\t\t\tmod = mod.WhereIn(dao.%v.Columns().%v, ids)\n\t\t\t}\n", field.GoName, servicePackName, field.GoName, in.In.DaoName, field.GoName))
|
||||
continue
|
||||
}
|
||||
|
||||
if IsNumberType(field.GoType) {
|
||||
linkMode = `in.` + field.GoName + ` > 0`
|
||||
} else if field.GoType == GoTypeBool {
|
||||
linkMode = `true` // bool 类型始终可以查询
|
||||
} else if field.GoType == GoTypeGTime {
|
||||
linkMode = `in.` + field.GoName + ` != nil`
|
||||
} else if field.GoType == GoTypeJson {
|
||||
linkMode = `!in.` + field.GoName + `.IsNil()`
|
||||
} else {
|
||||
linkMode = `in.` + field.GoName + ` != ""`
|
||||
}
|
||||
|
||||
if field.QueryWhere == WhereModeBetween || field.QueryWhere == WhereModeNotBetween {
|
||||
linkMode = `len(in.` + field.GoName + `) == 2`
|
||||
}
|
||||
|
||||
// 如果是关联表重新转换字段
|
||||
columnName = field.GoName
|
||||
if isLink {
|
||||
columnName = gstr.CaseCamel(field.Name)
|
||||
}
|
||||
|
||||
switch field.QueryWhere {
|
||||
case WhereModeEq:
|
||||
whereTag = "\tif " + linkMode + " {\n\t\tmod = mod." + wherePrefix + "(" + tablePrefix + "dao." + daoName + ".Columns()." + columnName + ", in." + field.GoName + ")\n\t}"
|
||||
case WhereModeNeq:
|
||||
whereTag = "\tif " + linkMode + " {\n\t\tmod = mod." + wherePrefix + "Not(" + tablePrefix + "dao." + daoName + ".Columns()." + columnName + ", in." + field.GoName + ")\n\t}"
|
||||
case WhereModeGt:
|
||||
whereTag = "\tif " + linkMode + " {\n\t\tmod = mod." + wherePrefix + "GT(" + tablePrefix + "dao." + daoName + ".Columns()." + columnName + ", in." + field.GoName + ")\n\t}"
|
||||
case WhereModeGte:
|
||||
whereTag = "\tif " + linkMode + " {\n\t\tmod = mod." + wherePrefix + "GTE(" + tablePrefix + "dao." + daoName + ".Columns()." + columnName + ", in." + field.GoName + ")\n\t}"
|
||||
case WhereModeLt:
|
||||
whereTag = "\tif " + linkMode + " {\n\t\tmod = mod." + wherePrefix + "LT(" + tablePrefix + "dao." + daoName + ".Columns()." + columnName + ", in." + field.GoName + ")\n\t}"
|
||||
case WhereModeLte:
|
||||
whereTag = "\tif " + linkMode + " {\n\t\tmod = mod." + wherePrefix + "LTE(" + tablePrefix + "dao." + daoName + ".Columns()." + columnName + ", in." + field.GoName + ")\n\t}"
|
||||
case WhereModeIn:
|
||||
whereTag = "\tif " + linkMode + " {\n\t\tmod = mod." + wherePrefix + "In(" + tablePrefix + "dao." + daoName + ".Columns()." + columnName + ", in." + field.GoName + ")\n\t}"
|
||||
case WhereModeNotIn:
|
||||
whereTag = "\tif " + linkMode + " {\n\t\tmod = mod." + wherePrefix + "NotIn(" + tablePrefix + "dao." + daoName + ".Columns()." + columnName + ", in." + field.GoName + ")\n\t}"
|
||||
case WhereModeBetween:
|
||||
whereTag = "\tif " + linkMode + " {\n\t\tmod = mod." + wherePrefix + "Between(" + tablePrefix + "dao." + daoName + ".Columns()." + columnName + ", in." + field.GoName + "[0], in." + field.GoName + "[1])\n\t}"
|
||||
case WhereModeNotBetween:
|
||||
whereTag = "\tif " + linkMode + " {\n\t\tmod = mod." + wherePrefix + "NotBetween(" + tablePrefix + "dao." + daoName + ".Columns()." + columnName + ", in." + field.GoName + "[0], in." + field.GoName + "[1])\n\t}"
|
||||
case WhereModeLike:
|
||||
fieldValue := "in." + field.GoName
|
||||
if field.GoType != GoTypeString && field.GoType != GoTypeBytes {
|
||||
fieldValue = "gconv.String(in." + field.GoName + ")"
|
||||
}
|
||||
whereTag = "\tif " + linkMode + " {\n\t\tmod = mod." + wherePrefix + "Like(" + tablePrefix + "dao." + daoName + ".Columns()." + columnName + ", " + fieldValue + ")\n\t}"
|
||||
case WhereModeLikeAll:
|
||||
val := `"%"+in.` + field.GoName + `+"%"`
|
||||
if field.GoType != GoTypeString && field.GoType != GoTypeBytes {
|
||||
val = `"%"+gconv.String(in.` + field.GoName + `)+"%"`
|
||||
}
|
||||
whereTag = "\tif " + linkMode + " {\n\t\tmod = mod." + wherePrefix + "Like(" + tablePrefix + "dao." + daoName + ".Columns()." + columnName + ", " + val + ")\n\t}"
|
||||
case WhereModeNotLike:
|
||||
fieldValue := "in." + field.GoName
|
||||
if field.GoType != GoTypeString && field.GoType != GoTypeBytes {
|
||||
fieldValue = "gconv.String(in." + field.GoName + ")"
|
||||
}
|
||||
whereTag = "\tif " + linkMode + " {\n\t\tmod = mod." + wherePrefix + "NotLike(" + tablePrefix + "dao." + daoName + ".Columns()." + columnName + ", " + fieldValue + ")\n\t}"
|
||||
case WhereModeJsonContains:
|
||||
val := tablePrefix + `"JSON_CONTAINS("+dao.` + daoName + `.Columns().` + columnName + `+",?)", in.` + field.GoName
|
||||
whereTag = "\tif " + linkMode + " {\n\t\tmod = mod." + wherePrefix + "(" + val + ")\n\t}"
|
||||
|
||||
default:
|
||||
buffer.WriteString(fmt.Sprintf(LogicWhereNoSupport, field.QueryWhere))
|
||||
}
|
||||
|
||||
buffer.WriteString(whereTag + "\n")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
// Package views
|
||||
// @Link https://github.com/bufanyun/hotgo
|
||||
// @Copyright Copyright (c) 2023 HotGo CLI
|
||||
// @Author Ms <133814250@qq.com>
|
||||
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
|
||||
package views
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/gogf/gf/v2/frame/g"
|
||||
"github.com/gogf/gf/v2/text/gstr"
|
||||
)
|
||||
|
||||
func (l *gCurd) webEditTplData(ctx context.Context, in *CurdPreviewInput) (data g.Map, err error) {
|
||||
data = make(g.Map)
|
||||
data["formItem"] = l.generateWebEditFormItem(ctx, in)
|
||||
data["script"] = l.generateWebEditScript(ctx, in)
|
||||
return
|
||||
}
|
||||
|
||||
func (l *gCurd) generateWebEditFormItem(ctx context.Context, in *CurdPreviewInput) string {
|
||||
buffer := bytes.NewBuffer(nil)
|
||||
for _, field := range in.masterFields {
|
||||
if !field.IsEdit {
|
||||
continue
|
||||
}
|
||||
|
||||
if IsIndexPK(field.Index) {
|
||||
continue
|
||||
}
|
||||
|
||||
var (
|
||||
defaultComponent = fmt.Sprintf(" <n-form-item label=\"%s\" path=\"%s\">\n <n-input\n placeholder=\"请输入%s\"\n v-model:value=\"formValue.%s\"\n />\n </n-form-item>", field.Dc, field.TsName, field.Dc, field.TsName)
|
||||
component string
|
||||
)
|
||||
|
||||
if in.options.Step.IsTreeTable && IsPidName(field.Name) {
|
||||
field.FormMode = FormModePidTreeSelect
|
||||
}
|
||||
|
||||
switch field.FormMode {
|
||||
case FormModeInput:
|
||||
component = defaultComponent
|
||||
|
||||
case FormModeInputNumber:
|
||||
component = fmt.Sprintf(" <n-form-item label=\"%s\" path=\"%s\">\n <n-input-number\n placeholder=\"请输入%s\"\n v-model:value=\"formValue.%s\"\n />\n </n-form-item>", field.Dc, field.TsName, field.Dc, field.TsName)
|
||||
|
||||
case FormModeInputTextarea:
|
||||
component = fmt.Sprintf(" <n-form-item label=\"%s\" path=\"%s\">\n <n-input\n type=\"textarea\"\n placeholder=\"%s\"\n v-model:value=\"formValue.%s\"\n />\n </n-form-item>", field.Dc, field.TsName, field.Dc, field.TsName)
|
||||
|
||||
case FormModeInputEditor:
|
||||
component = fmt.Sprintf(" <n-form-item label=\"%s\" path=\"%s\">\n <Editor style=\"height: 450px\" id=\"%s\" v-model:value=\"formValue.%s\" />\n </n-form-item>", field.Dc, field.TsName, field.TsName, field.TsName)
|
||||
|
||||
case FormModeInputYaml:
|
||||
component = fmt.Sprintf(" <n-form-item label=\"%s\" path=\"%s\">\n <YamlEditor\n ref=\"%sYamlRef\"\n v-model:value=\"formValue.%s\"\n :height=\"400\"\n placeholder=\"请输入%s\"\n validate-on-blur\n show-stats\n prevent-invalid-submit\n @error=\"handleYamlError\"\n @valid=\"handleYamlValid\"\n @validation-change=\"(isValid) => handleYamlValidationChange(isValid, '%s')\"\n />\n </n-form-item>", field.Dc, field.TsName, field.TsName, field.TsName, field.Dc, field.TsName)
|
||||
|
||||
case FormModeInputDynamic:
|
||||
component = fmt.Sprintf(" <n-form-item label=\"%s\" path=\"%s\">\n <n-dynamic-input\n v-model:value=\"formValue.%s\"\n preset=\"pair\"\n key-placeholder=\"键名\"\n value-placeholder=\"键值\"\n />\n </n-form-item>", field.Dc, field.TsName, field.TsName)
|
||||
|
||||
case FormModeDate:
|
||||
component = fmt.Sprintf(" <n-form-item label=\"%s\" path=\"%s\">\n <DatePicker v-model:formValue=\"formValue.%s\" type=\"date\" />\n </n-form-item>", field.Dc, field.TsName, field.TsName)
|
||||
|
||||
// case FormModeDateRange: // 必须要有两个字段,后面优化下
|
||||
|
||||
case FormModeTime:
|
||||
component = fmt.Sprintf(" <n-form-item label=\"%s\" path=\"%s\">\n <DatePicker v-model:formValue=\"formValue.%s\" type=\"datetime\" />\n </n-form-item>", field.Dc, field.TsName, field.TsName)
|
||||
|
||||
// case FormModeTimeRange: // 必须要有两个字段,后面优化下
|
||||
|
||||
case FormModeRadio:
|
||||
component = fmt.Sprintf(" <n-form-item label=\"%s\" path=\"%s\">\n <n-radio-group v-model:value=\"formValue.%s\" name=\"%s\">\n <n-radio-button\n v-for=\"%s in dict.getOptionUnRef('%s')\"\n :key=\"%s.value\"\n :value=\"%s.value\"\n :label=\"%s.label\"\n />\n </n-radio-group>\n </n-form-item>", field.Dc, field.TsName, field.TsName, field.TsName, field.TsName, in.options.dictMap[field.TsName], field.TsName, field.TsName, field.TsName)
|
||||
|
||||
case FormModeCheckbox:
|
||||
component = fmt.Sprintf(" <n-form-item label=\"%s\" path=\"%s\">\n <n-checkbox-group v-model:value=\"formValue.%s\">\n <n-space>\n <n-checkbox\n v-for=\"item in dict.getOptionUnRef('%s')\"\n :key=\"item.value\"\n :value=\"item.value\"\n :label=\"item.label\"\n />\n </n-space>\n </n-checkbox-group>\n </n-form-item>", field.Dc, field.TsName, field.TsName, in.options.dictMap[field.TsName])
|
||||
|
||||
case FormModeSelect:
|
||||
if in.options.dictMap[field.TsName] != nil {
|
||||
component = fmt.Sprintf(" <n-form-item label=\"%s\" path=\"%s\">\n <n-select v-model:value=\"formValue.%s\" :options=\"dict.getOptionUnRef('%s')\" />\n </n-form-item>", field.Dc, field.TsName, field.TsName, in.options.dictMap[field.TsName])
|
||||
} else {
|
||||
component = fmt.Sprintf(" <n-form-item label=\"%s\" path=\"%s\">\n <n-select v-model:value=\"formValue.%s\" options=\"\" />\n </n-form-item>", field.Dc, field.TsName, field.TsName)
|
||||
}
|
||||
|
||||
case FormModeSelectMultiple:
|
||||
component = fmt.Sprintf(" <n-form-item label=\"%s\" path=\"%s\">\n <n-select multiple v-model:value=\"formValue.%s\" :options=\"dict.getOptionUnRef('%s')\" />\n </n-form-item>", field.Dc, field.TsName, field.TsName, in.options.dictMap[field.TsName])
|
||||
|
||||
case FormModeUploadImage:
|
||||
component = fmt.Sprintf(" <n-form-item label=\"%s\" path=\"%s\">\n <UploadImage :maxNumber=\"1\" v-model:value=\"formValue.%s\" />\n </n-form-item>", field.Dc, field.TsName, field.TsName)
|
||||
|
||||
case FormModeUploadImages:
|
||||
component = fmt.Sprintf(" <n-form-item label=\"%s\" path=\"%s\">\n <UploadImage :maxNumber=\"10\" v-model:value=\"formValue.%s\" />\n </n-form-item>", field.Dc, field.TsName, field.TsName)
|
||||
|
||||
case FormModeUploadFile:
|
||||
component = fmt.Sprintf(" <n-form-item label=\"%s\" path=\"%s\">\n <UploadFile :maxNumber=\"1\" v-model:value=\"formValue.%s\" />\n </n-form-item>", field.Dc, field.TsName, field.TsName)
|
||||
|
||||
case FormModeUploadFiles:
|
||||
component = fmt.Sprintf(" <n-form-item label=\"%s\" path=\"%s\">\n <UploadFile :maxNumber=\"10\" v-model:value=\"formValue.%s\" />\n </n-form-item>", field.Dc, field.TsName, field.TsName)
|
||||
|
||||
case FormModeSwitch:
|
||||
component = fmt.Sprintf(" <n-form-item label=\"%s\" path=\"%s\">\n <n-switch\n :unchecked-value=\"2\"\n :checked-value=\"1\"\n v-model:value=\"formValue.%s\"\n />\n </n-form-item>", field.Dc, field.TsName, field.TsName)
|
||||
|
||||
case FormModeRate:
|
||||
component = fmt.Sprintf(" <n-form-item label=\"%s\" path=\"%s\">\n <n-rate allow-half :default-value=\"formValue.%s\" :on-update:value=\"update%s\" />\n </n-form-item>", field.Dc, field.TsName, field.TsName, field.GoName)
|
||||
|
||||
case FormModeCitySelector:
|
||||
component = fmt.Sprintf(" <n-form-item label=\"%s\" path=\"%s\">\n <CitySelector v-model:value=\"formValue.%s\" />\n </n-form-item>", field.Dc, field.TsName, field.TsName)
|
||||
|
||||
case FormModePidTreeSelect:
|
||||
component = fmt.Sprintf(` <n-form-item label="%v" path="pid">
|
||||
<n-tree-select
|
||||
:options="treeOption"
|
||||
v-model:value="formValue.pid"
|
||||
key-field="%v"
|
||||
label-field="%v"
|
||||
clearable
|
||||
filterable
|
||||
default-expand-all
|
||||
show-path
|
||||
/>
|
||||
</n-form-item>`, field.Dc, in.pk.TsName, in.options.Tree.TitleField.TsName)
|
||||
|
||||
case FormModeTreeSelect:
|
||||
component = fmt.Sprintf(` <n-form-item label="%v" path="%v">
|
||||
<n-tree-select
|
||||
placeholder="请选择%v"
|
||||
v-model:value="formValue.%v"
|
||||
:options="[{ label: 'AA', key: 1, children: [{ label: 'BB', key: 2 }] }]"
|
||||
clearable
|
||||
filterable
|
||||
default-expand-all
|
||||
/>
|
||||
</n-form-item>`, field.Dc, field.TsName, field.Dc, field.TsName)
|
||||
|
||||
case FormModeCascader:
|
||||
component = fmt.Sprintf(` <n-form-item label="%v" path="%v">
|
||||
<n-cascader
|
||||
placeholder="请选择%v"
|
||||
v-model:value="formValue.%v"
|
||||
:options="[{ label: 'AA', value: 1, children: [{ label: 'BB', value: 2 }] }]"
|
||||
clearable
|
||||
filterable
|
||||
/>
|
||||
</n-form-item>`, field.Dc, field.TsName, field.Dc, field.TsName)
|
||||
|
||||
default:
|
||||
component = defaultComponent
|
||||
}
|
||||
|
||||
buffer.WriteString(fmt.Sprintf("<n-gi span=\"%v\">\n%v\n </n-gi>\n\n", field.FormGridSpan, component))
|
||||
}
|
||||
return buffer.String()
|
||||
}
|
||||
|
||||
func (l *gCurd) generateWebEditScript(ctx context.Context, in *CurdPreviewInput) g.Map {
|
||||
var (
|
||||
data = make(g.Map)
|
||||
importBuffer = bytes.NewBuffer(nil)
|
||||
setupBuffer = bytes.NewBuffer(nil)
|
||||
hasYamlField = false
|
||||
)
|
||||
|
||||
// 导入字典
|
||||
if in.options.DictOps.Has {
|
||||
importBuffer.WriteString(" import { useDictStore } from '@/store/modules/dict';\n")
|
||||
}
|
||||
|
||||
// 导入api
|
||||
var importApiMethod = []string{"Edit", "View"}
|
||||
if in.options.Step.HasMaxSort {
|
||||
importApiMethod = append(importApiMethod, "MaxSort")
|
||||
}
|
||||
importBuffer.WriteString(" import " + ImportWebMethod(importApiMethod) + " from '" + in.options.ImportWebApi + "';\n")
|
||||
|
||||
// 导入model
|
||||
var importModelMethod = []string{"State", "newState"}
|
||||
if in.options.Step.IsTreeTable {
|
||||
importModelMethod = append(importModelMethod, []string{"treeOption", "loadTreeOption"}...)
|
||||
}
|
||||
|
||||
if in.options.Step.HasRules {
|
||||
importModelMethod = append(importModelMethod, "rules")
|
||||
}
|
||||
importBuffer.WriteString(" import " + ImportWebMethod(importModelMethod) + " from './model';\n")
|
||||
|
||||
for _, field := range in.masterFields {
|
||||
if !field.IsEdit {
|
||||
continue
|
||||
}
|
||||
switch field.FormMode {
|
||||
case FormModeDate, FormModeDateRange, FormModeTime, FormModeTimeRange:
|
||||
if !gstr.Contains(importBuffer.String(), `import DatePicker`) {
|
||||
importBuffer.WriteString(" import DatePicker from '@/components/DatePicker/datePicker.vue';\n")
|
||||
}
|
||||
case FormModeInputEditor:
|
||||
if !gstr.Contains(importBuffer.String(), `import Editor`) {
|
||||
importBuffer.WriteString(" import Editor from '@/components/Editor/editor.vue';\n")
|
||||
}
|
||||
case FormModeInputYaml:
|
||||
if !gstr.Contains(importBuffer.String(), `import YamlEditor`) {
|
||||
importBuffer.WriteString(" import YamlEditor from '@/components/YamlEditor/index.vue';\n")
|
||||
}
|
||||
hasYamlField = true
|
||||
case FormModeUploadImage, FormModeUploadImages:
|
||||
if !gstr.Contains(importBuffer.String(), `import UploadImage`) {
|
||||
importBuffer.WriteString(" import UploadImage from '@/components/Upload/uploadImage.vue';\n")
|
||||
}
|
||||
case FormModeUploadFile, FormModeUploadFiles:
|
||||
if !gstr.Contains(importBuffer.String(), `import UploadFile`) {
|
||||
importBuffer.WriteString(" import UploadFile from '@/components/Upload/uploadFile.vue';\n")
|
||||
}
|
||||
case FormModeRate:
|
||||
setupBuffer.WriteString(fmt.Sprintf(" function update%s(num) {\n formValue.value.%s = num;\n }\n", field.GoName, field.TsName))
|
||||
case FormModeCitySelector:
|
||||
if !gstr.Contains(importBuffer.String(), `import CitySelector`) {
|
||||
importBuffer.WriteString(" import CitySelector from '@/components/CitySelector/citySelector.vue';\n")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 根据是否有 YAML 字段添加相应的验证逻辑
|
||||
if hasYamlField {
|
||||
setupBuffer.WriteString(" const yamlValidationStates = ref(new Map());\n const isFormValid = computed(() => {\n for (const [fieldName, isValid] of yamlValidationStates.value) {\n if (!isValid) return false;\n }\n return true;\n });\n const handleYamlError = (error) => {\n console.error('YAML 验证错误:', error);\n };\n const handleYamlValid = (content) => {\n console.log('YAML 验证通过:', content);\n };\n const handleYamlValidationChange = (isValid, fieldName) => {\n yamlValidationStates.value.set(fieldName, isValid);\n };\n")
|
||||
} else {
|
||||
setupBuffer.WriteString(" const isFormValid = ref(true);\n")
|
||||
}
|
||||
|
||||
data["import"] = importBuffer.String()
|
||||
data["setup"] = setupBuffer.String()
|
||||
return data
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
// Package views
|
||||
// @Link https://github.com/bufanyun/hotgo
|
||||
// @Copyright Copyright (c) 2023 HotGo CLI
|
||||
// @Author Ms <133814250@qq.com>
|
||||
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
|
||||
package views
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
|
||||
"github.com/gogf/gf/v2/frame/g"
|
||||
)
|
||||
|
||||
func (l *gCurd) webIndexTplData(ctx context.Context, in *CurdPreviewInput) (g.Map, error) {
|
||||
var (
|
||||
data = make(g.Map)
|
||||
importBuffer = bytes.NewBuffer(nil)
|
||||
importVueMethod = []string{"h", "reactive", "ref", "computed"}
|
||||
importApiMethod = []string{"List"}
|
||||
importModelMethod = []string{"columns", "schemas", "State"}
|
||||
importUtilsMethod = []string{"adaTableScrollX"}
|
||||
importIcons []string
|
||||
actionWidth int64 = 72
|
||||
)
|
||||
|
||||
// 添加
|
||||
if in.options.Step.HasAdd {
|
||||
importIcons = append(importIcons, "PlusOutlined")
|
||||
}
|
||||
|
||||
// 编辑
|
||||
if in.options.Step.HasEdit {
|
||||
in.options.Step.ActionColumnWidth += actionWidth
|
||||
if in.options.Step.IsTreeTable && !in.options.Step.IsOptionTreeTable {
|
||||
in.options.Step.ActionColumnWidth += actionWidth
|
||||
}
|
||||
if in.options.Step.IsOptionTreeTable {
|
||||
importIcons = append(importIcons, "EditOutlined")
|
||||
}
|
||||
}
|
||||
|
||||
// 导出
|
||||
if in.options.Step.HasExport {
|
||||
importIcons = append(importIcons, "ExportOutlined")
|
||||
importApiMethod = append(importApiMethod, "Export")
|
||||
}
|
||||
|
||||
// 删除
|
||||
if in.options.Step.HasDel {
|
||||
importApiMethod = append(importApiMethod, "Delete")
|
||||
in.options.Step.ActionColumnWidth += actionWidth
|
||||
}
|
||||
|
||||
// 批量删除
|
||||
if in.options.Step.HasBatchDel {
|
||||
importIcons = append(importIcons, "DeleteOutlined")
|
||||
importApiMethod = append(importApiMethod, "Delete")
|
||||
}
|
||||
|
||||
// 修改状态
|
||||
if in.options.Step.HasStatus {
|
||||
importApiMethod = append(importApiMethod, "Status")
|
||||
in.options.Step.ActionColumnWidth += actionWidth
|
||||
}
|
||||
|
||||
// 更多
|
||||
// 查看详情
|
||||
if in.options.Step.HasView {
|
||||
in.options.Step.ActionColumnWidth += actionWidth
|
||||
}
|
||||
|
||||
// 展开树
|
||||
if in.options.Step.IsTreeTable {
|
||||
importIcons = append(importIcons, "AlignLeftOutlined")
|
||||
}
|
||||
|
||||
// 存在字典数据选项
|
||||
if in.options.DictOps.Has {
|
||||
importVueMethod = append(importVueMethod, "onMounted")
|
||||
importModelMethod = append(importModelMethod, "loadOptions")
|
||||
}
|
||||
|
||||
// 普通树表
|
||||
if in.options.Step.IsTreeTable && !in.options.Step.IsOptionTreeTable {
|
||||
importUtilsMethod = append(importUtilsMethod, "convertListToTree")
|
||||
}
|
||||
|
||||
// 选项式树表
|
||||
if in.options.Step.IsOptionTreeTable {
|
||||
importVueMethod = append(importVueMethod, []string{"onMounted", "unref"}...)
|
||||
importIcons = append(importIcons, []string{"FormOutlined", "SearchOutlined"}...)
|
||||
importApiMethod = append(importApiMethod, "TreeOption")
|
||||
importUtilsMethod = append(importUtilsMethod, "getTreeKeys")
|
||||
importModelMethod = append(importModelMethod, []string{"loadTreeOption", "treeOption", "State"}...)
|
||||
}
|
||||
|
||||
// 操作按钮宽度最小值
|
||||
if in.options.Step.ActionColumnWidth > 0 && in.options.Step.ActionColumnWidth < actionWidth*2 {
|
||||
in.options.Step.ActionColumnWidth = 100
|
||||
}
|
||||
|
||||
// 导入基础包
|
||||
importBuffer.WriteString(" import { useDialog, useMessage } from 'naive-ui';\n")
|
||||
importBuffer.WriteString(" import { BasicTable, TableAction } from '@/components/Table';\n")
|
||||
importBuffer.WriteString(" import { BasicForm, useForm } from '@/components/Form/index';\n")
|
||||
importBuffer.WriteString(" import { usePermission } from '@/hooks/web/usePermission';\n")
|
||||
|
||||
// 导入字典
|
||||
if in.options.DictOps.Has {
|
||||
importBuffer.WriteString(" import { useDictStore } from '@/store/modules/dict';\n")
|
||||
}
|
||||
|
||||
// 导入api
|
||||
importBuffer.WriteString(" import " + ImportWebMethod(importApiMethod) + " from '" + in.options.ImportWebApi + "';\n")
|
||||
|
||||
// 导入icons
|
||||
if len(importIcons) > 0 {
|
||||
importBuffer.WriteString(" import " + ImportWebMethod(importIcons) + " from '@vicons/antd';\n")
|
||||
}
|
||||
|
||||
// 导入model
|
||||
if in.options.Step.IsTreeTable {
|
||||
importModelMethod = append(importModelMethod, "newState")
|
||||
}
|
||||
importBuffer.WriteString(" import " + ImportWebMethod(importModelMethod) + " from './model';\n")
|
||||
|
||||
// 导入utils
|
||||
if len(importUtilsMethod) > 0 {
|
||||
importBuffer.WriteString(" import " + ImportWebMethod(importUtilsMethod) + " from '@/utils/hotgo';\n")
|
||||
}
|
||||
|
||||
// 导入edit组件
|
||||
if in.options.Step.HasEdit {
|
||||
importBuffer.WriteString(" import Edit from './edit.vue';\n")
|
||||
}
|
||||
|
||||
// 导入view组件
|
||||
if in.options.Step.HasView {
|
||||
importBuffer.WriteString(" import View from './view.vue';\n")
|
||||
}
|
||||
|
||||
// 没有需要查询的字段则隐藏搜索表单
|
||||
isSearchForm := false
|
||||
for _, field := range in.masterFields {
|
||||
if field.IsQuery {
|
||||
isSearchForm = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !isSearchForm {
|
||||
if len(in.options.Join) > 0 {
|
||||
LoopOut:
|
||||
for _, v := range in.options.Join {
|
||||
for _, column := range v.Columns {
|
||||
if column.IsQuery {
|
||||
isSearchForm = true
|
||||
break LoopOut
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
data["isSearchForm"] = isSearchForm
|
||||
data["import"] = importBuffer.String()
|
||||
return data, nil
|
||||
}
|
||||
@@ -0,0 +1,493 @@
|
||||
// Package views
|
||||
// @Link https://github.com/bufanyun/hotgo
|
||||
// @Copyright Copyright (c) 2023 HotGo CLI
|
||||
// @Author Ms <133814250@qq.com>
|
||||
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
|
||||
package views
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"hotgo/internal/dao"
|
||||
"hotgo/internal/library/dict"
|
||||
"hotgo/internal/model/input/sysin"
|
||||
"hotgo/utility/convert"
|
||||
"strings"
|
||||
|
||||
"github.com/gogf/gf/v2/errors/gerror"
|
||||
"github.com/gogf/gf/v2/frame/g"
|
||||
"github.com/gogf/gf/v2/util/gconv"
|
||||
)
|
||||
|
||||
type StateItem struct {
|
||||
Name string
|
||||
DefaultValue interface{}
|
||||
Dc string
|
||||
DataType string // 新增字段:存储字段类型信息
|
||||
}
|
||||
|
||||
func (l *gCurd) webModelTplData(ctx context.Context, in *CurdPreviewInput) (data g.Map, err error) {
|
||||
data = make(g.Map)
|
||||
data["stateItems"] = l.generateWebModelStateItems(ctx, in)
|
||||
data["rules"] = l.generateWebModelRules(ctx, in)
|
||||
data["formSchema"] = l.generateWebModelFormSchema(ctx, in)
|
||||
if data["columns"], err = l.generateWebModelColumns(ctx, in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 根据表单生成情况,按需导包
|
||||
data["import"], data["const"] = l.generateWebModelImport(ctx, in)
|
||||
return
|
||||
}
|
||||
|
||||
func (l *gCurd) generateWebModelImport(ctx context.Context, in *CurdPreviewInput) (string, string) {
|
||||
importBuffer := bytes.NewBuffer(nil)
|
||||
constBuffer := bytes.NewBuffer(nil)
|
||||
|
||||
// 导入基础组件
|
||||
if len(in.options.Step.ImportModel.NaiveUI) > 0 {
|
||||
importBuffer.WriteString("import " + ImportWebMethod(in.options.Step.ImportModel.NaiveUI) + " from 'naive-ui';\n")
|
||||
}
|
||||
|
||||
importBuffer.WriteString("import { cloneDeep } from 'lodash-es';\n")
|
||||
|
||||
// 导入表单搜索
|
||||
if in.options.Step.HasSearchForm {
|
||||
importBuffer.WriteString("import { FormSchema } from '@/components/Form';\n")
|
||||
}
|
||||
|
||||
// 导入工具类
|
||||
if len(in.options.Step.ImportModel.UtilsIs) > 0 {
|
||||
importBuffer.WriteString("import " + ImportWebMethod(in.options.Step.ImportModel.UtilsIs) + " from '@/utils/is';\n")
|
||||
}
|
||||
|
||||
if len(in.options.Step.ImportModel.UtilsUrl) > 0 {
|
||||
importBuffer.WriteString("import " + ImportWebMethod(in.options.Step.ImportModel.UtilsUrl) + " from '@/utils/urlUtils';\n")
|
||||
}
|
||||
|
||||
if len(in.options.Step.ImportModel.UtilsDate) > 0 {
|
||||
importBuffer.WriteString("import " + ImportWebMethod(in.options.Step.ImportModel.UtilsDate) + " from '@/utils/dateUtil';\n")
|
||||
}
|
||||
|
||||
if in.options.Step.HasRulesValidator {
|
||||
importBuffer.WriteString("import { validate } from '@/utils/validateUtil';\n")
|
||||
}
|
||||
|
||||
if len(in.options.Step.ImportModel.UtilsHotGo) > 0 {
|
||||
importBuffer.WriteString("import " + ImportWebMethod(in.options.Step.ImportModel.UtilsHotGo) + " from '@/utils/hotgo';\n")
|
||||
}
|
||||
|
||||
if len(in.options.Step.ImportModel.UtilsIndex) > 0 {
|
||||
importBuffer.WriteString("import " + ImportWebMethod(in.options.Step.ImportModel.UtilsIndex) + " from '@/utils';\n")
|
||||
}
|
||||
|
||||
// 导入api
|
||||
var importApiMethod []string
|
||||
if in.options.Step.HasSwitch {
|
||||
importApiMethod = append(importApiMethod, "Switch")
|
||||
}
|
||||
if in.options.Step.IsTreeTable {
|
||||
importApiMethod = append(importApiMethod, "TreeOption")
|
||||
}
|
||||
if len(importApiMethod) > 0 {
|
||||
importBuffer.WriteString("import " + ImportWebMethod(importApiMethod) + " from '" + in.options.ImportWebApi + "';\n")
|
||||
}
|
||||
|
||||
// 导入字典选项
|
||||
if in.options.DictOps.Has {
|
||||
importBuffer.WriteString("import { useDictStore } from '@/store/modules/dict';\n")
|
||||
constBuffer.WriteString("const dict = useDictStore();\n")
|
||||
}
|
||||
|
||||
if in.options.Step.HasSwitch {
|
||||
importBuffer.WriteString("import { usePermission } from '@/hooks/web/usePermission';\n")
|
||||
constBuffer.WriteString("const { hasPermission } = usePermission();\n")
|
||||
constBuffer.WriteString("const $message = window['$message'];\n")
|
||||
}
|
||||
|
||||
return importBuffer.String(), constBuffer.String()
|
||||
}
|
||||
|
||||
func (l *gCurd) generateWebModelStateItems(ctx context.Context, in *CurdPreviewInput) (items []*StateItem) {
|
||||
for _, field := range in.masterFields {
|
||||
dataType := field.DataType
|
||||
if dataType == "" && field.SqlType != "" {
|
||||
if parts := strings.SplitN(field.SqlType, "(", 2); len(parts) > 0 {
|
||||
dataType = parts[0]
|
||||
}
|
||||
}
|
||||
|
||||
isStr := isStringType(field.TsType, dataType)
|
||||
isArray := strings.HasPrefix(dataType, "_") || strings.Contains(field.SqlType, "[]")
|
||||
|
||||
var value = field.DefaultValue
|
||||
if value == nil {
|
||||
if isArray {
|
||||
value = "null"
|
||||
} else if isStr {
|
||||
value = ""
|
||||
} else {
|
||||
value = "null"
|
||||
}
|
||||
}
|
||||
if value == "" {
|
||||
if isArray || !isStr {
|
||||
value = "null"
|
||||
}
|
||||
} else if valueStr, ok := value.(string); ok && isStr {
|
||||
value = valueStr
|
||||
}
|
||||
|
||||
// 选项组件默认值调整
|
||||
if gconv.Int(value) == 0 && IsSelectFormMode(field.FormMode) {
|
||||
value = "null"
|
||||
}
|
||||
|
||||
if field.Name == "status" {
|
||||
value = 1
|
||||
}
|
||||
if field.FormMode == FormModeSwitch {
|
||||
value = 2
|
||||
}
|
||||
if field.FormMode == FormModeInputDynamic {
|
||||
value = "[]"
|
||||
}
|
||||
items = append(items, &StateItem{
|
||||
Name: field.TsName,
|
||||
DefaultValue: value,
|
||||
DataType: dataType,
|
||||
Dc: field.Dc,
|
||||
})
|
||||
|
||||
// 查询用户摘要
|
||||
if field.IsList && in.options.Step.HasHookMemberSummary && IsMemberSummaryField(field.Name) {
|
||||
items = append(items, &StateItem{
|
||||
Name: field.TsName + "Summa?: null | MemberSumma",
|
||||
DefaultValue: "null",
|
||||
DataType: dataType,
|
||||
Dc: field.Dc + "摘要信息",
|
||||
})
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (l *gCurd) generateWebModelDictOptions(ctx context.Context, in *CurdPreviewInput) error {
|
||||
type DictType struct {
|
||||
Id int64 `json:"id"`
|
||||
Type string `json:"type"`
|
||||
}
|
||||
|
||||
var (
|
||||
dictTypeIds []int64
|
||||
dictTypeList []*DictType
|
||||
builtinDictTypeIds []int64
|
||||
builtinDictTypeList []*DictType
|
||||
)
|
||||
|
||||
for _, field := range in.masterFields {
|
||||
if field.DictType > 0 {
|
||||
dictTypeIds = append(dictTypeIds, field.DictType)
|
||||
}
|
||||
|
||||
if field.DictType < 0 {
|
||||
builtinDictTypeIds = append(builtinDictTypeIds, field.DictType)
|
||||
}
|
||||
}
|
||||
|
||||
dictTypeIds = convert.UniqueSlice(dictTypeIds)
|
||||
builtinDictTypeIds = convert.UniqueSlice(builtinDictTypeIds)
|
||||
|
||||
if len(dictTypeIds) == 0 && len(builtinDictTypeIds) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
if len(dictTypeIds) > 0 {
|
||||
err := dao.SysDictType.Ctx(ctx).
|
||||
Fields(dao.SysDictType.Columns().Id, dao.SysDictType.Columns().Type).
|
||||
WhereIn(dao.SysDictType.Columns().Id, dictTypeIds).
|
||||
Scan(&dictTypeList)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if len(builtinDictTypeIds) > 0 {
|
||||
for _, id := range builtinDictTypeIds {
|
||||
typ, err := dict.GetTypeById(ctx, id)
|
||||
if err != nil && !errors.Is(err, dict.NotExistKeyError) {
|
||||
return err
|
||||
}
|
||||
if len(typ) > 0 {
|
||||
row := new(DictType)
|
||||
row.Id = id
|
||||
row.Type = typ
|
||||
builtinDictTypeList = append(builtinDictTypeList, row)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(dictTypeList) == 0 && len(builtinDictTypeList) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
if len(builtinDictTypeList) > 0 {
|
||||
dictTypeList = append(dictTypeList, builtinDictTypeList...)
|
||||
}
|
||||
|
||||
in.options.DictOps.Has = true
|
||||
|
||||
for _, v := range dictTypeList {
|
||||
// 字段映射字典
|
||||
for _, field := range in.masterFields {
|
||||
if field.DictType != 0 && v.Id == field.DictType {
|
||||
in.options.dictMap[field.TsName] = v.Type
|
||||
in.options.DictOps.Schemas = append(in.options.DictOps.Schemas, &OptionsSchemasField{
|
||||
Field: field.TsName,
|
||||
Type: v.Type,
|
||||
})
|
||||
}
|
||||
}
|
||||
in.options.DictOps.Types = append(in.options.DictOps.Types, v.Type)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (l *gCurd) generateWebModelRules(ctx context.Context, in *CurdPreviewInput) string {
|
||||
buffer := bytes.NewBuffer(nil)
|
||||
buffer.WriteString("export const rules = {\n")
|
||||
for _, field := range in.masterFields {
|
||||
if !field.IsEdit || (!field.Required && (field.FormRole == "" || field.FormRole == FormRoleNone)) {
|
||||
continue
|
||||
}
|
||||
|
||||
in.options.Step.HasRules = true
|
||||
if field.FormRole == "" || field.FormRole == FormRoleNone || field.FormRole == "required" {
|
||||
buffer.WriteString(fmt.Sprintf(" %s: {\n required: %v,\n trigger: ['blur', 'input'],\n type: '%s',\n message: '请输入%s',\n },\n", field.TsName, field.Required, field.TsType, field.Dc))
|
||||
} else {
|
||||
in.options.Step.HasRulesValidator = true
|
||||
buffer.WriteString(fmt.Sprintf(" %s: {\n required: %v,\n trigger: ['blur', 'input'],\n type: '%s',\n validator: validate.%v,\n },\n", field.TsName, field.Required, field.TsType, field.FormRole))
|
||||
}
|
||||
}
|
||||
buffer.WriteString("};\n")
|
||||
return buffer.String()
|
||||
}
|
||||
|
||||
func (l *gCurd) generateWebModelFormSchema(ctx context.Context, in *CurdPreviewInput) string {
|
||||
buffer := bytes.NewBuffer(nil)
|
||||
buffer.WriteString("export const schemas = ref<FormSchema[]>([\n")
|
||||
|
||||
// 主表
|
||||
l.generateWebModelFormSchemaEach(buffer, in.masterFields, in)
|
||||
|
||||
// 关联表
|
||||
if len(in.options.Join) > 0 {
|
||||
for _, v := range in.options.Join {
|
||||
if !isEffectiveJoin(v) {
|
||||
continue
|
||||
}
|
||||
l.generateWebModelFormSchemaEach(buffer, v.Columns, in)
|
||||
}
|
||||
}
|
||||
|
||||
buffer.WriteString("]);\n")
|
||||
return buffer.String()
|
||||
}
|
||||
|
||||
// generateWebDictOption 生产字典选项
|
||||
func (l *gCurd) generateWebDictOption(typ any) string {
|
||||
return fmt.Sprintf(`dict.getOption('%v')`, typ)
|
||||
}
|
||||
|
||||
func (l *gCurd) generateWebModelFormSchemaEach(buffer *bytes.Buffer, fields []*sysin.GenCodesColumnListModel, in *CurdPreviewInput) {
|
||||
for _, field := range fields {
|
||||
if !field.IsQuery {
|
||||
continue
|
||||
}
|
||||
in.options.Step.HasSearchForm = true
|
||||
|
||||
// 查询用户摘要
|
||||
if field.IsQuery && in.options.Step.HasQueryMemberSummary && IsMemberSummaryField(field.Name) {
|
||||
buffer.WriteString(fmt.Sprintf(" {\n field: '%s',\n component: '%s',\n label: '%s',\n componentProps: {\n placeholder: '请输入ID|用户名|姓名|手机号',\n onUpdateValue: (e: any) => {\n console.log(e);\n },\n },\n },\n", field.TsName, "NInput", field.Dc))
|
||||
continue
|
||||
}
|
||||
|
||||
var (
|
||||
defaultComponent = fmt.Sprintf(" {\n field: '%s',\n component: '%s',\n label: '%s',\n componentProps: {\n placeholder: '请输入%s',\n onUpdateValue: (e: any) => {\n console.log(e);\n },\n },\n },\n", field.TsName, "NInput", field.Dc, field.Dc)
|
||||
component string
|
||||
)
|
||||
|
||||
// 这里根据编辑表单组件来进行推断,如果没有则使用默认input,这可能会导致和查询条件所需参数不符的情况
|
||||
switch field.FormMode {
|
||||
case FormModeInput, FormModeInputTextarea, FormModeInputEditor, FormModeInputYaml:
|
||||
component = defaultComponent
|
||||
|
||||
case FormModeInputNumber:
|
||||
component = fmt.Sprintf(" {\n field: '%s',\n component: '%s',\n label: '%s',\n componentProps: {\n placeholder: '请输入%s',\n onUpdateValue: (e: any) => {\n console.log(e);\n },\n },\n },\n", field.TsName, "NInputNumber", field.Dc, field.Dc)
|
||||
|
||||
case FormModeDate:
|
||||
component = fmt.Sprintf(" {\n field: '%s',\n component: '%s',\n label: '%s',\n componentProps: {\n type: '%s',\n clearable: true,\n shortcuts: %s,\n onUpdateValue: (e: any) => {\n console.log(e);\n },\n },\n },\n", field.TsName, "NDatePicker", field.Dc, "date", "defShortcuts()")
|
||||
in.options.Step.ImportModel.UtilsDate = append(in.options.Step.ImportModel.UtilsDate, "defShortcuts")
|
||||
|
||||
case FormModeDateRange:
|
||||
component = fmt.Sprintf(" {\n field: '%s',\n component: '%s',\n label: '%s',\n componentProps: {\n type: '%s',\n clearable: true,\n shortcuts: %s,\n onUpdateValue: (e: any) => {\n console.log(e);\n },\n },\n },\n", field.TsName, "NDatePicker", field.Dc, "daterange", "defRangeShortcuts()")
|
||||
in.options.Step.ImportModel.UtilsDate = append(in.options.Step.ImportModel.UtilsDate, "defRangeShortcuts")
|
||||
|
||||
case FormModeTime:
|
||||
component = fmt.Sprintf(" {\n field: '%s',\n component: '%s',\n label: '%s',\n componentProps: {\n type: '%s',\n clearable: true,\n shortcuts: %s,\n onUpdateValue: (e: any) => {\n console.log(e);\n },\n },\n },\n", field.TsName, "NDatePicker", field.Dc, "datetime", "defShortcuts()")
|
||||
in.options.Step.ImportModel.UtilsDate = append(in.options.Step.ImportModel.UtilsDate, "defShortcuts")
|
||||
|
||||
case FormModeTimeRange:
|
||||
component = fmt.Sprintf(" {\n field: '%s',\n component: '%s',\n label: '%s',\n componentProps: {\n type: '%s',\n clearable: true,\n shortcuts: %s,\n onUpdateValue: (e: any) => {\n console.log(e);\n },\n },\n },\n", field.TsName, "NDatePicker", field.Dc, "datetimerange", "defRangeShortcuts()")
|
||||
in.options.Step.ImportModel.UtilsDate = append(in.options.Step.ImportModel.UtilsDate, "defRangeShortcuts")
|
||||
|
||||
case FormModeSwitch:
|
||||
fallthrough
|
||||
case FormModeRadio:
|
||||
component = fmt.Sprintf(" {\n field: '%s',\n component: '%s',\n label: '%s',\n giProps: {\n //span: 24,\n },\n componentProps: {\n options: %v,\n onUpdateChecked: (e: any) => {\n console.log(e);\n },\n },\n },\n", field.TsName, "NRadioGroup", field.Dc, l.generateWebDictOption(in.options.dictMap[field.TsName]))
|
||||
|
||||
case FormModeCheckbox:
|
||||
component = fmt.Sprintf(" {\n field: '%s',\n component: '%s',\n label: '%s',\n giProps: {\n span: 1,\n },\n componentProps: {\n placeholder: '请选择%s',\n options: %v,\n onUpdateChecked: (e: any) => {\n console.log(e);\n },\n },\n },\n", field.TsName, "NCheckbox", field.Dc, field.Dc, l.generateWebDictOption(in.options.dictMap[field.TsName]))
|
||||
|
||||
case FormModeSelect:
|
||||
component = fmt.Sprintf(" {\n field: '%s',\n component: '%s',\n label: '%s',\n defaultValue: null,\n componentProps: {\n placeholder: '请选择%s',\n options: %v,\n onUpdateValue: (e: any) => {\n console.log(e);\n },\n },\n },\n", field.TsName, "NSelect", field.Dc, field.Dc, l.generateWebDictOption(in.options.dictMap[field.TsName]))
|
||||
|
||||
case FormModeSelectMultiple:
|
||||
component = fmt.Sprintf(" {\n field: '%s',\n component: '%s',\n label: '%s',\n defaultValue: null,\n componentProps: {\n multiple: true,\n placeholder: '请选择%s',\n options: %v,\n onUpdateValue: (e: any) => {\n console.log(e);\n },\n },\n },\n", field.TsName, "NSelect", field.Dc, field.Dc, l.generateWebDictOption(in.options.dictMap[field.TsName]))
|
||||
|
||||
default:
|
||||
component = defaultComponent
|
||||
}
|
||||
|
||||
buffer.WriteString(component)
|
||||
}
|
||||
}
|
||||
|
||||
func (l *gCurd) generateWebModelColumns(ctx context.Context, in *CurdPreviewInput) (string, error) {
|
||||
buffer := bytes.NewBuffer(nil)
|
||||
buffer.WriteString("export const columns = [\n")
|
||||
|
||||
// 主表
|
||||
if err := l.generateWebModelColumnsEach(buffer, in, in.masterFields); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// 关联表
|
||||
if len(in.options.Join) > 0 {
|
||||
for _, v := range in.options.Join {
|
||||
if !isEffectiveJoin(v) {
|
||||
continue
|
||||
}
|
||||
if err := l.generateWebModelColumnsEach(buffer, in, v.Columns); err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
buffer.WriteString("];\n")
|
||||
return buffer.String(), nil
|
||||
}
|
||||
|
||||
func (l *gCurd) generateWebModelColumnsEach(buffer *bytes.Buffer, in *CurdPreviewInput, fields []*sysin.GenCodesColumnListModel) (err error) {
|
||||
for _, field := range fields {
|
||||
if !field.IsList {
|
||||
continue
|
||||
}
|
||||
var (
|
||||
defaultComponent = fmt.Sprintf(" {\n title: '%s',\n key: '%s',\n align: '%v',\n width: %v,\n },\n", field.Dc, field.TsName, field.Align, field.Width)
|
||||
component string
|
||||
)
|
||||
|
||||
// 查询用户摘要
|
||||
if in.options.Step.HasHookMemberSummary && IsMemberSummaryField(field.Name) {
|
||||
buffer.WriteString(fmt.Sprintf(" {\n title: '%v',\n key: '%v',\n align: '%v',\n width: %v,\n render(row: State) {\n return renderPopoverMemberSumma(row.%vSumma);\n },\n },\n", field.Dc, field.TsName, field.Align, field.Width, field.TsName))
|
||||
in.options.Step.ImportModel.UtilsIndex = append(in.options.Step.ImportModel.UtilsIndex, []string{"renderPopoverMemberSumma", "MemberSumma"}...)
|
||||
continue
|
||||
}
|
||||
|
||||
// 这里根据编辑表单组件来进行推断,如果没有则使用默认input,这可能会导致和查询条件所需参数不符的情况
|
||||
switch field.FormMode {
|
||||
case FormModeDate:
|
||||
component = fmt.Sprintf(" {\n title: '%s',\n key: '%s',\n align: '%v',\n width: %v,\n render(row: State) {\n return formatToDate(row.%s);\n },\n },\n", field.Dc, field.TsName, field.Align, field.Width, field.TsName)
|
||||
in.options.Step.ImportModel.UtilsDate = append(in.options.Step.ImportModel.UtilsDate, "formatToDate")
|
||||
|
||||
case FormModeRadio:
|
||||
fallthrough
|
||||
case FormModeSelect:
|
||||
if g.IsEmpty(in.options.dictMap[field.TsName]) {
|
||||
err = gerror.Newf("设置单选下拉框选项时,必须选择字典类型,字段名称:%v", field.Name)
|
||||
return
|
||||
}
|
||||
component = fmt.Sprintf(" {\n title: '%s',\n key: '%s',\n align: '%v',\n width: %v,\n render(row: State) {\n return renderOptionTag('%v', row.%v);\n },\n },\n", field.Dc, field.TsName, field.Align, field.Width, in.options.dictMap[field.TsName], field.TsName)
|
||||
in.options.Step.ImportModel.UtilsIndex = append(in.options.Step.ImportModel.UtilsIndex, "renderOptionTag")
|
||||
|
||||
case FormModeSelectMultiple:
|
||||
if g.IsEmpty(in.options.dictMap[field.TsName]) {
|
||||
err = gerror.Newf("设置多选下拉框选项时,必须选择字典类型,字段名称:%v", field.Name)
|
||||
return
|
||||
}
|
||||
component = fmt.Sprintf(" {\n title: '%s',\n key: '%s',\n align: '%v',\n width: %v,\n render(row: State) {\n if (isNullObject(row.%s) || !Array.isArray(row.%s)) {\n return ``;\n }\n return row.%s.map((tagKey) => {\n return renderOptionTag('%s', tagKey)\n });\n },\n },\n", field.Dc, field.TsName, field.Align, field.Width, field.TsName, field.TsName, field.TsName, in.options.dictMap[field.TsName])
|
||||
in.options.Step.ImportModel.NaiveUI = append(in.options.Step.ImportModel.NaiveUI, "NTag")
|
||||
in.options.Step.ImportModel.UtilsIs = append(in.options.Step.ImportModel.UtilsIs, "isNullObject")
|
||||
|
||||
case FormModeUploadImage:
|
||||
component = fmt.Sprintf(" {\n title: '%s',\n key: '%s',\n align: '%v',\n width: %v,\n render(row: State) {\n return renderImage(row.%v);\n },\n },\n", field.Dc, field.TsName, field.Align, field.Width, field.TsName)
|
||||
in.options.Step.ImportModel.UtilsIndex = append(in.options.Step.ImportModel.UtilsIndex, "renderImage")
|
||||
|
||||
case FormModeUploadImages:
|
||||
component = fmt.Sprintf(" {\n title: '%s',\n key: '%s',\n align: '%v',\n width: %v,\n render(row: State) {\n return renderImageGroup(row.%v);\n },\n },\n", field.Dc, field.TsName, field.Align, field.Width, field.TsName)
|
||||
in.options.Step.ImportModel.UtilsIndex = append(in.options.Step.ImportModel.UtilsIndex, "renderImageGroup")
|
||||
|
||||
case FormModeUploadFile:
|
||||
component = fmt.Sprintf(" {\n title: '%s',\n key: '%s',\n align: '%v',\n width: %v,\n render(row: State) {\n return renderFile(row.%v);\n },\n },\n", field.Dc, field.TsName, field.Align, field.Width, field.TsName)
|
||||
in.options.Step.ImportModel.UtilsIndex = append(in.options.Step.ImportModel.UtilsIndex, "renderFile")
|
||||
|
||||
case FormModeUploadFiles:
|
||||
component = fmt.Sprintf(" {\n title: '%s',\n key: '%s',\n align: '%v',\n width: %v,\n render(row: State) {\n return renderFileGroup(row.%v);\n },\n },\n", field.Dc, field.TsName, field.Align, field.Width, field.TsName)
|
||||
in.options.Step.ImportModel.UtilsIndex = append(in.options.Step.ImportModel.UtilsIndex, "renderFileGroup")
|
||||
|
||||
case FormModeSwitch:
|
||||
component = fmt.Sprintf(" {\n title: '%s',\n key: '%s',\n align: '%v',\n width: %v,\n render(row: State) {\n return h(%s, {\n value: row.%s === 1,\n checked: '开启',\n unchecked: '关闭',\n disabled: !hasPermission(['%s']),\n onUpdateValue: function (e) {\n console.log('onUpdateValue e:' + JSON.stringify(e));\n row.%s = e ? 1 : 2;\n Switch({ %s: row.%s, key: '%s', value: row.%s }).then((_res) => {\n $message.success('操作成功');\n });\n },\n });\n },\n },\n", field.Dc, field.TsName, field.Align, field.Width, "NSwitch", field.TsName, "/"+in.options.ApiPrefix+"/switch", field.TsName, in.pk.TsName, in.pk.TsName, convert.CamelCaseToUnderline(field.TsName), field.TsName)
|
||||
in.options.Step.ImportModel.NaiveUI = append(in.options.Step.ImportModel.NaiveUI, "NSwitch")
|
||||
|
||||
case FormModeRate:
|
||||
component = fmt.Sprintf(" {\n title: '%s',\n key: '%s',\n align: '%v',\n width: %v,\n render(row: State) {\n return h(%s, {\n allowHalf: true,\n readonly: true,\n defaultValue: row.%s,\n });\n },\n },\n", field.Dc, field.TsName, field.Align, field.Width, "NRate", field.TsName)
|
||||
in.options.Step.ImportModel.NaiveUI = append(in.options.Step.ImportModel.NaiveUI, "NRate")
|
||||
|
||||
default:
|
||||
component = defaultComponent
|
||||
}
|
||||
|
||||
buffer.WriteString(component)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// isStringType 判断字段是否为字符串类型
|
||||
func isStringType(tsType, dataType string) bool {
|
||||
// 根据 TypeScript 类型判断
|
||||
if tsType == "string" {
|
||||
return true
|
||||
}
|
||||
|
||||
// 根据数据库数据类型判断
|
||||
stringTypes := []string{
|
||||
// mysql
|
||||
"varchar", "char", "text", "longtext", "mediumtext", "tinytext",
|
||||
"nvarchar", "nchar", "ntext",
|
||||
"string", "enum", "set",
|
||||
// pgsql
|
||||
"bpchar", "date", "time", "timetz", "timestamp", "timestamptz", "interval",
|
||||
"uuid", "bytea", "inet", "cidr", "macaddr", "macaddr8", "bit", "varbit", "json", "jsonb",
|
||||
"point", "line", "lseg", "box", "path", "polygon", "circle", "money",
|
||||
}
|
||||
|
||||
for _, t := range stringTypes {
|
||||
if strings.EqualFold(dataType, t) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
// Package views
|
||||
// @Link https://github.com/bufanyun/hotgo
|
||||
// @Copyright Copyright (c) 2023 HotGo CLI
|
||||
// @Author Ms <133814250@qq.com>
|
||||
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
|
||||
package views
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/gogf/gf/v2/frame/g"
|
||||
)
|
||||
|
||||
func (l *gCurd) webViewTplData(ctx context.Context, in *CurdPreviewInput) (data g.Map, err error) {
|
||||
data = make(g.Map)
|
||||
item, hasUpload := l.generateWebViewItem(ctx, in)
|
||||
data["item"] = item
|
||||
data["hasUploadFile"] = hasUpload
|
||||
return
|
||||
}
|
||||
|
||||
func (l *gCurd) generateWebViewItem(ctx context.Context, in *CurdPreviewInput) (string, bool) {
|
||||
buffer := bytes.NewBuffer(nil)
|
||||
hasUploadFile := false
|
||||
|
||||
for _, field := range in.masterFields {
|
||||
if !field.IsEdit {
|
||||
continue
|
||||
}
|
||||
|
||||
// 检测是否使用了文件上传相关的组件
|
||||
if field.FormMode == FormModeUploadFile || field.FormMode == FormModeUploadFiles {
|
||||
hasUploadFile = true
|
||||
}
|
||||
|
||||
var (
|
||||
defaultComponent = fmt.Sprintf("<n-descriptions-item>\n <template #label> %s </template>\n {{ formValue.%s }}\n </n-descriptions-item>", field.Dc, field.TsName)
|
||||
component string
|
||||
)
|
||||
|
||||
switch field.FormMode {
|
||||
case FormModeInputTextarea, FormModeInputEditor:
|
||||
component = fmt.Sprintf("<n-descriptions-item>\n <template #label> %s </template>\n <span v-html=\"formValue.%s\"></span>\n </n-descriptions-item>", field.Dc, field.TsName)
|
||||
|
||||
case FormModeInputYaml:
|
||||
component = fmt.Sprintf("<n-descriptions-item>\n <template #label> %s </template>\n <pre style=\"white-space: pre-wrap; font-family: monospace; background: #f5f5f5; padding: 10px; border-radius: 4px;\">{{ formValue.%s }}</pre>\n </n-descriptions-item>", field.Dc, field.TsName)
|
||||
|
||||
case FormModeInputDynamic:
|
||||
component = defaultComponent
|
||||
|
||||
case FormModeDate:
|
||||
component = defaultComponent
|
||||
|
||||
case FormModeTime:
|
||||
component = defaultComponent
|
||||
|
||||
case FormModeRadio, FormModeSelect:
|
||||
component = fmt.Sprintf("<n-descriptions-item label=\"%s\">\n <n-tag\n :type=\"dict.getType('%s', formValue.%s)\"\n size=\"small\"\n class=\"min-left-space\"\n >\n {{ dict.getLabel('%s', formValue.%s) }}\n </n-tag>\n </n-descriptions-item>", field.Dc, in.options.dictMap[field.TsName], field.TsName, in.options.dictMap[field.TsName], field.TsName)
|
||||
|
||||
case FormModeCheckbox, FormModeSelectMultiple:
|
||||
component = fmt.Sprintf("<n-descriptions-item label=\"%s\">\n <template v-for=\"(item, key) in formValue.%s\" :key=\"key\">\n <n-tag\n :type=\"dict.getType('%s', item)\"\n size=\"small\"\n class=\"min-left-space\"\n >\n {{ dict.getLabel('%s', item) }}\n </n-tag>\n </template>\n </n-descriptions-item>", field.Dc, field.TsName, in.options.dictMap[field.TsName], in.options.dictMap[field.TsName])
|
||||
|
||||
case FormModeUploadImage:
|
||||
component = fmt.Sprintf("<n-descriptions-item>\n <template #label> %s </template>\n <n-image style=\"margin-left: 10px; height: 100px; width: 100px\" :src=\"formValue.%s\" />\n </n-descriptions-item>", field.Dc, field.TsName)
|
||||
|
||||
case FormModeUploadImages:
|
||||
component = fmt.Sprintf("<n-descriptions-item>\n <template #label> %s </template>\n <n-image-group>\n <n-space>\n <span v-for=\"(item, key) in formValue.%s\" :key=\"key\">\n <n-image style=\"margin-left: 10px; height: 100px; width: 100px\" :src=\"item\" />\n </span>\n </n-space>\n </n-image-group>\n </n-descriptions-item>", field.Dc, field.TsName)
|
||||
|
||||
case FormModeUploadFile:
|
||||
component = fmt.Sprintf("<n-descriptions-item>\n <template #label> %s </template>\n <div class=\"upload-card\" v-show=\"formValue.%s !== ''\" @click=\"download(formValue.%s)\">\n <div class=\"upload-card-item\" style=\"height: 100px; width: 100px\">\n <div class=\"upload-card-item-info\">\n <div class=\"img-box\">\n <n-avatar :style=\"fileAvatarCSS\">{{ getFileExt(formValue.%s) }}</n-avatar>\n </div>\n </div>\n </div>\n </div>\n </n-descriptions-item>", field.Dc, field.TsName, field.TsName, field.TsName)
|
||||
|
||||
case FormModeUploadFiles:
|
||||
component = fmt.Sprintf("<n-descriptions-item>\n <template #label> %s </template>\n <div class=\"upload-card\">\n <n-space style=\"gap: 0px 0px\">\n <div\n class=\"upload-card-item\"\n style=\"height: 100px; width: 100px\"\n v-for=\"(item, key) in formValue.%s\"\n :key=\"key\"\n >\n <div class=\"upload-card-item-info\">\n <div class=\"img-box\">\n <n-avatar :style=\"fileAvatarCSS\" @click=\"download(item)\">\n {{ getFileExt(item) }}\n </n-avatar>\n </div>\n </div>\n </div>\n </n-space>\n </div>\n </n-descriptions-item>", field.Dc, field.TsName)
|
||||
|
||||
case FormModeSwitch:
|
||||
component = fmt.Sprintf("<n-descriptions-item label=\"%s\">\n <n-switch\n v-model:value=\"formValue.%s\"\n :unchecked-value=\"2\"\n :checked-value=\"1\"\n :disabled=\"true\"\n />\n </n-descriptions-item>", field.Dc, field.TsName)
|
||||
|
||||
case FormModeRate:
|
||||
component = fmt.Sprintf("<n-descriptions-item label=\"%s\">\n <n-rate readonly :default-value=\"formValue.%s\" />\n </n-descriptions-item>", field.Dc, field.TsName)
|
||||
|
||||
default:
|
||||
component = defaultComponent
|
||||
}
|
||||
|
||||
buffer.WriteString(" " + component + "\n\n")
|
||||
}
|
||||
return buffer.String(), hasUploadFile
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package gohtml
|
||||
|
||||
const (
|
||||
defaultIndentString = " "
|
||||
startIndent = 0
|
||||
defaultLastElement = "</html>"
|
||||
)
|
||||
@@ -0,0 +1,2 @@
|
||||
// Package gohtml provides an HTML formatting function.
|
||||
package gohtml
|
||||
@@ -0,0 +1,7 @@
|
||||
package gohtml
|
||||
|
||||
// An element represents an HTML element.
|
||||
type element interface {
|
||||
isInline() bool
|
||||
write(*formattedBuffer, bool) bool
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package gohtml
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Format parses the input HTML string, formats it and returns the result.
|
||||
func Format(s string) string {
|
||||
return parse(strings.NewReader(s)).html()
|
||||
}
|
||||
|
||||
// FormatBytes parses input HTML as bytes, formats it and returns the result.
|
||||
func FormatBytes(b []byte) []byte {
|
||||
return parse(bytes.NewReader(b)).bytes()
|
||||
}
|
||||
|
||||
// Format parses the input HTML string, formats it and returns the result with line no.
|
||||
func FormatWithLineNo(s string) string {
|
||||
return AddLineNo(Format(s))
|
||||
}
|
||||
|
||||
func AddLineNo(s string) string {
|
||||
lines := strings.Split(s, "\n")
|
||||
maxLineNoStrLen := len(strconv.Itoa(len(lines)))
|
||||
bf := &bytes.Buffer{}
|
||||
for i, line := range lines {
|
||||
lineNoStr := strconv.Itoa(i + 1)
|
||||
if i > 0 {
|
||||
bf.WriteString("\n")
|
||||
}
|
||||
bf.WriteString(strings.Repeat(" ", maxLineNoStrLen-len(lineNoStr)) + lineNoStr + " " + line)
|
||||
}
|
||||
return bf.String()
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package gohtml
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"regexp"
|
||||
)
|
||||
|
||||
// Column to wrap lines to (disabled by default)
|
||||
var LineWrapColumn = 0
|
||||
|
||||
// Maxmimum characters a long word can extend past LineWrapColumn without wrapping
|
||||
var LineWrapMaxSpillover = 5
|
||||
|
||||
// An htmlDocument represents an HTML document.
|
||||
type htmlDocument struct {
|
||||
elements []element
|
||||
}
|
||||
|
||||
// html generates an HTML source code and returns it.
|
||||
func (htmlDoc *htmlDocument) html() string {
|
||||
str := string(htmlDoc.bytes())
|
||||
str = replaceMultipleNewlinesWithSpaceAndTabs(str)
|
||||
return str
|
||||
}
|
||||
|
||||
func replaceMultipleNewlinesWithSpaceAndTabs(input string) string {
|
||||
re := regexp.MustCompile(`\n\s*\n+`)
|
||||
formattedString := re.ReplaceAllString(input, "\n")
|
||||
return formattedString
|
||||
}
|
||||
|
||||
// bytes reads from htmlDocument's internal array of elements and returns HTML source code
|
||||
func (htmlDoc *htmlDocument) bytes() []byte {
|
||||
bf := &formattedBuffer{
|
||||
buffer: &bytes.Buffer{},
|
||||
|
||||
lineWrapColumn: LineWrapColumn,
|
||||
lineWrapMaxSpillover: LineWrapMaxSpillover,
|
||||
|
||||
indentString: defaultIndentString,
|
||||
indentLevel: startIndent,
|
||||
}
|
||||
|
||||
isPreviousNodeInline := true
|
||||
for _, child := range htmlDoc.elements {
|
||||
isPreviousNodeInline = child.write(bf, isPreviousNodeInline)
|
||||
}
|
||||
return bf.buffer.Bytes()
|
||||
}
|
||||
|
||||
// append appends an element to the htmlDocument.
|
||||
func (htmlDoc *htmlDocument) append(e element) {
|
||||
htmlDoc.elements = append(htmlDoc.elements, e)
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package gohtml
|
||||
|
||||
import (
|
||||
"io"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/net/html"
|
||||
)
|
||||
|
||||
// parse parses a stirng and converts it into an html.
|
||||
func parse(r io.Reader) *htmlDocument {
|
||||
htmlDoc := &htmlDocument{}
|
||||
tokenizer := html.NewTokenizer(r)
|
||||
for {
|
||||
if errorToken, _, _ := parseToken(tokenizer, htmlDoc, nil); errorToken {
|
||||
break
|
||||
}
|
||||
}
|
||||
return htmlDoc
|
||||
}
|
||||
|
||||
// Function that identifies which tags will be treated as containing preformatted
|
||||
// content. Such tags will have the formatting of all its contents preserved
|
||||
// unchanged.
|
||||
// The opening tag html.Token is passed to this function.
|
||||
// By default, only <pre> and <textarea> tags are considered preformatted.
|
||||
var IsPreformatted = func(token html.Token) bool {
|
||||
return token.Data == "pre" || token.Data == "textarea"
|
||||
}
|
||||
|
||||
func parseToken(tokenizer *html.Tokenizer, htmlDoc *htmlDocument, parent *tagElement) (bool, bool, string) {
|
||||
tokenType := tokenizer.Next()
|
||||
raw := string(tokenizer.Raw())
|
||||
switch tokenType {
|
||||
case html.ErrorToken:
|
||||
return true, false, ""
|
||||
case html.TextToken:
|
||||
text := string(tokenizer.Raw())
|
||||
if strings.TrimSpace(text) == "" && (parent == nil || !parent.isRaw) {
|
||||
break
|
||||
}
|
||||
textElement := &textElement{text: text, parent: parent}
|
||||
appendElement(htmlDoc, parent, textElement)
|
||||
case html.StartTagToken:
|
||||
raw := string(tokenizer.Raw())
|
||||
token := tokenizer.Token()
|
||||
tagElement := &tagElement{
|
||||
tagName: string(token.Data),
|
||||
startTagRaw: raw,
|
||||
isRaw: IsPreformatted(token) || (parent != nil && parent.isRaw),
|
||||
parent: parent,
|
||||
}
|
||||
appendElement(htmlDoc, parent, tagElement)
|
||||
for {
|
||||
errorToken, parentEnded, unsetEndTag := parseToken(tokenizer, htmlDoc, tagElement)
|
||||
if errorToken {
|
||||
return true, false, ""
|
||||
}
|
||||
if parentEnded {
|
||||
if unsetEndTag != "" {
|
||||
return false, false, unsetEndTag
|
||||
}
|
||||
break
|
||||
}
|
||||
if unsetEndTag != "" {
|
||||
tagName := setEndTagRaw(tokenizer, tagElement, unsetEndTag)
|
||||
return false, false, tagName
|
||||
}
|
||||
}
|
||||
case html.EndTagToken:
|
||||
tagName := setEndTagRaw(tokenizer, parent, getTagName(tokenizer))
|
||||
return false, true, tagName
|
||||
case html.DoctypeToken, html.CommentToken:
|
||||
tagElement := &tagElement{
|
||||
tagName: getTagName(tokenizer),
|
||||
startTagRaw: string(tokenizer.Raw()),
|
||||
isRaw: parent != nil && parent.isRaw,
|
||||
parent: parent,
|
||||
}
|
||||
appendElement(htmlDoc, parent, tagElement)
|
||||
case html.SelfClosingTagToken:
|
||||
tagElement := &tagElement{
|
||||
tagName: getTagName(tokenizer),
|
||||
startTagRaw: raw,
|
||||
isRaw: parent != nil && parent.isRaw,
|
||||
parent: parent,
|
||||
}
|
||||
appendElement(htmlDoc, parent, tagElement)
|
||||
}
|
||||
return false, false, ""
|
||||
}
|
||||
|
||||
// appendElement appends the element to the htmlDocument or parent tagElement.
|
||||
func appendElement(htmlDoc *htmlDocument, parent *tagElement, e element) {
|
||||
if parent != nil {
|
||||
parent.appendChild(e)
|
||||
} else {
|
||||
htmlDoc.append(e)
|
||||
}
|
||||
}
|
||||
|
||||
// getTagName gets a tagName from tokenizer.
|
||||
func getTagName(tokenizer *html.Tokenizer) string {
|
||||
tagName, _ := tokenizer.TagName()
|
||||
return string(tagName)
|
||||
}
|
||||
|
||||
// setEndTagRaw sets an endTagRaw to the parent.
|
||||
func setEndTagRaw(_ *html.Tokenizer, parent *tagElement, tagName string) string {
|
||||
if parent != nil && parent.tagName == tagName {
|
||||
parent.endTagRaw = `</` + fMustCompile(parent.startTagRaw) + `>` // string(tokenizer.Raw())
|
||||
return ""
|
||||
}
|
||||
return tagName
|
||||
}
|
||||
|
||||
func fMustCompile(input string) (result string) {
|
||||
re := regexp.MustCompile(`<([A-Za-z-]+)[\s\S]*?>`)
|
||||
match := re.FindStringSubmatch(input)
|
||||
|
||||
if len(match) > 1 {
|
||||
result = match[1]
|
||||
} else {
|
||||
result = input
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
package gohtml
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
)
|
||||
|
||||
// A tagElement represents a tag element of an HTML document.
|
||||
type tagElement struct {
|
||||
tagName string
|
||||
startTagRaw string
|
||||
endTagRaw string
|
||||
|
||||
parent *tagElement
|
||||
children []element
|
||||
|
||||
isRaw bool
|
||||
isChildrenInlineCache *bool
|
||||
}
|
||||
|
||||
// Enable condensing a tag with only inline children onto a single line, or
|
||||
// completely inlining it with sibling nodes.
|
||||
// Tags to be treated as inline can be set in `InlineTags`.
|
||||
// Only inline tags will be completely inlined, while other condensable tags
|
||||
// will be given their own dedicated (single) line.
|
||||
var Condense bool
|
||||
|
||||
// Tags that are considered inline tags.
|
||||
// Note: Text nodes are always considered to be inline
|
||||
var InlineTags = map[string]bool{
|
||||
"a": true,
|
||||
"code": true,
|
||||
"em": true,
|
||||
"span": true,
|
||||
"strong": true,
|
||||
}
|
||||
|
||||
// Maximum length of an opening inline tag before it's un-inlined
|
||||
var InlineTagMaxLength = 40
|
||||
|
||||
func (e *tagElement) isInline() bool {
|
||||
if e.isRaw || !InlineTags[e.tagName] || len(e.startTagRaw) > InlineTagMaxLength {
|
||||
return false
|
||||
}
|
||||
return e.isChildrenInline()
|
||||
}
|
||||
|
||||
func (e *tagElement) isChildrenInline() bool {
|
||||
if !Condense {
|
||||
return false
|
||||
}
|
||||
if e.isChildrenInlineCache != nil {
|
||||
return *e.isChildrenInlineCache
|
||||
}
|
||||
|
||||
isInline := true
|
||||
for _, child := range e.children {
|
||||
isInline = isInline && child.isInline()
|
||||
}
|
||||
|
||||
e.isChildrenInlineCache = &isInline
|
||||
return isInline
|
||||
}
|
||||
|
||||
// write writes a tag to the buffer.
|
||||
func (e *tagElement) write(bf *formattedBuffer, isPreviousNodeInline bool) bool {
|
||||
if e.isRaw {
|
||||
if e.parent != nil && !e.parent.isRaw {
|
||||
bf.writeLineFeed()
|
||||
bf.writeIndent()
|
||||
bf.rawMode = true
|
||||
defer func() {
|
||||
bf.rawMode = false
|
||||
}()
|
||||
}
|
||||
bf.writeToken(e.startTagRaw, formatterTokenType_Tag)
|
||||
for _, child := range e.children {
|
||||
child.write(bf, true)
|
||||
}
|
||||
bf.writeToken(e.endTagRaw, formatterTokenType_Tag)
|
||||
return false
|
||||
}
|
||||
|
||||
if e.isChildrenInline() && (e.endTagRaw != "" || e.isInline()) {
|
||||
// Write the condensed output to a separate buffer, in case it doesn't work out
|
||||
condensedBuffer := *bf
|
||||
condensedBuffer.buffer = &bytes.Buffer{}
|
||||
|
||||
if bf.buffer.Len() > 0 && (!isPreviousNodeInline || !e.isInline()) {
|
||||
condensedBuffer.writeLineFeed()
|
||||
}
|
||||
condensedBuffer.writeToken(e.startTagRaw, formatterTokenType_Tag)
|
||||
if !isPreviousNodeInline && e.endTagRaw != "" {
|
||||
condensedBuffer.indentLevel++
|
||||
}
|
||||
|
||||
for _, child := range e.children {
|
||||
child.write(&condensedBuffer, true)
|
||||
}
|
||||
if e.endTagRaw != "" {
|
||||
condensedBuffer.writeToken(e.endTagRaw, formatterTokenType_Tag)
|
||||
if !isPreviousNodeInline {
|
||||
condensedBuffer.indentLevel--
|
||||
}
|
||||
}
|
||||
|
||||
if e.isInline() || bytes.ContainsAny(condensedBuffer.buffer.Bytes()[1:], "\n") {
|
||||
// If we're an inline tag, or there were no newlines were in the buffer,
|
||||
// replace the original with the condensed version
|
||||
condensedBuffer.buffer = bytes.NewBuffer(bytes.Join([][]byte{
|
||||
bf.buffer.Bytes(), condensedBuffer.buffer.Bytes(),
|
||||
}, []byte{}))
|
||||
*bf = condensedBuffer
|
||||
|
||||
return e.isInline()
|
||||
}
|
||||
}
|
||||
|
||||
if bf.buffer.Len() > 0 {
|
||||
bf.writeLineFeed()
|
||||
}
|
||||
bf.writeToken(e.startTagRaw, formatterTokenType_Tag)
|
||||
if e.endTagRaw != "" {
|
||||
bf.indentLevel++
|
||||
}
|
||||
|
||||
isPreviousNodeInline = false
|
||||
for _, child := range e.children {
|
||||
isPreviousNodeInline = child.write(bf, isPreviousNodeInline)
|
||||
}
|
||||
|
||||
if e.endTagRaw != "" {
|
||||
if len(e.children) > 0 {
|
||||
bf.writeLineFeed()
|
||||
}
|
||||
bf.indentLevel--
|
||||
bf.writeToken(e.endTagRaw, formatterTokenType_Tag)
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// appendChild append an element to the element's children.
|
||||
func (e *tagElement) appendChild(child element) {
|
||||
e.children = append(e.children, child)
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package gohtml
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// A textElement represents a text element of an HTML document.
|
||||
type textElement struct {
|
||||
text string
|
||||
parent *tagElement
|
||||
}
|
||||
|
||||
func (e *textElement) isInline() bool {
|
||||
// Text nodes are always considered to be inline
|
||||
return true
|
||||
}
|
||||
|
||||
// write writes a text to the buffer.
|
||||
func (e *textElement) write(bf *formattedBuffer, isPreviousNodeInline bool) bool {
|
||||
text := unifyLineFeed(e.text)
|
||||
if e.parent != nil && e.parent.isRaw {
|
||||
bf.writeToken(text, formatterTokenType_Text)
|
||||
return true
|
||||
}
|
||||
|
||||
if !isPreviousNodeInline {
|
||||
bf.writeLineFeed()
|
||||
}
|
||||
|
||||
// Collapse leading and trailing spaces
|
||||
text = regexp.MustCompile(`^\s+|\s+$`).ReplaceAllString(text, " ")
|
||||
lines := strings.Split(text, "\n")
|
||||
for l, line := range lines {
|
||||
if l > 0 {
|
||||
bf.writeLineFeed()
|
||||
}
|
||||
for _, word := range strings.Split(line, " ") {
|
||||
bf.writeToken(word, formatterTokenType_Text)
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package gohtml
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"strings"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
type formatterTokenType int
|
||||
|
||||
const (
|
||||
formatterTokenType_Nothing formatterTokenType = iota
|
||||
formatterTokenType_Tag
|
||||
formatterTokenType_Text
|
||||
)
|
||||
|
||||
type formattedBuffer struct {
|
||||
buffer *bytes.Buffer
|
||||
rawMode bool
|
||||
|
||||
indentString string
|
||||
indentLevel int
|
||||
|
||||
lineWrapColumn int
|
||||
lineWrapMaxSpillover int
|
||||
|
||||
curLineLength int
|
||||
prevTokenType formatterTokenType
|
||||
}
|
||||
|
||||
func (bf *formattedBuffer) writeLineFeed() {
|
||||
if !bf.rawMode {
|
||||
// Strip trailing newlines
|
||||
bf.buffer = bytes.NewBuffer(bytes.TrimRightFunc(
|
||||
bf.buffer.Bytes(),
|
||||
func(r rune) bool {
|
||||
return r != '\n' && unicode.IsSpace(r)
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
bf.buffer.WriteString("\n")
|
||||
bf.curLineLength = 0
|
||||
bf.prevTokenType = formatterTokenType_Nothing
|
||||
}
|
||||
|
||||
func (bf *formattedBuffer) writeIndent() {
|
||||
bf.buffer.WriteString(strings.Repeat(bf.indentString, bf.indentLevel))
|
||||
bf.curLineLength += len(bf.indentString) * bf.indentLevel
|
||||
}
|
||||
|
||||
func (bf *formattedBuffer) writeToken(token string, kind formatterTokenType) {
|
||||
if bf.rawMode {
|
||||
bf.buffer.WriteString(token)
|
||||
bf.curLineLength += len(token)
|
||||
return
|
||||
}
|
||||
|
||||
if bf.prevTokenType == formatterTokenType_Nothing && strings.TrimSpace(token) == "" {
|
||||
// It's a whitespace token, but we already have indentation which functions
|
||||
// the same, so we ignore it
|
||||
return
|
||||
}
|
||||
|
||||
toWrite := token
|
||||
if kind == formatterTokenType_Text && bf.prevTokenType == formatterTokenType_Text {
|
||||
toWrite = " " + token
|
||||
}
|
||||
|
||||
if bf.prevTokenType != formatterTokenType_Nothing && bf.lineWrapColumn > 0 {
|
||||
switch {
|
||||
case bf.curLineLength > bf.lineWrapColumn:
|
||||
// Current line is too long
|
||||
fallthrough
|
||||
|
||||
case bf.curLineLength+len(toWrite) > bf.lineWrapColumn+bf.lineWrapMaxSpillover:
|
||||
// Current line + new token is too long even with allowed spillover
|
||||
fallthrough
|
||||
|
||||
case bf.curLineLength+len(toWrite) > bf.lineWrapColumn &&
|
||||
bf.curLineLength > bf.lineWrapColumn-bf.lineWrapMaxSpillover:
|
||||
// Current line + new token is too long and doesn't quality for spillover
|
||||
|
||||
bf.writeLineFeed()
|
||||
bf.writeToken(token, kind)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if bf.curLineLength == 0 {
|
||||
bf.writeIndent()
|
||||
}
|
||||
bf.buffer.WriteString(toWrite)
|
||||
bf.curLineLength += len(toWrite)
|
||||
bf.prevTokenType = kind
|
||||
}
|
||||
|
||||
// unifyLineFeed unifies line feeds.
|
||||
func unifyLineFeed(s string) string {
|
||||
return strings.ReplaceAll(strings.ReplaceAll(s, "\r\n", "\n"), "\r", "\n")
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package gohtml
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
)
|
||||
|
||||
// A Writer represents a formatted HTML source codes writer.
|
||||
type Writer struct {
|
||||
writer io.Writer
|
||||
lastElement string
|
||||
bf *bytes.Buffer
|
||||
}
|
||||
|
||||
// SetLastElement set the lastElement to the Writer.
|
||||
func (wr *Writer) SetLastElement(lastElement string) *Writer {
|
||||
wr.lastElement = lastElement
|
||||
return wr
|
||||
}
|
||||
|
||||
// Write writes the parameter.
|
||||
func (wr *Writer) Write(p []byte) (n int, err error) {
|
||||
n, _ = wr.bf.Write(p) // (*bytes.Buffer).Write never produces an error
|
||||
if bytes.HasSuffix(p, []byte(wr.lastElement)) {
|
||||
_, err = wr.writer.Write([]byte(Format(wr.bf.String()) + "\n"))
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
// NewWriter generates a Writer and returns it.
|
||||
func NewWriter(wr io.Writer) *Writer {
|
||||
return &Writer{writer: wr, lastElement: defaultLastElement, bf: &bytes.Buffer{}}
|
||||
}
|
||||
@@ -0,0 +1,543 @@
|
||||
// Package views
|
||||
// @Link https://github.com/bufanyun/hotgo
|
||||
// @Copyright Copyright (c) 2023 HotGo CLI
|
||||
// @Author Ms <133814250@qq.com>
|
||||
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
|
||||
package views
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"hotgo/internal/consts"
|
||||
"hotgo/internal/library/hggen/views/gohtml"
|
||||
"hotgo/internal/model"
|
||||
"hotgo/internal/model/input/sysin"
|
||||
"hotgo/utility/convert"
|
||||
"hotgo/utility/simple"
|
||||
"hotgo/utility/validate"
|
||||
"os"
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"github.com/gogf/gf/v2/util/gutil"
|
||||
|
||||
"github.com/gogf/gf/v2/database/gdb"
|
||||
"github.com/gogf/gf/v2/errors/gerror"
|
||||
"github.com/gogf/gf/v2/frame/g"
|
||||
"github.com/gogf/gf/v2/os/gfile"
|
||||
"github.com/gogf/gf/v2/os/gproc"
|
||||
"github.com/gogf/gf/v2/os/gtime"
|
||||
"github.com/gogf/gf/v2/text/gregex"
|
||||
"github.com/gogf/gf/v2/text/gstr"
|
||||
"github.com/gogf/gf/v2/util/gconv"
|
||||
"golang.org/x/tools/imports"
|
||||
)
|
||||
|
||||
// parseServFunName 解析业务服务名称
|
||||
func (l *gCurd) parseServFunName(templateGroup, varName string) string {
|
||||
templateGroup = gstr.UcFirst(templateGroup)
|
||||
if gstr.HasPrefix(varName, templateGroup) && varName != templateGroup {
|
||||
return varName
|
||||
}
|
||||
return templateGroup + varName
|
||||
}
|
||||
|
||||
// hasEffectiveJoin 存在有效的关联表
|
||||
func hasEffectiveJoins(joins []*CurdOptionsJoin) bool {
|
||||
for _, join := range joins {
|
||||
if isEffectiveJoin(join) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func isEffectiveJoin(join *CurdOptionsJoin) bool {
|
||||
return join.Alias != "" && join.Field != "" && join.LinkTable != "" && join.MasterField != "" && join.DaoName != "" && join.LinkMode > 0
|
||||
}
|
||||
|
||||
// formatComment formats the comment string to fit the golang code without any lines.
|
||||
func formatComment(comment string) string {
|
||||
comment = gstr.ReplaceByArray(comment, g.SliceStr{
|
||||
"\n", " ",
|
||||
"\r", " ",
|
||||
})
|
||||
comment = gstr.Replace(comment, `\n`, " ")
|
||||
comment = gstr.Trim(comment)
|
||||
return comment
|
||||
}
|
||||
|
||||
// 移除末尾的换行符
|
||||
func removeEndWrap(comment string) string {
|
||||
if len(comment) > 2 && comment[len(comment)-2:] == " \n" {
|
||||
comment = comment[:len(comment)-2]
|
||||
}
|
||||
return comment
|
||||
}
|
||||
|
||||
// ImportSql 导出sql文件
|
||||
func ImportSql(ctx context.Context, path string) error {
|
||||
rows, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sqlContent := string(rows)
|
||||
config := g.DB("default").GetConfig()
|
||||
if config.Type == consts.DBPgsql {
|
||||
return importSqlPgsql(ctx, sqlContent)
|
||||
}
|
||||
return importSqlMysql(ctx, sqlContent)
|
||||
}
|
||||
|
||||
// importSqlMysql 导出mysql文件
|
||||
func importSqlMysql(ctx context.Context, sqlContent string) error {
|
||||
sqlArr := strings.Split(sqlContent, "\n")
|
||||
for _, sql := range sqlArr {
|
||||
sql = strings.TrimSpace(sql)
|
||||
if sql == "" || strings.HasPrefix(sql, "--") {
|
||||
continue
|
||||
}
|
||||
exec, err := g.DB().Exec(ctx, sql)
|
||||
g.Log().Infof(ctx, "views.ImportSql sql:%v, exec:%+v, err:%+v", sql, exec, err)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// importSqlPgsql 导出pgsql文件
|
||||
func importSqlPgsql(ctx context.Context, sqlContent string) error {
|
||||
lines := strings.Split(sqlContent, "\n")
|
||||
var currentStmt strings.Builder
|
||||
inDoBlock := false
|
||||
for _, line := range lines {
|
||||
trimmedLine := strings.TrimSpace(line)
|
||||
|
||||
if trimmedLine == "" || strings.HasPrefix(trimmedLine, "--") {
|
||||
continue
|
||||
}
|
||||
|
||||
currentStmt.WriteString(line)
|
||||
currentStmt.WriteString("\n")
|
||||
|
||||
if strings.HasPrefix(trimmedLine, "DO $$") || strings.HasPrefix(trimmedLine, "DO $") {
|
||||
inDoBlock = true
|
||||
continue
|
||||
}
|
||||
|
||||
if inDoBlock && (strings.HasPrefix(trimmedLine, "END $$;") || strings.HasPrefix(trimmedLine, "END $")) {
|
||||
inDoBlock = false
|
||||
stmt := currentStmt.String()
|
||||
exec, err := g.DB().Exec(ctx, stmt)
|
||||
g.Log().Infof(ctx, "importSqlPgsql DO block executed, exec:%+v, err:%+v", exec, err)
|
||||
if err != nil {
|
||||
g.Log().Errorf(ctx, "importSqlPgsql error: %v, sql: %s", err, stmt)
|
||||
return err
|
||||
}
|
||||
currentStmt.Reset()
|
||||
continue
|
||||
}
|
||||
|
||||
if !inDoBlock && strings.HasSuffix(trimmedLine, ";") {
|
||||
stmt := currentStmt.String()
|
||||
exec, err := g.DB().Exec(ctx, stmt)
|
||||
g.Log().Infof(ctx, "importSqlPgsql sql executed, exec:%+v, err:%+v", exec, err)
|
||||
if err != nil {
|
||||
g.Log().Errorf(ctx, "importSqlPgsql error: %v, sql: %s", err, stmt)
|
||||
return err
|
||||
}
|
||||
currentStmt.Reset()
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func checkCurdPath(temp *model.GenerateAppCrudTemplate, addonName string) (err error) {
|
||||
if temp == nil {
|
||||
return gerror.New("生成模板配置不能为空")
|
||||
}
|
||||
|
||||
if temp.IsAddon {
|
||||
temp.TemplatePath = gstr.Replace(temp.TemplatePath, "{$name}", addonName)
|
||||
temp.ApiPath = gstr.Replace(temp.ApiPath, "{$name}", addonName)
|
||||
temp.InputPath = gstr.Replace(temp.InputPath, "{$name}", addonName)
|
||||
temp.ControllerPath = gstr.Replace(temp.ControllerPath, "{$name}", addonName)
|
||||
temp.LogicPath = gstr.Replace(temp.LogicPath, "{$name}", addonName)
|
||||
temp.RouterPath = gstr.Replace(temp.RouterPath, "{$name}", addonName)
|
||||
temp.SqlPath = gstr.Replace(temp.SqlPath, "{$name}", addonName)
|
||||
temp.WebApiPath = gstr.Replace(temp.WebApiPath, "{$name}", addonName)
|
||||
temp.WebViewsPath = gstr.Replace(temp.WebViewsPath, "{$name}", addonName)
|
||||
}
|
||||
|
||||
tip := `生成模板配置参数'%s'路径不存在,请先创建路径:%s`
|
||||
|
||||
if !gfile.Exists(temp.TemplatePath) {
|
||||
return gerror.Newf(tip, "TemplatePath", temp.TemplatePath)
|
||||
}
|
||||
if !gfile.Exists(temp.ApiPath) {
|
||||
return gerror.Newf(tip, "ApiPath", temp.ApiPath)
|
||||
}
|
||||
if !gfile.Exists(temp.InputPath) {
|
||||
return gerror.Newf(tip, "InputPath", temp.InputPath)
|
||||
}
|
||||
if !gfile.Exists(temp.ControllerPath) {
|
||||
return gerror.Newf(tip, "ControllerPath", temp.ControllerPath)
|
||||
}
|
||||
if !gfile.Exists(temp.LogicPath) {
|
||||
return gerror.Newf(tip, "LogicPath", temp.LogicPath)
|
||||
}
|
||||
if !gfile.Exists(temp.RouterPath) {
|
||||
return gerror.Newf(tip, "RouterPath", temp.RouterPath)
|
||||
}
|
||||
if !gfile.Exists(temp.SqlPath) {
|
||||
return gerror.Newf(tip, "SqlPath", temp.SqlPath)
|
||||
}
|
||||
if !gfile.Exists(temp.WebApiPath) {
|
||||
return gerror.Newf(tip, "WebApiPath", temp.WebApiPath)
|
||||
}
|
||||
if !gfile.Exists(temp.WebViewsPath) {
|
||||
return gerror.Newf(tip, "WebViewsPath", temp.WebViewsPath)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// GetModName 获取主包名
|
||||
func GetModName(ctx context.Context) (modName string, err error) {
|
||||
if !gfile.Exists("go.mod") {
|
||||
err = gerror.New("go.mod does not exist in current working directory")
|
||||
return
|
||||
}
|
||||
|
||||
var (
|
||||
goModContent = gfile.GetContents("go.mod")
|
||||
match, _ = gregex.MatchString(`^module\s+(.+)\s*`, goModContent)
|
||||
)
|
||||
|
||||
if len(match) > 1 {
|
||||
modName = gstr.Trim(match[1])
|
||||
} else {
|
||||
err = gerror.New("module name does not found in go.mod")
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// IsIndexPK 是否是主键
|
||||
func IsIndexPK(index string) bool {
|
||||
return gstr.ToUpper(index) == gstr.ToUpper(consts.GenCodesIndexPK)
|
||||
}
|
||||
|
||||
// IsIndexUNI 是否是唯一索引
|
||||
func IsIndexUNI(index string) bool {
|
||||
return gstr.ToUpper(index) == gstr.ToUpper(consts.GenCodesIndexUNI)
|
||||
}
|
||||
|
||||
// ParseDBConfigNodeLink 解析数据库连接配置
|
||||
func ParseDBConfigNodeLink(node *gdb.ConfigNode) *gdb.ConfigNode {
|
||||
const linkPattern = `(\w+):([\w\-\$]*):(.*?)@(\w+?)\((.+?)\)/{0,1}([^\?]*)\?{0,1}(.*)`
|
||||
const defaultCharset = `utf8`
|
||||
const defaultProtocol = `tcp`
|
||||
|
||||
var match []string
|
||||
if node.Link != "" {
|
||||
match, _ = gregex.MatchString(linkPattern, node.Link)
|
||||
if len(match) > 5 {
|
||||
node.Type = match[1]
|
||||
node.User = match[2]
|
||||
node.Pass = match[3]
|
||||
node.Protocol = match[4]
|
||||
array := gstr.Split(match[5], ":")
|
||||
if len(array) == 2 && node.Protocol != "file" {
|
||||
node.Host = array[0]
|
||||
node.Port = array[1]
|
||||
node.Name = match[6]
|
||||
} else {
|
||||
node.Name = match[5]
|
||||
}
|
||||
if len(match) > 6 && match[7] != "" {
|
||||
node.Extra = match[7]
|
||||
}
|
||||
node.Link = ""
|
||||
}
|
||||
}
|
||||
if node.Extra != "" {
|
||||
if m, _ := gstr.Parse(node.Extra); len(m) > 0 {
|
||||
_ = gconv.Struct(m, &node)
|
||||
}
|
||||
}
|
||||
// Default value checks.
|
||||
if node.Charset == "" {
|
||||
node.Charset = defaultCharset
|
||||
}
|
||||
if node.Protocol == "" {
|
||||
node.Protocol = defaultProtocol
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// ImportWebMethod 导入前端方法
|
||||
func ImportWebMethod(vs []string) string {
|
||||
vs = convert.UniqueSlice(vs)
|
||||
str := "{ " + strings.Join(vs, ", ") + " }"
|
||||
str = strings.TrimSuffix(str, ", ")
|
||||
return str
|
||||
}
|
||||
|
||||
// CheckTreeTableFields 检查树表字段
|
||||
func CheckTreeTableFields(columns []*sysin.GenCodesColumnListModel) (err error) {
|
||||
var fields = gutil.Copy(defaultTreeFields).([]string)
|
||||
for _, v := range columns {
|
||||
if validate.InSlice(fields, v.Name) {
|
||||
fields = convert.RemoveSlice(fields, v.Name)
|
||||
}
|
||||
}
|
||||
|
||||
if len(fields) > 0 {
|
||||
err = gerror.Newf("树表必须包含[%v]字段", strings.Join(fields, "、"))
|
||||
return err
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// CheckIllegalName 检查命名是否合理
|
||||
func CheckIllegalName(errPrefix string, names ...string) (err error) {
|
||||
reg, _ := regexp.Compile("^[a-z_][a-z0-9_]*$")
|
||||
for _, name := range names {
|
||||
name = strings.ToLower(name)
|
||||
match := reg.MatchString(name)
|
||||
if !match {
|
||||
err = gerror.Newf("%v存在格式不正确,必须全部小写且由字母、数字和下划线组成:%v", errPrefix, name)
|
||||
return
|
||||
}
|
||||
if strings.HasSuffix(name, "test") {
|
||||
err = gerror.Newf("%v当中不能以`test`结尾:%v", errPrefix, name)
|
||||
return
|
||||
}
|
||||
if StartsWithDigit(name) {
|
||||
err = gerror.Newf("%v当中不能以阿拉伯数字开头:%v", errPrefix, name)
|
||||
return
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func StartsWithDigit(s string) bool {
|
||||
r := []rune(s)
|
||||
if len(r) > 0 {
|
||||
return unicode.IsDigit(r[0])
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// IsPidName 是否是树表的pid字段
|
||||
func IsPidName(name string) bool {
|
||||
return name == "pid"
|
||||
}
|
||||
|
||||
func ToTSArray(vs []string) string {
|
||||
formattedStrings := make([]string, len(vs))
|
||||
for i, str := range vs {
|
||||
formattedStrings[i] = fmt.Sprintf("'%s'", str)
|
||||
}
|
||||
return fmt.Sprintf("[%s]", strings.Join(formattedStrings, ", "))
|
||||
}
|
||||
|
||||
func FormatGo(ctx context.Context, name, code string) (string, error) {
|
||||
path := GetTempGeneratePath(ctx) + "/" + name
|
||||
if err := gfile.PutContents(path, code); err != nil {
|
||||
return "", err
|
||||
}
|
||||
res, err := imports.Process(path, []byte(code), nil)
|
||||
if err != nil {
|
||||
err = gerror.Newf(`FormatGo error format "%s" go files: %v`, path, err)
|
||||
return "", err
|
||||
}
|
||||
return string(res), nil
|
||||
}
|
||||
|
||||
func FormatVue(code string) string {
|
||||
if formatted, ok := tryPrettierFormat(code, "vue"); ok {
|
||||
return formatted
|
||||
}
|
||||
|
||||
endTag := `</template>`
|
||||
vueLen := gstr.PosR(code, endTag)
|
||||
vueCode := code[:vueLen+len(endTag)]
|
||||
tsCode := code[vueLen+len(endTag):]
|
||||
|
||||
vueCode = gohtml.Format(vueCode)
|
||||
vueCode = formatVueTemplate(vueCode)
|
||||
tsCode = FormatTs(tsCode)
|
||||
return vueCode + tsCode
|
||||
}
|
||||
|
||||
func FormatTs(code string) string {
|
||||
if formatted, ok := tryPrettierFormat(code, "typescript"); ok {
|
||||
return formatted
|
||||
}
|
||||
code = replaceEmptyLinesWithSpace(code)
|
||||
code = formatTypeScript(code)
|
||||
return code + "\n"
|
||||
}
|
||||
|
||||
// tryPrettierFormat 尝试使用 Prettier 格式化代码
|
||||
func tryPrettierFormat(code string, parser string) (string, bool) {
|
||||
webDir := gfile.Abs("./web")
|
||||
prettierBin := gfile.Join(webDir, "node_modules", ".bin", "prettier")
|
||||
|
||||
if !gfile.Exists(prettierBin) {
|
||||
return "", false
|
||||
}
|
||||
|
||||
tmpFile := gfile.Temp(gtime.TimestampNanoStr()) + "." + getFileExt(parser)
|
||||
defer gfile.Remove(tmpFile)
|
||||
|
||||
if err := gfile.PutContents(tmpFile, code); err != nil {
|
||||
return "", false
|
||||
}
|
||||
|
||||
cmd := fmt.Sprintf("cd %s && %s --write %s 2>/dev/null", webDir, prettierBin, tmpFile)
|
||||
_, err := gproc.ShellExec(context.Background(), cmd)
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
|
||||
formatted := gfile.GetContents(tmpFile)
|
||||
if formatted == "" {
|
||||
return "", false
|
||||
}
|
||||
return formatted, true
|
||||
}
|
||||
|
||||
// getFileExt 根据 parser 类型返回文件扩展名
|
||||
func getFileExt(parser string) string {
|
||||
switch parser {
|
||||
case "vue":
|
||||
return "vue"
|
||||
case "typescript":
|
||||
return "ts"
|
||||
default:
|
||||
return "txt"
|
||||
}
|
||||
}
|
||||
|
||||
// formatVueTemplate 格式化 Vue 模板代码
|
||||
func formatVueTemplate(code string) string {
|
||||
lines := strings.Split(code, "\n")
|
||||
var result []string
|
||||
lastLineWasOpenTag := false
|
||||
|
||||
for _, line := range lines {
|
||||
trimmed := strings.TrimSpace(line)
|
||||
if lastLineWasOpenTag && trimmed == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
if strings.HasPrefix(trimmed, "<") && !strings.HasPrefix(trimmed, "</") &&
|
||||
!strings.HasSuffix(trimmed, "/>") && !strings.HasSuffix(trimmed, ">") &&
|
||||
!strings.HasPrefix(trimmed, "<!--") {
|
||||
lastLineWasOpenTag = true
|
||||
result = append(result, line)
|
||||
continue
|
||||
}
|
||||
|
||||
lastLineWasOpenTag = false
|
||||
if trimmed == "/>" {
|
||||
if len(result) > 0 {
|
||||
prevLine := result[len(result)-1]
|
||||
re := regexp.MustCompile(`^(\s*)`)
|
||||
matches := re.FindStringSubmatch(prevLine)
|
||||
if len(matches) > 1 {
|
||||
line = matches[1] + "/>"
|
||||
}
|
||||
}
|
||||
} else if strings.Contains(line, "/>") {
|
||||
re := regexp.MustCompile(`\s*/>`)
|
||||
line = re.ReplaceAllString(line, " />")
|
||||
}
|
||||
|
||||
if strings.HasPrefix(trimmed, "<") && !strings.HasPrefix(trimmed, "</") &&
|
||||
!strings.HasPrefix(trimmed, "<!--") && len(trimmed) > 100 {
|
||||
line = formatLongVueTag(line)
|
||||
}
|
||||
result = append(result, line)
|
||||
}
|
||||
return strings.Join(result, "\n")
|
||||
}
|
||||
|
||||
// formatLongVueTag 格式化过长的 Vue 标签
|
||||
func formatLongVueTag(line string) string {
|
||||
re := regexp.MustCompile(`\s+`)
|
||||
parts := strings.SplitN(line, ">", 2)
|
||||
if len(parts) == 2 {
|
||||
tagPart := re.ReplaceAllString(parts[0], " ")
|
||||
tagPart = strings.TrimSpace(tagPart)
|
||||
return tagPart + ">" + parts[1]
|
||||
}
|
||||
return line
|
||||
}
|
||||
|
||||
// formatTypeScript 格式化 TypeScript 代码
|
||||
func formatTypeScript(code string) string {
|
||||
lines := strings.Split(code, "\n")
|
||||
var result []string
|
||||
inClass := false
|
||||
lastWasField := false
|
||||
|
||||
for i, line := range lines {
|
||||
trimmed := strings.TrimSpace(line)
|
||||
if strings.HasPrefix(trimmed, "export class") {
|
||||
inClass = true
|
||||
result = append(result, line)
|
||||
continue
|
||||
}
|
||||
|
||||
if inClass && (strings.HasPrefix(trimmed, "constructor(") ||
|
||||
strings.HasPrefix(trimmed, "public ") && strings.Contains(trimmed, "(")) {
|
||||
if lastWasField && len(result) > 0 {
|
||||
result = append(result, "")
|
||||
}
|
||||
inClass = false
|
||||
lastWasField = false
|
||||
result = append(result, line)
|
||||
continue
|
||||
}
|
||||
|
||||
if inClass && strings.HasPrefix(trimmed, "public ") && strings.Contains(trimmed, "=") {
|
||||
if lastWasField && len(result) > 0 && strings.TrimSpace(result[len(result)-1]) == "" {
|
||||
result = result[:len(result)-1]
|
||||
}
|
||||
result = append(result, line)
|
||||
lastWasField = true
|
||||
continue
|
||||
}
|
||||
|
||||
if trimmed == "}" && lastWasField {
|
||||
result = append(result, "")
|
||||
lastWasField = false
|
||||
}
|
||||
|
||||
if trimmed == "" {
|
||||
if inClass && lastWasField {
|
||||
continue
|
||||
}
|
||||
if i > 0 && len(result) > 0 && strings.TrimSpace(result[len(result)-1]) == "" {
|
||||
continue
|
||||
}
|
||||
}
|
||||
result = append(result, line)
|
||||
}
|
||||
return strings.Join(result, "\n")
|
||||
}
|
||||
|
||||
func replaceEmptyLinesWithSpace(input string) string {
|
||||
re := regexp.MustCompile(`\n\s*\n\s*\n+`)
|
||||
result := re.ReplaceAllString(input, "\n\n")
|
||||
return result
|
||||
}
|
||||
|
||||
func GetTempGeneratePath(ctx context.Context) string {
|
||||
return gfile.Abs(gfile.Temp() + "/hotgo-generate/" + simple.AppName(ctx))
|
||||
}
|
||||
Reference in New Issue
Block a user