| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436 |
- package service
- import (
- "context"
- "dashoo.cn/opms_libary/multipart"
- "fmt"
- "github.com/gogf/gf/text/gstr"
- "github.com/gogf/gf/util/guid"
- "io/ioutil"
- "log"
- "net/http"
- "os"
- "reflect"
- "dashoo.cn/opms_libary/myerrors"
- "dashoo.cn/opms_libary/request"
- "github.com/gogf/gf/container/gmap"
- "github.com/gogf/gf/frame/g"
- "github.com/gogf/gf/util/gconv"
- "github.com/smallnest/rpcx/share"
- "dashoo.cn/common_definition/comm_def"
- "dashoo.cn/opms_libary/micro_srv"
- "github.com/gogf/gf/database/gdb"
- "github.com/gogf/gf/os/gtime"
- )
- var (
- // DingTalkSpaceId 钉钉 空间Id。
- DingTalkSpaceId = "21077726250"
- // CommonUpdateFieldEx UpdateFieldEx 更新过滤字段
- CommonUpdateFieldEx = []interface{}{"created_by", "created_name", "created_time"}
- UpdateFieldEx = []interface{}{"id", "created_by", "created_name", "created_time"}
- )
- func Sequence(db gdb.DB, name string) (string, error) {
- v, err := db.GetValue("select `nextval`( ? );", name)
- if err != nil {
- return "", err
- }
- return v.String(), nil
- }
- func SequenceYearRest(db gdb.DB, name string) (int, error) {
- v, err := db.GetValue("select `next_year_reset_val`( ? );", name)
- if err != nil {
- return 0, err
- }
- return v.Int(), nil
- }
- // SetCreatedInfo 插入数据库时设置创建信息
- func SetCreatedInfo(entry interface{}, id int, name string) {
- v := reflect.ValueOf(entry)
- t := reflect.TypeOf(entry)
- if t.Kind() == reflect.Map {
- data := entry.(map[string]interface{})
- data["created_by"] = id
- data["created_name"] = name
- data["created_time"] = gtime.Now()
- return
- }
- if t.Kind() == reflect.Ptr {
- t = t.Elem()
- v = v.Elem()
- }
- if t.Kind() == reflect.Slice {
- }
- if t.Kind() != reflect.Struct {
- log.Println("Check type error not Struct")
- return
- }
- for i := 0; i < t.NumField(); i++ {
- fieldName := t.Field(i).Name
- if tag, ok := t.Field(i).Tag.Lookup("orm"); ok {
- switch tag {
- case "created_by":
- v.FieldByName(fieldName).Set(reflect.ValueOf(id))
- case "created_name":
- v.FieldByName(fieldName).Set(reflect.ValueOf(name))
- case "created_time":
- v.FieldByName(fieldName).Set(reflect.ValueOf(gtime.Now()))
- }
- }
- }
- }
- // SetUpdatedInfo 插入数据库时设置修改信息
- func SetUpdatedInfo(entry interface{}, id int, name string) {
- v := reflect.ValueOf(entry)
- t := reflect.TypeOf(entry)
- if t.Kind() == reflect.Map {
- data := entry.(map[string]interface{})
- data["updated_by"] = id
- data["updated_name"] = name
- data["updated_time"] = gtime.Now()
- return
- }
- if t.Kind() == reflect.Ptr {
- t = t.Elem()
- v = v.Elem()
- }
- if t.Kind() != reflect.Struct {
- log.Println("Check type error not Struct")
- return
- }
- for i := 0; i < t.NumField(); i++ {
- fieldName := t.Field(i).Name
- if tag, ok := t.Field(i).Tag.Lookup("orm"); ok {
- switch tag {
- case "updated_by":
- v.FieldByName(fieldName).Set(reflect.ValueOf(id))
- case "updated_name":
- v.FieldByName(fieldName).Set(reflect.ValueOf(name))
- case "updated_time":
- v.FieldByName(fieldName).Set(reflect.ValueOf(gtime.Now()))
- }
- }
- }
- }
- // Div 数字转字母
- func Div(Num int) string {
- var (
- Str string = ""
- k int
- temp []int //保存转化后每一位数据的值,然后通过索引的方式匹配A-Z
- )
- //用来匹配的字符A-Z
- Slice := []string{"", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O",
- "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"}
- if Num > 26 { //数据大于26需要进行拆分
- for {
- k = Num % 26 //从个位开始拆分,如果求余为0,说明末尾为26,也就是Z,如果是转化为26进制数,则末尾是可以为0的,这里必须为A-Z中的一个
- if k == 0 {
- temp = append(temp, 26)
- k = 26
- } else {
- temp = append(temp, k)
- }
- Num = (Num - k) / 26 //减去Num最后一位数的值,因为已经记录在temp中
- if Num <= 26 { //小于等于26直接进行匹配,不需要进行数据拆分
- temp = append(temp, Num)
- break
- }
- }
- } else {
- return Slice[Num]
- }
- for _, value := range temp {
- Str = Slice[value] + Str //因为数据切分后存储顺序是反的,所以Str要放在后面
- }
- return Str
- }
- type GetDictReq struct {
- DictType string `p:"dictType" v:"required#字典类型不能为空"`
- DefaultValue string `p:"defaultValue"`
- }
- type GetDictLabelByTypeAndValueReq struct {
- DictType string `p:"dictType"` //字典类型
- DictValue string `p:"dictValue"` //字典标签
- }
- func baseGetDictDataByType(ctx context.Context, typ string) ([]interface{}, error) {
- srv := micro_srv.InitMicroSrvClient("Dict", "micro_srv.auth")
- defer srv.Close()
- resp := &comm_def.CommonMsg{}
- err := srv.Call(ctx, "GetDictDataByType", GetDictReq{
- DictType: typ,
- }, resp)
- if err != nil {
- return nil, fmt.Errorf("获取字典 %s %s", typ, err.Error())
- }
- fmt.Println(resp.Data)
- data := resp.Data.(map[string]interface{})["Values"].([]interface{})
- fmt.Println(data)
- return data, nil
- }
- func GetDictDataByType(ctx context.Context, typ string) (map[string]string, error) {
- data, err := baseGetDictDataByType(ctx, typ)
- if err != nil {
- return nil, err
- }
- res := map[string]string{}
- for _, i := range data {
- info := i.(map[string]interface{})
- res[info["DictValue"].(string)] = info["DictLabel"].(string)
- }
- return res, nil
- }
- // 有序
- func GetDictDataTreeByType(ctx context.Context, typ string) (*gmap.ListMap, error) {
- data, err := baseGetDictDataByType(ctx, typ)
- if err != nil {
- return nil, err
- }
- res := gmap.NewListMap(true)
- for _, i := range data {
- info := i.(map[string]interface{})
- res.Set(info["DictValue"], info["DictLabel"])
- }
- return res, nil
- }
- // 根据字典类型和字典值获取字典明细名称
- func GetDictLabelByTypeAndValue(ctx context.Context, dictType, value string) (string, error) {
- srv := micro_srv.InitMicroSrvClient("Dict", "micro_srv.auth")
- defer srv.Close()
- resp := &comm_def.CommonMsg{}
- err := srv.Call(ctx, "GetDictLabelByTypeAndValue", GetDictLabelByTypeAndValueReq{
- DictType: dictType,
- DictValue: value,
- }, resp)
- if err != nil {
- g.Log().Error(err)
- return value, nil
- }
- return gconv.String(resp.Data), nil
- }
- func StringSlicecontains(s []string, ele string) bool {
- for _, i := range s {
- if i == ele {
- return true
- }
- }
- return false
- }
- // CreateSystemMessage 创建系统消息
- func CreateSystemMessage(msg g.MapStrStr) error {
- srv := micro_srv.InitMicroSrvClient("SystemMessage", "micro_srv.auth")
- defer srv.Close()
- resp := &comm_def.CommonMsg{}
- tenant := g.Config().GetString("micro_srv.tenant")
- ctx := context.WithValue(context.TODO(), share.ReqMetaDataKey, map[string]string{"tenant": tenant})
- err := srv.Call(ctx, "Create", msg, resp)
- if err != nil {
- g.Log().Error(err)
- return myerrors.MicroCallError("系统创建消息失败")
- }
- fmt.Println(resp.Data)
- return nil
- }
- type DeptIdReq struct {
- DeptId int `json:"dept_id,omitempty"`
- Include bool `json:"include,omitempty"`
- }
- // GetUsersByDept 根据部门获取用户
- func GetUsersByDept(ctx context.Context, req *DeptIdReq) (map[string]int, error) {
- srv := micro_srv.InitMicroSrvClient("User", "micro_srv.auth")
- defer srv.Close()
- resp := &comm_def.CommonMsg{}
- err := srv.Call(ctx, "GetUserByDept", req, resp)
- if err != nil {
- return nil, myerrors.MicroCallError("获取部门下用户失败")
- }
- if resp.Data == nil {
- return nil, myerrors.TipsError("部门不存在")
- }
- fmt.Println(resp.Data)
- data := resp.Data.([]interface{})
- fmt.Println(data)
- res := map[string]int{}
- for _, i := range data {
- info := i.(map[string]interface{})
- res[info["NickName"].(string)] = gconv.Int(info["Id"])
- }
- return res, nil
- }
- type SysUserSearchReq struct {
- KeyWords string `json:"keyWords"`
- DeptId int `json:"deptId"` //部门id
- DeptIds []int //所属部门id数据
- Phone string `json:"phone"`
- Status string `json:"status"`
- Roles []string `json:"roles"`
- Posts []string `json:"posts"`
- Groups []string `json:"groups"`
- request.PageReq
- }
- // GetUsersByRoleCode 根据角色编码获取用户
- func GetUsersByRoleCode(ctx context.Context, roleCode []string, pageSize ...int) (map[string]int, error) {
- srv := micro_srv.InitMicroSrvClient("User", "micro_srv.auth")
- defer srv.Close()
- resp := &comm_def.CommonMsg{}
- req := &SysUserSearchReq{Roles: roleCode, Status: "10"}
- if len(pageSize) > 0 {
- req.PageSize = pageSize[0]
- }
- err := srv.Call(ctx, "GetList", req, resp)
- if err != nil {
- return nil, myerrors.MicroCallError("根据角色编码获取用户失败")
- }
- if resp.Data == nil {
- return nil, myerrors.TipsError("用户不存在")
- }
- data := resp.Data.(map[string]interface{})
- list := data["list"].([]interface{})
- res := map[string]int{}
- for _, i := range list {
- info := i.(map[string]interface{})
- res[info["NickName"].(string)] = gconv.Int(info["Id"])
- }
- return res, nil
- }
- // 获取用户权限
- func GetUserDataScope(userId int) (g.Map, error) {
- srv := micro_srv.InitMicroSrvClient("User", "micro_srv.auth")
- defer srv.Close()
- req := &comm_def.IdReq{Id: int64(userId)}
- resp := &comm_def.CommonMsg{}
- tenant := g.Config().GetString("micro_srv.tenant")
- ctx := context.WithValue(context.TODO(), share.ReqMetaDataKey, map[string]string{"tenant": tenant})
- err := srv.Call(ctx, "GetDataScope", req, resp)
- if err != nil || resp.Data == nil {
- g.Log().Error(err)
- return nil, myerrors.MicroCallError("获取用户权限失败")
- }
- return resp.Data.(g.Map), nil
- }
- // 跟进发送邮件消息
- func GSendMail(msg g.MapStrStr) error {
- srv := micro_srv.InitMicroSrvClient("Message", "micro_srv.auth")
- defer srv.Close()
- resp := &comm_def.CommonMsg{}
- tenant := g.Config().GetString("micro_srv.tenant")
- ctx := context.WithValue(context.TODO(), share.ReqMetaDataKey, map[string]string{"tenant": tenant})
- err := srv.Call(ctx, "SendMail", msg, resp)
- if err != nil {
- g.Log().Error(err)
- return myerrors.MicroCallError("项目未跟进发送邮件提醒失败")
- }
- fmt.Println(resp.Data)
- return nil
- }
- func ColumnInt(m *gdb.Model, name string) ([]int, error) {
- v, err := m.Fields(name).Array()
- if err != nil {
- return nil, err
- }
- res := []int{}
- for _, i := range v {
- res = append(res, i.Int())
- }
- return res, nil
- }
- func ColumnString(m *gdb.Model, name string) ([]string, error) {
- v, err := m.Fields(name).Array()
- if err != nil {
- return nil, err
- }
- res := []string{}
- for _, i := range v {
- res = append(res, i.String())
- }
- return res, nil
- }
- func StringsContains(s []string, ele string) bool {
- for _, i := range s {
- if i == ele {
- return true
- }
- }
- return false
- }
- func UserIdByRoles(db gdb.DB, roles ...string) ([]int, error) {
- roleId, err := ColumnInt(db.Table("sys_role").Where("role_key in (?)", roles), "id")
- if err != nil {
- return nil, err
- }
- return ColumnInt(db.Table("sys_user_role").Where("role_id in (?)", roleId), "user_id")
- }
- func SliceIntDeduplication(elems []int) []int {
- emap := map[int]struct{}{}
- for _, i := range elems {
- emap[i] = struct{}{}
- }
- ret := []int{}
- for i := range emap {
- ret = append(ret, i)
- }
- return ret
- }
- // DownloadTempFile 下载临时文件
- func DownloadTempFile(url string) (*multipart.FileHeader, error) {
- r, err := http.Get(url)
- if err != nil {
- g.Log().Error(err)
- return nil, err
- }
- if r.StatusCode != http.StatusOK {
- return nil, fmt.Errorf("DownloadFile from %s StatusCode %d", url, r.StatusCode)
- }
- defer r.Body.Close()
- bytes, err := ioutil.ReadAll(r.Body)
- if err != nil {
- g.Log().Error(err)
- return nil, err
- }
- names := gstr.Split(r.Header.Get("Content-Disposition"), "filename=")
- fileName := guid.S()
- if len(names) > 1 {
- fileName = gstr.TrimStr(names[1], `"`)
- }
- file, err := os.CreateTemp("", fileName)
- if err != nil {
- g.Log().Error(err)
- }
- file.Write(bytes)
- fmt.Println(file.Name())
- fileData := new(multipart.FileHeader)
- fileData.FileName = fileName
- fileData.FileSize = gconv.Int64(r.Header.Get("Content-Length"))
- fileData.File = file
- return fileData, nil
- }
|