plan.go 39 KB

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