Преглед изворни кода

Merge branch 'develop' of http://code.dashoo.cn/chengjian/opms_backend into feature/customer_1.0

wangxingcheng пре 3 година
родитељ
комит
604617ac98

+ 0 - 25
opms_admin/app/common/dao/casbin_rule.go

@@ -1,25 +0,0 @@
-// ============================================================================
-// This is auto-generated by gf cli tool only once. Fill this file as you wish.
-// ============================================================================
-
-package dao
-
-import (
-	"dashoo.cn/micro/app/common/dao/internal"
-)
-
-// casbinRuleDao is the manager for logic model data accessing
-// and custom defined data operations functions management. You can define
-// methods on it to extend its functionality as you wish.
-type casbinRuleDao struct {
-	internal.CasbinRuleDao
-}
-
-var (
-	// CasbinRule is globally public accessible object for table casbin_rule operations.
-	CasbinRule = casbinRuleDao{
-		internal.CasbinRule,
-	}
-)
-
-// Fill with you ideas below.

+ 0 - 394
opms_admin/app/common/dao/internal/casbin_rule.go

@@ -1,394 +0,0 @@
-// ==========================================================================
-// This is auto-generated by gf cli tool. DO NOT EDIT THIS FILE MANUALLY.
-// ==========================================================================
-
-package internal
-
-import (
-	"context"
-	"dashoo.cn/micro/app/common/model"
-	"database/sql"
-	"github.com/gogf/gf/database/gdb"
-	"github.com/gogf/gf/frame/g"
-	"github.com/gogf/gf/frame/gmvc"
-	"time"
-)
-
-// CasbinRuleDao is the manager for logic model data accessing
-// and custom defined data operations functions management.
-type CasbinRuleDao struct {
-	gmvc.M
-	DB      gdb.DB
-	Table   string
-	Columns casbinRuleColumns
-}
-
-// CasbinRuleColumns defines and stores column names for table casbin_rule.
-type casbinRuleColumns struct {
-	Ptype string //
-	V0    string //
-	V1    string //
-	V2    string //
-	V3    string //
-	V4    string //
-	V5    string //
-}
-
-var (
-	// CasbinRule is globally public accessible object for table casbin_rule operations.
-	CasbinRule = CasbinRuleDao{
-		M:     g.DB("default").Model("casbin_rule").Safe(),
-		DB:    g.DB("default"),
-		Table: "casbin_rule",
-		Columns: casbinRuleColumns{
-			Ptype: "ptype",
-			V0:    "v0",
-			V1:    "v1",
-			V2:    "v2",
-			V3:    "v3",
-			V4:    "v4",
-			V5:    "v5",
-		},
-	}
-)
-
-// Ctx is a chaining function, which creates and returns a new DB that is a shallow copy
-// of current DB object and with given context in it.
-// Note that this returned DB object can be used only once, so do not assign it to
-// a global or package variable for long using.
-func (d *CasbinRuleDao) Ctx(ctx context.Context) *CasbinRuleDao {
-	return &CasbinRuleDao{M: d.M.Ctx(ctx)}
-}
-
-// As sets an alias name for current table.
-func (d *CasbinRuleDao) As(as string) *CasbinRuleDao {
-	return &CasbinRuleDao{M: d.M.As(as)}
-}
-
-// TX sets the transaction for current operation.
-func (d *CasbinRuleDao) TX(tx *gdb.TX) *CasbinRuleDao {
-	return &CasbinRuleDao{M: d.M.TX(tx)}
-}
-
-// Master marks the following operation on master node.
-func (d *CasbinRuleDao) Master() *CasbinRuleDao {
-	return &CasbinRuleDao{M: d.M.Master()}
-}
-
-// Slave marks the following operation on slave node.
-// Note that it makes sense only if there's any slave node configured.
-func (d *CasbinRuleDao) Slave() *CasbinRuleDao {
-	return &CasbinRuleDao{M: d.M.Slave()}
-}
-
-// Args sets custom arguments for model operation.
-func (d *CasbinRuleDao) Args(args ...interface{}) *CasbinRuleDao {
-	return &CasbinRuleDao{M: d.M.Args(args...)}
-}
-
-// LeftJoin does "LEFT JOIN ... ON ..." statement on the model.
-// The parameter <table> can be joined table and its joined condition,
-// and also with its alias name, like:
-// Table("user").LeftJoin("user_detail", "user_detail.uid=user.uid")
-// Table("user", "u").LeftJoin("user_detail", "ud", "ud.uid=u.uid")
-func (d *CasbinRuleDao) LeftJoin(table ...string) *CasbinRuleDao {
-	return &CasbinRuleDao{M: d.M.LeftJoin(table...)}
-}
-
-// RightJoin does "RIGHT JOIN ... ON ..." statement on the model.
-// The parameter <table> can be joined table and its joined condition,
-// and also with its alias name, like:
-// Table("user").RightJoin("user_detail", "user_detail.uid=user.uid")
-// Table("user", "u").RightJoin("user_detail", "ud", "ud.uid=u.uid")
-func (d *CasbinRuleDao) RightJoin(table ...string) *CasbinRuleDao {
-	return &CasbinRuleDao{M: d.M.RightJoin(table...)}
-}
-
-// InnerJoin does "INNER JOIN ... ON ..." statement on the model.
-// The parameter <table> can be joined table and its joined condition,
-// and also with its alias name, like:
-// Table("user").InnerJoin("user_detail", "user_detail.uid=user.uid")
-// Table("user", "u").InnerJoin("user_detail", "ud", "ud.uid=u.uid")
-func (d *CasbinRuleDao) InnerJoin(table ...string) *CasbinRuleDao {
-	return &CasbinRuleDao{M: d.M.InnerJoin(table...)}
-}
-
-// Fields sets the operation fields of the model, multiple fields joined using char ','.
-// The parameter <fieldNamesOrMapStruct> can be type of string/map/*map/struct/*struct.
-func (d *CasbinRuleDao) Fields(fieldNamesOrMapStruct ...interface{}) *CasbinRuleDao {
-	return &CasbinRuleDao{M: d.M.Fields(fieldNamesOrMapStruct...)}
-}
-
-// FieldsEx sets the excluded operation fields of the model, multiple fields joined using char ','.
-// The parameter <fieldNamesOrMapStruct> can be type of string/map/*map/struct/*struct.
-func (d *CasbinRuleDao) FieldsEx(fieldNamesOrMapStruct ...interface{}) *CasbinRuleDao {
-	return &CasbinRuleDao{M: d.M.FieldsEx(fieldNamesOrMapStruct...)}
-}
-
-// Option sets the extra operation option for the model.
-func (d *CasbinRuleDao) Option(option int) *CasbinRuleDao {
-	return &CasbinRuleDao{M: d.M.Option(option)}
-}
-
-// OmitEmpty sets OPTION_OMITEMPTY option for the model, which automatically filers
-// the data and where attributes for empty values.
-func (d *CasbinRuleDao) OmitEmpty() *CasbinRuleDao {
-	return &CasbinRuleDao{M: d.M.OmitEmpty()}
-}
-
-// Filter marks filtering the fields which does not exist in the fields of the operated table.
-func (d *CasbinRuleDao) Filter() *CasbinRuleDao {
-	return &CasbinRuleDao{M: d.M.Filter()}
-}
-
-// Where sets the condition statement for the model. The parameter <where> can be type of
-// string/map/gmap/slice/struct/*struct, etc. Note that, if it's called more than one times,
-// multiple conditions will be joined into where statement using "AND".
-// Eg:
-// Where("uid=10000")
-// Where("uid", 10000)
-// Where("money>? AND name like ?", 99999, "vip_%")
-// Where("uid", 1).Where("name", "john")
-// Where("status IN (?)", g.Slice{1,2,3})
-// Where("age IN(?,?)", 18, 50)
-// Where(User{ Id : 1, UserName : "john"})
-func (d *CasbinRuleDao) Where(where interface{}, args ...interface{}) *CasbinRuleDao {
-	return &CasbinRuleDao{M: d.M.Where(where, args...)}
-}
-
-// WherePri does the same logic as M.Where except that if the parameter <where>
-// is a single condition like int/string/float/slice, it treats the condition as the primary
-// key value. That is, if primary key is "id" and given <where> parameter as "123", the
-// WherePri function treats the condition as "id=123", but M.Where treats the condition
-// as string "123".
-func (d *CasbinRuleDao) WherePri(where interface{}, args ...interface{}) *CasbinRuleDao {
-	return &CasbinRuleDao{M: d.M.WherePri(where, args...)}
-}
-
-// And adds "AND" condition to the where statement.
-func (d *CasbinRuleDao) And(where interface{}, args ...interface{}) *CasbinRuleDao {
-	return &CasbinRuleDao{M: d.M.And(where, args...)}
-}
-
-// Or adds "OR" condition to the where statement.
-func (d *CasbinRuleDao) Or(where interface{}, args ...interface{}) *CasbinRuleDao {
-	return &CasbinRuleDao{M: d.M.Or(where, args...)}
-}
-
-// Group sets the "GROUP BY" statement for the model.
-func (d *CasbinRuleDao) Group(groupBy string) *CasbinRuleDao {
-	return &CasbinRuleDao{M: d.M.Group(groupBy)}
-}
-
-// Order sets the "ORDER BY" statement for the model.
-func (d *CasbinRuleDao) Order(orderBy ...string) *CasbinRuleDao {
-	return &CasbinRuleDao{M: d.M.Order(orderBy...)}
-}
-
-// Limit sets the "LIMIT" statement for the model.
-// The parameter <limit> can be either one or two number, if passed two number is passed,
-// it then sets "LIMIT limit[0],limit[1]" statement for the model, or else it sets "LIMIT limit[0]"
-// statement.
-func (d *CasbinRuleDao) Limit(limit ...int) *CasbinRuleDao {
-	return &CasbinRuleDao{M: d.M.Limit(limit...)}
-}
-
-// Offset sets the "OFFSET" statement for the model.
-// It only makes sense for some databases like SQLServer, PostgreSQL, etc.
-func (d *CasbinRuleDao) Offset(offset int) *CasbinRuleDao {
-	return &CasbinRuleDao{M: d.M.Offset(offset)}
-}
-
-// Page sets the paging number for the model.
-// The parameter <page> is started from 1 for paging.
-// Note that, it differs that the Limit function start from 0 for "LIMIT" statement.
-func (d *CasbinRuleDao) Page(page, limit int) *CasbinRuleDao {
-	return &CasbinRuleDao{M: d.M.Page(page, limit)}
-}
-
-// Batch sets the batch operation number for the model.
-func (d *CasbinRuleDao) Batch(batch int) *CasbinRuleDao {
-	return &CasbinRuleDao{M: d.M.Batch(batch)}
-}
-
-// Cache sets the cache feature for the model. It caches the result of the sql, which means
-// if there's another same sql request, it just reads and returns the result from cache, it
-// but not committed and executed into the database.
-//
-// If the parameter <duration> < 0, which means it clear the cache with given <name>.
-// If the parameter <duration> = 0, which means it never expires.
-// If the parameter <duration> > 0, which means it expires after <duration>.
-//
-// The optional parameter <name> is used to bind a name to the cache, which means you can later
-// control the cache like changing the <duration> or clearing the cache with specified <name>.
-//
-// Note that, the cache feature is disabled if the model is operating on a transaction.
-func (d *CasbinRuleDao) Cache(duration time.Duration, name ...string) *CasbinRuleDao {
-	return &CasbinRuleDao{M: d.M.Cache(duration, name...)}
-}
-
-// Data sets the operation data for the model.
-// The parameter <data> can be type of string/map/gmap/slice/struct/*struct, etc.
-// Eg:
-// Data("uid=10000")
-// Data("uid", 10000)
-// Data(g.Map{"uid": 10000, "name":"john"})
-// Data(g.Slice{g.Map{"uid": 10000, "name":"john"}, g.Map{"uid": 20000, "name":"smith"})
-func (d *CasbinRuleDao) Data(data ...interface{}) *CasbinRuleDao {
-	return &CasbinRuleDao{M: d.M.Data(data...)}
-}
-
-// All does "SELECT FROM ..." statement for the model.
-// It retrieves the records from table and returns the result as []*model.CasbinRule.
-// It returns nil if there's no record retrieved with the given conditions from table.
-//
-// The optional parameter <where> is the same as the parameter of M.Where function,
-// see M.Where.
-func (d *CasbinRuleDao) All(where ...interface{}) ([]*model.CasbinRule, error) {
-	all, err := d.M.All(where...)
-	if err != nil {
-		return nil, err
-	}
-	var entities []*model.CasbinRule
-	if err = all.Structs(&entities); err != nil && err != sql.ErrNoRows {
-		return nil, err
-	}
-	return entities, nil
-}
-
-// One retrieves one record from table and returns the result as *model.CasbinRule.
-// It returns nil if there's no record retrieved with the given conditions from table.
-//
-// The optional parameter <where> is the same as the parameter of M.Where function,
-// see M.Where.
-func (d *CasbinRuleDao) One(where ...interface{}) (*model.CasbinRule, error) {
-	one, err := d.M.One(where...)
-	if err != nil {
-		return nil, err
-	}
-	var entity *model.CasbinRule
-	if err = one.Struct(&entity); err != nil && err != sql.ErrNoRows {
-		return nil, err
-	}
-	return entity, nil
-}
-
-// FindOne retrieves and returns a single Record by M.WherePri and M.One.
-// Also see M.WherePri and M.One.
-func (d *CasbinRuleDao) FindOne(where ...interface{}) (*model.CasbinRule, error) {
-	one, err := d.M.FindOne(where...)
-	if err != nil {
-		return nil, err
-	}
-	var entity *model.CasbinRule
-	if err = one.Struct(&entity); err != nil && err != sql.ErrNoRows {
-		return nil, err
-	}
-	return entity, nil
-}
-
-// FindAll retrieves and returns Result by by M.WherePri and M.All.
-// Also see M.WherePri and M.All.
-func (d *CasbinRuleDao) FindAll(where ...interface{}) ([]*model.CasbinRule, error) {
-	all, err := d.M.FindAll(where...)
-	if err != nil {
-		return nil, err
-	}
-	var entities []*model.CasbinRule
-	if err = all.Structs(&entities); err != nil && err != sql.ErrNoRows {
-		return nil, err
-	}
-	return entities, nil
-}
-
-// Struct retrieves one record from table and converts it into given struct.
-// The parameter <pointer> should be type of *struct/**struct. If type **struct is given,
-// it can create the struct internally during converting.
-//
-// The optional parameter <where> is the same as the parameter of Model.Where function,
-// see Model.Where.
-//
-// Note that it returns sql.ErrNoRows if there's no record retrieved with the given conditions
-// from table and <pointer> is not nil.
-//
-// Eg:
-// user := new(User)
-// err  := dao.User.Where("id", 1).Struct(user)
-//
-// user := (*User)(nil)
-// err  := dao.User.Where("id", 1).Struct(&user)
-func (d *CasbinRuleDao) Struct(pointer interface{}, where ...interface{}) error {
-	return d.M.Struct(pointer, where...)
-}
-
-// Structs retrieves records from table and converts them into given struct slice.
-// The parameter <pointer> should be type of *[]struct/*[]*struct. It can create and fill the struct
-// slice internally during converting.
-//
-// The optional parameter <where> is the same as the parameter of Model.Where function,
-// see Model.Where.
-//
-// Note that it returns sql.ErrNoRows if there's no record retrieved with the given conditions
-// from table and <pointer> is not empty.
-//
-// Eg:
-// users := ([]User)(nil)
-// err   := dao.User.Structs(&users)
-//
-// users := ([]*User)(nil)
-// err   := dao.User.Structs(&users)
-func (d *CasbinRuleDao) Structs(pointer interface{}, where ...interface{}) error {
-	return d.M.Structs(pointer, where...)
-}
-
-// Scan automatically calls Struct or Structs function according to the type of parameter <pointer>.
-// It calls function Struct if <pointer> is type of *struct/**struct.
-// It calls function Structs if <pointer> is type of *[]struct/*[]*struct.
-//
-// The optional parameter <where> is the same as the parameter of Model.Where function,
-// see Model.Where.
-//
-// Note that it returns sql.ErrNoRows if there's no record retrieved and given pointer is not empty or nil.
-//
-// Eg:
-// user  := new(User)
-// err   := dao.User.Where("id", 1).Scan(user)
-//
-// user  := (*User)(nil)
-// err   := dao.User.Where("id", 1).Scan(&user)
-//
-// users := ([]User)(nil)
-// err   := dao.User.Scan(&users)
-//
-// users := ([]*User)(nil)
-// err   := dao.User.Scan(&users)
-func (d *CasbinRuleDao) Scan(pointer interface{}, where ...interface{}) error {
-	return d.M.Scan(pointer, where...)
-}
-
-// Chunk iterates the table with given size and callback function.
-func (d *CasbinRuleDao) Chunk(limit int, callback func(entities []*model.CasbinRule, err error) bool) {
-	d.M.Chunk(limit, func(result gdb.Result, err error) bool {
-		var entities []*model.CasbinRule
-		err = result.Structs(&entities)
-		if err == sql.ErrNoRows {
-			return false
-		}
-		return callback(entities, err)
-	})
-}
-
-// LockUpdate sets the lock for update for current operation.
-func (d *CasbinRuleDao) LockUpdate() *CasbinRuleDao {
-	return &CasbinRuleDao{M: d.M.LockUpdate()}
-}
-
-// LockShared sets the lock in share mode for current operation.
-func (d *CasbinRuleDao) LockShared() *CasbinRuleDao {
-	return &CasbinRuleDao{M: d.M.LockShared()}
-}
-
-// Unscoped enables/disables the soft deleting feature.
-func (d *CasbinRuleDao) Unscoped() *CasbinRuleDao {
-	return &CasbinRuleDao{M: d.M.Unscoped()}
-}

