utils.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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. TargetId: increment.Id.Hex(),
  132. })
  133. // 拼接为序号
  134. return fmt.Sprintf("%s-%06d", cate.LetterName, index), nil
  135. }
  136. func searchBillTypeById(ctx *ApiSession, collectName string, id primitive.ObjectID) (string, error) {
  137. fmt.Println(id.Hex())
  138. found, curbill := repo.RepoSeachDocMap(ctx.CreateRepoCtx(), &repo.DocSearchOptions{
  139. CollectName: collectName,
  140. Project: []string{"type"},
  141. Query: repo.Map{"_id": id},
  142. Sort: bson.M{"_id": -1},
  143. })
  144. if !found {
  145. return "", fmt.Errorf("未找到该类型")
  146. }
  147. return curbill["type"].(string), nil
  148. }
  149. func excelToPdf(formBody *bytes.Buffer, pdfHost string) (*http.Response, error) {
  150. httpClient := &http.Client{
  151. Timeout: time.Duration(15) * time.Second,
  152. }
  153. client := &gotenberg.Client{Hostname: pdfHost, HTTPClient: httpClient}
  154. // 'merge="true"' \
  155. // --form 'pdfFormat="PDF/A-1a"' \
  156. // formData := url.Values{
  157. // "merge": {"true"},
  158. // "pdfFormat": {"PDF/A-1a"},
  159. // }
  160. // 构建请求体
  161. // reqData := bytes.NewBufferString(formData.Encode())
  162. // reqData.WriteTo(formBody)
  163. doc, err := gotenberg.NewDocumentFromBytes("foo.xlsx", formBody.Bytes())
  164. if err != nil {
  165. fmt.Println(" to pdf read data err:", err)
  166. return nil, err
  167. }
  168. req := gotenberg.NewOfficeRequest(doc)
  169. req.Landscape(true)
  170. return client.Post(req)
  171. }
  172. func isManager(roles []string) bool {
  173. if len(roles) > 0 {
  174. for _, role := range roles {
  175. if role == "manager" {
  176. return true
  177. }
  178. }
  179. }
  180. return false
  181. }
  182. func isSender(roles []string) bool {
  183. if len(roles) > 0 {
  184. for _, role := range roles {
  185. if role == "sender" {
  186. return true
  187. }
  188. }
  189. }
  190. return false
  191. }
  192. func getUserById(apictx *ApiSession, id primitive.ObjectID) (*model.UserSmaple, error) {
  193. user := &model.UserSmaple{}
  194. _, err := repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  195. Db: "box-user",
  196. CollectName: repo.CollectionUsers,
  197. Query: repo.Map{"_id": id},
  198. Project: []string{"name", "avatar", "city", "loginName", "roles", "phone"},
  199. }, user)
  200. return user, err
  201. }
  202. // 获取一天的起始终止时间
  203. // func getDayRange(t time.Time) (start, end time.Time) {
  204. // loc, _ := time.LoadLocation("Local")
  205. // date := t.Format("2006-01-02")
  206. // startDate := date + " 00:00:00"
  207. // startTime, _ := time.ParseInLocation("2006-01-02 15:04:05", startDate, loc)
  208. // endDate := date + " 23:59:59"
  209. // endTime, _ := time.ParseInLocation("2006-01-02 15:04:05", endDate, loc)
  210. // return startTime, endTime
  211. // }
  212. // 获取时间跨度的起始终止时间
  213. // startDate/endDate 2023-01-31
  214. func getTimeRange(startDate, endDate string) (start, end time.Time) {
  215. loc, _ := time.LoadLocation("Local")
  216. startDateTime := startDate + " 00:00:00"
  217. endDateTime := endDate + " 23:59:59"
  218. start, _ = time.ParseInLocation("2006-01-02 15:04:05", startDateTime, loc)
  219. end, _ = time.ParseInLocation("2006-01-02 15:04:05", endDateTime, loc)
  220. return
  221. }
  222. // 处理报表query条件
  223. func handleReportQuery(query map[string]interface{}) map[string]interface{} {
  224. // 条件处理
  225. query["status"] = "complete"
  226. if _supplierId, ok := query["supplierId"]; ok {
  227. delete(query, "supplierId")
  228. supplierId, _ := primitive.ObjectIDFromHex(_supplierId.(string))
  229. if !supplierId.IsZero() {
  230. query["supplierId"] = supplierId
  231. }
  232. }
  233. if _timeRange, ok := query["timeRange"]; ok {
  234. timeRange, _ := _timeRange.([]interface{})
  235. if len(timeRange) == 2 {
  236. start, end := getTimeRange(timeRange[0].(string), timeRange[1].(string))
  237. query["completeTime"] = bson.M{"$gte": start, "$lte": end}
  238. }
  239. delete(query, "timeRange")
  240. }
  241. if _planIds, ok := query["planIds"]; ok {
  242. if len(_planIds.([]interface{})) > 0 {
  243. planQuery := bson.A{}
  244. for _, _planId := range _planIds.([]interface{}) {
  245. planId, _ := primitive.ObjectIDFromHex(_planId.(string))
  246. planQuery = append(planQuery, bson.M{"planId": planId})
  247. }
  248. query["$or"] = planQuery
  249. }
  250. delete(query, "planIds")
  251. }
  252. return query
  253. }
  254. // 获取公司名字
  255. func getCompanyName(apictx *ApiSession) string {
  256. companyName := "中鱼互动"
  257. info := model.Setting{}
  258. found, _ := repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  259. CollectName: "infos",
  260. }, &info)
  261. if found {
  262. if info.CompanyName != "" {
  263. companyName = info.CompanyName
  264. }
  265. }
  266. return companyName
  267. }
  268. const (
  269. letterIdBits = 6
  270. letterIdMask = 1<<letterIdBits - 1
  271. letterIdMax = 63 / letterIdBits
  272. letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  273. )
  274. var src = rand.NewSource(time.Now().UnixNano())
  275. func randName(n int) string {
  276. b := make([]byte, n)
  277. for i, cache, remain := n-1, src.Int63(), letterIdMax; i >= 0; {
  278. if remain == 0 {
  279. cache, remain = src.Int63(), letterIdMax
  280. }
  281. if idx := int(cache & letterIdMask); idx < len(letters) {
  282. b[i] = letters[idx]
  283. i--
  284. }
  285. cache >>= letterIdBits
  286. remain--
  287. }
  288. return *(*string)(unsafe.Pointer(&b))
  289. }