utils.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package api
  2. import (
  3. "box-cost/db/model"
  4. "box-cost/db/repo"
  5. "fmt"
  6. "go.mongodb.org/mongo-driver/bson"
  7. "go.mongodb.org/mongo-driver/bson/primitive"
  8. )
  9. func generateSerial(ctx *ApiSession, typeName string) (serial string, err error) {
  10. // 获取类型
  11. cate := &model.Category{}
  12. found, err := repo.RepoSeachDoc(ctx.CreateRepoCtx(), &repo.DocSearchOptions{
  13. CollectName: "cates",
  14. Project: []string{"letterName"},
  15. Query: repo.Map{"name": typeName},
  16. Sort: bson.M{"_id": -1},
  17. }, cate)
  18. if !found || err != nil {
  19. return "", fmt.Errorf("未找到该类型")
  20. }
  21. // 自增器 increment index加1
  22. increment := &model.Increment{}
  23. found, _ = repo.RepoSeachDoc(ctx.CreateRepoCtx(), &repo.DocSearchOptions{
  24. CollectName: repo.CollectionIncrement,
  25. Query: repo.Map{"type": cate.LetterName},
  26. Project: []string{"index"},
  27. Sort: bson.M{"_id": -1},
  28. }, increment)
  29. if !found {
  30. repo.RepoAddDoc(ctx.CreateRepoCtx(), repo.CollectionIncrement, &model.Increment{
  31. Type: cate.LetterName,
  32. Index: 1,
  33. })
  34. return fmt.Sprintf("%s-%06d", cate.LetterName, 1), nil
  35. }
  36. index := increment.Index + 1
  37. repo.RepoUpdateSetDoc(ctx.CreateRepoCtx(), repo.CollectionIncrement, increment.Id.Hex(), &model.Increment{Index: index})
  38. // 拼接为序号
  39. return fmt.Sprintf("%s-%06d", cate.LetterName, index), nil
  40. }
  41. func searchBillTypeById(ctx *ApiSession, collectName string, id primitive.ObjectID) (string, error) {
  42. found, curbill := repo.RepoSeachDocMap(ctx.CreateRepoCtx(), &repo.DocSearchOptions{
  43. CollectName: collectName,
  44. Project: []string{"type"},
  45. Query: repo.Map{"_id": id},
  46. Sort: bson.M{"_id": -1},
  47. })
  48. if !found {
  49. return "", fmt.Errorf("未找到该类型")
  50. }
  51. return curbill["type"].(string), nil
  52. }