report.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954
  1. package api
  2. import (
  3. "archive/zip"
  4. "box-cost/db/model"
  5. "box-cost/db/repo"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "os"
  10. "path/filepath"
  11. "regexp"
  12. "strings"
  13. "sync"
  14. "time"
  15. "github.com/gin-gonic/gin"
  16. "github.com/go-redis/redis/v8"
  17. "github.com/xuri/excelize/v2"
  18. "go.mongodb.org/mongo-driver/bson"
  19. "go.mongodb.org/mongo-driver/bson/primitive"
  20. )
  21. // 统计报表 按时间范围,供应商 包装-计划(多选) 维度进行过滤,形成报表。可以下载
  22. func Report(r *GinRouter) {
  23. // 加工列表
  24. r.GETJWT("/report/produce/list", ReportProduceList)
  25. // 采购列表
  26. r.GETJWT("/report/purchase/list", ReportPurchaseList)
  27. r.GETJWT("/report/product/list", ReportProductList)
  28. r.GETJWT("/report/list", ReportList)
  29. r.GETJWT("/report/download", ReportListDownload)
  30. //
  31. r.GETJWT("/report/bills/download", ReportBillsDownload1)
  32. }
  33. // 下载单据
  34. func ReportBillsDownload1(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  35. _, _, query := UtilQueryPageSize(c)
  36. filtter := handleReportQuery(query)
  37. purchases := []*model.PurchaseBill{}
  38. produces := []*model.ProduceBill{}
  39. products := []*model.ProductBill{}
  40. repo.RepoDocsSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
  41. CollectName: repo.CollectionBillPurchase,
  42. Query: filtter,
  43. }, &purchases)
  44. repo.RepoDocsSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
  45. CollectName: repo.CollectionBillProduce,
  46. Query: filtter,
  47. }, &produces)
  48. repo.RepoDocsSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
  49. CollectName: repo.CollectionBillProduct,
  50. Query: filtter,
  51. }, &products)
  52. // 加入redis有序集合中进行排序
  53. // 把对应type_id:对象存入map中避免再次查询表
  54. typeBills := map[string]interface{}{}
  55. redisCli := apictx.Svc.Redis
  56. reportBillKey := "report-bill-list:" + apictx.User.Parent
  57. redisCli.Del(apictx.CreateRepoCtx().Ctx, reportBillKey)
  58. // isExist := redisCli.Exists(apictx.CreateRepoCtx().Ctx, reportBillKey).Val()
  59. // 不存在这个key时
  60. // if isExist < 1 {
  61. if len(purchases) > 0 {
  62. for _, purchase := range purchases {
  63. member := "purchase_" + purchase.Id.Hex()
  64. score := purchase.CompleteTime.Unix()
  65. redisCli.ZAdd(apictx.CreateRepoCtx().Ctx, reportBillKey, &redis.Z{Score: float64(score), Member: member})
  66. typeBills[member] = purchase
  67. }
  68. }
  69. if len(produces) > 0 {
  70. for _, produce := range produces {
  71. member := "produce_" + produce.Id.Hex()
  72. score := produce.CompleteTime.Unix()
  73. redisCli.ZAdd(apictx.CreateRepoCtx().Ctx, reportBillKey, &redis.Z{Score: float64(score), Member: member})
  74. typeBills[member] = produce
  75. }
  76. }
  77. if len(products) > 0 {
  78. for _, product := range products {
  79. member := "product_" + product.Id.Hex()
  80. score := product.CompleteTime.Unix()
  81. redisCli.ZAdd(apictx.CreateRepoCtx().Ctx, reportBillKey, &redis.Z{Score: float64(score), Member: member})
  82. typeBills[member] = product
  83. }
  84. }
  85. // 设置过期时间
  86. // redisCli.Expire(apictx.CreateRepoCtx().Ctx, reportBillKey, 1*time.Second)
  87. // }
  88. total, err := redisCli.ZCard(apictx.CreateRepoCtx().Ctx, reportBillKey).Uint64()
  89. fmt.Println("单据总数量: ", total)
  90. if err != nil {
  91. fmt.Println(err)
  92. return nil, err
  93. }
  94. reports, err := redisCli.ZRevRange(apictx.CreateRepoCtx().Ctx, reportBillKey, 0, -1).Result()
  95. if err != nil {
  96. return nil, err
  97. }
  98. if len(reports) < 1 {
  99. return nil, errors.New("没有单据信息")
  100. }
  101. // 获取供应商名称
  102. // supplier := &model.Supplier{}
  103. // repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  104. // CollectName: repo.CollectionSupplier,
  105. // Query: repo.Map{"_id": supplierId},
  106. // Project: []string{"name"},
  107. // }, supplier)
  108. ct := time.Now().Format("20060102150405")
  109. // 下载文件的名字
  110. // eName := fmt.Sprintf("统计单据_%s", ct)
  111. companyName := getCompanyName(apictx)
  112. zipName := fmt.Sprintf("统计单据_%s", ct)
  113. // 获取订单信息下载
  114. saveTmpDir := fmt.Sprintf("tmp1/report/%s", zipName)
  115. if isExistDir(saveTmpDir) {
  116. os.RemoveAll(saveTmpDir)
  117. }
  118. f := excelize.NewFile()
  119. f.SetDefaultFont("宋体")
  120. flagIndex := -1
  121. // 采购 加工 加工-印刷 加工-覆膜 加工-对裱 成品采购
  122. typeRows := []int{0, 0, 0, 0, 0, 0}
  123. for _, tId := range reports {
  124. var billExcel IExcel
  125. // 采购
  126. if strings.Contains(tId, "purchase") {
  127. purchase := typeBills[tId].(*model.PurchaseBill)
  128. sheetName := "采购单"
  129. index := f.NewSheet(sheetName)
  130. if flagIndex < 0 {
  131. flagIndex = index
  132. }
  133. billExcel = NewPurchaseBill(f)
  134. billExcel.SetSheetName(sheetName)
  135. // 获取签名信息
  136. if purchase.Reviewed == 1 {
  137. if len(purchase.SignUsers) > 0 {
  138. signs := []*model.Signature{}
  139. repo.RepoDocsSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
  140. CollectName: repo.CollectionSignature,
  141. Query: repo.Map{"_id": bson.M{"$in": purchase.SignUsers}},
  142. Sort: bson.M{"sort": 1},
  143. }, &signs)
  144. billExcel.SetSignatures(signs)
  145. }
  146. }
  147. // 获取计划名
  148. // plan := &model.ProductPlan{}
  149. // repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  150. // CollectName: repo.CollectionProductPlan,
  151. // Query: repo.Map{"_id": purchase.PlanId},
  152. // Project: []string{"name"},
  153. // }, plan)
  154. // productName = purchase.ProductName
  155. // supplierName = purchase.Supplier
  156. // serialNumber = purchase.SerialNumber
  157. billExcel.SetContent(purchase)
  158. billExcel.SetTitle(fmt.Sprintf("%s原材料采购单", companyName))
  159. billExcel.SetRow(typeRows[0])
  160. billExcel.Draws()
  161. typeRows[0] = billExcel.GetRow() + 5
  162. }
  163. // 加工单
  164. if strings.Contains(tId, "produce") {
  165. produce := typeBills[tId].(*model.ProduceBill)
  166. sheetName := "加工单"
  167. if produce.IsPrint {
  168. sheetName = "加工单-印刷"
  169. } else if produce.IsLam {
  170. sheetName = "加工单-覆膜"
  171. } else if produce.IsPaper {
  172. sheetName = "加工单-对裱"
  173. }
  174. index := f.NewSheet(sheetName)
  175. if flagIndex < 0 {
  176. flagIndex = index
  177. }
  178. billExcel = NewProduceBill(f)
  179. billExcel.SetSheetName(sheetName)
  180. // 获取签名信息
  181. if produce.Reviewed == 1 {
  182. if len(produce.SignUsers) > 0 {
  183. signs := []*model.Signature{}
  184. repo.RepoDocsSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
  185. CollectName: repo.CollectionSignature,
  186. Query: repo.Map{"_id": bson.M{"$in": produce.SignUsers}},
  187. Sort: bson.M{"sort": 1},
  188. }, &signs)
  189. billExcel.SetSignatures(signs)
  190. }
  191. }
  192. // 获取计划名
  193. // plan := &model.ProductPlan{}
  194. // repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  195. // CollectName: repo.CollectionProductPlan,
  196. // Query: repo.Map{"_id": produce.PlanId},
  197. // Project: []string{"name"},
  198. // }, plan)
  199. billExcel.SetContent(produce)
  200. billExcel.SetTitle(fmt.Sprintf("%s加工单", companyName))
  201. if produce.IsPrint {
  202. billExcel.SetRow(typeRows[2])
  203. billExcel.Draws()
  204. typeRows[2] = billExcel.GetRow() + 5
  205. } else if produce.IsLam {
  206. billExcel.SetRow(typeRows[3])
  207. billExcel.Draws()
  208. typeRows[3] = billExcel.GetRow() + 5
  209. } else if produce.IsPaper {
  210. billExcel.SetRow(typeRows[4])
  211. billExcel.Draws()
  212. typeRows[4] = billExcel.GetRow() + 5
  213. } else {
  214. billExcel.SetRow(typeRows[1])
  215. billExcel.Draws()
  216. typeRows[1] = billExcel.GetRow() + 5
  217. }
  218. }
  219. // 成品
  220. if strings.Contains(tId, "product") {
  221. product := typeBills[tId].(*model.ProductBill)
  222. sheetName := "成品采购单"
  223. index := f.NewSheet(sheetName)
  224. if flagIndex < 0 {
  225. flagIndex = index
  226. }
  227. billExcel = NewProductBill(f)
  228. billExcel.SetSheetName(sheetName)
  229. // 获取签名信息
  230. if product.Reviewed == 1 {
  231. if len(product.SignUsers) > 0 {
  232. signs := []*model.Signature{}
  233. repo.RepoDocsSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
  234. CollectName: repo.CollectionSignature,
  235. Query: repo.Map{"_id": bson.M{"$in": product.SignUsers}},
  236. Sort: bson.M{"sort": 1},
  237. }, &signs)
  238. billExcel.SetSignatures(signs)
  239. }
  240. }
  241. // 获取计划名
  242. // plan := &model.ProductPlan{}
  243. // repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  244. // CollectName: repo.CollectionProductPlan,
  245. // Query: repo.Map{"_id": product.PlanId},
  246. // Project: []string{"name"},
  247. // }, plan)
  248. billExcel.SetContent(product)
  249. billExcel.SetTitle(companyName)
  250. billExcel.SetRow(typeRows[5])
  251. billExcel.Draws()
  252. typeRows[5] = billExcel.GetRow() + 5
  253. }
  254. }
  255. // 设置活跃sheet
  256. f.SetActiveSheet(flagIndex)
  257. // 删除默认Sheet1
  258. f.DeleteSheet("Sheet1")
  259. buf, _ := f.WriteToBuffer()
  260. targeName := fmt.Sprintf("%s.xlsx", zipName)
  261. err = saveExcelToTmp1(saveTmpDir, targeName, buf.Bytes())
  262. if err != nil {
  263. return nil, err
  264. }
  265. c.Header("Content-Type", "application/octet-stream")
  266. c.Header("Content-Disposition", "attachment; filename="+fmt.Sprintf("%s.zip", zipName))
  267. c.Header("Content-Transfer-Encoding", "binary")
  268. archive := zip.NewWriter(c.Writer)
  269. defer archive.Close()
  270. // 遍历路径信息
  271. filepath.Walk(saveTmpDir, func(path string, info os.FileInfo, _ error) error {
  272. // 如果是源路径,提前进行下一个遍历
  273. if path == saveTmpDir {
  274. return nil
  275. }
  276. // 获取:文件头信息
  277. header, _ := zip.FileInfoHeader(info)
  278. header.Name = strings.TrimPrefix(path, saveTmpDir+`/`)
  279. // 判断:文件是不是文件夹
  280. if info.IsDir() {
  281. header.Name += `/`
  282. } else {
  283. // 设置:zip的文件压缩算法
  284. header.Method = zip.Deflate
  285. }
  286. // 创建:压缩包头部信息
  287. writer, _ := archive.CreateHeader(header)
  288. if !info.IsDir() {
  289. file, _ := os.Open(path)
  290. defer file.Close()
  291. io.Copy(writer, file)
  292. }
  293. return nil
  294. })
  295. // 删除缓存目录
  296. os.RemoveAll(saveTmpDir)
  297. return nil, nil
  298. }
  299. // 下载单据
  300. //
  301. // !更改为ReportBillsDownload1 确定不需要后删除
  302. func ReportBillsDownload(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  303. _, _, query := UtilQueryPageSize(c)
  304. // supplierId := primitive.NilObjectID
  305. // if _supplierId, ok := query["supplierId"]; ok {
  306. // supplierId, _ = primitive.ObjectIDFromHex(_supplierId.(string))
  307. // }
  308. _isPdf := "false"
  309. if isPdf, ok := query["isPdf"]; ok {
  310. delete(query, "isPdf")
  311. if isPdf.(string) == "true" {
  312. _isPdf = "true"
  313. }
  314. }
  315. // timeRange := []interface{}{}
  316. // if _timeRange, ok := query["timeRange"]; ok {
  317. // timeRange, _ = _timeRange.([]interface{})
  318. // }
  319. filtter := handleReportQuery(query)
  320. purchases := []*model.PurchaseBill{}
  321. produces := []*model.ProduceBill{}
  322. products := []*model.ProductBill{}
  323. repo.RepoDocsSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
  324. CollectName: repo.CollectionBillPurchase,
  325. Query: filtter,
  326. }, &purchases)
  327. repo.RepoDocsSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
  328. CollectName: repo.CollectionBillProduce,
  329. Query: filtter,
  330. }, &produces)
  331. repo.RepoDocsSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
  332. CollectName: repo.CollectionBillProduct,
  333. Query: filtter,
  334. }, &products)
  335. // 加入redis有序集合中进行排序
  336. // 把对应type_id:对象存入map中避免再次查询表
  337. typeBills := map[string]interface{}{}
  338. redisCli := apictx.Svc.Redis
  339. reportBillKey := "report-bill-list:" + apictx.User.Parent
  340. redisCli.Del(apictx.CreateRepoCtx().Ctx, reportBillKey)
  341. // isExist := redisCli.Exists(apictx.CreateRepoCtx().Ctx, reportBillKey).Val()
  342. // 不存在这个key时
  343. // if isExist < 1 {
  344. if len(purchases) > 0 {
  345. for _, purchase := range purchases {
  346. member := "purchase_" + purchase.Id.Hex()
  347. score := purchase.CompleteTime.Unix()
  348. redisCli.ZAdd(apictx.CreateRepoCtx().Ctx, reportBillKey, &redis.Z{Score: float64(score), Member: member})
  349. typeBills[member] = purchase
  350. }
  351. }
  352. if len(produces) > 0 {
  353. for _, produce := range produces {
  354. member := "produce_" + produce.Id.Hex()
  355. score := produce.CompleteTime.Unix()
  356. redisCli.ZAdd(apictx.CreateRepoCtx().Ctx, reportBillKey, &redis.Z{Score: float64(score), Member: member})
  357. typeBills[member] = produce
  358. }
  359. }
  360. if len(products) > 0 {
  361. for _, product := range products {
  362. member := "product_" + product.Id.Hex()
  363. score := product.CompleteTime.Unix()
  364. redisCli.ZAdd(apictx.CreateRepoCtx().Ctx, reportBillKey, &redis.Z{Score: float64(score), Member: member})
  365. typeBills[member] = product
  366. }
  367. }
  368. // 设置过期时间
  369. // redisCli.Expire(apictx.CreateRepoCtx().Ctx, reportBillKey, 1*time.Second)
  370. // }
  371. total, err := redisCli.ZCard(apictx.CreateRepoCtx().Ctx, reportBillKey).Uint64()
  372. fmt.Println("单据总数量: ", total)
  373. if err != nil {
  374. fmt.Println(err)
  375. return nil, err
  376. }
  377. reports, err := redisCli.ZRevRange(apictx.CreateRepoCtx().Ctx, reportBillKey, 0, -1).Result()
  378. if err != nil {
  379. return nil, err
  380. }
  381. if len(reports) < 1 {
  382. return nil, errors.New("没有单据信息")
  383. }
  384. // 获取供应商名称
  385. // supplier := &model.Supplier{}
  386. // repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  387. // CollectName: repo.CollectionSupplier,
  388. // Query: repo.Map{"_id": supplierId},
  389. // Project: []string{"name"},
  390. // }, supplier)
  391. r := regexp.MustCompile(`/`)
  392. ct := time.Now().Format("20060102150405")
  393. zipName := fmt.Sprintf("统计单据_%s", ct)
  394. // 获取订单信息下载
  395. saveTmpDir := fmt.Sprintf("tmp1/report/%s", zipName)
  396. if isExistDir(saveTmpDir) {
  397. os.RemoveAll(saveTmpDir)
  398. }
  399. // 记录文件数量
  400. var wg sync.WaitGroup
  401. c1 := make(chan int, 10)
  402. for _, tId := range reports {
  403. productName := ""
  404. supplierName := ""
  405. serialNumber := ""
  406. f := excelize.NewFile()
  407. index := f.NewSheet("Sheet1")
  408. f.SetActiveSheet(index)
  409. f.SetDefaultFont("宋体")
  410. tidArr := strings.Split(tId, "_")
  411. var billExcel IExcel
  412. // 采购
  413. if tidArr[0] == "purchase" {
  414. purchase := typeBills[tId].(*model.PurchaseBill)
  415. billExcel = NewPurchaseBill(f)
  416. // 获取签名信息
  417. if purchase.Reviewed == 1 {
  418. if len(purchase.SignUsers) > 0 {
  419. signs := []*model.Signature{}
  420. repo.RepoDocsSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
  421. CollectName: repo.CollectionSignature,
  422. Query: repo.Map{"_id": bson.M{"$in": purchase.SignUsers}},
  423. Sort: bson.M{"sort": 1},
  424. }, &signs)
  425. billExcel.SetSignatures(signs)
  426. }
  427. }
  428. // 获取计划名
  429. plan := &model.ProductPlan{}
  430. repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  431. CollectName: repo.CollectionProductPlan,
  432. Query: repo.Map{"_id": purchase.PlanId},
  433. Project: []string{"name"},
  434. }, plan)
  435. productName = purchase.ProductName
  436. supplierName = purchase.Supplier
  437. serialNumber = purchase.SerialNumber
  438. billExcel.SetContent(purchase)
  439. billExcel.SetTitle(fmt.Sprintf("%s原材料采购单", plan.Name))
  440. }
  441. // 工艺
  442. if tidArr[0] == "produce" {
  443. produce := typeBills[tId].(*model.ProduceBill)
  444. billExcel = NewProduceBill(f)
  445. if produce.Reviewed == 1 {
  446. if len(produce.SignUsers) > 0 {
  447. signs := []*model.Signature{}
  448. repo.RepoDocsSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
  449. CollectName: repo.CollectionSignature,
  450. Query: repo.Map{"_id": bson.M{"$in": produce.SignUsers}},
  451. Sort: bson.M{"sort": 1},
  452. }, &signs)
  453. billExcel.SetSignatures(signs)
  454. }
  455. }
  456. // 获取计划名
  457. plan := &model.ProductPlan{}
  458. repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  459. CollectName: repo.CollectionProductPlan,
  460. Query: repo.Map{"_id": produce.PlanId},
  461. Project: []string{"name"},
  462. }, plan)
  463. productName = produce.ProductName
  464. supplierName = produce.Supplier
  465. serialNumber = produce.SerialNumber
  466. billExcel.SetContent(produce)
  467. billExcel.SetTitle(fmt.Sprintf("%s加工单", plan.Name))
  468. }
  469. // 成品采购
  470. if tidArr[0] == "product" {
  471. product := typeBills[tId].(*model.ProductBill)
  472. billExcel = NewProductBill(f)
  473. if product.Reviewed == 1 {
  474. if len(product.SignUsers) > 0 {
  475. signs := []*model.Signature{}
  476. repo.RepoDocsSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
  477. CollectName: repo.CollectionSignature,
  478. Query: repo.Map{"_id": bson.M{"$in": product.SignUsers}},
  479. Sort: bson.M{"sort": 1},
  480. }, &signs)
  481. billExcel.SetSignatures(signs)
  482. }
  483. }
  484. // 获取计划名
  485. plan := &model.ProductPlan{}
  486. repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  487. CollectName: repo.CollectionProductPlan,
  488. Query: repo.Map{"_id": product.PlanId},
  489. Project: []string{"name"},
  490. }, plan)
  491. productName = product.ProductName
  492. supplierName = product.Supplier
  493. serialNumber = product.SerialNumber
  494. billExcel.SetContent(product)
  495. billExcel.SetTitle(plan.Name)
  496. }
  497. billExcel.SetIsPdf(_isPdf)
  498. billExcel.Draws()
  499. buf, _ := f.WriteToBuffer()
  500. ft := "xlsx"
  501. if _isPdf == "true" {
  502. ft = "pdf"
  503. }
  504. _productName := r.ReplaceAllString(productName, `&`)
  505. _supplierName := r.ReplaceAllString(supplierName, `&`)
  506. targePdfName := fmt.Sprintf("%s-%s-%s.%s", _supplierName, _productName, serialNumber, ft)
  507. wg.Add(1)
  508. if _isPdf == "true" {
  509. go toPdfAndSaveTask(buf, apictx.Svc.Conf.PdfApiAddr, saveTmpDir, targePdfName, c1, &wg)
  510. } else {
  511. go saveExcelToTmp(saveTmpDir, targePdfName, buf.Bytes(), c1, &wg)
  512. }
  513. }
  514. go func() {
  515. // 等待所有goroutine
  516. wg.Wait()
  517. // 关闭channel
  518. close(c1)
  519. }()
  520. // channel关闭后结束后停止遍历接收channel中的值
  521. for n := range c1 {
  522. if n == -1 {
  523. return nil, errors.New("下载失败,请重试")
  524. }
  525. }
  526. c.Header("Content-Type", "application/octet-stream")
  527. c.Header("Content-Disposition", "attachment; filename="+zipName+".zip")
  528. c.Header("Content-Transfer-Encoding", "binary")
  529. archive := zip.NewWriter(c.Writer)
  530. defer archive.Close()
  531. // 遍历路径信息
  532. filepath.Walk(saveTmpDir, func(path string, info os.FileInfo, _ error) error {
  533. // 如果是源路径,提前进行下一个遍历
  534. if path == saveTmpDir {
  535. return nil
  536. }
  537. // 获取:文件头信息
  538. header, _ := zip.FileInfoHeader(info)
  539. header.Name = strings.TrimPrefix(path, saveTmpDir+`/`)
  540. // 判断:文件是不是文件夹
  541. if info.IsDir() {
  542. header.Name += `/`
  543. } else {
  544. // 设置:zip的文件压缩算法
  545. header.Method = zip.Deflate
  546. }
  547. // 创建:压缩包头部信息
  548. writer, _ := archive.CreateHeader(header)
  549. if !info.IsDir() {
  550. file, _ := os.Open(path)
  551. defer file.Close()
  552. io.Copy(writer, file)
  553. }
  554. return nil
  555. })
  556. // 删除缓存目录
  557. os.RemoveAll(saveTmpDir)
  558. return nil, nil
  559. }
  560. // 加工单
  561. func ReportListDownload(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  562. _, _, query := UtilQueryPageSize(c)
  563. // start, stop := CreatePageRange(page, size)
  564. supplierId := primitive.NilObjectID
  565. if _supplierId, ok := query["supplierId"]; ok {
  566. supplierId, _ = primitive.ObjectIDFromHex(_supplierId.(string))
  567. }
  568. timeRange := []interface{}{}
  569. if _timeRange, ok := query["timeRange"]; ok {
  570. timeRange, _ = _timeRange.([]interface{})
  571. }
  572. filtter := handleReportQuery(query)
  573. purchases := []*model.PurchaseBill{}
  574. produces := []*model.ProduceBill{}
  575. products := []*model.ProductBill{}
  576. repo.RepoDocsSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
  577. CollectName: repo.CollectionBillPurchase,
  578. Query: filtter,
  579. Project: []string{"_id", "completeTime"},
  580. }, &purchases)
  581. repo.RepoDocsSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
  582. CollectName: repo.CollectionBillProduce,
  583. Query: filtter,
  584. Project: []string{"_id", "completeTime"},
  585. }, &produces)
  586. repo.RepoDocsSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
  587. CollectName: repo.CollectionBillProduct,
  588. Query: filtter,
  589. Project: []string{"_id", "completeTime"},
  590. }, &products)
  591. // 加入redis有序集合中
  592. redisCli := apictx.Svc.Redis
  593. reportBillKey := "report-bill-list:" + apictx.User.Parent
  594. redisCli.Del(apictx.CreateRepoCtx().Ctx, reportBillKey)
  595. // isExist := redisCli.Exists(apictx.CreateRepoCtx().Ctx, reportBillKey).Val()
  596. // 不存在这个key时
  597. // if isExist < 1 {
  598. if len(purchases) > 0 {
  599. for _, purchase := range purchases {
  600. member := "purchase_" + purchase.Id.Hex()
  601. score := purchase.CompleteTime.Unix()
  602. redisCli.ZAdd(apictx.CreateRepoCtx().Ctx, reportBillKey, &redis.Z{Score: float64(score), Member: member})
  603. }
  604. }
  605. if len(produces) > 0 {
  606. for _, produce := range produces {
  607. member := "produce_" + produce.Id.Hex()
  608. score := produce.CompleteTime.Unix()
  609. redisCli.ZAdd(apictx.CreateRepoCtx().Ctx, reportBillKey, &redis.Z{Score: float64(score), Member: member})
  610. }
  611. }
  612. if len(products) > 0 {
  613. for _, product := range products {
  614. member := "product_" + product.Id.Hex()
  615. score := product.CompleteTime.Unix()
  616. redisCli.ZAdd(apictx.CreateRepoCtx().Ctx, reportBillKey, &redis.Z{Score: float64(score), Member: member})
  617. }
  618. }
  619. // 设置过期时间
  620. // redisCli.Expire(apictx.CreateRepoCtx().Ctx, reportBillKey, 1*time.Second)
  621. // }
  622. total, err := redisCli.ZCard(apictx.CreateRepoCtx().Ctx, reportBillKey).Uint64()
  623. fmt.Println(total)
  624. if err != nil {
  625. fmt.Println(err)
  626. return nil, err
  627. }
  628. reports, err := redisCli.ZRevRange(apictx.CreateRepoCtx().Ctx, reportBillKey, 0, -1).Result()
  629. if err != nil {
  630. return nil, err
  631. }
  632. if len(reports) < 1 {
  633. return nil, errors.New("没有单据信息")
  634. }
  635. lists := []map[string]interface{}{}
  636. for _, report := range reports {
  637. billArray := strings.Split(report, "_")
  638. billType := billArray[0]
  639. _billId := billArray[1]
  640. billId, _ := primitive.ObjectIDFromHex(_billId)
  641. billData := map[string]interface{}{}
  642. found := false
  643. if billType == "purchase" {
  644. found, billData = repo.RepoSeachDocMap(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  645. CollectName: repo.CollectionBillPurchase,
  646. Query: repo.Map{"_id": billId},
  647. })
  648. }
  649. if billType == "produce" {
  650. found, billData = repo.RepoSeachDocMap(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  651. CollectName: repo.CollectionBillProduce,
  652. Query: repo.Map{"_id": billId},
  653. })
  654. }
  655. if billType == "product" {
  656. found, billData = repo.RepoSeachDocMap(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  657. CollectName: repo.CollectionBillProduct,
  658. Query: repo.Map{"_id": billId},
  659. })
  660. }
  661. if found {
  662. billData["billType"] = billType
  663. lists = append(lists, billData)
  664. }
  665. }
  666. f := excelize.NewFile()
  667. defer f.Close()
  668. index := f.NewSheet("Sheet1")
  669. f.SetActiveSheet(index)
  670. f.SetDefaultFont("宋体")
  671. report := NewReportExcel(f)
  672. supplier := model.Supplier{}
  673. supplierName := "【所有供应商】"
  674. if !supplierId.IsZero() {
  675. repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  676. CollectName: repo.CollectionSupplier,
  677. Query: repo.Map{"_id": supplierId},
  678. Project: []string{"name"},
  679. }, &supplier)
  680. supplierName = supplier.Name
  681. }
  682. report.SupplierName = supplierName
  683. if len(timeRange) == 2 {
  684. report.TimeRange = append(report.TimeRange, timeRange[0].(string), timeRange[1].(string))
  685. }
  686. report.Content = lists
  687. report.Draws()
  688. c.Header("Content-Type", "application/octet-stream")
  689. c.Header("Content-Disposition", "attachment; filename="+"report.xlsx")
  690. c.Header("Content-Transfer-Encoding", "binary")
  691. err = f.Write(c.Writer)
  692. if err != nil {
  693. return nil, err
  694. }
  695. return nil, nil
  696. }
  697. // 加工单
  698. func ReportList(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  699. page, size, query := UtilQueryPageSize(c)
  700. start, stop := CreatePageRange(page, size)
  701. filtter := handleReportQuery(query)
  702. purchases := []*model.PurchaseBill{}
  703. produces := []*model.ProduceBill{}
  704. products := []*model.ProductBill{}
  705. repo.RepoDocsSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
  706. CollectName: repo.CollectionBillPurchase,
  707. Query: filtter,
  708. Project: []string{"_id", "completeTime"},
  709. }, &purchases)
  710. repo.RepoDocsSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
  711. CollectName: repo.CollectionBillProduce,
  712. Query: filtter,
  713. Project: []string{"_id", "completeTime"},
  714. }, &produces)
  715. repo.RepoDocsSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
  716. CollectName: repo.CollectionBillProduct,
  717. Query: filtter,
  718. Project: []string{"_id", "completeTime"},
  719. }, &products)
  720. // 加入redis有序集合中
  721. redisCli := apictx.Svc.Redis
  722. reportBillKey := "report-bill-list:" + apictx.User.Parent
  723. redisCli.Del(apictx.CreateRepoCtx().Ctx, reportBillKey)
  724. // isExist := redisCli.Exists(apictx.CreateRepoCtx().Ctx, reportBillKey).Val()
  725. // 不存在这个key时
  726. // if isExist < 1 {
  727. if len(purchases) > 0 {
  728. for _, purchase := range purchases {
  729. member := "purchase_" + purchase.Id.Hex()
  730. score := purchase.CompleteTime.Unix()
  731. redisCli.ZAdd(apictx.CreateRepoCtx().Ctx, reportBillKey, &redis.Z{Score: float64(score), Member: member})
  732. }
  733. }
  734. if len(produces) > 0 {
  735. for _, produce := range produces {
  736. member := "produce_" + produce.Id.Hex()
  737. score := produce.CompleteTime.Unix()
  738. redisCli.ZAdd(apictx.CreateRepoCtx().Ctx, reportBillKey, &redis.Z{Score: float64(score), Member: member})
  739. }
  740. }
  741. if len(products) > 0 {
  742. for _, product := range products {
  743. member := "product_" + product.Id.Hex()
  744. score := product.CompleteTime.Unix()
  745. redisCli.ZAdd(apictx.CreateRepoCtx().Ctx, reportBillKey, &redis.Z{Score: float64(score), Member: member})
  746. }
  747. }
  748. // 设置过期时间
  749. // redisCli.Expire(apictx.CreateRepoCtx().Ctx, reportBillKey, 1*time.Second)
  750. // }
  751. total, err := redisCli.ZCard(apictx.CreateRepoCtx().Ctx, reportBillKey).Uint64()
  752. if err != nil {
  753. fmt.Println(err)
  754. return nil, err
  755. }
  756. reports, err := redisCli.ZRevRange(apictx.CreateRepoCtx().Ctx, reportBillKey, start, stop).Result()
  757. if err != nil {
  758. return nil, err
  759. }
  760. if len(reports) < 1 {
  761. return repo.PageResult{
  762. List: []map[string]interface{}{},
  763. Page: page,
  764. Size: size,
  765. Total: 0,
  766. }, nil
  767. }
  768. lists := []map[string]interface{}{}
  769. for _, report := range reports {
  770. billArray := strings.Split(report, "_")
  771. billType := billArray[0]
  772. _billId := billArray[1]
  773. billId, _ := primitive.ObjectIDFromHex(_billId)
  774. billData := map[string]interface{}{}
  775. found := false
  776. if billType == "purchase" {
  777. found, billData = repo.RepoSeachDocMap(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  778. CollectName: repo.CollectionBillPurchase,
  779. Query: repo.Map{"_id": billId},
  780. })
  781. }
  782. if billType == "produce" {
  783. found, billData = repo.RepoSeachDocMap(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  784. CollectName: repo.CollectionBillProduce,
  785. Query: repo.Map{"_id": billId},
  786. })
  787. }
  788. if billType == "product" {
  789. found, billData = repo.RepoSeachDocMap(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  790. CollectName: repo.CollectionBillProduct,
  791. Query: repo.Map{"_id": billId},
  792. })
  793. }
  794. if found {
  795. billData["billType"] = billType
  796. lists = append(lists, billData)
  797. }
  798. }
  799. return repo.PageResult{
  800. List: lists,
  801. Total: int64(total),
  802. Page: page,
  803. Size: size,
  804. }, nil
  805. }
  806. func CreatePageRange(page, size int64) (int64, int64) {
  807. if page < 1 {
  808. page = 1
  809. }
  810. if size < 1 {
  811. size = 10
  812. }
  813. start := (page - 1) * size
  814. stop := page*size - 1
  815. return start, stop
  816. }
  817. func ReportProduceList(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  818. page, size, query := UtilQueryPageSize(c)
  819. // 条件处理
  820. // 获取采购单符合条件的信息
  821. return repo.RepoPageSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
  822. CollectName: repo.CollectionBillProduce,
  823. Query: handleReportQuery(query),
  824. Page: page,
  825. Size: size,
  826. })
  827. }
  828. // 采购单
  829. func ReportPurchaseList(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  830. page, size, query := UtilQueryPageSize(c)
  831. return repo.RepoPageSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
  832. CollectName: repo.CollectionBillPurchase,
  833. Query: handleReportQuery(query),
  834. Page: page,
  835. Size: size,
  836. })
  837. }
  838. func ReportProductList(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  839. page, size, query := UtilQueryPageSize(c)
  840. return repo.RepoPageSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
  841. CollectName: repo.CollectionBillProduct,
  842. Query: handleReportQuery(query),
  843. Page: page,
  844. Size: size,
  845. })
  846. }