base.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. package service
  2. import (
  3. "context"
  4. "dashoo.cn/opms_libary/multipart"
  5. "fmt"
  6. "github.com/gogf/gf/text/gstr"
  7. "github.com/gogf/gf/util/guid"
  8. "io/ioutil"
  9. "log"
  10. "net/http"
  11. "os"
  12. "reflect"
  13. "dashoo.cn/opms_libary/myerrors"
  14. "dashoo.cn/opms_libary/request"
  15. "github.com/gogf/gf/container/gmap"
  16. "github.com/gogf/gf/frame/g"
  17. "github.com/gogf/gf/util/gconv"
  18. "github.com/smallnest/rpcx/share"
  19. "dashoo.cn/common_definition/comm_def"
  20. "dashoo.cn/opms_libary/micro_srv"
  21. "github.com/gogf/gf/database/gdb"
  22. "github.com/gogf/gf/os/gtime"
  23. )
  24. var (
  25. // DingTalkSpaceId 钉钉 空间Id。
  26. DingTalkSpaceId = "21077726250"
  27. // CommonUpdateFieldEx UpdateFieldEx 更新过滤字段
  28. CommonUpdateFieldEx = []interface{}{"created_by", "created_name", "created_time"}
  29. UpdateFieldEx = []interface{}{"id", "created_by", "created_name", "created_time"}
  30. )
  31. func Sequence(db gdb.DB, name string) (string, error) {
  32. v, err := db.GetValue("select `nextval`( ? );", name)
  33. if err != nil {
  34. return "", err
  35. }
  36. return v.String(), nil
  37. }
  38. func SequenceYearRest(db gdb.DB, name string) (int, error) {
  39. v, err := db.GetValue("select `next_year_reset_val`( ? );", name)
  40. if err != nil {
  41. return 0, err
  42. }
  43. return v.Int(), nil
  44. }
  45. // SetCreatedInfo 插入数据库时设置创建信息
  46. func SetCreatedInfo(entry interface{}, id int, name string) {
  47. v := reflect.ValueOf(entry)
  48. t := reflect.TypeOf(entry)
  49. if t.Kind() == reflect.Map {
  50. data := entry.(map[string]interface{})
  51. data["created_by"] = id
  52. data["created_name"] = name
  53. data["created_time"] = gtime.Now()
  54. return
  55. }
  56. if t.Kind() == reflect.Ptr {
  57. t = t.Elem()
  58. v = v.Elem()
  59. }
  60. if t.Kind() == reflect.Slice {
  61. }
  62. if t.Kind() != reflect.Struct {
  63. log.Println("Check type error not Struct")
  64. return
  65. }
  66. for i := 0; i < t.NumField(); i++ {
  67. fieldName := t.Field(i).Name
  68. if tag, ok := t.Field(i).Tag.Lookup("orm"); ok {
  69. switch tag {
  70. case "created_by":
  71. v.FieldByName(fieldName).Set(reflect.ValueOf(id))
  72. case "created_name":
  73. v.FieldByName(fieldName).Set(reflect.ValueOf(name))
  74. case "created_time":
  75. v.FieldByName(fieldName).Set(reflect.ValueOf(gtime.Now()))
  76. }
  77. }
  78. }
  79. }
  80. // SetUpdatedInfo 插入数据库时设置修改信息
  81. func SetUpdatedInfo(entry interface{}, id int, name string) {
  82. v := reflect.ValueOf(entry)
  83. t := reflect.TypeOf(entry)
  84. if t.Kind() == reflect.Map {
  85. data := entry.(map[string]interface{})
  86. data["updated_by"] = id
  87. data["updated_name"] = name
  88. data["updated_time"] = gtime.Now()
  89. return
  90. }
  91. if t.Kind() == reflect.Ptr {
  92. t = t.Elem()
  93. v = v.Elem()
  94. }
  95. if t.Kind() != reflect.Struct {
  96. log.Println("Check type error not Struct")
  97. return
  98. }
  99. for i := 0; i < t.NumField(); i++ {
  100. fieldName := t.Field(i).Name
  101. if tag, ok := t.Field(i).Tag.Lookup("orm"); ok {
  102. switch tag {
  103. case "updated_by":
  104. v.FieldByName(fieldName).Set(reflect.ValueOf(id))
  105. case "updated_name":
  106. v.FieldByName(fieldName).Set(reflect.ValueOf(name))
  107. case "updated_time":
  108. v.FieldByName(fieldName).Set(reflect.ValueOf(gtime.Now()))
  109. }
  110. }
  111. }
  112. }
  113. // Div 数字转字母
  114. func Div(Num int) string {
  115. var (
  116. Str string = ""
  117. k int
  118. temp []int //保存转化后每一位数据的值,然后通过索引的方式匹配A-Z
  119. )
  120. //用来匹配的字符A-Z
  121. Slice := []string{"", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O",
  122. "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"}
  123. if Num > 26 { //数据大于26需要进行拆分
  124. for {
  125. k = Num % 26 //从个位开始拆分,如果求余为0,说明末尾为26,也就是Z,如果是转化为26进制数,则末尾是可以为0的,这里必须为A-Z中的一个
  126. if k == 0 {
  127. temp = append(temp, 26)
  128. k = 26
  129. } else {
  130. temp = append(temp, k)
  131. }
  132. Num = (Num - k) / 26 //减去Num最后一位数的值,因为已经记录在temp中
  133. if Num <= 26 { //小于等于26直接进行匹配,不需要进行数据拆分
  134. temp = append(temp, Num)
  135. break
  136. }
  137. }
  138. } else {
  139. return Slice[Num]
  140. }
  141. for _, value := range temp {
  142. Str = Slice[value] + Str //因为数据切分后存储顺序是反的,所以Str要放在后面
  143. }
  144. return Str
  145. }
  146. type GetDictReq struct {
  147. DictType string `p:"dictType" v:"required#字典类型不能为空"`
  148. DefaultValue string `p:"defaultValue"`
  149. }
  150. type GetDictLabelByTypeAndValueReq struct {
  151. DictType string `p:"dictType"` //字典类型
  152. DictValue string `p:"dictValue"` //字典标签
  153. }
  154. func baseGetDictDataByType(ctx context.Context, typ string) ([]interface{}, error) {
  155. srv := micro_srv.InitMicroSrvClient("Dict", "micro_srv.auth")
  156. defer srv.Close()
  157. resp := &comm_def.CommonMsg{}
  158. err := srv.Call(ctx, "GetDictDataByType", GetDictReq{
  159. DictType: typ,
  160. }, resp)
  161. if err != nil {
  162. return nil, fmt.Errorf("获取字典 %s %s", typ, err.Error())
  163. }
  164. fmt.Println(resp.Data)
  165. data := resp.Data.(map[string]interface{})["Values"].([]interface{})
  166. fmt.Println(data)
  167. return data, nil
  168. }
  169. func GetDictDataByType(ctx context.Context, typ string) (map[string]string, error) {
  170. data, err := baseGetDictDataByType(ctx, typ)
  171. if err != nil {
  172. return nil, err
  173. }
  174. res := map[string]string{}
  175. for _, i := range data {
  176. info := i.(map[string]interface{})
  177. res[info["DictValue"].(string)] = info["DictLabel"].(string)
  178. }
  179. return res, nil
  180. }
  181. // 有序
  182. func GetDictDataTreeByType(ctx context.Context, typ string) (*gmap.ListMap, error) {
  183. data, err := baseGetDictDataByType(ctx, typ)
  184. if err != nil {
  185. return nil, err
  186. }
  187. res := gmap.NewListMap(true)
  188. for _, i := range data {
  189. info := i.(map[string]interface{})
  190. res.Set(info["DictValue"], info["DictLabel"])
  191. }
  192. return res, nil
  193. }
  194. // 根据字典类型和字典值获取字典明细名称
  195. func GetDictLabelByTypeAndValue(ctx context.Context, dictType, value string) (string, error) {
  196. srv := micro_srv.InitMicroSrvClient("Dict", "micro_srv.auth")
  197. defer srv.Close()
  198. resp := &comm_def.CommonMsg{}
  199. err := srv.Call(ctx, "GetDictLabelByTypeAndValue", GetDictLabelByTypeAndValueReq{
  200. DictType: dictType,
  201. DictValue: value,
  202. }, resp)
  203. if err != nil {
  204. g.Log().Error(err)
  205. return value, nil
  206. }
  207. return gconv.String(resp.Data), nil
  208. }
  209. func StringSlicecontains(s []string, ele string) bool {
  210. for _, i := range s {
  211. if i == ele {
  212. return true
  213. }
  214. }
  215. return false
  216. }
  217. // CreateSystemMessage 创建系统消息
  218. func CreateSystemMessage(msg g.MapStrStr) error {
  219. srv := micro_srv.InitMicroSrvClient("SystemMessage", "micro_srv.auth")
  220. defer srv.Close()
  221. resp := &comm_def.CommonMsg{}
  222. tenant := g.Config().GetString("micro_srv.tenant")
  223. ctx := context.WithValue(context.TODO(), share.ReqMetaDataKey, map[string]string{"tenant": tenant})
  224. err := srv.Call(ctx, "Create", msg, resp)
  225. if err != nil {
  226. g.Log().Error(err)
  227. return myerrors.MicroCallError("系统创建消息失败")
  228. }
  229. fmt.Println(resp.Data)
  230. return nil
  231. }
  232. type DeptIdReq struct {
  233. DeptId int `json:"dept_id,omitempty"`
  234. Include bool `json:"include,omitempty"`
  235. }
  236. // GetUsersByDept 根据部门获取用户
  237. func GetUsersByDept(ctx context.Context, req *DeptIdReq) (map[string]int, error) {
  238. srv := micro_srv.InitMicroSrvClient("User", "micro_srv.auth")
  239. defer srv.Close()
  240. resp := &comm_def.CommonMsg{}
  241. err := srv.Call(ctx, "GetUserByDept", req, resp)
  242. if err != nil {
  243. return nil, myerrors.MicroCallError("获取部门下用户失败")
  244. }
  245. if resp.Data == nil {
  246. return nil, myerrors.TipsError("部门不存在")
  247. }
  248. fmt.Println(resp.Data)
  249. data := resp.Data.([]interface{})
  250. fmt.Println(data)
  251. res := map[string]int{}
  252. for _, i := range data {
  253. info := i.(map[string]interface{})
  254. res[info["NickName"].(string)] = gconv.Int(info["Id"])
  255. }
  256. return res, nil
  257. }
  258. type SysUserSearchReq struct {
  259. KeyWords string `json:"keyWords"`
  260. DeptId int `json:"deptId"` //部门id
  261. DeptIds []int //所属部门id数据
  262. Phone string `json:"phone"`
  263. Status string `json:"status"`
  264. Roles []string `json:"roles"`
  265. Posts []string `json:"posts"`
  266. Groups []string `json:"groups"`
  267. request.PageReq
  268. }
  269. // GetUsersByRoleCode 根据角色编码获取用户
  270. func GetUsersByRoleCode(ctx context.Context, roleCode []string, pageSize ...int) (map[string]int, error) {
  271. srv := micro_srv.InitMicroSrvClient("User", "micro_srv.auth")
  272. defer srv.Close()
  273. resp := &comm_def.CommonMsg{}
  274. req := &SysUserSearchReq{Roles: roleCode, Status: "10"}
  275. if len(pageSize) > 0 {
  276. req.PageSize = pageSize[0]
  277. }
  278. err := srv.Call(ctx, "GetList", req, resp)
  279. if err != nil {
  280. return nil, myerrors.MicroCallError("根据角色编码获取用户失败")
  281. }
  282. if resp.Data == nil {
  283. return nil, myerrors.TipsError("用户不存在")
  284. }
  285. data := resp.Data.(map[string]interface{})
  286. list := data["list"].([]interface{})
  287. res := map[string]int{}
  288. for _, i := range list {
  289. info := i.(map[string]interface{})
  290. res[info["NickName"].(string)] = gconv.Int(info["Id"])
  291. }
  292. return res, nil
  293. }
  294. // 获取用户权限
  295. func GetUserDataScope(userId int) (g.Map, error) {
  296. srv := micro_srv.InitMicroSrvClient("User", "micro_srv.auth")
  297. defer srv.Close()
  298. req := &comm_def.IdReq{Id: int64(userId)}
  299. resp := &comm_def.CommonMsg{}
  300. tenant := g.Config().GetString("micro_srv.tenant")
  301. ctx := context.WithValue(context.TODO(), share.ReqMetaDataKey, map[string]string{"tenant": tenant})
  302. err := srv.Call(ctx, "GetDataScope", req, resp)
  303. if err != nil || resp.Data == nil {
  304. g.Log().Error(err)
  305. return nil, myerrors.MicroCallError("获取用户权限失败")
  306. }
  307. return resp.Data.(g.Map), nil
  308. }
  309. // 跟进发送邮件消息
  310. func GSendMail(msg g.MapStrStr) error {
  311. srv := micro_srv.InitMicroSrvClient("Message", "micro_srv.auth")
  312. defer srv.Close()
  313. resp := &comm_def.CommonMsg{}
  314. tenant := g.Config().GetString("micro_srv.tenant")
  315. ctx := context.WithValue(context.TODO(), share.ReqMetaDataKey, map[string]string{"tenant": tenant})
  316. err := srv.Call(ctx, "SendMail", msg, resp)
  317. if err != nil {
  318. g.Log().Error(err)
  319. return myerrors.MicroCallError("项目未跟进发送邮件提醒失败")
  320. }
  321. fmt.Println(resp.Data)
  322. return nil
  323. }
  324. func ColumnInt(m *gdb.Model, name string) ([]int, error) {
  325. v, err := m.Fields(name).Array()
  326. if err != nil {
  327. return nil, err
  328. }
  329. res := []int{}
  330. for _, i := range v {
  331. res = append(res, i.Int())
  332. }
  333. return res, nil
  334. }
  335. func ColumnString(m *gdb.Model, name string) ([]string, error) {
  336. v, err := m.Fields(name).Array()
  337. if err != nil {
  338. return nil, err
  339. }
  340. res := []string{}
  341. for _, i := range v {
  342. res = append(res, i.String())
  343. }
  344. return res, nil
  345. }
  346. func StringsContains(s []string, ele string) bool {
  347. for _, i := range s {
  348. if i == ele {
  349. return true
  350. }
  351. }
  352. return false
  353. }
  354. func UserIdByRoles(db gdb.DB, roles ...string) ([]int, error) {
  355. roleId, err := ColumnInt(db.Table("sys_role").Where("role_key in (?)", roles), "id")
  356. if err != nil {
  357. return nil, err
  358. }
  359. return ColumnInt(db.Table("sys_user_role").Where("role_id in (?)", roleId), "user_id")
  360. }
  361. func SliceIntDeduplication(elems []int) []int {
  362. emap := map[int]struct{}{}
  363. for _, i := range elems {
  364. emap[i] = struct{}{}
  365. }
  366. ret := []int{}
  367. for i := range emap {
  368. ret = append(ret, i)
  369. }
  370. return ret
  371. }
  372. // DownloadTempFile 下载临时文件
  373. func DownloadTempFile(url string) (*multipart.FileHeader, error) {
  374. r, err := http.Get(url)
  375. if err != nil {
  376. g.Log().Error(err)
  377. return nil, err
  378. }
  379. if r.StatusCode != http.StatusOK {
  380. return nil, fmt.Errorf("DownloadFile from %s StatusCode %d", url, r.StatusCode)
  381. }
  382. defer r.Body.Close()
  383. bytes, err := ioutil.ReadAll(r.Body)
  384. if err != nil {
  385. g.Log().Error(err)
  386. return nil, err
  387. }
  388. names := gstr.Split(r.Header.Get("Content-Disposition"), "filename=")
  389. fileName := guid.S()
  390. if len(names) > 1 {
  391. fileName = gstr.TrimStr(names[1], `"`)
  392. }
  393. file, err := os.CreateTemp("", fileName)
  394. if err != nil {
  395. g.Log().Error(err)
  396. }
  397. file.Write(bytes)
  398. fmt.Println(file.Name())
  399. fileData := new(multipart.FileHeader)
  400. fileData.FileName = fileName
  401. fileData.FileSize = gconv.Int64(r.Header.Get("Content-Length"))
  402. fileData.File = file
  403. return fileData, nil
  404. }