utils.go 6.5 KB

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