bill.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  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. notAck := false
  155. bill.IsAck = &notAck
  156. // 制单人数据
  157. userId, _ := primitive.ObjectIDFromHex(apictx.User.Parent)
  158. fmt.Println("userId:", apictx.User.Parent)
  159. userInfo := &model.UserSmaple{}
  160. if !userId.IsZero() {
  161. user, err := getUserById(apictx, userId)
  162. userInfo = user
  163. if err == nil {
  164. bill.UserName = user.Name
  165. bill.UserId = userId
  166. }
  167. }
  168. return repo.RepoAddDoc1(ctx, repo.CollectionBillPurchase, &bill, &repo.RecordLogReq{
  169. Path: c.Request.URL.Path,
  170. UserInfo: userInfo,
  171. TargetId: "",
  172. Type: "created",
  173. })
  174. }
  175. // 获取单据信息
  176. func GetBill(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  177. billId := c.Param("id")
  178. id, err := primitive.ObjectIDFromHex(billId)
  179. if err != nil {
  180. return nil, errors.New("非法id")
  181. }
  182. var bill model.PurchaseBill
  183. option := &repo.DocSearchOptions{
  184. CollectName: repo.CollectionBillPurchase,
  185. Query: repo.Map{"_id": id},
  186. }
  187. found, err := repo.RepoSeachDoc(apictx.CreateRepoCtx(), option, &bill)
  188. if !found || err != nil {
  189. log.Info(err)
  190. return nil, errors.New("数据未找到")
  191. }
  192. return bill, nil
  193. }
  194. // 获取单据列表
  195. func GetBills(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  196. page, size, query := UtilQueryPageSize(c)
  197. option := &repo.PageSearchOptions{
  198. CollectName: repo.CollectionBillPurchase,
  199. Query: makeBillQuery(query),
  200. Page: page,
  201. Size: size,
  202. Sort: bson.M{"createTime": -1},
  203. }
  204. return repo.RepoPageSearch(apictx.CreateRepoCtx(), option)
  205. }
  206. func DownLoadBills(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  207. billId := c.Query("id")
  208. isPdf := c.Query("isPdf")
  209. if len(billId) < 1 {
  210. return nil, fmt.Errorf("id不能为空")
  211. }
  212. id, err := primitive.ObjectIDFromHex(billId)
  213. if err != nil {
  214. return nil, errors.New("非法id")
  215. }
  216. var bill model.PurchaseBill
  217. option := &repo.DocSearchOptions{
  218. CollectName: repo.CollectionBillPurchase,
  219. Query: repo.Map{"_id": id},
  220. }
  221. found, err := repo.RepoSeachDoc(apictx.CreateRepoCtx(), option, &bill)
  222. if !found || err != nil {
  223. log.Info(err)
  224. return nil, errors.New("数据未找到")
  225. }
  226. f := excelize.NewFile()
  227. index := f.NewSheet("Sheet1")
  228. f.SetActiveSheet(index)
  229. f.SetDefaultFont("宋体")
  230. var billExcel *PurchaseBillExcel
  231. if len(bill.Paper) > 0 {
  232. billExcel = NewPurchaseBill(f)
  233. }
  234. if billExcel == nil {
  235. return nil, errors.New("数据未找到")
  236. }
  237. // 获取已审核的签名数据
  238. if bill.Reviewed == 1 {
  239. if len(bill.SignUsers) > 0 {
  240. signs := []*model.Signature{}
  241. repo.RepoDocsSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
  242. CollectName: repo.CollectionSignature,
  243. Query: repo.Map{"_id": bson.M{"$in": bill.SignUsers}},
  244. Sort: bson.M{"sort": 1}, // 升序
  245. }, &signs)
  246. billExcel.Signatures = signs
  247. }
  248. }
  249. billExcel.Content = &bill
  250. billExcel.IsPdf = isPdf
  251. companyName := getCompanyName(apictx)
  252. billExcel.Title = fmt.Sprintf("%s原材料采购单", companyName)
  253. //设置对应的数据
  254. billExcel.Draws()
  255. // 下载为pdf
  256. if isPdf == "true" {
  257. buf, _ := f.WriteToBuffer()
  258. res, err := excelToPdf(buf, apictx.Svc.Conf.PdfApiAddr)
  259. if err != nil {
  260. fmt.Println(err)
  261. return nil, errors.New("转化pdf失败")
  262. }
  263. defer res.Body.Close()
  264. c.Header("Content-Type", "application/octet-stream")
  265. c.Header("Content-Disposition", "attachment; filename="+"bill.pdf")
  266. c.Header("Content-Transfer-Encoding", "binary")
  267. err = res.Write(c.Writer)
  268. if err != nil {
  269. return nil, err
  270. }
  271. return nil, nil
  272. }
  273. // 下载为execl
  274. c.Header("Content-Type", "application/octet-stream")
  275. c.Header("Content-Disposition", "attachment; filename="+"bill.xlsx")
  276. c.Header("Content-Transfer-Encoding", "binary")
  277. err = f.Write(c.Writer)
  278. if err != nil {
  279. return nil, err
  280. }
  281. return nil, nil
  282. }
  283. // 更新单据
  284. func UpdateBill(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  285. var bill model.PurchaseBill
  286. err := c.ShouldBindJSON(&bill)
  287. if err != nil {
  288. fmt.Println(err)
  289. return nil, errors.New("参数错误")
  290. }
  291. if bill.Id.Hex() == "" {
  292. return nil, errors.New("id的为空")
  293. }
  294. // 如果更改类型
  295. if len(bill.Type) > 0 {
  296. billType, err := searchBillTypeById(apictx, repo.CollectionBillPurchase, bill.Id)
  297. if err != nil {
  298. return nil, err
  299. }
  300. if billType != bill.Type {
  301. bill.SerialNumber, err = generateSerial(c, apictx, bill.Type)
  302. if err != nil {
  303. return nil, err
  304. }
  305. }
  306. }
  307. userId, _ := primitive.ObjectIDFromHex(apictx.User.ID)
  308. user, _ := getUserById(apictx, userId)
  309. logType := "update"
  310. // 计算结算价格
  311. if bill.Status == "complete" {
  312. bill.CompleteTime = time.Now()
  313. logType = "complete"
  314. }
  315. if bill.Status == "deprecated" {
  316. logType = "deprecated"
  317. }
  318. if bill.Remark == "" {
  319. bill.Remark = " "
  320. }
  321. if bill.SupplierRemark == "" {
  322. bill.SupplierRemark = " "
  323. }
  324. // 修改单据信息需要同步plan中stage项
  325. if len(bill.Paper) > 0 {
  326. // 获取当前订单供应商id
  327. // 对比供应商是否变化,变化了就同步计划中的供应商
  328. currPurchase := &model.PurchaseBill{}
  329. repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  330. CollectName: repo.CollectionBillPurchase,
  331. Query: repo.Map{"_id": bill.Id},
  332. Project: []string{"supplierId"},
  333. }, currPurchase)
  334. var supplierInfo *model.Supplier
  335. if currPurchase.SupplierId != bill.SupplierId {
  336. // 查询更改后的supplierInfo
  337. supplierInfo = &model.Supplier{}
  338. repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  339. CollectName: repo.CollectionSupplier,
  340. }, supplierInfo)
  341. }
  342. idStatges := make(map[string]*UpdateBilltoStageReq)
  343. for _, paper := range bill.Paper {
  344. if len(paper.Id) == 0 {
  345. continue
  346. }
  347. width, _ := strconv.Atoi(paper.Width)
  348. Height, _ := strconv.Atoi(paper.Height)
  349. idStatges[paper.Id] = &UpdateBilltoStageReq{
  350. BillType: "purchase",
  351. SupplierInfo: supplierInfo,
  352. Norm: paper.Norm,
  353. Width: width,
  354. Height: Height,
  355. Price2: paper.Price2,
  356. OrderCount: paper.OrderCount,
  357. OrderPrice: paper.OrderPrice,
  358. Remark: paper.Remark,
  359. ConfirmCount: paper.ConfirmCount,
  360. DeliveryTime: paper.DeliveryTime,
  361. }
  362. }
  363. _, err := updateBilltoStage(c, bill.PlanId, idStatges, apictx)
  364. if err != nil {
  365. return nil, errors.New("该单据改动同步到产品失败")
  366. }
  367. fmt.Println("单据同步到产品,planId:", bill.PlanId)
  368. }
  369. bill.UpdateTime = time.Now()
  370. // return repo.RepoUpdateSetDoc(apictx.CreateRepoCtx(), repo.CollectionBillPurchase, bill.Id.Hex(), &bill)
  371. return repo.RepoUpdateSetDoc1(apictx.CreateRepoCtx(), repo.CollectionBillPurchase, bill.Id.Hex(), &bill, &repo.RecordLogReq{
  372. Path: c.Request.URL.Path,
  373. UserInfo: user,
  374. TargetId: bill.Id.Hex(),
  375. Type: logType,
  376. })
  377. }
  378. // 删除单据
  379. func DelBill(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  380. billId := c.Param("id")
  381. if billId == "" {
  382. return nil, errors.New("id为空")
  383. }
  384. return repo.RepoDeleteDoc(apictx.CreateRepoCtx(), repo.CollectionBillPurchase, billId)
  385. }