bill.go 10 KB

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