bill.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. package api
  2. import (
  3. "box-cost/db/model"
  4. "box-cost/db/repo"
  5. "box-cost/log"
  6. "errors"
  7. "fmt"
  8. "time"
  9. "github.com/gin-gonic/gin"
  10. "github.com/xuri/excelize/v2"
  11. "go.mongodb.org/mongo-driver/bson"
  12. "go.mongodb.org/mongo-driver/bson/primitive"
  13. )
  14. // 单据管理
  15. func Bill(r *GinRouter) {
  16. // 创建单据
  17. r.POSTJWT("/bill/purchase/create", CreateBill)
  18. // 获取单据详情
  19. r.GETJWT("/bill/purchase/detail/:id", GetBill)
  20. // 获取单据列表
  21. r.GETJWT("/bill/purchase/list", GetBills)
  22. // 获取单据列表
  23. r.GETJWT("/bill/purchase/download", DownLoadBills)
  24. // 更新单据
  25. r.POSTJWT("/bill/purchase/update", UpdateBill)
  26. // 删除单据
  27. r.POSTJWT("/bill/purchase/delete/:id", DelBill)
  28. // 审核单据
  29. r.POSTJWT("/bill/purchase/review/:id", PurchaseReview)
  30. // 对账单据
  31. r.POSTJWT("/bill/record", BillRecord)
  32. }
  33. type BillRecordReq struct {
  34. BillType string `json:"billType"`
  35. Id primitive.ObjectID `json:"id"`
  36. Record *bool `json:"record"`
  37. }
  38. // 对账单据
  39. func BillRecord(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  40. var req BillRecordReq
  41. err := c.ShouldBindJSON(&req)
  42. if err != nil {
  43. return nil, errors.New("参数错误!")
  44. }
  45. if req.Id.IsZero() {
  46. return nil, errors.New("id错误!")
  47. }
  48. collection := ""
  49. if req.BillType == "purchase" {
  50. collection = repo.CollectionBillPurchase
  51. } else if req.BillType == "produce" {
  52. collection = repo.CollectionBillProduce
  53. } else if req.BillType == "product" {
  54. collection = repo.CollectionBillProduct
  55. } else {
  56. return nil, errors.New("订单类型错误!")
  57. }
  58. update := bson.M{"isRecord": req.Record}
  59. // return repo.RepoUpdateSetDoc(apictx.CreateRepoCtx(), collection, req.Id.Hex(), &update)
  60. return repo.RepoUpdateSetDoc1(apictx.CreateRepoCtx(), collection, req.Id.Hex(), &update, &repo.RecordLogReq{
  61. Path: c.Request.URL.Path,
  62. UserId: apictx.User.ID,
  63. TargetId: req.Id.Hex(),
  64. })
  65. }
  66. // 审核单据
  67. func PurchaseReview(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  68. _id := c.Param("id")
  69. id, err := primitive.ObjectIDFromHex(_id)
  70. if err != nil {
  71. return nil, errors.New("id错误")
  72. }
  73. userId, err := primitive.ObjectIDFromHex(apictx.User.Parent)
  74. if err != nil {
  75. return nil, errors.New("用户异常")
  76. }
  77. user, err := getUserById(apictx, userId)
  78. if err != nil {
  79. return nil, errors.New("查找用户失败")
  80. }
  81. if !isManager(user.Roles) {
  82. return nil, errors.New("该用户没有权限")
  83. }
  84. // 查询单据获取已有的签字
  85. bill := model.PurchaseBill{}
  86. found, _ := repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  87. CollectName: repo.CollectionBillPurchase,
  88. Query: repo.Map{"_id": id, "reviewed": 1},
  89. }, &bill)
  90. signs := make([]primitive.ObjectID, 0)
  91. if found && len(bill.SignUsers) > 0 {
  92. // 如果自己已存在该集合中了
  93. for _, signUser := range bill.SignUsers {
  94. if signUser == userId {
  95. return nil, errors.New("该单据您已签字审核过了")
  96. }
  97. }
  98. signs = bill.SignUsers
  99. }
  100. // 更改状态为已审核 并签字
  101. signs = append(signs, userId)
  102. purchase := model.PurchaseBill{
  103. Reviewed: 1,
  104. UpdateTime: time.Now(),
  105. SignUsers: signs,
  106. }
  107. // return repo.RepoUpdateSetDoc(apictx.CreateRepoCtx(), repo.CollectionBillPurchase, _id, &purchase)
  108. return repo.RepoUpdateSetDoc1(apictx.CreateRepoCtx(), repo.CollectionBillPurchase, _id, &purchase, &repo.RecordLogReq{
  109. Path: c.Request.URL.Path,
  110. UserId: apictx.User.ID,
  111. TargetId: _id,
  112. })
  113. }
  114. type MatBillReq struct {
  115. Bill *model.PurchaseBill
  116. CompIndex *int
  117. MatIndex *int
  118. //MatKey string //components.0.mats.0.billId
  119. }
  120. // 创建单据
  121. func CreateBill(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  122. req := &model.PurchaseBill{}
  123. err := c.ShouldBindJSON(req)
  124. if err != nil {
  125. fmt.Println(err)
  126. return nil, errors.New("参数错误")
  127. }
  128. ctx := apictx.CreateRepoCtx()
  129. bill := req
  130. if bill.PackId.Hex() == "" {
  131. return nil, errors.New("包装产品id为空")
  132. }
  133. if bill.PlanId.Hex() == "" {
  134. return nil, errors.New("生产计划id为空")
  135. }
  136. if bill.Type == "" {
  137. return nil, errors.New("类型为空")
  138. }
  139. bill.SerialNumber, err = generateSerial(c, apictx, bill.Type)
  140. if err != nil {
  141. return nil, err
  142. }
  143. bill.Status = "created"
  144. if bill.Reviewed == 0 {
  145. bill.Reviewed = -1
  146. }
  147. bill.CreateTime = time.Now()
  148. bill.UpdateTime = time.Now()
  149. notAck := false
  150. bill.IsAck = &notAck
  151. // 制单人数据
  152. userId, _ := primitive.ObjectIDFromHex(apictx.User.Parent)
  153. fmt.Println("userId:", apictx.User.Parent)
  154. if !userId.IsZero() {
  155. user, err := getUserById(apictx, userId)
  156. if err == nil {
  157. bill.UserName = user.Name
  158. bill.UserId = userId
  159. }
  160. }
  161. return repo.RepoAddDoc(ctx, repo.CollectionBillPurchase, &bill)
  162. }
  163. // 获取单据信息
  164. func GetBill(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  165. billId := c.Param("id")
  166. id, err := primitive.ObjectIDFromHex(billId)
  167. if err != nil {
  168. return nil, errors.New("非法id")
  169. }
  170. var bill model.PurchaseBill
  171. option := &repo.DocSearchOptions{
  172. CollectName: repo.CollectionBillPurchase,
  173. Query: repo.Map{"_id": id},
  174. }
  175. found, err := repo.RepoSeachDoc(apictx.CreateRepoCtx(), option, &bill)
  176. if !found || err != nil {
  177. log.Info(err)
  178. return nil, errors.New("数据未找到")
  179. }
  180. return bill, nil
  181. }
  182. // 获取单据列表
  183. func GetBills(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  184. page, size, query := UtilQueryPageSize(c)
  185. option := &repo.PageSearchOptions{
  186. CollectName: repo.CollectionBillPurchase,
  187. Query: makeBillQuery(query),
  188. Page: page,
  189. Size: size,
  190. Sort: bson.M{"createTime": -1},
  191. }
  192. return repo.RepoPageSearch(apictx.CreateRepoCtx(), option)
  193. }
  194. func DownLoadBills(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  195. billId := c.Query("id")
  196. isPdf := c.Query("isPdf")
  197. if len(billId) < 1 {
  198. return nil, fmt.Errorf("id不能为空")
  199. }
  200. id, err := primitive.ObjectIDFromHex(billId)
  201. if err != nil {
  202. return nil, errors.New("非法id")
  203. }
  204. var bill model.PurchaseBill
  205. option := &repo.DocSearchOptions{
  206. CollectName: repo.CollectionBillPurchase,
  207. Query: repo.Map{"_id": id},
  208. }
  209. found, err := repo.RepoSeachDoc(apictx.CreateRepoCtx(), option, &bill)
  210. if !found || err != nil {
  211. log.Info(err)
  212. return nil, errors.New("数据未找到")
  213. }
  214. f := excelize.NewFile()
  215. index := f.NewSheet("Sheet1")
  216. f.SetActiveSheet(index)
  217. f.SetDefaultFont("宋体")
  218. var billExcel *PurchaseBillExcel
  219. if len(bill.Paper) > 0 {
  220. billExcel = NewPurchaseBill(f)
  221. }
  222. if billExcel == nil {
  223. return nil, errors.New("数据未找到")
  224. }
  225. // 获取已审核的签名数据
  226. if bill.Reviewed == 1 {
  227. if len(bill.SignUsers) > 0 {
  228. signs := []*model.Signature{}
  229. repo.RepoDocsSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
  230. CollectName: repo.CollectionSignature,
  231. Query: repo.Map{"_id": bson.M{"$in": bill.SignUsers}},
  232. Sort: bson.M{"sort": 1}, // 升序
  233. }, &signs)
  234. billExcel.Signatures = signs
  235. }
  236. }
  237. billExcel.Content = &bill
  238. billExcel.IsPdf = isPdf
  239. companyName := getCompanyName(apictx)
  240. billExcel.Title = fmt.Sprintf("%s原材料采购单", companyName)
  241. //设置对应的数据
  242. billExcel.Draws()
  243. // 下载为pdf
  244. if isPdf == "true" {
  245. buf, _ := f.WriteToBuffer()
  246. res, err := excelToPdf(buf, apictx.Svc.Conf.PdfApiAddr)
  247. if err != nil {
  248. fmt.Println(err)
  249. return nil, errors.New("转化pdf失败")
  250. }
  251. defer res.Body.Close()
  252. c.Header("Content-Type", "application/octet-stream")
  253. c.Header("Content-Disposition", "attachment; filename="+"bill.pdf")
  254. c.Header("Content-Transfer-Encoding", "binary")
  255. err = res.Write(c.Writer)
  256. if err != nil {
  257. return nil, err
  258. }
  259. return nil, nil
  260. }
  261. // 下载为execl
  262. c.Header("Content-Type", "application/octet-stream")
  263. c.Header("Content-Disposition", "attachment; filename="+"bill.xlsx")
  264. c.Header("Content-Transfer-Encoding", "binary")
  265. err = f.Write(c.Writer)
  266. if err != nil {
  267. return nil, err
  268. }
  269. return nil, nil
  270. }
  271. // 更新单据
  272. func UpdateBill(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  273. var bill model.PurchaseBill
  274. err := c.ShouldBindJSON(&bill)
  275. if err != nil {
  276. fmt.Println(err)
  277. return nil, errors.New("参数错误")
  278. }
  279. if bill.Id.Hex() == "" {
  280. return nil, errors.New("id的为空")
  281. }
  282. // 如果更改类型
  283. if len(bill.Type) > 0 {
  284. billType, err := searchBillTypeById(apictx, repo.CollectionBillPurchase, bill.Id)
  285. if err != nil {
  286. return nil, err
  287. }
  288. if billType != bill.Type {
  289. bill.SerialNumber, err = generateSerial(c, apictx, bill.Type)
  290. if err != nil {
  291. return nil, err
  292. }
  293. }
  294. }
  295. if bill.Status == "complete" {
  296. bill.CompleteTime = time.Now()
  297. }
  298. if bill.Remark == "" {
  299. bill.Remark = " "
  300. }
  301. if bill.SupplierRemark == "" {
  302. bill.SupplierRemark = " "
  303. }
  304. // 更新供应商确定数量与plan中stage项的同步
  305. if len(bill.Paper) > 0 {
  306. idCounts := map[string]int{}
  307. for _, paper := range bill.Paper {
  308. if len(paper.Id) == 0 {
  309. continue
  310. }
  311. idCounts[paper.Id] = paper.ConfirmCount
  312. }
  313. fmt.Println(idCounts)
  314. result, err := updateStageCount(c, bill.PlanId, idCounts, apictx)
  315. if err != nil {
  316. fmt.Println(err)
  317. log.Error(err)
  318. }
  319. fmt.Println(result)
  320. }
  321. bill.UpdateTime = time.Now()
  322. // return repo.RepoUpdateSetDoc(apictx.CreateRepoCtx(), repo.CollectionBillPurchase, bill.Id.Hex(), &bill)
  323. return repo.RepoUpdateSetDoc1(apictx.CreateRepoCtx(), repo.CollectionBillPurchase, bill.Id.Hex(), &bill, &repo.RecordLogReq{
  324. Path: c.Request.URL.Path,
  325. UserId: apictx.User.ID,
  326. TargetId: bill.Id.Hex(),
  327. })
  328. }
  329. // 删除单据
  330. func DelBill(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  331. billId := c.Param("id")
  332. if billId == "" {
  333. return nil, errors.New("id为空")
  334. }
  335. return repo.RepoDeleteDoc(apictx.CreateRepoCtx(), repo.CollectionBillPurchase, billId)
  336. }