mirror of
https://github.com/bufanyun/hotgo.git
synced 2025-11-14 21:23:47 +08:00
发布v2.15.1版本,更新内容请查看:https://github.com/bufanyun/hotgo/blob/v2.0/docs/guide-zh-CN/start-update-log.md
This commit is contained in:
@@ -181,12 +181,12 @@ func setDefaultFormMode(field *sysin.GenCodesColumnListModel) {
|
||||
return
|
||||
}
|
||||
|
||||
if field.GoType == GoTypeString && field.Length >= 200 && field.Length <= 500 {
|
||||
if field.GoType == GoTypeString && field.Length >= 256 && field.Length <= 512 {
|
||||
field.FormMode = FormModeInputTextarea
|
||||
return
|
||||
}
|
||||
|
||||
if field.GoType == GoTypeString && field.Length > 500 {
|
||||
if field.GoType == GoTypeString && field.Length > 512 {
|
||||
field.FormMode = FormModeInputEditor
|
||||
return
|
||||
}
|
||||
|
||||
@@ -3,12 +3,12 @@
|
||||
// @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"
|
||||
)
|
||||
|
||||
// 字段映射关系
|
||||
@@ -109,6 +109,8 @@ const (
|
||||
FormModeCheckbox = "Checkbox" // 复选按钮
|
||||
FormModeSelect = "Select" // 单选下拉框
|
||||
FormModeSelectMultiple = "SelectMultiple" // 多选下拉框
|
||||
FormModeTreeSelect = "TreeSelect" // 树型选择
|
||||
FormModeCascader = "Cascader" // 级联选择
|
||||
FormModeUploadImage = "UploadImage" // 单图上传
|
||||
FormModeUploadImages = "UploadImages" // 多图上传
|
||||
FormModeUploadFile = "UploadFile" // 单文件上传
|
||||
@@ -116,12 +118,13 @@ const (
|
||||
FormModeSwitch = "Switch" // 开关
|
||||
FormModeRate = "Rate" // 评分
|
||||
FormModeCitySelector = "CitySelector" // 省市区选择
|
||||
FormModePidTreeSelect = "PidTreeSelect" // 树型上级选择,树表生成专用
|
||||
)
|
||||
|
||||
var FormModes = []string{
|
||||
FormModeInput, FormModeInputNumber, FormModeInputTextarea, FormModeInputEditor, FormModeInputDynamic,
|
||||
FormModeDate, FormModeDateRange, FormModeTime, FormModeTimeRange,
|
||||
FormModeRadio, FormModeCheckbox, FormModeSelect, FormModeSelectMultiple,
|
||||
FormModeRadio, FormModeCheckbox, FormModeSelect, FormModeSelectMultiple, FormModeTreeSelect, FormModeCascader,
|
||||
FormModeUploadImage, FormModeUploadImages, FormModeUploadFile, FormModeUploadFiles,
|
||||
FormModeSwitch,
|
||||
FormModeRate,
|
||||
@@ -142,6 +145,8 @@ var FormModeMap = map[string]string{
|
||||
FormModeCheckbox: "复选按钮",
|
||||
FormModeSelect: "单选下拉框",
|
||||
FormModeSelectMultiple: "多选下拉框",
|
||||
FormModeTreeSelect: "树型选择",
|
||||
FormModeCascader: "级联选择",
|
||||
FormModeUploadImage: "单图上传",
|
||||
FormModeUploadImages: "多图上传",
|
||||
FormModeUploadFile: "单文件上传",
|
||||
@@ -190,20 +195,20 @@ var FormRoleMap = map[string]string{
|
||||
|
||||
// 查询条件
|
||||
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(json_doc, val)" // JSON_CONTAINS(json_doc, val[, path]) // 判断是否包含某个json值
|
||||
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,
|
||||
@@ -214,6 +219,21 @@ var WhereModes = []string{WhereModeEq,
|
||||
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 {
|
||||
@@ -225,8 +245,17 @@ func IsNumberType(goType string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func HasColumn(masterFields []*sysin.GenCodesColumnListModel, column string) bool {
|
||||
for _, field := range masterFields {
|
||||
// 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.GoName == column {
|
||||
return true
|
||||
}
|
||||
@@ -234,29 +263,77 @@ func HasColumn(masterFields []*sysin.GenCodesColumnListModel, column string) boo
|
||||
return false
|
||||
}
|
||||
|
||||
func HasColumnWithFormMode(masterFields []*sysin.GenCodesColumnListModel, column string) bool {
|
||||
for _, field := range masterFields {
|
||||
if field.FormMode == column {
|
||||
func HasColumnWithFormMode(fields []*sysin.GenCodesColumnListModel, formMode string) bool {
|
||||
for _, field := range fields {
|
||||
if field.FormMode == formMode {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func HasMaxSort(masterFields []*sysin.GenCodesColumnListModel) bool {
|
||||
return HasColumn(masterFields, "Sort")
|
||||
func HasMaxSort(fields []*sysin.GenCodesColumnListModel) bool {
|
||||
return HasColumn(fields, "Sort")
|
||||
}
|
||||
|
||||
func HasStatus(headOps []string, masterFields []*sysin.GenCodesColumnListModel) bool {
|
||||
func HasStatus(headOps []string, fields []*sysin.GenCodesColumnListModel) bool {
|
||||
if !gstr.InArray(headOps, "status") {
|
||||
return false
|
||||
}
|
||||
return HasColumn(masterFields, "Status")
|
||||
return HasColumn(fields, "Status")
|
||||
}
|
||||
|
||||
func HasSwitch(headOps []string, masterFields []*sysin.GenCodesColumnListModel) bool {
|
||||
if !gstr.InArray(headOps, "switch") {
|
||||
return false
|
||||
}
|
||||
return HasColumnWithFormMode(masterFields, "Switch")
|
||||
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
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ package views
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/gogf/gf/v2/container/gvar"
|
||||
"github.com/gogf/gf/v2/database/gdb"
|
||||
"github.com/gogf/gf/v2/errors/gerror"
|
||||
"github.com/gogf/gf/v2/frame/g"
|
||||
@@ -17,12 +18,13 @@ import (
|
||||
"hotgo/internal/consts"
|
||||
"hotgo/internal/dao"
|
||||
"hotgo/internal/library/hggen/internal/cmd/gendao"
|
||||
"hotgo/internal/library/hggen/internal/utility/utils"
|
||||
"hotgo/internal/library/hgorm"
|
||||
"hotgo/internal/model"
|
||||
"hotgo/internal/model/input/sysin"
|
||||
"hotgo/internal/service"
|
||||
"hotgo/utility/convert"
|
||||
"hotgo/utility/file"
|
||||
"hotgo/utility/tree"
|
||||
"runtime"
|
||||
"strings"
|
||||
)
|
||||
@@ -32,18 +34,41 @@ var Curd = gCurd{}
|
||||
type gCurd struct{}
|
||||
|
||||
type CurdStep struct {
|
||||
HasMaxSort bool `json:"hasMaxSort"`
|
||||
HasAdd bool `json:"hasAdd"`
|
||||
HasBatchDel bool `json:"hasBatchDel"`
|
||||
HasExport bool `json:"hasExport"`
|
||||
HasNotFilterAuth bool `json:"hasNotFilterAuth"`
|
||||
HasEdit bool `json:"hasEdit"`
|
||||
HasDel bool `json:"hasDel"`
|
||||
HasView bool `json:"hasView"`
|
||||
HasStatus bool `json:"hasStatus"`
|
||||
HasSwitch bool `json:"hasSwitch"`
|
||||
HasCheck bool `json:"hasCheck"`
|
||||
HasMenu bool `json:"hasMenu"`
|
||||
HasMaxSort bool // 最大排序
|
||||
HasAdd bool // 表单添加
|
||||
HasBatchDel bool // 批量删除
|
||||
HasExport bool // 表格导出
|
||||
HasNotFilterAuth bool // 不过滤认证权限
|
||||
HasEdit bool // 表单编辑
|
||||
HasDel bool // 删除
|
||||
HasView bool // 查看详情
|
||||
HasStatus bool // 修改状态
|
||||
HasSwitch bool // 数值开关
|
||||
HasCheck bool // 勾选列
|
||||
HasMenu bool // 菜单权限
|
||||
IsTreeTable bool // 树型列表
|
||||
IsOptionTreeTable bool // 选项式树型列表
|
||||
HasRules bool // 表单验证规则
|
||||
HasRulesValidator bool // 表单验证器
|
||||
HasSearchForm bool // 列表搜索
|
||||
HasDict bool // 字典
|
||||
HasFuncDict bool // 注册方法字典
|
||||
HasQueryMemberSummary bool // 查询用户摘要
|
||||
HasHookMemberSummary bool // hook用户摘要
|
||||
ImportModel ImportModel // 公用导包 - model.ts
|
||||
ActionColumnWidth int64 // 列表操作栏宽度
|
||||
IsAddon bool // 是否是插件
|
||||
}
|
||||
|
||||
// ImportModel 导包 - model.ts
|
||||
type ImportModel struct {
|
||||
NaiveUI []string
|
||||
UtilsIs []string
|
||||
UtilsUrl []string
|
||||
UtilsDate []string
|
||||
UtilsValidate []string
|
||||
UtilsHotGo []string
|
||||
UtilsIndex []string
|
||||
}
|
||||
|
||||
type CurdOptionsJoin struct {
|
||||
@@ -63,18 +88,52 @@ type CurdOptionsMenu struct {
|
||||
Sort int `json:"sort"`
|
||||
}
|
||||
|
||||
type OptionsTree struct {
|
||||
TitleColumn string `json:"titleColumn"`
|
||||
StyleType int `json:"styleType"`
|
||||
TitleField *sysin.GenCodesColumnListModel
|
||||
}
|
||||
|
||||
// PresetStep 预设生成流程参数
|
||||
type PresetStep struct {
|
||||
FormGridCols int `json:"formGridCols" dc:"表单显示的栅格数量"`
|
||||
}
|
||||
|
||||
type CurdOptions struct {
|
||||
AutoOps []string `json:"autoOps"`
|
||||
ColumnOps []string `json:"columnOps"`
|
||||
HeadOps []string `json:"headOps"`
|
||||
Join []*CurdOptionsJoin `json:"join"`
|
||||
Menu *CurdOptionsMenu `json:"menu"`
|
||||
Tree *OptionsTree `json:"tree"`
|
||||
TemplateGroup string `json:"templateGroup"`
|
||||
ApiPrefix string `json:"apiPrefix"`
|
||||
ImportWebApi string `json:"importWebApi"`
|
||||
FuncDict *FuncDict `json:"funcDict"`
|
||||
PresetStep *PresetStep `json:"presetStep"`
|
||||
Step *CurdStep // 转换后的流程控制条件
|
||||
DictOps CurdOptionsDict // 字典选项
|
||||
dictMap g.Map // 字典选项 -> 字段映射关系
|
||||
}
|
||||
|
||||
type FuncDict struct {
|
||||
ValueColumn string // 选项值
|
||||
LabelColumn string //选项名称
|
||||
Value *sysin.GenCodesColumnListModel
|
||||
Label *sysin.GenCodesColumnListModel
|
||||
}
|
||||
|
||||
type CurdOptionsDict struct {
|
||||
Has bool
|
||||
Types []string
|
||||
Schemas []*OptionsSchemasField
|
||||
}
|
||||
|
||||
type OptionsSchemasField struct {
|
||||
Field string
|
||||
Type string
|
||||
}
|
||||
|
||||
type CurdPreviewInput struct {
|
||||
In *sysin.GenCodesPreviewInp // 提交参数
|
||||
DaoConfig gendao.CGenDaoInput // 生成dao配置
|
||||
@@ -98,31 +157,44 @@ func (l *gCurd) initInput(ctx context.Context, in *CurdPreviewInput) (err error)
|
||||
in.content = new(sysin.GenCodesPreviewModel)
|
||||
in.content.Views = make(map[string]*sysin.GenFile)
|
||||
|
||||
// 加载主表配置
|
||||
if err = in.In.MasterColumns.Scan(&in.masterFields); err != nil {
|
||||
return
|
||||
// 初始化生成选项
|
||||
if err = initOptions(in); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(in.masterFields) == 0 {
|
||||
if in.masterFields, err = DoTableColumns(ctx, &sysin.GenCodesColumnListInp{Name: in.In.DbName, Table: in.In.TableName}, in.DaoConfig); err != nil {
|
||||
return
|
||||
}
|
||||
// 初始化表字段配置
|
||||
if err = initTableField(ctx, in); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 主键属性
|
||||
in.pk = l.getPkField(in)
|
||||
if in.pk == nil {
|
||||
return gerror.New("initInput no primary key is set in the table!")
|
||||
}
|
||||
|
||||
// 加载选项
|
||||
if err = in.In.Options.Scan(&in.options); err != nil {
|
||||
return
|
||||
// 初始化树表
|
||||
if err = initTableTree(in); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
initStep(in)
|
||||
in.options.dictMap = make(g.Map)
|
||||
|
||||
// 初始化方法字典
|
||||
if err = initFuncDict(in); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 初始化生成模板
|
||||
if err = initTemplate(in); err != nil {
|
||||
return err
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func initOptions(in *CurdPreviewInput) (err error) {
|
||||
if err = in.In.Options.Scan(&in.options); err != nil {
|
||||
return
|
||||
}
|
||||
in.options.dictMap = make(g.Map)
|
||||
return
|
||||
}
|
||||
|
||||
func initTemplate(in *CurdPreviewInput) (err error) {
|
||||
if len(in.Config.Application.Crud.Templates)-1 < in.In.GenTemplate {
|
||||
return gerror.New("没有找到生成模板的配置,请检查!")
|
||||
}
|
||||
@@ -141,20 +213,126 @@ func (l *gCurd) initInput(ctx context.Context, in *CurdPreviewInput) (err error)
|
||||
return
|
||||
}
|
||||
|
||||
func initFuncDict(in *CurdPreviewInput) (err error) {
|
||||
if !in.options.Step.HasFuncDict || in.options.FuncDict == nil {
|
||||
return
|
||||
}
|
||||
|
||||
if len(in.options.FuncDict.LabelColumn) == 0 || len(in.options.FuncDict.ValueColumn) == 0 {
|
||||
err = gerror.New("生成字典选项必须设置选项值和选项名称")
|
||||
return err
|
||||
}
|
||||
|
||||
for _, field := range in.masterFields {
|
||||
if field.Name == in.options.FuncDict.ValueColumn {
|
||||
in.options.FuncDict.Value = field
|
||||
}
|
||||
|
||||
if field.Name == in.options.FuncDict.LabelColumn {
|
||||
in.options.FuncDict.Label = field
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func initTableField(ctx context.Context, in *CurdPreviewInput) (err error) {
|
||||
// 加载主表配置
|
||||
if err = in.In.MasterColumns.Scan(&in.masterFields); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if len(in.masterFields) == 0 {
|
||||
if in.masterFields, err = DoTableColumns(ctx, &sysin.GenCodesColumnListInp{Name: in.In.DbName, Table: in.In.TableName}, in.DaoConfig); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// 主键属性
|
||||
in.pk = getPkField(in)
|
||||
if in.pk == nil {
|
||||
return gerror.New("initInput no primary key is set in the table!")
|
||||
}
|
||||
|
||||
in.masterFields = ReviseFields(in.masterFields)
|
||||
|
||||
// 检查表命名
|
||||
var names = []string{in.In.DaoName}
|
||||
for _, v := range in.options.Join {
|
||||
v.Columns = ReviseFields(v.Columns)
|
||||
names = append(names, v.DaoName)
|
||||
}
|
||||
if err = CheckIllegalName("数据库表名", names...); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if err = CheckIllegalName("实体命名", in.In.VarName); err != nil {
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func initTableTree(in *CurdPreviewInput) (err error) {
|
||||
// 检查树表字段
|
||||
if in.In.GenType == consts.GenCodesTypeTree {
|
||||
if err = CheckTreeTableFields(in.masterFields); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 解析选项树名称字段
|
||||
has := false
|
||||
for _, field := range in.masterFields {
|
||||
if in.options.Tree.TitleColumn == field.Name {
|
||||
in.options.Tree.TitleField = field
|
||||
has = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !has {
|
||||
err = gerror.New("请选择一个有效的树名称字段")
|
||||
return
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func initStep(in *CurdPreviewInput) {
|
||||
in.options.Step = new(CurdStep)
|
||||
in.options.Step.HasMaxSort = HasMaxSort(in.masterFields)
|
||||
in.options.Step.HasAdd = gstr.InArray(in.options.HeadOps, "add")
|
||||
in.options.Step.HasBatchDel = gstr.InArray(in.options.HeadOps, "batchDel")
|
||||
in.options.Step.HasBatchDel = gstr.InArray(in.options.HeadOps, "batchDel") && gstr.InArray(in.options.ColumnOps, "check")
|
||||
in.options.Step.HasExport = gstr.InArray(in.options.HeadOps, "export")
|
||||
in.options.Step.HasNotFilterAuth = gstr.InArray(in.options.ColumnOps, "notFilterAuth")
|
||||
in.options.Step.HasEdit = gstr.InArray(in.options.ColumnOps, "edit")
|
||||
in.options.Step.HasDel = gstr.InArray(in.options.ColumnOps, "del")
|
||||
in.options.Step.HasView = gstr.InArray(in.options.ColumnOps, "view")
|
||||
in.options.Step.HasStatus = HasStatus(in.options.ColumnOps, in.masterFields)
|
||||
in.options.Step.HasSwitch = HasSwitch(in.options.ColumnOps, in.masterFields)
|
||||
in.options.Step.HasSwitch = HasSwitch(in.masterFields)
|
||||
in.options.Step.HasCheck = gstr.InArray(in.options.ColumnOps, "check")
|
||||
in.options.Step.HasMenu = gstr.InArray(in.options.AutoOps, "genMenuPermissions")
|
||||
in.options.Step.HasQueryMemberSummary = HasQueryMemberSummary(in.masterFields)
|
||||
in.options.Step.HasHookMemberSummary = HasHookMemberSummary(in.masterFields)
|
||||
in.options.Step.IsTreeTable = in.In.GenType == consts.GenCodesTypeTree
|
||||
if in.options.Step.IsTreeTable {
|
||||
in.options.Step.IsOptionTreeTable = in.options.Tree.StyleType == consts.GenCodesTreeStyleTypeOption
|
||||
}
|
||||
in.options.Step.HasFuncDict = gstr.InArray(in.options.AutoOps, "genFuncDict")
|
||||
in.options.Step.IsAddon = in.Config.Application.Crud.Templates[in.In.GenTemplate].IsAddon
|
||||
if in.options.PresetStep.FormGridCols < 1 {
|
||||
in.options.PresetStep.FormGridCols = 1
|
||||
}
|
||||
}
|
||||
|
||||
// getPkField 获取主键
|
||||
func getPkField(in *CurdPreviewInput) *sysin.GenCodesColumnListModel {
|
||||
if len(in.masterFields) == 0 {
|
||||
panic("getPkField masterFields uninitialized.")
|
||||
}
|
||||
for _, field := range in.masterFields {
|
||||
if IsIndexPK(field.Index) {
|
||||
return field
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (l *gCurd) loadView(ctx context.Context, in *CurdPreviewInput) (err error) {
|
||||
@@ -170,14 +348,14 @@ func (l *gCurd) loadView(ctx context.Context, in *CurdPreviewInput) (err error)
|
||||
|
||||
now := gtime.Now()
|
||||
view.BindFuncMap(g.Map{
|
||||
"NowYear": now.Year, // 当前年
|
||||
"ToLower": strings.ToLower, // 全部小写
|
||||
"LcFirst": gstr.LcFirst, // 首字母小写
|
||||
"UcFirst": gstr.UcFirst, // 首字母大写
|
||||
"NowYear": now.Year, // 当前年
|
||||
"ToLower": strings.ToLower, // 全部小写
|
||||
"LcFirst": gstr.LcFirst, // 首字母小写
|
||||
"UcFirst": gstr.UcFirst, // 首字母大写
|
||||
"ToTSArray": ToTSArray, // 转为ts数组格式
|
||||
})
|
||||
|
||||
dictOptions, err := l.generateWebModelDictOptions(ctx, in)
|
||||
if err != nil {
|
||||
if err = l.generateWebModelDictOptions(ctx, in); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -193,9 +371,9 @@ func (l *gCurd) loadView(ctx context.Context, in *CurdPreviewInput) (err error)
|
||||
importService = "hotgo/addons/" + in.In.AddonName + "/service"
|
||||
}
|
||||
|
||||
importWebApi := "@/api/" + gstr.LcFirst(in.In.VarName)
|
||||
in.options.ImportWebApi = "@/api/" + gstr.LcFirst(in.In.VarName)
|
||||
if temp.IsAddon {
|
||||
importWebApi = "@/api/addons/" + in.In.AddonName + "/" + gstr.LcFirst(in.In.VarName)
|
||||
in.options.ImportWebApi = "@/api/addons/" + in.In.AddonName + "/" + gstr.LcFirst(in.In.VarName)
|
||||
}
|
||||
|
||||
componentPrefix := gstr.LcFirst(in.In.VarName)
|
||||
@@ -216,12 +394,12 @@ func (l *gCurd) loadView(ctx context.Context, in *CurdPreviewInput) (err error)
|
||||
"masterFields": in.masterFields, // 主表字段
|
||||
"pk": in.pk, // 主键属性
|
||||
"options": in.options, // 提交选项
|
||||
"dictOptions": dictOptions, // web字典选项
|
||||
"dictOptions": in.options.DictOps, // web字典选项
|
||||
"importApi": importApi, // 导入goApi包
|
||||
"importInput": importInput, // 导入input包
|
||||
"importController": importController, // 导入控制器包
|
||||
"importService": importService, // 导入业务服务
|
||||
"importWebApi": importWebApi, // 导入webApi
|
||||
"importWebApi": in.options.ImportWebApi, // 导入webApi
|
||||
"apiPrefix": in.options.ApiPrefix, // api前缀
|
||||
"componentPrefix": componentPrefix, // vue子组件前缀
|
||||
})
|
||||
@@ -231,6 +409,7 @@ func (l *gCurd) loadView(ctx context.Context, in *CurdPreviewInput) (err error)
|
||||
}
|
||||
|
||||
func (l *gCurd) DoBuild(ctx context.Context, in *CurdBuildInput) (err error) {
|
||||
st := gtime.Now()
|
||||
preview, err := l.DoPreview(ctx, in.PreviewIn)
|
||||
if err != nil {
|
||||
return
|
||||
@@ -296,10 +475,6 @@ func (l *gCurd) DoBuild(ctx context.Context, in *CurdBuildInput) (err error) {
|
||||
if err = gfile.PutContents(vi.Path, strings.TrimSpace(vi.Content)); err != nil {
|
||||
return gerror.Newf("writing content to '%s' failed: %v", vi.Path, err)
|
||||
}
|
||||
|
||||
if gstr.Str(vi.Path, `.`) == ".go" {
|
||||
utils.GoFmt(vi.Path)
|
||||
}
|
||||
}
|
||||
|
||||
// 后置操作
|
||||
@@ -312,6 +487,7 @@ func (l *gCurd) DoBuild(ctx context.Context, in *CurdBuildInput) (err error) {
|
||||
}
|
||||
}
|
||||
}
|
||||
g.Log().Debugf(ctx, "generate code operation completed, %vms", gtime.Now().Sub(st).Milliseconds())
|
||||
return
|
||||
}
|
||||
|
||||
@@ -386,6 +562,11 @@ func (l *gCurd) generateApiContent(ctx context.Context, in *CurdPreviewInput) (e
|
||||
return err
|
||||
}
|
||||
|
||||
genFile.Content, err = FormatGo(ctx, name, genFile.Content)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
genFile.Path = file.MergeAbs(in.Config.Application.Crud.Templates[in.In.GenTemplate].ApiPath, strings.ToLower(in.In.VarName), strings.ToLower(in.In.VarName)+".go")
|
||||
genFile.Meth = consts.GenCodesBuildMethCreate
|
||||
if gfile.Exists(genFile.Path) {
|
||||
@@ -417,6 +598,12 @@ func (l *gCurd) generateInputContent(ctx context.Context, in *CurdPreviewInput)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
genFile.Content, err = FormatGo(ctx, name, genFile.Content)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
genFile.Path = file.MergeAbs(in.Config.Application.Crud.Templates[in.In.GenTemplate].InputPath, convert.CamelCaseToUnderline(in.In.VarName)+".go")
|
||||
genFile.Meth = consts.GenCodesBuildMethCreate
|
||||
if gfile.Exists(genFile.Path) {
|
||||
@@ -443,6 +630,12 @@ func (l *gCurd) generateControllerContent(ctx context.Context, in *CurdPreviewIn
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
genFile.Content, err = FormatGo(ctx, name, genFile.Content)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
genFile.Path = file.MergeAbs(in.Config.Application.Crud.Templates[in.In.GenTemplate].ControllerPath, convert.CamelCaseToUnderline(in.In.VarName)+".go")
|
||||
genFile.Meth = consts.GenCodesBuildMethCreate
|
||||
if gfile.Exists(genFile.Path) {
|
||||
@@ -473,6 +666,12 @@ func (l *gCurd) generateLogicContent(ctx context.Context, in *CurdPreviewInput)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
genFile.Content, err = FormatGo(ctx, name, genFile.Content)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
genFile.Path = file.MergeAbs(in.Config.Application.Crud.Templates[in.In.GenTemplate].LogicPath, convert.CamelCaseToUnderline(in.In.VarName)+".go")
|
||||
genFile.Meth = consts.GenCodesBuildMethCreate
|
||||
if gfile.Exists(genFile.Path) {
|
||||
@@ -499,6 +698,11 @@ func (l *gCurd) generateRouterContent(ctx context.Context, in *CurdPreviewInput)
|
||||
return err
|
||||
}
|
||||
|
||||
genFile.Content, err = FormatGo(ctx, name, genFile.Content)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
genFile.Path = file.MergeAbs(in.Config.Application.Crud.Templates[in.In.GenTemplate].RouterPath, convert.CamelCaseToUnderline(in.In.VarName)+".go")
|
||||
genFile.Meth = consts.GenCodesBuildMethCreate
|
||||
if gfile.Exists(genFile.Path) {
|
||||
@@ -525,6 +729,8 @@ func (l *gCurd) generateWebApiContent(ctx context.Context, in *CurdPreviewInput)
|
||||
return err
|
||||
}
|
||||
|
||||
genFile.Content = FormatTs(genFile.Content)
|
||||
|
||||
genFile.Path = file.MergeAbs(in.Config.Application.Crud.Templates[in.In.GenTemplate].WebApiPath, gstr.LcFirst(in.In.VarName), "index.ts")
|
||||
genFile.Meth = consts.GenCodesBuildMethCreate
|
||||
if gfile.Exists(genFile.Path) {
|
||||
@@ -556,6 +762,8 @@ func (l *gCurd) generateWebModelContent(ctx context.Context, in *CurdPreviewInpu
|
||||
return
|
||||
}
|
||||
|
||||
genFile.Content = FormatTs(genFile.Content)
|
||||
|
||||
genFile.Path = file.MergeAbs(in.Config.Application.Crud.Templates[in.In.GenTemplate].WebViewsPath, gstr.LcFirst(in.In.VarName), "model.ts")
|
||||
genFile.Meth = consts.GenCodesBuildMethCreate
|
||||
if gfile.Exists(genFile.Path) {
|
||||
@@ -586,6 +794,8 @@ func (l *gCurd) generateWebIndexContent(ctx context.Context, in *CurdPreviewInpu
|
||||
return err
|
||||
}
|
||||
|
||||
genFile.Content = FormatVue(genFile.Content)
|
||||
|
||||
genFile.Path = file.MergeAbs(in.Config.Application.Crud.Templates[in.In.GenTemplate].WebViewsPath, gstr.LcFirst(in.In.VarName), "index.vue")
|
||||
genFile.Meth = consts.GenCodesBuildMethCreate
|
||||
if gfile.Exists(genFile.Path) {
|
||||
@@ -616,6 +826,8 @@ func (l *gCurd) generateWebEditContent(ctx context.Context, in *CurdPreviewInput
|
||||
return err
|
||||
}
|
||||
|
||||
genFile.Content = FormatVue(genFile.Content)
|
||||
|
||||
genFile.Path = file.MergeAbs(in.Config.Application.Crud.Templates[in.In.GenTemplate].WebViewsPath, gstr.LcFirst(in.In.VarName), "edit.vue")
|
||||
genFile.Meth = consts.GenCodesBuildMethCreate
|
||||
if gfile.Exists(genFile.Path) {
|
||||
@@ -651,6 +863,8 @@ func (l *gCurd) generateWebViewContent(ctx context.Context, in *CurdPreviewInput
|
||||
return err
|
||||
}
|
||||
|
||||
genFile.Content = FormatVue(genFile.Content)
|
||||
|
||||
genFile.Path = file.MergeAbs(in.Config.Application.Crud.Templates[in.In.GenTemplate].WebViewsPath, gstr.LcFirst(in.In.VarName), "view.vue")
|
||||
genFile.Meth = consts.GenCodesBuildMethCreate
|
||||
if gfile.Exists(genFile.Path) {
|
||||
@@ -683,6 +897,11 @@ func (l *gCurd) generateSqlContent(ctx context.Context, in *CurdPreviewInput) (e
|
||||
genFile = new(sysin.GenFile)
|
||||
)
|
||||
|
||||
menus, err := service.AdminMenu().GetFastList(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
tplData["dirPid"], tplData["dirLevel"], tplData["dirTree"], err = hgorm.AutoUpdateTree(ctx, &dao.AdminMenu, 0, int64(in.options.Menu.Pid))
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -692,9 +911,30 @@ func (l *gCurd) generateSqlContent(ctx context.Context, in *CurdPreviewInput) (e
|
||||
tplData["btnLevel"] = tplData["dirLevel"].(int) + 2
|
||||
tplData["sortLevel"] = tplData["dirLevel"].(int) + 3
|
||||
|
||||
pageRedirect := ""
|
||||
if in.options.Menu.Pid > 0 {
|
||||
tplData["mainComponent"] = "ParentLayout"
|
||||
menu, ok := menus[int64(in.options.Menu.Pid)]
|
||||
if !ok {
|
||||
err = gerror.New("选择的上级菜单不存在")
|
||||
return
|
||||
}
|
||||
for _, id := range tree.GetIds(menu.Tree) {
|
||||
if v, ok2 := menus[id]; ok2 {
|
||||
if !gstr.HasSuffix(pageRedirect, "/") && !gstr.HasPrefix(v.Path, "/") {
|
||||
pageRedirect += "/"
|
||||
}
|
||||
pageRedirect += v.Path
|
||||
}
|
||||
}
|
||||
|
||||
if !gstr.HasSuffix(pageRedirect, "/") && !gstr.HasPrefix(menu.Path, "/") {
|
||||
pageRedirect += "/"
|
||||
}
|
||||
pageRedirect += menu.Path
|
||||
}
|
||||
pageRedirect += "/" + gstr.LcFirst(in.In.VarName) + "/index"
|
||||
tplData["pageRedirect"] = pageRedirect
|
||||
|
||||
genFile.Path = file.MergeAbs(in.Config.Application.Crud.Templates[in.In.GenTemplate].SqlPath, convert.CamelCaseToUnderline(in.In.VarName)+"_menu.sql")
|
||||
genFile.Meth = consts.GenCodesBuildMethCreate
|
||||
@@ -708,6 +948,48 @@ func (l *gCurd) generateSqlContent(ctx context.Context, in *CurdPreviewInput) (e
|
||||
genFile.Required = false
|
||||
}
|
||||
|
||||
// 需要生成时,检查菜单命名是否存在
|
||||
if genFile.Meth == consts.GenCodesBuildMethCreate {
|
||||
menuNamePrefix := gstr.LcFirst(in.In.VarName)
|
||||
menuNames := []string{menuNamePrefix, menuNamePrefix + "Index"}
|
||||
if in.options.Step.HasEdit {
|
||||
menuNames = append(menuNames, menuNamePrefix+"Edit")
|
||||
menuNames = append(menuNames, menuNamePrefix+"View")
|
||||
}
|
||||
if in.options.Step.HasView {
|
||||
menuNames = append(menuNames, menuNamePrefix+"View")
|
||||
}
|
||||
if in.options.Step.HasMaxSort {
|
||||
menuNames = append(menuNames, menuNamePrefix+"MaxSort")
|
||||
}
|
||||
if in.options.Step.HasDel {
|
||||
menuNames = append(menuNames, menuNamePrefix+"Delete")
|
||||
}
|
||||
if in.options.Step.HasStatus {
|
||||
menuNames = append(menuNames, menuNamePrefix+"Status")
|
||||
}
|
||||
if in.options.Step.HasSwitch {
|
||||
menuNames = append(menuNames, menuNamePrefix+"Switch")
|
||||
}
|
||||
if in.options.Step.HasExport {
|
||||
menuNames = append(menuNames, menuNamePrefix+"Export")
|
||||
}
|
||||
if in.options.Step.IsTreeTable {
|
||||
menuNames = append(menuNames, menuNamePrefix+"TreeOption")
|
||||
}
|
||||
|
||||
menuNames = convert.UniqueSlice(menuNames)
|
||||
hasMenus, err := service.AdminMenu().Model(ctx).Fields("name").WhereIn("name", menuNames).Array()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(hasMenus) > 0 {
|
||||
err = gerror.Newf("要生成的菜单中有已存在的路由别名,请检查并删除:%v", strings.Join(gvar.New(hasMenus).Strings(), `、`))
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
tplData["generatePath"] = genFile.Path
|
||||
genFile.Content, err = in.view.Parse(ctx, name+".template", tplData)
|
||||
if err != nil {
|
||||
|
||||
@@ -28,6 +28,7 @@ const (
|
||||
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"
|
||||
)
|
||||
|
||||
@@ -39,21 +40,79 @@ func (l *gCurd) inputTplData(ctx context.Context, in *CurdPreviewInput) (data g.
|
||||
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++
|
||||
}
|
||||
}
|
||||
|
||||
tw := tablewriter.NewWriter(buffer)
|
||||
tw.SetBorder(false)
|
||||
tw.SetRowLine(false)
|
||||
tw.SetAutoWrapText(false)
|
||||
tw.SetColumnSeparator("")
|
||||
tw.AppendBulk(array)
|
||||
tw.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(field, inputType)
|
||||
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++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 关联表
|
||||
@@ -63,7 +122,7 @@ func (l *gCurd) generateInputListColumns(ctx context.Context, in *CurdPreviewInp
|
||||
continue
|
||||
}
|
||||
for _, field := range v.Columns {
|
||||
row := l.generateStructFieldDefinition(field, inputType)
|
||||
row := l.generateStructFieldDefinition(in, field, inputType, false)
|
||||
if row != nil {
|
||||
array[index] = row
|
||||
index++
|
||||
@@ -92,43 +151,62 @@ func (l *gCurd) generateInputListColumns(ctx context.Context, in *CurdPreviewInp
|
||||
}
|
||||
|
||||
// generateStructFieldForModel generates and returns the attribute definition for specified field.
|
||||
func (l *gCurd) generateStructFieldDefinition(field *sysin.GenCodesColumnListModel, inputType int) []string {
|
||||
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
|
||||
}
|
||||
|
||||
isQuery := false
|
||||
|
||||
switch inputType {
|
||||
case InputTypeListInp:
|
||||
if !field.IsQuery {
|
||||
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 {
|
||||
result = append(result, " #"+field.GoType)
|
||||
// 查询用户摘要时,固定接收字符串类型
|
||||
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 !field.IsList {
|
||||
// 主表的主键
|
||||
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
|
||||
}
|
||||
|
||||
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 InputTypeExportModel:
|
||||
if !field.IsExport {
|
||||
return nil
|
||||
}
|
||||
|
||||
result = append(result, " #"+field.GoType)
|
||||
result = append(result, " #"+fmt.Sprintf(tagKey+`json:"%s"`, field.TsName))
|
||||
result = append(result, " #"+fmt.Sprintf(`dc:"%s"`+tagKey, descriptionTag))
|
||||
addResult()
|
||||
case InputTypeEditInpValidator:
|
||||
if !field.IsEdit {
|
||||
return nil
|
||||
@@ -150,18 +228,23 @@ func (l *gCurd) generateStructFieldDefinition(field *sysin.GenCodesColumnListMod
|
||||
if !field.IsEdit && field.GoName != "UpdatedBy" {
|
||||
return nil
|
||||
}
|
||||
|
||||
result = append(result, " #"+field.GoType)
|
||||
result = append(result, " #"+fmt.Sprintf(tagKey+`json:"%s"`, field.TsName))
|
||||
result = append(result, " #"+fmt.Sprintf(`dc:"%s"`+tagKey, descriptionTag))
|
||||
addResult()
|
||||
case InputTypeInsertFields:
|
||||
if !field.IsEdit && field.GoName != "CreatedBy" {
|
||||
return nil
|
||||
}
|
||||
|
||||
result = append(result, " #"+field.GoType)
|
||||
result = append(result, " #"+fmt.Sprintf(tagKey+`json:"%s"`, field.TsName))
|
||||
result = append(result, " #"+fmt.Sprintf(`dc:"%s"`+tagKey, descriptionTag))
|
||||
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")
|
||||
}
|
||||
|
||||
@@ -16,22 +16,20 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
LogicWhereComments = "\n\t// 查询%s\n"
|
||||
LogicWhereNoSupport = "\t// TODO 暂不支持生成[ %s ]查询方式,请自行补充此处代码!"
|
||||
LogicListSimpleSelect = "\tfields, err := hgorm.GenSelect(ctx, sysin.%sListModel{}, dao.%s)\n\tif err != nil {\n\t\treturn\n\t}"
|
||||
LogicListJoinSelect = "\t// 关联表select\n\tfields, err := hgorm.GenJoinSelect(ctx, %sin.%sListModel{}, &dao.%s, []*hgorm.Join{\n%v\t})\n\n\tif err != nil {\n\t\terr = gerror.Wrap(err, \"获取%s关联字段失败,请稍后重试!\")\n\t\treturn\n\t}"
|
||||
LogicListJoinOnRelation = "\t// 关联表%s\n\tmod = mod.%s(hgorm.GenJoinOnRelation(\n\t\tdao.%s.Table(), dao.%s.Columns().%s, // 主表表名,关联字段\n\t\tdao.%s.Table(), \"%s\", dao.%s.Columns().%s, // 关联表表名,别名,关联字段\n\t)...)\n\n"
|
||||
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).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.Id); 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}"
|
||||
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).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.Id); 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}"
|
||||
)
|
||||
|
||||
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)
|
||||
@@ -113,76 +111,109 @@ func (l *gCurd) generateLogicEdit(ctx context.Context, in *CurdPreviewInput) g.M
|
||||
}
|
||||
|
||||
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(dao." + in.In.DaoName + ".Columns().Sort).")
|
||||
buffer.WriteString("OrderAsc(" + statement + "dao." + in.In.DaoName + ".Columns().Sort).")
|
||||
}
|
||||
buffer.WriteString("OrderDesc(dao." + in.In.DaoName + ".Columns()." + in.pk.GoName + ")")
|
||||
buffer.WriteString("OrderDesc(" + statement + "dao." + in.In.DaoName + ".Columns()." + in.pk.GoName + ")")
|
||||
return buffer.String()
|
||||
}
|
||||
|
||||
func (l *gCurd) generateLogicListJoin(ctx context.Context, in *CurdPreviewInput) g.Map {
|
||||
var data = make(g.Map)
|
||||
data["link"] = ""
|
||||
func (l *gCurd) generateLogicListJoin(ctx context.Context, in *CurdPreviewInput) (link string) {
|
||||
connector := `"="`
|
||||
if hasEffectiveJoins(in.options.Join) {
|
||||
var (
|
||||
selectBuffer = bytes.NewBuffer(nil)
|
||||
linkBuffer = bytes.NewBuffer(nil)
|
||||
joinSelectRows string
|
||||
)
|
||||
|
||||
linkBuffer := bytes.NewBuffer(nil)
|
||||
for _, join := range in.options.Join {
|
||||
if isEffectiveJoin(join) {
|
||||
joinSelectRows = joinSelectRows + fmt.Sprintf("\t\t{Dao: &dao.%s, Alias: \"%s\"},\n", join.DaoName, join.Alias)
|
||||
linkBuffer.WriteString(fmt.Sprintf(LogicListJoinOnRelation, join.Alias, consts.GenCodesJoinLinkMap[join.LinkMode], in.In.DaoName, in.In.DaoName, gstr.CaseCamel(join.MasterField), join.DaoName, join.Alias, join.DaoName, gstr.CaseCamel(join.Field)))
|
||||
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")
|
||||
}
|
||||
}
|
||||
|
||||
selectBuffer.WriteString(fmt.Sprintf(LogicListJoinSelect, in.options.TemplateGroup, in.In.VarName, in.In.DaoName, joinSelectRows, in.In.TableComment))
|
||||
|
||||
data["select"] = selectBuffer.String()
|
||||
data["fields"] = "fields"
|
||||
data["link"] = linkBuffer.String()
|
||||
} else {
|
||||
data["fields"] = fmt.Sprintf("%sin.%sListModel{}", in.options.TemplateGroup, in.In.VarName)
|
||||
link = linkBuffer.String()
|
||||
}
|
||||
return data
|
||||
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.masterFields, in.In.DaoName, "")
|
||||
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, v.Columns, v.DaoName, v.Alias)
|
||||
l.generateLogicListWhereEach(buffer, in, v.Columns, v.DaoName, v.Alias)
|
||||
}
|
||||
}
|
||||
}
|
||||
return buffer.String()
|
||||
}
|
||||
|
||||
func (l *gCurd) generateLogicListWhereEach(buffer *bytes.Buffer, fields []*sysin.GenCodesColumnListModel, daoName string, alias 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 {
|
||||
if !field.IsQuery || field.QueryWhere == "" {
|
||||
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 == GoTypeGTime {
|
||||
@@ -197,8 +228,6 @@ func (l *gCurd) generateLogicListWhereEach(buffer *bytes.Buffer, fields []*sysin
|
||||
linkMode = `len(in.` + field.GoName + `) == 2`
|
||||
}
|
||||
|
||||
buffer.WriteString(fmt.Sprintf(LogicWhereComments, field.Dc))
|
||||
|
||||
// 如果是关联表重新转换字段
|
||||
columnName = field.GoName
|
||||
if isLink {
|
||||
@@ -207,35 +236,35 @@ func (l *gCurd) generateLogicListWhereEach(buffer *bytes.Buffer, fields []*sysin
|
||||
|
||||
switch field.QueryWhere {
|
||||
case WhereModeEq:
|
||||
whereTag = "\tif " + linkMode + " {\n\t\tmod = mod.Where(" + alias + "dao." + daoName + ".Columns()." + columnName + ", in." + field.GoName + ")\n\t}"
|
||||
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.WhereNot(dao." + daoName + ".Columns()." + columnName + ", in." + field.GoName + ")\n\t}"
|
||||
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.WhereGT(dao." + daoName + ".Columns()." + columnName + ", in." + field.GoName + ")\n\t}"
|
||||
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.WhereGTE(dao." + daoName + ".Columns()." + columnName + ", in." + field.GoName + ")\n\t}"
|
||||
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.WhereLT(dao." + daoName + ".Columns()." + columnName + ", in." + field.GoName + ")\n\t}"
|
||||
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.WhereLTE(dao." + daoName + ".Columns()." + columnName + ", in." + field.GoName + ")\n\t}"
|
||||
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.WhereIn(dao." + daoName + ".Columns()." + columnName + ", in." + field.GoName + ")\n\t}"
|
||||
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.WhereNotIn(dao." + daoName + ".Columns()." + columnName + ", in." + field.GoName + ")\n\t}"
|
||||
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.WhereBetween(dao." + daoName + ".Columns()." + columnName + ", in." + field.GoName + "[0], in." + field.GoName + "[1])\n\t}"
|
||||
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.WhereNotBetween(dao." + daoName + ".Columns()." + columnName + ", in." + field.GoName + "[0], in." + field.GoName + "[1])\n\t}"
|
||||
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:
|
||||
whereTag = "\tif " + linkMode + " {\n\t\tmod = mod.WhereLike(dao." + daoName + ".Columns()." + columnName + ", in." + field.GoName + ")\n\t}"
|
||||
whereTag = "\tif " + linkMode + " {\n\t\tmod = mod." + wherePrefix + "Like(" + tablePrefix + "dao." + daoName + ".Columns()." + columnName + ", in." + field.GoName + ")\n\t}"
|
||||
case WhereModeLikeAll:
|
||||
val := `"%"+in.` + field.GoName + `+"%"`
|
||||
whereTag = "\tif " + linkMode + " {\n\t\tmod = mod.WhereLike(dao." + daoName + ".Columns()." + columnName + ", " + val + ")\n\t}"
|
||||
whereTag = "\tif " + linkMode + " {\n\t\tmod = mod." + wherePrefix + "Like(" + tablePrefix + "dao." + daoName + ".Columns()." + columnName + ", " + val + ")\n\t}"
|
||||
case WhereModeNotLike:
|
||||
whereTag = "\tif " + linkMode + " {\n\t\tmod = mod.WhereNotLike(dao." + daoName + ".Columns()." + columnName + ", in." + field.GoName + ")\n\t}"
|
||||
whereTag = "\tif " + linkMode + " {\n\t\tmod = mod." + wherePrefix + "NotLike(" + tablePrefix + "dao." + daoName + ".Columns()." + columnName + ", in." + field.GoName + ")\n\t}"
|
||||
case WhereModeJsonContains:
|
||||
val := "fmt.Sprintf(`JSON_CONTAINS(%s,'%v')`, dao." + daoName + ".Columns()." + columnName + ", in." + field.GoName + ")"
|
||||
whereTag = "\tif in." + field.GoName + linkMode + " {\n\t\tmod = mod.Where(" + val + ")\n\t}"
|
||||
val := tablePrefix + "fmt.Sprintf(`JSON_CONTAINS(%s,'%v')`, dao." + daoName + ".Columns()." + columnName + ", in." + field.GoName + ")"
|
||||
whereTag = "\tif in." + field.GoName + linkMode + " {\n\t\tmod = mod." + wherePrefix + "(" + val + ")\n\t}"
|
||||
|
||||
default:
|
||||
buffer.WriteString(fmt.Sprintf(LogicWhereNoSupport, field.QueryWhere))
|
||||
|
||||
@@ -22,7 +22,7 @@ func (l *gCurd) webEditTplData(ctx context.Context, in *CurdPreviewInput) (data
|
||||
|
||||
func (l *gCurd) generateWebEditFormItem(ctx context.Context, in *CurdPreviewInput) string {
|
||||
buffer := bytes.NewBuffer(nil)
|
||||
for k, field := range in.masterFields {
|
||||
for _, field := range in.masterFields {
|
||||
if !field.IsEdit {
|
||||
continue
|
||||
}
|
||||
@@ -36,6 +36,10 @@ func (l *gCurd) generateWebEditFormItem(ctx context.Context, in *CurdPreviewInpu
|
||||
component string
|
||||
)
|
||||
|
||||
if in.options.Step.IsTreeTable && IsPidName(field.Name) {
|
||||
field.FormMode = FormModePidTreeSelect
|
||||
}
|
||||
|
||||
switch field.FormMode {
|
||||
case FormModeInput:
|
||||
component = defaultComponent
|
||||
@@ -98,16 +102,45 @@ func (l *gCurd) generateWebEditFormItem(ctx context.Context, in *CurdPreviewInpu
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
if len(in.masterFields) == k {
|
||||
buffer.WriteString(" " + component)
|
||||
} else {
|
||||
buffer.WriteString(" " + component + "\n\n")
|
||||
}
|
||||
buffer.WriteString(fmt.Sprintf("<n-gi span=\"%v\">%v</n-gi>\n\n", field.FormGridSpan, component))
|
||||
}
|
||||
return buffer.String()
|
||||
}
|
||||
@@ -119,23 +152,25 @@ func (l *gCurd) generateWebEditScript(ctx context.Context, in *CurdPreviewInput)
|
||||
setupBuffer = bytes.NewBuffer(nil)
|
||||
)
|
||||
|
||||
importBuffer.WriteString(" import { ref, computed } from 'vue';\n")
|
||||
|
||||
// 导入api
|
||||
var importApiMethod = []string{"Edit", "View"}
|
||||
if in.options.Step.HasMaxSort {
|
||||
importBuffer.WriteString(" import { ref } from 'vue';\n")
|
||||
if in.Config.Application.Crud.Templates[in.In.GenTemplate].IsAddon {
|
||||
importBuffer.WriteString(" import { Edit, MaxSort, View } from '@/api/addons/" + in.In.AddonName + "/" + gstr.LcFirst(in.In.VarName) + "';\n")
|
||||
} else {
|
||||
importBuffer.WriteString(" import { Edit, MaxSort, View } from '@/api/" + gstr.LcFirst(in.In.VarName) + "';\n")
|
||||
}
|
||||
setupBuffer.WriteString(" function openModal(state: State) {\n adaModalWidth(dialogWidth);\n showModal.value = true;\n loading.value = true;\n\n // 新增\n if (!state || state.id < 1) {\n formValue.value = newState(state);\n MaxSort()\n .then((res) => {\n formValue.value.sort = res.sort;\n })\n .finally(() => {\n loading.value = false;\n });\n return;\n }\n\n // 编辑\n View({ id: state.id })\n .then((res) => {\n formValue.value = res;\n })\n .finally(() => {\n loading.value = false;\n });\n }")
|
||||
} else {
|
||||
importBuffer.WriteString(" import { ref } from 'vue';\n")
|
||||
if in.Config.Application.Crud.Templates[in.In.GenTemplate].IsAddon {
|
||||
importBuffer.WriteString(" import { Edit, View } from '@/api/addons/" + in.In.AddonName + "/" + gstr.LcFirst(in.In.VarName) + "';\n")
|
||||
} else {
|
||||
importBuffer.WriteString(" import { Edit, View } from '@/api/" + gstr.LcFirst(in.In.VarName) + "';\n")
|
||||
}
|
||||
setupBuffer.WriteString(" function openModal(state: State) {\n adaModalWidth(dialogWidth);\n showModal.value = true;\n loading.value = true;\n\n // 新增\n if (!state || state.id < 1) {\n formValue.value = newState(state);\n return;\n }\n\n // 编辑\n View({ id: state.id })\n .then((res) => {\n formValue.value = res;\n })\n .finally(() => {\n loading.value = false;\n });\n }")
|
||||
importApiMethod = append(importApiMethod, "MaxSort")
|
||||
}
|
||||
importBuffer.WriteString(" import " + ImportWebMethod(importApiMethod) + " from '" + in.options.ImportWebApi + "';\n")
|
||||
|
||||
// 导入model
|
||||
var importModelMethod = []string{"options", "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 {
|
||||
|
||||
@@ -6,59 +6,135 @@
|
||||
package views
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/gogf/gf/v2/frame/g"
|
||||
"github.com/gogf/gf/v2/text/gstr"
|
||||
)
|
||||
|
||||
const (
|
||||
IndexApiImport = " import {%v } from '@/api/%s';" // 这里将导入的包路径写死了,后面可以优化成根据配置动态读取
|
||||
IndexApiAddonsImport = " import {%v } from '@/api/addons/%s/%s';"
|
||||
IndexIconsImport = " import {%v } from '@vicons/antd';"
|
||||
)
|
||||
|
||||
func (l *gCurd) webIndexTplData(ctx context.Context, in *CurdPreviewInput) (g.Map, error) {
|
||||
var (
|
||||
data = make(g.Map)
|
||||
apiImport = []string{" List"}
|
||||
iconsImport []string
|
||||
data = make(g.Map)
|
||||
importBuffer = bytes.NewBuffer(nil)
|
||||
importVueMethod = []string{"h", "reactive", "ref", "computed"}
|
||||
importApiMethod = []string{"List"}
|
||||
importModelMethod = []string{"columns", "schemas"}
|
||||
importUtilsMethod = []string{"adaTableScrollX"}
|
||||
importIcons []string
|
||||
actionWidth int64 = 72
|
||||
)
|
||||
|
||||
// 添加
|
||||
if in.options.Step.HasAdd {
|
||||
iconsImport = append(iconsImport, " PlusOutlined")
|
||||
importIcons = append(importIcons, "PlusOutlined")
|
||||
}
|
||||
|
||||
// 编辑
|
||||
// if in.options.Step.HasEdit {
|
||||
// }
|
||||
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 {
|
||||
iconsImport = append(iconsImport, " ExportOutlined")
|
||||
apiImport = append(apiImport, " Export")
|
||||
importIcons = append(importIcons, "ExportOutlined")
|
||||
importApiMethod = append(importApiMethod, "Export")
|
||||
}
|
||||
|
||||
// 删除
|
||||
if in.options.Step.HasDel || in.options.Step.HasBatchDel {
|
||||
iconsImport = append(iconsImport, " DeleteOutlined")
|
||||
apiImport = append(apiImport, " Delete")
|
||||
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 {
|
||||
apiImport = append(apiImport, " Status")
|
||||
importApiMethod = append(importApiMethod, "Status")
|
||||
importUtilsMethod = append(importUtilsMethod, "getOptionLabel")
|
||||
importModelMethod = append(importModelMethod, "options")
|
||||
in.options.Step.ActionColumnWidth += actionWidth
|
||||
}
|
||||
|
||||
if in.Config.Application.Crud.Templates[in.In.GenTemplate].IsAddon {
|
||||
data["apiImport"] = fmt.Sprintf(IndexApiAddonsImport, gstr.Implode(",", apiImport), in.In.AddonName, gstr.LcFirst(in.In.VarName))
|
||||
} else {
|
||||
data["apiImport"] = fmt.Sprintf(IndexApiImport, gstr.Implode(",", apiImport), gstr.LcFirst(in.In.VarName))
|
||||
// 更多
|
||||
// 查看详情
|
||||
if in.options.Step.HasView {
|
||||
in.options.Step.ActionColumnWidth += actionWidth
|
||||
}
|
||||
if len(iconsImport) > 0 {
|
||||
data["iconsImport"] = fmt.Sprintf(IndexIconsImport, gstr.Implode(",", iconsImport))
|
||||
|
||||
// 展开树
|
||||
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 " + ImportWebMethod(importVueMethod) + " from 'vue';\n")
|
||||
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")
|
||||
|
||||
// 导入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")
|
||||
}
|
||||
|
||||
// 没有需要查询的字段则隐藏搜索表单
|
||||
@@ -83,5 +159,6 @@ func (l *gCurd) webIndexTplData(ctx context.Context, in *CurdPreviewInput) (g.Ma
|
||||
}
|
||||
}
|
||||
data["isSearchForm"] = isSearchForm
|
||||
data["import"] = importBuffer.String()
|
||||
return data, nil
|
||||
}
|
||||
|
||||
@@ -12,61 +12,148 @@ import (
|
||||
"fmt"
|
||||
"github.com/gogf/gf/v2/errors/gerror"
|
||||
"github.com/gogf/gf/v2/frame/g"
|
||||
"github.com/gogf/gf/v2/util/gconv"
|
||||
"hotgo/internal/library/dict"
|
||||
"hotgo/internal/model/input/sysin"
|
||||
"hotgo/utility/convert"
|
||||
)
|
||||
|
||||
const (
|
||||
ModelLoadOptionsTemplate = "async function loadOptions() {\n options.value = await Dicts({\n types: [\n %v ],\n });\n for (const item of schemas.value) {\n switch (item.field) {\n%v }\n }\n}\n\nawait loadOptions();"
|
||||
)
|
||||
type StateItem struct {
|
||||
Name string
|
||||
DefaultValue interface{}
|
||||
Dc string
|
||||
}
|
||||
|
||||
func (l *gCurd) webModelTplData(ctx context.Context, in *CurdPreviewInput) (data g.Map, err error) {
|
||||
data = make(g.Map)
|
||||
data["state"] = l.generateWebModelState(ctx, in)
|
||||
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"] = l.generateWebModelImport(ctx, in)
|
||||
return
|
||||
}
|
||||
|
||||
func (l *gCurd) generateWebModelState(ctx context.Context, in *CurdPreviewInput) string {
|
||||
buffer := bytes.NewBuffer(nil)
|
||||
buffer.WriteString("export class State {\n")
|
||||
func (l *gCurd) generateWebModelImport(ctx context.Context, in *CurdPreviewInput) string {
|
||||
importBuffer := bytes.NewBuffer(nil)
|
||||
|
||||
importBuffer.WriteString("import { h, ref } from 'vue';\n")
|
||||
|
||||
// 导入基础组件
|
||||
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 in.options.DictOps.Has {
|
||||
importBuffer.WriteString("import { Dicts } from '@/api/dict/dict';\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.Step.HasSwitch {
|
||||
importBuffer.WriteString("import { usePermission } from '@/hooks/web/usePermission';\n")
|
||||
importBuffer.WriteString("const { hasPermission } = usePermission();\n")
|
||||
importBuffer.WriteString("const $message = window['$message'];\n")
|
||||
}
|
||||
return importBuffer.String()
|
||||
}
|
||||
|
||||
func (l *gCurd) generateWebModelStateItems(ctx context.Context, in *CurdPreviewInput) (items []*StateItem) {
|
||||
for _, field := range in.masterFields {
|
||||
var value = field.DefaultValue
|
||||
if value == nil {
|
||||
value = "null"
|
||||
}
|
||||
if value == "" {
|
||||
value = "''"
|
||||
value = `''`
|
||||
}
|
||||
|
||||
// 选项组件默认值调整
|
||||
if gconv.Int(value) == 0 && IsSelectFormMode(field.FormMode) {
|
||||
value = "null"
|
||||
}
|
||||
|
||||
if field.Name == "status" {
|
||||
value = 1
|
||||
}
|
||||
if field.FormMode == "Switch" {
|
||||
if field.FormMode == FormModeSwitch {
|
||||
value = 2
|
||||
}
|
||||
if field.FormMode == "InputDynamic" {
|
||||
if field.FormMode == FormModeInputDynamic {
|
||||
value = "[]"
|
||||
}
|
||||
buffer.WriteString(fmt.Sprintf(" public %s = %v; // %s\n", field.TsName, value, field.Dc))
|
||||
items = append(items, &StateItem{
|
||||
Name: field.TsName,
|
||||
DefaultValue: value,
|
||||
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",
|
||||
Dc: field.Dc + "摘要信息",
|
||||
})
|
||||
}
|
||||
}
|
||||
buffer.WriteString("\n constructor(state?: Partial<State>) {\n if (state) {\n Object.assign(this, state);\n }\n }")
|
||||
buffer.WriteString("}")
|
||||
return buffer.String()
|
||||
return
|
||||
}
|
||||
|
||||
func (l *gCurd) generateWebModelDictOptions(ctx context.Context, in *CurdPreviewInput) (g.Map, error) {
|
||||
func (l *gCurd) generateWebModelDictOptions(ctx context.Context, in *CurdPreviewInput) error {
|
||||
type DictType struct {
|
||||
Id int64 `json:"id"`
|
||||
Type string `json:"type"`
|
||||
}
|
||||
|
||||
var (
|
||||
options = make(g.Map)
|
||||
dictTypeIds []int64
|
||||
dictTypeList []*DictType
|
||||
builtinDictTypeIds []int64
|
||||
@@ -87,8 +174,7 @@ func (l *gCurd) generateWebModelDictOptions(ctx context.Context, in *CurdPreview
|
||||
builtinDictTypeIds = convert.UniqueSlice(builtinDictTypeIds)
|
||||
|
||||
if len(dictTypeIds) == 0 && len(builtinDictTypeIds) == 0 {
|
||||
options["has"] = false
|
||||
return options, nil
|
||||
return nil
|
||||
}
|
||||
|
||||
if len(dictTypeIds) > 0 {
|
||||
@@ -97,71 +183,52 @@ func (l *gCurd) generateWebModelDictOptions(ctx context.Context, in *CurdPreview
|
||||
WhereIn("id", dictTypeIds).
|
||||
Scan(&dictTypeList)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if len(builtinDictTypeIds) > 0 {
|
||||
for _, id := range builtinDictTypeIds {
|
||||
opts, err := dict.GetOptionsById(ctx, id)
|
||||
typ, err := dict.GetTypeById(ctx, id)
|
||||
if err != nil && !errors.Is(err, dict.NotExistKeyError) {
|
||||
return nil, err
|
||||
return err
|
||||
}
|
||||
|
||||
if len(opts) > 0 {
|
||||
if len(typ) > 0 {
|
||||
row := new(DictType)
|
||||
row.Id = id
|
||||
row.Type = opts[0].Type
|
||||
row.Type = typ
|
||||
builtinDictTypeList = append(builtinDictTypeList, row)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(dictTypeList) == 0 && len(builtinDictTypeList) == 0 {
|
||||
options["has"] = false
|
||||
return options, nil
|
||||
return nil
|
||||
}
|
||||
|
||||
if len(builtinDictTypeList) > 0 {
|
||||
dictTypeList = append(dictTypeList, builtinDictTypeList...)
|
||||
}
|
||||
|
||||
options["has"] = true
|
||||
in.options.DictOps.Has = true
|
||||
|
||||
var (
|
||||
awaitLoadOptions string
|
||||
switchLoadOptions string
|
||||
)
|
||||
|
||||
interfaceOptionsBuffer := bytes.NewBuffer(nil)
|
||||
interfaceOptionsBuffer.WriteString("export interface IOptions extends Options {\n")
|
||||
constOptionsBuffer := bytes.NewBuffer(nil)
|
||||
constOptionsBuffer.WriteString("export const options = ref<IOptions>({\n")
|
||||
// 导入选项包
|
||||
in.options.Step.ImportModel.UtilsHotGo = append(in.options.Step.ImportModel.UtilsHotGo, "Option")
|
||||
|
||||
for _, v := range dictTypeList {
|
||||
// 字段映射字典
|
||||
for _, field := range in.masterFields {
|
||||
if field.DictType != 0 && v.Id == field.DictType {
|
||||
in.options.dictMap[field.TsName] = v.Type
|
||||
switchLoadOptions = fmt.Sprintf("%s case '%s':\n item.componentProps.options = options.value.%s;\n break;\n", switchLoadOptions, field.TsName, v.Type)
|
||||
in.options.DictOps.Schemas = append(in.options.DictOps.Schemas, &OptionsSchemasField{
|
||||
Field: field.TsName,
|
||||
Type: v.Type,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
awaitLoadOptions = fmt.Sprintf("%s '%s',\n", awaitLoadOptions, v.Type)
|
||||
interfaceOptionsBuffer.WriteString(" " + v.Type + ": Option[]; \n")
|
||||
constOptionsBuffer.WriteString(" " + v.Type + ": [],\n")
|
||||
in.options.DictOps.Types = append(in.options.DictOps.Types, v.Type)
|
||||
}
|
||||
|
||||
interfaceOptionsBuffer.WriteString("};\n")
|
||||
constOptionsBuffer.WriteString("});\n")
|
||||
|
||||
loadOptionsBuffer := bytes.NewBuffer(nil)
|
||||
loadOptionsBuffer.WriteString(fmt.Sprintf(ModelLoadOptionsTemplate, awaitLoadOptions, switchLoadOptions))
|
||||
|
||||
options["interface"] = interfaceOptionsBuffer.String()
|
||||
options["const"] = constOptionsBuffer.String()
|
||||
options["load"] = loadOptionsBuffer.String()
|
||||
return options, nil
|
||||
return nil
|
||||
}
|
||||
|
||||
func (l *gCurd) generateWebModelRules(ctx context.Context, in *CurdPreviewInput) string {
|
||||
@@ -172,9 +239,11 @@ func (l *gCurd) generateWebModelRules(ctx context.Context, in *CurdPreviewInput)
|
||||
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))
|
||||
}
|
||||
}
|
||||
@@ -187,7 +256,7 @@ func (l *gCurd) generateWebModelFormSchema(ctx context.Context, in *CurdPreviewI
|
||||
buffer.WriteString("export const schemas = ref<FormSchema[]>([\n")
|
||||
|
||||
// 主表
|
||||
l.generateWebModelFormSchemaEach(buffer, in.masterFields)
|
||||
l.generateWebModelFormSchemaEach(buffer, in.masterFields, in)
|
||||
|
||||
// 关联表
|
||||
if len(in.options.Join) > 0 {
|
||||
@@ -195,7 +264,7 @@ func (l *gCurd) generateWebModelFormSchema(ctx context.Context, in *CurdPreviewI
|
||||
if !isEffectiveJoin(v) {
|
||||
continue
|
||||
}
|
||||
l.generateWebModelFormSchemaEach(buffer, v.Columns)
|
||||
l.generateWebModelFormSchemaEach(buffer, v.Columns, in)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -203,11 +272,18 @@ func (l *gCurd) generateWebModelFormSchema(ctx context.Context, in *CurdPreviewI
|
||||
return buffer.String()
|
||||
}
|
||||
|
||||
func (l *gCurd) generateWebModelFormSchemaEach(buffer *bytes.Buffer, fields []*sysin.GenCodesColumnListModel) {
|
||||
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)
|
||||
@@ -224,15 +300,19 @@ func (l *gCurd) generateWebModelFormSchemaEach(buffer *bytes.Buffer, fields []*s
|
||||
|
||||
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
|
||||
@@ -287,14 +367,22 @@ func (l *gCurd) generateWebModelColumnsEach(buffer *bytes.Buffer, in *CurdPrevie
|
||||
continue
|
||||
}
|
||||
var (
|
||||
defaultComponent = fmt.Sprintf(" {\n title: '%s',\n key: '%s',\n },\n", field.Dc, field.TsName)
|
||||
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) {\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 render(row) {\n return formatToDate(row.%s);\n },\n },\n", field.Dc, field.TsName, field.TsName)
|
||||
component = fmt.Sprintf(" {\n title: '%s',\n key: '%s',\n align: '%v',\n width: %v,\n render(row) {\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
|
||||
@@ -303,32 +391,50 @@ func (l *gCurd) generateWebModelColumnsEach(buffer *bytes.Buffer, in *CurdPrevie
|
||||
err = gerror.Newf("设置单选下拉框选项时,必须选择字典类型,字段名称:%v", field.Name)
|
||||
return
|
||||
}
|
||||
component = fmt.Sprintf(" {\n title: '%s',\n key: '%s',\n render(row) {\n if (isNullObject(row.%s)) {\n return ``;\n }\n return h(\n NTag,\n {\n style: {\n marginRight: '6px',\n },\n type: getOptionTag(options.value.%s, row.%s),\n bordered: false,\n },\n {\n default: () => getOptionLabel(options.value.%s, row.%s),\n }\n );\n },\n },\n", field.Dc, field.TsName, field.TsName, in.options.dictMap[field.TsName], field.TsName, in.options.dictMap[field.TsName], field.TsName)
|
||||
component = fmt.Sprintf(" {\n title: '%s',\n key: '%s',\n align: '%v',\n width: %v,\n render(row) {\n if (isNullObject(row.%s)) {\n return ``;\n }\n return h(\n NTag,\n {\n style: {\n marginRight: '6px',\n },\n type: getOptionTag(options.value.%s, row.%s),\n bordered: false,\n },\n {\n default: () => getOptionLabel(options.value.%s, row.%s),\n }\n );\n },\n },\n", field.Dc, field.TsName, field.Align, field.Width, field.TsName, in.options.dictMap[field.TsName], field.TsName, in.options.dictMap[field.TsName], 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")
|
||||
in.options.Step.ImportModel.UtilsHotGo = append(in.options.Step.ImportModel.UtilsHotGo, []string{"getOptionLabel", "getOptionTag"}...)
|
||||
|
||||
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 render(row) {\n if (isNullObject(row.%s) || !isArray(row.%s)) {\n return ``;\n }\n return row.%s.map((tagKey) => {\n return h(\n NTag,\n {\n style: {\n marginRight: '6px',\n },\n type: getOptionTag(options.value.%s, tagKey),\n bordered: false,\n },\n {\n default: () => getOptionLabel(options.value.%s, tagKey),\n }\n );\n });\n },\n },\n", field.Dc, field.TsName, field.TsName, field.TsName, field.TsName, in.options.dictMap[field.TsName], in.options.dictMap[field.TsName])
|
||||
component = fmt.Sprintf(" {\n title: '%s',\n key: '%s',\n align: '%v',\n width: %v,\n render(row) {\n if (isNullObject(row.%s) || !isArray(row.%s)) {\n return ``;\n }\n return row.%s.map((tagKey) => {\n return h(\n NTag,\n {\n style: {\n marginRight: '6px',\n },\n type: getOptionTag(options.value.%s, tagKey),\n bordered: false,\n },\n {\n default: () => getOptionLabel(options.value.%s, tagKey),\n }\n );\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.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")
|
||||
in.options.Step.ImportModel.UtilsHotGo = append(in.options.Step.ImportModel.UtilsHotGo, []string{"getOptionLabel", "getOptionTag"}...)
|
||||
|
||||
case FormModeUploadImage:
|
||||
component = fmt.Sprintf(" {\n title: '%s',\n key: '%s',\n render(row) {\n return h(%s, {\n width: 32,\n height: 32,\n src: row.%s,\n onError: errorImg,\n style: {\n width: '32px',\n height: '32px',\n 'max-width': '100%%',\n 'max-height': '100%%',\n },\n });\n },\n },\n", field.Dc, field.TsName, "NImage", field.TsName)
|
||||
component = fmt.Sprintf(" {\n title: '%s',\n key: '%s',\n align: '%v',\n width: %v,\n render(row) {\n return h(%s, {\n width: 32,\n height: 32,\n src: row.%s,\n fallbackSrc: errorImg,\n onError: errorImg,\n style: {\n width: '32px',\n height: '32px',\n 'max-width': '100%%',\n 'max-height': '100%%',\n },\n });\n },\n },\n", field.Dc, field.TsName, field.Align, field.Width, "NImage", field.TsName)
|
||||
in.options.Step.ImportModel.NaiveUI = append(in.options.Step.ImportModel.NaiveUI, "NImage")
|
||||
in.options.Step.ImportModel.UtilsHotGo = append(in.options.Step.ImportModel.UtilsHotGo, "errorImg")
|
||||
|
||||
case FormModeUploadImages:
|
||||
component = fmt.Sprintf(" {\n title: '%s',\n key: '%s',\n render(row) {\n if (isNullObject(row.%s)) {\n return ``;\n }\n return row.%s.map((image) => {\n return h(%s, {\n width: 32,\n height: 32,\n src: image,\n onError: errorImg,\n style: {\n width: '32px',\n height: '32px',\n 'max-width': '100%%',\n 'max-height': '100%%',\n 'margin-left': '2px',\n },\n });\n });\n },\n },\n", field.Dc, field.TsName, field.TsName, field.TsName, "NImage")
|
||||
component = fmt.Sprintf(" {\n title: '%s',\n key: '%s',\n align: '%v',\n width: %v,\n render(row) {\n if (isNullObject(row.%s)) {\n return ``;\n }\n return row.%s.map((image) => {\n return h(%s, {\n width: 32,\n height: 32,\n src: image,\n onError: errorImg,\n style: {\n width: '32px',\n height: '32px',\n 'max-width': '100%%',\n 'max-height': '100%%',\n 'margin-left': '2px',\n },\n });\n });\n },\n },\n", field.Dc, field.TsName, field.Align, field.Width, field.TsName, field.TsName, "NImage")
|
||||
in.options.Step.ImportModel.NaiveUI = append(in.options.Step.ImportModel.NaiveUI, "NImage")
|
||||
in.options.Step.ImportModel.UtilsIs = append(in.options.Step.ImportModel.UtilsIs, "isArray")
|
||||
in.options.Step.ImportModel.UtilsHotGo = append(in.options.Step.ImportModel.UtilsHotGo, "errorImg")
|
||||
|
||||
case FormModeUploadFile:
|
||||
component = fmt.Sprintf(" {\n title: '%s',\n key: '%s',\n render(row) {\n if (row.%s === '') {\n return ``;\n }\n return h(\n %s,\n {\n size: 'small',\n },\n {\n default: () => getFileExt(row.%s),\n }\n );\n },\n },\n", field.Dc, field.TsName, field.TsName, "NAvatar", field.TsName)
|
||||
component = fmt.Sprintf(" {\n title: '%s',\n key: '%s',\n align: '%v',\n width: %v,\n render(row) {\n if (row.%s === '') {\n return ``;\n }\n return h(\n %s,\n {\n size: 'small',\n },\n {\n default: () => getFileExt(row.%s),\n }\n );\n },\n },\n", field.Dc, field.TsName, field.Align, field.Width, field.TsName, "NAvatar", field.TsName)
|
||||
in.options.Step.ImportModel.NaiveUI = append(in.options.Step.ImportModel.NaiveUI, "NAvatar")
|
||||
in.options.Step.ImportModel.UtilsUrl = append(in.options.Step.ImportModel.UtilsUrl, "getFileExt")
|
||||
|
||||
case FormModeUploadFiles:
|
||||
component = fmt.Sprintf(" {\n title: '%s',\n key: '%s',\n render(row) {\n if (isNullObject(row.%s)) {\n return ``;\n }\n return row.%s.map((attachfile) => {\n return h(\n %s,\n {\n size: 'small',\n style: {\n 'margin-left': '2px',\n },\n },\n {\n default: () => getFileExt(attachfile),\n }\n );\n });\n },\n },\n", field.Dc, field.TsName, field.TsName, field.TsName, "NAvatar")
|
||||
component = fmt.Sprintf(" {\n title: '%s',\n key: '%s',\n align: '%v',\n width: %v,\n render(row) {\n if (isNullObject(row.%s)) {\n return ``;\n }\n return row.%s.map((attachfile) => {\n return h(\n %s,\n {\n size: 'small',\n style: {\n 'margin-left': '2px',\n },\n },\n {\n default: () => getFileExt(attachfile),\n }\n );\n });\n },\n },\n", field.Dc, field.TsName, field.Align, field.Width, field.TsName, field.TsName, "NAvatar")
|
||||
in.options.Step.ImportModel.NaiveUI = append(in.options.Step.ImportModel.NaiveUI, "NAvatar")
|
||||
in.options.Step.ImportModel.UtilsIs = append(in.options.Step.ImportModel.UtilsIs, "isNullObject")
|
||||
in.options.Step.ImportModel.UtilsUrl = append(in.options.Step.ImportModel.UtilsUrl, "getFileExt")
|
||||
|
||||
case FormModeSwitch:
|
||||
component = fmt.Sprintf(" {\n title: '%s',\n key: '%s',\n width: 100,\n render(row) {\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, "NSwitch", field.TsName, "/"+in.options.ApiPrefix+"/switch", field.TsName, in.pk.TsName, in.pk.TsName, convert.CamelCaseToUnderline(field.TsName), field.TsName)
|
||||
component = fmt.Sprintf(" {\n title: '%s',\n key: '%s',\n align: '%v',\n width: %v,\n render(row) {\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 render(row) {\n return h(%s, {\n allowHalf: true,\n readonly: true,\n defaultValue: row.%s,\n });\n },\n },\n", field.Dc, field.TsName, "NRate", field.TsName)
|
||||
component = fmt.Sprintf(" {\n title: '%s',\n key: '%s',\n align: '%v',\n width: %v,\n render(row) {\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
|
||||
@@ -336,6 +442,5 @@ func (l *gCurd) generateWebModelColumnsEach(buffer *bytes.Buffer, in *CurdPrevie
|
||||
|
||||
buffer.WriteString(component)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
@@ -44,25 +44,25 @@ func (l *gCurd) generateWebViewItem(ctx context.Context, in *CurdPreviewInput) s
|
||||
component = defaultComponent
|
||||
|
||||
case FormModeRadio, FormModeSelect:
|
||||
component = fmt.Sprintf("<n-descriptions-item label=\"%s\">\n <n-tag\n :type=\"getOptionTag(options.%s, formValue?.%s)\"\n size=\"small\"\n class=\"min-left-space\"\n >{{ getOptionLabel(options.%s, formValue?.%s) }}</n-tag\n >\n </n-descriptions-item>", field.Dc, in.options.dictMap[field.TsName], field.TsName, in.options.dictMap[field.TsName], field.TsName)
|
||||
component = fmt.Sprintf("<n-descriptions-item label=\"%s\">\n <n-tag :type=\"getOptionTag(options.%s, formValue?.%s)\" size=\"small\" class=\"min-left-space\">{{ getOptionLabel(options.%s, formValue?.%s) }}</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=\"getOptionTag(options.%s, item)\"\n size=\"small\"\n class=\"min-left-space\"\n >{{ getOptionLabel(options.%s, item) }}</n-tag\n >\n </template>\n </n-descriptions-item>", field.Dc, field.TsName, in.options.dictMap[field.TsName], in.options.dictMap[field.TsName])
|
||||
component = fmt.Sprintf("<n-descriptions-item label=\"%s\">\n <template v-for=\"(item, key) in formValue?.%s\" :key=\"key\">\n <n-tag :type=\"getOptionTag(options.%s, item)\" size=\"small\" class=\"min-left-space\">{{ getOptionLabel(options.%s, item) }}</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)
|
||||
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-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\n class=\"upload-card\"\n v-show=\"formValue.%s !== ''\"\n @click=\"download(formValue.%s)\"\n >\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)
|
||||
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 v-model:value=\"formValue.%s\" :unchecked-value=\"2\" :checked-value=\"1\" :disabled=\"true\"\n /></n-descriptions-item>", field.Dc, field.TsName)
|
||||
component = fmt.Sprintf("<n-descriptions-item label=\"%s\">\n <n-switch v-model:value=\"formValue.%s\" :unchecked-value=\"2\" :checked-value=\"1\" :disabled=\"true\"/></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)
|
||||
|
||||
7
server/internal/library/hggen/views/gohtml/consts.go
Normal file
7
server/internal/library/hggen/views/gohtml/consts.go
Normal file
@@ -0,0 +1,7 @@
|
||||
package gohtml
|
||||
|
||||
const (
|
||||
defaultIndentString = " "
|
||||
startIndent = 0
|
||||
defaultLastElement = "</html>"
|
||||
)
|
||||
2
server/internal/library/hggen/views/gohtml/doc.go
Normal file
2
server/internal/library/hggen/views/gohtml/doc.go
Normal file
@@ -0,0 +1,2 @@
|
||||
// Package gohtml provides an HTML formatting function.
|
||||
package gohtml
|
||||
7
server/internal/library/hggen/views/gohtml/element.go
Normal file
7
server/internal/library/hggen/views/gohtml/element.go
Normal file
@@ -0,0 +1,7 @@
|
||||
package gohtml
|
||||
|
||||
// An element represents an HTML element.
|
||||
type element interface {
|
||||
isInline() bool
|
||||
write(*formattedBuffer, bool) bool
|
||||
}
|
||||
37
server/internal/library/hggen/views/gohtml/formatter.go
Normal file
37
server/internal/library/hggen/views/gohtml/formatter.go
Normal file
@@ -0,0 +1,37 @@
|
||||
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()
|
||||
|
||||
}
|
||||
54
server/internal/library/hggen/views/gohtml/html_document.go
Normal file
54
server/internal/library/hggen/views/gohtml/html_document.go
Normal file
@@ -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)
|
||||
}
|
||||
127
server/internal/library/hggen/views/gohtml/parser.go
Normal file
127
server/internal/library/hggen/views/gohtml/parser.go
Normal file
@@ -0,0 +1,127 @@
|
||||
package gohtml
|
||||
|
||||
import (
|
||||
"golang.org/x/net/html"
|
||||
"io"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// 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(tokenizer *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
|
||||
}
|
||||
145
server/internal/library/hggen/views/gohtml/tag_element.go
Normal file
145
server/internal/library/hggen/views/gohtml/tag_element.go
Normal file
@@ -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.IndexAny(condensedBuffer.buffer.Bytes()[1:], "\n") == -1 {
|
||||
// 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)
|
||||
}
|
||||
43
server/internal/library/hggen/views/gohtml/text_element.go
Normal file
43
server/internal/library/hggen/views/gohtml/text_element.go
Normal file
@@ -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
|
||||
}
|
||||
101
server/internal/library/hggen/views/gohtml/utils.go
Normal file
101
server/internal/library/hggen/views/gohtml/utils.go
Normal file
@@ -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.Replace(strings.Replace(s, "\r\n", "\n", -1), "\r", "\n", -1)
|
||||
}
|
||||
33
server/internal/library/hggen/views/gohtml/writer.go
Normal file
33
server/internal/library/hggen/views/gohtml/writer.go
Normal file
@@ -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{}}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ package views
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/gogf/gf/v2/database/gdb"
|
||||
"github.com/gogf/gf/v2/errors/gerror"
|
||||
"github.com/gogf/gf/v2/frame/g"
|
||||
@@ -14,11 +15,18 @@ import (
|
||||
"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"
|
||||
"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"
|
||||
)
|
||||
|
||||
// parseServFunName 解析业务服务名称
|
||||
@@ -30,19 +38,6 @@ func (l *gCurd) parseServFunName(templateGroup, varName string) string {
|
||||
return templateGroup + varName
|
||||
}
|
||||
|
||||
// getPkField 获取主键
|
||||
func (l *gCurd) getPkField(in *CurdPreviewInput) *sysin.GenCodesColumnListModel {
|
||||
if len(in.masterFields) == 0 {
|
||||
panic("getPkField masterFields uninitialized.")
|
||||
}
|
||||
for _, field := range in.masterFields {
|
||||
if IsIndexPK(field.Index) {
|
||||
return field
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// hasEffectiveJoin 存在有效的关联表
|
||||
func hasEffectiveJoins(joins []*CurdOptionsJoin) bool {
|
||||
for _, join := range joins {
|
||||
@@ -220,3 +215,107 @@ func ParseDBConfigNodeLink(node *gdb.ConfigNode) *gdb.ConfigNode {
|
||||
}
|
||||
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 = []string{"pid", "level", "tree"}
|
||||
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) {
|
||||
for _, name := range names {
|
||||
name = strings.ToLower(name)
|
||||
match, _ := regexp.MatchString("^[a-z_][a-z0-9_]*$", 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 {
|
||||
endTag := `</template>`
|
||||
vueLen := gstr.PosR(code, endTag)
|
||||
vueCode := code[:vueLen+len(endTag)]
|
||||
tsCode := code[vueLen+len(endTag):]
|
||||
vueCode = gohtml.Format(vueCode)
|
||||
tsCode = FormatTs(tsCode)
|
||||
return vueCode + tsCode
|
||||
}
|
||||
|
||||
func FormatTs(code string) string {
|
||||
code = replaceEmptyLinesWithSpace(code)
|
||||
return code + "\n"
|
||||
}
|
||||
|
||||
func replaceEmptyLinesWithSpace(input string) string {
|
||||
re := regexp.MustCompile(`\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