bill.go 12 KB

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