plan.go 33 KB

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