utils.go 6.6 KB

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