utils.go 7.4 KB

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