plan.go 38 KB

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