utils.go 6.2 KB

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