plan.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014
  1. package api
  2. import (
  3. "archive/zip"
  4. "box-cost/db/model"
  5. "box-cost/db/repo"
  6. "box-cost/log"
  7. "bytes"
  8. "errors"
  9. "fmt"
  10. "io"
  11. "os"
  12. "path/filepath"
  13. "regexp"
  14. "strings"
  15. "sync"
  16. "time"
  17. "github.com/gin-gonic/gin"
  18. "github.com/xuri/excelize/v2"
  19. "go.mongodb.org/mongo-driver/bson"
  20. "go.mongodb.org/mongo-driver/bson/primitive"
  21. )
  22. // 生产计划管理
  23. func ProductPlan(r *GinRouter) {
  24. // 创建生产计划
  25. r.POST("/plan/create", CreateProductPlan)
  26. // 获取生产计划详情
  27. r.GET("/plan/detail/:id", GetProductPlan)
  28. // 获取生产计划列表
  29. r.GET("/plan/list", GetProductPlans)
  30. // 更新生产计划
  31. r.POST("/plan/update", UpdateProductPlan)
  32. // 删除生产计划
  33. r.POST("/plan/delete/:id", DelProductPlan)
  34. // 下载部件单据
  35. // r.GET("/bill/plan/download", DownLoadCompBills)
  36. r.GET("/bill/plan/download", DownLoadPlanBills)
  37. r.GET("/bill/plan/downloadPdf", DownLoadPlanBillsPdf)
  38. // 生产成本表
  39. r.GET("/plan/cost/download", DownLoadPlanCost)
  40. }
  41. type SupplierPlanCost struct {
  42. *model.ProductPlan
  43. SupplierId string
  44. }
  45. func DownLoadPlanCost(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  46. _planId := c.Query("id")
  47. supplierId := c.Query("supplierId")
  48. planId, _ := primitive.ObjectIDFromHex(_planId)
  49. if planId.IsZero() {
  50. return nil, errors.New("planId错误")
  51. }
  52. supplierPlanCost := &SupplierPlanCost{}
  53. plan := model.ProductPlan{}
  54. found, err := repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  55. CollectName: repo.CollectionProductPlan,
  56. Query: repo.Map{"_id": planId},
  57. }, &plan)
  58. if !found || err != nil {
  59. return nil, errors.New("数据未找到")
  60. }
  61. supplierPlanCost.ProductPlan = &plan
  62. supplierPlanCost.SupplierId = supplierId
  63. f := excelize.NewFile()
  64. index := f.NewSheet("Sheet1")
  65. f.SetActiveSheet(index)
  66. f.SetDefaultFont("宋体")
  67. planCostExcel := NewPlanCostExcel(f)
  68. planCostExcel.Title = fmt.Sprintf("生产成本表(%s)%d盒", plan.Name, plan.Total)
  69. planCostExcel.Content = supplierPlanCost
  70. planCostExcel.Draws()
  71. c.Header("Content-Type", "application/octet-stream")
  72. c.Header("Content-Disposition", "attachment; filename="+"planCost.xlsx")
  73. c.Header("Content-Transfer-Encoding", "binary")
  74. err = f.Write(c.Writer)
  75. if err != nil {
  76. return nil, err
  77. }
  78. return nil, nil
  79. }
  80. func DownLoadPlanBills(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  81. _planId := c.Query("id")
  82. planId, err := primitive.ObjectIDFromHex(_planId)
  83. if err != nil {
  84. return nil, errors.New("planId错误")
  85. }
  86. plan := model.ProductPlan{}
  87. found, err := repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  88. CollectName: repo.CollectionProductPlan,
  89. Query: repo.Map{"_id": planId},
  90. }, &plan)
  91. if !found || err != nil {
  92. return nil, errors.New("数据未找到")
  93. }
  94. // 获取所有stages单据id
  95. billIds := make([]string, 0)
  96. for _, comp := range plan.Pack.Components {
  97. if comp.Id == "" || len(comp.Stages) == 0 {
  98. continue
  99. }
  100. for _, stage := range comp.Stages {
  101. billId, _ := primitive.ObjectIDFromHex(stage.BillId)
  102. if !billId.IsZero() {
  103. billIds = append(billIds, fmt.Sprintf("%d_%s", stage.BillType, stage.BillId))
  104. }
  105. }
  106. }
  107. // 去重单据号
  108. typeBillIds := removeDuplicationSort(billIds)
  109. if len(typeBillIds) < 1 {
  110. return nil, errors.New("未找到单据信息")
  111. }
  112. f := excelize.NewFile()
  113. f.SetDefaultFont("宋体")
  114. flagIndex := -1
  115. companyName := getCompanyName(apictx)
  116. // 采购 加工 加工-印刷 加工-覆膜 成品采购
  117. typeRows := []int{0, 0, 0, 0, 0}
  118. for _, tId := range typeBillIds {
  119. tidArr := strings.Split(tId, "_")
  120. var billExcel IExcel
  121. // 采购
  122. billId, _ := primitive.ObjectIDFromHex(tidArr[1])
  123. if tidArr[0] == "1" {
  124. purchase := model.PurchaseBill{}
  125. found, _ := repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  126. CollectName: repo.CollectionBillPurchase,
  127. Query: repo.Map{"_id": billId},
  128. }, &purchase)
  129. if found {
  130. sheetName := "采购单"
  131. index := f.NewSheet(sheetName)
  132. if flagIndex < 0 {
  133. flagIndex = index
  134. }
  135. // index := f.NewSheet("采购单")
  136. // f.SetActiveSheet(index)
  137. billExcel = NewPurchaseBill(f)
  138. billExcel.SetSheetName(sheetName)
  139. if purchase.Reviewed == 1 {
  140. if len(purchase.SignUsers) > 0 {
  141. signs := []*model.Signature{}
  142. repo.RepoDocsSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
  143. CollectName: repo.CollectionSignature,
  144. Query: repo.Map{"_id": bson.M{"$in": purchase.SignUsers}},
  145. Sort: bson.M{"sort": 1},
  146. }, &signs)
  147. billExcel.SetSignatures(signs)
  148. }
  149. }
  150. billExcel.SetContent(&purchase)
  151. billExcel.SetTitle(fmt.Sprintf("%s原材料采购单", companyName))
  152. }
  153. billExcel.SetRow(typeRows[0])
  154. billExcel.Draws()
  155. typeRows[0] = billExcel.GetRow() + 5
  156. }
  157. // 工艺
  158. if tidArr[0] == "2" {
  159. produce := model.ProduceBill{}
  160. found, _ := repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  161. CollectName: repo.CollectionBillProduce,
  162. Query: repo.Map{"_id": billId},
  163. }, &produce)
  164. if found {
  165. sheetName := "加工单"
  166. if produce.IsPrint {
  167. sheetName = "加工单-印刷"
  168. } else if produce.IsLam {
  169. sheetName = "加工单-覆膜"
  170. }
  171. index := f.NewSheet(sheetName)
  172. if flagIndex < 0 {
  173. flagIndex = index
  174. }
  175. billExcel = NewProduceBill(f)
  176. billExcel.SetSheetName(sheetName)
  177. if produce.Reviewed == 1 {
  178. if len(produce.SignUsers) > 0 {
  179. signs := []*model.Signature{}
  180. repo.RepoDocsSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
  181. CollectName: repo.CollectionSignature,
  182. Query: repo.Map{"_id": bson.M{"$in": produce.SignUsers}},
  183. Sort: bson.M{"sort": 1},
  184. }, &signs)
  185. billExcel.SetSignatures(signs)
  186. }
  187. }
  188. billExcel.SetContent(&produce)
  189. billExcel.SetTitle(fmt.Sprintf("%s加工单", companyName))
  190. }
  191. if produce.IsPrint {
  192. billExcel.SetRow(typeRows[2])
  193. billExcel.Draws()
  194. typeRows[2] = billExcel.GetRow() + 5
  195. } else if produce.IsLam {
  196. billExcel.SetRow(typeRows[3])
  197. billExcel.Draws()
  198. typeRows[3] = billExcel.GetRow() + 5
  199. } else {
  200. billExcel.SetRow(typeRows[1])
  201. billExcel.Draws()
  202. typeRows[1] = billExcel.GetRow() + 5
  203. }
  204. }
  205. // 成品采购
  206. if tidArr[0] == "3" {
  207. product := model.ProductBill{}
  208. found, _ := repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  209. CollectName: repo.CollectionBillProduct,
  210. Query: repo.Map{"_id": billId},
  211. }, &product)
  212. if found {
  213. sheetName := "成品采购单"
  214. index := f.NewSheet(sheetName)
  215. if flagIndex < 0 {
  216. flagIndex = index
  217. }
  218. billExcel = NewProductBill(f)
  219. billExcel.SetSheetName(sheetName)
  220. if product.Reviewed == 1 {
  221. if len(product.SignUsers) > 0 {
  222. signs := []*model.Signature{}
  223. repo.RepoDocsSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
  224. CollectName: repo.CollectionSignature,
  225. Query: repo.Map{"_id": bson.M{"$in": product.SignUsers}},
  226. Sort: bson.M{"sort": 1},
  227. }, &signs)
  228. billExcel.SetSignatures(signs)
  229. }
  230. }
  231. billExcel.SetContent(&product)
  232. billExcel.SetTitle(companyName)
  233. }
  234. billExcel.SetRow(typeRows[4])
  235. billExcel.Draws()
  236. typeRows[4] = billExcel.GetRow() + 5
  237. }
  238. if billExcel == nil {
  239. continue
  240. }
  241. }
  242. // 设置活跃sheet
  243. f.SetActiveSheet(flagIndex)
  244. // 删除默认Sheet1
  245. f.DeleteSheet("Sheet1")
  246. c.Header("Content-Type", "application/octet-stream")
  247. c.Header("Content-Disposition", "attachment; filename="+"bill.xlsx")
  248. c.Header("Content-Transfer-Encoding", "binary")
  249. err = f.Write(c.Writer)
  250. if err != nil {
  251. return nil, err
  252. }
  253. return nil, nil
  254. }
  255. // todo old 功能确定后删除
  256. func DownLoadPlanBillsBack(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  257. _planId := c.Query("id")
  258. planId, err := primitive.ObjectIDFromHex(_planId)
  259. if err != nil {
  260. return nil, errors.New("planId错误")
  261. }
  262. plan := model.ProductPlan{}
  263. found, err := repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  264. CollectName: repo.CollectionProductPlan,
  265. Query: repo.Map{"_id": planId},
  266. }, &plan)
  267. if !found || err != nil {
  268. return nil, errors.New("数据未找到")
  269. }
  270. // 获取所有stages单据id
  271. billIds := make([]string, 0)
  272. for _, comp := range plan.Pack.Components {
  273. if comp.Id == "" || len(comp.Stages) == 0 {
  274. continue
  275. }
  276. for _, stage := range comp.Stages {
  277. billId, _ := primitive.ObjectIDFromHex(stage.BillId)
  278. if !billId.IsZero() {
  279. billIds = append(billIds, fmt.Sprintf("%d_%s", stage.BillType, stage.BillId))
  280. }
  281. }
  282. }
  283. // 去重单据号
  284. typeBillIds := removeDuplicationSort(billIds)
  285. if len(typeBillIds) < 1 {
  286. return nil, errors.New("未找到单据信息")
  287. }
  288. f := excelize.NewFile()
  289. index := f.NewSheet("Sheet1")
  290. f.SetActiveSheet(index)
  291. f.SetDefaultFont("宋体")
  292. companyName := getCompanyName(apictx)
  293. row := 0
  294. for _, tId := range typeBillIds {
  295. tidArr := strings.Split(tId, "_")
  296. var billExcel IExcel
  297. // 采购
  298. billId, _ := primitive.ObjectIDFromHex(tidArr[1])
  299. if tidArr[0] == "1" {
  300. purchase := model.PurchaseBill{}
  301. found, _ := repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  302. CollectName: repo.CollectionBillPurchase,
  303. Query: repo.Map{"_id": billId},
  304. }, &purchase)
  305. if found {
  306. billExcel = NewPurchaseBill(f)
  307. if purchase.Reviewed == 1 {
  308. if len(purchase.SignUsers) > 0 {
  309. signs := []*model.Signature{}
  310. repo.RepoDocsSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
  311. CollectName: repo.CollectionSignature,
  312. Query: repo.Map{"_id": bson.M{"$in": purchase.SignUsers}},
  313. Sort: bson.M{"sort": 1},
  314. }, &signs)
  315. billExcel.SetSignatures(signs)
  316. }
  317. }
  318. billExcel.SetContent(&purchase)
  319. billExcel.SetTitle(fmt.Sprintf("%s原材料采购单", companyName))
  320. }
  321. }
  322. // 工艺
  323. if tidArr[0] == "2" {
  324. produce := model.ProduceBill{}
  325. found, _ := repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  326. CollectName: repo.CollectionBillProduce,
  327. Query: repo.Map{"_id": billId},
  328. }, &produce)
  329. if found {
  330. billExcel = NewProduceBill(f)
  331. if produce.Reviewed == 1 {
  332. if len(produce.SignUsers) > 0 {
  333. signs := []*model.Signature{}
  334. repo.RepoDocsSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
  335. CollectName: repo.CollectionSignature,
  336. Query: repo.Map{"_id": bson.M{"$in": produce.SignUsers}},
  337. Sort: bson.M{"sort": 1},
  338. }, &signs)
  339. billExcel.SetSignatures(signs)
  340. }
  341. }
  342. billExcel.SetContent(&produce)
  343. billExcel.SetTitle(fmt.Sprintf("%s加工单", companyName))
  344. }
  345. }
  346. // 成品采购
  347. if tidArr[0] == "3" {
  348. product := model.ProductBill{}
  349. found, _ := repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  350. CollectName: repo.CollectionBillProduct,
  351. Query: repo.Map{"_id": billId},
  352. }, &product)
  353. if found {
  354. billExcel = NewProductBill(f)
  355. if product.Reviewed == 1 {
  356. if len(product.SignUsers) > 0 {
  357. signs := []*model.Signature{}
  358. repo.RepoDocsSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
  359. CollectName: repo.CollectionSignature,
  360. Query: repo.Map{"_id": bson.M{"$in": product.SignUsers}},
  361. Sort: bson.M{"sort": 1},
  362. }, &signs)
  363. billExcel.SetSignatures(signs)
  364. }
  365. }
  366. billExcel.SetContent(&product)
  367. billExcel.SetTitle(companyName)
  368. }
  369. }
  370. if billExcel == nil {
  371. continue
  372. }
  373. billExcel.SetRow(row)
  374. billExcel.Draws()
  375. row = billExcel.GetRow() + 5
  376. }
  377. c.Header("Content-Type", "application/octet-stream")
  378. c.Header("Content-Disposition", "attachment; filename="+"bill.xlsx")
  379. c.Header("Content-Transfer-Encoding", "binary")
  380. err = f.Write(c.Writer)
  381. if err != nil {
  382. return nil, err
  383. }
  384. return nil, nil
  385. }
  386. func DownLoadPlanBillsPdf(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  387. _planId := c.Query("id")
  388. planId, err := primitive.ObjectIDFromHex(_planId)
  389. if err != nil {
  390. return nil, errors.New("planId错误")
  391. }
  392. plan := model.ProductPlan{}
  393. found, err := repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  394. CollectName: repo.CollectionProductPlan,
  395. Query: repo.Map{"_id": planId},
  396. }, &plan)
  397. if !found || err != nil {
  398. return nil, errors.New("数据未找到")
  399. }
  400. // 获取所有stages单据id
  401. billIds := make([]string, 0)
  402. for _, comp := range plan.Pack.Components {
  403. if comp.Id == "" || len(comp.Stages) == 0 {
  404. continue
  405. }
  406. for _, stage := range comp.Stages {
  407. billId, _ := primitive.ObjectIDFromHex(stage.BillId)
  408. if !billId.IsZero() {
  409. billIds = append(billIds, fmt.Sprintf("%d_%s", stage.BillType, stage.BillId))
  410. }
  411. }
  412. }
  413. // 去重单据号
  414. typeBillIds := removeDuplicationSort(billIds)
  415. if len(typeBillIds) < 1 {
  416. return nil, errors.New("未找到单据信息")
  417. }
  418. companyName := getCompanyName(apictx)
  419. _planName := plan.Name
  420. r := regexp.MustCompile(`/`)
  421. planName := r.ReplaceAllString(_planName, `&`)
  422. // fmt.Println(planName)
  423. // 打包pdf的缓存目录
  424. saveTmpDir := fmt.Sprintf("tmp1/%s", planName)
  425. if isExistDir(saveTmpDir) {
  426. os.RemoveAll(saveTmpDir)
  427. }
  428. // 记录文件数量
  429. var wg sync.WaitGroup
  430. c1 := make(chan int)
  431. for _, tId := range typeBillIds {
  432. productName := ""
  433. supplierName := ""
  434. serialNumber := ""
  435. f := excelize.NewFile()
  436. index := f.NewSheet("Sheet1")
  437. f.SetActiveSheet(index)
  438. f.SetDefaultFont("宋体")
  439. tidArr := strings.Split(tId, "_")
  440. var billExcel IExcel
  441. // 采购
  442. billId, _ := primitive.ObjectIDFromHex(tidArr[1])
  443. if tidArr[0] == "1" {
  444. purchase := model.PurchaseBill{}
  445. found, _ := repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  446. CollectName: repo.CollectionBillPurchase,
  447. Query: repo.Map{"_id": billId},
  448. }, &purchase)
  449. if found {
  450. billExcel = NewPurchaseBill(f)
  451. if purchase.Reviewed == 1 {
  452. if len(purchase.SignUsers) > 0 {
  453. signs := []*model.Signature{}
  454. repo.RepoDocsSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
  455. CollectName: repo.CollectionSignature,
  456. Query: repo.Map{"_id": bson.M{"$in": purchase.SignUsers}},
  457. Sort: bson.M{"sort": 1},
  458. }, &signs)
  459. billExcel.SetSignatures(signs)
  460. }
  461. }
  462. productName = purchase.ProductName
  463. supplierName = purchase.Supplier
  464. serialNumber = purchase.SerialNumber
  465. billExcel.SetContent(&purchase)
  466. billExcel.SetTitle(fmt.Sprintf("%s原材料采购单", companyName))
  467. }
  468. }
  469. // 工艺
  470. if tidArr[0] == "2" {
  471. produce := model.ProduceBill{}
  472. found, _ := repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  473. CollectName: repo.CollectionBillProduce,
  474. Query: repo.Map{"_id": billId},
  475. }, &produce)
  476. if found {
  477. billExcel = NewProduceBill(f)
  478. if produce.Reviewed == 1 {
  479. if len(produce.SignUsers) > 0 {
  480. signs := []*model.Signature{}
  481. repo.RepoDocsSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
  482. CollectName: repo.CollectionSignature,
  483. Query: repo.Map{"_id": bson.M{"$in": produce.SignUsers}},
  484. Sort: bson.M{"sort": 1},
  485. }, &signs)
  486. billExcel.SetSignatures(signs)
  487. }
  488. }
  489. productName = produce.ProductName
  490. supplierName = produce.Supplier
  491. serialNumber = produce.SerialNumber
  492. billExcel.SetContent(&produce)
  493. billExcel.SetTitle(fmt.Sprintf("%s加工单", companyName))
  494. }
  495. }
  496. // 成品采购
  497. if tidArr[0] == "3" {
  498. product := model.ProductBill{}
  499. found, _ := repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  500. CollectName: repo.CollectionBillProduct,
  501. Query: repo.Map{"_id": billId},
  502. }, &product)
  503. if found {
  504. billExcel = NewProductBill(f)
  505. if product.Reviewed == 1 {
  506. if len(product.SignUsers) > 0 {
  507. signs := []*model.Signature{}
  508. repo.RepoDocsSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
  509. CollectName: repo.CollectionSignature,
  510. Query: repo.Map{"_id": bson.M{"$in": product.SignUsers}},
  511. Sort: bson.M{"sort": 1},
  512. }, &signs)
  513. billExcel.SetSignatures(signs)
  514. }
  515. }
  516. productName = product.ProductName
  517. supplierName = product.Supplier
  518. serialNumber = product.SerialNumber
  519. billExcel.SetContent(&product)
  520. billExcel.SetTitle(companyName)
  521. }
  522. }
  523. if billExcel == nil {
  524. continue
  525. }
  526. billExcel.SetIsPdf("true")
  527. billExcel.Draws()
  528. buf, _ := f.WriteToBuffer()
  529. // r := regexp.MustCompile(`/`)
  530. _productName := r.ReplaceAllString(productName, `&`)
  531. _supplierName := r.ReplaceAllString(supplierName, `&`)
  532. targePdfName := fmt.Sprintf("%s-%s-%s.pdf", _supplierName, _productName, serialNumber)
  533. // fmt.Println(targePdfName)
  534. wg.Add(1)
  535. go toPdfAndSaveTask(buf, apictx.Svc.Conf.PdfApiAddr, saveTmpDir, targePdfName, c1, &wg)
  536. }
  537. go func() {
  538. // 等待所有goroutine
  539. wg.Wait()
  540. // 关闭channel
  541. close(c1)
  542. }()
  543. // channel关闭后结束后停止遍历接收channel中的值
  544. for n := range c1 {
  545. if n == -1 {
  546. return nil, errors.New("下载失败,请重试")
  547. }
  548. }
  549. c.Header("Content-Type", "application/octet-stream")
  550. c.Header("Content-Disposition", "attachment; filename="+planName+".zip")
  551. c.Header("Content-Transfer-Encoding", "binary")
  552. archive := zip.NewWriter(c.Writer)
  553. defer archive.Close()
  554. // 遍历路径信息
  555. filepath.Walk(saveTmpDir, func(path string, info os.FileInfo, _ error) error {
  556. // 如果是源路径,提前进行下一个遍历
  557. if path == saveTmpDir {
  558. return nil
  559. }
  560. // 获取:文件头信息
  561. header, _ := zip.FileInfoHeader(info)
  562. header.Name = strings.TrimPrefix(path, saveTmpDir+`/`)
  563. // 判断:文件是不是文件夹
  564. if info.IsDir() {
  565. header.Name += `/`
  566. } else {
  567. // 设置:zip的文件压缩算法
  568. header.Method = zip.Deflate
  569. }
  570. // 创建:压缩包头部信息
  571. writer, _ := archive.CreateHeader(header)
  572. if !info.IsDir() {
  573. file, _ := os.Open(path)
  574. defer file.Close()
  575. io.Copy(writer, file)
  576. }
  577. return nil
  578. })
  579. // 删除缓存目录
  580. os.RemoveAll(saveTmpDir)
  581. return nil, nil
  582. }
  583. type ToPdfResult struct {
  584. IsSucc bool
  585. Err error
  586. }
  587. func toPdfAndSaveTask(buf *bytes.Buffer, toPdfAddr, saveTmpDir, targetPdfName string, toPdfResult chan<- int, wg *sync.WaitGroup) {
  588. if buf.Len() < 1<<10 {
  589. fmt.Println("execl内容为空")
  590. log.Error("execl内容为空")
  591. toPdfResult <- -1
  592. wg.Done()
  593. return
  594. }
  595. res, err := excelToPdf(buf, toPdfAddr)
  596. if err != nil {
  597. fmt.Println(err)
  598. log.Error(err)
  599. // pdfRes := ToPdfResult{
  600. // IsSucc: false,
  601. // Err: err,
  602. // }
  603. // toPdfResult <- pdfRes
  604. toPdfResult <- -1
  605. wg.Done()
  606. return
  607. }
  608. byteData, err := io.ReadAll(res.Body)
  609. if err != nil {
  610. fmt.Println(err)
  611. // pdfRes := ToPdfResult{
  612. // IsSucc: false,
  613. // Err: err,
  614. // }
  615. // toPdfResult <- pdfRes
  616. toPdfResult <- -1
  617. wg.Done()
  618. return
  619. }
  620. if len(byteData) < 1 {
  621. fmt.Println("pdf内容为空")
  622. log.Error("pdf内容为空")
  623. toPdfResult <- -1
  624. wg.Done()
  625. return
  626. }
  627. defer res.Body.Close()
  628. err = savePdfToTmp(saveTmpDir, targetPdfName, byteData)
  629. if err != nil {
  630. // pdfRes := ToPdfResult{
  631. // IsSucc: false,
  632. // Err: err,
  633. // }
  634. // toPdfResult <- pdfRes
  635. toPdfResult <- -1
  636. wg.Done()
  637. return
  638. }
  639. // pdfRes := ToPdfResult{
  640. // IsSucc: true,
  641. // Err: err,
  642. // }
  643. // toPdfResult <- pdfRes
  644. toPdfResult <- 1
  645. wg.Done()
  646. }
  647. // todo 已弃用 功能稳定后删除
  648. func DownLoadCompBills(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  649. _planId := c.Query("id")
  650. compId := c.Query("compId")
  651. planId, err := primitive.ObjectIDFromHex(_planId)
  652. if err != nil {
  653. return nil, errors.New("planId错误")
  654. }
  655. plan := model.ProductPlan{}
  656. found, err := repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  657. CollectName: repo.CollectionProductPlan,
  658. Query: repo.Map{"_id": planId},
  659. }, &plan)
  660. if !found || err != nil {
  661. return nil, errors.New("数据未找到")
  662. }
  663. // 获取部件单据
  664. curComp := &model.PackComponent{}
  665. for _, comp := range plan.Pack.Components {
  666. if comp.Id == compId {
  667. curComp = comp
  668. }
  669. }
  670. if curComp.Id == "" {
  671. return nil, errors.New("该组件不存在")
  672. }
  673. // 获取bill
  674. if len(curComp.Stages) == 0 {
  675. return nil, errors.New("该组件数据不存在")
  676. }
  677. // 获取不同类型的单据id
  678. billIds := make([]string, 0)
  679. for _, stage := range curComp.Stages {
  680. billId, _ := primitive.ObjectIDFromHex(stage.BillId)
  681. if !billId.IsZero() {
  682. billIds = append(billIds, fmt.Sprintf("%d_%s", stage.BillType, stage.BillId))
  683. }
  684. }
  685. // 去重单据号
  686. typeBillIds := removeDuplicationSort(billIds)
  687. if len(typeBillIds) < 1 {
  688. return nil, errors.New("未找到单据信息")
  689. }
  690. f := excelize.NewFile()
  691. index := f.NewSheet("Sheet1")
  692. f.SetActiveSheet(index)
  693. f.SetDefaultFont("宋体")
  694. companyName := getCompanyName(apictx)
  695. row := 0
  696. for _, tId := range typeBillIds {
  697. tidArr := strings.Split(tId, "_")
  698. var billExcel IExcel
  699. // 采购
  700. billId, _ := primitive.ObjectIDFromHex(tidArr[1])
  701. if tidArr[0] == "1" {
  702. purchase := model.PurchaseBill{}
  703. found, _ := repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  704. CollectName: repo.CollectionBillPurchase,
  705. Query: repo.Map{"_id": billId},
  706. }, &purchase)
  707. if found {
  708. billExcel = NewPurchaseBill(f)
  709. if purchase.Reviewed == 1 {
  710. if len(purchase.SignUsers) > 0 {
  711. signs := []*model.Signature{}
  712. repo.RepoDocsSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
  713. CollectName: repo.CollectionSignature,
  714. Query: repo.Map{"_id": bson.M{"$in": purchase.SignUsers}},
  715. Sort: bson.M{"sort": 1},
  716. }, &signs)
  717. billExcel.SetSignatures(signs)
  718. }
  719. }
  720. billExcel.SetContent(&purchase)
  721. billExcel.SetTitle(fmt.Sprintf("%s原材料采购单", companyName))
  722. }
  723. }
  724. // 工艺
  725. if tidArr[0] == "2" {
  726. produce := model.ProduceBill{}
  727. found, _ := repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  728. CollectName: repo.CollectionBillProduce,
  729. Query: repo.Map{"_id": billId},
  730. }, &produce)
  731. if found {
  732. billExcel = NewProduceBill(f)
  733. if produce.Reviewed == 1 {
  734. if len(produce.SignUsers) > 0 {
  735. signs := []*model.Signature{}
  736. repo.RepoDocsSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
  737. CollectName: repo.CollectionSignature,
  738. Query: repo.Map{"_id": bson.M{"$in": produce.SignUsers}},
  739. Sort: bson.M{"sort": 1},
  740. }, &signs)
  741. billExcel.SetSignatures(signs)
  742. }
  743. }
  744. billExcel.SetContent(&produce)
  745. billExcel.SetTitle(fmt.Sprintf("%s加工单", companyName))
  746. }
  747. }
  748. // 成品采购
  749. if tidArr[0] == "3" {
  750. product := model.ProductBill{}
  751. found, _ := repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  752. CollectName: repo.CollectionBillProduct,
  753. Query: repo.Map{"_id": billId},
  754. }, &product)
  755. if found {
  756. billExcel = NewProductBill(f)
  757. if product.Reviewed == 1 {
  758. if len(product.SignUsers) > 0 {
  759. signs := []*model.Signature{}
  760. repo.RepoDocsSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
  761. CollectName: repo.CollectionSignature,
  762. Query: repo.Map{"_id": bson.M{"$in": product.SignUsers}},
  763. Sort: bson.M{"sort": 1},
  764. }, &signs)
  765. billExcel.SetSignatures(signs)
  766. }
  767. }
  768. billExcel.SetContent(&product)
  769. billExcel.SetTitle(companyName)
  770. }
  771. }
  772. if billExcel == nil {
  773. continue
  774. }
  775. billExcel.SetRow(row)
  776. billExcel.Draws()
  777. row = billExcel.GetRow() + 5
  778. }
  779. c.Header("Content-Type", "application/octet-stream")
  780. c.Header("Content-Disposition", "attachment; filename="+"bill.xlsx")
  781. c.Header("Content-Transfer-Encoding", "binary")
  782. err = f.Write(c.Writer)
  783. if err != nil {
  784. return nil, err
  785. }
  786. return nil, nil
  787. }
  788. // 创建生产计划
  789. func CreateProductPlan(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  790. var plan model.ProductPlan
  791. err := c.ShouldBindJSON(&plan)
  792. if err != nil {
  793. fmt.Println(err)
  794. return nil, errors.New("参数错误!")
  795. }
  796. if plan.Name == "" {
  797. return nil, errors.New("生产计划名为空")
  798. }
  799. if plan.Total == 0 {
  800. return nil, errors.New("生产计划数应不为0")
  801. }
  802. plan.Status = "process" // 进行中
  803. plan.CreateTime = time.Now()
  804. plan.UpdateTime = time.Now()
  805. result, err := repo.RepoAddDoc(apictx.CreateRepoCtx(), repo.CollectionProductPlan, &plan)
  806. return result, err
  807. }
  808. // 获取生产计划信息
  809. func GetProductPlan(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  810. planId := c.Param("id")
  811. id, err := primitive.ObjectIDFromHex(planId)
  812. if err != nil {
  813. return nil, errors.New("非法id")
  814. }
  815. var plan model.ProductPlan
  816. option := &repo.DocSearchOptions{
  817. CollectName: repo.CollectionProductPlan,
  818. Query: repo.Map{"_id": id},
  819. }
  820. found, err := repo.RepoSeachDoc(apictx.CreateRepoCtx(), option, &plan)
  821. if !found || err != nil {
  822. log.Info(err)
  823. return nil, errors.New("数据未找到")
  824. }
  825. billStates := map[string]string{}
  826. if plan.Pack != nil && plan.Pack.Components != nil {
  827. for _, comp := range plan.Pack.Components {
  828. if comp.Stages != nil {
  829. for _, stage := range comp.Stages {
  830. if len(stage.BillId) > 0 {
  831. collectName := ""
  832. // 材料
  833. if stage.BillType == 1 {
  834. collectName = repo.CollectionBillPurchase
  835. }
  836. // 工艺
  837. if stage.BillType == 2 {
  838. collectName = repo.CollectionBillProduce
  839. }
  840. // 成品
  841. if stage.BillType == 3 {
  842. collectName = repo.CollectionBillProduct
  843. }
  844. ok, state := repo.RepoSeachDocMap(apictx.CreateRepoCtx(), &repo.DocSearchOptions{CollectName: collectName, Query: repo.Map{"_id": stage.BillId}, Project: []string{"status"}})
  845. if ok {
  846. billStates[stage.BillId] = state["status"].(string)
  847. }
  848. }
  849. }
  850. }
  851. }
  852. }
  853. return map[string]interface{}{
  854. "plan": plan,
  855. "billStates": billStates,
  856. }, nil
  857. }
  858. // 获取生产计划列表
  859. func GetProductPlans(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  860. page, size, query := UtilQueryPageSize(c)
  861. if _packId, ok := query["packId"]; ok {
  862. packId, _ := primitive.ObjectIDFromHex(_packId.(string))
  863. query["pack._id"] = packId
  864. delete(query, "packId")
  865. }
  866. if _name, ok := query["name"]; ok {
  867. delete(query, "name")
  868. query["name"] = bson.M{"$regex": _name.(string)}
  869. }
  870. option := &repo.PageSearchOptions{
  871. CollectName: repo.CollectionProductPlan,
  872. Query: query,
  873. Page: page,
  874. Size: size,
  875. Sort: bson.M{"createTime": -1},
  876. Project: []string{"_id", "thumbnail", "name", "updateTime", "createTime", "createUser", "total", "totalPrice", "status"},
  877. }
  878. return repo.RepoPageSearch(apictx.CreateRepoCtx(), option)
  879. }
  880. // 更新生产计划
  881. func UpdateProductPlan(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  882. var plan model.ProductPlan
  883. err := c.ShouldBindJSON(&plan)
  884. if err != nil {
  885. return nil, errors.New("参数错误")
  886. }
  887. if plan.Id.Hex() == "" {
  888. return nil, errors.New("id的为空")
  889. }
  890. plan.UpdateTime = time.Now()
  891. return repo.RepoUpdateSetDoc(apictx.CreateRepoCtx(), repo.CollectionProductPlan, plan.Id.Hex(), &plan)
  892. }
  893. // 删除生产计划
  894. func DelProductPlan(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  895. planId := c.Param("id")
  896. if planId == "" {
  897. return nil, errors.New("id为空")
  898. }
  899. return repo.RepoDeleteDoc(apictx.CreateRepoCtx(), repo.CollectionProductPlan, planId)
  900. }