bill-produce.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  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. "strings"
  10. "time"
  11. "github.com/gin-gonic/gin"
  12. "github.com/xuri/excelize/v2"
  13. "go.mongodb.org/mongo-driver/bson"
  14. "go.mongodb.org/mongo-driver/bson/primitive"
  15. )
  16. // 单据管理
  17. func BillProduce(r *GinRouter) {
  18. // 创建单据
  19. r.POSTJWT("/bill/produce/create", CreateProduceBill)
  20. // 获取单据详情
  21. r.GETJWT("/bill/produce/detail/:id", GetProduceBill)
  22. // 获取单据列表
  23. r.GETJWT("/bill/produce/list", GetProduceBills)
  24. // 更新单据
  25. r.POSTJWT("/bill/produce/update", UpdateProduceBill)
  26. // 删除单据
  27. r.POSTJWT("/bill/produce/delete/:id", DelProduceBill)
  28. //下载单据
  29. r.GETJWT("/bill/produce/download", DownProduceBill)
  30. // 审核单据
  31. r.POSTJWT("/bill/produce/review/:id", ProduceReview)
  32. }
  33. // 审核单据
  34. func ProduceReview(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  35. _id := c.Param("id")
  36. id, err := primitive.ObjectIDFromHex(_id)
  37. if err != nil {
  38. return nil, errors.New("id错误")
  39. }
  40. userId, err := primitive.ObjectIDFromHex(apictx.User.Parent)
  41. if err != nil {
  42. return nil, errors.New("用户异常")
  43. }
  44. user, err := getUserById(apictx, userId)
  45. if err != nil {
  46. return nil, errors.New("查找用户失败")
  47. }
  48. if !isManager(user.Roles) {
  49. return nil, errors.New("该用户没有权限")
  50. }
  51. // 查询单据获取已有的签字
  52. bill := model.ProduceBill{}
  53. repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  54. CollectName: repo.CollectionBillProduce,
  55. Query: repo.Map{"_id": id, "reviewed": 1},
  56. }, &bill)
  57. signs := make([]primitive.ObjectID, 0)
  58. if len(bill.SignUsers) > 0 {
  59. // 如果自己已存在该集合中了
  60. for _, signUser := range bill.SignUsers {
  61. if signUser == userId {
  62. return nil, errors.New("该单据您已审核过了")
  63. }
  64. }
  65. signs = bill.SignUsers
  66. }
  67. // 更改状态为已审核 并签字
  68. signs = append(signs, userId)
  69. produce := model.ProduceBill{
  70. Reviewed: 1,
  71. UpdateTime: time.Now(),
  72. SignUsers: signs,
  73. }
  74. // return repo.RepoUpdateSetDoc(apictx.CreateRepoCtx(), repo.CollectionBillProduce, _id, &produce)
  75. return repo.RepoUpdateSetDoc1(apictx.CreateRepoCtx(), repo.CollectionBillProduce, _id, &produce, &repo.RecordLogReq{
  76. Path: c.Request.URL.Path,
  77. UserInfo: user,
  78. TargetId: _id,
  79. Type: "reviewed",
  80. })
  81. }
  82. // 创建生产加工单据
  83. func CreateProduceBill(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  84. bill := &model.ProduceBill{}
  85. err := c.ShouldBindJSON(bill)
  86. if err != nil {
  87. fmt.Println(err)
  88. return nil, errors.New("参数错误!")
  89. }
  90. ctx := apictx.CreateRepoCtx()
  91. if bill.PackId.Hex() == "" {
  92. return nil, errors.New("包装产品id为空")
  93. }
  94. if bill.PlanId.Hex() == "" {
  95. return nil, errors.New("生产计划id为空")
  96. }
  97. if bill.Type == "" {
  98. return nil, errors.New("类型为空")
  99. }
  100. bill.SerialNumber, err = generateSerial(c, apictx, bill.Type)
  101. if err != nil {
  102. return nil, err
  103. }
  104. bill.Status = "created"
  105. if bill.Reviewed == 0 {
  106. bill.Reviewed = -1
  107. }
  108. bill.CreateTime = time.Now()
  109. bill.UpdateTime = time.Now()
  110. notAck := false
  111. _isSend := false
  112. bill.IsSend = &_isSend
  113. bill.IsAck = &notAck
  114. // 制单人数据
  115. userId, _ := primitive.ObjectIDFromHex(apictx.User.Parent)
  116. fmt.Println("userId:", apictx.User.Parent)
  117. userInfo := &model.UserSmaple{}
  118. if !userId.IsZero() {
  119. user, err := getUserById(apictx, userId)
  120. userInfo = user
  121. if err == nil {
  122. bill.UserName = user.Name
  123. bill.UserId = userId
  124. }
  125. }
  126. result, err := repo.RepoAddDoc1(ctx, repo.CollectionBillProduce, &bill, &repo.RecordLogReq{
  127. Path: c.Request.URL.Path,
  128. UserInfo: userInfo,
  129. TargetId: "",
  130. Type: "created",
  131. })
  132. return result, err
  133. }
  134. // 获取单据信息
  135. func GetProduceBill(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  136. billId := c.Param("id")
  137. id, err := primitive.ObjectIDFromHex(billId)
  138. if err != nil {
  139. return nil, errors.New("非法id")
  140. }
  141. var bill model.ProduceBill
  142. option := &repo.DocSearchOptions{
  143. CollectName: repo.CollectionBillProduce,
  144. Query: repo.Map{"_id": id},
  145. }
  146. found, err := repo.RepoSeachDoc(apictx.CreateRepoCtx(), option, &bill)
  147. if !found || err != nil {
  148. log.Info(err)
  149. return nil, errors.New("数据未找到")
  150. }
  151. return bill, nil
  152. }
  153. // 获取单据列表
  154. func GetProduceBills(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  155. page, size, query := UtilQueryPageSize(c)
  156. sort := "createTime"
  157. if v, ok := query["sort"]; ok {
  158. if _sort, ok := v.(string); ok {
  159. if len(_sort) > 0 {
  160. sort = _sort
  161. }
  162. }
  163. delete(query, "sort")
  164. }
  165. option := &repo.PageSearchOptions{
  166. CollectName: repo.CollectionBillProduce,
  167. Query: makeBillQuery(query),
  168. Page: page,
  169. Size: size,
  170. Sort: bson.M{sort: -1},
  171. }
  172. return repo.RepoPageSearch(apictx.CreateRepoCtx(), option)
  173. }
  174. // 更新单据
  175. func UpdateProduceBill(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  176. var bill model.ProduceBill
  177. err := c.ShouldBindJSON(&bill)
  178. if err != nil {
  179. fmt.Println(err)
  180. return nil, errors.New("参数错误")
  181. }
  182. if bill.Id.Hex() == "" {
  183. return nil, errors.New("id的为空")
  184. }
  185. // 如果更改类型 重新生成订单号
  186. if len(bill.Type) > 0 {
  187. billType, err := searchBillTypeById(apictx, repo.CollectionBillProduce, bill.Id)
  188. if err != nil {
  189. return nil, err
  190. }
  191. if billType != bill.Type {
  192. bill.SerialNumber, err = generateSerial(c, apictx, bill.Type)
  193. if err != nil {
  194. return nil, err
  195. }
  196. }
  197. }
  198. userId, _ := primitive.ObjectIDFromHex(apictx.User.ID)
  199. user, _ := getUserById(apictx, userId)
  200. logType := "update"
  201. // 更改状态
  202. ok, err := isCompareStatus(apictx, repo.CollectionBillProduce, bill.Id, bill.Status)
  203. if err != nil {
  204. return nil, err
  205. }
  206. if bill.Status == "complete" {
  207. if !ok {
  208. bill.CompleteTime = time.Now()
  209. logType = "complete"
  210. }
  211. }
  212. if bill.Status == "deprecated" {
  213. if !ok {
  214. logType = "deprecated"
  215. }
  216. }
  217. if bill.Remark == "" {
  218. bill.Remark = " "
  219. }
  220. if bill.SupplierRemark == "" {
  221. bill.SupplierRemark = " "
  222. }
  223. // 修改单据信息需要同步plan中stage项
  224. if len(bill.Produces) > 0 {
  225. // 获取当前订单供应商id
  226. // 对比供应商是否变化,变化了就同步计划中的供应商
  227. currProduce := &model.ProduceBill{}
  228. repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  229. CollectName: repo.CollectionBillProduce,
  230. Query: repo.Map{"_id": bill.Id},
  231. Project: []string{"supplierId"},
  232. }, currProduce)
  233. var supplierInfo *model.Supplier
  234. if currProduce.SupplierId != bill.SupplierId {
  235. // 查询更改后的supplierInfo
  236. supplierInfo = &model.Supplier{}
  237. repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  238. CollectName: repo.CollectionSupplier,
  239. Query: repo.Map{"_id": bill.SupplierId},
  240. }, supplierInfo)
  241. }
  242. idStatges := make(map[string]*UpdateBilltoStageReq)
  243. for _, produce := range bill.Produces {
  244. if len(produce.Id) == 0 {
  245. continue
  246. }
  247. ps := strings.Split(produce.PrintSize, "*")
  248. width := 0
  249. height := 0
  250. if len(ps) == 2 {
  251. height, _ = strconv.Atoi(ps[0])
  252. width, _ = strconv.Atoi(ps[1])
  253. }
  254. idStatges[produce.Id] = &UpdateBilltoStageReq{
  255. BillType: "produce",
  256. IsChangePrice2: bill.IsLam,
  257. SupplierInfo: supplierInfo,
  258. Norm: produce.Norm,
  259. Price2: produce.Price2,
  260. OrderCount: produce.OrderCount,
  261. OrderPrice: produce.OrderPrice,
  262. ConfirmCount: produce.ConfirmCount,
  263. Remark: produce.Remark,
  264. Width: width,
  265. Height: height,
  266. DeliveryTime: produce.DeliveryTime,
  267. }
  268. }
  269. _, err := updateBilltoStage(c, bill.PlanId, idStatges, apictx)
  270. if err != nil {
  271. fmt.Println(err)
  272. return nil, errors.New("该单据改动同步到产品失败")
  273. }
  274. fmt.Println("单据同步到产品,planId:", bill.PlanId)
  275. }
  276. bill.UpdateTime = time.Now()
  277. // return repo.RepoUpdateSetDoc(apictx.CreateRepoCtx(), repo.CollectionBillProduce, bill.Id.Hex(), &bill)
  278. return repo.RepoUpdateSetDoc1(apictx.CreateRepoCtx(), repo.CollectionBillProduce, bill.Id.Hex(), &bill, &repo.RecordLogReq{
  279. Path: c.Request.URL.Path,
  280. UserInfo: user,
  281. TargetId: bill.Id.Hex(),
  282. Type: logType,
  283. })
  284. }
  285. // 删除单据
  286. func DelProduceBill(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  287. billId := c.Param("id")
  288. if billId == "" {
  289. return nil, errors.New("id为空")
  290. }
  291. return repo.RepoDeleteDoc(apictx.CreateRepoCtx(), repo.CollectionBillProduce, billId)
  292. }
  293. func DownProduceBill(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  294. billId := c.Query("id")
  295. isPdf := c.Query("isPdf")
  296. if len(billId) < 1 {
  297. return nil, fmt.Errorf("id不能为空")
  298. }
  299. id, err := primitive.ObjectIDFromHex(billId)
  300. if err != nil {
  301. return nil, errors.New("非法id")
  302. }
  303. var bill model.ProduceBill
  304. option := &repo.DocSearchOptions{
  305. CollectName: repo.CollectionBillProduce,
  306. Query: repo.Map{"_id": id},
  307. }
  308. found, err := repo.RepoSeachDoc(apictx.CreateRepoCtx(), option, &bill)
  309. if !found || err != nil {
  310. log.Info(err)
  311. return nil, errors.New("数据未找到")
  312. }
  313. f := excelize.NewFile()
  314. // Create a new sheet.
  315. index := f.NewSheet("Sheet1")
  316. f.SetActiveSheet(index)
  317. f.SetDefaultFont("宋体")
  318. billExcel := NewProduceBill(f)
  319. // 获取已审核的签名数据
  320. if bill.Reviewed == 1 {
  321. if len(bill.SignUsers) > 0 {
  322. signs := []*model.Signature{}
  323. repo.RepoDocsSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
  324. CollectName: repo.CollectionSignature,
  325. Query: repo.Map{"_id": bson.M{"$in": bill.SignUsers}},
  326. Sort: bson.M{"sort": 1}, // 升序
  327. }, &signs)
  328. billExcel.Signatures = signs
  329. }
  330. }
  331. // 覆膜、打印与其他有来纸尺寸类型互斥
  332. // 如果是这两种类型,不管isPaper的值,都需要有自己的表格
  333. if bill.IsLam || bill.IsPrint {
  334. bill.IsPaper = false
  335. }
  336. billExcel.Content = &bill
  337. billExcel.IsPdf = isPdf
  338. companyName := getCompanyName(apictx)
  339. billExcel.Title = fmt.Sprintf("%s加工单", companyName)
  340. //设置对应的数据
  341. billExcel.Draws()
  342. // 下载为pdf
  343. if isPdf == "true" {
  344. buf, _ := f.WriteToBuffer()
  345. res, err := excelToPdf(buf, apictx.Svc.Conf.PdfApiAddr)
  346. if err != nil {
  347. return nil, errors.New("转化pdf失败")
  348. }
  349. defer res.Body.Close()
  350. c.Header("Content-Type", "application/octet-stream")
  351. c.Header("Content-Disposition", "attachment; filename="+"bill.pdf")
  352. c.Header("Content-Transfer-Encoding", "binary")
  353. err = res.Write(c.Writer)
  354. if err != nil {
  355. return nil, err
  356. }
  357. return nil, nil
  358. }
  359. c.Header("Content-Type", "application/octet-stream")
  360. c.Header("Content-Disposition", "attachment; filename="+"bill.xlsx")
  361. c.Header("Content-Transfer-Encoding", "binary")
  362. err = f.Write(c.Writer)
  363. if err != nil {
  364. return nil, err
  365. }
  366. return nil, nil
  367. }