+ 0 - 14
opms_admin/app/common/model/casbin_rule.go

@@ -1,14 +0,0 @@
-// ==========================================================================
-// This is auto-generated by gf cli tool. Fill this file as you wish.
-// ==========================================================================
-
-package model
-
-import (
-	"dashoo.cn/micro/app/common/model/internal"
-)
-
-// CasbinRule is the golang structure for table casbin_rule.
-type CasbinRule internal.CasbinRule
-
-// Fill with you ideas below.

+ 0 - 16
opms_admin/app/common/model/internal/casbin_rule.go

@@ -1,16 +0,0 @@
-// ==========================================================================
-// This is auto-generated by gf cli tool. DO NOT EDIT THIS FILE MANUALLY.
-// ==========================================================================
-
-package internal
-
-// CasbinRule is the golang structure for table casbin_rule.
-type CasbinRule struct {
-	Ptype string `orm:"ptype" json:"ptype"` //
-	V0    string `orm:"v0"    json:"v0"`    //
-	V1    string `orm:"v1"    json:"v1"`    //
-	V2    string `orm:"v2"    json:"v2"`    //
-	V3    string `orm:"v3"    json:"v3"`    //
-	V4    string `orm:"v4"    json:"v4"`    //
-	V5    string `orm:"v5"    json:"v5"`    //
-}

+ 0 - 237
opms_admin/app/common/service/casbin.go

@@ -1,237 +0,0 @@
-package service
-
-import (
-	"dashoo.cn/micro/app/common/dao"
-	dbModel "dashoo.cn/micro/app/common/model"
-	"github.com/casbin/casbin/v2"
-	"github.com/casbin/casbin/v2/model"
-	"github.com/casbin/casbin/v2/persist"
-	"github.com/gogf/gf/frame/g"
-	"sync"
-)
-
-type cabin struct{}
-
-type adapterCasbin struct {
-	Enforcer    *casbin.SyncedEnforcer
-	EnforcerErr error
-}
-
-var (
-	Casbin = new(cabin)
-	once   sync.Once
-	m      sync.RWMutex
-	ac     *adapterCasbin
-)
-
-// GetEnforcer 获取adapter单例对象
-func (s *cabin) GetEnforcer() (enforcer *casbin.SyncedEnforcer, err error) {
-	once.Do(func() {
-		ac = s.newAdapter()
-	})
-	enforcer = ac.Enforcer
-	err = ac.EnforcerErr
-	return
-}
-
-// 初始化adapter操作
-func (s *cabin) newAdapter() (a *adapterCasbin) {
-	a = new(adapterCasbin)
-	a.initPolicy()
-	return
-}
-
-func (a *adapterCasbin) initPolicy() {
-	// Because the DB is empty at first,
-	// so we need to load the policy from the file adapter (.CSV) first.
-	e, err := casbin.NewSyncedEnforcer(g.Cfg().GetString("casbin.modelFile"),
-		g.Cfg().GetString("casbin.policyFile"))
-
-	if err != nil {
-		a.EnforcerErr = err
-		return
-	}
-
-	// This is a trick to save the current policy to the DB.
-	// We can't call e.SavePolicy() because the adapter in the enforcer is still the file adapter.
-	// The current policy means the policy in the Casbin enforcer (aka in memory).
-	//err = a.SavePolicy(e.GetModel())
-	//if err != nil {
-	//	return err
-	//}
-	//set adapter
-	e.SetAdapter(a)
-	// Clear the current policy.
-	e.ClearPolicy()
-	a.Enforcer = e
-	// Load the policy from DB.
-	err = a.LoadPolicy(e.GetModel())
-	if err != nil {
-		a.EnforcerErr = err
-		return
-	}
-}
-
-// SavePolicy saves policy to database.
-func (a *adapterCasbin) SavePolicy(model model.Model) (err error) {
-	err = a.dropTable()
-	if err != nil {
-		return
-	}
-	err = a.createTable()
-	if err != nil {
-		return
-	}
-	for ptype, ast := range model["p"] {
-		for _, rule := range ast.Policy {
-			line := savePolicyLine(ptype, rule)
-			_, err := dao.CasbinRule.Data(line).Insert()
-			if err != nil {
-				return err
-			}
-		}
-	}
-
-	for ptype, ast := range model["g"] {
-		for _, rule := range ast.Policy {
-			line := savePolicyLine(ptype, rule)
-			_, err := dao.CasbinRule.Data(line).Insert()
-			if err != nil {
-				return err
-			}
-		}
-	}
-	return
-}
-
-func (a *adapterCasbin) dropTable() (err error) {
-	return
-}
-
-func (a *adapterCasbin) createTable() (err error) {
-	return
-}
-
-// LoadPolicy loads policy from database.
-func (a *adapterCasbin) LoadPolicy(model model.Model) error {
-	var lines []*dbModel.CasbinRule
-	if err := dao.CasbinRule.Scan(&lines); err != nil {
-		return err
-	}
-	for _, line := range lines {
-		loadPolicyLine(line, model)
-	}
-	return nil
-}
-
-// AddPolicy adds a policy rule to the storage.
-func (a *adapterCasbin) AddPolicy(sec string, ptype string, rule []string) error {
-	line := savePolicyLine(ptype, rule)
-	_, err := dao.CasbinRule.Data(line).Insert()
-	return err
-}
-
-// RemovePolicy removes a policy rule from the storage.
-func (a *adapterCasbin) RemovePolicy(sec string, ptype string, rule []string) error {
-	line := savePolicyLine(ptype, rule)
-	err := rawDelete(a, line)
-	return err
-}
-
-// RemoveFilteredPolicy removes policy rules that match the filter from the storage.
-func (a *adapterCasbin) RemoveFilteredPolicy(sec string, ptype string,
-	fieldIndex int, fieldValues ...string) error {
-	line := &dbModel.CasbinRule{}
-	line.Ptype = ptype
-	if fieldIndex <= 0 && 0 < fieldIndex+len(fieldValues) {
-		line.V0 = fieldValues[0-fieldIndex]
-	}
-	if fieldIndex <= 1 && 1 < fieldIndex+len(fieldValues) {
-		line.V1 = fieldValues[1-fieldIndex]
-	}
-	if fieldIndex <= 2 && 2 < fieldIndex+len(fieldValues) {
-		line.V2 = fieldValues[2-fieldIndex]
-	}
-	if fieldIndex <= 3 && 3 < fieldIndex+len(fieldValues) {
-		line.V3 = fieldValues[3-fieldIndex]
-	}
-	if fieldIndex <= 4 && 4 < fieldIndex+len(fieldValues) {
-		line.V4 = fieldValues[4-fieldIndex]
-	}
-	if fieldIndex <= 5 && 5 < fieldIndex+len(fieldValues) {
-		line.V5 = fieldValues[5-fieldIndex]
-	}
-	err := rawDelete(a, line)
-	return err
-}
-
-func loadPolicyLine(line *dbModel.CasbinRule, model model.Model) {
-	lineText := line.Ptype
-	if line.V0 != "" {
-		lineText += ", " + line.V0
-	}
-	if line.V1 != "" {
-		lineText += ", " + line.V1
-	}
-	if line.V2 != "" {
-		lineText += ", " + line.V2
-	}
-	if line.V3 != "" {
-		lineText += ", " + line.V3
-	}
-	if line.V4 != "" {
-		lineText += ", " + line.V4
-	}
-	if line.V5 != "" {
-		lineText += ", " + line.V5
-	}
-	persist.LoadPolicyLine(lineText, model)
-}
-
-func savePolicyLine(ptype string, rule []string) *dbModel.CasbinRule {
-	line := &dbModel.CasbinRule{}
-	line.Ptype = ptype
-	if len(rule) > 0 {
-		line.V0 = rule[0]
-	}
-	if len(rule) > 1 {
-		line.V1 = rule[1]
-	}
-	if len(rule) > 2 {
-		line.V2 = rule[2]
-	}
-	if len(rule) > 3 {
-		line.V3 = rule[3]
-	}
-	if len(rule) > 4 {
-		line.V4 = rule[4]
-	}
-	if len(rule) > 5 {
-		line.V5 = rule[5]
-	}
-	return line
-}
-
-func rawDelete(a *adapterCasbin, line *dbModel.CasbinRule) error {
-	db := dao.CasbinRule.Where("ptype = ?", line.Ptype)
-	if line.V0 != "" {
-		db = db.Where("v0 = ?", line.V0)
-	}
-	if line.V1 != "" {
-		db = db.Where("v1 = ?", line.V1)
-	}
-	if line.V2 != "" {
-		db = db.Where("v2 = ?", line.V2)
-	}
-	if line.V3 != "" {
-		db = db.Where("v3 = ?", line.V3)
-	}
-	if line.V4 != "" {
-		db = db.Where("v4 = ?", line.V4)
-	}
-	if line.V5 != "" {
-		db = db.Where("v5 = ?", line.V5)
-	}
-	_, err := db.Delete()
-	return err
-}

+ 93 - 0
opms_admin/app/handler/group.go

@@ -0,0 +1,93 @@
+package handler
+
+import (
+	"context"
+	"dashoo.cn/common_definition/comm_def"
+	"dashoo.cn/micro/app/model"
+	"dashoo.cn/micro/app/service"
+	"dashoo.cn/opms_libary/myerrors"
+	"github.com/gogf/gf/errors/gerror"
+	"github.com/gogf/gf/frame/g"
+	"github.com/gogf/gf/util/gvalid"
+)
+
+type GroupHandler struct{}
+
+// GetList 获取列表
+func (h *GroupHandler) GetList(ctx context.Context, req *model.SysGroupSearchParams, rsp *comm_def.CommonMsg) error {
+	postService, err := service.NewGroupService(ctx)
+	if err != nil {
+		g.Log().Error(err)
+		return gerror.New("系统异常,请重新尝试")
+	}
+	total, list, err := postService.GetList(req)
+	_, _, rsp.Code, rsp.Msg = myerrors.CheckError(err)
+	rsp.Data = g.Map{"list": list, "total": total}
+	return nil
+}
+
+// GetEntityById 详情
+//func (o *GroupHandler) GetEntityById(ctx context.Context, req *comm_def.IdReq, rsp *comm_def.CommonMsg) error {
+//	// 参数校验
+//	if req.Id == 0 {
+//		return NoParamsErr
+//	}
+//	postService, err := service.NewGroupService(ctx)
+//	if err != nil {
+//		g.Log().Error(err)
+//		return gerror.New("系统异常,请重新尝试")
+//	}
+//	entity, err := postService.GetEntity(req.Id)
+//	_, _, rsp.Code, rsp.Msg = myerrors.CheckError(err)
+//	rsp.Data = entity
+//	return nil
+//}
+
+// Create 添加
+func (h *GroupHandler) Create(ctx context.Context, req *model.SysGroupReq, rsp *comm_def.CommonMsg) error {
+	// 检查请求参数
+	if v := gvalid.CheckStruct(ctx, req, nil); v != nil {
+		g.Log().Error(v)
+		return v
+	}
+	postService, err := service.NewGroupService(ctx)
+	if err != nil {
+		g.Log().Error(err)
+		return gerror.New("系统异常,请重新尝试")
+	}
+	err = postService.Create(req)
+	_, _, rsp.Code, rsp.Msg = myerrors.CheckError(err)
+	return nil
+}
+
+// UpdateById 编辑
+func (h *GroupHandler) UpdateById(ctx context.Context, req *model.UpdateSysGroupReq, rsp *comm_def.CommonMsg) error {
+	// 检查请求参数
+	if v := gvalid.CheckStruct(ctx, req, nil); v != nil {
+		g.Log().Error(v)
+		return v
+	}
+
+	postService, err := service.NewGroupService(ctx)
+	if err != nil {
+		g.Log().Error(err)
+		return gerror.New("系统异常,请重新尝试")
+	}
+
+	err = postService.UpdateById(req)
+	_, _, rsp.Code, rsp.Msg = myerrors.CheckError(err)
+	return nil
+}
+
+// DeleteByIds 删除菜单
+func (h *GroupHandler) DeleteByIds(ctx context.Context, req *comm_def.IdsReq, rsp *comm_def.CommonMsg) error {
+	postService, err := service.NewGroupService(ctx)
+	if err != nil {
+		g.Log().Error(err)
+		return gerror.New("系统异常,请重新尝试")
+	}
+
+	err = postService.DeleteByIds(req.Ids)
+	_, _, rsp.Code, rsp.Msg = myerrors.CheckError(err)
+	return nil
+}

+ 97 - 0
opms_admin/app/handler/post.go

