utils.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. package api
  2. import (
  3. "box-cost/db/model"
  4. "box-cost/db/repo"
  5. "bytes"
  6. "fmt"
  7. "math/rand"
  8. "net/http"
  9. "time"
  10. "unsafe"
  11. "github.com/thecodingmachine/gotenberg-go-client/v7"
  12. "go.mongodb.org/mongo-driver/bson"
  13. "go.mongodb.org/mongo-driver/bson/primitive"
  14. )
  15. func generateSerial(ctx *ApiSession, typeName string) (serial string, err error) {
  16. // 获取类型
  17. cate := &model.Category{}
  18. found, err := repo.RepoSeachDoc(ctx.CreateRepoCtx(), &repo.DocSearchOptions{
  19. CollectName: "cates",
  20. Project: []string{"letterName"},
  21. Query: repo.Map{"name": typeName},
  22. Sort: bson.M{"_id": -1},
  23. }, cate)
  24. if !found || err != nil {
  25. return "", fmt.Errorf("未找到该类型")
  26. }
  27. // 自增器 increment index加1
  28. increment := &model.Increment{}
  29. found, _ = repo.RepoSeachDoc(ctx.CreateRepoCtx(), &repo.DocSearchOptions{
  30. CollectName: repo.CollectionIncrement,
  31. Query: repo.Map{"type": cate.LetterName},
  32. Project: []string{"index"},
  33. Sort: bson.M{"_id": -1},
  34. }, increment)
  35. if !found {
  36. repo.RepoAddDoc(ctx.CreateRepoCtx(), repo.CollectionIncrement, &model.Increment{
  37. Type: cate.LetterName,
  38. Index: 1,
  39. })
  40. return fmt.Sprintf("%s-%06d", cate.LetterName, 1), nil
  41. }
  42. index := increment.Index + 1
  43. repo.RepoUpdateSetDoc(ctx.CreateRepoCtx(), repo.CollectionIncrement, increment.Id.Hex(), &model.Increment{Index: index})
  44. // 拼接为序号
  45. return fmt.Sprintf("%s-%06d", cate.LetterName, index), nil
  46. }
  47. func searchBillTypeById(ctx *ApiSession, collectName string, id primitive.ObjectID) (string, error) {
  48. found, curbill := repo.RepoSeachDocMap(ctx.CreateRepoCtx(), &repo.DocSearchOptions{
  49. CollectName: collectName,
  50. Project: []string{"type"},
  51. Query: repo.Map{"_id": id},
  52. Sort: bson.M{"_id": -1},
  53. })
  54. if !found {
  55. return "", fmt.Errorf("未找到该类型")
  56. }
  57. return curbill["type"].(string), nil
  58. }
  59. func excelToPdf(formBody *bytes.Buffer, pdfHost string) (*http.Response, error) {
  60. httpClient := &http.Client{
  61. Timeout: time.Duration(5) * time.Second,
  62. }
  63. client := &gotenberg.Client{Hostname: pdfHost, HTTPClient: httpClient}
  64. doc, err := gotenberg.NewDocumentFromBytes("foo.xlsx", formBody.Bytes())
  65. if err != nil {
  66. fmt.Println(" to pdf read data err:", err)
  67. return nil, err
  68. }
  69. req := gotenberg.NewOfficeRequest(doc)
  70. req.Landscape(true)
  71. return client.Post(req)
  72. }
  73. func isManager(roles []string) bool {
  74. if len(roles) > 0 {
  75. for _, role := range roles {
  76. if role == "manager" {
  77. return true
  78. }
  79. }
  80. }
  81. return false
  82. }
  83. func getUserById(apictx *ApiSession, id primitive.ObjectID) (*model.UserSmaple, error) {
  84. fmt.Println(id.Hex())
  85. user := &model.UserSmaple{}
  86. _, err := repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  87. Db: "box-user",
  88. CollectName: repo.CollectionUsers,
  89. Query: repo.Map{"_id": id},
  90. Project: []string{"name", "avatar", "city", "loginName", "roles"},
  91. }, user)
  92. return user, err
  93. }
  94. // 获取一天的起始终止时间
  95. // func getDayRange(t time.Time) (start, end time.Time) {
  96. // loc, _ := time.LoadLocation("Local")
  97. // date := t.Format("2006-01-02")
  98. // startDate := date + " 00:00:00"
  99. // startTime, _ := time.ParseInLocation("2006-01-02 15:04:05", startDate, loc)
  100. // endDate := date + " 23:59:59"
  101. // endTime, _ := time.ParseInLocation("2006-01-02 15:04:05", endDate, loc)
  102. // return startTime, endTime
  103. // }
  104. // 获取时间跨度的起始终止时间
  105. // startDate/endDate 2023-01-31
  106. func getTimeRange(startDate, endDate string) (start, end time.Time) {
  107. loc, _ := time.LoadLocation("Local")
  108. startDateTime := startDate + " 00:00:00"
  109. endDateTime := endDate + " 23:59:59"
  110. start, _ = time.ParseInLocation("2006-01-02 15:04:05", startDateTime, loc)
  111. end, _ = time.ParseInLocation("2006-01-02 15:04:05", endDateTime, loc)
  112. return
  113. }
  114. // 处理报表query条件
  115. func handleReportQuery(query map[string]interface{}) map[string]interface{} {
  116. // 条件处理
  117. query["status"] = "complete"
  118. if _supplierId, ok := query["supplierId"]; ok {
  119. delete(query, "supplierId")
  120. fmt.Printf("id::::%#v\n", _supplierId)
  121. supplierId, _ := primitive.ObjectIDFromHex(_supplierId.(string))
  122. if !supplierId.IsZero() {
  123. query["supplierId"] = supplierId
  124. }
  125. }
  126. if _timeRange, ok := query["timeRange"]; ok {
  127. timeRange, _ := _timeRange.([]interface{})
  128. if len(timeRange) == 2 {
  129. start, end := getTimeRange(timeRange[0].(string), timeRange[1].(string))
  130. query["completeTime"] = bson.M{"$gte": start, "$lte": end}
  131. }
  132. delete(query, "timeRange")
  133. }
  134. if _planIds, ok := query["planIds"]; ok {
  135. if len(_planIds.([]interface{})) > 0 {
  136. planQuery := bson.A{}
  137. for _, _planId := range _planIds.([]interface{}) {
  138. planId, _ := primitive.ObjectIDFromHex(_planId.(string))
  139. planQuery = append(planQuery, bson.M{"planId": planId})
  140. }
  141. query["$or"] = planQuery
  142. }
  143. delete(query, "planIds")
  144. }
  145. return query
  146. }
  147. // 获取公司名字
  148. func getCompanyName(apictx *ApiSession) string {
  149. companyName := "中鱼互动"
  150. info := model.Setting{}
  151. found, _ := repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  152. CollectName: "infos",
  153. }, &info)
  154. if found {
  155. if info.CompanyName != "" {
  156. companyName = info.CompanyName
  157. }
  158. }
  159. return companyName
  160. }
  161. const (
  162. // 6 bits to represent a letter index
  163. letterIdBits = 6
  164. // All 1-bits as many as letterIdBits
  165. letterIdMask = 1<<letterIdBits - 1
  166. letterIdMax = 63 / letterIdBits
  167. letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  168. )
  169. var src = rand.NewSource(time.Now().UnixNano())
  170. func randName(n int) string {
  171. b := make([]byte, n)
  172. // A rand.Int63() generates 63 random bits, enough for letterIdMax letters!
  173. for i, cache, remain := n-1, src.Int63(), letterIdMax; i >= 0; {
  174. if remain == 0 {
  175. cache, remain = src.Int63(), letterIdMax
  176. }
  177. if idx := int(cache & letterIdMask); idx < len(letters) {
  178. b[i] = letters[idx]
  179. i--
  180. }
  181. cache >>= letterIdBits
  182. remain--
  183. }
  184. return *(*string)(unsafe.Pointer(&b))
  185. }