utils.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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. // 'merge="true"' \
  110. // --form 'pdfFormat="PDF/A-1a"' \
  111. // formData := url.Values{
  112. // "merge": {"true"},
  113. // "pdfFormat": {"PDF/A-1a"},
  114. // }
  115. // 构建请求体
  116. // reqData := bytes.NewBufferString(formData.Encode())
  117. // reqData.WriteTo(formBody)
  118. doc, err := gotenberg.NewDocumentFromBytes("foo.xlsx", formBody.Bytes())
  119. if err != nil {
  120. fmt.Println(" to pdf read data err:", err)
  121. return nil, err
  122. }
  123. req := gotenberg.NewOfficeRequest(doc)
  124. req.Landscape(true)
  125. return client.Post(req)
  126. }
  127. func isManager(roles []string) bool {
  128. if len(roles) > 0 {
  129. for _, role := range roles {
  130. if role == "manager" {
  131. return true
  132. }
  133. }
  134. }
  135. return false
  136. }
  137. func isSender(roles []string) bool {
  138. if len(roles) > 0 {
  139. for _, role := range roles {
  140. if role == "sender" {
  141. return true
  142. }
  143. }
  144. }
  145. return false
  146. }
  147. func getUserById(apictx *ApiSession, id primitive.ObjectID) (*model.UserSmaple, error) {
  148. user := &model.UserSmaple{}
  149. _, err := repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  150. Db: "box-user",
  151. CollectName: repo.CollectionUsers,
  152. Query: repo.Map{"_id": id},
  153. Project: []string{"name", "avatar", "city", "loginName", "roles", "phone"},
  154. }, user)
  155. return user, err
  156. }
  157. // 获取一天的起始终止时间
  158. // func getDayRange(t time.Time) (start, end time.Time) {
  159. // loc, _ := time.LoadLocation("Local")
  160. // date := t.Format("2006-01-02")
  161. // startDate := date + " 00:00:00"
  162. // startTime, _ := time.ParseInLocation("2006-01-02 15:04:05", startDate, loc)
  163. // endDate := date + " 23:59:59"
  164. // endTime, _ := time.ParseInLocation("2006-01-02 15:04:05", endDate, loc)
  165. // return startTime, endTime
  166. // }
  167. // 获取时间跨度的起始终止时间
  168. // startDate/endDate 2023-01-31
  169. func getTimeRange(startDate, endDate string) (start, end time.Time) {
  170. loc, _ := time.LoadLocation("Local")
  171. startDateTime := startDate + " 00:00:00"
  172. endDateTime := endDate + " 23:59:59"
  173. start, _ = time.ParseInLocation("2006-01-02 15:04:05", startDateTime, loc)
  174. end, _ = time.ParseInLocation("2006-01-02 15:04:05", endDateTime, loc)
  175. return
  176. }
  177. // 处理报表query条件
  178. func handleReportQuery(query map[string]interface{}) map[string]interface{} {
  179. // 条件处理
  180. query["status"] = "complete"
  181. if _supplierId, ok := query["supplierId"]; ok {
  182. delete(query, "supplierId")
  183. supplierId, _ := primitive.ObjectIDFromHex(_supplierId.(string))
  184. if !supplierId.IsZero() {
  185. query["supplierId"] = supplierId
  186. }
  187. }
  188. if _timeRange, ok := query["timeRange"]; ok {
  189. timeRange, _ := _timeRange.([]interface{})
  190. if len(timeRange) == 2 {
  191. start, end := getTimeRange(timeRange[0].(string), timeRange[1].(string))
  192. query["completeTime"] = bson.M{"$gte": start, "$lte": end}
  193. }
  194. delete(query, "timeRange")
  195. }
  196. if _planIds, ok := query["planIds"]; ok {
  197. if len(_planIds.([]interface{})) > 0 {
  198. planQuery := bson.A{}
  199. for _, _planId := range _planIds.([]interface{}) {
  200. planId, _ := primitive.ObjectIDFromHex(_planId.(string))
  201. planQuery = append(planQuery, bson.M{"planId": planId})
  202. }
  203. query["$or"] = planQuery
  204. }
  205. delete(query, "planIds")
  206. }
  207. return query
  208. }
  209. // 获取公司名字
  210. func getCompanyName(apictx *ApiSession) string {
  211. companyName := "中鱼互动"
  212. info := model.Setting{}
  213. found, _ := repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  214. CollectName: "infos",
  215. }, &info)
  216. if found {
  217. if info.CompanyName != "" {
  218. companyName = info.CompanyName
  219. }
  220. }
  221. return companyName
  222. }
  223. const (
  224. letterIdBits = 6
  225. letterIdMask = 1<<letterIdBits - 1
  226. letterIdMax = 63 / letterIdBits
  227. letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  228. )
  229. var src = rand.NewSource(time.Now().UnixNano())
  230. func randName(n int) string {
  231. b := make([]byte, n)
  232. for i, cache, remain := n-1, src.Int63(), letterIdMax; i >= 0; {
  233. if remain == 0 {
  234. cache, remain = src.Int63(), letterIdMax
  235. }
  236. if idx := int(cache & letterIdMask); idx < len(letters) {
  237. b[i] = letters[idx]
  238. i--
  239. }
  240. cache >>= letterIdBits
  241. remain--
  242. }
  243. return *(*string)(unsafe.Pointer(&b))
  244. }