@@ -0,0 +1,97 @@
+package handler
+
+import (
+	"context"
+	"dashoo.cn/common_definition/comm_def"
+	"dashoo.cn/micro/app/model"
+	"dashoo.cn/micro/app/service"
+	"dashoo.cn/opms_libary/myerrors"
+	"github.com/gogf/gf/errors/gerror"
+	"github.com/gogf/gf/frame/g"
+	"github.com/gogf/gf/util/gvalid"
+)
+
+type PostHandler struct{}
+
+// GetList 获取列表
+func (h *PostHandler) GetList(ctx context.Context, req *model.SysPostSearchParams, rsp *comm_def.CommonMsg) error {
+	postService, err := service.NewPostService(ctx)
+	if err != nil {
+		g.Log().Error(err)
+		return gerror.New("系统异常,请重新尝试")
+	}
+	total, list, err := postService.GetList(req)
+	_, _, rsp.Code, rsp.Msg = myerrors.CheckError(err)
+	rsp.Data = g.Map{"list": list, "total": total}
+	return nil
+}
+
+// GetEntityById 详情
+//func (o *PostHandler) GetEntityById(ctx context.Context, req *comm_def.IdReq, rsp *comm_def.CommonMsg) error {
+//	// 参数校验
+//	if req.Id == 0 {
+//		return NoParamsErr
+//	}
+//	postService, err := service.NewPostService(ctx)
+//	if err != nil {
+//		g.Log().Error(err)
+//		return gerror.New("系统异常,请重新尝试")
+//	}
+//	entity, err := postService.GetEntity(req.Id)
+//	if err != nil {
+//		g.Log().Error(err)
+//		return err
+//	}
+//	_, _, rsp.Code, rsp.Msg = myerrors.CheckError(err)
+//	rsp.Data = entity
+//	return nil
+//}
+
+// Create 添加
+func (h *PostHandler) Create(ctx context.Context, req *model.SysPostReq, rsp *comm_def.CommonMsg) error {
+	// 检查请求参数
+	if v := gvalid.CheckStruct(ctx, req, nil); v != nil {
+		g.Log().Error(v)
+		return v
+	}
+	postService, err := service.NewPostService(ctx)
+	if err != nil {
+		g.Log().Error(err)
+		return gerror.New("系统异常,请重新尝试")
+	}
+	err = postService.Create(req)
+	_, _, rsp.Code, rsp.Msg = myerrors.CheckError(err)
+	return nil
+}
+
+// UpdateById 编辑
+func (h *PostHandler) UpdateById(ctx context.Context, req *model.UpdateSysPostReq, rsp *comm_def.CommonMsg) error {
+	// 检查请求参数
+	if v := gvalid.CheckStruct(ctx, req, nil); v != nil {
+		g.Log().Error(v)
+		return v
+	}
+
+	postService, err := service.NewPostService(ctx)
+	if err != nil {
+		g.Log().Error(err)
+		return gerror.New("系统异常,请重新尝试")
+	}
+
+	err = postService.UpdateById(req)
+	_, _, rsp.Code, rsp.Msg = myerrors.CheckError(err)
+	return nil
+}
+
+// DeleteByIds 删除菜单
+func (h *PostHandler) DeleteByIds(ctx context.Context, req *comm_def.IdsReq, rsp *comm_def.CommonMsg) error {
+	postService, err := service.NewPostService(ctx)
+	if err != nil {
+		g.Log().Error(err)
+		return gerror.New("系统异常,请重新尝试")
+	}
+
+	err = postService.DeleteByIds(req.Ids)
+	_, _, rsp.Code, rsp.Msg = myerrors.CheckError(err)
+	return nil
+}

+ 58 - 27
opms_admin/app/handler/role.go

