智慧食堂
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2838 lines
119 KiB

  1. package svc
  2. import (
  3. "applet/app/admin/md"
  4. "applet/app/db"
  5. "applet/app/db/model"
  6. "applet/app/enum"
  7. "applet/app/utils"
  8. "applet/app/utils/logx"
  9. "archive/zip"
  10. "encoding/json"
  11. "fmt"
  12. "github.com/360EntSecGroup-Skylar/excelize"
  13. "github.com/syyongx/php2go"
  14. "io"
  15. "os"
  16. "strconv"
  17. "strings"
  18. "time"
  19. )
  20. func NursingHomeDataStatisticsExport(req md.NursingHomeDataStatisticsExportReq) {
  21. var titleList []string
  22. var fileName string
  23. var now = time.Now()
  24. xlsx := excelize.NewFile()
  25. xlsx.SetSheetRow("Sheet1", "A1", &titleList)
  26. switch req.Kind {
  27. case 1:
  28. //订单列表
  29. fileName = "/export/nursing_home/订单列表_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
  30. //查找订单数据
  31. sess := db.Db.Desc("nursing_home_package_ord.id")
  32. if req.EnterpriseId != 0 {
  33. sess.And("nursing_home_package_ord.enterprise_id =?", req.EnterpriseId)
  34. }
  35. if req.StartDate != "" {
  36. sess.And("nursing_home_package_ord.create_at >= ?", req.StartDate)
  37. }
  38. if req.EndDate != "" {
  39. sess.And("nursing_home_package_ord.create_at <= ?", req.EndDate)
  40. }
  41. var m []*db.NursingHomePackageOrdWithUserIdentity
  42. _, err := sess.
  43. Join("LEFT", "user_identity", "nursing_home_package_ord.user_identity_id = user_identity.id").
  44. Join("LEFT", "enterprise", "enterprise.id = nursing_home_package_ord.enterprise_id").
  45. Join("LEFT", "user", "user.id = nursing_home_package_ord.uid").
  46. FindAndCount(&m)
  47. if err != nil {
  48. logx.Error(err)
  49. println("<<<<NursingHomeDataStatisticsExport1>>>>>Error:::", err.Error())
  50. return
  51. }
  52. titleList = []string{"单位名称", "用户身份名称", "用户手机号", "购买类型", "总价", "商户订单号", "支付状态", "购买时间"}
  53. xlsx.SetSheetRow("Sheet1", "A1", &titleList)
  54. j := 2 //表头被第一行用了,只能从第二行开始
  55. for _, v := range m {
  56. var kind string //1:按年购买 2:按月购买 3:按天购买 4:补餐
  57. switch v.NursingHomePackageOrd.Kind {
  58. case 1:
  59. kind = "按年购买"
  60. break
  61. case 2:
  62. kind = "按月购买"
  63. break
  64. case 3:
  65. kind = "按天购买"
  66. break
  67. case 4:
  68. kind = "补餐"
  69. break
  70. }
  71. var state string //0:待支付 1:支付成功 2:支付失败
  72. switch v.NursingHomePackageOrd.State {
  73. case enum.NursingHomePackageOrdStateForWait:
  74. state = enum.NursingHomePackageOrdState.String(enum.NursingHomePackageOrdStateForWait)
  75. break
  76. case enum.NursingHomePackageOrdStateForSuccess:
  77. state = enum.NursingHomePackageOrdState.String(enum.NursingHomePackageOrdStateForWait)
  78. break
  79. case enum.NursingHomePackageOrdStateForFail:
  80. state = enum.NursingHomePackageOrdState.String(enum.NursingHomePackageOrdStateForFail)
  81. break
  82. }
  83. xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{v.Enterprise.Name, v.NursingHomePackageOrd.UserIdentityName, v.User.Phone, kind, v.NursingHomePackageOrd.TotalPrice,
  84. v.NursingHomePackageOrd.OutTradeNo, state, v.NursingHomePackageOrd.CreateAt})
  85. j++
  86. }
  87. break
  88. case 2:
  89. //退款申请表
  90. fileName = "/export/nursing_home/退款申请表_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
  91. var m []*db.NursingHomeUserRefundDayWithData
  92. sess := db.Db.Desc("nursing_home_user_refund_day.id")
  93. if req.EnterpriseId != 0 {
  94. sess.And("enterprise.enterprise_id =?", req.EnterpriseId)
  95. }
  96. if req.StartDate != "" {
  97. sess.And("nursing_home_user_refund_day.create_at >= ?", req.StartDate)
  98. }
  99. if req.EndDate != "" {
  100. sess.And("nursing_home_user_refund_day.create_at <= ?", req.EndDate)
  101. }
  102. _, err := sess.
  103. Join("LEFT", "nursing_home_user_with_day", "nursing_home_user_refund_day.records_id = nursing_home_user_with_day.id").
  104. Join("LEFT", "nursing_home_package_ord", "nursing_home_user_refund_day.out_trade_no = nursing_home_package_ord.out_trade_no").
  105. Join("LEFT", "user_identity", "nursing_home_user_with_day.identity_id = user_identity.id").
  106. Join("LEFT", "user", "user_identity.uid = user.id").
  107. Join("LEFT", "enterprise", "user_identity.enterprise_id = enterprise.id").
  108. Desc("nursing_home_user_refund_day.id").
  109. FindAndCount(&m)
  110. if err != nil {
  111. logx.Error(err)
  112. println("<<<<NursingHomeDataStatisticsExport2>>>>>Error:::", err.Error())
  113. return
  114. }
  115. titleList = []string{"退款单号", "所属订单号", "单位名称", "用户身份名称", "用户手机号", "就餐类型", "就餐时间", "金额", "状态", "退款时间"}
  116. xlsx.SetSheetRow("Sheet1", "A1", &titleList)
  117. j := 2 //表头被第一行用了,只能从第二行开始
  118. for _, v := range m {
  119. var kind string //就餐类型(1:早餐 2:午餐 3:晚餐)
  120. switch v.NursingHomeUserWithDay.Kind {
  121. case enum.NursingHomeUserWithDayKindForBreakfast:
  122. kind = enum.NursingHomeUserWithDayKind.String(enum.NursingHomeUserWithDayKindForBreakfast)
  123. break
  124. case enum.NursingHomeUserWithDayKindForLunch:
  125. kind = enum.NursingHomeUserWithDayKind.String(enum.NursingHomeUserWithDayKindForLunch)
  126. break
  127. case enum.NursingHomeUserWithDayKindForDinner:
  128. kind = enum.NursingHomeUserWithDayKind.String(enum.NursingHomeUserWithDayKindForDinner)
  129. break
  130. }
  131. var state string //状态(1:审核中 2:审核通过 3:审核拒绝 4:退款已完成)
  132. switch v.NursingHomeUserRefundDay.State {
  133. case enum.NursingHomeUserRefundDayStateForAuditing:
  134. state = enum.NursingHomeUserRefundDayState.String(enum.NursingHomeUserRefundDayStateForAuditing)
  135. break
  136. case enum.NursingHomeUserRefundDayStateForAuditPass:
  137. state = enum.NursingHomeUserRefundDayState.String(enum.NursingHomeUserRefundDayStateForAuditPass)
  138. break
  139. case enum.NursingHomeUserRefundDayStateForAuditReject:
  140. state = enum.NursingHomeUserRefundDayState.String(enum.NursingHomeUserRefundDayStateForAuditReject)
  141. break
  142. case enum.NursingHomeUserRefundDayStateForAuditComplete:
  143. state = enum.NursingHomeUserRefundDayState.String(enum.NursingHomeUserRefundDayStateForAuditComplete)
  144. break
  145. }
  146. xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{v.NursingHomeUserRefundDay.OutRequestNo, v.NursingHomeUserRefundDay.OutTradeNo, v.Enterprise.Name,
  147. v.NursingHomePackageOrd.UserIdentityName, v.User.Phone, kind, v.NursingHomeUserWithDay.Date, v.NursingHomeUserRefundDay.Amount, state, v.NursingHomeUserRefundDay.RefundDate})
  148. j++
  149. }
  150. xlsx.SaveAs("./static" + fileName + ".xlsx")
  151. break
  152. case 3:
  153. //预定统计表
  154. fileName = "/export/nursing_home/预定统计表_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
  155. var m []*db.NursingHomePackageOrdForReserveWithUserIdentity
  156. sess := db.Db.Desc("nursing_home_package_ord_for_reserve.id")
  157. if req.EnterpriseId != 0 {
  158. sess.And("enterprise.enterprise_id =?", req.EnterpriseId)
  159. }
  160. if req.StartDate != "" {
  161. sess.And("nursing_home_package_ord_for_reserve.meal_time_start >= ?", req.StartDate)
  162. }
  163. if req.EndDate != "" {
  164. sess.And("nursing_home_package_ord_for_reserve.meal_time_start <= ?", req.EndDate)
  165. }
  166. _, err := sess.
  167. Join("LEFT", "nursing_home_package_ord", "nursing_home_package_ord_for_reserve.out_trade_no = nursing_home_package_ord.out_trade_no").
  168. Join("LEFT", "user_identity", "nursing_home_package_ord.user_identity_id = user_identity.id").
  169. Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id").
  170. Join("LEFT", "user", "user.id = user_identity.uid").FindAndCount(&m)
  171. if err != nil {
  172. logx.Error(err)
  173. println("<<<<NursingHomeDataStatisticsExport2>>>>>Error:::", err.Error())
  174. return
  175. }
  176. titleList = []string{"所属订单号", "单位名称", "用户身份名称", "用户手机号", "预定类型", "预定月份", "就餐时间-开始", "就餐时间-截止"}
  177. xlsx.SetSheetRow("Sheet1", "A1", &titleList)
  178. j := 2 //表头被第一行用了,只能从第二行开始
  179. for _, v := range m {
  180. var kind string //预定类型(1:早餐 2:午餐 3:晚餐)
  181. switch v.NursingHomePackageOrdForReserve.Kind {
  182. case enum.NursingHomeUserWithDayKindForBreakfast:
  183. kind = enum.NursingHomeUserWithDayKind.String(enum.NursingHomeUserWithDayKindForBreakfast)
  184. break
  185. case enum.NursingHomeUserWithDayKindForLunch:
  186. kind = enum.NursingHomeUserWithDayKind.String(enum.NursingHomeUserWithDayKindForLunch)
  187. break
  188. case enum.NursingHomeUserWithDayKindForDinner:
  189. kind = enum.NursingHomeUserWithDayKind.String(enum.NursingHomeUserWithDayKindForDinner)
  190. break
  191. }
  192. xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{v.NursingHomePackageOrdForReserve.OutTradeNo, v.Enterprise.Name, v.NursingHomePackageOrd.UserIdentityName,
  193. v.User.Phone, kind, v.NursingHomePackageOrdForReserve.ReserveMonth, v.NursingHomePackageOrdForReserve.MealTimeStart, v.NursingHomePackageOrdForReserve.MealTimeEnd})
  194. j++
  195. }
  196. xlsx.SaveAs("./static" + fileName + ".xlsx")
  197. break
  198. }
  199. //新增数据
  200. nursingHomeExportRecordsDb := db.NursingHomeExportRecordsDb{}
  201. nursingHomeExportRecordsDb.Set()
  202. marshal, _ := json.Marshal(req)
  203. nursingHomeExportRecordsDb.NursingHomeExportRecordsInsert(&model.NursingHomeExportRecords{
  204. Name: fileName,
  205. DownloadPath: fileName,
  206. Kind: req.Kind,
  207. ReqContent: string(marshal),
  208. CreateAt: now.Format("2006-01-02 15:04:05"),
  209. UpdateAt: now.Format("2006-01-02 15:04:05"),
  210. })
  211. }
  212. func SelfSupportForSchoolDataStatisticsExport(req md.SelfSupportForSchoolDataStatisticsExportReq) {
  213. var titleList []string
  214. var fileName, downloadPath string
  215. var now = time.Now()
  216. switch req.Kind {
  217. case 1:
  218. //教师消费统计表
  219. xlsx, _ := excelize.OpenFile("./static/template/自营学校(教师消费统计表).xlsx")
  220. fileName = "教师消费统计表_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
  221. downloadPath = "/export/self_support_for_school/" + fileName
  222. //查询数据
  223. var m []*db.SelfSupportForSchoolOrdWithUserIdentity
  224. sess := db.Db.Desc("self_support_for_school_ord.id").Where("self_support_for_school_ord.order_status =?", enum.SelfSupportForSchoolOrdOrderStatusForSuccess)
  225. if req.EnterpriseId != 0 {
  226. sess.And("self_support_for_school_ord.enterprise_id =?", req.EnterpriseId)
  227. }
  228. if req.StartDate != "" {
  229. sess.And("self_support_for_school_ord.face_time >= ?", req.StartDate)
  230. }
  231. if req.EndDate != "" {
  232. sess.And("self_support_for_school_ord.face_time <= ?", req.EndDate)
  233. }
  234. if req.EnterPriseKind != 0 {
  235. sess.And("enterprise.kind = ?", req.EnterPriseKind)
  236. }
  237. sess.And("user_identity.identity = ?", enum.UserIdentityForSelfSupportForTeacher) //只查询老师
  238. _, err := sess.
  239. Join("LEFT", "user_identity", "self_support_for_school_ord.user_identity_id = user_identity.id").
  240. Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id").
  241. Join("LEFT", "user", "user.id = user_identity.uid").
  242. Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id").
  243. Join("LEFT", "class", "class_with_user.class_id = class.id").
  244. Join("LEFT", "grade", "class.grade_id = grade.id").
  245. FindAndCount(&m)
  246. if err != nil {
  247. logx.Error(err)
  248. println("<<<<SelfSupportForSchoolDataStatisticsExport2>>>>>Error:::", err.Error())
  249. return
  250. }
  251. //整合数据
  252. var data = map[string]map[string]map[string]map[string]interface{}{}
  253. for _, vv := range m {
  254. if data[vv.Enterprise.Name] == nil {
  255. data[vv.Enterprise.Name] = make(map[string]map[string]map[string]interface{})
  256. }
  257. if data[vv.Enterprise.Name][vv.UserIdentity.Name] == nil {
  258. data[vv.Enterprise.Name][vv.UserIdentity.Name] = make(map[string]map[string]interface{})
  259. }
  260. mealZh := JudgeSelfSupportForMealTime(vv.SelfSupportForSchoolOrd.FaceTime)
  261. if data[vv.Enterprise.Name][vv.UserIdentity.Name][mealZh] == nil {
  262. data[vv.Enterprise.Name][vv.UserIdentity.Name][mealZh] = make(map[string]interface{})
  263. }
  264. data[vv.Enterprise.Name][vv.UserIdentity.Name]["编号"] = map[string]interface{}{
  265. "id": vv.UserIdentity.IdNo,
  266. }
  267. if data[vv.Enterprise.Name][vv.UserIdentity.Name]["合计"] == nil {
  268. data[vv.Enterprise.Name][vv.UserIdentity.Name]["合计"] = make(map[string]interface{})
  269. }
  270. data[vv.Enterprise.Name][vv.UserIdentity.Name][mealZh]["num"] = utils.AnyToInt64(data[vv.Enterprise.Name][vv.UserIdentity.Name][mealZh]["num"]) + 1
  271. data[vv.Enterprise.Name][vv.UserIdentity.Name][mealZh]["amount"] = utils.AnyToFloat64(data[vv.Enterprise.Name][vv.UserIdentity.Name][mealZh]["amount"]) + utils.AnyToFloat64(vv.SelfSupportForSchoolOrd.TradeAmount)
  272. data[vv.Enterprise.Name][vv.UserIdentity.Name]["合计"]["num"] = utils.AnyToInt64(data[vv.Enterprise.Name][vv.UserIdentity.Name]["合计"]["num"]) + 1
  273. data[vv.Enterprise.Name][vv.UserIdentity.Name]["合计"]["amount"] = utils.AnyToFloat64(data[vv.Enterprise.Name][vv.UserIdentity.Name]["合计"]["amount"]) + utils.AnyToFloat64(vv.SelfSupportForSchoolOrd.TradeAmount)
  274. }
  275. xlsx.SetSheetRow("", "A1", &titleList)
  276. sheetIndex := 2 //第一个表是模板表
  277. j := 3 //表头前两行被占用了,只能从第三行开始
  278. for k, v := range data {
  279. xlsx.NewSheet(k) //1、新建表格
  280. xlsx.CopySheet(1, sheetIndex)
  281. xlsx.SetSheetRow(k, "A1", &[]interface{}{"教 师 消 费 统 计 表 " + "(" + req.StartDate + "至" + req.EndDate + ")"})
  282. var userTotal, breakFastTotal, lunchTotal, dinnerTotal, supperTotal, totalTotal int64
  283. var breakFastAmountTotal, lunchAmountTotal, dinnerAmountTotal, supperAmountTotal, totalAmountTotal float64
  284. for kk, vv := range v {
  285. xlsx.SetSheetRow(k, "A"+strconv.Itoa(j), &[]interface{}{vv["编号"]["id"], kk,
  286. vv["早餐"]["num"], vv["早餐"]["amount"],
  287. vv["午餐"]["num"], vv["午餐"]["amount"],
  288. vv["晚餐"]["num"], vv["晚餐"]["amount"],
  289. vv["夜宵"]["num"], vv["夜宵"]["amount"],
  290. vv["合计"]["num"], vv["合计"]["amount"],
  291. })
  292. userTotal++
  293. if vv["早餐"]["num"] != nil {
  294. breakFastTotal += vv["早餐"]["num"].(int64)
  295. }
  296. if vv["午餐"]["num"] != nil {
  297. lunchTotal += vv["午餐"]["num"].(int64)
  298. }
  299. if vv["晚餐"]["num"] != nil {
  300. dinnerTotal += vv["晚餐"]["num"].(int64)
  301. }
  302. if vv["夜宵"]["num"] != nil {
  303. supperTotal += vv["夜宵"]["num"].(int64)
  304. }
  305. if vv["合计"]["num"] != nil {
  306. totalTotal += vv["合计"]["num"].(int64)
  307. }
  308. if vv["早餐"]["amount"] != nil {
  309. breakFastAmountTotal += vv["早餐"]["amount"].(float64)
  310. }
  311. if vv["午餐"]["amount"] != nil {
  312. lunchAmountTotal += vv["午餐"]["amount"].(float64)
  313. }
  314. if vv["晚餐"]["amount"] != nil {
  315. dinnerAmountTotal += vv["晚餐"]["amount"].(float64)
  316. }
  317. if vv["夜宵"]["amount"] != nil {
  318. supperAmountTotal += vv["夜宵"]["amount"].(float64)
  319. }
  320. if vv["合计"]["amount"] != nil {
  321. totalAmountTotal += vv["合计"]["amount"].(float64)
  322. }
  323. j++
  324. }
  325. xlsx.SetSheetRow(k, "A"+strconv.Itoa(j), &[]interface{}{"总计", userTotal,
  326. breakFastTotal, breakFastAmountTotal,
  327. lunchTotal, lunchAmountTotal,
  328. dinnerTotal, dinnerAmountTotal,
  329. supperTotal, supperAmountTotal,
  330. totalTotal, totalAmountTotal,
  331. })
  332. sheetIndex++
  333. }
  334. xlsx.DeleteSheet("template") //删除模板表
  335. //将文件保存至服务器
  336. xlsx.SaveAs("./static" + downloadPath)
  337. break
  338. case 2:
  339. //商家分餐数据统计表
  340. xlsx, _ := excelize.OpenFile("./static/template/自营学校(商家分餐数据统计表).xlsx")
  341. fileName = "商家分餐数据统计表_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
  342. downloadPath = "/export/self_support_for_school/" + fileName
  343. //查询出所有的商家
  344. var merchantList []*model.Merchant
  345. err := db.Db.Where("enterprise_id != 0").OrderBy("CONVERT(name USING gbk) ASC").Find(&merchantList)
  346. if err != nil {
  347. logx.Error(err)
  348. println("<<<<SelfSupportForSchoolDataStatisticsExport2>>>>>1111Error:::", err.Error())
  349. return
  350. }
  351. //查询出所有的设备
  352. var deviceList []*model.Device
  353. err = db.Db.Where("enterprise_id != 0").OrderBy("CONVERT(name USING gbk) ASC").Find(&deviceList)
  354. if err != nil {
  355. logx.Error(err)
  356. println("<<<<SelfSupportForSchoolDataStatisticsExport2>>>>>1111Error:::", err.Error())
  357. return
  358. }
  359. var merchantListMapping = map[int]model.Merchant{}
  360. var merchantDeviceListMapping = map[int]map[string]model.Device{}
  361. var deviceListMapping = map[string]model.Device{}
  362. var deviceNameArr []string
  363. var isHasDeviceName = map[string]bool{}
  364. for _, v := range deviceList {
  365. if merchantDeviceListMapping[v.MerchantId] == nil {
  366. merchantDeviceListMapping[v.MerchantId] = map[string]model.Device{}
  367. }
  368. merchantDeviceListMapping[v.MerchantId][v.DeviceSn] = *v
  369. deviceListMapping[v.DeviceSn] = *v
  370. if !isHasDeviceName[v.Name] {
  371. deviceNameArr = append(deviceNameArr, v.Name)
  372. isHasDeviceName[v.Name] = true
  373. }
  374. }
  375. for _, v := range merchantList {
  376. merchantListMapping[v.Id] = *v
  377. }
  378. var m []*db.SelfSupportForSchoolOrdWithUserIdentityV2
  379. eg := db.Db
  380. sess := eg.Desc("self_support_for_school_ord.id").Where("self_support_for_school_ord.order_status =?", enum.SelfSupportForSchoolOrdOrderStatusForSuccess)
  381. if req.EnterpriseId != 0 {
  382. sess.And("self_support_for_school_ord.enterprise_id =?", req.EnterpriseId)
  383. }
  384. if req.StartDate != "" {
  385. sess.And("self_support_for_school_ord.face_time >= ?", req.StartDate)
  386. }
  387. if req.EndDate != "" {
  388. sess.And("self_support_for_school_ord.face_time <= ?", req.EndDate)
  389. }
  390. if req.EnterPriseKind != 0 {
  391. sess.And("enterprise.kind = ?", req.EnterPriseKind)
  392. }
  393. _, err = sess.
  394. Join("LEFT", "enterprise", "self_support_for_school_ord.enterprise_id = enterprise.id").
  395. FindAndCount(&m)
  396. if err != nil {
  397. logx.Error(err)
  398. println("<<<<SelfSupportForSchoolDataStatisticsExport2>>>>>Error:::", err.Error())
  399. return
  400. }
  401. //整合数据
  402. var data = map[string]map[string]map[string]map[string]map[string]float64{}
  403. for _, vv := range m {
  404. device := deviceListMapping[vv.SelfSupportForSchoolOrd.DeviceSn]
  405. ordCreateAt, _ := time.ParseInLocation("2006-01-02 15:04:05", vv.SelfSupportForSchoolOrd.CreateAt, time.Local)
  406. merchantCreateAt, _ := time.ParseInLocation("2006-01-02 15:04:05", merchantListMapping[device.MerchantId].CreateAt, time.Local)
  407. shopName := merchantListMapping[device.MerchantId].Name
  408. if ordCreateAt.Before(merchantCreateAt) {
  409. shopName = "设备已更换商户"
  410. }
  411. deviceName := device.Name
  412. if data[vv.Enterprise.Name] == nil {
  413. data[vv.Enterprise.Name] = make(map[string]map[string]map[string]map[string]float64)
  414. }
  415. if data[vv.Enterprise.Name][shopName] == nil {
  416. data[vv.Enterprise.Name][shopName] = make(map[string]map[string]map[string]float64)
  417. }
  418. if data[vv.Enterprise.Name][shopName][deviceName] == nil {
  419. data[vv.Enterprise.Name][shopName][deviceName] = make(map[string]map[string]float64)
  420. }
  421. mealZh := JudgeSelfSupportForMealTime(vv.SelfSupportForSchoolOrd.FaceTime)
  422. if data[vv.Enterprise.Name][shopName][deviceName][mealZh] == nil {
  423. data[vv.Enterprise.Name][shopName][deviceName][mealZh] = make(map[string]float64)
  424. }
  425. if data[vv.Enterprise.Name][shopName][deviceName]["合计"] == nil {
  426. data[vv.Enterprise.Name][shopName][deviceName]["合计"] = make(map[string]float64)
  427. }
  428. data[vv.Enterprise.Name][shopName][deviceName][mealZh]["num"]++
  429. data[vv.Enterprise.Name][shopName][deviceName][mealZh]["amount"] += utils.StrToFloat64(vv.SelfSupportForSchoolOrd.TradeAmount)
  430. data[vv.Enterprise.Name][shopName][deviceName]["合计"]["num"]++
  431. data[vv.Enterprise.Name][shopName][deviceName]["合计"]["amount"] += utils.StrToFloat64(vv.SelfSupportForSchoolOrd.TradeAmount)
  432. }
  433. xlsx.SetSheetRow("", "A1", &titleList)
  434. sheetIndex := 2 //第一个表是模板表
  435. for k, v := range data {
  436. if k == "" {
  437. k = "未知"
  438. }
  439. xlsx.NewSheet(k) //1、新建表格
  440. xlsx.CopySheet(1, sheetIndex)
  441. xlsx.SetSheetRow(k, "A1", &[]interface{}{"商 家 分 餐 数 据 统 计 表 " + "(" + req.StartDate + "至" + req.EndDate + ")"})
  442. j := 4 //表头前三行被占用了,只能从第四行开始
  443. for kk, vv := range v {
  444. var startRow = 0
  445. var endRow = 0
  446. var breakFastTotal, lunchTotal, dinnerTotal, supperTotal, totalTotal float64
  447. var breakFastAmountTotal, lunchAmountTotal, dinnerAmountTotal, supperAmountTotal, totalAmountTotal float64
  448. for _, device := range deviceNameArr {
  449. for kkk, vvv := range vv {
  450. if kkk == "" {
  451. kkk = k
  452. }
  453. if device == kkk {
  454. xlsx.SetSheetRow(k, "A"+strconv.Itoa(j), &[]interface{}{kk, kkk,
  455. vvv["早餐"]["num"], vvv["早餐"]["amount"],
  456. vvv["午餐"]["num"], vvv["午餐"]["amount"],
  457. vvv["晚餐"]["num"], vvv["晚餐"]["amount"],
  458. vvv["夜宵"]["num"], vvv["夜宵"]["amount"],
  459. vvv["合计"]["num"], vvv["合计"]["amount"],
  460. })
  461. breakFastTotal += vvv["早餐"]["num"]
  462. lunchTotal += vvv["午餐"]["num"]
  463. dinnerTotal += vvv["晚餐"]["num"]
  464. supperTotal += vvv["夜宵"]["num"]
  465. totalTotal += vvv["合计"]["num"]
  466. breakFastAmountTotal += vvv["早餐"]["amount"]
  467. lunchAmountTotal += vvv["午餐"]["amount"]
  468. dinnerAmountTotal += vvv["晚餐"]["amount"]
  469. supperAmountTotal += vvv["夜宵"]["amount"]
  470. totalAmountTotal += vvv["合计"]["amount"]
  471. if startRow == 0 {
  472. startRow = j
  473. }
  474. endRow = j
  475. j++
  476. }
  477. }
  478. }
  479. xlsx.SetSheetRow(k, "A"+strconv.Itoa(j), &[]interface{}{"", "合计",
  480. breakFastTotal, breakFastAmountTotal,
  481. lunchTotal, lunchAmountTotal,
  482. dinnerTotal, dinnerAmountTotal,
  483. supperTotal, supperAmountTotal,
  484. totalTotal, totalAmountTotal,
  485. })
  486. if startRow == 0 {
  487. startRow = j
  488. }
  489. endRow = j
  490. j++
  491. style, err := xlsx.NewStyle(`{"alignment":{"horizontal":"center", "vertical": "center"}}`)
  492. if err != nil {
  493. logx.Error(err)
  494. println("<<<<SelfSupportForSchoolDataStatisticsExport2>>>>>Error:::", err.Error())
  495. panic(err)
  496. }
  497. xlsx.MergeCell(k, "A"+utils.IntToStr(startRow), "A"+utils.IntToStr(endRow)) //合并单元格
  498. xlsx.SetCellStyle(k, "A"+utils.IntToStr(startRow), "A"+utils.IntToStr(endRow), style)
  499. }
  500. sheetIndex++
  501. }
  502. xlsx.DeleteSheet("template") //删除模板表
  503. //将文件保存至服务器
  504. xlsx.SaveAs("./static" + downloadPath)
  505. break
  506. case 3:
  507. //就餐数据统计表
  508. xlsx, _ := excelize.OpenFile("./static/template/自营学校(就餐数据统计表).xlsx")
  509. fileName = "就餐数据统计表_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
  510. downloadPath = "/export/self_support_for_school/" + fileName
  511. //查询出所有的设备
  512. //var deviceList []*model.Device
  513. //err := db.Db.Where("enterprise_id != 0").Find(&deviceList)
  514. //if err != nil {
  515. // logx.Error(err)
  516. // println("<<<<SelfSupportForSchoolDataStatisticsExport2>>>>>1111Error:::", err.Error())
  517. // return
  518. //}
  519. //var deviceListMapping = map[string]model.Device{}
  520. //for _, v := range deviceList {
  521. // deviceListMapping[v.DeviceSn] = *v
  522. //}
  523. var m []*db.SelfSupportForSchoolOrdWithUserIdentity
  524. sess := db.Db.Desc("self_support_for_school_ord.id").Where("self_support_for_school_ord.order_status =?", enum.SelfSupportForSchoolOrdOrderStatusForSuccess)
  525. if req.EnterpriseId != 0 {
  526. sess.And("self_support_for_school_ord.enterprise_id =?", req.EnterpriseId)
  527. }
  528. if req.StartDate != "" {
  529. sess.And("self_support_for_school_ord.face_time >= ?", req.StartDate)
  530. }
  531. if req.EndDate != "" {
  532. sess.And("self_support_for_school_ord.face_time <= ?", req.EndDate)
  533. }
  534. if req.EnterPriseKind != 0 {
  535. sess.And("enterprise.kind = ?", req.EnterPriseKind)
  536. }
  537. _, err := sess.
  538. Join("LEFT", "user_identity", "self_support_for_school_ord.user_identity_id = user_identity.id").
  539. Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id").
  540. Join("LEFT", "user", "user.id = user_identity.uid").
  541. Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id").
  542. Join("LEFT", "class", "class_with_user.class_id = class.id").
  543. Join("LEFT", "grade", "class.grade_id = grade.id").
  544. FindAndCount(&m)
  545. if err != nil {
  546. logx.Error(err)
  547. println("<<<<SelfSupportForSchoolDataStatisticsExport3>>>>>Error:::", err.Error())
  548. return
  549. }
  550. //整合数据
  551. var data = map[string]map[string]map[string]map[string]float64{}
  552. date1, err := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
  553. if err != nil {
  554. logx.Error(err)
  555. println("<<<<SelfSupportForSchoolDataStatisticsExport3>>>>>Error:::", err.Error())
  556. return
  557. }
  558. date2, err := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
  559. if err != nil {
  560. logx.Error(err)
  561. println("<<<<SelfSupportForSchoolDataStatisticsExport3>>>>>Error:::", err.Error())
  562. return
  563. }
  564. diffDays := int(date2.Sub(date1).Hours() / 24)
  565. var dates []string
  566. for i := 0; i <= diffDays; i++ {
  567. date := date1.AddDate(0, 0, i)
  568. shopName := date.Format("2006-01-02")
  569. dates = append(dates, shopName)
  570. for _, vv := range m {
  571. tmpDate, err1 := time.ParseInLocation("2006-01-02 15:04:05", vv.SelfSupportForSchoolOrd.FaceTime, time.Local)
  572. if err1 != nil {
  573. logx.Error(err1)
  574. println("<<<<SelfSupportForSchoolDataStatisticsExport3>>>>>Error:::", err1.Error())
  575. return
  576. }
  577. fmt.Println(tmpDate.Format("2006-01-02"))
  578. if shopName == tmpDate.Format("2006-01-02") {
  579. if data[vv.Enterprise.Name] == nil {
  580. data[vv.Enterprise.Name] = make(map[string]map[string]map[string]float64)
  581. }
  582. if data[vv.Enterprise.Name][shopName] == nil {
  583. data[vv.Enterprise.Name][shopName] = make(map[string]map[string]float64)
  584. }
  585. mealZh := JudgeSelfSupportForMealTime(vv.SelfSupportForSchoolOrd.FaceTime)
  586. if data[vv.Enterprise.Name][shopName][mealZh] == nil {
  587. data[vv.Enterprise.Name][shopName][mealZh] = make(map[string]float64)
  588. }
  589. if data[vv.Enterprise.Name][shopName]["合计"] == nil {
  590. data[vv.Enterprise.Name][shopName]["合计"] = make(map[string]float64)
  591. }
  592. data[vv.Enterprise.Name][shopName][mealZh]["num"]++
  593. data[vv.Enterprise.Name][shopName][mealZh]["amount"] += utils.StrToFloat64(vv.SelfSupportForSchoolOrd.TradeAmount)
  594. data[vv.Enterprise.Name][shopName]["合计"]["num"]++
  595. data[vv.Enterprise.Name][shopName]["合计"]["amount"] += utils.StrToFloat64(vv.SelfSupportForSchoolOrd.TradeAmount)
  596. }
  597. }
  598. }
  599. xlsx.SetSheetRow("", "A1", &titleList)
  600. sheetIndex := 2 //第一个表是模板表
  601. for k, v := range data {
  602. if k == "" {
  603. k = "未知"
  604. }
  605. xlsx.NewSheet(k) //1、新建表格
  606. xlsx.CopySheet(1, sheetIndex)
  607. j := 4 //表头前三行被占用了,只能从第四行开始
  608. for _, date := range dates {
  609. for kk, vv := range v {
  610. if date == kk {
  611. xlsx.SetSheetRow(k, "A"+strconv.Itoa(j), &[]interface{}{kk,
  612. vv["早餐"]["num"], vv["早餐"]["amount"],
  613. vv["午餐"]["num"], vv["午餐"]["amount"],
  614. vv["晚餐"]["num"], vv["晚餐"]["amount"],
  615. vv["夜宵"]["num"], vv["夜宵"]["amount"],
  616. vv["合计"]["num"], vv["合计"]["amount"],
  617. })
  618. j++
  619. }
  620. sheetIndex++
  621. }
  622. }
  623. }
  624. xlsx.DeleteSheet("template") //删除模板表
  625. //将文件保存至服务器
  626. xlsx.SaveAs("./static" + downloadPath)
  627. break
  628. case 4:
  629. //设备就餐数据统计表
  630. fileName = "设备就餐数据统计_" + utils.Int64ToStr(now.UnixMilli()) + ".zip"
  631. downloadPath = "/export/self_support_for_school/" + fileName
  632. //查询出所有的设备
  633. var deviceList []*model.Device
  634. if req.EnterpriseId == 0 {
  635. err := db.Db.Where("enterprise_id != 0").OrderBy("CONVERT(name USING gbk) ASC").Find(&deviceList)
  636. if err != nil {
  637. logx.Error(err)
  638. println("<<<<SelfSupportForSchoolDataStatisticsExport4>>>>>1111Error:::", err.Error())
  639. return
  640. }
  641. } else {
  642. err := db.Db.Where("enterprise_id = ?", req.EnterpriseId).OrderBy("CONVERT(name USING gbk) ASC").Find(&deviceList)
  643. if err != nil {
  644. logx.Error(err)
  645. println("<<<<SelfSupportForSchoolDataStatisticsExport4>>>>>1111Error:::", err.Error())
  646. return
  647. }
  648. }
  649. date1, err := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
  650. if err != nil {
  651. logx.Error(err)
  652. println("<<<<SelfSupportForSchoolDataStatisticsExport4>>>>>Error:::", err.Error())
  653. return
  654. }
  655. date2, err := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
  656. if err != nil {
  657. logx.Error(err)
  658. println("<<<<SelfSupportForSchoolDataStatisticsExport4>>>>>Error:::", err.Error())
  659. return
  660. }
  661. diffDays := int(date2.Sub(date1).Hours() / 24)
  662. var deviceListMapping = map[string]model.Device{}
  663. //整合数据
  664. var data = map[string]map[string]map[string]map[string]float64{}
  665. var xlsFileName, xlsDownloadPath []string
  666. for _, v := range deviceList {
  667. deviceListMapping[v.DeviceSn] = *v
  668. var m []*db.SelfSupportForSchoolOrdWithUserIdentityV2
  669. sess := db.Db.Where("device_sn = ?", v.DeviceSn).And("self_support_for_school_ord.order_status =?", enum.SelfSupportForSchoolOrdOrderStatusForSuccess).And("enterprise_id =?", req.EnterpriseId).Desc("self_support_for_school_ord.id")
  670. if req.EnterpriseId != 0 {
  671. sess.And("self_support_for_school_ord.enterprise_id =?", req.EnterpriseId)
  672. }
  673. if req.StartDate != "" {
  674. sess.And("self_support_for_school_ord.face_time >= ?", req.StartDate)
  675. }
  676. if req.EndDate != "" {
  677. sess.And("self_support_for_school_ord.face_time <= ?", req.EndDate)
  678. }
  679. _, err = sess.Join("LEFT", "enterprise", "self_support_for_school_ord.enterprise_id = enterprise.id").FindAndCount(&m)
  680. if err != nil {
  681. logx.Error(err)
  682. println("<<<<SelfSupportForSchoolDataStatisticsExport4>>>>>Error:::", err.Error())
  683. return
  684. }
  685. for _, vv := range m {
  686. tmpTime, err1 := time.ParseInLocation("2006-01-02 15:04:05", vv.SelfSupportForSchoolOrd.FaceTime, time.Local)
  687. if err1 != nil {
  688. logx.Error(err1)
  689. println("<<<<SelfSupportForSchoolDataStatisticsExport4>>>>>Error:::", err1.Error())
  690. return
  691. }
  692. tmpDate := tmpTime.Format("2006-01-02")
  693. if data[vv.Enterprise.Name] == nil {
  694. data[vv.Enterprise.Name] = make(map[string]map[string]map[string]float64)
  695. }
  696. if data[vv.Enterprise.Name][v.Name] == nil {
  697. data[vv.Enterprise.Name][v.Name] = make(map[string]map[string]float64)
  698. }
  699. if data[vv.Enterprise.Name][v.Name][tmpDate] == nil {
  700. data[vv.Enterprise.Name][v.Name][tmpDate] = make(map[string]float64)
  701. }
  702. data[vv.Enterprise.Name][v.Name][tmpDate]["num"]++
  703. data[vv.Enterprise.Name][v.Name][tmpDate]["amount"] += utils.StrToFloat64(vv.SelfSupportForSchoolOrd.TradeAmount)
  704. }
  705. }
  706. for k1, v := range data {
  707. tmpFileName := k1 + "设备就餐数据统计表_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
  708. tmpDownloadPath := "./static/export/self_support_for_school/" + tmpFileName
  709. xlsx := excelize.NewFile()
  710. var totalData = map[string]map[string]float64{}
  711. for _, device := range deviceList {
  712. for k2, vv := range v {
  713. if k2 == device.Name {
  714. var sumNum, sumAmount = float64(0), float64(0)
  715. xlsx.NewSheet(k2)
  716. titleList = []string{" 设 备 分 餐 数 据 统 计 表 "}
  717. xlsx.SetSheetRow(k2, "A1", &titleList)
  718. titleList = []string{"日 期", "消费笔数", "消费金额"}
  719. xlsx.SetSheetRow(k2, "A2", &titleList)
  720. style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFF00"],"pattern":1}, "alignment":{"horizontal":"center"}}`)
  721. if err != nil {
  722. logx.Error(err)
  723. println("<<<<SelfSupportForSchoolDataStatisticsExport4>>>>>Error:::", err.Error())
  724. panic(err)
  725. }
  726. xlsx.MergeCell(k2, "A1", "C1") //合并单元格
  727. xlsx.SetCellStyle(k2, "A1", "C1", style)
  728. xlsx.SetColWidth(k2, "A", "C", 20)
  729. j := 3 //表头前两行用了,只能从第三行开始
  730. for i := 0; i <= diffDays; i++ {
  731. date := date1.AddDate(0, 0, i).Format("2006-01-02")
  732. if vv[date] != nil {
  733. xlsx.SetSheetRow(k2, "A"+strconv.Itoa(j), &[]interface{}{date, vv[date]["num"], vv[date]["amount"]})
  734. sumNum += vv[date]["num"]
  735. sumAmount += vv[date]["amount"]
  736. } else {
  737. xlsx.SetSheetRow(k2, "A"+strconv.Itoa(j), &[]interface{}{date, 0, 0})
  738. }
  739. j++
  740. }
  741. xlsx.SetSheetRow(k2, "A"+strconv.Itoa(j), &[]interface{}{
  742. "合计", sumNum, sumAmount})
  743. if totalData[k2] == nil {
  744. totalData[k2] = map[string]float64{}
  745. }
  746. totalData[k2]["num"] = sumNum
  747. totalData[k2]["amount"] = sumAmount
  748. }
  749. }
  750. }
  751. //xlsx.NewSheet("所有档口")
  752. xlsx.SetSheetName("Sheet1", "所有档口")
  753. titleList = []string{" 设 备 分 餐 数 据 统 计 表 "}
  754. xlsx.SetSheetRow("所有档口", "A1", &titleList)
  755. titleList = []string{"名 称", "消费笔数", "消费金额"}
  756. xlsx.SetSheetRow("所有档口", "A2", &titleList)
  757. style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFF00"],"pattern":1}, "alignment":{"horizontal":"center"}}`)
  758. if err != nil {
  759. logx.Error(err)
  760. println("<<<<SelfSupportForSchoolDataStatisticsExport4>>>>>Error:::", err.Error())
  761. panic(err)
  762. }
  763. xlsx.MergeCell("所有档口", "A1", "C1") //合并单元格
  764. xlsx.SetCellStyle("所有档口", "A1", "C1", style)
  765. xlsx.SetColWidth("所有档口", "A", "C", 20)
  766. j := 3 //表头前两行用了,只能从第三行开始
  767. var totalNum, totalAmount float64
  768. for _, device := range deviceList {
  769. for key, val := range totalData {
  770. if key == device.Name {
  771. totalNum += val["num"]
  772. totalAmount += val["amount"]
  773. xlsx.SetSheetRow("所有档口", "A"+strconv.Itoa(j), &[]interface{}{key, val["num"], val["amount"]})
  774. j++
  775. }
  776. }
  777. }
  778. xlsx.SetSheetRow("所有档口", "A"+strconv.Itoa(j), &[]interface{}{"合计", totalNum, totalAmount})
  779. //xlsx.DeleteSheet("Sheet1") //TODO::只能放这里删除
  780. //将文件保存至服务器
  781. err1 := xlsx.SaveAs(tmpDownloadPath)
  782. if err1 != nil {
  783. logx.Error(err1)
  784. println("<<<<SelfSupportForSchoolDataStatisticsExport4>>>>>Error:::", err1.Error())
  785. panic(err1)
  786. }
  787. xlsDownloadPath = append(xlsDownloadPath, tmpDownloadPath)
  788. xlsFileName = append(xlsFileName, tmpFileName)
  789. }
  790. archive, err := os.Create("./static" + downloadPath) //第一步,创建 zip 文件
  791. if err != nil {
  792. logx.Error(err)
  793. println("<<<<SelfSupportForSchoolDataStatisticsExport4>>>>>Error:::", err.Error())
  794. panic(err)
  795. }
  796. defer archive.Close()
  797. zipWriter := zip.NewWriter(archive) //第二步,创建一个新的 *Writer 对象
  798. for k, v := range xlsDownloadPath {
  799. w, err1 := zipWriter.Create("设备就餐数据统计/" + xlsFileName[k]) //向 zip 文件中添加一个文件,返回一个待压缩的文件内容应写入的 Writer
  800. if err1 != nil {
  801. logx.Error(err1)
  802. println("<<<<SelfSupportForSchoolDataStatisticsExport4>>>>>Error:::", err1.Error())
  803. panic(err1)
  804. }
  805. f, err1 := os.Open(v) //打开待压缩的文件
  806. if err1 != nil {
  807. logx.Error(err1)
  808. println("<<<<CentralKitchenForSchoolDataStatisticsExport7>>>>>Error:::", err1.Error())
  809. panic(err1)
  810. }
  811. if _, err1 = io.Copy(w, f); err != nil {
  812. logx.Error(err1)
  813. println("<<<<CentralKitchenForSchoolDataStatisticsExport7>>>>>Error:::", err1.Error())
  814. panic(err1)
  815. }
  816. if err1 != nil {
  817. logx.Error(err1)
  818. println("<<<<CentralKitchenForSchoolDataStatisticsExport7>>>>>Error:::", err1.Error())
  819. panic(err1)
  820. }
  821. f.Close()
  822. os.RemoveAll(v) //TODO::移除源文件
  823. }
  824. zipWriter.Close() // 第四步,关闭 zip writer,将所有数据写入指向基础 zip 文件的数据流
  825. if err != nil {
  826. panic(err)
  827. }
  828. break
  829. }
  830. //新增数据
  831. selfSupportForSchoolExportRecordsDb := db.SelfSupportForSchoolExportRecordsDb{}
  832. selfSupportForSchoolExportRecordsDb.Set()
  833. marshal, _ := json.Marshal(req)
  834. selfSupportForSchoolExportRecordsDb.SelfSupportForSchoolExportRecordsInsert(&model.SelfSupportForSchoolExportRecords{
  835. Name: fileName,
  836. DownloadPath: downloadPath,
  837. Kind: req.Kind,
  838. ReqContent: string(marshal),
  839. CreateAt: now.Format("2006-01-02 15:04:05"),
  840. UpdateAt: now.Format("2006-01-02 15:04:05"),
  841. })
  842. }
  843. func CentralKitchenForSchoolDataStatisticsExport(req md.CentralKitchenForSchoolDataStatisticsExportReq) {
  844. var titleList []string
  845. var fileName, downloadPath string
  846. var now = time.Now()
  847. for _, kind := range req.Kinds {
  848. switch kind {
  849. case 1:
  850. xlsx := excelize.NewFile()
  851. //订单列表
  852. fileName = "订单列表_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
  853. downloadPath = "/export/central_kitchen_for_school/" + fileName
  854. startDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
  855. endDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
  856. //查找订单数据
  857. sess := db.Db.Desc("central_kitchen_for_school_package_ord.id")
  858. sess.And("central_kitchen_for_school_package_ord.state =?", enum.CentralKitchenForSchoolPackageOrdStateForSuccess)
  859. if req.EnterpriseId != 0 {
  860. sess.And("central_kitchen_for_school_package_ord.enterprise_id =?", req.EnterpriseId)
  861. }
  862. if req.StartDate != "" {
  863. sess.And("central_kitchen_for_school_package_ord.pay_at >= ?", req.StartDate)
  864. }
  865. if req.EndDate != "" {
  866. sess.And("central_kitchen_for_school_package_ord.pay_at <= ?", req.EndDate)
  867. }
  868. if req.EnterPriseKind != 0 {
  869. sess.And("enterprise.kind = ?", req.EnterPriseKind)
  870. }
  871. var m []*db.CentralKitchenForSchoolPackageOrdWithUserIdentity
  872. _, err := sess.
  873. Join("LEFT", "user_identity", "central_kitchen_for_school_package_ord.user_identity_id = user_identity.id").
  874. Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id").
  875. Join("LEFT", "user", "user.id = user_identity.uid").
  876. Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id").
  877. Join("LEFT", "class", "class_with_user.class_id = class.id").
  878. Join("LEFT", "grade", "class.grade_id = grade.id").
  879. FindAndCount(&m)
  880. if err != nil {
  881. logx.Error(err)
  882. println("<<<<CentralKitchenForSchoolDataStatisticsExport1>>>>>Error:::", err.Error())
  883. return
  884. }
  885. //查找预定数据
  886. var outTradeNoList []string
  887. for _, v := range m {
  888. outTradeNoList = append(outTradeNoList, v.OutTradeNo)
  889. }
  890. var mm []model.CentralKitchenForSchoolPackageOrdForReserve
  891. sess1 := db.Db.Desc("id")
  892. if req.EnterpriseId != 0 {
  893. sess1.And("enterprise_id = ?", req.EnterpriseId)
  894. }
  895. if len(req.MealKindList) > 0 {
  896. sess1.In("kind", req.MealKindList)
  897. }
  898. err = sess1.In("out_trade_no", outTradeNoList).Find(&mm)
  899. if err != nil {
  900. logx.Error(err)
  901. println("<<<<CentralKitchenForSchoolDataStatisticsExport1>>>>>Error:::", err.Error())
  902. return
  903. }
  904. var exportOutTradeNoList []string
  905. for _, v := range mm {
  906. exportOutTradeNoList = append(exportOutTradeNoList, v.OutTradeNo)
  907. }
  908. titleList = []string{startDate.Format("2006-01-02") + "~~" + endDate.Format("2006-01-02") + " 订单表"}
  909. xlsx.SetSheetRow("Sheet1", "A1", &titleList)
  910. titleList = []string{"订单号", "学生姓名", "学校", "年级", "班级", "家长电话", "预定日期", "预定餐数", "订单价格", "支付时间", "订单状态"}
  911. xlsx.SetSheetRow("Sheet1", "A2", &titleList)
  912. xlsx.MergeCell("Sheet1", "A1", "K1") //合并单元格
  913. style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFF00"],"pattern":1}, "alignment":{"horizontal":"center"}}`)
  914. if err != nil {
  915. logx.Error(err)
  916. println("<<<<CentralKitchenForSchoolDataStatisticsExport3>>>>>Error:::", err.Error())
  917. panic(err)
  918. }
  919. xlsx.SetCellStyle("Sheet1", "A1", "K1", style)
  920. xlsx.SetColWidth("Sheet1", "A", "k", 20)
  921. j := 3 //表头前两行用了,只能从第三行开始
  922. for _, v := range m {
  923. if !utils.InArr(v.OutTradeNo, exportOutTradeNoList) {
  924. continue
  925. }
  926. var ordState string //订单状态(0:待支付 1:预约成功 2:退款中 3:部分退款 4:已退款 5:已完成)
  927. switch v.CentralKitchenForSchoolPackageOrd.OrdState {
  928. case enum.CentralKitchenForSchoolPackageOrdOrdStateForWait:
  929. ordState = enum.CentralKitchenForSchoolPackageOrdOrdState.String(enum.CentralKitchenForSchoolPackageOrdOrdStateForWait)
  930. break
  931. case enum.CentralKitchenForSchoolPackageOrdOrdStateForSuccess:
  932. ordState = enum.CentralKitchenForSchoolPackageOrdOrdState.String(enum.CentralKitchenForSchoolPackageOrdOrdStateForSuccess)
  933. break
  934. case enum.CentralKitchenForSchoolPackageOrdOrdStateForRefunding:
  935. ordState = enum.CentralKitchenForSchoolPackageOrdOrdState.String(enum.CentralKitchenForSchoolPackageOrdOrdStateForRefunding)
  936. break
  937. case enum.CentralKitchenForSchoolPackageOrdOrdStateForPartRefunded:
  938. ordState = enum.CentralKitchenForSchoolPackageOrdOrdState.String(enum.CentralKitchenForSchoolPackageOrdOrdStateForPartRefunded)
  939. break
  940. case enum.CentralKitchenForSchoolPackageOrdOrdStateForRefunded:
  941. ordState = enum.CentralKitchenForSchoolPackageOrdOrdState.String(enum.CentralKitchenForSchoolPackageOrdOrdStateForRefunded)
  942. break
  943. case enum.CentralKitchenForSchoolPackageOrdOrdStateForComplete:
  944. ordState = enum.CentralKitchenForSchoolPackageOrdOrdState.String(enum.CentralKitchenForSchoolPackageOrdOrdStateForComplete)
  945. break
  946. }
  947. //预定餐数、预定日期
  948. var list []*model.CentralKitchenForSchoolUserWithDay
  949. err1 := json.Unmarshal([]byte(v.CentralKitchenForSchoolPackageOrd.WithDayData), &list)
  950. if err1 != nil {
  951. logx.Error(err)
  952. println("<<<<CentralKitchenForSchoolDataStatisticsExport1>>>>>Error:::", err.Error())
  953. return
  954. }
  955. var reserveDays string
  956. for _, v1 := range list {
  957. reserveDays += v1.Date + ", "
  958. }
  959. if v.Grade.Name == "" {
  960. v.Grade.Name = "教师"
  961. }
  962. if v.Class.Name == "" {
  963. v.Class.Name = "教师"
  964. }
  965. xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{v.CentralKitchenForSchoolPackageOrd.OutTradeNo, v.CentralKitchenForSchoolPackageOrd.UserIdentityName, v.Enterprise.Name,
  966. v.Grade.Name, v.Class.Name, v.User.Phone, reserveDays, len(list), v.CentralKitchenForSchoolPackageOrd.TotalPrice, v.CentralKitchenForSchoolPackageOrd.CreateAt, ordState})
  967. j++
  968. }
  969. //将文件保存至服务器
  970. xlsx.SaveAs("./static" + downloadPath)
  971. break
  972. case 2:
  973. xlsx := excelize.NewFile()
  974. //退款申请表
  975. fileName = "退款申请表_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
  976. downloadPath = "/export/central_kitchen_for_school/" + fileName
  977. startDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
  978. endDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
  979. //查找退款申请数据
  980. sess := db.Db.Desc("central_kitchen_for_school_user_refund_day.id")
  981. if req.EnterpriseId != 0 {
  982. sess.And("enterprise.id =?", req.EnterpriseId)
  983. }
  984. if req.StartDate != "" {
  985. sess.And("central_kitchen_for_school_user_refund_day.create_at >= ?", req.StartDate)
  986. }
  987. if req.EndDate != "" {
  988. sess.And("central_kitchen_for_school_user_refund_day.create_at <= ?", req.EndDate)
  989. }
  990. if len(req.MealKindList) > 0 {
  991. sess.In("central_kitchen_for_school_user_with_day.kind", req.MealKindList)
  992. }
  993. if req.EnterPriseKind != 0 {
  994. sess.And("enterprise.kind = ?", req.EnterPriseKind)
  995. }
  996. var m []*db.CentralKitchenForSchoolUserRefundDayWithData
  997. _, err := sess.
  998. Join("LEFT", "central_kitchen_for_school_user_with_day", "central_kitchen_for_school_user_refund_day.records_id = central_kitchen_for_school_user_with_day.id").
  999. Join("LEFT", "central_kitchen_for_school_package_ord", "central_kitchen_for_school_user_refund_day.out_trade_no = central_kitchen_for_school_package_ord.out_trade_no").
  1000. Join("LEFT", "user_identity", "central_kitchen_for_school_user_with_day.identity_id = user_identity.id").
  1001. Join("LEFT", "user", "user_identity.uid = user.id").
  1002. Join("LEFT", "enterprise", "user_identity.enterprise_id = enterprise.id").
  1003. Join("LEFT", "class_with_user", "user_identity.id = class_with_user.user_identity_id").
  1004. Join("LEFT", "class", "class_with_user.class_id = class.id").
  1005. Join("LEFT", "grade", "class.grade_id = grade.id").
  1006. Desc("central_kitchen_for_school_user_refund_day.id").
  1007. FindAndCount(&m)
  1008. if err != nil {
  1009. logx.Error(err)
  1010. println("<<<<CentralKitchenForSchoolDataStatisticsExport2>>>>>Error:::", err.Error())
  1011. return
  1012. }
  1013. titleList = []string{startDate.Format("2006-01-02") + "~~" + endDate.Format("2006-01-02") + " 退款申请表"}
  1014. xlsx.SetSheetRow("Sheet1", "A1", &titleList)
  1015. titleList = []string{"学生姓名", "学校", "年级", "班级", "家长电话", "退款日期", "餐型", "退款金额", "退款状态", "支付时间", "退款操作时间"}
  1016. xlsx.SetSheetRow("Sheet1", "A2", &titleList)
  1017. xlsx.MergeCell("Sheet1", "A1", "K1") //合并单元格
  1018. style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFF00"],"pattern":1}, "alignment":{"horizontal":"center"}}`)
  1019. if err != nil {
  1020. logx.Error(err)
  1021. println("<<<<CentralKitchenForSchoolDataStatisticsExport3>>>>>Error:::", err.Error())
  1022. panic(err)
  1023. }
  1024. xlsx.SetCellStyle("Sheet1", "A1", "K1", style)
  1025. xlsx.SetColWidth("Sheet1", "A", "k", 20)
  1026. j := 3 //表头前两行用了,只能从第三行开始
  1027. for _, v := range m {
  1028. var kind string //就餐类型(1:早餐 2:午餐 3:晚餐)
  1029. switch v.CentralKitchenForSchoolUserWithDay.Kind {
  1030. case enum.CentralKitchenForSchoolUserWithDayKindForBreakfast:
  1031. kind = enum.CentralKitchenForSchoolUserWithDayKind.String(enum.CentralKitchenForSchoolUserWithDayKindForBreakfast)
  1032. break
  1033. case enum.CentralKitchenForSchoolUserWithDayKindForLunch:
  1034. kind = enum.CentralKitchenForSchoolUserWithDayKind.String(enum.CentralKitchenForSchoolUserWithDayKindForLunch)
  1035. break
  1036. case enum.CentralKitchenForSchoolUserWithDayKindForDinner:
  1037. kind = enum.CentralKitchenForSchoolUserWithDayKind.String(enum.CentralKitchenForSchoolUserWithDayKindForDinner)
  1038. break
  1039. }
  1040. var state string //状态(1:审核中 2:审核通过 3:审核拒绝 4:退款已完成)
  1041. switch v.CentralKitchenForSchoolUserRefundDay.State {
  1042. case enum.CentralKitchenForSchoolUserRefundDayStateForAuditing:
  1043. state = enum.CentralKitchenForSchoolUserRefundDayState.String(enum.CentralKitchenForSchoolUserRefundDayStateForAuditing)
  1044. break
  1045. case enum.CentralKitchenForSchoolUserRefundDayStateForAuditPass:
  1046. state = enum.CentralKitchenForSchoolUserRefundDayState.String(enum.CentralKitchenForSchoolUserRefundDayStateForAuditPass)
  1047. break
  1048. case enum.CentralKitchenForSchoolUserRefundDayStateForAuditReject:
  1049. state = enum.CentralKitchenForSchoolUserRefundDayState.String(enum.CentralKitchenForSchoolUserRefundDayStateForAuditReject)
  1050. break
  1051. case enum.CentralKitchenForSchoolUserRefundDayStateForAuditComplete:
  1052. state = enum.CentralKitchenForSchoolUserRefundDayState.String(enum.CentralKitchenForSchoolUserRefundDayStateForAuditComplete)
  1053. break
  1054. }
  1055. xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{v.CentralKitchenForSchoolPackageOrd.UserIdentityName, v.Enterprise.Name, v.Grade.Name, v.Class.Name, v.User.Phone,
  1056. v.CentralKitchenForSchoolUserWithDay.Date, kind, v.CentralKitchenForSchoolUserRefundDay.Amount, state, v.CentralKitchenForSchoolPackageOrd.CreateAt, v.CentralKitchenForSchoolUserRefundDay.RefundDate})
  1057. j++
  1058. }
  1059. //将文件保存至服务器
  1060. xlsx.SaveAs("./static" + downloadPath)
  1061. break
  1062. case 3:
  1063. //学校预定统计表
  1064. fileName = "学校预定统计表_" + utils.Int64ToStr(now.UnixMilli()) + ".zip"
  1065. downloadPath = "/export/central_kitchen_for_school/" + fileName
  1066. var m []*db.CentralKitchenForSchoolPackageOrdForReserveWithUserIdentity
  1067. sess := db.Db.Desc("central_kitchen_for_school_package_ord_for_reserve.id")
  1068. if req.EnterpriseId != 0 {
  1069. sess.And("central_kitchen_for_school_package_ord_for_reserve.enterprise_id =?", req.EnterpriseId)
  1070. }
  1071. var months []time.Month
  1072. if req.StartDate != "" {
  1073. sDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
  1074. eDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
  1075. _, sMonth, _ := sDate.Date()
  1076. _, eMonth, _ := eDate.Date()
  1077. diffMonth := sMonth - eMonth
  1078. if diffMonth == 0 {
  1079. //TODO::查询一个月
  1080. months = append(months, sMonth)
  1081. } else {
  1082. for i := sMonth; i <= eMonth; i++ {
  1083. months = append(months, i)
  1084. }
  1085. }
  1086. }
  1087. if len(months) > 0 {
  1088. sess.In("central_kitchen_for_school_package_ord_for_reserve.reserve_month", months)
  1089. }
  1090. //if req.EndDate != "" {
  1091. // sess.And("central_kitchen_for_school_package_ord_for_reserve.meal_time_start <= ?", req.EndDate)
  1092. //}
  1093. if len(req.MealKindList) > 0 {
  1094. sess.In("central_kitchen_for_school_package_ord_for_reserve.kind", req.MealKindList)
  1095. }
  1096. if req.EnterPriseKind != 0 {
  1097. sess.And("enterprise.kind = ?", req.EnterPriseKind)
  1098. }
  1099. _, err := sess.And("user_identity.identity = ?", enum.UserIdentityForCentralKitchenForStudent).
  1100. Join("LEFT", "central_kitchen_for_school_package_ord", "central_kitchen_for_school_package_ord_for_reserve.out_trade_no = central_kitchen_for_school_package_ord.out_trade_no").
  1101. Join("LEFT", "user_identity", "central_kitchen_for_school_package_ord_for_reserve.user_identity_id = user_identity.id").
  1102. Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id").
  1103. Join("LEFT", "user", "user.id = user_identity.uid").
  1104. Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id").
  1105. Join("LEFT", "class", "class_with_user.class_id = class.id").
  1106. Join("LEFT", "grade", "class.grade_id = grade.id").
  1107. FindAndCount(&m)
  1108. if err != nil {
  1109. logx.Error(err)
  1110. println("<<<<SelfSupportForSchoolDataStatisticsExport3>>>>>Error:::", err.Error())
  1111. return
  1112. }
  1113. var ordNoArr, mealKindListArr []string
  1114. for _, v := range m {
  1115. ordNoArr = append(ordNoArr, v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo)
  1116. }
  1117. var nativeSql = "SELECT COUNT(*) AS total, kind , enterprise_id, meal_label_name, ord_no FROM `central_kitchen_for_school_user_with_day` WHERE `ord_no` IN (%s) AND (state !=%d) AND (state !=%d) AND (DATE >= '%s') AND (DATE <= '%s') AND `kind` IN (%s) GROUP BY `ord_no`, `kind`, `meal_label_name`"
  1118. for _, v := range req.MealKindList {
  1119. mealKindListArr = append(mealKindListArr, utils.IntToStr(v))
  1120. }
  1121. sDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
  1122. eDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
  1123. nativeSql = fmt.Sprintf(nativeSql, strings.Join(ordNoArr, ","), enum.CentralKitchenForSchoolUserWithDayStateForCancel, enum.CentralKitchenForSchoolUserWithDayStateForCanceling, sDate.Format("2006-01-02"), eDate.Format("2006-01-02"), strings.Join(mealKindListArr, ","))
  1124. nativeResults, err := db.QueryNativeString(db.Db, nativeSql)
  1125. var nativeResultsMap = map[string]map[int]map[string]int64{}
  1126. var mealLabelMap = map[int]map[int]map[string]string{}
  1127. for _, v := range nativeResults {
  1128. if nativeResultsMap[v["ord_no"]] == nil {
  1129. nativeResultsMap[v["ord_no"]] = make(map[int]map[string]int64)
  1130. }
  1131. if nativeResultsMap[v["ord_no"]][utils.StrToInt(v["kind"])] == nil {
  1132. nativeResultsMap[v["ord_no"]][utils.StrToInt(v["kind"])] = make(map[string]int64)
  1133. }
  1134. nativeResultsMap[v["ord_no"]][utils.StrToInt(v["kind"])][v["meal_label_name"]] = utils.StrToInt64(v["total"])
  1135. if mealLabelMap[utils.StrToInt(v["enterprise_id"])] == nil {
  1136. mealLabelMap[utils.StrToInt(v["enterprise_id"])] = make(map[int]map[string]string)
  1137. }
  1138. if mealLabelMap[utils.StrToInt(v["enterprise_id"])][utils.StrToInt(v["kind"])] == nil {
  1139. mealLabelMap[utils.StrToInt(v["enterprise_id"])][utils.StrToInt(v["kind"])] = make(map[string]string)
  1140. }
  1141. if v["meal_label_name"] == "" {
  1142. fmt.Println(v)
  1143. }
  1144. mealLabelMap[utils.StrToInt(v["enterprise_id"])][utils.StrToInt(v["kind"])][v["meal_label_name"]] = v["meal_label_name"]
  1145. }
  1146. var mealLabel = map[int][]string{}
  1147. for k, v := range mealLabelMap {
  1148. if mealLabel[k] == nil {
  1149. mealLabel[k] = []string{"年级", "班级"}
  1150. }
  1151. for _, vv := range v[enum.CentralKitchenForSchoolUserWithDayKindForBreakfast] {
  1152. mealLabel[k] = append(mealLabel[k], vv)
  1153. }
  1154. for _, vv := range v[enum.CentralKitchenForSchoolUserWithDayKindForLunch] {
  1155. mealLabel[k] = append(mealLabel[k], vv)
  1156. }
  1157. for _, vv := range v[enum.CentralKitchenForSchoolUserWithDayKindForDinner] {
  1158. mealLabel[k] = append(mealLabel[k], vv)
  1159. }
  1160. }
  1161. centralKitchenForSchoolUserWithDayDb := db.CentralKitchenForSchoolUserWithDayDb{}
  1162. centralKitchenForSchoolUserWithDayDb.Set(0)
  1163. var list = map[string]map[string]map[string]map[string]int64{}
  1164. var xlsFileName, xlsDownloadPath []string
  1165. for _, v := range m {
  1166. if list[v.Enterprise.Name] == nil {
  1167. list[v.Enterprise.Name] = make(map[string]map[string]map[string]int64)
  1168. }
  1169. if list[v.Enterprise.Name][v.Grade.Name] == nil {
  1170. list[v.Enterprise.Name][v.Grade.Name] = make(map[string]map[string]int64)
  1171. }
  1172. if list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] == nil {
  1173. list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] = make(map[string]int64)
  1174. }
  1175. for kk, vv := range nativeResultsMap[v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo] {
  1176. if v.CentralKitchenForSchoolPackageOrdForReserve.Kind != kk {
  1177. continue
  1178. }
  1179. for kkk, vvv := range vv {
  1180. list[v.Enterprise.Name][v.Grade.Name][v.Class.Name][kkk] += vvv
  1181. }
  1182. }
  1183. }
  1184. for k1, v1 := range list {
  1185. xlsx := excelize.NewFile()
  1186. tmpFileName := k1 + "学校预定统计表_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
  1187. tmpDownloadPath := "./static/export/central_kitchen_for_school/" + tmpFileName
  1188. startDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
  1189. endDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
  1190. titleList = []string{startDate.Format("2006-01-02") + "~~" + endDate.Format("2006-01-02") + " (" + k1 + ") "}
  1191. xlsx.SetSheetRow("Sheet1", "A1", &titleList)
  1192. tmpEnterpriseDb := db.EnterpriseDb{}
  1193. tmpEnterpriseDb.Set()
  1194. tmpEnterprise, err11 := tmpEnterpriseDb.GetEnterpriseByName(k1)
  1195. if err11 != nil {
  1196. logx.Error(err11)
  1197. println("<<<<CentralKitchenForSchoolDataStatisticsExport3>>>>>Error:::", err11.Error())
  1198. panic(err11)
  1199. }
  1200. //titleList = []string{"年级", "班级", "早餐", "午餐", "晚餐"}
  1201. titleList = mealLabel[tmpEnterprise.Id]
  1202. xlsx.SetSheetRow("Sheet1", "A2", &titleList)
  1203. xlsx.MergeCell("Sheet1", "A1", "E1") //合并单元格
  1204. style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFF00"],"pattern":1}, "alignment":{"horizontal":"center"}}`)
  1205. if err != nil {
  1206. logx.Error(err)
  1207. println("<<<<CentralKitchenForSchoolDataStatisticsExport3>>>>>Error:::", err.Error())
  1208. panic(err)
  1209. }
  1210. xlsx.SetCellStyle("Sheet1", "A1", "M1", style)
  1211. xlsx.SetColWidth("Sheet1", "A", "M", 20)
  1212. j := 3 //表头前两行用了,只能从第三行开始
  1213. var sumTotal = map[string]int64{}
  1214. tmpClassDb := db.ClassDb{}
  1215. tmpClassDb.Set(0)
  1216. var classList *[]model.Class
  1217. //TODO::判断单位类型
  1218. if tmpEnterprise.Kind == enum.EnterpriseKindByCentralKitchenForSchool {
  1219. classList, err = tmpClassDb.FindClassAscByEnterprise(tmpEnterprise.Id)
  1220. if err != nil {
  1221. logx.Error(err)
  1222. println("<<<<CentralKitchenForSchoolDataStatisticsExport4>>>>>Error:::", err.Error())
  1223. panic(err)
  1224. }
  1225. } else {
  1226. classList, err = tmpClassDb.FindClassSortAscByEnterprise(tmpEnterprise.Id)
  1227. if err != nil {
  1228. logx.Error(err)
  1229. println("<<<<CentralKitchenForSchoolDataStatisticsExport4>>>>>Error:::", err.Error())
  1230. panic(err)
  1231. }
  1232. }
  1233. for _, class := range *classList {
  1234. for k2, v2 := range v1 {
  1235. if k2 == "" {
  1236. //若年级为空,则为教师餐
  1237. k2 = "教师餐"
  1238. }
  1239. for k3, v3 := range v2 {
  1240. if class.Name != k3 {
  1241. continue
  1242. }
  1243. if k3 == "" {
  1244. //若班级为空,则为教师餐
  1245. k3 = "教师餐"
  1246. }
  1247. var slice = []interface{}{k2, k3}
  1248. for key, meal := range mealLabel[tmpEnterprise.Id] {
  1249. if key != 0 && key != 1 {
  1250. slice = append(slice, v3[meal])
  1251. sumTotal[meal] += v3[meal]
  1252. }
  1253. }
  1254. xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &slice)
  1255. j++
  1256. }
  1257. }
  1258. }
  1259. var slice = []interface{}{"合计", ""}
  1260. for key, meal := range mealLabel[tmpEnterprise.Id] {
  1261. if key != 0 && key != 1 {
  1262. slice = append(slice, sumTotal[meal])
  1263. sumTotal[meal] += sumTotal[meal]
  1264. }
  1265. }
  1266. xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &slice)
  1267. //将文件保存至服务器
  1268. err1 := xlsx.SaveAs(tmpDownloadPath)
  1269. if err1 != nil {
  1270. logx.Error(err1)
  1271. println("<<<<CentralKitchenForSchoolDataStatisticsExport3>>>>>Error:::", err1.Error())
  1272. panic(err1)
  1273. }
  1274. xlsDownloadPath = append(xlsDownloadPath, tmpDownloadPath)
  1275. xlsFileName = append(xlsFileName, tmpFileName)
  1276. }
  1277. archive, err := os.Create("./static" + downloadPath) //第一步,创建 zip 文件
  1278. if err != nil {
  1279. logx.Error(err)
  1280. println("<<<<CentralKitchenForSchoolDataStatisticsExport3>>>>>Error:::", err.Error())
  1281. panic(err)
  1282. }
  1283. defer archive.Close()
  1284. zipWriter := zip.NewWriter(archive) //第二步,创建一个新的 *Writer 对象
  1285. for k, v := range xlsDownloadPath {
  1286. w, err1 := zipWriter.Create("学校预定统计/" + xlsFileName[k]) //向 zip 文件中添加一个文件,返回一个待压缩的文件内容应写入的 Writer
  1287. if err1 != nil {
  1288. logx.Error(err1)
  1289. println("<<<<CentralKitchenForSchoolDataStatisticsExport3>>>>>Error:::", err1.Error())
  1290. panic(err1)
  1291. }
  1292. f, err1 := os.Open(v) //打开待压缩的文件
  1293. if err1 != nil {
  1294. logx.Error(err1)
  1295. println("<<<<CentralKitchenForSchoolDataStatisticsExport3>>>>>Error:::", err1.Error())
  1296. panic(err1)
  1297. }
  1298. if _, err1 = io.Copy(w, f); err != nil {
  1299. logx.Error(err1)
  1300. println("<<<<CentralKitchenForSchoolDataStatisticsExport3>>>>>Error:::", err1.Error())
  1301. panic(err1)
  1302. }
  1303. if err1 != nil {
  1304. logx.Error(err1)
  1305. println("<<<<CentralKitchenForSchoolDataStatisticsExport3>>>>>Error:::", err1.Error())
  1306. panic(err1)
  1307. }
  1308. f.Close()
  1309. os.RemoveAll(v) //TODO::移除源文件
  1310. }
  1311. zipWriter.Close() // 第四步,关闭 zip writer,将所有数据写入指向基础 zip 文件的数据流
  1312. if err != nil {
  1313. panic(err)
  1314. }
  1315. break
  1316. case 4:
  1317. //班级明细表
  1318. fileName = "班级明细表_" + utils.Int64ToStr(now.UnixMilli()) + ".zip"
  1319. downloadPath = "/export/central_kitchen_for_school/" + fileName
  1320. var m []*db.CentralKitchenForSchoolPackageOrdForReserveWithUserIdentity
  1321. sess := db.Db.Desc("central_kitchen_for_school_package_ord_for_reserve.id")
  1322. if req.EnterpriseId != 0 {
  1323. sess.And("central_kitchen_for_school_package_ord_for_reserve.enterprise_id =?", req.EnterpriseId)
  1324. }
  1325. var months []time.Month
  1326. if req.StartDate != "" {
  1327. sDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
  1328. eDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
  1329. _, sMonth, _ := sDate.Date()
  1330. _, eMonth, _ := eDate.Date()
  1331. diffMonth := sMonth - eMonth
  1332. if diffMonth == 0 {
  1333. //TODO::查询一个月
  1334. months = append(months, sMonth)
  1335. } else {
  1336. for i := sMonth; i <= eMonth; i++ {
  1337. months = append(months, i)
  1338. }
  1339. }
  1340. }
  1341. if len(months) > 0 {
  1342. sess.In("central_kitchen_for_school_package_ord_for_reserve.reserve_month", months)
  1343. }
  1344. //if req.EndDate != "" {
  1345. // sess.And("central_kitchen_for_school_package_ord_for_reserve.meal_time_start <= ?", req.EndDate)
  1346. //}
  1347. if len(req.MealKindList) > 0 {
  1348. sess.In("central_kitchen_for_school_package_ord_for_reserve.kind", req.MealKindList)
  1349. }
  1350. if req.EnterPriseKind != 0 {
  1351. sess.And("enterprise.kind = ?", req.EnterPriseKind)
  1352. }
  1353. _, err := sess.And("user_identity.identity = ?", enum.UserIdentityForCentralKitchenForStudent).
  1354. Join("LEFT", "central_kitchen_for_school_package_ord", "central_kitchen_for_school_package_ord_for_reserve.out_trade_no = central_kitchen_for_school_package_ord.out_trade_no").
  1355. Join("LEFT", "user_identity", "central_kitchen_for_school_package_ord_for_reserve.user_identity_id = user_identity.id").
  1356. Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id").
  1357. Join("LEFT", "user", "user.id = user_identity.uid").
  1358. Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id").
  1359. Join("LEFT", "class", "class_with_user.class_id = class.id").
  1360. Join("LEFT", "grade", "class.grade_id = grade.id").
  1361. Asc("class.id").
  1362. FindAndCount(&m)
  1363. if err != nil {
  1364. logx.Error(err)
  1365. println("<<<<CentralKitchenForSchoolDataStatisticsExport4>>>>>Error:::", err.Error())
  1366. return
  1367. }
  1368. var ordNoArr, mealKindListArr []string
  1369. for _, v := range m {
  1370. ordNoArr = append(ordNoArr, v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo)
  1371. }
  1372. var nativeSql = "SELECT COUNT(*) AS total, kind , enterprise_id, meal_label_name, ord_no FROM `central_kitchen_for_school_user_with_day` WHERE `ord_no` IN (%s) AND (state !=%d) AND (state !=%d) AND (DATE >= '%s') AND (DATE <= '%s') AND `kind` IN (%s) GROUP BY `ord_no`, `kind`, `meal_label_name`"
  1373. for _, v := range req.MealKindList {
  1374. mealKindListArr = append(mealKindListArr, utils.IntToStr(v))
  1375. }
  1376. sDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
  1377. eDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
  1378. nativeSql = fmt.Sprintf(nativeSql, strings.Join(ordNoArr, ","), enum.CentralKitchenForSchoolUserWithDayStateForCancel, enum.CentralKitchenForSchoolUserWithDayStateForCanceling, sDate.Format("2006-01-02"), eDate.Format("2006-01-02"), strings.Join(mealKindListArr, ","))
  1379. fmt.Println(nativeSql)
  1380. nativeResults, err := db.QueryNativeString(db.Db, nativeSql)
  1381. var nativeResultsMap = map[string]map[int]map[string]int64{}
  1382. var mealLabelMap = map[int]map[int]map[string]string{}
  1383. for _, v := range nativeResults {
  1384. if nativeResultsMap[v["ord_no"]] == nil {
  1385. nativeResultsMap[v["ord_no"]] = make(map[int]map[string]int64)
  1386. }
  1387. if nativeResultsMap[v["ord_no"]][utils.StrToInt(v["kind"])] == nil {
  1388. nativeResultsMap[v["ord_no"]][utils.StrToInt(v["kind"])] = make(map[string]int64)
  1389. }
  1390. nativeResultsMap[v["ord_no"]][utils.StrToInt(v["kind"])][v["meal_label_name"]] = utils.StrToInt64(v["total"])
  1391. if mealLabelMap[utils.StrToInt(v["enterprise_id"])] == nil {
  1392. mealLabelMap[utils.StrToInt(v["enterprise_id"])] = make(map[int]map[string]string)
  1393. }
  1394. if mealLabelMap[utils.StrToInt(v["enterprise_id"])][utils.StrToInt(v["kind"])] == nil {
  1395. mealLabelMap[utils.StrToInt(v["enterprise_id"])][utils.StrToInt(v["kind"])] = make(map[string]string)
  1396. }
  1397. if v["meal_label_name"] == "" {
  1398. fmt.Println(v)
  1399. }
  1400. mealLabelMap[utils.StrToInt(v["enterprise_id"])][utils.StrToInt(v["kind"])][v["meal_label_name"]] = v["meal_label_name"]
  1401. }
  1402. var mealLabel = map[int][]string{}
  1403. for k, v := range mealLabelMap {
  1404. if mealLabel[k] == nil {
  1405. mealLabel[k] = []string{"年级"}
  1406. }
  1407. for _, vv := range v[enum.CentralKitchenForSchoolUserWithDayKindForBreakfast] {
  1408. mealLabel[k] = append(mealLabel[k], vv)
  1409. }
  1410. for _, vv := range v[enum.CentralKitchenForSchoolUserWithDayKindForLunch] {
  1411. mealLabel[k] = append(mealLabel[k], vv)
  1412. }
  1413. for _, vv := range v[enum.CentralKitchenForSchoolUserWithDayKindForDinner] {
  1414. mealLabel[k] = append(mealLabel[k], vv)
  1415. }
  1416. }
  1417. var list = map[string]map[string]map[string]map[string]map[string]int64{}
  1418. var xlsFileName, xlsDownloadPath []string
  1419. centralKitchenForSchoolUserWithDayDb := db.CentralKitchenForSchoolUserWithDayDb{}
  1420. centralKitchenForSchoolUserWithDayDb.Set(0)
  1421. for _, v := range m {
  1422. for kk, vv := range nativeResultsMap[v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo] {
  1423. if v.CentralKitchenForSchoolPackageOrdForReserve.Kind != kk {
  1424. continue
  1425. }
  1426. if list[v.Enterprise.Name] == nil {
  1427. list[v.Enterprise.Name] = make(map[string]map[string]map[string]map[string]int64)
  1428. }
  1429. if list[v.Enterprise.Name][v.Grade.Name] == nil {
  1430. list[v.Enterprise.Name][v.Grade.Name] = make(map[string]map[string]map[string]int64)
  1431. }
  1432. if list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] == nil {
  1433. list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] = make(map[string]map[string]int64)
  1434. }
  1435. if list[v.Enterprise.Name][v.Grade.Name][v.Class.Name][v.UserIdentity.Name] == nil {
  1436. list[v.Enterprise.Name][v.Grade.Name][v.Class.Name][v.UserIdentity.Name] = make(map[string]int64)
  1437. }
  1438. for kkk, vvv := range vv {
  1439. list[v.Enterprise.Name][v.Grade.Name][v.Class.Name][v.UserIdentity.Name][kkk] += vvv
  1440. }
  1441. }
  1442. }
  1443. for k1, v1 := range list {
  1444. xlsx := excelize.NewFile()
  1445. tmpFileName := k1 + "班级明细_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
  1446. tmpDownloadPath := "./static/export/central_kitchen_for_school/" + tmpFileName
  1447. startDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
  1448. endDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
  1449. //查询当前学校下的班级升序
  1450. tmpEnterpriseDb := db.EnterpriseDb{}
  1451. tmpEnterpriseDb.Set()
  1452. tmpEnterprise, err11 := tmpEnterpriseDb.GetEnterpriseByName(k1)
  1453. if err11 != nil {
  1454. logx.Error(err11)
  1455. println("<<<<CentralKitchenForSchoolDataStatisticsExport4>>>>>Error:::", err11.Error())
  1456. panic(err11)
  1457. }
  1458. tmpClassDb := db.ClassDb{}
  1459. tmpClassDb.Set(0)
  1460. var classList *[]model.Class
  1461. //TODO::判断单位类型
  1462. if tmpEnterprise.Kind == enum.EnterpriseKindByCentralKitchenForSchool {
  1463. classList, err = tmpClassDb.FindClassAscByEnterprise(tmpEnterprise.Id)
  1464. if err != nil {
  1465. logx.Error(err)
  1466. println("<<<<CentralKitchenForSchoolDataStatisticsExport4>>>>>Error:::", err.Error())
  1467. panic(err)
  1468. }
  1469. } else {
  1470. classList, err = tmpClassDb.FindClassSortAscByEnterprise(tmpEnterprise.Id)
  1471. if err != nil {
  1472. logx.Error(err)
  1473. println("<<<<CentralKitchenForSchoolDataStatisticsExport4>>>>>Error:::", err.Error())
  1474. panic(err)
  1475. }
  1476. }
  1477. for _, class := range *classList {
  1478. for k2, v2 := range v1 {
  1479. if k2 == "" {
  1480. //若年级为空,则为教师餐
  1481. continue
  1482. }
  1483. for k3, v3 := range v2 {
  1484. if class.Name != k3 {
  1485. continue
  1486. }
  1487. xlsx.NewSheet(k3)
  1488. titleList = []string{startDate.Format("2006-01-02") + "~~" + endDate.Format("2006-01-02") + " [" + k1 + ", " + k3 + "] 班级明细"}
  1489. xlsx.SetSheetRow(k3, "A1", &titleList)
  1490. //titleList = []string{"姓名", "早餐", "午餐", "晚餐"}
  1491. titleList = mealLabel[tmpEnterprise.Id]
  1492. xlsx.SetSheetRow(k3, "A2", &titleList)
  1493. xlsx.MergeCell(k3, "A1", "D1") //合并单元格
  1494. style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFF00"],"pattern":1}, "alignment":{"horizontal":"center"}}`)
  1495. if err != nil {
  1496. logx.Error(err)
  1497. println("<<<<CentralKitchenForSchoolDataStatisticsExport3>>>>>Error:::", err.Error())
  1498. panic(err)
  1499. }
  1500. xlsx.SetCellStyle(k3, "A1", "D1", style)
  1501. xlsx.SetColWidth(k3, "A", "D", 20)
  1502. var sumTotal = map[string]int64{}
  1503. j := 3 //表头前两行用了,只能从第三行开始
  1504. for k4, v4 := range v3 {
  1505. var slice = []interface{}{k4}
  1506. for key, meal := range mealLabel[tmpEnterprise.Id] {
  1507. if key != 0 {
  1508. slice = append(slice, v4[meal])
  1509. sumTotal[meal] += v4[meal]
  1510. }
  1511. }
  1512. xlsx.SetSheetRow(k3, "A"+strconv.Itoa(j), &slice)
  1513. j++
  1514. }
  1515. var slice = []interface{}{"合计"}
  1516. for key, meal := range mealLabel[tmpEnterprise.Id] {
  1517. if key != 0 {
  1518. slice = append(slice, sumTotal[meal])
  1519. sumTotal[meal] += sumTotal[meal]
  1520. }
  1521. }
  1522. xlsx.SetSheetRow(k3, "A"+strconv.Itoa(j), &slice)
  1523. }
  1524. }
  1525. }
  1526. //将文件保存至服务器
  1527. xlsx.DeleteSheet("Sheet1") //TODO::只能放这里删除
  1528. err1 := xlsx.SaveAs(tmpDownloadPath)
  1529. if err1 != nil {
  1530. logx.Error(err1)
  1531. println("<<<<CentralKitchenForSchoolDataStatisticsExport4>>>>>Error:::", err1.Error())
  1532. panic(err1)
  1533. }
  1534. xlsDownloadPath = append(xlsDownloadPath, tmpDownloadPath)
  1535. xlsFileName = append(xlsFileName, tmpFileName)
  1536. }
  1537. archive, err := os.Create("./static" + downloadPath) //第一步,创建 zip 文件
  1538. if err != nil {
  1539. logx.Error(err)
  1540. println("<<<<CentralKitchenForSchoolDataStatisticsExport4>>>>>Error:::", err.Error())
  1541. panic(err)
  1542. }
  1543. defer archive.Close()
  1544. zipWriter := zip.NewWriter(archive) //第二步,创建一个新的 *Writer 对象
  1545. for k, v := range xlsDownloadPath {
  1546. w, err1 := zipWriter.Create("班级明细/" + xlsFileName[k]) //向 zip 文件中添加一个文件,返回一个待压缩的文件内容应写入的 Writer
  1547. if err1 != nil {
  1548. logx.Error(err1)
  1549. println("<<<<CentralKitchenForSchoolDataStatisticsExport4>>>>>Error:::", err1.Error())
  1550. panic(err1)
  1551. }
  1552. f, err1 := os.Open(v) //打开待压缩的文件
  1553. if err1 != nil {
  1554. logx.Error(err1)
  1555. println("<<<<CentralKitchenForSchoolDataStatisticsExport4>>>>>Error:::", err1.Error())
  1556. panic(err1)
  1557. }
  1558. if _, err1 = io.Copy(w, f); err != nil {
  1559. logx.Error(err1)
  1560. println("<<<<CentralKitchenForSchoolDataStatisticsExport4>>>>>Error:::", err1.Error())
  1561. panic(err1)
  1562. }
  1563. if err1 != nil {
  1564. logx.Error(err1)
  1565. println("<<<<CentralKitchenForSchoolDataStatisticsExport4>>>>>Error:::", err1.Error())
  1566. panic(err1)
  1567. }
  1568. f.Close()
  1569. os.RemoveAll(v) //TODO::移除源文件
  1570. }
  1571. zipWriter.Close() // 第四步,关闭 zip writer,将所有数据写入指向基础 zip 文件的数据流
  1572. if err != nil {
  1573. panic(err)
  1574. }
  1575. break
  1576. case 5:
  1577. xlsx := excelize.NewFile()
  1578. //退款明细表
  1579. fileName = "退款明细表_" + utils.Int64ToStr(now.UnixMilli()) + ".zip"
  1580. downloadPath = "/export/central_kitchen_for_school/" + fileName
  1581. sess := db.Db.Where("central_kitchen_for_school_user_refund_day.state =?", enum.CentralKitchenForSchoolUserRefundDayStateForAuditComplete).Desc("central_kitchen_for_school_user_refund_day.id")
  1582. if req.EnterpriseId != 0 {
  1583. sess.And("enterprise.id =?", req.EnterpriseId)
  1584. }
  1585. if req.StartDate != "" {
  1586. sess.And("central_kitchen_for_school_user_refund_day.create_at >= ?", req.StartDate)
  1587. }
  1588. if req.EndDate != "" {
  1589. sess.And("central_kitchen_for_school_user_refund_day.create_at <= ?", req.EndDate)
  1590. }
  1591. if len(req.MealKindList) > 0 {
  1592. sess.In("central_kitchen_for_school_user_with_day.kind", req.MealKindList)
  1593. }
  1594. if req.EnterPriseKind != 0 {
  1595. sess.And("enterprise.kind = ?", req.EnterPriseKind)
  1596. }
  1597. var m []*db.CentralKitchenForSchoolUserRefundDayWithData
  1598. _, err := sess.
  1599. Join("LEFT", "central_kitchen_for_school_user_with_day", "central_kitchen_for_school_user_refund_day.records_id = central_kitchen_for_school_user_with_day.id").
  1600. Join("LEFT", "central_kitchen_for_school_package_ord", "central_kitchen_for_school_user_refund_day.out_trade_no = central_kitchen_for_school_package_ord.out_trade_no").
  1601. Join("LEFT", "user_identity", "central_kitchen_for_school_user_with_day.identity_id = user_identity.id").
  1602. Join("LEFT", "user", "user_identity.uid = user.id").
  1603. Join("LEFT", "enterprise", "user_identity.enterprise_id = enterprise.id").
  1604. Join("LEFT", "class_with_user", "user_identity.id = class_with_user.user_identity_id").
  1605. Join("LEFT", "class", "class_with_user.class_id = class.id").
  1606. Join("LEFT", "grade", "class.grade_id = grade.id").
  1607. Desc("central_kitchen_for_school_user_refund_day.id").
  1608. FindAndCount(&m)
  1609. if err != nil {
  1610. logx.Error(err)
  1611. println("<<<<CentralKitchenForSchoolDataStatisticsExport5>>>>>Error:::", err.Error())
  1612. return
  1613. }
  1614. var list = map[string]map[string]map[string]map[string]map[string]int{}
  1615. var xlsFileName, xlsDownloadPath []string
  1616. for _, v := range m {
  1617. if list[v.Enterprise.Name] == nil {
  1618. list[v.Enterprise.Name] = make(map[string]map[string]map[string]map[string]int)
  1619. }
  1620. if list[v.Enterprise.Name][v.Grade.Name] == nil {
  1621. list[v.Enterprise.Name][v.Grade.Name] = make(map[string]map[string]map[string]int)
  1622. }
  1623. if list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] == nil {
  1624. list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] = make(map[string]map[string]int)
  1625. }
  1626. if list[v.Enterprise.Name][v.Grade.Name][v.Class.Name][v.UserIdentity.Name] == nil {
  1627. list[v.Enterprise.Name][v.Grade.Name][v.Class.Name][v.UserIdentity.Name] = make(map[string]int)
  1628. }
  1629. //就餐类型(1:早餐 2:午餐 3:晚餐)
  1630. if v.CentralKitchenForSchoolUserWithDay.Kind == enum.CentralKitchenForSchoolUserWithDayKindForBreakfast {
  1631. list[v.Enterprise.Name][v.Grade.Name][v.Class.Name][v.UserIdentity.Name]["breakfast"]++
  1632. }
  1633. if v.CentralKitchenForSchoolUserWithDay.Kind == enum.CentralKitchenForSchoolUserWithDayKindForLunch {
  1634. list[v.Enterprise.Name][v.Grade.Name][v.Class.Name][v.UserIdentity.Name]["lunch"]++
  1635. }
  1636. if v.CentralKitchenForSchoolUserWithDay.Kind == enum.CentralKitchenForSchoolUserWithDayKindForDinner {
  1637. list[v.Enterprise.Name][v.Grade.Name][v.Class.Name][v.UserIdentity.Name]["dinner"]++
  1638. }
  1639. }
  1640. for k1, v1 := range list {
  1641. tmpFileName := k1 + "退款明细_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
  1642. tmpDownloadPath := "./static/export/central_kitchen_for_school/" + tmpFileName
  1643. startDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
  1644. endDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
  1645. for k2, v2 := range v1 {
  1646. if k2 == "" {
  1647. //若年级为空,则为教师餐
  1648. continue
  1649. }
  1650. for k3, v3 := range v2 {
  1651. xlsx.NewSheet(k3)
  1652. titleList = []string{startDate.Format("2006-01-02") + "~~" + endDate.Format("2006-01-02") + " [" + k1 + ", " + k3 + "] 退款明细"}
  1653. xlsx.SetSheetRow(k3, "A1", &titleList)
  1654. titleList = []string{"姓名", "早餐", "午餐", "晚餐"}
  1655. xlsx.SetSheetRow(k3, "A2", &titleList)
  1656. xlsx.MergeCell(k3, "A1", "D1") //合并单元格
  1657. style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFF00"],"pattern":1}, "alignment":{"horizontal":"center"}}`)
  1658. if err != nil {
  1659. logx.Error(err)
  1660. println("<<<<CentralKitchenForSchoolDataStatisticsExport3>>>>>Error:::", err.Error())
  1661. panic(err)
  1662. }
  1663. xlsx.SetCellStyle(k3, "A1", "D1", style)
  1664. xlsx.SetColWidth(k3, "A", "D", 20)
  1665. var sumBreakfast, sumLunch, sumDinner = 0, 0, 0
  1666. j := 3 //表头前两行用了,只能从第三行开始
  1667. for k4, v4 := range v3 {
  1668. xlsx.SetSheetRow(k3, "A"+strconv.Itoa(j), &[]interface{}{
  1669. k4, v4["breakfast"], v4["lunch"], v4["dinner"]})
  1670. sumBreakfast += v4["breakfast"]
  1671. sumLunch += v4["lunch"]
  1672. sumDinner += v4["dinner"]
  1673. j++
  1674. }
  1675. xlsx.SetSheetRow(k3, "A"+strconv.Itoa(j), &[]interface{}{
  1676. "合计", sumBreakfast, sumLunch, sumDinner})
  1677. }
  1678. }
  1679. //将文件保存至服务器
  1680. xlsx.DeleteSheet("Sheet1") //TODO::只能放这里删除
  1681. err1 := xlsx.SaveAs(tmpDownloadPath)
  1682. if err1 != nil {
  1683. logx.Error(err1)
  1684. println("<<<<CentralKitchenForSchoolDataStatisticsExport5>>>>>Error:::", err1.Error())
  1685. panic(err1)
  1686. }
  1687. xlsDownloadPath = append(xlsDownloadPath, tmpDownloadPath)
  1688. xlsFileName = append(xlsFileName, tmpFileName)
  1689. }
  1690. archive, err := os.Create("./static" + downloadPath) //第一步,创建 zip 文件
  1691. if err != nil {
  1692. logx.Error(err)
  1693. println("<<<<CentralKitchenForSchoolDataStatisticsExport5>>>>>Error:::", err.Error())
  1694. panic(err)
  1695. }
  1696. defer archive.Close()
  1697. zipWriter := zip.NewWriter(archive) //第二步,创建一个新的 *Writer 对象
  1698. for k, v := range xlsDownloadPath {
  1699. w, err1 := zipWriter.Create("退款明细/" + xlsFileName[k]) //向 zip 文件中添加一个文件,返回一个待压缩的文件内容应写入的 Writer
  1700. if err1 != nil {
  1701. logx.Error(err1)
  1702. println("<<<<CentralKitchenForSchoolDataStatisticsExport5>>>>>Error:::", err1.Error())
  1703. panic(err1)
  1704. }
  1705. f, err1 := os.Open(v) //打开待压缩的文件
  1706. if err1 != nil {
  1707. logx.Error(err1)
  1708. println("<<<<CentralKitchenForSchoolDataStatisticsExport5>>>>>Error:::", err1.Error())
  1709. panic(err1)
  1710. }
  1711. if _, err1 = io.Copy(w, f); err != nil {
  1712. logx.Error(err1)
  1713. println("<<<<CentralKitchenForSchoolDataStatisticsExport5>>>>>Error:::", err1.Error())
  1714. panic(err1)
  1715. }
  1716. if err1 != nil {
  1717. logx.Error(err1)
  1718. println("<<<<CentralKitchenForSchoolDataStatisticsExport5>>>>>Error:::", err1.Error())
  1719. panic(err1)
  1720. }
  1721. f.Close()
  1722. os.RemoveAll(v) //TODO::移除源文件
  1723. }
  1724. zipWriter.Close() // 第四步,关闭 zip writer,将所有数据写入指向基础 zip 文件的数据流
  1725. if err != nil {
  1726. panic(err)
  1727. }
  1728. break
  1729. case 6:
  1730. xlsx := excelize.NewFile()
  1731. //收款统计表
  1732. fileName = "收款统计表_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
  1733. downloadPath = "/export/central_kitchen_for_school/" + fileName
  1734. startDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
  1735. endDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
  1736. //查找数据
  1737. var m []model.Enterprise
  1738. sess := db.Db.Desc("id")
  1739. if req.EnterPriseKind != 0 {
  1740. sess.And("kind = ?", req.EnterPriseKind)
  1741. }
  1742. if req.EnterpriseId != 0 {
  1743. sess.And("id = ?", req.EnterpriseId)
  1744. }
  1745. err := sess.Find(&m)
  1746. if err != nil {
  1747. logx.Error(err)
  1748. println("<<<<CentralKitchenForSchoolDataStatisticsExport6>>>>>Error:::", err.Error())
  1749. return
  1750. }
  1751. titleList = []string{startDate.Format("2006-01-02") + "~~" + endDate.Format("2006-01-02") + " 收款统计表"}
  1752. xlsx.SetSheetRow("Sheet1", "A1", &titleList)
  1753. titleList = []string{"学校名称", "预定总费用", "退款总计", "实收费用", "预估费率"}
  1754. xlsx.SetSheetRow("Sheet1", "A2", &titleList)
  1755. xlsx.MergeCell("Sheet1", "A1", "E1") //合并单元格
  1756. style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFF00"],"pattern":1}, "alignment":{"horizontal":"center"}}`)
  1757. if err != nil {
  1758. logx.Error(err)
  1759. println("<<<<CentralKitchenForSchoolDataStatisticsExport3>>>>>Error:::", err.Error())
  1760. panic(err)
  1761. }
  1762. xlsx.SetCellStyle("Sheet1", "A1", "E1", style)
  1763. xlsx.SetColWidth("Sheet1", "A", "E", 20)
  1764. var incomeTotal, refundTotal, realityAmountTotal, rateFeeTotal float64
  1765. j := 3 //表头前两行用了,只能从第三行开始
  1766. for _, v := range m {
  1767. var income, refund string
  1768. //统计收入
  1769. sql1 := fmt.Sprintf("SELECT sum(total_price) as total FROM central_kitchen_for_school_package_ord where state = 1 and enterprise_id = %d and pay_at >= '%s' and pay_at < '%s'", v.Id, req.StartDate, req.EndDate)
  1770. mapArr1, err := db.QueryNativeString(db.Db, sql1)
  1771. if err != nil {
  1772. logx.Error(err)
  1773. println("<<<<CentralKitchenForSchoolDataStatisticsExport6>>>>>Error:::", err.Error())
  1774. return
  1775. }
  1776. if mapArr1 != nil {
  1777. income = mapArr1[0]["total"]
  1778. }
  1779. //统计退款
  1780. //查询出当前学校下所有的学生
  1781. userIdentityDb := db.UserIdentityDb{}
  1782. userIdentityDb.Set(0)
  1783. userIdentities, _ := userIdentityDb.FindUserIdentityForEnterprise(v.Id)
  1784. var userIdentityIds []string
  1785. for _, v := range *userIdentities {
  1786. userIdentityIds = append(userIdentityIds, utils.IntToStr(v.Id))
  1787. }
  1788. if len(userIdentityIds) != 0 {
  1789. userIdentityStr := php2go.Implode(",", userIdentityIds)
  1790. sql2 := fmt.Sprintf("SELECT sum(amount) as total FROM central_kitchen_for_school_user_refund_day where state = %d and identity_id IN (%s) and refund_date >= '%s' and refund_date < '%s'",
  1791. enum.CentralKitchenForSchoolUserRefundDayStateForAuditComplete, userIdentityStr, req.StartDate, req.EndDate)
  1792. mapArr2, err := db.QueryNativeString(db.Db, sql2)
  1793. if err != nil {
  1794. logx.Error(err)
  1795. println("<<<<CentralKitchenForSchoolDataStatisticsExport6>>>>>Error:::", err.Error())
  1796. return
  1797. }
  1798. if mapArr2 != nil {
  1799. refund = mapArr2[0]["total"]
  1800. }
  1801. }
  1802. realityAmount := utils.StrToFloat64(income) - utils.StrToFloat64(refund)
  1803. rateFee := realityAmount * 0.002
  1804. xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{v.Name, income, refund, realityAmount, rateFee})
  1805. incomeTotal += utils.StrToFloat64(income)
  1806. refundTotal += utils.StrToFloat64(refund)
  1807. realityAmountTotal += realityAmount
  1808. rateFeeTotal += rateFee
  1809. j++
  1810. }
  1811. xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{"总计", incomeTotal, refundTotal, realityAmountTotal, rateFeeTotal})
  1812. //将文件保存至服务器
  1813. xlsx.SaveAs("./static" + downloadPath)
  1814. break
  1815. case 7:
  1816. xlsx := excelize.NewFile()
  1817. //班级收款明细表
  1818. fileName = "班级收款明细表_" + utils.Int64ToStr(now.UnixMilli()) + ".zip"
  1819. downloadPath = "/export/central_kitchen_for_school/" + fileName
  1820. //查找订单数据
  1821. sess := db.Db.Desc("central_kitchen_for_school_package_ord.id")
  1822. sess.And("central_kitchen_for_school_package_ord.state =?", enum.CentralKitchenForSchoolPackageOrdStateForSuccess).And("user_identity.identity = ?", enum.UserIdentityForCentralKitchenForStudent)
  1823. if req.EnterpriseId != 0 {
  1824. sess.And("central_kitchen_for_school_package_ord.enterprise_id =?", req.EnterpriseId)
  1825. }
  1826. if req.StartDate != "" {
  1827. sess.And("central_kitchen_for_school_package_ord.pay_at >= ?", req.StartDate)
  1828. }
  1829. if req.EndDate != "" {
  1830. sess.And("central_kitchen_for_school_package_ord.pay_at <= ?", req.EndDate)
  1831. }
  1832. if req.EnterPriseKind != 0 {
  1833. sess.And("enterprise.kind = ?", req.EnterPriseKind)
  1834. }
  1835. var m []*db.CentralKitchenForSchoolPackageOrdWithUserIdentity
  1836. _, err := sess.
  1837. Join("LEFT", "user_identity", "central_kitchen_for_school_package_ord_for_reserve.user_identity_id = user_identity.id").
  1838. Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id").
  1839. Join("LEFT", "user", "user.id = user_identity.uid").
  1840. Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id").
  1841. Join("LEFT", "class", "class_with_user.class_id = class.id").
  1842. Join("LEFT", "grade", "class.grade_id = grade.id").
  1843. FindAndCount(&m)
  1844. if err != nil {
  1845. logx.Error(err)
  1846. println("<<<<CentralKitchenForSchoolDataStatisticsExport7>>>>>Error:::", err.Error())
  1847. return
  1848. }
  1849. sess1 := db.Db.Where("central_kitchen_for_school_user_refund_day.state =?", enum.CentralKitchenForSchoolUserRefundDayStateForAuditComplete).And("user_identity.identity = ?", enum.UserIdentityForCentralKitchenForStudent).Desc("central_kitchen_for_school_user_refund_day.id")
  1850. if req.EnterpriseId != 0 {
  1851. sess1.And("enterprise.id =?", req.EnterpriseId)
  1852. }
  1853. if req.StartDate != "" {
  1854. sess1.And("central_kitchen_for_school_user_refund_day.create_at >= ?", req.StartDate)
  1855. }
  1856. if req.EndDate != "" {
  1857. sess1.And("central_kitchen_for_school_user_refund_day.create_at <= ?", req.EndDate)
  1858. }
  1859. var mm []*db.CentralKitchenForSchoolUserRefundDayWithData
  1860. _, err = sess1.
  1861. Join("LEFT", "central_kitchen_for_school_user_with_day", "central_kitchen_for_school_user_refund_day.records_id = central_kitchen_for_school_user_with_day.id").
  1862. Join("LEFT", "central_kitchen_for_school_package_ord", "central_kitchen_for_school_user_refund_day.out_trade_no = central_kitchen_for_school_package_ord.out_trade_no").
  1863. Join("LEFT", "user_identity", "central_kitchen_for_school_user_with_day.identity_id = user_identity.id").
  1864. Join("LEFT", "user", "user_identity.uid = user.id").
  1865. Join("LEFT", "enterprise", "user_identity.enterprise_id = enterprise.id").
  1866. Join("LEFT", "class_with_user", "user_identity.id = class_with_user.user_identity_id").
  1867. Join("LEFT", "class", "class_with_user.class_id = class.id").
  1868. Join("LEFT", "grade", "class.grade_id = grade.id").
  1869. Desc("central_kitchen_for_school_user_refund_day.id").
  1870. FindAndCount(&mm)
  1871. if err != nil {
  1872. logx.Error(err)
  1873. println("<<<<CentralKitchenForSchoolDataStatisticsExport7>>>>>Error:::", err.Error())
  1874. return
  1875. }
  1876. var list = map[string]map[string]map[string]map[string]float64{}
  1877. for _, v := range m {
  1878. if list[v.Enterprise.Name] == nil {
  1879. list[v.Enterprise.Name] = make(map[string]map[string]map[string]float64)
  1880. }
  1881. if list[v.Enterprise.Name][v.Grade.Name] == nil {
  1882. list[v.Enterprise.Name][v.Grade.Name] = make(map[string]map[string]float64)
  1883. }
  1884. if list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] == nil {
  1885. list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] = make(map[string]float64)
  1886. }
  1887. list[v.Enterprise.Name][v.Grade.Name][v.Class.Name]["income"] += utils.StrToFloat64(v.CentralKitchenForSchoolPackageOrd.TotalPrice)
  1888. }
  1889. for _, v := range mm {
  1890. if list[v.Enterprise.Name] == nil {
  1891. list[v.Enterprise.Name] = make(map[string]map[string]map[string]float64)
  1892. }
  1893. if list[v.Enterprise.Name][v.Grade.Name] == nil {
  1894. list[v.Enterprise.Name][v.Grade.Name] = make(map[string]map[string]float64)
  1895. }
  1896. if list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] == nil {
  1897. list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] = make(map[string]float64)
  1898. }
  1899. list[v.Enterprise.Name][v.Grade.Name][v.Class.Name]["refund"] += utils.StrToFloat64(v.CentralKitchenForSchoolUserRefundDay.Amount)
  1900. }
  1901. var xlsFileName, xlsDownloadPath []string
  1902. for k1, v1 := range list {
  1903. tmpFileName := k1 + "班级收款明细_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
  1904. tmpDownloadPath := "./static/export/central_kitchen_for_school/" + tmpFileName
  1905. startDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
  1906. endDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
  1907. titleList = []string{startDate.Format("2006-01-02") + "~~" + endDate.Format("2006-01-02") + " (" + k1 + ") 班级收款明细"}
  1908. xlsx.SetSheetRow("Sheet1", "A1", &titleList)
  1909. titleList = []string{"年级", "班级", "预定总费用", "退款总计"}
  1910. xlsx.SetSheetRow("Sheet1", "A2", &titleList)
  1911. xlsx.MergeCell("Sheet1", "A1", "D1") //合并单元格
  1912. style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFF00"],"pattern":1}, "alignment":{"horizontal":"center"}}`)
  1913. if err != nil {
  1914. logx.Error(err)
  1915. println("<<<<CentralKitchenForSchoolDataStatisticsExport3>>>>>Error:::", err.Error())
  1916. panic(err)
  1917. }
  1918. xlsx.SetCellStyle("Sheet1", "A1", "D1", style)
  1919. xlsx.SetColWidth("Sheet1", "A", "D", 20)
  1920. j := 3 //表头前两行用了,只能从第三行开始
  1921. var sumClassNum = int64(0)
  1922. var sumIncome, sumRefund = float64(0), float64(0)
  1923. for k2, v2 := range v1 {
  1924. if k2 == "" {
  1925. //若年级为空,则为教师餐
  1926. continue
  1927. }
  1928. for k3, v3 := range v2 {
  1929. xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{k2, k3, utils.Float64ToStr(v3["income"]), utils.Float64ToStr(v3["refund"])})
  1930. sumClassNum++
  1931. sumIncome += v3["income"]
  1932. sumRefund += v3["refund"]
  1933. j++
  1934. }
  1935. }
  1936. xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{
  1937. "合计", sumClassNum, sumIncome, sumRefund})
  1938. //将文件保存至服务器
  1939. err1 := xlsx.SaveAs(tmpDownloadPath)
  1940. if err1 != nil {
  1941. logx.Error(err1)
  1942. println("<<<<CentralKitchenForSchoolDataStatisticsExport7>>>>>Error:::", err1.Error())
  1943. panic(err1)
  1944. }
  1945. xlsDownloadPath = append(xlsDownloadPath, tmpDownloadPath)
  1946. xlsFileName = append(xlsFileName, tmpFileName)
  1947. }
  1948. archive, err := os.Create("./static" + downloadPath) //第一步,创建 zip 文件
  1949. if err != nil {
  1950. logx.Error(err)
  1951. println("<<<<CentralKitchenForSchoolDataStatisticsExport7>>>>>Error:::", err.Error())
  1952. panic(err)
  1953. }
  1954. defer archive.Close()
  1955. zipWriter := zip.NewWriter(archive) //第二步,创建一个新的 *Writer 对象
  1956. for k, v := range xlsDownloadPath {
  1957. w, err1 := zipWriter.Create("班级收款明细/" + xlsFileName[k]) //向 zip 文件中添加一个文件,返回一个待压缩的文件内容应写入的 Writer
  1958. if err1 != nil {
  1959. logx.Error(err1)
  1960. println("<<<<CentralKitchenForSchoolDataStatisticsExport7>>>>>Error:::", err1.Error())
  1961. panic(err1)
  1962. }
  1963. f, err1 := os.Open(v) //打开待压缩的文件
  1964. if err1 != nil {
  1965. logx.Error(err1)
  1966. println("<<<<CentralKitchenForSchoolDataStatisticsExport7>>>>>Error:::", err1.Error())
  1967. panic(err1)
  1968. }
  1969. if _, err1 = io.Copy(w, f); err != nil {
  1970. logx.Error(err1)
  1971. println("<<<<CentralKitchenForSchoolDataStatisticsExport7>>>>>Error:::", err1.Error())
  1972. panic(err1)
  1973. }
  1974. if err1 != nil {
  1975. logx.Error(err1)
  1976. println("<<<<CentralKitchenForSchoolDataStatisticsExport7>>>>>Error:::", err1.Error())
  1977. panic(err1)
  1978. }
  1979. f.Close()
  1980. os.RemoveAll(v) //TODO::移除源文件
  1981. }
  1982. zipWriter.Close() // 第四步,关闭 zip writer,将所有数据写入指向基础 zip 文件的数据流
  1983. if err != nil {
  1984. panic(err)
  1985. }
  1986. break
  1987. case 8:
  1988. xlsx := excelize.NewFile()
  1989. //学校预定数量统计表
  1990. fileName = "学校预定数量统计表_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
  1991. downloadPath = "/export/central_kitchen_for_school/" + fileName
  1992. startDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
  1993. endDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
  1994. var m []*db.CentralKitchenForSchoolPackageOrdForReserveWithUserIdentity
  1995. sess := db.Db.Desc("central_kitchen_for_school_package_ord_for_reserve.id")
  1996. if req.EnterpriseId != 0 {
  1997. sess.And("central_kitchen_for_school_package_ord_for_reserve.enterprise_id =?", req.EnterpriseId)
  1998. }
  1999. var months []time.Month
  2000. if req.StartDate != "" {
  2001. sDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
  2002. eDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
  2003. _, sMonth, _ := sDate.Date()
  2004. _, eMonth, _ := eDate.Date()
  2005. diffMonth := sMonth - eMonth
  2006. if diffMonth == 0 {
  2007. //TODO::查询一个月
  2008. months = append(months, sMonth)
  2009. } else {
  2010. for i := sMonth; i <= eMonth; i++ {
  2011. months = append(months, i)
  2012. }
  2013. }
  2014. }
  2015. if len(months) > 0 {
  2016. sess.In("central_kitchen_for_school_package_ord_for_reserve.reserve_month", months)
  2017. }
  2018. //if req.StartDate != "" {
  2019. // sess.And("central_kitchen_for_school_package_ord_for_reserve.meal_time_start <= ?", req.StartDate).
  2020. // And("central_kitchen_for_school_package_ord_for_reserve.meal_time_end >= ?", req.StartDate)
  2021. //}
  2022. if len(req.MealKindList) > 0 {
  2023. sess.In("central_kitchen_for_school_package_ord_for_reserve.kind", req.MealKindList)
  2024. }
  2025. if req.EnterPriseKind != 0 {
  2026. sess.And("enterprise.kind = ?", req.EnterPriseKind)
  2027. }
  2028. _, err := sess.And("user_identity.identity = ?", enum.UserIdentityForCentralKitchenForStudent).
  2029. Join("LEFT", "central_kitchen_for_school_package_ord", "central_kitchen_for_school_package_ord_for_reserve.out_trade_no = central_kitchen_for_school_package_ord.out_trade_no").
  2030. Join("LEFT", "user_identity", "central_kitchen_for_school_package_ord_for_reserve.user_identity_id = user_identity.id").
  2031. Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id").
  2032. FindAndCount(&m)
  2033. if err != nil {
  2034. logx.Error(err)
  2035. println("<<<<SelfSupportForSchoolDataStatisticsExport3>>>>>Error:::", err.Error())
  2036. return
  2037. }
  2038. var ordNoArr, mealKindListArr []string
  2039. for _, v := range m {
  2040. ordNoArr = append(ordNoArr, v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo)
  2041. }
  2042. var nativeSql = "SELECT COUNT(*) AS total, kind ,meal_label_name, ord_no FROM `central_kitchen_for_school_user_with_day` WHERE `ord_no` IN (%s) AND (state !=%d) AND (state !=%d) AND (DATE >= '%s') AND (DATE <= '%s') AND `kind` IN (%s) GROUP BY `ord_no`, `kind`"
  2043. for _, v := range req.MealKindList {
  2044. mealKindListArr = append(mealKindListArr, utils.IntToStr(v))
  2045. }
  2046. sDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
  2047. eDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
  2048. nativeSql = fmt.Sprintf(nativeSql, strings.Join(ordNoArr, ","), enum.CentralKitchenForSchoolUserWithDayStateForCancel, enum.CentralKitchenForSchoolUserWithDayStateForCanceling, sDate.Format("2006-01-02"), eDate.Format("2006-01-02"), strings.Join(mealKindListArr, ","))
  2049. nativeResults, err := db.QueryNativeString(db.Db, nativeSql)
  2050. var nativeResultsMap = map[string]map[int]map[string]int64{}
  2051. var mealLabelMap = map[int]map[string]string{}
  2052. for _, v := range nativeResults {
  2053. if nativeResultsMap[v["ord_no"]] == nil {
  2054. nativeResultsMap[v["ord_no"]] = make(map[int]map[string]int64)
  2055. }
  2056. if nativeResultsMap[v["ord_no"]][utils.StrToInt(v["kind"])] == nil {
  2057. nativeResultsMap[v["ord_no"]][utils.StrToInt(v["kind"])] = make(map[string]int64)
  2058. }
  2059. nativeResultsMap[v["ord_no"]][utils.StrToInt(v["kind"])][v["meal_label_name"]] = utils.StrToInt64(v["total"])
  2060. if mealLabelMap[utils.StrToInt(v["kind"])] == nil {
  2061. mealLabelMap[utils.StrToInt(v["kind"])] = make(map[string]string)
  2062. }
  2063. if v["meal_label_name"] == "" {
  2064. fmt.Println(v)
  2065. }
  2066. mealLabelMap[utils.StrToInt(v["kind"])][v["meal_label_name"]] = v["meal_label_name"]
  2067. }
  2068. var mealLabel = []string{"学校名称", "预定总数"}
  2069. for _, v := range mealLabelMap[enum.CentralKitchenForSchoolUserWithDayKindForBreakfast] {
  2070. mealLabel = append(mealLabel, v)
  2071. }
  2072. for _, v := range mealLabelMap[enum.CentralKitchenForSchoolUserWithDayKindForLunch] {
  2073. mealLabel = append(mealLabel, v)
  2074. }
  2075. for _, v := range mealLabelMap[enum.CentralKitchenForSchoolUserWithDayKindForDinner] {
  2076. mealLabel = append(mealLabel, v)
  2077. }
  2078. var list = map[string]map[string]int64{}
  2079. centralKitchenForSchoolUserWithDayDb := db.CentralKitchenForSchoolUserWithDayDb{}
  2080. centralKitchenForSchoolUserWithDayDb.Set(0)
  2081. var count int64
  2082. for _, v := range m {
  2083. if list[v.Enterprise.Name] == nil {
  2084. list[v.Enterprise.Name] = map[string]int64{}
  2085. }
  2086. for kk, vv := range nativeResultsMap[v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo] {
  2087. if v.CentralKitchenForSchoolPackageOrdForReserve.Kind != kk {
  2088. continue
  2089. }
  2090. for kkk, vvv := range vv {
  2091. list[v.Enterprise.Name][kkk] += vvv
  2092. list[v.Enterprise.Name]["count"] += vvv
  2093. count += vvv
  2094. }
  2095. }
  2096. }
  2097. titleList = []string{startDate.Format("2006-01-02") + "~~" + endDate.Format("2006-01-02") + " 预定数量统计表"}
  2098. xlsx.SetSheetRow("Sheet1", "A1", &titleList)
  2099. titleList = mealLabel
  2100. xlsx.SetSheetRow("Sheet1", "A2", &titleList)
  2101. xlsx.MergeCell("Sheet1", "A1", "M1") //合并单元格
  2102. style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFF00"],"pattern":1}, "alignment":{"horizontal":"center"}}`)
  2103. if err != nil {
  2104. logx.Error(err)
  2105. println("<<<<CentralKitchenForSchoolDataStatisticsExport8>>>>>Error:::", err.Error())
  2106. panic(err)
  2107. }
  2108. xlsx.SetCellStyle("Sheet1", "A1", "M1", style)
  2109. xlsx.SetColWidth("Sheet1", "A", "A", 30)
  2110. xlsx.SetColWidth("Sheet1", "B", "M", 15)
  2111. j := 3 //表头前两行用了,只能从第三行开始
  2112. var sumTotal = map[string]int64{}
  2113. for k, v := range list {
  2114. var slice = []interface{}{k, v["count"]}
  2115. for key, meal := range mealLabel {
  2116. if key != 0 && key != 1 {
  2117. slice = append(slice, v[meal])
  2118. sumTotal[meal] += v[meal]
  2119. }
  2120. }
  2121. xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &slice)
  2122. j++
  2123. }
  2124. var slice = []interface{}{"合计", count}
  2125. for key, meal := range mealLabel {
  2126. if key != 0 && key != 1 {
  2127. slice = append(slice, sumTotal[meal])
  2128. sumTotal[meal] += sumTotal[meal]
  2129. }
  2130. }
  2131. xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &slice)
  2132. //将文件保存至服务器
  2133. xlsx.SaveAs("./static" + downloadPath)
  2134. break
  2135. case 10:
  2136. //就餐数据统计表
  2137. sTime, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
  2138. eTime, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
  2139. xls, _ := excelize.OpenFile("./static/template/央厨学校(就餐数据统计表).xlsx")
  2140. fileName = "【" + sTime.Format("2006-01-02") + "~" + eTime.Format("2006-01-02") + "】就餐数据统计表_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
  2141. downloadPath = "/export/central_kitchen_for_school/" + fileName
  2142. var list = map[string]map[string]map[string]float64{}
  2143. var dates []string
  2144. if req.StartDate != "" {
  2145. centralKitchenForSchoolUserWithDayDb := db.CentralKitchenForSchoolUserWithDayDb{}
  2146. centralKitchenForSchoolUserWithDayDb.Set(0)
  2147. diffDays := int(eTime.Sub(sTime).Hours() / 24)
  2148. for i := 0; i <= diffDays; i++ {
  2149. date := sTime.AddDate(0, 0, i)
  2150. dateName := date.Format("2006-01-02")
  2151. dates = append(dates, dateName)
  2152. for _, vv := range req.MealKindList {
  2153. tmpSum, err := centralKitchenForSchoolUserWithDayDb.SumCentralKitchenForSchoolUserWithDayByKind(req.EnterpriseId, dateName, dateName, vv, enum.CentralKitchenForSchoolUserWithDayStateForCancel, enum.CentralKitchenForSchoolUserWithDayStateForCanceling)
  2154. if err != nil {
  2155. logx.Error(err)
  2156. println("<<<<CentralKitchenForSchoolDataStatisticsExport9>>>>>Error:::", err.Error())
  2157. panic(err)
  2158. }
  2159. tmpCount, err := centralKitchenForSchoolUserWithDayDb.CountCentralKitchenForSchoolUserWithDayByKind(req.EnterpriseId, dateName, dateName, vv, enum.CentralKitchenForSchoolUserWithDayStateForCancel, enum.CentralKitchenForSchoolUserWithDayStateForCanceling)
  2160. if err != nil {
  2161. logx.Error(err)
  2162. println("<<<<CentralKitchenForSchoolDataStatisticsExport9>>>>>Error:::", err.Error())
  2163. panic(err)
  2164. }
  2165. if list[dateName] == nil {
  2166. list[dateName] = map[string]map[string]float64{}
  2167. }
  2168. if list[dateName][enum.CentralKitchenForSchoolUserWithDayKind(vv).String()] == nil {
  2169. list[dateName][enum.CentralKitchenForSchoolUserWithDayKind(vv).String()] = map[string]float64{}
  2170. }
  2171. if list[dateName]["合计"] == nil {
  2172. list[dateName]["合计"] = make(map[string]float64)
  2173. }
  2174. list[dateName][enum.CentralKitchenForSchoolUserWithDayKind(vv).String()]["sum"] = tmpSum
  2175. list[dateName][enum.CentralKitchenForSchoolUserWithDayKind(vv).String()]["count"] = float64(tmpCount)
  2176. list[dateName]["合计"]["sum"] += tmpSum
  2177. list[dateName]["合计"]["count"] += float64(tmpCount)
  2178. }
  2179. }
  2180. }
  2181. //xls.SetSheetRow("", "A1", &titleList)
  2182. //sheetIndex := 2 //第一个表是模板表
  2183. //xls.NewSheet("sheet1") //1、新建表格
  2184. //xls.CopySheet(1, sheetIndex)
  2185. j := 4 //表头前三"早餐"行被占用了,只能从第四行开始
  2186. var totalMap = map[string]float64{}
  2187. for _, date := range dates {
  2188. for kk, v := range list {
  2189. if date == kk {
  2190. xls.SetSheetRow("template", "A"+strconv.Itoa(j), &[]interface{}{kk,
  2191. v["早餐"]["count"], v["早餐"]["sum"],
  2192. v["午餐"]["count"], v["午餐"]["sum"],
  2193. v["晚餐"]["count"], v["晚餐"]["sum"],
  2194. v["合计"]["count"], v["合计"]["sum"],
  2195. })
  2196. totalMap["breakfast_count"] += v["早餐"]["count"]
  2197. totalMap["breakfast_sum"] += v["早餐"]["sum"]
  2198. totalMap["lunch_count"] += v["午餐"]["count"]
  2199. totalMap["lunch_sum"] += v["午餐"]["sum"]
  2200. totalMap["dinner_count"] += v["晚餐"]["count"]
  2201. totalMap["dinner_sum"] += v["晚餐"]["sum"]
  2202. totalMap["total_count"] += v["合计"]["count"]
  2203. totalMap["total_sum"] += v["合计"]["sum"]
  2204. j++
  2205. }
  2206. }
  2207. }
  2208. //xls.DeleteSheet("template") //删除模板表
  2209. xls.SetSheetRow("template", "A"+strconv.Itoa(j), &[]interface{}{"总计",
  2210. totalMap["breakfast_count"], totalMap["breakfast_sum"],
  2211. totalMap["lunch_count"], totalMap["lunch_sum"],
  2212. totalMap["dinner_count"], totalMap["dinner_sum"],
  2213. totalMap["total_count"], totalMap["total_sum"],
  2214. })
  2215. //将文件保存至服务器
  2216. xls.SaveAs("./static" + downloadPath)
  2217. break
  2218. case 11:
  2219. //教师就餐明细表
  2220. fileName = "教师就餐明细表_" + utils.Int64ToStr(now.UnixMilli()) + ".zip"
  2221. downloadPath = "/export/central_kitchen_for_school/" + fileName
  2222. var m []*db.CentralKitchenForSchoolPackageOrdForReserveWithUserIdentity
  2223. sess := db.Db.Desc("central_kitchen_for_school_package_ord_for_reserve.id")
  2224. if req.EnterpriseId != 0 {
  2225. sess.And("central_kitchen_for_school_package_ord_for_reserve.enterprise_id =?", req.EnterpriseId)
  2226. }
  2227. var months []time.Month
  2228. if req.StartDate != "" {
  2229. sDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
  2230. eDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
  2231. _, sMonth, _ := sDate.Date()
  2232. _, eMonth, _ := eDate.Date()
  2233. diffMonth := sMonth - eMonth
  2234. if diffMonth == 0 {
  2235. //TODO::查询一个月
  2236. months = append(months, sMonth)
  2237. } else {
  2238. for i := sMonth; i <= eMonth; i++ {
  2239. months = append(months, i)
  2240. }
  2241. }
  2242. }
  2243. if len(months) > 0 {
  2244. sess.In("central_kitchen_for_school_package_ord_for_reserve.reserve_month", months)
  2245. }
  2246. if len(req.MealKindList) > 0 {
  2247. sess.In("central_kitchen_for_school_package_ord_for_reserve.kind", req.MealKindList)
  2248. }
  2249. if req.EnterPriseKind != 0 {
  2250. sess.And("enterprise.kind = ?", req.EnterPriseKind)
  2251. }
  2252. sess.And("user_identity.identity != ?", 1) //不查学生的
  2253. _, err := sess.
  2254. Join("LEFT", "central_kitchen_for_school_package_ord", "central_kitchen_for_school_package_ord_for_reserve.out_trade_no = central_kitchen_for_school_package_ord.out_trade_no").
  2255. Join("LEFT", "user_identity", "central_kitchen_for_school_package_ord_for_reserve.user_identity_id = user_identity.id").
  2256. Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id").
  2257. Asc("enterprise.id").
  2258. FindAndCount(&m)
  2259. if err != nil {
  2260. logx.Error(err)
  2261. println("<<<<CentralKitchenForSchoolDataStatisticsExport11>>>>>Error:::", err.Error())
  2262. return
  2263. }
  2264. var ordNoArr, mealKindListArr []string
  2265. for _, v := range m {
  2266. ordNoArr = append(ordNoArr, v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo)
  2267. }
  2268. var nativeSql = "SELECT COUNT(*) AS total, kind , ord_no FROM `central_kitchen_for_school_user_with_day` WHERE `ord_no` IN (%s) AND (state !=%d) AND (state !=%d) AND (DATE >= '%s') AND (DATE <= '%s') AND `kind` IN (%s) GROUP BY `ord_no`, `kind`"
  2269. for _, v := range req.MealKindList {
  2270. mealKindListArr = append(mealKindListArr, utils.IntToStr(v))
  2271. }
  2272. sDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
  2273. eDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
  2274. nativeSql = fmt.Sprintf(nativeSql, strings.Join(ordNoArr, ","), enum.CentralKitchenForSchoolUserWithDayStateForCancel, enum.CentralKitchenForSchoolUserWithDayStateForCanceling, sDate.Format("2006-01-02"), eDate.Format("2006-01-02"), strings.Join(mealKindListArr, ","))
  2275. nativeResults, err := db.QueryNativeString(db.Db, nativeSql)
  2276. var nativeResultsMap = map[string]map[int]int64{}
  2277. for _, v := range nativeResults {
  2278. if nativeResultsMap[v["ord_no"]] == nil {
  2279. nativeResultsMap[v["ord_no"]] = make(map[int]int64)
  2280. }
  2281. nativeResultsMap[v["ord_no"]][utils.StrToInt(v["kind"])] = utils.StrToInt64(v["total"])
  2282. }
  2283. var list = map[string]map[string]map[string]int64{}
  2284. var xlsFileName, xlsDownloadPath []string
  2285. centralKitchenForSchoolUserWithDayDb := db.CentralKitchenForSchoolUserWithDayDb{}
  2286. centralKitchenForSchoolUserWithDayDb.Set(0)
  2287. for _, v := range m {
  2288. if list[v.Enterprise.Name] == nil {
  2289. list[v.Enterprise.Name] = make(map[string]map[string]int64)
  2290. }
  2291. if list[v.Enterprise.Name][v.UserIdentity.Name] == nil {
  2292. list[v.Enterprise.Name][v.UserIdentity.Name] = make(map[string]int64)
  2293. }
  2294. if v.CentralKitchenForSchoolPackageOrdForReserve.Kind == enum.CentralKitchenForSchoolUserWithDayKindForBreakfast {
  2295. list[v.Enterprise.Name][v.UserIdentity.Name]["breakfast"] += nativeResultsMap[v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo][enum.CentralKitchenForSchoolUserWithDayKindForBreakfast]
  2296. }
  2297. if v.CentralKitchenForSchoolPackageOrdForReserve.Kind == enum.CentralKitchenForSchoolUserWithDayKindForLunch {
  2298. list[v.Enterprise.Name][v.UserIdentity.Name]["lunch"] += nativeResultsMap[v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo][enum.CentralKitchenForSchoolUserWithDayKindForLunch]
  2299. }
  2300. if v.CentralKitchenForSchoolPackageOrdForReserve.Kind == enum.CentralKitchenForSchoolUserWithDayKindForDinner {
  2301. list[v.Enterprise.Name][v.UserIdentity.Name]["dinner"] += nativeResultsMap[v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo][enum.CentralKitchenForSchoolUserWithDayKindForDinner]
  2302. }
  2303. }
  2304. for k1, v1 := range list {
  2305. xlsx := excelize.NewFile()
  2306. tmpFileName := k1 + "_教师明细_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
  2307. tmpDownloadPath := "./static/export/central_kitchen_for_school/" + tmpFileName
  2308. startDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
  2309. endDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
  2310. xlsx.NewSheet(k1)
  2311. titleList = []string{startDate.Format("2006-01-02") + "~~" + endDate.Format("2006-01-02") + " [" + k1 + "] 教师明细"}
  2312. xlsx.SetSheetRow(k1, "A1", &titleList)
  2313. titleList = []string{"姓名", "早餐", "午餐", "晚餐"}
  2314. xlsx.SetSheetRow(k1, "A2", &titleList)
  2315. xlsx.MergeCell(k1, "A1", "D1") //合并单元格
  2316. style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFF00"],"pattern":1}, "alignment":{"horizontal":"center"}}`)
  2317. if err != nil {
  2318. logx.Error(err)
  2319. println("<<<<CentralKitchenForSchoolDataStatisticsExport11>>>>>Error:::", err.Error())
  2320. panic(err)
  2321. }
  2322. xlsx.SetCellStyle(k1, "A1", "D1", style)
  2323. xlsx.SetColWidth(k1, "A", "D", 20)
  2324. var sumBreakfast, sumLunch, sumDinner = int64(0), int64(0), int64(0)
  2325. j := 3 //表头前两行用了,只能从第三行开始
  2326. for k2, v2 := range v1 {
  2327. if v2["breakfast"] == 0 && v2["lunch"] == 0 && v2["dinner"] == 0 {
  2328. continue
  2329. }
  2330. xlsx.SetSheetRow(k1, "A"+strconv.Itoa(j), &[]interface{}{
  2331. k2, v2["breakfast"], v2["lunch"], v2["dinner"]})
  2332. sumBreakfast += v2["breakfast"]
  2333. sumLunch += v2["lunch"]
  2334. sumDinner += v2["dinner"]
  2335. j++
  2336. }
  2337. xlsx.SetSheetRow(k1, "A"+strconv.Itoa(j), &[]interface{}{
  2338. "合计", sumBreakfast, sumLunch, sumDinner})
  2339. //将文件保存至服务器
  2340. xlsx.DeleteSheet("Sheet1") //TODO::只能放这里删除
  2341. err1 := xlsx.SaveAs(tmpDownloadPath)
  2342. if err1 != nil {
  2343. logx.Error(err1)
  2344. println("<<<<CentralKitchenForSchoolDataStatisticsExport11>>>>>Error:::", err1.Error())
  2345. panic(err1)
  2346. }
  2347. xlsDownloadPath = append(xlsDownloadPath, tmpDownloadPath)
  2348. xlsFileName = append(xlsFileName, tmpFileName)
  2349. }
  2350. archive, err := os.Create("./static" + downloadPath) //第一步,创建 zip 文件
  2351. if err != nil {
  2352. logx.Error(err)
  2353. println("<<<<CentralKitchenForSchoolDataStatisticsExport11>>>>>Error:::", err.Error())
  2354. panic(err)
  2355. }
  2356. defer archive.Close()
  2357. zipWriter := zip.NewWriter(archive) //第二步,创建一个新的 *Writer 对象
  2358. for k, v := range xlsDownloadPath {
  2359. w, err1 := zipWriter.Create("教师就餐明细/" + xlsFileName[k]) //向 zip 文件中添加一个文件,返回一个待压缩的文件内容应写入的 Writer
  2360. if err1 != nil {
  2361. logx.Error(err1)
  2362. println("<<<<CentralKitchenForSchoolDataStatisticsExport11>>>>>Error:::", err1.Error())
  2363. panic(err1)
  2364. }
  2365. f, err1 := os.Open(v) //打开待压缩的文件
  2366. if err1 != nil {
  2367. logx.Error(err1)
  2368. println("<<<<CentralKitchenForSchoolDataStatisticsExport11>>>>>Error:::", err1.Error())
  2369. panic(err1)
  2370. }
  2371. if _, err1 = io.Copy(w, f); err != nil {
  2372. logx.Error(err1)
  2373. println("<<<<CentralKitchenForSchoolDataStatisticsExport11>>>>>Error:::", err1.Error())
  2374. panic(err1)
  2375. }
  2376. if err1 != nil {
  2377. logx.Error(err1)
  2378. println("<<<<CentralKitchenForSchoolDataStatisticsExport11>>>>>Error:::", err1.Error())
  2379. panic(err1)
  2380. }
  2381. f.Close()
  2382. os.RemoveAll(v) //TODO::移除源文件
  2383. }
  2384. zipWriter.Close() // 第四步,关闭 zip writer,将所有数据写入指向基础 zip 文件的数据流
  2385. if err != nil {
  2386. panic(err)
  2387. }
  2388. break
  2389. }
  2390. //新增数据
  2391. centralKitchenForSchoolExportRecordsDb := db.CentralKitchenForSchoolExportRecordsDb{}
  2392. centralKitchenForSchoolExportRecordsDb.Set()
  2393. marshal, _ := json.Marshal(req)
  2394. centralKitchenForSchoolExportRecordsDb.CentralKitchenForSchoolExportRecordsInsert(&model.CentralKitchenForSchoolExportRecords{
  2395. Name: fileName,
  2396. DownloadPath: downloadPath,
  2397. Kind: kind,
  2398. ReqContent: string(marshal),
  2399. CreateAt: now.Format("2006-01-02 15:04:05"),
  2400. UpdateAt: now.Format("2006-01-02 15:04:05"),
  2401. })
  2402. }
  2403. }
  2404. func CentralKitchenForSchoolDataStatisticsContrast(req md.CentralKitchenForSchoolDataStatisticsContrastReq) {
  2405. var titleList []string
  2406. var fileName, downloadPath string
  2407. var now = time.Now()
  2408. //数据对比
  2409. fileName = "数据对比_" + utils.Int64ToStr(now.UnixMilli()) + ".zip"
  2410. downloadPath = "/export/central_kitchen_for_school/" + fileName
  2411. var m []*db.CentralKitchenForSchoolPackageOrdForReserveWithUserIdentity
  2412. sess := db.Db.Desc("central_kitchen_for_school_package_ord_for_reserve.id")
  2413. if req.EnterpriseId != 0 {
  2414. sess.And("central_kitchen_for_school_package_ord_for_reserve.enterprise_id =?", req.EnterpriseId)
  2415. }
  2416. if req.Date1[0] != "" {
  2417. startDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.Date1[0], time.Local)
  2418. sess.And("central_kitchen_for_school_package_ord_for_reserve.meal_time_start >= ?", startDate.Format("2006-01-02"))
  2419. }
  2420. if req.Date1[1] != "" {
  2421. endDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.Date1[1], time.Local)
  2422. sess.And("central_kitchen_for_school_package_ord_for_reserve.meal_time_start <= ?", endDate.Format("2006-01-02"))
  2423. }
  2424. if len(req.MealKindList) > 0 {
  2425. sess.In("central_kitchen_for_school_package_ord_for_reserve.kind", req.MealKindList)
  2426. }
  2427. if req.EnterPriseKind != 0 {
  2428. sess.And("enterprise.kind = ?", req.EnterPriseKind)
  2429. }
  2430. _, err := sess.
  2431. Join("LEFT", "central_kitchen_for_school_package_ord", "central_kitchen_for_school_package_ord_for_reserve.out_trade_no = central_kitchen_for_school_package_ord.out_trade_no").
  2432. Join("LEFT", "user_identity", "central_kitchen_for_school_package_ord_for_reserve.user_identity_id = user_identity.id").
  2433. Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id").
  2434. Join("LEFT", "user", "user.id = user_identity.uid").
  2435. Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id").
  2436. Join("LEFT", "class", "class_with_user.class_id = class.id").
  2437. Join("LEFT", "grade", "class.grade_id = grade.id").
  2438. FindAndCount(&m)
  2439. if err != nil {
  2440. logx.Error(err)
  2441. println("<<<<CentralKitchenForSchoolDataStatisticsContrast>>>>>Error:::", err.Error())
  2442. return
  2443. }
  2444. var m1 []*db.CentralKitchenForSchoolPackageOrdForReserveWithUserIdentity
  2445. sess1 := db.Db.Desc("central_kitchen_for_school_package_ord_for_reserve.id")
  2446. if req.EnterpriseId != 0 {
  2447. sess1.And("central_kitchen_for_school_package_ord_for_reserve.enterprise_id =?", req.EnterpriseId)
  2448. }
  2449. if req.Date2[0] != "" {
  2450. startDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.Date2[0], time.Local)
  2451. sess1.And("central_kitchen_for_school_package_ord_for_reserve.meal_time_start >= ?", startDate.Format("2006-01-02"))
  2452. }
  2453. if req.Date2[1] != "" {
  2454. endDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.Date2[1], time.Local)
  2455. sess1.And("central_kitchen_for_school_package_ord_for_reserve.meal_time_start <= ?", endDate.Format("2006-01-02"))
  2456. }
  2457. if len(req.MealKindList) > 0 {
  2458. sess1.In("central_kitchen_for_school_package_ord_for_reserve.kind", req.MealKindList)
  2459. }
  2460. _, err1 := sess1.
  2461. Join("LEFT", "central_kitchen_for_school_package_ord", "central_kitchen_for_school_package_ord_for_reserve.out_trade_no = central_kitchen_for_school_package_ord.out_trade_no").
  2462. Join("LEFT", "user_identity", "central_kitchen_for_school_package_ord_for_reserve.user_identity_id = user_identity.id").
  2463. Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id").
  2464. Join("LEFT", "user", "user.id = user_identity.uid").
  2465. Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id").
  2466. Join("LEFT", "class", "class_with_user.class_id = class.id").
  2467. Join("LEFT", "grade", "class.grade_id = grade.id").
  2468. FindAndCount(&m1)
  2469. if err1 != nil {
  2470. logx.Error(err1)
  2471. println("<<<<CentralKitchenForSchoolDataStatisticsContrast>>>>>Error:::", err.Error())
  2472. return
  2473. }
  2474. var list = map[string]map[string]map[string]map[string]string{}
  2475. for _, v := range m {
  2476. if list[v.Enterprise.Name] == nil {
  2477. list[v.Enterprise.Name] = make(map[string]map[string]map[string]string)
  2478. }
  2479. if v.UserIdentity.Identity == enum.UserIdentityForCentralKitchenForTeacher {
  2480. if list[v.Enterprise.Name]["教职工"] == nil {
  2481. list[v.Enterprise.Name]["教职工"] = make(map[string]map[string]string)
  2482. }
  2483. if list[v.Enterprise.Name]["教职工"]["教职工"] == nil {
  2484. list[v.Enterprise.Name]["教职工"]["教职工"] = make(map[string]string)
  2485. }
  2486. list[v.Enterprise.Name]["教职工"]["教职工"][v.UserIdentity.Name] = v.User.Phone
  2487. } else {
  2488. if list[v.Enterprise.Name][v.Grade.Name] == nil {
  2489. list[v.Enterprise.Name][v.Grade.Name] = make(map[string]map[string]string)
  2490. }
  2491. if list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] == nil {
  2492. list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] = make(map[string]string)
  2493. }
  2494. list[v.Enterprise.Name][v.Grade.Name][v.Class.Name][v.UserIdentity.Name] = v.User.Phone
  2495. }
  2496. }
  2497. var list1 = map[string]map[string]map[string]map[string]string{}
  2498. for _, v := range m1 {
  2499. if list1[v.Enterprise.Name] == nil {
  2500. list1[v.Enterprise.Name] = make(map[string]map[string]map[string]string)
  2501. }
  2502. if v.UserIdentity.Identity == enum.UserIdentityForCentralKitchenForTeacher {
  2503. if list1[v.Enterprise.Name]["教职工"] == nil {
  2504. list1[v.Enterprise.Name]["教职工"] = make(map[string]map[string]string)
  2505. }
  2506. if list1[v.Enterprise.Name]["教职工"]["教职工"] == nil {
  2507. list1[v.Enterprise.Name]["教职工"]["教职工"] = make(map[string]string)
  2508. }
  2509. list1[v.Enterprise.Name]["教职工"]["教职工"][v.UserIdentity.Name] = v.User.Phone
  2510. } else {
  2511. if list1[v.Enterprise.Name][v.Grade.Name] == nil {
  2512. list1[v.Enterprise.Name][v.Grade.Name] = make(map[string]map[string]string)
  2513. }
  2514. if list1[v.Enterprise.Name][v.Grade.Name][v.Class.Name] == nil {
  2515. list1[v.Enterprise.Name][v.Grade.Name][v.Class.Name] = make(map[string]string)
  2516. }
  2517. list1[v.Enterprise.Name][v.Grade.Name][v.Class.Name][v.UserIdentity.Name] = v.User.Phone
  2518. }
  2519. }
  2520. var xlsFileName, xlsDownloadPath []string
  2521. for k1, v1 := range list {
  2522. tmpFileName := k1 + "数据对比_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
  2523. tmpDownloadPath := "./static/export/central_kitchen_for_school/" + tmpFileName
  2524. startDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.Date1[0], time.Local)
  2525. endDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.Date2[0], time.Local)
  2526. //查询当前学校下的班级升序
  2527. tmpEnterpriseDb := db.EnterpriseDb{}
  2528. tmpEnterpriseDb.Set()
  2529. tmpEnterprise, err11 := tmpEnterpriseDb.GetEnterpriseByName(k1)
  2530. if err11 != nil {
  2531. logx.Error(err11)
  2532. println("<<<<CentralKitchenForSchoolDataStatisticsExport4>>>>>Error:::", err11.Error())
  2533. panic(err11)
  2534. }
  2535. tmpClassDb := db.ClassDb{}
  2536. tmpClassDb.Set(0)
  2537. var classList *[]model.Class
  2538. //TODO::判断单位类型
  2539. if tmpEnterprise.Kind == enum.EnterpriseKindByCentralKitchenForSchool {
  2540. classList, err = tmpClassDb.FindClassAscByEnterprise(tmpEnterprise.Id)
  2541. if err != nil {
  2542. logx.Error(err)
  2543. println("<<<<CentralKitchenForSchoolDataStatisticsExport4>>>>>Error:::", err.Error())
  2544. panic(err)
  2545. }
  2546. } else {
  2547. classList, err = tmpClassDb.FindClassSortAscByEnterprise(tmpEnterprise.Id)
  2548. if err != nil {
  2549. logx.Error(err)
  2550. println("<<<<CentralKitchenForSchoolDataStatisticsExport4>>>>>Error:::", err.Error())
  2551. panic(err)
  2552. }
  2553. }
  2554. xlsx := excelize.NewFile()
  2555. for _, class := range *classList {
  2556. for k2, v2 := range v1 {
  2557. if k2 == "" {
  2558. //若年级为空,则为教师
  2559. continue
  2560. }
  2561. for k3, v3 := range v2 {
  2562. if k3 != "教职工" && class.Name != k3 {
  2563. continue
  2564. }
  2565. xlsx.NewSheet(k3)
  2566. titleList = []string{startDate.Format("2006-01") + "~~" + endDate.Format("2006-01") + " [" + k1 + ", " + k3 + "] 订餐数据对比"}
  2567. xlsx.SetSheetRow(k3, "A1", &titleList)
  2568. titleList = []string{"姓名", "家长联系电话"}
  2569. xlsx.SetSheetRow(k3, "A2", &titleList)
  2570. xlsx.MergeCell(k3, "A1", "B1") //合并单元格
  2571. style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFF00"],"pattern":1}, "alignment":{"horizontal":"center"}}`)
  2572. if err != nil {
  2573. logx.Error(err)
  2574. println("<<<<CentralKitchenForSchoolDataStatisticsExport3>>>>>Error:::", err.Error())
  2575. panic(err)
  2576. }
  2577. xlsx.SetCellStyle(k3, "A1", "B1", style)
  2578. xlsx.SetColWidth(k3, "A", "B", 40)
  2579. j := 2 //表头被第一行用了,只能从第二行开始
  2580. for k4, v4 := range v3 {
  2581. //TODO::判断当前用户是否在新的月份里面
  2582. fmt.Println("11111111111111", list1[k1])
  2583. fmt.Println("22222222222222", list1[k1][k2])
  2584. fmt.Println("33333333333333", list1[k1][k2][k3])
  2585. fmt.Println("44444444444444", list1[k1][k2][k3][k4])
  2586. if list1[k1] == nil || list1[k1][k2] == nil || list1[k1][k2][k3] == nil || list1[k1][k2][k3][k4] == "" {
  2587. xlsx.SetSheetRow(k3, "A"+strconv.Itoa(j), &[]interface{}{
  2588. k4, v4})
  2589. j++
  2590. }
  2591. }
  2592. }
  2593. }
  2594. }
  2595. //将文件保存至服务器
  2596. xlsx.DeleteSheet("Sheet1") //TODO::只能放这里删除
  2597. err1 := xlsx.SaveAs(tmpDownloadPath)
  2598. if err1 != nil {
  2599. logx.Error(err1)
  2600. println("<<<<CentralKitchenForSchoolDataStatisticsContrast>>>>>Error:::", err1.Error())
  2601. panic(err1)
  2602. }
  2603. xlsDownloadPath = append(xlsDownloadPath, tmpDownloadPath)
  2604. xlsFileName = append(xlsFileName, tmpFileName)
  2605. }
  2606. archive, err := os.Create("./static" + downloadPath) //第一步,创建 zip 文件
  2607. if err != nil {
  2608. logx.Error(err)
  2609. println("<<<<CentralKitchenForSchoolDataStatisticsContrast>>>>>Error:::", err.Error())
  2610. panic(err)
  2611. }
  2612. defer archive.Close()
  2613. zipWriter := zip.NewWriter(archive) //第二步,创建一个新的 *Writer 对象
  2614. for k, v := range xlsDownloadPath {
  2615. w, err1 := zipWriter.Create("数据对比/" + xlsFileName[k]) //向 zip 文件中添加一个文件,返回一个待压缩的文件内容应写入的 Writer
  2616. if err1 != nil {
  2617. logx.Error(err1)
  2618. println("<<<<CentralKitchenForSchoolDataStatisticsContrast>>>>>Error:::", err1.Error())
  2619. panic(err1)
  2620. }
  2621. f, err1 := os.Open(v) //打开待压缩的文件
  2622. if err1 != nil {
  2623. logx.Error(err1)
  2624. println("<<<<CentralKitchenForSchoolDataStatisticsContrast>>>>>Error:::", err1.Error())
  2625. panic(err1)
  2626. }
  2627. if _, err1 = io.Copy(w, f); err != nil {
  2628. logx.Error(err1)
  2629. println("<<<<CentralKitchenForSchoolDataStatisticsContrast>>>>>Error:::", err1.Error())
  2630. panic(err1)
  2631. }
  2632. if err1 != nil {
  2633. logx.Error(err1)
  2634. println("<<<<CentralKitchenForSchoolDataStatisticsContrast>>>>>Error:::", err1.Error())
  2635. panic(err1)
  2636. }
  2637. f.Close()
  2638. os.RemoveAll(v) //TODO::移除源文件
  2639. }
  2640. zipWriter.Close() // 第四步,关闭 zip writer,将所有数据写入指向基础 zip 文件的数据流
  2641. if err != nil {
  2642. panic(err)
  2643. }
  2644. //新增数据
  2645. centralKitchenForSchoolExportRecordsDb := db.CentralKitchenForSchoolExportRecordsDb{}
  2646. centralKitchenForSchoolExportRecordsDb.Set()
  2647. marshal, _ := json.Marshal(req)
  2648. centralKitchenForSchoolExportRecordsDb.CentralKitchenForSchoolExportRecordsInsert(&model.CentralKitchenForSchoolExportRecords{
  2649. Name: fileName,
  2650. DownloadPath: downloadPath,
  2651. Kind: 9, //数据对比
  2652. ReqContent: string(marshal),
  2653. CreateAt: now.Format("2006-01-02 15:04:05"),
  2654. UpdateAt: now.Format("2006-01-02 15:04:05"),
  2655. })
  2656. }
  2657. func JudgeSelfSupportForMealTime(mealDate string) (mealZh string) {
  2658. mealZh = "未知"
  2659. mealTime, _ := time.ParseInLocation("2006-01-02 15:04:05", mealDate, time.Local)
  2660. for _, v := range md.SelfSupportForMealTimeMapping {
  2661. //判断时间大小
  2662. tmpFromTime, _ := time.ParseInLocation("2006-01-02 15:04:05", mealTime.Format("2006-01-02")+" "+v["from"]+":00", time.Local)
  2663. tmpToTime, _ := time.ParseInLocation("2006-01-02 15:04:05", mealTime.Format("2006-01-02")+" "+v["to"]+":00", time.Local)
  2664. fmt.Println(">>>>>>>>>>>>>", mealTime.After(tmpFromTime))
  2665. fmt.Println("<<<<<<<<<<<<<", mealTime.Before(tmpToTime))
  2666. if mealTime.After(tmpFromTime) && mealTime.Before(tmpToTime) {
  2667. mealZh = v["name"]
  2668. }
  2669. }
  2670. return
  2671. }