utils.go 9.0 KB

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