bill-produce.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. package api
  2. import (
  3. "box-cost/db/model"
  4. "box-cost/db/repo"
  5. "box-cost/log"
  6. "errors"
  7. "fmt"
  8. "strconv"
  9. "time"
  10. "github.com/gin-gonic/gin"
  11. "github.com/xuri/excelize/v2"
  12. "go.mongodb.org/mongo-driver/bson"
  13. "go.mongodb.org/mongo-driver/bson/primitive"
  14. )
  15. // 单据管理
  16. func BillProduce(r *GinRouter) {
  17. // 创建单据
  18. r.POST("/bill/produce/create", CreateProduceBill)
  19. // 获取单据详情
  20. r.GET("/bill/produce/detail/:id", GetProduceBill)
  21. // 获取单据列表
  22. r.GET("/bill/produce/list", GetProduceBills)
  23. // 更新单据
  24. r.POST("/bill/produce/update", UpdateProduceBill)
  25. // 删除单据
  26. r.POST("/bill/produce/delete/:id", DelProduceBill)
  27. //下载单据
  28. r.GET("/bill/produce/download", DownProduceBill)
  29. // 审核单据
  30. r.POSTJWT("/bill/produce/review/:id", ProduceReview)
  31. }
  32. // 审核单据
  33. func ProduceReview(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  34. _id := c.Param("id")
  35. id, err := primitive.ObjectIDFromHex(_id)
  36. if err != nil {
  37. return nil, errors.New("id错误")
  38. }
  39. userId, err := primitive.ObjectIDFromHex(apictx.User.Parent)
  40. if err != nil {
  41. return nil, errors.New("用户异常")
  42. }
  43. user, err := getUserById(apictx, userId)
  44. if err != nil {
  45. return nil, errors.New("查找用户失败")
  46. }
  47. if !isManager(user.Roles) {
  48. return nil, errors.New("该用户没有权限")
  49. }
  50. // 查询单据获取已有的签字
  51. bill := model.ProduceBill{}
  52. repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  53. CollectName: repo.CollectionBillProduce,
  54. Query: repo.Map{"_id": id, "reviewed": 1},
  55. }, &bill)
  56. signs := make([]primitive.ObjectID, 0)
  57. if len(bill.SignUsers) > 0 {
  58. // 如果自己已存在该集合中了
  59. for _, signUser := range bill.SignUsers {
  60. if signUser == userId {
  61. return nil, errors.New("该单据您已审核过了")
  62. }
  63. }
  64. signs = bill.SignUsers
  65. }
  66. // 更改状态为已审核 并签字
  67. signs = append(signs, userId)
  68. produce := model.ProduceBill{
  69. Reviewed: 1,
  70. UpdateTime: time.Now(),
  71. SignUsers: signs,
  72. }
  73. return repo.RepoUpdateSetDoc(apictx.CreateRepoCtx(), repo.CollectionBillProduce, _id, &produce)
  74. }
  75. // 创建生产加工单据
  76. func CreateProduceBill(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  77. bill := &model.ProduceBill{}
  78. err := c.ShouldBindJSON(bill)
  79. if err != nil {
  80. fmt.Println(err)
  81. return nil, errors.New("参数错误!")
  82. }
  83. ctx := apictx.CreateRepoCtx()
  84. if bill.PackId.Hex() == "" {
  85. return nil, errors.New("包装产品id为空")
  86. }
  87. if bill.PlanId.Hex() == "" {
  88. return nil, errors.New("生产计划id为空")
  89. }
  90. if bill.Type == "" {
  91. return nil, errors.New("类型为空")
  92. }
  93. bill.SerialNumber, err = generateSerial(apictx, bill.Type)
  94. if err != nil {
  95. return nil, err
  96. }
  97. bill.Status = "created"
  98. if bill.Reviewed == 0 {
  99. bill.Reviewed = -1
  100. }
  101. bill.CreateTime = time.Now()
  102. bill.UpdateTime = time.Now()
  103. // 制单人数据
  104. userId, _ := primitive.ObjectIDFromHex(apictx.User.Parent)
  105. if !userId.IsZero() {
  106. user, err := getUserById(apictx, userId)
  107. if err != nil {
  108. bill.UserName = user.Name
  109. bill.UserId = userId
  110. }
  111. }
  112. result, err := repo.RepoAddDoc(ctx, repo.CollectionBillProduce, &bill)
  113. return result, err
  114. }
  115. // 获取单据信息
  116. func GetProduceBill(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  117. billId := c.Param("id")
  118. id, err := primitive.ObjectIDFromHex(billId)
  119. if err != nil {
  120. return nil, errors.New("非法id")
  121. }
  122. var bill model.ProduceBill
  123. option := &repo.DocSearchOptions{
  124. CollectName: repo.CollectionBillProduce,
  125. Query: repo.Map{"_id": id},
  126. }
  127. found, err := repo.RepoSeachDoc(apictx.CreateRepoCtx(), option, &bill)
  128. if !found || err != nil {
  129. log.Info(err)
  130. return nil, errors.New("数据未找到")
  131. }
  132. return bill, nil
  133. }
  134. // 获取单据列表
  135. func GetProduceBills(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  136. page, size, query := UtilQueryPageSize(c)
  137. if query["packId"] != nil {
  138. query["packId"], _ = primitive.ObjectIDFromHex(query["packId"].(string))
  139. }
  140. if query["planId"] != nil {
  141. query["planId"], _ = primitive.ObjectIDFromHex(query["planId"].(string))
  142. }
  143. // 时间范围查询
  144. // createTime 选中的当天时间
  145. st, ok1 := query["startTime"]
  146. delete(query, "startTime")
  147. et, ok2 := query["endTime"]
  148. delete(query, "endTime")
  149. if ok1 && ok2 {
  150. startTime := st.(string)
  151. endTime := et.(string)
  152. start, end := getTimeRange(startTime, endTime)
  153. query["createTime"] = bson.M{"$gte": start, "$lte": end}
  154. }
  155. option := &repo.PageSearchOptions{
  156. CollectName: repo.CollectionBillProduce,
  157. Query: query,
  158. Page: page,
  159. Size: size,
  160. Sort: bson.M{"createTime": -1},
  161. }
  162. return repo.RepoPageSearch(apictx.CreateRepoCtx(), option)
  163. }
  164. // 更新单据
  165. func UpdateProduceBill(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  166. var bill model.ProduceBill
  167. err := c.ShouldBindJSON(&bill)
  168. if err != nil {
  169. return nil, errors.New("参数错误")
  170. }
  171. if bill.Id.Hex() == "" {
  172. return nil, errors.New("id的为空")
  173. }
  174. billType, err := searchBillTypeById(apictx, repo.CollectionBillProduce, bill.Id)
  175. if err != nil {
  176. return nil, err
  177. }
  178. // 如果更改类型
  179. if billType != bill.Type {
  180. bill.SerialNumber, err = generateSerial(apictx, bill.Type)
  181. if err != nil {
  182. return nil, err
  183. }
  184. }
  185. bill.UpdateTime = time.Now()
  186. result, err := repo.RepoUpdateSetDoc(apictx.CreateRepoCtx(), repo.CollectionBillProduce, bill.Id.Hex(), &bill)
  187. // 计算结算价格
  188. if bill.Status == "complete" {
  189. bill.CompleteTime = time.Now()
  190. // 计算结算数量和结算金额
  191. produce := &model.ProduceBill{}
  192. repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  193. CollectName: repo.CollectionBillProduce,
  194. Query: repo.Map{"_id": bill.Id},
  195. }, produce)
  196. if len(produce.Produces) > 0 {
  197. // 取数组最后一个元素的下单数为整个流程结算的基础数
  198. last := produce.Produces[len(produce.Produces)-1]
  199. baseSet := last.ConfirmCount
  200. baseNumer := baseSet * last.BatchSize
  201. for _, pd := range produce.Produces {
  202. pd.SetCount = baseNumer / pd.BatchSize
  203. setAmount := float64(pd.SetCount) * pd.Price
  204. pd.SetAmount, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", setAmount), 64)
  205. }
  206. }
  207. repo.RepoUpdateSetDoc(apictx.CreateRepoCtx(), repo.CollectionBillProduce, bill.Id.Hex(), produce)
  208. }
  209. return result, err
  210. }
  211. // 删除单据
  212. func DelProduceBill(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  213. billId := c.Param("id")
  214. if billId == "" {
  215. return nil, errors.New("id为空")
  216. }
  217. return repo.RepoDeleteDoc(apictx.CreateRepoCtx(), repo.CollectionBillProduce, billId)
  218. }
  219. func DownProduceBill(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  220. billId := c.Query("id")
  221. isPdf := c.Query("isPdf")
  222. if len(billId) < 1 {
  223. return nil, fmt.Errorf("id不能为空")
  224. }
  225. id, err := primitive.ObjectIDFromHex(billId)
  226. if err != nil {
  227. return nil, errors.New("非法id")
  228. }
  229. var bill model.ProduceBill
  230. option := &repo.DocSearchOptions{
  231. CollectName: repo.CollectionBillProduce,
  232. Query: repo.Map{"_id": id},
  233. }
  234. found, err := repo.RepoSeachDoc(apictx.CreateRepoCtx(), option, &bill)
  235. if !found || err != nil {
  236. log.Info(err)
  237. return nil, errors.New("数据未找到")
  238. }
  239. f := excelize.NewFile()
  240. // Create a new sheet.
  241. index := f.NewSheet("Sheet1")
  242. f.SetActiveSheet(index)
  243. f.SetDefaultFont("宋体")
  244. billExcel := NewProduceBill(f)
  245. // 获取已审核的签名数据
  246. if bill.Reviewed == 1 {
  247. if len(bill.SignUsers) > 0 {
  248. signs := []*model.Signature{}
  249. repo.RepoDocsSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
  250. CollectName: repo.CollectionSignature,
  251. Query: repo.Map{"_id": bson.M{"$in": bill.SignUsers}},
  252. Sort: bson.M{"sort": 1}, // 升序
  253. }, &signs)
  254. billExcel.Signatures = signs
  255. }
  256. }
  257. billExcel.Content = &bill
  258. companyName := getCompanyName(apictx)
  259. billExcel.Title = fmt.Sprintf("%s加工单", companyName)
  260. //设置对应的数据
  261. billExcel.Draws()
  262. // 下载为pdf
  263. if isPdf == "true" {
  264. buf, _ := f.WriteToBuffer()
  265. res, err := excelToPdf(buf, apictx.Svc.Conf.PdfApiAddr)
  266. if err != nil {
  267. return nil, errors.New("转化pdf失败")
  268. }
  269. c.Header("Content-Type", "application/octet-stream")
  270. c.Header("Content-Disposition", "attachment; filename="+"bill.pdf")
  271. c.Header("Content-Transfer-Encoding", "binary")
  272. err = res.Write(c.Writer)
  273. if err != nil {
  274. return nil, err
  275. }
  276. return nil, nil
  277. }
  278. c.Header("Content-Type", "application/octet-stream")
  279. c.Header("Content-Disposition", "attachment; filename="+"bill.xlsx")
  280. c.Header("Content-Transfer-Encoding", "binary")
  281. err = f.Write(c.Writer)
  282. if err != nil {
  283. return nil, err
  284. }
  285. return nil, nil
  286. }