utils.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  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. fmt.Println(id.Hex())
  70. found, curbill := repo.RepoSeachDocMap(ctx.CreateRepoCtx(), &repo.DocSearchOptions{
  71. CollectName: collectName,
  72. Project: []string{"type"},
  73. Query: repo.Map{"_id": id},
  74. Sort: bson.M{"_id": -1},
  75. })
  76. if !found {
  77. return "", fmt.Errorf("未找到该类型")
  78. }
  79. return curbill["type"].(string), nil
  80. }
  81. func excelToPdf(formBody *bytes.Buffer, pdfHost string) (*http.Response, error) {
  82. httpClient := &http.Client{
  83. Timeout: time.Duration(5) * time.Second,
  84. }
  85. client := &gotenberg.Client{Hostname: pdfHost, HTTPClient: httpClient}
  86. doc, err := gotenberg.NewDocumentFromBytes("foo.xlsx", formBody.Bytes())
  87. if err != nil {
  88. fmt.Println(" to pdf read data err:", err)
  89. return nil, err
  90. }
  91. req := gotenberg.NewOfficeRequest(doc)
  92. req.Landscape(true)
  93. return client.Post(req)
  94. }
  95. func isManager(roles []string) bool {
  96. if len(roles) > 0 {
  97. for _, role := range roles {
  98. if role == "manager" {
  99. return true
  100. }
  101. }
  102. }
  103. return false
  104. }
  105. func getUserById(apictx *ApiSession, id primitive.ObjectID) (*model.UserSmaple, error) {
  106. fmt.Println(id.Hex())
  107. user := &model.UserSmaple{}
  108. _, err := repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  109. Db: "box-user",
  110. CollectName: repo.CollectionUsers,
  111. Query: repo.Map{"_id": id},
  112. Project: []string{"name", "avatar", "city", "loginName", "roles"},
  113. }, user)
  114. return user, err
  115. }
  116. // 获取一天的起始终止时间
  117. // func getDayRange(t time.Time) (start, end time.Time) {
  118. // loc, _ := time.LoadLocation("Local")
  119. // date := t.Format("2006-01-02")
  120. // startDate := date + " 00:00:00"
  121. // startTime, _ := time.ParseInLocation("2006-01-02 15:04:05", startDate, loc)
  122. // endDate := date + " 23:59:59"
  123. // endTime, _ := time.ParseInLocation("2006-01-02 15:04:05", endDate, loc)
  124. // return startTime, endTime
  125. // }
  126. // 获取时间跨度的起始终止时间
  127. // startDate/endDate 2023-01-31
  128. func getTimeRange(startDate, endDate string) (start, end time.Time) {
  129. loc, _ := time.LoadLocation("Local")
  130. startDateTime := startDate + " 00:00:00"
  131. endDateTime := endDate + " 23:59:59"
  132. start, _ = time.ParseInLocation("2006-01-02 15:04:05", startDateTime, loc)
  133. end, _ = time.ParseInLocation("2006-01-02 15:04:05", endDateTime, loc)
  134. return
  135. }
  136. // 处理报表query条件
  137. func handleReportQuery(query map[string]interface{}) map[string]interface{} {
  138. // 条件处理
  139. query["status"] = "complete"
  140. if _supplierId, ok := query["supplierId"]; ok {
  141. delete(query, "supplierId")
  142. fmt.Printf("id::::%#v\n", _supplierId)
  143. supplierId, _ := primitive.ObjectIDFromHex(_supplierId.(string))
  144. if !supplierId.IsZero() {
  145. query["supplierId"] = supplierId
  146. }
  147. }
  148. if _timeRange, ok := query["timeRange"]; ok {
  149. timeRange, _ := _timeRange.([]interface{})
  150. if len(timeRange) == 2 {
  151. start, end := getTimeRange(timeRange[0].(string), timeRange[1].(string))
  152. query["completeTime"] = bson.M{"$gte": start, "$lte": end}
  153. }
  154. delete(query, "timeRange")
  155. }
  156. if _planIds, ok := query["planIds"]; ok {
  157. if len(_planIds.([]interface{})) > 0 {
  158. planQuery := bson.A{}
  159. for _, _planId := range _planIds.([]interface{}) {
  160. planId, _ := primitive.ObjectIDFromHex(_planId.(string))
  161. planQuery = append(planQuery, bson.M{"planId": planId})
  162. }
  163. query["$or"] = planQuery
  164. }
  165. delete(query, "planIds")
  166. }
  167. return query
  168. }
  169. // 获取公司名字
  170. func getCompanyName(apictx *ApiSession) string {
  171. companyName := "中鱼互动"
  172. info := model.Setting{}
  173. found, _ := repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  174. CollectName: "infos",
  175. }, &info)
  176. if found {
  177. if info.CompanyName != "" {
  178. companyName = info.CompanyName
  179. }
  180. }
  181. return companyName
  182. }
  183. const (
  184. letterIdBits = 6
  185. letterIdMask = 1<<letterIdBits - 1
  186. letterIdMax = 63 / letterIdBits
  187. letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  188. )
  189. var src = rand.NewSource(time.Now().UnixNano())
  190. func randName(n int) string {
  191. b := make([]byte, n)
  192. for i, cache, remain := n-1, src.Int63(), letterIdMax; i >= 0; {
  193. if remain == 0 {
  194. cache, remain = src.Int63(), letterIdMax
  195. }
  196. if idx := int(cache & letterIdMask); idx < len(letters) {
  197. b[i] = letters[idx]
  198. i--
  199. }
  200. cache >>= letterIdBits
  201. remain--
  202. }
  203. return *(*string)(unsafe.Pointer(&b))
  204. }