plan.go 27 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013
  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. func DownLoadCompBills(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  648. _planId := c.Query("id")
  649. compId := c.Query("compId")
  650. planId, err := primitive.ObjectIDFromHex(_planId)
  651. if err != nil {
  652. return nil, errors.New("planId错误")
  653. }
  654. plan := model.ProductPlan{}
  655. found, err := repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  656. CollectName: repo.CollectionProductPlan,
  657. Query: repo.Map{"_id": planId},
  658. }, &plan)
  659. if !found || err != nil {
  660. return nil, errors.New("数据未找到")
  661. }
  662. // 获取部件单据
  663. curComp := &model.PackComponent{}
  664. for _, comp := range plan.Pack.Components {
  665. if comp.Id == compId {
  666. curComp = comp
  667. }
  668. }
  669. if curComp.Id == "" {
  670. return nil, errors.New("该组件不存在")
  671. }
  672. // 获取bill
  673. if len(curComp.Stages) == 0 {
  674. return nil, errors.New("该组件数据不存在")
  675. }
  676. // 获取不同类型的单据id
  677. billIds := make([]string, 0)
  678. for _, stage := range curComp.Stages {
  679. billId, _ := primitive.ObjectIDFromHex(stage.BillId)
  680. if !billId.IsZero() {
  681. billIds = append(billIds, fmt.Sprintf("%d_%s", stage.BillType, stage.BillId))
  682. }
  683. }
  684. // 去重单据号
  685. typeBillIds := removeDuplicationSort(billIds)
  686. if len(typeBillIds) < 1 {
  687. return nil, errors.New("未找到单据信息")
  688. }
  689. f := excelize.NewFile()
  690. index := f.NewSheet("Sheet1")
  691. f.SetActiveSheet(index)
  692. f.SetDefaultFont("宋体")
  693. companyName := getCompanyName(apictx)
  694. row := 0
  695. for _, tId := range typeBillIds {
  696. tidArr := strings.Split(tId, "_")
  697. var billExcel IExcel
  698. // 采购
  699. billId, _ := primitive.ObjectIDFromHex(tidArr[1])
  700. if tidArr[0] == "1" {
  701. purchase := model.PurchaseBill{}
  702. found, _ := repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  703. CollectName: repo.CollectionBillPurchase,
  704. Query: repo.Map{"_id": billId},
  705. }, &purchase)
  706. if found {
  707. billExcel = NewPurchaseBill(f)
  708. if purchase.Reviewed == 1 {
  709. if len(purchase.SignUsers) > 0 {
  710. signs := []*model.Signature{}
  711. repo.RepoDocsSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
  712. CollectName: repo.CollectionSignature,
  713. Query: repo.Map{"_id": bson.M{"$in": purchase.SignUsers}},
  714. Sort: bson.M{"sort": 1},
  715. }, &signs)
  716. billExcel.SetSignatures(signs)
  717. }
  718. }
  719. billExcel.SetContent(&purchase)
  720. billExcel.SetTitle(fmt.Sprintf("%s原材料采购单", companyName))
  721. }
  722. }
  723. // 工艺
  724. if tidArr[0] == "2" {
  725. produce := model.ProduceBill{}
  726. found, _ := repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  727. CollectName: repo.CollectionBillProduce,
  728. Query: repo.Map{"_id": billId},
  729. }, &produce)
  730. if found {
  731. billExcel = NewProduceBill(f)
  732. if produce.Reviewed == 1 {
  733. if len(produce.SignUsers) > 0 {
  734. signs := []*model.Signature{}
  735. repo.RepoDocsSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
  736. CollectName: repo.CollectionSignature,
  737. Query: repo.Map{"_id": bson.M{"$in": produce.SignUsers}},
  738. Sort: bson.M{"sort": 1},
  739. }, &signs)
  740. billExcel.SetSignatures(signs)
  741. }
  742. }
  743. billExcel.SetContent(&produce)
  744. billExcel.SetTitle(fmt.Sprintf("%s加工单", companyName))
  745. }
  746. }
  747. // 成品采购
  748. if tidArr[0] == "3" {
  749. product := model.ProductBill{}
  750. found, _ := repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  751. CollectName: repo.CollectionBillProduct,
  752. Query: repo.Map{"_id": billId},
  753. }, &product)
  754. if found {
  755. billExcel = NewProductBill(f)
  756. if product.Reviewed == 1 {
  757. if len(product.SignUsers) > 0 {
  758. signs := []*model.Signature{}
  759. repo.RepoDocsSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
  760. CollectName: repo.CollectionSignature,
  761. Query: repo.Map{"_id": bson.M{"$in": product.SignUsers}},
  762. Sort: bson.M{"sort": 1},
  763. }, &signs)
  764. billExcel.SetSignatures(signs)
  765. }
  766. }
  767. billExcel.SetContent(&product)
  768. billExcel.SetTitle(companyName)
  769. }
  770. }
  771. if billExcel == nil {
  772. continue
  773. }
  774. billExcel.SetRow(row)
  775. billExcel.Draws()
  776. row = billExcel.GetRow() + 5
  777. }
  778. c.Header("Content-Type", "application/octet-stream")
  779. c.Header("Content-Disposition", "attachment; filename="+"bill.xlsx")
  780. c.Header("Content-Transfer-Encoding", "binary")
  781. err = f.Write(c.Writer)
  782. if err != nil {
  783. return nil, err
  784. }
  785. return nil, nil
  786. }
  787. // 创建生产计划
  788. func CreateProductPlan(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  789. var plan model.ProductPlan
  790. err := c.ShouldBindJSON(&plan)
  791. if err != nil {
  792. fmt.Println(err)
  793. return nil, errors.New("参数错误!")
  794. }
  795. if plan.Name == "" {
  796. return nil, errors.New("生产计划名为空")
  797. }
  798. if plan.Total == 0 {
  799. return nil, errors.New("生产计划数应不为0")
  800. }
  801. plan.Status = "process" // 进行中
  802. plan.CreateTime = time.Now()
  803. plan.UpdateTime = time.Now()
  804. result, err := repo.RepoAddDoc(apictx.CreateRepoCtx(), repo.CollectionProductPlan, &plan)
  805. return result, err
  806. }
  807. // 获取生产计划信息
  808. func GetProductPlan(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  809. planId := c.Param("id")
  810. id, err := primitive.ObjectIDFromHex(planId)
  811. if err != nil {
  812. return nil, errors.New("非法id")
  813. }
  814. var plan model.ProductPlan
  815. option := &repo.DocSearchOptions{
  816. CollectName: repo.CollectionProductPlan,
  817. Query: repo.Map{"_id": id},
  818. }
  819. found, err := repo.RepoSeachDoc(apictx.CreateRepoCtx(), option, &plan)
  820. if !found || err != nil {
  821. log.Info(err)
  822. return nil, errors.New("数据未找到")
  823. }
  824. billStates := map[string]string{}
  825. if plan.Pack != nil && plan.Pack.Components != nil {
  826. for _, comp := range plan.Pack.Components {
  827. if comp.Stages != nil {
  828. for _, stage := range comp.Stages {
  829. if len(stage.BillId) > 0 {
  830. collectName := ""
  831. // 材料
  832. if stage.BillType == 1 {
  833. collectName = repo.CollectionBillPurchase
  834. }
  835. // 工艺
  836. if stage.BillType == 2 {
  837. collectName = repo.CollectionBillProduce
  838. }
  839. // 成品
  840. if stage.BillType == 3 {
  841. collectName = repo.CollectionBillProduct
  842. }
  843. ok, state := repo.RepoSeachDocMap(apictx.CreateRepoCtx(), &repo.DocSearchOptions{CollectName: collectName, Query: repo.Map{"_id": stage.BillId}, Project: []string{"status"}})
  844. if ok {
  845. billStates[stage.BillId] = state["status"].(string)
  846. }
  847. }
  848. }
  849. }
  850. }
  851. }
  852. return map[string]interface{}{
  853. "plan": plan,
  854. "billStates": billStates,
  855. }, nil
  856. }
  857. // 获取生产计划列表
  858. func GetProductPlans(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  859. page, size, query := UtilQueryPageSize(c)
  860. if _packId, ok := query["packId"]; ok {
  861. packId, _ := primitive.ObjectIDFromHex(_packId.(string))
  862. query["pack._id"] = packId
  863. delete(query, "packId")
  864. }
  865. if _name, ok := query["name"]; ok {
  866. delete(query, "name")
  867. query["name"] = bson.M{"$regex": _name.(string)}
  868. }
  869. option := &repo.PageSearchOptions{
  870. CollectName: repo.CollectionProductPlan,
  871. Query: query,
  872. Page: page,
  873. Size: size,
  874. Sort: bson.M{"createTime": -1},
  875. Project: []string{"_id", "thumbnail", "name", "updateTime", "createTime", "createUser", "total", "totalPrice", "status"},
  876. }
  877. return repo.RepoPageSearch(apictx.CreateRepoCtx(), option)
  878. }
  879. // 更新生产计划
  880. func UpdateProductPlan(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  881. var plan model.ProductPlan
  882. err := c.ShouldBindJSON(&plan)
  883. if err != nil {
  884. return nil, errors.New("参数错误")
  885. }
  886. if plan.Id.Hex() == "" {
  887. return nil, errors.New("id的为空")
  888. }
  889. plan.UpdateTime = time.Now()
  890. return repo.RepoUpdateSetDoc(apictx.CreateRepoCtx(), repo.CollectionProductPlan, plan.Id.Hex(), &plan)
  891. }
  892. // 删除生产计划
  893. func DelProductPlan(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  894. planId := c.Param("id")
  895. if planId == "" {
  896. return nil, errors.New("id为空")
  897. }
  898. return repo.RepoDeleteDoc(apictx.CreateRepoCtx(), repo.CollectionProductPlan, planId)
  899. }