utils.go 5.9 KB

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