utils.go 9.9 KB

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