plan.go 31 KB

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