plan.go 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052
  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.POSTJWT("/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. // 创建生产计划
  769. func CreateProductPlan(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  770. var plan model.ProductPlan
  771. err := c.ShouldBindJSON(&plan)
  772. if err != nil {
  773. fmt.Println(err)
  774. return nil, errors.New("参数错误!")
  775. }
  776. if plan.Name == "" {
  777. return nil, errors.New("生产计划名为空")
  778. }
  779. if plan.Total == 0 {
  780. return nil, errors.New("生产计划数应不为0")
  781. }
  782. plan.Status = "process" // 进行中
  783. plan.CreateTime = time.Now()
  784. plan.UpdateTime = time.Now()
  785. result, err := repo.RepoAddDoc(apictx.CreateRepoCtx(), repo.CollectionProductPlan, &plan)
  786. return result, err
  787. }
  788. // 获取生产计划信息
  789. func GetProductPlan(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  790. planId := c.Param("id")
  791. id, err := primitive.ObjectIDFromHex(planId)
  792. if err != nil {
  793. return nil, errors.New("非法id")
  794. }
  795. var plan model.ProductPlan
  796. option := &repo.DocSearchOptions{
  797. CollectName: repo.CollectionProductPlan,
  798. Query: repo.Map{"_id": id},
  799. }
  800. found, err := repo.RepoSeachDoc(apictx.CreateRepoCtx(), option, &plan)
  801. if !found || err != nil {
  802. log.Info(err)
  803. return nil, errors.New("数据未找到")
  804. }
  805. billData := map[string]interface{}{}
  806. if plan.Pack != nil && plan.Pack.Components != nil {
  807. for _, comp := range plan.Pack.Components {
  808. if comp.Stages != nil {
  809. for _, stage := range comp.Stages {
  810. if len(stage.BillId) > 0 {
  811. collectName := ""
  812. // 材料
  813. if stage.BillType == 1 {
  814. collectName = repo.CollectionBillPurchase
  815. }
  816. // 工艺
  817. if stage.BillType == 2 {
  818. collectName = repo.CollectionBillProduce
  819. }
  820. // 成品
  821. if stage.BillType == 3 {
  822. collectName = repo.CollectionBillProduct
  823. }
  824. ok, state := repo.RepoSeachDocMap(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  825. CollectName: collectName,
  826. Query: repo.Map{"_id": stage.BillId},
  827. // Project: []string{"status", "isSend", "reviewed", "isAck", "serialNumber", "sendTo", "remark"}
  828. })
  829. if ok {
  830. billData[stage.BillId] = state
  831. }
  832. }
  833. }
  834. }
  835. }
  836. }
  837. return map[string]interface{}{
  838. "plan": plan,
  839. "billData": billData,
  840. }, nil
  841. }
  842. // 获取生产计划列表
  843. func GetProductPlans(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  844. page, size, query := UtilQueryPageSize(c)
  845. if _packId, ok := query["packId"]; ok {
  846. packId, _ := primitive.ObjectIDFromHex(_packId.(string))
  847. query["pack._id"] = packId
  848. delete(query, "packId")
  849. }
  850. if _name, ok := query["name"]; ok {
  851. delete(query, "name")
  852. query["name"] = bson.M{"$regex": _name.(string)}
  853. }
  854. option := &repo.PageSearchOptions{
  855. CollectName: repo.CollectionProductPlan,
  856. Query: query,
  857. Page: page,
  858. Size: size,
  859. Sort: bson.M{"createTime": -1},
  860. Project: []string{"_id", "thumbnail", "name", "updateTime", "createTime", "createUser", "total", "totalPrice", "status"},
  861. }
  862. return repo.RepoPageSearch(apictx.CreateRepoCtx(), option)
  863. }
  864. // 更新生产计划
  865. func UpdateProductPlan(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  866. var plan model.ProductPlan
  867. err := c.ShouldBindJSON(&plan)
  868. if err != nil {
  869. fmt.Println(err)
  870. log.Error(err)
  871. return nil, errors.New("参数错误")
  872. }
  873. if plan.Id.Hex() == "" {
  874. return nil, errors.New("id的为空")
  875. }
  876. plan.UpdateTime = time.Now()
  877. return repo.RepoUpdateSetDoc(apictx.CreateRepoCtx(), repo.CollectionProductPlan, plan.Id.Hex(), &plan)
  878. }
  879. // 删除生产计划
  880. func DelProductPlan(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  881. userId, _ := primitive.ObjectIDFromHex(apictx.User.Parent)
  882. if userId.IsZero() {
  883. return nil, errors.New("用户错误,请重新登录")
  884. }
  885. _planId := c.Param("id")
  886. planId, _ := primitive.ObjectIDFromHex(_planId)
  887. if planId.IsZero() {
  888. return nil, errors.New("计划id错误")
  889. }
  890. plan := model.ProductPlan{}
  891. found, err := repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  892. CollectName: repo.CollectionProductPlan,
  893. Query: repo.Map{"_id": planId},
  894. }, &plan)
  895. if !found || err != nil {
  896. return nil, errors.New("计划数据未找到")
  897. }
  898. res, err := repo.RepoDeleteDoc(apictx.CreateRepoCtx(), repo.CollectionProductPlan, _planId)
  899. // 删除计划对应订单
  900. if err == nil {
  901. // 获取所有stages单据id
  902. billIds := make([]string, 0)
  903. for _, comp := range plan.Pack.Components {
  904. if comp.Id == "" || len(comp.Stages) == 0 {
  905. continue
  906. }
  907. for _, stage := range comp.Stages {
  908. billId, _ := primitive.ObjectIDFromHex(stage.BillId)
  909. if !billId.IsZero() {
  910. billIds = append(billIds, fmt.Sprintf("%d_%s", stage.BillType, stage.BillId))
  911. }
  912. }
  913. }
  914. // 去重单据号
  915. typeBillIds := removeDuplicationSort(billIds)
  916. if len(typeBillIds) < 1 {
  917. return res, err
  918. }
  919. for _, tId := range typeBillIds {
  920. tidArr := strings.Split(tId, "_")
  921. // 采购
  922. if tidArr[0] == "1" {
  923. repo.RepoDeleteDoc(apictx.CreateRepoCtx(), repo.CollectionBillPurchase, tidArr[1])
  924. }
  925. // 工艺
  926. if tidArr[0] == "2" {
  927. repo.RepoDeleteDoc(apictx.CreateRepoCtx(), repo.CollectionBillProduce, tidArr[1])
  928. }
  929. // 成品采购
  930. if tidArr[0] == "3" {
  931. repo.RepoDeleteDoc(apictx.CreateRepoCtx(), repo.CollectionBillProduct, tidArr[1])
  932. }
  933. }
  934. }
  935. return res, err
  936. }