bill.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  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. sort := "createTime"
  200. if v, ok := query["sort"]; ok {
  201. if _sort, ok := v.(string); ok {
  202. if len(_sort) > 0 {
  203. sort = _sort
  204. }
  205. }
  206. delete(query, "sort")
  207. }
  208. option := &repo.PageSearchOptions{
  209. CollectName: repo.CollectionBillPurchase,
  210. Query: makeBillQuery(query),
  211. Page: page,
  212. Size: size,
  213. Sort: bson.M{sort: -1},
  214. }
  215. return repo.RepoPageSearch(apictx.CreateRepoCtx(), option)
  216. }
  217. func DownLoadBills(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  218. billId := c.Query("id")
  219. isPdf := c.Query("isPdf")
  220. if len(billId) < 1 {
  221. return nil, fmt.Errorf("id不能为空")
  222. }
  223. id, err := primitive.ObjectIDFromHex(billId)
  224. if err != nil {
  225. return nil, errors.New("非法id")
  226. }
  227. var bill model.PurchaseBill
  228. option := &repo.DocSearchOptions{
  229. CollectName: repo.CollectionBillPurchase,
  230. Query: repo.Map{"_id": id},
  231. }
  232. found, err := repo.RepoSeachDoc(apictx.CreateRepoCtx(), option, &bill)
  233. if !found || err != nil {
  234. log.Info(err)
  235. return nil, errors.New("数据未找到")
  236. }
  237. f := excelize.NewFile()
  238. index := f.NewSheet("Sheet1")
  239. f.SetActiveSheet(index)
  240. f.SetDefaultFont("宋体")
  241. var billExcel *PurchaseBillExcel
  242. if len(bill.Paper) > 0 {
  243. billExcel = NewPurchaseBill(f)
  244. }
  245. if billExcel == nil {
  246. return nil, errors.New("数据未找到")
  247. }
  248. // 获取已审核的签名数据
  249. if bill.Reviewed == 1 {
  250. if len(bill.SignUsers) > 0 {
  251. signs := []*model.Signature{}
  252. repo.RepoDocsSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
  253. CollectName: repo.CollectionSignature,
  254. Query: repo.Map{"_id": bson.M{"$in": bill.SignUsers}},
  255. Sort: bson.M{"sort": 1}, // 升序
  256. }, &signs)
  257. billExcel.Signatures = signs
  258. }
  259. }
  260. billExcel.Content = &bill
  261. billExcel.IsPdf = isPdf
  262. companyName := getCompanyName(apictx)
  263. billExcel.Title = fmt.Sprintf("%s原材料采购单", companyName)
  264. //设置对应的数据
  265. billExcel.Draws()
  266. // 下载为pdf
  267. if isPdf == "true" {
  268. buf, _ := f.WriteToBuffer()
  269. res, err := excelToPdf(buf, apictx.Svc.Conf.PdfApiAddr)
  270. if err != nil {
  271. fmt.Println(err)
  272. return nil, errors.New("转化pdf失败")
  273. }
  274. defer res.Body.Close()
  275. c.Header("Content-Type", "application/octet-stream")
  276. c.Header("Content-Disposition", "attachment; filename="+"bill.pdf")
  277. c.Header("Content-Transfer-Encoding", "binary")
  278. err = res.Write(c.Writer)
  279. if err != nil {
  280. return nil, err
  281. }
  282. return nil, nil
  283. }
  284. // 下载为execl
  285. c.Header("Content-Type", "application/octet-stream")
  286. c.Header("Content-Disposition", "attachment; filename="+"bill.xlsx")
  287. c.Header("Content-Transfer-Encoding", "binary")
  288. err = f.Write(c.Writer)
  289. if err != nil {
  290. return nil, err
  291. }
  292. return nil, nil
  293. }
  294. // 更新单据
  295. func UpdateBill(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  296. var bill model.PurchaseBill
  297. err := c.ShouldBindJSON(&bill)
  298. if err != nil {
  299. fmt.Println(err)
  300. return nil, errors.New("参数错误")
  301. }
  302. if bill.Id.Hex() == "" {
  303. return nil, errors.New("id的为空")
  304. }
  305. // 如果更改类型
  306. if len(bill.Type) > 0 {
  307. billType, err := searchBillTypeById(apictx, repo.CollectionBillPurchase, bill.Id)
  308. if err != nil {
  309. return nil, err
  310. }
  311. if billType != bill.Type {
  312. bill.SerialNumber, err = generateSerial(c, apictx, bill.Type)
  313. if err != nil {
  314. return nil, err
  315. }
  316. }
  317. }
  318. userId, _ := primitive.ObjectIDFromHex(apictx.User.ID)
  319. user, _ := getUserById(apictx, userId)
  320. logType := "update"
  321. // 更改状态
  322. ok, err := isCompareStatus(apictx, repo.CollectionBillPurchase, bill.Id, bill.Status)
  323. if err != nil {
  324. return nil, err
  325. }
  326. if bill.Status == "complete" {
  327. if !ok {
  328. bill.CompleteTime = time.Now()
  329. logType = "complete"
  330. }
  331. }
  332. if bill.Status == "deprecated" {
  333. if !ok {
  334. logType = "deprecated"
  335. }
  336. }
  337. if bill.Remark == "" {
  338. bill.Remark = " "
  339. }
  340. if bill.SupplierRemark == "" {
  341. bill.SupplierRemark = " "
  342. }
  343. // 修改单据信息需要同步plan中stage项
  344. if len(bill.Paper) > 0 {
  345. // 获取当前订单供应商id
  346. // 对比供应商是否变化,变化了就同步计划中的供应商
  347. currPurchase := &model.PurchaseBill{}
  348. repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  349. CollectName: repo.CollectionBillPurchase,
  350. Query: repo.Map{"_id": bill.Id},
  351. Project: []string{"supplierId"},
  352. }, currPurchase)
  353. var supplierInfo *model.Supplier
  354. if currPurchase.SupplierId != bill.SupplierId {
  355. // 查询更改后的supplierInfo
  356. supplierInfo = &model.Supplier{}
  357. repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  358. CollectName: repo.CollectionSupplier,
  359. Query: repo.Map{"_id": bill.SupplierId},
  360. }, supplierInfo)
  361. }
  362. units := []string{"元/吨", "元/平方米"}
  363. idStatges := make(map[string]*UpdateBilltoStageReq)
  364. for _, paper := range bill.Paper {
  365. if len(paper.Id) == 0 {
  366. continue
  367. }
  368. width, _ := strconv.Atoi(paper.Width)
  369. Height, _ := strconv.Atoi(paper.Height)
  370. idStatges[paper.Id] = &UpdateBilltoStageReq{
  371. BillType: "purchase",
  372. SupplierInfo: supplierInfo,
  373. Norm: paper.Norm,
  374. Width: width,
  375. Height: Height,
  376. Price2: paper.Price2,
  377. OrderCount: paper.OrderCount,
  378. OrderPrice: paper.OrderPrice,
  379. Remark: paper.Remark,
  380. ConfirmCount: paper.ConfirmCount,
  381. DeliveryTime: paper.DeliveryTime,
  382. IsChangePrice2: isInclude(paper.Price2Unit, units),
  383. }
  384. }
  385. _, err := updateBilltoStage(c, bill.PlanId, idStatges, apictx)
  386. if err != nil {
  387. fmt.Println(err)
  388. return nil, errors.New("该单据改动同步到产品失败")
  389. }
  390. fmt.Println("单据同步到产品,planId:", bill.PlanId)
  391. }
  392. bill.UpdateTime = time.Now()
  393. // return repo.RepoUpdateSetDoc(apictx.CreateRepoCtx(), repo.CollectionBillPurchase, bill.Id.Hex(), &bill)
  394. return repo.RepoUpdateSetDoc1(apictx.CreateRepoCtx(), repo.CollectionBillPurchase, bill.Id.Hex(), &bill, &repo.RecordLogReq{
  395. Path: c.Request.URL.Path,
  396. UserInfo: user,
  397. TargetId: bill.Id.Hex(),
  398. Type: logType,
  399. })
  400. }
  401. func isInclude(str1 string, arr []string) bool {
  402. for _, a := range arr {
  403. if str1 == a {
  404. return true
  405. }
  406. }
  407. return false
  408. }
  409. // 删除单据
  410. func DelBill(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  411. billId := c.Param("id")
  412. if billId == "" {
  413. return nil, errors.New("id为空")
  414. }
  415. return repo.RepoDeleteDoc(apictx.CreateRepoCtx(), repo.CollectionBillPurchase, billId)
  416. }