作者 tangxuhui

字典curd功能实现

... ... @@ -7,23 +7,44 @@ import (
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-basic/pkg/domain"
)
type DictionaryItem struct {
// 项编码
ItemCode string `json:"itemCode" valid:"Required;MaxSize(30)"`
// 项标签
ItemLabel string `json:"itemLabel" valid:"Required;MaxSize(30)"`
// 值
ItemValue string `json:"itemValue" valid:"Required;MaxSize(30)"`
// 是否可见【1:不可以】【2:可以】
IsShow int `json:"isShow"`
// 显示序号
Sort int `json:"sort"`
}
type CreateDictionaryCommand struct {
// 字典编号 主键
DictionaryId int `json:"dictionaryId,omitempty"`
// 字典编码
DictCode string `json:"dictCode,omitempty"`
DictCode string `json:"dictCode" valid:"Required;MaxSize(30)"`
// 字典名称
DictName string `json:"dictName,omitempty"`
DictName string `json:"dictName" valid:"Required;MaxSize(30)"`
// 备注信息
Desc string `json:"desc,omitempty"`
// 是否可见【1:不可以】【2:可以】
IsShow int `json:"isShow,omitempty"`
Desc string `json:"desc" valid:"MaxSize(100)"`
// 字典值列表
DictItems []*domain.DictionaryItem `json:"dictItems,omitempty"`
DictItems []DictionaryItem `json:"dictItems"`
}
func (createDictionaryCommand *CreateDictionaryCommand) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
// 实现了接口 validation.ValidFormer
func (createDictionaryCommand *CreateDictionaryCommand) Valid(v *validation.Validation) {
//检查items
sortmap := make(map[int]struct{})
for _, item := range createDictionaryCommand.DictItems {
if _, ok := sortmap[item.Sort]; ok {
v.SetError("Sort", "明细项顺序值重复")
}
sortmap[item.Sort] = struct{}{}
vOk := domain.DictionaryItemShow(item.IsShow).Valid()
if !vOk {
v.SetError("IsShow", "明细项是否显示值异常")
}
}
}
func (createDictionaryCommand *CreateDictionaryCommand) ValidateCommand() error {
... ...
... ... @@ -8,11 +8,11 @@ import (
type RemoveDictionaryCommand struct {
// 字典编号 主键
DictionaryId int `json:"dictionaryId,omitempty"`
DictionaryId int `json:"dictionaryId" valid:"Required"`
}
func (removeDictionaryCommand *RemoveDictionaryCommand) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
}
func (removeDictionaryCommand *RemoveDictionaryCommand) ValidateCommand() error {
... ...
... ... @@ -9,21 +9,32 @@ import (
type UpdateDictionaryCommand struct {
// 字典编号 主键
DictionaryId int64 `json:"dictionaryId,omitempty"`
DictionaryId int64 `json:"dictionaryId" valid:"Required"`
// 字典编码
DictCode string `json:"dictCode,omitempty"`
DictCode string `json:"dictCode" valid:"Required;MaxSize(30)"`
// 字典名称
DictName string `json:"dictName,omitempty"`
DictName string `json:"dictName" valid:"Required;MaxSize(30)"`
// 备注信息
Desc string `json:"desc,omitempty"`
Desc string `json:"desc" valid:"Required;MaxSize(100)"`
// 是否可见【1:不可以】【2:可以】
IsShow int `json:"isShow,omitempty"`
IsShow int `json:"isShow"`
// 字典值列表
DictItems []*domain.DictionaryItem `json:"dictItems,omitempty"`
DictItems []DictionaryItem `json:"dictItems"`
}
func (updateDictionaryCommand *UpdateDictionaryCommand) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
func (updateDictionaryCommand *UpdateDictionaryCommand) Valid(v *validation.Validation) {
//检查items
sortmap := make(map[int]struct{})
for _, item := range updateDictionaryCommand.DictItems {
if _, ok := sortmap[item.Sort]; ok {
v.SetError("sort", "明细项顺序值重复")
}
sortmap[item.Sort] = struct{}{}
vOk := domain.DictionaryItemShow(item.IsShow).Valid()
if !vOk {
v.SetError("IsShow", "明细项是否显示值异常")
}
}
}
func (updateDictionaryCommand *UpdateDictionaryCommand) ValidateCommand() error {
... ...
... ... @@ -9,7 +9,7 @@ import (
type GetDictionaryQuery struct {
// 字典编码
DictionaryId int64 `json:"dictionaryId"`
DictCode string `json:"dictCode,omitempty"`
DictCode string `json:"dictCode"`
}
func (getDictionaryQuery *GetDictionaryQuery) Valid(validation *validation.Validation) {
... ...
... ... @@ -2,6 +2,7 @@ package service
import (
"fmt"
"sort"
"github.com/linmadan/egglib-go/core/application"
"github.com/linmadan/egglib-go/utils/tool_funs"
... ... @@ -30,7 +31,25 @@ func (dictionaryService *DictionaryService) CreateDictionary(createDictionaryCom
defer func() {
transactionContext.RollbackTransaction()
}()
newDictionary := &domain.Dictionary{} //TODO
var items []domain.DictionaryItem
for _, item := range createDictionaryCommand.DictItems {
i := domain.DictionaryItem{
ItemCode: item.ItemCode,
ItemLabel: item.ItemLabel,
ItemValue: item.ItemValue,
IsShow: item.IsShow,
Sort: item.Sort,
}
items = append(items, i)
}
sort.Sort(domain.DictionaryItems(items))
newDictionary := &domain.Dictionary{
DictCode: createDictionaryCommand.DictCode,
DictName: createDictionaryCommand.DictName,
Desc: createDictionaryCommand.Desc,
DictItems: items,
}
var dictionaryRepository domain.DictionaryRepository
if value, err := factory.CreateDictionaryRepository(map[string]interface{}{
"transactionContext": transactionContext,
... ... @@ -72,7 +91,14 @@ func (dictionaryService *DictionaryService) GetDictionary(getDictionaryQuery *qu
} else {
dictionaryRepository = value
}
dictionary, err := dictionaryRepository.FindOne(map[string]interface{}{"dictionaryId": getDictionaryQuery.DictCode})
queryCondition := make(map[string]interface{})
if len(getDictionaryQuery.DictCode) > 0 {
queryCondition["dictCode"] = getDictionaryQuery.DictCode
}
if getDictionaryQuery.DictionaryId > 0 {
queryCondition["dictionaryId"] = getDictionaryQuery.DictCode
}
dictionary, err := dictionaryRepository.FindOne(queryCondition)
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
... ... @@ -150,7 +176,7 @@ func (dictionaryService *DictionaryService) RemoveDictionary(removeDictionaryCom
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if dictionary == nil {
return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", string(removeDictionaryCommand.DictionaryId)))
return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%d", removeDictionaryCommand.DictionaryId))
}
if dictionary, err := dictionaryRepository.Remove(dictionary); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
... ... @@ -190,9 +216,27 @@ func (dictionaryService *DictionaryService) UpdateDictionary(updateDictionaryCom
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if dictionary == nil {
return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", string(updateDictionaryCommand.DictionaryId)))
}
if err := dictionary.Update(tool_funs.SimpleStructToMap(updateDictionaryCommand)); err != nil {
return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%d", updateDictionaryCommand.DictionaryId))
}
var items []domain.DictionaryItem
for _, item := range updateDictionaryCommand.DictItems {
i := domain.DictionaryItem{
ItemCode: item.ItemCode,
ItemLabel: item.ItemLabel,
ItemValue: item.ItemValue,
IsShow: item.IsShow,
Sort: item.Sort,
}
items = append(items, i)
}
sort.Sort(domain.DictionaryItems(items))
err = dictionary.Update(map[string]interface{}{
"dictCode": updateDictionaryCommand.DictCode,
"dictName": updateDictionaryCommand.DictName,
"desc": updateDictionaryCommand.Desc,
"dictItems": items,
})
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
if dictionary, err := dictionaryRepository.Save(dictionary); err != nil {
... ...
package constant
var ValidationMessageTmpls = map[string]string{
"Required": "不能为空",
"Min": "最小值: %d",
"Max": "最大值: %d",
"Range": "数值的范围 %d - %d",
"MinSize": "最小长度: %d",
"MaxSize": "最大长度: %d",
"Length": "指定长度: %d",
"Alpha": "必须为有效的字母字符",
"Numeric": "必须为有效的数字",
"AlphaNumeric": "必须为有效的字母或数字",
"Match": "必须匹配 %s",
"NoMatch": "必须不匹配 %s",
"AlphaDash": "必须为字母、数字或横杠(-_)",
"Email": "必须为邮箱格式",
"IP": "必须为有效的IP格式",
"Base64": "必须为有效的base64字符",
"Mobile": "必须有效的手机号码",
"Tel": "必须是有效的电话号码",
"Phone": "必须是有效的电话或手机号码",
"ZipCode": "必须是有效的邮政编码",
}
\ No newline at end of file
... ...
... ... @@ -10,10 +10,8 @@ type Dictionary struct {
DictName string `json:"dictName"`
// 备注信息
Desc string `json:"desc"`
// 是否可见【1:不可以】【2:可以】
IsShow int `json:"isShow"`
// 字典值列表
DictItems []*DictionaryItem `json:"dictItems"`
DictItems []DictionaryItem `json:"dictItems"`
}
type DictionaryRepository interface {
... ... @@ -43,11 +41,8 @@ func (dictionary *Dictionary) Update(data map[string]interface{}) error {
if desc, ok := data["desc"]; ok {
dictionary.Desc = desc.(string)
}
if isShow, ok := data["isShow"]; ok {
dictionary.IsShow = isShow.(int)
}
if dictItems, ok := data["dictItems"]; ok {
dictionary.DictItems = dictItems.([]*DictionaryItem)
dictionary.DictItems = dictItems.([]DictionaryItem)
}
return nil
}
... ...
... ... @@ -8,8 +8,35 @@ type DictionaryItem struct {
ItemLabel string `json:"itemLabel"`
// 值
ItemValue string `json:"itemValue"`
// 启用状态(启用:1 禁用:2)
EnableStatus string `json:"enableStatus"`
// 是否可见【1:不可以】【2:可以】
IsShow int `json:"isShow"`
// 显示序号
Sort int `json:"sort"`
}
type DictionaryItemShow int
const (
DictionaryItemIsShow int = 1 //不可见
DictionaryItemNotShow int = 2 //可见
)
func (show DictionaryItemShow) Valid() bool {
var ok bool
switch int(show) {
case DictionaryItemNotShow:
ok = true
case DictionaryItemIsShow:
ok = true
default:
ok = false
}
return ok
}
//明细项排序
type DictionaryItems []DictionaryItem
func (a DictionaryItems) Len() int { return len(a) }
func (a DictionaryItems) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a DictionaryItems) Less(i, j int) bool { return a[i].Sort < a[j].Sort }
... ...
... ... @@ -17,5 +17,5 @@ type Dictionary struct {
// 是否可见【1:不可以】【2:可以】
IsShow int
// 字典值列表
DictItems []*domain.DictionaryItem `pg:",array"`
DictItems []domain.DictionaryItem `pg:",array"`
}
... ...
... ... @@ -11,7 +11,6 @@ func TransformToDictionaryDomainModelFromPgModels(dictionaryModel *models.Dictio
DictCode: dictionaryModel.DictCode,
DictName: dictionaryModel.DictName,
Desc: dictionaryModel.Desc,
IsShow: dictionaryModel.IsShow,
DictItems: dictionaryModel.DictItems,
}, nil
}
... ...
package repository
import (
"github.com/linmadan/egglib-go/utils/snowflake"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-basic/pkg/log"
)
var idWorker *snowflake.IdWorker
func init() {
worker, err := snowflake.NewIdWorker(1)
if err != nil {
log.Logger.Panic("idWorker init err" + err.Error())
return
}
idWorker = worker
}
... ...
... ... @@ -6,7 +6,7 @@ import (
"github.com/go-pg/pg/v10"
"github.com/linmadan/egglib-go/persistent/pg/sqlbuilder"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"github.com/linmadan/egglib-go/utils/snowflake"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-basic/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-basic/pkg/infrastructure/pg/models"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-basic/pkg/infrastructure/pg/transform"
... ... @@ -17,20 +17,16 @@ type DictionaryRepository struct {
}
func (repository *DictionaryRepository) nextIdentify() (int64, error) {
IdWorker, err := snowflake.NewIdWorker(1)
if err != nil {
return 0, err
}
id, err := IdWorker.NextId()
id, err := idWorker.NextId()
return id, err
}
func (repository *DictionaryRepository) Save(dictionary *domain.Dictionary) (*domain.Dictionary, error) {
sqlBuildFields := []string{
"dictionary_id",
"dict_code",
"dict_name",
"desc",
"is_show",
"dict_items",
}
insertFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
... ... @@ -52,7 +48,6 @@ func (repository *DictionaryRepository) Save(dictionary *domain.Dictionary) (*do
&dictionary.DictCode,
&dictionary.DictName,
&dictionary.Desc,
&dictionary.IsShow,
pg.Array(&dictionary.DictItems),
),
fmt.Sprintf("INSERT INTO dictionarys (%s) VALUES (%s) RETURNING %s", insertFieldsSnippet, insertPlaceHoldersSnippet, returningFieldsSnippet),
... ... @@ -60,7 +55,6 @@ func (repository *DictionaryRepository) Save(dictionary *domain.Dictionary) (*do
dictionary.DictCode,
dictionary.DictName,
dictionary.Desc,
dictionary.IsShow,
pg.Array(dictionary.DictItems),
); err != nil {
return dictionary, err
... ... @@ -72,7 +66,6 @@ func (repository *DictionaryRepository) Save(dictionary *domain.Dictionary) (*do
&dictionary.DictCode,
&dictionary.DictName,
&dictionary.Desc,
&dictionary.IsShow,
pg.Array(&dictionary.DictItems),
),
fmt.Sprintf("UPDATE dictionarys SET %s WHERE dictionary_id=? RETURNING %s", updateFieldsSnippet, returningFieldsSnippet),
... ... @@ -80,7 +73,6 @@ func (repository *DictionaryRepository) Save(dictionary *domain.Dictionary) (*do
dictionary.DictCode,
dictionary.DictName,
dictionary.Desc,
dictionary.IsShow,
pg.Array(dictionary.DictItems),
dictionary.Identify(),
); err != nil {
... ... @@ -89,6 +81,7 @@ func (repository *DictionaryRepository) Save(dictionary *domain.Dictionary) (*do
}
return dictionary, nil
}
func (repository *DictionaryRepository) Remove(dictionary *domain.Dictionary) (*domain.Dictionary, error) {
tx := repository.transactionContext.PgTx
dictionaryModel := new(models.Dictionary)
... ... @@ -98,11 +91,13 @@ func (repository *DictionaryRepository) Remove(dictionary *domain.Dictionary) (*
}
return dictionary, nil
}
func (repository *DictionaryRepository) FindOne(queryOptions map[string]interface{}) (*domain.Dictionary, error) {
tx := repository.transactionContext.PgTx
dictionaryModel := new(models.Dictionary)
query := sqlbuilder.BuildQuery(tx.Model(dictionaryModel), queryOptions)
query.SetWhereByQueryOption("dictionary.dictionary_id = ?", "dictionaryId")
query.SetWhereByQueryOption("dictionary.dict_code=?", "dictCode")
if err := query.First(); err != nil {
if err.Error() == "pg: no rows in result set" {
return nil, fmt.Errorf("没有此资源")
... ... @@ -116,6 +111,7 @@ func (repository *DictionaryRepository) FindOne(queryOptions map[string]interfac
return transform.TransformToDictionaryDomainModelFromPgModels(dictionaryModel)
}
}
func (repository *DictionaryRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.Dictionary, error) {
tx := repository.transactionContext.PgTx
var dictionaryModels []*models.Dictionary
... ... @@ -136,6 +132,7 @@ func (repository *DictionaryRepository) Find(queryOptions map[string]interface{}
return int64(count), dictionarys, nil
}
}
func NewDictionaryRepository(transactionContext *pgTransaction.TransactionContext) (*DictionaryRepository, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
... ...
... ... @@ -4,8 +4,10 @@ import (
"os"
"strconv"
"github.com/beego/beego/v2/core/validation"
"github.com/beego/beego/v2/server/web"
"github.com/linmadan/egglib-go/web/beego/filters"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-basic/pkg/constant"
//_ "gitlab.fjmaimaimai.com/allied-creation/allied-creation-basic/pkg/port/beego/routers"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-basic/pkg/log"
... ... @@ -27,6 +29,7 @@ func init() {
web.BConfig.Listen.HTTPPort = port
}
}
validation.MessageTmpls = constant.ValidationMessageTmpls
web.InsertFilter("/*", web.BeforeExec, filters.AllowCors())
web.InsertFilter("/*", web.BeforeExec, filters.CreateRequstLogFilter(log.Logger))
web.InsertFilter("/*", web.AfterExec, filters.CreateResponseLogFilter(log.Logger), web.WithReturnOnOutput(false))
... ...