utils.go 8.5 KB

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