bill.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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. userId, _ := primitive.ObjectIDFromHex(apictx.User.ID)
  60. user, _ := getUserById(apictx, userId)
  61. desc := fmt.Sprintf("【%s】对订单进行了对账", user.Name)
  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. UserId: apictx.User.ID,
  66. TargetId: req.Id.Hex(),
  67. Desc: desc,
  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. desc := fmt.Sprintf("【%s】审核了订单", user.Name)
  112. // return repo.RepoUpdateSetDoc(apictx.CreateRepoCtx(), repo.CollectionBillPurchase, _id, &purchase)
  113. return repo.RepoUpdateSetDoc1(apictx.CreateRepoCtx(), repo.CollectionBillPurchase, _id, &purchase, &repo.RecordLogReq{
  114. Path: c.Request.URL.Path,
  115. UserId: apictx.User.ID,
  116. TargetId: _id,
  117. Desc: desc,
  118. })
  119. }
  120. type MatBillReq struct {
  121. Bill *model.PurchaseBill
  122. CompIndex *int
  123. MatIndex *int
  124. //MatKey string //components.0.mats.0.billId
  125. }
  126. // 创建单据
  127. func CreateBill(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  128. req := &model.PurchaseBill{}
  129. err := c.ShouldBindJSON(req)
  130. if err != nil {
  131. fmt.Println(err)
  132. return nil, errors.New("参数错误")
  133. }
  134. ctx := apictx.CreateRepoCtx()
  135. bill := req
  136. if bill.PackId.Hex() == "" {
  137. return nil, errors.New("包装产品id为空")
  138. }
  139. if bill.PlanId.Hex() == "" {
  140. return nil, errors.New("生产计划id为空")
  141. }
  142. if bill.Type == "" {
  143. return nil, errors.New("类型为空")
  144. }
  145. bill.SerialNumber, err = generateSerial(c, apictx, bill.Type)
  146. if err != nil {
  147. return nil, err
  148. }
  149. bill.Status = "created"
  150. if bill.Reviewed == 0 {
  151. bill.Reviewed = -1
  152. }
  153. bill.CreateTime = time.Now()
  154. bill.UpdateTime = time.Now()
  155. notAck := false
  156. bill.IsAck = &notAck
  157. // 制单人数据
  158. userId, _ := primitive.ObjectIDFromHex(apictx.User.Parent)
  159. fmt.Println("userId:", apictx.User.Parent)
  160. if !userId.IsZero() {
  161. user, err := getUserById(apictx, userId)
  162. if err == nil {
  163. bill.UserName = user.Name
  164. bill.UserId = userId
  165. }
  166. }
  167. return repo.RepoAddDoc(ctx, repo.CollectionBillPurchase, &bill)
  168. }
  169. // 获取单据信息
  170. func GetBill(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  171. billId := c.Param("id")
  172. id, err := primitive.ObjectIDFromHex(billId)
  173. if err != nil {
  174. return nil, errors.New("非法id")
  175. }
  176. var bill model.PurchaseBill
  177. option := &repo.DocSearchOptions{
  178. CollectName: repo.CollectionBillPurchase,
  179. Query: repo.Map{"_id": id},
  180. }
  181. found, err := repo.RepoSeachDoc(apictx.CreateRepoCtx(), option, &bill)
  182. if !found || err != nil {
  183. log.Info(err)
  184. return nil, errors.New("数据未找到")
  185. }
  186. return bill, nil
  187. }
  188. // 获取单据列表
  189. func GetBills(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  190. page, size, query := UtilQueryPageSize(c)
  191. option := &repo.PageSearchOptions{
  192. CollectName: repo.CollectionBillPurchase,
  193. Query: makeBillQuery(query),
  194. Page: page,
  195. Size: size,
  196. Sort: bson.M{"createTime": -1},
  197. }
  198. return repo.RepoPageSearch(apictx.CreateRepoCtx(), option)
  199. }
  200. func DownLoadBills(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  201. billId := c.Query("id")
  202. isPdf := c.Query("isPdf")
  203. if len(billId) < 1 {
  204. return nil, fmt.Errorf("id不能为空")
  205. }
  206. id, err := primitive.ObjectIDFromHex(billId)
  207. if err != nil {
  208. return nil, errors.New("非法id")
  209. }
  210. var bill model.PurchaseBill
  211. option := &repo.DocSearchOptions{
  212. CollectName: repo.CollectionBillPurchase,
  213. Query: repo.Map{"_id": id},
  214. }
  215. found, err := repo.RepoSeachDoc(apictx.CreateRepoCtx(), option, &bill)
  216. if !found || err != nil {
  217. log.Info(err)
  218. return nil, errors.New("数据未找到")
  219. }
  220. f := excelize.NewFile()
  221. index := f.NewSheet("Sheet1")
  222. f.SetActiveSheet(index)
  223. f.SetDefaultFont("宋体")
  224. var billExcel *PurchaseBillExcel
  225. if len(bill.Paper) > 0 {
  226. billExcel = NewPurchaseBill(f)
  227. }
  228. if billExcel == nil {
  229. return nil, errors.New("数据未找到")
  230. }
  231. // 获取已审核的签名数据
  232. if bill.Reviewed == 1 {
  233. if len(bill.SignUsers) > 0 {
  234. signs := []*model.Signature{}
  235. repo.RepoDocsSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
  236. CollectName: repo.CollectionSignature,
  237. Query: repo.Map{"_id": bson.M{"$in": bill.SignUsers}},
  238. Sort: bson.M{"sort": 1}, // 升序
  239. }, &signs)
  240. billExcel.Signatures = signs
  241. }
  242. }
  243. billExcel.Content = &bill
  244. billExcel.IsPdf = isPdf
  245. companyName := getCompanyName(apictx)
  246. billExcel.Title = fmt.Sprintf("%s原材料采购单", companyName)
  247. //设置对应的数据
  248. billExcel.Draws()
  249. // 下载为pdf
  250. if isPdf == "true" {
  251. buf, _ := f.WriteToBuffer()
  252. res, err := excelToPdf(buf, apictx.Svc.Conf.PdfApiAddr)
  253. if err != nil {
  254. fmt.Println(err)
  255. return nil, errors.New("转化pdf失败")
  256. }
  257. defer res.Body.Close()
  258. c.Header("Content-Type", "application/octet-stream")
  259. c.Header("Content-Disposition", "attachment; filename="+"bill.pdf")
  260. c.Header("Content-Transfer-Encoding", "binary")
  261. err = res.Write(c.Writer)
  262. if err != nil {
  263. return nil, err
  264. }
  265. return nil, nil
  266. }
  267. // 下载为execl
  268. c.Header("Content-Type", "application/octet-stream")
  269. c.Header("Content-Disposition", "attachment; filename="+"bill.xlsx")
  270. c.Header("Content-Transfer-Encoding", "binary")
  271. err = f.Write(c.Writer)
  272. if err != nil {
  273. return nil, err
  274. }
  275. return nil, nil
  276. }
  277. // 更新单据
  278. func UpdateBill(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  279. var bill model.PurchaseBill
  280. err := c.ShouldBindJSON(&bill)
  281. if err != nil {
  282. fmt.Println(err)
  283. return nil, errors.New("参数错误")
  284. }
  285. if bill.Id.Hex() == "" {
  286. return nil, errors.New("id的为空")
  287. }
  288. // 如果更改类型
  289. if len(bill.Type) > 0 {
  290. billType, err := searchBillTypeById(apictx, repo.CollectionBillPurchase, bill.Id)
  291. if err != nil {
  292. return nil, err
  293. }
  294. if billType != bill.Type {
  295. bill.SerialNumber, err = generateSerial(c, apictx, bill.Type)
  296. if err != nil {
  297. return nil, err
  298. }
  299. }
  300. }
  301. userId, _ := primitive.ObjectIDFromHex(apictx.User.ID)
  302. user, _ := getUserById(apictx, userId)
  303. desc := fmt.Sprintf("【%s】更新了订单", user.Name)
  304. if bill.Status == "complete" {
  305. bill.CompleteTime = time.Now()
  306. desc = fmt.Sprintf("【%s】完成了订单", user.Name)
  307. }
  308. if bill.Remark == "" {
  309. bill.Remark = " "
  310. }
  311. if bill.SupplierRemark == "" {
  312. bill.SupplierRemark = " "
  313. }
  314. // 更新供应商确定数量与plan中stage项的同步
  315. if len(bill.Paper) > 0 {
  316. idCounts := map[string]int{}
  317. for _, paper := range bill.Paper {
  318. if len(paper.Id) == 0 {
  319. continue
  320. }
  321. idCounts[paper.Id] = paper.ConfirmCount
  322. }
  323. fmt.Println(idCounts)
  324. result, err := updateStageCount(c, bill.PlanId, idCounts, apictx)
  325. if err != nil {
  326. fmt.Println(err)
  327. log.Error(err)
  328. }
  329. fmt.Println(result)
  330. }
  331. bill.UpdateTime = time.Now()
  332. // return repo.RepoUpdateSetDoc(apictx.CreateRepoCtx(), repo.CollectionBillPurchase, bill.Id.Hex(), &bill)
  333. return repo.RepoUpdateSetDoc1(apictx.CreateRepoCtx(), repo.CollectionBillPurchase, bill.Id.Hex(), &bill, &repo.RecordLogReq{
  334. Path: c.Request.URL.Path,
  335. UserId: apictx.User.ID,
  336. TargetId: bill.Id.Hex(),
  337. Desc: desc,
  338. })
  339. }
  340. // 删除单据
  341. func DelBill(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  342. billId := c.Param("id")
  343. if billId == "" {
  344. return nil, errors.New("id为空")
  345. }
  346. return repo.RepoDeleteDoc(apictx.CreateRepoCtx(), repo.CollectionBillPurchase, billId)
  347. }