utils.go 8.2 KB

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