diff --git a/api/version1/customerApp/appControll.go b/api/version1/customerApp/appControll.go index e8671b9..6a716db 100644 --- a/api/version1/customerApp/appControll.go +++ b/api/version1/customerApp/appControll.go @@ -2,6 +2,7 @@ package customerApp import ( "appPlatform/api/version1/customerform" + datacenter "appPlatform/api/version1/dataCenter" "appPlatform/api/version1/publicapi" "appPlatform/models/modelAppPlatform" "appPlatform/models/modelshr" @@ -868,10 +869,12 @@ func (a *ApiMethod) CreateAppForm(c *gin.Context) { publicmethod.Result(1, err, c, "未知表单标识!") return } + //获取人员信息 context, _ := c.Get(overall.MyContJwt) var userCont modelshr.ManCont userCont.GetLoginCont(context) cureeTime := time.Now().Unix() + var customerFormCont modelAppPlatform.CustomerForm err = customerFormCont.GetCont(map[string]interface{}{"`tablename`": formJsonCont.Form.Name}, "`id`") if err == nil || customerFormCont.Id != 0 { @@ -908,12 +911,36 @@ func (a *ApiMethod) CreateAppForm(c *gin.Context) { formVersion.Creater = userCont.Key //ult:0;not null;comment:创建人"` formVersion.CreaterTime = cureeTime //not null;comment:创建时间"` formVersion.EditTime = cureeTime //efault:0;not null;comment:编辑时间"` - // mastSql, _ := formJsonCont.CreateFormDatabaseTable() - // mastSql, _ := formJsonCont.DisassembleForm() - mastSql, _ := formJsonCont.CreateFormTable() + formVersion.Dict = requestData.Dict //字表结构"` + // return + fmt.Printf("进行数据源操作------------>%v\n", formJsonCont.Form) + if formJsonCont.Form.DataSource == "yes" { //进行数据源操作 + var sqlDb datacenter.DataBastType + sqlDb.Type = formJsonCont.Form.DataSourceConfig.DSN.SqlType + sqlDb.Ip = formJsonCont.Form.DataSourceConfig.DSN.Ip + sqlDb.DataBaseName = formJsonCont.Form.DataSourceConfig.DSN.DataBaseName + sqlDb.Port = formJsonCont.Form.DataSourceConfig.DSN.Port + sqlDb.UserName = formJsonCont.Form.DataSourceConfig.DSN.UserName + sqlDb.Pwd = formJsonCont.Form.DataSourceConfig.DSN.Password + sqlDborm, err := sqlDb.StartDataBast() + if err != nil { + sqlDborm, err = datacenter.GainDataStorce(formJsonCont.Form.DataSourceConfig.Id) + if err != nil { + publicmethod.Result(0, sqlDb, c) + return + } + } + mastSql, _ := formJsonCont.CreateActiveFormTable(sqlDborm, formJsonCont.Form.DataSourceConfig.TableKey) + formVersion.TableStructure = mastSql //;default:'';comment:字表结构"` + // publicmethod.Result(0, mastSql, c) + } else { //无数据源操作 + + // mastSql, _ := formJsonCont.CreateFormDatabaseTable() + // mastSql, _ := formJsonCont.DisassembleForm() + mastSql, _ := formJsonCont.CreateFormTable() + formVersion.TableStructure = mastSql //;default:'';comment:字表结构"` - formVersion.TableStructure = mastSql //;default:'';comment:字表结构"` - formVersion.Dict = requestData.Dict //字表结构"` + } createDb := overall.CONSTANT_DB_AppPlatform.Begin() errMain := createDb.Create(&customerFormCont).Error @@ -1046,10 +1073,35 @@ func (a *ApiMethod) SaveOtherVersion(c *gin.Context) { formVersion.EditTime = cureeTime //efault:0;not null;comment:编辑时间"` // mastSql, _ := formJsonCont.CreateFormDatabaseTable() // mastSql, _ := formJsonCont.DisassembleForm() - mastSql, _ := formJsonCont.CreateFormTable() - formVersion.TableStructure = mastSql //;default:'';comment:字表结构"` - formVersion.Dict = requestData.Dict //字表结构"` + if formJsonCont.Form.DataSource == "yes" { //进行数据源操作 + var sqlDb datacenter.DataBastType + sqlDb.Type = formJsonCont.Form.DataSourceConfig.DSN.SqlType + sqlDb.Ip = formJsonCont.Form.DataSourceConfig.DSN.Ip + sqlDb.DataBaseName = formJsonCont.Form.DataSourceConfig.DSN.DataBaseName + sqlDb.Port = formJsonCont.Form.DataSourceConfig.DSN.Port + sqlDb.UserName = formJsonCont.Form.DataSourceConfig.DSN.UserName + sqlDb.Pwd = formJsonCont.Form.DataSourceConfig.DSN.Password + sqlDborm, err := sqlDb.StartDataBast() + if err != nil { + sqlDborm, err = datacenter.GainDataStorce(formJsonCont.Form.DataSourceConfig.Id) + if err != nil { + publicmethod.Result(0, sqlDb, c) + return + } + } + mastSql, _ := formJsonCont.CreateActiveFormTable(sqlDborm, formJsonCont.Form.DataSourceConfig.TableKey) + formVersion.TableStructure = mastSql //;default:'';comment:字表结构"` + } else { //无数据源操作 + mastSql, _ := formJsonCont.CreateFormTable() + formVersion.TableStructure = mastSql //;default:'';comment:字表结构"` + + } + + // mastSql, _ := formJsonCont.CreateFormTable() + // formVersion.TableStructure = mastSql //;default:'';comment:字表结构"` + + formVersion.Dict = requestData.Dict //字表结构"` errVer := overall.CONSTANT_DB_AppPlatform.Create(&formVersion).Error if errVer != nil { publicmethod.Result(104, customerFormCont, c) @@ -1160,8 +1212,34 @@ func (a *ApiMethod) EditAppPageInfo(c *gin.Context) { versionData["`creater`"] = userCont.Key // mastSql, _ := formJsonCont.DisassembleForm() // mastSql, _ := formJsonCont.CreateFormDatabaseTable() - mastSql, _ := formJsonCont.CreateFormTable() - versionData["`table_structure`"] = mastSql + + if formJsonCont.Form.DataSource == "yes" { //进行数据源操作 + var sqlDb datacenter.DataBastType + sqlDb.Type = formJsonCont.Form.DataSourceConfig.DSN.SqlType + sqlDb.Ip = formJsonCont.Form.DataSourceConfig.DSN.Ip + sqlDb.DataBaseName = formJsonCont.Form.DataSourceConfig.DSN.DataBaseName + sqlDb.Port = formJsonCont.Form.DataSourceConfig.DSN.Port + sqlDb.UserName = formJsonCont.Form.DataSourceConfig.DSN.UserName + sqlDb.Pwd = formJsonCont.Form.DataSourceConfig.DSN.Password + sqlDborm, err := sqlDb.StartDataBast() + if err != nil { + sqlDborm, err = datacenter.GainDataStorce(formJsonCont.Form.DataSourceConfig.Id) + if err != nil { + publicmethod.Result(0, sqlDb, c) + return + } + } + mastSql, _ := formJsonCont.CreateActiveFormTable(sqlDborm, formJsonCont.Form.DataSourceConfig.TableKey) + versionData["`table_structure`"] = mastSql + } else { //无数据源操作 + mastSql, _ := formJsonCont.CreateFormTable() + versionData["`table_structure`"] = mastSql + + } + + // mastSql, _ := formJsonCont.CreateFormTable() + // versionData["`table_structure`"] = mastSql + versionData["`dict`"] = requestData.Dict var formVersion modelAppPlatform.CustomerFormVersion formVersion.EiteCont(map[string]interface{}{"`id`": requestData.Version}, versionData) diff --git a/api/version1/customerApp/runAppControll.go b/api/version1/customerApp/runAppControll.go index f8838e8..38a79fa 100644 --- a/api/version1/customerApp/runAppControll.go +++ b/api/version1/customerApp/runAppControll.go @@ -1,6 +1,8 @@ package customerApp import ( + "appPlatform/api/version1/customerform" + datacenter "appPlatform/api/version1/dataCenter" "appPlatform/models/customerForm" "appPlatform/models/modelAppPlatform" "appPlatform/models/modelshr" @@ -691,3 +693,82 @@ func (a *AppMenuList) AppMenuContent(appKey int64, menuInfo modelAppPlatform.App a.List = append(a.List, menuCont) fmt.Printf("获取所有子类:%v\n", a) } + +/* +* +@ 作者: 秦东 +@ 时间: 2025-01-03 14:42:36 +@ 功能: 获取有源数据表字段 +@ 参数 + + # + +@ 返回值 + + # + +@ 方法原型 + + # +*/ +func (a *ApiMethod) GainDataStorceAllField(c *gin.Context) { + var requestData DatabaseConfig + err := c.ShouldBindJSON(&requestData) + if err != nil { + publicmethod.Result(100, err, c) + return + } + if requestData.Id == "" { + publicmethod.Result(200, err, c) + return + } + if requestData.SqlType == "" { + publicmethod.Result(200, err, c) + return + } + if requestData.Name == "" { + publicmethod.Result(200, err, c) + return + } + if requestData.TableName == "" { + publicmethod.Result(200, err, c) + return + } + if requestData.Host == "" { + publicmethod.Result(200, err, c) + return + } + if requestData.Port == 0 { + publicmethod.Result(200, err, c) + return + } + if requestData.User == "" { + publicmethod.Result(200, err, c) + return + } + if requestData.Password == "" { + publicmethod.Result(200, err, c) + return + } + var sqlDb datacenter.DataBastType + sqlDb.Type = requestData.SqlType + sqlDb.Ip = requestData.Host + sqlDb.DataBaseName = requestData.Name + sqlDb.Port = requestData.Port + sqlDb.UserName = requestData.User + sqlDb.Pwd = requestData.Password + sqlDborm, err := sqlDb.StartDataBast() + if err != nil { + sqlDborm, err = datacenter.GainDataStorce(requestData.Id) + if err != nil { + publicmethod.Result(0, sqlDb, c) + return + } + } + fieldList, err := customerform.GainFormAllField(sqlDborm, requestData.TableName) + if err != nil { + publicmethod.Result(0, err, c) + return + } + publicmethod.Result(0, fieldList, c) +} diff --git a/api/version1/customerApp/type.go b/api/version1/customerApp/type.go index 603682e..5ae8613 100644 --- a/api/version1/customerApp/type.go +++ b/api/version1/customerApp/type.go @@ -267,3 +267,14 @@ type MenuGroupList struct { MenuAppTitle string `json:"title"` List []SendAppForm `json:"list"` } + +type DatabaseConfig struct { + publicmethod.PublicId + SqlType string `json:"sqlType"` + Name string `json:"name"` + TableName string `json:"tableName"` + Host string `json:"host"` + Port int64 `json:"prot"` + User string `json:"user"` + Password string `json:"pwd"` +} diff --git a/api/version1/customerform/dataSourcSql.go b/api/version1/customerform/dataSourcSql.go new file mode 100644 index 0000000..1f45fba --- /dev/null +++ b/api/version1/customerform/dataSourcSql.go @@ -0,0 +1,111 @@ +package customerform + +import ( + "appPlatform/overall/publicmethod" + "encoding/json" + "fmt" + "strings" + + "gorm.io/gorm" +) + +/* +* +@ 作者: 秦东 +@ 时间: 2025-01-03 08:58:14 +@ 功能: 获取指定数据表所有字段 +@ 参数 + + # + +@ 返回值 + + # + +@ 方法原型 + + # +*/ +func GainFormAllField(sqlDb *gorm.DB, formName string) (fieldAry []Result, err error) { + sqlStr := fmt.Sprintf("SHOW FULL COLUMNS FROM `%v`", formName) + err = sqlDb.Raw(sqlStr).Scan(&fieldAry).Error + return +} + +func GainFormAllFieldList(sqlDb *gorm.DB, formName string) (fieldList []Result, err error) { + sqlStr := fmt.Sprintf("SHOW FULL COLUMNS FROM `%v`", formName) + err = sqlDb.Raw(sqlStr).Scan(&fieldList).Error + for i, v := range fieldList { + attFiled := strings.Split(v.Type, " ") + if len(attFiled) >= 2 { + fieldList[i].Attribute = attFiled[1] + fieldList[i].Type = attFiled[0] + + } + if v.Field == "id" { + fieldList[i].Comment = "Id" + } + patternInfo := strings.Split(v.Type, "(") + if len(patternInfo) >= 1 { + fieldList[i].Pattern = patternInfo[0] + } + } + return +} + +/* +* +@ 作者: 秦东 +@ 时间: 2025-01-03 09:09:54 +@ 功能: 处理数据源数据表 +@ 参数 + + # + +@ 返回值 + + # + +@ 方法原型 + + # +*/ +func (c *CustomerFormMaster) CreateActiveFormTable(sqlDb *gorm.DB, formName string) (relevance string, err error) { + tableFieldList, err := GainFormAllField(sqlDb, formName) //获取当前主表的字段 + var tableFormSqlAry FormTableSql + tableFormSqlAry.TableSubUnitAnalysis(c.Form.DataSourceConfig.TableKey, c.List, true, tableFieldList) + jsonStr, _ := json.Marshal(tableFormSqlAry) + fmt.Printf("数据表-----》%v\n", string(jsonStr)) + // 存在要新增或修改的主表字段 + if len(tableFormSqlAry.MasterSql) > 0 { + CreateDataSourceFormFiled(sqlDb, c.Form.DataSourceConfig.TableKey, c.Form.FormName, true, tableFormSqlAry.MasterSql) //添加主表字段 + } + sunFormNameAry := make(map[string]string) + var sunTableNameAry []string + //当存在子表时进行子表操作 + if len(tableFormSqlAry.SunSql) > 0 { + for _, v := range tableFormSqlAry.SunSql { + if len(v.SqlAry) > 0 { + sunFormTableName := v.TableName + if !publicmethod.IsInTrue[string](sunFormTableName, sunTableNameAry) { + sunTableNameAry = append(sunTableNameAry, sunFormTableName) + sunFormNameAry[v.TableName] = sunFormTableName + } else { + sunFormTableName = fmt.Sprintf("%v%v", v.TableName, publicmethod.GetUUid(1)) + sunTableNameAry = append(sunTableNameAry, sunFormTableName) + sunFormNameAry[v.TableName] = sunFormTableName + } + err = CreateDataSourceForm(sqlDb, sunFormTableName, fmt.Sprintf("%v(%v)子表", c.Form.FormName, c.Form.Name), "InnoDB", false) + // fmt.Printf("%v------->%v------->%v\n", sunFormTableName, err, v.SqlAry) + if err == nil { + CreateDataSourceFormFiled(sqlDb, sunFormTableName, fmt.Sprintf("%v(%v)子表", c.Form.FormName, c.Form.Name), false, v.SqlAry) + } + } + } + } + if len(sunFormNameAry) > 0 { + relevanceByte, _ := json.Marshal(sunFormNameAry) + relevance = string(relevanceByte) + } + return +} diff --git a/api/version1/customerform/form.go b/api/version1/customerform/form.go index 0a49c74..dbdf001 100644 --- a/api/version1/customerform/form.go +++ b/api/version1/customerform/form.go @@ -12,6 +12,7 @@ import ( "time" "github.com/gin-gonic/gin" + "gorm.io/gorm" ) /* @@ -1439,3 +1440,60 @@ func (a *ApiMethod) SetOftenApp(c *gin.Context) { } publicmethod.Result(0, err, c) } + +/* +* +@ 作者: 秦东 +@ 时间: 2025-01-03 13:02:04 +@ 功能: 根据数据源创建表单字段 +@ 参数 + + #sqlDb 数据源指针 + #formName 表单名称 + #formNotes 表单备注 + #isMasters true 主表;false:子表 + #sqlList 语句列表 + +@ 返回值 + + # + +@ 方法原型 + + # +*/ +func CreateDataSourceFormFiled(sqlDb *gorm.DB, formName, formNotes string, isMasters bool, sqlList interface{}) { + if sql, isOk := sqlList.([]string); isOk { + for k, v := range sql { + syncSeting.Add(1) + go CoroutineDataSourceExecuteSql(sqlDb, k, v) + } + syncSeting.Wait() + } +} + +// 协程执行mysql语句 +func CoroutineDataSourceExecuteSql(sqlDb *gorm.DB, k int, sql string) { + defer syncSeting.Done() + sqlDb.Exec(sql) +} + +func CreateDataSourceForm(sqlDb *gorm.DB, formName, notes, engine string, isMasters bool) (err error) { + if engine == "" { + engine = "MyISAM" + } + //判断表单是否存在 + isTrue := sqlDb.Migrator().HasTable(formName) + if !isTrue { //当数据表不存在时进行创建 + if isMasters { + //创建主表 + sqlCreateTable := fmt.Sprintf("CREATE TABLE `%v` (`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,`masters_key` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '主表标识',`creater` bigint(20) unsigned DEFAULT '0' COMMENT '创建人',`creater_time` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '创建时间',`edit_time` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '编辑时间',`flow_id` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '流程识别标识',`states` int(11) unsigned NOT NULL DEFAULT '1' COMMENT '状态(1:启用,2:禁用;3:删除)',`flowIsOpen` int(1) unsigned NOT NULL DEFAULT '2' COMMENT '是否开启工作流',PRIMARY KEY (`id`) USING BTREE,UNIQUE KEY `id` (`id`) USING HASH,UNIQUE KEY `masters_key` (`masters_key`) USING HASH) ENGINE=%v DEFAULT CHARSET=utf8mb4 COMMENT='%v'", formName, engine, notes) + err = sqlDb.Exec(sqlCreateTable).Error + } else { + //创建子表 + sqlCreateTable := fmt.Sprintf("CREATE TABLE `%v` (`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,`masters_key` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '主表标识',`creater` bigint(20) unsigned DEFAULT '0' COMMENT '创建人',`creater_time` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '创建时间',`edit_time` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '编辑时间',`states` int(11) unsigned NOT NULL DEFAULT '1' COMMENT '状态(1:启用,2:禁用;3:删除)',PRIMARY KEY (`id`) USING BTREE,UNIQUE KEY `id` (`id`) USING HASH,KEY `masters_key` (`masters_key`) USING HASH) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='%v'", formName, notes) + err = sqlDb.Exec(sqlCreateTable).Error + } + } + return +} diff --git a/api/version1/customerform/formTable.go b/api/version1/customerform/formTable.go index aed1b60..6414121 100644 --- a/api/version1/customerform/formTable.go +++ b/api/version1/customerform/formTable.go @@ -1,6 +1,7 @@ package customerform import ( + datacenter "appPlatform/api/version1/dataCenter" "appPlatform/models/customerForm" "appPlatform/models/modelAppPlatform" "appPlatform/models/modelshr" @@ -342,9 +343,15 @@ func (c *CustomerFormMaster) CreateFormTable() (relevance string, err error) { func (f *FormTableSql) TableSubUnitAnalysis(tablename string, subUnitAry []MasterStruct, isMaster bool, fieldList []Result) { if len(subUnitAry) > 0 { var sqlAllAry []string - // fmt.Printf("tablename--->%v===>%v\n", tablename, isMaster) + fmt.Printf("tablename--->%v===>%v\n", tablename, isMaster) + + oldTable := []string{"id", "masters_key", "creater", "creater_time", "edit_time", "flow_id", "states", "flowIsOpen"} + var alreadyExists []string + for _, v := range subUnitAry { wordClass := AnalysisFormUnitClass(v) + wordClassJson, _ := json.Marshal(wordClass) + fmt.Printf("wordClass--->%T===>%v\n", wordClass, string(wordClassJson)) switch wordClass.UnitName { case "flex", "table": if len(v.List) > 0 { @@ -381,8 +388,23 @@ func (f *FormTableSql) TableSubUnitAnalysis(tablename string, subUnitAry []Maste // } } + + if publicmethod.IsInTrue[string](wordClass.WordName, oldTable) { + alreadyExists = append(alreadyExists, wordClass.WordName) + } } - // fmt.Printf("tablename--->%v===>%v===>%v\n", tablename, isMaster, sqlAllAry) + + for _, v := range fieldList { + if publicmethod.IsInTrue[string](v.Field, oldTable) { + alreadyExists = append(alreadyExists, v.Field) + } + } + + buConfSql := newFieldOld(tablename, oldTable, alreadyExists) + if len(buConfSql) > 0 { + sqlAllAry = append(sqlAllAry, buConfSql...) + } + fmt.Printf("tablename--->%v===>%v===>%v\n", tablename, isMaster, sqlAllAry) if len(sqlAllAry) > 0 { if isMaster { f.MasterSql = append(f.MasterSql, sqlAllAry...) @@ -413,6 +435,52 @@ func (f *FormTableSql) TableSubUnitAnalysis(tablename string, subUnitAry []Maste } } +/* +* +@ 作者: 秦东 +@ 时间: 2025-01-03 13:38:30 +@ 功能: 生成数据源没有的字段语句 +@ 参数 + + #tablename 数据表 + #oldTable 表默认字段 + #alreadyExists 已有字段 + +@ 返回值 + + # + +@ 方法原型 + + #oldTable := []string{"id", "masters_key", "creater", "creater_time", "edit_time", "flow_id", "states", "flowIsOpen"} +*/ +func newFieldOld(tablename string, oldTable, alreadyExists []string) (sql []string) { + for _, v := range oldTable { + if !publicmethod.IsInTrue[string](v, alreadyExists) { + switch v { + case "id": + sql = append(sql, fmt.Sprintf("ALTER TABLE `%v` ADD COLUMN %v bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT 'Id';", tablename, v)) + case "masters_key": + sql = append(sql, fmt.Sprintf("ALTER TABLE `%v` ADD COLUMN %v bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '主表标识';", tablename, v)) + case "creater": + sql = append(sql, fmt.Sprintf("ALTER TABLE `%v` ADD COLUMN %v bigint(20) unsigned DEFAULT '0' COMMENT '创建人';", tablename, v)) + case "creater_time": + sql = append(sql, fmt.Sprintf("ALTER TABLE `%v` ADD COLUMN %v bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '创建时间';", tablename, v)) + case "edit_time": + sql = append(sql, fmt.Sprintf("ALTER TABLE `%v` ADD COLUMN %v bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '编辑时间';", tablename, v)) + case "flow_id": + sql = append(sql, fmt.Sprintf("ALTER TABLE `%v` ADD COLUMN %v bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '流程识别标识';", tablename, v)) + case "states": + sql = append(sql, fmt.Sprintf("ALTER TABLE `%v` ADD COLUMN %v int(1) unsigned NOT NULL DEFAULT '1' COMMENT '状态(1:启用,2:禁用;3:删除)';", tablename, v)) + case "flowIsOpen": + sql = append(sql, fmt.Sprintf("ALTER TABLE `%v` ADD COLUMN %v int(1) unsigned NOT NULL DEFAULT '2' COMMENT '是否开启工作流';", tablename, v)) + default: + } + } + } + return +} + /* * @ 作者: 秦东 @@ -445,14 +513,14 @@ func MakeSql(tablename string, fieldCont AnalysisFormSubUnitClass, fieldList []R isNew = false if fieldCont.FieldType == "bigint" { if fieldCont.ValIsAry { - sql = append(sql, fmt.Sprintf("ALTER TABLE `%v` ADD COLUMN `%v` %v(%v) %v NOT NULL DEFAULT %v COMMENT '%v'", tablename, fieldCont.WordName, fieldCont.FieldType, fieldCont.MaxVal, unsigned, fieldCont.MinVal, "开始日期")) + sql = append(sql, fmt.Sprintf("ALTER TABLE `%v` ADD COLUMN `%v` %v(%v) %v NOT NULL DEFAULT %v COMMENT '%v';", tablename, fieldCont.WordName, fieldCont.FieldType, fieldCont.MaxVal, unsigned, fieldCont.MinVal, "开始日期")) endField := fmt.Sprintf("%v_end", fieldCont.WordName) - sql = append(sql, fmt.Sprintf("ALTER TABLE `%v` ADD COLUMN `%v` %v(%v) %v NOT NULL DEFAULT %v COMMENT '%v'", tablename, endField, fieldCont.FieldType, fieldCont.MaxVal, unsigned, fieldCont.MinVal, "结束日期")) + sql = append(sql, fmt.Sprintf("ALTER TABLE `%v` ADD COLUMN `%v` %v(%v) %v NOT NULL DEFAULT %v COMMENT '%v';", tablename, endField, fieldCont.FieldType, fieldCont.MaxVal, unsigned, fieldCont.MinVal, "结束日期")) } else { - sql = append(sql, fmt.Sprintf("ALTER TABLE `%v` ADD COLUMN `%v` %v(%v) %v NOT NULL DEFAULT %v COMMENT '%v'", tablename, fieldCont.WordName, fieldCont.FieldType, fieldCont.MaxVal, unsigned, fieldCont.MinVal, fieldCont.Describe)) + sql = append(sql, fmt.Sprintf("ALTER TABLE `%v` ADD COLUMN `%v` %v(%v) %v NOT NULL DEFAULT %v COMMENT '%v';", tablename, fieldCont.WordName, fieldCont.FieldType, fieldCont.MaxVal, unsigned, fieldCont.MinVal, fieldCont.Describe)) } } else { - sql = append(sql, fmt.Sprintf("ALTER TABLE `%v` MODIFY COLUMN %v %v COMMENT '%v'", tablename, fieldCont.WordName, v.Type, fieldCont.Describe)) + sql = append(sql, fmt.Sprintf("ALTER TABLE `%v` MODIFY COLUMN %v %v COMMENT '%v';", tablename, fieldCont.WordName, v.Type, fieldCont.Describe)) } } @@ -463,24 +531,24 @@ func MakeSql(tablename string, fieldCont AnalysisFormSubUnitClass, fieldList []R if isNew { switch fieldCont.FieldType { case "int": - sql = append(sql, fmt.Sprintf("ALTER TABLE `%v` ADD COLUMN `%v` %v(%v) %v NOT NULL DEFAULT %v COMMENT '%v'", tablename, fieldCont.WordName, fieldCont.FieldType, fieldCont.MaxVal, unsigned, fieldCont.MinVal, fieldCont.Describe)) + sql = append(sql, fmt.Sprintf("ALTER TABLE `%v` ADD COLUMN `%v` %v(%v) %v NOT NULL DEFAULT %v COMMENT '%v';", tablename, fieldCont.WordName, fieldCont.FieldType, fieldCont.MaxVal, unsigned, fieldCont.MinVal, fieldCont.Describe)) case "bigint": if fieldCont.ValIsAry { - sql = append(sql, fmt.Sprintf("ALTER TABLE `%v` ADD COLUMN `%v` %v(%v) %v NOT NULL DEFAULT %v COMMENT '%v'", tablename, fieldCont.WordName, fieldCont.FieldType, fieldCont.MaxVal, unsigned, fieldCont.MinVal, "开始日期")) + sql = append(sql, fmt.Sprintf("ALTER TABLE `%v` ADD COLUMN `%v` %v(%v) %v NOT NULL DEFAULT %v COMMENT '%v';", tablename, fieldCont.WordName, fieldCont.FieldType, fieldCont.MaxVal, unsigned, fieldCont.MinVal, "开始日期")) endField := fmt.Sprintf("%v_end", fieldCont.WordName) - sql = append(sql, fmt.Sprintf("ALTER TABLE `%v` ADD COLUMN `%v` %v(%v) %v NOT NULL DEFAULT %v COMMENT '%v'", tablename, endField, fieldCont.FieldType, fieldCont.MaxVal, unsigned, fieldCont.MinVal, "结束日期")) + sql = append(sql, fmt.Sprintf("ALTER TABLE `%v` ADD COLUMN `%v` %v(%v) %v NOT NULL DEFAULT %v COMMENT '%v';", tablename, endField, fieldCont.FieldType, fieldCont.MaxVal, unsigned, fieldCont.MinVal, "结束日期")) } else { - sql = append(sql, fmt.Sprintf("ALTER TABLE `%v` ADD COLUMN `%v` %v(%v) %v NOT NULL DEFAULT %v COMMENT '%v'", tablename, fieldCont.WordName, fieldCont.FieldType, fieldCont.MaxVal, unsigned, fieldCont.MinVal, fieldCont.Describe)) + sql = append(sql, fmt.Sprintf("ALTER TABLE `%v` ADD COLUMN `%v` %v(%v) %v NOT NULL DEFAULT %v COMMENT '%v';", tablename, fieldCont.WordName, fieldCont.FieldType, fieldCont.MaxVal, unsigned, fieldCont.MinVal, fieldCont.Describe)) } case "float": - sql = append(sql, fmt.Sprintf("ALTER TABLE `%v` ADD COLUMN `%v` %v(%v,%v) %v NOT NULL DEFAULT 0 COMMENT '%v'", tablename, fieldCont.WordName, fieldCont.FieldType, fieldCont.MaxVal, fieldCont.MinVal, unsigned, fieldCont.Describe)) + sql = append(sql, fmt.Sprintf("ALTER TABLE `%v` ADD COLUMN `%v` %v(%v,%v) %v NOT NULL DEFAULT 0 COMMENT '%v';", tablename, fieldCont.WordName, fieldCont.FieldType, fieldCont.MaxVal, fieldCont.MinVal, unsigned, fieldCont.Describe)) case "decimal": - sql = append(sql, fmt.Sprintf("ALTER TABLE `%v` ADD COLUMN `%v` %v(%v,%v) %v NOT NULL DEFAULT 0 COMMENT '%v'", tablename, fieldCont.WordName, fieldCont.FieldType, fieldCont.MaxVal, fieldCont.MinVal, unsigned, fieldCont.Describe)) + sql = append(sql, fmt.Sprintf("ALTER TABLE `%v` ADD COLUMN `%v` %v(%v,%v) %v NOT NULL DEFAULT 0 COMMENT '%v';", tablename, fieldCont.WordName, fieldCont.FieldType, fieldCont.MaxVal, fieldCont.MinVal, unsigned, fieldCont.Describe)) case "mediumtext", "longtext": - sql = append(sql, fmt.Sprintf("ALTER TABLE `%v` ADD COLUMN `%v` %v COMMENT '%v'", tablename, fieldCont.WordName, fieldCont.FieldType, fieldCont.Describe)) + sql = append(sql, fmt.Sprintf("ALTER TABLE `%v` ADD COLUMN `%v` %v COMMENT '%v';", tablename, fieldCont.WordName, fieldCont.FieldType, fieldCont.Describe)) case "varchar": - sql = append(sql, fmt.Sprintf("ALTER TABLE `%v` ADD COLUMN `%v` %v(%v) COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '%v'", tablename, fieldCont.WordName, fieldCont.FieldType, fieldCont.MaxVal, fieldCont.Describe)) + sql = append(sql, fmt.Sprintf("ALTER TABLE `%v` ADD COLUMN `%v` %v(%v) COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '%v';", tablename, fieldCont.WordName, fieldCont.FieldType, fieldCont.MaxVal, fieldCont.Describe)) default: } } @@ -731,9 +799,35 @@ func (a *ApiMethod) GainFormTableField(c *gin.Context) { masterTable = append(masterTable, myKeyWord) } } + var formJsonCont CustomerFormMaster + json.Unmarshal([]byte(customerFormMaster.MastesFormJson), &formJsonCont) + if formJsonCont.Form.DataSource == "yes" { + var sqlDb datacenter.DataBastType + sqlDb.Type = formJsonCont.Form.DataSourceConfig.DSN.SqlType + sqlDb.Ip = formJsonCont.Form.DataSourceConfig.DSN.Ip + sqlDb.DataBaseName = formJsonCont.Form.DataSourceConfig.DSN.DataBaseName + sqlDb.Port = formJsonCont.Form.DataSourceConfig.DSN.Port + sqlDb.UserName = formJsonCont.Form.DataSourceConfig.DSN.UserName + sqlDb.Pwd = formJsonCont.Form.DataSourceConfig.DSN.Password + sqlDborm, err := sqlDb.StartDataBast() + if err != nil { + sqlDborm, err = datacenter.GainDataStorce(formJsonCont.Form.DataSourceConfig.Id) + if err != nil { + publicmethod.Result(0, sqlDb, c) + return + } + } + masterTableAll, err := GainFormAllFieldList(sqlDborm, formJsonCont.Form.DataSourceConfig.TableKey) + if err == nil { + masterTable = append(masterTable, masterTableAll...) + } + } else { + masterTableAll, err := GainFormTableField(customerFormMaster.TableKey) + if err == nil { + masterTable = append(masterTable, masterTableAll...) + } - masterTableAll, err := GainFormTableField(customerFormMaster.TableKey) - masterTable = append(masterTable, masterTableAll...) + } if err != nil { publicmethod.Result(1, err, c, "未知表单!无法获取字段!") @@ -1255,89 +1349,183 @@ func (a *ApiMethod) GainFormPageListCont(c *gin.Context) { publicmethod.Result(1, err, c, "未知表单!无法获取字段!") return } - // why, err := AnalysisSerachTerm(requestData.SearchData) - // fmt.Printf("why---->%v\n", why) - var formList []map[string]interface{} - // gormDb := overall.CONSTANT_DB_CustomerForm.Table(formInfo.TableKey) - tableName := fmt.Sprintf("`%v` as f", formInfo.TableKey) - gormDb := overall.CONSTANT_DB_CustomerForm.Table(tableName).Select("f.*,t.status as taskStatus,t.runFlowId") - // if err == nil { - // gormDb = gormDb.Where(why) - // } - gormDb = gormDb.Joins("LEFT JOIN `taskrecord` as t ON f.masters_key = t.masters_key") - gormDb = gormDb.Where("f.`creater` = ? ", userCont.Key) - gormDb = gormDb.Where("f.`states` BETWEEN ? AND ?", 1, 2) - - gormDb = AnalysisSerachTermSql(requestData.SearchData, gormDb) - var total int64 - totalErr := gormDb.Count(&total).Error - if totalErr != nil { - total = 0 - } - gormDb = publicmethod.PageTurningSettings(gormDb, requestData.Page, requestData.PageSize) - err = gormDb.Order("f.`id` DESC").Find(&formList).Error - if err != nil && len(formList) < 1 { - publicmethod.Result(0, err, c) - return - } - // for i, _ := range formList { - // // formList[i]["flowIsOpen"] = formInfo.FlowIsOpen - // formList[i]["flowkey"] = strconv.FormatInt(formInfo.Flowkey, 10) - // } - if formInfo.ListJson != "" { - var listFieldsMap ListPageFields - err = json.Unmarshal([]byte(formInfo.ListJson), &listFieldsMap) - // fmt.Printf("%T----------->%v----------->%v\n", listFieldsMap, err, listFieldsMap) - if err == nil { - // fmt.Printf("%T----------->%v\n", listFieldsMap, listFieldsMap) - formList = listFieldsMap.DevelopSpecificationsSend(formList) - // formList = DevelopSpecificationsSend(formList, listFieldsMap) + var formJsonCont CustomerFormMaster + json.Unmarshal([]byte(formInfo.MastesFormJson), &formJsonCont) + if formJsonCont.Form.DataSource == "yes" { + var sqlDb datacenter.DataBastType + sqlDb.Type = formJsonCont.Form.DataSourceConfig.DSN.SqlType + sqlDb.Ip = formJsonCont.Form.DataSourceConfig.DSN.Ip + sqlDb.DataBaseName = formJsonCont.Form.DataSourceConfig.DSN.DataBaseName + sqlDb.Port = formJsonCont.Form.DataSourceConfig.DSN.Port + sqlDb.UserName = formJsonCont.Form.DataSourceConfig.DSN.UserName + sqlDb.Pwd = formJsonCont.Form.DataSourceConfig.DSN.Password + sqlDborm, err := sqlDb.StartDataBast() + if err != nil { + sqlDborm, err = datacenter.GainDataStorce(formJsonCont.Form.DataSourceConfig.Id) + if err != nil { + publicmethod.Result(0, sqlDb, c) + return + } + } + gormDb := sqlDborm.Table(formJsonCont.Form.DataSourceConfig.TableKey) + gormDb = gormDb.Where("`states` BETWEEN ? AND ?", 1, 2) + + gormDb = AnalysisSerachTermSql(requestData.SearchData, gormDb) + var total int64 + totalErr := gormDb.Count(&total).Error + if totalErr != nil { + total = 0 } + var formList []map[string]interface{} + gormDb = publicmethod.PageTurningSettings(gormDb, requestData.Page, requestData.PageSize) + err = gormDb.Order("`id` DESC").Find(&formList).Error + if err != nil && len(formList) < 1 { + publicmethod.Result(0, err, c) + return + } + // sqlDborm.Table(formJsonCont.Form.DataSourceConfig.TableKey).Find(&formList) + // fmt.Printf("%T----------->%v----------->%v\n", formList, err, formList) + if formInfo.ListJson != "" { + var listFieldsMap ListPageFields + err = json.Unmarshal([]byte(formInfo.ListJson), &listFieldsMap) + // fmt.Printf("%T----------->%v----------->%v\n", listFieldsMap, err, listFieldsMap) + if err == nil { + // fmt.Printf("%T----------->%v\n", listFieldsMap, listFieldsMap) + formList = listFieldsMap.DevelopSpecificationsSend(formList) + // formList = DevelopSpecificationsSend(formList, listFieldsMap) + } - } + } - //获取任务状态 - for i, v := range formList { - formList[i]["isRetract"] = false - if mastrKey, ok := v["runFlowId"]; ok { - // fmt.Printf("masters_key----------->%v\n", v["masters_key"]) - mastrKeyInt, _ := publicmethod.StringToInt64(mastrKey) - if mastrKeyInt != 0 { - var runFlowInfo customerForm.RunWorkflow - runFlowInfo.GetCont(map[string]interface{}{"`id`": mastrKey}, "`id`", "`current_step`", "`next_step`") - formList[i]["runFlowInfo"] = runFlowInfo.Id - // fmt.Printf("runFlowInfo----------->%v--------->%v\n", runFlowInfo, v["taskStatus"]) - if stateVal, ok := v["taskStatus"]; ok { - // fmt.Printf("NextStep----------->%T----------->%v--------->%v--------->%v\n", stateVal, stateVal, runFlowInfo.NextStep, runFlowInfo.CurrentStep) - if stauval, ok := stateVal.(string); ok { - if stauval == "3" && runFlowInfo.NextStep != 0 { - - if runFlowInfo.CurrentStep == 1 { - if createrName, ok := formList[i]["creater"].(string); ok { - if createrName == userCont.Name { - formList[i]["isRetract"] = true + //获取任务状态 + for i, v := range formList { + formList[i]["isRetract"] = false + if mastrKey, ok := v["runFlowId"]; ok { + // fmt.Printf("masters_key----------->%v\n", v["masters_key"]) + mastrKeyInt, _ := publicmethod.StringToInt64(mastrKey) + if mastrKeyInt != 0 { + var runFlowInfo customerForm.RunWorkflow + runFlowInfo.GetCont(map[string]interface{}{"`id`": mastrKey}, "`id`", "`current_step`", "`next_step`") + formList[i]["runFlowInfo"] = runFlowInfo.Id + // fmt.Printf("runFlowInfo----------->%v--------->%v\n", runFlowInfo, v["taskStatus"]) + if stateVal, ok := v["taskStatus"]; ok { + // fmt.Printf("NextStep----------->%T----------->%v--------->%v--------->%v\n", stateVal, stateVal, runFlowInfo.NextStep, runFlowInfo.CurrentStep) + if stauval, ok := stateVal.(string); ok { + if stauval == "3" && runFlowInfo.NextStep != 0 { + + if runFlowInfo.CurrentStep == 1 { + if createrName, ok := formList[i]["creater"].(string); ok { + if createrName == userCont.Name { + formList[i]["isRetract"] = true + } } - } + } } } + } + } + } + if mastrKeyVal, ok := v["masters_key"]; ok { + // fmt.Printf("mastrKeyVal----------->%T----------->%v\n", mastrKeyVal, mastrKeyVal) + if mastrKeyUint64, ok := mastrKeyVal.(uint64); ok { + formList[i]["masters_key"] = strconv.FormatUint(mastrKeyUint64, 10) } } + } + + // publicmethod.Result(100, formList, c) + publicmethod.ResultList(0, requestData.Page, requestData.PageSize, total, int64(len(formList)), formList, c) + + } else { + // why, err := AnalysisSerachTerm(requestData.SearchData) + // fmt.Printf("why---->%v\n", why) + var formList []map[string]interface{} + // gormDb := overall.CONSTANT_DB_CustomerForm.Table(formInfo.TableKey) + tableName := fmt.Sprintf("`%v` as f", formInfo.TableKey) + gormDb := overall.CONSTANT_DB_CustomerForm.Table(tableName).Select("f.*,t.status as taskStatus,t.runFlowId") + // if err == nil { + // gormDb = gormDb.Where(why) + // } + gormDb = gormDb.Joins("LEFT JOIN `taskrecord` as t ON f.masters_key = t.masters_key") + gormDb = gormDb.Where("f.`creater` = ? ", userCont.Key) + gormDb = gormDb.Where("f.`states` BETWEEN ? AND ?", 1, 2) + + gormDb = AnalysisSerachTermSql(requestData.SearchData, gormDb) + var total int64 + totalErr := gormDb.Count(&total).Error + if totalErr != nil { + total = 0 } - if mastrKeyVal, ok := v["masters_key"]; ok { - // fmt.Printf("mastrKeyVal----------->%T----------->%v\n", mastrKeyVal, mastrKeyVal) - if mastrKeyUint64, ok := mastrKeyVal.(uint64); ok { - formList[i]["masters_key"] = strconv.FormatUint(mastrKeyUint64, 10) + + gormDb = publicmethod.PageTurningSettings(gormDb, requestData.Page, requestData.PageSize) + err = gormDb.Order("f.`id` DESC").Find(&formList).Error + if err != nil && len(formList) < 1 { + publicmethod.Result(0, err, c) + return + } + // for i, _ := range formList { + // // formList[i]["flowIsOpen"] = formInfo.FlowIsOpen + // formList[i]["flowkey"] = strconv.FormatInt(formInfo.Flowkey, 10) + // } + if formInfo.ListJson != "" { + var listFieldsMap ListPageFields + err = json.Unmarshal([]byte(formInfo.ListJson), &listFieldsMap) + // fmt.Printf("%T----------->%v----------->%v\n", listFieldsMap, err, listFieldsMap) + if err == nil { + // fmt.Printf("%T----------->%v\n", listFieldsMap, listFieldsMap) + formList = listFieldsMap.DevelopSpecificationsSend(formList) + // formList = DevelopSpecificationsSend(formList, listFieldsMap) } + } - } - // publicmethod.Result(100, formList, c) - publicmethod.ResultList(0, requestData.Page, requestData.PageSize, total, int64(len(formList)), formList, c) + //获取任务状态 + for i, v := range formList { + formList[i]["isRetract"] = false + if mastrKey, ok := v["runFlowId"]; ok { + // fmt.Printf("masters_key----------->%v\n", v["masters_key"]) + mastrKeyInt, _ := publicmethod.StringToInt64(mastrKey) + if mastrKeyInt != 0 { + var runFlowInfo customerForm.RunWorkflow + runFlowInfo.GetCont(map[string]interface{}{"`id`": mastrKey}, "`id`", "`current_step`", "`next_step`") + formList[i]["runFlowInfo"] = runFlowInfo.Id + // fmt.Printf("runFlowInfo----------->%v--------->%v\n", runFlowInfo, v["taskStatus"]) + if stateVal, ok := v["taskStatus"]; ok { + // fmt.Printf("NextStep----------->%T----------->%v--------->%v--------->%v\n", stateVal, stateVal, runFlowInfo.NextStep, runFlowInfo.CurrentStep) + if stauval, ok := stateVal.(string); ok { + if stauval == "3" && runFlowInfo.NextStep != 0 { + + if runFlowInfo.CurrentStep == 1 { + if createrName, ok := formList[i]["creater"].(string); ok { + if createrName == userCont.Name { + formList[i]["isRetract"] = true + } + } + + } + } + } + + } + } + + } + if mastrKeyVal, ok := v["masters_key"]; ok { + // fmt.Printf("mastrKeyVal----------->%T----------->%v\n", mastrKeyVal, mastrKeyVal) + if mastrKeyUint64, ok := mastrKeyVal.(uint64); ok { + formList[i]["masters_key"] = strconv.FormatUint(mastrKeyUint64, 10) + } + } + } + + // publicmethod.Result(100, formList, c) + publicmethod.ResultList(0, requestData.Page, requestData.PageSize, total, int64(len(formList)), formList, c) + } } /* @@ -1354,9 +1542,13 @@ func (l *ListPageFields) DevelopSpecificationsSend(listData []map[string]interfa switch mi { case "creater": - var myInfo modelshr.PersonArchives - myInfo.GetCont(map[string]interface{}{"`key`": mv}, "`name`") - sendInfo[mi] = myInfo.Name + mvInt, _ := publicmethod.StringToInt64(mv) + if mvInt != 0 { + var myInfo modelshr.PersonArchives + myInfo.GetCont(map[string]interface{}{"`key`": mvInt}, "`name`") + sendInfo[mi] = myInfo.Name + } + case "creater_time": timeInt, _ := publicmethod.StringToInt64(mv) sendInfo[mi] = publicmethod.UnixTimeToDay(timeInt, 27) @@ -1778,8 +1970,33 @@ func (a *ApiMethod) GainListTableField(c *gin.Context) { publicmethod.Result(1, err, c, "未知表单!无法获取字段!") return } + var masterTable []Result + var formJsonCont CustomerFormMaster + json.Unmarshal([]byte(customerFormMaster.MastesFormJson), &formJsonCont) + if formJsonCont.Form.DataSource == "yes" { + var sqlDb datacenter.DataBastType + sqlDb.Type = formJsonCont.Form.DataSourceConfig.DSN.SqlType + sqlDb.Ip = formJsonCont.Form.DataSourceConfig.DSN.Ip + sqlDb.DataBaseName = formJsonCont.Form.DataSourceConfig.DSN.DataBaseName + sqlDb.Port = formJsonCont.Form.DataSourceConfig.DSN.Port + sqlDb.UserName = formJsonCont.Form.DataSourceConfig.DSN.UserName + sqlDb.Pwd = formJsonCont.Form.DataSourceConfig.DSN.Password + sqlDborm, err := sqlDb.StartDataBast() + if err != nil { + sqlDborm, err = datacenter.GainDataStorce(formJsonCont.Form.DataSourceConfig.Id) + if err != nil { + publicmethod.Result(0, sqlDb, c) + return + } + } + masterTable, err = GainFormAllFieldList(sqlDborm, formJsonCont.Form.DataSourceConfig.TableKey) + + } else { + masterTable, err = GainFormTableField(customerFormMaster.TableKey) + + } - masterTable, err := GainFormTableField(customerFormMaster.TableKey) + // masterTable, err := GainFormTableField(customerFormMaster.TableKey) if err != nil { publicmethod.Result(1, err, c, "未知表单!无法获取字段!") return diff --git a/api/version1/customerform/type.go b/api/version1/customerform/type.go index 7489c25..0c05cfa 100644 --- a/api/version1/customerform/type.go +++ b/api/version1/customerform/type.go @@ -193,12 +193,33 @@ type UnitConfigStruct struct { // 表单信息 type FormStruct struct { - Size string `json:"size"` - FormName string `json:"formName"` //表单名称 - Name string `json:"name"` //表单标识 - LabelWidth string `json:"labelWidth"` //表单宽度 - Class string `json:"class"` //表单样式 - ShowColon bool `json:"showColon"` + Size string `json:"size"` + FormName string `json:"formName"` //表单名称 + Name string `json:"name"` //表单标识 + LabelWidth string `json:"labelWidth"` //表单宽度 + Class string `json:"class"` //表单样式 + ShowColon bool `json:"showColon"` + DataSource string `json:"dataSource"` //yes:是引用数据集,No:不引用数据集 + DataSourceConfig DataSourceConfigInfo `json:"dataSourceConfig"` +} + +// 数据源设置 +type DataSourceConfigInfo struct { + publicmethod.PublicId //数据源ID + DataBaseName string `json:"dataBaseName"` //数据源名称 + TableName string `json:"tableName"` //数据源 数据库名称 + TableKey string `json:"tableKey"` //数据源 数据库关键字 + DSN DsnConfig `json:"dsn"` //DSN参数 +} + +// DSN设置 +type DsnConfig struct { + SqlType string `json:"sqlType"` //数据库类型 + Ip string `json:"ip"` + DataBaseName string `json:"dataBaseName"` + Port int64 `json:"port"` + UserName string `json:"userName"` + Password string `json:"password"` } // 属性配置 diff --git a/api/version1/dataCenter/databastHanld.go b/api/version1/dataCenter/databastHanld.go new file mode 100644 index 0000000..e3fb801 --- /dev/null +++ b/api/version1/dataCenter/databastHanld.go @@ -0,0 +1,362 @@ +package datacenter + +import ( + "appPlatform/overall/publicmethod" + "encoding/json" + "errors" + "fmt" + "strings" + + "gorm.io/driver/mysql" + "gorm.io/driver/postgres" + "gorm.io/driver/sqlite" + "gorm.io/driver/sqlserver" + "gorm.io/gorm" +) + +/* +* +@ 作者: 秦东 +@ 时间: 2024-12-24 11:28:46 +@ 功能: 建立SqlServer +@ 参数 + + # + +@ 返回值 + + # + +@ 方法原型 + + # +*/ +func (c *DatabaseConfig) ConnectToSqlServer() (*gorm.DB, error) { + // connStr := "provider=SQLOLEDB;data source=你的服务器名;initial catalog=你的数据库名;user id=你的用户名;password=你的密码;" + // db, err := sql.Open("adodb", connStr) + // connStr := fmt.Sprintf("server=%v;user id=<%v>;password=<%v>;port=<%v>;database=<%v>;", c.Host, + // c.User, c.Password, c.Port, c.Name) + // db, err := sql.Open("mssql", connStr) + dsn := fmt.Sprintf("sqlserver://gorm:LoremIpsum86@%v:%v?database=%v", c.Host, c.Port, c.Name) + db, err := gorm.Open(sqlserver.Open(dsn), &gorm.Config{}) + if err != nil { + return nil, err + } + return db, nil +} + +/* +* +@ 作者: 秦东 +@ 时间: 2024-12-24 09:59:12 +@ 功能: 建立PostgreSQL +@ 参数 + + # + +@ 返回值 + + # + +@ 方法原型 + + # +*/ +func (c *DatabaseConfig) ConnectToPostgreSQL() (*gorm.DB, error) { + connStr := fmt.Sprintf("user=%s password=%s dbname=%s host=%s port=%d sslmode=disable", + c.User, c.Password, c.Name, c.Host, c.Port) + // db, err := sql.Open("postgres", connStr) + db, err := gorm.Open(postgres.Open(connStr), &gorm.Config{}) + if err != nil { + return nil, err + } + return db, nil +} + +/* +* +@ 作者: 秦东 +@ 时间: 2024-12-24 09:59:12 +@ 功能: 建立MySQL +@ 参数 + + # + +@ 返回值 + + # + +@ 方法原型 + + # +*/ +func (c *DatabaseConfig) ConnectToMySQL() (*gorm.DB, error) { + connStr := fmt.Sprintf("%v:%v@tcp(%v:%v)/%v?charset=utf8mb4", c.User, c.Password, c.Host, c.Port, c.Name) + // db, err := sql.Open("mysql", connStr) + fmt.Printf("sqlOpen: %v\n", connStr) + + sqlConfig := mysql.Config{ + DSN: connStr, // DSN + DefaultStringSize: 255, // string 类型字段的默认长度 + DisableDatetimePrecision: true, // 禁用 datetime 精度,MySQL 5.6 之前的数据库不支持 + DontSupportRenameIndex: true, // 重命名索引时采用删除并新建的方式,MySQL 5.7 之前的数据库和 MariaDB 不支持重命名索引 + DontSupportRenameColumn: true, // 用 `change` 重命名列,MySQL 8 之前的数据库和 MariaDB 不支持重命名列 + SkipInitializeWithVersion: false, // 根据版本自动配置 + } + + db, err := gorm.Open(mysql.New(sqlConfig)) + if err != nil { + return nil, err + } + + return db, nil +} + +/* +* +@ 作者: 秦东 +@ 时间: 2024-12-24 09:59:12 +@ 功能: 建立SQLite +@ 参数 + + # + +@ 返回值 + + # + +@ 方法原型 + + # +*/ +func (c *DatabaseConfig) ConnectToSQLite() (*gorm.DB, error) { + // db, err := sql.Open("sqlite3", c.Name) + db, err := gorm.Open(sqlite.Open("gorm.db"), &gorm.Config{}) + if err != nil { + return nil, err + } + return db, nil +} + +/* +* +@ 作者: 秦东 +@ 时间: 2024-12-24 16:25:17 +@ 功能: Tidb +@ 参数 + + # + +@ 返回值 + + # + +@ 方法原型 + + # +*/ +func (c *DatabaseConfig) ConnectToTiDb() (*gorm.DB, error) { + sql := fmt.Sprintf("%v:%v@tcp(%v:%v)/%v", c.User, c.Password, c.Host, c.Port, c.Name) + db, err := gorm.Open(mysql.Open(sql), &gorm.Config{}) + if err != nil { + return nil, err + } + return db, nil +} + +/* +* +@ 作者: 秦东 +@ 时间: 2024-12-24 10:04:00 +@ 功能: 启动数据库 +@ 参数 + + # + +@ 返回值 + + # + +@ 方法原型 + + # +*/ +func (d *DataBastType) StartDataBast() (openDb *gorm.DB, err error) { + var configInfo DatabaseConfig + + configInfo.Name = d.DataBaseName + configInfo.Host = d.Ip + configInfo.Port = d.Port + configInfo.User = d.UserName + configInfo.Password = d.Pwd + switch strings.ToLower(d.Type) { + case "PostgreSQL", "postgresql", "postgre sql": + openDb, err = configInfo.ConnectToPostgreSQL() + case "MySQL", "mysql": + openDb, err = configInfo.ConnectToMySQL() + case "SQLite", "sqlite": + openDb, err = configInfo.ConnectToSQLite() + case "SqlServer", "sql server", "sqlserver": + openDb, err = configInfo.ConnectToSqlServer() + case "Tidb", "tidb", "TiDb", "TIDB": + openDb, err = configInfo.ConnectToMySQL() + default: + msg := fmt.Sprintf("对不起!当前不支持'%v'数据库。", d.DataBaseName) + err = errors.New(msg) + } + return +} + +/* +* +@ 作者: 秦东 +@ 时间: 2024-12-24 13:07:56 +@ 功能: 获取数据库中说有表 +@ 参数 + + # + +@ 返回值 + + # + +@ 方法原型 + + #获取数据库表comment +*/ +func (d *DataBastType) ObtainDataBaseAllTableMysql() (tableKeyValue []DataBaseTableInfo, err error) { + // tableKeyValue := publicmethod.MapOut[string]() + sqlDb, err := d.StartDataBast() + if err != nil { + return + } + var valData []string + // // sql := fmt.Sprintf("SHOW %v", d.DataBaseName) + sqlDb.Raw("SHOW TABLES").Scan(&valData) + // if err != nil { + // return tableKeyValue, err + // } + // fmt.Println(rows) + fmt.Printf("%T----->%v\n", valData, valData) + // var + for _, v := range valData { + fmt.Printf("%T----->%v\n", v, v) + // sqlStr := fmt.Sprintf("SHOW `%v`", v) + + // sql := "SELECT TABLE_NAME AS `Table`, TABLE_COMMENT AS `Table Comment` FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = ?" + + // var list []Result + // err = sqlDb.Raw(sqlStr).Scan(&list).Error + // tableKeyValue[v] = list + var tableName string + sql := fmt.Sprintf("SELECT TABLE_COMMENT FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = \"%v\" AND TABLE_NAME = \"%v\";", d.DataBaseName, v) + err = sqlDb.Raw(sql).Scan(&tableName).Error + // tableKeyValue[v] = tableInfo + var tableInfo DataBaseTableInfo + tableInfo.TableName = tableName + tableInfo.TableKey = v + sqlStr := fmt.Sprintf("SHOW FULL COLUMNS FROM `%v`", v) + err = sqlDb.Raw(sqlStr).Scan(&tableInfo.Fields).Error + tableKeyValue = append(tableKeyValue, tableInfo) + } + // defer rows.Close() + // var tableName []string + // for rows.Next() { + // var table string + // err = rows.Scan(&table) + // if err == nil { + // tableName = append(tableName, table) + // } + // } + // if len(tableName) > 0 { + + // rows, err = sqlDb.Query("SHOW TABLE_COMMENT FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA IS NOT NULL") + // for _,v := range tableName{ + // sql := fmt.Sprintf("SHOW TABLE_COMMENT FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = %v AND TABLE_NAME = %v",d.DataBaseName,v) + // rows, err = sqlDb.Query("SHOW TABLE_COMMENT FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA IS NOT NULL") + // } + // if err != nil { + // return tableKeyValue, err + // } + // defer rows.Close() + + // var tableComments = make(map[string]string) + // for rows.Next() { + // var table, comment string + // if err := rows.Scan(&table, &comment); err != nil { + // // log.Fatal(err) + // fmt.Printf("rows----err---->:%v\n", err) + // } + // tableComments[table] = comment + // } + // fmt.Printf("rows-------->:%v\n", tableComments) + // } + + return tableKeyValue, err +} + +/* +* +@ 作者: 秦东 +@ 时间: 2024-12-30 16:49:14 +@ 功能: 获取数据源 +@ 参数 + + # + +@ 返回值 + + # + +@ 方法原型 + + # +*/ +func GainDataStorce(dataId string) (openDb *gorm.DB, err error) { + sendUrl := fmt.Sprintf("http://120.224.6.6:29911/prod-api/database/app/datasource/page?pageNum=1&pageSize=%v&databaseName=&dataType=", 100000) + // fmt.Printf("1获取数据源===>%v\n", sendUrl) + getData := publicmethod.CurlGet(sendUrl) + // fmt.Printf("2获取数据源===>%v\n", getData) + var sendMap map[string]interface{} + json.Unmarshal(getData, &sendMap) + var sqlDb DataBastType + // fmt.Printf("3获取数据源===>%v\n", sendMap) + if code, ok := sendMap["code"]; ok { + // fmt.Printf("4获取数据源===>%v\n", code) + + codeInt, _ := publicmethod.StringToInt64(code) + if codeInt == 200 { + // jsonval, _ := json.Marshal(sendMap) + // fmt.Printf("\n\n\n6获取数据源===>%v\n\n\n", string(jsonval)) + if dataval, isOk := sendMap["data"]; isOk { + if dataMap, ok := dataval.(map[string]interface{}); ok { + if records, isOk := dataMap["records"]; isOk { + if recordAry, isOk := records.([]interface{}); isOk { + for _, v := range recordAry { + if vMAp, ok := v.(map[string]interface{}); ok { + // fmt.Printf("5获取数据源===>%T\n===>%v\n\n\n", vMAp, vMAp["id"]) + idStr := publicmethod.TypeToInterface(vMAp["id"]) + if idStr == dataId { + typeVal, _ := publicmethod.StringToInt64(vMAp["datasourceType"]) + sqlDb.Type = publicmethod.DatabaseIntToString(typeVal) + sqlDb.Ip = publicmethod.TypeToInterface(vMAp["ipAddress"]) + sqlDb.DataBaseName = publicmethod.TypeToInterface(vMAp["databaseName"]) + sqlDb.Port, _ = publicmethod.StringToInt64(vMAp["port"]) + sqlDb.UserName = publicmethod.TypeToInterface(vMAp["account"]) + sqlDb.Pwd = publicmethod.TypeToInterface(vMAp["password"]) + } + + } + // fmt.Printf("5获取数据源===>%T\n===>%v\n\n\n", v, v) + } + } + } + } + + } + } + } + // fmt.Printf("7获取数据源===>%T\n===>%v\n\n\n", sqlDb, sqlDb) + openDb, err = sqlDb.StartDataBast() + return +} diff --git a/api/version1/dataCenter/runDataBase.go b/api/version1/dataCenter/runDataBase.go new file mode 100644 index 0000000..6d09185 --- /dev/null +++ b/api/version1/dataCenter/runDataBase.go @@ -0,0 +1,58 @@ +package datacenter + +import ( + "appPlatform/overall/publicmethod" + "fmt" + + "github.com/gin-gonic/gin" +) + +/* +* +@ 作者: 秦东 +@ 时间: 2024-12-24 11:43:02 +@ 功能: 获取数据表 +@ 参数 + + # + +@ 返回值 + + # + +@ 方法原型 + + # +*/ +func (a *ApiMethod) GainDataTable(c *gin.Context) { + var requestData DataBastType + err := c.ShouldBindJSON(&requestData) + if err != nil { + publicmethod.Result(100, err, c) + return + } + if requestData.Type == "" { + publicmethod.Result(1, err, c, "未知数据库类型!请先确实是什么数据库类型!") + return + } + if requestData.DataBaseName == "" { + publicmethod.Result(1, err, c, "请输入数据库名称!") + return + } + if requestData.Ip == "" { + publicmethod.Result(1, err, c, "请输入数据库地址!") + return + } + + if requestData.UserName == "" { + publicmethod.Result(1, err, c, "请输入用户名!") + return + } + if requestData.Pwd == "" { + publicmethod.Result(1, err, c, "请输入密码!") + return + } + tableInfo, err := requestData.ObtainDataBaseAllTableMysql() + fmt.Printf("tableInfo:%v\n", tableInfo) + publicmethod.Result(0, tableInfo, c) +} diff --git a/api/version1/dataCenter/type.go b/api/version1/dataCenter/type.go index 65fd4d3..f2b535d 100644 --- a/api/version1/dataCenter/type.go +++ b/api/version1/dataCenter/type.go @@ -47,3 +47,44 @@ type DataInfoPost struct { Url string `json:"url"` DataInfo interface{} `json:"dataInfo"` } + +// 数据库链接参数 +type DataBastType struct { + Type string `json:"type"` //数据库类型 + DataBaseName string `json:"dataBaseName"` //数据库名称 + Ip string `json:"ip"` //数据库地址 + Port int64 `json:"port"` //数据库端口 + UserName string `json:"userName"` //数据库帐号 + Pwd string `json:"password"` //数据库密码 +} +type DatabaseConfig struct { + Name string + Host string + Port int64 + User string + Password string +} + +// 数据库表结构 +type Result struct { + Field string `json:"fieldes"` + Type string `json:"types"` + Attribute string `json:"attribute"` + Collation string `json:"collation"` + Null string `json:"nullVal"` + Key string `json:"key"` + Default string `json:"defaultVal"` + Extra string `json:"extra"` + Privileges string `json:"privileges"` + Comment string `json:"comment"` + Pattern string `json:"pattern"` + Classify string `json:"classify"` + Auxiliary string `json:"auxiliary"` +} + +// 输出数据表数据 +type DataBaseTableInfo struct { + TableName string `json:"tableName"` //数据表名称 + TableKey string `json:"tableKey"` //数据表标识 + Fields []Result `json:"fields"` //表字段 +} diff --git a/api/version1/taskplatform/taskmanagement/appControl.go b/api/version1/taskplatform/taskmanagement/appControl.go index e2a7be2..6ddd005 100644 --- a/api/version1/taskplatform/taskmanagement/appControl.go +++ b/api/version1/taskplatform/taskmanagement/appControl.go @@ -2,6 +2,7 @@ package taskmanagement import ( "appPlatform/api/version1/customerform" + datacenter "appPlatform/api/version1/dataCenter" "appPlatform/models/customerForm" "appPlatform/models/modelAppPlatform" "appPlatform/models/modelshr" @@ -123,21 +124,56 @@ func (a *ApiMethod) CreateAppTask(c *gin.Context) { taskCont.FlowRunSing = flowInfo.Id masrWriteMap["flow_id"] = flowInfo.Id } - //判断是否 - if len(sunFieldAry) > 0 { - //有子表 - sunTypeAry := make(map[string]map[string]customerform.MasterStruct) - for _, v := range formUnitCont.SunFormInfo { - sunTypeAry[v.TableName] = v.UbitInfo + + if formJsonCont.Form.DataSource == "yes" { + var sqlDb datacenter.DataBastType + sqlDb.Type = formJsonCont.Form.DataSourceConfig.DSN.SqlType + sqlDb.Ip = formJsonCont.Form.DataSourceConfig.DSN.Ip + sqlDb.DataBaseName = formJsonCont.Form.DataSourceConfig.DSN.DataBaseName + sqlDb.Port = formJsonCont.Form.DataSourceConfig.DSN.Port + sqlDb.UserName = formJsonCont.Form.DataSourceConfig.DSN.UserName + sqlDb.Pwd = formJsonCont.Form.DataSourceConfig.DSN.Password + sqlDborm, err := sqlDb.StartDataBast() + if err != nil { + sqlDborm, err = datacenter.GainDataStorce(formJsonCont.Form.DataSourceConfig.Id) + if err != nil { + publicmethod.Result(0, sqlDb, c) + return + } } + //判断是否 + if len(sunFieldAry) > 0 { + //有子表 + sunTypeAry := make(map[string]map[string]customerform.MasterStruct) + for _, v := range formUnitCont.SunFormInfo { + sunTypeAry[v.TableName] = v.UbitInfo + } - err = WriteSunDatabase(uuid, userCont.Key, cureeTime, formCont.TableKey, masrWriteMap, sunFieldAry, sunTypeAry) + err = WriteSunDatabaseSoucer(sqlDborm, uuid, userCont.Key, cureeTime, formJsonCont.Form.DataSourceConfig.TableKey, masrWriteMap, sunFieldAry, sunTypeAry) + } else { + // //无子表 + err = sqlDborm.Table(formJsonCont.Form.DataSourceConfig.TableKey).Create(masrWriteMap).Error + publicmethod.WriteLog("write", "写入自定义表单", formJsonCont.Form.DataSourceConfig.TableKey, err) + } } else { - // //无子表 - err = overall.CONSTANT_DB_CustomerForm.Table(formCont.TableKey).Create(masrWriteMap).Error - publicmethod.WriteLog("write", "写入自定义表单", formCont.TableKey, err) + //判断是否 + if len(sunFieldAry) > 0 { + //有子表 + sunTypeAry := make(map[string]map[string]customerform.MasterStruct) + for _, v := range formUnitCont.SunFormInfo { + sunTypeAry[v.TableName] = v.UbitInfo + } + + err = WriteSunDatabase(uuid, userCont.Key, cureeTime, formCont.TableKey, masrWriteMap, sunFieldAry, sunTypeAry) + + } else { + // //无子表 + err = overall.CONSTANT_DB_CustomerForm.Table(formCont.TableKey).Create(masrWriteMap).Error + publicmethod.WriteLog("write", "写入自定义表单", formCont.TableKey, err) + } } + if err != nil { publicmethod.Result(104, err, c) return diff --git a/api/version1/taskplatform/taskmanagement/formcontrol.go b/api/version1/taskplatform/taskmanagement/formcontrol.go index da3b573..1b15ab9 100644 --- a/api/version1/taskplatform/taskmanagement/formcontrol.go +++ b/api/version1/taskplatform/taskmanagement/formcontrol.go @@ -2,6 +2,7 @@ package taskmanagement import ( "appPlatform/api/version1/customerform" + datacenter "appPlatform/api/version1/dataCenter" "appPlatform/models/customerForm" "appPlatform/models/modelAppPlatform" "appPlatform/models/modelshr" @@ -15,6 +16,7 @@ import ( "time" "github.com/gin-gonic/gin" + "gorm.io/gorm" ) /* @@ -842,6 +844,9 @@ func (a *ApiMethod) AddCustomerForm(c *gin.Context) { } } + var formJsonCont customerform.CustomerFormMaster + json.Unmarshal([]byte(formCont.MastesFormJson), &formJsonCont) + masterField := publicmethod.MapOut[string]() //主表数据 sunFieldAry := publicmethod.MapOut[string]() //子表数据 for k, v := range mapData { @@ -859,9 +864,6 @@ func (a *ApiMethod) AddCustomerForm(c *gin.Context) { uuid := publicmethod.GetUUid(1) //统一识别符 cureeTime := time.Now().Unix() //写入时间 - var formJsonCont customerform.CustomerFormMaster - json.Unmarshal([]byte(formCont.MastesFormJson), &formJsonCont) - var formUnitCont customerform.FormUnitInfo formUnitCont.GainMasterAndSunFormUnit(formCont.TableKey, formJsonCont.List, true) masterUnitList := make(map[string]customerform.MasterStruct) @@ -891,20 +893,56 @@ func (a *ApiMethod) AddCustomerForm(c *gin.Context) { taskCont.FlowRunSing = flowInfo.Id } - //判断是否 - if len(sunFieldAry) > 0 { - //有子表 - sunTypeAry := make(map[string]map[string]customerform.MasterStruct) - for _, v := range formUnitCont.SunFormInfo { - sunTypeAry[v.TableName] = v.UbitInfo + if formJsonCont.Form.DataSource == "yes" { + var sqlDb datacenter.DataBastType + sqlDb.Type = formJsonCont.Form.DataSourceConfig.DSN.SqlType + sqlDb.Ip = formJsonCont.Form.DataSourceConfig.DSN.Ip + sqlDb.DataBaseName = formJsonCont.Form.DataSourceConfig.DSN.DataBaseName + sqlDb.Port = formJsonCont.Form.DataSourceConfig.DSN.Port + sqlDb.UserName = formJsonCont.Form.DataSourceConfig.DSN.UserName + sqlDb.Pwd = formJsonCont.Form.DataSourceConfig.DSN.Password + sqlDborm, err := sqlDb.StartDataBast() + if err != nil { + sqlDborm, err = datacenter.GainDataStorce(formJsonCont.Form.DataSourceConfig.Id) + if err != nil { + publicmethod.Result(0, sqlDb, c) + return + } } - err = WriteSunDatabase(uuid, userCont.Key, cureeTime, formCont.TableKey, masrWriteMap, sunFieldAry, sunTypeAry) + //判断是否 + if len(sunFieldAry) > 0 { + //有子表 + sunTypeAry := make(map[string]map[string]customerform.MasterStruct) + for _, v := range formUnitCont.SunFormInfo { + sunTypeAry[v.TableName] = v.UbitInfo + } + + err = WriteSunDatabaseSoucer(sqlDborm, uuid, userCont.Key, cureeTime, formJsonCont.Form.DataSourceConfig.TableKey, masrWriteMap, sunFieldAry, sunTypeAry) + + } else { + // //无子表 + err = sqlDborm.Table(formJsonCont.Form.DataSourceConfig.TableKey).Create(masrWriteMap).Error + publicmethod.WriteLog("write", "写入自定义表单", formJsonCont.Form.DataSourceConfig.TableKey, err) + } } else { - // //无子表 - err = overall.CONSTANT_DB_CustomerForm.Table(formCont.TableKey).Create(masrWriteMap).Error - publicmethod.WriteLog("write", "写入自定义表单", formCont.TableKey, err) + + //判断是否 + if len(sunFieldAry) > 0 { + //有子表 + sunTypeAry := make(map[string]map[string]customerform.MasterStruct) + for _, v := range formUnitCont.SunFormInfo { + sunTypeAry[v.TableName] = v.UbitInfo + } + + err = WriteSunDatabase(uuid, userCont.Key, cureeTime, formCont.TableKey, masrWriteMap, sunFieldAry, sunTypeAry) + + } else { + // //无子表 + err = overall.CONSTANT_DB_CustomerForm.Table(formCont.TableKey).Create(masrWriteMap).Error + publicmethod.WriteLog("write", "写入自定义表单", formCont.TableKey, err) + } } if err != nil { publicmethod.Result(104, err, c) @@ -930,4 +968,97 @@ func (a *ApiMethod) AddCustomerForm(c *gin.Context) { sendData["mapData"] = mapData publicmethod.Result(0, sendData, c) + +} + +/* +* +@ 作者: 秦东 +@ 时间: 2025-01-03 16:22:20 +@ 功能: 处理有源数据库数据 +@ 参数 + + #sqlDb 数据库句柄 + #uuid 唯一标识 + #creater 创建人 + #createrTime 创建时间 + #masterTableName 主表标识 + #masterDataCont 主表数据 + #sunDataList 字表数据列表 + +@ 返回值 + + # + +@ 方法原型 + + # +*/ +func WriteSunDatabaseSoucer(sqlDb *gorm.DB, uuid, creater, createrTime int64, masterTableName string, masterDataCont, sunDataList map[string]interface{}, sunTable map[string]map[string]customerform.MasterStruct) (err error) { + if len(masterDataCont) > 0 { + if len(sunDataList) > 0 { + sunMasterMap := publicmethod.MapOut[string]() + //子表存在时,执行主表和子表数据写入 + for k, v := range sunDataList { + // if k == "table1693811044212" { + s, ok := v.([]interface{}) //获取值类型 + if !ok { + err = errors.New("表单数据错误!请验证后重新提交!") + return + } else { + //判断是否有数据 + if len(s) > 0 { + var sunCont []map[string]interface{} + for _, sv := range s { //拆分子表 + if sdf, isOk := sv.(map[string]interface{}); isOk { + if sunTableType, sunIsOk := sunTable[k]; sunIsOk { + masterWriteVal := MakeFormMapData(uuid, creater, createrTime, sdf, sunTableType, 2) //转换数据表值 + if len(masterWriteVal) > 0 { + sunCont = append(sunCont, masterWriteVal) + } + } + } + } + if len(sunCont) > 0 { + sunMasterMap[k] = sunCont + } + } + } + } + if len(sunMasterMap) > 0 { + gormDb := overall.CONSTANT_DB_CustomerForm + masterErr := sqlDb.Table(masterTableName).Create(masterDataCont).Error + sunCreateIsOk := true + for k, v := range sunMasterMap { + sunErr := gormDb.Table(k).Create(v).Error + if sunErr != nil { + sunCreateIsOk = false + break + } + } + if masterErr == nil && sunCreateIsOk { + + publicmethod.WriteLog("write", "写入自定义表单", err, masterDataCont, sunDataList) + } else { + + err = errors.New("表单数据提交失败!请重新提交") + publicmethod.WriteLog("e", "写入自定义表单", masterTableName, err) + } + } else { + + masterErr := sqlDb.Table(masterTableName).Create(masterDataCont).Error + if masterErr != nil { + publicmethod.WriteLog("write", "写入自定义表单", masterTableName, masterErr) + } + } + } else { + //子表不存在时,写入主表数据 + err = sqlDb.Table(masterTableName).Create(masterDataCont).Error + publicmethod.WriteLog("write", "写入自定义表单", masterTableName, err) + } + } else { + err = errors.New("表单数据提交失败!请重新提交") + publicmethod.WriteLog("e", "写入自定义表单", masterTableName, err) + } + return } diff --git a/api/version1/taskplatform/taskmanagement/ruanTask.go b/api/version1/taskplatform/taskmanagement/ruanTask.go index dd073c8..4cd1f1f 100644 --- a/api/version1/taskplatform/taskmanagement/ruanTask.go +++ b/api/version1/taskplatform/taskmanagement/ruanTask.go @@ -2,6 +2,7 @@ package taskmanagement import ( "appPlatform/api/version1/customerform" + datacenter "appPlatform/api/version1/dataCenter" "appPlatform/models/customerForm" "appPlatform/models/modelAppPlatform" "appPlatform/models/modelshr" @@ -18,6 +19,7 @@ import ( "time" "github.com/gin-gonic/gin" + "gorm.io/gorm" ) /* @@ -74,10 +76,142 @@ func (a *ApiMethod) GainTaskFormInfo(c *gin.Context) { sendData := publicmethod.MapOut[string]() sendData["structure"] = formVersionInfo - sendData["tableData"] = GainOnlyOneCustomerFormLog(requestData.Id, formVersionInfo.TableKey, formVersionInfo.TableStructure, tableUnitList) + + if formJsonCont.Form.DataSource == "yes" { + var sqlDb datacenter.DataBastType + sqlDb.Type = formJsonCont.Form.DataSourceConfig.DSN.SqlType + sqlDb.Ip = formJsonCont.Form.DataSourceConfig.DSN.Ip + sqlDb.DataBaseName = formJsonCont.Form.DataSourceConfig.DSN.DataBaseName + sqlDb.Port = formJsonCont.Form.DataSourceConfig.DSN.Port + sqlDb.UserName = formJsonCont.Form.DataSourceConfig.DSN.UserName + sqlDb.Pwd = formJsonCont.Form.DataSourceConfig.DSN.Password + sqlDborm, err := sqlDb.StartDataBast() + if err != nil { + sqlDborm, err = datacenter.GainDataStorce(formJsonCont.Form.DataSourceConfig.Id) + if err != nil { + publicmethod.Result(0, sqlDb, c) + return + } + } + + sendData["tableData"] = GainOnlyOneCustomerFormLogYuan(sqlDborm, requestData.Id, formJsonCont.Form.DataSourceConfig.TableKey, formVersionInfo.TableStructure, tableUnitList) + + } else { + + sendData["tableData"] = GainOnlyOneCustomerFormLog(requestData.Id, formVersionInfo.TableKey, formVersionInfo.TableStructure, tableUnitList) + } + publicmethod.Result(0, sendData, c) } +/* +* +@ 作者: 秦东 +@ 时间: 2025-01-03 16:31:43 +@ 功能: +@ 参数 + + # + +@ 返回值 + + # + +@ 方法原型 + + # +*/ +func GainOnlyOneCustomerFormLogYuan(sqlDb *gorm.DB, id, masterTableName, sunTableJson string, tableUnitList customerform.TableFormUnit) map[string]interface{} { + sendData := publicmethod.MapOut[string]() + if masterTableName == "" || id == "" || id == "0" { + return sendData + } + + err := sqlDb.Table(masterTableName).Where("`masters_key` = ?", id).Find(&sendData).Error + if err != nil { + return sendData + } + + for i, v := range sendData { + switch i { + case "id": + sendData[i] = publicmethod.TypeToInterface(v) + case "masters_key": + sendData[i] = publicmethod.TypeToInterface(v) + case "creater": + sendData[i] = publicmethod.TypeToInterface(v) + case "creater_time": + sendData[i] = publicmethod.TypeToInterface(v) + case "edit_time": + sendData[i] = publicmethod.TypeToInterface(v) + case "flow_id": + sendData[i] = publicmethod.TypeToInterface(v) + default: + // sendData[i] = v + sendData[i] = ChuLiMasterTableData(i, v, tableUnitList.MasterInfo, sendData) + } + } + + if sunTableJson != "" { + sunSqlMap := make(map[string]string) + err = json.Unmarshal([]byte(sunTableJson), &sunSqlMap) + if err == nil { + if len(sunSqlMap) > 0 { + for _, v := range sunSqlMap { + var sunTableData []map[string]interface{} + overall.CONSTANT_DB_CustomerForm.Table(v).Where("`masters_key` = ?", id).Find(&sunTableData) + var sunTableFormInfor []map[string]interface{} + for _, tv := range sunTableData { + sunFormContent := publicmethod.MapOut[string]() + for si, sv := range tv { + switch si { + case "id": + sunFormContent[si] = publicmethod.TypeToInterface(sv) + case "masters_key": + sunFormContent[si] = publicmethod.TypeToInterface(sv) + case "creater": + sunFormContent[si] = publicmethod.TypeToInterface(sv) + case "creater_time": + sunFormContent[si] = publicmethod.TypeToInterface(sv) + case "edit_time": + sunFormContent[si] = publicmethod.TypeToInterface(sv) + case "flow_id": + sunFormContent[si] = publicmethod.TypeToInterface(sv) + default: + if len(tableUnitList.SunFormInfo) > 0 { + isWrite := true + for _, tv := range tableUnitList.SunFormInfo { + if sonUnitCont, ok := tv[v]; ok { + isWrite = false + sunFormContent[si] = ChuLiMasterTableData(si, sv, sonUnitCont, tv) + } + } + if isWrite { + sunFormContent[si] = sv + } + } else { + sunFormContent[si] = sv + } + + } + + } + sunTableFormInfor = append(sunTableFormInfor, sunFormContent) + } + // fmt.Printf("sunTableFormInfor----->%v----->%T----->%v\n", v, sunTableFormInfor, sunTableFormInfor) + if len(sunTableFormInfor) > 0 { + sendData[v] = sunTableFormInfor + } else { + sendData[v] = []string{} + } + + } + } + } + } + return sendData +} + /* * @ 作者: 秦东 @@ -551,8 +685,28 @@ func (a *ApiMethod) EditCustomerTable(c *gin.Context) { var userCont modelshr.ManCont userCont.GetLoginCont(context) //当前操作人 cureeTime := time.Now().Unix() + var masterOldData map[string]interface{} + if formJsonCont.Form.DataSource == "yes" { + var sqlDb datacenter.DataBastType + sqlDb.Type = formJsonCont.Form.DataSourceConfig.DSN.SqlType + sqlDb.Ip = formJsonCont.Form.DataSourceConfig.DSN.Ip + sqlDb.DataBaseName = formJsonCont.Form.DataSourceConfig.DSN.DataBaseName + sqlDb.Port = formJsonCont.Form.DataSourceConfig.DSN.Port + sqlDb.UserName = formJsonCont.Form.DataSourceConfig.DSN.UserName + sqlDb.Pwd = formJsonCont.Form.DataSourceConfig.DSN.Password + sqlDborm, err := sqlDb.StartDataBast() + if err != nil { + sqlDborm, err = datacenter.GainDataStorce(formJsonCont.Form.DataSourceConfig.Id) + if err != nil { + publicmethod.Result(0, sqlDb, c) + return + } + } + masterOldData, err = MasterTableHandleYuanNew(sqlDborm, formJsonCont.Form.DataSourceConfig.TableKey, userCont.Key, cureeTime, masterField, tableUnitList.MasterInfo) + } else { + masterOldData, err = MasterTableHandleNew(tableVersion.TableKey, userCont.Key, cureeTime, masterField, tableUnitList.MasterInfo) + } - masterOldData, err := MasterTableHandleNew(tableVersion.TableKey, userCont.Key, cureeTime, masterField, tableUnitList.MasterInfo) if err != nil { publicmethod.Result(106, err, c) return @@ -600,6 +754,106 @@ func (a *ApiMethod) EditCustomerTable(c *gin.Context) { publicmethod.Result(0, sendInfo, c) } +/* +* +@ 作者: 秦东 +@ 时间: 2025-01-03 16:52:28 +@ 功能: 主表处理数据(新版)有源 +@ 参数 + + # + +@ 返回值 + + # + +@ 方法原型 + + # +*/ +func MasterTableHandleYuanNew(sqlDb *gorm.DB, tableName string, creater, cureeTime int64, newsData map[string]interface{}, MasterInfo []customerform.UnitAttribute) (map[string]interface{}, error) { + var oldData map[string]interface{} + if len(newsData) > 0 { + var id interface{} + editData := publicmethod.MapOut[string]() + for i, v := range newsData { + + if i == "id" { + // if idStr, ok := v.(string); ok { + // id = idStr + // } else { + // id = idStr + // } + id = v + } + if !publicmethod.RemoveReservedWord(i) { + // fmt.Printf("i:%v---->t:%T---->v:%v\n", i, v, v) + + for _, mv := range MasterInfo { + if i == mv.Key { + fmt.Printf("mv:%v---->t:%v---->---->v:%v\n", i, mv.Class, mv.Auxiliary) + switch mv.Class { + case "datePicker": + auxVal := publicmethod.TypeToInterface(mv.Auxiliary) + if !publicmethod.RemoveReservedWordTime(auxVal) { + editData[i] = v + } else { + if valAry, isAry := v.([]interface{}); isAry { + if len(valAry) > 0 { + editData[i] = valAry[0] + endKey := fmt.Sprintf("%v_end", i) + editData[endKey] = valAry[len(valAry)-1] + } + } + } + case "checkbox": + valStrJson, _ := json.Marshal(v) + editData[i] = string(valStrJson) + case "select": + if auxVal, isAc := mv.Auxiliary.(bool); isAc { + if auxVal { + valStrJson, _ := json.Marshal(v) + editData[i] = string(valStrJson) + } else { + editData[i] = v + } + } else { + editData[i] = v + } + + default: + if valAry, isAry := v.([]interface{}); isAry { + + if len(valAry) > 0 { + valStrJson, _ := json.Marshal(valAry) + editData[i] = string(valStrJson) + } else { + editData[i] = "" + } + } else { + editData[i] = v + } + + } + } + + } + } + } + err := sqlDb.Table(tableName).Where("`id` = ?", id).Find(&oldData).Error + if err != nil { + return oldData, err + } + editData["`edit_time`"] = cureeTime + editData["`creater`"] = creater + editData["`states`"] = 1 + err = sqlDb.Table(tableName).Where("`id` = ?", id).Updates(&editData).Error + + return oldData, err + } + return oldData, nil +} + /* * @ 作者: 秦东 diff --git a/api/version1/taskplatform/taskmanagement/runTaskFlow.go b/api/version1/taskplatform/taskmanagement/runTaskFlow.go index 96175cc..7fb54d2 100644 --- a/api/version1/taskplatform/taskmanagement/runTaskFlow.go +++ b/api/version1/taskplatform/taskmanagement/runTaskFlow.go @@ -3,6 +3,7 @@ package taskmanagement import ( "appPlatform/api/version1/customerform" "appPlatform/models/customerForm" + "appPlatform/models/modelAppPlatform" "appPlatform/models/modelshr" "appPlatform/models/reviseform" "appPlatform/overall" @@ -919,3 +920,228 @@ func HistoryValueHand(field string, val interface{}, nameKey []customerform.Unit } return } + +/* +* +@ 作者: 秦东 +@ 时间: 2024-12-19 16:13:29 +@ 功能: 获取web表单数据 +@ 参数 + + # + +@ 返回值 + + # + +@ 方法原型 + + # +*/ +func (a *ApiMethod) GainWebTaskFlowInfo(c *gin.Context) { + var requestData publicmethod.PublicId + err := c.ShouldBindJSON(&requestData) + if err != nil { + publicmethod.Result(100, err, c) + return + } + if requestData.Id == "" { + publicmethod.Result(100, err, c) + return + } + //获取任务 + var taskInfo TaskInfoStruct + err = taskInfo.GetCont(map[string]interface{}{"`masters_key`": requestData.Id}) + if err != nil { + publicmethod.Result(107, err, c) + return + } + taskInfo.MastersKeyStr = strconv.FormatInt(taskInfo.MastersKey, 10) + taskInfo.FlowKeyStr = strconv.FormatInt(taskInfo.FlowKey, 10) + taskInfo.TableKeyStr = strconv.FormatInt(taskInfo.TableKey, 10) + taskInfo.AppKeyStr = strconv.FormatInt(taskInfo.AppKey, 10) + taskInfo.RunFlowIdStr = strconv.FormatInt(taskInfo.Id, 10) + taskInfo.RunFlowId = taskInfo.Id + taskInfo.FormVersionId = strconv.FormatInt(taskInfo.VersionId, 10) + taskInfo.IdStr = strconv.FormatInt(taskInfo.Id, 10) + taskInfo.RunFlowIdStr = strconv.FormatInt(taskInfo.Id, 10) + taskInfo.FlowKeys = strconv.FormatInt(taskInfo.FlowKey, 10) + taskInfo.CreaterInfo = GainSmaillUserInfo[int64](taskInfo.Creater) + taskInfo.MastersKeyStr = strconv.FormatInt(taskInfo.MastersKey, 10) + taskInfo.AppKeyStr = strconv.FormatInt(taskInfo.AppKey, 10) + taskInfo.TableKeyStr = strconv.FormatInt(taskInfo.TableKey, 10) + if taskInfo.NextExecutor != "" { + nextAry := strings.Split(taskInfo.NextExecutor, ",") + for _, v := range nextAry { + taskInfo.CurrentNodeUser = append(taskInfo.CurrentNodeUser, GainSmaillUserInfo[string](v)) + } + } + taskInfo.StartDate = publicmethod.UnixTimeToDay(taskInfo.StartTime, 27) + if taskInfo.NextStep != 0 { + nodeCont, idTrue := GainCurreNode(taskInfo.FlowCont, taskInfo.CurrentStep, taskInfo.NextStep, taskInfo.Status) + if idTrue { + taskInfo.CurrentNodeName = nodeCont.NodeName + } + } + if taskInfo.MastesForm == "" || taskInfo.MastesFormJson == "" { + taskInfo.MastesForm, taskInfo.MastesFormJson = GainTaskFormData(taskInfo.FlowKey) + } + if taskInfo.Status == 3 && taskInfo.NextStep != 0 { + if taskInfo.CurrentStep == 1 { + taskInfo.IsRetract = true + } + } + + //获取表单数据 + var formVersionInfo CallBackFormStruct + err = formVersionInfo.GetCont(map[string]interface{}{"`id`": taskInfo.VersionId}) + if err != nil { + publicmethod.Result(107, err, c) + return + } + formVersionInfo.FlowkeyStr = strconv.FormatInt(formVersionInfo.Flowkey, 10) + formVersionInfo.CreaterStr = strconv.FormatInt(formVersionInfo.Creater, 10) + formVersionInfo.MastesForm = taskInfo.MastesForm + formVersionInfo.MastesFormJson = taskInfo.MastesFormJson + + //展开表单 + var formJsonCont customerform.CustomerFormMaster + json.Unmarshal([]byte(taskInfo.MastesFormJson), &formJsonCont) + + var tableUnitList customerform.TableFormUnit + tableUnitList.AnalysisTableFormUnitAttribute("", formJsonCont.List) + + sendData := publicmethod.MapOut[string]() + sendData["taskInfo"] = taskInfo + sendData["structure"] = formVersionInfo + sendData["tableData"] = GainOnlyOneCustomerFormLog(requestData.Id, formVersionInfo.TableKey, formVersionInfo.TableStructure, tableUnitList) + publicmethod.Result(0, sendData, c) +} + +/* +* +@ 作者: 秦东 +@ 时间: 2023-11-23 16:17:17 +@ 功能: 获取简短人员信息 +@ 参数 + + #userKey 操作人 + +@ 返回值 + + # + +@ 方法原型 + + # +*/ +func GainSmaillUserInfo[T publicmethod.GenericityVariable](userKey T) (createrInfo UserSmallInfo) { + var userInfo modelshr.ManCont + err := userInfo.GetCont(map[string]interface{}{"`key`": userKey}, "`id`", "`key`", "`name`", "`number`", "`icon`", "`icon_photo`", "`wechat`", "`work_wechat`") + if err != nil { + return + } + createrInfo.Id = userInfo.Id + createrInfo.Key = strconv.FormatInt(userInfo.Key, 10) + createrInfo.Name = userInfo.Name + createrInfo.Number = userInfo.Number + createrInfo.Icon = userInfo.Icon + if userInfo.IconPhpto != "" { + createrInfo.Icon = userInfo.IconPhpto + } + createrInfo.WeChat = userInfo.Wechat + if userInfo.WorkWechat != "" { + createrInfo.WeChat = userInfo.WorkWechat + } + return +} + +/* +* +@ 作者: 秦东 +@ 时间: 2023-11-23 16:34:22 +@ 功能: 获取当前节点 +@ 参数 + + # + +@ 返回值 + + # + +@ 方法原型 + + # +*/ +func GainCurreNode(flowStr string, step, nextStep, state int) (nodeInfo RunFlow, isOk bool) { + if flowStr == "" { + return + } + var flowAry []RunFlow + err := json.Unmarshal([]byte(flowStr), &flowAry) + if err != nil { + return + } + if nextStep == 0 { + step = len(flowAry) + } else { + switch state { + case 1: + step = 0 + case 2: + if step != 1 { + step = step + 1 + } + case 3: + step = step + 1 + case 4: + step = len(flowAry) + default: + step = step + 1 + } + } + for _, v := range flowAry { + if v.Step == step { + nodeInfo = v + isOk = true + return + } + } + return +} + +/* +* +@ 作者: 秦东 +@ 时间: 2023-11-24 11:36:32 +@ 功能: 获取表单数据 +@ 参数 + + # + +@ 返回值 + + # + +@ 方法原型 + + # +*/ +func GainTaskFormData(taskId int64) (mastesform, mastesformjson string) { + if taskId > 0 { + var taskInfo modelAppPlatform.Task + err := taskInfo.GetCont(map[string]interface{}{"`masters_key`": taskId}, "`version_id`") + if err != nil { + return + } + var formVerInfo modelAppPlatform.CustomerFormVersion + err = formVerInfo.GetCont(map[string]interface{}{"`id`": taskInfo.VersionId}, "`mastesform`", "`mastesformjson`") + if err != nil { + return + } + mastesform = formVerInfo.MastesForm + mastesformjson = formVerInfo.MastesFormJson + taskInfo.EiteCont(map[string]interface{}{"`masters_key`": taskId}, map[string]interface{}{"`mastesform`": formVerInfo.MastesForm, "`mastesformjson`": formVerInfo.MastesFormJson}) + } + return +} diff --git a/api/version1/taskplatform/taskmanagement/sendWechatMsg.go b/api/version1/taskplatform/taskmanagement/sendWechatMsg.go index 8a740fd..dfbe75b 100644 --- a/api/version1/taskplatform/taskmanagement/sendWechatMsg.go +++ b/api/version1/taskplatform/taskmanagement/sendWechatMsg.go @@ -136,7 +136,7 @@ func (r *RunWorkFlow) SendWecharMsgTextCard(runStep int, nodeTitle, content stri sendMsg.Msgtype = "textcard" sendMsg.Textcard.Title = nodeTitle sendMsg.Textcard.Description = fmt.Sprintf("