utils.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package api
  2. import (
  3. "box-cost/db/model"
  4. "box-cost/db/repo"
  5. "bytes"
  6. "fmt"
  7. "net/http"
  8. "time"
  9. "github.com/thecodingmachine/gotenberg-go-client/v7"
  10. "go.mongodb.org/mongo-driver/bson"
  11. "go.mongodb.org/mongo-driver/bson/primitive"
  12. )
  13. func generateSerial(ctx *ApiSession, typeName string) (serial string, err error) {
  14. // 获取类型
  15. cate := &model.Category{}
  16. found, err := repo.RepoSeachDoc(ctx.CreateRepoCtx(), &repo.DocSearchOptions{
  17. CollectName: "cates",
  18. Project: []string{"letterName"},
  19. Query: repo.Map{"name": typeName},
  20. Sort: bson.M{"_id": -1},
  21. }, cate)
  22. if !found || err != nil {
  23. return "", fmt.Errorf("未找到该类型")
  24. }
  25. // 自增器 increment index加1
  26. increment := &model.Increment{}
  27. found, _ = repo.RepoSeachDoc(ctx.CreateRepoCtx(), &repo.DocSearchOptions{
  28. CollectName: repo.CollectionIncrement,
  29. Query: repo.Map{"type": cate.LetterName},
  30. Project: []string{"index"},
  31. Sort: bson.M{"_id": -1},
  32. }, increment)
  33. if !found {
  34. repo.RepoAddDoc(ctx.CreateRepoCtx(), repo.CollectionIncrement, &model.Increment{
  35. Type: cate.LetterName,
  36. Index: 1,
  37. })
  38. return fmt.Sprintf("%s-%06d", cate.LetterName, 1), nil
  39. }
  40. index := increment.Index + 1
  41. repo.RepoUpdateSetDoc(ctx.CreateRepoCtx(), repo.CollectionIncrement, increment.Id.Hex(), &model.Increment{Index: index})
  42. // 拼接为序号
  43. return fmt.Sprintf("%s-%06d", cate.LetterName, index), nil
  44. }
  45. func searchBillTypeById(ctx *ApiSession, collectName string, id primitive.ObjectID) (string, error) {
  46. found, curbill := repo.RepoSeachDocMap(ctx.CreateRepoCtx(), &repo.DocSearchOptions{
  47. CollectName: collectName,
  48. Project: []string{"type"},
  49. Query: repo.Map{"_id": id},
  50. Sort: bson.M{"_id": -1},
  51. })
  52. if !found {
  53. return "", fmt.Errorf("未找到该类型")
  54. }
  55. return curbill["type"].(string), nil
  56. }
  57. func excelToPdf(formBody *bytes.Buffer, pdfHost string) (*http.Response, error) {
  58. httpClient := &http.Client{
  59. Timeout: time.Duration(5) * time.Second,
  60. }
  61. client := &gotenberg.Client{Hostname: pdfHost, HTTPClient: httpClient}
  62. doc, err := gotenberg.NewDocumentFromBytes("foo.xlsx", formBody.Bytes())
  63. if err != nil {
  64. fmt.Println("fdf:", err)
  65. return nil, err
  66. }
  67. req := gotenberg.NewOfficeRequest(doc)
  68. req.Landscape(true)
  69. return client.Post(req)
  70. }