@@ -1,4 +1,3 @@
-// Package handler 角色管理
 package handler
 
 import (
@@ -28,25 +27,21 @@ func (h *RoleHandler) GetList(ctx context.Context, req *model.SelectPageReq, rsp
 }
 
 // GetEntityById 详情
-//func (o *RoleHandler) GetEntityById(ctx context.Context, req *comm_def.IdReq, rsp *comm_def.CommonMsg) error {
-//	// 参数校验
-//	if req.Id == 0 {
-//		return NoParamsErr
-//	}
-//	roleService, err := service.NewRoleService(ctx)
-//	if err != nil {
-//		g.Log().Error(err)
-//		return gerror.New("系统异常,请重新尝试")
-//	}
-//	entity, err := roleService.GetEntity(req.Id)
-//	if err != nil {
-//		g.Log().Error(err)
-//		return err
-//	}
-//	_, _, rsp.Code, rsp.Msg = myerrors.CheckError(err)
-//	rsp.Data = entity
-//	return nil
-//}
+func (o *RoleHandler) GetEntityById(ctx context.Context, req *comm_def.IdReq, rsp *comm_def.CommonMsg) error {
+	// 参数校验
+	if req.Id == 0 {
+		return NoParamsErr
+	}
+	roleService, err := service.NewRoleService(ctx)
+	if err != nil {
+		g.Log().Error(err)
+		return gerror.New("系统异常,请重新尝试")
+	}
+	entity, err := roleService.GetRoleById(req.Id)
+	_, _, rsp.Code, rsp.Msg = myerrors.CheckError(err)
+	rsp.Data = entity
+	return nil
+}
 
 // Create 添加
 func (h *RoleHandler) Create(ctx context.Context, req *model.SysRoleReq, rsp *comm_def.CommonMsg) error {
@@ -60,17 +55,13 @@ func (h *RoleHandler) Create(ctx context.Context, req *model.SysRoleReq, rsp *co
 		g.Log().Error(err)
 		return gerror.New("系统异常,请重新尝试")
 	}
-	err = roleService.CreateRolePost(req)
+	err = roleService.CreateRole(req)
 	_, _, rsp.Code, rsp.Msg = myerrors.CheckError(err)
 	return nil
 }
 
 // UpdateById 编辑
-func (h *RoleHandler) UpdateById(ctx context.Context, req *model.SysRoleReq, rsp *comm_def.CommonMsg) error {
-	// 参数校验
-	if req.Id <= 0 {
-		return NoParamsErr
-	}
+func (h *RoleHandler) UpdateById(ctx context.Context, req *model.UpdateSysRoleReq, rsp *comm_def.CommonMsg) error {
 	// 检查请求参数
 	if v := gvalid.CheckStruct(ctx, req, nil); v != nil {
 		g.Log().Error(v)
@@ -83,7 +74,7 @@ func (h *RoleHandler) UpdateById(ctx context.Context, req *model.SysRoleReq, rsp
 		return gerror.New("系统异常,请重新尝试")
 	}
 
-	err = roleService.UpdateRolePost(req)
+	err = roleService.UpdateRole(req)
 	_, _, rsp.Code, rsp.Msg = myerrors.CheckError(err)
 	return nil
 }
@@ -100,3 +91,43 @@ func (h *RoleHandler) DeleteByIds(ctx context.Context, req *comm_def.IdsReq, rsp
 	_, _, rsp.Code, rsp.Msg = myerrors.CheckError(err)
 	return nil
 }
+
+// GetRoleDeptTreeselect 获取角色下的自定义部门
+func (h *RoleHandler) GetRoleDeptTreeselect(ctx context.Context, req *comm_def.IdReq, rsp *comm_def.CommonMsg) error {
+	roleService, err := service.NewRoleService(ctx)
+	if err != nil {
+		g.Log().Error(err)
+		return gerror.New("系统异常,请重新尝试")
+	}
+
+	deptIds, err := roleService.GetRoleDeptTreeselect(req.Id)
+	_, _, rsp.Code, rsp.Msg = myerrors.CheckError(err)
+	rsp.Data = deptIds
+	return nil
+}
+
+// UpdateRoleStatus 修改角色状态
+func (h *RoleHandler) UpdateRoleStatus(ctx context.Context, req *model.StatusSetReq, rsp *comm_def.CommonMsg) error {
+	roleService, err := service.NewRoleService(ctx)
+	if err != nil {
+		g.Log().Error(err)
+		return gerror.New("系统异常,请重新尝试")
+	}
+
+	err = roleService.UpdateRoleStatus(req)
+	_, _, rsp.Code, rsp.Msg = myerrors.CheckError(err)
+	return nil
+}
+
+// UpdateRoleDataScope 角色下的数据权限
+func (h *RoleHandler) UpdateRoleDataScope(ctx context.Context, req *model.DataScopeReq, rsp *comm_def.CommonMsg) error {
+	roleService, err := service.NewRoleService(ctx)
+	if err != nil {
+		g.Log().Error(err)
+		return gerror.New("系统异常,请重新尝试")
+	}
+
+	err = roleService.UpdateRoleDataScope(req)
+	_, _, rsp.Code, rsp.Msg = myerrors.CheckError(err)
+	return nil
+}

+ 24 - 23
opms_admin/app/handler/user.go

@@ -99,7 +99,7 @@ func (e *UserHandler) GetUserInfo(ctx context.Context, req *comm_def.IdReq, rsp
 	userId := int(req.Id)
 	if req.Id == 0 {
 		// 从上下文中获取用户
-		userId = 1
+		userId = userService.GetCxtUserId()
 	}
 
 	data, err := userService.GetUserInfoById(userId)
@@ -107,30 +107,31 @@ func (e *UserHandler) GetUserInfo(ctx context.Context, req *comm_def.IdReq, rsp
 		g.Log().Error(err)
 		return err
 	}
-	//// 获取用户权限 角色
-	//permissionService, err := permission.NewService(tenant)
-	//if err != nil {
-	//	g.Log().Error(err)
-	//	return gerror.New("系统异常,请重新尝试")
-	//}
-	//userRoles, err := permissionService.GetRoleIdsByUser(gconv.Int32(req.Id))
-	//if err != nil {
-	//	g.Log().Error(err)
-	//	return err
-	//}
-	//userPositions, err := permissionService.GetPositionIdsByUser(gconv.Int32(req.Id))
-	//_, err, code, msg := myerrors.CheckError(err)
-	//if err != nil {
-	//	g.Log().Error(err)
-	//	return err
-	//}
-	//rsp.Code = code
-	//rsp.Msg = msg
+	// 获取用户权限 角色
+	userRoles, err := userService.GetUserRoleIds(userId)
+	_, err, rsp.Code, rsp.Msg = myerrors.CheckError(err)
+	if err != nil {
+		g.Log().Error(err)
+		return err
+	}
+	userPosts, err := userService.GetUserPostIds(userId)
+	_, err, rsp.Code, rsp.Msg = myerrors.CheckError(err)
+	if err != nil {
+		g.Log().Error(err)
+		return err
+	}
+	userGroups, err := userService.GetUserGroupIds(userId)
+	_, err, rsp.Code, rsp.Msg = myerrors.CheckError(err)
+	if err != nil {
+		g.Log().Error(err)
+		return err
+	}
 
 	rsp.Data = g.Map{
-		"entity": data,
-		//"role_ids": convert.ToStringArray(userRoles),
-		//"post_ids": convert.ToStringArray(userPositions),
+		"entity":   data,
+		"roleIds":  userRoles,
+		"postIds":  userPosts,
+		"groupIds": userGroups,
 	}
 	return nil
 }

+ 1 - 1
opms_admin/app/model/internal/sys_group.go

@@ -15,7 +15,7 @@ type SysGroup struct {
 	GroupName   string      `orm:"group_name"   json:"groupName"`   // 用户组名称
 	Status      string      `orm:"status"       json:"status"`      // 状态(10正常20停用)
 	Sort        int         `orm:"sort"         json:"sort"`        // 显示顺序
-	Remark      int         `orm:"remark"       json:"remark"`      // 备注
+	Remark      string      `orm:"remark"       json:"remark"`      // 备注
 	CreatedBy   int         `orm:"created_by"   json:"createdBy"`   // 创建人ID
 	CreatedName string      `orm:"created_name" json:"createdName"` // 创建人
 	CreatedTime *gtime.Time `orm:"created_time" json:"createdTime"` // 创建时间

+ 1 - 1
opms_admin/app/model/sys_dept.go

@@ -21,7 +21,7 @@ type SysDeptSearchParams struct {
 
 type SysDeptTreeRes struct {
 	*SysDept
-	Children []*SysDeptTreeRes `json:"children"`
+	Children []*SysDeptTreeRes `json:"children,omitempty"`
 }
 
 type SysDeptReq struct {

+ 24 - 0
opms_admin/app/model/sys_group.go

@@ -6,9 +6,33 @@ package model
 
 import (
 	"dashoo.cn/micro/app/model/internal"
+	"dashoo.cn/opms_libary/request"
 )
 
 // SysGroup is the golang structure for table sys_group.
 type SysGroup internal.SysGroup
 
 // Fill with you ideas below.
+
+// SysGroupSearchParams 搜索参数
+type SysGroupSearchParams struct {
+	GroupCode string `p:"groupCode"` //用户组编码
+	GroupName string `p:"groupName"` //用户组名称
+	Status    string `p:"status"`    //状态
+	request.PageReq
+}
+
+// SysGroupReq 添加用户组参数
+type SysGroupReq struct {
+	GroupCode string `p:"groupCode" v:"required#用户组编码不能为空"`
+	GroupName string `p:"groupName" v:"required#用户组名称不能为空"`
+	Sort      int    `p:"sort" v:"required#用户组排序不能为空"`
+	Status    string `p:"status" v:"required#状态不能为空"`
+	Remark    string `p:"remark"`
+}
+
+// UpdateSysGroupReq 修改用户组参数
+type UpdateSysGroupReq struct {
+	Id int64 `p:"id" v:"required#id必须"`
+	SysGroupReq
+}

+ 11 - 13
opms_admin/app/model/sys_post.go

@@ -22,19 +22,17 @@ type SysPostSearchParams struct {
 	request.PageReq
 }
 
-// SysPostAddParams 添加岗位参数
-type SysPostAddParams struct {
-	PostCode  string `p:"postCode" v:"required#岗位编码不能为空"`
-	PostName  string `p:"postName" v:"required#岗位名称不能为空"`
-	PostSort  int    `p:"postSort" v:"required#岗位排序不能为空"`
-	Status    string `p:"status" v:"required#状态不能为空"`
-	Remark    string `p:"remark"`
-	CreatedBy uint64
+// SysPostReq 添加岗位参数
+type SysPostReq struct {
+	PostCode string `p:"postCode" v:"required#岗位编码不能为空"`
+	PostName string `p:"postName" v:"required#岗位名称不能为空"`
+	Sort     int    `p:"sort" v:"required#岗位排序不能为空"`
+	Status   string `p:"status" v:"required#状态不能为空"`
+	Remark   string `p:"remark"`
 }
 
-// SysPostEditParams 修改岗位参数
-type SysPostEditParams struct {
-	PostId int64 `p:"postId" v:"required#id必须"`
-	SysPostAddParams
-	UpdatedBy uint64
+// UpdateSysPostReq 修改岗位参数
+type UpdateSysPostReq struct {
+	Id int64 `p:"id" v:"required#id必须"`
+	SysPostReq
 }

+ 17 - 10
opms_admin/app/model/sys_role.go

@@ -15,29 +15,36 @@ type SysRole internal.SysRole
 // Fill with you ideas below.
 
 type SysRoleReq struct {
-	Id        int    `json:"id"`        // 角色ID
-	RoleName  string `json:"roleName"`  // 角色名称
-	RoleKey   string `json:"roleKey"`   // 角色权限字符串
-	DataScope string `json:"dataScope"` // 数据范围;(10:全部数据权限 20:自定数据权限 30:本部门数据权限 40:本部门及以下数据权限)
-	Status    string `json:"status"`    // 角色状态(10正常20停用)
-	Sort      int    `json:"sort"`      // 显示顺序
-	Remark    string `son:"remark"`     // 备注
+	RoleName          string `json:"roleName" v:"required#状态不能为空"` // 角色名称
+	RoleKey           string `json:"roleKey" v:"required#状态不能为空"`  // 角色权限字符串
+	Status            string `json:"status" v:"required#状态不能为空"`   // 角色状态(10正常20停用)
+	MenuCheckStrictly string `json:"menuCheckStrictly"`            // 菜单树选择项是否关联显示
+	DeptCheckStrictly string `json:"deptCheckStrictly"`            // 部门树选择项是否关联显示
+	DataScope         string `json:"dataScope"`                    // 数据范围;(10:全部数据权限 20:自定数据权限 30:本部门数据权限 40:本部门及以下数据权限)
+	Sort              int    `json:"sort"`                         // 显示顺序
+	Remark            string `son:"remark"`                        // 备注
+	MenuIds           []int  `json:"menuIds,omitempty"`
 }
 
-// 分页请求参数
+type UpdateSysRoleReq struct {
+	Id int `json:"id" v:"required#角色ID不能为空"` // 角色ID
+	SysRoleReq
+}
+
+// SelectPageReq 分页请求参数
 type SelectPageReq struct {
 	RoleName string `p:"roleName"` //参数名称
 	Status   string `p:"status"`   //状态
 	request.PageReq
 }
 
-// 修改状态参数
+// StatusSetReq 修改状态参数
 type StatusSetReq struct {
 	RoleId uint `p:"roleId" v:"required#角色ID不能为空"`
 	Status uint `p:"status" v:"required#状态不能为空"`
 }
 
-// 角色数据授权参数
+// DataScopeReq 角色数据授权参数
 type DataScopeReq struct {
 	RoleId    uint   `p:"roleId" v:"required#角色ID不能为空"`
 	DataScope uint   `p:"dataScope" v:"required#权限范围不能为空"`

+ 1 - 1
opms_admin/app/model/sys_user.go

@@ -56,6 +56,7 @@ type SetUserReq struct {
 	IsAdmin  int    `p:"isAdmin"` // 是否后台管理员 1 是  0   否
 	RoleIds  []int  `p:"roleIds"`
 	PostIds  []int  `p:"postIds"`
+	GroupIds []int  `p:"groupIds"`
 }
 
 // AddUserReq 添加用户参数
@@ -63,7 +64,6 @@ type AddUserReq struct {
 	SetUserReq
 	UserName string `p:"userName" v:"required#用户账号不能为空"`
 	Password string `p:"password" v:"required|password#密码不能为空|密码以字母开头,只能包含字母、数字和下划线,长度在6~18之间"`
-	UserSalt string
 }
 
 type EditUserReq struct {

+ 19 - 11
opms_admin/app/service/base.go

@@ -1,23 +1,27 @@
 package service
 
 import (
+	"dashoo.cn/opms_libary/request"
 	"github.com/gogf/gf/os/gtime"
 	"log"
 	"reflect"
 )
 
 var (
-	// CommonUpdateFieldEx, UpdateFieldEx 更新过滤字段
+	// CommonUpdateFieldEx UpdateFieldEx 更新过滤字段
 	CommonUpdateFieldEx = []interface{}{"created_by", "created_name", "created_time"}
 	UpdateFieldEx       = []interface{}{"id", "created_by", "created_name", "created_time"}
 )
 
-// SetCreatedInfo 插入数据库时设置创建信息
-func SetCreatedInfo(entry interface{}, id int, name string) {
-	v := reflect.ValueOf(entry)
-	t := reflect.TypeOf(entry)
+// SetCurrentCreatedInfo 插入数据库时设置创建信息
+func SetCurrentCreatedInfo(entity interface{}, cxtUser *request.UserInfo) {
+	SetCreatedInfo(entity, cxtUser.Id, cxtUser.UserName)
+}
+func SetCreatedInfo(entity interface{}, id int, name string) {
+	v := reflect.ValueOf(entity)
+	t := reflect.TypeOf(entity)
 	if t.Kind() == reflect.Map {
-		data := entry.(map[string]interface{})
+		data := entity.(map[string]interface{})
 		data["created_by"] = id
 		data["created_name"] = name
 		data["created_time"] = gtime.Now()
@@ -46,12 +50,16 @@ func SetCreatedInfo(entry interface{}, id int, name string) {
 	}
 }
 
-// SetUpdatedInfo 插入数据库时设置修改信息
-func SetUpdatedInfo(entry interface{}, id int, name string) {
-	v := reflect.ValueOf(entry)
-	t := reflect.TypeOf(entry)
+// SetCurrentUpdatedInfo 插入数据库时设置修改信息
+func SetCurrentUpdatedInfo(entity interface{}, cxtUser *request.UserInfo) {
+	SetUpdatedInfo(entity, cxtUser.Id, cxtUser.UserName)
+}
+
+func SetUpdatedInfo(entity interface{}, id int, name string) {
+	v := reflect.ValueOf(entity)
+	t := reflect.TypeOf(entity)
 	if t.Kind() == reflect.Map {
-		data := entry.(map[string]interface{})
+		data := entity.(map[string]interface{})
 		data["updated_by"] = id
 		data["updated_name"] = name
 		data["updated_time"] = gtime.Now()

+ 94 - 0
opms_admin/app/service/context.go

@@ -2,14 +2,24 @@ package service
 
 import (
 	"context"
+	"dashoo.cn/micro/app/dao"
+	"dashoo.cn/micro/app/model"
 	"dashoo.cn/opms_libary/micro_srv"
 	"dashoo.cn/opms_libary/request"
+	"fmt"
+	"github.com/gogf/gf/container/gset"
+	"github.com/gogf/gf/database/gdb"
+	"github.com/gogf/gf/errors/gerror"
+	"github.com/gogf/gf/frame/g"
 	"github.com/gogf/gf/os/glog"
+	"github.com/gogf/gf/util/gconv"
+	"reflect"
 )
 
 // Context 上下文管理服务
 type contextService struct {
 	Tenant  string            `json:"tenant"`
+	Table   string            `json:"table"`
 	CxtUser *request.UserInfo `json:"cxtUser"`
 }
 
@@ -35,6 +45,90 @@ func (c *contextService) Init(ctx context.Context) (*contextService, error) {
 	return c, nil
 }
 
+// checkDataScopeWhere 检查结构体是否存在创建人字段
+func (c *contextService) checkDataScopeWhere(entity interface{}) error {
+	t := reflect.TypeOf(entity)
+	if t.Kind() == reflect.Ptr {
+		t = t.Elem()
+	}
+	if _, ok := t.FieldByName("CreatedBy"); !ok {
+		return gerror.New("结构体不存在创建人字段")
+	}
+	return nil
+}
+
+// SetDataScopeWhere 设置数据权限
+func (c *contextService) SetDataScopeWhere(M *gdb.Model) (*gdb.Model, error) {
+	where, err := c.GetDataScopeWhere()
+	if err != nil {
+		return nil, err
+	}
+	if where == nil {
+		return M, nil
+	}
+	M = M.LeftJoin(dao.SysUser.Table, "user", fmt.Sprintf("%v.created_by=`user`.id", c.Table)).Where(where)
+	return M, nil
+}
+
+// GetDataScopeWhere 获取数据权限判断条件
+func (c *contextService) GetDataScopeWhere() (where g.Map, err error) {
+	userSrv := &userService{
+		contextService: c,
+		Dao:            dao.NewSysUserDao(c.Tenant),
+	}
+	roleSrv := &roleService{
+		contextService: c,
+		Dao:            dao.NewSysRoleDao(c.Tenant),
+	}
+	deptSrv := &deptService{
+		contextService: c,
+		Dao:            dao.NewSysDeptDao(c.Tenant),
+	}
+	userInfo := c.CxtUser
+	whereJustMe := g.Map{} //本人数据权限
+	//若存在用户id的字段,则生成判断数据权限的条件
+	//1、获取当前用户所属角色
+	roles, err := userSrv.GetRolesByUserId(userInfo.Id)
+	if err != nil {
+		return nil, err
+	}
+	//2获取角色对应数据权限
+	deptIdArr := gset.New()
+	for _, role := range roles {
+		switch role.DataScope {
+		case "1": //全部数据权限
+			return nil, nil
+		case "2": //自定数据权限
+			deptIds, err := roleSrv.GetRoleDeptTreeselect(gconv.Int64(role.Id))
+			if err != nil {
+				return nil, err
+			}
+			deptIdArr.Add(gconv.Interfaces(deptIds)...)
+		case "3": //本部门数据权限
+			deptIdArr.Add(gconv.Int64(userInfo.DeptId))
+		case "4": //本部门及以下数据权限
+			deptIdArr.Add(gconv.Int64(userInfo.DeptId))
+			//获取正常状态部门数据
+			depts, err := deptSrv.GetList(&model.SysDeptSearchParams{Status: "10"})
+			if err != nil {
+				return nil, err
+			}
+			childrenList := deptSrv.FindSonByParentId(depts, userInfo.DeptId)
+			for _, children := range childrenList {
+				deptIdArr.Add(gconv.Int64(children.Id))
+			}
+		case "5": //仅本人数据权限
+			whereJustMe = g.Map{"`user`.id": userInfo.Id}
+		}
+	}
+	if deptIdArr.Size() > 0 {
+		where = g.Map{"`user`.dept_id": deptIdArr.Slice()}
+	} else if len(whereJustMe) > 0 {
+		where = whereJustMe
+	}
+	return
+}
+
 func (c *contextService) GetCxtUserId() int {
 	if c.CxtUser == nil {
 		return -1

+ 10 - 9
opms_admin/app/service/sys_dept.go

@@ -18,11 +18,12 @@ func NewDeptService(ctx context.Context) (svc *deptService, err error) {
 		return nil, err
 	}
 	svc.Dao = dao.NewSysDeptDao(svc.Tenant)
+	svc.Table = svc.Dao.Table
 	return svc, nil
 }
 
 func (s *deptService) GetList(searchParams *model.SysDeptSearchParams) ([]*model.SysDept, error) {
-	deptModel := dao.SysDept.M
+	deptModel := s.Dao.M
 	if searchParams.DeptName != "" {
 		deptModel = deptModel.Where("dept_name like ?", "%"+searchParams.DeptName+"%")
 	}
@@ -47,13 +48,13 @@ func (s *deptService) GetList(searchParams *model.SysDeptSearchParams) ([]*model
 }
 
 func (s *deptService) GetRoleDepts(roleId int) ([]int, error) {
-	var entitys []*model.SysRoleDept
-	err := dao.SysRoleDept.Where("role_id", roleId).Scan(&entitys)
+	var entityList []*model.SysRoleDept
+	err := s.Dao.Where("role_id", roleId).Scan(&entityList)
 	if err != nil {
 		return nil, err
 	}
 	result := make([]int, 0)
-	for _, v := range entitys {
+	for _, v := range entityList {
 		result = append(result, v.DeptId)
 	}
 	return result, nil
@@ -89,7 +90,7 @@ func (s *deptService) GetDeptListTree(pid int, list []*model.SysDept) []*model.S
 }
 
 func (s *deptService) GetDeptById(id int64) (dept *model.SysDept, err error) {
-	err = dao.SysDept.Where("id", id).Scan(&dept)
+	err = s.Dao.Where("id", id).Scan(&dept)
 	return
 }
 
@@ -99,7 +100,7 @@ func (s *deptService) Create(req *model.SysDeptReq) (err error) {
 		return err
 	}
 	SetCreatedInfo(data, s.GetCxtUserId(), s.GetCxtUserName())
-	_, err = dao.SysDept.Insert(data)
+	_, err = s.Dao.Insert(data)
 	return
 }
 
@@ -109,14 +110,14 @@ func (s *deptService) UpdateById(req *model.UpdateSysDeptReq) error {
 		return err
 	}
 	SetUpdatedInfo(data, s.GetCxtUserId(), s.GetCxtUserName())
-	_, err := dao.SysDept.FieldsEx(dao.SysDept.Columns.Id, dao.SysDept.Columns.CreatedBy, dao.SysDept.Columns.CreatedName, dao.SysDept.Columns.CreatedTime).WherePri(data.Id).
+	_, err := s.Dao.FieldsEx(UpdateFieldEx...).WherePri(data.Id).
 		Update(data)
 	return err
 }
 
 func (s *deptService) DeleteById(id int) error {
 	var list []*model.SysDept
-	err := dao.SysDept.Scan(&list)
+	err := s.Dao.Scan(&list)
 	if err != nil {
 		return err
 	}
@@ -126,6 +127,6 @@ func (s *deptService) DeleteById(id int) error {
 		ids = append(ids, v.Id)
 	}
 	ids = append(ids, id)
-	_, err = dao.SysDept.Where(dao.SysDept.Columns.Id+" in (?)", ids).Delete()
+	_, err = s.Dao.Where(s.Dao.Columns.Id+" in (?)", ids).Delete()
 	return err
 }

+ 18 - 23
opms_admin/app/service/sys_dict_data.go

@@ -15,7 +15,7 @@ import (
 
 type dictDataService struct {
 	*contextService
-	Dao *dao.SysDictTypeDao
+	Dao *dao.SysDictDataDao
 }
 
 func NewDictDataService(ctx context.Context) (svc *dictDataService, err error) {
@@ -23,34 +23,31 @@ func NewDictDataService(ctx context.Context) (svc *dictDataService, err error) {
 	if svc.contextService, err = svc.Init(ctx); err != nil {
 		return nil, err
 	}
-	svc.Dao = dao.NewSysDictTypeDao(svc.Tenant)
+	svc.Dao = dao.NewSysDictDataDao(svc.Tenant)
+	svc.Table = svc.Dao.Table
 	return svc, nil
 }
 
 func (s *dictDataService) GetDictDataList(req *model.SelectDictPageReq) (total int, list []*model.SysDictData, err error) {
-	d := dao.SysDictData.Ctx(req.Ctx)
+	db := s.Dao.Ctx(req.Ctx)
 	if req != nil {
 		if req.DictLabel != "" {
-			d = d.Where(dao.SysDictData.Columns.DictLabel+" like ?", "%"+req.DictLabel+"%")
+			db = db.Where(s.Dao.Columns.DictLabel+" like ?", "%"+req.DictLabel+"%")
 		}
 		if req.Status != "" {
-			d = d.Where(dao.SysDictData.Columns.Status+" = ", gconv.Int(req.Status))
+			db = db.Where(s.Dao.Columns.Status+" = ", gconv.Int(req.Status))
 		}
 		if req.DictType != "" {
-			d = d.Where(dao.SysDictData.Columns.DictType+" = ?", req.DictType)
+			db = db.Where(s.Dao.Columns.DictType+" = ?", req.DictType)
 		}
-		total, err = d.Count()
+		total, err = db.Count()
 		if err != nil {
 			g.Log().Error(err)
 			err = gerror.New("获取总行数失败")
 			return
 		}
-		if req.PageNum == 0 {
-			req.PageNum = 1
-		}
 	}
-	list, err = d.Page(req.GetPage()).Order(dao.SysDictData.Columns.DictSort + " asc," +
-		dao.SysDictData.Columns.DictCode + " asc").All()
+	list, err = db.Page(req.GetPage()).Order(s.Dao.Columns.DictSort + " asc," + s.Dao.Columns.DictCode + " asc").All()
 	if err != nil {
 		g.Log().Error(err)
 		err = gerror.New("获取数据失败")
@@ -61,7 +58,7 @@ func (s *dictDataService) GetDictDataList(req *model.SelectDictPageReq) (total i
 
 // GetDictDataById 通过字典数据id获取字典数据
 func (s *dictDataService) GetDictDataById(id int64) (data *model.SysDictData, err error) {
-	data, err = dao.SysDictData.FindOne(dao.SysDictData.Columns.DictCode, id)
+	data, err = s.Dao.FindOne(s.Dao.Columns.DictCode, id)
 	if err != nil {
 		g.Log().Error(err)
 		err = gerror.New("获取字典数据失败")
@@ -88,16 +85,14 @@ func (s *dictDataService) GetDictWithDataByType(req *model.GetDictReq) (dict *mo
 		//从数据库获取
 		dict = &model.DictRes{}
 		//获取类型数据
-		err = dao.SysDictType.Ctx(req.Ctx).Where(dao.SysDictType.Columns.DictType, req.DictType).
-			And(dao.SysDictType.Columns.Status, 1).Fields(model.DictTypeRes{}).Scan(&dict.Info)
+		err = s.Dao.DB.Model("sys_dict_type").Where(dao.SysDictType.Columns.DictType, req.DictType).
+			Where(dao.SysDictType.Columns.Status, "10").Fields(model.DictTypeRes{}).Scan(&dict.Info)
 		if err != nil {
 			g.Log().Error(err)
 			err = gerror.New("获取字典类型失败")
 		}
-		err = dao.SysDictData.Ctx(req.Ctx).Fields(model.DictDataRes{}).
-			Where(dao.SysDictData.Columns.DictType, req.DictType).
-			Order(dao.SysDictData.Columns.DictSort + " asc," +
-				dao.SysDictData.Columns.DictCode + " asc").
+		err = s.Dao.Where(s.Dao.Columns.DictType, req.DictType).Where(s.Dao.Columns.Status, "10").
+			Order(s.Dao.Columns.DictSort + " asc," + s.Dao.Columns.DictCode + " asc").
 			Scan(&dict.Values)
 		if err != nil {
 			g.Log().Error(err)
@@ -123,7 +118,7 @@ func (s *dictDataService) GetDictWithDataByType(req *model.GetDictReq) (dict *mo
 
 // CheckDictTypeUniqueAll 检查字典类型是否唯一
 func (s *dictDataService) CheckDictTypeUniqueAll(dictType string) bool {
-	dict, err := dao.SysDictData.FindOne(dao.SysDictData.Columns.DictType+"=?", dictType)
+	dict, err := s.Dao.FindOne(s.Dao.Columns.DictType+"=?", dictType)
 	if err != nil {
 		g.Log().Error(err)
 		return false
@@ -142,7 +137,7 @@ func (s *dictDataService) Create(req *model.DictDataAddReq) (id int64, err error
 		return -1, err
 	}
 	SetCreatedInfo(data, s.GetCxtUserId(), s.GetCxtUserName())
-	res, err = dao.SysDictData.Data(data).Insert()
+	res, err = s.Dao.Data(data).Insert()
 	if err != nil {
 		g.Log().Error(err)
 		err = gerror.New("添加字典数据失败")
@@ -160,13 +155,13 @@ func (s *dictDataService) UpdateByDict(req *model.EditDictDataReq) (err error) {
 	}
 	SetUpdatedInfo(data, s.GetCxtUserId(), s.GetCxtUserName())
 	updateFieldEx := append(CommonUpdateFieldEx, dao.SysDictData.Columns.DictCode)
-	_, err = dao.SysDictData.FieldsEx(updateFieldEx...).WherePri(req.DictCode).Update(data)
+	_, err = s.Dao.FieldsEx(updateFieldEx...).WherePri(req.DictCode).Update(data)
 	return
 }
 
 // DeleteDictDataByIds 删除字典数据
 func (s *dictDataService) DeleteDictDataByIds(ids []int64) error {
-	_, err := dao.SysDictData.Where(dao.SysDictData.Columns.DictCode+" in(?)", ids).Delete()
+	_, err := s.Dao.Where(s.Dao.Columns.DictCode+" in(?)", ids).Delete()
 	if err != nil {
 		g.Log().Error(err)
 		return gerror.New("删除失败")

+ 19 - 20
opms_admin/app/service/sys_dict_type.go

@@ -24,19 +24,20 @@ func NewDictTypeService(ctx context.Context) (svc *dictTypeService, err error) {
 		return nil, err
 	}
 	svc.Dao = dao.NewSysDictTypeDao(svc.Tenant)
+	svc.Table = svc.Dao.Table
 	return svc, nil
 }
 
 func (s *dictTypeService) GetList(req *model.ListSysDictTypeReq) (total int, list []*model.SysDictType, err error) {
-	db := s.Dao.M
+	db := s.Dao
 	if req.DictName != "" {
-		db = db.Where(dao.SysDictType.Columns.DictName+" like ?", "%"+req.DictName+"%")
+		db.Where(s.Dao.Columns.DictName+" like ?", "%"+req.DictName+"%")
 	}
 	if req.DictType != "" {
-		db = db.Where(dao.SysDictType.Columns.DictType+" like ?", "%"+req.DictType+"%")
+		db.Where(s.Dao.Columns.DictType+" like ?", "%"+req.DictType+"%")
 	}
 	if req.Status != "" {
-		db = db.Where(dao.SysDictType.Columns.Status+" = ", gconv.Int(req.Status))
+		db.Where(s.Dao.Columns.Status+" = ", gconv.Int(req.Status))
 	}
 	total, err = db.Count()
 	if err != nil {
@@ -44,7 +45,7 @@ func (s *dictTypeService) GetList(req *model.ListSysDictTypeReq) (total int, lis
 		err = gerror.New("获取总行数失败")
 		return
 	}
-	err = db.Page(req.GetPage()).Order(dao.SysDictType.Columns.Id + " asc").Scan(&list)
+	err = db.Page(req.GetPage()).Order(s.Dao.Columns.Id + " asc").Scan(&list)
 	if err != nil {
 		g.Log().Error(err)
 		err = gerror.New("获取数据失败")
@@ -54,7 +55,7 @@ func (s *dictTypeService) GetList(req *model.ListSysDictTypeReq) (total int, lis
 
 // GetDictById 获取字典类型
 func (s *dictTypeService) GetDictById(id int64) (dict *model.SysDictType, err error) {
-	dict, err = dao.SysDictType.FindOne(dao.SysDictType.Columns.Id, id)
+	dict, err = s.Dao.FindOne(s.Dao.Columns.Id, id)
 	if err != nil {
 		g.Log().Error(err)
 		err = gerror.New("获取字典类型失败")
@@ -75,7 +76,7 @@ func (s *dictTypeService) GetAllDictType() (list []*model.SysDictType, err error
 		err = gconv.Structs(data, &list)
 		return
 	}
-	err = dao.SysDictType.Where("status", 1).Order("dict_id ASC").Scan(&list)
+	err = s.Dao.Where("status", 1).Order("dict_id ASC").Scan(&list)
 	if err != nil {
 		g.Log().Error(err)
 		err = gerror.New("获取字典类型数据出错")
@@ -88,10 +89,9 @@ func (s *dictTypeService) GetAllDictType() (list []*model.SysDictType, err error
 
 // ExistsDictType 检查类型是否已经存在
 func (s *dictTypeService) ExistsDictType(dictType string, dictId ...int64) bool {
-	d := dao.SysDictType.Fields(dao.SysDictType.Columns.Id).
-		Where(dao.SysDictType.Columns.DictType, dictType)
+	d := s.Dao.Fields(s.Dao.Columns.Id).Where(s.Dao.Columns.DictType, dictType)
 	if len(dictId) > 0 {
-		d = d.And(dao.SysDictType.Columns.Id+" !=? ", dictId)
+		d = d.And(s.Dao.Columns.Id+" !=? ", dictId)
 	}
 	dict, err := d.FindOne()
 	if err != nil {
@@ -110,7 +110,7 @@ func (s *dictTypeService) Create(req *model.SysDictTypeAddReq) error {
 		return err
 	}
 	SetCreatedInfo(data, s.GetCxtUserId(), s.GetCxtUserName())
-	_, err := dao.SysDictType.Insert(data)
+	_, err := s.Dao.Insert(data)
 	if err != nil {
 		g.Log().Debug(err)
 		err = gerror.New("保存到数据库失败")
@@ -120,7 +120,7 @@ func (s *dictTypeService) Create(req *model.SysDictTypeAddReq) error {
 
 func (s *dictTypeService) UpdateById(req *model.SysDictTypeEditReq) error {
 	err := s.Dao.Transaction(s.Dao.GetCtx(), func(ctx context.Context, tx *gdb.TX) error {
-		dt, err := dao.SysDictType.Fields(dao.SysDictType.Columns.DictType).FindOne(req.Id)
+		dt, err := s.Dao.Fields(dao.SysDictType.Columns.DictType).FindOne(req.Id)
 		if err != nil {
 			return err
 		}
@@ -129,14 +129,14 @@ func (s *dictTypeService) UpdateById(req *model.SysDictTypeEditReq) error {
 		if err := gconv.Struct(req, data); err != nil {
 			return err
 		}
-		SetUpdatedInfo(data, s.GetCxtUserId(), s.GetCxtUserName())
+		SetCurrentUpdatedInfo(data, s.CxtUser)
 		updateFieldEx := append(CommonUpdateFieldEx, dao.SysDictData.Columns.DictCode)
-		_, err = dao.SysDictType.TX(tx).FieldsEx(updateFieldEx...).WherePri(req.Id).Update(req)
+		_, err = s.Dao.TX(tx).FieldsEx(updateFieldEx...).WherePri(req.Id).Update(req)
 		if err != nil {
 			return err
 		}
 		//修改字段数据的类型
-		_, err = dao.SysDictData.TX(tx).Data(g.Map{dao.SysDictData.Columns.DictType: req.DictType}).
+		_, err = tx.Model("sys_dict_data").Data(g.Map{dao.SysDictData.Columns.DictType: req.DictType}).
 			Where(dao.SysDictData.Columns.DictType, dt.DictType).Update()
 		return err
 	})
@@ -149,8 +149,7 @@ func (s *dictTypeService) UpdateById(req *model.SysDictTypeEditReq) error {
 
 func (s *dictTypeService) Delete(dictIds []int64) (err error) {
 	discs := ([]*model.SysDictType)(nil)
-	discs, err = dao.SysDictType.Fields(dao.SysDictType.Columns.DictType).
-		Where(dao.SysDictType.Columns.Id+" in (?) ", dictIds).All()
+	discs, err = s.Dao.Fields(s.Dao.Columns.DictType).Where(s.Dao.Columns.Id+" in (?) ", dictIds).All()
 	if err != nil {
 		g.Log().Error(err)
 		err = gerror.New("没有要删除的数据")
@@ -161,14 +160,14 @@ func (s *dictTypeService) Delete(dictIds []int64) (err error) {
 		types.Append(dt.DictType)
 	}
 	if types.Len() > 0 {
-		err = g.DB().Transaction(s.Dao.GetCtx(), func(ctx context.Context, tx *gdb.TX) error {
-			_, err = dao.SysDictType.TX(tx).Delete(dao.SysDictType.Columns.Id+" in (?) ", dictIds)
+		err = s.Dao.Transaction(s.Dao.GetCtx(), func(ctx context.Context, tx *gdb.TX) error {
+			_, err = s.Dao.TX(tx).Delete(s.Dao.Columns.Id+" in (?) ", dictIds)
 			if err != nil {
 				g.Log().Error(err)
 				err = gerror.New("删除类型失败")
 				return err
 			}
-			_, err = dao.SysDictData.TX(tx).Delete(dao.SysDictData.Columns.DictType+" in (?) ", types.Slice())
+			_, err = tx.Model("sys_dict_data").Delete(dao.SysDictData.Columns.DictType+" in (?) ", types.Slice())
 			if err != nil {
 				g.Log().Error(err)
 				err = gerror.New("删除字典数据失败")

+ 84 - 0
opms_admin/app/service/sys_group.go

@@ -0,0 +1,84 @@
+package service
+
+import (
+	"context"
+	"dashoo.cn/micro/app/dao"
+	"dashoo.cn/micro/app/model"
+	"github.com/gogf/gf/errors/gerror"
+	"github.com/gogf/gf/frame/g"
+	"github.com/gogf/gf/util/gconv"
+)
+
+type groupService struct {
+	*contextService
+	Dao *dao.SysGroupDao
+}
+
+func NewGroupService(ctx context.Context) (svc *groupService, err error) {
+	svc = new(groupService)
+	if svc.contextService, err = svc.Init(ctx); err != nil {
+		return nil, err
+	}
+	svc.Dao = dao.NewSysGroupDao(svc.Tenant)
+	svc.Table = svc.Dao.Table
+	return svc, nil
+}
+
+func (s *groupService) GetList(req *model.SysGroupSearchParams) (total int, list []*model.SysGroup, err error) {
+	db := s.Dao.M
+	if req != nil {
+		if req.GroupCode != "" {
+			db = db.WhereLike(s.Dao.Columns.GroupCode, req.GroupCode)
+		}
+		if req.GroupName != "" {
+			db = db.WhereLike(s.Dao.Columns.GroupName, req.GroupName)
+		}
+		if req.Status != "" {
+			db = db.Where(s.Dao.Columns.Status, req.Status)
+		}
+	}
+
+	total, err = db.Count()
+
+	if err != nil {
+		g.Log().Error(err)
+		err = gerror.New("获取总行数失败")
+	}
+
+	err = db.Page(req.GetPage()).Order("sort asc,id asc").Scan(&list)
+	if err != nil {
+		g.Log().Error(err)
+		err = gerror.New("获取数据失败")
+	}
+	return
+}
+
+func (s *groupService) GetEntity(id int64) (group *model.SysGroup, err error) {
+	err = s.Dao.WherePri(id).Scan(&group)
+	return
+}
+
+func (s *groupService) Create(params *model.SysGroupReq) error {
+	data := new(model.SysGroup)
+	if err := gconv.Struct(params, data); err != nil {
+		return err
+	}
+	SetCreatedInfo(data, s.GetCxtUserId(), s.GetCxtUserName())
+	_, err := s.Dao.Insert(data)
+	return err
+}
+
+func (s *groupService) UpdateById(params *model.UpdateSysGroupReq) (err error) {
+	data := new(model.SysGroup)
+	if err := gconv.Struct(params, data); err != nil {
+		return err
+	}
+	SetUpdatedInfo(data, s.GetCxtUserId(), s.GetCxtUserName())
+	_, err = s.Dao.FieldsEx(UpdateFieldEx...).WherePri(params.Id).Update(data)
+	return err
+}
+
+func (s *groupService) DeleteByIds(ids []int64) error {
+	_, err := s.Dao.WhereIn(s.Dao.Columns.Id, ids).Delete()
+	return err
+}

+ 4 - 4
opms_admin/app/service/sys_menu.go

@@ -26,6 +26,7 @@ func NewMenuService(ctx context.Context) (svc *menuService, err error) {
 		return nil, err
 	}
 	svc.Dao = dao.NewSysMenuDao(svc.Tenant)
+	svc.Table = svc.Dao.Table
 	return svc, nil
 }
 
@@ -36,7 +37,7 @@ func (s menuService) Create(param *model.SysMenuReq) (id int64, err error) {
 		return -1, errors.New("权限标识不能为空!")
 	}
 	if param.Perms != "" {
-		count, err := s.Dao.M.Count("Perms", param.Perms)
+		count, err := s.Dao.Count("Perms", param.Perms)
 		if err != nil {
 			return -1, err
 		}
@@ -58,7 +59,7 @@ func (s menuService) Create(param *model.SysMenuReq) (id int64, err error) {
 	//	return 0, err
 	//}
 	SetCreatedInfo(entity, s.GetCxtUserId(), s.GetCxtUserName())
-	if result, err := s.Dao.M.Insert(entity); err != nil {
+	if result, err := s.Dao.Insert(entity); err != nil {
 		return -1, err
 	} else {
 		id, err := result.LastInsertId()
@@ -194,13 +195,12 @@ func (s menuService) GetList(param *menu_def.SelectReq) ([]model.SysMenu, error)
 
 // GetMenuTree 获取菜单树
 func (s menuService) GetMenuTree(isAll bool) ([]model.MenuTree, error) {
-	db := s.Dao.M
 	menuType := g.Slice{"M", "C"}
 	if isAll {
 		menuType = g.Slice{"M", "C", "F"}
 	}
 	menuList := make([]model.SysMenu, 0)
-	err := db.Where("status = 10").Where("menu_type IN (?)", menuType).Order("sort").Scan(&menuList)
+	err := s.Dao.Where("status = 10").Where("menu_type IN (?)", menuType).Order("sort").Scan(&menuList)
 
 	treeMap := make(map[int][]model.MenuTree, 0)
 	for _, v := range menuList {

+ 25 - 16
opms_admin/app/service/sys_post.go

@@ -6,6 +6,7 @@ import (
 	"dashoo.cn/micro/app/model"
 	"github.com/gogf/gf/errors/gerror"
 	"github.com/gogf/gf/frame/g"
+	"github.com/gogf/gf/util/gconv"
 )
 
 type postService struct {
@@ -19,22 +20,21 @@ func NewPostService(ctx context.Context) (svc *postService, err error) {
 		return nil, err
 	}
 	svc.Dao = dao.NewSysPostDao(svc.Tenant)
+	svc.Table = svc.Dao.Table
 	return svc, nil
 }
 
-func (s *postService) GetList(req *model.SysPostSearchParams) (total, page int, list []*model.SysPost, err error) {
-	db := dao.SysPost.M
+func (s *postService) GetList(req *model.SysPostSearchParams) (total int, list []*model.SysPost, err error) {
+	db := s.Dao.M
 	if req != nil {
 		if req.PostCode != "" {
-			db.Where("post_code like ?", "%"+req.PostCode+"%")
+			db = db.WhereLike(s.Dao.Columns.PostCode, req.PostCode)
 		}
-
 		if req.PostName != "" {
-			db.Where("post_name like ?", "%"+req.PostName+"%")
+			db = db.WhereLike(s.Dao.Columns.PostName, req.PostName)
 		}
-
 		if req.Status != "" {
-			db.Where("status", req.Status)
+			db = db.Where(s.Dao.Columns.Status, req.Status)
 		}
 	}
 
@@ -45,7 +45,7 @@ func (s *postService) GetList(req *model.SysPostSearchParams) (total, page int,
 		err = gerror.New("获取总行数失败")
 	}
 
-	err = db.Page(req.GetPage()).Order("post_sort asc,post_id asc").Scan(&list)
+	err = db.Page(req.GetPage()).Order(s.Dao.Columns.Sort + " asc," + s.Dao.Columns.Id + " asc").Scan(&list)
 	if err != nil {
 		g.Log().Error(err)
 		err = gerror.New("获取数据失败")
@@ -54,22 +54,31 @@ func (s *postService) GetList(req *model.SysPostSearchParams) (total, page int,
 }
 
 func (s *postService) GetEntity(id int64) (post *model.SysPost, err error) {
-	err = dao.SysPost.WherePri(id).Scan(&post)
+	err = s.Dao.WherePri(id).Scan(&post)
 	return
 }
 
-func (s *postService) Create(params *model.SysPostAddParams) error {
-	_, err := dao.SysPost.Insert(params)
+func (s *postService) Create(params *model.SysPostReq) error {
+	data := new(model.SysPost)
+	if err := gconv.Struct(params, data); err != nil {
+		return err
+	}
+	SetCreatedInfo(data, s.GetCxtUserId(), s.GetCxtUserName())
+	_, err := s.Dao.Insert(data)
 	return err
 }
 
-func (s *postService) UpdateById(params *model.SysPostEditParams) (err error) {
-	_, err = dao.SysPost.FieldsEx(dao.SysPost.Columns.Id, dao.SysPost.Columns.CreatedBy).
-		WherePri(params.PostId).Update(params)
+func (s *postService) UpdateById(params *model.UpdateSysPostReq) (err error) {
+	data := new(model.SysPost)
+	if err := gconv.Struct(params, data); err != nil {
+		return err
+	}
+	SetUpdatedInfo(data, s.GetCxtUserId(), s.GetCxtUserName())
+	_, err = s.Dao.FieldsEx(UpdateFieldEx...).WherePri(params.Id).Update(data)
 	return err
 }
 
-func (s *postService) DeleteByIds(ids []int) error {
-	_, err := dao.SysPost.Where(dao.SysPost.Columns.Id+" in(?)", ids).Delete()
+func (s *postService) DeleteByIds(ids []int64) error {
+	_, err := s.Dao.WhereIn(s.Dao.Columns.Id, ids).Delete()
 	return err
 }

+ 105 - 195
opms_admin/app/service/sys_role.go

@@ -7,31 +7,33 @@ import (
 	"dashoo.cn/micro/app/dao"
 	"dashoo.cn/micro/app/model"
 	"dashoo.cn/opms_libary/utils"
-	"database/sql"
-	"fmt"
 	"github.com/gogf/gf/database/gdb"
 	"github.com/gogf/gf/errors/gerror"
 	"github.com/gogf/gf/frame/g"
 	"github.com/gogf/gf/util/gconv"
-	"github.com/gogf/gf/util/gvalid"
 )
 
-type RoleService struct {
+type roleService struct {
 	*contextService
-	Dao *dao.SysRoleDao
+	Dao         *dao.SysRoleDao
+	roleMenuDao *dao.SysRoleMenuDao
+	roleDeptDao *dao.SysRoleDeptDao
 }
 
-func NewRoleService(ctx context.Context) (svc *RoleService, err error) {
-	svc = new(RoleService)
+func NewRoleService(ctx context.Context) (svc *roleService, err error) {
+	svc = new(roleService)
 	if svc.contextService, err = svc.Init(ctx); err != nil {
 		return nil, err
 	}
 	svc.Dao = dao.NewSysRoleDao(svc.Tenant)
+	svc.Table = svc.Dao.Table
+	svc.roleMenuDao = dao.NewSysRoleMenuDao(svc.Tenant)
+	svc.roleDeptDao = dao.NewSysRoleDeptDao(svc.Tenant)
 	return svc, nil
 }
 
 // GetRoleList 获取角色列表
-func (s *RoleService) GetRoleList() (list []*model.SysRole, err error) {
+func (s *roleService) GetRoleList() (list []*model.SysRole, err error) {
 	cache := service.Cache.New()
 	//从缓存获取
 	iList := cache.Get(global.SysRole)
@@ -40,7 +42,7 @@ func (s *RoleService) GetRoleList() (list []*model.SysRole, err error) {
 		return
 	}
 	//从数据库获取
-	list, err = dao.SysRole.Order(dao.SysRole.Columns.Sort + " asc," + dao.SysRole.Columns.Id + " asc").All()
+	list, err = s.Dao.Order(s.Dao.Columns.Sort + " asc," + s.Dao.Columns.Id + " asc").All()
 	if err != nil {
 		g.Log().Error(err)
 		err = gerror.New("获取角色数据失败")
@@ -51,7 +53,7 @@ func (s *RoleService) GetRoleList() (list []*model.SysRole, err error) {
 	return
 }
 
-func (s *RoleService) GetRoleListSearch(req *model.SelectPageReq) (total int, list []*model.SysRole, err error) {
+func (s *roleService) GetRoleListSearch(req *model.SelectPageReq) (total int, list []*model.SysRole, err error) {
 	db := dao.SysRole.M
 	if req.RoleName != "" {
 		db = db.Where("role_name like ?", "%"+req.RoleName+"%")
@@ -80,90 +82,58 @@ func (s *RoleService) GetRoleListSearch(req *model.SelectPageReq) (total int, li
 	return
 }
 
-// 插入角色
-func (s *RoleService) CreateRolePost(req *model.SysRoleReq) error {
-	tx, err := g.DB("default").Begin() //开启事务
-
-	if err != nil {
-		return err
+func (s *roleService) GetRoleById(id int64) (roleInfo *model.UpdateSysRoleReq, err error) {
+	roleInfo = new(model.UpdateSysRoleReq)
+	role := new(model.SysRole)
+	err = s.Dao.WherePri(id).Scan(&role)
+	if err := gconv.Struct(role, roleInfo); err != nil {
+		return nil, err
 	}
-	//插入角色
-	insertId, err := s.CreateRole(tx, req)
+	var menuList []model.SysRoleMenu
+	err = s.roleMenuDao.Where("role_id", id).Scan(&menuList)
 	if err != nil {
-		tx.Rollback() //回滚
-		return err
+		return nil, err
 	}
-	//添加角色权限
-	fmt.Println(insertId)
-	//err = s.CreateRoleRule(m["menuIds"], insertId)
-
-	if err != nil {
-		tx.Rollback() //回滚
-		g.Log().Error(err.Error())
-		return err
+	roleInfo.MenuIds = []int{}
+	for _, v := range menuList {
+		roleInfo.MenuIds = append(roleInfo.MenuIds, v.MenuId)
 	}
-
-	tx.Commit()
-	//清除TAG缓存
-	service.Cache.New().RemoveByTag(global.SysAuthTag)
-	return nil
+	return
 }
 
-func (s *RoleService) CreateRole(tx *gdb.TX, req *model.SysRoleReq) (InsId int64, err error) {
-	data := new(model.SysRole)
-	if err = gconv.Struct(req, data); err != nil {
-		return
+func (s *roleService) GetRoleDeptTreeselect(id int64) (deptIds []int, err error) {
+	count, err := s.Dao.WherePri(id).Count()
+	if err != nil || count == 0 {
+		return nil, gerror.New("角色不存在")
 	}
-	SetCreatedInfo(data, s.GetCxtUserId(), s.GetCxtUserName())
-	var res sql.Result
-	res, err = tx.Model(model.SysRole{}).Data(data).Save()
+	roleDeptList, err := s.roleDeptDao.Where("role_id", id).FindAll()
 	if err != nil {
-		return
+		return nil, err
 	}
-	InsId, _ = res.LastInsertId()
-	return
-}
-
-// AddRoleRule 添加角色权限
-func (s *RoleService) CreateRoleRule(iRule interface{}, roleId int64) (err error) {
-	enforcer, e := service.Casbin.GetEnforcer()
-	if e != nil {
-		err = e
-		return
-	}
-	rule := gconv.Strings(iRule)
-	for _, v := range rule {
-		_, err = enforcer.AddPolicy(fmt.Sprintf("%d", roleId), fmt.Sprintf("%s", v), "All")
-		if err != nil {
-			break
-		}
+	deptIds = make([]int, len(roleDeptList))
+	for _, v := range roleDeptList {
+		deptIds = append(deptIds, v.DeptId)
 	}
 	return
 }
 
-// 修改角色信息
-func (s *RoleService) UpdateRolePost(req *model.SysRoleReq) error {
-	tx, err := g.DB("default").Begin() //开启事务
-	if err != nil {
-		return err
-	}
-	err = s.UpdateRole(tx, req)
-	if err != nil {
-		tx.Rollback()
-		return err
-	}
-	//err = s.UpdateRoleRule(m["menuIds"], id)
-	if err != nil {
-		tx.Rollback() //回滚
+func (s *roleService) CreateRole(req *model.SysRoleReq) error {
+	data := new(model.SysRole)
+	if err := gconv.Struct(req, data); err != nil {
 		return err
 	}
-	tx.Commit()
-	//清除TAG缓存
-	service.Cache.New().RemoveByTag(global.SysAuthTag)
-	return nil
+	SetCreatedInfo(data, s.GetCxtUserId(), s.GetCxtUserName())
+	err := s.Dao.Transaction(context.TODO(), func(ctx context.Context, tx *gdb.TX) error {
+		roleId, err := s.Dao.TX(tx).Data(data).InsertAndGetId()
+		if err != nil {
+			return err
+		}
+		return s.createRoleMenu(tx, roleId, req.MenuIds)
+	})
+	return err
 }
 
-func (s *RoleService) UpdateRole(tx *gdb.TX, req *model.SysRoleReq) error {
+func (s *roleService) UpdateRole(req *model.UpdateSysRoleReq) error {
 	//保存角色信息
 	roleMap := gdb.Map{
 		"id":        req.Id,
@@ -174,92 +144,57 @@ func (s *RoleService) UpdateRole(tx *gdb.TX, req *model.SysRoleReq) error {
 		"remark":    req.Remark,
 	}
 	SetUpdatedInfo(roleMap, s.GetCxtUserId(), s.GetCxtUserName())
-	_, err := tx.Model(model.SysRole{}).Data(roleMap).WherePri(req.Id).Update()
-	if err != nil {
-		return err
-	}
-	return nil
-}
-
-// 修改角色的授权规则
-func (s *RoleService) UpdateRoleRule(iRule interface{}, roleId int64) (err error) {
-	enforcer, e := service.Casbin.GetEnforcer()
-	if e != nil {
-		return e
-	}
-
-	//删除旧权限
-	_, err = enforcer.RemoveFilteredPolicy(0, fmt.Sprintf("%d", roleId))
-	if err != nil {
-		return
-	}
-	// 添加新权限
-	rule := gconv.Strings(iRule)
-	for _, v := range rule {
-		_, err = enforcer.AddPolicy(fmt.Sprintf("%d", roleId), fmt.Sprintf("%s", v), "All")
+	err := s.Dao.Transaction(context.TODO(), func(ctx context.Context, tx *gdb.TX) error {
+		_, err := tx.Model(model.SysRole{}).Data(roleMap).WherePri(req.Id).Update()
 		if err != nil {
-			break
+			return err
 		}
-	}
-
-	return
-
+		_, err = s.roleMenuDao.TX(tx).Where(dao.SysRoleMenu.Columns.RoleId, req.Id).Delete()
+		if err != nil {
+			return err
+		}
+		return s.createRoleMenu(tx, int64(req.Id), req.MenuIds)
+	})
+	return err
 }
 
-func (s *RoleService) DeleteByIds(ids []int64) (err error) {
-	tx, err := g.DB("default").Begin() //开启事务
-	if err != nil {
-		g.Log().Error(err)
-		err = gerror.New("事务处理失败")
-		return
+// 角色关联菜单
+func (s *roleService) createRoleMenu(tx *gdb.TX, roleId int64, menuIds []int) error {
+	list := g.Slice{}
+	for _, v := range menuIds {
+		list = append(list, g.Map{
+			dao.SysRoleMenu.Columns.RoleId: roleId,
+			dao.SysRoleMenu.Columns.MenuId: v,
+		})
 	}
-
-	_, err = tx.Model(model.SysRole{}).Where("id in(?)", ids).Delete()
+	_, err := s.roleMenuDao.TX(tx).Insert(list)
 	if err != nil {
-		g.Log().Error(err)
-		tx.Rollback()
-		err = gerror.New("删除失败")
-		return
+		return err
 	}
-	//删除角色的权限和管理的部门数据权限
-	//enforcer, e := service.Casbin.GetEnforcer()
-	//if e != nil {
-	//	tx.Rollback()
-	//	return e
-	//}
-	//for _, v := range ids {
-	//	_, err = enforcer.RemoveFilteredPolicy(0, fmt.Sprintf("%d", v))
-	//	if err != nil {
-	//		tx.Rollback()
-	//		return err
-	//	}
-	//	_, err = tx.Model(model.SysRoleDept{}).Delete("role_id", v)
-	//	if err != nil {
-	//		tx.Rollback()
-	//		return err
-	//	}
-	//}
-	tx.Commit()
-	//清除TAG缓存
-	service.Cache.New().RemoveByTag(global.SysAuthTag)
 	return nil
 }
 
-func (s *RoleService) checkRoleData(params map[string]interface{}) error {
-	rules := []string{
-		"roleName@required|length:1,20#请填写角色名称|名称应在:min到:max个字符之间",
-	}
+func (s *roleService) DeleteByIds(ids []int64) (err error) {
+	err = s.Dao.Transaction(context.TODO(), func(ctx context.Context, tx *gdb.TX) error {
+		_, err = s.Dao.TX(tx).Where("id in(?)", ids).Delete()
+		if err != nil {
+			return err
+		}
+		// 删除角色菜单权限
+		_, err = s.roleMenuDao.TX(tx).WhereIn(dao.SysRoleMenu.Columns.RoleId, ids).Delete()
+		if err != nil {
+			return err
+		}
+		// 删除角色数据权限
+		_, err = s.roleDeptDao.TX(tx).WhereIn(dao.SysRoleMenu.Columns.RoleId, ids).Delete()
+		return err
+	})
 
-	e := gvalid.CheckMap(nil, params, rules)
-	if e != nil {
-		return e
-	}
-	return nil
+	return err
 }
 
-func (s *RoleService) StatusSetRole(req *model.StatusSetReq) error {
-	_, err := dao.SysRole.Where(dao.SysRole.Columns.Id, req.RoleId).Data(dao.SysRole.Columns.Status, req.Status).
-		Update()
+func (s *roleService) UpdateRoleStatus(req *model.StatusSetReq) error {
+	_, err := s.Dao.Where(s.Dao.Columns.Id, req.RoleId).Data(s.Dao.Columns.Status, req.Status).Update()
 	if err == nil {
 		//清除TAG缓存
 		service.Cache.New().RemoveByTag(global.SysAuthTag)
@@ -268,52 +203,27 @@ func (s *RoleService) StatusSetRole(req *model.StatusSetReq) error {
 }
 
 // 设置角色数据权限
-func (s *RoleService) RoleDataScope(req *model.DataScopeReq) error {
-	tx, err := g.DB().Begin()
-	if err != nil {
-		g.Log().Error(err)
-		return gerror.New("设置失败")
-	}
-	_, err = tx.Model(model.SysRole{}).Where("id", req.RoleId).Data(g.Map{"data_scope": req.DataScope}).Update()
-	if err != nil {
-		g.Log().Error(err)
-		tx.Rollback()
-		return gerror.New("设置失败")
-	}
-	if req.DataScope == 2 {
-		_, err := tx.Model(model.SysRoleDept{}).Where("role_id", req.RoleId).Delete()
+func (s *roleService) UpdateRoleDataScope(req *model.DataScopeReq) error {
+	err := s.Dao.Transaction(context.TODO(), func(ctx context.Context, tx *gdb.TX) error {
+		_, err := s.Dao.TX(tx).Where("id", req.RoleId).Data(g.Map{"data_scope": req.DataScope}).Update()
 		if err != nil {
-			g.Log().Error(err)
-			tx.Rollback()
-			return gerror.New("设置失败")
+			return err
 		}
-		data := g.List{}
-		for _, deptId := range req.DeptIds {
-			data = append(data, g.Map{"role_id": req.RoleId, "dept_id": deptId})
-		}
-		_, err = tx.Model(model.SysRoleDept{}).Data(data).Insert()
-		if err != nil {
-			g.Log().Error(err)
-			tx.Rollback()
-			return gerror.New("设置失败")
+		if req.DataScope == 2 {
+			_, err := s.roleDeptDao.Where(s.roleDeptDao.Columns.RoleId, req.RoleId).Delete()
+			if err != nil {
+				return err
+			}
+			data := g.List{}
+			for _, deptId := range req.DeptIds {
+				data = append(data, g.Map{"role_id": req.RoleId, "dept_id": deptId})
+			}
+			_, err = s.roleDeptDao.Data(data).Insert()
+			if err != nil {
+				return err
+			}
 		}
-	}
-	tx.Commit()
-	return nil
-}
-
-// 获取角色关联的菜单规则
-func (s *RoleService) GetFilteredNamedPolicy(id int) ([]int, error) {
-	enforcer, err := service.Casbin.GetEnforcer()
-	if err != nil {
-		g.Log().Error(err)
-		return nil, err
-	}
-	gp := enforcer.GetFilteredNamedPolicy("p", 0, fmt.Sprintf("%d", id))
-	gpSlice := make([]int, len(gp))
-	for k, v := range gp {
-		gpSlice[k] = gconv.Int(v[1])
-	}
-
-	return gpSlice, nil
+		return nil
+	})
+	return err
 }

+ 164 - 283
opms_admin/app/service/sys_user.go

@@ -2,13 +2,11 @@ package service
 
 import (
 	"context"
-	"dashoo.cn/micro/app/common/service"
 	"dashoo.cn/micro/app/dao"
 	"dashoo.cn/micro/app/model"
 	"dashoo.cn/opms_libary/request"
 	"dashoo.cn/opms_libary/utils"
 	"errors"
-	"fmt"
 	"github.com/gogf/gf/container/gset"
 	"github.com/gogf/gf/database/gdb"
 	"github.com/gogf/gf/errors/gerror"
@@ -19,7 +17,10 @@ import (
 
 type userService struct {
 	*contextService
-	Dao *dao.SysUserDao
+	Dao          *dao.SysUserDao
+	userRoleDao  *dao.SysUserRoleDao
+	userPostDao  *dao.SysUserPostDao
+	userGroupDao *dao.SysUserGroupDao
 }
 
 func NewUserService(ctx context.Context) (svc *userService, err error) {
@@ -28,6 +29,10 @@ func NewUserService(ctx context.Context) (svc *userService, err error) {
 		return nil, err
 	}
 	svc.Dao = dao.NewSysUserDao(svc.Tenant)
+	svc.Table = svc.Dao.Table
+	//svc.userRoleDao = dao.NewSysUserRoleDao(svc.Tenant)
+	//svc.userPostDao = dao.NewSysUserPostDao(svc.Tenant)
+	//svc.userGroupDao = dao.NewSysUserGroupDao(svc.Tenant)
 	return svc, nil
 }
 
@@ -66,40 +71,40 @@ func (s *userService) Login(username, password string) (*request.UserInfo, error
 }
 
 func (s *userService) GetUserList(req *model.SysUserSearchReq) (total int, userList []*model.SysUser, err error) {
-	userModel := dao.SysUser.M
+	userModel := s.Dao.M
 	if req.KeyWords != "" {
 		keyWords := "%" + req.KeyWords + "%"
-		userModel = userModel.Where("user_name like ? or  nick_name like ?", keyWords, keyWords)
+		userModel = userModel.Where("sys_user.user_name like ? or  sys_user.nick_name like ?", keyWords, keyWords)
 	}
 	if req.DeptId != 0 {
-		userModel = userModel.Where("dept_id", req.DeptId)
+		userModel = userModel.Where("sys_user.dept_id", req.DeptId)
 	}
 	if len(req.DeptIds) != 0 {
-		userModel = userModel.Where("dept_id in (?)", req.DeptIds)
+		userModel = userModel.WhereIn("sys_user.dept_id", req.DeptIds)
 	}
 	if req.Status != "" {
-		userModel = userModel.Where("status", gconv.Int(req.Status))
+		userModel = userModel.Where("sys_user.status", gconv.Int(req.Status))
 	}
 	if req.Phone != "" {
-		userModel = userModel.Where("phone like ?", "%"+req.Phone+"%")
+		userModel = userModel.WhereLike("sys_user.phone", "%"+req.Phone+"%")
 	}
 	if req.BeginTime != "" {
-		userModel = userModel.Where("created_at >=?", req.BeginTime)
+		userModel = userModel.WhereGTE("sys_user.created_time", req.BeginTime)
 	}
 	if req.EndTime != "" {
-		userModel = userModel.Where("created_at <=?", req.EndTime)
+		userModel = userModel.WhereLTE("sys_user.created_time", req.EndTime)
 	}
+	if userModel, err = s.SetDataScopeWhere(userModel); err != nil {
+		return 0, nil, err
+	}
+
 	total, err = userModel.Count()
 	if err != nil {
 		g.Log().Error(err)
 		err = gerror.New("获取总行数失败")
 		return
 	}
-	if req.PageNum == 0 {
-		req.PageNum = 1
-	}
-	err = userModel.FieldsEx(dao.SysUser.Columns.Password, dao.SysUser.Columns.UserSalt).
-		Page(req.PageNum, req.PageSize).Order("id asc").Scan(&userList)
+	err = userModel.Fields("sys_user.*").Page(req.PageNum, req.PageSize).Order("id asc").Scan(&userList)
 	return
 }
 
@@ -183,73 +188,6 @@ func (s *userService) LoginLog(params *model.LoginLogParams) {
 //	dao.SysUserOnline.SaveOnline(params)
 //}
 
-// GetAdminRole 获取用户角色
-func (s *userService) GetAdminRole(userId int, allRoleList []*model.SysRole) (roles []*model.SysRole, err error) {
-	var roleIds []uint
-	roleIds, err = s.GetAdminRoleIds(userId)
-	if err != nil {
-		return
-	}
-	roles = make([]*model.SysRole, 0, len(allRoleList))
-	for _, v := range allRoleList {
-		for _, id := range roleIds {
-			if int(id) == v.Id {
-				roles = append(roles, v)
-			}
-		}
-		if len(roles) == len(roleIds) {
-			break
-		}
-	}
-	return
-}
-
-// GetAdminRoleIds 获取用户角色ids
-func (s *userService) GetAdminRoleIds(userId int) (roleIds []uint, err error) {
-	enforcer, e := service.Casbin.GetEnforcer()
-	if e != nil {
-		err = e
-		return
-	}
-	//查询关联角色规则
-	groupPolicy := enforcer.GetFilteredGroupingPolicy(0, gconv.String(userId))
-	if len(groupPolicy) > 0 {
-		roleIds = make([]uint, len(groupPolicy))
-		//得到角色id的切片
-		for k, v := range groupPolicy {
-			roleIds[k] = gconv.Uint(v[1])
-		}
-	}
-	return
-}
-
-// AddUserPost 添加用户岗位信息
-func (s *userService) AddUserPost(postIds []int, userId int64, tx *gdb.TX) (err error) {
-	//删除旧岗位信息
-	_, err = dao.SysUserPost.TX(tx).Where(dao.SysUserPost.Columns.UserId, userId).Delete()
-	if err != nil {
-		g.Log().Error(err)
-		return
-	}
-	if len(postIds) == 0 {
-		return
-	}
-	//添加用户岗位信息
-	data := g.List{}
-	for _, v := range postIds {
-		data = append(data, g.Map{
-			dao.SysUserPost.Columns.UserId: userId,
-			dao.SysUserPost.Columns.PostId: v,
-		})
-	}
-	_, err = dao.SysUserPost.TX(tx).Data(data).Insert()
-	if err != nil {
-		g.Log().Error(err)
-		return
-	}
-	return
-}
-
 // GetUserInfoById 通过Id获取用户信息
 func (s *userService) GetUserInfoById(id int, withPwd ...bool) (user *model.SysUser, err error) {
 	if len(withPwd) > 0 && withPwd[0] {
@@ -267,89 +205,72 @@ func (s *userService) GetUserInfoById(id int, withPwd ...bool) (user *model.SysU
 	return
 }
 
-// GetEditUser 获取要修改的用户信息
-func (s *userService) GetEditUser(id int) (g.Map, error) {
-	userData, err := s.GetUserInfoById(id)
-	//获取角色信息
-	//roleList, err := SysRole.GetRoleList()
-	if err != nil {
-		g.Log().Error(err)
-		return nil, errors.New("获取角色数据失败")
-	}
-	//获取已选择的角色信息
-	checkedRoleIds, err := s.GetAdminRoleIds(id)
+// GetUserRoleIds 获取用户角色
+func (s *userService) GetUserRoleIds(userId int) (roleIds []int, err error) {
+	s.userRoleDao = dao.NewSysUserRoleDao(s.Tenant)
+	list, err := s.userRoleDao.Where(dao.SysUserRole.Columns.UserId, userId).All()
 	if err != nil {
 		g.Log().Error(err)
-		return nil, errors.New("获取用户角色数据失败")
-	}
-	if checkedRoleIds == nil {
-		checkedRoleIds = []uint{}
-	}
-	//获取岗位信息
-	posts, err := s.GetUsedPost()
-	if err != nil {
-		return nil, err
-	}
-	checkedPosts, err := s.GetUserPostIds(id)
-	if err != nil {
-		return nil, err
-	}
-
-	if checkedPosts == nil {
-		checkedPosts = []int{}
+		return nil, gerror.New("获取用户岗位信息失败")
 	}
-
-	res := g.Map{
-		//"roleList":       roleList,
-		"userInfo":       userData,
-		"checkedRoleIds": checkedRoleIds,
-		"posts":          posts,
-		"checkedPosts":   checkedPosts,
+	roleIds = make([]int, 0)
+	for _, entity := range list {
+		roleIds = append(roleIds, entity.RoleId)
 	}
-
-	return res, nil
+	return
 }
 
-// GetUsedPost 获取正常状态的岗位
-func (s *userService) GetUsedPost() (list []*model.SysPost, err error) {
-	err = dao.SysPost.Where(dao.SysPost.Columns.Status, 1).
-		Order(dao.SysPost.Columns.Sort + " ASC, " + dao.SysPost.Columns.Id + " ASC ").Scan(&list)
+// GetUserPostIds 获取用户岗位
+func (s *userService) GetUserPostIds(userId int) (postIds []int, err error) {
+	s.userPostDao = dao.NewSysUserPostDao(s.Tenant)
+	list, err := s.userPostDao.Where(dao.SysUserPost.Columns.UserId, userId).All()
 	if err != nil {
 		g.Log().Error(err)
-		err = gerror.New("获取岗位数据失败")
+		return nil, gerror.New("获取用户岗位信息失败")
+	}
+	postIds = make([]int, 0)
+	for _, entity := range list {
+		postIds = append(postIds, entity.PostId)
 	}
 	return
 }
 
-// GetUserPostIds 获取用户岗位
-func (s *userService) GetUserPostIds(userId int) (postIds []int, err error) {
-	var list []*model.SysUserPost
-	err = dao.SysUserPost.Where(dao.SysUserPost.Columns.UserId, userId).Scan(&list)
+// GetUserGroupIds 获取用户的用户组
+func (s *userService) GetUserGroupIds(userId int) (postIds []int, err error) {
+	s.userGroupDao = dao.NewSysUserGroupDao(s.Tenant)
+	list, err := s.userGroupDao.Where(dao.SysUserGroup.Columns.UserId, userId).All()
 	if err != nil {
 		g.Log().Error(err)
 		return nil, gerror.New("获取用户岗位信息失败")
 	}
 	postIds = make([]int, 0)
 	for _, entity := range list {
-		postIds = append(postIds, int(entity.PostId))
+		postIds = append(postIds, entity.GroupId)
 	}
 	return
 }
 
+// GetRolesByUserId 根据用户id获取岗位信息详情
+func (s *userService) GetRolesByUserId(userId int) ([]*model.SysRole, error) {
+	roleIds, err := s.GetUserRoleIds(userId)
+	if err != nil {
+		return nil, err
+	}
+	roles, err := dao.NewSysRoleDao(s.Tenant).Where(dao.SysRole.Columns.Id+" in (?)", roleIds).All()
+	return roles, err
+}
+
 // GetPostsByUserId 根据用户id获取岗位信息详情
 func (s *userService) GetPostsByUserId(userId int) ([]*model.SysPost, error) {
 	postIds, err := s.GetUserPostIds(userId)
 	if err != nil {
 		return nil, err
 	}
-	var posts []*model.SysPost
-	err = dao.SysPost.Where(dao.SysPost.Columns.Id+" in (?)", postIds).Scan(&posts)
+	posts, err := dao.NewSysPostDao(s.Tenant).Where(dao.SysPost.Columns.Id+" in (?)", postIds).All()
 	return posts, err
 }
 
 func (s *userService) CreateUser(req *model.AddUserReq) (err error) {
-	req.UserSalt = grand.S(10)
-	req.Password = utils.EncryptPassword(req.Password, req.UserSalt)
 	var tx *gdb.TX
 	tx, err = g.DB().Begin()
 	if err != nil {
@@ -368,60 +289,134 @@ func (s *userService) CreateUser(req *model.AddUserReq) (err error) {
 		return
 	}
 	userData := new(model.SysUser)
-	//userData.UserName = req.UserName
-	//userData.DeptId = req.DeptId
-	//userData.Status = req.Status
-	//userData.Phone = req.Phone
-	//userData.Sex = req.Sex
-	//userData.Email = req.Email
-	//userData.NickName = req.NickName
-	//userData.UserSalt = req.UserSalt
-	//userData.Password = req.Password
-	//userData.Remark = req.Remark
-
 	if err = gconv.Struct(req, userData); err != nil {
 		tx.Rollback()
 		return
 	}
+	userData.UserSalt = grand.S(10)
+	userData.Password = utils.EncryptPassword(userData.Password, userData.UserSalt)
 	SetCreatedInfo(userData, s.GetCxtUserId(), s.GetCxtUserName())
 	res, err := Model.Insert(userData)
 	if err != nil {
 		tx.Rollback()
 		return
 	}
-	InsertId, _ := res.LastInsertId()
-	fmt.Println(InsertId)
-	//err = s.AddUserRole(req.RoleIds, InsertId)
-	//if err != nil {
-	//	g.Log().Error(err)
-	//	err = gerror.New("设置用户权限失败")
-	//	tx.Rollback()
-	//	return
-	//}
-	//err = s.AddUserPost(req.PostIds, InsertId, tx)
+	insertId, _ := res.LastInsertId()
+	if err := s.AddUserOtherInfo(req.SetUserReq, insertId, tx); err != nil {
+		return err
+	}
+	tx.Commit()
+	return
+}
+
+// AddUserOtherInfo 重新设置用户相关其他表信息
+func (s *userService) AddUserOtherInfo(req model.SetUserReq, insertId int64, tx *gdb.TX) (err error) {
+	// 设置用户角色信息
+	err = s.AddUserRole(req.RoleIds, insertId, tx)
+	if err != nil {
+		g.Log().Error(err)
+		err = gerror.New("设置用户权限失败")
+		tx.Rollback()
+		return
+	}
+	// 设置用户岗位信息
+	err = s.AddUserPost(req.PostIds, insertId, tx)
 	if err != nil {
 		g.Log().Error(err)
 		err = gerror.New("设置用户岗位信息失败")
 		tx.Rollback()
 		return
 	}
-	tx.Commit()
+	// 设置用户的用户组信息
+	err = s.AddUserGroup(req.GroupIds, insertId, tx)
+	if err != nil {
+		g.Log().Error(err)
+		err = gerror.New("设置用户组信息失败")
+		tx.Rollback()
+		return
+	}
 	return
 }
 
 // AddUserRole 添加用户角色信息
-func (s *userService) AddUserRole(roleIds interface{}, userId int64) (err error) {
-	enforcer, e := service.Casbin.GetEnforcer()
-	if e != nil {
-		err = e
+func (s *userService) AddUserRole(roleIds []int, userId int64, tx *gdb.TX) (err error) {
+	//删除旧用户角色信息
+	_, err = dao.SysUserRole.TX(tx).Where(dao.SysUserPost.Columns.UserId, userId).Delete()
+	if err != nil {
+		g.Log().Error(err)
 		return
 	}
-	rule := gconv.Ints(roleIds)
-	for _, v := range rule {
-		_, err = enforcer.AddGroupingPolicy(fmt.Sprintf("%d", userId), fmt.Sprintf("%d", v))
-		if err != nil {
-			return
-		}
+	if len(roleIds) == 0 {
+		return
+	}
+	//添加用户岗位信息
+	data := g.List{}
+	for _, v := range roleIds {
+		data = append(data, g.Map{
+			dao.SysUserRole.Columns.UserId: userId,
+			dao.SysUserRole.Columns.RoleId: v,
+		})
+	}
+	_, err = dao.SysUserRole.TX(tx).Data(data).Insert()
+	if err != nil {
+		g.Log().Error(err)
+		return
+	}
+	return
+}
+
+// AddUserPost 添加用户岗位信息
+func (s *userService) AddUserPost(postIds []int, userId int64, tx *gdb.TX) (err error) {
+	//删除旧岗位信息
+	_, err = dao.SysUserPost.TX(tx).Where(dao.SysUserPost.Columns.UserId, userId).Delete()
+	if err != nil {
+		g.Log().Error(err)
+		return
+	}
+	if len(postIds) == 0 {
+		return
+	}
+	//添加用户岗位信息
+	data := g.List{}
+	for _, v := range postIds {
+		data = append(data, g.Map{
+			dao.SysUserPost.Columns.UserId: userId,
+			dao.SysUserPost.Columns.PostId: v,
+		})
+	}
+	_, err = dao.SysUserPost.TX(tx).Data(data).Insert()
+	if err != nil {
+		g.Log().Error(err)
+		return
+	}
+	return
+}
+
+// AddUserGroup 添加用户的用户组信息
+func (s *userService) AddUserGroup(groupIds []int, userId int64, tx *gdb.TX) (err error) {
+	//删除旧用户组信息
+	_, err = dao.SysUserGroup.TX(tx).Where(dao.SysUserGroup.Columns.UserId, userId).Delete()
+	if err != nil {
+		g.Log().Error(err)
+		return
+	}
+	if len(groupIds) == 0 {
+		return
+	}
+	//添加用户的用户组信息
+	data := g.List{}
+	for _, v := range groupIds {
+		data = append(data, g.Map{
+			dao.SysUserGroup.Columns.UserId:      userId,
+			dao.SysUserGroup.Columns.GroupId:     v,
+			dao.SysUserGroup.Columns.CreatedBy:   userId,
+			dao.SysUserGroup.Columns.CreatedName: v,
+		})
+	}
+	_, err = dao.SysUserGroup.TX(tx).Data(data).Insert()
+	if err != nil {
+		g.Log().Error(err)
+		return
 	}
 	return
 }
@@ -442,13 +437,6 @@ func (s *userService) UpdateUser(req *model.EditUserReq) (err error) {
 		err = gerror.New("获取用户信息失败")
 		return
 	}
-	//userData.DeptId = req.DeptId
-	//userData.Status = req.Status
-	//userData.Phone = req.Phone
-	//userData.Sex = req.Sex
-	//userData.Email = req.Email
-	//userData.NickName = req.NickName
-	//userData.Remark = req.Remark
 	if err = gconv.Struct(req, userData); err != nil {
 		tx.Rollback()
 		return
@@ -463,42 +451,10 @@ func (s *userService) UpdateUser(req *model.EditUserReq) (err error) {
 		tx.Rollback()
 		return
 	}
-	//设置用户所属角色信息
-	//err = s.EditUserRole(req.RoleIds, req.Id)
-	//if err != nil {
-	//	g.Log().Error(err)
-	//	err = gerror.New("设置用户权限失败")
-	//	tx.Rollback()
-	//	return
-	//}
-	//设置用户岗位数据
-	//err = s.AddUserPost(req.PostIds, int64(req.Id), tx)
-	//if err != nil {
-	//	g.Log().Error(err)
-	//	err = gerror.New("设置用户岗位信息失败")
-	//	tx.Rollback()
-	//	return
-	//}
-	tx.Commit()
-	return
-}
-
-// EditUserRole 修改用户角色信息
-func (s *userService) EditUserRole(roleIds interface{}, userId int) (err error) {
-	enforcer, e := service.Casbin.GetEnforcer()
-	if e != nil {
-		err = e
-		return
-	}
-	rule := gconv.Ints(roleIds)
-	//删除用户旧角色信息
-	enforcer.RemoveFilteredGroupingPolicy(0, fmt.Sprintf("%d", userId))
-	for _, v := range rule {
-		_, err = enforcer.AddGroupingPolicy(fmt.Sprintf("%d", userId), fmt.Sprintf("%d", v))
-		if err != nil {
-			return
-		}
+	if err := s.AddUserOtherInfo(req.SetUserReq, int64(req.Id), tx); err != nil {
+		return err
 	}
+	tx.Commit()
 	return
 }
 
@@ -524,13 +480,6 @@ func (s *userService) ChangeUserStatus(req *model.SysUserStatusReq) error {
 func (s *userService) DeleteUserByIds(ctx context.Context, ids []int64) error {
 	return g.DB().Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
 		_, err := s.Dao.Ctx(ctx).TX(tx).Where(dao.SysUser.Columns.Id+" in(?)", ids).Delete()
-		//删除对应权限
-		enforcer, err := service.Casbin.GetEnforcer()
-		if err == nil {
-			for _, v := range ids {
-				enforcer.RemoveFilteredGroupingPolicy(0, fmt.Sprintf("%d", v))
-			}
-		}
 		//删除用户对应的岗位
 		_, err = dao.SysUserPost.Ctx(ctx).TX(tx).Delete(dao.SysUserPost.Columns.UserId+" in (?)", ids)
 		return err
@@ -570,74 +519,6 @@ func (s *userService) ProfileUpdatePwd(req *model.ProfileUpdatePwdReq) error {
 	return err
 }
 
-// GetDataWhere 获取数据权限判断条件
-//func (s *sysUser) GetDataWhere(userInfo *dao.CtxUser, entity interface{}) (where g.Map, err error) {
-//	whereJustMe := g.Map{} //本人数据权限
-//	t := reflect.TypeOf(entity)
-//	for i := 0; i < t.Elem().NumField(); i++ {
-//		if t.Elem().Field(i).Name == "CreatedBy" {
-//			//若存在用户id的字段,则生成判断数据权限的条件
-//			//1、获取当前用户所属角色
-//			allRoles := ([]*model.SysRole)(nil)
-//			allRoles, err = SysRole.GetRoleList()
-//			if err != nil {
-//				return nil, err
-//			}
-//			roles := ([]*model.SysRole)(nil)
-//			roles, err = s.GetAdminRole(userInfo.Id, allRoles)
-//			if err != nil {
-//				return nil, err
-//			}
-//			//2获取角色对应数据权限
-//			deptIdArr := gset.New()
-//			for _, role := range roles {
-//				switch role.DataScope {
-//				case 1: //全部数据权限
-//					return
-//				case 2: //自定数据权限
-//					var deptIds []int
-//					deptIds, err = Dept.GetRoleDepts(gconv.int(role.Id))
-//					if err != nil {
-//						return
-//					}
-//					deptIdArr.Add(gconv.Interfaces(deptIds)...)
-//				case 3: //本部门数据权限
-//					deptIdArr.Add(gconv.int(userInfo.DeptId))
-//				case 4: //本部门及以下数据权限
-//					deptIdArr.Add(gconv.int(userInfo.DeptId))
-//					//获取正常状态部门数据
-//					depts := ([]*model.SysDept)(nil)
-//					depts, err = Dept.GetList(&dao.SysDeptSearchParams{Status: "1"})
-//					if err != nil {
-//						return
-//					}
-//					var dList g.List
-//					for _, d := range depts {
-//						m := g.Map{
-//							"id":    d.DeptId,
-//							"pid":   d.ParentId,
-//							"label": d.DeptName,
-//						}
-//						dList = append(dList, m)
-//					}
-//					l := library.FindSonByParentId(dList, gconv.Int(userInfo.DeptId), "pid", "id")
-//					for _, li := range l {
-//						deptIdArr.Add(gconv.int(li["id"]))
-//					}
-//				case 5: //仅本人数据权限
-//					whereJustMe = g.Map{"user.id": userInfo.Id}
-//				}
-//			}
-//			if deptIdArr.Size() > 0 {
-//				where = g.Map{"user.dept_id": deptIdArr.Slice()}
-//			} else if len(whereJustMe) > 0 {
-//				where = whereJustMe
-//			}
-//		}
-//	}
-//	return
-//}
-
 // GetUsers 通过用户ids查询多个用户信息
 func (s *userService) GetUsers(ids []int) (users []*model.SysUserRes, err error) {
 	if len(ids) == 0 {

+ 0 - 39
opms_admin/app/service/sys_user_group.go

@@ -1,39 +0,0 @@
-package service
-
-import (
-	"dashoo.cn/micro/app/dao"
-	"dashoo.cn/micro/app/model"
-)
-
-type sysUserGroup struct {
-}
-
-var SysUserGroup = new(sysUserGroup)
-
-func (s *sysUserGroup) GetList(searchParams *model.SysDeptSearchParams) ([]*model.SysUserGroup, error) {
-	sysUserGroupModel := dao.SysUserGroup.M
-	if searchParams.DeptName != "" {
-		sysUserGroupModel = sysUserGroupModel.Where("dept_name like ?", "%"+searchParams.DeptName+"%")
-	}
-	if searchParams.Status != "" {
-		sysUserGroupModel = sysUserGroupModel.Where("status", searchParams.Status)
-	}
-	sysUserGroupList := ([]*model.SysUserGroup)(nil)
-	if err := sysUserGroupModel.Scan(&sysUserGroupList); err != nil {
-		return nil, err
-	}
-	return sysUserGroupList, nil
-}
-
-func (s *sysUserGroup) GetRoleDepts(roleId int) ([]int, error) {
-	var entitys []*model.SysRoleDept
-	err := dao.SysRoleDept.Where("role_id", roleId).Scan(&entitys)
-	if err != nil {
-		return nil, err
-	}
-	result := make([]int, 0)
-	for _, v := range entitys {
-		result = append(result, v.DeptId)
-	}
-	return result, nil
-}

+ 3 - 0
opms_admin/config/config.toml

@@ -16,6 +16,9 @@
 [database]
     [[database.default]]
         Debug = true
+        createdAt = "created_time"
+        updatedAt = "updated_time"
+        deletedAt = "deleted_time"
         link = "mysql:root:Dashoo#190801@ali@tcp(192.168.0.252:3306)/dashoo_crm"
 
 # token认证设置

+ 3 - 1
opms_admin/main.go

@@ -14,12 +14,14 @@ func main() {
 	// 创建总服务包
 	s := micro_srv.CreateAndInitService(basePath)
 	// 注册服务对象
+	s.RegisterName("Dict", new(handler.DictHandler), "")
 	s.RegisterName("Auth", new(handler.AuthHandler), "")
 	s.RegisterName("User", new(handler.UserHandler), "")
 	s.RegisterName("Menu", new(handler.MenuHandler), "")
 	s.RegisterName("Dept", new(handler.DeptHandler), "")
 	s.RegisterName("Role", new(handler.RoleHandler), "")
-	s.RegisterName("Dict", new(handler.DictHandler), "")
+	s.RegisterName("Post", new(handler.PostHandler), "")
+	s.RegisterName("Group", new(handler.GroupHandler), "")
 
 	// 注册文件处理Service对象
 	//dynamic.BeanFactory.BeanRegister(service.NewRoleService())